root/branches/libfreebob-downloader/src/bebob/bebob_dl_mgr.cpp

Revision 271, 19.3 kB (checked in by wagi, 16 years ago)

2006-06-21 Daniel Wagner <wagi@monom.org>

  • freebob-downloader first version added
Line 
1 /* bebob_dl_mgr.cpp
2  * Copyright (C) 2006 by Daniel Wagner
3  *
4  * This file is part of FreeBoB.
5  *
6  * FreeBoB is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  * FreeBoB is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with FreeBoB; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
18  * MA 02111-1307 USA.
19  */
20
21 #include "bebob_dl_mgr.h"
22 #include "bebob_dl_codes.h"
23 #include "bebob_dl_bcd.h"
24
25 #include "configrom.h"
26 #include "libfreebobavc/ieee1394service.h"
27 #include "libfreebobavc/serialize.h"
28
29 #include <netinet/in.h>
30
31 #include <cstdio>
32
33 namespace BeBoB {
34     enum {
35         AddrRegInfo    = 0xffffc8020000ULL,
36         AddrRegReq     = 0xffffc8021000ULL,
37         AddrRegReqBuf  = 0xffffc8021040ULL,
38         AddrRegResp    = 0xffffc8029000ULL,
39         AddrRegRespBuf = 0xffffc8029040ULL,
40     };
41
42     enum {
43         RegInfoManufactorIdOffset =      0x00,
44         RegInfoProtocolVersionOffset =   0x08,
45         RegInfoBootloaderVersionOffset = 0x0c,
46         RegInfoGUID =                    0x10,
47         RegInfoHardwareModelId =         0x18,
48         RegInfoHardwareRevision =        0x1c,
49         RegInfoSoftwareDate =            0x20,
50         RegInfoSoftwareTime =            0x28,
51         RegInfoSoftwareId =              0x30,
52         RegInfoSoftwareVersion =         0x34,
53         RegInfoBaseAddress =             0x38,
54         RegInfoMaxImageLen =             0x3c,
55         RegInfoBootloaderDate =          0x40,
56         RegInfoBootloaderTime =          0x48,
57         RegInfoDebuggerDate =            0x50,
58         RegInfoDebuggerTime =            0x58,
59         RegInfoDebuggerId =              0x60,
60         RegInfoDebuggerVersion =         0x64
61     };
62
63     enum {
64         MaxRetries = 10,
65     };
66
67     IMPL_DEBUG_MODULE( BootloaderManager, BootloaderManager, DEBUG_LEVEL_NORMAL );
68 }
69
70 BeBoB::BootloaderManager::BootloaderManager(Ieee1394Service& ieee1349service,
71                                             fb_nodeid_t nodeId )
72     : m_ieee1394service( &ieee1349service )
73     , m_protocolVersion( eBPV_Unknown )
74     , m_isAppRunning( false )
75 {
76     memset( &m_cachedInfoRegs, 0, sizeof( m_cachedInfoRegs ) );
77
78     m_configRom = new ConfigRom( m_ieee1394service, nodeId );
79     // XXX throw exception if initialize fails!
80     m_configRom->initialize();
81     cacheInfoRegisters();
82
83     switch(  m_cachedInfoRegs.m_protocolVersion ) {
84     case 1:
85         m_protocolVersion = eBPV_V1;
86         break;
87     case 3:
88         m_protocolVersion = eBPV_V3;
89         break;
90     default:
91         // exception?
92         break;
93     }
94
95     pthread_mutex_init( &m_mutex, 0 );
96     pthread_cond_init( &m_cond, 0 );
97
98     m_functor = new MemberFunctor0< BeBoB::BootloaderManager*,
99                 void (BeBoB::BootloaderManager::*)() >
100                 ( this, &BeBoB::BootloaderManager::busresetHandler, false );
101     m_ieee1394service->addBusResetHandler( m_functor );
102 }
103
104 BeBoB::BootloaderManager::~BootloaderManager()
105 {
106     m_ieee1394service->remBusResetHandler( m_functor );
107     delete( m_functor );
108
109     delete m_configRom;
110
111     pthread_cond_destroy( &m_cond );
112     pthread_mutex_destroy( &m_mutex );
113 }
114
115 bool
116 BeBoB::BootloaderManager::cacheInfoRegisters()
117 {
118     if ( !m_configRom->updatedNodeId() ) {
119         return false;
120     }
121
122     if ( !m_ieee1394service->read(
123              0xffc0 | m_configRom->getNodeId(),
124              AddrRegInfo,
125              sizeof( m_cachedInfoRegs )/4,
126              reinterpret_cast<fb_quadlet_t*>( &m_cachedInfoRegs ) ) )
127     {
128         return false;
129     }
130
131     if ( m_cachedInfoRegs.m_bootloaderVersion != 0x0 ) {
132         m_isAppRunning = false;
133     } else {
134         m_isAppRunning = true;
135     }
136
137     m_cachedInfoRegs.m_guid = ( m_cachedInfoRegs.m_guid >> 32 )
138                               | ( m_cachedInfoRegs.m_guid << 32 );
139
140     return true;
141 }
142
143 bool
144 BeBoB::BootloaderManager::cacheInfoRegisters( int retries )
145 {
146     for ( int i = 0; i < retries; ++i ) {
147         if ( cacheInfoRegisters() ) {
148             return true;
149         }
150         sleep( 1 );
151     }
152
153     return false;
154 }
155
156 void
157 BeBoB::BootloaderManager::printInfoRegisters()
158 {
159     using namespace std;
160
161     if ( !cacheInfoRegisters() ) {
162         debugError( "Could not read info registers\n" );
163         return;
164     }
165
166     printf( "Info Registers\n" );
167     printf( "\tManufactors Id:\t\t%s\n",
168             makeString( m_cachedInfoRegs.m_manId ).c_str() );
169     printf( "\tProtocol Version:\t0x%08x\n",
170             m_cachedInfoRegs.m_protocolVersion );
171     printf( "\tBootloader Version:\t0x%08x\n",
172             m_cachedInfoRegs.m_bootloaderVersion );
173     printf( "\tGUID:\t\t\t0x%08x%08x\n",
174             ( unsigned int )( m_cachedInfoRegs.m_guid >> 32 ),
175             ( unsigned int )( m_cachedInfoRegs.m_guid & 0xffffffff ) );
176     printf( "\tHardware Model ID:\t0x%08x\n",
177             m_cachedInfoRegs.m_hardwareModelId );
178     printf( "\tHardware Revision:\t0x%08x\n",
179             m_cachedInfoRegs.m_hardwareRevision );
180     if (  m_cachedInfoRegs.m_softwareDate
181           && m_cachedInfoRegs.m_softwareTime )
182     {
183         printf( "\tSoftware Date:\t\t%s, %s\n",
184                 makeDate( m_cachedInfoRegs.m_softwareDate ).c_str(),
185                 makeTime( m_cachedInfoRegs.m_softwareTime ).c_str() );
186     }
187     printf( "\tSoftware Id:\t\t0x%08x\n", m_cachedInfoRegs.m_softwareId );
188     printf( "\tSoftware Version:\t0x%08x\n",
189             m_cachedInfoRegs.m_softwareVersion );
190     printf( "\tBase Address:\t\t0x%08x\n", m_cachedInfoRegs.m_baseAddress );
191     printf( "\tMax. Image Len:\t\t0x%08x\n", m_cachedInfoRegs.m_maxImageLen );
192     if ( m_cachedInfoRegs.m_bootloaderDate
193          && m_cachedInfoRegs.m_bootloaderTime )
194     {
195         printf( "\tBootloader Date:\t%s, %s\n",
196                 makeDate( m_cachedInfoRegs.m_bootloaderDate ).c_str(),
197                 makeTime( m_cachedInfoRegs.m_bootloaderTime ).c_str() );
198     }
199     if ( m_cachedInfoRegs.m_debuggerDate
200          && m_cachedInfoRegs.m_debuggerTime )
201     {
202         printf( "\tDebugger Date:\t\t%s, %s\n",
203                 makeDate( m_cachedInfoRegs.m_debuggerDate ).c_str(),
204                 makeTime( m_cachedInfoRegs.m_debuggerTime ).c_str() );
205     }
206     printf( "\tDebugger Id:\t\t0x%08x\n", m_cachedInfoRegs.m_debuggerId );
207     printf( "\tDebugger Version:\t0x%08x\n",
208             m_cachedInfoRegs.m_debuggerVersion );
209 }
210
211 bool
212 BeBoB::BootloaderManager::downloadFirmware( std::string filename )
213 {
214     using namespace std;
215
216     std::auto_ptr<BCD> bcd = std::auto_ptr<BCD>( new BCD( filename ) );
217     if ( !bcd.get() ) {
218         debugError( "downloadFirmware: Could not open or parse BCD '%s'\n",
219                     filename.c_str() );
220         return false;
221     }
222
223     if ( !bcd->parse() ) {
224         debugError( "downloadFirmware: BCD parsing failed\n" );
225         return false;
226     }
227
228     if ( !startBootloaderCmd() ) {
229         debugError( "downloadFirmware: Could not start bootloader\n" );
230         return false;
231     }
232     waitForBusReset();
233     if ( !cacheInfoRegisters( MaxRetries ) ) {
234         debugError( "downloadFirmware: Could not read info registers\n" );
235         return false;
236     }
237
238     // wait for bootloader finish startup sequence
239     // there is no way to find out when it has finished
240     sleep( 10 );
241
242     if ( !downloadObject( *bcd, eOT_Application ) ) {
243         debugError( "downloadFirmware: Firmware download failed\n" );
244         return false;
245     }
246
247     if ( !downloadObject( *bcd, eOT_CnE ) ) {
248         debugError( "downloadFirmware: CnE download failed\n" );
249         return false;
250     }
251
252     sleep( 5 );
253
254     // Let's try to start the image in any case...
255     if ( !startApplicationCmd() ) {
256         debugError( "downloadFirmware: Could not restart application\n" );
257         return false;
258     }
259
260     return true;
261 }
262
263 bool
264 BeBoB::BootloaderManager::downloadCnE( std::string filename )
265 {
266     using namespace std;
267
268     std::auto_ptr<BCD> bcd = std::auto_ptr<BCD>( new BCD( filename ) );
269     if ( !bcd.get() ) {
270         debugError( "downloadCnE: Could not open or parse BCD '%s'\n",
271                     filename.c_str() );
272         return false;
273     }
274
275     if ( !bcd->parse() ) {
276         debugError( "downloadCnE: BCD parsing failed\n" );
277         return false;
278     }
279
280     if ( !startBootloaderCmd() ) {
281         debugError( "downloadCnE: Could not start bootloader\n" );
282         return false;
283     }
284     waitForBusReset();
285     if ( !cacheInfoRegisters( MaxRetries ) ) {
286         debugError( "downloadCnE: Could not read info registers\n" );
287         return false;
288     }
289
290     // wait for bootloader finish startup sequence
291     // there is no way to find out when it has finished
292     sleep( 10 );
293
294     get1394Serivce()->setVerbose( true );
295
296     if ( !downloadObject( *bcd, eOT_CnE ) ) {
297         debugError( "downloadCnE: CnE download failed\n" );
298         return false;
299     }
300
301     if ( !initializeConfigToFactorySettingCmd() ) {
302         debugError( "downloadCnE: Setting default config "
303                     "settings failed\n" );
304         return false;
305     }
306
307     sleep( 5 );
308
309     // Let's try to start the image in any case...
310     if ( !startApplicationCmd() ) {
311         debugError( "downloadCnE: Could not restart application\n" );
312         return false;
313     }
314
315     return true;
316 }
317
318
319 bool
320 BeBoB::BootloaderManager::downloadObject( BCD& bcd, EObjectType eObject )
321 {
322     using namespace std;
323
324     CommandCodesDownloadStart::EObject eCCDSObject;
325     fb_quadlet_t baseAddress;
326     fb_quadlet_t imageLength;
327     fb_quadlet_t crc;
328     fb_quadlet_t offset;
329
330     switch ( eObject ) {
331     case eOT_Application:
332         eCCDSObject = CommandCodesDownloadStart::eO_Application;
333         baseAddress = bcd.getImageBaseAddress();
334         imageLength = bcd.getImageLength();
335         crc = bcd.getImageCRC();
336         offset = bcd.getImageOffset();
337         break;
338     case eOT_CnE:
339         eCCDSObject = CommandCodesDownloadStart::eO_Config;
340         baseAddress = 0;
341         imageLength = bcd.getCnELength();
342         crc = bcd.getCnECRC();
343         offset = bcd.getCnEOffset();
344         break;
345     default:
346         return false;
347     }
348
349     CommandCodesDownloadStart ccDStart ( m_protocolVersion, eCCDSObject );
350     ccDStart.setDate( bcd.getSoftwareDate() );
351     ccDStart.setTime( bcd.getSoftwareTime() );
352     ccDStart.setId( bcd.getSoftwareId() );
353     ccDStart.setVersion( bcd.getSoftwareVersion() );
354     ccDStart.setBaseAddress( baseAddress );
355     ccDStart.setLength( imageLength );
356     ccDStart.setCRC( crc );
357
358     if ( !writeRequest( ccDStart ) ) {
359         debugError( "downloadObject: start command write request failed\n" );
360         return false;
361     }
362
363     // bootloader erases the flash, have to wait until is ready
364     // to answer our next request
365     sleep( 20 );
366
367     if ( !readResponse( ccDStart ) ) {
368         debugError( "downloadObject: (start) command read request failed\n" );
369         return false;
370     }
371
372     if ( ccDStart.getMaxBlockSize() < 0 ) {
373         debugError( "downloadObject: (start) command reported error %d\n",
374                     ccDStart.getMaxBlockSize() );
375         return false;
376     }
377
378     unsigned int maxBlockSize = m_configRom->getAsyMaxPayload();
379     unsigned int i = 0;
380     fb_quadlet_t address = 0;
381     bool result = true;
382     int nrBlocks = ( imageLength + maxBlockSize - 1 ) / maxBlockSize;
383     while ( imageLength > 0 ) {
384         unsigned int blockSize = imageLength > maxBlockSize ?
385                         maxBlockSize  : imageLength;
386
387         fb_byte_t block[blockSize];
388         if ( !bcd.read( offset, block, blockSize ) ) {
389             result = false;
390             break;
391         }
392
393         if ( !get1394Serivce()->write(
394                  0xffc0 | getConfigRom()->getNodeId(),
395                  AddrRegReqBuf,
396                  ( blockSize + 3 ) / 4,
397                  reinterpret_cast<fb_quadlet_t*>( block ) ) )
398         {
399             debugError( "downloadObject: Could not write to node %d\n",
400                         getConfigRom()->getNodeId() );
401             return false;
402         }
403
404         CommandCodesDownloadBlock ccBlock( m_protocolVersion );
405         ccBlock.setSeqNumber( i );
406         ccBlock.setAddress( baseAddress + address );
407         ccBlock.setNumberBytes( blockSize );
408
409         if ( !writeRequest( ccBlock ) ) {
410             debugError( "downloadObject: (block) write request failed" );
411             result = false;
412             break;
413         }
414         usleep( 1000 );
415
416         if ( !readResponse( ccBlock ) ) {
417             debugError( "downloadObject: (block) read request failed\n" );
418             result = false;
419             break;
420         }
421
422         if ( i != ccBlock.getRespSeqNumber() ) {
423             debugError( "downloadObject: (block) wrong sequence number "
424                         "reported. %d expected, %d reported\n",
425                         i, ccBlock.getRespSeqNumber() );
426             result = false;
427             break;
428         }
429         if ( ccBlock.getRespErrorCode() != 0 ) {
430             debugError( "downloadObject: (block) failed download with "
431                         "error code 0x%08x\n", ccBlock.getRespErrorCode() );
432             result = false;
433             break;
434         }
435
436         if ( ( i % 1000 ) == 0 ) {
437            printf( "[%04d/%04d] packets downloaded\n", i, nrBlocks );
438         }
439
440         imageLength -= blockSize;
441         address += blockSize;
442         offset += blockSize;
443         i++;
444     }
445
446     if ( !result ) {
447         debugError( "downloadObject: seqNumber = %d, "
448                     "address = 0%08x, offset = 0x%08x, "
449                     "restImageLength = 0x%08x\n",
450                     i, address, offset, imageLength );
451     }
452
453     CommandCodesDownloadEnd ccEnd( m_protocolVersion );
454     if ( !writeRequest( ccEnd ) ) {
455         debugError( "downloadObject: (end) command write failed\n" );
456     }
457
458     sleep( 10 );
459
460     if ( !readResponse( ccEnd ) ) {
461         debugError( "downloadObject: (end) command read failed\n" );
462     }
463
464     if ( result ) {
465         if ( ccEnd.getRespIsValid() ) {
466             if ( ccEnd.getRespCrc32() == crc ) {
467                 debugOutput( DebugModule::eDL_Normal,
468                              "downloadObject: CRC match\n" );
469             } else {
470                 debugError( "downloadObject: CRC mismatch. 0x%08x expected, "
471                             "0x%08x reported",
472                             crc, ccEnd.getRespCrc32() );
473                 result = false;
474             }
475         } else {
476             debugError( "downloadObject: (end) object is not valid\n" );
477             result = false;
478         }
479     }
480     return result;
481 }
482
483 bool
484 BeBoB::BootloaderManager::programGUID( fb_octlet_t guid )
485 {
486     if ( !startBootloaderCmd() ) {
487         debugError( "programGUID: Could not start bootloader\n" );
488         return false;
489     }
490
491     waitForBusReset();
492     if ( !cacheInfoRegisters( MaxRetries ) ) {
493         debugError( "programGUID: Could not read info registers\n" );
494         return false;
495     }
496
497     // wait for bootloader finish startup sequence
498     // there is no way to find out when it has finished
499     sleep( 10 );
500
501     if ( !programGUIDCmd( guid ) ) {
502         debugError( "programGUID: Could not program guid\n" );
503         return false;
504     }
505
506     if ( !startApplicationCmd() ) {
507         debugError( "Could not restart application\n");
508         return false;
509     }
510
511     return true;
512 }
513
514 void
515 BeBoB::BootloaderManager::busresetHandler()
516 {
517     pthread_cond_signal( &m_cond );
518 }
519
520 void
521 BeBoB::BootloaderManager::waitForBusReset()
522 {
523     pthread_cond_wait( &m_cond, &m_mutex );
524 }
525
526 bool
527 BeBoB::BootloaderManager::writeRequest( CommandCodes& cmd )
528 {
529     unsigned char buf[ ( ( cmd.getMaxSize()+3 )/4 ) * 4 ];
530     memset( buf, 0, sizeof( buf ) );
531
532     BufferSerialize se( buf,  sizeof( buf ) );
533     if ( !cmd.serialize( se ) ) {
534         debugError( "writeRequest: Could not serialize command code %d\n",
535                     cmd.getCommandCode() );
536         return false;
537     }
538
539     if ( !get1394Serivce()->write(
540              0xffc0 | getConfigRom()->getNodeId(),
541              AddrRegReq,
542              sizeof( buf )/4,
543              reinterpret_cast<fb_quadlet_t*>( buf ) ) )
544     {
545         debugError( "writeRequest: Could not ARM write to node %d\n",
546                     getConfigRom()->getNodeId() );
547         return false;
548     }
549
550     return true;
551 }
552
553 bool
554 BeBoB::BootloaderManager::readResponse( CommandCodes& writeRequestCmd )
555 {
556     const size_t buf_length = 0x40;
557     unsigned char raw[buf_length];
558     if ( !get1394Serivce()->read(
559              0xffc0 | getConfigRom()->getNodeId(),
560              AddrRegResp,
561              writeRequestCmd.getRespSizeInQuadlets(),
562              reinterpret_cast<fb_quadlet_t*>( raw ) ) )
563     {
564         return false;
565     }
566
567     BufferDeserialize de( raw, buf_length );
568     if ( !writeRequestCmd.deserialize( de ) ) {
569         debugError( "readResponse: deserialize failed\n" );
570         return false;
571     }
572
573     bool result =
574         writeRequestCmd.getProtocolVersion()
575         == writeRequestCmd.getRespProtocolVersion();
576     result &=
577         writeRequestCmd.getCommandId()
578         == writeRequestCmd.getRespCommandId();
579     result &=
580         writeRequestCmd.getCommandCode()
581         == writeRequestCmd.getRespCommandCode();
582     #ifdef DEBUG
583        if ( !result ) {
584            debugError( "readResponse: protocol version: %d expected, "
585                        " %d reported\n",
586                        writeRequestCmd.getProtocolVersion(),
587                        writeRequestCmd.getRespProtocolVersion() );
588            debugError( "readResponse: command id: %d expected, "
589                        " %d reported\n",
590                        writeRequestCmd.getCommandId(),
591                        writeRequestCmd.getRespCommandId() );
592            debugError( "readResponse: command code: %d expected, "
593                        " %d reported\n",
594                        writeRequestCmd.getCommandCode(),
595                        writeRequestCmd.getRespCommandCode() );
596        }
597     #endif
598     return result;
599 }
600
601 bool
602 BeBoB::BootloaderManager::startBootloaderCmd()
603 {
604     CommandCodesReset cmd( m_protocolVersion,
605                            CommandCodesReset::eSM_Bootloader ) ;
606     if ( !writeRequest( cmd ) ) {
607         debugError( "startBootloaderCmd: writeRequest failed\n" );
608         return false;
609     }
610
611     return true;
612 }
613
614 bool
615 BeBoB::BootloaderManager::startApplicationCmd()
616 {
617     CommandCodesReset cmd( m_protocolVersion,
618                            CommandCodesReset::eSM_Application ) ;
619     if ( !writeRequest( cmd ) ) {
620         debugError( "startApplicationCmd: writeRequest failed\n" );
621         return false;
622     }
623
624     return true;
625 }
626
627 bool
628 BeBoB::BootloaderManager::programGUIDCmd( fb_octlet_t guid )
629 {
630     CommandCodesProgramGUID cmd( m_protocolVersion, guid );
631     if ( !writeRequest( cmd ) ) {
632         debugError( "programGUIDCmd: writeRequest failed\n" );
633         return false;
634     }
635
636     return true;
637 }
638
639 bool
640 BeBoB::BootloaderManager::initializePersParamCmd()
641 {
642     CommandCodesInitializePersParam cmd( m_protocolVersion );
643     if ( !writeRequest( cmd ) ) {
644         debugError( "initializePersParamCmd: writeRequest failed\n" );
645         return false;
646     }
647
648     return true;
649 }
650
651 bool
652 BeBoB::BootloaderManager::initializeConfigToFactorySettingCmd()
653 {
654     CommandCodesInitializeConfigToFactorySetting cmd( m_protocolVersion );
655     if ( !writeRequest( cmd ) ) {
656         debugError( "initializeConfigToFactorySettingCmd: writeRequest failed\n" );
657         return false;
658     }
659
660     return true;
661 }
Note: See TracBrowser for help on using the browser.