diff --git a/doc/USB.html b/doc/USB.html index d57c70cd0..45baa9772 100644 --- a/doc/USB.html +++ b/doc/USB.html @@ -51,16 +51,19 @@

USB in simavr.

tests/test_usb_host.h is a complete example that enumerates a device and exchanges bulk data.

-When no data is ready, a read from a bulk IN endpoint returns 0 with a size -of zero rather than AVR_IOCTL_USB_NAK. Suspend and resume, OTG and host mode, double-buffered endpoints and data toggle checking are not simulated.

-examples/extra_board_usb connects the simulated device to Linux -through the out-of-tree usb-vhci kernel module, so that it appears as a real -USB device. -That module is no longer maintained and does not build on current kernels -without patches. +examples/parts/usbip_usb.c plays the host for you and exports the +simulated device over USB/IP, so that a USB/IP client attaches it to a +real USB stack, where it appears as an ordinary USB device. +On Linux the client is the mainline vhci-hcd driver and the usbip +tool, on Windows usbip-win2. +examples/board_simduino_leonardo is an Arduino Leonardo this way, +an ATmega32U4 with Arduino's Caterina bootloader that avrdude uploads +sketches to. +examples/board_usbserial is the Arduino Uno R3's USB to +serial adapter, an ATmega16U2 with its USART looped back or on a pty. diff --git a/doc/manual/setupguide.tex b/doc/manual/setupguide.tex index 9c408bd6d..8cf900f00 100644 --- a/doc/manual/setupguide.tex +++ b/doc/manual/setupguide.tex @@ -37,10 +37,6 @@ \subsection{Software Dependencies} \item make 3.82 \end{itemize} -Furthermore, the board\_usb example depends on libusb\_vhci and vhci\_hcd. For -further details, see \emph{examples/board\_usb/README}. Note however that these -are not required for a fully working \simavr build. - \subsection{Compilation and Installation} \simavr's build system relies on standard makefiles. The simplest compilation diff --git a/examples/Makefile b/examples/Makefile index 65cc8933b..cebcf0f73 100644 --- a/examples/Makefile +++ b/examples/Makefile @@ -2,7 +2,7 @@ boards_base=${wildcard board_*} # Remove simduino until FileMapping is implemented to work around missing mmap in Win32 ifeq (${shell uname -o}, Msys) -boards=${subst board_usb,,${subst board_simduino,,$(boards_base)}} +boards=$(filter-out board_simduino,$(boards_base)) else boards=$(boards_base) endif @@ -12,11 +12,3 @@ all: clean: for bi in ${boards}; do $(MAKE) -C $$bi clean; done - -# -# The USB example is not made by default, as it downloads stuff -# for the vhci library, it fails the debian policy on being able -# to build offline. -# -extra_board_usb: - make -C extra_board_usb diff --git a/examples/board_simduino_leonardo/Caterina-Leonardo-bootloader.hex b/examples/board_simduino_leonardo/Caterina-Leonardo-bootloader.hex new file mode 100644 index 000000000..f2a0595f9 --- /dev/null +++ b/examples/board_simduino_leonardo/Caterina-Leonardo-bootloader.hex @@ -0,0 +1,128 @@ +:2070000055C000006EC000006CC000006AC0000068C0000066C0000064C0000062C0000043 +:2070200060C000005EC00000F2C400005AC0000058C0000056C0000054C0000052C00000EE +:2070400050C0000078C000004CC000004AC0000048C0000046C0000044C0000042C00000BE +:2070600040C000003EC000003CC000003AC0000038C0000036C0000034C0000032C0000048 +:2070800030C000002EC000002CC000002AC0000028C0000026C0000024C0000022C00000A8 +:2070A00020C000001EC000001CC0000011241FBECFEFDAE0DEBFCDBF11E0A0E0B1E0E2E3BC +:2070C000FFE702C005900D92A83AB107D9F711E0A8EAB1E001C01D92AE3BB107E1F78FD30B +:2070E00026C78ECFF89410926F0010928100109285001092840081E085BF15BE47985D9AEB +:20710000289A0C94000008952091B2013091B3012F5F3F4F3093B3012093B201932F37FFA6 +:2071200003C08EEF831B982F990F921710F447980895479A08951F920F920FB60F9211246E +:207140002F938F939F93EF93FF9310928500109284008091A8019091A901009741F00197D3 +:207160009093A9018093A801892B09F45D9A8091AA019091AB01009741F001979093AB0126 +:207180008093AA01892B09F4289AE0E0F0E0859194918F5F9F4F49F08091AC019091AD0151 +:2071A00001969093AD018093AC01FF91EF919F918F912F910F900FBE0F901F90189584E0BC +:2071C0008093E9000DC08091E8008B778093E80003C08EB3882351F08091E80082FFF9CFBE +:2071E0008091E80085FFEFCF8091F1000895982F83E08093E9008091E80085FD0DC0809136 +:20720000E8008E778093E80003C08EB3882369F08091E80080FFF9CF9093F1005D9884E6CB +:2072200090E09093A9018093A80108954F925F926F927F928F929F92AF92BF92CF92DF921E +:20724000EF92FF920F931F93CF93DF9384E08093E9008091E80082FF57C2289884E690E067 +:207260009093AB018093AA01AADF182F853481F48CE49DE19093AD018093AC0107B600FC4B +:20728000FDCFF999FECF81E180935700E89503C0843519F494DF8DE00DC28C34E1F38035F9 +:2072A000D1F3843721F484E4A2DF80E003C2813611F489E5FFC18134B1F481DF182F7FDFE3 +:2072C00090E0880F991FAA2797FDA095BA2F312F330F20E0442737FD4095542F822B932B68 +:2072E000A42BB52BB8C1803711F483E5E3C1833549F4C0E0D1E089917ADF21E0C730D20714 +:20730000D1F7D9C1863521F481E371DF80E3D2C1833731F487E86BDF85E969DF8EE1CAC149 +:207320008536B9F4E0E0F0E093E085E090935700E89507B600FCFDCF80935700E89507B65D +:2073400000FCFDCFE058FF4FA0E7E030FA0771F7A2CF823739F4E1E0F0E089E08093570024 +:207360008491A8C1863439F4E0E0F0E089E08093570084919FC18E3439F4E3E0F0E089E0E5 +:2073800080935700849196C1813539F4E2E0F0E089E08093570084918DC1823631F489E521 +:2073A00026DF80E024DF80E885C1823419F0873609F0E5C01092AD011092AC0100DF082FE8 +:2073C000FEDEF82EFCDE682E8554823008F071C1902F80E0CF2DD0E0C82BD92B10926F00B3 +:2073E000173609F04BC081E180935700E895DD24CC24C3943FC0E090AE01F090AF010091CC +:20740000B0011091B101B6E46B16D9F4ED2DF0E0EE29FF29E4918E2FEADEDD2081F082E08D +:2074200090E0A0E0B0E0E80EF91E0A1F1B1FE092AE01F092AF010093B0011093B101DC2470 +:2074400018C0D801C701B695A7959795879559D5CEDE82E090E0A0E0B0E0E80EF91E0A1FF2 +:207460001B1FE092AE01F092AF010093B0011093B1012197209709F0BECF7DC08090AE01F5 +:207480009090AF01A090B001B090B10196E4691609F05DC083E0F40180935700E89507B63E +:2074A00000FCFDCF54C0F6E46F1661F5772031F1E090AE01F090AF010091B0011091B1019E +:2074C0007EDED82ECC24852D90E08C299D29F7010C0140925700E895112482E090E0A0E08B +:2074E000B0E0E80EF91E0A1F1B1FE092AE01F092AF010093B0011093B10102C060DE582E1A +:20750000742423C0E090AE01F090AF010091B0011091B10116950795F794E79450DE682FFA +:20752000C701F7D48091AE019091AF01A091B001B091B1010296A11DB11D8093AE01909349 +:20754000AF01A093B001B093B101219704C05524772444244394209709F0A5CF96E46916B6 +:2075600041F485E0F40180935700E89507B600FCFDCF8DE03CDE82E080936F009CC0833492 +:2075800071F40091AE011091AF0119DE90E021E0F8010C0120935700E89511247CCE8336C8 +:2075A00019F5E090AE01F090AF010091B0011091B10105DEF701E16090E021E00C0120938C +:2075C0005700E895112482E090E0A0E0B0E0E80EF91E0A1F1B1FE092AE01F092AF0100936A +:2075E000B0011093B10157CE8D3661F4E091AE01F091AF0185E080935700E89507B600FCF2 +:20760000FDCF49CE823551F4E091AE01F091AF0105911491812FEBDD802F4CC0843421F5FE +:20762000E090AE01F090AF010091B0011091B10116950795F794E794C2DD682FC70169D4DE +:207640008091AE019091AF01A091B001B091B1010296A11DB11D8093AE019093AF01A093D8 +:20766000B001B093B10117CE843609F5E090AE01F090AF010091B0011091B101D801C70142 +:20768000B695A795979587953CD4B1DD82E090E0A0E0B0E0E80EF91E0A1F1B1FE092AE010A +:2076A000F092AF010093B0011093B10104C08B3111F08FE39CDD83E08093E9009091E8002B +:2076C0008091E8008E778093E80095FF04C010C08EB38823C9F08091E80080FFF9CF809193 +:2076E000E8008E778093E80003C08EB3882361F08091E80080FFF9CF84E08093E9008091F1 +:20770000E8008B778093E800DF91CF911F910F91FF90EF90DF90CF90BF90AF909F908F90AC +:207720007F906F905F904F9008959091B601892F8F77813249F58091B7018032A1F081328A +:2077400019F5913A09F58091E800877F8093E8008DE091E067E070E00BD28091E8008B770B +:207760008093E8000895913279F48091E800877F8093E8008DE091E067E070E05DD2809192 +:20778000E8008E778093E800089582E061EC42E0B5D083E061E842E1B1D084E060E842E1EF +:2077A000ADC084B7877F84BF88E10FB6F89480936000109260000FBE20E880E090E00FB63F +:2077C000F89420936100809361000FBE81E085BF92E095BF3F9A209A559AE1E6F0E02083A1 +:2077E000108247985D9A289A109289008AEF8093880090936F0083E080938100F0C0409116 +:20780000000850910108109201081092000894B714BE88E10FB6F8948093600010926000D5 +:207820000FBE292F30E0F901E270F07091FD18C090FF05C0859194918F5F9F4F81F423FFFF +:207840000FC08091090190910A014817590741F0E0E0F0E0859194918F5F9F4F09F042DC64 +:20786000A0DF78941092AD011092AC010CC0DEDC36D38091AC019091AD0181549F4110F00D +:207880001092140141DC80911401882381F78091E00081608093E00025DC80E090E0089598 +:2078A000FA01923049F0933061F09130F9F485E191E022E130E01EC087E291E02EE330E04D +:2078C00019C0882329F485E691E024E030E012C0813029F489E691E022E230E00BC0823006 +:2078E00029F48DE891E028E130E004C080E090E020E030E091838083C90108958093E9004E +:207900008091EB0081608093EB001092ED006093EC004093ED008091EE00881F8827881F62 +:2079200008958091B60188238CF403C08EB38823B1F08091E80082FFF9CF8091E8008B772A +:207940008093E80008958EB3882349F08091E80080FFF9CF8091E8008E778093E800089594 +:20796000EF92FF920F931F9345D04CD008ED10E0F80180818F77808380818068808380819B +:207980008F7D808319BC1EBA1092B40180EEE82EF12CF70180818B7F8083F8018081816052 +:2079A000808380E060E042E0A9DFE1EEF0E080818E7F8083E2EEF0E0808181608083808144 +:2079C00088608083F70180818E7F8083F8018081806180831F910F91FF90EF900895E7ED06 +:2079E000F0E08081816080838AE482BF81E08093B501B6CFE8EDF0E080818E7F808310921C +:207A0000E20008951092DA001092E10008951F920F920FB60F9211242F933F934F935F93F6 +:207A20006F937F938F939F93AF93BF93EF93FF938091DA0080FF1BC08091D80080FF17C0B2 +:207A40008091DA008E7F8093DA008091D90080FF0BC080E189BD82E189BD09B400FEFDCF36 +:207A600081E08EBB3BD203C019BC1EBA37D28091E10080FF17C08091E20080FF13C0809138 +:207A8000E2008E7F8093E2008091E20080618093E2008091D80080628093D80019BC85E049 +:207AA0008EBB1CD28091E10084FF2CC08091E20084FF28C080E189BD82E189BD09B400FEC5 +:207AC000FDCF8091D8008F7D8093D8008091E1008F7E8093E1008091E2008F7E8093E20012 +:207AE0008091E20081608093E2008091B401882331F48091E30087FD02C081E001C084E067 +:207B00008EBBECD18091E10083FF21C08091E20083FF1DC08091E100877F8093E10082E06A +:207B20008EBB1092B4018091E1008E7F8093E1008091E2008E7F8093E2008091E2008061E9 +:207B40008093E20080E060E042E0D8DEC7D1FF91EF91BF91AF919F918F917F916F915F9130 +:207B60004F913F912F910F900FBE0F901F9018959C014091BC015091BD014617570718F49D +:207B8000F90190E044C06115710511F0AB01F8CF8091E8008E778093E80040E050E0F0CF0F +:207BA0008EB3882309F444C0853009F443C08091E80083FF02C081E008958091E80082FD70 +:207BC00031C08091E80080FF22C08091F3009091F200782F60E0292F30E0262B372B07C07A +:207BE00081918093F100415050402F5F3F4F4115510519F02830310598F390E02830310566 +:207C000009F491E08091E8008E778093E8004115510531F6992321F605C08EB3882341F075 +:207C2000853041F08091E80082FFF7CF80E0089582E0089583E008959C016115710529F47C +:207C40008091E8008B778093E800F90126C08EB3882391F1853091F18091E80083FF02C06C +:207C600081E008958091E80082FFF1CF06C08091F10081936150704059F02091F300809191 +:207C8000F200322F20E090E0822B932B892B79F78091E8008B778093E80061157105B9F601 +:207CA00005C08EB3882341F0853041F08091E80080FFF7CF80E0089582E0089583E00895C2 +:207CC0000F931F93DF93CF9300D0CDB7DEB7E6EBF1E08091F100819381E0EE3BF807C9F792 +:207CE00024DD8091E80083FFE4C08091B6019091B701953009F46DC0963040F4913081F1A7 +:207D0000913070F0933009F0D4C02AC0983009F4A3C0993009F4B2C0963009F0CAC07CC023 +:207D2000803809F4C6C0823809F0C3C08091BA0187708093E9008091EB001092E9002091DB +:207D4000E800277F2093E80090E025E0969587952A95E1F781708093F1001092F10087C0D8 +:207D6000882319F0823009F0A4C08F71823009F0A0C08091B801882331F52091BA01277097 +:207D800009F497C02093E9008091EB0080FF1BC0933021F48091EB00806213C08091EB0018 +:207DA00080618093EB0081E090E002C0880F991F2A95E2F78093EA001092EA008091EB00E5 +:207DC00088608093EB001092E9008091E800877F51C0882309F06DC01091B8011F770FB79B +:207DE000F8948091E800877F8093E8009ADD8091E80080FFFCCF8091E3008078812B809398 +:207E0000E30080688093E300112311F482E001C083E08EBB0FBF4DC08058823008F049C033 +:207E20008091B8019091B9016091BA01AE014F5F5F4F36DDBC01009709F43BC08091E8008E +:207E4000877F8093E80089819A8192DE8091E8008B778093E8002DC0803859F58091E800AA +:207E6000877F8093E8008091B4018093F1008091E8008E778093E80054DD1BC08823C9F4CA +:207E80009091B8019230A8F48091E800877F8093E8009093B40145DD8091B401882331F420 +:207EA0008091E30087FD02C081E001C084E08EBB6CDC8091E80083FF0AC08091EB0080624E +:207EC0008093EB008091E800877F8093E8000F900F90CF91DF911F910F91089508951F9360 +:207EE0008EB3882361F01091E9001092E9008091E80083FF01C0E4DE17701093E9001F916F +:207F00000895F999FECF92BD81BDF89A992780B50895262FF999FECF1FBA92BD81BD20BDBD +:207F20000FB6F894FA9AF99A0FBE01960895F894FFCF4341544552494E4100777700080031 +:207F40000000000000080112011001020000084123360001000201000109023E00020100FF +:207F600080320904000001020201000524001001042402040524060001070582030800FF0C +:207F800009040100020A000000070504021000010705830210000104030904220341007216 +:207FA000006400750069006E006F0020004C0065006F006E006100720064006F0000001836 +:1A7FC00003410072006400750069006E006F0020004C004C004300000000D7 +:00000001FF diff --git a/examples/board_simduino_leonardo/LICENSE b/examples/board_simduino_leonardo/LICENSE new file mode 100644 index 000000000..bb3ed9539 --- /dev/null +++ b/examples/board_simduino_leonardo/LICENSE @@ -0,0 +1,40 @@ +Caterina-Leonardo-bootloader.hex +================================ + +Arduino's Caterina bootloader, built for the Leonardo, is a modified +version of the CDC class bootloader of Dean Camera's LUFA library, built +against LUFA 111009. The image comes from Arduino's ArduinoCore-avr +repository, https://github.com/arduino/ArduinoCore-avr: + + bootloaders/caterina/Caterina-Leonardo.hex + commit 11b9130371e8447920edb65a75706a6c951e51fc + git blob 47053bc531df86341eb31c361e1ac42f7ef8ad56 + +The records below address 0x7000 were removed. They hold a sketch built +with the Arduino core, which is not part of the bootloader and is not +covered by the notice below. The bootloader sources, +bootloaders/caterina/Caterina.c and the files next to it, carry LUFA's +license, which LUFA's documentation calls the MIT license. Its notice, +as it appears in those sources: + + Copyright 2011 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaim all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. + +The USB vendor and product IDs in the image (2341:0036) are Arduino's. diff --git a/examples/extra_board_usb/Makefile b/examples/board_simduino_leonardo/Makefile similarity index 55% rename from examples/extra_board_usb/Makefile rename to examples/board_simduino_leonardo/Makefile index f7f668eb9..23bd86a51 100644 --- a/examples/extra_board_usb/Makefile +++ b/examples/board_simduino_leonardo/Makefile @@ -1,5 +1,5 @@ -# -# Copyright 2012 Torbjorn Tyridal +# +# Arduino Leonardo with the Caterina bootloader over USB/IP, see README. # # This file is part of simavr. # @@ -16,46 +16,28 @@ # You should have received a copy of the GNU General Public License # along with simavr. If not, see . -target= simusb -firm_src = at90usb162_cdc_loopback.c -firmware = ${firm_src:.c=.hex} +target= simduino_leonardo simavr = ../../ IPATH = . IPATH += ../parts -IPATH += ../vhci/include -IPATH += ../vhci IPATH += ${simavr}/include IPATH += ${simavr}/simavr/sim -#IPATH += /usr/local/include VPATH = . VPATH += ../parts -LDFLAGS += -lpthread -lusb_vhci -L../vhci/lib - -all: obj ${firmware} ${target} +all: obj ${target} include ${simavr}/Makefile.common board = ${OBJ}/${target}.elf -${board} : ${OBJ}/vhci_usb.o +${board} : ${OBJ}/usbip_usb.o ${board} : ${OBJ}/${target}.o -../vhci/lib/libusb_vhci.a: - @echo -n "BUILDIN $@ " - @{ export CC=;export CFLAGS=; $(MAKE) -j -C ../vhci >/tmp/vhci.build.log 2>&1 || \ - { echo "ERROR check /tmp/vhci.build.log"; exit 1; }; } && \ - echo " Done" - -vhci : ../vhci/lib/libusb_vhci.a - -clean-vhci: - $(MAKE) -C ../vhci clean - -${target}: vhci ${board} +${target}: ${board} @echo $@ done -clean: clean-${OBJ} clean-vhci - rm -rf *.a *.axf *.hex ${target} *.vcd +clean: clean-${OBJ} + rm -rf *.a *.axf ${target} *.vcd diff --git a/examples/board_simduino_leonardo/README b/examples/board_simduino_leonardo/README new file mode 100644 index 000000000..4fcdcd697 --- /dev/null +++ b/examples/board_simduino_leonardo/README @@ -0,0 +1,88 @@ +simduino_leonardo is an Arduino Leonardo: an ATmega32U4 at 16MHz running +Arduino's Caterina bootloader, with the board's USB port exported over +USB/IP. Once a USB/IP client attaches it, it is a Leonardo plugged into +the host, and avrdude, the Arduino IDE or arduino-cli upload sketches to +it the same way. + + make + ./obj-*/simduino_leonardo.elf + +Linux +----- +The client is the mainline vhci-hcd driver (USBIP_VHCI_HCD in the kernel +configuration) and the usbip tool, packaged as usbip, linux-tools or +net-misc/usbip depending on the distribution: + + sudo modprobe vhci-hcd + usbip list -r 127.0.0.1 + sudo usbip attach -r 127.0.0.1 -b 1-1 + +The bootloader shows up as 2341:0036 and a /dev/ttyACM device, which +avrdude programs: + + avrdude -c avr109 -p m32u4 -P /dev/ttyACM0 -U flash:w:sketch.hex + +"sudo usbip port" lists attached devices and "sudo usbip detach -p +" removes one. + +If opening the port fails with an I/O error, and the kernel log shows the +board being reset and reconnected under a new device number, USB +autosuspend is enabled (power/control is "auto", often set by a power +management tool). Caterina is built without the answer to GET_STATUS for +the device, which Linux asks for when it resumes a suspended device; it +then resets the board and takes it for a new one. A real Leonardo in its +bootloader does the same. Turn autosuspend off for devices that appear +from then on, until the next boot: + + echo -1 | sudo tee /sys/module/usbcore/parameters/autosuspend + +or for the attached board only, until it re-enumerates: + + echo on | sudo tee /sys/bus/usb/devices//power/control + +Windows +------- +Build simavr in MSYS2 as usual. The client is usbip-win2 +(https://github.com/vadimgrn/usbip-win2, or "winget install +vadimgrn.usbip-win2"), Windows 10 1903 or later. From an administrator +prompt: + + usbip list -r 127.0.0.1 + usbip attach -r 127.0.0.1 -b 1-1 + +The board then has a COM port. + +Resets and reattaching +---------------------- +As on the board, the flash starts erased, and Caterina waits in the +bootloader until it is given a sketch. After a power-on with a sketch in +the flash, Caterina starts it at once. After the reset button, it waits +8 seconds for an upload first. -r starts the simulation as after the +reset button, and Ctrl-\ presses it while it runs (not on Windows). A +sketch built with the Arduino core resets into the bootloader when the +port is opened at 1200 baud and closed, the usual way to upload, through +a watchdog reset. + +Each time the firmware disconnects from the bus, when the bootloader +starts the sketch, at a reset, or when a sketch is reset into the +bootloader, the USB/IP connection is closed and the board has to be +attached again, which is when a real board re-enumerates. + +The flash and the EEPROM are kept in simduino_leonardo_memory.hex in the +current directory, an Intel HEX file with the EEPROM at simavr's 0x810000 +offset. It is written back when simduino_leonardo stops (Ctrl-C included), +so the next run finds the sketch uploaded last and what it stored. -F +names another .hex file, -n starts erased and keeps nothing. A sketch +given on the command line, .hex or .elf, is programmed over it at start. + +simduino_leonardo.elf -h lists the options. The server only listens on +127.0.0.1 unless given another address with -a; "-a 0.0.0.0" lets other +machines attach the board. + +The bootloader +-------------- +Caterina-Leonardo-bootloader.hex is Arduino's Caterina-Leonardo.hex with +the records below 0x7000 removed, which hold a demonstration sketch, so +that only the bootloader remains, at 0x7000 to 0x7FD9. See LICENSE. + +USB/IP: https://docs.kernel.org/usb/usbip_protocol.html diff --git a/examples/board_simduino_leonardo/simduino_leonardo.c b/examples/board_simduino_leonardo/simduino_leonardo.c new file mode 100644 index 000000000..502229b7a --- /dev/null +++ b/examples/board_simduino_leonardo/simduino_leonardo.c @@ -0,0 +1,280 @@ +/* + simduino_leonardo.c + + An Arduino Leonardo: an ATmega32U4 at 16MHz running Arduino's Caterina + bootloader, with its USB port exported over USB/IP. A USB/IP client + attaches it to the host's USB stack, where avrdude or the Arduino IDE + upload sketches to it as to a real board. See README. + + This file is part of simavr. + + simavr is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + simavr is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with simavr. If not, see . + */ + +#include +#include +#include +#include +#include +#include + +#include "sim_avr.h" +#include "sim_elf.h" +#include "sim_hex.h" +#include "sim_gdb.h" +#include "avr_eeprom.h" +#include "usbip_usb.h" + +#define MMCU "atmega32u4" +#define FREQUENCY 16000000 +#define BOOTLOADER "Caterina-Leonardo-bootloader.hex" +#define MEMORY_FILE "simduino_leonardo_memory.hex" +#define HEX_LINE 16 // data bytes per Intel HEX record + +static volatile sig_atomic_t stop, reset_button; + +static void +sig_stop(int sig) +{ + stop = 1; +} + +#ifdef SIGQUIT +static void +sig_reset(int sig) +{ + reset_button = 1; +} +#endif + +// one Intel HEX record, its checksum makes the bytes add up to 0 +static void +hex_record(FILE * file, uint8_t type, uint16_t addr, const uint8_t * data, + uint8_t len) +{ + uint8_t sum = len + (addr >> 8) + addr + type; + + fprintf(file, ":%02X%04X%02X", len, addr, type); + for (int i = 0; i < len; i++) { + fprintf(file, "%02X", data[i]); + sum += data[i]; + } + fprintf(file, "%02X\n", (uint8_t)-sum); +} + +// the records of a memory at base, leaving out the erased (0xff) lines +static void +hex_write(FILE * file, uint32_t base, const uint8_t * mem, uint32_t size) +{ + uint32_t upper = ~0; // upper 16 address bits of the last record + + for (uint32_t offset = 0; offset < size; offset += HEX_LINE) { + uint32_t addr = base + offset; + uint8_t len = HEX_LINE; + int erased = 1; + + if (size - offset < HEX_LINE) + len = size - offset; + for (int i = 0; i < len; i++) + if (mem[offset + i] != 0xff) + erased = 0; + if (erased) + continue; + if (addr >> 16 != upper) { + uint8_t extended[2] = { addr >> 24, addr >> 16 }; + + upper = addr >> 16; + hex_record(file, 4, 0, extended, 2); + } + hex_record(file, 0, addr, mem + offset, len); + } +} + +/* + * The flash and the EEPROM survive between runs, as on the board, so + * that the bootloader finds the sketch it was given last time. They are + * saved as an Intel HEX file from avr_terminate(), the EEPROM at + * simavr's EEPROM offset, and load() reads the file back at start. + */ +static void +memory_save(avr_t * avr, void * data) +{ + const char * path = data; + avr_eeprom_desc_t eeprom = { .size = avr->e2end + 1 }; + FILE * file = fopen(path, "w"); + + if (!file) { + perror(path); + return; + } + hex_write(file, 0, avr->flash, avr->flashend + 1); + // with no buffer given, the ioctl points ee at the EEPROM contents + if (avr_ioctl(avr, AVR_IOCTL_EEPROM_GET, &eeprom) == 0) + hex_write(file, AVR_SEGMENT_OFFSET_EEPROM, eeprom.ee, eeprom.size); + hex_record(file, 1, 0, NULL, 0); // end of file + if (fclose(file)) + perror(path); +} + +// .hex (gaps stay as they are) or .elf, into the flash +static void +load(avr_t * avr, const char * path, const char * progname) +{ + elf_firmware_t fw = { .mmcu = MMCU, .frequency = FREQUENCY }; + + sim_setup_firmware(path, 0, &fw, progname); + if (strcmp(fw.mmcu, MMCU)) + fprintf(stderr, "%s: warning, %s is built for %s\n", progname, + path, fw.mmcu); + fw.frequency = 0; // the board's crystal, whatever the .elf says + avr_load_firmware(avr, &fw); +} + +static void +usage(const char * name) +{ + fprintf(stderr, + "Usage: %s [-a addr] [-p port] [-F flash.bin] [-n] [-r] [-g] [-v]\n" + " [sketch]\n" + " sketch .hex or .elf, programmed at 0 as an upload would\n" + " -a addr USB/IP listening address, default 127.0.0.1,\n" + " 0.0.0.0 lets other machines attach the board\n" + " -p port USB/IP TCP port, default %d\n" + " -F file flash and EEPROM kept between runs, .hex, default\n" + " " MEMORY_FILE "\n" + " -n start with an erased flash and don't keep it\n" + " -r start as after a press of the reset button: the\n" + " bootloader waits for an upload for 8s, a power-on\n" + " runs the sketch at once\n" + " -g wait for gdb on port 1234\n" + " -v more logging, repeat for more\n" + "%s", + name, USBIP_USB_DEFAULT_PORT, +#ifdef SIGQUIT + "Ctrl-\\ presses the reset button while it runs.\n" +#else + "" +#endif + ); + exit(1); +} + +int main(int argc, char *argv[]) +{ + char boot[1024]; + const char * sketch = NULL; + const char * memory_file = MEMORY_FILE; + const char * addr = "127.0.0.1"; + uint16_t port = USBIP_USB_DEFAULT_PORT; + int gdb = 0, verbose = 0, button = 0; + int opt; + avr_t * avr; + + while ((opt = getopt(argc, argv, "a:p:F:nrgvh")) != -1) { + switch (opt) { + case 'a': addr = optarg; break; + case 'p': port = strtoul(optarg, NULL, 0); break; + case 'F': memory_file = optarg; break; + case 'n': memory_file = NULL; break; + case 'r': button = 1; break; + case 'g': gdb = 1; break; + case 'v': verbose++; break; + default: usage(argv[0]); + } + } + if (optind < argc) + sketch = argv[optind++]; + if (optind < argc) + usage(argv[0]); + // the bootloader sits next to the obj-* directory of the binary + snprintf(boot, sizeof(boot), "%s/../%s", dirname(strdup(argv[0])), + BOOTLOADER); + + avr = avr_make_mcu_by_name(MMCU); + if (!avr) { + fprintf(stderr, "%s: Error creating the AVR core\n", argv[0]); + exit(1); + } + // a Leonardo's BOOTRST and BOOTSZ, programmed: Caterina's 2048 words + // boot section at 0x7000, where every reset starts + avr->fuse[avr->boot_fuse] &= ~((1 << AVR_FUSE_BOOTRST) | AVR_FUSE_BOOTSZ_MASK); + avr_init(avr); + avr->frequency = FREQUENCY; + avr->log = LOG_WARNING + verbose; + + if (memory_file) { + FILE * file = fopen(memory_file, "r"); + + if (file) { // there is none on the first run, the flash starts erased + fclose(file); + load(avr, memory_file, argv[0]); + } + avr->custom.deinit = memory_save; + avr->custom.data = (void *)memory_file; + } + load(avr, boot, argv[0]); + if (sketch) + load(avr, sketch, argv[0]); + // the bootloader writes the application with SPM + avr->codeend = avr->flashend; + // the MCUSR reset cause: the reset button (EXTRF) instead of the + // power-on (PORF), so Caterina waits for an upload first + if (button) { + avr_regbit_clear(avr, avr->reset_flags.porf); + avr_regbit_set(avr, avr->reset_flags.extrf); + } + + // even if not setup at startup, activate gdb if crashing + avr->gdb_port = 1234; + if (gdb) { + avr->state = cpu_Stopped; + avr_gdb_init(avr); + } + + if (!usbip_usb_init(avr, addr, port)) + exit(1); + printf("Arduino Leonardo, USB/IP server on %s port %u. To attach it:\n" + " Linux: sudo modprobe vhci-hcd\n" + " sudo usbip attach -r 127.0.0.1 -b %s\n" + " Windows: usbip attach -r 127.0.0.1 -b %s (usbip-win2," + " from an administrator prompt)\n", + addr, port, + USBIP_USB_BUSID, USBIP_USB_BUSID); + fflush(stdout); + + signal(SIGINT, sig_stop); + signal(SIGTERM, sig_stop); +#ifdef SIGQUIT + signal(SIGQUIT, sig_reset); +#endif + while (!stop) { + int state = avr_run(avr); + if (state == cpu_Done || state == cpu_Crashed) + break; + if (reset_button) { + reset_button = 0; + printf("Reset button\n"); + fflush(stdout); + // MCUSR shows only EXTRF, as after a press of the button: the + // earlier causes are cleared and avr_reset() keeps the flags + avr_regbit_clear(avr, avr->reset_flags.porf); + avr_regbit_clear(avr, avr->reset_flags.borf); + avr_regbit_clear(avr, avr->reset_flags.wdrf); + avr_regbit_set(avr, avr->reset_flags.extrf); + avr_reset(avr); + } + } + avr_terminate(avr); // saves the memory file + return 0; +} diff --git a/examples/board_usbserial/Arduino-usbserial-atmega16u2-Uno-Rev3.hex b/examples/board_usbserial/Arduino-usbserial-atmega16u2-Uno-Rev3.hex new file mode 100644 index 000000000..d1404eef0 --- /dev/null +++ b/examples/board_usbserial/Arduino-usbserial-atmega16u2-Uno-Rev3.hex @@ -0,0 +1,254 @@ +:1000000090C00000A9C00000A7C00000A5C000006B +:10001000A3C00000A1C000009FC000009DC0000060 +:100020009BC0000099C0000097C0000048C40000B9 +:100030000CC4000091C000008FC000008DC0000003 +:100040008BC0000089C0000087C0000085C0000090 +:1000500083C0000081C000007FC0000002C100001A +:100060007BC0000079C0000077C0000075C00000B0 +:1000700073C0000071C000006FC000006DC00000C0 +:100080006BC0000069C0000067C0000065C00000D0 +:1000900063C0000061C000001201100102000008EE +:1000A0004123430001000102DC0109023E0002017C +:1000B00000C0320904000001020201000524000111 +:1000C0001004240206052406000107058203080027 +:1000D000FF09040100020A000000070504024000B5 +:1000E00001070583024000010403090432034100B3 +:1000F00072006400750069006E006F002000280027 +:100100007700770077002E006100720064007500B0 +:1001100069006E006F002E0063006300290000007C +:10012000000011241FBECFEFD2E0DEBFCDBF11E033 +:10013000A0E0B1E0ECEAFFE002C005900D92A6312C +:10014000B107D9F712E0A6E1B1E001C01D92AF32CC +:10015000B107E1F7F1D028C753CF9C01DC01AE57BE +:10016000BF4FED91FC91119741911196FC93EE9345 +:1001700080589F4FE817F90711F42D933C939FB7D0 +:10018000F894F901EC57FF4F8081815080839FBF25 +:10019000842F0895DF92EF92FF920F931F93FC013B +:1001A0008489813019F0823021F405C040E3D42ED7 +:1001B00004C0DD2402C030E2D32E8389823011F4E2 +:1001C00088E0D82A8589873031F0883031F0863050 +:1001D00031F482E003C084E001C086E0D82A1092A6 +:1001E000C9001092C8001092CA00E784F088018903 +:1001F000128980E0E81681EEF80680E0080780E0CA +:10020000180719F420E130E00FC0C801B701969536 +:1002100087957795679560587B47814E9F4FA801DA +:100220009701A0D6215030403093CD002093CC00D0 +:10023000D092CA0080E0E81681EEF80680E0080758 +:1002400080E0180711F082E001C080E08093C800D0 +:1002500088E98093C9001F910F91FF90EF90DF9084 +:1002600008951F920F920FB60F9211242F938F9320 +:100270009F93EF93FF939091CE008EB38430F1F46F +:10028000E0919901F0919A019083E0919901F091A8 +:100290009A01CF01019690939A018093990189590F +:1002A000914021F489E191E0928381839FB7F89492 +:1002B00080919D018F5F80939D019FBFFF91EF9182 +:1002C0009F918F912F910F900FBE0F901F901895B7 +:1002D000FC01858580FF02C05F9808955F9A0895AC +:1002E00080E091E0D5C580E091E088C584B7877F44 +:1002F00084BF28E10FB6F89420936000109260004C +:100300000FBE87E690E09093CD008093CC0086E00E +:100310008093CA001092C8002093C900539A5A9A39 +:100320008AB180638AB98BB180638BB983D284E050 +:1003300085BD5F9A579A08950F931F93CF93DF93CC +:10034000D5DF2FB7F8948EE991E090931F02809348 +:100350001E0290932102809320022FBF2FB7F894A2 +:1003600089E191E090939A018093990190939C0187 +:1003700080939B012FBF7894CEE9D1E003E08FB743 +:10038000F894909122028FBF903809F180E091E0BB +:10039000ABD497FD1CC0E0911E02F0911F02808338 +:1003A000E0911E02F0911F02CF01019690931F026F +:1003B00080931E028E51924011F4D283C1839FB765 +:1003C000F894809122028F5F809322029FBF8FB7A3 +:1003D000F89410919D018FBFA89902C0113678F151 +:1003E000A89A80919D01882361F05D980093160181 +:1003F00008C089E191E0B1DE682F80E091E0DAD4B5 +:1004000011501123B1F780911601882351F080918A +:10041000160181508093160180911601882309F4FA +:100420005D9A80911701882351F0809117018150C6 +:100430008093170180911701882309F45C9A8FB784 +:10044000F894909122028FBF992369F08EE991E090 +:1004500084DE982F8091C80085FFFCCF9093CE005A +:100460005C980093170180E091E095D42AD487CF5F +:10047000DA01923049F0933061F09130F9F4E8E913 +:10048000F0E022E130E01EC0EAEAF0E02EE330E0E6 +:1004900019C0813049F0813018F0823079F408C0F9 +:1004A000E8EEF0E0849107C0ECEEF0E0849103C048 +:1004B000E0E2F1E08491282F30E004C0E0E0F0E0D9 +:1004C00020E030E0ED93FC93C901089528E030E08E +:1004D00040E003C04F5F220F331F28173907D0F3C6 +:1004E000842F8295807F08958093E9008091EB00AE +:1004F00081608093EB001092ED006093EC004093DC +:10050000ED008091EE00881F8827881F08951092C3 +:10051000F40090E09093E9001092F0001092E8004F +:100520001092ED008091EB008E7F8093EB009F5F37 +:10053000953081F708958091270288238CF403C0B9 +:100540008EB38823B1F08091E80082FFF9CF8091CB +:10055000E8008B778093E80008958EB3882349F0F4 +:100560008091E80080FFF9CF8091E8008E7780933A +:10057000E800089594E68091EC0080FF05C080912A +:10058000E80080FF05C023C08091E80082FD1FC005 +:100590008EB3882311F482E008958EB3853011F470 +:1005A00083E008958091EB0085FF02C081E008950B +:1005B0008091E10082FFDFCF8091E1008B7F80930B +:1005C000E100992311F484E008959150D4CF80E0A4 +:1005D00008959C0140912D0250912E024617570715 +:1005E00018F4F90120E038C06115710511F0AB0174 +:1005F000F8CF8091E8008E778093E80040E050E0EB +:10060000F0CF8091E80083FF02C081E008958091DF +:10061000E80082FD2DC08EB3882381F18EB3853032 +:1006200079F18091E80080FF17C09091F20006C038 +:1006300081918093F100415050409F5F41155105D9 +:1006400011F09830A8F320E0983009F421E080916F +:10065000E8008E778093E8004115510591F622233A +:1006600081F606C08EB3882349F08EB3853041F001 +:100670008091E80082FFF6CF80E0089582E008953F +:1006800083E008959C0140912D0250912E0246175F +:10069000570710F490E03BC06115710511F0AB01F4 +:1006A000F9CF8091E8008E778093E80040E050E039 +:1006B000F1CF8091E80083FF02C081E0089580912E +:1006C000E80082FD30C08EB3882399F18EB3853067 +:1006D00091F18091E80080FF1AC08091F20009C07A +:1006E000F9012F5F3F4FE491E093F10041505040FA +:1006F0008F5F4115510511F0883090F390E08830FC +:1007000009F491E08091E8008E778093E80041152C +:10071000510579F6992369F606C08EB3882349F00E +:100720008EB3853041F08091E80082FFF6CF80E003 +:10073000089582E0089583E008959C016115710594 +:1007400029F48091E8008B778093E800F90120C0BC +:100750008091E80083FF02C081E008958EB3882372 +:1007600039F18EB3853031F18091E80082FFF0CF0E +:1007700006C08091F10081936150704021F080911A +:10078000F2008823B1F78091E8008B778093E8002E +:1007900061157105E9F606C08EB3882349F08EB362 +:1007A000853041F08091E80080FFF6CF80E0089529 +:1007B00082E0089583E0089542D044D01EBA10929A +:1007C0002502109224021092230284E089BD89B58B +:1007D000826089BD09B400FEFDCF8091D800982FBA +:1007E0009F779093D80080688093D80080916300B1 +:1007F0008E7F809363008091D8008F7D8093D80096 +:100800008091E0008E7F8093E0008091E1008E7FF8 +:100810008093E1008091E20081608093E20080910A +:10082000E100877F8093E1008091E20088608093FF +:10083000E2000895C1DF81E08093260208951092BE +:10084000E20008951092E10008951F920F920FB6F2 +:100850000F9211241F932F933F934F935F936F93A6 +:100860007F938F939F93AF93BF93EF93FF93E9EEA3 +:10087000F0E0108117701082E0EFF0E08081877F58 +:1008800080837894C3D0F894A9EEB0E01C92E0EF96 +:10089000F0E08081886080831C93FF91EF91BF918D +:1008A000AF919F918F917F916F915F914F913F9108 +:1008B0002F911F910F900FBE0F901F9018951F92B0 +:1008C0000F920FB60F9211242F933F934F935F9384 +:1008D0006F937F938F939F93AF93BF93EF93FF9308 +:1008E0008091E10080FF1BC08091E20080FF17C073 +:1008F0008091E1008E7F8093E1008091E2008E7F05 +:100900008093E2008091E20080618093E200809118 +:10091000D80080628093D80019BC1EBAD1D18091D2 +:10092000E10084FF29C08091E20084FF25C084E0BB +:1009300089BD89B5826089BD09B400FEFDCF809173 +:10094000D8008F7D8093D8008091E1008F7E8093C6 +:10095000E1008091E2008F7E8093E2008091E200CE +:1009600081608093E20080912502882311F481E068 +:1009700001C084E08EBBA4D18091E10083FF27C039 +:100980008091E20083FF23C08091E100877F809304 +:10099000E10082E08EBB109225028091E1008E7F03 +:1009A0008093E1008091E2008E7F8093E20080914D +:1009B000E20080618093E200AADD80E060E042E036 +:1009C00093DD8091F00088608093F00079D1809170 +:1009D000E10082FF0AC08091E20082FF06C08091A0 +:1009E000E1008B7F8093E1006BD1FF91EF91BF918C +:1009F000AF919F918F917F916F915F914F913F91B7 +:100A00002F910F900FBE0F901F9018951F93DF939B +:100A1000CF93CDB7DEB7AC970FB6F894DEBF0FBE5D +:100A2000CDBFE7E2F2E08091F100819322E0EF3266 +:100A3000F207C9F78091270230912802353009F476 +:100A400087C0363040F43130C9F1313070F0333086 +:100A500009F01DC133C0383009F4EFC0393009F452 +:100A6000FEC0363009F013C192C0803821F08238C0 +:100A700009F00DC108C090912302809124028823BF +:100A800099F0926011C080912B0287708093E900E9 +:100A90008091EB0090E025E0969587952A95E1F707 +:100AA000982F91701092E9008091E800877F8093E1 +:100AB000E8009093F1001092F100CAC0882319F069 +:100AC000823009F0E4C090E08F719070009721F0BF +:100AD000029709F0DDC00CC080912902813009F035 +:100AE000D7C010922402333069F5809324022AC0C3 +:100AF00080912902882331F520912B02277009F477 +:100B0000C7C02093E9008091EB0080FFC1C0333063 +:100B100021F48091EB00806213C08091EB00806132 +:100B20008093EB0081E090E002C0880F991F2A9526 +:100B3000E2F78093EA001092EA008091EB0088606F +:100B40008093EB001092E9008091E800877F83C0DA +:100B5000882309F09CC0109129028091E800877FCA +:100B60008093E800E8DC04C08EB3882309F490C0C9 +:100B70008091E80080FFF8CF812F8F7711F492E009 +:100B800001C093E09EBB80688093E30081C08058E1 +:100B9000823008F07CC08091290290912A0223E0E3 +:100BA0008C3D920799F55FB7F894DE0115964EE0FB +:100BB00020E030E061E2E42FF0E0609357008491A0 +:100BC00020FF03C082958F704F5F982F9F70892FF1 +:100BD000805D8A3308F0895F8C9311961C9211977F +:100BE0002F5F3F4F12962431310529F75FBF8AE20C +:100BF0008B8383E08C838091E800877F8093E8007B +:100C0000CE0103966AE270E0E4DC11C060912B0231 +:100C1000AE014F5F5F4F2CDCBC010097C9F18091A2 +:100C2000E800877F8093E80089819A812BDD80919D +:100C3000E8008B778093E8002BC0803841F58091E5 +:100C4000E800877F8093E800809125028093F1007F +:100C50008091E8008E778093E8006DDC19C08823CE +:100C6000B1F490912902923098F48091E800877F46 +:100C70008093E800909325025EDC80912502882312 +:100C800011F483E001C084E08EBB2DDB01C028DBC2 +:100C90008091E80083FF0AC08091EB00806280931E +:100CA000EB008091E800877F8093E800AC960FB658 +:100CB000F894DEBF0FBECDBFCF91DF911F91089595 +:100CC00008951F938EB3882361F01091E90010926C +:100CD000E9008091E80083FF01C098DE177010934F +:100CE000E9001F9108950895FC018EB3843021F529 +:100CF00087859089A189B2890097A105B105E1F0A6 +:100D000085818093E9008091E80082FF15C0809181 +:100D1000F200882319F42FEF3FEF04C08091F10017 +:100D2000282F30E08091F200882341F48091E80080 +:100D30008B778093E80002C02FEF3FEFC901089541 +:100D4000FC018EB3843011F587859089A189B28921 +:100D50000097A105B105D1F081818093E9008091D0 +:100D6000F2008823A9F09091E8008091E8008E7746 +:100D70008093E80095FD0CC0FDDB982F882349F493 +:100D80008091E8008E778093E80003C092E001C074 +:100D900090E0892F0895FC018EB3843051F487854B +:100DA0009089A189B2890097A105B10511F0CF0101 +:100DB000C7CF08951F93FC01162F8EB38430D9F44A +:100DC00087859089A189B2890097A105B10599F01D +:100DD00081818093E9008091E80085FD08C08091C1 +:100DE000E8008E778093E800C5DB882329F4109310 +:100DF000F10080E001C082E01F9108950F931F93DE +:100E0000CF93DF93EC010D96FC0189E0DF011D9289 +:100E10008A95E9F72A813B8109818C81882311F425 +:100E200010E001C014E0C90151DB182B1260802FC3 +:100E300061E8412F59DB882329F12E813F810D8103 +:100E40008885882311F410E001C014E0C9013EDB5D +:100E5000182B1260802F60E8412F46DB882391F029 +:100E60002A853B8509858C85882311F410E001C013 +:100E700014E0C9012BDB182B1260802F61EC412F8D +:100E800033DB01C080E0DF91CF911F910F91089576 +:100E9000CF93DF93EC018091E80083FF60C08881ED +:100EA00090E020912B0230912C022817390709F08D +:100EB00056C080912802813261F0823220F4803263 +:100EC00009F04DC019C0823269F1833209F047C080 +:100ED00038C080912702813A09F041C08091E80032 +:100EE000877F8093E800CE010F9667E070E071DBAA +:100EF0008091E8008B7713C080912702813279F5C9 +:100F00008091E800877F8093E800CE010F9667E02C +:100F100070E013DCCE013ED98091E8008E7780939B +:100F2000E8001DC0809127028132C9F48091E80059 +:100F3000877F8093E800809129028D87CE01C8D9F0 +:100F40000DC080912702813251F48091E800877FA3 +:100F50008093E800CE0160912902C5DEECDADF91D2 +:100F6000CF910895A1E21A2EAA1BBB1BFD010DC053 +:100F7000AA1FBB1FEE1FFF1FA217B307E407F50749 +:100F800020F0A21BB30BE40BF50B661F771F881F25 +:100F9000991F1A9469F760957095809590959B01BB +:0C0FA000AC01BD01CF010895F894FFCF13 +:100FAC0000034000000440000002080000000000A4 +:060FBC000000000000002F +:00000001FF diff --git a/examples/board_usbserial/LICENSE b/examples/board_usbserial/LICENSE new file mode 100644 index 000000000..78a607bb4 --- /dev/null +++ b/examples/board_usbserial/LICENSE @@ -0,0 +1,38 @@ +Arduino-usbserial-atmega16u2-Uno-Rev3.hex +========================================= + +Arduino-usbserial, the USB to serial firmware of the Arduino Uno R3's +ATmega16U2, is a modified version of the USBtoSerial demonstration of +Dean Camera's LUFA library, built against LUFA 100807. The image comes +unchanged from Arduino's ArduinoCore-avr repository, +https://github.com/arduino/ArduinoCore-avr: + + firmwares/atmegaxxu2/arduino-usbserial/Arduino-usbserial-atmega16u2-Uno-Rev3.hex + commit 11b9130371e8447920edb65a75706a6c951e51fc + git blob d1404eef09b6ced4e3442064ce13bf2cd9a8ec26 + +Its sources, Arduino-usbserial.c and the files next to it, carry LUFA's +license, which LUFA's documentation calls the MIT license. Its notice, +as it appears in those sources: + + Copyright 2010 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaim all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. + +The USB vendor and product IDs in the image (2341:0043) are Arduino's. diff --git a/examples/board_usbserial/Makefile b/examples/board_usbserial/Makefile new file mode 100644 index 000000000..eac5a6186 --- /dev/null +++ b/examples/board_usbserial/Makefile @@ -0,0 +1,49 @@ +# +# The Arduino Uno R3's ATmega16U2 USB to serial adapter over USB/IP, +# see README. +# +# This file is part of simavr. +# +# simavr is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# simavr is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with simavr. If not, see . + +target= usbserial +simavr = ../../ + +IPATH = . +IPATH += ../parts +IPATH += ${simavr}/include +IPATH += ${simavr}/simavr/sim + +VPATH = . +VPATH += ../parts + +all: obj ${target} + +include ${simavr}/Makefile.common + +board = ${OBJ}/${target}.elf + +${board} : ${OBJ}/usbip_usb.o +${board} : ${OBJ}/${target}.o +# the pty for USART1, POSIX only +ifneq (${shell uname -o}, Msys) +LDFLAGS += -lpthread -lutil +${board} : ${OBJ}/uart_pty.o +endif + +${target}: ${board} + @echo $@ done + +clean: clean-${OBJ} + rm -rf *.a *.axf ${target} *.vcd diff --git a/examples/board_usbserial/README b/examples/board_usbserial/README new file mode 100644 index 000000000..8a443451c --- /dev/null +++ b/examples/board_usbserial/README @@ -0,0 +1,64 @@ +usbserial is the USB side of an Arduino Uno R3: its ATmega16U2 at 16MHz +running Arduino-usbserial, the board's USB to serial firmware, with the +USB port exported over USB/IP. Once a USB/IP client attaches it, the host +sees the Uno's serial port (2341:0043). + + make + ./obj-*/usbserial.elf + +On the board, USART1 of the 16U2 goes to the ATmega328P and DTR pulls the +328P's RESET low (PD7). Here USART1 is looped back, TX to RX, so what is +written to the serial port comes back, at the baud rate the host set. +With -t (not on Windows) USART1 is connected to a pty instead, linked +from /tmp/simavr-uart1, where another program can play the 328P. Changes +of the RESET line are printed. + +Other firmware for the part can be given on the command line, as .hex or +.elf; an .elf with an AVR_MCU section selects the part and clock itself. + + ./obj-*/usbserial.elf -t + ./obj-*/usbserial.elf firmware.elf + +Linux +----- +The client is the mainline vhci-hcd driver (USBIP_VHCI_HCD in the kernel +configuration) and the usbip tool, packaged as usbip, linux-tools or +net-misc/usbip depending on the distribution: + + sudo modprobe vhci-hcd + usbip list -r 127.0.0.1 + sudo usbip attach -r 127.0.0.1 -b 1-1 + +The device then shows up in lsusb and as a /dev/ttyACM device. "sudo usbip +port" lists attached devices and "sudo usbip detach -p " removes +one. Stopping usbserial detaches it too. + +Windows +------- +Build simavr in MSYS2 as usual. The client is usbip-win2 +(https://github.com/vadimgrn/usbip-win2, or "winget install +vadimgrn.usbip-win2"), Windows 10 1903 or later. From an administrator +prompt: + + usbip list -r 127.0.0.1 + usbip attach -r 127.0.0.1 -b 1-1 + +"usbip port" and "usbip detach -p " work as on Linux. + +Options +------- +usbserial.elf -h lists them. The server only listens on 127.0.0.1 unless +given another address with -a; "-a 0.0.0.0" lets other machines attach +the device. When the firmware disconnects from the bus, the USB/IP +connection is closed and the device has to be attached again. + +usbip_check.py exercises the server without a kernel: it imports the +device, enumerates it and sends data through the loopback, the way +vhci-hcd and cdc-acm would. + +The firmware +------------ +Arduino-usbserial-atmega16u2-Uno-Rev3.hex is Arduino's image, unchanged. +See LICENSE. + +USB/IP: https://docs.kernel.org/usb/usbip_protocol.html diff --git a/examples/board_usbserial/usbip_check.py b/examples/board_usbserial/usbip_check.py new file mode 100755 index 000000000..77289cc33 --- /dev/null +++ b/examples/board_usbserial/usbip_check.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python3 +""" +Minimal USB/IP client to check the USB/IP server without a kernel: lists +and imports the device, enumerates it, then sends data through +Arduino-usbserial and USART1, looped back, and reads it back, the way +vhci-hcd and cdc-acm would, including an unlink of a pending IN URB. + + ./obj-*/usbserial.elf & + ./usbip_check.py [host] [port] +""" +import socket +import struct +import sys + +host = sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1" +port = int(sys.argv[2]) if len(sys.argv) > 2 else 3240 +DEVID = (1 << 16) | 1 +seq = 0 + + +def recv_exact(s, n): + b = b"" + while len(b) < n: + c = s.recv(n - len(b)) + if not c: + raise SystemExit("FAIL: connection closed") + b += c + return b + + +def op(s, code, payload=b""): + s.sendall(struct.pack(">HHI", 0x0111, code, 0) + payload) + ver, rcode, status = struct.unpack(">HHI", recv_exact(s, 8)) + return rcode, status + + +def parse_dev(b): + path, busid = b[:256].rstrip(b"\0"), b[256:288].rstrip(b"\0") + busnum, devnum, speed, vid, pid, bcd = struct.unpack(">IIIHHH", b[288:306]) + cls, sub, proto, cfg, ncfg, nif = b[306:312] + return dict(path=path.decode(), busid=busid.decode(), speed=speed, + vid=vid, pid=pid, cls=cls, nif=nif, cfg=cfg) + + +def submit(s, ep, direction, length=0, data=b"", setup=bytes(8), flags=0): + global seq + seq += 1 + hdr = struct.pack(">IIIII", 1, seq, DEVID, direction, ep) + hdr += struct.pack(">IiiiI", flags, length if direction else len(data), + 0, 0, 0) + setup + s.sendall(hdr + data) + return seq + + +def ret(s): + h = recv_exact(s, 48) + cmd, sq = struct.unpack(">II", h[:8]) + if cmd == 3: + status, actual = struct.unpack(">ii", h[20:28]) + return cmd, sq, status, h, actual + if cmd == 4: + status, = struct.unpack(">i", h[20:24]) + return cmd, sq, status, h, 0 + raise SystemExit("FAIL: unexpected reply %d" % cmd) + + +def control(s, setup, length=0, data=b"", direction=None): + if direction is None: + direction = 1 if setup[0] & 0x80 else 0 + sq = submit(s, 0, direction, length, data, setup) + cmd, rsq, status, h, actual = ret(s) + assert cmd == 3 and rsq == sq, (cmd, rsq, sq) + payload = recv_exact(s, actual) if direction and actual else b"" + return status, payload + + +def devlist(): + s = socket.create_connection((host, port)) + s.sendall(struct.pack(">HHI", 0x0111, 0x8005, 0)) + ver, code, status = struct.unpack(">HHI", recv_exact(s, 8)) + n, = struct.unpack(">I", recv_exact(s, 4)) + assert code == 0x0005 and status == 0 and n == 1, (code, status, n) + d = parse_dev(recv_exact(s, 312)) + ifs = [recv_exact(s, 4) for _ in range(d["nif"])] + s.close() + return d, ifs + + +# 1. device list +d, ifs = devlist() +print("devlist: %s %04x:%04x speed %d, %d interface(s): %s" % ( + d["busid"], d["vid"], d["pid"], d["speed"], d["nif"], + " ".join("%02x/%02x/%02x" % tuple(i[:3]) for i in ifs))) + +# 2. import +s = socket.create_connection((host, port)) +code, status = op(s, 0x8003, d["busid"].encode().ljust(32, b"\0")) +assert code == 0x0003 and status == 0, (code, status) +d = parse_dev(recv_exact(s, 312)) +print("imported %s" % d["busid"]) + +# while imported, other clients can still list the device, not import it +devlist() +s2 = socket.create_connection((host, port)) +code, status = op(s2, 0x8003, d["busid"].encode().ljust(32, b"\0")) +assert code == 0x0003 and status == 2, (code, status) # ST_DEV_BUSY +s2.close() +print("listed while imported, second import refused as busy") + +# 3. enumeration as Linux does it (SET_ADDRESS is handled by vhci-hcd) +st, dd = control(s, struct.pack("IIIII", 2, global_seq, DEVID, 0, 0) + + struct.pack(">I", victim) + bytes(24)) + seq = global_seq + cmd, sq, status, h, actual = ret(s) + while cmd == 3: + assert sq in in_seqs and status == 0, (sq, status) + recv_exact(s, actual) + in_seqs.remove(sq) + cmd, sq, status, h, actual = ret(s) + expected = -104 if victim in in_seqs else 0 + assert cmd == 4 and sq == global_seq and status == expected, (cmd, sq, status) + if victim in in_seqs: + in_seqs.remove(victim) + unlinked += 1 +print("unlinked %d pending IN URB(s)" % unlinked) +s.close() +print("PASS") diff --git a/examples/board_usbserial/usbserial.c b/examples/board_usbserial/usbserial.c new file mode 100644 index 000000000..d5ce1122e --- /dev/null +++ b/examples/board_usbserial/usbserial.c @@ -0,0 +1,178 @@ +/* + usbserial.c + + The USB side of an Arduino Uno R3: its ATmega16U2 at 16MHz running + Arduino-usbserial, the USB to serial firmware, with the USB port + exported over USB/IP. USART1, which goes to the ATmega328P on the + board, is looped back or connected to a pty. See README. + + This file is part of simavr. + + simavr is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + simavr is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with simavr. If not, see . + */ + +#include +#include +#include +#include +#include +#include + +#include "sim_avr.h" +#include "sim_elf.h" +#include "sim_hex.h" +#include "sim_gdb.h" +#include "avr_uart.h" +#include "avr_ioport.h" +#include "usbip_usb.h" +#ifndef __MINGW32__ +#include "uart_pty.h" +#endif + +#define MMCU "atmega16u2" +#define FREQUENCY 16000000 +#define FIRMWARE "Arduino-usbserial-atmega16u2-Uno-Rev3.hex" +#define RESET_PIN 7 // PD7, to the ATmega328P's RESET + +static volatile sig_atomic_t stop; + +static void +sig_stop(int sig) +{ + stop = 1; +} + +// DTR pulls the 328P's reset line low, that's how avrdude resets it +static void +reset_line_hook(struct avr_irq_t * irq, uint32_t value, void * param) +{ + printf("328P RESET %s\n", value ? "released" : "pulled low (DTR)"); + fflush(stdout); +} + +static void +usage(const char * name) +{ + fprintf(stderr, + "Usage: %s [-a addr] [-p port] [-t] [-g] [-v] [firmware]\n" + " firmware .hex or .elf, default " FIRMWARE "\n" + " -a addr USB/IP listening address, default 127.0.0.1,\n" + " 0.0.0.0 lets other machines attach the board\n" + " -p port USB/IP TCP port, default %d\n" +#ifndef __MINGW32__ + " -t USART1 to a pty (/tmp/simavr-uart1) instead of\n" + " looping it back\n" +#endif + " -g wait for gdb on port 1234\n" + " -v more logging, repeat for more\n", + name, USBIP_USB_DEFAULT_PORT); + exit(1); +} + +int main(int argc, char *argv[]) +{ + elf_firmware_t fw = { .mmcu = MMCU, .frequency = FREQUENCY }; + char path[1024]; + const char * firmware = NULL; + const char * addr = "127.0.0.1"; + uint16_t port = USBIP_USB_DEFAULT_PORT; + int gdb = 0, verbose = 0, pty = 0; + int opt; + avr_t * avr; + + while ((opt = getopt(argc, argv, "a:p:tgvh")) != -1) { + switch (opt) { + case 'a': addr = optarg; break; + case 'p': port = strtoul(optarg, NULL, 0); break; +#ifndef __MINGW32__ + case 't': pty = 1; break; +#endif + case 'g': gdb = 1; break; + case 'v': verbose++; break; + default: usage(argv[0]); + } + } + if (optind < argc) + firmware = argv[optind++]; + if (optind < argc) + usage(argv[0]); + if (!firmware) { + // next to the obj-* directory of the binary + snprintf(path, sizeof(path), "%s/../%s", dirname(strdup(argv[0])), + FIRMWARE); + firmware = path; + } + + sim_setup_firmware(firmware, 0, &fw, argv[0]); + avr = avr_make_mcu_by_name(fw.mmcu); + if (!avr) { + fprintf(stderr, "%s: Error creating the AVR core %s\n", argv[0], + fw.mmcu); + exit(1); + } + avr_init(avr); + avr_load_firmware(avr, &fw); + avr->log = LOG_WARNING + verbose; + + // even if not setup at startup, activate gdb if crashing + avr->gdb_port = 1234; + if (gdb) { + avr->state = cpu_Stopped; + avr_gdb_init(avr); + } + + avr_irq_register_notify(avr_io_getirq(avr, AVR_IOCTL_IOPORT_GETIRQ('D'), + IOPORT_IRQ_PIN0 + RESET_PIN), reset_line_hook, NULL); +#ifndef __MINGW32__ + static uart_pty_t uart_pty; + if (pty) { + uart_pty_init(avr, &uart_pty); + uart_pty_connect(&uart_pty, '1'); + } else +#endif + { + // a wire from TX to RX: what is sent to the serial port comes back + avr_connect_irq( + avr_io_getirq(avr, AVR_IOCTL_UART_GETIRQ('1'), UART_IRQ_OUTPUT), + avr_io_getirq(avr, AVR_IOCTL_UART_GETIRQ('1'), UART_IRQ_INPUT)); + } + + if (!usbip_usb_init(avr, addr, port)) + exit(1); + printf("%s at %u Hz, USART1 %s, USB/IP server on %s port %u.\n" + "To attach it:\n" + " Linux: sudo modprobe vhci-hcd\n" + " sudo usbip attach -r 127.0.0.1 -b %s\n" + " Windows: usbip attach -r 127.0.0.1 -b %s (usbip-win2," + " from an administrator prompt)\n", + avr->mmcu, (unsigned)avr->frequency, + pty ? "on /tmp/simavr-uart1" : "looped back", + addr, port, + USBIP_USB_BUSID, USBIP_USB_BUSID); + fflush(stdout); + + signal(SIGINT, sig_stop); + signal(SIGTERM, sig_stop); + while (!stop) { + int state = avr_run(avr); + if (state == cpu_Done || state == cpu_Crashed) + break; + } +#ifndef __MINGW32__ + if (pty) + uart_pty_stop(&uart_pty); +#endif + avr_terminate(avr); + return 0; +} diff --git a/examples/extra_board_usb/.gitignore b/examples/extra_board_usb/.gitignore deleted file mode 100644 index 04e1d751c..000000000 --- a/examples/extra_board_usb/.gitignore +++ /dev/null @@ -1 +0,0 @@ -simusb_flash.bin diff --git a/examples/extra_board_usb/README b/examples/extra_board_usb/README deleted file mode 100644 index e1ea409ba..000000000 --- a/examples/extra_board_usb/README +++ /dev/null @@ -1,47 +0,0 @@ -This will bridge the usb avr to the vhci-usb virtual usb host. -Unfortunately it depends on VHCI, a Linux kernel module that -has not been maintained recently. - -You'll need vhci-usb and vhci-usb-lib to build and use it. -(http://sourceforge.net/projects/usb-vhci/) - -When setup, your avr project will connect to the linux usb system -as a real device. - -BUILDING usb-vhci ------------------ -git://usb-vhci.git.sourceforge.net/gitroot/usb-vhci/vhci_hcd - -The driver doesn't compile on recent linux kernels. -(commit 203800f0 Mon Apr 4) -0001-SPIN_LOCK_UNLOCKED-has-been-depreciated.patch -and -0002-need-transaction-translator.patch -should fix that. - -then simply "make && make install" - -might need to copy the api header file: -mkdir -p /usr/local/include/linux -sudo cp usb-vhci.h /usr/local/include/linux - - -BUILDING libusb_vhci --------------------- -git://usb-vhci.git.sourceforge.net/gitroot/usb-vhci/libusb_vhci - -This was a little more troublesome, but I didn't care to figure it out. -with libusb_vhci trunk (commit 5927f39a Sun Mar 27) - -add -0001-Comment-out-function-that-doesn-t-compile.patch -patch to remove that won't compile (and we don't use) -then: -cd src -gcc -c libusb_vhci.c -ar rcs libusb_vhci.a libusb_vhci.o -sudo cp libusb_vhci.a /usr/local/lib -mkdir -p /usr/local/include/linux -sudo cp libusb_vhci.h /usr/local/include/linux - -Gives us what we need diff --git a/examples/extra_board_usb/at90usb162_cdc_loopback.c b/examples/extra_board_usb/at90usb162_cdc_loopback.c deleted file mode 100644 index 738522fdb..000000000 --- a/examples/extra_board_usb/at90usb162_cdc_loopback.c +++ /dev/null @@ -1,959 +0,0 @@ -/* vim: set sts=4:sw=4:ts=4:noexpandtab - * - * USB Serial Example for Teensy USB Development Board - * http://www.pjrc.com/teensy/usb_serial.html - * Copyright (c) 2008,2010,2011 PJRC.COM, LLC - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -// Version 1.0: Initial Release -// Version 1.1: support Teensy++ -// Version 1.2: fixed usb_serial_available -// Version 1.3: added transmit bandwidth test -// Version 1.4: added usb_serial_write -// Version 1.5: add support for Teensy 2.0 -// Version 1.6: fix zero length packet bug -// Version 1.7: fix usb_serial_set_control - -#define USB_SERIAL_PRIVATE_INCLUDE -#include "at90usb162_cdc_loopback.h" - -/************************************************************************** - * - * Configurable Options - * - **************************************************************************/ - -// You can change these to give your code its own name. On Windows, -// these are only used before an INF file (driver install) is loaded. -#define STR_MANUFACTURER L"Your Name" -#define STR_PRODUCT L"USB Serial" - -// All USB serial devices are supposed to have a serial number -// (according to Microsoft). On windows, a new COM port is created -// for every unique serial/vendor/product number combination. If -// you program 2 identical boards with 2 different serial numbers -// and they are assigned COM7 and COM8, each will always get the -// same COM port number because Windows remembers serial numbers. -// -// On Mac OS-X, a device file is created automatically which -// incorperates the serial number, eg, /dev/cu-usbmodem12341 -// -// Linux by default ignores the serial number, and creates device -// files named /dev/ttyACM0, /dev/ttyACM1... in the order connected. -// Udev rules (in /etc/udev/rules.d) can define persistent device -// names linked to this serial number, as well as permissions, owner -// and group settings. -#define STR_SERIAL_NUMBER L"12345" - -// Mac OS-X and Linux automatically load the correct drivers. On -// Windows, even though the driver is supplied by Microsoft, an -// INF file is needed to load the driver. These numbers need to -// match the INF file. -#define VENDOR_ID 0x16C0 -#define PRODUCT_ID 0x047A - -// When you write data, it goes into a USB endpoint buffer, which -// is transmitted to the PC when it becomes full, or after a timeout -// with no more writes. Even if you write in exactly packet-size -// increments, this timeout is used to send a "zero length packet" -// that tells the PC no more data is expected and it should pass -// any buffered data to the application that may be waiting. If -// you want data sent immediately, call usb_serial_flush_output(). -#define TRANSMIT_FLUSH_TIMEOUT 5 /* in milliseconds */ - -// If the PC is connected but not "listening", this is the length -// of time before usb_serial_getchar() returns with an error. This -// is roughly equivilant to a real UART simply transmitting the -// bits on a wire where nobody is listening, except you get an error -// code which you can ignore for serial-like discard of data, or -// use to know your data wasn't sent. -#define TRANSMIT_TIMEOUT 25 /* in milliseconds */ - -// USB devices are supposed to implment a halt feature, which is -// rarely (if ever) used. If you comment this line out, the halt -// code will be removed, saving 116 bytes of space (gcc 4.3.0). -// This is not strictly USB compliant, but works with all major -// operating systems. -#define SUPPORT_ENDPOINT_HALT - - - -/************************************************************************** - * - * Endpoint Buffer Configuration - * - **************************************************************************/ - -// These buffer sizes are best for most applications, but perhaps if you -// want more buffering on some endpoint at the expense of others, this -// is where you can make such changes. The AT90USB162 has only 176 bytes -// of DPRAM (USB buffers) and only endpoints 3 & 4 can double buffer. - -#define ENDPOINT0_SIZE 16 -#define CDC_ACM_ENDPOINT 2 -#define CDC_RX_ENDPOINT 3 -#define CDC_TX_ENDPOINT 4 -#if defined(__AVR_AT90USB162__) -#define CDC_ACM_SIZE 16 -#define CDC_ACM_BUFFER EP_SINGLE_BUFFER -#define CDC_RX_SIZE 32 -#define CDC_RX_BUFFER EP_DOUBLE_BUFFER -#define CDC_TX_SIZE 32 -#define CDC_TX_BUFFER EP_DOUBLE_BUFFER -#else -#define CDC_ACM_SIZE 16 -#define CDC_ACM_BUFFER EP_SINGLE_BUFFER -#define CDC_RX_SIZE 64 -#define CDC_RX_BUFFER EP_DOUBLE_BUFFER -#define CDC_TX_SIZE 64 -#define CDC_TX_BUFFER EP_DOUBLE_BUFFER -#endif - -static const uint8_t PROGMEM endpoint_config_table[] = { - 0, - 1, EP_TYPE_INTERRUPT_IN, EP_SIZE(CDC_ACM_SIZE) | CDC_ACM_BUFFER, - 1, EP_TYPE_BULK_OUT, EP_SIZE(CDC_RX_SIZE) | CDC_RX_BUFFER, - 1, EP_TYPE_BULK_IN, EP_SIZE(CDC_TX_SIZE) | CDC_TX_BUFFER -}; - - -/************************************************************************** - * - * Descriptor Data - * - **************************************************************************/ - -// Descriptors are the data that your computer reads when it auto-detects -// this USB device (called "enumeration" in USB lingo). The most commonly -// changed items are editable at the top of this file. Changing things -// in here should only be done by those who've read chapter 9 of the USB -// spec and relevant portions of any USB class specifications! - -static const uint8_t PROGMEM device_descriptor[] = { - 18, // bLength - 1, // bDescriptorType - 0x00, 0x02, // bcdUSB - 2, // bDeviceClass - 0, // bDeviceSubClass - 0, // bDeviceProtocol - ENDPOINT0_SIZE, // bMaxPacketSize0 - LSB(VENDOR_ID), MSB(VENDOR_ID), // idVendor - LSB(PRODUCT_ID), MSB(PRODUCT_ID), // idProduct - 0x00, 0x01, // bcdDevice - 1, // iManufacturer - 2, // iProduct - 3, // iSerialNumber - 1 // bNumConfigurations -}; - -#define CONFIG1_DESC_SIZE (9+9+5+5+4+5+7+9+7+7) -static const uint8_t PROGMEM config1_descriptor[CONFIG1_DESC_SIZE] = { - // configuration descriptor, USB spec 9.6.3, page 264-266, Table 9-10 - 9, // bLength; - 2, // bDescriptorType; - LSB(CONFIG1_DESC_SIZE), // wTotalLength - MSB(CONFIG1_DESC_SIZE), - 2, // bNumInterfaces - 1, // bConfigurationValue - 0, // iConfiguration - 0xC0, // bmAttributes - 50, // bMaxPower - // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12 - 9, // bLength - 4, // bDescriptorType - 0, // bInterfaceNumber - 0, // bAlternateSetting - 1, // bNumEndpoints - 0x02, // bInterfaceClass - 0x02, // bInterfaceSubClass - 0x01, // bInterfaceProtocol - 0, // iInterface - // CDC Header Functional Descriptor, CDC Spec 5.2.3.1, Table 26 - 5, // bFunctionLength - 0x24, // bDescriptorType - 0x00, // bDescriptorSubtype - 0x10, 0x01, // bcdCDC - // Call Management Functional Descriptor, CDC Spec 5.2.3.2, Table 27 - 5, // bFunctionLength - 0x24, // bDescriptorType - 0x01, // bDescriptorSubtype - 0x01, // bmCapabilities - 1, // bDataInterface - // Abstract Control Management Functional Descriptor, CDC Spec 5.2.3.3, Table 28 - 4, // bFunctionLength - 0x24, // bDescriptorType - 0x02, // bDescriptorSubtype - 0x06, // bmCapabilities - // Union Functional Descriptor, CDC Spec 5.2.3.8, Table 33 - 5, // bFunctionLength - 0x24, // bDescriptorType - 0x06, // bDescriptorSubtype - 0, // bMasterInterface - 1, // bSlaveInterface0 - // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13 - 7, // bLength - 5, // bDescriptorType - CDC_ACM_ENDPOINT | 0x80, // bEndpointAddress - 0x03, // bmAttributes (0x03=intr) - CDC_ACM_SIZE, 0, // wMaxPacketSize - 64, // bInterval - // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12 - 9, // bLength - 4, // bDescriptorType - 1, // bInterfaceNumber - 0, // bAlternateSetting - 2, // bNumEndpoints - 0x0A, // bInterfaceClass - 0x00, // bInterfaceSubClass - 0x00, // bInterfaceProtocol - 0, // iInterface - // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13 - 7, // bLength - 5, // bDescriptorType - CDC_RX_ENDPOINT, // bEndpointAddress - 0x02, // bmAttributes (0x02=bulk) - CDC_RX_SIZE, 0, // wMaxPacketSize - 0, // bInterval - // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13 - 7, // bLength - 5, // bDescriptorType - CDC_TX_ENDPOINT | 0x80, // bEndpointAddress - 0x02, // bmAttributes (0x02=bulk) - CDC_TX_SIZE, 0, // wMaxPacketSize - 0 // bInterval -}; - -// If you're desperate for a little extra code memory, these strings -// can be completely removed if iManufacturer, iProduct, iSerialNumber -// in the device desciptor are changed to zeros. -struct usb_string_descriptor_struct { - uint8_t bLength; - uint8_t bDescriptorType; - int16_t wString[]; -}; -static const struct usb_string_descriptor_struct PROGMEM string0 = { - 4, - 3, - {0x0409} -}; -static const struct usb_string_descriptor_struct PROGMEM string1 = { - sizeof(STR_MANUFACTURER), - 3, - STR_MANUFACTURER -}; -static const struct usb_string_descriptor_struct PROGMEM string2 = { - sizeof(STR_PRODUCT), - 3, - STR_PRODUCT -}; -static const struct usb_string_descriptor_struct PROGMEM string3 = { - sizeof(STR_SERIAL_NUMBER), - 3, - STR_SERIAL_NUMBER -}; - -// This table defines which descriptor data is sent for each specific -// request from the host (in wValue and wIndex). -static const struct descriptor_list_struct { - uint16_t wValue; - uint16_t wIndex; - const uint8_t *addr; - uint8_t length; -} PROGMEM descriptor_list[] = { - {0x0100, 0x0000, device_descriptor, sizeof(device_descriptor)}, - {0x0200, 0x0000, config1_descriptor, sizeof(config1_descriptor)}, - {0x0300, 0x0000, (const uint8_t *)&string0, 4}, - {0x0301, 0x0409, (const uint8_t *)&string1, sizeof(STR_MANUFACTURER)}, - {0x0302, 0x0409, (const uint8_t *)&string2, sizeof(STR_PRODUCT)}, - {0x0303, 0x0409, (const uint8_t *)&string3, sizeof(STR_SERIAL_NUMBER)} -}; -#define NUM_DESC_LIST (sizeof(descriptor_list)/sizeof(struct descriptor_list_struct)) - - -/************************************************************************** - * - * Variables - these are the only non-stack RAM usage - * - **************************************************************************/ - -// zero when we are not configured, non-zero when enumerated -static volatile uint8_t usb_configuration=0; - -// the time remaining before we transmit any partially full -// packet, or send a zero length packet. -static volatile uint8_t transmit_flush_timer=0; -static uint8_t transmit_previous_timeout=0; - -// serial port settings (baud rate, control signals, etc) set -// by the PC. These are ignored, but kept in RAM. -static uint8_t cdc_line_coding[7]={0x00, 0xE1, 0x00, 0x00, 0x00, 0x00, 0x08}; -static uint8_t cdc_line_rtsdtr=0; - - -/************************************************************************** - * - * Public Functions - these are the API intended for the user - * - **************************************************************************/ - -// initialize USB serial -void usb_init(void) -{ - sei(); - HW_CONFIG(); - USB_FREEZE(); // enable USB - PLL_CONFIG(); // config PLL, 16 MHz xtal - while (!(PLLCSR & (1< size) write_size = size; - size -= write_size; - - // write the packet - switch (write_size) { - #if (CDC_TX_SIZE == 64) - case 64: UEDATX = *buffer++; - case 63: UEDATX = *buffer++; - case 62: UEDATX = *buffer++; - case 61: UEDATX = *buffer++; - case 60: UEDATX = *buffer++; - case 59: UEDATX = *buffer++; - case 58: UEDATX = *buffer++; - case 57: UEDATX = *buffer++; - case 56: UEDATX = *buffer++; - case 55: UEDATX = *buffer++; - case 54: UEDATX = *buffer++; - case 53: UEDATX = *buffer++; - case 52: UEDATX = *buffer++; - case 51: UEDATX = *buffer++; - case 50: UEDATX = *buffer++; - case 49: UEDATX = *buffer++; - case 48: UEDATX = *buffer++; - case 47: UEDATX = *buffer++; - case 46: UEDATX = *buffer++; - case 45: UEDATX = *buffer++; - case 44: UEDATX = *buffer++; - case 43: UEDATX = *buffer++; - case 42: UEDATX = *buffer++; - case 41: UEDATX = *buffer++; - case 40: UEDATX = *buffer++; - case 39: UEDATX = *buffer++; - case 38: UEDATX = *buffer++; - case 37: UEDATX = *buffer++; - case 36: UEDATX = *buffer++; - case 35: UEDATX = *buffer++; - case 34: UEDATX = *buffer++; - case 33: UEDATX = *buffer++; - #endif - #if (CDC_TX_SIZE >= 32) - case 32: UEDATX = *buffer++; - case 31: UEDATX = *buffer++; - case 30: UEDATX = *buffer++; - case 29: UEDATX = *buffer++; - case 28: UEDATX = *buffer++; - case 27: UEDATX = *buffer++; - case 26: UEDATX = *buffer++; - case 25: UEDATX = *buffer++; - case 24: UEDATX = *buffer++; - case 23: UEDATX = *buffer++; - case 22: UEDATX = *buffer++; - case 21: UEDATX = *buffer++; - case 20: UEDATX = *buffer++; - case 19: UEDATX = *buffer++; - case 18: UEDATX = *buffer++; - case 17: UEDATX = *buffer++; - #endif - #if (CDC_TX_SIZE >= 16) - case 16: UEDATX = *buffer++; - case 15: UEDATX = *buffer++; - case 14: UEDATX = *buffer++; - case 13: UEDATX = *buffer++; - case 12: UEDATX = *buffer++; - case 11: UEDATX = *buffer++; - case 10: UEDATX = *buffer++; - case 9: UEDATX = *buffer++; - #endif - case 8: UEDATX = *buffer++; - case 7: UEDATX = *buffer++; - case 6: UEDATX = *buffer++; - case 5: UEDATX = *buffer++; - case 4: UEDATX = *buffer++; - case 3: UEDATX = *buffer++; - case 2: UEDATX = *buffer++; - default: - case 1: UEDATX = *buffer++; - case 0: break; - } - // if this completed a packet, transmit it now! - if (!(UEINTX & (1<= NUM_DESC_LIST) { - UECONX = (1< desc_length) len = desc_length; - do { - // wait for host ready for IN packet - do { - i = UEINTX; - } while (!(i & ((1<= 1 && i <= MAX_ENDPOINT) { - usb_send_in(); - UENUM = i; - if (bRequest == SET_FEATURE) { - UECONX = (1< -static int dw_putchar(char __c, FILE *__stream) { DWDR = __c;(void)__stream; return __c;} -FILE dwout = FDEV_SETUP_STREAM(dw_putchar, NULL, _FDEV_SETUP_WRITE); -stdout=&dwout; -#endif - -// Very simple character echo test -int main(void) -{ - CPU_PRESCALE(0); - usb_init(); - while(usb_configured()==0); - while (1) { - int n = usb_serial_getchar(); - if (n >= 0) usb_serial_putchar(n); - } -} diff --git a/examples/extra_board_usb/at90usb162_cdc_loopback.h b/examples/extra_board_usb/at90usb162_cdc_loopback.h deleted file mode 100644 index 2d8370687..000000000 --- a/examples/extra_board_usb/at90usb162_cdc_loopback.h +++ /dev/null @@ -1,125 +0,0 @@ -/* vim: set sts=4:sw=4:ts=4:noexpandtab */ -#ifndef usb_serial_h__ -#define usb_serial_h__ - -#include - -// setup -void usb_init(void); // initialize everything -uint8_t usb_configured(void); // is the USB port configured - -// receiving data -int16_t usb_serial_getchar(void); // receive a character (-1 if timeout/error) -uint8_t usb_serial_available(void); // number of bytes in receive buffer -void usb_serial_flush_input(void); // discard any buffered input - -// transmitting data -int8_t usb_serial_putchar(uint8_t c); // transmit a character -int8_t usb_serial_putchar_nowait(uint8_t c); // transmit a character, do not wait -int8_t usb_serial_write(const uint8_t *buffer, uint16_t size); // transmit a buffer -void usb_serial_flush_output(void); // immediately transmit any buffered output - -// serial parameters -uint32_t usb_serial_get_baud(void); // get the baud rate -uint8_t usb_serial_get_stopbits(void); // get the number of stop bits -uint8_t usb_serial_get_paritytype(void);// get the parity type -uint8_t usb_serial_get_numbits(void); // get the number of data bits -uint8_t usb_serial_get_control(void); // get the RTS and DTR signal state -int8_t usb_serial_set_control(uint8_t signals); // set DSR, DCD, RI, etc - -// constants corresponding to the various serial parameters -#define USB_SERIAL_DTR 0x01 -#define USB_SERIAL_RTS 0x02 -#define USB_SERIAL_1_STOP 0 -#define USB_SERIAL_1_5_STOP 1 -#define USB_SERIAL_2_STOP 2 -#define USB_SERIAL_PARITY_NONE 0 -#define USB_SERIAL_PARITY_ODD 1 -#define USB_SERIAL_PARITY_EVEN 2 -#define USB_SERIAL_PARITY_MARK 3 -#define USB_SERIAL_PARITY_SPACE 4 -#define USB_SERIAL_DCD 0x01 -#define USB_SERIAL_DSR 0x02 -#define USB_SERIAL_BREAK 0x04 -#define USB_SERIAL_RI 0x08 -#define USB_SERIAL_FRAME_ERR 0x10 -#define USB_SERIAL_PARITY_ERR 0x20 -#define USB_SERIAL_OVERRUN_ERR 0x40 - -// This file does not include the HID debug functions, so these empty -// macros replace them with nothing, so users can compile code that -// has calls to these functions. -#define usb_debug_putchar(c) -#define usb_debug_flush_output() - - - -// Everything below this point is only intended for usb_serial.c -#ifdef USB_SERIAL_PRIVATE_INCLUDE -#include -#include -#include - -#define EP_TYPE_CONTROL 0x00 -#define EP_TYPE_BULK_IN 0x81 -#define EP_TYPE_BULK_OUT 0x80 -#define EP_TYPE_INTERRUPT_IN 0xC1 -#define EP_TYPE_INTERRUPT_OUT 0xC0 -#define EP_TYPE_ISOCHRONOUS_IN 0x41 -#define EP_TYPE_ISOCHRONOUS_OUT 0x40 -#define EP_SINGLE_BUFFER 0x02 -#define EP_DOUBLE_BUFFER 0x06 -#define EP_SIZE(s) ((s) == 64 ? 0x30 : \ - ((s) == 32 ? 0x20 : \ - ((s) == 16 ? 0x10 : \ - 0x00))) - -#define MAX_ENDPOINT 4 - -#define LSB(n) (n & 255) -#define MSB(n) ((n >> 8) & 255) - -#if defined(__AVR_AT90USB162__) -#define HW_CONFIG() -#define PLL_CONFIG() (PLLCSR = ((1< - - This file is part of simavr. - - simavr is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - simavr is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with simavr. If not, see . - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "sim_avr.h" -#include "avr_ioport.h" -#include "sim_elf.h" -#include "sim_hex.h" -#include "sim_gdb.h" -#include "vhci_usb.h" -#include "sim_vcd_file.h" - -struct vhci_usb_t vhci_usb; -avr_t * avr = NULL; -avr_vcd_t vcd_file; - - -struct avr_flash { - char avr_flash_path[1024]; - int avr_flash_fd; -}; - -// avr special flash initalization -// here: open and map a file to enable a persistent storage for the flash memory -void avr_special_init( avr_t* avr, void *data) -{ - struct avr_flash *flash_data = (struct avr_flash *)data; - //puts(" --=== INIT CALLED ===--"); - // release flash memory if allocated - if(avr->flash) free(avr->flash); - // open the file - flash_data->avr_flash_fd = open(flash_data->avr_flash_path, - O_RDWR|O_CREAT, 0644); - if (flash_data->avr_flash_fd < 0) { - perror(flash_data->avr_flash_path); - exit(1); - } - // resize and map the file the file - (void)ftruncate(flash_data->avr_flash_fd, avr->flashend + 1); - avr->flash = (uint8_t*)mmap(NULL, avr->flashend + 1, // 32k is multiple of 4096 - PROT_READ|PROT_WRITE, MAP_SHARED, flash_data->avr_flash_fd, 0); - if (!avr->flash) { - fprintf(stderr, "unable to map memory\n"); - perror(flash_data->avr_flash_path); - exit(1); - } -} - -// avr special flash deinitalization -// here: cleanup the persistent storage -void avr_special_deinit( avr_t* avr, void *data) -{ - struct avr_flash *flash_data = (struct avr_flash *)data; - //puts(" --=== DEINIT CALLED ===--"); - // unmap and close the file - munmap( avr->flash, avr->flashend + 1); - close(flash_data->avr_flash_fd); - // signal that cleanup is done - avr->flash = NULL; -} - -int main(int argc, char *argv[]) -{ -// elf_firmware_t f; - const char * pwd = dirname(argv[0]); - struct avr_flash flash_data; - - avr = avr_make_mcu_by_name("at90usb162"); - if (!avr) { - fprintf(stderr, "%s: Error creating the AVR core\n", argv[0]); - exit(1); - } - strcpy(flash_data.avr_flash_path, "simusb_flash.bin"); - flash_data.avr_flash_fd = 0; - // register our own functions - avr->custom.init = avr_special_init; - avr->custom.deinit = avr_special_deinit; - avr->custom.data = &flash_data; - //avr->reset = NULL; - avr_init(avr); - avr->frequency = 8000000; - - // this trick creates a file that contains /and keep/ the flash - // in the same state as it was before. This allow the bootloader - // app to be kept, and re-run if the bootloader doesn't get a - // new one - { - char path[1024]; - uint32_t base, size; - snprintf(path, sizeof(path), "%s/../%s", pwd, "at90usb162_cdc_loopback.hex"); - - uint8_t * boot = read_ihex_file(path, &size, &base); - if (!boot) { - fprintf(stderr, "%s: Unable to load %s\n", argv[0], path); - exit(1); - } - printf("Bootloader %04x: %d\n", base, size); - memcpy(avr->flash + base, boot, size); - free(boot); - avr->pc = base; - avr->codeend = avr->flashend; - } - - // even if not setup at startup, activate gdb if crashing - avr->gdb_port = 1234; - if (0) { - //avr->state = cpu_Stopped; - avr_gdb_init(avr); - } - - vhci_usb_init(avr, &vhci_usb); - vhci_usb_connect(&vhci_usb, '0'); - - - while (1) { - avr_run(avr); - } -} diff --git a/examples/parts/Makefile b/examples/parts/Makefile index 7a490988f..4518e4003 100644 --- a/examples/parts/Makefile +++ b/examples/parts/Makefile @@ -34,13 +34,6 @@ ifeq (${shell uname -o}, Msys) objects := $(filter-out %uart_pty.o, $(objects)) endif -# Unless the VHCI_USB env var is set, don't build this because it requires -# a supporting library to be installed. See examples/extra_board_usb/README -# for details on how to build it. -ifndef VHCI_USB - objects := $(filter-out %vhci_usb.o, $(objects)) -endif - # # Static library # diff --git a/examples/parts/usbip_usb.c b/examples/parts/usbip_usb.c new file mode 100644 index 000000000..edb43fe3a --- /dev/null +++ b/examples/parts/usbip_usb.c @@ -0,0 +1,1065 @@ +/* + usbip_usb.c + + USB/IP server for the simavr USB device model, see usbip_usb.h. + + USB/IP carries USB requests over TCP, so that a USB device plugged + into one machine (the server) is used by the USB stack of another + (the client) as if it were plugged in there. The protocol is version + 1.1.1 of Documentation/usb/usbip_protocol.rst in the Linux kernel + tree. All fields are big endian. On Linux the client is the usbip + tool and the vhci-hcd driver, a virtual host controller whose ports + the imported devices are plugged into. On Windows it is usbip-win2. + + A session over one TCP connection, default port 3240: + + client server + OP_REQ_DEVLIST ----> + <---- OP_REP_DEVLIST + (the connection is closed, "usbip list" is done) + + OP_REQ_IMPORT, busid "1-1" ----> + <---- OP_REP_IMPORT + (the socket is handed to vhci-hcd, "usbip attach" is done) + USBIP_CMD_SUBMIT, seqnum 1 ----> + USBIP_CMD_SUBMIT, seqnum 2 ----> + <---- USBIP_RET_SUBMIT, seqnum 1 + USBIP_CMD_UNLINK of seqnum 2 ----> + <---- USBIP_RET_UNLINK + ... + + - OP_REQ_DEVLIST lists the exported devices: the fields of their + device descriptor and the class of each interface. + - OP_REQ_IMPORT asks for one device by its bus ID. Once it is + accepted, the connection carries that device's URBs until either + side closes it. The server closing it is how the client learns + that the device was unplugged. + - A URB (USB request block) is one transfer on one endpoint: a + control transfer on EP0 with its 8 byte SETUP, or a bulk or + interrupt transfer of up to transfer_buffer_length bytes. + USBIP_CMD_SUBMIT carries it with the OUT data following the + header. USBIP_RET_SUBMIT completes it with the same seqnum, a + status (0 or a Linux errno, negated) and the IN data following + the header. The client keeps several URBs pending, so replies + can come in any order. A bulk IN URB that the device has no data + for stays pending until it has some. + - USBIP_CMD_UNLINK cancels a pending URB, a client does that when + it times out or the file using the device is closed. The + USBIP_RET_UNLINK is -ECONNRESET if the URB was still pending, + which then gets no USBIP_RET_SUBMIT, or 0 if it had completed + already. + - The client's host controller answers SET_ADDRESS itself, it + never reaches the server. The server resets and addresses its + own device, as the Linux usbip-host driver does with a real one. + + The part is the server, with the simulated device behind it: + - It runs from a cycle timer every TICK_US of simulated time: + accepts connections, reads the sockets, answers requests and + moves the queued URBs on. + - It enumerates the device itself when the firmware attaches, + to list it and to learn its endpoint sizes, and resets it when a + client imports it. + - Each URB is a series of AVR_IOCTL_USB_SETUP, _READ and _WRITE + calls to avr_usb.c, one per packet. A packet the firmware isn't + ready for (NAK) is tried again on the next tick. + - When the firmware detaches from the bus, it closes the importing + connection, and lists the device again once it has re-enumerated. + + This file is part of simavr. + + simavr is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + simavr is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with simavr. If not, see . + */ + +#include +#include +#include +#include +#include + +#include "sim_avr.h" +#include "sim_io.h" +#include "sim_time.h" +#include "sim_network.h" +#include "avr_usb.h" +#include "usbip_usb.h" + +/* + * The sockets are non-blocking, and only read or accepted from once + * select() says they are ready. A connection that went away between the + * two then can't make accept() or recv() wait, which would stop the + * simulation. A send() that finds the socket buffer full waits for room + * in select() instead, so a client that stops reading holds the + * simulation until it reads again or closes the connection. + */ +#ifdef __MINGW32__ +#define sock_close(fd) closesocket(fd) +#define sock_error() WSAGetLastError() +#define sock_blocked() (WSAGetLastError() == WSAEWOULDBLOCK) +#define SOCK_EINTR WSAEINTR +#else +#include +#include +#define sock_close(fd) close(fd) +#define sock_error() errno +#define sock_blocked() (errno == EAGAIN || errno == EWOULDBLOCK) +#define SOCK_EINTR EINTR +#endif + +// macOS has no MSG_NOSIGNAL, SO_NOSIGPIPE is set on the socket instead +#ifndef MSG_NOSIGNAL +#define MSG_NOSIGNAL 0 +#endif + +#define TICK_US 100 // socket and URB polling period +#define RESET_RECOVERY (10000 / TICK_US) // 10ms after a bus reset, TRSTRCY +#define MAX_CONNS 4 // clients listing the device, one importing it +#define BULK_PER_TICK 16 // packets on a pipe while the firmware keeps up + +#define USBIP_VERSION 0x0111 +#define OP_REQ_DEVLIST 0x8005 +#define OP_REP_DEVLIST 0x0005 +#define OP_REQ_IMPORT 0x8003 +#define OP_REP_IMPORT 0x0003 +#define ST_OK 0 +#define ST_NA 1 +#define ST_DEV_BUSY 2 + +#define USBIP_CMD_SUBMIT 1 +#define USBIP_CMD_UNLINK 2 +#define USBIP_RET_SUBMIT 3 +#define USBIP_RET_UNLINK 4 +#define USBIP_DIR_IN 1 +#define USBIP_ISO_DESC_SIZE 16 +#define URB_ZERO_PACKET 0x0040 // USBIP_URB_ZERO_PACKET in + +// URB status codes are Linux errno values, whatever the host's are +#define USBIP_EINVAL 22 +#define USBIP_EPIPE 32 +#define USBIP_ECONNRESET 104 + +#define USB_SPEED_FULL 2 +#define BUSNUM 1 +#define DEVNUM 1 +#define MAX_IFACES 32 + +/* + * The messages, as they are on the wire. Every field is naturally + * aligned, so there is no padding, and each one is converted with + * htonl()/htons() or ntohl()/ntohs(). + * + * They are copies of the Linux definitions, under our names, the paths + * being in the Linux kernel tree: + * - usbip_op_t is struct op_common, in tools/usb/usbip/src/usbip_network.h + * - usbip_device_t and usbip_iface_t are struct usbip_usb_device and + * struct usbip_usb_interface, in tools/usb/usbip/libsrc/usbip_common.h, + * installed as + * - usbip_hdr_t is struct usbip_header, in drivers/usb/usbip/usbip_common.h + * The first and the last are internal to the usbip tools and the kernel, + * and needs libudev and the Linux uapi headers. + * None of them exist on Windows or macOS, so the part has its own. + */ + +// starts OP_REQ_* and OP_REP_*, OP_REQ_IMPORT adds a 32 byte busid +typedef struct usbip_op_t { + uint16_t version; // USBIP_VERSION + uint16_t code; // OP_REQ_* or OP_REP_* + uint32_t status; // ST_*, 0 in requests +} usbip_op_t; + +// a device in OP_REP_DEVLIST, after the device count, and in OP_REP_IMPORT +typedef struct usbip_device_t { + char path[256]; + char busid[32]; + uint32_t busnum; + uint32_t devnum; + uint32_t speed; + uint16_t id_vendor; + uint16_t id_product; + uint16_t bcd_device; + uint8_t device_class; + uint8_t device_subclass; + uint8_t device_protocol; + uint8_t configuration_value; + uint8_t num_configurations; + uint8_t num_interfaces; +} usbip_device_t; + +// follows each device in OP_REP_DEVLIST, num_interfaces of them +typedef struct usbip_iface_t { + uint8_t iface_class; + uint8_t iface_subclass; + uint8_t iface_protocol; + uint8_t padding; +} usbip_iface_t; + +// starts every message once a device is imported +typedef struct usbip_hdr_t { + uint32_t command; // USBIP_CMD_* or USBIP_RET_* + uint32_t seqnum; // the client's, a reply has its request's + uint32_t devid; // busnum << 16 | devnum + uint32_t direction; // 0 OUT, USBIP_DIR_IN + uint32_t ep; // endpoint number, without the direction bit + union { + struct { + uint32_t transfer_flags; // Linux URB flags, URB_ZERO_PACKET + uint32_t transfer_buffer_length; + uint32_t start_frame; + // isochronous only, 0 or 0xffffffff otherwise + uint32_t number_of_packets; + uint32_t interval; + uint8_t setup[8]; // SETUP packet of a control transfer + } submit; + struct { + uint32_t status; // 0 or a negative Linux errno + uint32_t actual_length; // bytes transferred + uint32_t start_frame; + uint32_t number_of_packets; + uint32_t error_count; + uint8_t padding[8]; + } ret; + struct { + uint32_t seqnum; // of the USBIP_CMD_SUBMIT to cancel + uint8_t padding[24]; + } unlink; + }; +} usbip_hdr_t; + +enum { DEV_DETACHED, DEV_ENUMERATING, DEV_READY }; + +// stages of a transfer, the status one being a zero length packet +enum { XFER_SETUP, XFER_DATA, XFER_STATUS }; +// what urb_step() did +enum { STEP_NAK, STEP_MORE, STEP_DONE }; + +/* + * The part's own enumeration, done with URBs: enum_setups[step - 1]. + * ENUM_IMPORT is the SET_ADDRESS after the bus reset done on import. + */ +static const uint8_t enum_setups[][8] = { + { 0x00, 5, DEVNUM, 0, 0, 0, 0, 0 }, // SET_ADDRESS + { 0x80, 6, 0, 1, 0, 0, 18, 0 }, // GET_DESCRIPTOR(device) + { 0x80, 6, 0, 2, 0, 0, 9, 0 }, // GET_DESCRIPTOR(configuration), head + { 0x80, 6, 0, 2, 0, 0, 0, 0 }, // and all of it, wTotalLength set +}; +#define ENUM_IMPORT 5 + +typedef struct urb_t { + struct urb_t * next; + uint32_t seqnum; + uint8_t ep, in, stage; + uint8_t internal; // enumeration step, 0 for client URBs + uint8_t setup[8]; + uint32_t flags, len, done; + int32_t status; + uint8_t buf[]; +} urb_t; + +typedef struct conn_t { + int fd; // -1 when the slot is free + uint8_t * rx; + size_t rx_len, rx_size; +} conn_t; + +typedef struct usbip_usb_t { + avr_io_t io; // for the reset and dealloc callbacks + avr_t * avr; + int listen_fd; + conn_t conns[MAX_CONNS]; + conn_t * imp; // the connection that imported the device + + int dev_state; + int attached, attach_changed; // from the attach IRQ + int hold_ticks; // no transfers until 0, after a bus reset + + uint8_t dev_desc[18]; + uint8_t n_ifaces; + usbip_iface_t ifaces[MAX_IFACES]; + uint16_t ep_maxp[16][2]; // [ep][in], 0 until the device gives it + uint8_t cfg_value; + + urb_t * urbs; +} usbip_usb_t; + +// USB descriptors are little endian +static uint16_t +le16(const uint8_t * bytes) +{ + return bytes[0] | bytes[1] << 8; +} + +static urb_t * +urb_new(uint32_t len) +{ + urb_t * urb = calloc(1, sizeof(*urb) + len); + + urb->len = len; + return urb; +} + +static void +urb_queue(usbip_usb_t * usbip, urb_t * urb) +{ + urb_t ** link = &usbip->urbs; + + while (*link) + link = &(*link)->next; + urb->next = NULL; + *link = urb; +} + +// all URBs, or only the client's +static void +urbs_flush(usbip_usb_t * usbip, int client_only) +{ + for (urb_t ** link = &usbip->urbs; *link; ) { + urb_t * urb = *link; + if (client_only && urb->internal) { + link = &urb->next; + continue; + } + *link = urb->next; + free(urb); + } +} + +/* + * Connections + */ + +static void +conn_close(usbip_usb_t * usbip, conn_t * conn, const char * why) +{ + if (!conn || conn->fd < 0) + return; + AVR_LOG(usbip->avr, LOG_TRACE, "USBIP: closing connection: %s\n", why); + sock_close(conn->fd); + conn->fd = -1; + conn->rx_len = 0; + if (conn == usbip->imp) { + usbip->imp = NULL; + urbs_flush(usbip, 1); // the enumeration keeps going + } +} + +static int +sock_nonblock(int fd) +{ +#ifdef __MINGW32__ + u_long on = 1; + + return ioctlsocket(fd, FIONBIO, &on); +#else + int flags = fcntl(fd, F_GETFL); + + if (flags < 0) + return -1; + return fcntl(fd, F_SETFL, flags | O_NONBLOCK); +#endif +} + +// until there is room in the socket buffer, or the client has gone +static void +sock_wait_writable(int fd) +{ + fd_set set; + + FD_ZERO(&set); + FD_SET(fd, &set); + select(fd + 1, NULL, &set, NULL, NULL); +} + +static int +conn_send(usbip_usb_t * usbip, conn_t * conn, const void * buf, size_t len) +{ + const uint8_t * bytes = buf; + + while (len && conn->fd >= 0) { + ssize_t sent = send(conn->fd, bytes, len, MSG_NOSIGNAL); + if (sent < 0 && sock_error() == SOCK_EINTR) + continue; + if (sent < 0 && sock_blocked()) { + sock_wait_writable(conn->fd); + continue; + } + if (sent <= 0) { + conn_close(usbip, conn, "send failed"); + return -1; + } + bytes += sent; + len -= sent; + } + if (conn->fd < 0) + return -1; + return 0; +} + +static int +sock_readable(int fd) +{ + fd_set set; + struct timeval tv = { 0, 0 }; + + FD_ZERO(&set); + FD_SET(fd, &set); + return select(fd + 1, &set, NULL, NULL, &tv) > 0; +} + +static void +conn_accept(usbip_usb_t * usbip) +{ + int fd = accept(usbip->listen_fd, NULL, NULL); + int one = 1; + + if (fd < 0) + return; // gone already, or nothing to accept + for (int i = 0; i < MAX_CONNS; i++) { + conn_t * conn = &usbip->conns[i]; + if (conn->fd >= 0) + continue; + // Linux doesn't pass O_NONBLOCK on from the listening socket + if (sock_nonblock(fd)) { + AVR_LOG(usbip->avr, LOG_WARNING, + "USBIP: can't make the connection non-blocking\n"); + sock_close(fd); + return; + } + setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); +#ifdef SO_NOSIGPIPE + setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(one)); +#endif + conn->fd = fd; + conn->rx_len = 0; + AVR_LOG(usbip->avr, LOG_TRACE, "USBIP: client connected\n"); + return; + } + AVR_LOG(usbip->avr, LOG_WARNING, "USBIP: too many clients\n"); + sock_close(fd); +} + +// one recv() per tick, once select() says there is something to read +static void +conn_read(usbip_usb_t * usbip, conn_t * conn) +{ + ssize_t got; + + if (conn->rx_size - conn->rx_len < 4096) { + if (conn->rx_size) + conn->rx_size *= 2; + else + conn->rx_size = 16384; + conn->rx = realloc(conn->rx, conn->rx_size); + } + got = recv(conn->fd, conn->rx + conn->rx_len, conn->rx_size - conn->rx_len, 0); + if (got > 0) + conn->rx_len += got; + else if (got == 0) + conn_close(usbip, conn, "client closed"); + else if (sock_error() != SOCK_EINTR && !sock_blocked()) + conn_close(usbip, conn, "recv failed"); +} + +static void +rx_consume(conn_t * conn, size_t len) +{ + memmove(conn->rx, conn->rx + len, conn->rx_len - len); + conn->rx_len -= len; +} + +/* + * Replies. OP_REP_DEVLIST is the header, the number of devices, then + * the device and its interfaces. OP_REP_IMPORT is the header and, when + * the import is accepted, the device without its interfaces. + */ + +static uint8_t * +append(uint8_t * end, const void * data, size_t len) +{ + memcpy(end, data, len); + return end + len; +} + +static void +op_reply(usbip_usb_t * usbip, conn_t * conn, uint16_t code, uint32_t status, + int devices) +{ + uint8_t msg[sizeof(usbip_op_t) + sizeof(uint32_t) + sizeof(usbip_device_t) + + sizeof(usbip->ifaces)]; + usbip_op_t op = { + .version = htons(USBIP_VERSION), + .code = htons(code), + .status = htonl(status), + }; + uint8_t * end = append(msg, &op, sizeof(op)); + + if (code == OP_REP_DEVLIST) { + uint32_t count = htonl(devices); + end = append(end, &count, sizeof(count)); + } + if (devices) { + const uint8_t * desc = usbip->dev_desc; + usbip_device_t dev = { + .busnum = htonl(BUSNUM), + .devnum = htonl(DEVNUM), + .speed = htonl(USB_SPEED_FULL), + .id_vendor = htons(le16(desc + 8)), + .id_product = htons(le16(desc + 10)), + .bcd_device = htons(le16(desc + 12)), + .device_class = desc[4], + .device_subclass = desc[5], + .device_protocol = desc[6], + .configuration_value = usbip->cfg_value, + .num_configurations = desc[17], + .num_interfaces = usbip->n_ifaces, + }; + snprintf(dev.path, sizeof(dev.path), "/sys/devices/simavr/usb%d/%s", + BUSNUM, USBIP_USB_BUSID); + snprintf(dev.busid, sizeof(dev.busid), "%s", USBIP_USB_BUSID); + end = append(end, &dev, sizeof(dev)); + if (code == OP_REP_DEVLIST) + end = append(end, usbip->ifaces, + usbip->n_ifaces * sizeof(usbip->ifaces[0])); + } + conn_send(usbip, conn, msg, end - msg); +} + +// USBIP_RET_SUBMIT or USBIP_RET_UNLINK to the importing client, data +// following the header for an IN transfer +static void +ret_send(usbip_usb_t * usbip, uint32_t command, uint32_t seqnum, + int32_t status, const uint8_t * data, uint32_t actual) +{ + usbip_hdr_t hdr = { + .command = htonl(command), + .seqnum = htonl(seqnum), + .ret = { + .status = htonl(status), + .actual_length = htonl(actual), + }, + }; + + if (usbip->imp && conn_send(usbip, usbip->imp, &hdr, sizeof(hdr)) == 0 && + data && actual) + conn_send(usbip, usbip->imp, data, actual); +} + +/* + * Enumeration + */ + +static void +enum_queue(usbip_usb_t * usbip, int step, uint16_t len) +{ + int entry = step - 1; + const uint8_t * setup; + urb_t * urb; + + if (step == ENUM_IMPORT) + entry = 0; // the SET_ADDRESS again + setup = enum_setups[entry]; + if (!len) + len = setup[6]; + urb = urb_new(len); + memcpy(urb->setup, setup, 8); + urb->setup[6] = len; + urb->setup[7] = len >> 8; + urb->in = setup[0] >> 7; + urb->internal = step; + urb_queue(usbip, urb); +} + +/* + * Bus reset. As a real host does, the device is given the reset recovery + * time before the next transfer: the firmware handles the end of reset + * in an interrupt and sets EP0 up again, which would lose a SETUP that + * came first. + */ +static int +bus_reset(usbip_usb_t * usbip) +{ + if (avr_ioctl(usbip->avr, AVR_IOCTL_USB_RESET, NULL)) + return -1; + usbip->hold_ticks = RESET_RECOVERY; + return 0; +} + +static void +enum_start(usbip_usb_t * usbip) +{ + usbip->dev_state = DEV_ENUMERATING; + usbip->cfg_value = 0; + memset(usbip->ep_maxp, 0, sizeof(usbip->ep_maxp)); + if (bus_reset(usbip)) + usbip->dev_state = DEV_DETACHED; + else + enum_queue(usbip, 1, 0); +} + +// interfaces (their first alternate setting) and endpoint sizes +static void +parse_config(usbip_usb_t * usbip, const uint8_t * cfg, uint32_t len) +{ + memset(usbip->ifaces, 0, sizeof(usbip->ifaces)); + usbip->n_ifaces = 0; + for (uint32_t i = 0; i + 2 <= len && cfg[i] >= 2; i += cfg[i]) { + const uint8_t * desc = cfg + i; + if (i + desc[0] > len) + break; + if (desc[1] == 4 && desc[0] >= 9 && desc[3] == 0 && + usbip->n_ifaces < MAX_IFACES) { + usbip_iface_t * iface = &usbip->ifaces[usbip->n_ifaces++]; + iface->iface_class = desc[5]; + iface->iface_subclass = desc[6]; + iface->iface_protocol = desc[7]; + } else if (desc[1] == 5 && desc[0] >= 7) + usbip->ep_maxp[desc[2] & 0xf][desc[2] >> 7] = le16(desc + 4) & 0x7ff; + } +} + +static void +enum_done(usbip_usb_t * usbip, urb_t * urb) +{ + if (urb->status || urb->done < urb->len) { + AVR_LOG(usbip->avr, LOG_WARNING, + "USBIP: enumeration step %d failed (%d)\n", + urb->internal, urb->status); + if (urb->internal != ENUM_IMPORT) + usbip->dev_state = DEV_DETACHED; + return; + } + switch (urb->internal) { + case 1: + enum_queue(usbip, 2, 0); + break; + case 2: + memcpy(usbip->dev_desc, urb->buf, 18); + usbip->ep_maxp[0][0] = usbip->ep_maxp[0][1] = urb->buf[7]; + enum_queue(usbip, 3, 0); + break; + case 3: + enum_queue(usbip, 4, le16(urb->buf + 2)); + break; + case 4: + parse_config(usbip, urb->buf, urb->done); + usbip->dev_state = DEV_READY; + AVR_LOG(usbip->avr, LOG_TRACE, + "USBIP: device %04x:%04x ready, %d interface(s)\n", + le16(usbip->dev_desc + 8), le16(usbip->dev_desc + 10), + usbip->n_ifaces); + break; + } +} + +/* + * Transfers. One IOCTL per call: STEP_NAK, STEP_MORE, or STEP_DONE with + * the status in urb->status. Until the device gives an endpoint's size + * (ep_maxp 0, EP0 during the enumeration) a data stage reads whatever + * the firmware sends, until it has the length asked for. + */ +static int +urb_step(usbip_usb_t * usbip, urb_t * urb) +{ + uint16_t maxp = usbip->ep_maxp[urb->ep][urb->in]; + struct avr_io_usb pkt = { urb->ep, 0, NULL }; + uint32_t ctl; + int ret; + + if (!maxp && urb->ep) + maxp = 64; + switch (urb->stage) { + case XFER_SETUP: + pkt.sz = 8; + pkt.buf = urb->setup; + ctl = AVR_IOCTL_USB_SETUP; + break; + case XFER_DATA: + pkt.sz = urb->len - urb->done; + if (maxp && pkt.sz > maxp) + pkt.sz = maxp; + pkt.buf = urb->buf + urb->done; + ctl = urb->in ? AVR_IOCTL_USB_READ : AVR_IOCTL_USB_WRITE; + break; + default: // EP0 status, opposite to the data, or a bulk OUT ZLP + if (urb->in || urb->ep) + ctl = AVR_IOCTL_USB_WRITE; + else + ctl = AVR_IOCTL_USB_READ; + break; + } + ret = avr_ioctl(usbip->avr, ctl, &pkt); + if (ret == AVR_IOCTL_USB_NAK) + return STEP_NAK; + if (ret) { + urb->status = -USBIP_EPIPE; // STALL, or an endpoint the part doesn't have + return STEP_DONE; + } + switch (urb->stage) { + case XFER_SETUP: + urb->stage = urb->len ? XFER_DATA : XFER_STATUS; + return STEP_MORE; + case XFER_DATA: + urb->done += pkt.sz; + if (urb->done < urb->len && !(urb->in && maxp && pkt.sz < maxp)) + return STEP_MORE; // more packets + if (urb->ep == 0 || (!urb->in && urb->len && + (urb->flags & URB_ZERO_PACKET) && !(urb->len % maxp))) { + urb->stage = XFER_STATUS; + return STEP_MORE; + } + return STEP_DONE; + default: + return STEP_DONE; + } +} + +static void +urb_complete(usbip_usb_t * usbip, urb_t * urb) +{ + AVR_LOG(usbip->avr, LOG_TRACE, "USBIP: #%u EP%d%s %02x %02x %u/%u: %d\n", + urb->seqnum, urb->ep, urb->in ? " IN" : "", urb->setup[0], + urb->setup[1], urb->done, urb->len, urb->status); + if (urb->internal) + enum_done(usbip, urb); + else { + const uint8_t * data = NULL; + uint32_t actual = 0; + + // SET_CONFIGURATION, to report it in later device listings + if (!urb->status && urb->ep == 0 && urb->setup[0] == 0x00 && + urb->setup[1] == 9) + usbip->cfg_value = urb->setup[2]; + if (!urb->status) + actual = urb->done; + if (urb->in) + data = urb->buf; // follows the reply + ret_send(usbip, USBIP_RET_SUBMIT, urb->seqnum, urb->status, data, + actual); + } + free(urb); +} + +/* + * Each pipe's oldest URB runs once per tick, so that transfers on a pipe + * complete in order and endpoints interleave. EP0 gets one transaction: + * the firmware has to run between the stages of a control transfer, as + * a real host lets it, LUFA stalls a SETUP that comes straight after a + * status stage or answers a status stage with data left from the + * previous one. A bulk pipe goes on while the firmware keeps up, up to + * BULK_PER_TICK packets, more than full speed allows in 100us. URBs are + * completed after the pass, as that can close the connection. + */ +static void +urbs_run(usbip_usb_t * usbip) +{ + uint32_t busy = 0; + urb_t * done = NULL, ** done_tail = &done; + + if (usbip->hold_ticks) { + usbip->hold_ticks--; + return; + } + for (urb_t ** link = &usbip->urbs; *link; ) { + urb_t * urb = *link; + uint32_t pipe = 1; // EP0, both directions + int packets = 1; + int step = STEP_NAK; + + if (urb->ep) { + pipe = 1u << urb->ep; + if (urb->in) + pipe <<= 16; + packets = BULK_PER_TICK; + } + if (!(busy & pipe)) { + busy |= pipe; + for (int n = 0; n < packets; n++) + if ((step = urb_step(usbip, urb)) != STEP_MORE) + break; + } + if (step == STEP_DONE) { + *link = urb->next; + urb->next = NULL; + *done_tail = urb; + done_tail = &urb->next; + } else + link = &urb->next; + } + while (done) { + urb_t * urb = done; + done = urb->next; + urb_complete(usbip, urb); + } +} + +/* + * Requests from the clients + */ + +static void +handle_op(usbip_usb_t * usbip, conn_t * conn) +{ + while (conn->fd >= 0 && conn->rx_len >= sizeof(usbip_op_t)) { + usbip_op_t op; + char busid[33] = { 0 }; + + memcpy(&op, conn->rx, sizeof(op)); + if (ntohs(op.code) == OP_REQ_DEVLIST) { + rx_consume(conn, sizeof(op)); + op_reply(usbip, conn, OP_REP_DEVLIST, ST_OK, + usbip->dev_state == DEV_READY); + continue; + } + if (ntohs(op.code) != OP_REQ_IMPORT) { + conn_close(usbip, conn, "unknown request"); + return; + } + if (conn->rx_len < sizeof(op) + 32) + return; + memcpy(busid, conn->rx + sizeof(op), 32); + rx_consume(conn, sizeof(op) + 32); + if (usbip->imp || usbip->dev_state != DEV_READY || + strcmp(busid, USBIP_USB_BUSID)) { + op_reply(usbip, conn, OP_REP_IMPORT, + usbip->imp ? ST_DEV_BUSY : ST_NA, 0); + conn_close(usbip, conn, "import refused"); + return; + } + op_reply(usbip, conn, OP_REP_IMPORT, ST_OK, 1); + usbip->imp = conn; + // a fresh device for the client, as after plugging it in + usbip->cfg_value = 0; + if (bus_reset(usbip) == 0) + enum_queue(usbip, ENUM_IMPORT, 0); + AVR_LOG(usbip->avr, LOG_TRACE, "USBIP: device imported\n"); + return; + } +} + +static void +handle_cmd(usbip_usb_t * usbip) +{ + conn_t * conn = usbip->imp; + + while (usbip->imp == conn && conn->fd >= 0 && + conn->rx_len >= sizeof(usbip_hdr_t)) { + usbip_hdr_t hdr; + + memcpy(&hdr, conn->rx, sizeof(hdr)); + uint32_t command = ntohl(hdr.command), seqnum = ntohl(hdr.seqnum); + if (command == USBIP_CMD_UNLINK) { + uint32_t victim = ntohl(hdr.unlink.seqnum); + urb_t ** link = &usbip->urbs; + + rx_consume(conn, sizeof(hdr)); + while (*link && ((*link)->internal || (*link)->seqnum != victim)) + link = &(*link)->next; + // -ECONNRESET: unlinked before completion, 0: already completed + ret_send(usbip, USBIP_RET_UNLINK, seqnum, + *link ? -USBIP_ECONNRESET : 0, NULL, 0); + if (*link) { + urb_t * urb = *link; + *link = urb->next; + free(urb); + } + continue; + } + if (command != USBIP_CMD_SUBMIT) { + conn_close(usbip, conn, "unknown command"); + return; + } + uint32_t in = ntohl(hdr.direction) == USBIP_DIR_IN; + uint32_t len = ntohl(hdr.submit.transfer_buffer_length); + uint32_t npackets = ntohl(hdr.submit.number_of_packets); + int iso = npackets != 0 && npackets != 0xffffffff; + size_t need = sizeof(hdr); + + if (!in) + need += len; // the OUT data follows the header + if (iso) + need += USBIP_ISO_DESC_SIZE * (size_t)npackets; + + if (len > 1 << 20) { + conn_close(usbip, conn, "transfer too large"); + return; + } + if (conn->rx_len < need) + return; + urb_t * urb = urb_new(len); + urb->seqnum = seqnum; + urb->ep = ntohl(hdr.ep) & 0xf; + urb->in = in; + urb->flags = ntohl(hdr.submit.transfer_flags); + memcpy(urb->setup, hdr.submit.setup, 8); + if (!in) + memcpy(urb->buf, conn->rx + sizeof(hdr), len); + rx_consume(conn, need); + if (iso) { + AVR_LOG(usbip->avr, LOG_WARNING, + "USBIP: isochronous transfers are not supported\n"); + ret_send(usbip, USBIP_RET_SUBMIT, seqnum, -USBIP_EINVAL, NULL, 0); + free(urb); + continue; + } + if (urb->ep == 0) { + uint16_t wlength = le16(urb->setup + 6); + urb->in = urb->setup[0] >> 7; + if (wlength < urb->len) + urb->len = wlength; + } else + urb->stage = XFER_DATA; + urb_queue(usbip, urb); + } +} + +static avr_cycle_count_t +usbip_tick( + struct avr_t * avr, + avr_cycle_count_t when, + void * param) +{ + usbip_usb_t * usbip = param; + + if (usbip->attach_changed) { // a detach, an attach, or both + usbip->attach_changed = 0; + urbs_flush(usbip, 0); + conn_close(usbip, usbip->imp, "device detached"); + usbip->dev_state = DEV_DETACHED; + if (usbip->attached) + enum_start(usbip); + } + if (sock_readable(usbip->listen_fd)) + conn_accept(usbip); + for (int i = 0; i < MAX_CONNS; i++) { + conn_t * conn = &usbip->conns[i]; + + if (conn->fd >= 0 && sock_readable(conn->fd)) + conn_read(usbip, conn); + // requests wait while the device is being (re)enumerated + if (conn->fd < 0 || usbip->dev_state == DEV_ENUMERATING) + continue; + if (conn == usbip->imp) + handle_cmd(usbip); + else + handle_op(usbip, conn); + } + urbs_run(usbip); + return when + avr_usec_to_cycles(avr, TICK_US); +} + +// IOCTLs can't be made from here, in the middle of a register write +static void +usbip_attach_hook( + struct avr_irq_t * irq, + uint32_t value, + void * param) +{ + usbip_usb_t * usbip = param; + + usbip->attached = value; + usbip->attach_changed = 1; +} + +/* + * An AVR reset (watchdog, reset pin) cancels all cycle timers. The + * device detaches on the way, through the attach IRQ, so the tick only + * has to be started again. + */ +static void +usbip_reset( + avr_io_t * io) +{ + usbip_usb_t * usbip = (usbip_usb_t *)io; + + avr_cycle_timer_register_usec(usbip->avr, TICK_US, usbip_tick, usbip); +} + +static void +usbip_dealloc( + avr_io_t * io) +{ + usbip_usb_t * usbip = (usbip_usb_t *)io; + + avr_cycle_timer_cancel(usbip->avr, usbip_tick, usbip); + urbs_flush(usbip, 0); + for (int i = 0; i < MAX_CONNS; i++) { + conn_close(usbip, &usbip->conns[i], "shutdown"); + free(usbip->conns[i].rx); + } + sock_close(usbip->listen_fd); + network_release(); + free(usbip); +} + +struct usbip_usb_t * +usbip_usb_init( + struct avr_t * avr, + const char * addr, + uint16_t port) +{ + usbip_usb_t * usbip = calloc(1, sizeof(*usbip)); + struct sockaddr_in sa = { 0 }; + avr_irq_t * irq = avr_io_getirq(avr, AVR_IOCTL_USB_GETIRQ(), USB_IRQ_ATTACH); + + if (!irq) { + fprintf(stderr, "usbip: %s has no USB controller\n", avr->mmcu); + free(usbip); + return NULL; + } + usbip->avr = avr; + for (int i = 0; i < MAX_CONNS; i++) + usbip->conns[i].fd = -1; + if (network_init()) { + fprintf(stderr, "usbip: can't initialise the network\n"); + free(usbip); + return NULL; + } + usbip->listen_fd = socket(AF_INET, SOCK_STREAM, 0); + if (usbip->listen_fd < 0 || sock_nonblock(usbip->listen_fd)) + goto fail; + if (!port) + port = USBIP_USB_DEFAULT_PORT; +#ifndef __MINGW32__ + { // restart without waiting for TIME_WAIT. On Windows this would let + // another program bind the same port, and isn't needed there. + int one = 1; + setsockopt(usbip->listen_fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); + } +#endif + sa.sin_family = AF_INET; + sa.sin_port = htons(port); + sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + if (addr && inet_pton(AF_INET, addr, &sa.sin_addr) != 1) { + fprintf(stderr, "usbip: bad address %s\n", addr); + goto fail; + } + if (bind(usbip->listen_fd, (struct sockaddr *)&sa, sizeof(sa)) < 0 || + listen(usbip->listen_fd, MAX_CONNS) < 0) { + fprintf(stderr, "usbip: can't listen on port %u, error %d\n", + ntohs(sa.sin_port), sock_error()); + goto fail; + } + avr_irq_register_notify(irq, usbip_attach_hook, usbip); + usbip->io.kind = "usbip"; + usbip->io.reset = usbip_reset; + usbip->io.dealloc = usbip_dealloc; + avr_register_io(avr, &usbip->io); + avr_ioctl(avr, AVR_IOCTL_USB_VBUS, (void *)1); + avr_cycle_timer_register_usec(avr, TICK_US, usbip_tick, usbip); + return usbip; +fail: + if (usbip->listen_fd >= 0) + sock_close(usbip->listen_fd); + network_release(); + free(usbip); + return NULL; +} diff --git a/examples/parts/usbip_usb.h b/examples/parts/usbip_usb.h new file mode 100644 index 000000000..a9612d3fe --- /dev/null +++ b/examples/parts/usbip_usb.h @@ -0,0 +1,56 @@ +/* + usbip_usb.h + + USB/IP server for the simavr USB device model. + + The simulated AVR is exported as a USB/IP device, so that a USB/IP + client attaches it to the host's USB stack, e.g. on Linux, with the + mainline vhci-hcd driver: + + modprobe vhci-hcd + usbip list -r 127.0.0.1 + usbip attach -r 127.0.0.1 -b 1-1 + + Everything runs in the simulation thread, from a cycle timer. + + This file is part of simavr. + + simavr is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + simavr is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with simavr. If not, see . + */ + +#ifndef __USBIP_USB_H__ +#define __USBIP_USB_H__ + +#include + +struct avr_t; +struct usbip_usb_t; + +#define USBIP_USB_DEFAULT_PORT 3240 +#define USBIP_USB_BUSID "1-1" + +/* + * Starts listening on addr:port and asserts VBUS, as if the device were + * plugged into a powered port. addr NULL listens on 127.0.0.1 only, + * "0.0.0.0" on all interfaces, which lets other machines attach the + * device. Port 0 is the default 3240. Returns NULL if the socket can't + * be set up. avr_terminate() closes the sockets and frees it. + */ +struct usbip_usb_t * +usbip_usb_init( + struct avr_t * avr, + const char * addr, + uint16_t port); + +#endif /* __USBIP_USB_H__ */ diff --git a/examples/parts/vhci_usb.c b/examples/parts/vhci_usb.c deleted file mode 100644 index 382555f1c..000000000 --- a/examples/parts/vhci_usb.c +++ /dev/null @@ -1,414 +0,0 @@ -/* vim: set sts=4:sw=4:ts=4:noexpandtab - vhci_usb.c - - Copyright 2012 Torbjorn Tyridal - - This file is part of simavr. - - simavr is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - simavr is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with simavr. If not, see . - */ - -/* - this avrsim part is an usb connection between an usb AVR and the virtual - host controller interface vhci-usb - making your sim-avr connect as a real - usb device to the developer machine. - - You'll need vhci-usb and libusb_vhci to make it work. - http://sourceforge.net/projects/usb-vhci/ -*/ - -/* TODO iso endpoint support */ - -#include "vhci_usb.h" -#include "libusb_vhci.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "avr_usb.h" - -static void -vhci_usb_attach_hook( - struct avr_irq_t * irq, - uint32_t value, - void * param) -{ - struct vhci_usb_t * p = (struct vhci_usb_t*) param; - p->attached = !!value; - printf("avr attached: %d\n", p->attached); -} - -struct usbsetup { -uint8_t reqtype; uint8_t req; uint16_t wValue; uint16_t wIndex; uint16_t wLength; -}__attribute__((__packed__)); - -struct _ep { - uint8_t epnum; - uint8_t epsz; -}; - -char * setuprequests[] = - { "GET_STATUS", "CLEAR_FEAT", "", "SET_FEAT", "", "SET_ADDR", "GET_DESCR", - "SET_DESCR", "GET_CONF", "SET_CONF" }; - -static int -control_read( - struct vhci_usb_t * p, - struct _ep * ep, - uint8_t reqtype, - uint8_t req, - uint16_t wValue, - uint16_t wIndex, - uint16_t wLength, - uint8_t * data) -{ - assert(reqtype&0x80); - int ret; - struct usbsetup buf = - { reqtype, req, wValue, wIndex, wLength }; - struct avr_io_usb pkt = - { ep->epnum, sizeof(struct usbsetup), (uint8_t*) &buf }; - - avr_ioctl(p->avr, AVR_IOCTL_USB_SETUP, &pkt); - - pkt.sz = wLength; - pkt.buf = data; - while (wLength) { - usleep(1000); - ret = avr_ioctl(p->avr, AVR_IOCTL_USB_READ, &pkt); - if (ret == AVR_IOCTL_USB_NAK) { - printf(" NAK\n"); - usleep(50000); - continue; - } - if (ret == AVR_IOCTL_USB_STALL) { - printf(" STALL\n"); - return ret; - } - assert(ret==0); - pkt.buf += pkt.sz; - if (ep->epsz != pkt.sz) - break; - wLength -= pkt.sz; - pkt.sz = wLength; - } - wLength = pkt.buf - data; - - usleep(1000); - pkt.sz = 0; - while ((ret = avr_ioctl(p->avr, AVR_IOCTL_USB_WRITE, &pkt)) - == AVR_IOCTL_USB_NAK) { - usleep(50000); - } - assert(ret==0); - return wLength; -} - -static int -control_write( - struct vhci_usb_t * p, - struct _ep * ep, - uint8_t reqtype, - uint8_t req, - uint16_t wValue, - uint16_t wIndex, - uint16_t wLength, - uint8_t * data) -{ - assert((reqtype&0x80)==0); - int ret; - struct usbsetup buf = - { reqtype, req, wValue, wIndex, wLength }; - struct avr_io_usb pkt = - { ep->epnum, sizeof(struct usbsetup), (uint8_t*) &buf }; - - avr_ioctl(p->avr, AVR_IOCTL_USB_SETUP, &pkt); - usleep(10000); - - if (wLength > 0) { - pkt.sz = (wLength > ep->epsz ? ep->epsz : wLength); - pkt.buf = data; - while ((ret = avr_ioctl(p->avr, AVR_IOCTL_USB_WRITE, &pkt)) != 0) { - if (ret == AVR_IOCTL_USB_NAK) { - usleep(50000); - continue; - } - if (ret == AVR_IOCTL_USB_STALL) { - printf(" STALL\n"); - return ret; - } - assert(ret==0); - if (pkt.sz != ep->epsz) - break; - pkt.buf += pkt.sz; - wLength -= pkt.sz; - pkt.sz = (wLength > ep->epsz ? ep->epsz : wLength); - } - } - - pkt.sz = 0; - while ((ret = avr_ioctl(p->avr, AVR_IOCTL_USB_READ, &pkt)) - == AVR_IOCTL_USB_NAK) { - usleep(50000); - } - return ret; -} - -static void -handle_status_change( - struct vhci_usb_t * p, - struct usb_vhci_port_stat*prev, - struct usb_vhci_port_stat*curr) -{ - if (~prev->status & USB_VHCI_PORT_STAT_POWER - && curr->status & USB_VHCI_PORT_STAT_POWER) { - avr_ioctl(p->avr, AVR_IOCTL_USB_VBUS, (void*) 1); - if (p->attached) { - if (usb_vhci_port_connect(p->fd, 1, USB_VHCI_DATA_RATE_FULL) < 0) { - perror("port_connect"); - abort(); - } - } - } - if (prev->status & USB_VHCI_PORT_STAT_POWER - && ~curr->status & USB_VHCI_PORT_STAT_POWER) - avr_ioctl(p->avr, AVR_IOCTL_USB_VBUS, 0); - - if (curr->change & USB_VHCI_PORT_STAT_C_RESET - && ~curr->status & USB_VHCI_PORT_STAT_RESET - && curr->status & USB_VHCI_PORT_STAT_ENABLE) { -// printf("END OF RESET\n"); - } - if (~prev->status & USB_VHCI_PORT_STAT_RESET - && curr->status & USB_VHCI_PORT_STAT_RESET) { - avr_ioctl(p->avr, AVR_IOCTL_USB_RESET, NULL); - usleep(50000); - if (curr->status & USB_VHCI_PORT_STAT_CONNECTION) { - if (usb_vhci_port_reset_done(p->fd, 1, 1) < 0) { - perror("reset_done"); - abort(); - } - } - } - if (~prev->flags & USB_VHCI_PORT_STAT_FLAG_RESUMING - && curr->flags & USB_VHCI_PORT_STAT_FLAG_RESUMING) { - printf("port resuming\n"); - if (curr->status & USB_VHCI_PORT_STAT_CONNECTION) { - printf(" completing\n"); - if (usb_vhci_port_resumed(p->fd, 1) < 0) { - perror("resumed"); - abort(); - } - } - } - if (~prev->status & USB_VHCI_PORT_STAT_SUSPEND - && curr->status & USB_VHCI_PORT_STAT_SUSPEND) - printf("port suspedning\n"); - if (prev->status & USB_VHCI_PORT_STAT_ENABLE - && ~curr->status & USB_VHCI_PORT_STAT_ENABLE) - printf("port disabled\n"); - - *prev = *curr; -} - -static int -get_ep0_size( - struct vhci_usb_t * p) -{ - struct _ep ep0 = - { 0, 8 }; - uint8_t data[8]; - - int res = control_read(p, &ep0, 0x80, 6, 1 << 8, 0, 8, data); - assert(res==8); - return data[7]; -} - -static void -handle_ep0_control( - struct vhci_usb_t * p, - struct _ep * ep0, - struct usb_vhci_urb * urb) -{ - int res; - if (urb->bmRequestType &0x80) { - res = control_read(p,ep0, - urb->bmRequestType, - urb->bRequest, - urb->wValue, - urb->wIndex, - urb->wLength, - urb->buffer); - if (res>=0) { - urb->buffer_actual=res; - res=0; - } - } - else - res = control_write(p,ep0, - urb->bmRequestType, - urb->bRequest, - urb->wValue, - urb->wIndex, - urb->wLength, - urb->buffer); - - if (res==AVR_IOCTL_USB_STALL) - urb->status = USB_VHCI_STATUS_STALL; - else - urb->status = USB_VHCI_STATUS_SUCCESS; -} - -static void * -vhci_usb_thread( - void * param) -{ - struct vhci_usb_t * p = (struct vhci_usb_t*) param; - struct _ep ep0 = - { 0, 0 }; - struct usb_vhci_port_stat port_status; - int id, busnum; - char*busid; - p->fd = usb_vhci_open(1, &id, &busnum, &busid); - - if (p->fd < 0) { - perror("open vhci failed"); - printf("driver loaded, and access bits ok?\n"); - abort(); - } - printf("Created virtual usb host with 1 port at %s (bus# %d)\n", busid, - busnum); - memset(&port_status, 0, sizeof port_status); - - bool avrattached = false; - - for (unsigned cycle = 0;; cycle++) { - struct usb_vhci_work wrk; - - int res = usb_vhci_fetch_work(p->fd, &wrk); - - if (p->attached != avrattached) { - if (p->attached && port_status.status & USB_VHCI_PORT_STAT_POWER) { - if (usb_vhci_port_connect(p->fd, 1, USB_VHCI_DATA_RATE_FULL) - < 0) { - perror("port_connect"); - abort(); - } - } - if (!p->attached) { - ep0.epsz = 0; - //disconnect - } - avrattached = p->attached; - } - - if (res < 0) { - if (errno == ETIMEDOUT || errno == EINTR || errno == ENODATA) - continue; - perror("fetch work failed"); - abort(); - } - - switch (wrk.type) { - case USB_VHCI_WORK_TYPE_PORT_STAT: - handle_status_change(p, &port_status, &wrk.work.port_stat); - break; - case USB_VHCI_WORK_TYPE_PROCESS_URB: - if (!ep0.epsz) - ep0.epsz = get_ep0_size(p); - - wrk.work.urb.buffer = 0; - wrk.work.urb.iso_packets = 0; - if (wrk.work.urb.buffer_length) - wrk.work.urb.buffer = malloc(wrk.work.urb.buffer_length); - if (wrk.work.urb.packet_count) - wrk.work.urb.iso_packets = malloc( - wrk.work.urb.packet_count - * sizeof(struct usb_vhci_iso_packet)); - if (res) { - if (usb_vhci_fetch_data(p->fd, &wrk.work.urb) < 0) { - if (errno != ECANCELED) - perror("fetch_data"); - free(wrk.work.urb.buffer); - free(wrk.work.urb.iso_packets); - usb_vhci_giveback(p->fd, &wrk.work.urb); - break; - } - } - - if (usb_vhci_is_control(wrk.work.urb.type) - && !(wrk.work.urb.epadr & 0x7f)) { - handle_ep0_control(p, &ep0, &wrk.work.urb); - - } else { - struct avr_io_usb pkt = - { wrk.work.urb.epadr, wrk.work.urb.buffer_actual, - wrk.work.urb.buffer }; - if (usb_vhci_is_out(wrk.work.urb.epadr)) - res = avr_ioctl(p->avr, AVR_IOCTL_USB_WRITE, &pkt); - else { - pkt.sz = wrk.work.urb.buffer_length; - res = avr_ioctl(p->avr, AVR_IOCTL_USB_READ, &pkt); - wrk.work.urb.buffer_actual = pkt.sz; - } - if (res == AVR_IOCTL_USB_STALL) - wrk.work.urb.status = USB_VHCI_STATUS_STALL; - else if (res == AVR_IOCTL_USB_NAK) - wrk.work.urb.status = USB_VHCI_STATUS_TIMEDOUT; - else - wrk.work.urb.status = USB_VHCI_STATUS_SUCCESS; - } - if (usb_vhci_giveback(p->fd, &wrk.work.urb) < 0) - perror("giveback"); - free(wrk.work.urb.buffer); - free(wrk.work.urb.iso_packets); - break; - case USB_VHCI_WORK_TYPE_CANCEL_URB: - printf("cancel urb\n"); - break; - default: - printf("illegal work type\n"); - abort(); - } - - } -} - -void -vhci_usb_init( - struct avr_t * avr, - struct vhci_usb_t * p) -{ - p->avr = avr; - pthread_t thread; - - pthread_create(&thread, NULL, vhci_usb_thread, p); - -} - -void -vhci_usb_connect( - struct vhci_usb_t * p, - char uart) -{ - avr_irq_t * t = avr_io_getirq(p->avr, AVR_IOCTL_USB_GETIRQ(), - USB_IRQ_ATTACH); - avr_irq_register_notify(t, vhci_usb_attach_hook, p); -} - diff --git a/examples/parts/vhci_usb.h b/examples/parts/vhci_usb.h deleted file mode 100644 index 55d3012fc..000000000 --- a/examples/parts/vhci_usb.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - vhci_usb.h - - Copyright 2012 Torbjorn Tyridal - - This file is part of simavr. - - simavr is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - simavr is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with simavr. If not, see . - */ - -#include - -struct avr_t; -typedef struct vhci_usb_t { - struct avr_t * avr; - - bool attached; - int fd; -} vhci_usb_t; - - -void vhci_usb_connect(struct vhci_usb_t * p, char uart); -void vhci_usb_init(struct avr_t * avr, struct vhci_usb_t * p); diff --git a/examples/vhci/.gitignore b/examples/vhci/.gitignore deleted file mode 100644 index dec268127..000000000 --- a/examples/vhci/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -include -lib -linux -*.bz2 -libusb_vhci-* -vhci-hcd-* diff --git a/examples/vhci/Makefile b/examples/vhci/Makefile deleted file mode 100644 index 0164152c8..000000000 --- a/examples/vhci/Makefile +++ /dev/null @@ -1,54 +0,0 @@ -# -# This makefile attempts to compile the vhci core module and the -# libusb-vhci library by downloading known tarballs, hacking them -# a little and compiling them -# -# This has been tested on debian, but coild possibly work in other -# distro. the only "real" dependency is to have the linux kernel -# header symlinked at /lib/modules/ -Date: Sun, 19 Feb 2012 17:20:55 +0100 -Subject: [PATCH 1/2] SPIN_LOCK_UNLOCKED has been depreciated - ---- - usb-vhci-hcd.c | 2 +- - 1 files changed, 1 insertions(+), 1 deletions(-) - -diff --git a/usb-vhci-hcd.c b/usb-vhci-hcd.c -index fed46aa..b107e1b 100644 ---- a/usb-vhci-hcd.c -+++ b/usb-vhci-hcd.c -@@ -1040,7 +1040,7 @@ static int device_enum(struct device *dev, void *data) - return unlikely(*((const int *)data) == pdev->id) ? -EINVAL : 0; - } - --static spinlock_t dev_enum_lock = SPIN_LOCK_UNLOCKED; -+static DEFINE_SPINLOCK(dev_enum_lock); - - int usb_vhci_hcd_register(const struct usb_vhci_ifc *ifc, void *context, u8 port_count, struct usb_vhci_device **vdev_ret) - { --- -1.7.5.4 - diff --git a/examples/vhci/patches/hcd-0002-need-transaction-translator.patch b/examples/vhci/patches/hcd-0002-need-transaction-translator.patch deleted file mode 100644 index 5dab784ca..000000000 --- a/examples/vhci/patches/hcd-0002-need-transaction-translator.patch +++ /dev/null @@ -1,25 +0,0 @@ -From 11483dc8c623b93c1ab419a48387161abcf75a45 Mon Sep 17 00:00:00 2001 -From: root -Date: Sun, 19 Feb 2012 17:21:07 +0100 -Subject: [PATCH 2/2] need transaction translator - ---- - usb-vhci-hcd.c | 2 ++ - 1 files changed, 2 insertions(+), 0 deletions(-) - -diff --git a/usb-vhci-hcd.c b/usb-vhci-hcd.c -index b107e1b..fcb9755 100644 ---- a/usb-vhci-hcd.c -+++ b/usb-vhci-hcd.c -@@ -921,6 +921,8 @@ static int vhci_hcd_probe(struct platform_device *pdev) - if(unlikely(!hcd)) return -ENOMEM; - vdev->vhc = usbhcd_to_vhcihcd(hcd); - -+ hcd->has_tt=1; -+ - retval = usb_add_hcd(hcd, 0, 0); // calls vhci_start - if(unlikely(retval)) usb_put_hcd(hcd); - --- -1.7.5.4 - diff --git a/examples/vhci/patches/vhci-0001-Comment-out-function-that-doesn-t-compile.patch b/examples/vhci/patches/vhci-0001-Comment-out-function-that-doesn-t-compile.patch deleted file mode 100644 index 0db9beb37..000000000 --- a/examples/vhci/patches/vhci-0001-Comment-out-function-that-doesn-t-compile.patch +++ /dev/null @@ -1,29 +0,0 @@ -From 8450b39ce40b2cc2e9e7cf3cfceaafdae2605f17 Mon Sep 17 00:00:00 2001 -From: Torbjorn Tyridal -Date: Thu, 23 Feb 2012 13:37:19 +0100 -Subject: [PATCH] Comment out function that doesn't compile - ---- - src/libusb_vhci.c | 8 ++++---- - 1 files changed, 4 insertions(+), 4 deletions(-) - -diff --git a/src/libusb_vhci.c b/src/libusb_vhci.c -index 47fc381..002d7aa 100644 ---- a/src/libusb_vhci.c -+++ b/src/libusb_vhci.c -@@ -389,8 +389,8 @@ int usb_vhci_to_iso_packets_errno(int32_t status) - return usb_vhci_to_errno(status, 0); - } - --int32_t usb_vhci_from_iso_packets_errno(int errno) --{ -- return usb_vhci_from_errno(errno, 0); --} -+// int32_t usb_vhci_from_iso_packets_errno(int errno) -+// { -+// return usb_vhci_from_errno(errno, 0); -+// } - --- -1.7.5.4 - diff --git a/examples/vhci/patches/vhci-0002-need-unistd-for-usleep.patch b/examples/vhci/patches/vhci-0002-need-unistd-for-usleep.patch deleted file mode 100644 index a33471bf9..000000000 --- a/examples/vhci/patches/vhci-0002-need-unistd-for-usleep.patch +++ /dev/null @@ -1,11 +0,0 @@ -diff -uwr libusb_vhci-0.6.orig/src/local_hcd.cpp libusb_vhci-0.6/src/local_hcd.cpp ---- libusb_vhci-0.6.orig/src/local_hcd.cpp 2012-05-18 11:52:17.097659487 +0100 -+++ libusb_vhci-0.6/src/local_hcd.cpp 2012-05-18 11:52:45.161659975 +0100 -@@ -21,6 +21,7 @@ - #endif - - #include -+#include - #include - #include "libusb_vhci.h" - diff --git a/simavr/sim/avr_usb.c b/simavr/sim/avr_usb.c index 37d18835d..3f8beda3b 100644 --- a/simavr/sim/avr_usb.c +++ b/simavr/sim/avr_usb.c @@ -1006,14 +1006,7 @@ avr_usb_ioctl( ret = ep_fifo_usb_read(p, epstate, d->buf, d->sz); if (ret < 0) { raise_ep_interrupt(io->avr, p, ep, nakini); - // is this correct? It makes the cdc example work. - // Linux stops polling the data ep if we send naks,but - // according to usb spec nak'ing should be ok. - if (epstate->uecfg0x.eptype == 2) { - d->sz = 0; - return 0; - } else - return ret; + return ret; } d->sz = ret; epstate->ueintx.fifocon = 1; @@ -1027,6 +1020,11 @@ avr_usb_ioctl( raise_ep_interrupt(io->avr, p, ep, stalledi); return AVR_IOCTL_USB_STALL; } + // the bank still holds a SETUP the firmware hasn't read + if (epstate->ueintx.rxstpi) { + raise_ep_interrupt(io->avr, p, ep, nakouti); + return AVR_IOCTL_USB_NAK; + } ret = ep_fifo_usb_write(p, ep, d->buf, d->sz); if (ret < 0) { diff --git a/simavr/sim/avr_usb.h b/simavr/sim/avr_usb.h index c0880ece9..2fb95e41b 100644 --- a/simavr/sim/avr_usb.h +++ b/simavr/sim/avr_usb.h @@ -46,7 +46,6 @@ enum { * WRITE: OUT data, sz bytes. More than the endpoint size is * truncated and flagged as an overflow to the firmware. * READ: IN data, sz is the buffer size in, the byte count out. - * A bulk endpoint with no data returns OK with sz 0, not NAK. * A zero length READ or WRITE on EP0 is a control status stage. * RESET: bus reset, NULL parameter. -1 while detached. * VBUS: VBUS level as the parameter, (void*)1 when the host powers the diff --git a/simavr/sim/sim_avr.c b/simavr/sim/sim_avr.c index e093c5d2d..feec9afa0 100644 --- a/simavr/sim/sim_avr.c +++ b/simavr/sim/sim_avr.c @@ -257,6 +257,8 @@ avr_reset( avr->sreg[i] = 0; avr_interrupt_reset(avr); avr_cycle_timer_reset(avr); + // before the peripherals reset, as they may start cycle timers + avr->cycle = 0; if (avr->reset) avr->reset(avr); avr_io_t * port = avr->io_port; @@ -277,7 +279,6 @@ avr_reset( port->reset(port); port = port->next; } - avr->cycle = 0; // Prevent crash avr->resetting = 0; }