aboutsummaryrefslogtreecommitdiffstats
path: root/drivers/char/sonypi.c
blob: 73f66d03624dfd2b1e51a0aab8c236fc6ec4c7d6 (plain) (blame)
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
/*
 * Sony Programmable I/O Control Device driver for VAIO
 *
 * Copyright (C) 2007 Mattia Dongili <malattia@linux.it>
 *
 * Copyright (C) 2001-2005 Stelian Pop <stelian@popies.net>
 *
 * Copyright (C) 2005 Narayanan R S <nars@kadamba.org>
 *
 * Copyright (C) 2001-2002 Alcôve <www.alcove.com>
 *
 * Copyright (C) 2001 Michael Ashley <m.ashley@unsw.edu.au>
 *
 * Copyright (C) 2001 Junichi Morita <jun1m@mars.dti.ne.jp>
 *
 * Copyright (C) 2000 Takaya Kinjo <t-kinjo@tc4.so-net.ne.jp>
 *
 * Copyright (C) 2000 Andrew Tridgell <tridge@valinux.com>
 *
 * Earlier work by Werner Almesberger, Paul `Rusty' Russell and Paul Mackerras.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#include <linux/module.h>
#include <linux/sched.h>
#include <linux/input.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/miscdevice.h>
#include <linux/poll.h>
#include <linux/delay.h>
#include <linux/wait.h>
#include <linux/acpi.h>
#include <linux/dmi.h>
#include <linux/err.h>
#include <linux/kfifo.h>
#include <linux/platform_device.h>
#include <linux/gfp.h>

#include <asm/uaccess.h>
#include <asm/io.h>
#include <asm/system.h>

#include <linux/sonypi.h>

#define SONYPI_DRIVER_VERSION	 "1.26"

MODULE_AUTHOR("Stelian Pop <stelian@popies.net>");
MODULE_DESCRIPTION("Sony Programmable I/O Control Device driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(SONYPI_DRIVER_VERSION);

static int minor = -1;
module_param(minor, int, 0);
MODULE_PARM_DESC(minor,
		 "minor number of the misc device, default is -1 (automatic)");

static int verbose;		/* = 0 */
module_param(verbose, int, 0644);
MODULE_PARM_DESC(verbose, "be verbose, default is 0 (no)");

static int fnkeyinit;		/* = 0 */
module_param(fnkeyinit, int, 0444);
MODULE_PARM_DESC(fnkeyinit,
		 "set this if your Fn keys do not generate any event");

static int camera;		/* = 0 */
module_param(camera, int, 0444);
MODULE_PARM_DESC(camera,
		 "set this if you have a MotionEye camera (PictureBook series)");

static int compat;		/* = 0 */
module_param(compat, int, 0444);
MODULE_PARM_DESC(compat,
		 "set this if you want to enable backward compatibility mode");

static unsigned long mask = 0xffffffff;
module_param(mask, ulong, 0644);
MODULE_PARM_DESC(mask,
		 "set this to the mask of event you want to enable (see doc)");

static int useinput = 1;
module_param(useinput, int, 0444);
MODULE_PARM_DESC(useinput,
		 "set this if you would like sonypi to feed events to the input subsystem");

static int check_ioport = 1;
module_param(check_ioport, int, 0444);
MODULE_PARM_DESC(check_ioport,
		 "set this to 0 if you think the automatic ioport check for sony-laptop is wrong");

#define SONYPI_DEVICE_MODEL_TYPE1	1
#define SONYPI_DEVICE_MODEL_TYPE2	2
#define SONYPI_DEVICE_MODEL_TYPE3	3

/* type1 models use those */
#define SONYPI_IRQ_PORT			0x8034
#define SONYPI_IRQ_SHIFT		22
#define SONYPI_TYPE1_BASE		0x50
#define SONYPI_G10A			(SONYPI_TYPE1_BASE+0x14)
#define SONYPI_TYPE1_REGION_SIZE	0x08
#define SONYPI_TYPE1_EVTYPE_OFFSET	0x04

/* type2 series specifics */
#define SONYPI_SIRQ			0x9b
#define SONYPI_SLOB			0x9c
#define SONYPI_SHIB			0x9d
#define SONYPI_TYPE2_REGION_SIZE	0x20
#define SONYPI_TYPE2_EVTYPE_OFFSET	0x12

/* type3 series specifics */
#define SONYPI_TYPE3_BASE		0x40
#define SONYPI_TYPE3_GID2		(SONYPI_TYPE3_BASE+0x48) /* 16 bits */
#define SONYPI_TYPE3_MISC		(SONYPI_TYPE3_BASE+0x6d) /* 8 bits  */
#define SONYPI_TYPE3_REGION_SIZE	0x20
#define SONYPI_TYPE3_EVTYPE_OFFSET	0x12

/* battery / brightness addresses */
#define SONYPI_BAT_FLAGS	0x81
#define SONYPI_LCD_LIGHT	0x96
#define SONYPI_BAT1_PCTRM	0xa0
#define SONYPI_BAT1_LEFT	0xa2
#define SONYPI_BAT1_MAXRT	0xa4
#define SONYPI_BAT2_PCTRM	0xa8
#define SONYPI_BAT2_LEFT	0xaa
#define SONYPI_BAT2_MAXRT	0xac
#define SONYPI_BAT1_MAXTK	0xb0
#define SONYPI_BAT1_FULL	0xb2
#define SONYPI_BAT2_MAXTK	0xb8
#define SONYPI_BAT2_FULL	0xba

/* FAN0 information (reverse engineered from ACPI tables) */
#define SONYPI_FAN0_STATUS	0x93
#define SONYPI_TEMP_STATUS	0xC1

/* ioports used for brightness and type2 events */
#define SONYPI_DATA_IOPORT	0x62
#define SONYPI_CST_IOPORT	0x66

/* The set of possible ioports */
struct sonypi_ioport_list {
	u16	port1;
	u16	port2;
};

static struct sonypi_ioport_list sonypi_type1_ioport_list[] = {
	{ 0x10c0, 0x10c4 },	/* looks like the default on C1Vx */
	{ 0x1080, 0x1084 },
	{ 0x1090, 0x1094 },
	{ 0x10a0, 0x10a4 },
	{ 0x10b0, 0x10b4 },
	{ 0x0, 0x0 }
};

static struct sonypi_ioport_list sonypi_type2_ioport_list[] = {
	{ 0x1080, 0x1084 },
	{ 0x10a0, 0x10a4 },
	{ 0x10c0, 0x10c4 },
	{ 0x10e0, 0x10e4 },
	{ 0x0, 0x0 }
};

/* same as in type 2 models */
static struct sonypi_ioport_list *sonypi_type3_ioport_list =
	sonypi_type2_ioport_list;

/* The set of possible interrupts */
struct sonypi_irq_list {
	u16	irq;
	u16	bits;
};

static struct sonypi_irq_list sonypi_type1_irq_list[] = {
	{ 11, 0x2 },	/* IRQ 11, GO22=0,GO23=1 in AML */
	{ 10, 0x1 },	/* IRQ 10, GO22=1,GO23=0 in AML */
	{  5, 0x0 },	/* IRQ  5, GO22=0,GO23=0 in AML */
	{  0, 0x3 }	/* no IRQ, GO22=1,GO23=1 in AML */
};

static struct sonypi_irq_list sonypi_type2_irq_list[] = {
	{ 11, 0x80 },	/* IRQ 11, 0x80 in SIRQ in AML */
	{ 10, 0x40 },	/* IRQ 10, 0x40 in SIRQ in AML */
	{  9, 0x20 },	/* IRQ  9, 0x20 in SIRQ in AML */
	{  6, 0x10 },	/* IRQ  6, 0x10 in SIRQ in AML */
	{  0, 0x00 }	/* no IRQ, 0x00 in SIRQ in AML */
};

/* same as in type2 models */
static struct sonypi_irq_list *sonypi_type3_irq_list = sonypi_type2_irq_list;

#define SONYPI_CAMERA_BRIGHTNESS		0
#define SONYPI_CAMERA_CONTRAST			1
#define SONYPI_CAMERA_HUE			2
#define SONYPI_CAMERA_COLOR			3
#define SONYPI_CAMERA_SHARPNESS			4

#define SONYPI_CAMERA_PICTURE			5
#define SONYPI_CAMERA_EXPOSURE_MASK		0xC
#define SONYPI_CAMERA_WHITE_BALANCE_MASK	0x3
#define SONYPI_CAMERA_PICTURE_MODE_MASK		0x30
#define SONYPI_CAMERA_MUTE_MASK			0x40

/* the rest don't need a loop until not 0xff */
#define SONYPI_CAMERA_AGC			6
#define SONYPI_CAMERA_AGC_MASK			0x30
#define SONYPI_CAMERA_SHUTTER_MASK 		0x7

#define SONYPI_CAMERA_SHUTDOWN_REQUEST		7
#define SONYPI_CAMERA_CONTROL			0x10

#define SONYPI_CAMERA_STATUS 			7
#define SONYPI_CAMERA_STATUS_READY 		0x2
#define SONYPI_CAMERA_STATUS_POSITION		0x4

#define SONYPI_DIRECTION_BACKWARDS 		0x4

#define SONYPI_CAMERA_REVISION 			8
#define SONYPI_CAMERA_ROMVERSION 		9

/* Event masks */
#define SONYPI_JOGGER_MASK			0x00000001
#define SONYPI_CAPTURE_MASK			0x00000002
#define SONYPI_FNKEY_MASK			0x00000004
#define SONYPI_BLUETOOTH_MASK			0x00000008
#define SONYPI_PKEY_MASK			0x00000010
#define SONYPI_BACK_MASK			0x00000020
#define SONYPI_HELP_MASK			0x00000040
#define SONYPI_LID_MASK				0x00000080
#define SONYPI_ZOOM_MASK			0x00000100
#define SONYPI_THUMBPHRASE_MASK			0x00000200
#define SONYPI_MEYE_MASK			0x00000400
#define SONYPI_MEMORYSTICK_MASK			0x00000800
#define SONYPI_BATTERY_MASK			0x00001000
#define SONYPI_WIRELESS_MASK			0x00002000

struct sonypi_event {
	u8	data;
	u8	event;
};

/* The set of possible button release events */
static struct sonypi_event sonypi_releaseev[] = {
	{ 0x00, SONYPI_EVENT_ANYBUTTON_RELEASED },
	{ 0, 0 }
};

/* The set of possible jogger events  */
static struct sonypi_event sonypi_joggerev[] = {
	{ 0x1f, SONYPI_EVENT_JOGDIAL_UP },
	{ 0x01, SONYPI_EVENT_JOGDIAL_DOWN },
	{ 0x5f, SONYPI_EVENT_JOGDIAL_UP_PRESSED },
	{ 0x41, SONYPI_EVENT_JOGDIAL_DOWN_PRESSED },
	{ 0x1e, SONYPI_EVENT_JOGDIAL_FAST_UP },
	{ 0x02, SONYPI_EVENT_JOGDIAL_FAST_DOWN },
	{ 0x5e, SONYPI_EVENT_JOGDIAL_FAST_UP_PRESSED },
	{ 0x42, SONYPI_EVENT_JOGDIAL_FAST_DOWN_PRESSED },
	{ 0x1d, SONYPI_EVENT_JOGDIAL_VFAST_UP },
	{ 0x03, SONYPI_EVENT_JOGDIAL_VFAST_DOWN },
	{ 0x5d, SONYPI_EVENT_JOGDIAL_VFAST_UP_PRESSED },
	{ 0x43, SONYPI_EVENT_JOGDIAL_VFAST_DOWN_PRESSED },
	{ 0x40, SONYPI_EVENT_JOGDIAL_PRESSED },
	{ 0, 0 }
};

/* The set of possible capture button events */
static struct sonypi_event sonypi_captureev[] = {
	{ 0x05, SONYPI_EVENT_CAPTURE_PARTIALPRESSED },
	{ 0x07, SONYPI_EVENT_CAPTURE_PRESSED },
	{ 0x01, SONYPI_EVENT_CAPTURE_PARTIALRELEASED },
	{ 0, 0 }
};

/* The set of possible fnkeys events */
static struct sonypi_event sonypi_fnkeyev[] = {
	{ 0x10, SONYPI_EVENT_FNKEY_ESC },
	{ 0x11, SONYPI_EVENT_FNKEY_F1 },
	{ 0x12, SONYPI_EVENT_FNKEY_F2 },
	{ 0x13, SONYPI_EVENT_FNKEY_F3 },
	{ 0x14, SONYPI_EVENT_FNKEY_F4 },
	{ 0x15, SONYPI_EVENT_FNKEY_F5 },
	{ 0x16, SONYPI_EVENT_FNKEY_F6 },
	{ 0x17, SONYPI_EVENT_FNKEY_F7 },
	{ 0x18, SONYPI_EVENT_FNKEY_F8 },
	{ 0x19, SONYPI_EVENT_FNKEY_F9 },
	{ 0x1a, SONYPI_EVENT_FNKEY_F10 },
	{ 0x1b, SONYPI_EVENT_FNKEY_F11 },
	{ 0x1c, SONYPI_EVENT_FNKEY_F12 },
	{ 0x1f, SONYPI_EVENT_FNKEY_RELEASED },
	{ 0x21, SONYPI_EVENT_FNKEY_1 },
	{ 0x22, SONYPI_EVENT_FNKEY_2 },
	{ 0x31, SONYPI_EVENT_FNKEY_D },
	{ 0x32, SONYPI_EVENT_FNKEY_E },
	{ 0x33, SONYPI_EVENT_FNKEY_F },
	{ 0x34, SONYPI_EVENT_FNKEY_S },
	{ 0x35, SONYPI_EVENT_FNKEY_B },
	{ 0x36, SONYPI_EVENT_FNKEY_ONLY },
	{ 0, 0 }
};

/* The set of possible program key events */
static struct sonypi_event sonypi_pkeyev[] = {
	{ 0x01, SONYPI_EVENT_PKEY_P1 },
	{ 0x02, SONYPI_EVENT_PKEY_P2 },
	{ 0x04, SONYPI_EVENT_PKEY_P3 },
	{ 0x5c, SONYPI_EVENT_PKEY_P1 },
	{ 0, 0 }
};

/* The set of possible bluetooth events */
static struct sonypi_event sonypi_blueev[] = {
	{ 0x55, SONYPI_EVENT_BLUETOOTH_PRESSED },
	{ 0x59, SONYPI_EVENT_BLUETOOTH_ON },
	{ 0x5a, SONYPI_EVENT_BLUETOOTH_OFF },
	{ 0, 0 }
};

/* The set of possible wireless events */
static struct sonypi_event sonypi_wlessev[] = {
	{ 0x59, SONYPI_EVENT_WIRELESS_ON },
	{ 0x5a, SONYPI_EVENT_WIRELESS_OFF },
	{ 0, 0 }
};

/* The set of possible back button events */
static struct sonypi_event sonypi_backev[] = {
	{ 0x20, SONYPI_EVENT_BACK_PRESSED },
	{ 0, 0 }
};

/* The set of possible help button events */
static struct sonypi_event sonypi_helpev[] = {
	{ 0x3b, SONYPI_EVENT_HELP_PRESSED },
	{ 0, 0 }
};


/* The set of possible lid events */
static struct sonypi_event sonypi_lidev[] = {
	{ 0x51, SONYPI_EVENT_LID_CLOSED },
	{ 0x50, SONYPI_EVENT_LID_OPENED },
	{ 0, 0 }
};

/* The set of possible zoom events */
static struct sonypi_event sonypi_zoomev[] = {
	{ 0x39, SONYPI_EVENT_ZOOM_PRESSED },
	{ 0, 0 }
};

/* The set of possible thumbphrase events */
static struct sonypi_event sonypi_thumbphraseev[] = {
	{ 0x3a, SONYPI_EVENT_THUMBPHRASE_PRESSED },
	{ 0, 0 }
};

/* The set of possible motioneye camera events */
static struct sonypi_event sonypi_meyeev[] = {
	{ 0x00, SONYPI_EVENT_MEYE_FACE },
	{ 0x01, SONYPI_EVENT_MEYE_OPPOSITE },
	{ 0, 0 }
};

/* The set of possible memorystick events */
static struct sonypi_event sonypi_memorystickev[] = {
	{ 0x53, SONYPI_EVENT_MEMORYSTICK_INSERT },
	{ 0x54, SONYPI_EVENT_MEMORYSTICK_EJECT },
	{ 0, 0 }
};

/* The set of possible battery events */
static struct sonypi_event sonypi_batteryev[] = {
	{ 0x20, SONYPI_EVENT_BATTERY_INSERT },
	{ 0x30, SONYPI_EVENT_BATTERY_REMOVE },
	{ 0, 0 }
};

static struct sonypi_eventtypes {
	int			model;
	u8			data;
	unsigned long		mask;
	struct sonypi_event *	events;
} sonypi_eventtypes[] = {
	{ SONYPI_DEVICE_MODEL_TYPE1, 0, 0xffffffff, sonypi_releaseev },
	{ SONYPI_DEVICE_MODEL_TYPE1, 0x70, SONYPI_MEYE_MASK, sonypi_meyeev },
	{ SONYPI_DEVICE_MODEL_TYPE1, 0x30, SONYPI_LID_MASK, sonypi_lidev },
	{ SONYPI_DEVICE_MODEL_TYPE1, 0x60, SONYPI_CAPTURE_MASK, sonypi_captureev },
	{ SONYPI_DEVICE_MODEL_TYPE1, 0x10, SONYPI_JOGGER_MASK, sonypi_joggerev },
	{ SONYPI_DEVICE_MODEL_TYPE1, 0x20, SONYPI_FNKEY_MASK, sonypi_fnkeyev },
	{ SONYPI_DEVICE_MODEL_TYPE1, 0x30, SONYPI_BLUETOOTH_MASK, sonypi_blueev },
	{ SONYPI_DEVICE_MODEL_TYPE1, 0x40, SONYPI_PKEY_MASK, sonypi_pkeyev },
	{ SONYPI_DEVICE_MODEL_TYPE1, 0x30, SONYPI_MEMORYSTICK_MASK, sonypi_memorystickev },
	{ SONYPI_DEVICE_MODEL_TYPE1, 0x40, SONYPI_BATTERY_MASK, sonypi_batteryev },

	{ SONYPI_DEVICE_MODEL_TYPE2, 0, 0xffffffff, sonypi_releaseev },
	{ SONYPI_DEVICE_MODEL_TYPE2, 0x38, SONYPI_LID_MASK, sonypi_lidev },
	{ SONYPI_DEVICE_MODEL_TYPE2, 0x11, SONYPI_JOGGER_MASK, sonypi_joggerev },
	{ SONYPI_DEVICE_MODEL_TYPE2, 0x61, SONYPI_CAPTURE_MASK, sonypi_captureev },
	{ SONYPI_DEVICE_MODEL_TYPE2, 0x21, SONYPI_FNKEY_MASK, sonypi_fnkeyev },
	{ SONYPI_DEVICE_MODEL_TYPE2, 0x31, SONYPI_BLUETOOTH_MASK, sonypi_blueev },
	{ SONYPI_DEVICE_MODEL_TYPE2, 0x08, SONYPI_PKEY_MASK, sonypi_pkeyev },
	{ SONYPI_DEVICE_MODEL_TYPE2, 0x11, SONYPI_BACK_MASK, sonypi_backev },
	{ SONYPI_DEVICE_MODEL_TYPE2, 0x21, SONYPI_HELP_MASK, sonypi_helpev },
	{ SONYPI_DEVICE_MODEL_TYPE2, 0x21, SONYPI_ZOOM_MASK, sonypi_zoomev },
	{ SONYPI_DEVICE_MODEL_TYPE2, 0x20, SONYPI_THUMBPHRASE_MASK, sonypi_thumbphraseev },
	{ SONYPI_DEVICE_MODEL_TYPE2, 0x31, SONYPI_MEMORYSTICK_MASK, sonypi_memorystickev },
	{ SONYPI_DEVICE_MODEL_TYPE2, 0x41, SONYPI_BATTERY_MASK, sonypi_batteryev },
	{ SONYPI_DEVICE_MODEL_TYPE2, 0x31, SONYPI_PKEY_MASK, sonypi_pkeyev },

	{ SONYPI_DEVICE_MODEL_TYPE3, 0, 0xffffffff, sonypi_releaseev },
	{ SONYPI_DEVICE_MODEL_TYPE3, 0x21, SONYPI_FNKEY_MASK, sonypi_fnkeyev },
	{ SONYPI_DEVICE_MODEL_TYPE3, 0x31, SONYPI_WIRELESS_MASK, sonypi_wlessev },
	{ SONYPI_DEVICE_MODEL_TYPE3, 0x31, SONYPI_MEMORYSTICK_MASK, sonypi_memorystickev },
	{ SONYPI_DEVICE_MODEL_TYPE3, 0x41, SONYPI_BATTERY_MASK, sonypi_batteryev },
	{ SONYPI_DEVICE_MODEL_TYPE3, 0x31, SONYPI_PKEY_MASK, sonypi_pkeyev },
	{ 0 }
};

#define SONYPI_BUF_SIZE	128

/* Correspondance table between sonypi events and input layer events */
static struct {
	int sonypiev;
	int inputev;
} sonypi_inputkeys[] = {
	{ SONYPI_EVENT_CAPTURE_PRESSED,	 	KEY_CAMERA },
	{ SONYPI_EVENT_FNKEY_ONLY, 		KEY_FN },
	{ SONYPI_EVENT_FNKEY_ESC, 		KEY_FN_ESC },
	{ SONYPI_EVENT_FNKEY_F1, 		KEY_FN_F1 },
	{ SONYPI_EVENT_FNKEY_F2, 		KEY_FN_F2 },
	{ SONYPI_EVENT_FNKEY_F3, 		KEY_FN_F3 },
	{ SONYPI_EVENT_FNKEY_F4, 		KEY_FN_F4 },
	{ SONYPI_EVENT_FNKEY_F5, 		KEY_FN_F5 },
	{ SONYPI_EVENT_FNKEY_F6, 		KEY_FN_F6 },
	{ SONYPI_EVENT_FNKEY_F7, 		KEY_FN_F7 },
	{ SONYPI_EVENT_FNKEY_F8, 		KEY_FN_F8 },
	{ SONYPI_EVENT_FNKEY_F9,		KEY_FN_F9 },
	{ SONYPI_EVENT_FNKEY_F10,		KEY_FN_F10 },
	{ SONYPI_EVENT_FNKEY_F11, 		KEY_FN_F11 },
	{ SONYPI_EVENT_FNKEY_F12,		KEY_FN_F12 },
	{ SONYPI_EVENT_FNKEY_1, 		KEY_FN_1 },
	{ SONYPI_EVENT_FNKEY_2, 		KEY_FN_2 },
	{ SONYPI_EVENT_FNKEY_D,			KEY_FN_D },
	{ SONYPI_EVENT_FNKEY_E,			KEY_FN_E },
	{ SONYPI_EVENT_FNKEY_F,			KEY_FN_F },
	{ SONYPI_EVENT_FNKEY_S,			KEY_FN_S },
	{ SONYPI_EVENT_FNKEY_B,			KEY_FN_B },
	{ SONYPI_EVENT_BLUETOOTH_PRESSED, 	KEY_BLUE },
	{ SONYPI_EVENT_BLUETOOTH_ON, 		KEY_BLUE },
	{ SONYPI_EVENT_PKEY_P1, 		KEY_PROG1 },
	{ SONYPI_EVENT_PKEY_P2, 		KEY_PROG2 },
	{ SONYPI_EVENT_PKEY_P3, 		KEY_PROG3 },
	{ SONYPI_EVENT_BACK_PRESSED, 		KEY_BACK },
	{ SONYPI_EVENT_HELP_PRESSED, 		KEY_HELP },
	{ SONYPI_EVENT_ZOOM_PRESSED, 		KEY_ZOOM },
	{ SONYPI_EVENT_THUMBPHRASE_PRESSED, 	BTN_THUMB },
	{ 0, 0 },
};

struct sonypi_keypress {
	struct input_dev *dev;
	int key;
};

static struct sonypi_device {
	struct pci_dev *dev;
	u16 irq;
	u16 bits;
	u16 ioport1;
	u16 ioport2;
	u16 region_size;
	u16 evtype_offset;
	int camera_power;
	int bluetooth_power;
	struct mutex lock;
	struct kfifo fifo;
	spinlock_t fifo_lock;
	wait_queue_head_t fifo_proc_list;
	struct fasync_struct *fifo_async;
	int open_count;
	int model;
	struct input_dev *input_jog_dev;
	struct input_dev *input_key_dev;
	struct work_struct input_work;
	struct kfifo input_fifo;
	spinlock_t input_fifo_lock;
} sonypi_device;

#define ITERATIONS_LONG		10000
#define ITERATIONS_SHORT	10

#define wait_on_command(quiet, command, iterations) { \
	unsigned int n = iterations; \
	while (--n && (command)) \
		udelay(1); \
	if (!n && (verbose || !quiet)) \
		printk(KERN_WARNING "sonypi command failed at %s : %s (line %d)\n", __FILE__, __func__, __LINE__); \
}

#ifdef CONFIG_ACPI
#define SONYPI_ACPI_ACTIVE (!acpi_disabled)
#else
#define SONYPI_ACPI_ACTIVE 0
#endif				/* CONFIG_ACPI */

#ifdef CONFIG_ACPI
static struct acpi_device *sonypi_acpi_device;
static int acpi_driver_registered;
#endif

static int sonypi_ec_write(u8 addr, u8 value)
{
#ifdef CONFIG_ACPI
	if (SONYPI_ACPI_ACTIVE)
		return ec_write(addr, value);
#endif
	wait_on_command(1, inb_p(SONYPI_CST_IOPORT) & 3, ITERATIONS_LONG);
	outb_p(0x81, SONYPI_CST_IOPORT);
	wait_on_command(0, inb_p(SONYPI_CST_IOPORT) & 2, ITERATIONS_LONG);
	outb_p(addr, SONYPI_DATA_IOPORT);
	wait_on_command(0, inb_p(SONYPI_CST_IOPORT) & 2, ITERATIONS_LONG);
	outb_p(value, SONYPI_DATA_IOPORT);
	wait_on_command(0, inb_p(SONYPI_CST_IOPORT) & 2, ITERATIONS_LONG);
	return 0;
}

static int sonypi_ec_read(u8 addr, u8 *value)
{
#ifdef CONFIG_ACPI
	if (SONYPI_ACPI_ACTIVE)
		return ec_read(addr, value);
#endif
	wait_on_command(1, inb_p(SONYPI_CST_IOPORT) & 3, ITERATIONS_LONG);
	outb_p(0x80, SONYPI_CST_IOPORT);
	wait_on_command(0, inb_p(SONYPI_CST_IOPORT) & 2, ITERATIONS_LONG);
	outb_p(addr, SONYPI_DATA_IOPORT);
	wait_on_command(0, inb_p(SONYPI_CST_IOPORT) & 2, ITERATIONS_LONG);
	*value = inb_p(SONYPI_DATA_IOPORT);
	return 0;
}

static int ec_read16(u8 addr, u16 *value)
{
	u8 val_lb, val_hb;
	if (sonypi_ec_read(addr, &val_lb))
		return -1;
	if (sonypi_ec_read(addr + 1, &val_hb))
		return -1;
	*value = val_lb | (val_hb << 8);
	return 0;
}

/* Initializes the device - this comes from the AML code in the ACPI bios */
static void sonypi_type1_srs(void)
{
	u32 v;

	pci_read_config_dword(sonypi_device.dev, SONYPI_G10A, &v);
	v = (v & 0xFFFF0000) | ((u32) sonypi_device.ioport1);
	pci_write_config_dword(sonypi_device.dev, SONYPI_G10A, v);

	pci_read_config_dword(sonypi_device.dev, SONYPI_G10A, &v);
	v = (v & 0xFFF0FFFF) |
	    (((u32) sonypi_device.ioport1 ^ sonypi_device.ioport2) << 16);
	pci_write_config_dword(sonypi_device.dev, SONYPI_G10A, v);

	v = inl(SONYPI_IRQ_PORT);
	v &= ~(((u32) 0x3) << SONYPI_IRQ_SHIFT);
	v |= (((u32) sonypi_device.bits) << SONYPI_IRQ_SHIFT);
	outl(v, SONYPI_IRQ_PORT);

	pci_read_config_dword(sonypi_device.dev, SONYPI_G10A, &v);
	v = (v & 0xFF1FFFFF) | 0x00C00000;
	pci_write_config_dword(sonypi_device.dev, SONYPI_G10A, v);
}

static void sonypi_type2_srs(void)
{
	if (sonypi_ec_write(SONYPI_SHIB, (sonypi_device.ioport1 & 0xFF00) >> 8))
		printk(KERN_WARNING "ec_write failed\n");
	if (sonypi_ec_write(SONYPI_SLOB, sonypi_device.ioport1 & 0x00FF))
		printk(KERN_WARNING "ec_write failed\n");
	if (sonypi_ec_write(SONYPI_SIRQ, sonypi_device.bits))
		printk(KERN_WARNING "ec_write failed\n");
	udelay(10);
}

static void sonypi_type3_srs(void)
{
	u16 v16;
	u8  v8;

	/* This model type uses the same initialiazation of
	 * the embedded controller as the type2 models. */
	sonypi_type2_srs();

	/* Initialization of PCI config space of the LPC interface bridge. */
	v16 = (sonypi_device.ioport1 & 0xFFF0) | 0x01;
	pci_write_config_word(sonypi_device.dev, SONYPI_TYPE3_GID2, v16);
	pci_read_config_byte(sonypi_device.dev, SONYPI_TYPE3_MISC, &v8);
	v8 = (v8 & 0xCF) | 0x10;
	pci_write_config_byte(sonypi_device.dev, SONYPI_TYPE3_MISC, v8);
}

/* Disables the device - this comes from the AML code in the ACPI bios */
static void sonypi_type1_dis(void)
{
	u32 v;

	pci_read_config_dword(sonypi_device.dev, SONYPI_G10A, &v);
	v = v & 0xFF3FFFFF;
	pci_write_config_dword(sonypi_device.dev, SONYPI_G10A, v);

	v = inl(SONYPI_IRQ_PORT);
	v |= (0x3 << SONYPI_IRQ_SHIFT);
	outl(v, SONYPI_IRQ_PORT);
}

static void sonypi_type2_dis(void)
{
	if (sonypi_ec_write(SONYPI_SHIB, 0))
		printk(KERN_WARNING "ec_write failed\n");
	if (sonypi_ec_write(SONYPI_SLOB, 0))
		printk(KERN_WARNING "ec_write failed\n");
	if (sonypi_ec_write(SONYPI_SIRQ, 0))
		printk(KERN_WARNING "ec_write failed\n");
}

static void sonypi_type3_dis(void)
{
	sonypi_type2_dis();
	udelay(10);
	pci_write_config_word(sonypi_device.dev, SONYPI_TYPE3_GID2, 0);
}

static u8 sonypi_call1(u8 dev)
{
	u8 v1, v2;

	wait_on_command(0, inb_p(sonypi_device.ioport2) & 2, ITERATIONS_LONG);
	outb(dev, sonypi_device.ioport2);
	v1 = inb_p(sonypi_device.ioport2);
	v2 = inb_p(sonypi_device.ioport1);
	return v2;
}

static u8 sonypi_call2(u8 dev, u8 fn)
{
	u8 v1;

	wait_on_command(0, inb_p(sonypi_device.ioport2) & 2, ITERATIONS_LONG);
	outb(dev, sonypi_device.ioport2);
	wait_on_command(0, inb_p(sonypi_device.ioport2) & 2, ITERATIONS_LONG);
	outb(fn, sonypi_device.ioport1);
	v1 = inb_p(sonypi_device.ioport1);
	return v1;
}

static u8 sonypi_call3(u8 dev, u8 fn, u8 v)
{
	u8 v1;

	wait_on_command(0, inb_p(sonypi_device.ioport2) & 2, ITERATIONS_LONG);
	outb(dev, sonypi_device.ioport2);
	wait_on_command(0, inb_p(sonypi_device.ioport2) & 2, ITERATIONS_LONG);
	outb(fn, sonypi_device.ioport1);
	wait_on_command(0, inb_p(sonypi_device.ioport2) & 2, ITERATIONS_LONG);
	outb(v, sonypi_device.ioport1);
	v1 = inb_p(sonypi_device.ioport1);
	return v1;
}

#if 0
/* Get brightness, hue etc. Unreliable... */
static u8 sonypi_read(u8 fn)
{
	u8 v1, v2;
	int n = 100;

	while (n--) {
		v1 = sonypi_call2(0x8f, fn);
		v2 = sonypi_call2(0x8f, fn);
		if (v1 == v2 && v1 != 0xff)
			return v1;
	}
	return 0xff;
}
#endif

/* Set brightness, hue etc */
static void sonypi_set(u8 fn, u8 v)
{
	wait_on_command(0, sonypi_call3(0x90, fn, v), ITERATIONS_SHORT);
}

/* Tests if the camera is ready */
static int sonypi_camera_ready(void)
{
	u8 v;

	v = sonypi_call2(0x8f, SONYPI_CAMERA_STATUS);
	return (v != 0xff && (v & SONYPI_CAMERA_STATUS_READY));
}

/* Turns the camera off */
static void sonypi_camera_off(void)
{
	sonypi_set(SONYPI_CAMERA_PICTURE, SONYPI_CAMERA_MUTE_MASK);

	if (!sonypi_device.camera_power)
		return;

	sonypi_call2(0x91, 0);
	sonypi_device.camera_power = 0;
}

/* Turns the camera on */
static void sonypi_camera_on(void)
{
	int i, j;

	if (sonypi_device.camera_power)
		return;

	for (j = 5; j > 0; j--) {

		while (sonypi_call2(0x91, 0x1))
			msleep(10);
		sonypi_call1(0x93);

		for (i = 400; i > 0; i--) {
			if (sonypi_camera_ready())
				break;
			msleep(10);
		}
		if (i)
			break;
	}

	if (j == 0) {
		printk(KERN_WARNING "sonypi: failed to power on camera\n");
		return;
	}

	sonypi_set(0x10, 0x5a);
	sonypi_device.camera_power = 1;
}

/* sets the bluetooth subsystem power state */
static void sonypi_setbluetoothpower(u8 state)
{
	state = !!state;

	if (sonypi_device.bluetooth_power == state)
		return;

	sonypi_call2(0x96, state);
	sonypi_call1(0x82);
	sonypi_device.bluetooth_power = state;
}

static void input_keyrelease(struct work_struct *work)
{
	struct sonypi_keypress kp;

	while (kfifo_out_locked(&sonypi_device.input_fifo, (unsigned char *)&kp,
			 sizeof(kp), &sonypi_device.input_fifo_lock)
			== sizeof(kp)) {
		msleep(10);
		input_report_key(kp.dev, kp.key, 0);
		input_sync(kp.dev);
	}
}

static void sonypi_report_input_event(u8 event)
{
	struct input_dev *jog_dev = sonypi_device.input_jog_dev;
	struct input_dev *key_dev = sonypi_device.input_key_dev;
	struct sonypi_keypress kp = { NULL };
	int i;

	switch (event) {
	case SONYPI_EVENT_JOGDIAL_UP:
	case SONYPI_EVENT_JOGDIAL_UP_PRESSED:
		input_report_rel(jog_dev, REL_WHEEL, 1);
		input_sync(jog_dev);
		break;

	case SONYPI_EVENT_JOGDIAL_DOWN:
	case SONYPI_EVENT_JOGDIAL_DOWN_PRESSED:
		input_report_rel(jog_dev, REL_WHEEL, -1);
		input_sync(jog_dev);
		break;

	case SONYPI_EVENT_JOGDIAL_PRESSED:
		kp.key = BTN_MIDDLE;
		kp.dev = jog_dev;
		break;

	case SONYPI_EVENT_FNKEY_RELEASED:
		/* Nothing, not all VAIOs generate this event */
		break;

	default:
		for (i = 0; sonypi_inputkeys[i].sonypiev; i++)
			if (event == sonypi_inputkeys[i].sonypiev) {
				kp.dev = key_dev;
				kp.key = sonypi_inputkeys[i].inputev;
				break;
			}
		break;
	}

	if (kp.dev) {
		input_report_key(kp.dev, kp.key, 1);
		input_sync(kp.dev);
		kfifo_in_locked(&sonypi_device.input_fifo,
			(unsigned char *)&kp, sizeof(kp),
			&sonypi_device.input_fifo_lock);
		schedule_work(&sonypi_device.input_work);
	}
}

/* Interrupt handler: some event is available */
static irqreturn_t sonypi_irq(int irq, void *dev_id)
{
	u8 v1, v2, event = 0;
	int i, j;

	v1 = inb_p(sonypi_device.ioport1);
	v2 = inb_p(sonypi_device.ioport1 + sonypi_device.evtype_offset);

	for (i = 0; sonypi_eventtypes[i].model; i++) {
		if (sonypi_device.model != sonypi_eventtypes[i].model)
			continue;
		if ((v2 & sonypi_eventtypes[i].data) !=
		    sonypi_eventtypes[i].data)
			continue;
		if (!(mask & sonypi_eventtypes[i].mask))
			continue;
		for (j = 0; sonypi_eventtypes[i].events[j].event; j++) {
			if (v1 == sonypi_eventtypes[i].events[j].data) {
				event = sonypi_eventtypes[i].events[j].event;
				goto found;
			}
		}
	}

	if (verbose)
		printk(KERN_WARNING
		       "sonypi: unknown event port1=0x%02x,port2=0x%02x\n",
		       v1, v2);
	/* We need to return IRQ_HANDLED here because there *are*
	 * events belonging to the sonypi device we don't know about,
	 * but we still don't want those to pollute the logs... */
	return IRQ_HANDLED;

found:
	if (verbose > 1)
		printk(KERN_INFO
		       "sonypi: event port1=0x%02x,port2=0x%02x\n", v1, v2);

	if (useinput)
		sonypi_report_input_event(event);

#ifdef CONFIG_ACPI
	if (sonypi_acpi_device)
		acpi_bus_generate_proc_event(sonypi_acpi_device, 1, event);
#endif

	kfifo_in_locked(&sonypi_device.fifo, (unsigned char *)&event,
			sizeof(event), &sonypi_device.fifo_lock);
	kill_fasync(&sonypi_device.fifo_async, SIGIO, POLL_IN);
	wake_up_interruptible(&sonypi_device.fifo_proc_list);

	return IRQ_HANDLED;
}

static int sonypi_misc_fasync(int fd, struct file *filp, int on)
{
	return fasync_helper(fd, filp, on, &sonypi_device.fifo_async);
}

static int sonypi_misc_release(struct inode *inode, struct file *file)
{
	mutex_lock(&sonypi_device.lock);
	sonypi_device.open_count--;
	mutex_unlock(&sonypi_device.lock);
	return 0;
}

static int sonypi_misc_open(struct inode *inode, struct file *file)
{
	mutex_lock(&sonypi_device.lock);
	/* Flush input queue on first open */
	if (!sonypi_device.open_count)
		kfifo_reset(&sonypi_device.fifo);
	sonypi_device.open_count++;
	mutex_unlock(&sonypi_device.lock);

	return 0;
}

static ssize_t sonypi_misc_read(struct file *file, char __user *buf,
				size_t count, loff_t *pos)
{
	ssize_t ret;
	unsigned char c;

	if ((kfifo_len(&sonypi_device.fifo) == 0) &&
	    (file->f_flags & O_NONBLOCK))
		return -EAGAIN;

	ret = wait_event_interruptible(sonypi_device.fifo_proc_list,
				       kfifo_len(&sonypi_device.fifo) != 0);
	if (ret)
		return ret;

	while (ret < count &&
	       (kfifo_out_locked(&sonypi_device.fifo, &c, sizeof(c),
				 &sonypi_device.fifo_lock) == sizeof(c))) {
		if (put_user(c, buf++))
			return -EFAULT;
		ret++;
	}

	if (ret > 0) {
		struct inode *inode = file->f_path.dentry->d_inode;
		inode->i_atime = current_fs_time(inode->i_sb);
	}

	return ret;
}

static unsigned int sonypi_misc_poll(struct file *file, poll_table *wait)
{
	poll_wait(file, &sonypi_device.fifo_proc_list, wait);
	if (kfifo_len(&sonypi_device.fifo))
		return POLLIN | POLLRDNORM;
	return 0;
}

static long sonypi_misc_ioctl(struct file *fp,
			     unsigned int cmd, unsigned long arg)
{
	long ret = 0;
	void __user *argp = (void __user *)arg;
	u8 val8;
	u16 val16;

	mutex_lock(&sonypi_device.lock);
	switch (cmd) {
	case SONYPI_IOCGBRT:
		if (sonypi_ec_read(SONYPI_LCD_LIGHT, &val8)) {
			ret = -EIO;
			break;
		}
		if (copy_to_user(argp, &val8, sizeof(val8)))
			ret = -EFAULT;
		break;
	case SONYPI_IOCSBRT:
		if (copy_from_user(&val8, argp, sizeof(val8))) {
			ret = -EFAULT;
			break;
		}
		if (sonypi_ec_write(SONYPI_LCD_LIGHT, val8))
			ret = -EIO;
		break;
	case SONYPI_IOCGBAT1CAP:
		if (ec_read16(SONYPI_BAT1_FULL, &val16)) {
			ret = -EIO;
			break;
		}
		if (copy_to_user(argp, &val16, sizeof(val16)))
			ret = -EFAULT;
		break;
	case SONYPI_IOCGBAT1REM:
		if (ec_read16(SONYPI_BAT1_LEFT, &val16)) {
			ret = -EIO;
			break;
		}
		if (copy_to_user(argp, &val16, sizeof(val16)))
			ret = -EFAULT;
		break;
	case SONYPI_IOCGBAT2CAP:
		if (ec_read16(SONYPI_BAT2_FULL, &val16)) {
			ret = -EIO;
			break;
		}
		if (copy_to_user(argp, &val16, sizeof(val16)))
			ret = -EFAULT;
		break;
	case SONYPI_IOCGBAT2REM:
		if (ec_read16(SONYPI_BAT2_LEFT, &val16)) {
			ret = -EIO;
			break;
		}
		if (copy_to_user(argp, &val16, sizeof(val16)))
			ret = -EFAULT;
		break;
	case SONYPI_IOCGBATFLAGS:
		if (sonypi_ec_read(SONYPI_BAT_FLAGS, &val8)) {
			ret = -EIO;
			break;
		}
		val8 &= 0x07;
		if (copy_to_user(argp, &val8, sizeof(val8)))
			ret = -EFAULT;
		break;
	case SONYPI_IOCGBLUE:
		val8 = sonypi_device.bluetooth_power;
		if (copy_to_user(argp, &val8, sizeof(val8)))
			ret = -EFAULT;
		break;
	case SONYPI_IOCSBLUE:
		if (copy_from_user(&val8, argp, sizeof(val8))) {
			ret = -EFAULT;
			break;
		}
		sonypi_setbluetoothpower(val8);
		break;
	/* FAN Controls */
	case SONYPI_IOCGFAN:
		if (sonypi_ec_read(SONYPI_FAN0_STATUS, &val8)) {
			ret = -EIO;
			break;
		}
		if (copy_to_user(argp, &val8, sizeof(val8)))
			ret = -EFAULT;
		break;
	case SONYPI_IOCSFAN:
		if (copy_from_user(&val8, argp, sizeof(val8))) {
			ret = -EFAULT;
			break;
		}
		if (sonypi_ec_write(SONYPI_FAN0_STATUS, val8))
			ret = -EIO;
		break;
	/* GET Temperature (useful under APM) */
	case SONYPI_IOCGTEMP:
		if (sonypi_ec_read(SONYPI_TEMP_STATUS, &val8)) {
			ret = -EIO;
			break;
		}
		if (copy_to_user(argp, &val8, sizeof(val8)))
			ret = -EFAULT;
		break;
	default:
		ret = -EINVAL;
	}
	mutex_unlock(&sonypi_device.lock);
	return ret;
}

static const struct file_operations sonypi_misc_fops = {
	.owner		= THIS_MODULE,
	.read		= sonypi_misc_read,
	.poll		= sonypi_misc_poll,
	.open		= sonypi_misc_open,
	.release	= sonypi_misc_release,
	.fasync		= sonypi_misc_fasync,
	.unlocked_ioctl	= sonypi_misc_ioctl,
	.llseek		= no_llseek,
};

static struct miscdevice sonypi_misc_device = {
	.minor		= MISC_DYNAMIC_MINOR,
	.name		= "sonypi",
	.fops		= &sonypi_misc_fops,
};

static void sonypi_enable(unsigned int camera_on)
{
	switch (sonypi_device.model) {
	case SONYPI_DEVICE_MODEL_TYPE1:
		sonypi_type1_srs();
		break;
	case SONYPI_DEVICE_MODEL_TYPE2:
		sonypi_type2_srs();
		break;
	case SONYPI_DEVICE_MODEL_TYPE3:
		sonypi_type3_srs();
		break;
	}

	sonypi_call1(0x82);
	sonypi_call2(0x81, 0xff);
	sonypi_call1(compat ? 0x92 : 0x82);

	/* Enable ACPI mode to get Fn key events */
	if (!SONYPI_ACPI_ACTIVE && fnkeyinit)
		outb(0xf0, 0xb2);

	if (camera && camera_on)
		sonypi_camera_on();
}

static int sonypi_disable(void)
{
	sonypi_call2(0x81, 0);	/* make sure we don't get any more events */
	if (camera)
		sonypi_camera_off();

	/* disable ACPI mode */
	if (!SONYPI_ACPI_ACTIVE && fnkeyinit)
		outb(0xf1, 0xb2);

	switch (sonypi_device.model) {
	case SONYPI_DEVICE_MODEL_TYPE1:
		sonypi_type1_dis();
		break;
	case SONYPI_DEVICE_MODEL_TYPE2:
		sonypi_type2_dis();
		break;
	case SONYPI_DEVICE_MODEL_TYPE3:
		sonypi_type3_dis();
		break;
	}

	return 0;
}

#ifdef CONFIG_ACPI
static int sonypi_acpi_add(struct acpi_device *device)
{
	sonypi_acpi_device = device;
	strcpy(acpi_device_name(device), "Sony laptop hotkeys");
	strcpy(acpi_device_class(device), "sony/hotkey");
	return 0;
}

static int sonypi_acpi_remove(struct acpi_device *device, int type)
{
	sonypi_acpi_device = NULL;
	return 0;
}

static const struct acpi_device_id sonypi_device_ids[] = {
	{"SNY6001", 0},
	{"", 0},
};

static struct acpi_driver sonypi_acpi_driver = {
	.name           = "sonypi",
	.class          = "hkey",
	.ids            = sonypi_device_ids,
	.ops            = {
		           .add = sonypi_acpi_add,
			   .remove = sonypi_acpi_remove,
	},
};
#endif

static int __devinit sonypi_create_input_devices(struct platform_device *pdev)
{
	struct input_dev *jog_dev;
	struct input_dev *key_dev;
	int i;
	int error;

	sonypi_device.input_jog_dev = jog_dev = input_allocate_device();
	if (!jog_dev)
		return -ENOMEM;

	jog_dev->name = "Sony Vaio Jogdial";
	jog_dev->id.bustype = BUS_ISA;
	jog_dev->id.vendor = PCI_VENDOR_ID_SONY;
	jog_dev->dev.parent = &pdev->dev;

	jog_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
	jog_dev->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_MIDDLE);
	jog_dev->relbit[0] = BIT_MASK(REL_WHEEL);

	sonypi_device.input_key_dev = key_dev = input_allocate_device();
	if (!key_dev) {
		error = -ENOMEM;
		goto err_free_jogdev;
	}

	key_dev->name = "Sony Vaio Keys";
	key_dev->id.bustype = BUS_ISA;
	key_dev->id.vendor = PCI_VENDOR_ID_SONY;
	key_dev->dev.parent = &pdev->dev;

	/* Initialize the Input Drivers: special keys */
	key_dev->evbit[0] = BIT_MASK(EV_KEY);
	for (i = 0; sonypi_inputkeys[i].sonypiev; i++)
		if (sonypi_inputkeys[i].inputev)
			set_bit(sonypi_inputkeys[i].inputev, key_dev->keybit);

	error = input_register_device(jog_dev);
	if (error)
		goto err_free_keydev;

	error = input_register_device(key_dev);
	if (error)
		goto err_unregister_jogdev;

	return 0;

 err_unregister_jogdev:
	input_unregister_device(jog_dev);
	/* Set to NULL so we don't free it again below */
	jog_dev = NULL;
 err_free_keydev:
	input_free_device(key_dev);
	sonypi_device.input_key_dev = NULL;
 err_free_jogdev:
	input_free_device(jog_dev);
	sonypi_device.input_jog_dev = NULL;

	return error;
}

static int __devinit sonypi_setup_ioports(struct sonypi_device *dev,
				const struct sonypi_ioport_list *ioport_list)
{
	/* try to detect if sony-laptop is being used and thus
	 * has already requested one of the known ioports.
	 * As in the deprecated check_region this is racy has we have
	 * multiple ioports available and one of them can be requested
	 * between this check and the subsequent request. Anyway, as an
	 * attempt to be some more user-friendly as we currently are,
	 * this is enough.
	 */
	const struct sonypi_ioport_list *check = ioport_list;
	while (check_ioport && check->port1) {
		if (!request_region(check->port1,
				   sonypi_device.region_size,
				   "Sony Programable I/O Device Check")) {
			printk(KERN_ERR "sonypi: ioport 0x%.4x busy, using sony-laptop? "
					"if not use check_ioport=0\n",
					check->port1);
			return -EBUSY;
		}
		release_region(check->port1, sonypi_device.region_size);
		check++;
	}

	while (ioport_list->port1) {

		if (request_region(ioport_list->port1,
				   sonypi_device.region_size,
				   "Sony Programable I/O Device")) {
			dev->ioport1 = ioport_list->port1;
			dev->ioport2 = ioport_list->port2;
			return 0;
		}
		ioport_list++;
	}

	return -EBUSY;
}

static int __devinit sonypi_setup_irq(struct sonypi_device *dev,
				      const struct sonypi_irq_list *irq_list)
{
	while (irq_list->irq) {

		if (!request_irq(irq_list->irq, sonypi_irq,
				 IRQF_SHARED, "sonypi", sonypi_irq)) {
			dev->irq = irq_list->irq;
			dev->bits = irq_list->bits;
			return 0;
		}
		irq_list++;
	}

	return -EBUSY;
}

static void __devinit sonypi_display_info(void)
{
	printk(KERN_INFO "sonypi: detected type%d model, "
	       "verbose = %d, fnkeyinit = %s, camera = %s, "
	       "compat = %s, mask = 0x%08lx, useinput = %s, acpi = %s\n",
	       sonypi_device.model,
	       verbose,
	       fnkeyinit ? "on" : "off",
	       camera ? "on" : "off",
	       compat ? "on" : "off",
	       mask,
	       useinput ? "on" : "off",
	       SONYPI_ACPI_ACTIVE ? "on" : "off");
	printk(KERN_INFO "sonypi: enabled at irq=%d, port1=0x%x, port2=0x%x\n",
	       sonypi_device.irq,
	       sonypi_device.ioport1, sonypi_device.ioport2);

	if (minor == -1)
		printk(KERN_INFO "sonypi: device allocated minor is %d\n",
		       sonypi_misc_device.minor);
}

static int __devinit sonypi_probe(struct platform_device *dev)
{
	const struct sonypi_ioport_list *ioport_list;
	const struct sonypi_irq_list *irq_list;
	struct pci_dev *pcidev;
	int error;

	printk(KERN_WARNING "sonypi: please try the sony-laptop module instead "
			"and report failures, see also "
			"http://www.linux.it/~malattia/wiki/index.php/Sony_drivers\n");

	spin_lock_init(&sonypi_device.fifo_lock);
	error = kfifo_alloc(&sonypi_device.fifo, SONYPI_BUF_SIZE, GFP_KERNEL);
	if (error) {
		printk(KERN_ERR "sonypi: kfifo_alloc failed\n");
		return error;
	}

	init_waitqueue_head(&sonypi_device.fifo_proc_list);
	mutex_init(&sonypi_device.lock);
	sonypi_device.bluetooth_power = -1;

	if ((pcidev = pci_get_device(PCI_VENDOR_ID_INTEL,
				     PCI_DEVICE_ID_INTEL_82371AB_3, NULL)))
		sonypi_device.model = SONYPI_DEVICE_MODEL_TYPE1;
	else if ((pcidev = pci_get_device(PCI_VENDOR_ID_INTEL,
					  PCI_DEVICE_ID_INTEL_ICH6_1, NULL)))
		sonypi_device.model = SONYPI_DEVICE_MODEL_TYPE3;
	else if ((pcidev = pci_get_device(PCI_VENDOR_ID_INTEL,
					  PCI_DEVICE_ID_INTEL_ICH7_1, NULL)))
		sonypi_device.model = SONYPI_DEVICE_MODEL_TYPE3;
	else
		sonypi_device.model = SONYPI_DEVICE_MODEL_TYPE2;

	if (pcidev && pci_enable_device(pcidev)) {
		printk(KERN_ERR "sonypi: pci_enable_device failed\n");
		error = -EIO;
		goto err_put_pcidev;
	}

	sonypi_device.dev = pcidev;

	if (sonypi_device.model == SONYPI_DEVICE_MODEL_TYPE1) {
		ioport_list = sonypi_type1_ioport_list;
		sonypi_device.region_size = SONYPI_TYPE1_REGION_SIZE;
		sonypi_device.evtype_offset = SONYPI_TYPE1_EVTYPE_OFFSET;
		irq_list = sonypi_type1_irq_list;
	} else if (sonypi_device.model == SONYPI_DEVICE_MODEL_TYPE2) {
		ioport_list = sonypi_type2_ioport_list;
		sonypi_device.region_size = SONYPI_TYPE2_REGION_SIZE;
		sonypi_device.evtype_offset = SONYPI_TYPE2_EVTYPE_OFFSET;
		irq_list = sonypi_type2_irq_list;
	} else {
		ioport_list = sonypi_type3_ioport_list;
		sonypi_device.region_size = SONYPI_TYPE3_REGION_SIZE;
		sonypi_device.evtype_offset = SONYPI_TYPE3_EVTYPE_OFFSET;
		irq_list = sonypi_type3_irq_list;
	}

	error = sonypi_setup_ioports(&sonypi_device, ioport_list);
	if (error) {
		printk(KERN_ERR "sonypi: failed to request ioports\n");
		goto err_disable_pcidev;
	}

	error = sonypi_setup_irq(&sonypi_device, irq_list);
	if (error) {
		printk(KERN_ERR "sonypi: request_irq failed\n");
		goto err_free_ioports;
	}

	if (minor != -1)
		sonypi_misc_device.minor = minor;
	error = misc_register(&sonypi_misc_device);
	if (error) {
		printk(KERN_ERR "sonypi: misc_register failed\n");
		goto err_free_irq;
	}

	sonypi_display_info();

	if (useinput) {

		error = sonypi_create_input_devices(dev);
		if (error) {
			printk(KERN_ERR
				"sonypi: failed to create input devices\n");
			goto err_miscdev_unregister;
		}

		spin_lock_init(&sonypi_device.input_fifo_lock);
		error = kfifo_alloc(&sonypi_device.input_fifo, SONYPI_BUF_SIZE,
				GFP_KERNEL);
		if (error) {
			printk(KERN_ERR "sonypi: kfifo_alloc failed\n");
			goto err_inpdev_unregister;
		}

		INIT_WORK(&sonypi_device.input_work, input_keyrelease);
	}

	sonypi_enable(0);

	return 0;

 err_inpdev_unregister:
	input_unregister_device(sonypi_device.input_key_dev);
	input_unregister_device(sonypi_device.input_jog_dev);
 err_miscdev_unregister:
	misc_deregister(&sonypi_misc_device);
 err_free_irq:
	free_irq(sonypi_device.irq, sonypi_irq);
 err_free_ioports:
	release_region(sonypi_device.ioport1, sonypi_device.region_size);
 err_disable_pcidev:
	if (pcidev)
		pci_disable_device(pcidev);
 err_put_pcidev:
	pci_dev_put(pcidev);
	kfifo_free(&sonypi_device.fifo);

	return error;
}

static int __devexit sonypi_remove(struct platform_device *dev)
{
	sonypi_disable();

	synchronize_irq(sonypi_device.irq);
	flush_scheduled_work();

	if (useinput) {
		input_unregister_device(sonypi_device.input_key_dev);
		input_unregister_device(sonypi_device.input_jog_dev);
		kfifo_free(&sonypi_device.input_fifo);
	}

	misc_deregister(&sonypi_misc_device);

	free_irq(sonypi_device.irq, sonypi_irq);
	release_region(sonypi_device.ioport1, sonypi_device.region_size);

	if (sonypi_device.dev) {
		pci_disable_device(sonypi_device.dev);
		pci_dev_put(sonypi_device.dev);
	}

	kfifo_free(&sonypi_device.fifo);

	return 0;
}

#ifdef CONFIG_PM
static int old_camera_power;

static int sonypi_suspend(struct platform_device *dev, pm_message_t state)
{
	old_camera_power = sonypi_device.camera_power;
	sonypi_disable();

	return 0;
}

static int sonypi_resume(struct platform_device *dev)
{
	sonypi_enable(old_camera_power);
	return 0;
}
#else
#define sonypi_suspend	NULL
#define sonypi_resume	NULL
#endif

static void sonypi_shutdown(struct platform_device *dev)
{
	sonypi_disable();
}

static struct platform_driver sonypi_driver = {
	.driver		= {
		.name	= "sonypi",
		.owner	= THIS_MODULE,
	},
	.probe		= sonypi_probe,
	.remove		= __devexit_p(sonypi_remove),
	.shutdown	= sonypi_shutdown,
	.suspend	= sonypi_suspend,
	.resume		= sonypi_resume,
};

static struct platform_device *sonypi_platform_device;

static struct dmi_system_id __initdata sonypi_dmi_table[] = {
	{
		.ident = "Sony Vaio",
		.matches = {
			DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
			DMI_MATCH(DMI_PRODUCT_NAME, "PCG-"),
		},
	},
	{
		.ident = "Sony Vaio",
		.matches = {
			DMI_MATCH(DMI_SYS_VENDOR, "Sony Corporation"),
			DMI_MATCH(DMI_PRODUCT_NAME, "VGN-"),
		},
	},
	{ }
};

static int __init sonypi_init(void)
{
	int error;

	printk(KERN_INFO
		"sonypi: Sony Programmable I/O Controller Driver v%s.\n",
		SONYPI_DRIVER_VERSION);

	if (!dmi_check_system(sonypi_dmi_table))
		return -ENODEV;

	error = platform_driver_register(&sonypi_driver);
	if (error)
		return error;

	sonypi_platform_device = platform_device_alloc("sonypi", -1);
	if (!sonypi_platform_device) {
		error = -ENOMEM;
		goto err_driver_unregister;
	}

	error = platform_device_add(sonypi_platform_device);
	if (error)
		goto err_free_device;

#ifdef CONFIG_ACPI
	if (acpi_bus_register_driver(&sonypi_acpi_driver) >= 0)
		acpi_driver_registered = 1;
#endif

	return 0;

 err_free_device:
	platform_device_put(sonypi_platform_device);
 err_driver_unregister:
	platform_driver_unregister(&sonypi_driver);
	return error;
}

static void __exit sonypi_exit(void)
{
#ifdef CONFIG_ACPI
	if (acpi_driver_registered)
		acpi_bus_unregister_driver(&sonypi_acpi_driver);
#endif
	platform_device_unregister(sonypi_platform_device);
	platform_driver_unregister(&sonypi_driver);
	printk(KERN_INFO "sonypi: removed.\n");
}

module_init(sonypi_init);
module_exit(sonypi_exit);
'n2662' href='#n2662'>2662 2663 2664 2665 2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
                                                                          


                                                                       

                                                           








                                                                             


















                              
                     






                          
                   



                         
                     
                      







                        



                   
                                


                                                               


                                                                        
 



                                                                             





                                                                          
 































































































                                                                                        



















                                                                               
                                           
              
                                             



                                                                               
                                           
              
                                             

 
                                         
 
                               













                                                                              
                                                        
              
                                                          



                                                                              
                                                        
              
                                                          

 
                                        
 
                                         



























                                                                                     
                                                          
                
                                                            

                                                     
                                                          
                
                                                            
          
                                                                    














                                                                                       
                                                                
                
                                                                  

                                                     
                                                                
                
                                                                  
          



                                                                  









































































































































































































                                                                                      
 




























































































































































































































































































































































































































































































































































































































































































































                                                                                                         
                                           










































































                                                                                       
                                                              












































































































































































































































































































                                                                                             
                    



































                                                                    
                         














































































                                                                                              




                                                               











































































                                                                                   
 





































































































































































































































































                                                                                            
                                                                          














                                                                                                         


                                                                                
                                                                            










                                                                                       
                                                                       
                                                   

















                                                                                           
                                                              
 

                                                  


































                                                                           
                                                                




























































                                                                               
                                                                       
                                          

                                                                                        





































































                                                                                    
                                                 

                                                                             














































































































































































































































                                                                                       
                                                   








                                                   
                                                     














                                                               
                                                                                     

























                                                                       
                                                                               
 



                              







                                                             
 



























                                                                    
                                                         






                                                                                         
 
                                        








                                                             


                        
                                                                        





























                                                            
                                                                                 
 
                                                  




                                  
                             















                                                              
                                              














                                                                  
                
                                          







                                                                      









                                        
                                                                            
                                            












                                                                   
                                                                             





                                                                
                                                                             





                                                                
                                                                             





                                                                        
                                                                             





                                                                         
                                                                           


                                     
                                                                    












                                                                     

                                                                       




























                                                                             

                                                      






























                                                                            

                                              






                                                                                        
                                                      
 




























                                                            
                    





























                                                                     
                                                                                                    





















                                                                    
                                 


                        
                 



                                                                               

                                                   
 


                              
 

                                                      
 






                                                                              
 






                                                 
                            
 

                                                                          

                                  
                   
                               







                                 
                             

                                                    
                   

                                         







                                              




                                    














                                                                          

















                                                
         












                                                                                                 
                                                                












                                                                                  
                   
                                          

                        
                                     
                                               


                                                                               






                                                                     
 






                                                 
                   
                                                                    

                                                                 
















                                                                    
                   






























                                                                                

                                                      




























                                                                              

                                        












                                                                                                                
                                                            









                                                                                               
                                                      
 
















                                                 
 
                                                                 
 

                                                            
 











                                             
 
 
                                                   
                                                                       












                                                             
 
                                                    
 
 










                                                   
         
 
 

      

                                                                                            
 

                                                          
                                                               
                                           
 

                                                                
 







                                                           
                                   















                                                    
 


                 













                                               
 
                                        
 





                                                       
 


                                            
 


                                                                   
 

                   
 



                                               
 







                                                    
 
      
 


                                        
 









                                               

         












                                        


                              
                             
/* sunhme.c: Sparc HME/BigMac 10/100baseT half/full duplex auto switching,
 *           auto carrier detecting ethernet driver.  Also known as the
 *           "Happy Meal Ethernet" found on SunSwift SBUS cards.
 *
 * Copyright (C) 1996, 1998, 1999, 2002, 2003,
		 2006 David S. Miller (davem@davemloft.net)
 *
 * Changes :
 * 2000/11/11 Willy Tarreau <willy AT meta-x.org>
 *   - port to non-sparc architectures. Tested only on x86 and
 *     only currently works with QFE PCI cards.
 *   - ability to specify the MAC address at module load time by passing this
 *     argument : macaddr=0x00,0x10,0x20,0x30,0x40,0x50
 */

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/in.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/crc32.h>
#include <linux/random.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/mm.h>
#include <linux/bitops.h>

#include <asm/system.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <asm/byteorder.h>

#ifdef CONFIG_SPARC
#include <asm/idprom.h>
#include <asm/sbus.h>
#include <asm/openprom.h>
#include <asm/oplib.h>
#include <asm/prom.h>
#include <asm/auxio.h>
#endif
#include <asm/uaccess.h>

#include <asm/pgtable.h>
#include <asm/irq.h>

#ifdef CONFIG_PCI
#include <linux/pci.h>
#endif

#include "sunhme.h"

#define DRV_NAME	"sunhme"
#define DRV_VERSION	"3.00"
#define DRV_RELDATE	"June 23, 2006"
#define DRV_AUTHOR	"David S. Miller (davem@davemloft.net)"

static char version[] =
	DRV_NAME ".c:v" DRV_VERSION " " DRV_RELDATE " " DRV_AUTHOR "\n";

MODULE_VERSION(DRV_VERSION);
MODULE_AUTHOR(DRV_AUTHOR);
MODULE_DESCRIPTION("Sun HappyMealEthernet(HME) 10/100baseT ethernet driver");
MODULE_LICENSE("GPL");

static int macaddr[6];

/* accept MAC address of the form macaddr=0x08,0x00,0x20,0x30,0x40,0x50 */
module_param_array(macaddr, int, NULL, 0);
MODULE_PARM_DESC(macaddr, "Happy Meal MAC address to set");

#ifdef CONFIG_SBUS
static struct quattro *qfe_sbus_list;
#endif

#ifdef CONFIG_PCI
static struct quattro *qfe_pci_list;
#endif

#undef HMEDEBUG
#undef SXDEBUG
#undef RXDEBUG
#undef TXDEBUG
#undef TXLOGGING

#ifdef TXLOGGING
struct hme_tx_logent {
	unsigned int tstamp;
	int tx_new, tx_old;
	unsigned int action;
#define TXLOG_ACTION_IRQ	0x01
#define TXLOG_ACTION_TXMIT	0x02
#define TXLOG_ACTION_TBUSY	0x04
#define TXLOG_ACTION_NBUFS	0x08
	unsigned int status;
};
#define TX_LOG_LEN	128
static struct hme_tx_logent tx_log[TX_LOG_LEN];
static int txlog_cur_entry;
static __inline__ void tx_add_log(struct happy_meal *hp, unsigned int a, unsigned int s)
{
	struct hme_tx_logent *tlp;
	unsigned long flags;

	save_and_cli(flags);
	tlp = &tx_log[txlog_cur_entry];
	tlp->tstamp = (unsigned int)jiffies;
	tlp->tx_new = hp->tx_new;
	tlp->tx_old = hp->tx_old;
	tlp->action = a;
	tlp->status = s;
	txlog_cur_entry = (txlog_cur_entry + 1) & (TX_LOG_LEN - 1);
	restore_flags(flags);
}
static __inline__ void tx_dump_log(void)
{
	int i, this;

	this = txlog_cur_entry;
	for (i = 0; i < TX_LOG_LEN; i++) {
		printk("TXLOG[%d]: j[%08x] tx[N(%d)O(%d)] action[%08x] stat[%08x]\n", i,
		       tx_log[this].tstamp,
		       tx_log[this].tx_new, tx_log[this].tx_old,
		       tx_log[this].action, tx_log[this].status);
		this = (this + 1) & (TX_LOG_LEN - 1);
	}
}
static __inline__ void tx_dump_ring(struct happy_meal *hp)
{
	struct hmeal_init_block *hb = hp->happy_block;
	struct happy_meal_txd *tp = &hb->happy_meal_txd[0];
	int i;

	for (i = 0; i < TX_RING_SIZE; i+=4) {
		printk("TXD[%d..%d]: [%08x:%08x] [%08x:%08x] [%08x:%08x] [%08x:%08x]\n",
		       i, i + 4,
		       le32_to_cpu(tp[i].tx_flags), le32_to_cpu(tp[i].tx_addr),
		       le32_to_cpu(tp[i + 1].tx_flags), le32_to_cpu(tp[i + 1].tx_addr),
		       le32_to_cpu(tp[i + 2].tx_flags), le32_to_cpu(tp[i + 2].tx_addr),
		       le32_to_cpu(tp[i + 3].tx_flags), le32_to_cpu(tp[i + 3].tx_addr));
	}
}
#else
#define tx_add_log(hp, a, s)		do { } while(0)
#define tx_dump_log()			do { } while(0)
#define tx_dump_ring(hp)		do { } while(0)
#endif

#ifdef HMEDEBUG
#define HMD(x)  printk x
#else
#define HMD(x)
#endif

/* #define AUTO_SWITCH_DEBUG */

#ifdef AUTO_SWITCH_DEBUG
#define ASD(x)  printk x
#else
#define ASD(x)
#endif

#define DEFAULT_IPG0      16 /* For lance-mode only */
#define DEFAULT_IPG1       8 /* For all modes */
#define DEFAULT_IPG2       4 /* For all modes */
#define DEFAULT_JAMSIZE    4 /* Toe jam */

/* NOTE: In the descriptor writes one _must_ write the address
 *	 member _first_.  The card must not be allowed to see
 *	 the updated descriptor flags until the address is
 *	 correct.  I've added a write memory barrier between
 *	 the two stores so that I can sleep well at night... -DaveM
 */

#if defined(CONFIG_SBUS) && defined(CONFIG_PCI)
static void sbus_hme_write32(void __iomem *reg, u32 val)
{
	sbus_writel(val, reg);
}

static u32 sbus_hme_read32(void __iomem *reg)
{
	return sbus_readl(reg);
}

static void sbus_hme_write_rxd(struct happy_meal_rxd *rxd, u32 flags, u32 addr)
{
	rxd->rx_addr = (__force hme32)addr;
	wmb();
	rxd->rx_flags = (__force hme32)flags;
}

static void sbus_hme_write_txd(struct happy_meal_txd *txd, u32 flags, u32 addr)
{
	txd->tx_addr = (__force hme32)addr;
	wmb();
	txd->tx_flags = (__force hme32)flags;
}

static u32 sbus_hme_read_desc32(hme32 *p)
{
	return (__force u32)*p;
}

static void pci_hme_write32(void __iomem *reg, u32 val)
{
	writel(val, reg);
}

static u32 pci_hme_read32(void __iomem *reg)
{
	return readl(reg);
}

static void pci_hme_write_rxd(struct happy_meal_rxd *rxd, u32 flags, u32 addr)
{
	rxd->rx_addr = (__force hme32)cpu_to_le32(addr);
	wmb();
	rxd->rx_flags = (__force hme32)cpu_to_le32(flags);
}

static void pci_hme_write_txd(struct happy_meal_txd *txd, u32 flags, u32 addr)
{
	txd->tx_addr = (__force hme32)cpu_to_le32(addr);
	wmb();
	txd->tx_flags = (__force hme32)cpu_to_le32(flags);
}

static u32 pci_hme_read_desc32(hme32 *p)
{
	return le32_to_cpup((__le32 *)p);
}

#define hme_write32(__hp, __reg, __val) \
	((__hp)->write32((__reg), (__val)))
#define hme_read32(__hp, __reg) \
	((__hp)->read32(__reg))
#define hme_write_rxd(__hp, __rxd, __flags, __addr) \
	((__hp)->write_rxd((__rxd), (__flags), (__addr)))
#define hme_write_txd(__hp, __txd, __flags, __addr) \
	((__hp)->write_txd((__txd), (__flags), (__addr)))
#define hme_read_desc32(__hp, __p) \
	((__hp)->read_desc32(__p))
#define hme_dma_map(__hp, __ptr, __size, __dir) \
	((__hp)->dma_map((__hp)->happy_dev, (__ptr), (__size), (__dir)))
#define hme_dma_unmap(__hp, __addr, __size, __dir) \
	((__hp)->dma_unmap((__hp)->happy_dev, (__addr), (__size), (__dir)))
#define hme_dma_sync_for_cpu(__hp, __addr, __size, __dir) \
	((__hp)->dma_sync_for_cpu((__hp)->happy_dev, (__addr), (__size), (__dir)))
#define hme_dma_sync_for_device(__hp, __addr, __size, __dir) \
	((__hp)->dma_sync_for_device((__hp)->happy_dev, (__addr), (__size), (__dir)))
#else
#ifdef CONFIG_SBUS
/* SBUS only compilation */
#define hme_write32(__hp, __reg, __val) \
	sbus_writel((__val), (__reg))
#define hme_read32(__hp, __reg) \
	sbus_readl(__reg)
#define hme_write_rxd(__hp, __rxd, __flags, __addr) \
do {	(__rxd)->rx_addr = (__force hme32)(u32)(__addr); \
	wmb(); \
	(__rxd)->rx_flags = (__force hme32)(u32)(__flags); \
} while(0)
#define hme_write_txd(__hp, __txd, __flags, __addr) \
do {	(__txd)->tx_addr = (__force hme32)(u32)(__addr); \
	wmb(); \
	(__txd)->tx_flags = (__force hme32)(u32)(__flags); \
} while(0)
#define hme_read_desc32(__hp, __p)	((__force u32)(hme32)*(__p))
#define hme_dma_map(__hp, __ptr, __size, __dir) \
	sbus_map_single((__hp)->happy_dev, (__ptr), (__size), (__dir))
#define hme_dma_unmap(__hp, __addr, __size, __dir) \
	sbus_unmap_single((__hp)->happy_dev, (__addr), (__size), (__dir))
#define hme_dma_sync_for_cpu(__hp, __addr, __size, __dir) \
	sbus_dma_sync_single_for_cpu((__hp)->happy_dev, (__addr), (__size), (__dir))
#define hme_dma_sync_for_device(__hp, __addr, __size, __dir) \
	sbus_dma_sync_single_for_device((__hp)->happy_dev, (__addr), (__size), (__dir))
#else
/* PCI only compilation */
#define hme_write32(__hp, __reg, __val) \
	writel((__val), (__reg))
#define hme_read32(__hp, __reg) \
	readl(__reg)
#define hme_write_rxd(__hp, __rxd, __flags, __addr) \
do {	(__rxd)->rx_addr = (__force hme32)cpu_to_le32(__addr); \
	wmb(); \
	(__rxd)->rx_flags = (__force hme32)cpu_to_le32(__flags); \
} while(0)
#define hme_write_txd(__hp, __txd, __flags, __addr) \
do {	(__txd)->tx_addr = (__force hme32)cpu_to_le32(__addr); \
	wmb(); \
	(__txd)->tx_flags = (__force hme32)cpu_to_le32(__flags); \
} while(0)
static inline u32 hme_read_desc32(struct happy_meal *hp, hme32 *p)
{
	return le32_to_cpup((__le32 *)p);
}
#define hme_dma_map(__hp, __ptr, __size, __dir) \
	pci_map_single((__hp)->happy_dev, (__ptr), (__size), (__dir))
#define hme_dma_unmap(__hp, __addr, __size, __dir) \
	pci_unmap_single((__hp)->happy_dev, (__addr), (__size), (__dir))
#define hme_dma_sync_for_cpu(__hp, __addr, __size, __dir) \
	pci_dma_sync_single_for_cpu((__hp)->happy_dev, (__addr), (__size), (__dir))
#define hme_dma_sync_for_device(__hp, __addr, __size, __dir) \
	pci_dma_sync_single_for_device((__hp)->happy_dev, (__addr), (__size), (__dir))
#endif
#endif


#ifdef SBUS_DMA_BIDIRECTIONAL
#	define DMA_BIDIRECTIONAL	SBUS_DMA_BIDIRECTIONAL
#else
#	define DMA_BIDIRECTIONAL	0
#endif

#ifdef SBUS_DMA_FROMDEVICE
#	define DMA_FROMDEVICE		SBUS_DMA_FROMDEVICE
#else
#	define DMA_TODEVICE		1
#endif

#ifdef SBUS_DMA_TODEVICE
#	define DMA_TODEVICE		SBUS_DMA_TODEVICE
#else
#	define DMA_FROMDEVICE		2
#endif


/* Oh yes, the MIF BitBang is mighty fun to program.  BitBucket is more like it. */
static void BB_PUT_BIT(struct happy_meal *hp, void __iomem *tregs, int bit)
{
	hme_write32(hp, tregs + TCVR_BBDATA, bit);
	hme_write32(hp, tregs + TCVR_BBCLOCK, 0);
	hme_write32(hp, tregs + TCVR_BBCLOCK, 1);
}

#if 0
static u32 BB_GET_BIT(struct happy_meal *hp, void __iomem *tregs, int internal)
{
	u32 ret;

	hme_write32(hp, tregs + TCVR_BBCLOCK, 0);
	hme_write32(hp, tregs + TCVR_BBCLOCK, 1);
	ret = hme_read32(hp, tregs + TCVR_CFG);
	if (internal)
		ret &= TCV_CFG_MDIO0;
	else
		ret &= TCV_CFG_MDIO1;

	return ret;
}
#endif

static u32 BB_GET_BIT2(struct happy_meal *hp, void __iomem *tregs, int internal)
{
	u32 retval;

	hme_write32(hp, tregs + TCVR_BBCLOCK, 0);
	udelay(1);
	retval = hme_read32(hp, tregs + TCVR_CFG);
	if (internal)
		retval &= TCV_CFG_MDIO0;
	else
		retval &= TCV_CFG_MDIO1;
	hme_write32(hp, tregs + TCVR_BBCLOCK, 1);

	return retval;
}

#define TCVR_FAILURE      0x80000000     /* Impossible MIF read value */

static int happy_meal_bb_read(struct happy_meal *hp,
			      void __iomem *tregs, int reg)
{
	u32 tmp;
	int retval = 0;
	int i;

	ASD(("happy_meal_bb_read: reg=%d ", reg));

	/* Enable the MIF BitBang outputs. */
	hme_write32(hp, tregs + TCVR_BBOENAB, 1);

	/* Force BitBang into the idle state. */
	for (i = 0; i < 32; i++)
		BB_PUT_BIT(hp, tregs, 1);

	/* Give it the read sequence. */
	BB_PUT_BIT(hp, tregs, 0);
	BB_PUT_BIT(hp, tregs, 1);
	BB_PUT_BIT(hp, tregs, 1);
	BB_PUT_BIT(hp, tregs, 0);

	/* Give it the PHY address. */
	tmp = hp->paddr & 0xff;
	for (i = 4; i >= 0; i--)
		BB_PUT_BIT(hp, tregs, ((tmp >> i) & 1));

	/* Tell it what register we want to read. */
	tmp = (reg & 0xff);
	for (i = 4; i >= 0; i--)
		BB_PUT_BIT(hp, tregs, ((tmp >> i) & 1));

	/* Close down the MIF BitBang outputs. */
	hme_write32(hp, tregs + TCVR_BBOENAB, 0);

	/* Now read in the value. */
	(void) BB_GET_BIT2(hp, tregs, (hp->tcvr_type == internal));
	for (i = 15; i >= 0; i--)
		retval |= BB_GET_BIT2(hp, tregs, (hp->tcvr_type == internal));
	(void) BB_GET_BIT2(hp, tregs, (hp->tcvr_type == internal));
	(void) BB_GET_BIT2(hp, tregs, (hp->tcvr_type == internal));
	(void) BB_GET_BIT2(hp, tregs, (hp->tcvr_type == internal));
	ASD(("value=%x\n", retval));
	return retval;
}

static void happy_meal_bb_write(struct happy_meal *hp,
				void __iomem *tregs, int reg,
				unsigned short value)
{
	u32 tmp;
	int i;

	ASD(("happy_meal_bb_write: reg=%d value=%x\n", reg, value));

	/* Enable the MIF BitBang outputs. */
	hme_write32(hp, tregs + TCVR_BBOENAB, 1);

	/* Force BitBang into the idle state. */
	for (i = 0; i < 32; i++)
		BB_PUT_BIT(hp, tregs, 1);

	/* Give it write sequence. */
	BB_PUT_BIT(hp, tregs, 0);
	BB_PUT_BIT(hp, tregs, 1);
	BB_PUT_BIT(hp, tregs, 0);
	BB_PUT_BIT(hp, tregs, 1);

	/* Give it the PHY address. */
	tmp = (hp->paddr & 0xff);
	for (i = 4; i >= 0; i--)
		BB_PUT_BIT(hp, tregs, ((tmp >> i) & 1));

	/* Tell it what register we will be writing. */
	tmp = (reg & 0xff);
	for (i = 4; i >= 0; i--)
		BB_PUT_BIT(hp, tregs, ((tmp >> i) & 1));

	/* Tell it to become ready for the bits. */
	BB_PUT_BIT(hp, tregs, 1);
	BB_PUT_BIT(hp, tregs, 0);

	for (i = 15; i >= 0; i--)
		BB_PUT_BIT(hp, tregs, ((value >> i) & 1));

	/* Close down the MIF BitBang outputs. */
	hme_write32(hp, tregs + TCVR_BBOENAB, 0);
}

#define TCVR_READ_TRIES   16

static int happy_meal_tcvr_read(struct happy_meal *hp,
				void __iomem *tregs, int reg)
{
	int tries = TCVR_READ_TRIES;
	int retval;

	ASD(("happy_meal_tcvr_read: reg=0x%02x ", reg));
	if (hp->tcvr_type == none) {
		ASD(("no transceiver, value=TCVR_FAILURE\n"));
		return TCVR_FAILURE;
	}

	if (!(hp->happy_flags & HFLAG_FENABLE)) {
		ASD(("doing bit bang\n"));
		return happy_meal_bb_read(hp, tregs, reg);
	}

	hme_write32(hp, tregs + TCVR_FRAME,
		    (FRAME_READ | (hp->paddr << 23) | ((reg & 0xff) << 18)));
	while (!(hme_read32(hp, tregs + TCVR_FRAME) & 0x10000) && --tries)
		udelay(20);
	if (!tries) {
		printk(KERN_ERR "happy meal: Aieee, transceiver MIF read bolixed\n");
		return TCVR_FAILURE;
	}
	retval = hme_read32(hp, tregs + TCVR_FRAME) & 0xffff;
	ASD(("value=%04x\n", retval));
	return retval;
}

#define TCVR_WRITE_TRIES  16

static void happy_meal_tcvr_write(struct happy_meal *hp,
				  void __iomem *tregs, int reg,
				  unsigned short value)
{
	int tries = TCVR_WRITE_TRIES;

	ASD(("happy_meal_tcvr_write: reg=0x%02x value=%04x\n", reg, value));

	/* Welcome to Sun Microsystems, can I take your order please? */
	if (!(hp->happy_flags & HFLAG_FENABLE)) {
		happy_meal_bb_write(hp, tregs, reg, value);
		return;
	}

	/* Would you like fries with that? */
	hme_write32(hp, tregs + TCVR_FRAME,
		    (FRAME_WRITE | (hp->paddr << 23) |
		     ((reg & 0xff) << 18) | (value & 0xffff)));
	while (!(hme_read32(hp, tregs + TCVR_FRAME) & 0x10000) && --tries)
		udelay(20);

	/* Anything else? */
	if (!tries)
		printk(KERN_ERR "happy meal: Aieee, transceiver MIF write bolixed\n");

	/* Fifty-two cents is your change, have a nice day. */
}

/* Auto negotiation.  The scheme is very simple.  We have a timer routine
 * that keeps watching the auto negotiation process as it progresses.
 * The DP83840 is first told to start doing it's thing, we set up the time
 * and place the timer state machine in it's initial state.
 *
 * Here the timer peeks at the DP83840 status registers at each click to see
 * if the auto negotiation has completed, we assume here that the DP83840 PHY
 * will time out at some point and just tell us what (didn't) happen.  For
 * complete coverage we only allow so many of the ticks at this level to run,
 * when this has expired we print a warning message and try another strategy.
 * This "other" strategy is to force the interface into various speed/duplex
 * configurations and we stop when we see a link-up condition before the
 * maximum number of "peek" ticks have occurred.
 *
 * Once a valid link status has been detected we configure the BigMAC and
 * the rest of the Happy Meal to speak the most efficient protocol we could
 * get a clean link for.  The priority for link configurations, highest first
 * is:
 *                 100 Base-T Full Duplex
 *                 100 Base-T Half Duplex
 *                 10 Base-T Full Duplex
 *                 10 Base-T Half Duplex
 *
 * We start a new timer now, after a successful auto negotiation status has
 * been detected.  This timer just waits for the link-up bit to get set in
 * the BMCR of the DP83840.  When this occurs we print a kernel log message
 * describing the link type in use and the fact that it is up.
 *
 * If a fatal error of some sort is signalled and detected in the interrupt
 * service routine, and the chip is reset, or the link is ifconfig'd down
 * and then back up, this entire process repeats itself all over again.
 */
static int try_next_permutation(struct happy_meal *hp, void __iomem *tregs)
{
	hp->sw_bmcr = happy_meal_tcvr_read(hp, tregs, MII_BMCR);

	/* Downgrade from full to half duplex.  Only possible
	 * via ethtool.
	 */
	if (hp->sw_bmcr & BMCR_FULLDPLX) {
		hp->sw_bmcr &= ~(BMCR_FULLDPLX);
		happy_meal_tcvr_write(hp, tregs, MII_BMCR, hp->sw_bmcr);
		return 0;
	}

	/* Downgrade from 100 to 10. */
	if (hp->sw_bmcr & BMCR_SPEED100) {
		hp->sw_bmcr &= ~(BMCR_SPEED100);
		happy_meal_tcvr_write(hp, tregs, MII_BMCR, hp->sw_bmcr);
		return 0;
	}

	/* We've tried everything. */
	return -1;
}

static void display_link_mode(struct happy_meal *hp, void __iomem *tregs)
{
	printk(KERN_INFO "%s: Link is up using ", hp->dev->name);
	if (hp->tcvr_type == external)
		printk("external ");
	else
		printk("internal ");
	printk("transceiver at ");
	hp->sw_lpa = happy_meal_tcvr_read(hp, tregs, MII_LPA);
	if (hp->sw_lpa & (LPA_100HALF | LPA_100FULL)) {
		if (hp->sw_lpa & LPA_100FULL)
			printk("100Mb/s, Full Duplex.\n");
		else
			printk("100Mb/s, Half Duplex.\n");
	} else {
		if (hp->sw_lpa & LPA_10FULL)
			printk("10Mb/s, Full Duplex.\n");
		else
			printk("10Mb/s, Half Duplex.\n");
	}
}

static void display_forced_link_mode(struct happy_meal *hp, void __iomem *tregs)
{
	printk(KERN_INFO "%s: Link has been forced up using ", hp->dev->name);
	if (hp->tcvr_type == external)
		printk("external ");
	else
		printk("internal ");
	printk("transceiver at ");
	hp->sw_bmcr = happy_meal_tcvr_read(hp, tregs, MII_BMCR);
	if (hp->sw_bmcr & BMCR_SPEED100)
		printk("100Mb/s, ");
	else
		printk("10Mb/s, ");
	if (hp->sw_bmcr & BMCR_FULLDPLX)
		printk("Full Duplex.\n");
	else
		printk("Half Duplex.\n");
}

static int set_happy_link_modes(struct happy_meal *hp, void __iomem *tregs)
{
	int full;

	/* All we care about is making sure the bigmac tx_cfg has a
	 * proper duplex setting.
	 */
	if (hp->timer_state == arbwait) {
		hp->sw_lpa = happy_meal_tcvr_read(hp, tregs, MII_LPA);
		if (!(hp->sw_lpa & (LPA_10HALF | LPA_10FULL | LPA_100HALF | LPA_100FULL)))
			goto no_response;
		if (hp->sw_lpa & LPA_100FULL)
			full = 1;
		else if (hp->sw_lpa & LPA_100HALF)
			full = 0;
		else if (hp->sw_lpa & LPA_10FULL)
			full = 1;
		else
			full = 0;
	} else {
		/* Forcing a link mode. */
		hp->sw_bmcr = happy_meal_tcvr_read(hp, tregs, MII_BMCR);
		if (hp->sw_bmcr & BMCR_FULLDPLX)
			full = 1;
		else
			full = 0;
	}

	/* Before changing other bits in the tx_cfg register, and in
	 * general any of other the TX config registers too, you
	 * must:
	 * 1) Clear Enable
	 * 2) Poll with reads until that bit reads back as zero
	 * 3) Make TX configuration changes
	 * 4) Set Enable once more
	 */
	hme_write32(hp, hp->bigmacregs + BMAC_TXCFG,
		    hme_read32(hp, hp->bigmacregs + BMAC_TXCFG) &
		    ~(BIGMAC_TXCFG_ENABLE));
	while (hme_read32(hp, hp->bigmacregs + BMAC_TXCFG) & BIGMAC_TXCFG_ENABLE)
		barrier();
	if (full) {
		hp->happy_flags |= HFLAG_FULL;
		hme_write32(hp, hp->bigmacregs + BMAC_TXCFG,
			    hme_read32(hp, hp->bigmacregs + BMAC_TXCFG) |
			    BIGMAC_TXCFG_FULLDPLX);
	} else {
		hp->happy_flags &= ~(HFLAG_FULL);
		hme_write32(hp, hp->bigmacregs + BMAC_TXCFG,
			    hme_read32(hp, hp->bigmacregs + BMAC_TXCFG) &
			    ~(BIGMAC_TXCFG_FULLDPLX));
	}
	hme_write32(hp, hp->bigmacregs + BMAC_TXCFG,
		    hme_read32(hp, hp->bigmacregs + BMAC_TXCFG) |
		    BIGMAC_TXCFG_ENABLE);
	return 0;
no_response:
	return 1;
}

static int happy_meal_init(struct happy_meal *hp);

static int is_lucent_phy(struct happy_meal *hp)
{
	void __iomem *tregs = hp->tcvregs;
	unsigned short mr2, mr3;
	int ret = 0;

	mr2 = happy_meal_tcvr_read(hp, tregs, 2);
	mr3 = happy_meal_tcvr_read(hp, tregs, 3);
	if ((mr2 & 0xffff) == 0x0180 &&
	    ((mr3 & 0xffff) >> 10) == 0x1d)
		ret = 1;

	return ret;
}

static void happy_meal_timer(unsigned long data)
{
	struct happy_meal *hp = (struct happy_meal *) data;
	void __iomem *tregs = hp->tcvregs;
	int restart_timer = 0;

	spin_lock_irq(&hp->happy_lock);

	hp->timer_ticks++;
	switch(hp->timer_state) {
	case arbwait:
		/* Only allow for 5 ticks, thats 10 seconds and much too
		 * long to wait for arbitration to complete.
		 */
		if (hp->timer_ticks >= 10) {
			/* Enter force mode. */
	do_force_mode:
			hp->sw_bmcr = happy_meal_tcvr_read(hp, tregs, MII_BMCR);
			printk(KERN_NOTICE "%s: Auto-Negotiation unsuccessful, trying force link mode\n",
			       hp->dev->name);
			hp->sw_bmcr = BMCR_SPEED100;
			happy_meal_tcvr_write(hp, tregs, MII_BMCR, hp->sw_bmcr);

			if (!is_lucent_phy(hp)) {
				/* OK, seems we need do disable the transceiver for the first
				 * tick to make sure we get an accurate link state at the
				 * second tick.
				 */
				hp->sw_csconfig = happy_meal_tcvr_read(hp, tregs, DP83840_CSCONFIG);
				hp->sw_csconfig &= ~(CSCONFIG_TCVDISAB);
				happy_meal_tcvr_write(hp, tregs, DP83840_CSCONFIG, hp->sw_csconfig);
			}
			hp->timer_state = ltrywait;
			hp->timer_ticks = 0;
			restart_timer = 1;
		} else {
			/* Anything interesting happen? */
			hp->sw_bmsr = happy_meal_tcvr_read(hp, tregs, MII_BMSR);
			if (hp->sw_bmsr & BMSR_ANEGCOMPLETE) {
				int ret;

				/* Just what we've been waiting for... */
				ret = set_happy_link_modes(hp, tregs);
				if (ret) {
					/* Ooops, something bad happened, go to force
					 * mode.
					 *
					 * XXX Broken hubs which don't support 802.3u
					 * XXX auto-negotiation make this happen as well.
					 */
					goto do_force_mode;
				}

				/* Success, at least so far, advance our state engine. */
				hp->timer_state = lupwait;
				restart_timer = 1;
			} else {
				restart_timer = 1;
			}
		}
		break;

	case lupwait:
		/* Auto negotiation was successful and we are awaiting a
		 * link up status.  I have decided to let this timer run
		 * forever until some sort of error is signalled, reporting
		 * a message to the user at 10 second intervals.
		 */
		hp->sw_bmsr = happy_meal_tcvr_read(hp, tregs, MII_BMSR);
		if (hp->sw_bmsr & BMSR_LSTATUS) {
			/* Wheee, it's up, display the link mode in use and put
			 * the timer to sleep.
			 */
			display_link_mode(hp, tregs);
			hp->timer_state = asleep;
			restart_timer = 0;
		} else {
			if (hp->timer_ticks >= 10) {
				printk(KERN_NOTICE "%s: Auto negotiation successful, link still "
				       "not completely up.\n", hp->dev->name);
				hp->timer_ticks = 0;
				restart_timer = 1;
			} else {
				restart_timer = 1;
			}
		}
		break;

	case ltrywait:
		/* Making the timeout here too long can make it take
		 * annoyingly long to attempt all of the link mode
		 * permutations, but then again this is essentially
		 * error recovery code for the most part.
		 */
		hp->sw_bmsr = happy_meal_tcvr_read(hp, tregs, MII_BMSR);
		hp->sw_csconfig = happy_meal_tcvr_read(hp, tregs, DP83840_CSCONFIG);
		if (hp->timer_ticks == 1) {
			if (!is_lucent_phy(hp)) {
				/* Re-enable transceiver, we'll re-enable the transceiver next
				 * tick, then check link state on the following tick.
				 */
				hp->sw_csconfig |= CSCONFIG_TCVDISAB;
				happy_meal_tcvr_write(hp, tregs,
						      DP83840_CSCONFIG, hp->sw_csconfig);
			}
			restart_timer = 1;
			break;
		}
		if (hp->timer_ticks == 2) {
			if (!is_lucent_phy(hp)) {
				hp->sw_csconfig &= ~(CSCONFIG_TCVDISAB);
				happy_meal_tcvr_write(hp, tregs,
						      DP83840_CSCONFIG, hp->sw_csconfig);
			}
			restart_timer = 1;
			break;
		}
		if (hp->sw_bmsr & BMSR_LSTATUS) {
			/* Force mode selection success. */
			display_forced_link_mode(hp, tregs);
			set_happy_link_modes(hp, tregs); /* XXX error? then what? */
			hp->timer_state = asleep;
			restart_timer = 0;
		} else {
			if (hp->timer_ticks >= 4) { /* 6 seconds or so... */
				int ret;

				ret = try_next_permutation(hp, tregs);
				if (ret == -1) {
					/* Aieee, tried them all, reset the
					 * chip and try all over again.
					 */

					/* Let the user know... */
					printk(KERN_NOTICE "%s: Link down, cable problem?\n",
					       hp->dev->name);

					ret = happy_meal_init(hp);
					if (ret) {
						/* ho hum... */
						printk(KERN_ERR "%s: Error, cannot re-init the "
						       "Happy Meal.\n", hp->dev->name);
					}
					goto out;
				}
				if (!is_lucent_phy(hp)) {
					hp->sw_csconfig = happy_meal_tcvr_read(hp, tregs,
									       DP83840_CSCONFIG);
					hp->sw_csconfig |= CSCONFIG_TCVDISAB;
					happy_meal_tcvr_write(hp, tregs,
							      DP83840_CSCONFIG, hp->sw_csconfig);
				}
				hp->timer_ticks = 0;
				restart_timer = 1;
			} else {
				restart_timer = 1;
			}
		}
		break;

	case asleep:
	default:
		/* Can't happens.... */
		printk(KERN_ERR "%s: Aieee, link timer is asleep but we got one anyways!\n",
		       hp->dev->name);
		restart_timer = 0;
		hp->timer_ticks = 0;
		hp->timer_state = asleep; /* foo on you */
		break;
	};

	if (restart_timer) {
		hp->happy_timer.expires = jiffies + ((12 * HZ)/10); /* 1.2 sec. */
		add_timer(&hp->happy_timer);
	}

out:
	spin_unlock_irq(&hp->happy_lock);
}

#define TX_RESET_TRIES     32
#define RX_RESET_TRIES     32

/* hp->happy_lock must be held */
static void happy_meal_tx_reset(struct happy_meal *hp, void __iomem *bregs)
{
	int tries = TX_RESET_TRIES;

	HMD(("happy_meal_tx_reset: reset, "));

	/* Would you like to try our SMCC Delux? */
	hme_write32(hp, bregs + BMAC_TXSWRESET, 0);
	while ((hme_read32(hp, bregs + BMAC_TXSWRESET) & 1) && --tries)
		udelay(20);

	/* Lettuce, tomato, buggy hardware (no extra charge)? */
	if (!tries)
		printk(KERN_ERR "happy meal: Transceiver BigMac ATTACK!");

	/* Take care. */
	HMD(("done\n"));
}

/* hp->happy_lock must be held */
static void happy_meal_rx_reset(struct happy_meal *hp, void __iomem *bregs)
{
	int tries = RX_RESET_TRIES;

	HMD(("happy_meal_rx_reset: reset, "));

	/* We have a special on GNU/Viking hardware bugs today. */
	hme_write32(hp, bregs + BMAC_RXSWRESET, 0);
	while ((hme_read32(hp, bregs + BMAC_RXSWRESET) & 1) && --tries)
		udelay(20);

	/* Will that be all? */
	if (!tries)
		printk(KERN_ERR "happy meal: Receiver BigMac ATTACK!");

	/* Don't forget your vik_1137125_wa.  Have a nice day. */
	HMD(("done\n"));
}

#define STOP_TRIES         16

/* hp->happy_lock must be held */
static void happy_meal_stop(struct happy_meal *hp, void __iomem *gregs)
{
	int tries = STOP_TRIES;

	HMD(("happy_meal_stop: reset, "));

	/* We're consolidating our STB products, it's your lucky day. */
	hme_write32(hp, gregs + GREG_SWRESET, GREG_RESET_ALL);
	while (hme_read32(hp, gregs + GREG_SWRESET) && --tries)
		udelay(20);

	/* Come back next week when we are "Sun Microelectronics". */
	if (!tries)
		printk(KERN_ERR "happy meal: Fry guys.");

	/* Remember: "Different name, same old buggy as shit hardware." */
	HMD(("done\n"));
}

/* hp->happy_lock must be held */
static void happy_meal_get_counters(struct happy_meal *hp, void __iomem *bregs)
{
	struct net_device_stats *stats = &hp->net_stats;

	stats->rx_crc_errors += hme_read32(hp, bregs + BMAC_RCRCECTR);
	hme_write32(hp, bregs + BMAC_RCRCECTR, 0);

	stats->rx_frame_errors += hme_read32(hp, bregs + BMAC_UNALECTR);
	hme_write32(hp, bregs + BMAC_UNALECTR, 0);

	stats->rx_length_errors += hme_read32(hp, bregs + BMAC_GLECTR);
	hme_write32(hp, bregs + BMAC_GLECTR, 0);

	stats->tx_aborted_errors += hme_read32(hp, bregs + BMAC_EXCTR);

	stats->collisions +=
		(hme_read32(hp, bregs + BMAC_EXCTR) +
		 hme_read32(hp, bregs + BMAC_LTCTR));
	hme_write32(hp, bregs + BMAC_EXCTR, 0);
	hme_write32(hp, bregs + BMAC_LTCTR, 0);
}

/* hp->happy_lock must be held */
static void happy_meal_poll_stop(struct happy_meal *hp, void __iomem *tregs)
{
	ASD(("happy_meal_poll_stop: "));

	/* If polling disabled or not polling already, nothing to do. */
	if ((hp->happy_flags & (HFLAG_POLLENABLE | HFLAG_POLL)) !=
	   (HFLAG_POLLENABLE | HFLAG_POLL)) {
		HMD(("not polling, return\n"));
		return;
	}

	/* Shut up the MIF. */
	ASD(("were polling, mif ints off, "));
	hme_write32(hp, tregs + TCVR_IMASK, 0xffff);

	/* Turn off polling. */
	ASD(("polling off, "));
	hme_write32(hp, tregs + TCVR_CFG,
		    hme_read32(hp, tregs + TCVR_CFG) & ~(TCV_CFG_PENABLE));

	/* We are no longer polling. */
	hp->happy_flags &= ~(HFLAG_POLL);

	/* Let the bits set. */
	udelay(200);
	ASD(("done\n"));
}

/* Only Sun can take such nice parts and fuck up the programming interface
 * like this.  Good job guys...
 */
#define TCVR_RESET_TRIES       16 /* It should reset quickly        */
#define TCVR_UNISOLATE_TRIES   32 /* Dis-isolation can take longer. */

/* hp->happy_lock must be held */
static int happy_meal_tcvr_reset(struct happy_meal *hp, void __iomem *tregs)
{
	u32 tconfig;
	int result, tries = TCVR_RESET_TRIES;

	tconfig = hme_read32(hp, tregs + TCVR_CFG);
	ASD(("happy_meal_tcvr_reset: tcfg<%08lx> ", tconfig));
	if (hp->tcvr_type == external) {
		ASD(("external<"));
		hme_write32(hp, tregs + TCVR_CFG, tconfig & ~(TCV_CFG_PSELECT));
		hp->tcvr_type = internal;
		hp->paddr = TCV_PADDR_ITX;
		ASD(("ISOLATE,"));
		happy_meal_tcvr_write(hp, tregs, MII_BMCR,
				      (BMCR_LOOPBACK|BMCR_PDOWN|BMCR_ISOLATE));
		result = happy_meal_tcvr_read(hp, tregs, MII_BMCR);
		if (result == TCVR_FAILURE) {
			ASD(("phyread_fail>\n"));
			return -1;
		}
		ASD(("phyread_ok,PSELECT>"));
		hme_write32(hp, tregs + TCVR_CFG, tconfig | TCV_CFG_PSELECT);
		hp->tcvr_type = external;
		hp->paddr = TCV_PADDR_ETX;
	} else {
		if (tconfig & TCV_CFG_MDIO1) {
			ASD(("internal<PSELECT,"));
			hme_write32(hp, tregs + TCVR_CFG, (tconfig | TCV_CFG_PSELECT));
			ASD(("ISOLATE,"));
			happy_meal_tcvr_write(hp, tregs, MII_BMCR,
					      (BMCR_LOOPBACK|BMCR_PDOWN|BMCR_ISOLATE));
			result = happy_meal_tcvr_read(hp, tregs, MII_BMCR);
			if (result == TCVR_FAILURE) {
				ASD(("phyread_fail>\n"));
				return -1;
			}
			ASD(("phyread_ok,~PSELECT>"));
			hme_write32(hp, tregs + TCVR_CFG, (tconfig & ~(TCV_CFG_PSELECT)));
			hp->tcvr_type = internal;
			hp->paddr = TCV_PADDR_ITX;
		}
	}

	ASD(("BMCR_RESET "));
	happy_meal_tcvr_write(hp, tregs, MII_BMCR, BMCR_RESET);

	while (--tries) {
		result = happy_meal_tcvr_read(hp, tregs, MII_BMCR);
		if (result == TCVR_FAILURE)
			return -1;
		hp->sw_bmcr = result;
		if (!(result & BMCR_RESET))
			break;
		udelay(20);
	}
	if (!tries) {
		ASD(("BMCR RESET FAILED!\n"));
		return -1;
	}
	ASD(("RESET_OK\n"));

	/* Get fresh copies of the PHY registers. */
	hp->sw_bmsr      = happy_meal_tcvr_read(hp, tregs, MII_BMSR);
	hp->sw_physid1   = happy_meal_tcvr_read(hp, tregs, MII_PHYSID1);
	hp->sw_physid2   = happy_meal_tcvr_read(hp, tregs, MII_PHYSID2);
	hp->sw_advertise = happy_meal_tcvr_read(hp, tregs, MII_ADVERTISE);

	ASD(("UNISOLATE"));
	hp->sw_bmcr &= ~(BMCR_ISOLATE);
	happy_meal_tcvr_write(hp, tregs, MII_BMCR, hp->sw_bmcr);

	tries = TCVR_UNISOLATE_TRIES;
	while (--tries) {
		result = happy_meal_tcvr_read(hp, tregs, MII_BMCR);
		if (result == TCVR_FAILURE)
			return -1;
		if (!(result & BMCR_ISOLATE))
			break;
		udelay(20);
	}
	if (!tries) {
		ASD((" FAILED!\n"));
		return -1;
	}
	ASD((" SUCCESS and CSCONFIG_DFBYPASS\n"));
	if (!is_lucent_phy(hp)) {
		result = happy_meal_tcvr_read(hp, tregs,
					      DP83840_CSCONFIG);
		happy_meal_tcvr_write(hp, tregs,
				      DP83840_CSCONFIG, (result | CSCONFIG_DFBYPASS));
	}
	return 0;
}

/* Figure out whether we have an internal or external transceiver.
 *
 * hp->happy_lock must be held
 */
static void happy_meal_transceiver_check(struct happy_meal *hp, void __iomem *tregs)
{
	unsigned long tconfig = hme_read32(hp, tregs + TCVR_CFG);

	ASD(("happy_meal_transceiver_check: tcfg=%08lx ", tconfig));
	if (hp->happy_flags & HFLAG_POLL) {
		/* If we are polling, we must stop to get the transceiver type. */
		ASD(("<polling> "));
		if (hp->tcvr_type == internal) {
			if (tconfig & TCV_CFG_MDIO1) {
				ASD(("<internal> <poll stop> "));
				happy_meal_poll_stop(hp, tregs);
				hp->paddr = TCV_PADDR_ETX;
				hp->tcvr_type = external;
				ASD(("<external>\n"));
				tconfig &= ~(TCV_CFG_PENABLE);
				tconfig |= TCV_CFG_PSELECT;
				hme_write32(hp, tregs + TCVR_CFG, tconfig);
			}
		} else {
			if (hp->tcvr_type == external) {
				ASD(("<external> "));
				if (!(hme_read32(hp, tregs + TCVR_STATUS) >> 16)) {
					ASD(("<poll stop> "));
					happy_meal_poll_stop(hp, tregs);
					hp->paddr = TCV_PADDR_ITX;
					hp->tcvr_type = internal;
					ASD(("<internal>\n"));
					hme_write32(hp, tregs + TCVR_CFG,
						    hme_read32(hp, tregs + TCVR_CFG) &
						    ~(TCV_CFG_PSELECT));
				}
				ASD(("\n"));
			} else {
				ASD(("<none>\n"));
			}
		}
	} else {
		u32 reread = hme_read32(hp, tregs + TCVR_CFG);

		/* Else we can just work off of the MDIO bits. */
		ASD(("<not polling> "));
		if (reread & TCV_CFG_MDIO1) {
			hme_write32(hp, tregs + TCVR_CFG, tconfig | TCV_CFG_PSELECT);
			hp->paddr = TCV_PADDR_ETX;
			hp->tcvr_type = external;
			ASD(("<external>\n"));
		} else {
			if (reread & TCV_CFG_MDIO0) {
				hme_write32(hp, tregs + TCVR_CFG,
					    tconfig & ~(TCV_CFG_PSELECT));
				hp->paddr = TCV_PADDR_ITX;
				hp->tcvr_type = internal;
				ASD(("<internal>\n"));
			} else {
				printk(KERN_ERR "happy meal: Transceiver and a coke please.");
				hp->tcvr_type = none; /* Grrr... */
				ASD(("<none>\n"));
			}
		}
	}
}

/* The receive ring buffers are a bit tricky to get right.  Here goes...
 *
 * The buffers we dma into must be 64 byte aligned.  So we use a special
 * alloc_skb() routine for the happy meal to allocate 64 bytes more than
 * we really need.
 *
 * We use skb_reserve() to align the data block we get in the skb.  We
 * also program the etxregs->cfg register to use an offset of 2.  This
 * imperical constant plus the ethernet header size will always leave
 * us with a nicely aligned ip header once we pass things up to the
 * protocol layers.
 *
 * The numbers work out to:
 *
 *         Max ethernet frame size         1518
 *         Ethernet header size              14
 *         Happy Meal base offset             2
 *
 * Say a skb data area is at 0xf001b010, and its size alloced is
 * (ETH_FRAME_LEN + 64 + 2) = (1514 + 64 + 2) = 1580 bytes.
 *
 * First our alloc_skb() routine aligns the data base to a 64 byte
 * boundary.  We now have 0xf001b040 as our skb data address.  We
 * plug this into the receive descriptor address.
 *
 * Next, we skb_reserve() 2 bytes to account for the Happy Meal offset.
 * So now the data we will end up looking at starts at 0xf001b042.  When
 * the packet arrives, we will check out the size received and subtract
 * this from the skb->length.  Then we just pass the packet up to the
 * protocols as is, and allocate a new skb to replace this slot we have
 * just received from.
 *
 * The ethernet layer will strip the ether header from the front of the
 * skb we just sent to it, this leaves us with the ip header sitting
 * nicely aligned at 0xf001b050.  Also, for tcp and udp packets the
 * Happy Meal has even checksummed the tcp/udp data for us.  The 16
 * bit checksum is obtained from the low bits of the receive descriptor
 * flags, thus:
 *
 * 	skb->csum = rxd->rx_flags & 0xffff;
 * 	skb->ip_summed = CHECKSUM_COMPLETE;
 *
 * before sending off the skb to the protocols, and we are good as gold.
 */
static void happy_meal_clean_rings(struct happy_meal *hp)
{
	int i;

	for (i = 0; i < RX_RING_SIZE; i++) {
		if (hp->rx_skbs[i] != NULL) {
			struct sk_buff *skb = hp->rx_skbs[i];
			struct happy_meal_rxd *rxd;
			u32 dma_addr;

			rxd = &hp->happy_block->happy_meal_rxd[i];
			dma_addr = hme_read_desc32(hp, &rxd->rx_addr);
			hme_dma_unmap(hp, dma_addr, RX_BUF_ALLOC_SIZE, DMA_FROMDEVICE);
			dev_kfree_skb_any(skb);
			hp->rx_skbs[i] = NULL;
		}
	}

	for (i = 0; i < TX_RING_SIZE; i++) {
		if (hp->tx_skbs[i] != NULL) {
			struct sk_buff *skb = hp->tx_skbs[i];
			struct happy_meal_txd *txd;
			u32 dma_addr;
			int frag;

			hp->tx_skbs[i] = NULL;

			for (frag = 0; frag <= skb_shinfo(skb)->nr_frags; frag++) {
				txd = &hp->happy_block->happy_meal_txd[i];
				dma_addr = hme_read_desc32(hp, &txd->tx_addr);
				hme_dma_unmap(hp, dma_addr,
					      (hme_read_desc32(hp, &txd->tx_flags)
					       & TXFLAG_SIZE),
					      DMA_TODEVICE);

				if (frag != skb_shinfo(skb)->nr_frags)
					i++;
			}

			dev_kfree_skb_any(skb);
		}
	}
}

/* hp->happy_lock must be held */
static void happy_meal_init_rings(struct happy_meal *hp)
{
	struct hmeal_init_block *hb = hp->happy_block;
	struct net_device *dev = hp->dev;
	int i;

	HMD(("happy_meal_init_rings: counters to zero, "));
	hp->rx_new = hp->rx_old = hp->tx_new = hp->tx_old = 0;

	/* Free any skippy bufs left around in the rings. */
	HMD(("clean, "));
	happy_meal_clean_rings(hp);

	/* Now get new skippy bufs for the receive ring. */
	HMD(("init rxring, "));
	for (i = 0; i < RX_RING_SIZE; i++) {
		struct sk_buff *skb;

		skb = happy_meal_alloc_skb(RX_BUF_ALLOC_SIZE, GFP_ATOMIC);
		if (!skb) {
			hme_write_rxd(hp, &hb->happy_meal_rxd[i], 0, 0);
			continue;
		}
		hp->rx_skbs[i] = skb;
		skb->dev = dev;

		/* Because we reserve afterwards. */
		skb_put(skb, (ETH_FRAME_LEN + RX_OFFSET + 4));
		hme_write_rxd(hp, &hb->happy_meal_rxd[i],
			      (RXFLAG_OWN | ((RX_BUF_ALLOC_SIZE - RX_OFFSET) << 16)),
			      hme_dma_map(hp, skb->data, RX_BUF_ALLOC_SIZE, DMA_FROMDEVICE));
		skb_reserve(skb, RX_OFFSET);
	}

	HMD(("init txring, "));
	for (i = 0; i < TX_RING_SIZE; i++)
		hme_write_txd(hp, &hb->happy_meal_txd[i], 0, 0);

	HMD(("done\n"));
}

/* hp->happy_lock must be held */
static void happy_meal_begin_auto_negotiation(struct happy_meal *hp,
					      void __iomem *tregs,
					      struct ethtool_cmd *ep)
{
	int timeout;

	/* Read all of the registers we are interested in now. */
	hp->sw_bmsr      = happy_meal_tcvr_read(hp, tregs, MII_BMSR);
	hp->sw_bmcr      = happy_meal_tcvr_read(hp, tregs, MII_BMCR);
	hp->sw_physid1   = happy_meal_tcvr_read(hp, tregs, MII_PHYSID1);
	hp->sw_physid2   = happy_meal_tcvr_read(hp, tregs, MII_PHYSID2);

	/* XXX Check BMSR_ANEGCAPABLE, should not be necessary though. */

	hp->sw_advertise = happy_meal_tcvr_read(hp, tregs, MII_ADVERTISE);
	if (ep == NULL || ep->autoneg == AUTONEG_ENABLE) {
		/* Advertise everything we can support. */
		if (hp->sw_bmsr & BMSR_10HALF)
			hp->sw_advertise |= (ADVERTISE_10HALF);
		else
			hp->sw_advertise &= ~(ADVERTISE_10HALF);

		if (hp->sw_bmsr & BMSR_10FULL)
			hp->sw_advertise |= (ADVERTISE_10FULL);
		else
			hp->sw_advertise &= ~(ADVERTISE_10FULL);
		if (hp->sw_bmsr & BMSR_100HALF)
			hp->sw_advertise |= (ADVERTISE_100HALF);
		else
			hp->sw_advertise &= ~(ADVERTISE_100HALF);
		if (hp->sw_bmsr & BMSR_100FULL)
			hp->sw_advertise |= (ADVERTISE_100FULL);
		else
			hp->sw_advertise &= ~(ADVERTISE_100FULL);
		happy_meal_tcvr_write(hp, tregs, MII_ADVERTISE, hp->sw_advertise);

		/* XXX Currently no Happy Meal cards I know off support 100BaseT4,
		 * XXX and this is because the DP83840 does not support it, changes
		 * XXX would need to be made to the tx/rx logic in the driver as well
		 * XXX so I completely skip checking for it in the BMSR for now.
		 */

#ifdef AUTO_SWITCH_DEBUG
		ASD(("%s: Advertising [ ", hp->dev->name));
		if (hp->sw_advertise & ADVERTISE_10HALF)
			ASD(("10H "));
		if (hp->sw_advertise & ADVERTISE_10FULL)
			ASD(("10F "));
		if (hp->sw_advertise & ADVERTISE_100HALF)
			ASD(("100H "));
		if (hp->sw_advertise & ADVERTISE_100FULL)
			ASD(("100F "));
#endif

		/* Enable Auto-Negotiation, this is usually on already... */
		hp->sw_bmcr |= BMCR_ANENABLE;
		happy_meal_tcvr_write(hp, tregs, MII_BMCR, hp->sw_bmcr);

		/* Restart it to make sure it is going. */
		hp->sw_bmcr |= BMCR_ANRESTART;
		happy_meal_tcvr_write(hp, tregs, MII_BMCR, hp->sw_bmcr);

		/* BMCR_ANRESTART self clears when the process has begun. */

		timeout = 64;  /* More than enough. */
		while (--timeout) {
			hp->sw_bmcr = happy_meal_tcvr_read(hp, tregs, MII_BMCR);
			if (!(hp->sw_bmcr & BMCR_ANRESTART))
				break; /* got it. */
			udelay(10);
		}
		if (!timeout) {
			printk(KERN_ERR "%s: Happy Meal would not start auto negotiation "
			       "BMCR=0x%04x\n", hp->dev->name, hp->sw_bmcr);
			printk(KERN_NOTICE "%s: Performing force link detection.\n",
			       hp->dev->name);
			goto force_link;
		} else {
			hp->timer_state = arbwait;
		}
	} else {
force_link:
		/* Force the link up, trying first a particular mode.
		 * Either we are here at the request of ethtool or
		 * because the Happy Meal would not start to autoneg.
		 */

		/* Disable auto-negotiation in BMCR, enable the duplex and
		 * speed setting, init the timer state machine, and fire it off.
		 */
		if (ep == NULL || ep->autoneg == AUTONEG_ENABLE) {
			hp->sw_bmcr = BMCR_SPEED100;
		} else {
			if (ep->speed == SPEED_100)
				hp->sw_bmcr = BMCR_SPEED100;
			else
				hp->sw_bmcr = 0;
			if (ep->duplex == DUPLEX_FULL)
				hp->sw_bmcr |= BMCR_FULLDPLX;
		}
		happy_meal_tcvr_write(hp, tregs, MII_BMCR, hp->sw_bmcr);

		if (!is_lucent_phy(hp)) {
			/* OK, seems we need do disable the transceiver for the first
			 * tick to make sure we get an accurate link state at the
			 * second tick.
			 */
			hp->sw_csconfig = happy_meal_tcvr_read(hp, tregs,
							       DP83840_CSCONFIG);
			hp->sw_csconfig &= ~(CSCONFIG_TCVDISAB);
			happy_meal_tcvr_write(hp, tregs, DP83840_CSCONFIG,
					      hp->sw_csconfig);
		}
		hp->timer_state = ltrywait;
	}

	hp->timer_ticks = 0;
	hp->happy_timer.expires = jiffies + (12 * HZ)/10;  /* 1.2 sec. */
	hp->happy_timer.data = (unsigned long) hp;
	hp->happy_timer.function = &happy_meal_timer;
	add_timer(&hp->happy_timer);
}

/* hp->happy_lock must be held */
static int happy_meal_init(struct happy_meal *hp)
{
	void __iomem *gregs        = hp->gregs;
	void __iomem *etxregs      = hp->etxregs;
	void __iomem *erxregs      = hp->erxregs;
	void __iomem *bregs        = hp->bigmacregs;
	void __iomem *tregs        = hp->tcvregs;
	u32 regtmp, rxcfg;
	unsigned char *e = &hp->dev->dev_addr[0];

	/* If auto-negotiation timer is running, kill it. */
	del_timer(&hp->happy_timer);

	HMD(("happy_meal_init: happy_flags[%08x] ",
	     hp->happy_flags));
	if (!(hp->happy_flags & HFLAG_INIT)) {
		HMD(("set HFLAG_INIT, "));
		hp->happy_flags |= HFLAG_INIT;
		happy_meal_get_counters(hp, bregs);
	}

	/* Stop polling. */
	HMD(("to happy_meal_poll_stop\n"));
	happy_meal_poll_stop(hp, tregs);

	/* Stop transmitter and receiver. */
	HMD(("happy_meal_init: to happy_meal_stop\n"));
	happy_meal_stop(hp, gregs);

	/* Alloc and reset the tx/rx descriptor chains. */
	HMD(("happy_meal_init: to happy_meal_init_rings\n"));
	happy_meal_init_rings(hp);

	/* Shut up the MIF. */
	HMD(("happy_meal_init: Disable all MIF irqs (old[%08x]), ",
	     hme_read32(hp, tregs + TCVR_IMASK)));
	hme_write32(hp, tregs + TCVR_IMASK, 0xffff);

	/* See if we can enable the MIF frame on this card to speak to the DP83840. */
	if (hp->happy_flags & HFLAG_FENABLE) {
		HMD(("use frame old[%08x], ",
		     hme_read32(hp, tregs + TCVR_CFG)));
		hme_write32(hp, tregs + TCVR_CFG,
			    hme_read32(hp, tregs + TCVR_CFG) & ~(TCV_CFG_BENABLE));
	} else {
		HMD(("use bitbang old[%08x], ",
		     hme_read32(hp, tregs + TCVR_CFG)));
		hme_write32(hp, tregs + TCVR_CFG,
			    hme_read32(hp, tregs + TCVR_CFG) | TCV_CFG_BENABLE);
	}

	/* Check the state of the transceiver. */
	HMD(("to happy_meal_transceiver_check\n"));
	happy_meal_transceiver_check(hp, tregs);

	/* Put the Big Mac into a sane state. */
	HMD(("happy_meal_init: "));
	switch(hp->tcvr_type) {
	case none:
		/* Cannot operate if we don't know the transceiver type! */
		HMD(("AAIEEE no transceiver type, EAGAIN"));
		return -EAGAIN;

	case internal:
		/* Using the MII buffers. */
		HMD(("internal, using MII, "));
		hme_write32(hp, bregs + BMAC_XIFCFG, 0);
		break;

	case external:
		/* Not using the MII, disable it. */
		HMD(("external, disable MII, "));
		hme_write32(hp, bregs + BMAC_XIFCFG, BIGMAC_XCFG_MIIDISAB);
		break;
	};

	if (happy_meal_tcvr_reset(hp, tregs))
		return -EAGAIN;

	/* Reset the Happy Meal Big Mac transceiver and the receiver. */
	HMD(("tx/rx reset, "));
	happy_meal_tx_reset(hp, bregs);
	happy_meal_rx_reset(hp, bregs);

	/* Set jam size and inter-packet gaps to reasonable defaults. */
	HMD(("jsize/ipg1/ipg2, "));
	hme_write32(hp, bregs + BMAC_JSIZE, DEFAULT_JAMSIZE);
	hme_write32(hp, bregs + BMAC_IGAP1, DEFAULT_IPG1);
	hme_write32(hp, bregs + BMAC_IGAP2, DEFAULT_IPG2);

	/* Load up the MAC address and random seed. */
	HMD(("rseed/macaddr, "));

	/* The docs recommend to use the 10LSB of our MAC here. */
	hme_write32(hp, bregs + BMAC_RSEED, ((e[5] | e[4]<<8)&0x3ff));

	hme_write32(hp, bregs + BMAC_MACADDR2, ((e[4] << 8) | e[5]));
	hme_write32(hp, bregs + BMAC_MACADDR1, ((e[2] << 8) | e[3]));
	hme_write32(hp, bregs + BMAC_MACADDR0, ((e[0] << 8) | e[1]));

	HMD(("htable, "));
	if ((hp->dev->flags & IFF_ALLMULTI) ||
	    (hp->dev->mc_count > 64)) {
		hme_write32(hp, bregs + BMAC_HTABLE0, 0xffff);
		hme_write32(hp, bregs + BMAC_HTABLE1, 0xffff);
		hme_write32(hp, bregs + BMAC_HTABLE2, 0xffff);
		hme_write32(hp, bregs + BMAC_HTABLE3, 0xffff);
	} else if ((hp->dev->flags & IFF_PROMISC) == 0) {
		u16 hash_table[4];
		struct dev_mc_list *dmi = hp->dev->mc_list;
		char *addrs;
		int i;
		u32 crc;

		for (i = 0; i < 4; i++)
			hash_table[i] = 0;

		for (i = 0; i < hp->dev->mc_count; i++) {
			addrs = dmi->dmi_addr;
			dmi = dmi->next;

			if (!(*addrs & 1))
				continue;

			crc = ether_crc_le(6, addrs);
			crc >>= 26;
			hash_table[crc >> 4] |= 1 << (crc & 0xf);
		}
		hme_write32(hp, bregs + BMAC_HTABLE0, hash_table[0]);
		hme_write32(hp, bregs + BMAC_HTABLE1, hash_table[1]);
		hme_write32(hp, bregs + BMAC_HTABLE2, hash_table[2]);
		hme_write32(hp, bregs + BMAC_HTABLE3, hash_table[3]);
	} else {
		hme_write32(hp, bregs + BMAC_HTABLE3, 0);
		hme_write32(hp, bregs + BMAC_HTABLE2, 0);
		hme_write32(hp, bregs + BMAC_HTABLE1, 0);
		hme_write32(hp, bregs + BMAC_HTABLE0, 0);
	}

	/* Set the RX and TX ring ptrs. */
	HMD(("ring ptrs rxr[%08x] txr[%08x]\n",
	     ((__u32)hp->hblock_dvma + hblock_offset(happy_meal_rxd, 0)),
	     ((__u32)hp->hblock_dvma + hblock_offset(happy_meal_txd, 0))));
	hme_write32(hp, erxregs + ERX_RING,
		    ((__u32)hp->hblock_dvma + hblock_offset(happy_meal_rxd, 0)));
	hme_write32(hp, etxregs + ETX_RING,
		    ((__u32)hp->hblock_dvma + hblock_offset(happy_meal_txd, 0)));

	/* Parity issues in the ERX unit of some HME revisions can cause some
	 * registers to not be written unless their parity is even.  Detect such
	 * lost writes and simply rewrite with a low bit set (which will be ignored
	 * since the rxring needs to be 2K aligned).
	 */
	if (hme_read32(hp, erxregs + ERX_RING) !=
	    ((__u32)hp->hblock_dvma + hblock_offset(happy_meal_rxd, 0)))
		hme_write32(hp, erxregs + ERX_RING,
			    ((__u32)hp->hblock_dvma + hblock_offset(happy_meal_rxd, 0))
			    | 0x4);

	/* Set the supported burst sizes. */
	HMD(("happy_meal_init: old[%08x] bursts<",
	     hme_read32(hp, gregs + GREG_CFG)));

#ifndef CONFIG_SPARC
	/* It is always PCI and can handle 64byte bursts. */
	hme_write32(hp, gregs + GREG_CFG, GREG_CFG_BURST64);
#else
	if ((hp->happy_bursts & DMA_BURST64) &&
	    ((hp->happy_flags & HFLAG_PCI) != 0
#ifdef CONFIG_SBUS
	     || sbus_can_burst64(hp->happy_dev)
#endif
	     || 0)) {
		u32 gcfg = GREG_CFG_BURST64;

		/* I have no idea if I should set the extended
		 * transfer mode bit for Cheerio, so for now I
		 * do not.  -DaveM
		 */
#ifdef CONFIG_SBUS
		if ((hp->happy_flags & HFLAG_PCI) == 0 &&
		    sbus_can_dma_64bit(hp->happy_dev)) {
			sbus_set_sbus64(hp->happy_dev,
					hp->happy_bursts);
			gcfg |= GREG_CFG_64BIT;
		}
#endif

		HMD(("64>"));
		hme_write32(hp, gregs + GREG_CFG, gcfg);
	} else if (hp->happy_bursts & DMA_BURST32) {
		HMD(("32>"));
		hme_write32(hp, gregs + GREG_CFG, GREG_CFG_BURST32);
	} else if (hp->happy_bursts & DMA_BURST16) {
		HMD(("16>"));
		hme_write32(hp, gregs + GREG_CFG, GREG_CFG_BURST16);
	} else {
		HMD(("XXX>"));
		hme_write32(hp, gregs + GREG_CFG, 0);
	}
#endif /* CONFIG_SPARC */

	/* Turn off interrupts we do not want to hear. */
	HMD((", enable global interrupts, "));
	hme_write32(hp, gregs + GREG_IMASK,
		    (GREG_IMASK_GOTFRAME | GREG_IMASK_RCNTEXP |
		     GREG_IMASK_SENTFRAME | GREG_IMASK_TXPERR));

	/* Set the transmit ring buffer size. */
	HMD(("tx rsize=%d oreg[%08x], ", (int)TX_RING_SIZE,
	     hme_read32(hp, etxregs + ETX_RSIZE)));
	hme_write32(hp, etxregs + ETX_RSIZE, (TX_RING_SIZE >> ETX_RSIZE_SHIFT) - 1);

	/* Enable transmitter DVMA. */
	HMD(("tx dma enable old[%08x], ",
	     hme_read32(hp, etxregs + ETX_CFG)));
	hme_write32(hp, etxregs + ETX_CFG,
		    hme_read32(hp, etxregs + ETX_CFG) | ETX_CFG_DMAENABLE);

	/* This chip really rots, for the receiver sometimes when you
	 * write to its control registers not all the bits get there
	 * properly.  I cannot think of a sane way to provide complete
	 * coverage for this hardware bug yet.
	 */
	HMD(("erx regs bug old[%08x]\n",
	     hme_read32(hp, erxregs + ERX_CFG)));
	hme_write32(hp, erxregs + ERX_CFG, ERX_CFG_DEFAULT(RX_OFFSET));
	regtmp = hme_read32(hp, erxregs + ERX_CFG);
	hme_write32(hp, erxregs + ERX_CFG, ERX_CFG_DEFAULT(RX_OFFSET));
	if (hme_read32(hp, erxregs + ERX_CFG) != ERX_CFG_DEFAULT(RX_OFFSET)) {
		printk(KERN_ERR "happy meal: Eieee, rx config register gets greasy fries.\n");
		printk(KERN_ERR "happy meal: Trying to set %08x, reread gives %08x\n",
		       ERX_CFG_DEFAULT(RX_OFFSET), regtmp);
		/* XXX Should return failure here... */
	}

	/* Enable Big Mac hash table filter. */
	HMD(("happy_meal_init: enable hash rx_cfg_old[%08x], ",
	     hme_read32(hp, bregs + BMAC_RXCFG)));
	rxcfg = BIGMAC_RXCFG_HENABLE | BIGMAC_RXCFG_REJME;
	if (hp->dev->flags & IFF_PROMISC)
		rxcfg |= BIGMAC_RXCFG_PMISC;
	hme_write32(hp, bregs + BMAC_RXCFG, rxcfg);

	/* Let the bits settle in the chip. */
	udelay(10);

	/* Ok, configure the Big Mac transmitter. */
	HMD(("BIGMAC init, "));
	regtmp = 0;
	if (hp->happy_flags & HFLAG_FULL)
		regtmp |= BIGMAC_TXCFG_FULLDPLX;

	/* Don't turn on the "don't give up" bit for now.  It could cause hme
	 * to deadlock with the PHY if a Jabber occurs.
	 */
	hme_write32(hp, bregs + BMAC_TXCFG, regtmp /*| BIGMAC_TXCFG_DGIVEUP*/);

	/* Give up after 16 TX attempts. */
	hme_write32(hp, bregs + BMAC_ALIMIT, 16);

	/* Enable the output drivers no matter what. */
	regtmp = BIGMAC_XCFG_ODENABLE;

	/* If card can do lance mode, enable it. */
	if (hp->happy_flags & HFLAG_LANCE)
		regtmp |= (DEFAULT_IPG0 << 5) | BIGMAC_XCFG_LANCE;

	/* Disable the MII buffers if using external transceiver. */
	if (hp->tcvr_type == external)
		regtmp |= BIGMAC_XCFG_MIIDISAB;

	HMD(("XIF config old[%08x], ",
	     hme_read32(hp, bregs + BMAC_XIFCFG)));
	hme_write32(hp, bregs + BMAC_XIFCFG, regtmp);

	/* Start things up. */
	HMD(("tx old[%08x] and rx [%08x] ON!\n",
	     hme_read32(hp, bregs + BMAC_TXCFG),
	     hme_read32(hp, bregs + BMAC_RXCFG)));

	/* Set larger TX/RX size to allow for 802.1q */
	hme_write32(hp, bregs + BMAC_TXMAX, ETH_FRAME_LEN + 8);
	hme_write32(hp, bregs + BMAC_RXMAX, ETH_FRAME_LEN + 8);

	hme_write32(hp, bregs + BMAC_TXCFG,
		    hme_read32(hp, bregs + BMAC_TXCFG) | BIGMAC_TXCFG_ENABLE);
	hme_write32(hp, bregs + BMAC_RXCFG,
		    hme_read32(hp, bregs + BMAC_RXCFG) | BIGMAC_RXCFG_ENABLE);

	/* Get the autonegotiation started, and the watch timer ticking. */
	happy_meal_begin_auto_negotiation(hp, tregs, NULL);

	/* Success. */
	return 0;
}

/* hp->happy_lock must be held */
static void happy_meal_set_initial_advertisement(struct happy_meal *hp)
{
	void __iomem *tregs	= hp->tcvregs;
	void __iomem *bregs	= hp->bigmacregs;
	void __iomem *gregs	= hp->gregs;

	happy_meal_stop(hp, gregs);
	hme_write32(hp, tregs + TCVR_IMASK, 0xffff);
	if (hp->happy_flags & HFLAG_FENABLE)
		hme_write32(hp, tregs + TCVR_CFG,
			    hme_read32(hp, tregs + TCVR_CFG) & ~(TCV_CFG_BENABLE));
	else
		hme_write32(hp, tregs + TCVR_CFG,
			    hme_read32(hp, tregs + TCVR_CFG) | TCV_CFG_BENABLE);
	happy_meal_transceiver_check(hp, tregs);
	switch(hp->tcvr_type) {
	case none:
		return;
	case internal:
		hme_write32(hp, bregs + BMAC_XIFCFG, 0);
		break;
	case external:
		hme_write32(hp, bregs + BMAC_XIFCFG, BIGMAC_XCFG_MIIDISAB);
		break;
	};
	if (happy_meal_tcvr_reset(hp, tregs))
		return;

	/* Latch PHY registers as of now. */
	hp->sw_bmsr      = happy_meal_tcvr_read(hp, tregs, MII_BMSR);
	hp->sw_advertise = happy_meal_tcvr_read(hp, tregs, MII_ADVERTISE);

	/* Advertise everything we can support. */
	if (hp->sw_bmsr & BMSR_10HALF)
		hp->sw_advertise |= (ADVERTISE_10HALF);
	else
		hp->sw_advertise &= ~(ADVERTISE_10HALF);

	if (hp->sw_bmsr & BMSR_10FULL)
		hp->sw_advertise |= (ADVERTISE_10FULL);
	else
		hp->sw_advertise &= ~(ADVERTISE_10FULL);
	if (hp->sw_bmsr & BMSR_100HALF)
		hp->sw_advertise |= (ADVERTISE_100HALF);
	else
		hp->sw_advertise &= ~(ADVERTISE_100HALF);
	if (hp->sw_bmsr & BMSR_100FULL)
		hp->sw_advertise |= (ADVERTISE_100FULL);
	else
		hp->sw_advertise &= ~(ADVERTISE_100FULL);

	/* Update the PHY advertisement register. */
	happy_meal_tcvr_write(hp, tregs, MII_ADVERTISE, hp->sw_advertise);
}

/* Once status is latched (by happy_meal_interrupt) it is cleared by
 * the hardware, so we cannot re-read it and get a correct value.
 *
 * hp->happy_lock must be held
 */
static int happy_meal_is_not_so_happy(struct happy_meal *hp, u32 status)
{
	int reset = 0;

	/* Only print messages for non-counter related interrupts. */
	if (status & (GREG_STAT_STSTERR | GREG_STAT_TFIFO_UND |
		      GREG_STAT_MAXPKTERR | GREG_STAT_RXERR |
		      GREG_STAT_RXPERR | GREG_STAT_RXTERR | GREG_STAT_EOPERR |
		      GREG_STAT_MIFIRQ | GREG_STAT_TXEACK | GREG_STAT_TXLERR |
		      GREG_STAT_TXPERR | GREG_STAT_TXTERR | GREG_STAT_SLVERR |
		      GREG_STAT_SLVPERR))
		printk(KERN_ERR "%s: Error interrupt for happy meal, status = %08x\n",
		       hp->dev->name, status);

	if (status & GREG_STAT_RFIFOVF) {
		/* Receive FIFO overflow is harmless and the hardware will take
		   care of it, just some packets are lost. Who cares. */
		printk(KERN_DEBUG "%s: Happy Meal receive FIFO overflow.\n", hp->dev->name);
	}

	if (status & GREG_STAT_STSTERR) {
		/* BigMAC SQE link test failed. */
		printk(KERN_ERR "%s: Happy Meal BigMAC SQE test failed.\n", hp->dev->name);
		reset = 1;
	}

	if (status & GREG_STAT_TFIFO_UND) {
		/* Transmit FIFO underrun, again DMA error likely. */
		printk(KERN_ERR "%s: Happy Meal transmitter FIFO underrun, DMA error.\n",
		       hp->dev->name);
		reset = 1;
	}

	if (status & GREG_STAT_MAXPKTERR) {
		/* Driver error, tried to transmit something larger
		 * than ethernet max mtu.
		 */
		printk(KERN_ERR "%s: Happy Meal MAX Packet size error.\n", hp->dev->name);
		reset = 1;
	}

	if (status & GREG_STAT_NORXD) {
		/* This is harmless, it just means the system is
		 * quite loaded and the incoming packet rate was
		 * faster than the interrupt handler could keep up
		 * with.
		 */
		printk(KERN_INFO "%s: Happy Meal out of receive "
		       "descriptors, packet dropped.\n",
		       hp->dev->name);
	}

	if (status & (GREG_STAT_RXERR|GREG_STAT_RXPERR|GREG_STAT_RXTERR)) {
		/* All sorts of DMA receive errors. */
		printk(KERN_ERR "%s: Happy Meal rx DMA errors [ ", hp->dev->name);
		if (status & GREG_STAT_RXERR)
			printk("GenericError ");
		if (status & GREG_STAT_RXPERR)
			printk("ParityError ");
		if (status & GREG_STAT_RXTERR)
			printk("RxTagBotch ");
		printk("]\n");
		reset = 1;
	}

	if (status & GREG_STAT_EOPERR) {
		/* Driver bug, didn't set EOP bit in tx descriptor given
		 * to the happy meal.
		 */
		printk(KERN_ERR "%s: EOP not set in happy meal transmit descriptor!\n",
		       hp->dev->name);
		reset = 1;
	}

	if (status & GREG_STAT_MIFIRQ) {
		/* MIF signalled an interrupt, were we polling it? */
		printk(KERN_ERR "%s: Happy Meal MIF interrupt.\n", hp->dev->name);
	}

	if (status &
	    (GREG_STAT_TXEACK|GREG_STAT_TXLERR|GREG_STAT_TXPERR|GREG_STAT_TXTERR)) {
		/* All sorts of transmit DMA errors. */
		printk(KERN_ERR "%s: Happy Meal tx DMA errors [ ", hp->dev->name);
		if (status & GREG_STAT_TXEACK)
			printk("GenericError ");
		if (status & GREG_STAT_TXLERR)
			printk("LateError ");
		if (status & GREG_STAT_TXPERR)
			printk("ParityErro ");
		if (status & GREG_STAT_TXTERR)
			printk("TagBotch ");
		printk("]\n");
		reset = 1;
	}

	if (status & (GREG_STAT_SLVERR|GREG_STAT_SLVPERR)) {
		/* Bus or parity error when cpu accessed happy meal registers
		 * or it's internal FIFO's.  Should never see this.
		 */
		printk(KERN_ERR "%s: Happy Meal register access SBUS slave (%s) error.\n",
		       hp->dev->name,
		       (status & GREG_STAT_SLVPERR) ? "parity" : "generic");
		reset = 1;
	}

	if (reset) {
		printk(KERN_NOTICE "%s: Resetting...\n", hp->dev->name);
		happy_meal_init(hp);
		return 1;
	}
	return 0;
}

/* hp->happy_lock must be held */
static void happy_meal_mif_interrupt(struct happy_meal *hp)
{
	void __iomem *tregs = hp->tcvregs;

	printk(KERN_INFO "%s: Link status change.\n", hp->dev->name);
	hp->sw_bmcr = happy_meal_tcvr_read(hp, tregs, MII_BMCR);
	hp->sw_lpa = happy_meal_tcvr_read(hp, tregs, MII_LPA);

	/* Use the fastest transmission protocol possible. */
	if (hp->sw_lpa & LPA_100FULL) {
		printk(KERN_INFO "%s: Switching to 100Mbps at full duplex.", hp->dev->name);
		hp->sw_bmcr |= (BMCR_FULLDPLX | BMCR_SPEED100);
	} else if (hp->sw_lpa & LPA_100HALF) {
		printk(KERN_INFO "%s: Switching to 100MBps at half duplex.", hp->dev->name);
		hp->sw_bmcr |= BMCR_SPEED100;
	} else if (hp->sw_lpa & LPA_10FULL) {
		printk(KERN_INFO "%s: Switching to 10MBps at full duplex.", hp->dev->name);
		hp->sw_bmcr |= BMCR_FULLDPLX;
	} else {
		printk(KERN_INFO "%s: Using 10Mbps at half duplex.", hp->dev->name);
	}
	happy_meal_tcvr_write(hp, tregs, MII_BMCR, hp->sw_bmcr);

	/* Finally stop polling and shut up the MIF. */
	happy_meal_poll_stop(hp, tregs);
}

#ifdef TXDEBUG
#define TXD(x) printk x
#else
#define TXD(x)
#endif

/* hp->happy_lock must be held */
static void happy_meal_tx(struct happy_meal *hp)
{
	struct happy_meal_txd *txbase = &hp->happy_block->happy_meal_txd[0];
	struct happy_meal_txd *this;
	struct net_device *dev = hp->dev;
	int elem;

	elem = hp->tx_old;
	TXD(("TX<"));
	while (elem != hp->tx_new) {
		struct sk_buff *skb;
		u32 flags, dma_addr, dma_len;
		int frag;

		TXD(("[%d]", elem));
		this = &txbase[elem];
		flags = hme_read_desc32(hp, &this->tx_flags);
		if (flags & TXFLAG_OWN)
			break;
		skb = hp->tx_skbs[elem];
		if (skb_shinfo(skb)->nr_frags) {
			int last;

			last = elem + skb_shinfo(skb)->nr_frags;
			last &= (TX_RING_SIZE - 1);
			flags = hme_read_desc32(hp, &txbase[last].tx_flags);
			if (flags & TXFLAG_OWN)
				break;
		}
		hp->tx_skbs[elem] = NULL;
		hp->net_stats.tx_bytes += skb->len;

		for (frag = 0; frag <= skb_shinfo(skb)->nr_frags; frag++) {
			dma_addr = hme_read_desc32(hp, &this->tx_addr);
			dma_len = hme_read_desc32(hp, &this->tx_flags);

			dma_len &= TXFLAG_SIZE;
			hme_dma_unmap(hp, dma_addr, dma_len, DMA_TODEVICE);

			elem = NEXT_TX(elem);
			this = &txbase[elem];
		}

		dev_kfree_skb_irq(skb);
		hp->net_stats.tx_packets++;
	}
	hp->tx_old = elem;
	TXD((">"));

	if (netif_queue_stopped(dev) &&
	    TX_BUFFS_AVAIL(hp) > (MAX_SKB_FRAGS + 1))
		netif_wake_queue(dev);
}

#ifdef RXDEBUG
#define RXD(x) printk x
#else
#define RXD(x)
#endif

/* Originally I used to handle the allocation failure by just giving back just
 * that one ring buffer to the happy meal.  Problem is that usually when that
 * condition is triggered, the happy meal expects you to do something reasonable
 * with all of the packets it has DMA'd in.  So now I just drop the entire
 * ring when we cannot get a new skb and give them all back to the happy meal,
 * maybe things will be "happier" now.
 *
 * hp->happy_lock must be held
 */
static void happy_meal_rx(struct happy_meal *hp, struct net_device *dev)
{
	struct happy_meal_rxd *rxbase = &hp->happy_block->happy_meal_rxd[0];
	struct happy_meal_rxd *this;
	int elem = hp->rx_new, drops = 0;
	u32 flags;

	RXD(("RX<"));
	this = &rxbase[elem];
	while (!((flags = hme_read_desc32(hp, &this->rx_flags)) & RXFLAG_OWN)) {
		struct sk_buff *skb;
		int len = flags >> 16;
		u16 csum = flags & RXFLAG_CSUM;
		u32 dma_addr = hme_read_desc32(hp, &this->rx_addr);

		RXD(("[%d ", elem));

		/* Check for errors. */
		if ((len < ETH_ZLEN) || (flags & RXFLAG_OVERFLOW)) {
			RXD(("ERR(%08x)]", flags));
			hp->net_stats.rx_errors++;
			if (len < ETH_ZLEN)
				hp->net_stats.rx_length_errors++;
			if (len & (RXFLAG_OVERFLOW >> 16)) {
				hp->net_stats.rx_over_errors++;
				hp->net_stats.rx_fifo_errors++;
			}

			/* Return it to the Happy meal. */
	drop_it:
			hp->net_stats.rx_dropped++;
			hme_write_rxd(hp, this,
				      (RXFLAG_OWN|((RX_BUF_ALLOC_SIZE-RX_OFFSET)<<16)),
				      dma_addr);
			goto next;
		}
		skb = hp->rx_skbs[elem];
		if (len > RX_COPY_THRESHOLD) {
			struct sk_buff *new_skb;

			/* Now refill the entry, if we can. */
			new_skb = happy_meal_alloc_skb(RX_BUF_ALLOC_SIZE, GFP_ATOMIC);
			if (new_skb == NULL) {
				drops++;
				goto drop_it;
			}
			hme_dma_unmap(hp, dma_addr, RX_BUF_ALLOC_SIZE, DMA_FROMDEVICE);
			hp->rx_skbs[elem] = new_skb;
			new_skb->dev = dev;
			skb_put(new_skb, (ETH_FRAME_LEN + RX_OFFSET + 4));
			hme_write_rxd(hp, this,
				      (RXFLAG_OWN|((RX_BUF_ALLOC_SIZE-RX_OFFSET)<<16)),
				      hme_dma_map(hp, new_skb->data, RX_BUF_ALLOC_SIZE, DMA_FROMDEVICE));
			skb_reserve(new_skb, RX_OFFSET);

			/* Trim the original skb for the netif. */
			skb_trim(skb, len);
		} else {
			struct sk_buff *copy_skb = dev_alloc_skb(len + 2);

			if (copy_skb == NULL) {
				drops++;
				goto drop_it;
			}

			skb_reserve(copy_skb, 2);
			skb_put(copy_skb, len);
			hme_dma_sync_for_cpu(hp, dma_addr, len, DMA_FROMDEVICE);
			skb_copy_from_linear_data(skb, copy_skb->data, len);
			hme_dma_sync_for_device(hp, dma_addr, len, DMA_FROMDEVICE);

			/* Reuse original ring buffer. */
			hme_write_rxd(hp, this,
				      (RXFLAG_OWN|((RX_BUF_ALLOC_SIZE-RX_OFFSET)<<16)),
				      dma_addr);

			skb = copy_skb;
		}

		/* This card is _fucking_ hot... */
		skb->csum = csum_unfold(~(__force __sum16)htons(csum));
		skb->ip_summed = CHECKSUM_COMPLETE;

		RXD(("len=%d csum=%4x]", len, csum));
		skb->protocol = eth_type_trans(skb, dev);
		netif_rx(skb);

		dev->last_rx = jiffies;
		hp->net_stats.rx_packets++;
		hp->net_stats.rx_bytes += len;
	next:
		elem = NEXT_RX(elem);
		this = &rxbase[elem];
	}
	hp->rx_new = elem;
	if (drops)
		printk(KERN_INFO "%s: Memory squeeze, deferring packet.\n", hp->dev->name);
	RXD((">"));
}

static irqreturn_t happy_meal_interrupt(int irq, void *dev_id)
{
	struct net_device *dev = dev_id;
	struct happy_meal *hp  = netdev_priv(dev);
	u32 happy_status       = hme_read32(hp, hp->gregs + GREG_STAT);

	HMD(("happy_meal_interrupt: status=%08x ", happy_status));

	spin_lock(&hp->happy_lock);

	if (happy_status & GREG_STAT_ERRORS) {
		HMD(("ERRORS "));
		if (happy_meal_is_not_so_happy(hp, /* un- */ happy_status))
			goto out;
	}

	if (happy_status & GREG_STAT_MIFIRQ) {
		HMD(("MIFIRQ "));
		happy_meal_mif_interrupt(hp);
	}

	if (happy_status & GREG_STAT_TXALL) {
		HMD(("TXALL "));
		happy_meal_tx(hp);
	}

	if (happy_status & GREG_STAT_RXTOHOST) {
		HMD(("RXTOHOST "));
		happy_meal_rx(hp, dev);
	}

	HMD(("done\n"));
out:
	spin_unlock(&hp->happy_lock);

	return IRQ_HANDLED;
}

#ifdef CONFIG_SBUS
static irqreturn_t quattro_sbus_interrupt(int irq, void *cookie)
{
	struct quattro *qp = (struct quattro *) cookie;
	int i;

	for (i = 0; i < 4; i++) {
		struct net_device *dev = qp->happy_meals[i];
		struct happy_meal *hp  = dev->priv;
		u32 happy_status       = hme_read32(hp, hp->gregs + GREG_STAT);

		HMD(("quattro_interrupt: status=%08x ", happy_status));

		if (!(happy_status & (GREG_STAT_ERRORS |
				      GREG_STAT_MIFIRQ |
				      GREG_STAT_TXALL |
				      GREG_STAT_RXTOHOST)))
			continue;

		spin_lock(&hp->happy_lock);

		if (happy_status & GREG_STAT_ERRORS) {
			HMD(("ERRORS "));
			if (happy_meal_is_not_so_happy(hp, happy_status))
				goto next;
		}

		if (happy_status & GREG_STAT_MIFIRQ) {
			HMD(("MIFIRQ "));
			happy_meal_mif_interrupt(hp);
		}

		if (happy_status & GREG_STAT_TXALL) {
			HMD(("TXALL "));
			happy_meal_tx(hp);
		}

		if (happy_status & GREG_STAT_RXTOHOST) {
			HMD(("RXTOHOST "));
			happy_meal_rx(hp, dev);
		}

	next:
		spin_unlock(&hp->happy_lock);
	}
	HMD(("done\n"));

	return IRQ_HANDLED;
}
#endif

static int happy_meal_open(struct net_device *dev)
{
	struct happy_meal *hp = dev->priv;
	int res;

	HMD(("happy_meal_open: "));

	/* On SBUS Quattro QFE cards, all hme interrupts are concentrated
	 * into a single source which we register handling at probe time.
	 */
	if ((hp->happy_flags & (HFLAG_QUATTRO|HFLAG_PCI)) != HFLAG_QUATTRO) {
		if (request_irq(dev->irq, &happy_meal_interrupt,
				IRQF_SHARED, dev->name, (void *)dev)) {
			HMD(("EAGAIN\n"));
			printk(KERN_ERR "happy_meal(SBUS): Can't order irq %d to go.\n",
			       dev->irq);

			return -EAGAIN;
		}
	}

	HMD(("to happy_meal_init\n"));

	spin_lock_irq(&hp->happy_lock);
	res = happy_meal_init(hp);
	spin_unlock_irq(&hp->happy_lock);

	if (res && ((hp->happy_flags & (HFLAG_QUATTRO|HFLAG_PCI)) != HFLAG_QUATTRO))
		free_irq(dev->irq, dev);
	return res;
}

static int happy_meal_close(struct net_device *dev)
{
	struct happy_meal *hp = dev->priv;

	spin_lock_irq(&hp->happy_lock);
	happy_meal_stop(hp, hp->gregs);
	happy_meal_clean_rings(hp);

	/* If auto-negotiation timer is running, kill it. */
	del_timer(&hp->happy_timer);

	spin_unlock_irq(&hp->happy_lock);

	/* On Quattro QFE cards, all hme interrupts are concentrated
	 * into a single source which we register handling at probe
	 * time and never unregister.
	 */
	if ((hp->happy_flags & (HFLAG_QUATTRO|HFLAG_PCI)) != HFLAG_QUATTRO)
		free_irq(dev->irq, dev);

	return 0;
}

#ifdef SXDEBUG
#define SXD(x) printk x
#else
#define SXD(x)
#endif

static void happy_meal_tx_timeout(struct net_device *dev)
{
	struct happy_meal *hp = dev->priv;

	printk (KERN_ERR "%s: transmit timed out, resetting\n", dev->name);
	tx_dump_log();
	printk (KERN_ERR "%s: Happy Status %08x TX[%08x:%08x]\n", dev->name,
		hme_read32(hp, hp->gregs + GREG_STAT),
		hme_read32(hp, hp->etxregs + ETX_CFG),
		hme_read32(hp, hp->bigmacregs + BMAC_TXCFG));

	spin_lock_irq(&hp->happy_lock);
	happy_meal_init(hp);
	spin_unlock_irq(&hp->happy_lock);

	netif_wake_queue(dev);
}

static int happy_meal_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
	struct happy_meal *hp = dev->priv;
 	int entry;
 	u32 tx_flags;

	tx_flags = TXFLAG_OWN;
	if (skb->ip_summed == CHECKSUM_PARTIAL) {
		const u32 csum_start_off = skb_transport_offset(skb);
		const u32 csum_stuff_off = csum_start_off + skb->csum_offset;

		tx_flags = (TXFLAG_OWN | TXFLAG_CSENABLE |
			    ((csum_start_off << 14) & TXFLAG_CSBUFBEGIN) |
			    ((csum_stuff_off << 20) & TXFLAG_CSLOCATION));
	}

	spin_lock_irq(&hp->happy_lock);

 	if (TX_BUFFS_AVAIL(hp) <= (skb_shinfo(skb)->nr_frags + 1)) {
		netif_stop_queue(dev);
		spin_unlock_irq(&hp->happy_lock);
		printk(KERN_ERR "%s: BUG! Tx Ring full when queue awake!\n",
		       dev->name);
		return 1;
	}

	entry = hp->tx_new;
	SXD(("SX<l[%d]e[%d]>", len, entry));
	hp->tx_skbs[entry] = skb;

	if (skb_shinfo(skb)->nr_frags == 0) {
		u32 mapping, len;

		len = skb->len;
		mapping = hme_dma_map(hp, skb->data, len, DMA_TODEVICE);
		tx_flags |= (TXFLAG_SOP | TXFLAG_EOP);
		hme_write_txd(hp, &hp->happy_block->happy_meal_txd[entry],
			      (tx_flags | (len & TXFLAG_SIZE)),
			      mapping);
		entry = NEXT_TX(entry);
	} else {
		u32 first_len, first_mapping;
		int frag, first_entry = entry;

		/* We must give this initial chunk to the device last.
		 * Otherwise we could race with the device.
		 */
		first_len = skb_headlen(skb);
		first_mapping = hme_dma_map(hp, skb->data, first_len, DMA_TODEVICE);
		entry = NEXT_TX(entry);

		for (frag = 0; frag < skb_shinfo(skb)->nr_frags; frag++) {
			skb_frag_t *this_frag = &skb_shinfo(skb)->frags[frag];
			u32 len, mapping, this_txflags;

			len = this_frag->size;
			mapping = hme_dma_map(hp,
					      ((void *) page_address(this_frag->page) +
					       this_frag->page_offset),
					      len, DMA_TODEVICE);
			this_txflags = tx_flags;
			if (frag == skb_shinfo(skb)->nr_frags - 1)
				this_txflags |= TXFLAG_EOP;
			hme_write_txd(hp, &hp->happy_block->happy_meal_txd[entry],
				      (this_txflags | (len & TXFLAG_SIZE)),
				      mapping);
			entry = NEXT_TX(entry);
		}
		hme_write_txd(hp, &hp->happy_block->happy_meal_txd[first_entry],
			      (tx_flags | TXFLAG_SOP | (first_len & TXFLAG_SIZE)),
			      first_mapping);
	}

	hp->tx_new = entry;

	if (TX_BUFFS_AVAIL(hp) <= (MAX_SKB_FRAGS + 1))
		netif_stop_queue(dev);

	/* Get it going. */
	hme_write32(hp, hp->etxregs + ETX_PENDING, ETX_TP_DMAWAKEUP);

	spin_unlock_irq(&hp->happy_lock);

	dev->trans_start = jiffies;

	tx_add_log(hp, TXLOG_ACTION_TXMIT, 0);
	return 0;
}

static struct net_device_stats *happy_meal_get_stats(struct net_device *dev)
{
	struct happy_meal *hp = dev->priv;

	spin_lock_irq(&hp->happy_lock);
	happy_meal_get_counters(hp, hp->bigmacregs);
	spin_unlock_irq(&hp->happy_lock);

	return &hp->net_stats;
}

static void happy_meal_set_multicast(struct net_device *dev)
{
	struct happy_meal *hp = dev->priv;
	void __iomem *bregs = hp->bigmacregs;
	struct dev_mc_list *dmi = dev->mc_list;
	char *addrs;
	int i;
	u32 crc;

	spin_lock_irq(&hp->happy_lock);

	netif_stop_queue(dev);

	if ((dev->flags & IFF_ALLMULTI) || (dev->mc_count > 64)) {
		hme_write32(hp, bregs + BMAC_HTABLE0, 0xffff);
		hme_write32(hp, bregs + BMAC_HTABLE1, 0xffff);
		hme_write32(hp, bregs + BMAC_HTABLE2, 0xffff);
		hme_write32(hp, bregs + BMAC_HTABLE3, 0xffff);
	} else if (dev->flags & IFF_PROMISC) {
		hme_write32(hp, bregs + BMAC_RXCFG,
			    hme_read32(hp, bregs + BMAC_RXCFG) | BIGMAC_RXCFG_PMISC);
	} else {
		u16 hash_table[4];

		for (i = 0; i < 4; i++)
			hash_table[i] = 0;

		for (i = 0; i < dev->mc_count; i++) {
			addrs = dmi->dmi_addr;
			dmi = dmi->next;

			if (!(*addrs & 1))
				continue;

			crc = ether_crc_le(6, addrs);
			crc >>= 26;
			hash_table[crc >> 4] |= 1 << (crc & 0xf);
		}
		hme_write32(hp, bregs + BMAC_HTABLE0, hash_table[0]);
		hme_write32(hp, bregs + BMAC_HTABLE1, hash_table[1]);
		hme_write32(hp, bregs + BMAC_HTABLE2, hash_table[2]);
		hme_write32(hp, bregs + BMAC_HTABLE3, hash_table[3]);
	}

	netif_wake_queue(dev);

	spin_unlock_irq(&hp->happy_lock);
}

/* Ethtool support... */
static int hme_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
	struct happy_meal *hp = dev->priv;

	cmd->supported =
		(SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full |
		 SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full |
		 SUPPORTED_Autoneg | SUPPORTED_TP | SUPPORTED_MII);

	/* XXX hardcoded stuff for now */
	cmd->port = PORT_TP; /* XXX no MII support */
	cmd->transceiver = XCVR_INTERNAL; /* XXX no external xcvr support */
	cmd->phy_address = 0; /* XXX fixed PHYAD */

	/* Record PHY settings. */
	spin_lock_irq(&hp->happy_lock);
	hp->sw_bmcr = happy_meal_tcvr_read(hp, hp->tcvregs, MII_BMCR);
	hp->sw_lpa = happy_meal_tcvr_read(hp, hp->tcvregs, MII_LPA);
	spin_unlock_irq(&hp->happy_lock);

	if (hp->sw_bmcr & BMCR_ANENABLE) {
		cmd->autoneg = AUTONEG_ENABLE;
		cmd->speed =
			(hp->sw_lpa & (LPA_100HALF | LPA_100FULL)) ?
			SPEED_100 : SPEED_10;
		if (cmd->speed == SPEED_100)
			cmd->duplex =
				(hp->sw_lpa & (LPA_100FULL)) ?
				DUPLEX_FULL : DUPLEX_HALF;
		else
			cmd->duplex =
				(hp->sw_lpa & (LPA_10FULL)) ?
				DUPLEX_FULL : DUPLEX_HALF;
	} else {
		cmd->autoneg = AUTONEG_DISABLE;
		cmd->speed =
			(hp->sw_bmcr & BMCR_SPEED100) ?
			SPEED_100 : SPEED_10;
		cmd->duplex =
			(hp->sw_bmcr & BMCR_FULLDPLX) ?
			DUPLEX_FULL : DUPLEX_HALF;
	}
	return 0;
}

static int hme_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
	struct happy_meal *hp = dev->priv;

	/* Verify the settings we care about. */
	if (cmd->autoneg != AUTONEG_ENABLE &&
	    cmd->autoneg != AUTONEG_DISABLE)
		return -EINVAL;
	if (cmd->autoneg == AUTONEG_DISABLE &&
	    ((cmd->speed != SPEED_100 &&
	      cmd->speed != SPEED_10) ||
	     (cmd->duplex != DUPLEX_HALF &&
	      cmd->duplex != DUPLEX_FULL)))
		return -EINVAL;

	/* Ok, do it to it. */
	spin_lock_irq(&hp->happy_lock);
	del_timer(&hp->happy_timer);
	happy_meal_begin_auto_negotiation(hp, hp->tcvregs, cmd);
	spin_unlock_irq(&hp->happy_lock);

	return 0;
}

static void hme_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
	struct happy_meal *hp = dev->priv;

	strcpy(info->driver, "sunhme");
	strcpy(info->version, "2.02");
	if (hp->happy_flags & HFLAG_PCI) {
		struct pci_dev *pdev = hp->happy_dev;
		strcpy(info->bus_info, pci_name(pdev));
	}
#ifdef CONFIG_SBUS
	else {
		struct sbus_dev *sdev = hp->happy_dev;
		sprintf(info->bus_info, "SBUS:%d",
			sdev->slot);
	}
#endif
}

static u32 hme_get_link(struct net_device *dev)
{
	struct happy_meal *hp = dev->priv;

	spin_lock_irq(&hp->happy_lock);
	hp->sw_bmcr = happy_meal_tcvr_read(hp, hp->tcvregs, MII_BMCR);
	spin_unlock_irq(&hp->happy_lock);

	return (hp->sw_bmsr & BMSR_LSTATUS);
}

static const struct ethtool_ops hme_ethtool_ops = {
	.get_settings		= hme_get_settings,
	.set_settings		= hme_set_settings,
	.get_drvinfo		= hme_get_drvinfo,
	.get_link		= hme_get_link,
};

static int hme_version_printed;

#ifdef CONFIG_SBUS
void __devinit quattro_get_ranges(struct quattro *qp)
{
	struct sbus_dev *sdev = qp->quattro_dev;
	int err;

	err = prom_getproperty(sdev->prom_node,
			       "ranges",
			       (char *)&qp->ranges[0],
			       sizeof(qp->ranges));
	if (err == 0 || err == -1) {
		qp->nranges = 0;
		return;
	}
	qp->nranges = (err / sizeof(struct linux_prom_ranges));
}

static void __devinit quattro_apply_ranges(struct quattro *qp, struct happy_meal *hp)
{
	struct sbus_dev *sdev = hp->happy_dev;
	int rng;

	for (rng = 0; rng < qp->nranges; rng++) {
		struct linux_prom_ranges *rngp = &qp->ranges[rng];
		int reg;

		for (reg = 0; reg < 5; reg++) {
			if (sdev->reg_addrs[reg].which_io ==
			    rngp->ot_child_space)
				break;
		}
		if (reg == 5)
			continue;

		sdev->reg_addrs[reg].which_io = rngp->ot_parent_space;
		sdev->reg_addrs[reg].phys_addr += rngp->ot_parent_base;
	}
}

/* Given a happy meal sbus device, find it's quattro parent.
 * If none exist, allocate and return a new one.
 *
 * Return NULL on failure.
 */
static struct quattro * __devinit quattro_sbus_find(struct sbus_dev *goal_sdev)
{
	struct sbus_dev *sdev;
	struct quattro *qp;
	int i;

	for (qp = qfe_sbus_list; qp != NULL; qp = qp->next) {
		for (i = 0, sdev = qp->quattro_dev;
		     (sdev != NULL) && (i < 4);
		     sdev = sdev->next, i++) {
			if (sdev == goal_sdev)
				return qp;
		}
	}

	qp = kmalloc(sizeof(struct quattro), GFP_KERNEL);
	if (qp != NULL) {
		int i;

		for (i = 0; i < 4; i++)
			qp->happy_meals[i] = NULL;

		qp->quattro_dev = goal_sdev;
		qp->next = qfe_sbus_list;
		qfe_sbus_list = qp;
		quattro_get_ranges(qp);
	}
	return qp;
}

/* After all quattro cards have been probed, we call these functions
 * to register the IRQ handlers.
 */
static void __init quattro_sbus_register_irqs(void)
{
	struct quattro *qp;

	for (qp = qfe_sbus_list; qp != NULL; qp = qp->next) {
		struct sbus_dev *sdev = qp->quattro_dev;
		int err;

		err = request_irq(sdev->irqs[0],
				  quattro_sbus_interrupt,
				  IRQF_SHARED, "Quattro",
				  qp);
		if (err != 0) {
			printk(KERN_ERR "Quattro: Fatal IRQ registery error %d.\n", err);
			panic("QFE request irq");
		}
	}
}

static void quattro_sbus_free_irqs(void)
{
	struct quattro *qp;

	for (qp = qfe_sbus_list; qp != NULL; qp = qp->next) {
		struct sbus_dev *sdev = qp->quattro_dev;

		free_irq(sdev->irqs[0], qp);
	}
}
#endif /* CONFIG_SBUS */

#ifdef CONFIG_PCI
static struct quattro * __devinit quattro_pci_find(struct pci_dev *pdev)
{
	struct pci_dev *bdev = pdev->bus->self;
	struct quattro *qp;

	if (!bdev) return NULL;
	for (qp = qfe_pci_list; qp != NULL; qp = qp->next) {
		struct pci_dev *qpdev = qp->quattro_dev;

		if (qpdev == bdev)
			return qp;
	}
	qp = kmalloc(sizeof(struct quattro), GFP_KERNEL);
	if (qp != NULL) {
		int i;

		for (i = 0; i < 4; i++)
			qp->happy_meals[i] = NULL;

		qp->quattro_dev = bdev;
		qp->next = qfe_pci_list;
		qfe_pci_list = qp;

		/* No range tricks necessary on PCI. */
		qp->nranges = 0;
	}
	return qp;
}
#endif /* CONFIG_PCI */

#ifdef CONFIG_SBUS
static int __devinit happy_meal_sbus_probe_one(struct sbus_dev *sdev, int is_qfe)
{
	struct device_node *dp = sdev->ofdev.node;
	struct quattro *qp = NULL;
	struct happy_meal *hp;
	struct net_device *dev;
	int i, qfe_slot = -1;
	int err = -ENODEV;
	DECLARE_MAC_BUF(mac);

	if (is_qfe) {
		qp = quattro_sbus_find(sdev);
		if (qp == NULL)
			goto err_out;
		for (qfe_slot = 0; qfe_slot < 4; qfe_slot++)
			if (qp->happy_meals[qfe_slot] == NULL)
				break;
		if (qfe_slot == 4)
			goto err_out;
	}

	err = -ENOMEM;
	dev = alloc_etherdev(sizeof(struct happy_meal));
	if (!dev)
		goto err_out;
	SET_NETDEV_DEV(dev, &sdev->ofdev.dev);

	if (hme_version_printed++ == 0)
		printk(KERN_INFO "%s", version);

	/* If user did not specify a MAC address specifically, use
	 * the Quattro local-mac-address property...
	 */
	for (i = 0; i < 6; i++) {
		if (macaddr[i] != 0)
			break;
	}
	if (i < 6) { /* a mac address was given */
		for (i = 0; i < 6; i++)
			dev->dev_addr[i] = macaddr[i];
		macaddr[5]++;
	} else {
		const unsigned char *addr;
		int len;

		addr = of_get_property(dp, "local-mac-address", &len);

		if (qfe_slot != -1 && addr && len == 6)
			memcpy(dev->dev_addr, addr, 6);
		else
			memcpy(dev->dev_addr, idprom->id_ethaddr, 6);
	}

	hp = dev->priv;

	hp->happy_dev = sdev;

	spin_lock_init(&hp->happy_lock);

	err = -ENODEV;
	if (sdev->num_registers != 5) {
		printk(KERN_ERR "happymeal: Device needs 5 regs, has %d.\n",
		       sdev->num_registers);
		goto err_out_free_netdev;
	}

	if (qp != NULL) {
		hp->qfe_parent = qp;
		hp->qfe_ent = qfe_slot;
		qp->happy_meals[qfe_slot] = dev;
		quattro_apply_ranges(qp, hp);
	}

	hp->gregs = sbus_ioremap(&sdev->resource[0], 0,
				 GREG_REG_SIZE, "HME Global Regs");
	if (!hp->gregs) {
		printk(KERN_ERR "happymeal: Cannot map global registers.\n");
		goto err_out_free_netdev;
	}

	hp->etxregs = sbus_ioremap(&sdev->resource[1], 0,
				   ETX_REG_SIZE, "HME TX Regs");
	if (!hp->etxregs) {
		printk(KERN_ERR "happymeal: Cannot map MAC TX registers.\n");
		goto err_out_iounmap;
	}

	hp->erxregs = sbus_ioremap(&sdev->resource[2], 0,
				   ERX_REG_SIZE, "HME RX Regs");
	if (!hp->erxregs) {
		printk(KERN_ERR "happymeal: Cannot map MAC RX registers.\n");
		goto err_out_iounmap;
	}

	hp->bigmacregs = sbus_ioremap(&sdev->resource[3], 0,
				      BMAC_REG_SIZE, "HME BIGMAC Regs");
	if (!hp->bigmacregs) {
		printk(KERN_ERR "happymeal: Cannot map BIGMAC registers.\n");
		goto err_out_iounmap;
	}

	hp->tcvregs = sbus_ioremap(&sdev->resource[4], 0,
				   TCVR_REG_SIZE, "HME Tranceiver Regs");
	if (!hp->tcvregs) {
		printk(KERN_ERR "happymeal: Cannot map TCVR registers.\n");
		goto err_out_iounmap;
	}

	hp->hm_revision = of_getintprop_default(dp, "hm-rev", 0xff);
	if (hp->hm_revision == 0xff)
		hp->hm_revision = 0xa0;

	/* Now enable the feature flags we can. */
	if (hp->hm_revision == 0x20 || hp->hm_revision == 0x21)
		hp->happy_flags = HFLAG_20_21;
	else if (hp->hm_revision != 0xa0)
		hp->happy_flags = HFLAG_NOT_A0;

	if (qp != NULL)
		hp->happy_flags |= HFLAG_QUATTRO;

	/* Get the supported DVMA burst sizes from our Happy SBUS. */
	hp->happy_bursts = of_getintprop_default(sdev->bus->ofdev.node,
						 "burst-sizes", 0x00);

	hp->happy_block = sbus_alloc_consistent(hp->happy_dev,
						PAGE_SIZE,
						&hp->hblock_dvma);
	err = -ENOMEM;
	if (!hp->happy_block) {
		printk(KERN_ERR "happymeal: Cannot allocate descriptors.\n");
		goto err_out_iounmap;
	}

	/* Force check of the link first time we are brought up. */
	hp->linkcheck = 0;

	/* Force timer state to 'asleep' with count of zero. */
	hp->timer_state = asleep;
	hp->timer_ticks = 0;

	init_timer(&hp->happy_timer);

	hp->dev = dev;
	dev->open = &happy_meal_open;
	dev->stop = &happy_meal_close;
	dev->hard_start_xmit = &happy_meal_start_xmit;
	dev->get_stats = &happy_meal_get_stats;
	dev->set_multicast_list = &happy_meal_set_multicast;
	dev->tx_timeout = &happy_meal_tx_timeout;
	dev->watchdog_timeo = 5*HZ;
	dev->ethtool_ops = &hme_ethtool_ops;

	/* Happy Meal can do it all... */
	dev->features |= NETIF_F_SG | NETIF_F_HW_CSUM;

	dev->irq = sdev->irqs[0];

#if defined(CONFIG_SBUS) && defined(CONFIG_PCI)
	/* Hook up PCI register/dma accessors. */
	hp->read_desc32 = sbus_hme_read_desc32;
	hp->write_txd = sbus_hme_write_txd;
	hp->write_rxd = sbus_hme_write_rxd;
	hp->dma_map = (u32 (*)(void *, void *, long, int))sbus_map_single;
	hp->dma_unmap = (void (*)(void *, u32, long, int))sbus_unmap_single;
	hp->dma_sync_for_cpu = (void (*)(void *, u32, long, int))
		sbus_dma_sync_single_for_cpu;
	hp->dma_sync_for_device = (void (*)(void *, u32, long, int))
		sbus_dma_sync_single_for_device;
	hp->read32 = sbus_hme_read32;
	hp->write32 = sbus_hme_write32;
#endif

	/* Grrr, Happy Meal comes up by default not advertising
	 * full duplex 100baseT capabilities, fix this.
	 */
	spin_lock_irq(&hp->happy_lock);
	happy_meal_set_initial_advertisement(hp);
	spin_unlock_irq(&hp->happy_lock);

	if (register_netdev(hp->dev)) {
		printk(KERN_ERR "happymeal: Cannot register net device, "
		       "aborting.\n");
		goto err_out_free_consistent;
	}

	dev_set_drvdata(&sdev->ofdev.dev, hp);

	if (qfe_slot != -1)
		printk(KERN_INFO "%s: Quattro HME slot %d (SBUS) 10/100baseT Ethernet ",
		       dev->name, qfe_slot);
	else
		printk(KERN_INFO "%s: HAPPY MEAL (SBUS) 10/100baseT Ethernet ",
		       dev->name);

	printk("%s\n", print_mac(mac, dev->dev_addr));

	return 0;

err_out_free_consistent:
	sbus_free_consistent(hp->happy_dev,
			     PAGE_SIZE,
			     hp->happy_block,
			     hp->hblock_dvma);

err_out_iounmap:
	if (hp->gregs)
		sbus_iounmap(hp->gregs, GREG_REG_SIZE);
	if (hp->etxregs)
		sbus_iounmap(hp->etxregs, ETX_REG_SIZE);
	if (hp->erxregs)
		sbus_iounmap(hp->erxregs, ERX_REG_SIZE);
	if (hp->bigmacregs)
		sbus_iounmap(hp->bigmacregs, BMAC_REG_SIZE);
	if (hp->tcvregs)
		sbus_iounmap(hp->tcvregs, TCVR_REG_SIZE);

err_out_free_netdev:
	free_netdev(dev);

err_out:
	return err;
}
#endif

#ifdef CONFIG_PCI
#ifndef CONFIG_SPARC
static int is_quattro_p(struct pci_dev *pdev)
{
	struct pci_dev *busdev = pdev->bus->self;
	struct list_head *tmp;
	int n_hmes;

	if (busdev == NULL ||
	    busdev->vendor != PCI_VENDOR_ID_DEC ||
	    busdev->device != PCI_DEVICE_ID_DEC_21153)
		return 0;

	n_hmes = 0;
	tmp = pdev->bus->devices.next;
	while (tmp != &pdev->bus->devices) {
		struct pci_dev *this_pdev = pci_dev_b(tmp);

		if (this_pdev->vendor == PCI_VENDOR_ID_SUN &&
		    this_pdev->device == PCI_DEVICE_ID_SUN_HAPPYMEAL)
			n_hmes++;

		tmp = tmp->next;
	}

	if (n_hmes != 4)
		return 0;

	return 1;
}

/* Fetch MAC address from vital product data of PCI ROM. */
static int find_eth_addr_in_vpd(void __iomem *rom_base, int len, int index, unsigned char *dev_addr)
{
	int this_offset;

	for (this_offset = 0x20; this_offset < len; this_offset++) {
		void __iomem *p = rom_base + this_offset;

		if (readb(p + 0) != 0x90 ||
		    readb(p + 1) != 0x00 ||
		    readb(p + 2) != 0x09 ||
		    readb(p + 3) != 0x4e ||
		    readb(p + 4) != 0x41 ||
		    readb(p + 5) != 0x06)
			continue;

		this_offset += 6;
		p += 6;

		if (index == 0) {
			int i;

			for (i = 0; i < 6; i++)
				dev_addr[i] = readb(p + i);
			return 1;
		}
		index--;
	}
	return 0;
}

static void get_hme_mac_nonsparc(struct pci_dev *pdev, unsigned char *dev_addr)
{
	size_t size;
	void __iomem *p = pci_map_rom(pdev, &size);

	if (p) {
		int index = 0;
		int found;

		if (is_quattro_p(pdev))
			index = PCI_SLOT(pdev->devfn);

		found = readb(p) == 0x55 &&
			readb(p + 1) == 0xaa &&
			find_eth_addr_in_vpd(p, (64 * 1024), index, dev_addr);
		pci_unmap_rom(pdev, p);
		if (found)
			return;
	}

	/* Sun MAC prefix then 3 random bytes. */
	dev_addr[0] = 0x08;
	dev_addr[1] = 0x00;
	dev_addr[2] = 0x20;
	get_random_bytes(&dev_addr[3], 3);
	return;
}
#endif /* !(CONFIG_SPARC) */

static int __devinit happy_meal_pci_probe(struct pci_dev *pdev,
					  const struct pci_device_id *ent)
{
	struct quattro *qp = NULL;
#ifdef CONFIG_SPARC
	struct device_node *dp;
#endif
	struct happy_meal *hp;
	struct net_device *dev;
	void __iomem *hpreg_base;
	unsigned long hpreg_res;
	int i, qfe_slot = -1;
	char prom_name[64];
	int err;
	DECLARE_MAC_BUF(mac);

	/* Now make sure pci_dev cookie is there. */
#ifdef CONFIG_SPARC
	dp = pci_device_to_OF_node(pdev);
	strcpy(prom_name, dp->name);
#else
	if (is_quattro_p(pdev))
		strcpy(prom_name, "SUNW,qfe");
	else
		strcpy(prom_name, "SUNW,hme");
#endif

	err = -ENODEV;

	if (pci_enable_device(pdev))
		goto err_out;
	pci_set_master(pdev);

	if (!strcmp(prom_name, "SUNW,qfe") || !strcmp(prom_name, "qfe")) {
		qp = quattro_pci_find(pdev);
		if (qp == NULL)
			goto err_out;
		for (qfe_slot = 0; qfe_slot < 4; qfe_slot++)
			if (qp->happy_meals[qfe_slot] == NULL)
				break;
		if (qfe_slot == 4)
			goto err_out;
	}

	dev = alloc_etherdev(sizeof(struct happy_meal));
	err = -ENOMEM;
	if (!dev)
		goto err_out;
	SET_NETDEV_DEV(dev, &pdev->dev);

	if (hme_version_printed++ == 0)
		printk(KERN_INFO "%s", version);

	dev->base_addr = (long) pdev;

	hp = (struct happy_meal *)dev->priv;
	memset(hp, 0, sizeof(*hp));

	hp->happy_dev = pdev;

	spin_lock_init(&hp->happy_lock);

	if (qp != NULL) {
		hp->qfe_parent = qp;
		hp->qfe_ent = qfe_slot;
		qp->happy_meals[qfe_slot] = dev;
	}

	hpreg_res = pci_resource_start(pdev, 0);
	err = -ENODEV;
	if ((pci_resource_flags(pdev, 0) & IORESOURCE_IO) != 0) {
		printk(KERN_ERR "happymeal(PCI): Cannot find proper PCI device base address.\n");
		goto err_out_clear_quattro;
	}
	if (pci_request_regions(pdev, DRV_NAME)) {
		printk(KERN_ERR "happymeal(PCI): Cannot obtain PCI resources, "
		       "aborting.\n");
		goto err_out_clear_quattro;
	}

	if ((hpreg_base = ioremap(hpreg_res, 0x8000)) == NULL) {
		printk(KERN_ERR "happymeal(PCI): Unable to remap card memory.\n");
		goto err_out_free_res;
	}

	for (i = 0; i < 6; i++) {
		if (macaddr[i] != 0)
			break;
	}
	if (i < 6) { /* a mac address was given */
		for (i = 0; i < 6; i++)
			dev->dev_addr[i] = macaddr[i];
		macaddr[5]++;
	} else {
#ifdef CONFIG_SPARC
		const unsigned char *addr;
		int len;

		if (qfe_slot != -1 &&
		    (addr = of_get_property(dp,
					    "local-mac-address", &len)) != NULL
		    && len == 6) {
			memcpy(dev->dev_addr, addr, 6);
		} else {
			memcpy(dev->dev_addr, idprom->id_ethaddr, 6);
		}
#else
		get_hme_mac_nonsparc(pdev, &dev->dev_addr[0]);
#endif
	}

	/* Layout registers. */
	hp->gregs      = (hpreg_base + 0x0000UL);
	hp->etxregs    = (hpreg_base + 0x2000UL);
	hp->erxregs    = (hpreg_base + 0x4000UL);
	hp->bigmacregs = (hpreg_base + 0x6000UL);
	hp->tcvregs    = (hpreg_base + 0x7000UL);

#ifdef CONFIG_SPARC
	hp->hm_revision = of_getintprop_default(dp, "hm-rev", 0xff);
	if (hp->hm_revision == 0xff)
		hp->hm_revision = 0xc0 | (pdev->revision & 0x0f);
#else
	/* works with this on non-sparc hosts */
	hp->hm_revision = 0x20;
#endif

	/* Now enable the feature flags we can. */
	if (hp->hm_revision == 0x20 || hp->hm_revision == 0x21)
		hp->happy_flags = HFLAG_20_21;
	else if (hp->hm_revision != 0xa0 && hp->hm_revision != 0xc0)
		hp->happy_flags = HFLAG_NOT_A0;

	if (qp != NULL)
		hp->happy_flags |= HFLAG_QUATTRO;

	/* And of course, indicate this is PCI. */
	hp->happy_flags |= HFLAG_PCI;

#ifdef CONFIG_SPARC
	/* Assume PCI happy meals can handle all burst sizes. */
	hp->happy_bursts = DMA_BURSTBITS;
#endif

	hp->happy_block = (struct hmeal_init_block *)
		pci_alloc_consistent(pdev, PAGE_SIZE, &hp->hblock_dvma);

	err = -ENODEV;
	if (!hp->happy_block) {
		printk(KERN_ERR "happymeal(PCI): Cannot get hme init block.\n");
		goto err_out_iounmap;
	}

	hp->linkcheck = 0;
	hp->timer_state = asleep;
	hp->timer_ticks = 0;

	init_timer(&hp->happy_timer);

	hp->dev = dev;
	dev->open = &happy_meal_open;
	dev->stop = &happy_meal_close;
	dev->hard_start_xmit = &happy_meal_start_xmit;
	dev->get_stats = &happy_meal_get_stats;
	dev->set_multicast_list = &happy_meal_set_multicast;
	dev->tx_timeout = &happy_meal_tx_timeout;
	dev->watchdog_timeo = 5*HZ;
	dev->ethtool_ops = &hme_ethtool_ops;
	dev->irq = pdev->irq;
	dev->dma = 0;

	/* Happy Meal can do it all... */
	dev->features |= NETIF_F_SG | NETIF_F_HW_CSUM;

#if defined(CONFIG_SBUS) && defined(CONFIG_PCI)
	/* Hook up PCI register/dma accessors. */
	hp->read_desc32 = pci_hme_read_desc32;
	hp->write_txd = pci_hme_write_txd;
	hp->write_rxd = pci_hme_write_rxd;
	hp->dma_map = (u32 (*)(void *, void *, long, int))pci_map_single;
	hp->dma_unmap = (void (*)(void *, u32, long, int))pci_unmap_single;
	hp->dma_sync_for_cpu = (void (*)(void *, u32, long, int))
		pci_dma_sync_single_for_cpu;
	hp->dma_sync_for_device = (void (*)(void *, u32, long, int))
		pci_dma_sync_single_for_device;
	hp->read32 = pci_hme_read32;
	hp->write32 = pci_hme_write32;
#endif

	/* Grrr, Happy Meal comes up by default not advertising
	 * full duplex 100baseT capabilities, fix this.
	 */
	spin_lock_irq(&hp->happy_lock);
	happy_meal_set_initial_advertisement(hp);
	spin_unlock_irq(&hp->happy_lock);

	if (register_netdev(hp->dev)) {
		printk(KERN_ERR "happymeal(PCI): Cannot register net device, "
		       "aborting.\n");
		goto err_out_iounmap;
	}

	dev_set_drvdata(&pdev->dev, hp);

	if (!qfe_slot) {
		struct pci_dev *qpdev = qp->quattro_dev;

		prom_name[0] = 0;
		if (!strncmp(dev->name, "eth", 3)) {
			int i = simple_strtoul(dev->name + 3, NULL, 10);
			sprintf(prom_name, "-%d", i + 3);
		}
		printk(KERN_INFO "%s%s: Quattro HME (PCI/CheerIO) 10/100baseT Ethernet ", dev->name, prom_name);
		if (qpdev->vendor == PCI_VENDOR_ID_DEC &&
		    qpdev->device == PCI_DEVICE_ID_DEC_21153)
			printk("DEC 21153 PCI Bridge\n");
		else
			printk("unknown bridge %04x.%04x\n",
				qpdev->vendor, qpdev->device);
	}

	if (qfe_slot != -1)
		printk(KERN_INFO "%s: Quattro HME slot %d (PCI/CheerIO) 10/100baseT Ethernet ",
		       dev->name, qfe_slot);
	else
		printk(KERN_INFO "%s: HAPPY MEAL (PCI/CheerIO) 10/100BaseT Ethernet ",
		       dev->name);

	printk("%s\n", print_mac(mac, dev->dev_addr));

	return 0;

err_out_iounmap:
	iounmap(hp->gregs);

err_out_free_res:
	pci_release_regions(pdev);

err_out_clear_quattro:
	if (qp != NULL)
		qp->happy_meals[qfe_slot] = NULL;

	free_netdev(dev);

err_out:
	return err;
}

static void __devexit happy_meal_pci_remove(struct pci_dev *pdev)
{
	struct happy_meal *hp = dev_get_drvdata(&pdev->dev);
	struct net_device *net_dev = hp->dev;

	unregister_netdev(net_dev);

	pci_free_consistent(hp->happy_dev,
			    PAGE_SIZE,
			    hp->happy_block,
			    hp->hblock_dvma);
	iounmap(hp->gregs);
	pci_release_regions(hp->happy_dev);

	free_netdev(net_dev);

	dev_set_drvdata(&pdev->dev, NULL);
}

static struct pci_device_id happymeal_pci_ids[] = {
	{ PCI_DEVICE(PCI_VENDOR_ID_SUN, PCI_DEVICE_ID_SUN_HAPPYMEAL) },
	{ }			/* Terminating entry */
};

MODULE_DEVICE_TABLE(pci, happymeal_pci_ids);

static struct pci_driver hme_pci_driver = {
	.name		= "hme",
	.id_table	= happymeal_pci_ids,
	.probe		= happy_meal_pci_probe,
	.remove		= __devexit_p(happy_meal_pci_remove),
};

static int __init happy_meal_pci_init(void)
{
	return pci_register_driver(&hme_pci_driver);
}

static void happy_meal_pci_exit(void)
{
	pci_unregister_driver(&hme_pci_driver);

	while (qfe_pci_list) {
		struct quattro *qfe = qfe_pci_list;
		struct quattro *next = qfe->next;

		kfree(qfe);

		qfe_pci_list = next;
	}
}

#endif

#ifdef CONFIG_SBUS
static int __devinit hme_sbus_probe(struct of_device *dev, const struct of_device_id *match)
{
	struct sbus_dev *sdev = to_sbus_device(&dev->dev);
	struct device_node *dp = dev->node;
	const char *model = of_get_property(dp, "model", NULL);
	int is_qfe = (match->data != NULL);

	if (!is_qfe && model && !strcmp(model, "SUNW,sbus-qfe"))
		is_qfe = 1;

	return happy_meal_sbus_probe_one(sdev, is_qfe);
}

static int __devexit hme_sbus_remove(struct of_device *dev)
{
	struct happy_meal *hp = dev_get_drvdata(&dev->dev);
	struct net_device *net_dev = hp->dev;

	unregister_netdev(net_dev);

	/* XXX qfe parent interrupt... */

	sbus_iounmap(hp->gregs, GREG_REG_SIZE);
	sbus_iounmap(hp->etxregs, ETX_REG_SIZE);
	sbus_iounmap(hp->erxregs, ERX_REG_SIZE);
	sbus_iounmap(hp->bigmacregs, BMAC_REG_SIZE);
	sbus_iounmap(hp->tcvregs, TCVR_REG_SIZE);
	sbus_free_consistent(hp->happy_dev,
			     PAGE_SIZE,
			     hp->happy_block,
			     hp->hblock_dvma);

	free_netdev(net_dev);

	dev_set_drvdata(&dev->dev, NULL);

	return 0;
}

static struct of_device_id hme_sbus_match[] = {
	{
		.name = "SUNW,hme",
	},
	{
		.name = "SUNW,qfe",
		.data = (void *) 1,
	},
	{
		.name = "qfe",
		.data = (void *) 1,
	},
	{},
};

MODULE_DEVICE_TABLE(of, hme_sbus_match);

static struct of_platform_driver hme_sbus_driver = {
	.name		= "hme",
	.match_table	= hme_sbus_match,
	.probe		= hme_sbus_probe,
	.remove		= __devexit_p(hme_sbus_remove),
};

static int __init happy_meal_sbus_init(void)
{
	int err;

	err = of_register_driver(&hme_sbus_driver, &sbus_bus_type);
	if (!err)
		quattro_sbus_register_irqs();

	return err;
}

static void happy_meal_sbus_exit(void)
{
	of_unregister_driver(&hme_sbus_driver);
	quattro_sbus_free_irqs();

	while (qfe_sbus_list) {
		struct quattro *qfe = qfe_sbus_list;
		struct quattro *next = qfe->next;

		kfree(qfe);

		qfe_sbus_list = next;
	}
}
#endif

static int __init happy_meal_probe(void)
{
	int err = 0;

#ifdef CONFIG_SBUS
	err = happy_meal_sbus_init();
#endif
#ifdef CONFIG_PCI
	if (!err) {
		err = happy_meal_pci_init();
#ifdef CONFIG_SBUS
		if (err)
			happy_meal_sbus_exit();
#endif
	}
#endif

	return err;
}


static void __exit happy_meal_exit(void)
{
#ifdef CONFIG_SBUS
	happy_meal_sbus_exit();
#endif
#ifdef CONFIG_PCI
	happy_meal_pci_exit();
#endif
}

module_init(happy_meal_probe);
module_exit(happy_meal_exit);