File: flashmem.cpp

package info (click to toggle)
raidutils 0.0.6-19
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 15,468 kB
  • sloc: cpp: 39,795; ansic: 22,774; sh: 9,964; makefile: 23
file content (863 lines) | stat: -rw-r--r-- 21,631 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
/* Copyright (c) 1996-2004, Adaptec Corporation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * - Neither the name of the Adaptec Corporation nor the names of its
 *   contributors may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/****************************************************************************
*
* Created:  1/18/2000
*
*****************************************************************************
*
* File Name:		FlashMem.cpp
* Module:
* Contributors:		David Dillard
*                   Mark Salazyn
* Description:		Contains the definitions of the following flash memory
*                   related classes:
*
*                   FlashMemory - A base class for the other flash memory
*                               classes.
*
*                   BiosFlashMemory - A class which represents the BIOS flash
*                               memory on a particular controller.
*
*                   SmorFlashMemory - A class which represents the SMOR flash
*                               memory on a particular controller.
*
*                   FlashMemoryStreamBuf - A streambuf subclass which is used
*                               to treat the contents of some region of flash
*                               memory as a stream.
*
* Notes:            This set of classes could be improved by introducing stream
*                   classes which could be used to handle BIOS or SMOR images
*                   that were either in flash memory or were files (or
*                   buffered in RAM).
*
* Version Control:
*
* $Revision$
* $NoKeywords: $
* $Log$
* Revision 1.1.1.1  2004-05-05 12:49:12  bap
* Imported upstream version 0.0.4. 
*
*****************************************************************************/

/*** INCLUDES ***/
#include "flashmem.h"
#include "lzstrbuf.h"

/*** MACROS ***/
#ifndef min
#define min(x, y)   ((x) < (y) ? (x) : (y))
#endif





//
// Class variables.
//
DPT_TAG_T FlashMemory::m_LastTag;
FlashMemory::Region FlashMemory::m_LastRegion = FlashMemory::None;





//=============================================================================
//
//Name: mkulong
//
//Abstract: Makes a uLONG value from four bytes (unsigned characters).
//
//Parameters: The four bytes that make up a uLONG value.
//
//Return Values: The constructed uLONG value.
//
//Error Codes: None
//
//Global Variables Affected: None
//
//Notes: This really should be in some global header file, but I'm trying
//       to minimize changes to other files right now.  Perhaps, at some
//       future time, this function can be moved.
//
//-----------------------------------------------------------------------------
inline uLONG mkulong(uCHAR b3, uCHAR b2, uCHAR b1, uCHAR b0)
{

    return(((uLONG) b3 << 24) + ((uLONG) b2 << 16) + ((uLONG) b1 << 8) + b0);
}





//=============================================================================
//
//Name: 
//
//Abstract: 
//
//Parameters: None
//
//Return Values: None
//
//Error Codes: None
//
//Global Variables Affected: None
//
//Notes: None
//
//-----------------------------------------------------------------------------
DPT_RTN_T FlashMemory::Read(
    uLONG offset,
    uLONG length,
    void *buf
)
{

    DPT_RTN_T rc = MSG_RTN_COMPLETED;


    //
    // See if the last region read is the same as the region to read now.
    // If it isn't then set the region.  This allows for the reading of
    // different regions in an interleaved fashion.
    //
    if (( m_Tag != m_LastTag ) || ( m_Region != m_LastRegion ))
    {
        m_Engine.Reset();
        m_Engine.Insert((uLONG) m_Region);
        rc = m_Engine.Send(MSG_FLASH_SET_REGION, m_Tag);
        if ( rc == MSG_RTN_COMPLETED )
        {
            m_LastTag = m_Tag;
            m_LastRegion = m_Region;
        }
    }



    //
    // Read in data from the specified offset.
    //
    if ( rc == MSG_RTN_COMPLETED )
    {
        m_Engine.Reset();
        m_Engine.Insert(offset);
        m_Engine.Insert(length);
        rc = m_Engine.Send(MSG_FLASH_READ, m_Tag);
        if ( rc == MSG_RTN_COMPLETED )
        {
            m_Engine.Extract(buf, length);
        }
    }



    //
    // Return to the caller.
    //
    return(rc);
}





//=============================================================================
//
//Name: BiosFlashMemory::GetLength
//
//Abstract: Gets the length of the BIOS in flash memory.
//
//Parameters: bytes - Reference to the number of bytes used by the BIOS in
//                    flash memory.
//
//Return Values: MSG_RTN_COMPLETED indicates success.
//               DPT_RTN_T value to indicate an error.
//
//Error Codes: DPT_RTN_T value
//
//Global Variables Affected: None
//
//Notes: Exceptions should be used instead of returning an error code to
//       indicate an error, but unfortunately that's not an option because not
//       all of the compilers that are used support exceptions.
//
//-----------------------------------------------------------------------------
DPT_RTN_T BiosFlashMemory::GetLength(
    uLONG &bytes
)
{

    DPT_RTN_T rc = MSG_RTN_COMPLETED;


    //
    // If the length hasn't been cached then get it.
    //
    if ( m_Length == 0 )
    {
        //
        // Read in the number of blocks from the image.  If that doesn't fail
        // then calculate the number of bytes.
        //
        Properties buf;
        rc = Read(PropertiesOffset, sizeof(buf), &buf);
        if ( rc == MSG_RTN_COMPLETED )
        {
            if (( buf.m_Signature[0] == 0x55 ) && ( buf.m_Signature[1] == 0xAA ))
            {
                m_Length = (uLONG) buf.m_Blocks * BlockSize;


                //
                // If the length is unreasonable then set it to 0.
                //
                if ( m_Length > 65536L )
                {
                    m_Length = 0;
                }
            }
        }
    }



    //
    // If we've gotten the length then return it.
    //
    if ( rc == MSG_RTN_COMPLETED )
    {
        bytes = m_Length;
    }



    //
    // Return to the caller.
    //
    return(rc);
}





//=============================================================================
//
//Name: BiosFlashMemory::GetSignature
//
//Abstract: Gets the signature from the associated BIOS flash memory.
//
//Parameters: None.
//
//Return Values: The signature.
//
//Error Codes: None.
//
//Global Variables Affected: None
//
//Notes: Exceptions should be used instead of returning a zero'd structure to
//       indicate an error, but unfortunately that's not an option because not
//       all of the compilers that are used support exceptions.
//
//-----------------------------------------------------------------------------
dpt_sig_S BiosFlashMemory::GetSignature()
{

    FlashMemoryStreamBuf biosStreamBuf(*this);
    std::istream biosStream(&biosStreamBuf);

    return(DptSignature(biosStream));
}





//=============================================================================
//
//Name: SmorFlashMemory::Ctor
//
//Abstract: Initializes an object.
//
//Parameters: engine - A reference to the engine object.
//            hba_tag - The tag of the host adapter on which the SMOR flash
//                      memory resides.
//
//Return Values: None.
//
//Error Codes: None.
//
//Global Variables Affected: None
//
//Notes: Exceptions should be used instead of returning a zero'd structure to
//       indicate an error, but unfortunately that's not an option because not
//       all of the compilers that are used support exceptions.
//
//       The compression state and the length of the SMOR image are cached
//       here for later use.
//
//-----------------------------------------------------------------------------
SmorFlashMemory::SmorFlashMemory(
    DPT_EngineIO_C &engine,
    DPT_TAG_T hba_tag
) : FlashMemory(engine, hba_tag, FlashMemory::SMOR),
    m_Length(0),
    m_CompressionState(Unknown)
{

    //
    // Determine some properties of the SMOR flash memory.
    //
    //      - The length of the SMOR image in memory
    //      - If the SMOR image is compressed
    //
    Properties buf;
    DPT_RTN_T rc = Read((uLONG) 0, (uLONG) sizeof(buf), &buf);
    if ( rc == MSG_RTN_COMPLETED )
    {
        //
        // Look for the signature at the beginning of the buffer to see if
        // the image is compressed.
        //
        if (( buf.m_Signature[0] == 0x55 ) && ( buf.m_Signature[1] == 0xAA ))
        {
            m_CompressionState = Compressed;
        }
        else if (( buf.m_Signature[0] == 0x5A ) && ( buf.m_Signature[1] == 0x55 ))
        {
            m_CompressionState = NotCompressed;
        }



        //
        // If the compression state is known, i.e. a valid signature was
        // found, then determine the length.
        //
        if ( m_CompressionState != Unknown )
        {
            m_Length = mkulong(buf.m_Length[3], buf.m_Length[2],
                               buf.m_Length[1], buf.m_Length[0]);

            if ( m_Length > 512L * 1024L )
            {
                m_Length = 0;
            }
        }
    }
}




//=============================================================================
//
//Name: SmorFlashMemory::GetLength
//
//Abstract: Gets the length of SMOR in flash memory.
//
//Parameters: bytes - Reference to the number of bytes used by SMOR in flash
//                    memory.
//
//Return Values: MSG_RTN_COMPLETED indicates success.
//               DPT_RTN_T value to indicate an error.
//
//Error Codes: DPT_RTN_T value
//
//Global Variables Affected: None
//
//Notes: Exceptions should be used instead of returning an error code to
//       indicate an error, but unfortunately that's not an option because not
//       all of the compilers that are used support exceptions.
//
//-----------------------------------------------------------------------------
DPT_RTN_T SmorFlashMemory::GetLength(
    uLONG &bytes
)
{

    DPT_RTN_T rc;
    

    //
    // Determine the return code based upon the length.  If length is 0 then
    // an error occurred.
    //
    if ( m_Length == 0 )
    {
        rc = MSG_RTN_FAILED;
    }
    else
    {
        bytes = m_Length;
        rc = MSG_RTN_COMPLETED;
    }



    //
    // Return to the caller.
    //
    return(rc);
}





//=============================================================================
//
//Name: SmorFlashMemory::GetSignature
//
//Abstract: Gets the signature from the associated BIOS flash memory.
//
//Parameters: None.
//
//Return Values: The signature.
//
//Error Codes: None.
//
//Global Variables Affected: None
//
//Notes: Exceptions should be used instead of returning a zero'd structure to
//       indicate an error, but unfortunately that's not an option because not
//       all of the compilers that are used support exceptions.
//
//-----------------------------------------------------------------------------
dpt_sig_S SmorFlashMemory::GetSignature()
{

    //
    // Allocate a streambuf for the SMOR flash memory.  The kind of streambuf
    // that is used depends on if the SMOR image is compressed or not.
    //
    // These should be auto_ptr's, but can't count on having that available.
    // Can't count on having templates either so can't write my own auto_ptr.
    // Got to do all of this manually  :-(
    //
    std::streambuf *smorStreamBuf = NULL;
    std::istream *compressedSmorStream = NULL;
    switch ( GetCompressionState() )
    {
        case Compressed:
        {
            FlashMemoryStreamBuf *compressedSmorStreamBuf =
                                        new FlashMemoryStreamBuf(*this);

            compressedSmorStream = new std::istream(compressedSmorStreamBuf);
            if ( compressedSmorStream == NULL )
            {
                delete compressedSmorStreamBuf;
            }

            compressedSmorStream->seekg(HeaderSize, std::ios::beg);
            smorStreamBuf = new LzInStreamBuf(*compressedSmorStream);
            break;
        }

        case NotCompressed:
            smorStreamBuf = new FlashMemoryStreamBuf(*this);
            break;
    }



    //
    // If a streambuf was allocated then use it to set the signature for SMOR.
    // If no streambuf was allocated (for whatever reason) then there is no
    // way to get the SMOR version number.
    //
    DptSignature signature;
    signature.Clear();

    if ( smorStreamBuf != NULL )
    {
        std::istream smorStream(smorStreamBuf);
        signature.Set(smorStream);


        //
        // Free up resources
        //
        delete smorStreamBuf;
        delete compressedSmorStream;
    }



    //
    // Return the signature.
    //
    return(signature);
}





//=============================================================================
//
//Name: SmorFlashMemory::GetCompressionState
//
//Abstract: Gets the compression state of SMOR in flash memory.
//
//Parameters: None
//
//Return Values: Compressed - SMOR is compressed in flash memory
//               NotCompressed - SMOR is not compressed in flash memory
//               Unknown - SMOR's compression state cannot be determined
//                         because an error occurred
//
//Error Codes: Unknown
//
//Global Variables Affected: None
//
//Notes: None
//
//-----------------------------------------------------------------------------
SmorFlashMemory::CompressionState SmorFlashMemory::GetCompressionState()
{

    return(m_CompressionState);
}





//=============================================================================
//
//Name: FlashMemoryStreamBuf::Ctor
//
//Abstract: Initializes the streambuf object with a buffer whose size may be
//          based upon the size of the flash memory that is being buffered.
//
//Parameters: None
//
//Return Values: None
//
//Error Codes: None
//
//Global Variables Affected: None
//
//Notes: Calls the virtual method GetLength().  Since the subclass provides
//       the implementation of this method and since the subclass object is
//       not initialized when the GetLength() method is called that method
//       cannot depend upon any member variables of the subclass being
//       initialized.
//
//-----------------------------------------------------------------------------
FlashMemoryStreamBuf::FlashMemoryStreamBuf(
    FlashMemory &flashMemory
) : m_FlashMemory(flashMemory),
    m_BufSize(0),
    m_CurrentOffset(0),
    m_StreamLength(0)
{

    //
    // Get the stream length.  Use this to help determine what the maximum
    // buffer size is.  No need to allocate a buffer larger than the flash
    // memory that's being buffering.
    //
    if ( m_FlashMemory.GetLength(m_StreamLength) == MSG_RTN_COMPLETED )
    {
        size_t maxBufSize = min(m_StreamLength, MaxBufSize);
        m_BufSize = AllocBuf(maxBufSize, MinBufSize, BufSizeDecrement);
    }
}





//=============================================================================
//
//Name: FlashMemoryStreamBuf::underflow
//
//Abstract: Buffers the next set of data from the associated flash memory.
//
//Parameters: None
//
//Return Values: The first character in the buffer that was just read or EOF
//               if an error occurred.
//
//Error Codes: EOF
//
//Global Variables Affected: None
//
//Notes: None
//
//-----------------------------------------------------------------------------
int FlashMemoryStreamBuf::underflow()
{

    int rc = EOF;


    //
    // Is there any data to read?
    //
    if ( m_CurrentOffset < m_StreamLength )
    {
        //
        // Determine how much data to read.
        //
        const uLONG readSize = min(m_BufSize, m_StreamLength - m_CurrentOffset);
        char *buf = eback();
        if ( buf != NULL )
        {
            //
            // Read the data from the flash memory, update the various fields, and
            // return the first character of the data that was read.
            //
            if ( m_FlashMemory.Read(m_CurrentOffset, readSize, buf) == MSG_RTN_COMPLETED )
            {
                m_CurrentOffset += readSize;
                setg(buf, buf, buf + readSize);
                rc = (unsigned char) buf[0];
            }
        }
    }



    //
    // Return status to the caller.
    //
    return(rc);
}






//=============================================================================
//
//Name: DptSignature::Ctor
//
//Abstract: Sets the signature to all zeros (except for the id string)
//
//Parameters: None
//
//Return Values: None
//
//Error Codes: None
//
//Global Variables Affected: None
//
//Notes: None
//
//-----------------------------------------------------------------------------
DptSignature::DptSignature()
{

    memset(this, 0, sizeof(*this));

    dsSignature[0] = 'd';
    dsSignature[1] = 'P';
    dsSignature[2] = 't';
    dsSignature[3] = 'S';
    dsSignature[4] = 'i';
    dsSignature[5] = 'G';
}





//=============================================================================
//
//Name: DptSignature::Ctor
//
//Abstract: Sets the signature structure from the specified stream.
//
//Parameters: stream - The input stream to be searched.
//
//Return Values: None
//
//Error Codes: None
//
//Global Variables Affected: None
//
//Notes: If there was an error getting the signature then all fields of the
//       structure will be zero.
//
//-----------------------------------------------------------------------------
DptSignature::DptSignature(
    std::istream &stream
)
{

    Set(stream);
}





//=============================================================================
//
//Name: DptSignature::Set
//
//Abstract: Sets the signature structure from the specified stream.
//
//Parameters: stream - The input stream to be searched.
//
//Return Values: None
//
//Error Codes: None
//
//Global Variables Affected: None
//
//Notes: If there was an error getting the signature then all fields of the
//       structure will be zero.
//
//-----------------------------------------------------------------------------
void DptSignature::Set(
    std::istream &stream
)
{

    const int BeginningState = 0;
    const int FoundState = 0x7F;


    int state = BeginningState;
    while ( state != FoundState )
    {
        int c = stream.get();
        if ( c == EOF )
        {
            break;
        }

        switch (state)
        {
            case BeginningState:
                if (c == 'd')
                    state = 'd';
                break;

            case 'd':
                if (c == 'P')
                    state = 'P';
                else
                    state = BeginningState;
                break;

            case 'P':
                if (c == 't')
                    state = 't';
                else
                    state = BeginningState;
                break;


            case 't':
                if (c == 'S')
                    state = 'S';
                else
                    state = BeginningState;
                break;

            case 'S':
                if (c == 'i')
                    state = 'i';
                else
                    state = BeginningState;
                break;

            case 'i':
                if (c == 'G')
                    state = FoundState;
                else
                    state = BeginningState;
                break;

            default:
                state = BeginningState;
                break;
        }
    }

    if (state == FoundState)
    {
        char *p = (char *) &dsSigVersion;

        dsSignature[0] = 'd';
        dsSignature[1] = 'P';
        dsSignature[2] = 't';
        dsSignature[3] = 'S';
        dsSignature[4] = 'i';
        dsSignature[5] = 'G';

        for (int j = sizeof(dpt_sig_S) - 6; j > 0; j--)
            *p++ = stream.get();

        dsDescription[dsDescription_size - 1] = '\0';
    }
    else
    {
        Clear();
    }
}





//=============================================================================
//
//Name: DptSignature::Clear
//
//Abstract: Zeros out the associated instructure.
//
//Parameters: stream - None.
//
//Return Values: None
//
//Error Codes: None
//
//Global Variables Affected: None
//
//Notes: None.
//
//-----------------------------------------------------------------------------
void DptSignature::Clear()
{

    memset(this, 0, sizeof(*this));
}