-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy path__init__.py
More file actions
1758 lines (1634 loc) · 61.4 KB
/
__init__.py
File metadata and controls
1758 lines (1634 loc) · 61.4 KB
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
# This file is part of python-functionfs
# Copyright (C) 2016-2021 Vincent Pelletier <[email protected]>
#
# python-functionfs 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 3 of the License, or
# (at your option) any later version.
#
# python-functionfs 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 python-functionfs. If not, see <http://www.gnu.org/licenses/>.
"""
Interfaces with functionfs to simplify USB gadget function declaration and
implementation on Linux.
Defines standard USB descriptors (see "ch9" sub-module) and sends them to the
kernel to declare function's structure.
Provides methods for accessing each endpoint and to react to events.
"""
import ctypes
import errno
import fcntl
import functools
import io
import itertools
import math
import mmap
import os
import select
import struct
import warnings
import libaio
from .common import (
USBDescriptorHeader,
le32,
)
from . import ch9
from .ch9 import (
USBInterfaceDescriptor,
USBEndpointDescriptorNoAudio,
USBEndpointDescriptor,
USBSSEPCompDescriptor,
# USBSSPIsocEndpointDescriptor is not implemented in kernel as of this
# writing.
USBSSPIsocEndpointDescriptor,
# USBQualifierDescriptor is reserved for gadgets, so don't expose it.
USBOTGDescriptor,
USBOTG20Descriptor,
# USBDebugDescriptor is not implemented in kernel as of this writing.
USBDebugDescriptor,
USBInterfaceAssocDescriptor,
)
from . import hid
from .hid import (
getUSBHIDDescriptorClass,
USB_INTERFACE_PROTOCOL_NONE,
)
from .functionfs import (
DESCRIPTORS_MAGIC, STRINGS_MAGIC, DESCRIPTORS_MAGIC_V2,
FLAGS,
DescsHeadV2,
DescsHead,
OSDescHeader,
OSDescHeaderBCount,
OSExtCompatDesc,
OSExtPropDescHead,
StringsHead,
StringBase,
Event,
FIFO_STATUS, FIFO_FLUSH, CLEAR_HALT, INTERFACE_REVMAP, ENDPOINT_REVMAP, ENDPOINT_DESC,
)
# pylint: disable=no-name-in-module
from .functionfs import (
HAS_FS_DESC,
HAS_HS_DESC,
HAS_SS_DESC,
HAS_MS_OS_DESC,
EVENTFD,
ALL_CTRL_RECIP,
CONFIG0_SETUP,
BIND, UNBIND, ENABLE, DISABLE, SETUP, SUSPEND, RESUME,
)
# pylint: enable=no-name-in-module
from . import _version
__version__ = _version.get_versions()['version']
__all__ = (
'ch9',
'hid',
'Function',
# XXX: Not very pythonic...
'getInterfaceInAllSpeeds',
'getDescriptor',
'getOSDesc',
'getOSExtPropDesc',
'USBInterfaceDescriptor',
'USBEndpointDescriptorNoAudio',
'USBEndpointDescriptor',
'USBSSEPCompDescriptor',
'USBSSPIsocEndpointDescriptor',
'USBOTGDescriptor',
'USBOTG20Descriptor',
'USBDebugDescriptor',
'USBInterfaceAssocDescriptor',
'OSExtCompatDesc',
'getUSBHIDDescriptorClass',
)
_MAX_PACKET_SIZE_DICT = {
ch9.USB_ENDPOINT_XFER_ISOC: (
1023, # 0..1023
1024, # 0..1024
1024, # 0..1024
),
ch9.USB_ENDPOINT_XFER_BULK: (
64, # 8, 16, 32, 64
512, # 512 only
1024, # 1024 only
),
ch9.USB_ENDPOINT_XFER_INT: (
64, # 0..64
1024, # 0..1024
1024, # 1..1024
),
}
_MARKER = object()
_EMPTY_DICT = {} # For internal ** fallback usage
def getInterfaceInAllSpeeds(interface, endpoint_list, class_descriptor_list=()):
"""
Produce similar fs, hs and ss interface and endpoints descriptors.
Should be useful for devices desiring to work in all 3 speeds with maximum
endpoint wMaxPacketSize. Reduces data duplication from descriptor
declarations.
Not intended to cover fancy combinations.
interface (dict):
Keyword arguments for
getDescriptor(USBInterfaceDescriptor, ...)
in all speeds.
bNumEndpoints must not be provided.
endpoint_list (list of dicts)
Each dict represents an endpoint, and may contain the following items:
- "endpoint": required, contains keyword arguments for
getDescriptor(USBEndpointDescriptorNoAudio, ...)
or
getDescriptor(USBEndpointDescriptor, ...)
The with-audio variant is picked when its extra fields are assigned a
value.
wMaxPacketSize may be missing, in which case it will be set to the
maximum size for given speed and endpoint type.
bmAttributes must be provided.
If bEndpointAddress is zero (excluding direction bit) on the first
endpoint, endpoints will be assigned their rank in this list,
starting at 1. Their direction bit is preserved.
If bInterval is present on a INT or ISO endpoint, it must be in
millisecond units (but may not be an integer), and will be converted
to the nearest integer millisecond for full-speed descriptor, and
nearest possible interval for high- and super-speed descriptors.
If bInterval is present on a BULK endpoint, it is set to zero on
full-speed descriptor and used as provided on high- and super-speed
descriptors.
- "superspeed": optional, contains keyword arguments for
getDescriptor(USBSSEPCompDescriptor, ...)
- "superspeed_iso": optional, contains keyword arguments for
getDescriptor(USBSSPIsocEndpointDescriptor, ...)
Must be provided and non-empty only when endpoint is isochronous and
"superspeed" dict has "bmAttributes" bit 7 set.
class_descriptor_list (list of descriptors of any type)
Descriptors to insert in all speeds between the interface descriptor and
endpoint descriptors.
Returns a 3-tuple of lists:
- fs descriptors
- hs descriptors
- ss descriptors
"""
interface = getDescriptor(
USBInterfaceDescriptor,
bNumEndpoints=len(endpoint_list),
**interface
)
class_descriptor_list = list(class_descriptor_list)
fs_list = [interface] + class_descriptor_list
hs_list = [interface] + class_descriptor_list
ss_list = [interface] + class_descriptor_list
need_address = (
endpoint_list[0]['endpoint'].get(
'bEndpointAddress',
0,
) & ~ch9.USB_DIR_IN == 0
)
for index, endpoint in enumerate(endpoint_list, 1):
endpoint_kw = endpoint['endpoint'].copy()
transfer_type = endpoint_kw[
'bmAttributes'
] & ch9.USB_ENDPOINT_XFERTYPE_MASK
fs_max, hs_max, ss_max = _MAX_PACKET_SIZE_DICT[transfer_type]
if need_address:
endpoint_kw['bEndpointAddress'] = index | (
endpoint_kw.get('bEndpointAddress', 0) & ch9.USB_DIR_IN
)
klass = (
USBEndpointDescriptor
if 'bRefresh' in endpoint_kw or 'bSynchAddress' in endpoint_kw else
USBEndpointDescriptorNoAudio
)
interval = endpoint_kw.pop('bInterval', _MARKER)
if interval is _MARKER:
fs_interval = hs_interval = 0
else:
if transfer_type == ch9.USB_ENDPOINT_XFER_BULK:
fs_interval = 0
hs_interval = interval
else: # USB_ENDPOINT_XFER_ISOC or USB_ENDPOINT_XFER_INT
fs_interval = max(1, min(255, round(interval)))
# 8 is the number of micro-frames in a millisecond
hs_interval = max(
1,
min(16, int(round(1 + math.log(interval * 8, 2)))),
)
packet_size = endpoint_kw.pop('wMaxPacketSize', _MARKER)
if packet_size is _MARKER:
fs_packet_size = fs_max
hs_packet_size = hs_max
ss_packet_size = ss_max
else:
fs_packet_size = min(fs_max, packet_size)
hs_packet_size = min(hs_max, packet_size)
ss_packet_size = min(ss_max, packet_size)
fs_list.append(getDescriptor(
klass,
wMaxPacketSize=fs_packet_size,
bInterval=fs_interval,
**endpoint_kw
))
hs_list.append(getDescriptor(
klass,
wMaxPacketSize=hs_packet_size,
bInterval=hs_interval,
**endpoint_kw
))
ss_list.append(getDescriptor(
klass,
wMaxPacketSize=ss_packet_size,
bInterval=hs_interval,
**endpoint_kw
))
ss_companion_kw = endpoint.get('superspeed', _EMPTY_DICT)
ss_list.append(getDescriptor(
USBSSEPCompDescriptor,
**ss_companion_kw
))
ssp_iso_kw = endpoint.get('superspeed_iso', _EMPTY_DICT)
if bool(ssp_iso_kw) != (
endpoint_kw.get('bmAttributes', 0) &
ch9.USB_ENDPOINT_XFERTYPE_MASK ==
ch9.USB_ENDPOINT_XFER_ISOC and
bool(ch9.USB_SS_SSP_ISOC_COMP(
ss_companion_kw.get('bmAttributes', 0),
))
):
raise ValueError('Inconsistent isochronous companion')
if ssp_iso_kw:
ss_list.append(getDescriptor(
USBSSPIsocEndpointDescriptor,
**ssp_iso_kw
))
return (fs_list, hs_list, ss_list)
def getDescriptor(klass, **kw):
"""
Automatically fills bLength and bDescriptorType.
"""
# XXX: ctypes Structure.__init__ ignores arguments which do not exist
# as structure fields. So check it.
# This is annoying, but not doing it is a huge waste of time for the
# developer.
empty = klass()
assert hasattr(empty, 'bLength')
assert hasattr(empty, 'bDescriptorType')
unknown = [x for x in kw if not hasattr(empty, x)]
if unknown:
raise TypeError('Unknown fields %r' % (unknown, ))
# XXX: not very pythonic...
return klass(
bLength=ctypes.sizeof(klass),
# pylint: disable=protected-access
bDescriptorType=klass._bDescriptorType,
# pylint: enable=protected-access
**kw
)
def getOSDesc(interface, ext_list):
"""
Return an OS description header.
interface (int)
Related interface number.
ext_list (list of OSExtCompatDesc or OSExtPropDesc)
List of instances of extended descriptors.
"""
try:
ext_type, = {type(x) for x in ext_list}
except ValueError:
raise TypeError('Extensions of a single type are required.') from None
if issubclass(ext_type, OSExtCompatDesc):
w_index = 4
kw = {
'b': OSDescHeaderBCount(
bCount=len(ext_list),
Reserved=0,
),
}
elif issubclass(ext_type, OSExtPropDescHead):
w_index = 5
kw = {
'wCount': len(ext_list),
}
else:
raise TypeError('Extensions of unexpected type')
ext_list_type = ext_type * len(ext_list)
klass = type(
'OSDesc',
(OSDescHeader, ),
{
'_fields_': [
('ext_list', ext_list_type),
],
},
)
return klass(
interface=interface,
dwLength=ctypes.sizeof(klass),
bcdVersion=1,
wIndex=w_index,
ext_list=ext_list_type(*ext_list),
**kw
)
def getOSExtPropDesc(data_type, name, value):
"""
Returns an OS extension property descriptor.
data_type (int)
See wPropertyDataType documentation.
name (string)
See PropertyName documentation.
value (string)
See PropertyData documentation.
NULL chars must be explicitly included in the value when needed,
this function does not add any terminating NULL for example.
"""
klass = type(
'OSExtPropDesc',
(OSExtPropDescHead, ),
{
'_fields_': [
('bPropertyName', ctypes.c_char * len(name)),
('dwPropertyDataLength', le32),
('bProperty', ctypes.c_char * len(value)),
],
}
)
return klass(
dwSize=ctypes.sizeof(klass),
dwPropertyDataType=data_type,
wPropertyNameLength=len(name),
bPropertyName=name,
dwPropertyDataLength=len(value),
bProperty=value,
)
def getDescsV2(flags, fs_list=(), hs_list=(), ss_list=(), os_list=(), eventfd=None):
"""
Return a FunctionFS descriptor suitable for serialisation.
flags (int)
Any combination of VIRTUAL_ADDR, ALL_CTRL_RECIP, CONFIG0_SETUP.
{fs,hs,ss,os}_list (list of descriptors)
Instances of the following classes:
{fs,hs,ss}_list:
USBInterfaceDescriptor
USBEndpointDescriptorNoAudio
USBEndpointDescriptor
USBSSEPCompDescriptor
USBSSPIsocEndpointDescriptor
USBOTGDescriptor
USBOTG20Descriptor
USBInterfaceAssocDescriptor
USBHIDDescriptor, as provided by getUSBHIDDescriptorClass
All (non-empty) lists must define the same number of interfaces
and endpoints, and endpoint descriptors must be given in the same
order, bEndpointAddress-wise.
os_list:
OSDesc
eventfd (file, None)
eventfd file instance. If not None, must have fileno method.
"""
count_field_list = []
descr_field_list = []
kw = {}
if eventfd is not None:
flags |= EVENTFD
count_field_list.append(('eventfd', le32))
kw['eventfd'] = eventfd.fileno()
for descriptor_list, flag, prefix, allowed_descriptor_klass in (
(fs_list, HAS_FS_DESC, 'fs', USBDescriptorHeader),
(hs_list, HAS_HS_DESC, 'hs', USBDescriptorHeader),
(ss_list, HAS_SS_DESC, 'ss', USBDescriptorHeader),
(os_list, HAS_MS_OS_DESC, 'os', OSDescHeader),
):
if descriptor_list:
for index, descriptor in enumerate(descriptor_list):
if not isinstance(descriptor, allowed_descriptor_klass):
raise TypeError(
'Descriptor %r of unexpected type: %r' % (
index,
type(descriptor),
),
)
descriptor_map = [
('desc_%i' % x, y)
for x, y in enumerate(descriptor_list)
]
flags |= flag
count_name = prefix + 'count'
descr_name = prefix + 'descr'
count_field_list.append((count_name, le32))
descr_type = type(
't_' + descr_name,
(ctypes.LittleEndianStructure, ),
{
'_pack_': 1,
'_fields_': [
(x, type(y))
for x, y in descriptor_map
],
}
)
descr_field_list.append((descr_name, descr_type))
kw[count_name] = len(descriptor_map)
kw[descr_name] = descr_type(**dict(descriptor_map))
elif flags & flag:
raise ValueError(
'Flag %r set but descriptor list empty, cannot generate type.' % (
FLAGS.get(flag),
)
)
klass = type(
'DescsV2_0x%02x' % (
flags & (
HAS_FS_DESC |
HAS_HS_DESC |
HAS_SS_DESC |
HAS_MS_OS_DESC
),
# XXX: include contained descriptors type information ? (and name ?)
),
(DescsHeadV2, ),
{
'_fields_': count_field_list + descr_field_list,
},
)
return klass(
magic=DESCRIPTORS_MAGIC_V2,
length=ctypes.sizeof(klass),
flags=flags,
**kw
)
def getStrings(lang_dict):
"""
Return a FunctionFS descriptor suitable for serialisation.
lang_dict (dict)
Key: language ID (ex: 0x0409 for en-us)
Value: list of unicode objects
All values must have the same number of items.
"""
field_list = []
kw = {}
try:
str_count = len(next(iter(lang_dict.values())))
except StopIteration:
str_count = 0
else:
for lang, string_list in lang_dict.items():
if len(string_list) != str_count:
raise ValueError('All values must have the same string count.')
field_id = 'strings_%04x' % lang
strings = b'\x00'.join(x.encode('utf-8') for x in string_list) + b'\x00'
field_type = type(
'String',
(StringBase, ),
{
'_fields_': [
('strings', ctypes.c_char * len(strings)),
],
},
)
field_list.append((field_id, field_type))
kw[field_id] = field_type(
lang=lang,
strings=strings,
)
klass = type(
'Strings',
(StringsHead, ),
{
'_fields_': field_list,
},
)
return klass(
magic=STRINGS_MAGIC,
length=ctypes.sizeof(klass),
str_count=str_count,
lang_count=len(lang_dict),
**kw
)
def serialise(structure):
"""
structure (ctypes.Structure)
The structure to serialise.
Returns a ctypes.c_char array.
Does not copy memory.
"""
return ctypes.cast(
ctypes.pointer(structure),
ctypes.POINTER(ctypes.c_char * ctypes.sizeof(structure)),
).contents
class EndpointFileBase(io.FileIO):
"""
File object representing a endpoint. Abstract.
"""
def __init__(self, path):
super().__init__(path, 'r+')
def _ioctl(self, func, *args, **kw):
result = fcntl.ioctl(self, func, *args, **kw)
if result < 0:
raise IOError(result)
return result
class Endpoint0File(EndpointFileBase):
"""
File object exposing ioctls available on endpoint zero.
"""
def halt(self, request_type):
"""
Halt current endpoint.
"""
try:
if request_type & ch9.USB_DIR_IN:
self.read(0)
else:
self.write(b'')
except IOError as exc:
if exc.errno != errno.EL2HLT:
raise
else:
raise ValueError('halt did not return EL2HLT ?')
def getRealInterfaceNumber(self, interface):
"""
Returns the host-visible interface number, or None if there is no such
interface.
"""
try:
return self._ioctl(INTERFACE_REVMAP, interface)
except IOError as exc:
if exc.errno == errno.EDOM:
return None
raise
# TODO: Add any standard IOCTL in usb_gadget_ops.ioctl ?
class EndpointFile(EndpointFileBase):
"""
File object exposing ioctls available on non-zero endpoints.
"""
_halted = False
def getRealEndpointNumber(self):
"""
Returns the host-visible endpoint number.
"""
return self._ioctl(ENDPOINT_REVMAP)
def clearHalt(self):
"""
Clears endpoint halt, and resets toggle.
See drivers/usb/gadget/udc/core.c:usb_ep_clear_halt
"""
self._ioctl(CLEAR_HALT)
self._halted = False
def getFIFOStatus(self):
"""
Returns the number of bytes in fifo.
"""
return self._ioctl(FIFO_STATUS)
def flushFIFO(self):
"""
Discards Endpoint FIFO content.
"""
self._ioctl(FIFO_FLUSH)
def getDescriptor(self):
"""
Returns the currently active endpoint descriptor
(depending on current USB speed).
"""
result = USBEndpointDescriptor()
self._ioctl(ENDPOINT_DESC, result, True)
return result
def _halt(self):
raise NotImplementedError
def halt(self):
"""
Halt current endpoint.
"""
try:
self._halt()
except IOError as exc:
if exc.errno != errno.EBADMSG:
raise
else:
raise ValueError('halt did not return EBADMSG ?')
self._halted = True
def isHalted(self):
"""
Whether endpoint is currently halted.
"""
return self._halted
class EndpointINFile(EndpointFile):
"""
Write-only endpoint file.
"""
def __init__(self, path, submit, eventfd):
"""
path (string)
Endpoint file path.
submit (AIOContext.submit)
To submit AIOBlocks.
eventfd (EventFD)
eventfd to set on all AIOBlocks created for this endpoint.
"""
super().__init__(path)
self._submit = submit
self._eventfd = eventfd
@staticmethod
def read(*_, **__):
"""
Always raises IOError.
"""
raise IOError('File not open for reading')
readinto = read
readall = read
readlines = read
readline = read
@staticmethod
def readable():
"""
Never readable.
"""
return False
def _halt(self):
super().read(0)
def submit(self, buffer_list, user_data=None):
"""
Non-blocking, zero-copy, AIO-based alternative to "write".
Queue a list of buffers for sending from this endpoint as a single
USB transfer (which may be composed of multiple transactions, the last
one of which will be automatically be made less than wMaxPacketSize so
host knows we are done sending).
buffer_list (sized iterable of mutable buffer objects)
Buffer mutability is needed because they are not internally copied
and will leave python interpreter. Nothing is expected to mutate
them, though.
Also, you should not mutate them between this call and
corresponding completion event (see onComplete).
user_data (anything)
Opaque object passed verbatim to onComplete on completion of this
transfer.
May raise OSError(EAGAIN) if there is currently no room for AIO blocks
(see __init__ in_aio_blocks_max).
"""
try:
self._submit((
libaio.AIOBlock(
mode=libaio.AIOBLOCK_MODE_WRITE,
target_file=self,
buffer_list=buffer_list,
offset=0,
eventfd=self._eventfd,
onCompletion=functools.partial(
self._onComplete,
buffer_list,
user_data,
),
),
))
except OSError as exc:
if exc.errno != errno.EAGAIN:
raise
self.onSubmitEAGAIN(buffer_list, user_data)
def _onComplete(
self,
buffer_list, user_data, # from functools.partial
aio_block, res, res2, # from libaio
):
# res2 is ignored as it just repeats res.
_ = res2 # silence pylint
callback_result = self.onComplete(
buffer_list,
user_data,
res,
)
if callback_result:
if res == -errno.ESHUTDOWN:
raise ValueError(
'onComplete cannot ask to resubmit transfer which '
'completed with status %i' % res,
)
if callback_result is not True:
aio_block.buffer_list = callback_result
aio_block.onCompletion = functools.partial(
self._onComplete,
callback_result,
user_data,
)
try:
self._submit((aio_block, ))
except OSError as exc:
if exc.errno != errno.EAGAIN:
raise
self.onSubmitEAGAIN(aio_block.buffer_list, user_data)
# pylint: disable=unused-argument
def onComplete(self, buffer_list, user_data, status):
"""
Called when a transfer, queued using submit, completed.
buffer_list, user_data:
Values which were provided to submit when initiating this
transfer.
status (int)
Error code if there was an error (negative errno value), number of
bytes transferred otherwise.
If a true value is returned, the same transfer is resubmitted:
- if returned value is True (the builtin), transfer reuses the same
buffers
- otherwise, it must be a value similar to buffer_list argument of
submit method, and will replace buffer in transfer before it gets
resubmitted. This is especially useful when large buffers are
prepared, but a different-sized chunk must be submitted on each
transfer. In which case, this value would be a tuple of memoryview
instance(s) covering the intended buffer chunk(s), for example.
Must not return a true value if status is -errno.ESHUTDOWN.
May be overridden in subclass.
"""
return False
def onSubmitEAGAIN(self, buffer_list, user_data):
"""
Called when submit fails with EAGAIN.
This may be during a call to submit or when onComplete requested its
transfer to be resubmitted.
By default, re-raises the original OSError exception.
buffer_list, user_data:
Values which were provided to submit when initiating this
transfer.
May be overridden in subclass.
"""
raise # pylint: disable=misplaced-bare-raise
# pylint: enable=unused-argument
class EndpointOUTFile(EndpointFile):
"""
Read-only endpoint file.
"""
def __init__(self, path, submit, release, aio_block_list):
"""
path (string)
Endpoint file path.
submit (AIOContext.submit)
To submit AIOBlocks to after completion.
release ((AIOBlock) -> None)
Called when a completed AIOBlock is not resubmitted.
aio_block_list (list of AIOBlock)
Blocks which belong to this endpoint. Modified to bind them to
this file object (target_file and onCompletion).
"""
super().__init__(path)
self._submit = submit
self._release = release
for aio_block in aio_block_list:
aio_block.target_file = self
aio_block.onCompletion = self._onComplete
@staticmethod
def write(*_, **__):
"""
Always raises IOError.
"""
raise IOError('File not open for writing')
writelines = write
@staticmethod
def writable():
"""
Never writable.
"""
return False
def _halt(self):
super().write(b'')
def _onComplete(self, aio_block, res, res2):
# res2 is ignored as it just repeats res.
_ = res2
if res < 0:
data = None
status = res
else:
aio_buffer, = aio_block.buffer_list
data = memoryview(aio_buffer)[:res]
status = 0
self.onComplete(
data=data,
status=status,
)
if res == -errno.ESHUTDOWN:
self._release(aio_block)
else:
# XXX: is it good to resubmit on any other error ?
# XXX: what should be done on EAGAIN ?
self._submit((aio_block, ))
def onComplete(self, data, status):
"""
Called when this endpoint received data.
data (memoryview, None)
Data received, or None if there was an error.
Once this method returns the underlying buffer will be reused,
so you must copy any piece you cannot immediately process.
status (int, None)
Error code if there was an error (negative errno value), zero
otherwise.
May be overridden in subclass.
"""
# FunctionFS can queue up to 4 events, so let's read that much.
_EP0_EVENT_LIST_TYPE = Event * 4
_EP0_EVENT_SIZE = ctypes.sizeof(Event)
# XXX: how reliable is kernel version checking ?
_, _, _KERNEL_VERSION, _, _ = os.uname()
class Function:
"""
Pythonic class for interfacing with FunctionFS.
Instance properties available:
function_remote_wakeup_capable (bool)
Whether the function wishes to be allowed to wake host.
function_remote_wakeup (bool)
Whether host has allowed the function to wake it up.
Set and cleared by onSetup by calling enableRemoteWakeup and
disableRemoteWakeup, respectively.
all_ctrl_recip, config0_setup:
Same value as given to constructor.
For forward compatibility, do not modify these properties (currently it
has no effect on the function at all).
Class properties available:
quirks_ffs_unsafe_eventfd (bool)
Whether the current kernel has issues with f_fs eventfd support.
Initialised on module initialisation with a simple condition on
kernel-version. May be changed prior to instantiation to override
this heuristic either way. Modification does not affect existing
instances.
"""
_open = False
_ep_list = ()
_in_aio_context = _out_aio_context = None
function_remote_wakeup_capable = False
function_remote_wakeup = False
# f_fs, before kernel version 5.16, had a bug which caused the
# kernel-internal eventfd reference counter to underflow during gadget
# tear-down. Depending on the exact version, maybe build options and
# maybe architecture, this could lead to kernel panics.
# Add backward-compatibility with such versions by working around the
# issue: do not give an eventfd to f_fs, and instead submit an extra AIO
# operation to still get eventfd notified when ep0 becomes readable.
quirks_ffs_unsafe_eventfd = (
_KERNEL_VERSION < '5.16'
)
def __init__( # pylint: disable=too-many-arguments
self,
path,
fs_list=(), hs_list=(), ss_list=(),
os_list=(),
lang_dict=(),
all_ctrl_recip=False, config0_setup=False,
in_aio_blocks_max=32,
out_aio_blocks_per_endpoint=2,
out_aio_blocks_max_packet_count=10,
):
"""
path (string)
Path to the functionfs mountpoint (where the ep* files are
located).
{fs,hs,ss}_list (list of descriptors)
XXX: may change to avoid requiring ctype objects.
os_list (list of descriptors)
XXX: may change to avoid requiring ctype objects.
lang_dict (dict)
Keys: language id (ex: 0x0402 for "us-en").
Values: List of unicode objects. First item becomes string
descriptor 1, and so on. Must contain at least as many
string descriptors as the highest string index declared
in all descriptors.
all_ctrl_recip (bool)
When true, this function will receive all control transactions.
Useful when implementing non-standard control transactions.
config0_setup (bool)
When true, this function will receive control transactions before
any configuration gets enabled.
in_aio_blocks_max (int)
Maximum number of IN transfers in-flight at any given time.
Submitting more transfers (using submitIN) may raise
OSError(EAGAIN).
There may be a system-wide limit (64k AIO transfers as of 4.18).
out_aio_blocks_per_endpoint (int)
Number of OUT transfers to submit for each OUT endpoint.
out_aio_blocks_max_packet_count (int)
Maximum number of maximum-size USB packets to receive on each
OUT endpoint AIO block.
Memory usage from these buffers will be:
out_aio_blocks_per_endpoint * sum_OUT_wMaxPacketSize *
out_aio_blocks_max_packet_count
So by default 10kB per 512-bytes OUT endpoint will be allocated.
"""
self._path = path
self._ep_address_dict = ep_address_dict = {}
self._eventfd = eventfd = libaio.EventFD(flags=libaio.EFD_NONBLOCK)
self.all_ctrl_recip = all_ctrl_recip
self.config0_setup = config0_setup
flags = 0
if all_ctrl_recip:
flags |= ALL_CTRL_RECIP
if config0_setup:
flags |= CONFIG0_SETUP
self.__quirks_ffs_unsafe_eventfd = quirks_ffs_unsafe_eventfd = (
self.quirks_ffs_unsafe_eventfd
)
self._function_descriptor = getDescsV2(
flags,
fs_list=fs_list,
hs_list=hs_list,
ss_list=ss_list,
os_list=os_list,
eventfd=(
None
if quirks_ffs_unsafe_eventfd else
eventfd
),
)