summaryrefslogtreecommitdiff
path: root/sys/arch/arm64/dev/apldc.c
blob: 7f4d8fb56f0b979976cf0d841801b332d6d6926e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
/*	$OpenBSD: apldc.c,v 1.8 2023/05/02 19:39:10 kettenis Exp $	*/
/*
 * Copyright (c) 2022 Mark Kettenis <kettenis@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/evcount.h>
#include <sys/malloc.h>
#include <sys/task.h>
#include <sys/timeout.h>

#include <machine/bus.h>
#include <machine/fdt.h>

#include <dev/ofw/openfirm.h>
#include <dev/ofw/ofw_gpio.h>
#include <dev/ofw/fdt.h>

#include <dev/wscons/wsconsio.h>
#include <dev/wscons/wskbdvar.h>
#include <dev/wscons/wsksymdef.h>
#include <dev/wscons/wsmousevar.h>

#include <dev/hid/hid.h>
#include <dev/hid/hidkbdsc.h>
#include <dev/hid/hidmsvar.h>

#include <arm64/dev/rtkit.h>
#include <arm64/dev/simplebusvar.h>

#include "apldc.h"

#define DC_IRQ_MASK		0x0000
#define DC_IRQ_STAT		0x0004

#define DC_CONFIG_TX_THRESH	0x0000
#define DC_CONFIG_RX_THRESH	0x0004

#define DC_DATA_TX8		0x0004
#define DC_DATA_TX32		0x0010
#define DC_DATA_TX_FREE		0x0014
#define DC_DATA_RX8		0x001c
#define  DC_DATA_RX8_COUNT(d)	((d) & 0x7f)
#define  DC_DATA_RX8_DATA(d)	(((d) >> 8) & 0xff)
#define DC_DATA_RX32		0x0028
#define DC_DATA_RX_COUNT	0x002c

#define APLDC_MAX_INTR		32

#define HREAD4(sc, reg)							\
	(bus_space_read_4((sc)->sc_iot, (sc)->sc_ioh, (reg)))
#define HWRITE4(sc, reg, val)						\
	bus_space_write_4((sc)->sc_iot, (sc)->sc_ioh, (reg), (val))
#define HSET4(sc, reg, bits)						\
	HWRITE4((sc), (reg), HREAD4((sc), (reg)) | (bits))
#define HCLR4(sc, reg, bits)						\
	HWRITE4((sc), (reg), HREAD4((sc), (reg)) & ~(bits))

struct apldchidev_attach_args {
	const char *aa_name;
	void	*aa_desc;
	size_t	aa_desclen;
};

struct intrhand {
	int (*ih_func)(void *);
	void *ih_arg;
	int ih_ipl;
	int ih_irq;
	int ih_level;
	struct evcount ih_count;
	char *ih_name;
	void *ih_sc;
};

struct apldc_softc {
	struct simplebus_softc	sc_sbus;
	bus_space_tag_t		sc_iot;
	bus_space_handle_t	sc_ioh;

	void			*sc_ih;
	struct intrhand		*sc_handlers[APLDC_MAX_INTR];
	struct interrupt_controller sc_ic;
};

int	apldc_match(struct device *, void *, void *);
void	apldc_attach(struct device *, struct device *, void *);

const struct cfattach apldc_ca = {
	sizeof (struct apldc_softc), apldc_match, apldc_attach
};

struct cfdriver apldc_cd = {
	NULL, "apldc", DV_DULL
};

int	apldc_intr(void *);
void	*apldc_intr_establish(void *, int *, int, struct cpu_info *,
	    int (*)(void *), void *, char *);
void	apldc_intr_enable(void *);
void	apldc_intr_disable(void *);
void	apldc_intr_barrier(void *);

int
apldc_match(struct device *parent, void *match, void *aux)
{
	struct fdt_attach_args *faa = aux;

	return OF_is_compatible(faa->fa_node, "apple,dockchannel");
}

void
apldc_attach(struct device *parent, struct device *self, void *aux)
{
	struct apldc_softc *sc = (struct apldc_softc *)self;
	struct fdt_attach_args *faa = aux;

	if (faa->fa_nreg < 1) {
		printf(": no registers\n");
		return;
	}

	sc->sc_iot = faa->fa_iot;
	if (bus_space_map(sc->sc_iot, faa->fa_reg[0].addr,
	    faa->fa_reg[0].size, 0, &sc->sc_ioh)) {
		printf(": can't map registers\n");
		return;
	}

	/* Disable and clear all interrupts. */
	HWRITE4(sc, DC_IRQ_MASK, 0);
	HWRITE4(sc, DC_IRQ_STAT, 0xffffffff);

	sc->sc_ih = fdt_intr_establish(faa->fa_node, IPL_TTY,
	    apldc_intr, sc, sc->sc_sbus.sc_dev.dv_xname);

	sc->sc_ic.ic_node = faa->fa_node;
	sc->sc_ic.ic_cookie = sc;
	sc->sc_ic.ic_establish = apldc_intr_establish;
	sc->sc_ic.ic_enable = apldc_intr_enable;
	sc->sc_ic.ic_disable = apldc_intr_disable;
	sc->sc_ic.ic_barrier = apldc_intr_barrier;
	fdt_intr_register(&sc->sc_ic);

	simplebus_attach(parent, &sc->sc_sbus.sc_dev, faa);
}

int
apldc_intr(void *arg)
{
	struct apldc_softc *sc = arg;
	struct intrhand *ih;
	uint32_t stat, pending;
	int irq, s;

	stat = HREAD4(sc, DC_IRQ_STAT);

	pending = stat;
	while (pending) {
		irq = ffs(pending) - 1;
		ih = sc->sc_handlers[irq];
		if (ih) {
			s = splraise(ih->ih_ipl);
			if (ih->ih_func(ih->ih_arg))
				ih->ih_count.ec_count++;
			splx(s);
		}

		pending &= ~(1 << irq);
	}

	HWRITE4(sc, DC_IRQ_STAT, stat);

	return 1;
}

void *
apldc_intr_establish(void *cookie, int *cells, int ipl,
    struct cpu_info *ci, int (*func)(void *), void *arg, char *name)
{
	struct apldc_softc *sc = cookie;
	struct intrhand *ih;
	int irq = cells[0];
	int level = cells[1];

	if (irq < 0 || irq >= APLDC_MAX_INTR)
		return NULL;

	if (ipl != IPL_TTY)
		return NULL;

	if (ci != NULL && !CPU_IS_PRIMARY(ci))
		return NULL;

	if (sc->sc_handlers[irq])
		return NULL;

	ih = malloc(sizeof(*ih), M_DEVBUF, M_WAITOK);
	ih->ih_func = func;
	ih->ih_arg = arg;
	ih->ih_ipl = ipl & IPL_IRQMASK;
	ih->ih_irq = irq;
	ih->ih_name = name;
	ih->ih_level = level;
	ih->ih_sc = sc;

	sc->sc_handlers[irq] = ih;

	if (name != NULL)
		evcount_attach(&ih->ih_count, name, &ih->ih_irq);

	return ih;
}

void
apldc_intr_enable(void *cookie)
{
	struct intrhand	*ih = cookie;
	struct apldc_softc *sc = ih->ih_sc;

	HSET4(sc, DC_IRQ_MASK, 1 << ih->ih_irq);
}

void
apldc_intr_disable(void *cookie)
{
	struct intrhand	*ih = cookie;
	struct apldc_softc *sc = ih->ih_sc;

	HCLR4(sc, DC_IRQ_MASK, 1 << ih->ih_irq);
}

void
apldc_intr_barrier(void *cookie)
{
	struct intrhand	*ih = cookie;
	struct apldc_softc *sc = ih->ih_sc;

	intr_barrier(sc->sc_ih);
}

#define APLDCHIDEV_DESC_MAX	512
#define APLDCHIDEV_PKT_MAX	1024
#define APLDCHIDEV_GPIO_MAX	4

#define APLDCHIDEV_NUM_GPIOS	16

struct apldchidev_gpio {
	struct apldchidev_softc	*ag_sc;
	uint8_t			ag_id;
	uint8_t			ag_iface;
	uint32_t		ag_gpio[APLDCHIDEV_GPIO_MAX];
	struct task		ag_task;
};

struct apldchidev_softc {
	struct device		sc_dev;
	bus_space_tag_t		sc_iot;
	bus_space_handle_t	sc_cfg_ioh;
	bus_space_handle_t	sc_data_ioh;

	bus_dma_tag_t		sc_dmat;
	int			sc_node;

	void			*sc_rx_ih;

	uint8_t			sc_seq_comm;

	uint8_t			sc_iface_stm;
	uint8_t			sc_seq_stm;
	uint8_t			sc_stmdesc[APLDCHIDEV_DESC_MAX];
	size_t			sc_stmdesclen;
	int			sc_stm_ready;

	uint8_t			sc_iface_kbd;
	uint8_t			sc_seq_kbd;
	struct device		*sc_kbd;
	uint8_t			sc_kbddesc[APLDCHIDEV_DESC_MAX];
	size_t			sc_kbddesclen;
	int			sc_kbd_ready;

	uint8_t			sc_iface_mt;
	uint8_t			sc_seq_mt;
	struct device		*sc_mt;
	uint8_t			sc_mtdesc[APLDCHIDEV_DESC_MAX];
	size_t			sc_mtdesclen;
	int			sc_mt_ready;

	struct apldchidev_gpio	sc_gpio[APLDCHIDEV_NUM_GPIOS];
	u_int			sc_ngpios;
	uint8_t			sc_gpio_cmd[APLDCHIDEV_PKT_MAX];
	size_t			sc_gpio_cmd_len;

	uint8_t			sc_cmd_iface;
	uint8_t			sc_cmd_seq;
	uint32_t		sc_retcode;
	int			sc_busy;
};

int	apldchidev_match(struct device *, void *, void *);
void	apldchidev_attach(struct device *, struct device *, void *);

const struct cfattach apldchidev_ca = {
	sizeof(struct apldchidev_softc), apldchidev_match, apldchidev_attach
};

struct cfdriver apldchidev_cd = {
	NULL, "apldchidev", DV_DULL
};

void	apldchidev_attachhook(struct device *);
void	apldchidev_cmd(struct apldchidev_softc *, uint8_t, uint8_t,
	    void *, size_t);
void	apldchidev_wait(struct apldchidev_softc *);
int	apldchidev_send_firmware(struct apldchidev_softc *, int,
	    void *, size_t);
void	apldchidev_enable(struct apldchidev_softc *, uint8_t);
void	apldchidev_reset(struct apldchidev_softc *, uint8_t, uint8_t);
int	apldchidev_rx_intr(void *);
void	apldchidev_gpio_task(void *);

int
apldchidev_match(struct device *parent, void *cfdata, void *aux)
{
	struct fdt_attach_args *faa = aux;

	return OF_is_compatible(faa->fa_node, "apple,dockchannel-hid");
}

void
apldchidev_attach(struct device *parent, struct device *self, void *aux)
{
	struct apldchidev_softc *sc = (struct apldchidev_softc *)self;
	struct fdt_attach_args *faa = aux;
	struct apldchidev_attach_args aa;
	uint32_t phandle;
	int error, idx, retry;

	if (faa->fa_nreg < 2) {
		printf(": no registers\n");
		return;
	}

	sc->sc_iot = faa->fa_iot;
	if (bus_space_map(sc->sc_iot, faa->fa_reg[0].addr,
	    faa->fa_reg[0].size, 0, &sc->sc_cfg_ioh)) {
		printf(": can't map registers\n");
		return;
	}
	if (bus_space_map(sc->sc_iot, faa->fa_reg[1].addr,
	    faa->fa_reg[1].size, 0, &sc->sc_data_ioh)) {
		printf(": can't map registers\n");
		return;
	}

	sc->sc_dmat = faa->fa_dmat;
	sc->sc_node = faa->fa_node;

	idx = OF_getindex(faa->fa_node, "rx", "interrupt-names");
	if (idx < 0) {
		printf(": no rx interrupt\n");
		return;
	}
	sc->sc_rx_ih = fdt_intr_establish_idx(faa->fa_node, idx, IPL_TTY,
	    apldchidev_rx_intr, sc, sc->sc_dev.dv_xname);
	if (sc->sc_rx_ih == NULL) {
		printf(": can't establish interrupt\n");
		return;
	}

	phandle = OF_getpropint(faa->fa_node, "apple,helper-cpu", 0);
	if (phandle) {
		error = aplrtk_start(phandle);
		if (error) {
			printf(": can't start helper CPU\n");
			return;
		}
	}

	printf("\n");

	/* Poll until we have received the STM HID descriptor. */
	for (retry = 10; retry > 0; retry--) {
		if (sc->sc_stmdesclen > 0)
			break;
		apldchidev_rx_intr(sc);
		delay(1000);
	}

	if (sc->sc_stmdesclen > 0) {
		/* Enable interface. */
		apldchidev_enable(sc, sc->sc_iface_stm);
	}

	/* Poll until we have received the keyboard HID descriptor. */
	for (retry = 10; retry > 0; retry--) {
		if (sc->sc_kbddesclen > 0)
			break;
		apldchidev_rx_intr(sc);
		delay(1000);
	}

	if (sc->sc_kbddesclen > 0) {
		/* Enable interface. */
		apldchidev_enable(sc, sc->sc_iface_kbd);

		aa.aa_name = "keyboard";
		aa.aa_desc = sc->sc_kbddesc;
		aa.aa_desclen = sc->sc_kbddesclen;
		sc->sc_kbd = config_found(self, &aa, NULL);
	}

	bus_space_write_4(sc->sc_iot, sc->sc_cfg_ioh, DC_CONFIG_RX_THRESH, 8);
	fdt_intr_enable(sc->sc_rx_ih);

#if NAPLDCMS > 0
	config_mountroot(self, apldchidev_attachhook);
#endif
}

int
apldchidev_read(struct apldchidev_softc *sc, void *buf, size_t len,
    uint32_t *checksum)
{
	uint8_t *dst = buf;
	uint32_t data;
	int shift = 0;

	while (len > 0) {
		data = bus_space_read_4(sc->sc_iot, sc->sc_data_ioh,
		    DC_DATA_RX8);
		if (DC_DATA_RX8_COUNT(data) > 0) {
			*dst++ = DC_DATA_RX8_DATA(data);
			*checksum += (DC_DATA_RX8_DATA(data) << shift);
			shift += 8;
			if (shift > 24)
				shift = 0;
			len--;
		} else {
			delay(10);
		}
	}

	return 0;
}

int
apldchidev_write(struct apldchidev_softc *sc, const void *buf, size_t len,
    uint32_t *checksum)
{
	const uint8_t *src = buf;
	uint32_t free;
	int shift = 0;

	while (len > 0) {
		free = bus_space_read_4(sc->sc_iot, sc->sc_data_ioh,
		    DC_DATA_TX_FREE);
		if (free > 0) {
			if (checksum)
				*checksum -= *src << shift;
			bus_space_write_4(sc->sc_iot, sc->sc_data_ioh,
			    DC_DATA_TX8, *src++);
			shift += 8;
			if (shift > 24)
				shift = 0;
			len--;
		} else {
			delay(10);
		}
	}

	return 0;
}

struct mtp_hdr {
	uint8_t hdr_len;
	uint8_t chan;
#define MTP_CHAN_CMD		0x11
#define MTP_CHAN_REPORT		0x12
	uint16_t pkt_len;
	uint8_t seq;
	uint8_t iface;
#define MTP_IFACE_COMM		0
	uint16_t pad;
} __packed;

struct mtp_subhdr {
	uint8_t flags;
#define MTP_GROUP_SHIFT	6
#define MTP_GROUP(x)		((x >> 6) & 0x3)
#define MTP_GROUP_INPUT	0
#define MTP_GROUP_OUTPUT	1
#define MTP_GROUP_CMD		2
#define MTP_REQ_SHIFT		0
#define MTP_REQ(x)		((x >> 0) & 0x3f)
#define MTP_REQ_SET_REPORT	0
#define MTP_REQ_GET_REPORT	1
	uint8_t unk;
	uint16_t len;
	uint32_t retcode;
} __packed;

struct mtp_init_hdr {
	uint8_t type;
#define MTP_EVENT_GPIO_CMD	0xa0
#define MTP_EVENT_INIT	0xf0
#define MTP_EVENT_READY	0xf1
	uint8_t unk1;
	uint8_t unk2;
	uint8_t iface;
	char name[16];
} __packed;

struct mtp_init_block_hdr {
	uint16_t type;
#define MTP_BLOCK_DESCRIPTOR	0
#define MTP_BLOCK_GPIO_REQ	1
#define MTP_BLOCK_END		2
	uint16_t subtype;
	uint16_t len;
} __packed;

struct mtp_gpio_req {
	uint16_t unk;
	uint16_t id;
	char name[32];
} __packed;

struct mtp_gpio_cmd {
	uint8_t type;
	uint8_t iface;
	uint8_t id;
	uint8_t unk;
	uint8_t cmd;
#define MTP_GPIO_CMD_TOGGLE	0x03
} __packed;

struct mtp_gpio_ack {
	uint8_t type;
	uint32_t retcode;
	uint8_t cmd[512];
} __packed;

#define MTP_CMD_RESET_INTERFACE	0x40
#define MTP_CMD_SEND_FIRMWARE		0x95
#define MTP_CMD_ENABLE_INTERFACE	0xb4
#define MTP_CMD_ACK_GPIO_CMD		0xa1

void
apldchidev_handle_gpio_req(struct apldchidev_softc *sc, uint8_t iface,
    void *buf, size_t len)
{
	struct mtp_gpio_req *req = buf;
	uint32_t gpio[APLDCHIDEV_GPIO_MAX];
	char name[64];
	int node = -1;

	if (len < sizeof(*req))
		return;

	if (sc->sc_ngpios >= APLDCHIDEV_NUM_GPIOS)
		return;

	if (iface == sc->sc_iface_mt)
		node = OF_getnodebyname(sc->sc_node, "multi-touch");
	else if (iface == sc->sc_iface_stm)
		node = OF_getnodebyname(sc->sc_node, "stm");
	if (node == -1)
		return;

	snprintf(name, sizeof(name), "apple,%s-gpios", req->name);
	len = OF_getproplen(node, name);
	if (len <= 0 || len > sizeof(gpio))
		return;
	OF_getpropintarray(node, name, gpio, len);
	gpio_controller_config_pin(gpio, GPIO_CONFIG_OUTPUT);
	gpio_controller_set_pin(gpio, 0);

	sc->sc_gpio[sc->sc_ngpios].ag_sc = sc;
	sc->sc_gpio[sc->sc_ngpios].ag_id = req->id;
	sc->sc_gpio[sc->sc_ngpios].ag_iface = iface;
	memcpy(sc->sc_gpio[sc->sc_ngpios].ag_gpio, gpio, len);
	task_set(&sc->sc_gpio[sc->sc_ngpios].ag_task,
	    apldchidev_gpio_task, &sc->sc_gpio[sc->sc_ngpios]);
	sc->sc_ngpios++;
}

void
apldchidev_handle_init(struct apldchidev_softc *sc, uint8_t iface,
    void *buf, size_t len)
{
	struct mtp_init_block_hdr *bhdr = buf;

	for (;;) {
		if (len < sizeof(*bhdr))
			return;
		len -= sizeof(*bhdr);

		if (len < bhdr->len)
			return;
		len -= bhdr->len;

		switch (bhdr->type) {
		case MTP_BLOCK_DESCRIPTOR:
			if (iface == sc->sc_iface_kbd &&
			    bhdr->len <= sizeof(sc->sc_kbddesc)) {
				memcpy(sc->sc_kbddesc, bhdr + 1, bhdr->len);
				sc->sc_kbddesclen = bhdr->len;
			} else if (iface == sc->sc_iface_mt &&
			    bhdr->len <= sizeof(sc->sc_mtdesc)) {
				memcpy(sc->sc_mtdesc, bhdr + 1, bhdr->len);
				sc->sc_mtdesclen = bhdr->len;
			} else if (iface == sc->sc_iface_stm &&
			    bhdr->len <= sizeof(sc->sc_stmdesc)) {
				memcpy(sc->sc_stmdesc, bhdr + 1, bhdr->len);
				sc->sc_stmdesclen = bhdr->len;
			}
			break;
		case MTP_BLOCK_GPIO_REQ:
			apldchidev_handle_gpio_req(sc, iface,
			    bhdr + 1, bhdr->len);
			break;
		case MTP_BLOCK_END:
			return;
		default:
			printf("%s: unhandled block type 0x%04x\n",
			    sc->sc_dev.dv_xname, bhdr->type);
			break;
		}

		bhdr = (struct mtp_init_block_hdr *)
		    ((uint8_t *)(bhdr + 1) + bhdr->len);
	}
}

void
apldchidev_handle_comm(struct apldchidev_softc *sc, void *buf, size_t len)
{
	struct mtp_init_hdr *ihdr = buf;
	struct mtp_gpio_cmd *cmd = buf;
	uint8_t iface;
	int i;

	switch (ihdr->type) {
	case MTP_EVENT_INIT:
		if (strcmp(ihdr->name, "keyboard") == 0) {
			sc->sc_iface_kbd = ihdr->iface;
			apldchidev_handle_init(sc, ihdr->iface,
			    ihdr + 1, len - sizeof(*ihdr));
		}
		if (strcmp(ihdr->name, "multi-touch") == 0) {
			sc->sc_iface_mt = ihdr->iface;
			apldchidev_handle_init(sc, ihdr->iface,
			    ihdr + 1, len - sizeof(*ihdr));
		}
		if (strcmp(ihdr->name, "stm") == 0) {
			sc->sc_iface_stm = ihdr->iface;
			apldchidev_handle_init(sc, ihdr->iface,
			    ihdr + 1, len - sizeof(*ihdr));
		}
		break;
	case MTP_EVENT_READY:
		iface = ihdr->unk1;
		if (iface == sc->sc_iface_stm)
			sc->sc_stm_ready = 1;
		if (iface == sc->sc_iface_kbd)
			sc->sc_kbd_ready = 1;
		if (iface == sc->sc_iface_mt)
			sc->sc_mt_ready = 1;
		break;
	case MTP_EVENT_GPIO_CMD:
		for (i =0; i < sc->sc_ngpios; i++) {
			if (cmd->id == sc->sc_gpio[i].ag_id &&
			    cmd->iface == sc->sc_gpio[i].ag_iface &&
			    cmd->cmd == MTP_GPIO_CMD_TOGGLE) {
				/* Stash the command for the reply. */
				KASSERT(len < sizeof(sc->sc_gpio_cmd));
				memcpy(sc->sc_gpio_cmd, buf, len);
				sc->sc_gpio_cmd_len = len;
				task_add(systq, &sc->sc_gpio[i].ag_task);
				return;
			}
		}
		printf("%s: unhandled gpio id %d iface %d cmd 0x%02x\n",
		       sc->sc_dev.dv_xname, cmd->id, cmd->iface, cmd->cmd);
		break;
	default:
		printf("%s: unhandled comm event 0x%02x\n",
		    sc->sc_dev.dv_xname, ihdr->type);
		break;
	}
}

void
apldchidev_gpio_task(void *arg)
{
	struct apldchidev_gpio *ag = arg;
	struct apldchidev_softc *sc = ag->ag_sc;
	struct mtp_gpio_ack *ack;
	uint8_t flags;
	size_t len;

	gpio_controller_set_pin(ag->ag_gpio, 1);
	delay(10000);
	gpio_controller_set_pin(ag->ag_gpio, 0);

	len = sizeof(*ack) + sc->sc_gpio_cmd_len;
	ack = malloc(len, M_TEMP, M_WAITOK);
	ack->type = MTP_CMD_ACK_GPIO_CMD;
	ack->retcode = 0;
	memcpy(ack->cmd, sc->sc_gpio_cmd, sc->sc_gpio_cmd_len);

	flags = MTP_GROUP_CMD << MTP_GROUP_SHIFT;
	flags |= MTP_REQ_SET_REPORT << MTP_REQ_SHIFT;
	apldchidev_cmd(sc, MTP_IFACE_COMM, flags, ack, len);

	free(ack, M_TEMP, len);
}

void apldckbd_intr(struct device *, uint8_t *, size_t);
void apldcms_intr(struct device *, uint8_t *, size_t);

int
apldchidev_rx_intr(void *arg)
{
	struct apldchidev_softc *sc = arg;
	struct mtp_hdr hdr;
	struct mtp_subhdr *shdr;
	uint32_t checksum = 0;
	char buf[APLDCHIDEV_PKT_MAX];

	apldchidev_read(sc, &hdr, sizeof(hdr), &checksum);
	apldchidev_read(sc, buf, hdr.pkt_len + 4, &checksum);
	if (checksum != 0xffffffff) {
		printf("%s: packet checksum error\n", sc->sc_dev.dv_xname);
		return 1;
	}
	if (hdr.pkt_len < sizeof(*shdr)) {
		printf("%s: packet too small\n", sc->sc_dev.dv_xname);
		return 1;
	}

	shdr = (struct mtp_subhdr *)buf;
	if (MTP_GROUP(shdr->flags) == MTP_GROUP_OUTPUT ||
	    MTP_GROUP(shdr->flags) == MTP_GROUP_CMD) {
		if (hdr.iface != sc->sc_cmd_iface) {
			printf("%s: got ack for unexpected iface\n",
			    sc->sc_dev.dv_xname);
		}
		if (hdr.seq != sc->sc_cmd_seq) {
			printf("%s: got ack with unexpected seq\n",
			    sc->sc_dev.dv_xname);
		}
		sc->sc_retcode = shdr->retcode;
		sc->sc_busy = 0;
		wakeup(sc);
		return 1;
	}
	if (MTP_GROUP(shdr->flags) != MTP_GROUP_INPUT) {
		printf("%s: unhandled group 0x%02x\n",
		    sc->sc_dev.dv_xname, shdr->flags);
		return 1;
	}

	if (hdr.iface == MTP_IFACE_COMM)
		apldchidev_handle_comm(sc, shdr + 1, shdr->len);
	else if (hdr.iface == sc->sc_iface_kbd && sc->sc_kbd)
		apldckbd_intr(sc->sc_kbd, (uint8_t *)(shdr + 1), shdr->len);
	else if (hdr.iface == sc->sc_iface_mt && sc->sc_mt)
		apldcms_intr(sc->sc_mt, (uint8_t *)(shdr + 1), shdr->len);
	else {
		printf("%s: unhandled iface %d\n",
		    sc->sc_dev.dv_xname, hdr.iface);
	}

	wakeup(sc);
	return 1;
}

void
apldchidev_cmd(struct apldchidev_softc *sc, uint8_t iface, uint8_t flags,
    void *data, size_t len)
{
	struct mtp_hdr hdr;
	struct mtp_subhdr shdr;
	uint32_t checksum = 0xffffffff;
	uint8_t pad[4];

	KASSERT(sc->sc_busy == 0);
	sc->sc_busy = 1;

	memset(&hdr, 0, sizeof(hdr));
	hdr.hdr_len = sizeof(hdr);
	hdr.chan = MTP_CHAN_CMD;
	hdr.pkt_len = roundup(len, 4) + sizeof(shdr);
	if (iface == MTP_IFACE_COMM)
		hdr.seq = sc->sc_seq_comm++;
	else if (iface == sc->sc_iface_kbd)
		hdr.seq = sc->sc_seq_kbd++;
	else if (iface == sc->sc_iface_mt)
		hdr.seq = sc->sc_seq_mt++;
	else if (iface == sc->sc_iface_stm)
		hdr.seq = sc->sc_seq_stm++;
	hdr.iface = iface;
	sc->sc_cmd_iface = hdr.iface;
	sc->sc_cmd_seq = hdr.seq;
	memset(&shdr, 0, sizeof(shdr));
	shdr.flags = flags;
	shdr.len = len;
	apldchidev_write(sc, &hdr, sizeof(hdr), &checksum);
	apldchidev_write(sc, &shdr, sizeof(shdr), &checksum);
	apldchidev_write(sc, data, len & ~3, &checksum);
	if (len & 3) {
		memset(pad, 0, sizeof(pad));
		memcpy(pad, &data[len & ~3], len & 3);
		apldchidev_write(sc, pad, sizeof(pad), &checksum);
	}
	apldchidev_write(sc, &checksum, sizeof(checksum), NULL);
}

void
apldchidev_wait(struct apldchidev_softc *sc)
{
	int retry, error;

	if (cold) {
		for (retry = 10; retry > 0; retry--) {
			if (sc->sc_busy == 0)
				break;
			apldchidev_rx_intr(sc);
			delay(1000);
		}
		return;
	}
	
	while (sc->sc_busy) {
		error = tsleep_nsec(sc, PZERO, "apldcwt", SEC_TO_NSEC(1));
		if (error == EWOULDBLOCK)
			return;
	}

	if (sc->sc_retcode) {
		printf("%s: command failed with error 0x%04x\n",
		    sc->sc_dev.dv_xname, sc->sc_retcode);
	}
}

void
apldchidev_enable(struct apldchidev_softc *sc, uint8_t iface)
{
	uint8_t cmd[2] = { MTP_CMD_ENABLE_INTERFACE, iface };
	uint8_t flags;

	flags = MTP_GROUP_CMD << MTP_GROUP_SHIFT;
	flags |= MTP_REQ_SET_REPORT << MTP_REQ_SHIFT;
	apldchidev_cmd(sc, MTP_IFACE_COMM, flags, cmd, sizeof(cmd));
	apldchidev_wait(sc);
}

void
apldchidev_reset(struct apldchidev_softc *sc, uint8_t iface, uint8_t state)
{
	uint8_t cmd[4] = { MTP_CMD_RESET_INTERFACE, 1, iface, state };
	uint8_t flags;

	flags = MTP_GROUP_CMD << MTP_GROUP_SHIFT;
	flags |= MTP_REQ_SET_REPORT << MTP_REQ_SHIFT;
	apldchidev_cmd(sc, MTP_IFACE_COMM, flags, cmd, sizeof(cmd));
	apldchidev_wait(sc);
}

#if NAPLDCMS > 0

int
apldchidev_send_firmware(struct apldchidev_softc *sc, int iface,
    void *ucode, size_t ucode_size)
{
	bus_dmamap_t map;
	bus_dma_segment_t seg;
	uint8_t cmd[16] = {};
	uint64_t addr;
	uint32_t size;
	uint8_t flags;
	caddr_t buf;
	int nsegs;
	int error;

	error = bus_dmamap_create(sc->sc_dmat, ucode_size, 1, ucode_size, 0,
	    BUS_DMA_WAITOK, &map);
	if (error)
		return error;

	error = bus_dmamem_alloc(sc->sc_dmat, ucode_size, 4 * PAGE_SIZE, 0,
	    &seg, 1, &nsegs, BUS_DMA_WAITOK);
	if (error) {
		bus_dmamap_destroy(sc->sc_dmat, map);
		return error;
	}

	error = bus_dmamem_map(sc->sc_dmat, &seg, 1, ucode_size, &buf,
	    BUS_DMA_WAITOK);
	if (error) {
		bus_dmamem_free(sc->sc_dmat, &seg, 1);
		bus_dmamap_destroy(sc->sc_dmat, map);
		return error;
	}

	error = bus_dmamap_load_raw(sc->sc_dmat, map, &seg, 1,
	    ucode_size, BUS_DMA_WAITOK);
	if (error) {
		bus_dmamem_unmap(sc->sc_dmat, buf, ucode_size);
		bus_dmamem_free(sc->sc_dmat, &seg, 1);
		bus_dmamap_destroy(sc->sc_dmat, map);
		return error;
	}

	memcpy(buf, ucode, ucode_size);
	bus_dmamap_sync(sc->sc_dmat, map, 0, ucode_size, BUS_DMASYNC_PREWRITE);

	cmd[0] = MTP_CMD_SEND_FIRMWARE;
	cmd[1] = 2;
	cmd[2] = 0;
	cmd[3] = iface;
	addr = map->dm_segs[0].ds_addr;
	memcpy(&cmd[4], &addr, sizeof(addr));
	size = map->dm_segs[0].ds_len;
	memcpy(&cmd[12], &size, sizeof(size));

	flags = MTP_GROUP_CMD << MTP_GROUP_SHIFT;
	flags |= MTP_REQ_SET_REPORT << MTP_REQ_SHIFT;
	apldchidev_cmd(sc, MTP_IFACE_COMM, flags, cmd, sizeof(cmd));
	apldchidev_wait(sc);

	bus_dmamap_unload(sc->sc_dmat, map);
	bus_dmamem_unmap(sc->sc_dmat, buf, ucode_size);
	bus_dmamem_free(sc->sc_dmat, &seg, 1);
	bus_dmamap_destroy(sc->sc_dmat, map);

	return 0;
}

struct mtp_fwhdr {
	uint32_t magic;
#define MTP_FW_MAGIC	0x46444948
	uint32_t version;
#define MTP_FW_VERSION	1
	uint32_t hdr_len;
	uint32_t data_len;
	uint32_t iface_off;
};

int
apldchidev_load_firmware(struct apldchidev_softc *sc, const char *name)
{
	struct mtp_fwhdr *hdr;
	uint8_t *ucode;
	size_t ucode_size;
	uint8_t *data;
	size_t size;
	int error;

	error = loadfirmware(name, &ucode, &ucode_size);
	if (error) {
		printf("%s: error %d, could not read firmware %s\n",
		    sc->sc_dev.dv_xname, error, name);
		return error;
	}

	hdr = (struct mtp_fwhdr *)ucode;
	if (sizeof(hdr) > ucode_size ||
	    hdr->hdr_len + hdr->data_len > ucode_size) {
		printf("%s: loaded firmware is too small\n",
		    sc->sc_dev.dv_xname);
		return EINVAL;
	}
	if (hdr->magic != MTP_FW_MAGIC) {
		printf("%s: wrong firmware magic number 0x%08x\n",
		    sc->sc_dev.dv_xname, hdr->magic);
		return EINVAL;
	}
	if (hdr->version != MTP_FW_VERSION) {
		printf("%s: wrong firmware version %d\n",
		    sc->sc_dev.dv_xname, hdr->version);
		return EINVAL;
	}
	data = ucode + hdr->hdr_len;
	if (hdr->iface_off)
		data[hdr->iface_off] = sc->sc_iface_mt;
	size = hdr->data_len;

	apldchidev_send_firmware(sc, sc->sc_iface_mt, data, size);
	apldchidev_reset(sc, sc->sc_iface_mt, 0);
	apldchidev_reset(sc, sc->sc_iface_mt, 2);

	/* Wait until ready. */
	while (sc->sc_mt_ready == 0) {
		error = tsleep_nsec(sc, PZERO, "apldcmt", SEC_TO_NSEC(2));
		if (error == EWOULDBLOCK)
			return error;
	}

	return 0;
}

void
apldchidev_attachhook(struct device *self)
{
	struct apldchidev_softc *sc = (struct apldchidev_softc *)self;
	struct apldchidev_attach_args aa;
	char *firmware_name;
	int node, len;
	int retry;
	int error;

	/* Enable interface. */
	apldchidev_enable(sc, sc->sc_iface_mt);

	node = OF_getnodebyname(sc->sc_node, "multi-touch");
	if (node == -1)
		return;
	len = OF_getproplen(node, "firmware-name");
	if (len <= 0)
		return;

	/* Wait until we have received the multi-touch HID descriptor. */
	while (sc->sc_mtdesclen == 0) {
		error = tsleep_nsec(sc, PZERO, "apldcmt", SEC_TO_NSEC(1));
		if (error == EWOULDBLOCK)
			return;
	}

	firmware_name = malloc(len, M_TEMP, M_WAITOK);
	OF_getprop(node, "firmware-name", firmware_name, len);

	for (retry = 5; retry > 0; retry--) {
		error = apldchidev_load_firmware(sc, firmware_name);
		if (error != EWOULDBLOCK)
			break;
	}
	if (error)
		goto out;

	aa.aa_name = "multi-touch";
	aa.aa_desc = sc->sc_mtdesc;
	aa.aa_desclen = sc->sc_mtdesclen;
	sc->sc_mt = config_found(self, &aa, NULL);

out:
	free(firmware_name, M_TEMP, len);
}

#endif

void
apldchidev_set_leds(struct apldchidev_softc *sc, uint8_t leds)
{
	uint8_t report[2] = { 1, leds };
	uint8_t flags;

	flags = MTP_GROUP_OUTPUT << MTP_GROUP_SHIFT;
	flags |= MTP_REQ_SET_REPORT << MTP_REQ_SHIFT;
	apldchidev_cmd(sc, sc->sc_iface_kbd, flags, report, sizeof(report));
}

/* Keyboard */

struct apldckbd_softc {
	struct device		sc_dev;
	struct apldchidev_softc	*sc_hidev;
	struct hidkbd		sc_kbd;
	int			sc_spl;
};

void	apldckbd_cngetc(void *, u_int *, int *);
void	apldckbd_cnpollc(void *, int);
void	apldckbd_cnbell(void *, u_int, u_int, u_int);

const struct wskbd_consops apldckbd_consops = {
	apldckbd_cngetc,
	apldckbd_cnpollc,
	apldckbd_cnbell,
};

int	apldckbd_enable(void *, int);
void	apldckbd_set_leds(void *, int);
int	apldckbd_ioctl(void *, u_long, caddr_t, int, struct proc *);

const struct wskbd_accessops apldckbd_accessops = {
	.enable = apldckbd_enable,
	.ioctl = apldckbd_ioctl,
	.set_leds = apldckbd_set_leds,
};

int	 apldckbd_match(struct device *, void *, void *);
void	 apldckbd_attach(struct device *, struct device *, void *);

const struct cfattach apldckbd_ca = {
	sizeof(struct apldckbd_softc), apldckbd_match, apldckbd_attach
};

struct cfdriver apldckbd_cd = {
	NULL, "apldckbd", DV_DULL
};

int
apldckbd_match(struct device *parent, void *match, void *aux)
{
	struct apldchidev_attach_args *aa = aux;

	return strcmp(aa->aa_name, "keyboard") == 0;
}

void
apldckbd_attach(struct device *parent, struct device *self, void *aux)
{
	struct apldckbd_softc *sc = (struct apldckbd_softc *)self;
	struct apldchidev_attach_args *aa = aux;
	struct hidkbd *kbd = &sc->sc_kbd;

#define APLHIDEV_KBD_DEVICE	1
	sc->sc_hidev = (struct apldchidev_softc *)parent;
	if (hidkbd_attach(self, kbd, 1, 0, APLHIDEV_KBD_DEVICE,
	    aa->aa_desc, aa->aa_desclen))
		return;

	printf("\n");

	if (hid_locate(aa->aa_desc, aa->aa_desclen, HID_USAGE2(HUP_APPLE, HUG_FN_KEY),
	    1, hid_input, &kbd->sc_fn, NULL))
		kbd->sc_munge = hidkbd_apple_munge;

	if (kbd->sc_console_keyboard) {
		extern struct wskbd_mapdata ukbd_keymapdata;

		ukbd_keymapdata.layout = KB_US | KB_DEFAULT;
		wskbd_cnattach(&apldckbd_consops, sc, &ukbd_keymapdata);
		apldckbd_enable(sc, 1);
	}

	hidkbd_attach_wskbd(kbd, KB_US | KB_DEFAULT, &apldckbd_accessops);
}

void
apldckbd_intr(struct device *self, uint8_t *packet, size_t packetlen)
{
	struct apldckbd_softc *sc = (struct apldckbd_softc *)self;
	struct hidkbd *kbd = &sc->sc_kbd;

	if (kbd->sc_enabled)
		hidkbd_input(kbd, &packet[1], packetlen - 1);
}

int
apldckbd_enable(void *v, int on)
{
	struct apldckbd_softc *sc = v;
	struct hidkbd *kbd = &sc->sc_kbd;

	return hidkbd_enable(kbd, on);
}

int
apldckbd_ioctl(void *v, u_long cmd, caddr_t data, int flag, struct proc *p)
{
	struct apldckbd_softc *sc = v;
	struct hidkbd *kbd = &sc->sc_kbd;

	switch (cmd) {
	case WSKBDIO_GTYPE:
		/* XXX: should we set something else? */
		*(u_int *)data = WSKBD_TYPE_USB;
		return 0;
	case WSKBDIO_SETLEDS:
		apldckbd_set_leds(v, *(int *)data);
		return 0;
	default:
		return hidkbd_ioctl(kbd, cmd, data, flag, p);
	}
}

void
apldckbd_set_leds(void *v, int leds)
{
	struct apldckbd_softc *sc = v;
	struct hidkbd *kbd = &sc->sc_kbd;
	uint8_t res;

	if (hidkbd_set_leds(kbd, leds, &res))
		apldchidev_set_leds(sc->sc_hidev, res);
}

/* Console interface. */
void
apldckbd_cngetc(void *v, u_int *type, int *data)
{
	struct apldckbd_softc *sc = v;
	struct hidkbd *kbd = &sc->sc_kbd;

	kbd->sc_polling = 1;
	while (kbd->sc_npollchar <= 0) {
		apldchidev_rx_intr(sc->sc_dev.dv_parent);
		delay(1000);
	}
	kbd->sc_polling = 0;
	hidkbd_cngetc(kbd, type, data);
}

void
apldckbd_cnpollc(void *v, int on)
{
	struct apldckbd_softc *sc = v;

	if (on)
		sc->sc_spl = spltty();
	else
		splx(sc->sc_spl);
}

void
apldckbd_cnbell(void *v, u_int pitch, u_int period, u_int volume)
{
	hidkbd_bell(pitch, period, volume, 1);
}

#if NAPLDCMS > 0

/* Touchpad */

/*
 * The contents of the touchpad event packets is identical to those
 * used by the ubcmtp(4) driver.  The relevant definitions and the
 * code to decode the packets is replicated here.
 */

struct ubcmtp_finger {
	uint16_t	origin;
	uint16_t	abs_x;
	uint16_t	abs_y;
	uint16_t	rel_x;
	uint16_t	rel_y;
	uint16_t	tool_major;
	uint16_t	tool_minor;
	uint16_t	orientation;
	uint16_t	touch_major;
	uint16_t	touch_minor;
	uint16_t	unused[2];
	uint16_t	pressure;
	uint16_t	multi;
} __packed __attribute((aligned(2)));

#define UBCMTP_MAX_FINGERS	16

#define UBCMTP_TYPE4_TPOFF	(20 * sizeof(uint16_t))
#define UBCMTP_TYPE4_BTOFF	23
#define UBCMTP_TYPE4_FINGERPAD	(1 * sizeof(uint16_t))

/* Use a constant, synaptics-compatible pressure value for now. */
#define DEFAULT_PRESSURE	40

struct apldcms_softc {
	struct device	sc_dev;
	struct device	*sc_wsmousedev;

	int		sc_enabled;

	int		tp_offset;
	int		tp_fingerpad;

	struct mtpoint	frame[UBCMTP_MAX_FINGERS];
	int		contacts;
	int		btn;
};

int	apldcms_enable(void *);
void	apldcms_disable(void *);
int	apldcms_ioctl(void *, u_long, caddr_t, int, struct proc *);

const struct wsmouse_accessops apldcms_accessops = {
	.enable = apldcms_enable,
	.disable = apldcms_disable,
	.ioctl = apldcms_ioctl,
};

int	 apldcms_match(struct device *, void *, void *);
void	 apldcms_attach(struct device *, struct device *, void *);

const struct cfattach apldcms_ca = {
	sizeof(struct apldcms_softc), apldcms_match, apldcms_attach
};

struct cfdriver apldcms_cd = {
	NULL, "apldcms", DV_DULL
};

int	apldcms_configure(struct apldcms_softc *);

int
apldcms_match(struct device *parent, void *match, void *aux)
{
	struct apldchidev_attach_args *aa = aux;

	return strcmp(aa->aa_name, "multi-touch") == 0;
}

void
apldcms_attach(struct device *parent, struct device *self, void *aux)
{
	struct apldcms_softc *sc = (struct apldcms_softc *)self;
	struct wsmousedev_attach_args aa;

	printf("\n");

	sc->tp_offset = UBCMTP_TYPE4_TPOFF;
	sc->tp_fingerpad = UBCMTP_TYPE4_FINGERPAD;

	aa.accessops = &apldcms_accessops;
	aa.accesscookie = sc;

	sc->sc_wsmousedev = config_found(self, &aa, wsmousedevprint);
	if (sc->sc_wsmousedev != NULL && apldcms_configure(sc))
		apldcms_disable(sc);
}

int
apldcms_configure(struct apldcms_softc *sc)
{
	struct wsmousehw *hw = wsmouse_get_hw(sc->sc_wsmousedev);

	/* The values below are for the MacBookPro17,1 */
	hw->type = WSMOUSE_TYPE_TOUCHPAD;
	hw->hw_type = WSMOUSEHW_CLICKPAD;
	hw->x_min = -6046;
	hw->x_max = 6536;
	hw->y_min = -164;
	hw->y_max = 7439;
	hw->mt_slots = UBCMTP_MAX_FINGERS;
	hw->flags = WSMOUSEHW_MT_TRACKING;

	return wsmouse_configure(sc->sc_wsmousedev, NULL, 0);
}

void
apldcms_intr(struct device *self, uint8_t *packet, size_t packetlen)
{
	struct apldcms_softc *sc = (struct apldcms_softc *)self;
	struct ubcmtp_finger *finger;
	int off, s, btn, contacts;

	if (!sc->sc_enabled)
		return;

	contacts = 0;
	for (off = sc->tp_offset; off < packetlen;
	    off += (sizeof(struct ubcmtp_finger) + sc->tp_fingerpad)) {
		finger = (struct ubcmtp_finger *)(packet + off);

		if ((int16_t)letoh16(finger->touch_major) == 0)
			continue; /* finger lifted */

		sc->frame[contacts].x = (int16_t)letoh16(finger->abs_x);
		sc->frame[contacts].y = (int16_t)letoh16(finger->abs_y);
		sc->frame[contacts].pressure = DEFAULT_PRESSURE;
		contacts++;
	}

	btn = sc->btn;
	sc->btn = !!((int16_t)letoh16(packet[UBCMTP_TYPE4_BTOFF]));

	if (contacts || sc->contacts || sc->btn != btn) {
		sc->contacts = contacts;
		s = spltty();
		wsmouse_buttons(sc->sc_wsmousedev, sc->btn);
		wsmouse_mtframe(sc->sc_wsmousedev, sc->frame, contacts);
		wsmouse_input_sync(sc->sc_wsmousedev);
		splx(s);
	}
}

int
apldcms_enable(void *v)
{
	struct apldcms_softc *sc = v;

	if (sc->sc_enabled)
		return EBUSY;

	sc->sc_enabled = 1;
	return 0;
}

void
apldcms_disable(void *v)
{
	struct apldcms_softc *sc = v;

	sc->sc_enabled = 0;
}

int
apldcms_ioctl(void *v, u_long cmd, caddr_t data, int flag, struct proc *p)
{
	struct apldcms_softc *sc = v;
	struct wsmousehw *hw = wsmouse_get_hw(sc->sc_wsmousedev);
	struct wsmouse_calibcoords *wsmc = (struct wsmouse_calibcoords *)data;
	int wsmode;

	switch (cmd) {
	case WSMOUSEIO_GTYPE:
		*(u_int *)data = hw->type;
		break;

	case WSMOUSEIO_GCALIBCOORDS:
		wsmc->minx = hw->x_min;
		wsmc->maxx = hw->x_max;
		wsmc->miny = hw->y_min;
		wsmc->maxy = hw->y_max;
		wsmc->swapxy = 0;
		wsmc->resx = 0;
		wsmc->resy = 0;
		break;

	case WSMOUSEIO_SETMODE:
		wsmode = *(u_int *)data;
		if (wsmode != WSMOUSE_COMPAT && wsmode != WSMOUSE_NATIVE) {
			printf("%s: invalid mode %d\n", sc->sc_dev.dv_xname,
			    wsmode);
			return (EINVAL);
		}
		wsmouse_set_mode(sc->sc_wsmousedev, wsmode);
		break;

	default:
		return -1;
	}

	return 0;
}

#else

void
apldcms_intr(struct device *self, uint8_t *packet, size_t packetlen)
{
}

#endif