3 #USB Mass Storage Emulator
5 #with thanks to Brandon Wilson and his Linky project.
12 from GoodFETMAXUSB import *;
15 """Returns a list of zeroes of the specified length."""
21 class GoodFETMAXUSBMass(GoodFETMAXUSBDevice):
22 """This emulates a USB Mass Storage device."""
24 #Too much data to watch everything.
27 def getSectorData(self,lba):
28 """Overload this to return data from a given 512-byte sector."""
29 print "You forgot to overload getSectorData(). Returning something neighborly.";
31 0xE9, 0x86, 0x00, 0x0A, 0x47, 0x6F, 0x6F, 0x64, 0x44, 0x69, 0x73, 0x6B, 0x20, 0x30, 0x2E, 0x30,
32 0x31, 0x0A, 0x0D, 0x62, 0x79, 0x20, 0x54, 0x72, 0x61, 0x76, 0x69, 0x73, 0x20, 0x47, 0x6F, 0x6F,
33 0x64, 0x73, 0x70, 0x65, 0x65, 0x64, 0x0A, 0x0A, 0x0D, 0x00, 0x59, 0x6F, 0x75, 0x20, 0x68, 0x61,
34 0x76, 0x65, 0x20, 0x62, 0x65, 0x65, 0x6E, 0x20, 0x65, 0x61, 0x74, 0x65, 0x6E, 0x20, 0x62, 0x79,
35 0x20, 0x61, 0x20, 0x67, 0x72, 0x75, 0x65, 0x2E, 0x20, 0x20, 0x53, 0x6F, 0x72, 0x72, 0x79, 0x2E,
36 0x0A, 0x0D, 0x00, 0x31, 0x29, 0x20, 0x52, 0x65, 0x61, 0x64, 0x69, 0x6E, 0x67, 0x20, 0x6B, 0x65,
37 0x72, 0x6E, 0x65, 0x6C, 0x20, 0x66, 0x72, 0x6F, 0x6D, 0x20, 0x64, 0x69, 0x73, 0x6B, 0x2E, 0x0A,
38 0x0D, 0x00, 0x32, 0x29, 0x20, 0x45, 0x78, 0x65, 0x63, 0x75, 0x74, 0x69, 0x6E, 0x67, 0x20, 0x6B,
39 0x65, 0x72, 0x6E, 0x65, 0x6C, 0x2E, 0x0A, 0x0D, 0x00, 0xBE, 0x03, 0x7C, 0xE8, 0x41, 0x00, 0xE8,
40 0x7B, 0x00, 0x31, 0xC0, 0x30, 0x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xF9, 0x00, 0x02, 0x75, 0xF0,
52 0xC3, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45,
53 0x46, 0x50, 0x56, 0x83, 0xE0, 0x0F, 0x05, 0x51, 0x7D, 0x89, 0xC6, 0xAC, 0xB4, 0x0E, 0xCD, 0x10,
54 0x5E, 0x58, 0xC3, 0xB8, 0x20, 0x0E, 0xCD, 0x10, 0xC3, 0x31, 0xC0, 0xCD, 0x12, 0x72, 0x05, 0x85,
55 0xC0, 0x74, 0x01, 0xC3, 0xBE, 0x2A, 0x7C, 0xE8, 0x46, 0xFF, 0xEB, 0xFE, 0xEA, 0x00, 0x00, 0xFF,
56 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
57 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
58 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
59 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
60 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
61 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
62 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xAA
65 def putSectorData(self,lba,block):
66 """Overload this to write data to a given 512-byte sector."""
67 print "You forgot to overload putSectorData(). Ignoring sector write.";
70 def getSectorCount(self):
71 """Returns the number of viable Logical Block Addresses."""
72 print "You forgot to overload getSectorCount(). Guessing 0x200.";
76 """Initialize a USB Mass Storage device."""
77 self.usb_disconnect();
83 """Main loop of the USB Mass Storage emulator."""
84 print "Starting a Mass Storage device.";
89 """Handle USB Enumeration"""
91 #Grab the SETUP packet from the buffer.
92 SUD=self.readbytes(rSUDFIFO,8);
94 #Parse the SETUP packet
95 print "Handling a setup packet of %s" % self.setup2str(SUD);
96 setuptype=(ord(SUD[bmRequestType])&0x60);
98 self.std_request(SUD);
100 self.class_request(SUD);
101 elif setuptype==0x40:
102 self.vendor_request(SUD);
104 print "Unknown bmRequestType=0x%02x." % ord(SUD[bmRequestType])
106 def class_request(self,SUD):
107 """Handle a class request."""
108 requesttype=ord(SUD[bmRequestType]);
109 request=ord(SUD[bRequest]);
110 if requesttype==0xA1 and request==0xFE:
111 print "Reporting 0 as the maximum LUN.";
112 #This is a Get Max LUN request.
113 #Return 1-byte maximum Logical Unit Number
114 self.wreg(rEP0FIFO,0x00); # Just one LUN.
115 self.wregAS(rEP0BC,1); # ARM and fire!
116 return; #Don't stall.
117 if requesttype==0x21 and request==0xff:
118 print "Received BBB reset."
119 self.wregAS(rEP0BC,0); # ARM and fire!
120 return; #Don't stall.
121 print "Stalling an unknown class request: %s" % self.setup2str(SUD);
123 def vendor_request(self,SUD):
124 """Handle a vendor request."""
125 request=ord(SUD[bRequest]);
126 print "Why the hell is there a vendor request?";
127 #self.wreg(rEP0FIFO,0);
128 self.wregAS(rEP0BC,0);
129 def std_request(self,SUD):
130 """Handles a standard setup request."""
131 setuptype=ord(SUD[bRequest]);
132 if setuptype==SR_GET_DESCRIPTOR: self.send_descriptor(SUD);
133 #elif setuptype==SR_SET_FEATURE: self.feature(1);
134 elif setuptype==SR_SET_CONFIGURATION: self.set_configuration(SUD);
135 elif setuptype==SR_GET_STATUS: self.get_status(SUD);
136 elif setuptype==SR_SET_ADDRESS: self.rregAS(rFNADDR);
137 elif setuptype==SR_GET_INTERFACE: self.get_interface(SUD);
139 #print "Stalling Unknown standard setup request type %02x" % setuptype;
140 #self.STALL_EP0(SUD);
141 print "Accepting unknown standard setup request type %02x" % setuptype;
142 self.wregAS(rEP0BC,0);
144 def get_interface(self,SUD):
145 """Handles a setup request for SR_GET_INTERFACE."""
146 if ord(SUD[wIndexL]==0):
147 self.wreg(rEP0FIFO,0);
148 self.wregAS(rEP0BC,1);
158 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x40,
160 0x50, 0x51, #SDCZ2 Cruzer Mini Flash Drive (thin)
162 0x01, 0x02, 0x03, #Strings
167 #Configuration Descriptor
173 0x00, 0x01, 0x01, 0x00, 0xE0, 0x00, 0x09, 0x04, 0x00, 0x00,
175 0x08, #Mass Storage Bulk Only
180 0x07, 0x05, 0x01, 0x02, 0x40, 0x00, 0x00,
182 0x07, 0x05, 0x83, 0x02, 0x40, 0x00, 0x00,
186 # STRING descriptor 0--Language string
190 # 0x03, # bDescriptorType = string
191 # 0x09,0x04 # wLANGID(L/H) = English-United Sates
193 # STRING descriptor 1--Manufacturer ID
194 "\x10\x03G\x00o\x00o\x00d\x00F\x00E\x00T\x00",
195 # STRING descriptor 2 - Product ID
196 "\x1C\x03M\x00A\x00S\x00S\x00 \x00E\x00m\x00u\x00l\x00a\x00t\x00o\x00r\x00",
197 # STRING descriptor 3 - Serial Number ID
198 "\x14\x03S\x00/\x00N\x00 \x003\x004\x002\x000\x00E\x00"
201 def get_status(self,SUD):
202 """Get the USB Setup Status."""
203 testbyte=ord(SUD[bmRequestType])
207 self.wreg(rEP0FIFO,0x03); #Enable RWU and self-powered
208 self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
209 self.wregAS(rEP0BC,2); #Load byte count, arm transfer, and ack CTL.
212 self.wreg(rEP0FIFO,0x00);
213 self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
214 self.wregAS(rEP0BC,2);
217 if(ord(SUD[wIndexL])==0x83):
218 print "This code almost certainly doesn't work.";
219 self.wreg(rEP0FIFO,0x01); #Stall EP3
220 self.wreg(rEP0FIFO,0x00); #Second byte is always zero.
221 self.wregAS(rEP0BC,2);
223 print "Stalling unknown status.";
226 print "Stalling unknown status.";
230 """Handle IN3 input event."""
231 # Do nothing here, as it'll be taken care of elsewhere. The
232 # interrupt just means that the buffer is empty, not that we
233 # are expected to fill it.
236 """Handle an OUT1 output event."""
237 l=self.rreg(rEP1OUTBC);
238 frame=self.readbytes(rEP1OUTFIFO,l);
239 self.handleCBW(frame);
242 def handleCBW(self,cbw):
243 """Handles an incoming Command Block Wrapper. See USB Mass
244 Storage Class for details."""
247 print "Invalid CBW length of %i bytes. Aborting." % len(cbw);
251 print "Invalid CBW signature: %s. Should be USBC; aborting." % sig;
255 dtlen=ord(cbw[8])+(ord(cbw[9])<<8)+(ord(cbw[10])<<16)+(ord(cbw[11])<<24);
257 dtdir=flags&0x80; # 0x80 for dev->host, 0x00 for host->dev
258 lun=ord(cbw[13])&0x0F; # Should be zero, as we only reported one LUN.
259 cblen=ord(cbw[14])&0x1F;
261 self.handleCB(cb,cblen,dtlen,dtdir);
263 def handleCB(self,cb,cblen,dtlen,dtdir):
264 """Handles a command block, then replies with a CSW."""
266 print "Got command block, type 0x%02x requesting 0x%02x bytes" % (
269 status=00; #good, set to 1 for bad.
270 if verb==0x00: # Test Unit Ready
271 # Send nothing, just the success code.
273 elif verb==0x03: # Request Sense
274 print "Responding to Request Sense. Needed for Macs.";
275 response=[0x70, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0A,
276 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00,
280 self.writebytes(rEP3INFIFO,
282 self.wreg(rEP3INBC,len(response));
283 elif verb==0x12: #Inquiry
284 #print "Responding to CB inquiry.";
286 0x00, # 00 for Direct, 1F for "no floppy"
287 0x80, # make 0x80 for removable media, 0x00 for fixed
289 0x01, # Response Data Format
290 0x1f, #Additional length.
293 ord('G'),ord('o'),ord('o'),ord('d'),ord('F'),ord('E'),ord('T'),0x20,
295 ord('G'),ord('o'),ord('o'),ord('d'),ord('F'),ord('E'),ord('T'),0x20,
296 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
297 ord('0'),ord('.'),ord('0'),ord('1')]
298 #print "Sending %i byte reply to %i byte query." % (
299 # len(response),dtlen);
300 while len(response)<dtlen:
301 response=response+[0];
302 #while not(self.rreg(rEPIRQ)&bmIN3BAVIRQ):
303 # #Wait for the packet to complete before sending the next.
304 # print "Waiting to complete inquiry."
306 self.writebytes(rEP3INFIFO,
308 self.wregAS(rEP3INBC,
311 #self.wreg(rEPIRQ,bmIN3BAVIRQ); #Clear the bit
312 #while not(self.rreg(rEPIRQ)&bmIN3BAVIRQ):
313 # #Wait for the packet to complete before sending the next.
314 # print "Waiting to complete inquiry."
316 elif verb==0x1e: #Prevent/Allow Removal
317 # Give a good status to pretend we understand.
319 elif verb==0x1A: #Mode Sense (6)
320 # I should probably send six bytes here.
321 print "Mode Sense (6) requesting %i byte Page Code %02x" % (
322 dtlen,ord(cb[2])&0x3F);
323 #This is completely wrong.
324 response=[0x12,0,0,0, 0,0,0,0x1C];
325 self.fifo_ep3in_tx(response);
326 elif verb==0x5A: #Mode Sense (10)
327 # I should probably send ten bytes here.
328 print "Mode Sense (10) requesting %i byte Page Code %02x" % (
329 dtlen,ord(cb[2])&0x3F);
330 #This is completely wrong.
331 response=[0x12,0x00,0,0, 0,0,0,0x1C]
332 self.fifo_ep3in_tx(response);
333 elif verb==0x23: #Read Format Capacity
335 0x00, 0,0x00,0x08, #Capacity list length.
336 0,0x00,0x10,0x00, # Number of sectors, implying 10MB.
337 0x01,0x00, #reserved/desciptor code.
338 0x02,0x00 # 512 bytes/sector. Why is this twice?
340 self.writebytes(rEP3INFIFO,
342 self.wregAS(rEP3INBC,
344 elif verb==0x25: #Read Capacity
345 lastlba=self.getSectorCount();
347 #0x00, 0, 0x0f, 0xFF, # Last LBA
348 (lastlba>>24)&0xFF, (lastlba>>16)&0xFF, (lastlba>>8)&0xFF, lastlba&0xFF, # Last LBA
349 0x00,0x00,0x02,0x00 # Block length of 512 bytes.
351 self.writebytes(rEP3INFIFO,
353 self.wregAS(rEP3INBC,
355 elif verb==0x28: #READ SECTOR
364 print "Fetching %i blocks starting at LBA %i." % (count,baselba);
367 status=1; #Fail if we're asked to read more than 32 blocks.
368 #Now we need to stall EP3. It's not acceptable to just forget to transmit.
369 self.wreg(rEPSTALLS,0x10);
370 for i in range(0,count):
371 data=self.getSectorData(baselba+i);
373 #print "Sending block fragment %i,%i" % (i,j);
374 #Transmit each 64-byte block fragment, then wait for next.
375 while not(self.rreg(rEPIRQ)&bmIN3BAVIRQ): pass;
376 response=data[j*64:j*64+64];
377 self.writebytes(rEP3INFIFO,
379 self.wregAS(rEP3INBC,
382 elif verb==0x2A: #WRITE SECTOR
383 print "Haven't implemented WRITE SECTOR.";
385 elif verb==0x1B: #EJECT/RETRACT DISK
386 print "Haven't implemented SCSI Start Stop Unit Command (1B)";
387 print "https://en.wikipedia.org/wiki/SCSI_Start_Stop_Unit_Command";
390 print "ERROR: Unknown SCSI command block verb %02x." % verb;
391 status=1; #Command Failed
393 print "Sending %i bytes of dummy data here." % dtlen;
394 self.fifo_ep3in_tx(zeros(dtlen));
398 #Now we need to send the CSW.
401 ord('U'),ord('S'),ord('B'),ord('S'),
402 #CBW key; must be the same as the one we're replying to.
403 ord(cbw[4]),ord(cbw[5]),ord(cbw[6]),ord(cbw[7]),
404 #CSW Data Residue, probably oughtn't be zeroed.
406 #Status byte: 00 for good, 01 for bad.
408 self.writebytes(rEP3INFIFO,
410 self.wregAS(rEP3INBC,len(csw));
415 class GoodFETMAXUSBMassFile(GoodFETMAXUSBMass):
416 """This emulates a USB Mass Storage Device, providing a file as
417 its image. Writes are not yet supported, and this is very slow.
418 Performance hacks will come after the code stabilizes."""
422 def openImage(self,filename):
423 """Opens an image for use. Call this *before* massinit()."""
424 self.datafile=open(filename,"rb");
425 print "Opened an image with %i blocks." % self.getSectorCount();
426 def putSectorData(self,lba,block):
427 """Writes a 512-byte sector to the lba address."""
428 print "Writes aren't yet supported.";
431 def getSectorData(self,lba):
432 """Returns data from a 512-byte sector."""
435 #Seek to the appropraite block.
436 #print "Seeking to position %i"% (lba*512)
437 self.datafile.seek(lba*512,0);
438 pos=self.datafile.tell();
440 print "SEEK ERROR: Seeked to %i (lba=%i), but now I'm at %i (lba=%i)" % (
445 #Dump the data out, assuming no blocking and filling with nonsense.
446 toret=self.datafile.read(512);
448 print "Holy hell, I only have %i bytes of 512." % len(toret);
450 toretbytes=range(0,len(toret));
451 for b in range(0,len(toret)): toretbytes[b]=ord(toret[b]);
454 def getSectorCount(self):
455 """Returns the number of viable Logical Block Addresses."""
457 # Python must have a better way to read a file length, but for
458 # now we just read the whole damned thing and then throw it
459 # away. With present performance, we can't read anything
460 # large enough for this to be a problem.
461 if self.datafilelen==None:
462 self.datafile.seek(0);
463 self.datafilelen=len(self.datafile.read());
464 if self.datafilelen%512!=0:
465 print "ERROR: Image does not have an integer number of blocks!"
466 print "%i \% 512 == %i" % (self.datafilelen,
467 self.datafilelen%512);
469 return self.datafilelen/512-1;
471 if(len(sys.argv)==1):
472 print "Usage: %s disk.img\n" % sys.argv[0];
476 #Initialize FET and set baud rate
477 client=GoodFETMAXUSBMassFile();
480 client.openImage(sys.argv[1]);
482 client.MAXUSBsetup();