← Documents Documentation/usb/gadget-testing.rst GitHub 원문 ↗

Linux 6.18.37 · USB

USB Gadget Function 시험

21개 USB gadget function의 모듈, configfs 속성, 기본값과 제한, device/host 시험 절차를 function별로 정리합니다.

Source pathDocumentation/usb/gadget-testing.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

gadget-testing.rst:1-1152

이 문서는 21개 gadget function을 같은 형식으로 비교할 수 있는 시험 레퍼런스입니다. 먼저 function을 제공하는 kernel module과 configfs 디렉터리 이름을 확인하고, function별 속성 및 기본값을 구성한 뒤 device와 host에서 대응 도구를 실행합니다.

serial 계열은 `ttyGS`와 host TTY 사이의 양방향 `cat`, network 계열은 양쪽 IP 설정 후 ping, loopback/source-sink는 `test-usb`, audio·MIDI·video 계열은 ALSA/V4L2 사용자 공간 도구로 검증합니다.

속성 이름, 대소문자를 구분하는 function 이름, port·LUN·queue·packet 범위는 ABI이므로 번역문에서도 그대로 유지했습니다. 시험 전에는 UDC 바인딩 시점과 function이 아직 수정 가능한 상태인지 함께 확인해야 합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 ==============
2 Gadget Testing
3 ==============
4
5 This file summarizes information on basic testing of USB functions
6 provided by gadgets.
7
8 .. contents
9
10 1. ACM function
11 2. ECM function
12 3. ECM subset function
13 4. EEM function
14 5. FFS function
15 6. HID function
16 7. LOOPBACK function
17 8. MASS STORAGE function
18 9. MIDI function
19 10. NCM function
20 11. OBEX function
21 12. PHONET function
22 13. RNDIS function
23 14. SERIAL function
24 15. SOURCESINK function
25 16. UAC1 function (legacy implementation)
26 17. UAC2 function
27 18. UVC function
28 19. PRINTER function
29 20. UAC1 function (new API)
30 21. MIDI2 function
31
32
33 1. ACM function
34 ===============
35
36 The function is provided by usb_f_acm.ko module.
37
38 Function-specific configfs interface
39 ------------------------------------
40
41 The function name to use when creating the function directory is "acm".
42 The ACM function provides just one attribute in its function directory:
43
44 port_num
45
46 The attribute is read-only.
47
48 There can be at most 4 ACM/generic serial/OBEX ports in the system.
49
50
51 Testing the ACM function
52 ------------------------
53
54 On the host::
55
56 cat > /dev/ttyACM<X>
57
58 On the device::
59
60 cat /dev/ttyGS<Y>
61
62 then the other way round
63
64 On the device::
65
66 cat > /dev/ttyGS<Y>
67
68 On the host::
69
70 cat /dev/ttyACM<X>
71
72 2. ECM function
73 ===============
74
75 The function is provided by usb_f_ecm.ko module.
76
77 Function-specific configfs interface
78 ------------------------------------
79
80 The function name to use when creating the function directory is "ecm".
81 The ECM function provides these attributes in its function directory:
82
83 =============== ==================================================
84 ifname network device interface name associated with this
85 function instance
86 qmult queue length multiplier for high and super speed
87 host_addr MAC address of host's end of this
88 Ethernet over USB link
89 dev_addr MAC address of device's end of this
90 Ethernet over USB link
91 =============== ==================================================
92
93 and after creating the functions/ecm.<instance name> they contain default
94 values: qmult is 5, dev_addr and host_addr are randomly selected.
95 The ifname can be written to if the function is not bound. A write must be an
96 interface pattern such as "usb%d", which will cause the net core to choose the
97 next free usbX interface. By default, it is set to "usb%d".
98
99 Testing the ECM function
100 ------------------------
101
102 Configure IP addresses of the device and the host. Then:
103
104 On the device::
105
106 ping <host's IP>
107
108 On the host::
109
110 ping <device's IP>
111
112 3. ECM subset function
113 ======================
114
115 The function is provided by usb_f_ecm_subset.ko module.
116
117 Function-specific configfs interface
118 ------------------------------------
119
120 The function name to use when creating the function directory is "geth".
121 The ECM subset function provides these attributes in its function directory:
122
123 =============== ==================================================
124 ifname network device interface name associated with this
125 function instance
126 qmult queue length multiplier for high and super speed
127 host_addr MAC address of host's end of this
128 Ethernet over USB link
129 dev_addr MAC address of device's end of this
130 Ethernet over USB link
131 =============== ==================================================
132
133 and after creating the functions/ecm.<instance name> they contain default
134 values: qmult is 5, dev_addr and host_addr are randomly selected.
135 The ifname can be written to if the function is not bound. A write must be an
136 interface pattern such as "usb%d", which will cause the net core to choose the
137 next free usbX interface. By default, it is set to "usb%d".
138
139 Testing the ECM subset function
140 -------------------------------
141
142 Configure IP addresses of the device and the host. Then:
143
144 On the device::
145
146 ping <host's IP>
147
148 On the host::
149
150 ping <device's IP>
151
152 4. EEM function
153 ===============
154
155 The function is provided by usb_f_eem.ko module.
156
157 Function-specific configfs interface
158 ------------------------------------
159
160 The function name to use when creating the function directory is "eem".
161 The EEM function provides these attributes in its function directory:
162
163 =============== ==================================================
164 ifname network device interface name associated with this
165 function instance
166 qmult queue length multiplier for high and super speed
167 host_addr MAC address of host's end of this
168 Ethernet over USB link
169 dev_addr MAC address of device's end of this
170 Ethernet over USB link
171 =============== ==================================================
172
173 and after creating the functions/eem.<instance name> they contain default
174 values: qmult is 5, dev_addr and host_addr are randomly selected.
175 The ifname can be written to if the function is not bound. A write must be an
176 interface pattern such as "usb%d", which will cause the net core to choose the
177 next free usbX interface. By default, it is set to "usb%d".
178
179 Testing the EEM function
180 ------------------------
181
182 Configure IP addresses of the device and the host. Then:
183
184 On the device::
185
186 ping <host's IP>
187
188 On the host::
189
190 ping <device's IP>
191
192 5. FFS function
193 ===============
194
195 The function is provided by usb_f_fs.ko module.
196
197 Function-specific configfs interface
198 ------------------------------------
199
200 The function name to use when creating the function directory is "ffs".
201 The function directory is intentionally empty and not modifiable.
202
203 After creating the directory there is a new instance (a "device") of FunctionFS
204 available in the system. Once a "device" is available, the user should follow
205 the standard procedure for using FunctionFS (mount it, run the userspace
206 process which implements the function proper). The gadget should be enabled
207 by writing a suitable string to usb_gadget/<gadget>/UDC.
208
209 The FFS function provides just one attribute in its function directory:
210
211 ready
212
213 The attribute is read-only and signals if the function is ready (1) to be
214 used, E.G. if userspace has written descriptors and strings to ep0, so
215 the gadget can be enabled.
216
217 Testing the FFS function
218 ------------------------
219
220 On the device: start the function's userspace daemon, enable the gadget
221
222 On the host: use the USB function provided by the device
223
224 6. HID function
225 ===============
226
227 The function is provided by usb_f_hid.ko module.
228
229 Function-specific configfs interface
230 ------------------------------------
231
232 The function name to use when creating the function directory is "hid".
233 The HID function provides these attributes in its function directory:
234
235 =============== ===========================================
236 protocol HID protocol to use
237 report_desc data to be used in HID reports, except data
238 passed with /dev/hidg<X>
239 report_length HID report length
240 subclass HID subclass to use
241 =============== ===========================================
242
243 For a keyboard the protocol and the subclass are 1, the report_length is 8,
244 while the report_desc is::
245
246 $ hd my_report_desc
247 00000000 05 01 09 06 a1 01 05 07 19 e0 29 e7 15 00 25 01 |..........)...%.|
248 00000010 75 01 95 08 81 02 95 01 75 08 81 03 95 05 75 01 |u.......u.....u.|
249 00000020 05 08 19 01 29 05 91 02 95 01 75 03 91 03 95 06 |....).....u.....|
250 00000030 75 08 15 00 25 65 05 07 19 00 29 65 81 00 c0 |u...%e....)e...|
251 0000003f
252
253 Such a sequence of bytes can be stored to the attribute with echo::
254
255 $ echo -ne \\x05\\x01\\x09\\x06\\xa1.....
256
257 Testing the HID function
258 ------------------------
259
260 Device:
261
262 - create the gadget
263 - connect the gadget to a host, preferably not the one used
264 to control the gadget
265 - run a program which writes to /dev/hidg<N>, e.g.
266 a userspace program found in Documentation/usb/gadget_hid.rst::
267
268 $ ./hid_gadget_test /dev/hidg0 keyboard
269
270 Host:
271
272 - observe the keystrokes from the gadget
273
274 7. LOOPBACK function
275 ====================
276
277 The function is provided by usb_f_ss_lb.ko module.
278
279 Function-specific configfs interface
280 ------------------------------------
281
282 The function name to use when creating the function directory is "Loopback".
283 The LOOPBACK function provides these attributes in its function directory:
284
285 =============== =======================
286 qlen depth of loopback queue
287 bulk_buflen buffer length
288 =============== =======================
289
290 Testing the LOOPBACK function
291 -----------------------------
292
293 device: run the gadget
294
295 host: test-usb (tools/usb/testusb.c)
296
297 8. MASS STORAGE function
298 ========================
299
300 The function is provided by usb_f_mass_storage.ko module.
301
302 Function-specific configfs interface
303 ------------------------------------
304
305 The function name to use when creating the function directory is "mass_storage".
306 The MASS STORAGE function provides these attributes in its directory:
307 files:
308
309 =============== ==============================================
310 stall Set to permit function to halt bulk endpoints.
311 Disabled on some USB devices known not to work
312 correctly. You should set it to true.
313 num_buffers Number of pipeline buffers. Valid numbers
314 are 2..4. Available only if
315 CONFIG_USB_GADGET_DEBUG_FILES is set.
316 =============== ==============================================
317
318 and a default lun.0 directory corresponding to SCSI LUN #0.
319
320 A new lun can be added with mkdir::
321
322 $ mkdir functions/mass_storage.0/partition.5
323
324 Lun numbering does not have to be continuous, except for lun #0 which is
325 created by default. A maximum of 8 luns can be specified and they all must be
326 named following the <name>.<number> scheme. The numbers can be 0..8.
327 Probably a good convention is to name the luns "lun.<number>",
328 although it is not mandatory.
329
330 In each lun directory there are the following attribute files:
331
332 =============== ==============================================
333 file The path to the backing file for the LUN.
334 Required if LUN is not marked as removable.
335 ro Flag specifying access to the LUN shall be
336 read-only. This is implied if CD-ROM emulation
337 is enabled as well as when it was impossible
338 to open "filename" in R/W mode.
339 removable Flag specifying that LUN shall be indicated as
340 being removable.
341 cdrom Flag specifying that LUN shall be reported as
342 being a CD-ROM.
343 nofua Flag specifying that FUA flag
344 in SCSI WRITE(10,12)
345 forced_eject This write-only file is useful only when
346 the function is active. It causes the backing
347 file to be forcibly detached from the LUN,
348 regardless of whether the host has allowed it.
349 Any non-zero number of bytes written will
350 result in ejection.
351 =============== ==============================================
352
353 Testing the MASS STORAGE function
354 ---------------------------------
355
356 device: connect the gadget, enable it
357 host: dmesg, see the USB drives appear (if system configured to automatically
358 mount)
359
360 9. MIDI function
361 ================
362
363 The function is provided by usb_f_midi.ko module.
364
365 Function-specific configfs interface
366 ------------------------------------
367
368 The function name to use when creating the function directory is "midi".
369 The MIDI function provides these attributes in its function directory:
370
371 =============== ====================================
372 buflen MIDI buffer length
373 id ID string for the USB MIDI adapter
374 in_ports number of MIDI input ports
375 index index value for the USB MIDI adapter
376 out_ports number of MIDI output ports
377 qlen USB read request queue length
378 =============== ====================================
379
380 Testing the MIDI function
381 -------------------------
382
383 There are two cases: playing a mid from the gadget to
384 the host and playing a mid from the host to the gadget.
385
386 1) Playing a mid from the gadget to the host:
387
388 host::
389
390 $ arecordmidi -l
391 Port Client name Port name
392 14:0 Midi Through Midi Through Port-0
393 24:0 MIDI Gadget MIDI Gadget MIDI 1
394 $ arecordmidi -p 24:0 from_gadget.mid
395
396 gadget::
397
398 $ aplaymidi -l
399 Port Client name Port name
400 20:0 f_midi f_midi
401
402 $ aplaymidi -p 20:0 to_host.mid
403
404 2) Playing a mid from the host to the gadget
405
406 gadget::
407
408 $ arecordmidi -l
409 Port Client name Port name
410 20:0 f_midi f_midi
411
412 $ arecordmidi -p 20:0 from_host.mid
413
414 host::
415
416 $ aplaymidi -l
417 Port Client name Port name
418 14:0 Midi Through Midi Through Port-0
419 24:0 MIDI Gadget MIDI Gadget MIDI 1
420
421 $ aplaymidi -p24:0 to_gadget.mid
422
423 The from_gadget.mid should sound identical to the to_host.mid.
424
425 The from_host.id should sound identical to the to_gadget.mid.
426
427 MIDI files can be played to speakers/headphones with e.g. timidity installed::
428
429 $ aplaymidi -l
430 Port Client name Port name
431 14:0 Midi Through Midi Through Port-0
432 24:0 MIDI Gadget MIDI Gadget MIDI 1
433 128:0 TiMidity TiMidity port 0
434 128:1 TiMidity TiMidity port 1
435 128:2 TiMidity TiMidity port 2
436 128:3 TiMidity TiMidity port 3
437
438 $ aplaymidi -p 128:0 file.mid
439
440 MIDI ports can be logically connected using the aconnect utility, e.g.::
441
442 $ aconnect 24:0 128:0 # try it on the host
443
444 After the gadget's MIDI port is connected to timidity's MIDI port,
445 whatever is played at the gadget side with aplaymidi -l is audible
446 in host's speakers/headphones.
447
448 10. NCM function
449 ================
450
451 The function is provided by usb_f_ncm.ko module.
452
453 Function-specific configfs interface
454 ------------------------------------
455
456 The function name to use when creating the function directory is "ncm".
457 The NCM function provides these attributes in its function directory:
458
459 ======================= ==================================================
460 ifname network device interface name associated with this
461 function instance
462 qmult queue length multiplier for high and super speed
463 host_addr MAC address of host's end of this
464 Ethernet over USB link
465 dev_addr MAC address of device's end of this
466 Ethernet over USB link
467 max_segment_size Segment size required for P2P connections. This
468 will set MTU to 14 bytes
469 ======================= ==================================================
470
471 and after creating the functions/ncm.<instance name> they contain default
472 values: qmult is 5, dev_addr and host_addr are randomly selected.
473 The ifname can be written to if the function is not bound. A write must be an
474 interface pattern such as "usb%d", which will cause the net core to choose the
475 next free usbX interface. By default, it is set to "usb%d".
476
477 Testing the NCM function
478 ------------------------
479
480 Configure IP addresses of the device and the host. Then:
481
482 On the device::
483
484 ping <host's IP>
485
486 On the host::
487
488 ping <device's IP>
489
490 11. OBEX function
491 =================
492
493 The function is provided by usb_f_obex.ko module.
494
495 Function-specific configfs interface
496 ------------------------------------
497
498 The function name to use when creating the function directory is "obex".
499 The OBEX function provides just one attribute in its function directory:
500
501 port_num
502
503 The attribute is read-only.
504
505 There can be at most 4 ACM/generic serial/OBEX ports in the system.
506
507 Testing the OBEX function
508 -------------------------
509
510 On device::
511
512 seriald -f /dev/ttyGS<Y> -s 1024
513
514 On host::
515
516 serialc -v <vendorID> -p <productID> -i<interface#> -a1 -s1024 \
517 -t<out endpoint addr> -r<in endpoint addr>
518
519 where seriald and serialc are Felipe's utilities found here:
520
521 https://github.com/felipebalbi/usb-tools.git master
522
523 12. PHONET function
524 ===================
525
526 The function is provided by usb_f_phonet.ko module.
527
528 Function-specific configfs interface
529 ------------------------------------
530
531 The function name to use when creating the function directory is "phonet".
532 The PHONET function provides just one attribute in its function directory:
533
534 =============== ==================================================
535 ifname network device interface name associated with this
536 function instance
537 =============== ==================================================
538
539 Testing the PHONET function
540 ---------------------------
541
542 It is not possible to test the SOCK_STREAM protocol without a specific piece
543 of hardware, so only SOCK_DGRAM has been tested. For the latter to work,
544 in the past I had to apply the patch mentioned here:
545
546 http://www.spinics.net/lists/linux-usb/msg85689.html
547
548 These tools are required:
549
550 git://git.gitorious.org/meego-cellular/phonet-utils.git
551
552 On the host::
553
554 $ ./phonet -a 0x10 -i usbpn0
555 $ ./pnroute add 0x6c usbpn0
556 $./pnroute add 0x10 usbpn0
557 $ ifconfig usbpn0 up
558
559 On the device::
560
561 $ ./phonet -a 0x6c -i upnlink0
562 $ ./pnroute add 0x10 upnlink0
563 $ ifconfig upnlink0 up
564
565 Then a test program can be used::
566
567 http://www.spinics.net/lists/linux-usb/msg85690.html
568
569 On the device::
570
571 $ ./pnxmit -a 0x6c -r
572
573 On the host::
574
575 $ ./pnxmit -a 0x10 -s 0x6c
576
577 As a result some data should be sent from host to device.
578 Then the other way round:
579
580 On the host::
581
582 $ ./pnxmit -a 0x10 -r
583
584 On the device::
585
586 $ ./pnxmit -a 0x6c -s 0x10
587
588 13. RNDIS function
589 ==================
590
591 The function is provided by usb_f_rndis.ko module.
592
593 Function-specific configfs interface
594 ------------------------------------
595
596 The function name to use when creating the function directory is "rndis".
597 The RNDIS function provides these attributes in its function directory:
598
599 =============== ==================================================
600 ifname network device interface name associated with this
601 function instance
602 qmult queue length multiplier for high and super speed
603 host_addr MAC address of host's end of this
604 Ethernet over USB link
605 dev_addr MAC address of device's end of this
606 Ethernet over USB link
607 =============== ==================================================
608
609 and after creating the functions/rndis.<instance name> they contain default
610 values: qmult is 5, dev_addr and host_addr are randomly selected.
611 The ifname can be written to if the function is not bound. A write must be an
612 interface pattern such as "usb%d", which will cause the net core to choose the
613 next free usbX interface. By default, it is set to "usb%d".
614
615 Testing the RNDIS function
616 --------------------------
617
618 Configure IP addresses of the device and the host. Then:
619
620 On the device::
621
622 ping <host's IP>
623
624 On the host::
625
626 ping <device's IP>
627
628 14. SERIAL function
629 ===================
630
631 The function is provided by usb_f_gser.ko module.
632
633 Function-specific configfs interface
634 ------------------------------------
635
636 The function name to use when creating the function directory is "gser".
637 The SERIAL function provides just one attribute in its function directory:
638
639 port_num
640
641 The attribute is read-only.
642
643 There can be at most 4 ACM/generic serial/OBEX ports in the system.
644
645 Testing the SERIAL function
646 ---------------------------
647
648 On host::
649
650 insmod usbserial
651 echo VID PID >/sys/bus/usb-serial/drivers/generic/new_id
652
653 On host::
654
655 cat > /dev/ttyUSB<X>
656
657 On target::
658
659 cat /dev/ttyGS<Y>
660
661 then the other way round
662
663 On target::
664
665 cat > /dev/ttyGS<Y>
666
667 On host::
668
669 cat /dev/ttyUSB<X>
670
671 15. SOURCESINK function
672 =======================
673
674 The function is provided by usb_f_ss_lb.ko module.
675
676 Function-specific configfs interface
677 ------------------------------------
678
679 The function name to use when creating the function directory is "SourceSink".
680 The SOURCESINK function provides these attributes in its function directory:
681
682 =============== ==================================
683 pattern 0 (all zeros), 1 (mod63), 2 (none)
684 isoc_interval 1..16
685 isoc_maxpacket 0 - 1023 (fs), 0 - 1024 (hs/ss)
686 isoc_mult 0..2 (hs/ss only)
687 isoc_maxburst 0..15 (ss only)
688 bulk_buflen buffer length
689 bulk_qlen depth of queue for bulk
690 iso_qlen depth of queue for iso
691 =============== ==================================
692
693 Testing the SOURCESINK function
694 -------------------------------
695
696 device: run the gadget
697
698 host: test-usb (tools/usb/testusb.c)
699
700
701 16. UAC1 function (legacy implementation)
702 =========================================
703
704 The function is provided by usb_f_uac1_legacy.ko module.
705
706 Function-specific configfs interface
707 ------------------------------------
708
709 The function name to use when creating the function directory
710 is "uac1_legacy".
711 The uac1 function provides these attributes in its function directory:
712
713 =============== ====================================
714 audio_buf_size audio buffer size
715 fn_cap capture pcm device file name
716 fn_cntl control device file name
717 fn_play playback pcm device file name
718 req_buf_size ISO OUT endpoint request buffer size
719 req_count ISO OUT endpoint request count
720 =============== ====================================
721
722 The attributes have sane default values.
723
724 Testing the UAC1 function
725 -------------------------
726
727 device: run the gadget
728
729 host::
730
731 aplay -l # should list our USB Audio Gadget
732
733 17. UAC2 function
734 =================
735
736 The function is provided by usb_f_uac2.ko module.
737
738 Function-specific configfs interface
739 ------------------------------------
740
741 The function name to use when creating the function directory is "uac2".
742 The uac2 function provides these attributes in its function directory:
743
744 ================ ====================================================
745 c_chmask capture channel mask
746 c_srate list of capture sampling rates (comma-separated)
747 c_ssize capture sample size (bytes)
748 c_sync capture synchronization type (async/adaptive)
749 c_mute_present capture mute control enable
750 c_volume_present capture volume control enable
751 c_volume_min capture volume control min value (in 1/256 dB)
752 c_volume_max capture volume control max value (in 1/256 dB)
753 c_volume_res capture volume control resolution (in 1/256 dB)
754 c_hs_bint capture bInterval for HS/SS (1-4: fixed, 0: auto)
755 fb_max maximum extra bandwidth in async mode
756 p_chmask playback channel mask
757 p_srate list of playback sampling rates (comma-separated)
758 p_ssize playback sample size (bytes)
759 p_mute_present playback mute control enable
760 p_volume_present playback volume control enable
761 p_volume_min playback volume control min value (in 1/256 dB)
762 p_volume_max playback volume control max value (in 1/256 dB)
763 p_volume_res playback volume control resolution (in 1/256 dB)
764 p_hs_bint playback bInterval for HS/SS (1-4: fixed, 0: auto)
765 req_number the number of pre-allocated request for both capture
766 and playback
767 function_name name of the interface
768 if_ctrl_name topology control name
769 clksrc_in_name input clock name
770 clksrc_out_name output clock name
771 p_it_name playback input terminal name
772 p_it_ch_name playback input first channel name
773 p_ot_name playback output terminal name
774 p_fu_vol_name playback function unit name
775 c_it_name capture input terminal name
776 c_it_ch_name capture input first channel name
777 c_ot_name capture output terminal name
778 c_fu_vol_name capture functional unit name
779 c_terminal_type code of the capture terminal type
780 p_terminal_type code of the playback terminal type
781 ================ ====================================================
782
783 The attributes have sane default values.
784
785 Testing the UAC2 function
786 -------------------------
787
788 device: run the gadget
789 host: aplay -l # should list our USB Audio Gadget
790
791 This function does not require real hardware support, it just
792 sends a stream of audio data to/from the host. In order to
793 actually hear something at the device side, a command similar
794 to this must be used at the device side::
795
796 $ arecord -f dat -t wav -D hw:2,0 | aplay -D hw:0,0 &
797
798 e.g.::
799
800 $ arecord -f dat -t wav -D hw:CARD=UAC2Gadget,DEV=0 | \
801 aplay -D default:CARD=OdroidU3
802
803 18. UVC function
804 ================
805
806 The function is provided by usb_f_uvc.ko module.
807
808 Function-specific configfs interface
809 ------------------------------------
810
811 The function name to use when creating the function directory is "uvc".
812 The uvc function provides these attributes in its function directory:
813
814 =================== ================================================
815 streaming_interval interval for polling endpoint for data transfers
816 streaming_maxburst bMaxBurst for super speed companion descriptor
817 streaming_maxpacket maximum packet size this endpoint is capable of
818 sending or receiving when this configuration is
819 selected
820 function_name name of the interface
821 =================== ================================================
822
823 There are also "control" and "streaming" subdirectories, each of which contain
824 a number of their subdirectories. There are some sane defaults provided, but
825 the user must provide the following:
826
827 ================== ====================================================
828 control header create in control/header, link from control/class/fs
829 and/or control/class/ss
830 streaming header create in streaming/header, link from
831 streaming/class/fs and/or streaming/class/hs and/or
832 streaming/class/ss
833 format description create in streaming/mjpeg and/or
834 streaming/uncompressed
835 frame description create in streaming/mjpeg/<format> and/or in
836 streaming/uncompressed/<format>
837 ================== ====================================================
838
839 Each frame description contains frame interval specification, and each
840 such specification consists of a number of lines with an interval value
841 in each line. The rules stated above are best illustrated with an example::
842
843 # mkdir functions/uvc.usb0/control/header/h
844 # cd functions/uvc.usb0/control/
845 # ln -s header/h class/fs
846 # ln -s header/h class/ss
847 # mkdir -p functions/uvc.usb0/streaming/uncompressed/u/360p
848 # cat <<EOF > functions/uvc.usb0/streaming/uncompressed/u/360p/dwFrameInterval
849 666666
850 1000000
851 5000000
852 EOF
853 # cd $GADGET_CONFIGFS_ROOT
854 # mkdir functions/uvc.usb0/streaming/header/h
855 # cd functions/uvc.usb0/streaming/header/h
856 # ln -s ../../uncompressed/u
857 # cd ../../class/fs
858 # ln -s ../../header/h
859 # cd ../../class/hs
860 # ln -s ../../header/h
861 # cd ../../class/ss
862 # ln -s ../../header/h
863
864
865 Testing the UVC function
866 ------------------------
867
868 device: run the gadget, modprobe vivid::
869
870 # uvc-gadget -u /dev/video<uvc video node #> -v /dev/video<vivid video node #>
871
872 where uvc-gadget is this program:
873 http://git.ideasonboard.org/uvc-gadget.git
874
875 with these patches:
876
877 https://lore.kernel.org/r/1386675637-18243-1-git-send-email-r.baldyga@samsung.com/
878
879 host::
880
881 luvcview -f yuv
882
883 19. PRINTER function
884 ====================
885
886 The function is provided by usb_f_printer.ko module.
887
888 Function-specific configfs interface
889 ------------------------------------
890
891 The function name to use when creating the function directory is "printer".
892 The printer function provides these attributes in its function directory:
893
894 ========== ===========================================
895 pnp_string Data to be passed to the host in pnp string
896 q_len Number of requests per endpoint
897 ========== ===========================================
898
899 Testing the PRINTER function
900 ----------------------------
901
902 The most basic testing:
903
904 device: run the gadget::
905
906 # ls -l /devices/virtual/usb_printer_gadget/
907
908 should show g_printer<number>.
909
910 If udev is active, then /dev/g_printer<number> should appear automatically.
911
912 host:
913
914 If udev is active, then e.g. /dev/usb/lp0 should appear.
915
916 host->device transmission:
917
918 device::
919
920 # cat /dev/g_printer<number>
921
922 host::
923
924 # cat > /dev/usb/lp0
925
926 device->host transmission::
927
928 # cat > /dev/g_printer<number>
929
930 host::
931
932 # cat /dev/usb/lp0
933
934 More advanced testing can be done with the prn_example
935 described in Documentation/usb/gadget_printer.rst.
936
937
938 20. UAC1 function (virtual ALSA card, using u_audio API)
939 ========================================================
940
941 The function is provided by usb_f_uac1.ko module.
942 It will create a virtual ALSA card and the audio streams are simply
943 sinked to and sourced from it.
944
945 Function-specific configfs interface
946 ------------------------------------
947
948 The function name to use when creating the function directory is "uac1".
949 The uac1 function provides these attributes in its function directory:
950
951 ================ ====================================================
952 c_chmask capture channel mask
953 c_srate list of capture sampling rates (comma-separated)
954 c_ssize capture sample size (bytes)
955 c_mute_present capture mute control enable
956 c_volume_present capture volume control enable
957 c_volume_min capture volume control min value (in 1/256 dB)
958 c_volume_max capture volume control max value (in 1/256 dB)
959 c_volume_res capture volume control resolution (in 1/256 dB)
960 p_chmask playback channel mask
961 p_srate list of playback sampling rates (comma-separated)
962 p_ssize playback sample size (bytes)
963 p_mute_present playback mute control enable
964 p_volume_present playback volume control enable
965 p_volume_min playback volume control min value (in 1/256 dB)
966 p_volume_max playback volume control max value (in 1/256 dB)
967 p_volume_res playback volume control resolution (in 1/256 dB)
968 req_number the number of pre-allocated requests for both capture
969 and playback
970 function_name name of the interface
971 p_it_name playback input terminal name
972 p_it_ch_name playback channels name
973 p_ot_name playback output terminal name
974 p_fu_vol_name playback mute/volume functional unit name
975 c_it_name capture input terminal name
976 c_it_ch_name capture channels name
977 c_ot_name capture output terminal name
978 c_fu_vol_name capture mute/volume functional unit name
979 ================ ====================================================
980
981 The attributes have sane default values.
982
983 Testing the UAC1 function
984 -------------------------
985
986 device: run the gadget
987 host: aplay -l # should list our USB Audio Gadget
988
989 This function does not require real hardware support, it just
990 sends a stream of audio data to/from the host. In order to
991 actually hear something at the device side, a command similar
992 to this must be used at the device side::
993
994 $ arecord -f dat -t wav -D hw:2,0 | aplay -D hw:0,0 &
995
996 e.g.::
997
998 $ arecord -f dat -t wav -D hw:CARD=UAC1Gadget,DEV=0 | \
999 aplay -D default:CARD=OdroidU3
1002 21. MIDI2 function
1003 ==================
1005 The function is provided by usb_f_midi2.ko module.
1006 It will create a virtual ALSA card containing a UMP rawmidi device
1007 where the UMP packet is looped back. In addition, a legacy rawmidi
1008 device is created. The UMP rawmidi is bound with ALSA sequencer
1009 clients, too.
1011 Function-specific configfs interface
1012 ------------------------------------
1014 The function name to use when creating the function directory is "midi2".
1015 The midi2 function provides these attributes in its function directory
1016 as the card top-level information:
1018 ============= =================================================
1019 process_ump Bool flag to process UMP Stream messages (0 or 1)
1020 static_block Bool flag for static blocks (0 or 1)
1021 iface_name Optional interface name string
1022 ============= =================================================
1024 The directory contains a subdirectory "ep.0", and this provides the
1025 attributes for a UMP Endpoint (which is a pair of USB MIDI Endpoints):
1027 ============= =================================================
1028 protocol_caps MIDI protocol capabilities;
1029 1: MIDI 1.0, 2: MIDI 2.0, or 3: both protocols
1030 protocol Default MIDI protocol (either 1 or 2)
1031 ep_name UMP Endpoint name string
1032 product_id Product ID string
1033 manufacturer Manufacture ID number (24 bit)
1034 family Device family ID number (16 bit)
1035 model Device model ID number (16 bit)
1036 sw_revision Software revision (32 bit)
1037 ============= =================================================
1039 Each Endpoint subdirectory contains a subdirectory "block.0", which
1040 represents the Function Block for Block 0 information.
1041 Its attributes are:
1043 ================= ===============================================
1044 name Function Block name string
1045 direction Direction of this FB
1046 1: input, 2: output, or 3: bidirectional
1047 first_group The first UMP Group number (0-15)
1048 num_groups The number of groups in this FB (1-16)
1049 midi1_first_group The first UMP Group number for MIDI 1.0 (0-15)
1050 midi1_num_groups The number of groups for MIDI 1.0 (0-16)
1051 ui_hint UI-hint of this FB
1052 0: unknown, 1: receiver, 2: sender, 3: both
1053 midi_ci_version Supported MIDI-CI version number (8 bit)
1054 is_midi1 Legacy MIDI 1.0 device (0-2)
1055 0: MIDI 2.0 device,
1056 1: MIDI 1.0 without restriction, or
1057 2: MIDI 1.0 with low speed
1058 sysex8_streams Max number of SysEx8 streams (8 bit)
1059 active Bool flag for FB activity (0 or 1)
1060 ================= ===============================================
1062 If multiple Function Blocks are required, you can add more Function
1063 Blocks by creating subdirectories "block.<num>" with the corresponding
1064 Function Block number (1, 2, ....). The FB subdirectories can be
1065 dynamically removed, too. Note that the Function Block numbers must be
1066 continuous.
1068 Similarly, if you multiple UMP Endpoints are required, you can add
1069 more Endpoints by creating subdirectories "ep.<num>". The number must
1070 be continuous.
1072 For emulating the old MIDI 2.0 device without UMP v1.1 support, pass 0
1073 to `process_ump` flag. Then the whole UMP v1.1 requests are ignored.
1075 Testing the MIDI2 function
1076 --------------------------
1078 On the device: run the gadget, and running::
1080 $ cat /proc/asound/cards
1082 will show a new sound card containing a MIDI2 device.
1084 OTOH, on the host::
1086 $ cat /proc/asound/cards
1088 will show a new sound card containing either MIDI1 or MIDI2 device,
1089 depending on the USB audio driver configuration.
1091 On both, when ALSA sequencer is enabled on the host, you can find the
1092 UMP MIDI client such as "MIDI 2.0 Gadget".
1094 As the driver simply loops back the data, there is no need for a real
1095 device just for testing.
1097 For testing a MIDI input from the gadget to the host (e.g. emulating a
1098 MIDI keyboard), you can send a MIDI stream like the following.
1100 On the gadget::
1102 $ aconnect -o
1103 ....
1104 client 20: 'MIDI 2.0 Gadget' [type=kernel,card=1]
1105 0 'MIDI 2.0 '
1106 1 'Group 1 (MIDI 2.0 Gadget I/O)'
1107 $ aplaymidi -p 20:1 to_host.mid
1109 On the host::
1111 $ aconnect -i
1112 ....
1113 client 24: 'MIDI 2.0 Gadget' [type=kernel,card=2]
1114 0 'MIDI 2.0 '
1115 1 'Group 1 (MIDI 2.0 Gadget I/O)'
1116 $ arecordmidi -p 24:1 from_gadget.mid
1118 If you have a UMP-capable application, you can use the UMP port to
1119 send/receive the raw UMP packets, too. For example, aseqdump program
1120 with UMP support can receive from UMP port. On the host::
1122 $ aseqdump -u 2 -p 24:1
1123 Waiting for data. Press Ctrl+C to end.
1124 Source Group Event Ch Data
1125 24:1 Group 0, Program change 0, program 0, Bank select 0:0
1126 24:1 Group 0, Channel pressure 0, value 0x80000000
1128 For testing a MIDI output to the gadget to the host (e.g. emulating a
1129 MIDI synth), it'll be just other way round.
1131 On the gadget::
1133 $ arecordmidi -p 20:1 from_host.mid
1135 On the host::
1137 $ aplaymidi -p 24:1 to_gadget.mid
1139 The access to MIDI 1.0 on altset 0 on the host is supported, and it's
1140 translated from/to UMP packets on the gadget. It's bound to only
1141 Function Block 0.
1143 The current operation mode can be observed in ALSA control element
1144 "Operation Mode" for SND_CTL_IFACE_RAWMIDI. For example::
1146 $ amixer -c1 contents
1147 numid=1,iface=RAWMIDI,name='Operation Mode'
1148 ; type=INTEGER,access=r--v----,values=1,min=0,max=2,step=0
1149 : values=2
1151 where 0 = unused, 1 = MIDI 1.0 (altset 0), 2 = MIDI 2.0 (altset 1).
1152 The example above shows it's running in 2, i.e. MIDI 2.0.

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

문서 범위와 대상 function

1-32

이 문서는 USB gadget이 제공하는 function을 기본적으로 시험하는 데 필요한 정보를 요약합니다.

대상은 ACM, ECM, ECM subset, EEM, FFS, HID, LOOPBACK, MASS STORAGE, MIDI, NCM, OBEX, PHONET, RNDIS, SERIAL, SOURCESINK, 구형 UAC1, UAC2, UVC, PRINTER, `u_audio` API 기반 UAC1, MIDI2의 21종입니다.

시험 대상 21개 function
항목설명
Serial 계열ACM, OBEX, SERIAL
Network 계열ECM, ECM subset, EEM, NCM, PHONET, RNDIS
Data/test 계열FFS, HID, LOOPBACK, MASS STORAGE, SOURCESINK, PRINTER
Media 계열MIDI, UAC1 legacy, UAC2, UVC, UAC1 u_audio, MIDI2

문서의 진행 순서와 function 계열을 정리했습니다.

==============
Gadget Testing
==============

This file summarizes information on basic testing of USB functions
provided by gadgets.

.. contents

   1. ACM function
   2. ECM function
   3. ECM subset function
   4. EEM function
   5. FFS function
   6. HID function
   7. LOOPBACK function
   8. MASS STORAGE function
   9. MIDI function
   10. NCM function
   11. OBEX function
   12. PHONET function
   13. RNDIS function
   14. SERIAL function
   15. SOURCESINK function
   16. UAC1 function (legacy implementation)
   17. UAC2 function
   18. UVC function
   19. PRINTER function
   20. UAC1 function (new API)
   21. MIDI2 function

1. ACM function

33-71

ACM function은 `usb_f_acm.ko` 모듈이 제공합니다.

function 디렉터리를 만들 때 사용하는 이름은 `acm`입니다. 디렉터리에는 읽기 전용 `port_num` 속성 하나가 있습니다.

시스템 전체에서 ACM, generic serial, OBEX port를 합쳐 최대 4개까지 만들 수 있습니다.

시험은 host의 `/dev/ttyACM<X>`와 device의 `/dev/ttyGS<Y>` 사이에서 `cat`으로 데이터를 양방향 전송해 확인합니다.

ACM 구성
항목설명
moduleusb_f_acm.ko
function nameacm
port_num읽기 전용 port number
port limitACM/generic serial/OBEX 합계 최대 4개

ACM function의 모듈, 디렉터리 이름, 속성, 한도입니다.

ACM 양방향 TTY 시험
Host: cat > /dev/ttyACM<X>Device: cat /dev/ttyGS<Y>
Device: cat > /dev/ttyGS<Y>Host: cat /dev/ttyACM<X>

host와 device에서 송신·수신 역할을 서로 바꿉니다.

1. ACM function
===============

The function is provided by usb_f_acm.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "acm".
The ACM function provides just one attribute in its function directory:

	port_num

The attribute is read-only.

There can be at most 4 ACM/generic serial/OBEX ports in the system.


Testing the ACM function
------------------------

On the host::

	cat > /dev/ttyACM<X>

On the device::

	cat /dev/ttyGS<Y>

then the other way round

On the device::

	cat > /dev/ttyGS<Y>

On the host::

	cat /dev/ttyACM<X>

2. ECM function

72-111

ECM function은 `usb_f_ecm.ko` 모듈이 제공하며 function 디렉터리 이름은 `ecm`입니다.

`ifname`은 연결된 network interface 이름, `qmult`는 high/super speed queue 길이 배수, `host_addr`와 `dev_addr`는 Ethernet-over-USB 양 끝의 MAC address입니다.

`functions/ecm.<instance name>`을 만들면 `qmult` 기본값은 5이고 두 MAC address는 무작위로 선택됩니다.

function이 바인딩되지 않은 동안에는 `ifname`을 쓸 수 있습니다. `usb%d` 같은 interface pattern을 쓰면 network core가 다음 빈 `usbX` interface를 선택하며 기본 pattern도 `usb%d`입니다.

시험할 때 device와 host에 IP address를 구성하고 서로의 IP로 ping을 보냅니다.

ECM configfs 속성
항목설명
ifname이 function instance에 연결된 network interface 이름
qmulthigh/super speed용 queue length multiplier
host_addrEthernet-over-USB 링크의 host 측 MAC address
dev_addrEthernet-over-USB 링크의 device 측 MAC address
defaultsqmult=5, MAC address 무작위, ifname=usb%d

ECM instance의 network 속성과 기본값입니다.

ECM 양방향 시험
Device IP 구성ping <host's IP>Host 응답
Host IP 구성ping <device's IP>Device 응답

장치와 호스트에 IP address를 설정한 뒤 양쪽에서 ping을 보냅니다.

2. ECM function
===============

The function is provided by usb_f_ecm.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "ecm".
The ECM function provides these attributes in its function directory:

	=============== ==================================================
	ifname		network device interface name associated with this
			function instance
	qmult		queue length multiplier for high and super speed
	host_addr	MAC address of host's end of this
			Ethernet over USB link
	dev_addr	MAC address of device's end of this
			Ethernet over USB link
	=============== ==================================================

and after creating the functions/ecm.<instance name> they contain default
values: qmult is 5, dev_addr and host_addr are randomly selected.
The ifname can be written to if the function is not bound. A write must be an
interface pattern such as "usb%d", which will cause the net core to choose the
next free usbX interface. By default, it is set to "usb%d".

Testing the ECM function
------------------------

Configure IP addresses of the device and the host. Then:

On the device::

	ping <host's IP>

On the host::

	ping <device's IP>

3. ECM subset function

112-151

ECM subset function은 `usb_f_ecm_subset.ko` 모듈이 제공하며 function 디렉터리 이름은 `geth`입니다.

`ifname`, `qmult`, `host_addr`, `dev_addr`의 의미는 ECM과 같습니다.

원문은 function 생성 뒤의 기본값 설명에서 `functions/ecm.<instance name>` 경로를 사용합니다. 여기에 적힌 기본값은 `qmult=5`, 무작위 `dev_addr`와 `host_addr`입니다.

바인딩 전에는 `ifname`에 `usb%d` 같은 pattern을 쓸 수 있으며 network core가 다음 빈 `usbX`를 고릅니다. 기본값은 `usb%d`입니다.

device와 host에 IP address를 구성한 뒤 양방향 ping으로 시험합니다.

ECM subset configfs 속성
항목설명
ifname이 function instance에 연결된 network interface 이름
qmulthigh/super speed용 queue length multiplier
host_addrEthernet-over-USB 링크의 host 측 MAC address
dev_addrEthernet-over-USB 링크의 device 측 MAC address
function namegeth

`geth` function instance의 network 속성입니다.

ECM subset 양방향 시험
Device IP 구성ping <host's IP>Host 응답
Host IP 구성ping <device's IP>Device 응답

장치와 호스트에 IP address를 설정한 뒤 양쪽에서 ping을 보냅니다.

3. ECM subset function
======================

The function is provided by usb_f_ecm_subset.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "geth".
The ECM subset function provides these attributes in its function directory:

	=============== ==================================================
	ifname		network device interface name associated with this
			function instance
	qmult		queue length multiplier for high and super speed
	host_addr	MAC address of host's end of this
			Ethernet over USB link
	dev_addr	MAC address of device's end of this
			Ethernet over USB link
	=============== ==================================================

and after creating the functions/ecm.<instance name> they contain default
values: qmult is 5, dev_addr and host_addr are randomly selected.
The ifname can be written to if the function is not bound. A write must be an
interface pattern such as "usb%d", which will cause the net core to choose the
next free usbX interface. By default, it is set to "usb%d".

Testing the ECM subset function
-------------------------------

Configure IP addresses of the device and the host. Then:

On the device::

	ping <host's IP>

On the host::

	ping <device's IP>

4. EEM function

152-191

EEM function은 `usb_f_eem.ko` 모듈이 제공하며 function 디렉터리 이름은 `eem`입니다.

제공 속성은 `ifname`, `qmult`, `host_addr`, `dev_addr`입니다.

`functions/eem.<instance name>` 생성 뒤 `qmult`는 5, host/device MAC address는 무작위 값입니다.

function을 아직 바인딩하지 않았다면 `ifname`에 `usb%d` 같은 pattern을 쓸 수 있습니다. 기본 pattern도 `usb%d`이며 network core가 다음 빈 `usbX`를 고릅니다.

device와 host에 IP address를 설정한 뒤 서로 ping을 보내 시험합니다.

EEM configfs 속성
항목설명
ifname이 function instance에 연결된 network interface 이름
qmulthigh/super speed용 queue length multiplier
host_addrEthernet-over-USB 링크의 host 측 MAC address
dev_addrEthernet-over-USB 링크의 device 측 MAC address
defaultsqmult=5, MAC address 무작위, ifname=usb%d

EEM Ethernet-over-USB instance의 속성과 기본값입니다.

EEM 양방향 시험
Device IP 구성ping <host's IP>Host 응답
Host IP 구성ping <device's IP>Device 응답

장치와 호스트에 IP address를 설정한 뒤 양쪽에서 ping을 보냅니다.

4. EEM function
===============

The function is provided by usb_f_eem.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "eem".
The EEM function provides these attributes in its function directory:

	=============== ==================================================
	ifname		network device interface name associated with this
			function instance
	qmult		queue length multiplier for high and super speed
	host_addr	MAC address of host's end of this
			Ethernet over USB link
	dev_addr	MAC address of device's end of this
			Ethernet over USB link
	=============== ==================================================

and after creating the functions/eem.<instance name> they contain default
values: qmult is 5, dev_addr and host_addr are randomly selected.
The ifname can be written to if the function is not bound. A write must be an
interface pattern such as "usb%d", which will cause the net core to choose the
next free usbX interface. By default, it is set to "usb%d".

Testing the EEM function
------------------------

Configure IP addresses of the device and the host. Then:

On the device::

	ping <host's IP>

On the host::

	ping <device's IP>

5. FFS function

192-223

FFS function은 `usb_f_fs.ko` 모듈이 제공하며 function 디렉터리 이름은 `ffs`입니다.

function 디렉터리는 의도적으로 비어 있고 수정할 수 없습니다. 디렉터리를 만들면 새 FunctionFS instance, 즉 device가 시스템에 생깁니다.

instance가 생기면 FunctionFS의 표준 절차에 따라 mount하고 실제 function을 구현하는 사용자 공간 process를 실행해야 합니다. 적절한 문자열을 `usb_gadget/<gadget>/UDC`에 써서 gadget을 활성화합니다.

FFS function은 읽기 전용 `ready` 속성 하나를 제공합니다. 사용자 공간이 ep0에 descriptor와 string을 써서 gadget을 활성화할 준비가 되면 값이 1입니다.

시험은 device에서 function의 사용자 공간 daemon을 시작하고 gadget을 활성화한 뒤, host에서 device가 제공한 USB function을 사용하는 방식입니다.

FFS 상태
항목설명
moduleusb_f_fs.ko
function nameffs
ready읽기 전용; descriptor/string이 ep0에 기록되어 사용 가능하면 1
enableusb_gadget/<gadget>/UDC에 UDC 이름 기록

FunctionFS instance의 준비 상태와 활성화 조건입니다.

FFS 시험 순서
ffs instance 생성FunctionFS mountuserspace daemon이 ep0에 descriptor/string 기록ready=1UDC 기록Host에서 function 사용

사용자 공간 구현이 준비된 뒤에 gadget을 활성화해야 합니다.

5. FFS function
===============

The function is provided by usb_f_fs.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "ffs".
The function directory is intentionally empty and not modifiable.

After creating the directory there is a new instance (a "device") of FunctionFS
available in the system. Once a "device" is available, the user should follow
the standard procedure for using FunctionFS (mount it, run the userspace
process which implements the function proper). The gadget should be enabled
by writing a suitable string to usb_gadget/<gadget>/UDC.

The FFS function provides just one attribute in its function directory:

	ready

The attribute is read-only and signals if the function is ready (1) to be
used, E.G. if userspace has written descriptors and strings to ep0, so
the gadget can be enabled.

Testing the FFS function
------------------------

On the device: start the function's userspace daemon, enable the gadget

On the host: use the USB function provided by the device

6. HID function

224-273

HID function은 `usb_f_hid.ko` 모듈이 제공하며 function 디렉터리 이름은 `hid`입니다.

`protocol`은 HID protocol, `report_desc`는 `/dev/hidg<X>`로 전달하는 데이터 이외의 HID report descriptor 데이터, `report_length`는 report 길이, `subclass`는 HID subclass를 지정합니다.

키보드 예제에서는 `protocol=1`, `subclass=1`, `report_length=8`을 사용합니다. 원문은 `hd my_report_desc`로 63바이트 report descriptor를 보여 줍니다.

이 byte sequence는 `echo -ne \x05\x01...` 형식으로 `report_desc` 속성에 저장할 수 있습니다.

device에서 gadget을 만들고 가능하면 제어에 쓰는 host와 다른 host에 연결한 뒤 `/dev/hidg<N>`에 쓰는 프로그램을 실행합니다.

예제 `./hid_gadget_test /dev/hidg0 keyboard`는 `Documentation/usb/gadget_hid.rst`의 사용자 공간 프로그램이며, host에서 gadget이 보낸 keystroke를 관찰합니다.

HID configfs 속성
항목설명
protocol사용할 HID protocol; keyboard 예제 1
report_descHID report descriptor byte data
report_lengthHID report 길이; keyboard 예제 8
subclass사용할 HID subclass; keyboard 예제 1

HID descriptor와 report 전송을 정의하는 속성입니다.

HID keyboard 시험
HID gadget 생성별도 host에 연결hid_gadget_test가 /dev/hidg0에 report 기록USB HID 전송Host에서 keystroke 관찰

device의 hidg node에 쓴 report가 host의 키 입력으로 관찰됩니다.

6. HID function
===============

The function is provided by usb_f_hid.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "hid".
The HID function provides these attributes in its function directory:

	=============== ===========================================
	protocol	HID protocol to use
	report_desc	data to be used in HID reports, except data
			passed with /dev/hidg<X>
	report_length	HID report length
	subclass	HID subclass to use
	=============== ===========================================

For a keyboard the protocol and the subclass are 1, the report_length is 8,
while the report_desc is::

  $ hd my_report_desc
  00000000  05 01 09 06 a1 01 05 07  19 e0 29 e7 15 00 25 01  |..........)...%.|
  00000010  75 01 95 08 81 02 95 01  75 08 81 03 95 05 75 01  |u.......u.....u.|
  00000020  05 08 19 01 29 05 91 02  95 01 75 03 91 03 95 06  |....).....u.....|
  00000030  75 08 15 00 25 65 05 07  19 00 29 65 81 00 c0     |u...%e....)e...|
  0000003f

Such a sequence of bytes can be stored to the attribute with echo::

  $ echo -ne \\x05\\x01\\x09\\x06\\xa1.....

Testing the HID function
------------------------

Device:

- create the gadget
- connect the gadget to a host, preferably not the one used
  to control the gadget
- run a program which writes to /dev/hidg<N>, e.g.
  a userspace program found in Documentation/usb/gadget_hid.rst::

	$ ./hid_gadget_test /dev/hidg0 keyboard

Host:

- observe the keystrokes from the gadget

7. LOOPBACK function

274-296

LOOPBACK function은 `usb_f_ss_lb.ko` 모듈이 제공하며 function 디렉터리 이름은 대소문자를 포함한 `Loopback`입니다.

`qlen`은 loopback queue 깊이이고 `bulk_buflen`은 buffer 길이입니다.

device에서는 gadget을 실행합니다.

host에서는 `tools/usb/testusb.c`의 `test-usb`를 사용해 시험합니다.

LOOPBACK configfs 속성
항목설명
qlenloopback queue depth
bulk_buflenbuffer length

loopback data path의 queue와 buffer 크기입니다.

LOOPBACK 시험
Device: Loopback gadget 실행USB 연결Host: test-usb전송 데이터 loopback 확인

host의 test-usb가 gadget loopback endpoint를 검증합니다.

7. LOOPBACK function
====================

The function is provided by usb_f_ss_lb.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "Loopback".
The LOOPBACK function provides these attributes in its function directory:

	=============== =======================
	qlen		depth of loopback queue
	bulk_buflen	buffer length
	=============== =======================

Testing the LOOPBACK function
-----------------------------

device: run the gadget

host: test-usb (tools/usb/testusb.c)

8. MASS STORAGE function

297-359

MASS STORAGE function은 `usb_f_mass_storage.ko` 모듈이 제공하며 function 디렉터리 이름은 `mass_storage`입니다.

function 수준의 `stall`은 bulk endpoint halt 허용 여부입니다. 올바르게 동작하지 않는 것으로 알려진 일부 USB device에서는 비활성화되지만, 일반적으로 true로 설정해야 합니다.

`num_buffers`는 pipeline buffer 수이며 유효 범위는 2부터 4입니다. `CONFIG_USB_GADGET_DEBUG_FILES`가 설정된 경우에만 노출됩니다.

기본으로 SCSI LUN #0에 해당하는 `lun.0` 디렉터리가 생깁니다. `mkdir functions/mass_storage.0/partition.5`처럼 새 LUN을 추가할 수 있습니다.

LUN 번호는 기본 생성되는 0번을 제외하면 연속일 필요가 없습니다. 최대 8개를 지정할 수 있고 이름은 `<name>.<number>` 형식이어야 하며 번호는 0..8입니다. `lun.<number>`가 권장 관례지만 필수는 아닙니다.

각 LUN에서 `file`은 backing file 경로, `ro`는 읽기 전용, `removable`은 이동식 표시, `cdrom`은 CD-ROM 표시, `nofua`는 SCSI WRITE(10,12)의 FUA flag 관련 설정입니다. `forced_eject`는 활성 function의 backing file을 host 허가와 무관하게 강제로 분리하는 쓰기 전용 파일이며 0이 아닌 바이트를 쓰면 eject됩니다.

시험은 device에서 gadget을 연결·활성화하고 host의 `dmesg`와 자동 mount 결과에서 USB drive가 나타나는지 확인합니다.

MASS STORAGE function 속성
항목설명
stallbulk endpoint halt 허용; 일반적으로 true 권장
num_bufferspipeline buffer 2..4; CONFIG_USB_GADGET_DEBUG_FILES 필요
default LUNlun.0 / SCSI LUN #0
LUN limit최대 8개, 번호 0..8, <name>.<number> 형식

function 전체에 적용되는 endpoint와 pipeline 설정입니다.

LUN 속성
항목설명
fileLUN backing file 경로; non-removable이면 필수
ro읽기 전용; CD-ROM 또는 R/W open 실패 때도 암시됨
removable이동식 LUN 표시
cdromCD-ROM으로 보고
nofuaSCSI WRITE(10,12)의 FUA flag 설정
forced_eject쓰기 전용; 0이 아닌 write로 backing file 강제 분리

각 backing store의 접근 방식과 매체 특성을 설정합니다.

MASS STORAGE 시험
Backing file과 LUN 구성Mass Storage gadget 활성화Host USB enumerationdmesg 확인USB drive 또는 자동 mount 확인

활성화한 LUN이 host에 USB storage drive로 열거되는지 확인합니다.

8. MASS STORAGE function
========================

The function is provided by usb_f_mass_storage.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "mass_storage".
The MASS STORAGE function provides these attributes in its directory:
files:

	=============== ==============================================
	stall		Set to permit function to halt bulk endpoints.
			Disabled on some USB devices known not to work
			correctly. You should set it to true.
	num_buffers	Number of pipeline buffers. Valid numbers
			are 2..4. Available only if
			CONFIG_USB_GADGET_DEBUG_FILES is set.
	=============== ==============================================

and a default lun.0 directory corresponding to SCSI LUN #0.

A new lun can be added with mkdir::

	$ mkdir functions/mass_storage.0/partition.5

Lun numbering does not have to be continuous, except for lun #0 which is
created by default. A maximum of 8 luns can be specified and they all must be
named following the <name>.<number> scheme. The numbers can be 0..8.
Probably a good convention is to name the luns "lun.<number>",
although it is not mandatory.

In each lun directory there are the following attribute files:

	=============== ==============================================
	file		The path to the backing file for the LUN.
			Required if LUN is not marked as removable.
	ro		Flag specifying access to the LUN shall be
			read-only. This is implied if CD-ROM emulation
			is enabled as well as when it was impossible
			to open "filename" in R/W mode.
	removable	Flag specifying that LUN shall be indicated as
			being removable.
	cdrom		Flag specifying that LUN shall be reported as
			being a CD-ROM.
	nofua		Flag specifying that FUA flag
			in SCSI WRITE(10,12)
	forced_eject	This write-only file is useful only when
			the function is active. It causes the backing
			file to be forcibly detached from the LUN,
			regardless of whether the host has allowed it.
			Any non-zero number of bytes written will
			result in ejection.
	=============== ==============================================

Testing the MASS STORAGE function
---------------------------------

device: connect the gadget, enable it
host: dmesg, see the USB drives appear (if system configured to automatically
mount)

9. MIDI function

360-447

MIDI function은 `usb_f_midi.ko` 모듈이 제공하며 function 디렉터리 이름은 `midi`입니다.

속성은 MIDI buffer 길이 `buflen`, USB MIDI adapter ID 문자열 `id`, 입력·출력 port 수 `in_ports`·`out_ports`, adapter index `index`, USB read request queue 길이 `qlen`입니다.

시험은 gadget에서 host로 MIDI 파일을 재생하는 경우와 host에서 gadget으로 재생하는 경우로 나뉩니다.

gadget→host 시험에서 host는 `arecordmidi -p 24:0 from_gadget.mid`로 기록하고 gadget은 `aplaymidi -p 20:0 to_host.mid`로 재생합니다. `from_gadget.mid`는 `to_host.mid`와 동일하게 들려야 합니다.

host→gadget 시험에서는 gadget이 `arecordmidi -p 20:0 from_host.mid`로 기록하고 host가 `aplaymidi -p24:0 to_gadget.mid`로 재생합니다. 원문은 결과 파일을 `from_host.id`라고 적고 있으며 `to_gadget.mid`와 동일하게 들려야 한다고 설명합니다.

TiMidity가 설치되어 있으면 `aplaymidi -p 128:0 file.mid`처럼 MIDI 파일을 speaker/headphone으로 재생할 수 있습니다.

`aconnect 24:0 128:0`처럼 MIDI port를 논리적으로 연결할 수 있습니다.

gadget MIDI port를 TiMidity port에 연결하면 gadget 측에서 재생한 내용이 host speaker/headphone으로 들립니다. 원문의 마지막 문장은 gadget 측 명령을 `aplaymidi -l`로 표기합니다.

MIDI configfs 속성
항목설명
buflenMIDI buffer length
idUSB MIDI adapter ID string
in_portsMIDI input port 수
indexUSB MIDI adapter index
out_portsMIDI output port 수
qlenUSB read request queue length

USB MIDI adapter의 buffer, port, queue를 설정합니다.

MIDI 파일 양방향 시험
Gadget: aplaymidi -p 20:0 to_host.midHost: arecordmidi -p 24:0 from_gadget.mid두 파일 비교
Host: aplaymidi -p24:0 to_gadget.midGadget: arecordmidi -p 20:0 from_host.mid두 파일 비교

송신 측 aplaymidi와 수신 측 arecordmidi의 결과 파일을 비교합니다.

MIDI 실시간 청취
MIDI Gadget port 24:0aconnectTiMidity port 128:0Host speaker/headphone

aconnect로 gadget port를 TiMidity port에 연결해 host audio output으로 듣습니다.

9. MIDI function
================

The function is provided by usb_f_midi.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "midi".
The MIDI function provides these attributes in its function directory:

	=============== ====================================
	buflen		MIDI buffer length
	id		ID string for the USB MIDI adapter
	in_ports	number of MIDI input ports
	index		index value for the USB MIDI adapter
	out_ports	number of MIDI output ports
	qlen		USB read request queue length
	=============== ====================================

Testing the MIDI function
-------------------------

There are two cases: playing a mid from the gadget to
the host and playing a mid from the host to the gadget.

1) Playing a mid from the gadget to the host:

host::

  $ arecordmidi -l
   Port    Client name                      Port name
   14:0    Midi Through                     Midi Through Port-0
   24:0    MIDI Gadget                      MIDI Gadget MIDI 1
  $ arecordmidi -p 24:0 from_gadget.mid

gadget::

  $ aplaymidi -l
   Port    Client name                      Port name
   20:0    f_midi                           f_midi

  $ aplaymidi -p 20:0 to_host.mid

2) Playing a mid from the host to the gadget

gadget::

  $ arecordmidi -l
   Port    Client name                      Port name
   20:0    f_midi                           f_midi

  $ arecordmidi -p 20:0 from_host.mid

host::

  $ aplaymidi -l
   Port    Client name                      Port name
   14:0    Midi Through                     Midi Through Port-0
   24:0    MIDI Gadget                      MIDI Gadget MIDI 1

  $ aplaymidi -p24:0 to_gadget.mid

The from_gadget.mid should sound identical to the to_host.mid.

The from_host.id should sound identical to the to_gadget.mid.

MIDI files can be played to speakers/headphones with e.g. timidity installed::

  $ aplaymidi -l
   Port    Client name                      Port name
   14:0    Midi Through                     Midi Through Port-0
   24:0    MIDI Gadget                      MIDI Gadget MIDI 1
  128:0    TiMidity                         TiMidity port 0
  128:1    TiMidity                         TiMidity port 1
  128:2    TiMidity                         TiMidity port 2
  128:3    TiMidity                         TiMidity port 3

  $ aplaymidi -p 128:0 file.mid

MIDI ports can be logically connected using the aconnect utility, e.g.::

  $ aconnect 24:0 128:0 # try it on the host

After the gadget's MIDI port is connected to timidity's MIDI port,
whatever is played at the gadget side with aplaymidi -l is audible
in host's speakers/headphones.

10. NCM function

448-489

NCM function은 `usb_f_ncm.ko` 모듈이 제공하며 function 디렉터리 이름은 `ncm`입니다.

`ifname`, `qmult`, `host_addr`, `dev_addr`는 다른 Ethernet gadget과 같은 의미입니다.

`max_segment_size`는 P2P 연결에 필요한 segment 크기이며 원문은 이것이 MTU를 14바이트로 설정한다고 설명합니다.

instance 생성 뒤 `qmult=5`, 두 MAC address는 무작위, `ifname=usb%d`가 기본입니다. 바인딩 전에는 interface pattern을 써서 다음 빈 `usbX`를 선택하게 할 수 있습니다.

device와 host에 IP address를 구성한 뒤 양방향 ping으로 시험합니다.

NCM configfs 속성
항목설명
ifname이 function instance에 연결된 network interface 이름
qmulthigh/super speed용 queue length multiplier
host_addrEthernet-over-USB 링크의 host 측 MAC address
dev_addrEthernet-over-USB 링크의 device 측 MAC address
max_segment_sizeP2P connection segment size; 원문 기준 MTU 14 bytes
defaultsqmult=5, MAC address 무작위, ifname=usb%d

NCM network 속성에 P2P용 segment 크기가 추가됩니다.

NCM 양방향 시험
Device IP 구성ping <host's IP>Host 응답
Host IP 구성ping <device's IP>Device 응답

장치와 호스트에 IP address를 설정한 뒤 양쪽에서 ping을 보냅니다.

10. NCM function
================

The function is provided by usb_f_ncm.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "ncm".
The NCM function provides these attributes in its function directory:

	======================= ==================================================
	ifname			network device interface name associated with this
				function instance
	qmult			queue length multiplier for high and super speed
	host_addr		MAC address of host's end of this
				Ethernet over USB link
	dev_addr		MAC address of device's end of this
				Ethernet over USB link
	max_segment_size	Segment size required for P2P connections. This
				will set MTU to 14 bytes
	======================= ==================================================

and after creating the functions/ncm.<instance name> they contain default
values: qmult is 5, dev_addr and host_addr are randomly selected.
The ifname can be written to if the function is not bound. A write must be an
interface pattern such as "usb%d", which will cause the net core to choose the
next free usbX interface. By default, it is set to "usb%d".

Testing the NCM function
------------------------

Configure IP addresses of the device and the host. Then:

On the device::

	ping <host's IP>

On the host::

	ping <device's IP>

11. OBEX function

490-522

OBEX function은 `usb_f_obex.ko` 모듈이 제공하며 function 디렉터리 이름은 `obex`입니다.

읽기 전용 `port_num` 속성 하나를 제공합니다.

시스템의 ACM, generic serial, OBEX port 합계는 최대 4개입니다.

device에서는 `seriald -f /dev/ttyGS<Y> -s 1024`를 실행합니다. host에서는 vendor/product ID, interface 번호, endpoint address를 지정해 `serialc`를 실행합니다.

`seriald`와 `serialc`는 `https://github.com/felipebalbi/usb-tools.git`의 master branch에 있는 Felipe의 utility입니다.

OBEX 구성
항목설명
moduleusb_f_obex.ko
function nameobex
port_num읽기 전용
port limitACM/generic serial/OBEX 합계 최대 4
toolsFelipe usb-tools의 seriald / serialc

OBEX port와 시험 utility입니다.

OBEX serial 시험
Device: seriald + /dev/ttyGS<Y>USB OBEX interfaceHost: serialc + VID/PID/interface/endpoints전송 결과 확인

device daemon과 host client 사이에 1024-byte 전송을 구성합니다.

11. OBEX function
=================

The function is provided by usb_f_obex.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "obex".
The OBEX function provides just one attribute in its function directory:

	port_num

The attribute is read-only.

There can be at most 4 ACM/generic serial/OBEX ports in the system.

Testing the OBEX function
-------------------------

On device::

	seriald -f /dev/ttyGS<Y> -s 1024

On host::

	serialc -v <vendorID> -p <productID> -i<interface#> -a1 -s1024 \
                -t<out endpoint addr> -r<in endpoint addr>

where seriald and serialc are Felipe's utilities found here:

	https://github.com/felipebalbi/usb-tools.git master

12. PHONET function

523-587

PHONET function은 `usb_f_phonet.ko` 모듈이 제공하며 function 디렉터리 이름은 `phonet`입니다.

function instance에 연결된 network interface 이름을 나타내는 `ifname` 속성 하나를 제공합니다.

특정 하드웨어 없이는 `SOCK_STREAM` protocol을 시험할 수 없으므로 원문에서는 `SOCK_DGRAM`만 시험했습니다. 과거에는 이를 위해 원문에 연결된 linux-usb patch가 필요했습니다.

시험에는 `git://git.gitorious.org/meego-cellular/phonet-utils.git`의 도구가 필요합니다.

host는 주소 `0x10`을 `usbpn0`에 지정하고 `0x6c`, `0x10` route를 추가한 뒤 interface를 올립니다. device는 주소 `0x6c`을 `upnlink0`에 지정하고 `0x10` route를 추가한 뒤 interface를 올립니다.

host→device 시험은 device에서 `pnxmit -a 0x6c -r`, host에서 `pnxmit -a 0x10 -s 0x6c`을 실행하며 데이터가 device로 전달되어야 합니다.

반대 방향은 host에서 `pnxmit -a 0x10 -r`, device에서 `pnxmit -a 0x6c -s 0x10`을 실행합니다.

PHONET 구성
항목설명
ifnamefunction instance의 network interface 이름
Hostusbpn0, address 0x10, routes 0x6c/0x10
Deviceupnlink0, address 0x6c, route 0x10
검증 protocolSOCK_DGRAM; SOCK_STREAM은 특정 hardware 필요

interface, 주소, route 구성을 구분합니다.

PHONET 양방향 pnxmit 시험
Device: pnxmit -a 0x6c -rHost: pnxmit -a 0x10 -s 0x6cHost→Device data
Host: pnxmit -a 0x10 -rDevice: pnxmit -a 0x6c -s 0x10Device→Host data

수신 측을 먼저 실행한 뒤 반대편에서 지정 주소로 송신합니다.

12. PHONET function
===================

The function is provided by usb_f_phonet.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "phonet".
The PHONET function provides just one attribute in its function directory:

	=============== ==================================================
	ifname		network device interface name associated with this
			function instance
	=============== ==================================================

Testing the PHONET function
---------------------------

It is not possible to test the SOCK_STREAM protocol without a specific piece
of hardware, so only SOCK_DGRAM has been tested. For the latter to work,
in the past I had to apply the patch mentioned here:

http://www.spinics.net/lists/linux-usb/msg85689.html

These tools are required:

git://git.gitorious.org/meego-cellular/phonet-utils.git

On the host::

	$ ./phonet -a 0x10 -i usbpn0
	$ ./pnroute add 0x6c usbpn0
	$./pnroute add 0x10 usbpn0
	$ ifconfig usbpn0 up

On the device::

	$ ./phonet -a 0x6c -i upnlink0
	$ ./pnroute add 0x10 upnlink0
	$ ifconfig upnlink0 up

Then a test program can be used::

	http://www.spinics.net/lists/linux-usb/msg85690.html

On the device::

	$ ./pnxmit -a 0x6c -r

On the host::

	$ ./pnxmit -a 0x10 -s 0x6c

As a result some data should be sent from host to device.
Then the other way round:

On the host::

	$ ./pnxmit -a 0x10 -r

On the device::

	$ ./pnxmit -a 0x6c -s 0x10

13. RNDIS function

588-627

RNDIS function은 `usb_f_rndis.ko` 모듈이 제공하며 function 디렉터리 이름은 `rndis`입니다.

속성은 `ifname`, `qmult`, `host_addr`, `dev_addr`입니다.

`functions/rndis.<instance name>` 생성 뒤 `qmult=5`, MAC address는 무작위로 선택됩니다.

바인딩 전에는 `ifname`에 `usb%d` 같은 interface pattern을 쓸 수 있고 network core가 다음 빈 `usbX`를 선택합니다. 기본값은 `usb%d`입니다.

device와 host에 IP address를 구성한 뒤 양방향 ping으로 시험합니다.

RNDIS configfs 속성
항목설명
ifname이 function instance에 연결된 network interface 이름
qmulthigh/super speed용 queue length multiplier
host_addrEthernet-over-USB 링크의 host 측 MAC address
dev_addrEthernet-over-USB 링크의 device 측 MAC address
defaultsqmult=5, MAC address 무작위, ifname=usb%d

RNDIS Ethernet-over-USB instance의 속성과 기본값입니다.

RNDIS 양방향 시험
Device IP 구성ping <host's IP>Host 응답
Host IP 구성ping <device's IP>Device 응답

장치와 호스트에 IP address를 설정한 뒤 양쪽에서 ping을 보냅니다.

13. RNDIS function
==================

The function is provided by usb_f_rndis.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "rndis".
The RNDIS function provides these attributes in its function directory:

	=============== ==================================================
	ifname		network device interface name associated with this
			function instance
	qmult		queue length multiplier for high and super speed
	host_addr	MAC address of host's end of this
			Ethernet over USB link
	dev_addr	MAC address of device's end of this
			Ethernet over USB link
	=============== ==================================================

and after creating the functions/rndis.<instance name> they contain default
values: qmult is 5, dev_addr and host_addr are randomly selected.
The ifname can be written to if the function is not bound. A write must be an
interface pattern such as "usb%d", which will cause the net core to choose the
next free usbX interface. By default, it is set to "usb%d".

Testing the RNDIS function
--------------------------

Configure IP addresses of the device and the host. Then:

On the device::

	ping <host's IP>

On the host::

	ping <device's IP>

14. SERIAL function

628-670

SERIAL function은 `usb_f_gser.ko` 모듈이 제공하며 function 디렉터리 이름은 `gser`입니다.

읽기 전용 `port_num` 속성 하나를 제공합니다.

시스템의 ACM, generic serial, OBEX port 합계는 최대 4개입니다.

host에서 `usbserial`을 로드하고 `generic/new_id`에 gadget의 VID와 PID를 등록합니다.

그 뒤 host의 `/dev/ttyUSB<X>`와 target의 `/dev/ttyGS<Y>`에서 `cat` 송수신 방향을 서로 바꿔 양방향 전송을 확인합니다.

SERIAL 구성
항목설명
moduleusb_f_gser.ko
function namegser
port_num읽기 전용
host driverusbserial + generic/new_id에 VID PID 등록
port limitACM/generic serial/OBEX 합계 최대 4

generic USB serial driver 등록과 port 제한입니다.

SERIAL 양방향 TTY 시험
Host: cat > /dev/ttyUSB<X>Target: cat /dev/ttyGS<Y>
Target: cat > /dev/ttyGS<Y>Host: cat /dev/ttyUSB<X>

host의 ttyUSB와 target의 ttyGS 사이를 양방향으로 시험합니다.

14. SERIAL function
===================

The function is provided by usb_f_gser.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "gser".
The SERIAL function provides just one attribute in its function directory:

	port_num

The attribute is read-only.

There can be at most 4 ACM/generic serial/OBEX ports in the system.

Testing the SERIAL function
---------------------------

On host::

	insmod usbserial
	echo VID PID >/sys/bus/usb-serial/drivers/generic/new_id

On host::

	cat > /dev/ttyUSB<X>

On target::

	cat /dev/ttyGS<Y>

then the other way round

On target::

	cat > /dev/ttyGS<Y>

On host::

	cat /dev/ttyUSB<X>

15. SOURCESINK function

671-700

SOURCESINK function은 LOOPBACK과 같은 `usb_f_ss_lb.ko` 모듈이 제공하며 function 디렉터리 이름은 대소문자를 포함한 `SourceSink`입니다.

`pattern`은 0이면 all zeros, 1이면 mod63, 2이면 pattern 없음입니다. isochronous 설정은 `isoc_interval` 1..16, `isoc_maxpacket`은 full speed 0..1023 및 high/super speed 0..1024, `isoc_mult`는 high/super speed에서 0..2, `isoc_maxburst`는 super speed에서 0..15입니다.

bulk와 iso queue는 `bulk_buflen`, `bulk_qlen`, `iso_qlen`으로 buffer 길이와 queue 깊이를 설정합니다.

device에서 gadget을 실행하고 host에서 `tools/usb/testusb.c`의 `test-usb`로 시험합니다.

SOURCESINK configfs 속성
항목설명
pattern0=zeros, 1=mod63, 2=none
isoc_interval1..16
isoc_maxpacket0..1023 fs, 0..1024 hs/ss
isoc_mult0..2, hs/ss only
isoc_maxburst0..15, ss only
bulk_buflenbulk buffer length
bulk_qlenbulk queue depth
iso_qleniso queue depth

data pattern과 bulk/iso endpoint queue를 구성합니다.

SOURCESINK 시험
Device: SourceSink gadget 실행pattern/bulk/iso 설정USB 연결Host: test-usbsource/sink 결과 확인

host의 test-usb가 지정 pattern과 endpoint 전송을 검증합니다.

15. SOURCESINK function
=======================

The function is provided by usb_f_ss_lb.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "SourceSink".
The SOURCESINK function provides these attributes in its function directory:

	=============== ==================================
	pattern		0 (all zeros), 1 (mod63), 2 (none)
	isoc_interval	1..16
	isoc_maxpacket	0 - 1023 (fs), 0 - 1024 (hs/ss)
	isoc_mult	0..2 (hs/ss only)
	isoc_maxburst	0..15 (ss only)
	bulk_buflen	buffer length
	bulk_qlen	depth of queue for bulk
	iso_qlen	depth of queue for iso
	=============== ==================================

Testing the SOURCESINK function
-------------------------------

device: run the gadget

host: test-usb (tools/usb/testusb.c)

16. UAC1 function (legacy)

701-732

구형 UAC1 function은 `usb_f_uac1_legacy.ko` 모듈이 제공하며 function 디렉터리 이름은 `uac1_legacy`입니다.

`audio_buf_size`는 audio buffer 크기, `fn_cap`은 capture PCM device 파일, `fn_cntl`은 control device 파일, `fn_play`는 playback PCM device 파일입니다.

`req_buf_size`와 `req_count`는 각각 ISO OUT endpoint request buffer 크기와 request 수이며, 모든 속성에는 합리적인 기본값이 있습니다.

device에서 gadget을 실행하고 host에서 `aplay -l`을 실행해 USB Audio Gadget이 목록에 나타나는지 확인합니다.

UAC1 legacy configfs 속성
항목설명
audio_buf_sizeaudio buffer size
fn_capcapture PCM device file name
fn_cntlcontrol device file name
fn_playplayback PCM device file name
req_buf_sizeISO OUT request buffer size
req_countISO OUT request count

기존 ALSA device file 연결과 ISO OUT request를 설정합니다.

UAC1 legacy 시험
Device: uac1_legacy gadget 실행USB Audio enumerationHost: aplay -lUSB Audio Gadget 항목 확인

host ALSA 목록에서 USB Audio Gadget을 확인합니다.

16. UAC1 function (legacy implementation)
=========================================

The function is provided by usb_f_uac1_legacy.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory
is "uac1_legacy".
The uac1 function provides these attributes in its function directory:

	=============== ====================================
	audio_buf_size	audio buffer size
	fn_cap		capture pcm device file name
	fn_cntl		control device file name
	fn_play		playback pcm device file name
	req_buf_size	ISO OUT endpoint request buffer size
	req_count	ISO OUT endpoint request count
	=============== ====================================

The attributes have sane default values.

Testing the UAC1 function
-------------------------

device: run the gadget

host::

	aplay -l # should list our USB Audio Gadget

17. UAC2 function

733-802

UAC2 function은 `usb_f_uac2.ko` 모듈이 제공하며 function 디렉터리 이름은 `uac2`입니다.

capture 속성은 channel mask `c_chmask`, comma-separated sample rate 목록 `c_srate`, sample size `c_ssize`, synchronization type `c_sync`, mute/volume enable, 1/256dB 단위 volume min/max/resolution, HS/SS `bInterval`인 `c_hs_bint`입니다.

`fb_max`는 asynchronous mode의 최대 추가 대역폭입니다. playback 쪽은 `p_chmask`, `p_srate`, `p_ssize`, mute/volume enable, volume min/max/resolution, `p_hs_bint`를 제공합니다.

`req_number`는 capture와 playback 양쪽에 미리 할당할 request 수입니다. `function_name`, `if_ctrl_name`, input/output clock, playback/capture terminal·channel·function unit 이름과 terminal type code도 설정할 수 있습니다.

모든 속성에는 합리적인 기본값이 있습니다.

device에서 gadget을 실행하고 host의 `aplay -l`에서 USB Audio Gadget을 확인합니다. 실제 hardware 없이 host와 audio data stream을 주고받을 수 있습니다.

device에서 실제 소리를 들으려면 `arecord`로 gadget capture stream을 읽어 `aplay`로 실제 sound card에 전달합니다. 원문은 `hw:2,0 → hw:0,0`과 `UAC2Gadget → OdroidU3` 예제를 제공합니다.

UAC2 capture와 playback 속성
항목설명
c_chmask / p_chmaskcapture / playback channel mask
c_srate / p_sratecomma-separated sampling rate 목록
c_ssize / p_ssizesample size(bytes)
c_synccapture sync type: async/adaptive
c_mute_present / p_mute_presentmute control enable
c_volume_present / p_volume_presentvolume control enable
*_volume_min/max/res1/256dB 단위 min/max/resolution
c_hs_bint / p_hs_bintHS/SS bInterval; 1..4 fixed, 0 auto
fb_maxasync mode 최대 추가 대역폭
req_numbercapture/playback pre-allocated request 수

양방향 audio format, control, endpoint interval을 구성합니다.

UAC2 이름과 terminal 속성
항목설명
function_name / if_ctrl_nameinterface 이름 / topology control 이름
clksrc_in_name / clksrc_out_nameinput/output clock 이름
p_it_name / p_it_ch_name / p_ot_nameplayback input terminal, first channel, output terminal 이름
p_fu_vol_nameplayback function unit 이름
c_it_name / c_it_ch_name / c_ot_namecapture input terminal, first channel, output terminal 이름
c_fu_vol_namecapture functional unit 이름
c_terminal_type / p_terminal_typecapture / playback terminal type code

USB Audio topology에 노출할 interface, clock, terminal, unit 이름과 type입니다.

UAC2 실제 청취 경로
Host audio streamUAC2 GadgetDevice arecordpipeDevice aplay실제 sound card / speaker

가상 UAC2 capture를 실제 ALSA playback 장치로 pipe합니다.

17. UAC2 function
=================

The function is provided by usb_f_uac2.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "uac2".
The uac2 function provides these attributes in its function directory:

	================ ====================================================
	c_chmask         capture channel mask
	c_srate          list of capture sampling rates (comma-separated)
	c_ssize          capture sample size (bytes)
	c_sync           capture synchronization type (async/adaptive)
	c_mute_present   capture mute control enable
	c_volume_present capture volume control enable
	c_volume_min     capture volume control min value (in 1/256 dB)
	c_volume_max     capture volume control max value (in 1/256 dB)
	c_volume_res     capture volume control resolution (in 1/256 dB)
	c_hs_bint        capture bInterval for HS/SS (1-4: fixed, 0: auto)
	fb_max           maximum extra bandwidth in async mode
	p_chmask         playback channel mask
	p_srate          list of playback sampling rates (comma-separated)
	p_ssize          playback sample size (bytes)
	p_mute_present   playback mute control enable
	p_volume_present playback volume control enable
	p_volume_min     playback volume control min value (in 1/256 dB)
	p_volume_max     playback volume control max value (in 1/256 dB)
	p_volume_res     playback volume control resolution (in 1/256 dB)
	p_hs_bint        playback bInterval for HS/SS (1-4: fixed, 0: auto)
	req_number       the number of pre-allocated request for both capture
	                 and playback
	function_name    name of the interface
	if_ctrl_name     topology control name
	clksrc_in_name   input clock name
	clksrc_out_name  output clock name
	p_it_name        playback input terminal name
	p_it_ch_name     playback input first channel name
	p_ot_name        playback output terminal name
	p_fu_vol_name    playback function unit name
	c_it_name        capture input terminal name
	c_it_ch_name     capture input first channel name
	c_ot_name        capture output terminal name
	c_fu_vol_name    capture functional unit name
	c_terminal_type  code of the capture terminal type
	p_terminal_type  code of the playback terminal type
	================ ====================================================

The attributes have sane default values.

Testing the UAC2 function
-------------------------

device: run the gadget
host: aplay -l # should list our USB Audio Gadget

This function does not require real hardware support, it just
sends a stream of audio data to/from the host. In order to
actually hear something at the device side, a command similar
to this must be used at the device side::

	$ arecord -f dat -t wav -D hw:2,0 | aplay -D hw:0,0 &

e.g.::

	$ arecord -f dat -t wav -D hw:CARD=UAC2Gadget,DEV=0 | \
	  aplay -D default:CARD=OdroidU3

18. UVC function

803-882

UVC function은 `usb_f_uvc.ko` 모듈이 제공하며 function 디렉터리 이름은 `uvc`입니다.

function root 속성은 endpoint polling interval `streaming_interval`, SuperSpeed companion descriptor의 `bMaxBurst`인 `streaming_maxburst`, endpoint 최대 packet 크기 `streaming_maxpacket`, interface 이름 `function_name`입니다.

`control`과 `streaming` 하위 디렉터리에는 다시 여러 하위 디렉터리가 있습니다. 합리적인 기본값도 있지만 control header, streaming header, format description, frame description은 사용자가 제공해야 합니다.

control header는 `control/header`에 만들고 `control/class/fs` 및/또는 `control/class/ss`에서 링크합니다. streaming header는 `streaming/header`에 만들고 fs/hs/ss class에서 필요한 속도에 링크합니다.

format은 `streaming/mjpeg` 및/또는 `streaming/uncompressed`에 만들고, frame은 해당 format 디렉터리 아래에 만듭니다. 각 frame의 `dwFrameInterval`은 줄마다 interval 값 하나를 갖습니다.

시험할 때 device에서 gadget과 `vivid`를 실행하고 `uvc-gadget -u <uvc node> -v <vivid node>`를 사용합니다. 원문은 ideasonboard의 uvc-gadget과 지정 patch를 참조합니다.

host에서는 `luvcview -f yuv`로 영상 스트림을 확인합니다.

UVC function root 속성
항목설명
streaming_intervaldata endpoint polling interval
streaming_maxburstSuperSpeed companion descriptor bMaxBurst
streaming_maxpacket선택 configuration에서 endpoint가 송수신 가능한 최대 packet size
function_nameinterface 이름

streaming endpoint와 interface 이름을 구성합니다.

UVC 사용자가 제공할 descriptor 구조
항목설명
control headercontrol/header 생성 → control/class/fs 및/또는 class/ss 링크
streaming headerstreaming/header 생성 → class/fs, class/hs, class/ss 링크
format descriptionstreaming/mjpeg 및/또는 streaming/uncompressed
frame description각 format 아래 생성; dwFrameInterval은 줄당 값 하나

control/streaming header와 format/frame 위치입니다.

UVC 시험 경로
Device: modprobe vividvivid /dev/video nodeuvc-gadgetUVC /dev/video nodeUSB hostluvcview -f yuv

vivid source를 uvc-gadget으로 전달하고 host viewer에서 확인합니다.

18. UVC function
================

The function is provided by usb_f_uvc.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "uvc".
The uvc function provides these attributes in its function directory:

	=================== ================================================
	streaming_interval  interval for polling endpoint for data transfers
	streaming_maxburst  bMaxBurst for super speed companion descriptor
	streaming_maxpacket maximum packet size this endpoint is capable of
			    sending or receiving when this configuration is
			    selected
	function_name       name of the interface
	=================== ================================================

There are also "control" and "streaming" subdirectories, each of which contain
a number of their subdirectories. There are some sane defaults provided, but
the user must provide the following:

	================== ====================================================
	control header     create in control/header, link from control/class/fs
			   and/or control/class/ss
	streaming header   create in streaming/header, link from
			   streaming/class/fs and/or streaming/class/hs and/or
			   streaming/class/ss
	format description create in streaming/mjpeg and/or
			   streaming/uncompressed
	frame description  create in streaming/mjpeg/<format> and/or in
			   streaming/uncompressed/<format>
	================== ====================================================

Each frame description contains frame interval specification, and each
such specification consists of a number of lines with an interval value
in each line. The rules stated above are best illustrated with an example::

  # mkdir functions/uvc.usb0/control/header/h
  # cd functions/uvc.usb0/control/
  # ln -s header/h class/fs
  # ln -s header/h class/ss
  # mkdir -p functions/uvc.usb0/streaming/uncompressed/u/360p
  # cat <<EOF > functions/uvc.usb0/streaming/uncompressed/u/360p/dwFrameInterval
  666666
  1000000
  5000000
  EOF
  # cd $GADGET_CONFIGFS_ROOT
  # mkdir functions/uvc.usb0/streaming/header/h
  # cd functions/uvc.usb0/streaming/header/h
  # ln -s ../../uncompressed/u
  # cd ../../class/fs
  # ln -s ../../header/h
  # cd ../../class/hs
  # ln -s ../../header/h
  # cd ../../class/ss
  # ln -s ../../header/h


Testing the UVC function
------------------------

device: run the gadget, modprobe vivid::

  # uvc-gadget -u /dev/video<uvc video node #> -v /dev/video<vivid video node #>

where uvc-gadget is this program:
	http://git.ideasonboard.org/uvc-gadget.git

with these patches:

	https://lore.kernel.org/r/1386675637-18243-1-git-send-email-r.baldyga@samsung.com/

host::

	luvcview -f yuv

19. PRINTER function

883-937

PRINTER function은 `usb_f_printer.ko` 모듈이 제공하며 function 디렉터리 이름은 `printer`입니다.

`pnp_string`은 host에 전달할 PNP string 데이터이고 `q_len`은 endpoint당 request 수입니다.

가장 기본적인 시험에서 device는 gadget을 실행하고 `/devices/virtual/usb_printer_gadget/`을 나열해 `g_printer<number>`가 보이는지 확인합니다.

udev가 활성화되어 있으면 device의 `/dev/g_printer<number>`와 host의 `/dev/usb/lp0`이 자동으로 생겨야 합니다.

host→device 전송은 device에서 `cat /dev/g_printer<number>`로 읽고 host에서 `cat > /dev/usb/lp0`으로 씁니다.

device→host 전송은 device에서 `cat > /dev/g_printer<number>`로 쓰고 host에서 `cat /dev/usb/lp0`으로 읽습니다.

고급 시험은 `Documentation/usb/gadget_printer.rst`에 설명된 `prn_example`로 수행할 수 있습니다.

PRINTER configfs 속성
항목설명
pnp_stringhost에 전달할 PNP string data
q_lenendpoint당 request 수

host descriptor 문자열과 endpoint request queue를 설정합니다.

PRINTER 양방향 전송
Host: cat > /dev/usb/lp0Device: cat /dev/g_printer<number>
Device: cat > /dev/g_printer<number>Host: cat /dev/usb/lp0

device의 g_printer node와 host의 lp node에서 송수신 역할을 바꿉니다.

PRINTER 장치 node 확인
Printer gadget 실행/devices/virtual/usb_printer_gadget/g_printer<number>udevDevice /dev/g_printer<number>Host /dev/usb/lp0

gadget enumeration과 udev가 양쪽 device node를 생성하는지 확인합니다.

19. PRINTER function
====================

The function is provided by usb_f_printer.ko module.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "printer".
The printer function provides these attributes in its function directory:

	==========	===========================================
	pnp_string	Data to be passed to the host in pnp string
	q_len		Number of requests per endpoint
	==========	===========================================

Testing the PRINTER function
----------------------------

The most basic testing:

device: run the gadget::

	# ls -l /devices/virtual/usb_printer_gadget/

should show g_printer<number>.

If udev is active, then /dev/g_printer<number> should appear automatically.

host:

If udev is active, then e.g. /dev/usb/lp0 should appear.

host->device transmission:

device::

	# cat /dev/g_printer<number>

host::

	# cat > /dev/usb/lp0

device->host transmission::

	# cat > /dev/g_printer<number>

host::

	# cat /dev/usb/lp0

More advanced testing can be done with the prn_example
described in Documentation/usb/gadget_printer.rst.

20. UAC1 function (u_audio API)

938-1001

새 UAC1 function은 `usb_f_uac1.ko` 모듈이 제공하며 가상 ALSA card를 만들고 audio stream을 그 card로 sink/source합니다. function 디렉터리 이름은 `uac1`입니다.

capture 쪽은 `c_chmask`, comma-separated `c_srate`, `c_ssize`, mute/volume enable, 1/256dB 단위 volume min/max/resolution을 제공합니다.

playback 쪽은 대응하는 `p_chmask`, `p_srate`, `p_ssize`, mute/volume enable, volume min/max/resolution을 제공합니다.

`req_number`는 capture와 playback 양쪽의 pre-allocated request 수이고 `function_name`은 interface 이름입니다. playback/capture input terminal, channel, output terminal, mute/volume functional unit 이름도 설정할 수 있습니다.

속성에는 합리적인 기본값이 있습니다. 실제 hardware 없이 host와 audio data stream을 주고받습니다.

device에서 gadget을 실행하고 host의 `aplay -l`에서 USB Audio Gadget을 확인합니다. 실제 소리를 들으려면 device의 `arecord` 출력을 실제 sound card의 `aplay`로 pipe하며 원문은 `UAC1Gadget → OdroidU3` 예제를 제공합니다.

UAC1 u_audio capture/playback 속성
항목설명
c_chmask / p_chmaskcapture / playback channel mask
c_srate / p_sratecomma-separated sampling rate 목록
c_ssize / p_ssizesample size(bytes)
c_mute_present / p_mute_presentmute control enable
c_volume_present / p_volume_presentvolume control enable
*_volume_min/max/res1/256dB 단위 min/max/resolution
req_numbercapture/playback pre-allocated request 수
function_nameinterface 이름

가상 ALSA card의 양방향 format과 control을 설정합니다.

UAC1 u_audio topology 이름
항목설명
p_it_name / p_it_ch_name / p_ot_nameplayback input terminal, channels, output terminal
p_fu_vol_nameplayback mute/volume functional unit
c_it_name / c_it_ch_name / c_ot_namecapture input terminal, channels, output terminal
c_fu_vol_namecapture mute/volume functional unit

USB Audio terminal, channel, functional unit의 표시 이름입니다.

UAC1 u_audio 실제 청취 경로
Host audio streamUAC1 GadgetVirtual ALSA cardDevice arecordpipeDevice aplay실제 speaker

가상 UAC1 capture stream을 실제 playback 장치로 전달합니다.

20. UAC1 function (virtual ALSA card, using u_audio API)
========================================================

The function is provided by usb_f_uac1.ko module.
It will create a virtual ALSA card and the audio streams are simply
sinked to and sourced from it.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "uac1".
The uac1 function provides these attributes in its function directory:

	================ ====================================================
	c_chmask         capture channel mask
	c_srate          list of capture sampling rates (comma-separated)
	c_ssize          capture sample size (bytes)
	c_mute_present   capture mute control enable
	c_volume_present capture volume control enable
	c_volume_min     capture volume control min value (in 1/256 dB)
	c_volume_max     capture volume control max value (in 1/256 dB)
	c_volume_res     capture volume control resolution (in 1/256 dB)
	p_chmask         playback channel mask
	p_srate          list of playback sampling rates (comma-separated)
	p_ssize          playback sample size (bytes)
	p_mute_present   playback mute control enable
	p_volume_present playback volume control enable
	p_volume_min     playback volume control min value (in 1/256 dB)
	p_volume_max     playback volume control max value (in 1/256 dB)
	p_volume_res     playback volume control resolution (in 1/256 dB)
	req_number       the number of pre-allocated requests for both capture
	                 and playback
	function_name    name of the interface
	p_it_name        playback input terminal name
	p_it_ch_name     playback channels name
	p_ot_name        playback output terminal name
	p_fu_vol_name    playback mute/volume functional unit name
	c_it_name        capture input terminal name
	c_it_ch_name     capture channels name
	c_ot_name        capture output terminal name
	c_fu_vol_name    capture mute/volume functional unit name
	================ ====================================================

The attributes have sane default values.

Testing the UAC1 function
-------------------------

device: run the gadget
host: aplay -l # should list our USB Audio Gadget

This function does not require real hardware support, it just
sends a stream of audio data to/from the host. In order to
actually hear something at the device side, a command similar
to this must be used at the device side::

	$ arecord -f dat -t wav -D hw:2,0 | aplay -D hw:0,0 &

e.g.::

	$ arecord -f dat -t wav -D hw:CARD=UAC1Gadget,DEV=0 | \
	  aplay -D default:CARD=OdroidU3

21. MIDI2 function

1002-1152

MIDI2 function은 `usb_f_midi2.ko` 모듈이 제공합니다. UMP packet을 loopback하는 UMP rawmidi device가 포함된 가상 ALSA card를 만들고, legacy rawmidi device도 함께 생성합니다. UMP rawmidi는 ALSA sequencer client에도 바인딩됩니다.

function 디렉터리 이름은 `midi2`입니다. card 최상위에는 UMP Stream message 처리 여부 `process_ump`, static block 여부 `static_block`, 선택적 interface 이름 `iface_name`이 있습니다.

`ep.0` 하위 디렉터리는 USB MIDI endpoint 한 쌍을 나타내는 UMP Endpoint 속성을 제공합니다. `protocol_caps`는 MIDI 1.0, MIDI 2.0 또는 둘 다를 1, 2, 3으로 표시하고 `protocol`은 기본 protocol 1 또는 2입니다.

Endpoint에는 `ep_name`, `product_id`, 24-bit `manufacturer`, 16-bit `family`와 `model`, 32-bit `sw_revision`도 있습니다.

각 Endpoint의 `block.0`은 Function Block 0을 나타냅니다. 이름, direction, 첫 group과 group 수, MIDI 1.0용 group 범위, UI hint, MIDI-CI version, legacy MIDI 1.0 유형, SysEx8 stream 최대 수, active flag를 설정합니다.

`direction`은 input=1, output=2, bidirectional=3입니다. `first_group`은 0..15, `num_groups`는 1..16, MIDI 1.0용 첫 group은 0..15이고 group 수는 0..16입니다.

`ui_hint`는 unknown=0, receiver=1, sender=2, both=3입니다. `is_midi1`은 MIDI 2.0 device=0, 제한 없는 MIDI 1.0=1, low speed MIDI 1.0=2입니다.

여러 Function Block이 필요하면 연속 번호의 `block.<num>`을 만들며 동적으로 제거할 수도 있습니다. 여러 UMP Endpoint도 연속 번호의 `ep.<num>`으로 추가합니다.

UMP v1.1을 지원하지 않는 구형 MIDI 2.0 device를 모방하려면 `process_ump=0`으로 설정해 모든 UMP v1.1 요청을 무시합니다.

device와 host 각각에서 `/proc/asound/cards`를 확인하면 새 sound card가 나타납니다. host에서는 USB audio driver 구성에 따라 MIDI1 또는 MIDI2 device로 보입니다. ALSA sequencer가 활성화되면 양쪽에서 `MIDI 2.0 Gadget` 같은 UMP MIDI client를 찾을 수 있습니다.

driver는 데이터를 단순 loopback하므로 시험에 실제 MIDI hardware가 필요하지 않습니다.

gadget→host 입력 시험은 gadget에서 `aplaymidi -p 20:1 to_host.mid`, host에서 `arecordmidi -p 24:1 from_gadget.mid`를 사용합니다. UMP 지원 응용 프로그램은 raw UMP packet도 송수신할 수 있고, 예제 `aseqdump -u 2 -p 24:1`은 Program change와 Channel pressure를 표시합니다.

host→gadget 출력 시험은 gadget에서 `arecordmidi -p 20:1 from_host.mid`, host에서 `aplaymidi -p 24:1 to_gadget.mid`를 실행합니다.

host의 altset 0 MIDI 1.0 접근도 지원되며 gadget에서 UMP packet으로 상호 변환되고 Function Block 0에만 연결됩니다. 현재 mode는 `SND_CTL_IFACE_RAWMIDI`의 ALSA control `Operation Mode`로 확인합니다. 값 0은 unused, 1은 MIDI 1.0(altset 0), 2는 MIDI 2.0(altset 1)이며 원문 예제 값 2는 MIDI 2.0 동작을 뜻합니다.

MIDI2 card 최상위 속성
항목설명
process_umpUMP Stream message 처리 bool; 0이면 UMP v1.1 요청 무시
static_blockstatic block bool, 0 또는 1
iface_name선택적 interface name string

MIDI2 interface와 UMP message 처리 방식을 설정합니다.

MIDI2 UMP Endpoint 속성
항목설명
protocol_caps1=MIDI 1.0, 2=MIDI 2.0, 3=both
protocol기본 protocol 1 또는 2
ep_nameUMP Endpoint name
product_idProduct ID string
manufacturer24-bit Manufacture ID
family / model16-bit family / model ID
sw_revision32-bit software revision

`ep.<num>`의 protocol capability와 device identity입니다.

MIDI2 Function Block 속성
항목설명
nameFunction Block name
direction1=input, 2=output, 3=bidirectional
first_group / num_groups첫 UMP Group 0..15 / group 수 1..16
midi1_first_group / midi1_num_groupsMIDI 1.0 첫 group 0..15 / group 수 0..16
ui_hint0=unknown, 1=receiver, 2=sender, 3=both
midi_ci_version8-bit MIDI-CI version
is_midi10=MIDI2, 1=MIDI1 unrestricted, 2=MIDI1 low speed
sysex8_streams8-bit SysEx8 stream 최대 수
activeFunction Block active bool

`block.<num>`의 group 범위, 방향, capability와 상태입니다.

MIDI2 configfs 계층
midi2 functionep.0block.0
midi2 functionep.1 ... ep.Nblock.0 ... block.N

Endpoint와 Function Block은 각각 연속 번호로 확장합니다.

MIDI2 양방향 sequencer 시험
Gadget: aplaymidi -p 20:1Host: arecordmidi -p 24:1gadget→host
Host: aplaymidi -p 24:1Gadget: arecordmidi -p 20:1host→gadget

ALSA sequencer port 20:1과 24:1 사이에서 MIDI 파일을 주고받습니다.

MIDI2 Operation Mode
amixer -c1 contentsOperation Mode0 unused / 1 MIDI 1.0 altset 0 / 2 MIDI 2.0 altset 1

ALSA RAWMIDI control 값이 현재 alternate setting과 protocol을 나타냅니다.

21. MIDI2 function
==================

The function is provided by usb_f_midi2.ko module.
It will create a virtual ALSA card containing a UMP rawmidi device
where the UMP packet is looped back. In addition, a legacy rawmidi
device is created. The UMP rawmidi is bound with ALSA sequencer
clients, too.

Function-specific configfs interface
------------------------------------

The function name to use when creating the function directory is "midi2".
The midi2 function provides these attributes in its function directory
as the card top-level information:

	=============	=================================================
	process_ump	Bool flag to process UMP Stream messages (0 or 1)
	static_block	Bool flag for static blocks (0 or 1)
	iface_name	Optional interface name string
	=============	=================================================

The directory contains a subdirectory "ep.0", and this provides the
attributes for a UMP Endpoint (which is a pair of USB MIDI Endpoints):

	=============	=================================================
	protocol_caps	MIDI protocol capabilities;
			1: MIDI 1.0, 2: MIDI 2.0, or 3: both protocols
	protocol	Default MIDI protocol (either 1 or 2)
	ep_name		UMP Endpoint name string
	product_id	Product ID string
	manufacturer	Manufacture ID number (24 bit)
	family		Device family ID number (16 bit)
	model		Device model ID number (16 bit)
	sw_revision	Software revision (32 bit)
	=============	=================================================

Each Endpoint subdirectory contains a subdirectory "block.0", which
represents the Function Block for Block 0 information.
Its attributes are:

	=================	===============================================
	name			Function Block name string
	direction		Direction of this FB
				1: input, 2: output, or 3: bidirectional
	first_group		The first UMP Group number (0-15)
	num_groups		The number of groups in this FB (1-16)
	midi1_first_group	The first UMP Group number for MIDI 1.0 (0-15)
	midi1_num_groups	The number of groups for MIDI 1.0 (0-16)
	ui_hint			UI-hint of this FB
				0: unknown, 1: receiver, 2: sender, 3: both
	midi_ci_version		Supported MIDI-CI version number (8 bit)
	is_midi1		Legacy MIDI 1.0 device (0-2)
				0: MIDI 2.0 device,
				1: MIDI 1.0 without restriction, or
				2: MIDI 1.0 with low speed
	sysex8_streams		Max number of SysEx8 streams (8 bit)
	active			Bool flag for FB activity (0 or 1)
	=================	===============================================

If multiple Function Blocks are required, you can add more Function
Blocks by creating subdirectories "block.<num>" with the corresponding
Function Block number (1, 2, ....). The FB subdirectories can be
dynamically removed, too. Note that the Function Block numbers must be
continuous.

Similarly, if you multiple UMP Endpoints are required, you can add
more Endpoints by creating subdirectories "ep.<num>". The number must
be continuous.

For emulating the old MIDI 2.0 device without UMP v1.1 support, pass 0
to `process_ump` flag. Then the whole UMP v1.1 requests are ignored.

Testing the MIDI2 function
--------------------------

On the device: run the gadget, and running::

  $ cat /proc/asound/cards

will show a new sound card containing a MIDI2 device.

OTOH, on the host::

  $ cat /proc/asound/cards

will show a new sound card containing either MIDI1 or MIDI2 device,
depending on the USB audio driver configuration.

On both, when ALSA sequencer is enabled on the host, you can find the
UMP MIDI client such as "MIDI 2.0 Gadget".

As the driver simply loops back the data, there is no need for a real
device just for testing.

For testing a MIDI input from the gadget to the host (e.g. emulating a
MIDI keyboard), you can send a MIDI stream like the following.

On the gadget::

  $ aconnect -o
  ....
  client 20: 'MIDI 2.0 Gadget' [type=kernel,card=1]
      0 'MIDI 2.0        '
      1 'Group 1 (MIDI 2.0 Gadget I/O)'
  $ aplaymidi -p 20:1 to_host.mid

On the host::

  $ aconnect -i
  ....
  client 24: 'MIDI 2.0 Gadget' [type=kernel,card=2]
      0 'MIDI 2.0        '
      1 'Group 1 (MIDI 2.0 Gadget I/O)'
  $ arecordmidi -p 24:1 from_gadget.mid

If you have a UMP-capable application, you can use the UMP port to
send/receive the raw UMP packets, too. For example, aseqdump program
with UMP support can receive from UMP port. On the host::

  $ aseqdump -u 2 -p 24:1
  Waiting for data. Press Ctrl+C to end.
  Source  Group    Event                  Ch  Data
   24:1   Group  0, Program change          0, program 0, Bank select 0:0
   24:1   Group  0, Channel pressure        0, value 0x80000000

For testing a MIDI output to the gadget to the host (e.g. emulating a
MIDI synth), it'll be just other way round.

On the gadget::

  $ arecordmidi -p 20:1 from_host.mid

On the host::

  $ aplaymidi -p 24:1 to_gadget.mid

The access to MIDI 1.0 on altset 0 on the host is supported, and it's
translated from/to UMP packets on the gadget. It's bound to only
Function Block 0.

The current operation mode can be observed in ALSA control element
"Operation Mode" for SND_CTL_IFACE_RAWMIDI.  For example::

  $ amixer -c1 contents
  numid=1,iface=RAWMIDI,name='Operation Mode'
    ; type=INTEGER,access=r--v----,values=1,min=0,max=2,step=0
    : values=2

where 0 = unused, 1 = MIDI 1.0 (altset 0), 2 = MIDI 2.0 (altset 1).
The example above shows it's running in 2, i.e. MIDI 2.0.