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

#include <machine/apmvar.h>
#include <machine/bus.h>
#include <machine/fdt.h>
#include <uvm/uvm_extern.h>

#include <dev/ofw/openfirm.h>
#include <dev/ofw/ofw_clock.h>
#include <dev/ofw/ofw_misc.h>
#include <dev/ofw/ofw_power.h>
#include <dev/ofw/fdt.h>

#include "apm.h"

extern int qcscm_pas_init_image(uint32_t, paddr_t);
extern int qcscm_pas_mem_setup(uint32_t, paddr_t, size_t);
extern int qcscm_pas_auth_and_reset(uint32_t);
extern int qcscm_pas_shutdown(uint32_t);

#define MDT_TYPE_MASK				(7 << 24)
#define MDT_TYPE_HASH				(2 << 24)
#define MDT_RELOCATABLE				(1 << 27)

#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))

struct qcpas_dmamem {
	bus_dmamap_t		tdm_map;
	bus_dma_segment_t	tdm_seg;
	size_t			tdm_size;
	caddr_t			tdm_kva;
};
#define QCPAS_DMA_MAP(_tdm)	((_tdm)->tdm_map)
#define QCPAS_DMA_LEN(_tdm)	((_tdm)->tdm_size)
#define QCPAS_DMA_DVA(_tdm)	((_tdm)->tdm_map->dm_segs[0].ds_addr)
#define QCPAS_DMA_KVA(_tdm)	((void *)(_tdm)->tdm_kva)

struct qcpas_softc {
	struct device		sc_dev;
	bus_space_tag_t		sc_iot;
	bus_space_handle_t	sc_ioh;
	bus_dma_tag_t		sc_dmat;
	int			sc_node;

	void			*sc_ih[6];

	paddr_t			sc_mem_phys[2];
	size_t			sc_mem_size[2];
	void			*sc_mem_region[2];
	vaddr_t			sc_mem_reloc[2];

	uint32_t		sc_pas_id;
	uint32_t		sc_dtb_pas_id;
	uint32_t		sc_lite_pas_id;
	char			*sc_load_state;

	struct qcpas_dmamem	*sc_metadata[2];

	/* GLINK */
	volatile uint32_t	*sc_tx_tail;
	volatile uint32_t	*sc_tx_head;
	volatile uint32_t	*sc_rx_tail;
	volatile uint32_t	*sc_rx_head;

	uint32_t		sc_tx_off;
	uint32_t		sc_rx_off;

	uint8_t			*sc_tx_fifo;
	int			sc_tx_fifolen;
	uint8_t			*sc_rx_fifo;
	int			sc_rx_fifolen;
	void			*sc_glink_ih;

	struct mbox_channel	*sc_mc;

	struct task		sc_glink_rx;
	uint32_t		sc_glink_max_channel;
	TAILQ_HEAD(,qcpas_glink_channel) sc_glink_channels;

#ifndef SMALL_KERNEL
	uint32_t		sc_last_full_capacity;
	uint32_t		sc_warning_capacity;
	uint32_t		sc_low_capacity;
	struct ksensor		sc_sens[11];
	struct ksensordev	sc_sensdev;
#endif
};

int	qcpas_match(struct device *, void *, void *);
void	qcpas_attach(struct device *, struct device *, void *);

const struct cfattach qcpas_ca = {
	sizeof (struct qcpas_softc), qcpas_match, qcpas_attach
};

struct cfdriver qcpas_cd = {
	NULL, "qcpas", DV_DULL
};

void	qcpas_mountroot(struct device *);
int	qcpas_map_memory(struct qcpas_softc *);
int	qcpas_mdt_init(struct qcpas_softc *, int, u_char *, size_t);
void	qcpas_glink_attach(struct qcpas_softc *, int);

struct qcpas_dmamem *
	qcpas_dmamem_alloc(struct qcpas_softc *, bus_size_t, bus_size_t);
void	qcpas_dmamem_free(struct qcpas_softc *, struct qcpas_dmamem *);

void	qcpas_intr_establish(struct qcpas_softc *, int, char *, void *);
int	qcpas_intr_wdog(void *);
int	qcpas_intr_fatal(void *);
int	qcpas_intr_ready(void *);
int	qcpas_intr_handover(void *);
int	qcpas_intr_stop_ack(void *);
int	qcpas_intr_shutdown_ack(void *);

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

	return OF_is_compatible(faa->fa_node, "qcom,sc8280xp-adsp-pas") ||
	    OF_is_compatible(faa->fa_node, "qcom,x1e80100-adsp-pas");
}

void
qcpas_attach(struct device *parent, struct device *self, void *aux)
{
	struct qcpas_softc *sc = (struct qcpas_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;
	}
	sc->sc_dmat = faa->fa_dmat;
	sc->sc_node = faa->fa_node;

	if (OF_is_compatible(faa->fa_node, "qcom,sc8280xp-adsp-pas")) {
		sc->sc_pas_id = 1;
		sc->sc_load_state = "adsp";
	}
	if (OF_is_compatible(faa->fa_node, "qcom,sc8280xp-nsp0-pas")) {
		sc->sc_pas_id = 18;
	}
	if (OF_is_compatible(faa->fa_node, "qcom,sc8280xp-nsp1-pas")) {
		sc->sc_pas_id = 30;
	}

	if (OF_is_compatible(faa->fa_node, "qcom,x1e80100-adsp-pas")) {
		sc->sc_pas_id = 1;
		sc->sc_dtb_pas_id = 36;
		sc->sc_lite_pas_id = 31;
		sc->sc_load_state = "adsp";
	}

	qcpas_intr_establish(sc, 0, "wdog", qcpas_intr_wdog);
	qcpas_intr_establish(sc, 1, "fatal", qcpas_intr_fatal);
	qcpas_intr_establish(sc, 2, "ready", qcpas_intr_ready);
	qcpas_intr_establish(sc, 3, "handover", qcpas_intr_handover);
	qcpas_intr_establish(sc, 4, "stop-ack", qcpas_intr_stop_ack);
	qcpas_intr_establish(sc, 5, "shutdown-ack", qcpas_intr_shutdown_ack);

	printf("\n");

	config_mountroot(self, qcpas_mountroot);
}

extern int qcaoss_send(char *, size_t);

void
qcpas_mountroot(struct device *self)
{
	struct qcpas_softc *sc = (struct qcpas_softc *)self;
	char fwname[128];
	size_t fwlen, dtb_fwlen;
	u_char *fw, *dtb_fw;
	int node, ret;
	int error;

	if (qcpas_map_memory(sc) != 0)
		return;

	if (OF_getproplen(sc->sc_node, "firmware-name") <= 0)
		return;
	OF_getprop(sc->sc_node, "firmware-name", fwname, sizeof(fwname));
	fwname[sizeof(fwname) - 1] = '\0';

	/* If we need a second firmware, make sure we have a name for it. */
	if (sc->sc_dtb_pas_id && strlen(fwname) == sizeof(fwname) - 1)
		return;

	error = loadfirmware(fwname, &fw, &fwlen);
	if (error) {
		printf("%s: failed to load %s: %d\n",
		    sc->sc_dev.dv_xname, fwname, error);
		return;
	}

	if (sc->sc_lite_pas_id) {
		if (qcscm_pas_shutdown(sc->sc_lite_pas_id)) {
			printf("%s: failed to shutdown lite firmware\n",
			    sc->sc_dev.dv_xname);
		}
	}

	if (sc->sc_dtb_pas_id) {
		error = loadfirmware(fwname + strlen(fwname) + 1,
		    &dtb_fw, &dtb_fwlen);
		if (error) {
			printf("%s: failed to load %s: %d\n",
			    sc->sc_dev.dv_xname, fwname, error);
			return;
		}
	}

	if (sc->sc_load_state) {
		char buf[64];
		snprintf(buf, sizeof(buf),
		    "{class: image, res: load_state, name: %s, val: on}",
		    sc->sc_load_state);
		ret = qcaoss_send(buf, sizeof(buf));
		if (ret != 0) {
			printf("%s: failed to toggle load state\n",
			    sc->sc_dev.dv_xname);
			return;
		}
	}

	power_domain_enable_all(sc->sc_node);
	clock_enable(sc->sc_node, "xo");

	if (sc->sc_dtb_pas_id) {
		qcpas_mdt_init(sc, sc->sc_dtb_pas_id, dtb_fw, dtb_fwlen);
		free(dtb_fw, M_DEVBUF, dtb_fwlen);
	}

	ret = qcpas_mdt_init(sc, sc->sc_pas_id, fw, fwlen);
	free(fw, M_DEVBUF, fwlen);
	if (ret != 0) {
		printf("%s: failed to boot coprocessor\n",
		    sc->sc_dev.dv_xname);
		return;
	}

	node = OF_getnodebyname(sc->sc_node, "glink-edge");
	if (node)
		qcpas_glink_attach(sc, node);

#ifndef SMALL_KERNEL
	strlcpy(sc->sc_sensdev.xname, sc->sc_dev.dv_xname,
	    sizeof(sc->sc_sensdev.xname));

	strlcpy(sc->sc_sens[0].desc, "last full capacity",
	    sizeof(sc->sc_sens[0].desc));
	sc->sc_sens[0].type = SENSOR_WATTHOUR;
	sc->sc_sens[0].flags = SENSOR_FUNKNOWN;
	sensor_attach(&sc->sc_sensdev, &sc->sc_sens[0]);

	strlcpy(sc->sc_sens[1].desc, "warning capacity",
	    sizeof(sc->sc_sens[1].desc));
	sc->sc_sens[1].type = SENSOR_WATTHOUR;
	sc->sc_sens[1].flags = SENSOR_FUNKNOWN;
	sensor_attach(&sc->sc_sensdev, &sc->sc_sens[1]);
	
	strlcpy(sc->sc_sens[2].desc, "low capacity",
	    sizeof(sc->sc_sens[2].desc));
	sc->sc_sens[2].type = SENSOR_WATTHOUR;
	sc->sc_sens[2].flags = SENSOR_FUNKNOWN;
	sensor_attach(&sc->sc_sensdev, &sc->sc_sens[2]);

	strlcpy(sc->sc_sens[3].desc, "voltage", sizeof(sc->sc_sens[3].desc));
	sc->sc_sens[3].type = SENSOR_VOLTS_DC;
	sc->sc_sens[3].flags = SENSOR_FUNKNOWN;
	sensor_attach(&sc->sc_sensdev, &sc->sc_sens[3]);

	strlcpy(sc->sc_sens[4].desc, "battery unknown",
	    sizeof(sc->sc_sens[4].desc));
	sc->sc_sens[4].type = SENSOR_INTEGER;
	sc->sc_sens[4].flags = SENSOR_FUNKNOWN;
	sensor_attach(&sc->sc_sensdev, &sc->sc_sens[4]);

	strlcpy(sc->sc_sens[5].desc, "rate", sizeof(sc->sc_sens[5].desc));
	sc->sc_sens[5].type =SENSOR_WATTS;
	sc->sc_sens[5].flags = SENSOR_FUNKNOWN;
	sensor_attach(&sc->sc_sensdev, &sc->sc_sens[5]);

	strlcpy(sc->sc_sens[6].desc, "remaining capacity",
	    sizeof(sc->sc_sens[6].desc));
	sc->sc_sens[6].type = SENSOR_WATTHOUR;
	sc->sc_sens[6].flags = SENSOR_FUNKNOWN;
	sensor_attach(&sc->sc_sensdev, &sc->sc_sens[6]);

	strlcpy(sc->sc_sens[7].desc, "current voltage",
	    sizeof(sc->sc_sens[7].desc));
	sc->sc_sens[7].type = SENSOR_VOLTS_DC;
	sc->sc_sens[7].flags = SENSOR_FUNKNOWN;
	sensor_attach(&sc->sc_sensdev, &sc->sc_sens[7]);

	strlcpy(sc->sc_sens[8].desc, "design capacity",
	    sizeof(sc->sc_sens[8].desc));
	sc->sc_sens[8].type = SENSOR_WATTHOUR;
	sc->sc_sens[8].flags = SENSOR_FUNKNOWN;
	sensor_attach(&sc->sc_sensdev, &sc->sc_sens[8]);

	strlcpy(sc->sc_sens[9].desc, "discharge cycles",
	    sizeof(sc->sc_sens[9].desc));
	sc->sc_sens[9].type = SENSOR_INTEGER;
	sc->sc_sens[9].flags = SENSOR_FUNKNOWN;
	sensor_attach(&sc->sc_sensdev, &sc->sc_sens[9]);

	strlcpy(sc->sc_sens[10].desc, "temperature",
	    sizeof(sc->sc_sens[10].desc));
	sc->sc_sens[10].type = SENSOR_TEMP;
	sc->sc_sens[10].flags = SENSOR_FUNKNOWN;
	sensor_attach(&sc->sc_sensdev, &sc->sc_sens[10]);

	sensordev_install(&sc->sc_sensdev);
#endif
}

int
qcpas_map_memory(struct qcpas_softc *sc)
{
	uint32_t memreg[2] = {};
	uint32_t reg[4];
	size_t off;
	int node;
	int i;

	OF_getpropintarray(sc->sc_node, "memory-region",
	    memreg, sizeof(memreg));
	if (memreg[0] == 0)
		return EINVAL;

	for (i = 0; i < nitems(memreg); i++) {
		if (memreg[i] == 0)
			break;
		node = OF_getnodebyphandle(memreg[i]);
		if (node == 0)
			return EINVAL;
		if (OF_getpropintarray(node, "reg", reg,
		    sizeof(reg)) != sizeof(reg))
			return EINVAL;

		sc->sc_mem_phys[i] = (uint64_t)reg[0] << 32 | reg[1];
		KASSERT((sc->sc_mem_phys[i] & PAGE_MASK) == 0);
		sc->sc_mem_size[i] = (uint64_t)reg[2] << 32 | reg[3];
		KASSERT((sc->sc_mem_size[i] & PAGE_MASK) == 0);

		sc->sc_mem_region[i] = km_alloc(sc->sc_mem_size[i],
		    &kv_any, &kp_none, &kd_nowait);
		if (!sc->sc_mem_region[i])
			return ENOMEM;

		for (off = 0; off < sc->sc_mem_size[i]; off += PAGE_SIZE) {
			pmap_kenter_cache((vaddr_t)sc->sc_mem_region[i] + off,
			    sc->sc_mem_phys[i] + off, PROT_READ | PROT_WRITE,
			    PMAP_CACHE_DEV_NGNRNE);
		}
	}

	return 0;
}

int
qcpas_mdt_init(struct qcpas_softc *sc, int pas_id, u_char *fw, size_t fwlen)
{
	Elf32_Ehdr *ehdr;
	Elf32_Phdr *phdr;
	paddr_t minpa = -1, maxpa = 0;
	int i, hashseg = 0, relocate = 0;
	int error;
	ssize_t off;
	int idx;

	if (pas_id == sc->sc_dtb_pas_id)
		idx = 1;
	else
		idx = 0;

	ehdr = (Elf32_Ehdr *)fw;
	phdr = (Elf32_Phdr *)&ehdr[1];

	if (ehdr->e_phnum < 2 || phdr[0].p_type == PT_LOAD)
		return EINVAL;

	for (i = 0; i < ehdr->e_phnum; i++) {
		if ((phdr[i].p_flags & MDT_TYPE_MASK) == MDT_TYPE_HASH) {
			if (i > 0 && !hashseg)
				hashseg = i;
			continue;
		}
		if (phdr[i].p_type != PT_LOAD || phdr[i].p_memsz == 0)
			continue;
		if (phdr[i].p_flags & MDT_RELOCATABLE)
			relocate = 1;
		if (phdr[i].p_paddr < minpa)
			minpa = phdr[i].p_paddr;
		if (phdr[i].p_paddr + phdr[i].p_memsz > maxpa)
			maxpa =
			    roundup(phdr[i].p_paddr + phdr[i].p_memsz,
			    PAGE_SIZE);
	}

	if (!hashseg)
		return EINVAL;

	sc->sc_metadata[idx] = qcpas_dmamem_alloc(sc, phdr[0].p_filesz +
	    phdr[hashseg].p_filesz, PAGE_SIZE);
	if (sc->sc_metadata[idx] == NULL)
		return EINVAL;

	memcpy(QCPAS_DMA_KVA(sc->sc_metadata[idx]), fw, phdr[0].p_filesz);
	if (phdr[0].p_filesz + phdr[hashseg].p_filesz == fwlen) {
		memcpy(QCPAS_DMA_KVA(sc->sc_metadata[idx]) + phdr[0].p_filesz,
		    fw + phdr[0].p_filesz, phdr[hashseg].p_filesz);
	} else if (phdr[hashseg].p_offset + phdr[hashseg].p_filesz <= fwlen) {
		memcpy(QCPAS_DMA_KVA(sc->sc_metadata[idx]) + phdr[0].p_filesz,
		    fw + phdr[hashseg].p_offset, phdr[hashseg].p_filesz);
	} else {
		printf("%s: metadata split segment not supported\n",
		    sc->sc_dev.dv_xname);
		return EINVAL;
	}

	membar_producer();

	if (qcscm_pas_init_image(pas_id,
	    QCPAS_DMA_DVA(sc->sc_metadata[idx])) != 0) {
		printf("%s: init image failed\n", sc->sc_dev.dv_xname);
		qcpas_dmamem_free(sc, sc->sc_metadata[idx]);
		return EINVAL;
	}

	if (qcscm_pas_mem_setup(pas_id,
	    sc->sc_mem_phys[idx], maxpa - minpa) != 0) {
		printf("%s: mem setup failed\n", sc->sc_dev.dv_xname);
		qcpas_dmamem_free(sc, sc->sc_metadata[idx]);
		return EINVAL;
	}

	sc->sc_mem_reloc[idx] = relocate ? minpa : sc->sc_mem_phys[idx];

	for (i = 0; i < ehdr->e_phnum; i++) {
		if ((phdr[i].p_flags & MDT_TYPE_MASK) == MDT_TYPE_HASH ||
		    phdr[i].p_type != PT_LOAD || phdr[i].p_memsz == 0)
			continue;
		off = phdr[i].p_paddr - sc->sc_mem_reloc[idx];
		if (off < 0 || off + phdr[i].p_memsz > sc->sc_mem_size[0])
			return EINVAL;
		if (phdr[i].p_filesz > phdr[i].p_memsz)
			return EINVAL;

		if (phdr[i].p_filesz && phdr[i].p_offset < fwlen &&
		    phdr[i].p_offset + phdr[i].p_filesz <= fwlen) {
			memcpy(sc->sc_mem_region[idx] + off,
			    fw + phdr[i].p_offset, phdr[i].p_filesz);
		} else if (phdr[i].p_filesz) {
			printf("%s: firmware split segment not supported\n",
			    sc->sc_dev.dv_xname);
			return EINVAL;
		}

		if (phdr[i].p_memsz > phdr[i].p_filesz)
			memset(sc->sc_mem_region[idx] + off + phdr[i].p_filesz,
			    0, phdr[i].p_memsz - phdr[i].p_filesz);
	}

	membar_producer();

	if (qcscm_pas_auth_and_reset(pas_id) != 0) {
		printf("%s: auth and reset failed\n", sc->sc_dev.dv_xname);
		qcpas_dmamem_free(sc, sc->sc_metadata[idx]);
		return EINVAL;
	}

	if (pas_id == sc->sc_dtb_pas_id)
		return 0;

	error = tsleep_nsec(sc, PWAIT, "qcpas", SEC_TO_NSEC(5));
	if (error) {
		printf("%s: failed to receive ready signal\n",
		    sc->sc_dev.dv_xname);
		return error;
	}

	/* XXX: free metadata ? */

	return 0;
}

struct qcpas_dmamem *
qcpas_dmamem_alloc(struct qcpas_softc *sc, bus_size_t size, bus_size_t align)
{
	struct qcpas_dmamem *tdm;
	int nsegs;

	tdm = malloc(sizeof(*tdm), M_DEVBUF, M_WAITOK | M_ZERO);
	tdm->tdm_size = size;

	if (bus_dmamap_create(sc->sc_dmat, size, 1, size, 0,
	    BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW, &tdm->tdm_map) != 0)
		goto tdmfree;

	if (bus_dmamem_alloc_range(sc->sc_dmat, size, align, 0,
	    &tdm->tdm_seg, 1, &nsegs, BUS_DMA_WAITOK, 0, 0xffffffff) != 0)
		goto destroy;

	if (bus_dmamem_map(sc->sc_dmat, &tdm->tdm_seg, nsegs, size,
	    &tdm->tdm_kva, BUS_DMA_WAITOK | BUS_DMA_COHERENT) != 0)
		goto free;

	if (bus_dmamap_load(sc->sc_dmat, tdm->tdm_map, tdm->tdm_kva, size,
	    NULL, BUS_DMA_WAITOK) != 0)
		goto unmap;

	bzero(tdm->tdm_kva, size);

	return (tdm);

unmap:
	bus_dmamem_unmap(sc->sc_dmat, tdm->tdm_kva, size);
free:
	bus_dmamem_free(sc->sc_dmat, &tdm->tdm_seg, 1);
destroy:
	bus_dmamap_destroy(sc->sc_dmat, tdm->tdm_map);
tdmfree:
	free(tdm, M_DEVBUF, 0);

	return (NULL);
}

void
qcpas_dmamem_free(struct qcpas_softc *sc, struct qcpas_dmamem *tdm)
{
	bus_dmamem_unmap(sc->sc_dmat, tdm->tdm_kva, tdm->tdm_size);
	bus_dmamem_free(sc->sc_dmat, &tdm->tdm_seg, 1);
	bus_dmamap_destroy(sc->sc_dmat, tdm->tdm_map);
	free(tdm, M_DEVBUF, 0);
}

void
qcpas_intr_establish(struct qcpas_softc *sc, int i, char *name, void *handler)
{
	int idx;

	idx = OF_getindex(sc->sc_node, name, "interrupt-names");
	if (idx >= 0)
		sc->sc_ih[i] =
		    fdt_intr_establish_idx(sc->sc_node, idx, IPL_BIO,
		    handler, sc, sc->sc_dev.dv_xname);
}

int
qcpas_intr_wdog(void *cookie)
{
	return 0;
}

int
qcpas_intr_fatal(void *cookie)
{
	return 0;
}

int
qcpas_intr_ready(void *cookie)
{
	struct qcpas_softc *sc = cookie;

	wakeup(sc);
	return 0;
}

int
qcpas_intr_handover(void *cookie)
{
	return 0;
}

int
qcpas_intr_stop_ack(void *cookie)
{
	return 0;
}

int
qcpas_intr_shutdown_ack(void *cookie)
{
	return 0;
}

/* GLINK */

#define SMEM_GLINK_NATIVE_XPRT_DESCRIPTOR	478
#define SMEM_GLINK_NATIVE_XPRT_FIFO_0		479
#define SMEM_GLINK_NATIVE_XPRT_FIFO_1		480

struct glink_msg {
	uint16_t cmd;
	uint16_t param1;
	uint32_t param2;
	uint8_t data[];
} __packed;

struct qcpas_glink_intent_pair {
	uint32_t size;
	uint32_t iid;
} __packed;

struct qcpas_glink_intent {
	TAILQ_ENTRY(qcpas_glink_intent) it_q;
	uint32_t it_id;
	uint32_t it_size;
	int it_inuse;
};

struct qcpas_glink_channel {
	TAILQ_ENTRY(qcpas_glink_channel) ch_q;
	struct qcpas_softc *ch_sc;
	struct qcpas_glink_protocol *ch_proto;
	uint32_t ch_rcid;
	uint32_t ch_lcid;
	uint32_t ch_max_intent;
	TAILQ_HEAD(,qcpas_glink_intent) ch_l_intents;
	TAILQ_HEAD(,qcpas_glink_intent) ch_r_intents;
};

#define GLINK_CMD_VERSION		0
#define GLINK_CMD_VERSION_ACK		1
#define  GLINK_VERSION				1
#define  GLINK_FEATURE_INTENT_REUSE		(1 << 0)
#define GLINK_CMD_OPEN			2
#define GLINK_CMD_CLOSE			3
#define GLINK_CMD_OPEN_ACK		4
#define GLINK_CMD_INTENT		5
#define GLINK_CMD_RX_DONE		6
#define GLINK_CMD_RX_INTENT_REQ		7
#define GLINK_CMD_RX_INTENT_REQ_ACK	8
#define GLINK_CMD_TX_DATA		9
#define GLINK_CMD_CLOSE_ACK		11
#define GLINK_CMD_TX_DATA_CONT		12
#define GLINK_CMD_READ_NOTIF		13
#define GLINK_CMD_RX_DONE_W_REUSE	14

void	qcpas_glink_recv(void *);
int	qcpas_glink_intr(void *);

void	qcpas_glink_tx(struct qcpas_softc *, uint8_t *, int);
void	qcpas_glink_tx_commit(struct qcpas_softc *);
void	qcpas_glink_rx(struct qcpas_softc *, uint8_t *, int);
void	qcpas_glink_rx_commit(struct qcpas_softc *);

void	qcpas_glink_send(void *, void *, int);

extern int qcsmem_alloc(int, int, int);
extern void *qcsmem_get(int, int, int *);

int	qcpas_pmic_rtr_init(void *);
int	qcpas_pmic_rtr_recv(void *, uint8_t *, int);
int	qcpas_pmic_rtr_apminfo(struct apm_power_info *);

struct qcpas_glink_protocol {
	char *name;
	int (*init)(void *cookie);
	int (*recv)(void *cookie, uint8_t *buf, int len);
} qcpas_glink_protocols[] = {
	{ "PMIC_RTR_ADSP_APPS", qcpas_pmic_rtr_init , qcpas_pmic_rtr_recv },
};

void
qcpas_glink_attach(struct qcpas_softc *sc, int node)
{
	uint32_t remote;
	uint32_t *descs;
	int size;

	remote = OF_getpropint(node, "qcom,remote-pid", -1);
	if (remote == -1)
		return;

	if (qcsmem_alloc(remote, SMEM_GLINK_NATIVE_XPRT_DESCRIPTOR, 32) != 0 ||
	    qcsmem_alloc(remote, SMEM_GLINK_NATIVE_XPRT_FIFO_0, 16384) != 0)
		return;

	descs = qcsmem_get(remote, SMEM_GLINK_NATIVE_XPRT_DESCRIPTOR, &size);
	if (descs == NULL || size != 32)
		return;

	sc->sc_tx_tail = &descs[0];
	sc->sc_tx_head = &descs[1];
	sc->sc_rx_tail = &descs[2];
	sc->sc_rx_head = &descs[3];

	sc->sc_tx_fifo = qcsmem_get(remote, SMEM_GLINK_NATIVE_XPRT_FIFO_0,
	    &sc->sc_tx_fifolen);
	if (sc->sc_tx_fifo == NULL)
		return;
	sc->sc_rx_fifo = qcsmem_get(remote, SMEM_GLINK_NATIVE_XPRT_FIFO_1,
	    &sc->sc_rx_fifolen);
	if (sc->sc_rx_fifo == NULL)
		return;

	sc->sc_mc = mbox_channel_idx(node, 0, NULL);
	if (sc->sc_mc == NULL)
		return;

	TAILQ_INIT(&sc->sc_glink_channels);
	task_set(&sc->sc_glink_rx, qcpas_glink_recv, sc);

	sc->sc_glink_ih = fdt_intr_establish(node, IPL_BIO,
	    qcpas_glink_intr, sc, sc->sc_dev.dv_xname);
	if (sc->sc_glink_ih == NULL)
		return;

	/* Expect peer to send initial message */
}

void
qcpas_glink_rx(struct qcpas_softc *sc, uint8_t *buf, int len)
{
	uint32_t head, tail;
	int avail;

	head = *sc->sc_rx_head;
	tail = *sc->sc_rx_tail + sc->sc_rx_off;
	if (tail >= sc->sc_rx_fifolen)
		tail -= sc->sc_rx_fifolen;

	/* Checked by caller */
	KASSERT(head != tail);

	if (head >= tail)
		avail = head - tail;
	else
		avail = (sc->sc_rx_fifolen - tail) + head;

	/* Dumb, but should do. */
	KASSERT(avail >= len);

	while (len > 0) {
		*buf = sc->sc_rx_fifo[tail];
		tail++;
		if (tail >= sc->sc_rx_fifolen)
			tail -= sc->sc_rx_fifolen;
		buf++;
		sc->sc_rx_off++;
		len--;
	}
}

void
qcpas_glink_rx_commit(struct qcpas_softc *sc)
{
	uint32_t tail;

	tail = *sc->sc_rx_tail + roundup(sc->sc_rx_off, 8);
	if (tail >= sc->sc_rx_fifolen)
		tail -= sc->sc_rx_fifolen;

	membar_producer();
	*sc->sc_rx_tail = tail;
	sc->sc_rx_off = 0;
}

void
qcpas_glink_tx(struct qcpas_softc *sc, uint8_t *buf, int len)
{
	uint32_t head, tail;
	int avail;

	head = *sc->sc_tx_head + sc->sc_tx_off;
	if (head >= sc->sc_tx_fifolen)
		head -= sc->sc_tx_fifolen;
	tail = *sc->sc_tx_tail;

	if (head < tail)
		avail = tail - head;
	else
		avail = (sc->sc_rx_fifolen - head) + tail;

	/* Dumb, but should do. */
	KASSERT(avail >= len);

	while (len > 0) {
		sc->sc_tx_fifo[head] = *buf;
		head++;
		if (head >= sc->sc_tx_fifolen)
			head -= sc->sc_tx_fifolen;
		buf++;
		sc->sc_tx_off++;
		len--;
	}
}

void
qcpas_glink_tx_commit(struct qcpas_softc *sc)
{
	uint32_t head;

	head = *sc->sc_tx_head + roundup(sc->sc_tx_off, 8);
	if (head >= sc->sc_tx_fifolen)
		head -= sc->sc_tx_fifolen;

	membar_producer();
	*sc->sc_tx_head = head;
	sc->sc_tx_off = 0;
	mbox_send(sc->sc_mc, NULL, 0);
}

void
qcpas_glink_send(void *cookie, void *buf, int len)
{
	struct qcpas_glink_channel *ch = cookie;
	struct qcpas_softc *sc = ch->ch_sc;
	struct qcpas_glink_intent *it;
	struct glink_msg msg;
	uint32_t chunk_size, left_size;

	TAILQ_FOREACH(it, &ch->ch_r_intents, it_q) {
		if (!it->it_inuse)
			break;
		if (it->it_size < len)
			continue;
	}
	if (it == NULL) {
		printf("%s: all intents in use\n",
		    sc->sc_dev.dv_xname);
		return;
	}
	it->it_inuse = 1;

	msg.cmd = GLINK_CMD_TX_DATA;
	msg.param1 = ch->ch_lcid;
	msg.param2 = it->it_id;

	chunk_size = len;
	left_size = 0;

	qcpas_glink_tx(sc, (char *)&msg, sizeof(msg));
	qcpas_glink_tx(sc, (char *)&chunk_size, sizeof(chunk_size));
	qcpas_glink_tx(sc, (char *)&left_size, sizeof(left_size));
	qcpas_glink_tx(sc, buf, len);
	qcpas_glink_tx_commit(sc);
}

void
qcpas_glink_recv_version(struct qcpas_softc *sc, uint32_t version,
    uint32_t features)
{
	struct glink_msg msg;

	if (version != GLINK_VERSION) {
		printf("%s: unsupported glink version %u\n",
		    sc->sc_dev.dv_xname, version);
		return;
	}

	msg.cmd = GLINK_CMD_VERSION_ACK;
	msg.param1 = GLINK_VERSION;
	msg.param2 = features & GLINK_FEATURE_INTENT_REUSE;

	qcpas_glink_tx(sc, (char *)&msg, sizeof(msg));
	qcpas_glink_tx_commit(sc);
}

void
qcpas_glink_recv_open(struct qcpas_softc *sc, uint32_t rcid, uint32_t namelen)
{
	struct qcpas_glink_protocol *proto = NULL;
	struct qcpas_glink_channel *ch;
	struct glink_msg msg;
	char *name;
	int i, err;

	name = malloc(namelen, M_TEMP, M_WAITOK);
	qcpas_glink_rx(sc, name, namelen);
	qcpas_glink_rx_commit(sc);

	TAILQ_FOREACH(ch, &sc->sc_glink_channels, ch_q) {
		if (ch->ch_rcid == rcid) {
			printf("%s: duplicate open for %s\n",
			    sc->sc_dev.dv_xname, name);
			free(name, M_TEMP, namelen);
			return;
		}
	}

	for (i = 0; i < nitems(qcpas_glink_protocols); i++) {
		if (strcmp(qcpas_glink_protocols[i].name, name) != 0)
			continue;
		proto = &qcpas_glink_protocols[i];
		break;
	}
	if (proto == NULL) {
		free(name, M_TEMP, namelen);
		return;
	}

	ch = malloc(sizeof(*ch), M_DEVBUF, M_WAITOK | M_ZERO);
	ch->ch_sc = sc;
	ch->ch_proto = proto;
	ch->ch_rcid = rcid;
	ch->ch_lcid = ++sc->sc_glink_max_channel;
	TAILQ_INIT(&ch->ch_l_intents);
	TAILQ_INIT(&ch->ch_r_intents);
	TAILQ_INSERT_TAIL(&sc->sc_glink_channels, ch, ch_q);

	/* Assume we can leave HW dangling if proto init fails */
	err = proto->init(ch);
	if (err) {
		TAILQ_REMOVE(&sc->sc_glink_channels, ch, ch_q);
		free(ch, M_TEMP, sizeof(*ch));
		free(name, M_TEMP, namelen);
		return;
	}

	msg.cmd = GLINK_CMD_OPEN_ACK;
	msg.param1 = ch->ch_rcid;
	msg.param2 = 0;

	qcpas_glink_tx(sc, (char *)&msg, sizeof(msg));
	qcpas_glink_tx_commit(sc);

	msg.cmd = GLINK_CMD_OPEN;
	msg.param1 = ch->ch_lcid;
	msg.param2 = strlen(name) + 1;

	qcpas_glink_tx(sc, (char *)&msg, sizeof(msg));
	qcpas_glink_tx(sc, name, strlen(name) + 1);
	qcpas_glink_tx_commit(sc);

	free(name, M_TEMP, namelen);
}

void
qcpas_glink_recv_open_ack(struct qcpas_softc *sc, uint32_t lcid)
{
	struct qcpas_glink_channel *ch;
	struct glink_msg msg;
	struct qcpas_glink_intent_pair intent;
	int i;

	TAILQ_FOREACH(ch, &sc->sc_glink_channels, ch_q) {
		if (ch->ch_lcid == lcid)
			break;
	}
	if (ch == NULL) {
		printf("%s: unknown channel %u for OPEN_ACK\n",
		    sc->sc_dev.dv_xname, lcid);
		return;
	}

	/* Respond with default intent now that channel is open */
	for (i = 0; i < 5; i++) {
		struct qcpas_glink_intent *it;

		it = malloc(sizeof(*it), M_DEVBUF, M_WAITOK | M_ZERO);
		it->it_id = ++ch->ch_max_intent;
		it->it_size = 1024;
		TAILQ_INSERT_TAIL(&ch->ch_l_intents, it, it_q);

		msg.cmd = GLINK_CMD_INTENT;
		msg.param1 = ch->ch_lcid;
		msg.param2 = 1;
		intent.size = it->it_size;
		intent.iid = it->it_id;
	}

	qcpas_glink_tx(sc, (char *)&msg, sizeof(msg));
	qcpas_glink_tx(sc, (char *)&intent, sizeof(intent));
	qcpas_glink_tx_commit(sc);
}

void
qcpas_glink_recv_intent(struct qcpas_softc *sc, uint32_t rcid, uint32_t count)
{
	struct qcpas_glink_intent_pair *intents;
	struct qcpas_glink_channel *ch;
	struct qcpas_glink_intent *it;
	int i;

	intents = malloc(sizeof(*intents) * count, M_TEMP, M_WAITOK);
	qcpas_glink_rx(sc, (char *)intents, sizeof(*intents) * count);
	qcpas_glink_rx_commit(sc);

	TAILQ_FOREACH(ch, &sc->sc_glink_channels, ch_q) {
		if (ch->ch_rcid == rcid)
			break;
	}
	if (ch == NULL) {
		printf("%s: unknown channel %u for INTENT\n",
		    sc->sc_dev.dv_xname, rcid);
		free(intents, M_TEMP, sizeof(*intents) * count);
		return;
	}

	for (i = 0; i < count; i++) {
		it = malloc(sizeof(*it), M_DEVBUF, M_WAITOK | M_ZERO);
		it->it_id = intents[i].iid;
		it->it_size = intents[i].size;
		TAILQ_INSERT_TAIL(&ch->ch_r_intents, it, it_q);
	}

	free(intents, M_TEMP, sizeof(*intents) * count);
}

void
qcpas_glink_recv_tx_data(struct qcpas_softc *sc, uint32_t rcid, uint32_t liid)
{
	struct qcpas_glink_channel *ch;
	struct qcpas_glink_intent *it;
	struct glink_msg msg;
	uint32_t chunk_size, left_size;
	char *buf;

	qcpas_glink_rx(sc, (char *)&chunk_size, sizeof(chunk_size));
	qcpas_glink_rx(sc, (char *)&left_size, sizeof(left_size));
	qcpas_glink_rx_commit(sc);

	buf = malloc(chunk_size, M_TEMP, M_WAITOK);
	qcpas_glink_rx(sc, buf, chunk_size);
	qcpas_glink_rx_commit(sc);

	TAILQ_FOREACH(ch, &sc->sc_glink_channels, ch_q) {
		if (ch->ch_rcid == rcid)
			break;
	}
	if (ch == NULL) {
		printf("%s: unknown channel %u for TX_DATA\n",
		    sc->sc_dev.dv_xname, rcid);
		free(buf, M_TEMP, chunk_size);
		return;
	}

	TAILQ_FOREACH(it, &ch->ch_l_intents, it_q) {
		if (it->it_id == liid)
			break;
	}
	if (it == NULL) {
		printf("%s: unknown intent %u for TX_DATA\n",
		    sc->sc_dev.dv_xname, liid);
		free(buf, M_TEMP, chunk_size);
		return;
	}

	/* FIXME: handle message chunking */
	KASSERT(left_size == 0);

	ch->ch_proto->recv(ch, buf, chunk_size);
	free(buf, M_TEMP, chunk_size);

	if (!left_size) {
		msg.cmd = GLINK_CMD_RX_DONE_W_REUSE;
		msg.param1 = ch->ch_lcid;
		msg.param2 = it->it_id;

		qcpas_glink_tx(sc, (char *)&msg, sizeof(msg));
		qcpas_glink_tx_commit(sc);
	}
}

void
qcpas_glink_recv_rx_done(struct qcpas_softc *sc, uint32_t rcid, uint32_t riid,
    int reuse)
{
	struct qcpas_glink_channel *ch;
	struct qcpas_glink_intent *it;

	TAILQ_FOREACH(ch, &sc->sc_glink_channels, ch_q) {
		if (ch->ch_rcid == rcid)
			break;
	}
	if (ch == NULL) {
		printf("%s: unknown channel %u for RX_DONE\n",
		    sc->sc_dev.dv_xname, rcid);
		return;
	}

	TAILQ_FOREACH(it, &ch->ch_r_intents, it_q) {
		if (it->it_id == riid)
			break;
	}
	if (it == NULL) {
		printf("%s: unknown intent %u for RX_DONE\n",
		    sc->sc_dev.dv_xname, riid);
		return;
	}

	/* FIXME: handle non-reuse */
	KASSERT(reuse);

	KASSERT(it->it_inuse);
	it->it_inuse = 0;
}

void
qcpas_glink_recv(void *cookie)
{
	struct qcpas_softc *sc = cookie;
	struct glink_msg msg;

	while (*sc->sc_rx_tail != *sc->sc_rx_head) {
		membar_consumer();
		qcpas_glink_rx(sc, (uint8_t *)&msg, sizeof(msg));
		qcpas_glink_rx_commit(sc);

		switch (msg.cmd) {
		case GLINK_CMD_VERSION:
			qcpas_glink_recv_version(sc, msg.param1, msg.param2);
			break;
		case GLINK_CMD_OPEN:
			qcpas_glink_recv_open(sc, msg.param1, msg.param2);
			break;
		case GLINK_CMD_OPEN_ACK:
			qcpas_glink_recv_open_ack(sc, msg.param1);
			break;
		case GLINK_CMD_INTENT:
			qcpas_glink_recv_intent(sc, msg.param1, msg.param2);
			break;
		case GLINK_CMD_RX_INTENT_REQ:
			/* Nothing to do so far */
			break;
		case GLINK_CMD_TX_DATA:
			qcpas_glink_recv_tx_data(sc, msg.param1, msg.param2);
			break;
		case GLINK_CMD_RX_DONE:
			qcpas_glink_recv_rx_done(sc, msg.param1, msg.param2, 0);
			break;
		case GLINK_CMD_RX_DONE_W_REUSE:
			qcpas_glink_recv_rx_done(sc, msg.param1, msg.param2, 1);
			break;
		default:
			printf("%s: unknown cmd %u\n", __func__, msg.cmd);
			return;
		}
	}
}

int
qcpas_glink_intr(void *cookie)
{
	struct qcpas_softc *sc = cookie;

	task_add(systq, &sc->sc_glink_rx);
	return 1;
}

/* GLINK PMIC Router */

struct pmic_glink_hdr {
	uint32_t owner;
#define PMIC_GLINK_OWNER_BATTMGR	32778
#define PMIC_GLINK_OWNER_USBC		32779
#define PMIC_GLINK_OWNER_USBC_PAN	32780
	uint32_t type;
#define PMIC_GLINK_TYPE_REQ_RESP	1
#define PMIC_GLINK_TYPE_NOTIFY		2
	uint32_t opcode;
};

#define BATTMGR_OPCODE_BAT_STATUS		0x1
#define BATTMGR_OPCODR_REQUEST_NOTIFICATION	0x4
#define BATTMGR_OPCODE_NOTIF			0x7
#define BATTMGR_OPCODE_BAT_INFO			0x9
#define BATTMGR_OPCODE_BAT_DISCHARGE_TIME	0xc
#define BATTMGR_OPCODE_BAT_CHARGE_TIME		0xd

#define BATTMGR_NOTIF_BAT_PROPERTY		0x30
#define BATTMGR_NOTIF_USB_PROPERTY		0x32
#define BATTMGR_NOTIF_WLS_PROPERTY		0x34
#define BATTMGR_NOTIF_BAT_STATUS		0x80
#define BATTMGR_NOTIF_BAT_INFO			0x81

#define BATTMGR_CHEMISTRY_LEN			4
#define BATTMGR_STRING_LEN			128

struct battmgr_bat_info {
	uint32_t power_unit;
	uint32_t design_capacity;
	uint32_t last_full_capacity;
	uint32_t battery_tech;
	uint32_t design_voltage;
	uint32_t capacity_low;
	uint32_t capacity_warning;
	uint32_t cycle_count;
	uint32_t accuracy;
	uint32_t max_sample_time_ms;
	uint32_t min_sample_time_ms;
	uint32_t max_average_interval_ms;
	uint32_t min_average_interval_ms;
	uint32_t capacity_granularity1;
	uint32_t capacity_granularity2;
	uint32_t swappable;
	uint32_t capabilities;
	char model_number[BATTMGR_STRING_LEN];
	char serial_number[BATTMGR_STRING_LEN];
	char battery_type[BATTMGR_STRING_LEN];
	char oem_info[BATTMGR_STRING_LEN];
	char battery_chemistry[BATTMGR_CHEMISTRY_LEN];
	char uid[BATTMGR_STRING_LEN];
	uint32_t critical_bias;
	uint8_t day;
	uint8_t month;
	uint16_t year;
	uint32_t battery_id;
};

struct battmgr_bat_status {
	uint32_t battery_state;
#define BATTMGR_BAT_STATE_DISCHARGE	(1 << 0)
#define BATTMGR_BAT_STATE_CHARGING	(1 << 1)
#define BATTMGR_BAT_STATE_CRITICAL_LOW	(1 << 2)
	uint32_t capacity;
	int32_t rate;
	uint32_t battery_voltage;
	uint32_t power_state;
#define BATTMGR_PWR_STATE_AC_ON			(1 << 0)
	uint32_t charging_source;
#define BATTMGR_CHARGING_SOURCE_AC		1
#define BATTMGR_CHARGING_SOURCE_USB		2
#define BATTMGR_CHARGING_SOURCE_WIRELESS	3
	uint32_t temperature;
};

void	qcpas_pmic_rtr_refresh(void *);
void	qcpas_pmic_rtr_bat_info(struct qcpas_softc *,
	    struct battmgr_bat_info *);
void	qcpas_pmic_rtr_bat_status(struct qcpas_softc *,
	    struct battmgr_bat_status *);

void
qcpas_pmic_rtr_battmgr_req_info(void *cookie)
{
	struct {
		struct pmic_glink_hdr hdr;
		uint32_t battery_id;
	} msg;

	msg.hdr.owner = PMIC_GLINK_OWNER_BATTMGR;
	msg.hdr.type = PMIC_GLINK_TYPE_REQ_RESP;
	msg.hdr.opcode = BATTMGR_OPCODE_BAT_INFO;
	msg.battery_id = 0;
	qcpas_glink_send(cookie, &msg, sizeof(msg));
}

void
qcpas_pmic_rtr_battmgr_req_status(void *cookie)
{
	struct {
		struct pmic_glink_hdr hdr;
		uint32_t battery_id;
	} msg;

	msg.hdr.owner = PMIC_GLINK_OWNER_BATTMGR;
	msg.hdr.type = PMIC_GLINK_TYPE_REQ_RESP;
	msg.hdr.opcode = BATTMGR_OPCODE_BAT_STATUS;
	msg.battery_id = 0;
	qcpas_glink_send(cookie, &msg, sizeof(msg));
}

#if NAPM > 0
struct apm_power_info qcpas_pmic_rtr_apm_power_info;
void *qcpas_pmic_rtr_apm_cookie;
#endif

int
qcpas_pmic_rtr_init(void *cookie)
{
#if NAPM > 0
	struct apm_power_info *info;

	info = &qcpas_pmic_rtr_apm_power_info;
	info->battery_state = APM_BATT_UNKNOWN;
	info->ac_state = APM_AC_UNKNOWN;
	info->battery_life = 0;
	info->minutes_left = -1;

	qcpas_pmic_rtr_apm_cookie = cookie;
	apm_setinfohook(qcpas_pmic_rtr_apminfo);
#endif
#ifndef SMALL_KERNEL
	sensor_task_register(cookie, qcpas_pmic_rtr_refresh, 5);
#endif
	return 0;
}

int
qcpas_pmic_rtr_recv(void *cookie, uint8_t *buf, int len)
{
	struct qcpas_glink_channel *ch = cookie;
	struct qcpas_softc *sc = ch->ch_sc;
	struct pmic_glink_hdr hdr;
	uint32_t notification;

	if (len < sizeof(hdr)) {
		printf("%s: pmic glink message too small\n",
		    __func__);
		return 0;
	}

	memcpy(&hdr, buf, sizeof(hdr));

	switch (hdr.owner) {
	case PMIC_GLINK_OWNER_BATTMGR:
		switch (hdr.opcode) {
		case BATTMGR_OPCODE_NOTIF:
			if (len - sizeof(hdr) != sizeof(uint32_t)) {
				printf("%s: invalid battgmr notification\n",
				    __func__);
				return 0;
			}
			memcpy(&notification, buf + sizeof(hdr),
			    sizeof(uint32_t));
			switch (notification) {
			case BATTMGR_NOTIF_BAT_INFO:
				qcpas_pmic_rtr_battmgr_req_info(cookie);
				/* FALLTHROUGH */
			case BATTMGR_NOTIF_BAT_STATUS:
			case BATTMGR_NOTIF_BAT_PROPERTY:
				qcpas_pmic_rtr_battmgr_req_status(cookie);
				break;
			default:
				printf("%s: unknown battmgr notification"
				    " 0x%02x\n", __func__, notification);
				break;
			}
			break;
		case BATTMGR_OPCODE_BAT_INFO: {
			struct battmgr_bat_info *bat;
			if (len - sizeof(hdr) < sizeof(*bat)) {
				printf("%s: invalid battgmr bat info\n",
				    __func__);
				return 0;
			}
			bat = malloc(sizeof(*bat), M_TEMP, M_WAITOK);
			memcpy(bat, buf + sizeof(hdr), sizeof(*bat));
			qcpas_pmic_rtr_bat_info(sc, bat);
			free(bat, M_TEMP, sizeof(*bat));
			break;
		}
		case BATTMGR_OPCODE_BAT_STATUS: {
			struct battmgr_bat_status *bat;
			if (len - sizeof(hdr) != sizeof(*bat)) {
				printf("%s: invalid battgmr bat status\n",
				    __func__);
				return 0;
			}
			bat = malloc(sizeof(*bat), M_TEMP, M_WAITOK);
			memcpy(bat, buf + sizeof(hdr), sizeof(*bat));
			qcpas_pmic_rtr_bat_status(sc, bat);
			free(bat, M_TEMP, sizeof(*bat));
			break;
		}
		default:
			printf("%s: unknown battmgr opcode 0x%02x\n",
			    __func__, hdr.opcode);
			break;
		}
		break;
	default:
		printf("%s: unknown pmic glink owner 0x%04x\n",
		    __func__, hdr.owner);
		break;
	}

	return 0;
}

#if NAPM > 0
int
qcpas_pmic_rtr_apminfo(struct apm_power_info *info)
{
	int error;

	qcpas_pmic_rtr_battmgr_req_status(qcpas_pmic_rtr_apm_cookie);
	error = tsleep_nsec(&qcpas_pmic_rtr_apm_power_info, PWAIT | PCATCH,
	    "qcapm", SEC_TO_NSEC(5));
	if (error)
		return error;

	memcpy(info, &qcpas_pmic_rtr_apm_power_info, sizeof(*info));
	return 0;
}
#endif

void
qcpas_pmic_rtr_refresh(void *arg)
{
	qcpas_pmic_rtr_battmgr_req_status(arg);
}

void
qcpas_pmic_rtr_bat_info(struct qcpas_softc *sc, struct battmgr_bat_info *bat)
{
#ifndef SMALL_KERNEL
	sc->sc_last_full_capacity = bat->last_full_capacity;
	sc->sc_warning_capacity = bat->capacity_warning;
	sc->sc_low_capacity = bat->capacity_low;

	sc->sc_sens[0].value = bat->last_full_capacity * 1000;
	sc->sc_sens[0].flags &= ~SENSOR_FUNKNOWN;

	sc->sc_sens[1].value = bat->capacity_warning * 1000;
	sc->sc_sens[1].flags &= ~SENSOR_FUNKNOWN;

	sc->sc_sens[2].value = bat->capacity_low * 1000;
	sc->sc_sens[2].flags &= ~SENSOR_FUNKNOWN;

	sc->sc_sens[3].value = bat->design_voltage * 1000;
	sc->sc_sens[3].flags &= ~SENSOR_FUNKNOWN;

	sc->sc_sens[8].value = bat->design_capacity * 1000;
	sc->sc_sens[8].flags &= ~SENSOR_FUNKNOWN;

	sc->sc_sens[9].value = bat->cycle_count;
	sc->sc_sens[9].flags &= ~SENSOR_FUNKNOWN;
#endif
}

void
qcpas_pmic_rtr_bat_status(struct qcpas_softc *sc,
    struct battmgr_bat_status *bat)
{
#if NAPM > 0
	extern int hw_power;
	struct apm_power_info *info = &qcpas_pmic_rtr_apm_power_info;
	uint32_t delta;
#endif

#ifndef SMALL_KERNEL
	if (bat->capacity >= sc->sc_last_full_capacity)
		strlcpy(sc->sc_sens[4].desc, "battery full",
		    sizeof(sc->sc_sens[4].desc));
	else if (bat->battery_state & BATTMGR_BAT_STATE_DISCHARGE)
		strlcpy(sc->sc_sens[4].desc, "battery discharging",
		    sizeof(sc->sc_sens[4].desc));
	else if (bat->battery_state & BATTMGR_BAT_STATE_CHARGING)
		strlcpy(sc->sc_sens[4].desc, "battery charging",
		    sizeof(sc->sc_sens[4].desc));
	else
		strlcpy(sc->sc_sens[4].desc, "battery idle",
		    sizeof(sc->sc_sens[4].desc));
	if (bat->battery_state & BATTMGR_BAT_STATE_CRITICAL_LOW)
		sc->sc_sens[4].status = SENSOR_S_CRIT;
	else
		sc->sc_sens[4].status = SENSOR_S_OK;
	sc->sc_sens[4].value = bat->battery_state;
	sc->sc_sens[4].flags &= ~SENSOR_FUNKNOWN;

	sc->sc_sens[5].value = abs(bat->rate) * 1000;
	sc->sc_sens[5].flags &= ~SENSOR_FUNKNOWN;

	sc->sc_sens[6].value = bat->capacity * 1000;
	if (bat->capacity < sc->sc_low_capacity)
		sc->sc_sens[6].status = SENSOR_S_CRIT;
	else if (bat->capacity < sc->sc_warning_capacity)
		sc->sc_sens[6].status = SENSOR_S_WARN;
	else
		sc->sc_sens[6].status = SENSOR_S_OK;
	sc->sc_sens[6].flags &= ~SENSOR_FUNKNOWN;

	sc->sc_sens[7].value = bat->battery_voltage * 1000;
	sc->sc_sens[7].flags &= ~SENSOR_FUNKNOWN;

	sc->sc_sens[10].value = (bat->temperature * 10000) + 273150000;
	sc->sc_sens[10].flags &= ~SENSOR_FUNKNOWN;
#endif

#if NAPM > 0
	/* Needs BAT_INFO fist */
	if (sc->sc_last_full_capacity == 0) {
		wakeup(&qcpas_pmic_rtr_apm_power_info);
		return;
	}

	info->battery_life =
	    ((bat->capacity * 100) / sc->sc_last_full_capacity);
	if (info->battery_life > 50)
		info->battery_state = APM_BATT_HIGH;
	else if (info->battery_life > 25)
		info->battery_state = APM_BATT_LOW;
	else
		info->battery_state = APM_BATT_CRITICAL;
	if (bat->battery_state & BATTMGR_BAT_STATE_CHARGING)
		info->battery_state = APM_BATT_CHARGING;
	else if (bat->battery_state & BATTMGR_BAT_STATE_CRITICAL_LOW)
		info->battery_state = APM_BATT_CRITICAL;

	if (bat->rate < 0)
		delta = bat->capacity;
	else
		delta = sc->sc_last_full_capacity - bat->capacity;
	if (bat->rate == 0)
		info->minutes_left = -1;
	else
		info->minutes_left = (60 * delta) / abs(bat->rate);

	if (bat->power_state & BATTMGR_PWR_STATE_AC_ON) {
		info->ac_state = APM_AC_ON;
		hw_power = 1;
	} else {
		info->ac_state = APM_AC_OFF;
		hw_power = 0;
	}

	wakeup(&qcpas_pmic_rtr_apm_power_info);
#endif
}