A program to unplug/eject removable drives

Status
Not open for further replies.

DaisyMan

Ars Tribunus Militum
2,135
So, I recently got a new toy: a nifty 32 MB PenDrive (www.pendrive.com), which I'm using to carry my work files about to and from home/laptop/work/etc. It's a great system, and saves me a lot of hassle. The only issue I have is that I can't stand the current means available for safely ejecting the device, which uses that silly Unplug/Eject hardware wizard - too many mouse clicks, too troublesome when I have to run. So I'm looking for a way to automate it, preferably without screenscraping.

So far I've stumbled onto this li'l article all about Ejecting Removable Media in Windows NT-2000-XP (note that this discovery was, naturally, subsequent to numerous hours plugging away at DeviceIoControl unsuccessfully in Delphi). A quick recompile later, and despite the VC++'s program's assurances to the contrary (voiced in the forms of "Media in Drive E has been ejected safely."
and "Media in Drive E can be safely removed."), it was clear that while the program could succeed in unmounting the device (gee, thanks, like mountvol.exe couldn't do that already :rolleyes:), it was incapable of stopping it to the satisfaction of Win2K's Unplug/Eject icon, which was quite convinced I was committing a grave violation of the hapless device each time it was so unceremoniously removed.

I would love to simply brush off the warnings, if someone could assure me that it was indeed harmless overreacting on Windows' part, but the cautious left-brain side is in a tizzy. Have you ever seen a brain in a tizzy? Not pretty.

So, if anyone can suggest some good linkage (or even better, Delphi code fragments :)) on how to handle truly unloading the device, I will be eternally grateful, or at least until I forget about this. Thanks muchly.

Since so few posts in this forum seem to have images I thought I would liven it up with a nice pic of the toy as well:
pendrive.jpg
 
There are two types of ejects, ejects of media and ejects of physical devices. These are *not* the same.

Media ejects are what you get when you right-click in My Computer and hit eject. Device ejects use that hotplug applet thingy.

Win2K does OS-level write caching on all non-floppy storage devices. Because of this, the OS always complains if the device is removed improperly, even if the volume was dismounted (if the media isn't removable, the device's internal cache might not be flushed!)

The API that properly prepares a device for physical ejection is CM_Request_Device_Eject. I think it's documented in the DDK, not the SDK.

On XP, write caching is automatically disabled for USB, 1394, and PCMCIA devices (controllable by device manager property pages). As such, this isn't a problem (unless it's using proprietary drivers). Hence MS removed the popups.
 
Hence MS removed the popups.
No they haven't.

If a device's driver does not say "I support surprise removals" then Windows XP will still give you a warning.

The IRP that readies a device for physical removal (which is what this thing needs) is called IRP_MN_REMOVE_DEVICE. This is what Windows sends to the device when you disable it in the little applet -- it tells the driver to free resources. The plug and play manager sends this IRP to each child of the device, starting at the bottom, sends a remove request to any filesystem drivers, and only then does it send IRP_MN_REMOVE_DEVICE to the device.

This is distinct from dismounting, and also from stopping. It is the thing that needs doing to hot-swap devices that you want to unplug.

CM_Request_Device_Eject, which is a Configuration Manager call (which controls PnP), may send this IRP, though its name suggests otherwise. All the IRP stuff calls these events removals, all the CM stuff calls them ejects. I think the IRP terminology is rather better.
 
No they haven't.

Yes they have. There are no surprise removal popups in XP anymore. You might get a bubble for a lazy-write delay, but that's about it.

The IRP that readies a device for physical removal (which is what this thing needs) is called IRP_MN_REMOVE_DEVICE. This is what Windows sends to the device when you disable it in the little applet -- it tells the driver to free resources. The plug and play manager sends this IRP to each child of the device, starting at the bottom, sends a remove request to any filesystem drivers, and only then does it send IRP_MN_REMOVE_DEVICE to the device.

Actually, it works like this.
When the OS first encounters a device, it sends IRP_MN_QUERY_CAPABILITIES.
For this discussion, there are three interesting fields:
->Removable - The device is physically detachable from it's bus
->EjectSupported - The device requires an additional command to prepare for removal
->SurpriseRemovalOK - The device can safely be removed without warning


A device is shown in the hotplug applet on Win2K and XP if ((Removable || EjectSupported) && !SurpriseRemovalOK)

On Win2K, a popup will be generated if the device is yanked in a Started state and doesn't have the SurpriseRemovalOK bit set. (Now you know why some USB printers kick up the dialog - bad drivers)


USB devices, 1394 devices, PCMCIA devices, etc have the Removable bit set to TRUE and the EjectSupported bit set to FALSE.

Things like hotswap IDE drives have EjectSupported set to TRUE. This is because, for them, shutting down the stack isn't enough - some amount of power is still flowing to the device, specifically enumeration power. And for these devices, this power must be cut before the device can be safely removed (unlike say USB).


The Eject sequence is thus this:

// Notify apps, services, drivers
Send IRP_MN_QUERY_REMOVE_DEVICE from the bottom up of the device tree
Send IRP_MN_REMOVE_DEVICE from the bottom up of the device tree

if (EjectSupported)
Send IRP_MN_EJECT_DEVICE to the target of the eject.

If the device supports Eject, the OS expects it will be gone (non-enumerable) after the IRP is sent. If the device is still present, the OS restarts it.

If the device *doesn't* support Eject, the OS gives the device a problem (CM_PROB_HELD_FOR_EJECT on XP), and just waits for it to disappear.
 

DaisyMan

Ars Tribunus Militum
2,135
Nifty. I looked up IRP_MN_REMOVE_DEVICE on MSDN, and under the "Sending This IRP" section it says "Reserved for system use. Drivers must not send this IRP." I take that to mean I can't really call this from user-mode, can I? All the API calls which seem to invoke the various IRP messages to be kernel-level stuff, Ioxxx, etc. Isn't that a problem, unless I'm writing a driver or the like?

[This message was edited by DaisyMan on March 10, 2002 at 06:00.]
 

DaisyMan

Ars Tribunus Militum
2,135
Ah, I see, I need to invoke the IRP with CM_Request_Device_Eject. Does anyone know where I can check out the device identification string for a given device, so that I can pass it to CM_Locate_DevNode and obtain the device instance ID necessary for a call to said CM_Request_Device_Eject? I assume that this device should start with \USB, but I'm lost after that.

Thanks for all the fascinating info thus far, by the way. :)
 
Yes they have. There are no surprise removal popups in XP anymore. You might get a bubble for a lazy-write delay, but that's about it.
During my brief stints of using XP, removing my USB ADSL modem (which doesn't set the surprise removal bit), would make it complain at me if I surprise removed it. In spite of it being USB, and in spite of it not having a filesystem (or anything like that), it didn't like surprise removal.

I would imagine that note at the bottom of Q298504 should still be true, as it's a hardware flaw, too.
 

DaisyMan

Ars Tribunus Militum
2,135
Bit of an update:

I decided to try writing this in C#, and it actually started off quite nicely. I used DllImport on the CfgMgr32.dll successfully, working off of the CfgMgr32.h file from the DDK, and managed to call enough of the various support functions successfully that I finally got to the stage of calling CM_Request_Device_Eject with the appropriate DevNode.

Then tragedy struck; CM_Request_Device_Eject could not be located in said DLL. In vain, I altered the function to CM_Request_Device_Eject_Ex. I also tried setting the EntryPoint to variations using "A" and "W" at the end of both, to cover my ANSI/Unicode bases, but also to no avail. Finally, I popped open the offending DLL in question and discovered it doesn't have any such function. This was quite surprising, since I had been rather under the impression from the header file and MSDN that CfgMgr32.DLL would be the home of CM_Request_Device_Eject, et al.

Any ideas?

Edit: Hmm. Just did a search in $SYSTEM32 and it seems that SetupAPI.DLL has most of the same entry points as CfgMgf32, plus the CM_Request_Device_EjectXXX ones I was looking for. Let's see what that does...

Further Edit: Fatal execution engine error. This sucks.

[This message was edited by DaisyMan on March 12, 2002 at 05:24.]
 

DaisyMan

Ars Tribunus Militum
2,135
Seemed to have missed the edit time.

Well, finally muddled through that last bit. Now its making the call to CM_Request_Device_EjectW, just not successfully. Specifically it's giving me the error code of CR_REMOVE_VETOED (0x00000017). Checking the veto info also returned by the call, that's specifically PNP_VetoIllegalDeviceRequest, plus the correct path to the USB device it had returned earlier.

So it looks like the node being passed in is the correct one, but something in the system is vetoing my request. Which is odd, since two seconds later I can use the tray icon to eject it just fine. I'm posting the code in hopes that helps. It's very beta, so please don't rake me over the coals ...

code:<HR>
Code:
// created on 3/12/2002 at 3:16 AM
using System;
using System.Text;
using System.Runtime.InteropServices;

public class CfgMgr {
	
	//some boring constants from the .h
	
	public const int CM_GETIDLIST_FILTER_NONE 			   =   (0x00000000);
	public const int CM_GETIDLIST_FILTER_ENUMERATOR        =   (0x00000001);
	public const int CM_GETIDLIST_FILTER_SERVICE           =   (0x00000002);
	
	public const int  CM_LOCATE_DEVNODE_NORMAL       = 0x00000000;
	public const int  CM_LOCATE_DEVNODE_PHANTOM      = 0x00000001;
	public const int  CM_LOCATE_DEVNODE_CANCELREMOVE = 0x00000002;
	public const int  CM_LOCATE_DEVNODE_NOVALIDATION = 0x00000004;
	public const int  CM_LOCATE_DEVNODE_BITS         = 0x00000007;

	public const int MAX_PATH = 256;
	
	//boring enum too!
	
	public enum PNP_VETO_TYPE {
    PNP_VetoTypeUnknown,            // Name is unspecified
    PNP_VetoLegacyDevice,           // Name is an Instance Path
    PNP_VetoPendingClose,           // Name is an Instance Path
    PNP_VetoWindowsApp,             // Name is a Module
    PNP_VetoWindowsService,         // Name is a Service
    PNP_VetoOutstandingOpen,        // Name is an Instance Path
    PNP_VetoDevice,                 // Name is an Instance Path
    PNP_VetoDriver,                 // Name is a Driver Service Name
    PNP_VetoIllegalDeviceRequest,   // Name is an Instance Path
    PNP_VetoInsufficientPower,      // Name is unspecified
    PNP_VetoNonDisableable,         // Name is an Instance Path
    PNP_VetoLegacyDriver,           // Name is a Service
    PNP_VetoInsufficientRights      // Name is unspecified
	}  
	
	//look, boring API calls! Actually, these weren't so boring
	
	[ DllImport( "SetupAPI.dll", EntryPoint="CM_Get_Device_ID_List_Size", CharSet=CharSet.Auto )]
	public static extern int IDListSize([In, Out] ref int pulLen, string pszFilter, int ulFlags);
	
	[ DllImport( "SetupAPI.dll", EntryPoint="CM_Get_Device_ID_List", CharSet=CharSet.Auto )]
	public static extern int IDList(string pszFilter, StringBuilder retBuffer, int BufferLength, int ulFlags);
	
	[ DllImport( "SetupAPI.dll", EntryPoint="CM_Locate_DevNode", CharSet=CharSet.Auto )]
	public static extern int DevNode([In, Out] ref int pdnDevInst, StringBuilder pDeviceID, int ulFlags);

	[ DllImport( "SetupAPI.dll", EntryPoint="CM_Request_Device_EjectW", CharSet=CharSet.Auto )]
	public static extern int DevEject(
    	int dnDevInst,
    	[In, Out] ref PNP_VETO_TYPE pVetoType,
    	StringBuilder pszVetoName,
    	int ulNameLength,
    	int ulFlags
    	);
}

public class EjectDisk
	{
	
	
	//make sure I'm running the right file
	public static double version = 1.2;	
	
	//for general error checking
	static void RetCheck(int ReturnCode){
			if (0 != ReturnCode) {
				System.Console.WriteLine("Error: " + ReturnCode.ToString());				
				Environment.Exit(ReturnCode);	
			};
		}
	
	public static void Main() {

		System.Console.WriteLine("Disk Eject Program, version " + version.ToString());
		int Ret;
	
		//find out how long the ID buffer must be
		int Len = 0;		
		Ret = CfgMgr.IDListSize(ref Len, "USB", CfgMgr.CM_GETIDLIST_FILTER_ENUMERATOR);
		RetCheck(Ret);
		System.Console.WriteLine("ID List Size: " + Len.ToString());

		//fill the ID buffer (idBuf)
		StringBuilder idBuf = new StringBuilder(Len);
		Ret = CfgMgr.IDList("USB", idBuf, Len, CfgMgr.CM_GETIDLIST_FILTER_ENUMERATOR);
		RetCheck(Ret);
		/*
		 * just wanted to check that nothing else was being returned and trimmed
		 * after the first 0x00 - my system only returned one USB device here,
		 * which is why I don't bother with fancier processing to isolate the 
		 * correct USB device
		 */
		string work = idBuf.ToString();
		System.Console.WriteLine("-- " + work.Replace(0x00.ToString(), " --"));
		
		//get the Node from the ID in idBuf
		int Node = 0;			
		Ret = CfgMgr.DevNode(ref Node, idBuf, CfgMgr.CM_LOCATE_DEVNODE_NORMAL);		
		RetCheck(Ret);
		System.Console.WriteLine("DevNode value: " + Node.ToString());
		
		//Finally, do the eject
		Len = CfgMgr.MAX_PATH;
		StringBuilder vetoBuf = new StringBuilder(Len);		
		CfgMgr.PNP_VETO_TYPE Veto = CfgMgr.PNP_VETO_TYPE.PNP_VetoTypeUnknown;		
		Ret = CfgMgr.DevEject(Node, ref Veto, vetoBuf, Len, 0);
		if (23 == Ret) { 
			//23 means this is a Veto problem, so show that info
			System.Console.WriteLine("It's Danny da Vito! (ouch)");
			System.Console.WriteLine("Veto type: " + CfgMgr.PNP_VETO_TYPE.GetName(Veto.GetType(), Veto));	
			System.Console.WriteLine("Veto text: " + vetoBuf);	
		}
		RetCheck(Ret);
		System.Console.WriteLine("Device unloaded succesfully!");
			
	}
	
	}

Gah, that didn't format well.
 

DaisyMan

Ars Tribunus Militum
2,135
:mad: STUPID .NET! :mad:

Why didn't I just do this in Delphi, like I knew I should have?

Anyway, turns out the source of all my problems (well, my most recent ones, anyway) lay in the fact that the String and StringBuilder classes were trying to be "helpful" by trimming everything after the first null character. For most external API functions where I'm passing in a character buffer intending it to be filled, that makes sense. But not every function uses null-termination, and I would have thought these guys knew that when the docs recommend StringBuilder for such instances. Case in point was CM_Get_Device_ID_List.

To make matters worse, StringBuilder doesn't even have a property I could find to tell it to ignore the nulls, and so I was forced to resort to the use of a char[] array, which was kludgy but at least it worked in the end.

Bah and humbug. I can post the source if anyone cares to see it.
 

DaisyMan

Ars Tribunus Militum
2,135
You can download it from http://daisyman.arsware.org/EjectDisk.exe

Oddly enough, whereas when I try to open normal Win32 exe's on the web from IE, I get a prompt to download them, when I attempt to just click and download this file it tries to *run*, right then and there. A side effect of the .NET security, giving IE the confidence to run straight-away? Who knows, but it's annoying when I want to save to disk. Right-click to Save Target As.. in IE.
 
Peter: I'd set the content-disp, but it isn't exactly my server, and it's not running IIS. I suppose I should e-mail someone or another. It's fascinating that IE could distinguish between standard and .NET Win32 exe's though. Wow.
Oh, it's not very hard to do; you read the PE header and look to see if it has a particular entry in the section directory. It's not all that surprising that it should do it, because it has to do it for downloaded controls and things.
 
Status
Not open for further replies.