summaryrefslogtreecommitdiffstats
path: root/src/drivers/usb/usbio.c
blob: e91416fdceac353843708134171a836203381a8e (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
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
/*
 * Copyright (C) 2015 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 *
 * You can also choose to distribute this program under the terms of
 * the Unmodified Binary Distribution Licence (as given in the file
 * COPYING.UBDL), provided that you have satisfied its requirements.
 */

FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );

#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <ipxe/efi/efi.h>
#include <ipxe/efi/efi_driver.h>
#include <ipxe/efi/efi_utils.h>
#include <ipxe/efi/Protocol/UsbIo.h>
#include <ipxe/usb.h>
#include "usbio.h"

/** @file
 *
 * EFI_USB_IO_PROTOCOL pseudo Host Controller Interface driver
 *
 *
 * The EFI_USB_IO_PROTOCOL is an almost unbelievably poorly designed
 * abstraction of a USB device.  It would be just about forgivable for
 * an API to support only synchronous operation for bulk OUT
 * endpoints.  It is imbecilic to support only synchronous operation
 * for bulk IN endpoints.  This apparently intern-designed API
 * throttles a typical NIC down to 1.5% of its maximum throughput.
 * That isn't a typo.  It really is that slow.
 *
 * We can't even work around this stupidity by talking to the host
 * controller abstraction directly, because an identical limitation
 * exists in the EFI_USB2_HC_PROTOCOL.
 *
 * Unless you derive therapeutic value from watching download progress
 * indicators lethargically creep through every single integer from 0
 * to 100, you should use iPXE's native USB host controller drivers
 * instead.  (Or just upgrade from UEFI to "legacy" BIOS, which will
 * produce a similar speed increase.)
 *
 *
 * For added excitement, the EFI_USB_IO_PROTOCOL makes the
 * (demonstrably incorrect) assumption that a USB driver needs to
 * attach to exactly one interface within a USB device, and provides a
 * helper method to retrieve "the" interface descriptor.  Since pretty
 * much every USB network device requires binding to a pair of
 * control+data interfaces, this aspect of EFI_USB_IO_PROTOCOL is of
 * no use to us.
 *
 * We have our own existing code for reading USB descriptors, so we
 * don't actually care that the UsbGetInterfaceDescriptor() method
 * provided by EFI_USB_IO_PROTOCOL is useless for network devices.  We
 * can read the descriptors ourselves (via UsbControlTransfer()) and
 * get all of the information we need this way.  We can even work
 * around the fact that EFI_USB_IO_PROTOCOL provides separate handles
 * for each of the two interfaces comprising our network device.
 *
 * However, if we discover that we need to select an alternative
 * device configuration (e.g. for devices exposing both RNDIS and
 * ECM), then all hell breaks loose.  EFI_USB_IO_PROTOCOL starts to
 * panic because its cached interface and endpoint descriptors will no
 * longer be valid.  As mentioned above, the cached descriptors are
 * useless for network devices anyway so we _really_ don't care about
 * this, but EFI_USB_IO_PROTOCOL certainly cares.  It prints out a
 * manic warning message containing no fewer than six exclamation
 * marks and then literally commits seppuku in the middle of the
 * UsbControlTransfer() method by attempting to uninstall itself.
 * Quite how the caller is supposed to react when asked to stop using
 * the EFI_USB_IO_PROTOCOL instance while in the middle of an
 * uninterruptible call to said instance is left as an exercise for
 * the interested reader.
 *
 * There is no sensible way to work around this, so we just
 * preemptively fail if asked to change the device configuration, on
 * the basis that reporting a sarcastic error message is often
 * preferable to jumping through a NULL pointer and crashing the
 * system.
 */

/* Disambiguate the various error causes */
#define ENOTSUP_MORONIC_SPECIFICATION					\
	__einfo_error ( EINFO_ENOTSUP_MORONIC_SPECIFICATION )
#define EINFO_ENOTSUP_MORONIC_SPECIFICATION				\
	__einfo_uniqify ( EINFO_ENOTSUP, 0x01,				\
			  "EFI_USB_IO_PROTOCOL was designed by morons" )

/******************************************************************************
 *
 * Device model
 *
 ******************************************************************************
 */

/**
 * Determine endpoint interface number
 *
 * @v usbio		USB I/O device
 * @v ep		USB Endpoint
 * @ret interface	Interface number, or negative error
 */
static int usbio_interface ( struct usbio_device *usbio,
			     struct usb_endpoint *ep ) {
	EFI_HANDLE handle = usbio->handle;
	struct usb_device *usb = ep->usb;
	struct usb_configuration_descriptor *config;
	struct usb_interface_descriptor *interface;
	struct usb_endpoint_descriptor *endpoint;
	struct usb_function *func;
	unsigned int i;

	/* The control endpoint is not part of a described interface */
	if ( ep->address == USB_EP0_ADDRESS )
		return 0;

	/* Iterate over all interface descriptors looking for a match */
	config = usbio->config;
	for_each_config_descriptor ( interface, config ) {

		/* Skip non-interface descriptors */
		if ( interface->header.type != USB_INTERFACE_DESCRIPTOR )
			continue;

		/* Iterate over all endpoint descriptors looking for a match */
		for_each_interface_descriptor ( endpoint, config, interface ) {

			/* Skip non-endpoint descriptors */
			if ( endpoint->header.type != USB_ENDPOINT_DESCRIPTOR )
				continue;

			/* Check endpoint address */
			if ( endpoint->endpoint != ep->address )
				continue;

			/* Check interface belongs to this function */
			list_for_each_entry ( func, &usb->functions, list ) {

				/* Skip non-matching functions */
				if ( func->interface[0] != usbio->first )
					continue;

				/* Iterate over all interfaces for a match */
				for ( i = 0 ; i < func->desc.count ; i++ ) {
					if ( interface->interface ==
					     func->interface[i] )
						return interface->interface;
				}
			}
		}
	}

	DBGC ( usbio, "USBIO %s cannot find interface for %s",
	       efi_handle_name ( handle ), usb_endpoint_name ( ep ) );
	return -ENOENT;
}

/**
 * Open USB I/O interface
 *
 * @v usbio		USB I/O device
 * @v interface		Interface number
 * @ret rc		Return status code
 */
static int usbio_open ( struct usbio_device *usbio, unsigned int interface ) {
	EFI_BOOT_SERVICES *bs = efi_systab->BootServices;
	EFI_HANDLE handle = usbio->handle;
	struct usbio_interface *intf = &usbio->interface[interface];
	EFI_DEVICE_PATH_PROTOCOL *path;
	EFI_DEVICE_PATH_PROTOCOL *end;
	USB_DEVICE_PATH *usbpath;
	union {
		void *interface;
		EFI_USB_IO_PROTOCOL *io;
	} u;
	EFI_STATUS efirc;
	int rc;

	/* Sanity check */
	assert ( interface < usbio->config->interfaces );

	/* If interface is already open, just increment the usage count */
	if ( intf->count ) {
		intf->count++;
		return 0;
	}

	/* Construct device path for this interface */
	path = usbio->path;
	usbpath = usbio->usbpath;
	usbpath->InterfaceNumber = interface;
	end = efi_devpath_end ( path );

	/* Locate handle for this endpoint's interface */
	if ( ( efirc = bs->LocateDevicePath ( &efi_usb_io_protocol_guid, &path,
					      &intf->handle ) ) != 0 ) {
		rc = -EEFI ( efirc );
		DBGC ( usbio, "USBIO %s could not locate ",
		       efi_handle_name ( handle ) );
		DBGC ( usbio, "%s: %s\n",
		       efi_devpath_text ( usbio->path ), strerror ( rc ) );
		return rc;
	}

	/* Check that expected path was located */
	if ( path != end ) {
		DBGC ( usbio, "USBIO %s located incomplete ",
		       efi_handle_name ( handle ) );
		DBGC ( usbio, "%s\n", efi_handle_name ( intf->handle ) );
		return -EXDEV;
	}

	/* Open USB I/O protocol on this handle */
	if ( ( efirc = bs->OpenProtocol ( intf->handle,
					  &efi_usb_io_protocol_guid,
					  &u.interface, efi_image_handle,
					  intf->handle,
					  ( EFI_OPEN_PROTOCOL_BY_DRIVER |
					    EFI_OPEN_PROTOCOL_EXCLUSIVE )))!=0){
		rc = -EEFI ( efirc );
		DBGC ( usbio, "USBIO %s cannot open ",
		       efi_handle_name ( handle ) );
		DBGC ( usbio, "%s: %s\n",
		       efi_handle_name ( intf->handle ), strerror ( rc ) );
		DBGC_EFI_OPENERS ( usbio, intf->handle,
				   &efi_usb_io_protocol_guid );
		return rc;
	}
	intf->io = u.io;

	/* Increment usage count */
	intf->count++;

	return 0;
}

/**
 * Close USB I/O interface
 *
 * @v usbio		USB I/O device
 * @v interface		Interface number
 */
static void usbio_close ( struct usbio_device *usbio, unsigned int interface ) {
	EFI_BOOT_SERVICES *bs = efi_systab->BootServices;
	struct usbio_interface *intf = &usbio->interface[interface];

	/* Sanity checks */
	assert ( interface < usbio->config->interfaces );
	assert ( intf->count > 0 );

	/* Decrement usage count */
	intf->count--;

	/* Do nothing if interface is still in use */
	if ( intf->count )
		return;

	/* Close USB I/O protocol */
	bs->CloseProtocol ( intf->handle, &efi_usb_io_protocol_guid,
			    efi_image_handle, intf->handle );
}

/******************************************************************************
 *
 * Control endpoints
 *
 ******************************************************************************
 */

/**
 * Open control endpoint
 *
 * @v endpoint		Endpoint
 * @ret rc		Return status code
 */
static int usbio_control_open ( struct usbio_endpoint *endpoint __unused ) {

	/* Nothing to do */
	return 0;
}

/**
 * Close control endpoint
 *
 * @v endpoint		Endpoint
 */
static void usbio_control_close ( struct usbio_endpoint *endpoint __unused ) {

	/* Nothing to do */
}

/**
 * Poll control endpoint
 *
 * @v endpoint		Endpoint
 */
static void usbio_control_poll ( struct usbio_endpoint *endpoint ) {
	struct usbio_device *usbio = endpoint->usbio;
	struct usb_endpoint *ep = endpoint->ep;
	EFI_HANDLE handle = usbio->handle;
	EFI_USB_IO_PROTOCOL *io;
	union {
		struct usb_setup_packet setup;
		EFI_USB_DEVICE_REQUEST efi;
	} *msg;
	EFI_USB_DATA_DIRECTION direction;
	struct io_buffer *iobuf;
	unsigned int index;
	unsigned int flags;
	unsigned int recipient;
	unsigned int interface;
	uint16_t request;
	void *data;
	size_t len;
	UINT32 status;
	EFI_STATUS efirc;
	int rc;

	/* Do nothing if ring is empty */
	if ( endpoint->cons == endpoint->prod )
		return;

	/* Consume next transfer */
	index = ( endpoint->cons++ % USBIO_RING_COUNT );
	iobuf = endpoint->iobuf[index];
	flags = endpoint->flags[index];

	/* Sanity check */
	if ( ! ( flags & USBIO_MESSAGE ) ) {
		DBGC ( usbio, "USBIO %s %s non-message transfer\n",
		       efi_handle_name ( handle ), usb_endpoint_name ( ep ) );
		rc = -ENOTSUP;
		goto err_not_message;
	}

	/* Construct transfer */
	msg = iob_push ( iobuf, sizeof ( *msg ) );
	iob_pull ( iobuf, sizeof ( *msg ) );
	request = le16_to_cpu ( msg->setup.request );
	len = iob_len ( iobuf );
	if ( len ) {
		data = iobuf->data;
		direction = ( ( request & USB_DIR_IN ) ?
			      EfiUsbDataIn : EfiUsbDataOut );
	} else {
		data = NULL;
		direction = EfiUsbNoData;
	}

	/* Determine interface for this transfer */
	recipient = ( request & USB_RECIP_MASK );
	if ( recipient == USB_RECIP_INTERFACE ) {
		/* Recipient is an interface: use interface number directly */
		interface = le16_to_cpu ( msg->setup.index );
	} else {
		/* Route all other requests through the first interface */
		interface = 0;
	}

	/* Open interface */
	if ( ( rc = usbio_open ( usbio, interface ) ) != 0 )
		goto err_open;
	io = usbio->interface[interface].io;

	/* Due to the design of EFI_USB_IO_PROTOCOL, attempting to set
	 * the configuration to a non-default value is basically a
	 * self-destruct button.
	 */
	if ( ( request == USB_SET_CONFIGURATION ) &&
	     ( le16_to_cpu ( msg->setup.value ) != usbio->config->config ) ) {
		rc = -ENOTSUP_MORONIC_SPECIFICATION;
		DBGC ( usbio, "USBIO %s cannot change configuration: %s\n",
		       efi_handle_name ( handle ), strerror ( rc ) );
		goto err_moronic_specification;
	}

	/* Submit transfer */
	if ( ( efirc = io->UsbControlTransfer ( io, &msg->efi, direction, 0,
						data, len, &status ) ) != 0 ) {
		rc = -EEFI ( efirc );
		DBGC ( usbio, "USBIO %s %s could not submit control transfer ",
		       efi_handle_name ( handle ), usb_endpoint_name ( ep ) );
		DBGC ( usbio, "via %s: %s (status %04x)\n",
		       efi_handle_name ( usbio->interface[interface].handle ),
		       strerror ( rc ), status );
		goto err_transfer;
	}

	/* Close interface */
	usbio_close ( usbio, interface );

	/* Complete transfer */
	usb_complete ( ep, iobuf );

	return;

 err_transfer:
 err_moronic_specification:
	usbio_close ( usbio, interface );
 err_open:
 err_not_message:
	usb_complete_err ( ep, iobuf, rc );
}

/** Control endpoint operations */
static struct usbio_operations usbio_control_operations = {
	.open	= usbio_control_open,
	.close	= usbio_control_close,
	.poll	= usbio_control_poll,
};

/******************************************************************************
 *
 * Bulk IN endpoints
 *
 ******************************************************************************
 */

/**
 * Open bulk IN endpoint
 *
 * @v endpoint		Endpoint
 * @ret rc		Return status code
 */
static int usbio_bulk_in_open ( struct usbio_endpoint *endpoint __unused ) {

	/* Nothing to do */
	return 0;
}

/**
 * Close bulk IN endpoint
 *
 * @v endpoint		Endpoint
 */
static void usbio_bulk_in_close ( struct usbio_endpoint *endpoint __unused ) {

	/* Nothing to do */
}

/**
 * Poll bulk IN endpoint
 *
 * @v endpoint		Endpoint
 */
static void usbio_bulk_in_poll ( struct usbio_endpoint *endpoint ) {
	struct usbio_device *usbio = endpoint->usbio;
	struct usb_endpoint *ep = endpoint->ep;
	EFI_USB_IO_PROTOCOL *io = endpoint->io;
	EFI_HANDLE handle = usbio->handle;
	struct io_buffer *iobuf;
	unsigned int index;
	UINTN len;
	UINT32 status;
	EFI_STATUS efirc;
	int rc;

	/* Do nothing if ring is empty */
	if ( endpoint->cons == endpoint->prod )
		return;

	/* Attempt (but do not yet consume) next transfer */
	index = ( endpoint->cons % USBIO_RING_COUNT );
	iobuf = endpoint->iobuf[index];

	/* Construct transfer */
	len = iob_len ( iobuf );

	/* Upon being turned on, the EFI_USB_IO_PROTOCOL did nothing
	 * for several minutes before firing a small ARP packet a few
	 * millimetres into the ether.
	 */
	efirc = io->UsbBulkTransfer ( io, ep->address, iobuf->data,
				      &len, 1, &status );
	if ( efirc == EFI_TIMEOUT )
		return;

	/* Consume transfer */
	endpoint->cons++;

	/* Check for failure */
	if ( efirc != 0 ) {
		rc = -EEFI ( efirc );
		DBGC2 ( usbio, "USBIO %s %s could not submit bulk IN transfer: "
			"%s (status %04x)\n", efi_handle_name ( handle ),
			usb_endpoint_name ( ep ), strerror ( rc ), status );
		usb_complete_err ( ep, iobuf, rc );
		return;
	}

	/* Update length */
	iob_put ( iobuf, ( len - iob_len ( iobuf ) ) );

	/* Complete transfer */
	usb_complete ( ep, iobuf );
}

/** Bulk endpoint operations */
static struct usbio_operations usbio_bulk_in_operations = {
	.open	= usbio_bulk_in_open,
	.close	= usbio_bulk_in_close,
	.poll	= usbio_bulk_in_poll,
};

/******************************************************************************
 *
 * Bulk OUT endpoints
 *
 ******************************************************************************
 */

/**
 * Open bulk OUT endpoint
 *
 * @v endpoint		Endpoint
 * @ret rc		Return status code
 */
static int usbio_bulk_out_open ( struct usbio_endpoint *endpoint __unused ) {

	/* Nothing to do */
	return 0;
}

/**
 * Close bulk OUT endpoint
 *
 * @v endpoint		Endpoint
 */
static void usbio_bulk_out_close ( struct usbio_endpoint *endpoint __unused ) {

	/* Nothing to do */
}

/**
 * Poll bulk OUT endpoint
 *
 * @v endpoint		Endpoint
 */
static void usbio_bulk_out_poll ( struct usbio_endpoint *endpoint ) {
	struct usbio_device *usbio = endpoint->usbio;
	struct usb_endpoint *ep = endpoint->ep;
	EFI_USB_IO_PROTOCOL *io = endpoint->io;
	EFI_HANDLE handle = usbio->handle;
	struct io_buffer *iobuf;
	unsigned int index;
	unsigned int flags;
	UINTN len;
	UINT32 status;
	EFI_STATUS efirc;
	int rc;

	/* Do nothing if ring is empty */
	if ( endpoint->cons == endpoint->prod )
		return;

	/* Consume next transfer */
	index = ( endpoint->cons++ % USBIO_RING_COUNT );
	iobuf = endpoint->iobuf[index];
	flags = endpoint->flags[index];

	/* Construct transfer */
	len = iob_len ( iobuf );

	/* Submit transfer */
	if ( ( efirc = io->UsbBulkTransfer ( io, ep->address, iobuf->data,
					     &len, 0, &status ) ) != 0 ) {
		rc = -EEFI ( efirc );
		DBGC ( usbio, "USBIO %s %s could not submit bulk OUT transfer: "
		       "%s (status %04x)\n", efi_handle_name ( handle ),
		       usb_endpoint_name ( ep ), strerror ( rc ), status );
		goto err;
	}

	/* Update length */
	iob_put ( iobuf, ( len - iob_len ( iobuf ) ) );

	/* Submit zero-length transfer if required */
	len = 0;
	if ( ( flags & USBIO_ZLEN ) &&
	     ( efirc = io->UsbBulkTransfer ( io, ep->address, NULL, &len, 0,
					     &status ) ) != 0 ) {
		rc = -EEFI ( efirc );
		DBGC ( usbio, "USBIO %s %s could not submit zero-length "
		       "transfer: %s (status %04x)\n",
		       efi_handle_name ( handle ), usb_endpoint_name ( ep ),
		       strerror ( rc ), status );
		goto err;
	}

	/* Complete transfer */
	usb_complete ( ep, iobuf );

	return;

 err:
	usb_complete_err ( ep, iobuf, rc );
}

/** Bulk endpoint operations */
static struct usbio_operations usbio_bulk_out_operations = {
	.open	= usbio_bulk_out_open,
	.close	= usbio_bulk_out_close,
	.poll	= usbio_bulk_out_poll,
};

/******************************************************************************
 *
 * Interrupt endpoints
 *
 ******************************************************************************
 *
 * The EFI_USB_IO_PROTOCOL provides two ways to interact with
 * interrupt endpoints, neither of which naturally model the hardware
 * interaction.  The UsbSyncInterruptTransfer() method allows imposes
 * a 1ms overhead for every interrupt transfer (which could result in
 * up to a 50% decrease in overall throughput for the device).  The
 * UsbAsyncInterruptTransfer() method provides no way for us to
 * prevent transfers when no I/O buffers are available.
 *
 * We work around this design by utilising a small, fixed ring buffer
 * into which the interrupt callback delivers the data.  This aims to
 * provide buffer space even if no I/O buffers have yet been enqueued.
 * The scheme is not guaranteed since the fixed ring buffer may also
 * become full.  However:
 *
 *   - devices which send a constant stream of interrupts (and which
 *     therefore might exhaust the fixed ring buffer) tend to be
 *     responding to every interrupt request, and can tolerate lost
 *     packets, and
 *
 *   - devices which cannot tolerate lost interrupt packets tend to send
 *     only a few small messages.
 *
 * The scheme should therefore work in practice.
 */

/**
 * Interrupt endpoint callback
 *
 * @v data		Received data
 * @v len		Length of received data
 * @v context		Callback context
 * @v status		Transfer status
 * @ret efirc		EFI status code
 */
static EFI_STATUS EFIAPI usbio_interrupt_callback ( VOID *data, UINTN len,
						    VOID *context,
						    UINT32 status ) {
	struct usbio_interrupt_ring *intr = context;
	struct usbio_endpoint *endpoint = intr->endpoint;
	struct usbio_device *usbio = endpoint->usbio;
	struct usb_endpoint *ep = endpoint->ep;
	EFI_HANDLE handle = usbio->handle;
	unsigned int fill;
	unsigned int index;

	/* Sanity check */
	assert ( len <= ep->mtu );

	/* Do nothing if ring is empty */
	fill = ( intr->prod - intr->cons );
	if ( fill >= USBIO_INTR_COUNT ) {
		DBGC ( usbio, "USBIO %s %s dropped interrupt completion\n",
		       efi_handle_name ( handle ), usb_endpoint_name ( ep ) );
		return 0;
	}

	/* Do nothing if transfer was unsuccessful */
	if ( status != 0 ) {
		DBGC ( usbio, "USBIO %s %s interrupt completion status %04x\n",
		       efi_handle_name ( handle ), usb_endpoint_name ( ep ),
		       status );
		return 0; /* Unclear what failure actually means here */
	}

	/* Copy data to buffer and increment producer counter */
	index = ( intr->prod % USBIO_INTR_COUNT );
	memcpy ( intr->data[index], data, len );
	intr->len[index] = len;
	intr->prod++;

	return 0;
}

/**
 * Open interrupt endpoint
 *
 * @v endpoint		Endpoint
 * @ret rc		Return status code
 */
static int usbio_interrupt_open ( struct usbio_endpoint *endpoint ) {
	struct usbio_device *usbio = endpoint->usbio;
	struct usbio_interrupt_ring *intr;
	struct usb_endpoint *ep = endpoint->ep;
	EFI_USB_IO_PROTOCOL *io = endpoint->io;
	EFI_HANDLE handle = usbio->handle;
	unsigned int interval;
	unsigned int i;
	void *data;
	EFI_STATUS efirc;
	int rc;

	/* Allocate interrupt ring buffer */
	intr = zalloc ( sizeof ( *intr ) + ( USBIO_INTR_COUNT * ep->mtu ) );
	if ( ! intr ) {
		rc = -ENOMEM;
		goto err_alloc;
	}
	endpoint->intr = intr;
	intr->endpoint = endpoint;
	data = ( ( ( void * ) intr ) + sizeof ( *intr ) );
	for ( i = 0 ; i < USBIO_INTR_COUNT ; i++ ) {
		intr->data[i] = data;
		data += ep->mtu;
	}

	/* Determine polling interval */
	interval = ( ep->interval >> 3 /* microframes -> milliseconds */ );
	if ( ! interval )
		interval = 1; /* May not be zero */

	/* Add to periodic schedule */
	if ( ( efirc = io->UsbAsyncInterruptTransfer ( io, ep->address, TRUE,
						       interval, ep->mtu,
						       usbio_interrupt_callback,
						       intr ) ) != 0 ) {
		rc = -EEFI ( efirc );
		DBGC ( usbio, "USBIO %s %s could not schedule interrupt "
		       "transfer: %s\n", efi_handle_name ( handle ),
		       usb_endpoint_name ( ep ), strerror ( rc ) );
		goto err_schedule;
	}

	return 0;

	io->UsbAsyncInterruptTransfer ( io, ep->address, FALSE, 0, 0,
					NULL, NULL );
 err_schedule:
	free ( intr );
 err_alloc:
	return rc;
}

/**
 * Close interrupt endpoint
 *
 * @v endpoint		Endpoint
 */
static void usbio_interrupt_close ( struct usbio_endpoint *endpoint ) {
	struct usb_endpoint *ep = endpoint->ep;
	EFI_USB_IO_PROTOCOL *io = endpoint->io;

	/* Remove from periodic schedule */
	io->UsbAsyncInterruptTransfer ( io, ep->address, FALSE, 0, 0,
					NULL, NULL );

	/* Free interrupt ring buffer */
	free ( endpoint->intr );
}

/**
 * Poll interrupt endpoint
 *
 * @v endpoint		Endpoint
 */
static void usbio_interrupt_poll ( struct usbio_endpoint *endpoint ) {
	struct usbio_interrupt_ring *intr = endpoint->intr;
	struct usb_endpoint *ep = endpoint->ep;
	struct io_buffer *iobuf;
	unsigned int index;
	unsigned int intr_index;
	size_t len;

	/* Do nothing if ring is empty */
	if ( endpoint->cons == endpoint->prod )
		return;

	/* Do nothing if interrupt ring is empty */
	if ( intr->cons == intr->prod )
		return;

	/* Consume next transfer */
	index = ( endpoint->cons++ % USBIO_RING_COUNT );
	iobuf = endpoint->iobuf[index];

	/* Populate I/O buffer */
	intr_index = ( intr->cons++ % USBIO_INTR_COUNT );
	len = intr->len[intr_index];
	assert ( len <= iob_len ( iobuf ) );
	iob_put ( iobuf, ( len - iob_len ( iobuf ) ) );
	memcpy ( iobuf->data, intr->data[intr_index], len );

	/* Complete transfer */
	usb_complete ( ep, iobuf );
}

/** Interrupt endpoint operations */
static struct usbio_operations usbio_interrupt_operations = {
	.open	= usbio_interrupt_open,
	.close	= usbio_interrupt_close,
	.poll	= usbio_interrupt_poll,
};

/******************************************************************************
 *
 * Endpoint operations
 *
 ******************************************************************************
 */

/**
 * Open endpoint
 *
 * @v ep		USB endpoint
 * @ret rc		Return status code
 */
static int usbio_endpoint_open ( struct usb_endpoint *ep ) {
	struct usb_bus *bus = ep->usb->port->hub->bus;
	struct usbio_device *usbio = usb_bus_get_hostdata ( bus );
	struct usbio_endpoint *endpoint;
	EFI_HANDLE handle = usbio->handle;
	unsigned int attr = ( ep->attributes & USB_ENDPOINT_ATTR_TYPE_MASK );
	int interface;
	int rc;

	/* Allocate and initialise structure */
	endpoint = zalloc ( sizeof ( *endpoint ) );
	if ( ! endpoint ) {
		rc = -ENOMEM;
		goto err_alloc;
	}
	usb_endpoint_set_hostdata ( ep, endpoint );
	endpoint->usbio = usbio;
	endpoint->ep = ep;

	/* Identify endpoint operations */
	if ( attr == USB_ENDPOINT_ATTR_CONTROL ) {
		endpoint->op = &usbio_control_operations;
	} else if ( attr == USB_ENDPOINT_ATTR_BULK ) {
		endpoint->op = ( ( ep->address & USB_DIR_IN ) ?
				 &usbio_bulk_in_operations :
				 &usbio_bulk_out_operations );
	} else if ( attr == USB_ENDPOINT_ATTR_INTERRUPT ) {
		endpoint->op = &usbio_interrupt_operations;
	} else {
		rc = -ENOTSUP;
		goto err_operations;
	}

	/* Identify interface for this endpoint */
	interface = usbio_interface ( usbio, ep );
	if ( interface < 0 ) {
		rc = interface;
		goto err_interface;
	}
	endpoint->interface = interface;

	/* Open interface */
	if ( ( rc = usbio_open ( usbio, interface ) ) != 0 )
		goto err_open_interface;
	endpoint->handle = usbio->interface[interface].handle;
	endpoint->io = usbio->interface[interface].io;
	DBGC ( usbio, "USBIO %s %s using ",
	       efi_handle_name ( handle ), usb_endpoint_name ( ep ) );
	DBGC ( usbio, "%s\n", efi_handle_name ( endpoint->handle ) );

	/* Open endpoint */
	if ( ( rc = endpoint->op->open ( endpoint ) ) != 0 )
		goto err_open_endpoint;

	/* Add to list of endpoints */
	list_add_tail ( &endpoint->list, &usbio->endpoints );

	return 0;

	list_del ( &endpoint->list );
	endpoint->op->close ( endpoint );
 err_open_endpoint:
	usbio_close ( usbio, interface );
 err_open_interface:
 err_interface:
 err_operations:
	free ( endpoint );
 err_alloc:
	return rc;
}

/**
 * Close endpoint
 *
 * @v ep		USB endpoint
 */
static void usbio_endpoint_close ( struct usb_endpoint *ep ) {
	struct usbio_endpoint *endpoint = usb_endpoint_get_hostdata ( ep );
	struct usbio_device *usbio = endpoint->usbio;
	struct io_buffer *iobuf;
	unsigned int index;

	/* Remove from list of endpoints */
	list_del ( &endpoint->list );

	/* Close endpoint */
	endpoint->op->close ( endpoint );

	/* Close interface */
	usbio_close ( usbio, endpoint->interface );

	/* Cancel any incomplete transfers */
	while ( endpoint->cons != endpoint->prod ) {
		index = ( endpoint->cons++ % USBIO_RING_COUNT );
		iobuf = endpoint->iobuf[index];
		usb_complete_err ( ep, iobuf, -ECANCELED );
	}

	/* Free endpoint */
	free ( endpoint );
}

/**
 * Reset endpoint
 *
 * @v ep		USB endpoint
 * @ret rc		Return status code
 */
static int usbio_endpoint_reset ( struct usb_endpoint *ep __unused ) {

	/* Nothing to do */
	return 0;
}

/**
 * Update MTU
 *
 * @v ep		USB endpoint
 * @ret rc		Return status code
 */
static int usbio_endpoint_mtu ( struct usb_endpoint *ep __unused ) {

	/* Nothing to do */
	return 0;
}

/**
 * Enqueue transfer
 *
 * @v ep		USB endpoint
 * @v iobuf		I/O buffer
 * @v flags		Transfer flags
 * @ret rc		Return status code
 */
static int usbio_endpoint_enqueue ( struct usb_endpoint *ep,
				    struct io_buffer *iobuf,
				    unsigned int flags ) {
	struct usbio_endpoint *endpoint = usb_endpoint_get_hostdata ( ep );
	unsigned int fill;
	unsigned int index;

	/* Fail if transfer ring is full */
	fill = ( endpoint->prod - endpoint->cons );
	if ( fill >= USBIO_RING_COUNT )
		return -ENOBUFS;

	/* Add to ring */
	index = ( endpoint->prod++ % USBIO_RING_COUNT );
	endpoint->iobuf[index] = iobuf;
	endpoint->flags[index] = flags;

	return 0;
}

/**
 * Enqueue message transfer
 *
 * @v ep		USB endpoint
 * @v iobuf		I/O buffer
 * @ret rc		Return status code
 */
static int usbio_endpoint_message ( struct usb_endpoint *ep,
				    struct io_buffer *iobuf ) {
	struct usb_setup_packet *setup;

	/* Adjust I/O buffer to start of data payload */
	assert ( iob_len ( iobuf ) >= sizeof ( *setup ) );
	iob_pull ( iobuf, sizeof ( *setup ) );

	/* Enqueue transfer */
	return usbio_endpoint_enqueue ( ep, iobuf, USBIO_MESSAGE );
}

/**
 * Enqueue stream transfer
 *
 * @v ep		USB endpoint
 * @v iobuf		I/O buffer
 * @v zlp		Append a zero-length packet
 * @ret rc		Return status code
 */
static int usbio_endpoint_stream ( struct usb_endpoint *ep,
				   struct io_buffer *iobuf, int zlp ) {

	/* Enqueue transfer */
	return usbio_endpoint_enqueue ( ep, iobuf, ( zlp ? USBIO_ZLEN : 0 ) );
}

/**
 * Poll for completions
 *
 * @v endpoint		Endpoint
 */
static void usbio_endpoint_poll ( struct usbio_endpoint *endpoint ) {

	/* Poll endpoint */
	endpoint->op->poll ( endpoint );
}

/******************************************************************************
 *
 * Device operations
 *
 ******************************************************************************
 */

/**
 * Open device
 *
 * @v usb		USB device
 * @ret rc		Return status code
 */
static int usbio_device_open ( struct usb_device *usb ) {
	struct usbio_device *usbio =
		usb_bus_get_hostdata ( usb->port->hub->bus );

	usb_set_hostdata ( usb, usbio );
	return 0;
}

/**
 * Close device
 *
 * @v usb		USB device
 */
static void usbio_device_close ( struct usb_device *usb __unused ) {

	/* Nothing to do */
}

/**
 * Assign device address
 *
 * @v usb		USB device
 * @ret rc		Return status code
 */
static int usbio_device_address ( struct usb_device *usb __unused ) {

	/* Nothing to do */
	return 0;
}

/******************************************************************************
 *
 * Hub operations
 *
 ******************************************************************************
 */

/**
 * Open hub
 *
 * @v hub		USB hub
 * @ret rc		Return status code
 */
static int usbio_hub_open ( struct usb_hub *hub ) {

	/* Disallow non-root hubs */
	if ( hub->usb )
		return -ENOTSUP;

	/* Nothing to do */
	return 0;
}

/**
 * Close hub
 *
 * @v hub		USB hub
 */
static void usbio_hub_close ( struct usb_hub *hub __unused ) {

	/* Nothing to do */
}

/******************************************************************************
 *
 * Root hub operations
 *
 ******************************************************************************
 */

/**
 * Open root hub
 *
 * @v hub		USB hub
 * @ret rc		Return status code
 */
static int usbio_root_open ( struct usb_hub *hub __unused ) {

	/* Nothing to do */
	return 0;
}

/**
 * Close root hub
 *
 * @v hub		USB hub
 */
static void usbio_root_close ( struct usb_hub *hub __unused ) {

	/* Nothing to do */
}

/**
 * Enable port
 *
 * @v hub		USB hub
 * @v port		USB port
 * @ret rc		Return status code
 */
static int usbio_root_enable ( struct usb_hub *hub __unused,
			       struct usb_port *port __unused ) {

	/* Nothing to do */
	return 0;
}

/**
 * Disable port
 *
 * @v hub		USB hub
 * @v port		USB port
 * @ret rc		Return status code
 */
static int usbio_root_disable ( struct usb_hub *hub __unused,
				struct usb_port *port __unused ) {

	/* Nothing to do */
	return 0;
}

/**
 * Update root hub port speed
 *
 * @v hub		USB hub
 * @v port		USB port
 * @ret rc		Return status code
 */
static int usbio_root_speed ( struct usb_hub *hub __unused,
			      struct usb_port *port ) {

	/* Not actually exposed via EFI_USB_IO_PROTOCOL */
	port->speed = USB_SPEED_HIGH;
	return 0;
}

/**
 * Clear transaction translator buffer
 *
 * @v hub		USB hub
 * @v port		USB port
 * @v ep		USB endpoint
 * @ret rc		Return status code
 */
static int usbio_root_clear_tt ( struct usb_hub *hub __unused,
				 struct usb_port *port __unused,
				 struct usb_endpoint *ep __unused ) {

	/* Should never be called; this is a root hub */
	return -ENOTSUP;
}

/******************************************************************************
 *
 * Bus operations
 *
 ******************************************************************************
 */

/**
 * Open USB bus
 *
 * @v bus		USB bus
 * @ret rc		Return status code
 */
static int usbio_bus_open ( struct usb_bus *bus __unused ) {

	/* Nothing to do */
	return 0;
}

/**
 * Close USB bus
 *
 * @v bus		USB bus
 */
static void usbio_bus_close ( struct usb_bus *bus __unused ) {

	/* Nothing to do */
}

/**
 * Poll USB bus
 *
 * @v bus		USB bus
 */
static void usbio_bus_poll ( struct usb_bus *bus ) {
	struct usbio_device *usbio = usb_bus_get_hostdata ( bus );
	struct usbio_endpoint *endpoint;

	/* Poll all endpoints.  We trust that completion handlers are
	 * minimal and will not do anything that could plausibly
	 * affect the endpoint list itself.
	 */
	list_for_each_entry ( endpoint, &usbio->endpoints, list )
		usbio_endpoint_poll ( endpoint );
}

/******************************************************************************
 *
 * EFI driver interface
 *
 ******************************************************************************
 */

/** USB I/O host controller driver operations */
static struct usb_host_operations usbio_operations = {
	.endpoint = {
		.open = usbio_endpoint_open,
		.close = usbio_endpoint_close,
		.reset = usbio_endpoint_reset,
		.mtu = usbio_endpoint_mtu,
		.message = usbio_endpoint_message,
		.stream = usbio_endpoint_stream,
	},
	.device = {
		.open = usbio_device_open,
		.close = usbio_device_close,
		.address = usbio_device_address,
	},
	.bus = {
		.open = usbio_bus_open,
		.close = usbio_bus_close,
		.poll = usbio_bus_poll,
	},
	.hub = {
		.open = usbio_hub_open,
		.close = usbio_hub_close,
	},
	.root = {
		.open = usbio_root_open,
		.close = usbio_root_close,
		.enable = usbio_root_enable,
		.disable = usbio_root_disable,
		.speed = usbio_root_speed,
		.clear_tt = usbio_root_clear_tt,
	},
};

/**
 * Check to see if driver supports a device
 *
 * @v handle		EFI device handle
 * @ret rc		Return status code
 */
static int usbio_supported ( EFI_HANDLE handle ) {
	EFI_BOOT_SERVICES *bs = efi_systab->BootServices;
	EFI_USB_DEVICE_DESCRIPTOR device;
	EFI_USB_INTERFACE_DESCRIPTOR interface;
	struct usb_function_descriptor desc;
	struct usb_driver *driver;
	struct usb_device_id *id;
	union {
		void *interface;
		EFI_USB_IO_PROTOCOL *io;
	} usb;
	EFI_STATUS efirc;
	int rc;

	/* Get protocol */
	if ( ( efirc = bs->OpenProtocol ( handle, &efi_usb_io_protocol_guid,
					  &usb.interface, efi_image_handle,
					  handle,
					  EFI_OPEN_PROTOCOL_GET_PROTOCOL ))!=0){
		rc = -EEFI ( efirc );
		DBGCP ( handle, "USB %s is not a USB device\n",
			efi_handle_name ( handle ) );
		goto err_open_protocol;
	}

	/* Get device descriptor */
	if ( ( efirc = usb.io->UsbGetDeviceDescriptor ( usb.io,
							&device ) ) != 0 ) {
		rc = -EEFI ( efirc );
		DBGC ( handle, "USB %s could not get device descriptor: "
		       "%s\n", efi_handle_name ( handle ), strerror ( rc ) );
		goto err_get_device_descriptor;
	}
	memset ( &desc, 0, sizeof ( desc ) );
	desc.vendor = device.IdVendor;
	desc.product = device.IdProduct;

	/* Get interface descriptor */
	if ( ( efirc = usb.io->UsbGetInterfaceDescriptor ( usb.io,
							   &interface ) ) !=0){
		rc = -EEFI ( efirc );
		DBGC ( handle, "USB %s could not get interface descriptor: "
		       "%s\n", efi_handle_name ( handle ), strerror ( rc ) );
		goto err_get_interface_descriptor;
	}
	desc.class.class.class = interface.InterfaceClass;
	desc.class.class.subclass = interface.InterfaceSubClass;
	desc.class.class.protocol = interface.InterfaceProtocol;

	/* Look for a driver for this interface */
	driver = usb_find_driver ( &desc, &id );
	if ( ! driver ) {
		rc = -ENOTSUP;
		goto err_unsupported;
	}

	/* Success */
	rc = 0;

 err_unsupported:
 err_get_interface_descriptor:
 err_get_device_descriptor:
	bs->CloseProtocol ( handle, &efi_usb_io_protocol_guid,
			    efi_image_handle, handle );
 err_open_protocol:
	return rc;
}

/**
 * Fetch configuration descriptor
 *
 * @v usbio		USB I/O device
 * @ret rc		Return status code
 */
static int usbio_config ( struct usbio_device *usbio ) {
	EFI_HANDLE handle = usbio->handle;
	EFI_USB_IO_PROTOCOL *io = usbio->io;
	EFI_USB_DEVICE_DESCRIPTOR device;
	EFI_USB_CONFIG_DESCRIPTOR partial;
	union {
		struct usb_setup_packet setup;
		EFI_USB_DEVICE_REQUEST efi;
	} msg;
	UINT32 status;
	size_t len;
	unsigned int count;
	unsigned int value;
	unsigned int i;
	EFI_STATUS efirc;
	int rc;

	/* Get device descriptor */
	if ( ( efirc = io->UsbGetDeviceDescriptor ( io, &device ) ) != 0 ) {
		rc = -EEFI ( efirc );
		DBGC ( usbio, "USB %s could not get device descriptor: "
		       "%s\n", efi_handle_name ( handle ), strerror ( rc ) );
		goto err_get_device_descriptor;
	}
	count = device.NumConfigurations;

	/* Get current partial configuration descriptor */
	if ( ( efirc = io->UsbGetConfigDescriptor ( io, &partial ) ) != 0 ) {
		rc = -EEFI ( efirc );
		DBGC ( usbio, "USB %s could not get partial configuration "
		       "descriptor: %s\n", efi_handle_name ( handle ),
		       strerror ( rc ) );
		goto err_get_configuration_descriptor;
	}
	len = le16_to_cpu ( partial.TotalLength );

	/* Allocate configuration descriptor */
	usbio->config = malloc ( len );
	if ( ! usbio->config ) {
		rc = -ENOMEM;
		goto err_alloc;
	}

	/* There is, naturally, no way to retrieve the entire device
	 * configuration descriptor via EFI_USB_IO_PROTOCOL.  Worse,
	 * there is no way to even retrieve the index of the current
	 * configuration descriptor.  We have to iterate over all
	 * possible configuration descriptors looking for the
	 * descriptor that matches the current configuration value.
	 */
	for ( i = 0 ; i < count ; i++ ) {

		/* Construct request */
		msg.setup.request = cpu_to_le16 ( USB_GET_DESCRIPTOR );
		value = ( ( USB_CONFIGURATION_DESCRIPTOR << 8 ) | i );
		msg.setup.value = cpu_to_le16 ( value );
		msg.setup.index = 0;
		msg.setup.len = cpu_to_le16 ( len );

		/* Get full configuration descriptor */
		if ( ( efirc = io->UsbControlTransfer ( io, &msg.efi,
							EfiUsbDataIn, 0,
							usbio->config, len,
							&status ) ) != 0 ) {
			rc = -EEFI ( efirc );
			DBGC ( usbio, "USB %s could not get configuration %d "
			       "descriptor: %s\n", efi_handle_name ( handle ),
			       i, strerror ( rc ) );
			goto err_control_transfer;
		}

		/* Ignore unless this is the current configuration */
		if ( usbio->config->config != partial.ConfigurationValue )
			continue;

		/* Check length */
		if ( le16_to_cpu ( usbio->config->len ) != len ) {
			DBGC ( usbio, "USB %s configuration descriptor length "
			       "mismatch\n", efi_handle_name ( handle ) );
			rc = -EINVAL;
			goto err_len;
		}

		return 0;
	}

	/* No match found */
	DBGC ( usbio, "USB %s could not find current configuration "
	       "descriptor\n", efi_handle_name ( handle ) );
	rc = -ENOENT;

 err_len:
 err_control_transfer:
	free ( usbio->config );
 err_alloc:
 err_get_configuration_descriptor:
 err_get_device_descriptor:
	return rc;
}

/**
 * Construct device path for opening other interfaces
 *
 * @v usbio		USB I/O device
 * @ret rc		Return status code
 */
static int usbio_path ( struct usbio_device *usbio ) {
	EFI_BOOT_SERVICES *bs = efi_systab->BootServices;
	EFI_HANDLE handle = usbio->handle;
	EFI_DEVICE_PATH_PROTOCOL *path;
	EFI_DEVICE_PATH_PROTOCOL *end;
	USB_DEVICE_PATH *usbpath;
	union {
		void *interface;
		EFI_DEVICE_PATH_PROTOCOL *path;
	} u;
	size_t len;
	EFI_STATUS efirc;
	int rc;

	/* Open device path protocol */
	if ( ( efirc = bs->OpenProtocol ( handle,
					  &efi_device_path_protocol_guid,
					  &u.interface, efi_image_handle,
					  handle,
					  EFI_OPEN_PROTOCOL_GET_PROTOCOL ))!=0){
		rc = -EEFI ( efirc );
		DBGC ( usbio, "USBIO %s cannot open device path protocol: "
		       "%s\n", efi_handle_name ( handle ), strerror ( rc ) );
		goto err_open_protocol;
	}
	path = u.interface;

	/* Locate end of device path and sanity check */
	len = efi_devpath_len ( path );
	if ( len < sizeof ( *usbpath ) ) {
		DBGC ( usbio, "USBIO %s underlength device path\n",
		       efi_handle_name ( handle ) );
		rc = -EINVAL;
		goto err_underlength;
	}
	usbpath = ( ( ( void * ) path ) + len - sizeof ( *usbpath ) );
	if ( ! ( ( usbpath->Header.Type == MESSAGING_DEVICE_PATH ) &&
		 ( usbpath->Header.SubType == MSG_USB_DP ) ) ) {
		DBGC ( usbio, "USBIO %s not a USB device path: ",
		       efi_handle_name ( handle ) );
		DBGC ( usbio, "%s\n", efi_devpath_text ( path ) );
		rc = -EINVAL;
		goto err_non_usb;
	}

	/* Allocate copy of device path */
	usbio->path = malloc ( len + sizeof ( *end ) );
	if ( ! usbio->path ) {
		rc = -ENOMEM;
		goto err_alloc;
	}
	memcpy ( usbio->path, path, ( len + sizeof ( *end ) ) );
	usbio->usbpath = ( ( ( void * ) usbio->path ) + len -
			   sizeof ( *usbpath ) );

	/* Close protocol */
	bs->CloseProtocol ( handle, &efi_device_path_protocol_guid,
			    efi_image_handle, handle );

	return 0;

	free ( usbio->path );
 err_alloc:
 err_non_usb:
 err_underlength:
	bs->CloseProtocol ( handle, &efi_device_path_protocol_guid,
			    efi_image_handle, handle );
 err_open_protocol:
	return rc;
}

/**
 * Construct interface list
 *
 * @v usbio		USB I/O device
 * @ret rc		Return status code
 */
static int usbio_interfaces ( struct usbio_device *usbio ) {
	EFI_HANDLE handle = usbio->handle;
	EFI_USB_IO_PROTOCOL *io = usbio->io;
	EFI_USB_INTERFACE_DESCRIPTOR interface;
	unsigned int first;
	unsigned int count;
	EFI_STATUS efirc;
	int rc;

	/* Get interface descriptor */
	if ( ( efirc = io->UsbGetInterfaceDescriptor ( io, &interface ) ) != 0){
		rc = -EEFI ( efirc );
		DBGC ( usbio, "USB %s could not get interface descriptor: "
		       "%s\n", efi_handle_name ( handle ), strerror ( rc ) );
		goto err_get_interface_descriptor;
	}

	/* Record first interface number */
	first = interface.InterfaceNumber;
	count = usbio->config->interfaces;
	assert ( first < count );
	usbio->first = first;

	/* Allocate interface list */
	usbio->interface = zalloc ( count * sizeof ( usbio->interface[0] ) );
	if ( ! usbio->interface ) {
		rc = -ENOMEM;
		goto err_alloc;
	}

	/* Use already-opened protocol for control transfers and for
	 * the first interface.
	 */
	usbio->interface[0].handle = handle;
	usbio->interface[0].io = io;
	usbio->interface[0].count = 1;
	usbio->interface[first].handle = handle;
	usbio->interface[first].io = io;
	usbio->interface[first].count = 1;

	return 0;

	free ( usbio->interface );
 err_alloc:
 err_get_interface_descriptor:
	return rc;
}

/**
 * Attach driver to device
 *
 * @v efidev		EFI device
 * @ret rc		Return status code
 */
static int usbio_start ( struct efi_device *efidev ) {
	EFI_BOOT_SERVICES *bs = efi_systab->BootServices;
	EFI_HANDLE handle = efidev->device;
	struct usbio_device *usbio;
	struct usb_port *port;
	union {
		void *interface;
		EFI_USB_IO_PROTOCOL *io;
	} u;
	EFI_STATUS efirc;
	int rc;

	/* Allocate and initialise structure */
	usbio = zalloc ( sizeof ( *usbio ) );
	if ( ! usbio ) {
		rc = -ENOMEM;
		goto err_alloc;
	}
	efidev_set_drvdata ( efidev, usbio );
	usbio->handle = handle;
	INIT_LIST_HEAD ( &usbio->endpoints );

	/* Open USB I/O protocol */
	if ( ( efirc = bs->OpenProtocol ( handle, &efi_usb_io_protocol_guid,
					  &u.interface, efi_image_handle,
					  handle,
					  ( EFI_OPEN_PROTOCOL_BY_DRIVER |
					    EFI_OPEN_PROTOCOL_EXCLUSIVE )))!=0){
		rc = -EEFI ( efirc );
		DBGC ( usbio, "USBIO %s cannot open USB I/O protocol: %s\n",
		       efi_handle_name ( handle ), strerror ( rc ) );
		DBGC_EFI_OPENERS ( usbio, handle, &efi_usb_io_protocol_guid );
		goto err_open_usbio;
	}
	usbio->io = u.io;

	/* Describe generic device */
	efi_device_info ( handle, "USB", &usbio->dev );
	usbio->dev.parent = &efidev->dev;
	list_add ( &usbio->dev.siblings, &efidev->dev.children );
	INIT_LIST_HEAD ( &usbio->dev.children );

	/* Fetch configuration descriptor */
	if ( ( rc = usbio_config ( usbio ) ) != 0 )
		goto err_config;

	/* Construct device path */
	if ( ( rc = usbio_path ( usbio ) ) != 0 )
		goto err_path;

	/* Construct interface list */
	if ( ( rc = usbio_interfaces ( usbio ) ) != 0 )
		goto err_interfaces;

	/* Allocate USB bus */
	usbio->bus = alloc_usb_bus ( &usbio->dev, 1 /* single "port" */,
				     USBIO_MTU, &usbio_operations );
	if ( ! usbio->bus ) {
		rc = -ENOMEM;
		goto err_alloc_bus;
	}
	usb_bus_set_hostdata ( usbio->bus, usbio );
	usb_hub_set_drvdata ( usbio->bus->hub, usbio );

	/* Set port protocol */
	port = usb_port ( usbio->bus->hub, 1 );
	port->protocol = USB_PROTO_2_0;

	/* Register USB bus */
	if ( ( rc = register_usb_bus ( usbio->bus ) ) != 0 )
		goto err_register;

	return 0;

	unregister_usb_bus ( usbio->bus );
 err_register:
	free_usb_bus ( usbio->bus );
 err_alloc_bus:
	free ( usbio->interface );
 err_interfaces:
	free ( usbio->path );
 err_path:
	free ( usbio->config );
 err_config:
	list_del ( &usbio->dev.siblings );
	bs->CloseProtocol ( handle, &efi_usb_io_protocol_guid,
			    efi_image_handle, handle );
 err_open_usbio:
	free ( usbio );
 err_alloc:
	return rc;
}

/**
 * Detach driver from device
 *
 * @v efidev		EFI device
 */
static void usbio_stop ( struct efi_device *efidev ) {
	EFI_BOOT_SERVICES *bs = efi_systab->BootServices;
	EFI_HANDLE handle = efidev->device;
	struct usbio_device *usbio = efidev_get_drvdata ( efidev );

	unregister_usb_bus ( usbio->bus );
	free_usb_bus ( usbio->bus );
	free ( usbio->interface );
	free ( usbio->path );
	free ( usbio->config );
	list_del ( &usbio->dev.siblings );
	bs->CloseProtocol ( handle, &efi_usb_io_protocol_guid,
			    efi_image_handle, handle );
	free ( usbio );
}

/** EFI USB I/O driver */
struct efi_driver usbio_driver __efi_driver ( EFI_DRIVER_NORMAL ) = {
	.name = "USBIO",
	.supported = usbio_supported,
	.start = usbio_start,
	.stop = usbio_stop,
};