[USB OTG] [11DEC13] [PATCH] Externally Powered USB OTG

Search This thread

ziddey

Senior Member
Aug 26, 2007
1,905
1,613
I'm compiling my own. I haven't been able to get your zip file to update framework-res.apk with any of the recoveries (cwm 6.0.2.3 and several twrp versions).

My description works fine, i.e. it says USB STORAGE. The bar below that even seems to indicate that most of the storage is available, but it just won't tell me how much (I know I have over 26GB out of 29.71GB available). Is there something in the storage_list.xml that should change since you posted the "source" a few weeks ago? I mean, I copied that, and I've been using that for my compile. So is there something you have changed in that "source" that I may not have included?
I wonder what the issue is with the script. I'm now running the latest TWRP and everything is still working. Does it create the .1 backups? Add the line to build.prop? It did change your platform.xml, so the script is running..

Not sure about the available storage, especially since you're compiling your own storage_list.xml.

I've made a powered otg cable by modifing a normal otg cable.
I've tested it with this kernel and it sometimes works and sometimes not..

When i use a mouse, it works but sometimes the cursor stops moving for some secs and then it works again..
Mass storages are detected but after some secs they become not accessible...

I don't know if it is due to my bad cable or not, anyway if you have any suggestion i'd be glad to be helped by you...
Thank you.
Sounds like an intermittent bad connection to me. Hell, my microusb port is a whole lot looser now than it was a few weeks ago before I started fiddling with all this :(

I think you also need to include ALSA support besides USB Audio; audio devices are being detected, but sound isn't being re-routed to them (not even after a reboot), as if there was no audio device priority logic, which I believe is included in ALSA.
I would do some tests myself but I don't have a linux partition right now.

Thanks for helping out!
ALSA support is also already included. I don't know off the top of my head, but I think you might need to do the rerouting yourself? Sorry I don't have a usb dac to test with.
 

SetiroN

Senior Member
Aug 6, 2010
313
290
github.com
You're right ziddey, everything is enabled in the kernel, I was erroneously assuming that because audio wasn't being re-routed after a restart (which is the usual behaviour so far on every device that has kernel but not framework support) something was missing from it. After manually checking that everything was in place, (no luck in trying to use the usual linux tools - aconf and alsaconf -) I realised that everything needs to be done at framework level on android. Luckily, the guys over at the Nexus 7 forums have already stumbled upon the same issue and developed a solution:
a windows-based services.jar patcher that includes plug&play support.
http://xdaforums.com/showthread.php?t=2029728
Although being developed with the N7 in mind, of course the relevant section and classes of services.jar are identical, thus the patch works handsomelyy on every AOSP-based jelly bean ROM.
You could put a link to that patch in the OP.

A cleaner solution would be to modify the source, Timur developed a very elegant solution (http://timur.mobi/img/usbhost_screenshot3b.png) but it would be up to ROM developers to include it.
 
Last edited:

danba

Senior Member
Jun 22, 2008
184
89
ALSA support is also already included. I don't know off the top of my head, but I think you might need to do the rerouting yourself? Sorry I don't have a usb dac to test with.
There are some very cheap USB DAC/headphone amplifiers: HDE 7.1 Channel USB External Sound Card Audio Adapter for example
http://www.amazon.com/s/ref=nb_sb_n...sb+sound+card&rh=i:aps,k:cm119+usb+sound+card
http://www.ebay.com/sch/i.html?_trk...&_nkw=cm119+usb+sound+card&_sacat=0&_from=R40
 

sga999

Senior Member
Mar 13, 2012
968
165
ziddey, the .1 backup does get created, and build.prop is updated correctly.

ziddey, I decided to flash the PA 3.15 rom. I have been content with stock for several months, but I was curious to see what would happen with another rom. I'm still using TWRP 2.4.4.0 (which had not "worked" when I was on the stock rom, i.e. framework-res.apk was not updated properly). So...I flashed your latest zip file, and it DOES update framework-res.apk. The "bad string" turns into "ISSUED ON:"

Unfortunately, the "Available" space problem is still exactly the same, i.e. smaller font below it with "Available". I can plug this same micro sd card into the OTG cable attached to a Samsung Galaxy Tab 2 7.0, and it works well. This is so strange.

(ASIDE: Oh, I just saw "disable smilies" in text below about options in sending messages....I could have done that to fix the colon p problem last night!).

EDIT: I recompiled framework-res.apk myself with the correct storage_list.xml, and installed it on the same setup as above, i.e. PA 3.15. Now the "bad string" is correct (now it says "USB STORAGE"), but I still have the "Available" problem.

I'm just going to ignore the "Available" problem for now. But about your 2 issues (usbdisk not working at all or a "bad string" displays), it must be that the .xml you're creating cannot be just inserted into the framework-res.apk. It's like there are some "unresolved linkages" (that's my terminology) in your file that only get resolved by actually recompiling all of the pieces and recreating the apk (I know you are already aware of this problem, but I'm just describing it in my own way) . Whenever I have recompiled, the apk has worked for all roms that I've tried....stock deodexed or odexed, or this new PA 3.15. It seems like compiling and recreating the apk is the only surefire way to get a good framework-res.apk.
 

Attachments

  • Screenshot_2013-04-08-15-40-22.jpg
    Screenshot_2013-04-08-15-40-22.jpg
    30.2 KB · Views: 513
Last edited:

sga999

Senior Member
Mar 13, 2012
968
165
ziddey, I just finished editing my prior post to give you a little more info, and then I decided to try one other thing. I decompiled YOUR framework-res.apk. This line shows in storage_list.xml:
<storage android:mountPoint="/storage/usbdisk0" android:storageDescription="@string/issued_on" android:removable="true" />

"Issued on:" was the string I was getting when flashing your zip on this PA rom. Maybe you were already aware that the decompile was showing this, and if so, just ignore this.

EDIT: I just noticed that the first line from the decompile of your apk is bad too. Here are both lines:
<storage android:storageDescription="@string/issued_by" android:emulated="true" android:mtpReserve="100" />
<storage android:mountPoint="/storage/usbdisk0" android:storageDescription="@string/issued_on" android:removable="true" />

If I decompile the original apk, that first line has "@string/storage_internal", which is what we expect.

What is even more strange is that my settings - storage screen shows "INTERNAL STORAGE" despite that bad string in the first line, but the 2nd line displays "ISSUED ON:". That really makes no sense.

These strings are in strings.xml. The PA strings file has more strings than the stock strings file, so the "index" to the string points further down in the stock rom strings file (19 lines?), so it must be choosing the wrong string. (In my particular files, the "issued by" does seem to be at about the right place to cause this problem).

I have no idea if this has any bearing, but when I was trying framework flasher weeks ago, I ran across some things I didn't understand.
1. Someone said to do this before decompiling an apk. They said it would install the device's framework to your system. (This is probably completely unrelated to the problems we're having).
apktool if framework-res.apk
2. Someone said that when creating an update.zip, META-INF/com/google/android/update-binary was rom dependent, and "You will need to pull this from a ROM or Theme.zip".

Are you using an update-binary from your specific rom? Again, I don't know what this all means, but maybe each of us would have to have the right one.
 
Last edited:

simobile

Member
Jul 21, 2007
46
189
Silicon Valley/Bay Area
Slimport and Qualcomm PMIC chips on Nexus 4 support bus powered USBOTG. Even though Qualcomm blows and don't share their datasheets as they should. Information is available elsewhere and can easily be found with some extra digging.

The op here has done a great job in finding a way to get devices identified/connected and now let's get part two working. I don't want to hear that "its not possible". Everything is possible with enough time and patience. So, I'm sure there are many items that need to be looked into for USB bus power output but for now I have found this...

From: https://groups.google.com/forum/?fromgroups=#!topic/android-kernel/B8qgcWjN_G8



Hello,

As per USB compliance update, a device that is actively drawing more
than 100mA from USB must report itself as bus-powered. But currently
in android composite device, the bMaxPower is set to 500 mA and in
bmAttributes, it's set to Self Powered. This is wrong as per the UsB
spec and USBCV throws error as :
A SELF POWERED device cannot draw more than 100ma from the USB bus.
Device consumes > 100ma when SELF POWERED : 500mA

The following patch corrects this.

diff --git a/drivers/usb/gadget/android.c b/drivers/usb/gadget/
android.c
index 5e778e6..d8cf4c9 100644
--- a/drivers/usb/gadget/android.c
+++ b/drivers/usb/gadget/android.c
@@ -183,7 +183,7 @@ static struct usb_configuration
android_config_driver = {
.setup = android_setup_config,
.bConfigurationValue = 1,
.bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
- .bMaxPower = 0xFA, /* 500ma */
+ .bMaxPower = CONFIG_USB_GADGET_VBUS_DRAW / 2,
};

static int android_setup_config(struct usb_configuration *c,
@@ -273,6 +273,19 @@ static int android_bind(struct usb_composite_dev
*cdev)
strings_dev[STRING_SERIAL_IDX].id = id;
device_desc.iSerialNumber = id;

+ /*
+ * As per USB compliance update, a device that is actively drawing
+ * more than 100mA from USB must report itself as bus-powered in
+ * the GetStatus(DEVICE) call.
+ */
+ if (android_config_driver.bMaxPower <=
+ (USB_SELF_POWER_VBUS_MAX_DRAW / 2)) {
+ android_config_driver.bmAttributes =
+ USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER;
+ usb_gadget_set_selfpowered(gadget);
+ } else
+ android_config_driver.bmAttributes = USB_CONFIG_ATT_ONE;
+
/* register our configuration */
ret = usb_add_config(cdev, &android_config_driver);
if (ret) {
@@ -296,7 +309,6 @@ static int android_bind(struct usb_composite_dev
*cdev)
device_desc.bcdDevice = __constant_cpu_to_le16(0x9999);
}

- usb_gadget_set_selfpowered(gadget);
dev->cdev = cdev;
product_id = get_product_id(dev);
device_desc.idProduct = __constant_cpu_to_le16(product_id);

I can confirm that sys/bus/usb/devices/1-1:1.8/subsystem/drivers/usb/usb1/bmaxpower is set to 0ma. I don't have my Micro USBOTG here as Ieft it at work. However, i'll change that value and see what happens when I get a chance. I also have an Acer A500 tablet with a full size USB host port. That file is also labeled as 0ma but I think that is because that voltage is always being presented to the port with an on board regulator. It's not asking Android to enable anything. So Android see's the device as drawing 0ma from the power bus.

I'm no hacker or programmer but I'm more than happy to dig in as much as I can. Also, this is just a thought and it might mean nothing. I was bored and I know this can be solved.
 

ziddey

Senior Member
Aug 26, 2007
1,905
1,613
That's well beyond where the actual problem is. To start, take a look at msm_hsusb_vbus_power() in drivers/usb/otg/msm_otg.c. This function is responsible for actually enabling vbus power. If you look at the kernel messages, you'll see "vbus_otg is NULL." From here, it simply bails out of the function without actually enabling vbus_otg (obviously it can't and will crash since it doesn't exist). Because of lazy coding, it then just assumes that it is enabled and proceeds (good for us since it continues to enable host mode..).

Chasing the issue a little further "upstream", take a look at msm_otg_set_host(). There's a specific if condition of !machine_is_apq_8064_mako(). That is to say, specifically DON'T set vbus_otg for the Nexus 4.. Talk about hardcoding.. I've played around with removing the if condition, but then it's "Unable to get vbus_otg" and bails out hard, pretty much wrecking otg in its entirety (no peripheral mode, host mode, or hsic).

From here, I believe we need to go up to arch/arm/mach-msm/lge/mako/board-mako.c to see that there is no vbus_otg. It'd be worth comparing with j1 code (Optimus G): http://xdaforums.com/showthread.php?p=39019345#post39019345

It looks like the implementation was more in board-j1.c for the LGOG vs. in msm_otg.c itself for us.

I did try to simply boot the "OptimusNexus" kernel (http://xdaforums.com/showthread.php?t=2175663) but it's clearly incompatible and trashed something in /data that killed wifi. I'm going to make a backup of my /data and then try the whole OptimusNexus and see if that runs any differently. If not, we're probably barking up the wrong tree. So far, it still doesn't seem to be confirmed that host mode is indeed working for the LGOG. Somebody with that phone needs to try it..
 
Last edited:

EDV11

Senior Member
Aug 3, 2007
180
13
As much as I would like to have Slimport + OTG working at the same time, I think it is not possible by design.

Here is the spec sheet for ANX7808: http://www.analogix.com/pdf/ANX7808_PB.pdf. It says

The same connector on the device can be used for USB when a SlimPort® receiver is not connected.

So when slimport is connected, the transmitter blocks the USB signal. I have even tried it to connect to the computer while connected to Slimport (USB from computer-Slimport adapter-phone), but only charging is working.

Also

USB host, device or OTG data passes through by default

OTG goes through by default, but when Slimport is connected, it will switch into video output.

Here is a message from Analogix stating that Slimport and OTG will not work together right now. I tried to get more clarification on this, as they say it is planned but I don't know if it will be available for ANX7808 or it will need a different transmitter (probably the latest).

Now, this is a diagram for the communication

LTsfmOm.jpg


Do you think the configuration for this resides in the Slimport transmitter, or is it inside kernel?
 

sga999

Senior Member
Mar 13, 2012
968
165
ziddey, I've gotten the update zip to work on stock 4.2.2 I changed otgmod.sh to stdout the output of the results of the ./zip command into a file so that I could see it later. Also, I changed the option -rf to -rfv (v for verbose). The output said "res/xml/storage_list.xml up to date."

Then I tried changing the option -rf to leave out 'f' (also with v for verbose so that I could see the results again), i.e. no freshening. That worked for me! I would imagine leaving out the freshening is not going to accomplish what you're trying to do for all cases. But at least this gets around the problem for stock. Maybe someone else who has had problems can give this a try too. (I had been recompiling, so I was already getting around this problem, but I wanted to know what was going wrong).

Has this problem been seen on roms other than stock? I know I could go back through all the posts, but if someone can just tell me, that would be great.

NOTE: This does nothing to fix the problem of the wrong string being displayed instead of USB STORAGE. That's due to storage_list,xml and strings.xml "incompatibility" due to being from different roms.
 

ziddey

Senior Member
Aug 26, 2007
1,905
1,613
Huh! Thanks. I'll change that for the next release. I thought about removing the freshen flag anyway now that the script simply assumes the .1 backup is good and doesn't using zip in an if condition anymore (was figuring that might have not been completely kosher). Don't know why that would make any difference though.
 
Last edited:

simobile

Member
Jul 21, 2007
46
189
Silicon Valley/Bay Area
That's well beyond where the actual problem is. To start, take a look at msm_hsusb_vbus_power() in drivers/usb/otg/msm_otg.c. This function is responsible for actually enabling vbus power. If you look at the kernel messages, you'll see "vbus_otg is NULL." From here, it simply bails out of the function without actually enabling vbus_otg (obviously it can't and will crash since it doesn't exist). Because of lazy coding, it then just assumes that it is enabled and proceeds (good for us since it continues to enable host mode..).

Chasing the issue a little further "upstream", take a look at msm_otg_set_host(). There's a specific if condition of !machine_is_apq_8064_mako(). That is to say, specifically DON'T set vbus_otg for the Nexus 4.. Talk about hardcoding.. I've played around with removing the if condition, but then it's "Unable to get vbus_otg" and bails out hard, pretty much wrecking otg in its entirety (no peripheral mode, host mode, or hsic).

From here, I believe we need to go up to arch/arm/mach-msm/lge/mako/board-mako.c to see that there is no vbus_otg. It'd be worth comparing with j1 code (Optimus G): http://xdaforums.com/show...5#post39019345

It looks like the implementation was more in board-j1.c for the LGOG vs. in msm_otg.c itself for us.

I did try to simply boot the "OptimusNexus" kernel (http://xdaforums.com/show....php?t=2175663) but it's clearly incompatible and trashed something in /data that killed wifi. I'm going to make a backup of my /data and then try the whole OptimusNexus and see if that runs any differently. If not, we're probably barking up the wrong tree. So far, it still doesn't seem to be confirmed that host mode is indeed working for the LGOG. Somebody with that phone needs to try it..

Ziddey, I totally agree.

I looked over those files and they really have borked this thing! The only way to get voltage out that I see is spoofing Slimport to send it. It is already enabled to output usb 5volt, 500ma but the trick would be getting that power but keeping it disabled. May or may not ever happen. My head hurts from looking over so many files. I'm a hardware guy by trade (silicon valley robotics) and software only interest me enough to get my hardware to work the way I want it to. If I run across anything else that may be helpful, I'll post it up here. Keep up the good work!
 

ziddey

Senior Member
Aug 26, 2007
1,905
1,613
Where are you seeing 5v 500ma from slimport?

Working with drivers/misc/slimport_anx7808/slimport.c, I've been trying to do some testing to see if I could get enough power to get a usb device working (power from phone, data to computer, since I haven't figured out how to prevent the data pins from being switched for slimport use). I've been able to get 3.1v by forcing slimport, but I haven't tested how much current I can draw before it trips the overcurrent. Of course, usb is 5v, so this requires a device that can either run on 3.1v, or actually is a 3.3v with whatever regulation to step down 5v to 3.3v, in which case it could be modded.

So far, I haven't gotten anywhere. I haven't modded my usb sticks, but they seem to not get enough power. My usb hub seems to trip the overcurrent, losing vbus entirely. I got a few Kingston G2 microsd-usb adapters to play around with ($3 each from http://www.staples.com/Kingston-G2-USB-20-microSDHC-Flash-Memory-Card-Reader-FCR-MRG2/product_651710Staples[/url]. I figure sd is 3.3v/1.8v, so if the controller can work with 3.3v and slimport power can provide enough current, it may be a viable solution (provided we can figure out how to prevent the data pins from switching over).

I remember reading somewhere that the spec for slimport power was 4-50mA @ 3.3V, which may not be enough for sustained operation / initial power-up. That said, a capacitor might allow it to function under most situations..

Anyway, if you want to do some testing, this is the relevant code executed when slimport is connected (slimport_cable_plug_proc()):

Code:
sp_tx_pd_mode = 0; // not exactly needed for our purposes
sp_tx_hardware_poweron();
sp_tx_power_on(SP_TX_PWR_REG);
sp_tx_power_on(SP_TX_PWR_TOTAL);
//hdmi_rx_initialization();
//sp_tx_initialization();
sp_tx_vbus_poweron();

The initialization functions aren't required, but the others look to be essential for now. Basically, I commented out the code in anx7808_cbl_det_isr() and stuffed that in its place.

I'm not sure what the slimport resistance between the id pin and ground is, but either way, an otg cable (id grounded) will not trigger the cable detect. Unplugging it will though, so that's what I've been doing to get things rolling. From there, I've hacked up a cable so that the usb port gets power from the phone, but has the data wires going to my pc. Now to mod up one of these things and test it..
 

simobile

Member
Jul 21, 2007
46
189
Silicon Valley/Bay Area
Slimport is a DisplayPort VESA technology. So it must follow their rules. Your right, about 3.3volts@100milliwatts is what Analogix claims. I'm not sure I believe that current figure as it has to run a dongle IC but whatever. That 3.3volts comes from an onboard regulator on the Slimport IC.I ran into some Slimport power files last night that said it's permitted to receive up to 5 volts from another regulator. Basically, the one that powers the Slimport IC, should be powering our USBOTG.

Not sure if it can be diverted or not.

Thanks for the code. I'll run some test and see what I can come up with.


Lucky Goldstar, she is a cruel mistress.
 

Kodam

Member
Mar 1, 2010
14
2
Ziddey, could you make an otg enabled matr1x kernel?
Franco kernel is really slow for me and reboot really often, but i'd like to use my usb drives.
Thanks,
Kodam
 

ziddey

Senior Member
Aug 26, 2007
1,905
1,613
Ziddey, could you make an otg enabled matr1x kernel?
Franco kernel is really slow for me and reboot really often, but i'd like to use my usb drives.
Thanks,
Kodam

All my changes are provided in the 2nd post (github for msm_otg.c). Feel free to apply and compile matr1x kernel with them.
 

adidas007

Senior Member
Nov 7, 2012
1,204
229
Ziddey, could you make an otg enabled matr1x kernel?
Franco kernel is really slow for me and reboot really often, but i'd like to use my usb drives.
Thanks,
Kodam

+1. I too have no idea about compiling kernels and stuff. Don't want to mess around with this beauty!

It would be really grateful if you could enable usb otg on matr1x kernel whenever you get time.

Sent from my Nexus 4 using xda premium
 

forcedairinduction

Senior Member
Mar 24, 2013
465
44
Ziddey you da man : ). I've been waiting patiently for my y cable to arrive from China (about a month lol). I'd previously bought a5v power pack & today downloaded your kernel & its all worked silky smooth for otg.
Thanks a million mate. It may have been discussed previously but instead of trawling through milliond of posts.....ill ask anyway
Do you intend to make other kernels (particularly trinity & stock carbon) comparable with otg so I don't have to keep re flashing????
Cheeeeers. Mark.
 

EDV11

Senior Member
Aug 3, 2007
180
13
Ziddey you da man : ). I've been waiting patiently for my y cable to arrive from China (about a month lol). I'd previously bought a5v power pack & today downloaded your kernel & its all worked silky smooth for otg.
Thanks a million mate. It may have been discussed previously but instead of trawling through milliond of posts.....ill ask anyway
Do you intend to make other kernels (particularly trinity & stock carbon) comparable with otg so I don't have to keep re flashing????
Cheeeeers. Mark.

You just have to read two posts over yours

Enviado desde mi Nexus 4
 
  • Like
Reactions: forcedairinduction

Top Liked Posts

  • There are no posts matching your filters.
  • 228
    Externally Powered USB OTG - Nexus 4

    This is an all-in-one patch to enable externally powered OTG (technically usb host mode) support. It's built off either the stock kernel or Franco's kernel sources, and should work with any ROM (that these kernels otherwise support). Refer to the second post for details on modifications and additions.

    Again, power MUST be supplied externally, as there is no way for the phone to provide it.


    Requirements:

    Power MUST be supplied to both the USB device and phone. The easiest way would be by using an OTG Y-cable:


    If using a traditional OTG cable, a USB Y-cable can be used:


    Some powered USB hubs also send power up to the host and can be used directly with a regular OTG cable.

    I am not endorsing any specific product or seller. Links are provided solely as examples, and are by no means definitive. As long as the phone and device both get 5V (charger, computer, etc.), and the data pins are connected, host mode will work (provided enough current can be supplied).


    Installation:

    Simply install the zip in recovery. Script will automatically install/patch necessary files. Must reinstall any time ROM is updated.

    To uninstall, simply reflash your ROM. Data wipe is not necessary. If for some reason that's not an option, use the flashable unmod script to remove ROM-side modifications. Flash your kernel of choice afterwards (must flash "reset" kernel first if flashing an "anykernel").


    Recovery:
    (Optional)

    For support in recovery, I've created a sort of "any-any" script. It replaces the recovery's kernel with the boot one. Therefore, by flashing this after the main patch, OTG will effectively be enabled in recovery (after a reboot). However, it is on the actual recovery itself to provide support for usb drives-- TWRP does. Otherwise, you'll have to manually mount any drives via linux console commands.

    For your own safety/sanity, ensure the main patch works before flashing this. If recovery fails to boot after flashing, it can easily be replaced by using GooManager or similar. Worst case scenario, a new recovery can always be flashed via fastboot.


    Downloads:
    (Changelog at end of second post)

    MAKE SURE TO DOWNLOAD THE RIGHT VERSION FOR YOUR ROM.
    I don't keep track of all the different ROMs so it's on you guys to figure out which one is appropriate. The -CM builds have the two "CAF" commits that are now required for CM and its derivatives (unless they have specifically reverted the associated commits).

    Franco-CM builds make use of a ramdisk mod script, which may have unpredictable results. Be ready in case it doesn't boot.

    Current:

    Old:

    Bugs / Notes:
    • An OTG cable has the ID pin grounded out, which is used to trigger usb host mode. However, ID pin detection is broken in the Nexus 4 (although working for Slimport detection). Instead, we rely on detection of a "proprietary" charger (voltage on the data pins) in order to determine when to enable host mode.
    • Self-powered devices (e.g. digital cameras) don't send power to the phone. This will cause the device to not be detectable. Therefore, external power is still required.
    • Slimport cannot work concurrently with usb data due to hardware limitations (Slimport takes over the usb data pins).
    • USB drive will automatically mount at /storage/usbdisk0 (also accessible at /usbdisk and /mnt/usbdisk). Media scanning should occur automatically. Make sure to unmount before removal to avoid data loss.
    • Stock Android only supports FAT for storage. NTFS/exFAT/ext4 partitions may require the use of a third party app like StickMount (CM now supports these partitions natively!).
    • There appears to be a minor bug in the AOSP code that prevents available space from being reported in Settings->Storage->USB Storage. The screenshot is of CM10.1, which has this fixed
    • Current builds do not allow for host mode without charging. Use this as a workaround:
      For those that want to stop usb charging, create a script modifying this to either 1 (disabled) or 0 (enabled). Works for me :) Not responsible for your phone(s) exploding.

      echo 1 > /sys/module/pm8921_charger/parameters/disabled
      echo 0 > /sys/module/pm8921_charger/parameters/disabled
    • Standard Disclaimer-- Flashing this patch is at your own risk, and carries no warranty or liability on my part. The assumption is that you will perform due diligence before flashing and make any necessary backups if required.

    Screenshots:




    Credits:
    • CaptainMuon, for proving that host mode is possible on the Nexus 4.
    • Franco, for his kernel, which this patch is based off.
    • garyd9, for his command to patch platform.xml.
    • Chainfire, for his usb host wisdom, and article on secondary storage write permissions.
    • arpruss, for his compiled zip-for-android
    • All you guys for testing!
    61
    Patch Overview:
    • Kernel with modified msm_otg.c -- This will REPLACE whatever kernel you currently have installed. If you flash a different kernel on top, you will obviously lose OTG capability. This contains the necessary workaround to enable usb host mode ("OTG").
    • Modified init.mako.rc/init.mako.usbdisk.rc -- Required for creating usb drive directories.
    • Precompiled modified storage_list.xml -- Allows unmounting usb drive in Settings->Storage. Hex offsets for storageDescription patched during flash.
    • Addition to build.prop -- Enables downloading apps from play store that require usb host mode support.
    • Addition to platform.xml -- Workaround to allow apps write access to usb drives
    • Addition to handheld_core_hardware.xml -- Activate android.hardware.usb.host.xml
    • android.hardware.usb.host.xml -- Enables Android API support for usb host mode.
    • fstab.mako (4.3) / vold.fstab (4.2) -- Required for automounting usb drive
    • Modules cifs.ko, ff-memless.ko, hid-dr.ko, hid-logitech.ko, and xpad.ko (/system/lib/modules). Manually insmod as needed or create an appropriate init.d script to load on boot. These are only required for certain gamepads. Refer here for more information.

    Patch Details:

    There seems to be an issue with detecting the state of the ID pin on the OTG cable, so we need to come up with an alternate way of determining when to switch to host mode. drivers/usb/otg/msm_otg.c (kernel) is responsible for detecting the charger type and setting host mode, among other tasks. I noticed that when connected to a powered OTG cable, the charge type becomes USB_PROPRIETARY_CHARGER (vs USB_DCP_CHARGER when connected to the wall, and USB_SDP_CHARGER to a computer). This will be the condition that we use to trigger host mode.

    Standard OTG cables will have the ID pin shorted to ground. There are also usb accessory charger adapters (ACA) that provide different resistances between these pins to signal functionality (see http://en.wikipedia.org/wiki/USB_On-The-Go#OTG_Micro_Plugs). Support for accessory charger detection isn't enabled in the kernel originally, and doesn't seem to work properly anyway. However, one of the modes is essentially what we're trying to achieve (ID_A): "A charger and a B-device are attached. The OTG device is allowed to charge and enter host mode." So I've added code when USB_PROPRIETARY_CHARGER is detected to simulate the case of ID_A being detected. Following through the code for host mode, certain events are handled differently when ACA support is enabled (specifically, suspension of host mode). In these instances, we need to simulate ACA support since ID_A is technically dependent on it (run into issues with the usb controller getting stuck in a suspended state otherwise). Now we have host mode with charging working properly.

    Finally, we need a method of detecting when the OTG cable is unplugged so the device can switch out of host mode. Fortunately, since power (vbus) detection does work, we can use that. Normally, changes in vbus state are ignored while in host mode, so we need to address that. From there, we simulate ACA detection for the case of no ID_A, which is just clearing the ID_A bit and charger. Afterwards, it'll automatically reset the usb state, ready to start all over again.

    The dirty hacks to msm_otg.c are complete, and externally-powered OTG is functional.

    Refer here for actual changes: https://github.com/ziddey/mako/commits/nightlies-4.3-JSS

    No changes are needed to the kernel's .config. Do not enable Drivers->USB->OTG support (we get our support through "OTG support for Qualcomm on-chip USB controller" which is already enabled) or Support for ACA (does not work and most users don't have the proper adapter anyway).


    Now we run into a problem with usb storage. Since there is no /system/etc/vold.fstab, usb drives get automatically mounted to /mnt/shell/emulated/0 (at least in CM10.1), which overloads the emulated sdcard, and causes major problems. So we create /system/etc/vold.fstab:

    Code:
    dev_mount usbdisk /storage/usbdisk0 auto /devices/platform/msm_hsusb_host/usb2

    Update:
    In 4.3, Google did away with vold.fstab, instead unifying mounting with fstab.mako (on the ramdisk). The replacement line would be:

    Code:
    /devices/platform/msm_hsusb_host/usb2 /storage/usbdisk0 auto defaults voldmanaged=usbdisk0:auto

    Update:
    In 4.4, mountpoint is set to auto instead of /storage/usbdisk0, and will be taken care of by vold / fuse daemon.

    But /storage/usbdisk0 does not exist, so it will fail to mount. We will be using /init.mako.rc to create this directory and symlink associated legacy ones. This file resides in a ramdisk (which combines with the kernel to form boot.img), so we need to modify that instead of /init.mako.rc on the device itself (since it wouldn't be able to persist through a reboot). As well, we define the environmental variable SECONDARY_STORAGE. Below the analogous /storage/sdcard0 lines, add:

    Code:
    export SECONDARY_STORAGE /storage/usbdisk0
    
    mkdir /storage/usbdisk0 0666 system system
    
    symlink /storage/usbdisk0 /usbdisk
    symlink /storage/usbdisk0 /mnt/usbdisk

    Update:
    In 4.4, usb disks must be further FUSE mounted. Rather than insert the script into init.mako.rc, it will now reside in init.mako.usbdisk.rc and be imported to init.mako.rc (strictly for ease/neatness and not standard convention):

    Code:
    # USB Storage -ziddey
    
    on init
        mkdir /mnt/media_rw/usbdisk0 0700 media_rw media_rw
        mkdir /storage/usbdisk0 0700 root root
    
        export SECONDARY_STORAGE /storage/usbdisk0
    
        # Support legacy paths
        symlink /storage/usbdisk0 /usbdisk
        symlink /storage/usbdisk0 /mnt/usbdisk
    
    service fuse_usbdisk0 /system/bin/sdcard -u 1023 -g 1023 -d /mnt/media_rw/usbdisk0 /storage/usbdisk0
        class late_start
        disabled

    In order to enable Settings->Storage->USB Storage, res/xml/storage_list.xml in /system/framework/framework-res.apk needs to be modified. We should be able to simply inject an encoded version of our modified storage_list.xml. I'm not sure if it's possible to simply encode a single file, so I decompiled framework-res.apk in order to make the following addition to res/xml/storage_list.xml (inside StorageList):

    Code:
        <storage android:mountPoint="/storage/usbdisk0"
                 android:storageDescription="@string/storage_usb"
                 android:primary="false"
                 android:removable="true" />

    After recompiling, we should now be able to extract our newly encoded storage_list.xml for use with any ROM's framework-res.apk.

    To allow downloading apps from the market that require usb host support, we need to add the following to /system/build.prop:

    Code:
    ro.usb.host=1

    To enable android api support for usb host, we need to create /system/etc/permissions/android.hardware.usb.host.xml with the following:

    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <permissions>
        <feature name="android.hardware.usb.host" />
    </permissions>

    Now to "activate" this file, we add to /system/etc/permissions/handheld_core_hardware.xml:

    Code:
    <feature name="android.hardware.usb.host" />

    Google assigned a different permission group for secondary storage devices (e.g. usb drives), media_rw, for which user apps cannot have write access (Chainfire has a good article on the issue here). We need to modify /system/etc/permissions/platform.xml to allow write access. Add the line in red ("officially" used by Samsung):

    Code:
    <permission name="android.permission.WRITE_EXTERNAL_STORAGE" >
        [color=red]<group gid="media_rw" />[/color]
        <group gid="sdcard_rw" />
    </permission>

    That's it! Externally powered usb host mode should be fully functional.

    For full disclosure, these are the changes to the kernel config vs stock (really just NTFS and modules):

    Code:
            echo "CONFIG_INPUT_JOYSTICK=y" >> .config
            echo "CONFIG_JOYSTICK_XPAD=m" >> .config
            echo "CONFIG_JOYSTICK_XPAD_FF=y" >> .config
            echo "CONFIG_JOYSTICK_XPAD_LEDS=y" >> .config
            echo "CONFIG_INPUT_FF_MEMLESS=m" >> .config
            echo "CONFIG_HID_LOGITECH=m" >> .config
            echo "CONFIG_LOGITECH_FF=y" >> .config
            echo "CONFIG_LOGIRUMBLEPAD2_FF=y" >> .config
            echo "CONFIG_LOGIG940_FF=y" >> .config
            echo "CONFIG_LOGIWHEELS_FF=y" >> .config
            echo "CONFIG_HID_DRAGONRISE=m" >> .config
            echo "CONFIG_DRAGONRISE_FF=y" >> .config
            echo "CONFIG_CIFS=m" >> .config
    
            echo "CONFIG_NTFS_FS=y" >> .config
    #        echo "CONFIG_USB_DEBUG=y" >> .config
            sed 's/\(CONFIG_USB_STORAGE_DEBUG\)=y/# \1 is not set/' -i .config


    Changelog:
    • 4.4: 2013.12.01 0349ET: [fk r196] [fk r196-CM] [aosp r5] aosp includes gamepad kernel modules.
    • 4.4: 2013.11.29 0219ET: [fk r195] [fk r195-CM] CM build attempts to patch Franco ramdisk mods on the fly, so be prepared if things go south.
    • 4.4: 2013.11.21 1922ET: [fk r194] [aosp r2] Update to 4.4 configuration for mounting usbdisk.
    • 4.3: 2013.10.22 2201ET r191: [JWR] [JSS/JLS] Allow potentially faster charging in host mode, re-add manual host mode
    • 4.3: 2013.10.22 2204ET r191-CM: [JWR] [JSS/JLS] ^ + 2 "CAF" commits for CM compatibility
    • 4.3: 2013.10.09 2148ET r190: [JWR] [JSS/JLS] Re-enable USB debug messages
    • 4.3: 2013.10.01 1954ET r188: [JWR] [JSS/JLS] Zipalign framework-res.apk
    • ziddey-otg-r183-09141713.zip ziddey-otg-r183-JSS-09141713.zip Add SECONDARY_STORAGE env., do ramdisk patching during flash, include CIFS module -- rebase to r183.
    • ziddey-otg-r182-09041823.zip ziddey-otg-r182-JSS-09041823.zip Remove module unloading support, patch handheld_core_hardware.xml -- rebase to Franco r182.
    • ziddey-otg-r178-08240234.zip ziddey-otg-r178-JSS-08240238.zipDisable modversions, enable kernel wakelock stats-- rebase to Franco r178.
    • JSS15J 4.3.0 2013.08.13 1533ET: ziddey-otg-r174-08131533.zip First release for JSS15J. Updated to 4.3's new unified fstab (native mounting support). Using an "anyramdisk" method for compatibility with different ROMs (specifically, different su implementations). Based off Franco r174.
    • 2013.07.29 1101ET: ziddey-otg-r165-07291101.zip Maintenance build-- rebase to Franco r165.
    • 2013.07.14 2015ET: ziddey-otg-r163-07142015.zip Allow automatic host mode without charging-- rebase to Franco r163.
    • 2013.07.08 1420ET: ziddey-otg-r162-07081420.zip Update storage_list.xml for compatibility with new CM nightlies-- rebase to Franco r162.
    • 2013.06.28 1551ET: ziddey-otg-M3-06281551.zip Maintenance build-- rebase to Franco M3.
    • 2013.06.27 0427ET: ziddey-otg-r156-06270427.zip Re-enable read-only NTFS support in kernel.
      • 2013.06.06 1736ET: ziddey-otg-r151-06061736.zip Releases will now include modules ff-memless.ko, hid-dr.ko, hid-logitech.ko, and xpad.ko (/system/lib/modules). Manually insmod as needed or create an appropriate init.d script to load on boot. Rebase to Franco r151.
      • 2013.05.25 0749ET: ziddey-otg-05250749.zip Fix compatibility issue with CWM (MTP crashes).
      • 2013.05.23 2119ET: ziddey-otg-05232119.zip Start charging immediately when entering host mode. This resolves issues with proprietary chargers.
      • 2013.05.22 2305ET: ziddey-otg-05222305.zip Rebase to Franco's r140. Revert checks for actual proprietary chargers in favor of manually disabling automatic host mode (temporary). Issue "# echo disable > /sys/kernel/debug/msm_otg/aca" to disable automatic host mode (enable to re-enable).
      • 2013.05.17 0107ET: ziddey-otg-05170107.zip Added check for other proprietary charger case. Rebase to Franco's r137.
      • 2013.05.15 0124ET: ziddey-otg-05150124.zip Attempt to detect actual proprietary chargers (Apple-compatible) and charge properly. Rebase to Franco's r136.
      • 2013.05.09 1729ET: ziddey-otg-05091729.zip Should now patch precompiled storage_list.xml to address incorrect strings (Internal Storage/USB Storage). Re-enabled verbose usb debugging messages (dmesg).
      • 2013.05.06 1846ET: ziddey-otg-05061846.zip Maintenance build. Based off Franco's current nightlies branch (r134?). Updated storage_list.xml to match current CM nightlites. Removed freshen flag to hopefully address issues with framework-res.apk not being patched (thanks sga999). Verbose usb debugging messages not enabled (unaltered r134 config)
      • 2013.04.07 0355ET: ziddey-otg-04070355.zip Now modifies /system/etc/permissions/platform.xml to allow app write access to usb storage (thanks garyd9 for script code). Kernel build number reverted to 105 to match Franco's M1 build number.
      • 2013.03.27.2338ET: ziddey-otg-03272334.zip Allow host mode when slimport connected (must manually enable for now. not sure if it actually works, so please report results.) Prevent forced host mode from entering suspended state so it won't get stuck (perhaps worth reinvestigating if we ever get internal power working). Allow forcing mode via /sys/kernel/debug/msm_otg/mode regardless of current state (original code had conditions that were unreasonable. it is designed to be used for debugging after all..). Forgot to reset the build number; should be 105. Would only potentially matter if using Franco's app.
      • 2013.03.23 2000ET: ziddey-otg-03231951.zip All-in-one update now enables android api for usb host mode. Should automatically rescan media library when usb storage is connected. Kernel updated to Franco M1 (milestone), and will probably stay here for a while.
      • 2013.03.17 1548ET: otg-aio-20130317.zip All-in-one flashable zip that includes modified kernel/ramdisk, vold.fstab, and precompiled storage_list.xml for framework-res.apk (thanks arpruss for precompiled zip-for-android). Kernel unchanged from last release (Franco r102 base), but removed unrelated line previously added to default.prop in ramdisk
      • 2013.03.14 1648ET: otg-franco-boot-03141621.img Should have fixed all issues involving unpopulated hubs, unplugged devices, host mode timeout, and charging. Changed main mount point to /storage/usbdisk0 since that seems to be the new standard (manually update vold.fstab accordingly). Based on Franco's git as of 3/12 (after r102)
      • 2013.03.11 2244ET: otg_boot_r3.img Interim build to address wall charging issues (do not attach/detach devices while otg cable connected to phone)
      • 2013.03.09 0739ET: otg_boot_r2.img Should charge (faster) in host mode
      • 2013.03.08 1128ET: otg_franco.zip Initial release in this thread.
      • 2013.03.07 1350ET: franco-otg-201303071328.img "Pre-alpha" build posted in CaptainMuon's thread. Forces disabling of host mode on device unplug.
      • 2013.03.07 1102ET: franco-otg-201303071032.img "Pre-alpha" build posted in CaptainMuon's thread. Forces host mode on detection of "proprietary" type charger (vs usb = sdp, wall = dcp).
    References:

    22
    4.4.x: 2013.12.30 0348ET: [fk r200] [fk r200-CM]
    17
    4.4.1: 2013.12.11 1604ET: [fk r199] [fk r199-cm]
    15
    MAKE SURE TO DOWNLOAD THE RIGHT VERSION FOR YOUR ROM.

    JSS15J 4.3.0 2013.08.14 2031ET: ziddey-otg-r176-JSS-08142031.zip Use Franco's ramdisk (plus necessary mods) instead of "anyramdisk" method-- rebase to Franco r176.
    JWR66V 4.3.0 2013.08.14 2035ET: ziddey-otg-r176-08142035.zip First release for JWR66V-- based on Franco r176.
    JDQ39E 4.2.2 2013.07.29 1101ET: ziddey-otg-r165-07291101.zip Maintenance build-- rebase to Franco r165.


    Ramdisks are prebuilt now and not dynamically patched during flash (only the last JSS15J version had this patching). The issue is/was with various implementations of root access. If you are having issues, you may need to flash a different supersu/superuser/etc. Refer to your ROM's thread for details.

    Also worth noting that modules support is enabled in the 4.3 kernels.