Index: trunk/i386/libsaio/xml.c =================================================================== --- trunk/i386/libsaio/xml.c (revision 2326) +++ trunk/i386/libsaio/xml.c (revision 2327) @@ -68,20 +68,20 @@ } struct Module { - struct Module *nextModule; - long willLoad; - TagPtr dict; - char *plistAddr; - long plistLength; - char *driverPath; + struct Module *nextModule; + long willLoad; + TagPtr dict; + char *plistAddr; + long plistLength; + char *driverPath; }; typedef struct Module Module, *ModulePtr; struct DriverInfo { - char *plistAddr; - long plistLength; - void *moduleAddr; - long moduleLength; + char *plistAddr; + long plistLength; + void *moduleAddr; + long moduleLength; }; typedef struct DriverInfo DriverInfo, *DriverInfoPtr; @@ -89,20 +89,20 @@ #define kDriverPackageSignature2 'MOSX' struct DriversPackage { - unsigned long signature1; - unsigned long signature2; - unsigned long length; - unsigned long adler32; - unsigned long version; - unsigned long numDrivers; - unsigned long reserved1; - unsigned long reserved2; + unsigned long signature1; + unsigned long signature2; + unsigned long length; + unsigned long adler32; + unsigned long version; + unsigned long numDrivers; + unsigned long reserved1; + unsigned long reserved2; }; typedef struct DriversPackage DriversPackage; enum { - kCFBundleType2, - kCFBundleType3 + kCFBundleType2, + kCFBundleType3 }; @@ -114,6 +114,7 @@ static long ParseTagInteger(char *buffer, TagPtr *tag); static long ParseTagData(char *buffer, TagPtr *tag); static long ParseTagDate(char *buffer, TagPtr *tag); +//static long ParseTagBoolean(char *buffer, TagPtr *tag, long type); static long GetNextTag(char *buffer, char **tag, long *start); static long FixDataMatchingTag(char *buffer, char *tag); static TagPtr NewTag(void); @@ -127,7 +128,7 @@ // XMLGetProperty TagPtr -XMLGetProperty( TagPtr dict, const char * key ) +XMLGetProperty(TagPtr dict, const char * key) { TagPtr tagList, tag; @@ -140,12 +141,16 @@ tag = tagList; tagList = tag->tagNext; - if ((tag->type != kTagTypeKey) || (tag->string == 0)) continue; - - if (!strcmp(tag->string, key)) return tag->tag; - } - - return 0; + if ((tag->type != kTagTypeKey) || (tag->string == 0)) { + continue; + } + + if (!strcmp(tag->string, key)) { + return tag->tag; + } + } + + return 0; } //========================================================================== @@ -154,31 +159,40 @@ TagPtr XMLGetKey( TagPtr dict, int id ) { - TagPtr tagList, tag; + TagPtr tagList, tag; - if (dict->type != kTagTypeDict) return 0; - - tag = 0; - int element = 0; - tagList = dict->tag; - while (tagList && element != id) - { - tag = tagList; - tagList = tag->tagNext; - - if ((tag->type != kTagTypeKey) || (tag->string == 0)) continue; - element++; - if(id == element) return tag; - } - return 0; + if (dict->type != kTagTypeDict) { + return 0; + } + + tag = 0; + int element = 0; + tagList = dict->tag; + while (tagList && element != id) + { + tag = tagList; + tagList = tag->tagNext; + + if ((tag->type != kTagTypeKey) || (tag->string == 0)) { + continue; + } + + element++; + if(id == element) { + return tag; + } + + } + return 0; } TagPtr XMLGetValueForKey(TagPtr key) { - if (!key || - key->type != kTagTypeKey) return 0; - - return key->tag; + if (!key || key->type != kTagTypeKey) { + return 0; + } + + return key->tag; } @@ -190,30 +204,37 @@ int count = 0; TagPtr tagList, tag; - if (dict->type != kTagTypeDict && dict->type != kTagTypeArray) return 0; + if (dict->type != kTagTypeDict && dict->type != kTagTypeArray) { + return 0; + } + tag = 0; - tagList = dict->tag; - while (tagList) - { + tagList = dict->tag; + while (tagList) + { tag = tagList; - tagList = tag->tagNext; + tagList = tag->tagNext; if (((tag->type != kTagTypeKey) && ((tag->string == 0) || (tag->string[0] == 0))) && (dict->type != kTagTypeArray) // If we are an array, any element is valid - ) continue; + ) { + continue; + } //if(tag->type == kTagTypeKey) printf("Located key %s\n", tag->string); count++; - } + } return count; } TagPtr XMLGetElement( TagPtr dict, int id ) { - if(dict->type != kTagTypeArray) return 0; - + if(dict->type != kTagTypeArray) { + return 0; + } + int element = 0; TagPtr tmp = dict->tag; @@ -230,59 +251,58 @@ char* XMLDecode(const char* src) { - typedef const struct XMLEntity { - const char* name; - size_t nameLen; - char value; - } XMLEntity; - - /* This is ugly, but better than specifying the lengths by hand */ - #define _e(str,c) {str,sizeof(str)-1,c} - const XMLEntity ents[] = { - _e("quot;",'"'), _e("apos;",'\''), - _e("lt;", '<'), _e("gt;", '>'), - _e("amp;", '&') - }; - - size_t len; - const char *s; - char *out, *o; - - if ( !src || !(len = strlen(src)) || !(out = malloc(len+1)) ) - return 0; - - o = out; - s = src; - while (s <= src+len) /* Make sure the terminator is also copied */ - { - if ( *s == '&' ) - { - bool entFound = false; - int i; - - s++; - for ( i = 0; i < sizeof(ents)/sizeof(ents[0]); i++) - { - if ( strncmp(s, ents[i].name, ents[i].nameLen) == 0 ) - { - entFound = true; - break; - } - } - if ( entFound ) - { - *o++ = ents[i].value; - s += ents[i].nameLen; - continue; - } - } - - *o++ = *s++; - } + typedef const struct XMLEntity { + const char* name; + size_t nameLen; + char value; + } XMLEntity; - return out; -} + /* This is ugly, but better than specifying the lengths by hand */ + #define _e(str,c) {str,sizeof(str)-1,c} + const XMLEntity ents[] = { + _e("quot;",'"'), _e("apos;",'\''), + _e("lt;", '<'), _e("gt;", '>'), + _e("amp;", '&') + }; + size_t len; + const char *s; + char *out, *o; + + if ( !src || !(len = strlen(src)) || !(out = malloc(len+1)) ) { + return 0; + } + + o = out; + s = src; + while (s <= src+len) /* Make sure the terminator is also copied */ + { + if ( *s == '&' ) { + bool entFound = false; + int i; + + s++; + for ( i = 0; i < sizeof(ents)/sizeof(ents[0]); i++) + { + if ( strncmp(s, ents[i].name, ents[i].nameLen) == 0 ) { + entFound = true; + break; + } + } + if ( entFound ) { + *o++ = ents[i].value; + s += ents[i].nameLen; + + continue; + } + } + + *o++ = *s++; + } + + return out; +} + //#if UNUSED //========================================================================== // XMLParseFile @@ -294,25 +314,25 @@ long XMLParseFile( char * buffer, TagPtr * dict ) { - long length, pos; - TagPtr tag; - pos = 0; + long length, pos; + TagPtr tag; + pos = 0; char *configBuffer; - - int strlength = strlen(buffer); - configBuffer = malloc(strlength+1); - bcopy(buffer, configBuffer, strlength); - configBuffer[strlength] = 0; + int strlength = strlen(buffer); + configBuffer = malloc(strlength+1); + bcopy(buffer, configBuffer, strlength); + configBuffer[strlength] = 0; + buffer_start = configBuffer; while (1) { length = XMLParseNextTag(configBuffer + pos, &tag); if (length == -1) break; - + pos += length; - + if (tag == 0) continue; if (tag->type == kTagTypeDict) break; @@ -335,14 +355,18 @@ { long length, pos; char * tagName; - + length = GetNextTag(buffer, &tagName, 0); - if (length == -1) return -1; - + if (length == -1) { + return -1; + } + pos = length; if (!strncmp(tagName, kXMLTagPList, 6)) { length = 0; + // just a header; nothing to parse + // return-via-reference tag should be left alone } /***** dict ****/ else if (!strcmp(tagName, kXMLTagDict)) @@ -362,7 +386,7 @@ { length = ParseTagKey(buffer + pos, tag); } - + /***** string ****/ else if (!strcmp(tagName, kXMLTagString)) { @@ -431,7 +455,7 @@ //printf("Located IDREF, id = %d, string = %s\n", id, str); } } - + /***** integer ****/ else if (!strcmp(tagName, kXMLTagInteger)) { @@ -518,13 +542,13 @@ { length = ParseTagDate(buffer + pos, tag); } - + /***** date ****/ else if (!strncmp(tagName, kXMLTagDate " ", strlen(kXMLTagDate " "))) { length = ParseTagDate(buffer + pos, tag); } - + /***** false ****/ else if (!strcmp(tagName, kXMLTagFalse)) { @@ -535,7 +559,7 @@ { length = ParseTagBoolean(buffer + pos, tag, kTagTypeTrue); } - + /***** array ****/ else if (!strcmp(tagName, kXMLTagArray)) { @@ -549,16 +573,19 @@ { length = ParseTagList(buffer + pos, tag, kTagTypeArray, 1); } - + /***** unknown ****/ else { + // it wasn't parsed so we consumed no additional characters *tag = 0; length = 0; } - - if (length == -1) return -1; - + + if (length == -1) { + return -1; + } + return pos + length; } @@ -571,46 +598,51 @@ long length, pos; TagPtr tagList, tmpTag; - tagList = 0; - pos = 0; + tagList = 0; + pos = 0; - if (!empty) - { - while (1) - { - length = XMLParseNextTag(buffer + pos, &tmpTag); - if (length == -1) break; + if (!empty) + { + while (1) + { + length = XMLParseNextTag(buffer + pos, &tmpTag); + if (length == -1) { + break; + } - pos += length; + pos += length; - if (tmpTag == 0) break; - tmpTag->tagNext = tagList; - tagList = tmpTag; - } - - if (length == -1) - { - XMLFreeTag(tagList); - return -1; - } - } + // detect end of list + if (tmpTag == 0) { + break; + } + tmpTag->tagNext = tagList; + tagList = tmpTag; + } + + if (length == -1) + { + XMLFreeTag(tagList); + return -1; + } + } - tmpTag = NewTag(); - if (tmpTag == 0) - { - XMLFreeTag(tagList); - return -1; - } + tmpTag = NewTag(); + if (tmpTag == 0) + { + XMLFreeTag(tagList); + return -1; + } - tmpTag->type = type; - tmpTag->string = 0; + tmpTag->type = type; + tmpTag->string = 0; tmpTag->offset = buffer_start ? buffer - buffer_start : 0; - tmpTag->tag = tagList; - tmpTag->tagNext = 0; - - *tag = tmpTag; - - return pos; + tmpTag->tag = tagList; + tmpTag->tagNext = 0; + + *tag = tmpTag; + + return pos; } //========================================================================== @@ -619,40 +651,42 @@ static long ParseTagKey( char * buffer, TagPtr * tag ) { - long length, length2; - char *string; - TagPtr tmpTag, subTag; + long length, length2; + char *string; + TagPtr tmpTag, subTag; - length = FixDataMatchingTag(buffer, kXMLTagKey); - if (length == -1) return -1; + length = FixDataMatchingTag(buffer, kXMLTagKey); + if (length == -1) { + return -1; + } - length2 = XMLParseNextTag(buffer + length, &subTag); - if (length2 == -1) return -1; + length2 = XMLParseNextTag(buffer + length, &subTag); + if (length2 == -1) { + return -1; + } + + tmpTag = NewTag(); + if (tmpTag == 0) { + XMLFreeTag(subTag); + return -1; + } - tmpTag = NewTag(); - if (tmpTag == 0) - { - XMLFreeTag(subTag); - return -1; - } + string = NewSymbol(buffer); + if (string == 0) { + XMLFreeTag(subTag); + XMLFreeTag(tmpTag); + return -1; + } - string = NewSymbol(buffer); - if (string == 0) - { - XMLFreeTag(subTag); - XMLFreeTag(tmpTag); - return -1; - } - - tmpTag->type = kTagTypeKey; - tmpTag->string = string; - tmpTag->tag = subTag; + tmpTag->type = kTagTypeKey; + tmpTag->string = string; + tmpTag->tag = subTag; tmpTag->offset = buffer_start ? buffer - buffer_start: 0; - tmpTag->tagNext = 0; + tmpTag->tagNext = 0; - *tag = tmpTag; + *tag = tmpTag; - return length + length2; + return length + length2; } //========================================================================== @@ -661,30 +695,33 @@ static long ParseTagString( char * buffer, TagPtr * tag ) { - long length; - char * string; + long length; + char * string; - length = FixDataMatchingTag(buffer, kXMLTagString); - if (length == -1) return -1; + length = FixDataMatchingTag(buffer, kXMLTagString); + if (length == -1) { + return -1; + } TagPtr tmpTag = NewTag(); - if (tmpTag == 0) return -1; + if (tmpTag == 0) { + return -1; + } - string = NewSymbol(buffer); - if (string == 0) - { - XMLFreeTag(tmpTag); - return -1; - } + string = NewSymbol(buffer); + if (string == 0) { + XMLFreeTag(tmpTag); + return -1; + } - tmpTag->type = kTagTypeString; - tmpTag->string = string; - tmpTag->tag = 0; + tmpTag->type = kTagTypeString; + tmpTag->string = string; + tmpTag->tag = 0; tmpTag->offset = buffer_start ? buffer - buffer_start: 0; - tmpTag->tagNext = 0; - - *tag = tmpTag; - return length; + tmpTag->tagNext = 0; + + *tag = tmpTag; + return length; } //========================================================================== @@ -693,11 +730,11 @@ static long ParseTagInteger( char * buffer, TagPtr * tag ) { - long length, integer; + long length, integer; bool negative = false; - TagPtr tmpTag; + TagPtr tmpTag; char* val = buffer; - int size; + int size; if(buffer[0] == '<') { @@ -715,14 +752,14 @@ return 0; } - size = length = FixDataMatchingTag(buffer, kXMLTagInteger); - if (length == -1) return -1; - - tmpTag = NewTag(); - if (tmpTag == 0) return -1; - - integer = 0; + size = length = FixDataMatchingTag(buffer, kXMLTagInteger); + if (length == -1) return -1; + tmpTag = NewTag(); + if (tmpTag == 0) return -1; + + integer = 0; + if(size > 1 && (val[1] == 'x' || val[1] == 'X')) // Hex value { val += 2; @@ -744,7 +781,7 @@ { printf("ParseTagInteger hex error (0x%x) in buffer %s\n", *val, buffer); getchar(); - XMLFreeTag(tmpTag); + XMLFreeTag(tmpTag); return -1; } } @@ -776,16 +813,16 @@ if (negative) integer = -integer; } - - tmpTag->type = kTagTypeInteger; + + tmpTag->type = kTagTypeInteger; tmpTag->string = (char *)integer; tmpTag->tag = 0; tmpTag->offset = buffer_start ? buffer - buffer_start: 0; - tmpTag->tagNext = 0; - - *tag = tmpTag; - - return length; + tmpTag->tagNext = 0; + + *tag = tmpTag; + + return length; } //========================================================================== @@ -794,30 +831,30 @@ static long ParseTagData( char * buffer, TagPtr * tag ) { - int actuallen = 0; - long length; - TagPtr tmpTag; + int actuallen = 0; + long length; + TagPtr tmpTag; - length = FixDataMatchingTag(buffer, kXMLTagData); - if (length == -1) return -1; - - tmpTag = NewTag(); - if (tmpTag == 0) return -1; - + length = FixDataMatchingTag(buffer, kXMLTagData); + if (length == -1) return -1; + + tmpTag = NewTag(); + if (tmpTag == 0) return -1; + //printf("ParseTagData unimplimented\n"); //printf("Data: %s\n", buffer); // getchar(); char* string = BASE64Decode(buffer, strlen(buffer), &actuallen); - tmpTag->type = kTagTypeData; - tmpTag->string = string; - tmpTag->tag = 0; + tmpTag->type = kTagTypeData; + tmpTag->string = string; + tmpTag->tag = 0; tmpTag->offset = actuallen; // buffer_start ? buffer - buffer_start: 0; - tmpTag->tagNext = 0; - - *tag = tmpTag; - - return length; + tmpTag->tagNext = 0; + + *tag = tmpTag; + + return length; } //========================================================================== @@ -826,27 +863,27 @@ static long ParseTagDate( char * buffer, TagPtr * tag ) { - long length; - TagPtr tmpTag; - - length = FixDataMatchingTag(buffer, kXMLTagDate); - if (length == -1) return -1; - - tmpTag = NewTag(); - if (tmpTag == 0) return -1; - + long length; + TagPtr tmpTag; + + length = FixDataMatchingTag(buffer, kXMLTagDate); + if (length == -1) return -1; + + tmpTag = NewTag(); + if (tmpTag == 0) return -1; + printf("ParseTagDate unimplimented\n"); getchar(); - - tmpTag->type = kTagTypeDate; - tmpTag->string = 0; - tmpTag->tag = 0; + + tmpTag->type = kTagTypeDate; + tmpTag->string = 0; + tmpTag->tag = 0; tmpTag->offset = buffer_start ? buffer - buffer_start: 0; - tmpTag->tagNext = 0; - - *tag = tmpTag; - - return length; + tmpTag->tagNext = 0; + + *tag = tmpTag; + + return length; } //========================================================================== @@ -855,20 +892,20 @@ long ParseTagBoolean( char * buffer, TagPtr * tag, long type ) { - TagPtr tmpTag; - - tmpTag = NewTag(); - if (tmpTag == 0) return -1; - - tmpTag->type = type; - tmpTag->string = 0; - tmpTag->tag = 0; + TagPtr tmpTag; + + tmpTag = NewTag(); + if (tmpTag == 0) return -1; + + tmpTag->type = type; + tmpTag->string = 0; + tmpTag->tag = 0; tmpTag->offset = buffer_start ? buffer - buffer_start: 0; - tmpTag->tagNext = 0; - - *tag = tmpTag; - - return 0; + tmpTag->tagNext = 0; + + *tag = tmpTag; + + return 0; } //========================================================================== @@ -877,26 +914,25 @@ static long GetNextTag( char * buffer, char ** tag, long * start ) { - long cnt, cnt2; + long cnt, cnt2; - if (tag == 0) return -1; - - // Find the start of the tag. - cnt = 0; - while ((buffer[cnt] != '\0') && (buffer[cnt] != '<')) cnt++; - if (buffer[cnt] == '\0') return -1; - - // Find the end of the tag. - cnt2 = cnt + 1; - while ((buffer[cnt2] != '\0') && (buffer[cnt2] != '>')) cnt2++; - if (buffer[cnt2] == '\0') return -1; + if (tag == 0) return -1; - // Fix the tag data. - *tag = buffer + cnt + 1; - buffer[cnt2] = '\0'; - if (start) *start = cnt; - - return cnt2 + 1; +// Find the start of the tag. + cnt = 0; + while ((buffer[cnt] != '\0') && (buffer[cnt] != '<')) cnt++; + if (buffer[cnt] == '\0') return -1; + // Find the end of the tag. + cnt2 = cnt + 1; + while ((buffer[cnt2] != '\0') && (buffer[cnt2] != '>')) cnt2++; + if (buffer[cnt2] == '\0') return -1; + + // Fix the tag data. + *tag = buffer + cnt + 1; + buffer[cnt2] = '\0'; + if (start) *start = cnt; + + return cnt2 + 1; } //========================================================================== @@ -970,22 +1006,28 @@ XMLFreeTag( TagPtr tag ) { #if DOFREE - if (tag == 0) return; + if (tag == 0) + { + return; + } - if (!XMLIsInteger(tag) && tag->string) FreeSymbol(tag->string); + if (!XMLIsInteger(tag) && tag->string) + { + FreeSymbol(tag->string); + } + + XMLFreeTag(tag->tag); + XMLFreeTag(tag->tagNext); - XMLFreeTag(tag->tag); - XMLFreeTag(tag->tagNext); - - // Clear and free the tag. - tag->type = kTagTypeNone; - tag->string = 0; - tag->tag = 0; + // Clear and free the tag. + tag->type = kTagTypeNone; + tag->string = 0; + tag->tag = 0; tag->offset = 0; - tag->tagNext = gTagsFree; - gTagsFree = tag; + tag->tagNext = gTagsFree; + gTagsFree = tag; #else - return; + return; #endif } @@ -994,9 +1036,9 @@ struct Symbol { - long refCount; - struct Symbol *next; - char string[]; + long refCount; + struct Symbol *next; + char string[]; }; typedef struct Symbol Symbol, *SymbolPtr; @@ -1010,33 +1052,39 @@ static char * NewSymbol( char * string ) { -static SymbolPtr lastGuy = 0; + static SymbolPtr lastGuy = 0; SymbolPtr symbol; - - // Look for string in the list of symbols. - symbol = FindSymbol(string, 0); - + + // Look for string in the list of symbols. + symbol = FindSymbol(string, 0); + // Add the new symbol. - if (symbol == 0) - { - symbol = (SymbolPtr)malloc(sizeof(Symbol) + 1 + strlen(string)); - if (symbol == 0) //return 0; - stop("NULL symbol!"); - - // Set the symbol's data. - symbol->refCount = 0; - strcpy(symbol->string, string); - - // Add the symbol to the list. - symbol->next = gSymbolsHead; - gSymbolsHead = symbol; - } - - // Update the refCount and return the string. - symbol->refCount++; + if (symbol == 0) + { + symbol = (SymbolPtr)malloc(sizeof(Symbol) + 1 + strlen(string)); + if (symbol == 0) //return 0; + { + stop("NULL symbol!"); + } - if (lastGuy && lastGuy->next != 0) stop("last guy not last!"); - return symbol->string; + // Set the symbol's data. + symbol->refCount = 0; + strcpy(symbol->string, string); + + // Add the symbol to the list. + symbol->next = gSymbolsHead; + gSymbolsHead = symbol; + } + + // Update the refCount and return the string. + symbol->refCount++; + + if (lastGuy && lastGuy->next != 0) + { + stop("last guy not last!"); + } + + return symbol->string; } //========================================================================== @@ -1046,24 +1094,36 @@ static void FreeSymbol( char * string ) { - SymbolPtr symbol, prev; + SymbolPtr symbol, prev; prev = 0; - - // Look for string in the list of symbols. - symbol = FindSymbol(string, &prev); - if (symbol == 0) return; - - // Update the refCount. - symbol->refCount--; - - if (symbol->refCount != 0) return; - - // Remove the symbol from the list. - if (prev != 0) prev->next = symbol->next; - else gSymbolsHead = symbol->next; - - // Free the symbol's memory. - free(symbol); + + // Look for string in the list of symbols. + symbol = FindSymbol(string, &prev); + if (symbol == 0) + { + return; + } + + // Update the refCount. + symbol->refCount--; + + if (symbol->refCount != 0) + { + return; + } + + // Remove the symbol from the list. + if (prev != 0) + { + prev->next = symbol->next; + } + else + { + gSymbolsHead = symbol->next; + } + + // Free the symbol's memory. + free(symbol); } #endif @@ -1073,40 +1133,60 @@ static SymbolPtr FindSymbol( char * string, SymbolPtr * prevSymbol ) { - SymbolPtr symbol, prev; + SymbolPtr symbol, prev; - symbol = gSymbolsHead; - prev = 0; + symbol = gSymbolsHead; + prev = 0; - while (symbol != 0) { - if (!strcmp(symbol->string, string)) break; + while (symbol != 0) + { + if (!strcmp(symbol->string, string)) + { + break; + } - prev = symbol; - symbol = symbol->next; - } + prev = symbol; + symbol = symbol->next; + } - if ((symbol != 0) && (prevSymbol != 0)) *prevSymbol = prev; - - return symbol; + if ((symbol != 0) && (prevSymbol != 0)) + { + *prevSymbol = prev; + } + + return symbol; } bool XMLIsType(TagPtr dict, enum xmltype type) { - if(!dict) return (type == kTagTypeNone); + if(!dict) + { + return (type == kTagTypeNone); + } return (dict->type == type); } /*** Cast functions ***/ bool XMLIsArray(TagPtr entry) { - return entry && (entry->type == kTagTypeArray); + return entry && (entry->type == kTagTypeArray); } TagPtr XMLCastArray(TagPtr dict) { - if(!dict) return NULL; - if(dict->type == kTagTypeArray) return dict; - else return NULL; + if(!dict) + { + return NULL; + } + + if(dict->type == kTagTypeArray) + { + return dict; + } + else + { + return NULL; + } } bool XMLIsDict(TagPtr entry) @@ -1116,43 +1196,58 @@ bool XMLIsData(TagPtr entry) { - return entry && (entry->type == kTagTypeData); + return entry && (entry->type == kTagTypeData); } TagPtr XMLCastDict(TagPtr dict) { - if(!dict) return NULL; - if(dict->type == kTagTypeDict) return dict; - else return NULL; + if(!dict) + { + return NULL; + } + + if(dict->type == kTagTypeDict) + { + return dict; + } + else + { + return NULL; + } } bool XMLIsString(TagPtr entry) { - return entry && - ((entry->type == kTagTypeString) || - (entry->type == kTagTypeKey)); + return entry && ((entry->type == kTagTypeString) || (entry->type == kTagTypeKey)); } char* XMLCastString(TagPtr dict) { - if(!dict) return NULL; + if(!dict) + { + return NULL; + } - if((dict->type == kTagTypeString) || - (dict->type == kTagTypeKey)) return dict->string; - + if((dict->type == kTagTypeString) || (dict->type == kTagTypeKey)) + { + return dict->string; + } + return NULL; } char* XMLCastData(TagPtr dict, int* length) { - if(!dict) return NULL; - - if((dict->type == kTagTypeData) || - (dict->type == kTagTypeKey)) - { - *length = dict->offset; - return dict->string; - } + if(!dict) + { + return NULL; + } + + if((dict->type == kTagTypeData) || (dict->type == kTagTypeKey)) + { + *length = dict->offset; + return dict->string; + } *length = 0; return NULL; } @@ -1160,9 +1255,7 @@ long XMLCastStringOffset(TagPtr dict) { - if(dict && - ((dict->type == kTagTypeString) || - (dict->type == kTagTypeKey))) + if(dict && ((dict->type == kTagTypeString) || (dict->type == kTagTypeKey))) { return dict->offset; } @@ -1174,15 +1267,21 @@ bool XMLIsBoolean(TagPtr entry) { - return entry && - ((entry->type == kTagTypeTrue) || - (entry->type == kTagTypeFalse)); + return entry && ((entry->type == kTagTypeTrue) || (entry->type == kTagTypeFalse)); } bool XMLCastBoolean(TagPtr dict) { - if(!dict) return false; - if(dict->type == kTagTypeTrue) return true; + if(!dict) + { + return false; + } + + if(dict->type == kTagTypeTrue) + { + return true; + } + return false; } @@ -1198,50 +1297,57 @@ //printf("XMLCastInteger: null dict\n"); return 0; } - if(dict->type == kTagTypeInteger) return (int)(dict->string); + if(dict->type == kTagTypeInteger) + { + return (int)(dict->string); + } + return 0; } bool XMLAddTagToDictionary(TagPtr dict, char* key, TagPtr value) { - if (!dict || dict->type != kTagTypeDict) return false; + if (!dict || dict->type != kTagTypeDict) + { + return false; + } - TagPtr tmpTag; - char* string; + TagPtr tmpTag; + char* string; - tmpTag = NewTag(); - if (tmpTag == 0) - { - return false; - } - - string = NewSymbol(key); - if (string == 0) - { - XMLFreeTag(tmpTag); - return false; - } - - tmpTag->type = kTagTypeKey; - tmpTag->string = string; - tmpTag->tag = value; + tmpTag = NewTag(); + if (tmpTag == 0) + { + return false; + } + + string = NewSymbol(key); + if (string == 0) + { + XMLFreeTag(tmpTag); + return false; + } + + tmpTag->type = kTagTypeKey; + tmpTag->string = string; + tmpTag->tag = value; tmpTag->offset = 0; - tmpTag->tagNext = 0; - - TagPtr tagList = dict->tag; - if(!tagList) - { - // First tag - dict->tag = tmpTag; - return true; - } - while(tagList && tagList->tagNext) tagList = tagList->tagNext; - if(tagList) - { - tagList->tagNext = tmpTag; - return true; - } + tmpTag->tagNext = 0; - XMLFreeTag(tmpTag); - return false; + TagPtr tagList = dict->tag; + if(!tagList) + { + // First tag + dict->tag = tmpTag; + return true; + } + while(tagList && tagList->tagNext) tagList = tagList->tagNext; + if(tagList) + { + tagList->tagNext = tmpTag; + return true; + } + + XMLFreeTag(tmpTag); + return false; } Index: trunk/i386/libsaio/asm.s =================================================================== --- trunk/i386/libsaio/asm.s (revision 2326) +++ trunk/i386/libsaio/asm.s (revision 2327) @@ -82,7 +82,7 @@ * New boot0 (boot1 has been deprecated). Booter must now reside in its own partition, no disk label required. * * Revision 1.1.1.2 1999/08/04 21:16:57 wsanchez - * Impoort of boot-66 + * Import of boot-66 * * Revision 1.3 1999/08/04 21:12:12 wsanchez * Update APSL @@ -348,7 +348,7 @@ push %ebp mov %esp, %ebp - mov 0xc(%ebp), %eax // argument to program + mov 0xc(%ebp), %eax // argument to program - bootargs to mach_kernel mov 0x8(%ebp), %ecx // entry offset mov $0x28, %ebx // segment push %ebx Index: trunk/i386/libsaio/console.c =================================================================== --- trunk/i386/libsaio/console.c (revision 2326) +++ trunk/i386/libsaio/console.c (revision 2327) @@ -50,8 +50,8 @@ extern int vprf(const char * fmt, va_list ap); -bool gVerboseMode; -bool gErrors; +bool gVerboseMode = false; +bool gErrors = false; /* * Azi: Doubled available log size; this seems to fix some hangs and instant reboots caused by @@ -69,8 +69,8 @@ struct putc_info //Azi: exists on gui.c & printf.c { - char * str; - char * last_str; + char * str; + char * last_str; }; static int @@ -83,7 +83,7 @@ return 0; } *(pi->str)++ = c; - return c; + return c; } void initBooterLog(void) @@ -99,11 +99,13 @@ va_list ap; struct putc_info pi; - if (!msgbuf) + if (!msgbuf) { return; + } - if (((cursor - msgbuf) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) + if (((cursor - msgbuf) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) { return; + } va_start(ap, fmt); pi.str = cursor; @@ -115,8 +117,9 @@ void setupBooterLog(void) { - if (!msgbuf) + if (!msgbuf) { return; + } Node *node = DT__FindNode("/", false); if (node) @@ -129,30 +132,29 @@ */ int putchar(int c) { - if ( c == '\t' ) - { + if ( c == '\t' ) { for (c = 0; c < 8; c++) bios_putchar(' '); return c; } - if ( c == '\n' ) - { + if ( c == '\n' ) { bios_putchar('\r'); - } + } bios_putchar(c); - return c; + return c; } int getc() { - int c = bgetc(); + int c = bgetc(); - if ((c & 0xff) == 0) - return c; - else - return (c & 0xff); + if ((c & 0xff) == 0) { + return c; + } else { + return (c & 0xff); + } } // Read and echo a character from console. This doesn't echo backspace @@ -165,28 +167,31 @@ // if ( c == '\r' ) c = '\n'; // if ( c >= ' ' && c < 0x7f) putchar(c); - + return (c); } int printf(const char * fmt, ...) { - va_list ap; + va_list ap; va_start(ap, fmt); - if (bootArgs->Video.v_display == VGA_TEXT_MODE) + if (bootArgs->Video.v_display == VGA_TEXT_MODE) { prf(fmt, ap, putchar, 0); - else + } else { vprf(fmt, ap); + } { // Kabyl: BooterLog struct putc_info pi; - if (!msgbuf) + if (!msgbuf) { return 0; + } - if (((cursor - msgbuf) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) + if (((cursor - msgbuf) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) { return 0; + } pi.str = cursor; pi.last_str = 0; prf(fmt, ap, sputc, &pi); @@ -194,52 +199,55 @@ } va_end(ap); - return 0; + return 0; } int verbose(const char * fmt, ...) { - va_list ap; + va_list ap; va_start(ap, fmt); - if (gVerboseMode) - { - if (bootArgs->Video.v_display == VGA_TEXT_MODE) + if (gVerboseMode) { + if (bootArgs->Video.v_display == VGA_TEXT_MODE) { prf(fmt, ap, putchar, 0); - else + } else { vprf(fmt, ap); - } + } + } { // Kabyl: BooterLog struct putc_info pi; - if (!msgbuf) + if (!msgbuf) { return 0; + } - if (((cursor - msgbuf) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) + if (((cursor - msgbuf) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) { return 0; + } pi.str = cursor; pi.last_str = 0; prf(fmt, ap, sputc, &pi); cursor += strlen((char *)cursor); } - va_end(ap); - return(0); + va_end(ap); + return(0); } int error(const char * fmt, ...) { - va_list ap; - gErrors = true; - va_start(ap, fmt); - if (bootArgs->Video.v_display == VGA_TEXT_MODE) + va_list ap; + gErrors = true; + va_start(ap, fmt); + if (bootArgs->Video.v_display == VGA_TEXT_MODE) { prf(fmt, ap, putchar, 0); - else + } else { vprf(fmt, ap); + } va_end(ap); - return(0); + return(0); } void stop(const char * fmt, ...) Index: trunk/i386/libsaio/xml.h =================================================================== --- trunk/i386/libsaio/xml.h (revision 2326) +++ trunk/i386/libsaio/xml.h (revision 2327) @@ -26,16 +26,16 @@ #define __LIBSAIO_XML_H enum xmltype { - kTagTypeNone = 0, - kTagTypeDict, - kTagTypeKey, - kTagTypeString, - kTagTypeInteger, - kTagTypeData, - kTagTypeDate, - kTagTypeFalse, - kTagTypeTrue, - kTagTypeArray + kTagTypeNone = 0, + kTagTypeDict, + kTagTypeKey, + kTagTypeString, + kTagTypeInteger, + kTagTypeData, + kTagTypeDate, + kTagTypeFalse, + kTagTypeTrue, + kTagTypeArray }; struct string_ref @@ -48,20 +48,21 @@ extern string_ref* ref_strings; -#define kXMLTagPList "plist " -#define kXMLTagDict "dict" -#define kXMLTagKey "key" -#define kXMLTagString "string" -#define kXMLTagInteger "integer" -#define kXMLTagData "data" -#define kXMLTagDate "date" -#define kXMLTagFalse "false/" -#define kXMLTagTrue "true/" -#define kXMLTagArray "array" +#define kXMLTagPList "plist " +#define kXMLTagDict "dict" +#define kXMLTagKey "key" +#define kXMLTagString "string" +#define kXMLTagInteger "integer" +#define kXMLTagData "data" +#define kXMLTagDate "date" +#define kXMLTagFalse "false/" +#define kXMLTagTrue "true/" +#define kXMLTagArray "array" +// for back-references used by libkern serializer +#define kXMLTagReference "reference" +#define kXMLStringID "ID=" +#define kXMLStringIDRef "IDREF=" -#define kXMLStringID "ID=" -#define kXMLStringIDRef "IDREF=" - #define kPropCFBundleIdentifier ("CFBundleIdentifier") #define kPropCFBundleExecutable ("CFBundleExecutable") #define kPropOSBundleRequired ("OSBundleRequired") @@ -71,10 +72,10 @@ /* struct Tag { - long type; - char *string; - struct Tag *tag; - struct Tag *tagNext; + long type; + char *string; + struct Tag *tag; + struct Tag *tagNext; }; typedef struct Tag Tag, *TagPtr; */ Index: trunk/i386/libsaio/efi.h =================================================================== --- trunk/i386/libsaio/efi.h (revision 2326) +++ trunk/i386/libsaio/efi.h (revision 2327) @@ -71,9 +71,8 @@ */ -// // Modifiers for EFI Runtime and Boot Services -// + #define EFI_RUNTIMESERVICE #define EFIAPI #define IN @@ -82,9 +81,7 @@ #define EFI_MAX_BIT 0x80000000 -// // Set the upper bit to indicate EFI Error. -// #define EFIERR(a) (EFI_MAX_BIT | (a)) #define EFIWARN(a) (a) @@ -118,11 +115,16 @@ #define EFI_INCOMPATIBLE_VERSION EFIERR (25) #define EFI_SECURITY_VIOLATION EFIERR (26) #define EFI_CRC_ERROR EFIERR (27) +#define EFI_END_OF_MEDIA EFIERR (28) +#define EFI_END_OF_FILE EFIERR (31) +#define EFI_INVALID_LANGUAGE EFIERR (32) +#define EFI_COMPROMISED_DATA EFIERR (33) #define EFI_WARN_UNKNOWN_GLYPH EFIWARN (1) #define EFI_WARN_DELETE_FAILURE EFIWARN (2) #define EFI_WARN_WRITE_FAILURE EFIWARN (3) #define EFI_WARN_BUFFER_TOO_SMALL EFIWARN (4) +#define EFI_WARN_STALE_DATA EFIWARN (5) // // EFI Specification Revision information @@ -141,7 +143,7 @@ {0xAC39C713, 0x7E50, 0x423D, {0x88, 0x9D, 0x27,0x8F, 0xCC, 0x34, 0x22, 0xB6} } #define EFI_GLOBAL_VARIABLE_GUID \ - {0x8BE4DF61, 0x93CA, 0x11d2, {0xAA, 0x0D, 0x00, 0xE0, 0x98, 0x03, 0x2B, 0x8C} } + {0x8BE4DF61, 0x93CA, 0x11D2, {0xAA, 0x0D, 0x00, 0xE0, 0x98, 0x03, 0x2B, 0x8C} } typedef union { EFI_GUID Guid; @@ -160,75 +162,74 @@ // TimeZone: -1440 to 1440 or 2047 // typedef struct { - EFI_UINT16 Year; - EFI_UINT8 Month; - EFI_UINT8 Day; - EFI_UINT8 Hour; - EFI_UINT8 Minute; - EFI_UINT8 Second; - EFI_UINT8 Pad1; - EFI_UINT32 Nanosecond; - EFI_INT16 TimeZone; - EFI_UINT8 Daylight; - EFI_UINT8 Pad2; + EFI_UINT16 Year; + EFI_UINT8 Month; + EFI_UINT8 Day; + EFI_UINT8 Hour; + EFI_UINT8 Minute; + EFI_UINT8 Second; + EFI_UINT8 Pad1; + EFI_UINT32 Nanosecond; + EFI_INT16 TimeZone; + EFI_UINT8 Daylight; + EFI_UINT8 Pad2; } EFI_TIME; -// + // Bit definitions for EFI_TIME.Daylight -// + #define EFI_TIME_ADJUST_DAYLIGHT 0x01 #define EFI_TIME_IN_DAYLIGHT 0x02 -// + // Value definition for EFI_TIME.TimeZone -// + #define EFI_UNSPECIFIED_TIMEZONE 0x07FF typedef enum { - EfiReservedMemoryType, - EfiLoaderCode, - EfiLoaderData, - EfiBootServicesCode, - EfiBootServicesData, - EfiRuntimeServicesCode, - EfiRuntimeServicesData, - EfiConventionalMemory, - EfiUnusableMemory, - EfiACPIReclaimMemory, - EfiACPIMemoryNVS, - EfiMemoryMappedIO, - EfiMemoryMappedIOPortSpace, - EfiPalCode, - EfiMaxMemoryType + EfiReservedMemoryType, + EfiLoaderCode, + EfiLoaderData, + EfiBootServicesCode, + EfiBootServicesData, + EfiRuntimeServicesCode, + EfiRuntimeServicesData, + EfiConventionalMemory, + EfiUnusableMemory, + EfiACPIReclaimMemory, + EfiACPIMemoryNVS, + EfiMemoryMappedIO, + EfiMemoryMappedIOPortSpace, + EfiPalCode, + EfiMaxMemoryType } EFI_MEMORY_TYPE; typedef struct { - EFI_UINT64 Signature; - EFI_UINT32 Revision; - EFI_UINT32 HeaderSize; - EFI_UINT32 CRC32; - EFI_UINT32 Reserved; + EFI_UINT64 Signature; + EFI_UINT32 Revision; + EFI_UINT32 HeaderSize; + EFI_UINT32 CRC32; + EFI_UINT32 Reserved; } __attribute__((aligned(8))) EFI_TABLE_HEADER; -// // possible caching types for the memory range -// + #define EFI_MEMORY_UC 0x0000000000000001ULL #define EFI_MEMORY_WC 0x0000000000000002ULL #define EFI_MEMORY_WT 0x0000000000000004ULL #define EFI_MEMORY_WB 0x0000000000000008ULL #define EFI_MEMORY_UCE 0x0000000000000010ULL -// + // physical memory protection on range -// + #define EFI_MEMORY_WP 0x0000000000001000ULL #define EFI_MEMORY_RP 0x0000000000002000ULL #define EFI_MEMORY_XP 0x0000000000004000ULL -// + // range requires a runtime mapping -// + #define EFI_MEMORY_RUNTIME 0x8000000000000000ULL typedef EFI_UINT64 EFI_PHYSICAL_ADDRESS; @@ -236,12 +237,12 @@ #define EFI_MEMORY_DESCRIPTOR_VERSION 1 typedef struct { - EFI_UINT32 Type; - EFI_UINT32 Pad; - EFI_PHYSICAL_ADDRESS PhysicalStart; - EFI_VIRTUAL_ADDRESS VirtualStart; - EFI_UINT64 NumberOfPages; - EFI_UINT64 Attribute; + EFI_UINT32 Type; + EFI_UINT32 Pad; + EFI_PHYSICAL_ADDRESS PhysicalStart; + EFI_VIRTUAL_ADDRESS VirtualStart; + EFI_UINT64 NumberOfPages; + EFI_UINT64 Attribute; } __attribute__((aligned(8))) EFI_MEMORY_DESCRIPTOR; @@ -263,9 +264,9 @@ IN OUT VOID **Address ) __attribute__((regparm(0))); -// + // Variable attributes -// + #define EFI_VARIABLE_NON_VOLATILE 0x00000001 #define EFI_VARIABLE_BOOTSERVICE_ACCESS 0x00000002 #define EFI_VARIABLE_RUNTIME_ACCESS 0x00000004 @@ -302,13 +303,13 @@ IN VOID * Data ) __attribute__((regparm(0))); -// + // EFI Time -// + typedef struct { - EFI_UINT32 Resolution; - EFI_UINT32 Accuracy; - EFI_BOOLEAN SetsToZero; + EFI_UINT32 Resolution; + EFI_UINT32 Accuracy; + EFI_BOOLEAN SetsToZero; } __attribute__((aligned(4))) EFI_TIME_CAPABILITIES; typedef @@ -371,18 +372,14 @@ OUT EFI_UINT32 * HighCount ) __attribute__((regparm(0))); -// // Definition of Status Code extended data header -// -// HeaderSize The size of the architecture. This is specified to enable -// the future expansion -// -// Size The size of the data in bytes. This does not include the size -// of the header structure. -// + +// HeaderSize The size of the architecture. This is specified to enable the future expansion + +// Size The size of the data in bytes. This does not include the size of the header structure. + // Type A GUID defining the type of the data -// -// + #ifdef TIANO_EXTENSION_FLAG typedef @@ -404,83 +401,74 @@ #define EFI_RUNTIME_SERVICES_REVISION ((EFI_SPECIFICATION_MAJOR_REVISION << 16) | (EFI_SPECIFICATION_MINOR_REVISION)) typedef struct { - EFI_TABLE_HEADER Hdr; + EFI_TABLE_HEADER Hdr; - // - // Time services - // - EFI_PTR32 GetTime; - EFI_PTR32 SetTime; - EFI_PTR32 GetWakeupTime; - EFI_PTR32 SetWakeupTime; + // Time Services + EFI_PTR32 GetTime; + EFI_PTR32 SetTime; + EFI_PTR32 GetWakeupTime; + EFI_PTR32 SetWakeupTime; - // - // Virtual memory services - // - EFI_PTR32 SetVirtualAddressMap; - EFI_PTR32 ConvertPointer; + // Virtual Memory Services - // - // Variable services - // - EFI_PTR32 GetVariable; - EFI_PTR32 GetNextVariableName; - EFI_PTR32 SetVariable; + EFI_PTR32 SetVirtualAddressMap; + EFI_PTR32 ConvertPointer; - // - // Misc - // - EFI_PTR32 GetNextHighMonotonicCount; - EFI_PTR32 ResetSystem; + // Variable Services + EFI_PTR32 GetVariable; + EFI_PTR32 GetNextVariableName; + EFI_PTR32 SetVariable; + + // Miscellaneous Services + EFI_PTR32 GetNextHighMonotonicCount; + EFI_PTR32 ResetSystem; + #ifdef TIANO_EXTENSION_FLAG - // - // //////////////////////////////////////////////////// - // Extended EFI Services - ////////////////////////////////////////////////////// - // - EFI_PTR32 ReportStatusCode; + + // //////////////////////////////////////////////////// + // Extended EFI Services + ////////////////////////////////////////////////////// + + EFI_PTR32 ReportStatusCode; #endif } __attribute__((aligned(8))) EFI_RUNTIME_SERVICES_32; typedef struct { - EFI_TABLE_HEADER Hdr; + EFI_TABLE_HEADER Hdr; - // - // Time services - // - EFI_PTR64 GetTime; - EFI_PTR64 SetTime; - EFI_PTR64 GetWakeupTime; - EFI_PTR64 SetWakeupTime; - // - // Virtual memory services - // - EFI_PTR64 SetVirtualAddressMap; - EFI_PTR64 ConvertPointer; + // Time services - // - // Variable services - // - EFI_PTR64 GetVariable; - EFI_PTR64 GetNextVariableName; - EFI_PTR64 SetVariable; + EFI_PTR64 GetTime; + EFI_PTR64 SetTime; + EFI_PTR64 GetWakeupTime; + EFI_PTR64 SetWakeupTime; - // - // Misc - // - EFI_PTR64 GetNextHighMonotonicCount; - EFI_PTR64 ResetSystem; + // Virtual memory services + EFI_PTR64 SetVirtualAddressMap; + EFI_PTR64 ConvertPointer; + + // Variable services + + EFI_PTR64 GetVariable; + EFI_PTR64 GetNextVariableName; + EFI_PTR64 SetVariable; + + // Misc + + EFI_PTR64 GetNextHighMonotonicCount; + EFI_PTR64 ResetSystem; + #ifdef TIANO_EXTENSION_FLAG - // - // //////////////////////////////////////////////////// - // Extended EFI Services - ////////////////////////////////////////////////////// - // - EFI_PTR64 ReportStatusCode; + + // //////////////////////////////////////////////////// + // Extended EFI Services + ////////////////////////////////////////////////////// + + EFI_PTR64 ReportStatusCode; #endif } __attribute__((aligned(8))) EFI_RUNTIME_SERVICES_64; @@ -489,18 +477,18 @@ // EFI Configuration Table // typedef struct { - EFI_GUID VendorGuid; - EFI_PTR32 VendorTable; + EFI_GUID VendorGuid; + EFI_PTR32 VendorTable; } EFI_CONFIGURATION_TABLE_32; typedef struct { - EFI_GUID VendorGuid; - EFI_PTR64 VendorTable; + EFI_GUID VendorGuid; + EFI_PTR64 VendorTable; } __attribute__((aligned(8))) EFI_CONFIGURATION_TABLE_64; -// + // EFI System Table -// + #define EFI_SYSTEM_TABLE_SIGNATURE 0x5453595320494249ULL #define EFI_SYSTEM_TABLE_REVISION ((EFI_SPECIFICATION_MAJOR_REVISION << 16) | (EFI_SPECIFICATION_MINOR_REVISION)) #define EFI_2_00_SYSTEM_TABLE_REVISION ((2 << 16) | 00) @@ -508,51 +496,49 @@ #define EFI_1_10_SYSTEM_TABLE_REVISION ((1 << 16) | 10) typedef struct EFI_SYSTEM_TABLE_32 { - EFI_TABLE_HEADER Hdr; + EFI_TABLE_HEADER Hdr; - EFI_PTR32 FirmwareVendor; - EFI_UINT32 FirmwareRevision; + EFI_PTR32 FirmwareVendor; + EFI_UINT32 FirmwareRevision; - EFI_HANDLE32 ConsoleInHandle; - EFI_PTR32 ConIn; + EFI_HANDLE32 ConsoleInHandle; + EFI_PTR32 ConIn; - EFI_HANDLE32 ConsoleOutHandle; - EFI_PTR32 ConOut; + EFI_HANDLE32 ConsoleOutHandle; + EFI_PTR32 ConOut; - EFI_HANDLE32 StandardErrorHandle; - EFI_PTR32 StdErr; + EFI_HANDLE32 StandardErrorHandle; + EFI_PTR32 StdErr; - EFI_PTR32 RuntimeServices; - EFI_PTR32 BootServices; + EFI_PTR32 RuntimeServices; + EFI_PTR32 BootServices; - EFI_UINT32 NumberOfTableEntries; - EFI_PTR32 ConfigurationTable; + EFI_UINT32 NumberOfTableEntries; + EFI_PTR32 ConfigurationTable; } __attribute__((aligned(8))) EFI_SYSTEM_TABLE_32; typedef struct EFI_SYSTEM_TABLE_64 { - EFI_TABLE_HEADER Hdr; + EFI_TABLE_HEADER Hdr; - EFI_PTR64 FirmwareVendor; - EFI_UINT32 FirmwareRevision; + EFI_PTR64 FirmwareVendor; + EFI_UINT32 FirmwareRevision; - EFI_UINT32 __pad; + EFI_UINT32 __pad; + EFI_HANDLE64 ConsoleInHandle; + EFI_PTR64 ConIn; - EFI_HANDLE64 ConsoleInHandle; - EFI_PTR64 ConIn; + EFI_HANDLE64 ConsoleOutHandle; + EFI_PTR64 ConOut; - EFI_HANDLE64 ConsoleOutHandle; - EFI_PTR64 ConOut; + EFI_HANDLE64 StandardErrorHandle; + EFI_PTR64 StdErr; - EFI_HANDLE64 StandardErrorHandle; - EFI_PTR64 StdErr; + EFI_PTR64 RuntimeServices; + EFI_PTR64 BootServices; - EFI_PTR64 RuntimeServices; - EFI_PTR64 BootServices; - - EFI_UINT64 NumberOfTableEntries; - EFI_PTR64 ConfigurationTable; - + EFI_UINT64 NumberOfTableEntries; + EFI_PTR64 ConfigurationTable; } __attribute__((aligned(8))) EFI_SYSTEM_TABLE_64; #endif /* _PEXPERT_I386_EFI_H */ Index: trunk/i386/libsaio/bootstruct.h =================================================================== --- trunk/i386/libsaio/bootstruct.h (revision 2326) +++ trunk/i386/libsaio/bootstruct.h (revision 2327) @@ -44,7 +44,6 @@ //#define FB_TEXT_MODE 2 - /* * Maximum number of boot drivers that can be loaded. */ @@ -75,9 +74,9 @@ } PCI_bus_info_t; typedef struct { - unsigned long address; // address where driver was loaded - unsigned long size; // number of bytes - unsigned long type; // driver type + unsigned long address; // address where driver was loaded + unsigned long size; // number of bytes + unsigned long type; // driver type } driver_config_t; /* @@ -91,12 +90,12 @@ * ACPI defined memory range types. */ enum { - kMemoryRangeUsable = 1, // RAM usable by the OS. - kMemoryRangeReserved = 2, // Reserved. (Do not use) - kMemoryRangeACPI = 3, // ACPI tables. Can be reclaimed. - kMemoryRangeNVS = 4, // ACPI NVS memory. (Do not use) + kMemoryRangeUsable = 1, // RAM usable by the OS. + kMemoryRangeReserved = 2, // Reserved. (Do not use) + kMemoryRangeACPI = 3, // ACPI tables. Can be reclaimed. + kMemoryRangeNVS = 4, // ACPI NVS memory. (Do not use) - /* Undefined types should be treated as kMemoryRangeReserved */ + /* Undefined types should be treated as kMemoryRangeReserved */ }; /*! @@ -108,30 +107,30 @@ to the kernel and are thus located in bootArgs although with different field names. */ typedef struct PrivateBootInfo { - int convmem; // conventional memory - int extmem; // extended memory + int convmem; // conventional memory + int extmem; // extended memory #if 0 - int numBootDrivers; // number of drivers loaded + int numBootDrivers; // number of drivers loaded #endif - char bootFile[128]; // kernel file name + char bootFile[128]; // kernel file name - unsigned long memoryMapCount; - MemoryRange memoryMap[kMemoryMapCountMax]; + unsigned long memoryMapCount; + MemoryRange memoryMap[kMemoryMapCountMax]; - PCI_bus_info_t pciInfo; + PCI_bus_info_t pciInfo; #if 0 - driver_config_t driverConfig[NDRIVERS]; + driver_config_t driverConfig[NDRIVERS]; #endif - char * configEnd; // pointer to end of config files - char config[CONFIG_SIZE]; + char * configEnd; // pointer to end of config files + char config[CONFIG_SIZE]; - config_file_t bootConfig; // com.apple.Boot.plist - config_file_t chameleonConfig; // org.chameleon.Boot.plist which can override bootConfig keys - config_file_t themeConfig; // theme.plist - config_file_t smbiosConfig; // smbios.plist - config_file_t helperConfig; // boot helper partition's boot.plist - config_file_t ramdiskConfig; // RAMDisk.plist + config_file_t bootConfig; // com.apple.Boot.plist + config_file_t chameleonConfig; // org.chameleon.Boot.plist which can override bootConfig keys + config_file_t themeConfig; // theme.plist + config_file_t smbiosConfig; // smbios.plist + config_file_t helperConfig; // boot helper partition's boot.plist + config_file_t ramdiskConfig; // RAMDisk.plist bool memDetect; } PrivateBootInfo_t; Index: trunk/i386/libsaio/device_tree.c =================================================================== --- trunk/i386/libsaio/device_tree.c (revision 2326) +++ trunk/i386/libsaio/device_tree.c (revision 2327) @@ -1,31 +1,49 @@ /* - * Copyright (c) 2005 Apple Computer, Inc. All Rights Reserved. + * Copyright (c) 2005 Apple Computer, Inc. All rights reserved. + * + * Portions Copyright (c) 1999-2003 Apple Computer, Inc. All Rights + * Reserved. This file contains Original Code and/or Modifications of + * Original Code as defined in and that are subject to the Apple Public + * Source License Version 2.0 (the "License"). You may not use this file + * except in compliance with the License. Please obtain a copy of the + * License at http://www.apple.com/publicsource and read it before using + * this file. + * + * The Original Code and all software distributed under the License are + * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON- INFRINGEMENT. Please see the + * License for the specific language governing rights and limitations + * under the License. + * */ #if 1 /* - + Structures for a Flattened Device Tree */ #define kPropNameLength 32 typedef struct DeviceTreeNodeProperty { - char name[kPropNameLength]; // NUL terminated property name - unsigned long length; // Length (bytes) of folloing prop value + char name[kPropNameLength]; // NUL terminated property name + unsigned long length; // Length (bytes) of folloing prop value // unsigned long value[1]; // Variable length value of property // Padded to a multiple of a longword? } DeviceTreeNodeProperty; typedef struct OpaqueDTEntry { - unsigned long nProperties; // Number of props[] elements (0 => end) - unsigned long nChildren; // Number of children[] elements + unsigned long nProperties; // Number of props[] elements (0 => end) + unsigned long nChildren; // Number of children[] elements // DeviceTreeNodeProperty props[];// array size == nProperties // DeviceTreeNode children[]; // array size == nChildren } DeviceTreeNode; typedef char DTPropertyNameBuf[32]; -/* Entry Name Definitions (Entry Names are C-Strings)*/ + +// Entry Name Definitions (Entry Names are C-Strings). enum { kDTMaxEntryNameLength = 31 /* Max length of a C-String Entry Name (terminator not included) */ }; @@ -49,9 +67,9 @@ #define RoundToLong(x) (((x) + 3) & ~3) static struct _DTSizeInfo { - uint32_t numNodes; - uint32_t numProperties; - uint32_t totalPropertySize; + uint32_t numNodes; + uint32_t numProperties; + uint32_t totalPropertySize; } DTInfo; #define kAllocSize 4096 @@ -61,105 +79,142 @@ static Node *freeNodes, *allocedNodes; static Property *freeProperties, *allocedProperties; + +//============================================================================== + Property * DT__AddProperty(Node *node, const char *name, uint32_t length, void *value) { - Property *prop; + Property *prop; - DPRINTF("DT__AddProperty([Node '%s'], '%s', %d, 0x%x)\n", DT__GetName(node), name, length, value); - if (freeProperties == NULL) { - void *buf = malloc(kAllocSize); - int i; - - DPRINTF("Allocating more free properties\n"); - if (buf == 0) return 0; - bzero(buf, kAllocSize); - // Use the first property to record the allocated buffer - // for later freeing. - prop = (Property *)buf; - prop->next = allocedProperties; - allocedProperties = prop; - prop->value = buf; - prop++; - for (i=1; i<(kAllocSize / sizeof(Property)); i++) { - prop->next = freeProperties; - freeProperties = prop; - prop++; - } - } - prop = freeProperties; - freeProperties = prop->next; + DPRINTF("DT__AddProperty([Node '%s'], '%s', %d, 0x%x)\n", DT__GetName(node), name, length, value); - prop->name = name; - prop->length = length; - prop->value = value; + if (freeProperties == NULL) { + void *buf = malloc(kAllocSize); + int i; - // Always add to end of list - if (node->properties == 0) { - node->properties = prop; - } else { - node->last_prop->next = prop; - } - node->last_prop = prop; - prop->next = 0; + DPRINTF("Allocating more free properties\n"); - DPRINTF("Done [0x%x]\n", prop); - - DTInfo.numProperties++; - DTInfo.totalPropertySize += RoundToLong(length); + if (buf == 0) { + return 0; + } - return prop; + bzero(buf, kAllocSize); + // Use the first property to record the allocated buffer + // for later freeing. + prop = (Property *)buf; + prop->next = allocedProperties; + allocedProperties = prop; + prop->value = buf; + prop++; + + for (i = 1; i < (kAllocSize / sizeof(Property)); i++) { + prop->next = freeProperties; + freeProperties = prop; + prop++; + } + } + + prop = freeProperties; + freeProperties = prop->next; + + prop->name = name; + prop->length = length; + prop->value = value; + + // Always add to end of list + if (node->properties == 0) { + node->properties = prop; + } else { + node->last_prop->next = prop; + } + + node->last_prop = prop; + prop->next = 0; + + DPRINTF("Done [0x%x]\n", prop); + + DTInfo.numProperties++; + DTInfo.totalPropertySize += RoundToLong(length); + + return prop; } + +//============================================================================== + Node * DT__AddChild(Node *parent, const char *name) { - Node *node; + Node *node; - if (freeNodes == NULL) { - void *buf = malloc(kAllocSize); - int i; - - DPRINTF("Allocating more free nodes\n"); - if (buf == 0) return 0; - bzero(buf, kAllocSize); - node = (Node *)buf; - // Use the first node to record the allocated buffer - // for later freeing. - node->next = allocedNodes; - allocedNodes = node; - node->children = (Node *)buf; - node++; - for (i=1; i<(kAllocSize / sizeof(Node)); i++) { - node->next = freeNodes; - freeNodes = node; - node++; - } - } - DPRINTF("DT__AddChild(0x%x, '%s')\n", parent, name); - node = freeNodes; - freeNodes = node->next; - DPRINTF("Got free node 0x%x\n", node); - DPRINTF("prop = 0x%x, children = 0x%x, next = 0x%x\n", node->properties, node->children, node->next); + if (freeNodes == NULL) + { + void *buf = malloc(kAllocSize); - if (parent == NULL) { - rootNode = node; - node->next = 0; - } else { - node->next = parent->children; - parent->children = node; - } - DTInfo.numNodes++; - DT__AddProperty(node, "name", strlen(name) + 1, (void *) name); - return node; + if (buf == 0) + { + return 0; + } + + int i; + + DPRINTF("Allocating more free nodes\n"); + + bzero(buf, kAllocSize); + node = (Node *)buf; + + // Use the first node to record the allocated buffer for later freeing. + node->next = allocedNodes; + allocedNodes = node; + node->children = (Node *)buf; + node++; + + for (i = 1; i < (kAllocSize / sizeof(Node)); i++) + { + node->next = freeNodes; + freeNodes = node; + node++; + } + } + + DPRINTF("DT__AddChild(0x%x, '%s')\n", parent, name); + + node = freeNodes; + freeNodes = node->next; + + DPRINTF("Got free node 0x%x\n", node); + DPRINTF("prop = 0x%x, children = 0x%x, next = 0x%x\n", node->properties, node->children, node->next); + + if (parent == NULL) + { + rootNode = node; + node->next = 0; + } + else + { + node->next = parent->children; + parent->children = node; + } + + DTInfo.numNodes++; + DT__AddProperty(node, "name", strlen(name) + 1, (void *) name); + + return node; } + +//============================================================================== + void DT__FreeProperty(Property *prop) { - prop->next = freeProperties; - freeProperties = prop; + prop->next = freeProperties; + freeProperties = prop; } + +//============================================================================== + void DT__FreeNode(Node *node) { @@ -167,89 +222,103 @@ freeNodes = node; } +//============================================================================== + void DT__Initialize(void) { - DPRINTF("DT__Initialize\n"); - - freeNodes = 0; - allocedNodes = 0; - freeProperties = 0; - allocedProperties = 0; - - DTInfo.numNodes = 0; - DTInfo.numProperties = 0; - DTInfo.totalPropertySize = 0; - - rootNode = DT__AddChild(NULL, "/"); - DPRINTF("DT__Initialize done\n"); + DPRINTF("DT__Initialize\n"); + + freeNodes = 0; + allocedNodes = 0; + freeProperties = 0; + allocedProperties = 0; + + DTInfo.numNodes = 0; + DTInfo.numProperties = 0; + DTInfo.totalPropertySize = 0; + + rootNode = DT__AddChild(NULL, "/"); + DPRINTF("DT__Initialize done\n"); } +//============================================================================== /* - * Free up memory used by in-memory representation - * of device tree. + * Free up memory used by in-memory representation of device tree. */ void DT__Finalize(void) { - Node *node; - Property *prop; + Node *node; + Property *prop; - DPRINTF("DT__Finalize\n"); - for (prop = allocedProperties; prop != NULL; prop = prop->next) { - free(prop->value); - } - allocedProperties = NULL; - freeProperties = NULL; + DPRINTF("DT__Finalize\n"); - for (node = allocedNodes; node != NULL; node = node->next) { - free((void *)node->children); - } - allocedNodes = NULL; - freeNodes = NULL; - rootNode = NULL; + for (prop = allocedProperties; prop != NULL; prop = prop->next) + { + free(prop->value); + } + + allocedProperties = NULL; + freeProperties = NULL; + + for (node = allocedNodes; node != NULL; node = node->next) + { + free((void *)node->children); + } + + allocedNodes = NULL; + freeNodes = NULL; + rootNode = NULL; - // XXX leaks any created strings - - DTInfo.numNodes = 0; - DTInfo.numProperties = 0; - DTInfo.totalPropertySize = 0; + // XXX leaks any created strings + DTInfo.numNodes = 0; + DTInfo.numProperties = 0; + DTInfo.totalPropertySize = 0; } +//============================================================================== + static void * FlattenNodes(Node *node, void *buffer) { - Property *prop; - DeviceTreeNode *flatNode; - DeviceTreeNodeProperty *flatProp; - int count; + Property *prop; + DeviceTreeNode *flatNode; + DeviceTreeNodeProperty *flatProp; + int count; - if (node == 0) return buffer; + if (node == 0) { + return buffer; + } - flatNode = (DeviceTreeNode *)buffer; - buffer += sizeof(DeviceTreeNode); + flatNode = (DeviceTreeNode *)buffer; + buffer += sizeof(DeviceTreeNode); - for (count = 0, prop = node->properties; prop != 0; count++, prop = prop->next) { - flatProp = (DeviceTreeNodeProperty *)buffer; - strcpy(flatProp->name, prop->name); - flatProp->length = prop->length; - buffer += sizeof(DeviceTreeNodeProperty); - bcopy(prop->value, buffer, prop->length); - buffer += RoundToLong(prop->length); - } - flatNode->nProperties = count; + for (count = 0, prop = node->properties; prop != 0; count++, prop = prop->next) + { + flatProp = (DeviceTreeNodeProperty *)buffer; + strcpy(flatProp->name, prop->name); + flatProp->length = prop->length; + buffer += sizeof(DeviceTreeNodeProperty); + bcopy(prop->value, buffer, prop->length); + buffer += RoundToLong(prop->length); + } - for (count = 0, node = node->children; node != 0; count++, node = node->next) { - buffer = FlattenNodes(node, buffer); - } - flatNode->nChildren = count; + flatNode->nProperties = count; - return buffer; + for (count = 0, node = node->children; node != 0; count++, node = node->next) + { + buffer = FlattenNodes(node, buffer); + } + + flatNode->nChildren = count; + + return buffer; } -/* - * Flatten the in-memory representation of the device tree - * into a binary DT block. + +/*============================================================================== + * Flatten the in-memory representation of the device tree into a binary DT block. * To get the buffer size needed, call with result = 0. * To have a buffer allocated for you, call with *result = 0. * To use your own buffer, call with *result = &buffer. @@ -258,282 +327,361 @@ void DT__FlattenDeviceTree(void **buffer_p, uint32_t *length) { - uint32_t totalSize; - void *buf; + uint32_t totalSize; + void * buf; - DPRINTF("DT__FlattenDeviceTree(0x%x, 0x%x)\n", buffer_p, length); + DPRINTF("DT__FlattenDeviceTree(0x%x, 0x%x)\n", buffer_p, length); + #if DEBUG - if (buffer_p) DT__PrintTree(rootNode); + if (buffer_p) { + DT__PrintTree(rootNode); + } #endif - totalSize = DTInfo.numNodes * sizeof(DeviceTreeNode) + - DTInfo.numProperties * sizeof(DeviceTreeNodeProperty) + - DTInfo.totalPropertySize; + totalSize = DTInfo.numNodes * sizeof(DeviceTreeNode) + + DTInfo.numProperties * sizeof(DeviceTreeNodeProperty) + + DTInfo.totalPropertySize; - DPRINTF("Total size 0x%x\n", totalSize); - if (buffer_p != 0) { - if (totalSize == 0) { - buf = 0; - } else { - if (*buffer_p == 0) { - buf = malloc(totalSize); - } else { - buf = *buffer_p; - } - bzero(buf, totalSize); - - FlattenNodes(rootNode, buf); - } - *buffer_p = buf; - } - if (length) - *length = totalSize; + DPRINTF("Total size 0x%x\n", totalSize); + + if (buffer_p != 0) + { + if (totalSize == 0) + { + buf = 0; + } + else + { + if (*buffer_p == 0) + { + buf = malloc(totalSize); + } + else + { + buf = *buffer_p; + } + + bzero(buf, totalSize); + + FlattenNodes(rootNode, buf); + } + + *buffer_p = buf; + } + + if (length) + { + *length = totalSize; + } } +//============================================================================== + char * DT__GetName(Node *node) { - Property *prop; + Property *prop; - //DPRINTF("DT__GetName(0x%x)\n", node); - //DPRINTF("Node properties = 0x%x\n", node->properties); - for (prop = node->properties; prop; prop = prop->next) { - //DPRINTF("Prop '%s'\n", prop->name); - if (strcmp(prop->name, "name") == 0) { - return prop->value; - } - } - //DPRINTF("DT__GetName returns 0\n"); - return "(null)"; + //DPRINTF("DT__GetName(0x%x)\n", node); + //DPRINTF("Node properties = 0x%x\n", node->properties); + for (prop = node->properties; prop; prop = prop->next) + { + //DPRINTF("Prop '%s'\n", prop->name); + if (strcmp(prop->name, "name") == 0) + { + return prop->value; + } + } + + //DPRINTF("DT__GetName returns 0\n"); + return "(null)"; } +//============================================================================== + Node * DT__FindNode(const char *path, bool createIfMissing) { - Node *node, *child; - DTPropertyNameBuf nameBuf; - char *bp; - int i; + Node *node, *child; + DTPropertyNameBuf nameBuf; + char *bp; + int i; - DPRINTF("DT__FindNode('%s', %d)\n", path, createIfMissing); + DPRINTF("DT__FindNode('%s', %d)\n", path, createIfMissing); - // Start at root - node = rootNode; - DPRINTF("root = 0x%x\n", rootNode); + // Start at root + node = rootNode; - while (node) { - // Skip leading slash - while (*path == '/') path++; + DPRINTF("root = 0x%x\n", rootNode); - for (i=0, bp = nameBuf; ++i < kDTMaxEntryNameLength && *path && *path != '/'; bp++, path++) *bp = *path; - *bp = '\0'; + while (node) + { + // Skip leading slash + while (*path == '/') + { + path++; + } - if (nameBuf[0] == '\0') { - // last path entry - break; - } - DPRINTF("Node '%s'\n", nameBuf); + for (i = 0, bp = nameBuf; ++i < kDTMaxEntryNameLength && *path && *path != '/'; bp++, path++) + { + *bp = *path; + } - for (child = node->children; child != 0; child = child->next) { - DPRINTF("Child 0x%x\n", child); - if (strcmp(DT__GetName(child), nameBuf) == 0) { - break; - } - } - if (child == 0 && createIfMissing) { - DPRINTF("Creating node\n"); - char *str = malloc(strlen(nameBuf) + 1); - // XXX this will leak - strcpy(str, nameBuf); + *bp = '\0'; - child = DT__AddChild(node, str); - } - node = child; - } - return node; + if (nameBuf[0] == '\0') + { + // last path entry + break; + } + + DPRINTF("Node '%s'\n", nameBuf); + + for (child = node->children; child != 0; child = child->next) + { + DPRINTF("Child 0x%x\n", child); + + if (strcmp(DT__GetName(child), nameBuf) == 0) + { + break; + } + } + + if (child == 0 && createIfMissing) + { + DPRINTF("Creating node\n"); + + char *str = malloc(strlen(nameBuf) + 1); + // XXX this will leak + strcpy(str, nameBuf); + + child = DT__AddChild(node, str); + } + + node = child; + } + + return node; } #if DEBUG +//============================================================================== + void DT__PrintNode(Node *node, int level) { - char spaces[10], *cp = spaces; - Property *prop; + char spaces[10], *cp = spaces; + Property *prop; - if (level > 9) level = 9; - while (level--) *cp++ = ' '; - *cp = '\0'; + if (level > 9) + { + level = 9; + } - printf("%s===Node===\n", spaces); - for (prop = node->properties; prop; prop = prop->next) { - char c = *((char *)prop->value); - if (prop->length < 64 && ( - strcmp(prop->name, "name") == 0 || - (c >= '0' && c <= '9') || - (c >= 'a' && c <= 'z') || - (c >= 'A' && c <= 'Z') || c == '_')) { - printf("%s Property '%s' [%d] = '%s'\n", spaces, prop->name, prop->length, prop->value); - } else { - printf("%s Property '%s' [%d] = (data)\n", spaces, prop->name, prop->length); - } - } - printf("%s==========\n", spaces); + while (level--) + { + *cp++ = ' '; + } + + *cp = '\0'; + + printf("%s===Node===\n", spaces); + + for (prop = node->properties; prop; prop = prop->next) + { + char c = *((char *)prop->value); + if (prop->length < 64 && (strcmp(prop->name, "name") == 0 || (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_')) + { + printf("%s Property '%s' [%d] = '%s'\n", spaces, prop->name, prop->length, prop->value); + } + else + { + printf("%s Property '%s' [%d] = (data)\n", spaces, prop->name, prop->length); + } + } + + printf("%s==========\n", spaces); } +//============================================================================== + static void _PrintTree(Node *node, int level) { - DT__PrintNode(node, level); - level++; - for (node = node->children; node; node = node->next) - _PrintTree(node, level); + DT__PrintNode(node, level); + + level++; + + for (node = node->children; node; node = node->next) + { + _PrintTree(node, level); + } } +//============================================================================== + void DT__PrintTree(Node *node) { - if (node == 0) node = rootNode; - _PrintTree(node, 0); + if (node == 0) node = rootNode; + _PrintTree(node, 0); } +//============================================================================== + void DT__PrintFlattenedNode(DTEntry entry, int level) { - char spaces[10], *cp = spaces; - DTPropertyIterator propIter; - char *name; - void *prop; - int propSize; + char spaces[10], *cp = spaces; + DTPropertyIterator propIter; + char *name; + void *prop; + int propSize; - if (level > 9) level = 9; - while (level--) *cp++ = ' '; - *cp = '\0'; + if (level > 9) level = 9; + while (level--) *cp++ = ' '; + *cp = '\0'; - printf("%s===Entry %p===\n", spaces, entry); - if (kSuccess != DTCreatePropertyIterator(entry, &propIter)) { - printf("Couldn't create property iterator\n"); - return; - } - while( kSuccess == DTIterateProperties( propIter, &name)) { - if( kSuccess != DTGetProperty( entry, name, &prop, &propSize )) - continue; - printf("%s Property %s = %s\n", spaces, name, prop); - } - DTDisposePropertyIterator(propIter); + printf("%s===Entry %p===\n", spaces, entry); + if (kSuccess != DTCreatePropertyIterator(entry, &propIter)) + { + printf("Couldn't create property iterator\n"); + return; + } + while( kSuccess == DTIterateProperties( propIter, &name)) + { + if( kSuccess != DTGetProperty( entry, name, &prop, &propSize )) + continue; + printf("%s Property %s = %s\n", spaces, name, prop); + } + DTDisposePropertyIterator(propIter); - printf("%s==========\n", spaces); + printf("%s==========\n", spaces); } +//============================================================================== + static void _PrintFlattenedTree(DTEntry entry, int level) { - DTEntryIterator entryIter; + DTEntryIterator entryIter; - PrintFlattenedNode(entry, level); + PrintFlattenedNode(entry, level); - if (kSuccess != DTCreateEntryIterator(entry, &entryIter)) { - printf("Couldn't create entry iterator\n"); - return; - } - level++; - while (kSuccess == DTIterateEntries( entryIter, &entry )) { - _PrintFlattenedTree(entry, level); - } - DTDisposeEntryIterator(entryIter); + if (kSuccess != DTCreateEntryIterator(entry, &entryIter)) + { + printf("Couldn't create entry iterator\n"); + return; + } + level++; + while (kSuccess == DTIterateEntries( entryIter, &entry )) + { + _PrintFlattenedTree(entry, level); + } + DTDisposeEntryIterator(entryIter); } +//============================================================================== + void DT__PrintFlattenedTree(DTEntry entry) { - _PrintFlattenedTree(entry, 0); + _PrintFlattenedTree(entry, 0); } +//============================================================================== int main(int argc, char **argv) { - DTEntry dtEntry; - DTPropertyIterator propIter; - DTEntryIterator entryIter; - void *prop; - int propSize; - char *name; - void *flatTree; - uint32_t flatSize; + DTEntry dtEntry; + DTPropertyIterator propIter; + DTEntryIterator entryIter; + void *prop; + int propSize; + char *name; + void *flatTree; + uint32_t flatSize; - Node *node; + Node *node; - node = AddChild(NULL, "device-tree"); - AddProperty(node, "potato", 4, "foo"); - AddProperty(node, "chemistry", 4, "bar"); - AddProperty(node, "physics", 4, "baz"); + node = AddChild(NULL, "device-tree"); + AddProperty(node, "potato", 4, "foo"); + AddProperty(node, "chemistry", 4, "bar"); + AddProperty(node, "physics", 4, "baz"); - node = AddChild(node, "dev"); - AddProperty(node, "one", 4, "one"); - AddProperty(node, "two", 4, "two"); - AddProperty(node, "three", 6, "three"); + node = AddChild(node, "dev"); + AddProperty(node, "one", 4, "one"); + AddProperty(node, "two", 4, "two"); + AddProperty(node, "three", 6, "three"); - node = AddChild(rootNode, "foo"); - AddProperty(node, "aaa", 4, "aab"); - AddProperty(node, "bbb", 4, "bbc"); - AddProperty(node, "cccc", 6, "ccccd"); + node = AddChild(rootNode, "foo"); + AddProperty(node, "aaa", 4, "aab"); + AddProperty(node, "bbb", 4, "bbc"); + AddProperty(node, "cccc", 6, "ccccd"); - node = FindNode("/this/is/a/test", 1); - AddProperty(node, "dddd", 12, "abcdefghijk"); + node = FindNode("/this/is/a/test", 1); + AddProperty(node, "dddd", 12, "abcdefghijk"); - printf("In-memory tree:\n\n"); + printf("In-memory tree:\n\n"); - PrintTree(rootNode); + PrintTree(rootNode); - FlattenDeviceTree(&flatTree, &flatSize); + FlattenDeviceTree(&flatTree, &flatSize); - printf("Flat tree = %p, size %d\n", flatTree, flatSize); + printf("Flat tree = %p, size %d\n", flatTree, flatSize); - dtEntry = (DTEntry)flatTree; + dtEntry = (DTEntry)flatTree; - printf("\n\nPrinting flat tree\n\n"); + printf("\n\nPrinting flat tree\n\n"); - DTInit(dtEntry); + DTInit(dtEntry); - PrintFlattenedTree((DTEntry)flatTree); + PrintFlattenedTree((DTEntry)flatTree); #if 0 - printf("=== Entry %p ===\n", dtEntry); - if (kSuccess != DTCreatePropertyIterator(dtEntry, &propIter)) { - printf("Couldn't create property iterator\n"); - return 1; + printf("=== Entry %p ===\n", dtEntry); + if (kSuccess != DTCreatePropertyIterator(dtEntry, &propIter)) + { + printf("Couldn't create property iterator\n"); + return 1; + } + while( kSuccess == DTIterateProperties( propIter, &name)) + { + if( kSuccess != DTGetProperty( dtEntry, name, &prop, &propSize )) + continue; + printf(" Property %s = %s\n", name, prop); } - while( kSuccess == DTIterateProperties( propIter, &name)) { - if( kSuccess != DTGetProperty( dtEntry, name, &prop, &propSize )) - continue; - printf(" Property %s = %s\n", name, prop); - } - DTDisposePropertyIterator(propIter); - printf("========\n"); + DTDisposePropertyIterator(propIter); + printf("========\n"); - if (kSuccess != DTCreateEntryIterator(dtEntry, &entryIter)) { - printf("Couldn't create entry iterator\n"); - return 1; - } - while (kSuccess == DTIterateEntries( entryIter, &dtEntry )) { - printf("=== Entry %p ===\n", dtEntry); + if (kSuccess != DTCreateEntryIterator(dtEntry, &entryIter)) + { + printf("Couldn't create entry iterator\n"); + return 1; + } + while (kSuccess == DTIterateEntries( entryIter, &dtEntry )) + { + printf("=== Entry %p ===\n", dtEntry); - if (kSuccess != DTCreatePropertyIterator(dtEntry, &propIter)) { - printf("Couldn't create property iterator\n"); - return 1; - } - while( kSuccess == DTIterateProperties( propIter, &name)) { - if( kSuccess != DTGetProperty( dtEntry, name, &prop, &propSize )) - continue; - printf(" Property %s = %s\n", name, prop); - } - DTDisposePropertyIterator(propIter); - printf("========\n"); - } - DTDisposeEntryIterator(entryIter); + if (kSuccess != DTCreatePropertyIterator(dtEntry, &propIter)) + { + printf("Couldn't create property iterator\n"); + return 1; + } + while( kSuccess == DTIterateProperties( propIter, &name)) + { + if( kSuccess != DTGetProperty( dtEntry, name, &prop, &propSize )) + continue; + printf(" Property %s = %s\n", name, prop); + } + DTDisposePropertyIterator(propIter); + printf("========\n"); + } + DTDisposeEntryIterator(entryIter); #endif - return 0; + return 0; } #endif Index: trunk/i386/libsaio/hfs.c =================================================================== --- trunk/i386/libsaio/hfs.c (revision 2326) +++ trunk/i386/libsaio/hfs.c (revision 2327) @@ -109,156 +109,187 @@ u_int16_t *uniStr2, u_int32_t len2); +//============================================================================== + static void SwapFinderInfo(FndrFileInfo *dst, FndrFileInfo *src) { - dst->fdType = SWAP_BE32(src->fdType); - dst->fdCreator = SWAP_BE32(src->fdCreator); - dst->fdFlags = SWAP_BE16(src->fdFlags); - // Don't bother with location + dst->fdType = SWAP_BE32(src->fdType); + dst->fdCreator = SWAP_BE32(src->fdCreator); + dst->fdFlags = SWAP_BE16(src->fdFlags); + // Don't bother with location } + +//============================================================================== + void HFSFree(CICell ih) { - if(gCurrentIH == ih) - gCurrentIH = 0; - free(ih); + if(gCurrentIH == ih) { + gCurrentIH = 0; + } + free(ih); } + +//============================================================================== + bool HFSProbe (const void *buf) { const HFSMasterDirectoryBlock *mdb; const HFSPlusVolumeHeader *header; - mdb=(const HFSMasterDirectoryBlock *)(((const char*)buf)+kMDBBaseOffset); - header=(const HFSPlusVolumeHeader *)(((const char*)buf)+kMDBBaseOffset); + mdb = (const HFSMasterDirectoryBlock *)(((const char*)buf)+kMDBBaseOffset); + header = (const HFSPlusVolumeHeader *)(((const char*)buf)+kMDBBaseOffset); - if ( SWAP_BE16(mdb->drSigWord) == kHFSSigWord ) + if ( SWAP_BE16(mdb->drSigWord) == kHFSSigWord ) { return true; - if (SWAP_BE16(header->signature) != kHFSPlusSigWord && - SWAP_BE16(header->signature) != kHFSXSigWord) + } + + if (SWAP_BE16(header->signature) != kHFSPlusSigWord && SWAP_BE16(header->signature) != kHFSXSigWord) { return false; + } return true; } + +//============================================================================== + long HFSInitPartition(CICell ih) { - long extentSize, extentFile, nodeSize; - void *extent; + long extentSize, extentFile, nodeSize; + void *extent; - if (ih == gCurrentIH) { + if (ih == gCurrentIH) + { #ifdef __i386__ - CacheInit(ih, gCacheBlockSize); + CacheInit(ih, gCacheBlockSize); #endif - return 0; - } + return 0; + } #ifdef __i386__ - if (!gTempStr) gTempStr = (char *)malloc(4096); - if (!gLinkTemp) gLinkTemp = (char *)malloc(64); - if (!gBTreeHeaderBuffer) gBTreeHeaderBuffer = (char *)malloc(512); - if (!gHFSMdbVib) { - gHFSMdbVib = (char *)malloc(kBlockSize); - gHFSMDB = (HFSMasterDirectoryBlock *)gHFSMdbVib; - } - if (!gHFSPlusHeader) { - gHFSPlusHeader = (char *)malloc(kBlockSize); - gHFSPlus = (HFSPlusVolumeHeader *)gHFSPlusHeader; - } - if (!gTempStr || !gLinkTemp || !gBTreeHeaderBuffer || - !gHFSMdbVib || !gHFSPlusHeader) return -1; + if (!gTempStr) + { + gTempStr = (char *)malloc(4096); + } + if (!gLinkTemp) + { + gLinkTemp = (char *)malloc(64); + } + if (!gBTreeHeaderBuffer) + { + gBTreeHeaderBuffer = (char *)malloc(512); + } + if (!gHFSMdbVib) + { + gHFSMdbVib = (char *)malloc(kBlockSize); + gHFSMDB = (HFSMasterDirectoryBlock *)gHFSMdbVib; + } + if (!gHFSPlusHeader) + { + gHFSPlusHeader = (char *)malloc(kBlockSize); + gHFSPlus = (HFSPlusVolumeHeader *)gHFSPlusHeader; + } + if (!gTempStr || !gLinkTemp || !gBTreeHeaderBuffer || !gHFSMdbVib || !gHFSPlusHeader) + { + return -1; + } #endif /* __i386__ */ - gAllocationOffset = 0; - gIsHFSPlus = 0; - gCaseSensitive = 0; - gBTHeaders[0] = 0; - gBTHeaders[1] = 0; + gAllocationOffset = 0; + gIsHFSPlus = 0; + gCaseSensitive = 0; + gBTHeaders[0] = 0; + gBTHeaders[1] = 0; - // Look for the HFS MDB - Seek(ih, kMDBBaseOffset); - Read(ih, (long)gHFSMdbVib, kBlockSize); + // Look for the HFS MDB + Seek(ih, kMDBBaseOffset); + Read(ih, (long)gHFSMdbVib, kBlockSize); - if ( SWAP_BE16(gHFSMDB->drSigWord) == kHFSSigWord ) { - gAllocationOffset = SWAP_BE16(gHFSMDB->drAlBlSt) * kBlockSize; + if (SWAP_BE16(gHFSMDB->drSigWord) == kHFSSigWord) + { + gAllocationOffset = SWAP_BE16(gHFSMDB->drAlBlSt) * kBlockSize; - // See if it is HFSPlus - if (SWAP_BE16(gHFSMDB->drEmbedSigWord) != kHFSPlusSigWord) { - // Normal HFS; - gCacheBlockSize = gBlockSize = SWAP_BE32(gHFSMDB->drAlBlkSiz); - CacheInit(ih, gCacheBlockSize); - gCurrentIH = ih; + // See if it is HFSPlus + if (SWAP_BE16(gHFSMDB->drEmbedSigWord) != kHFSPlusSigWord) + { + // Normal HFS; + gCacheBlockSize = gBlockSize = SWAP_BE32(gHFSMDB->drAlBlkSiz); + CacheInit(ih, gCacheBlockSize); + gCurrentIH = ih; - // grab the 64 bit volume ID - bcopy(&gHFSMDB->drFndrInfo[6], &gVolID, 8); + // grab the 64 bit volume ID + bcopy(&gHFSMDB->drFndrInfo[6], &gVolID, 8); - // Get the Catalog BTree node size. - extent = (HFSExtentDescriptor *)&gHFSMDB->drCTExtRec; - extentSize = SWAP_BE32(gHFSMDB->drCTFlSize); - extentFile = kHFSCatalogFileID; - ReadExtent(extent, extentSize, extentFile, 0, 256, - gBTreeHeaderBuffer + kBTreeCatalog * 256, 0); + // Get the Catalog BTree node size. + extent = (HFSExtentDescriptor *)&gHFSMDB->drCTExtRec; + extentSize = SWAP_BE32(gHFSMDB->drCTFlSize); + extentFile = kHFSCatalogFileID; + ReadExtent(extent, extentSize, extentFile, 0, 256, gBTreeHeaderBuffer + kBTreeCatalog * 256, 0); - nodeSize = SWAP_BE16(((BTHeaderRec *)(gBTreeHeaderBuffer + kBTreeCatalog * 256 + - sizeof(BTNodeDescriptor)))->nodeSize); + nodeSize = SWAP_BE16(((BTHeaderRec *)(gBTreeHeaderBuffer + kBTreeCatalog * 256 + sizeof(BTNodeDescriptor)))->nodeSize); - // If the BTree node size is larger than the block size, reset the cache. - if (nodeSize > gBlockSize) { - gCacheBlockSize = nodeSize; - CacheInit(ih, gCacheBlockSize); - } + // If the BTree node size is larger than the block size, reset the cache. + if (nodeSize > gBlockSize) + { + gCacheBlockSize = nodeSize; + CacheInit(ih, gCacheBlockSize); + } - return 0; - } + return 0; + } - // Calculate the offset to the embeded HFSPlus volume. - gAllocationOffset += (long long)SWAP_BE16(gHFSMDB->drEmbedExtent.startBlock) * + // Calculate the offset to the embeded HFSPlus volume. + gAllocationOffset += (long long)SWAP_BE16(gHFSMDB->drEmbedExtent.startBlock) * SWAP_BE32(gHFSMDB->drAlBlkSiz); - } + } - // Look for the HFSPlus Header - Seek(ih, gAllocationOffset + kMDBBaseOffset); - Read(ih, (long)gHFSPlusHeader, kBlockSize); + // Look for the HFSPlus Header + Seek(ih, gAllocationOffset + kMDBBaseOffset); + Read(ih, (long)gHFSPlusHeader, kBlockSize); - // Not a HFS+ or HFSX volume. - if (SWAP_BE16(gHFSPlus->signature) != kHFSPlusSigWord && - SWAP_BE16(gHFSPlus->signature) != kHFSXSigWord) { - verbose("HFS signature was not present.\n"); - gCurrentIH = 0; - return -1; - } + // Not a HFS+ or HFSX volume. + if (SWAP_BE16(gHFSPlus->signature) != kHFSPlusSigWord && SWAP_BE16(gHFSPlus->signature) != kHFSXSigWord) + { + verbose("HFS signature was not present.\n"); + gCurrentIH = 0; + return -1; + } - gIsHFSPlus = 1; - gCacheBlockSize = gBlockSize = SWAP_BE32(gHFSPlus->blockSize); - CacheInit(ih, gCacheBlockSize); - gCurrentIH = ih; + gIsHFSPlus = 1; + gCacheBlockSize = gBlockSize = SWAP_BE32(gHFSPlus->blockSize); + CacheInit(ih, gCacheBlockSize); + gCurrentIH = ih; ih->modTime = SWAP_BE32(gHFSPlus->modifyDate) - 2082844800; - - // grab the 64 bit volume ID - bcopy(&gHFSPlus->finderInfo[24], &gVolID, 8); - // Get the Catalog BTree node size. - extent = &gHFSPlus->catalogFile.extents; - extentSize = SWAP_BE64(gHFSPlus->catalogFile.logicalSize); - extentFile = kHFSCatalogFileID; + // grab the 64 bit volume ID + bcopy(&gHFSPlus->finderInfo[24], &gVolID, 8); - ReadExtent(extent, extentSize, extentFile, 0, 256, - gBTreeHeaderBuffer + kBTreeCatalog * 256, 0); + // Get the Catalog BTree node size. + extent = &gHFSPlus->catalogFile.extents; + extentSize = SWAP_BE64(gHFSPlus->catalogFile.logicalSize); + extentFile = kHFSCatalogFileID; - nodeSize = SWAP_BE16(((BTHeaderRec *)(gBTreeHeaderBuffer + kBTreeCatalog * 256 + - sizeof(BTNodeDescriptor)))->nodeSize); + ReadExtent(extent, extentSize, extentFile, 0, 256, gBTreeHeaderBuffer + kBTreeCatalog * 256, 0); - // If the BTree node size is larger than the block size, reset the cache. - if (nodeSize > gBlockSize) { - gCacheBlockSize = nodeSize; - CacheInit(ih, gCacheBlockSize); - } + nodeSize = SWAP_BE16(((BTHeaderRec *)(gBTreeHeaderBuffer + kBTreeCatalog * 256 + sizeof(BTNodeDescriptor)))->nodeSize); - return 0; + // If the BTree node size is larger than the block size, reset the cache. + if (nodeSize > gBlockSize) + { + gCacheBlockSize = nodeSize; + CacheInit(ih, gCacheBlockSize); + } + + return 0; } + +//============================================================================== + long HFSLoadFile(CICell ih, char * filePath) { - return HFSReadFile(ih, filePath, (void *)gFSLoadAddress, 0, 0); + return HFSReadFile(ih, filePath, (void *)gFSLoadAddress, 0, 0); } long HFSReadFile(CICell ih, char * filePath, void *base, uint64_t offset, uint64_t length) @@ -267,43 +298,64 @@ char devStr[12]; long dirID, result, flags; - if (HFSInitPartition(ih) == -1) return -1; - - dirID = kHFSRootFolderID; - // Skip a lead '\'. Start in the system folder if there are two. - if (filePath[0] == '/') { - if (filePath[1] == '/') { - if (gIsHFSPlus) dirID = SWAP_BE32(((long *)gHFSPlus->finderInfo)[5]); - else dirID = SWAP_BE32(gHFSMDB->drFndrInfo[5]); - if (dirID == 0) { + if (HFSInitPartition(ih) == -1) + { return -1; - } - filePath++; - } - filePath++; - } + } - result = ResolvePathToCatalogEntry(filePath, &flags, entry, dirID, 0); - if ((result == -1) || ((flags & kFileTypeMask) != kFileTypeFlat)) { - return -1; - } + dirID = kHFSRootFolderID; + // Skip a lead '\'. Start in the system folder if there are two. + if (filePath[0] == '/') + { + if (filePath[1] == '/') + { + if (gIsHFSPlus) + { + dirID = SWAP_BE32(((long *)gHFSPlus->finderInfo)[5]); + } + else + { + dirID = SWAP_BE32(gHFSMDB->drFndrInfo[5]); + } + if (dirID == 0) + { + return -1; + } + + filePath++; + } + + filePath++; + } + + result = ResolvePathToCatalogEntry(filePath, &flags, entry, dirID, 0); + + if ((result == -1) || ((flags & kFileTypeMask) != kFileTypeFlat)) + { + return -1; + } + #if UNUSED - // Not yet for Intel. System.config/Default.table will fail this check. - // Check file owner and permissions. - if (flags & (kOwnerNotRoot | kPermGroupWrite | kPermOtherWrite)) return -1; + // Not yet for Intel. System.config/Default.table will fail this check. + // Check file owner and permissions. + if (flags & (kOwnerNotRoot | kPermGroupWrite | kPermOtherWrite)) + { + return -1; + } #endif - result = ReadFile(entry, &length, base, offset); - if (result == -1) { - return -1; - } + result = ReadFile(entry, &length, base, offset); + if (result == -1) + { + return -1; + } - getDeviceDescription(ih, devStr); - verbose("Read HFS%s file: [%s/%s] %d bytes.\n", - (gIsHFSPlus ? "+" : ""), devStr, filePath, (uint32_t)length); - - return length; + getDeviceDescription(ih, devStr); + verbose("Read HFS%s file: [%s/%s] %d bytes.\n", + (gIsHFSPlus ? "+" : ""), devStr, filePath, (uint32_t)length); + + return length; } long HFSGetDirEntry(CICell ih, char * dirPath, long long * dirIndex, char ** name, @@ -1030,13 +1082,13 @@ { HFSPlusExtentKey *searchKey, *trialKey; long result; - + searchKey = key; trialKey = testKey; - + // assume searchKey < trialKey - result = -1; - + result = -1; + if (searchKey->fileID == trialKey->fileID) { // FileNum's are equal; compare fork types if (searchKey->forkType == trialKey->forkType) { Index: trunk/i386/libsaio/acpi_patcher.c =================================================================== --- trunk/i386/libsaio/acpi_patcher.c (revision 2326) +++ trunk/i386/libsaio/acpi_patcher.c (revision 2327) @@ -103,19 +103,17 @@ // Start searching any potential location for ACPI Table snprintf(dirSpec, sizeof(dirSpec), "%s", filename); fd = open(dirSpec, 0); - if (fd < 0) - { - snprintf(dirSpec, sizeof(dirSpec), "/Extra/%s", filename); - fd = open(dirSpec, 0); - if (fd < 0) + if (fd < 0) { + snprintf(dirSpec, sizeof(dirSpec), "/Extra/%s", filename); + fd = open(dirSpec, 0); + if (fd < 0) { - snprintf(dirSpec, sizeof(dirSpec), "bt(0,0)/Extra/%s", filename); - fd = open(dirSpec, 0); - if (fd < 0) - { - // NOT FOUND: - verbose("ACPI Table not found: %s\n", filename); - *dirSpec = '\0'; + snprintf(dirSpec, sizeof(dirSpec), "bt(0,0)/Extra/%s", filename); + fd = open(dirSpec, 0); + if (fd < 0) { + // NOT FOUND: + verbose("ACPI Table not found: %s\n", filename); + *dirSpec = '\0'; } } } @@ -273,14 +271,14 @@ unsigned char cstates_count = 1 + (c2_enabled ? 1 : 0) + (c3_enabled ? 1 : 0); - struct aml_chunk* root = aml_create_node(NULL); + AML_CHUNK* root = aml_create_node(NULL); aml_add_buffer(root, ssdt_header, sizeof(ssdt_header)); // SSDT header - struct aml_chunk* scop = aml_add_scope(root, "\\_PR_"); - struct aml_chunk* name = aml_add_name(scop, "CST_"); - struct aml_chunk* pack = aml_add_package(name); + AML_CHUNK* scop = aml_add_scope(root, "\\_PR_"); + AML_CHUNK* name = aml_add_name(scop, "CST_"); + AML_CHUNK* pack = aml_add_package(name); aml_add_byte(pack, cstates_count); - struct aml_chunk* tmpl = aml_add_package(pack); + AML_CHUNK* tmpl = aml_add_package(pack); if (cst_using_systemio) { // C1 @@ -288,9 +286,9 @@ resource_template_register_fixedhw[9] = 0x00; resource_template_register_fixedhw[18] = 0x00; aml_add_buffer(tmpl, resource_template_register_fixedhw, sizeof(resource_template_register_fixedhw)); - aml_add_byte(tmpl, 0x01); // C1 - aml_add_word(tmpl, 0x0001); // Latency - aml_add_dword(tmpl, 0x000003e8); // Power + aml_add_byte(tmpl, 0x01); // C1 + aml_add_word(tmpl, 0x0001); // Latency + aml_add_dword(tmpl, 0x000003e8); // Power uint8_t p_blk_lo, p_blk_hi; @@ -303,9 +301,9 @@ resource_template_register_systemio[11] = p_blk_lo; // C2 resource_template_register_systemio[12] = p_blk_hi; // C2 aml_add_buffer(tmpl, resource_template_register_systemio, sizeof(resource_template_register_systemio)); - aml_add_byte(tmpl, 0x02); // C2 - aml_add_word(tmpl, 0x0040); // Latency - aml_add_dword(tmpl, 0x000001f4); // Power + aml_add_byte(tmpl, 0x02); // C2 + aml_add_word(tmpl, 0x0040); // Latency + aml_add_dword(tmpl, 0x000001f4); // Power } if (c4_enabled) // C4 @@ -317,9 +315,9 @@ resource_template_register_systemio[11] = p_blk_lo; // C4 resource_template_register_systemio[12] = p_blk_hi; // C4 aml_add_buffer(tmpl, resource_template_register_systemio, sizeof(resource_template_register_systemio)); - aml_add_byte(tmpl, 0x04); // C4 - aml_add_word(tmpl, 0x0080); // Latency - aml_add_dword(tmpl, 0x000000C8); // Power + aml_add_byte(tmpl, 0x04); // C4 + aml_add_word(tmpl, 0x0080); // Latency + aml_add_dword(tmpl, 0x000000C8); // Power } else if (c3_enabled) // C3 { @@ -330,8 +328,8 @@ resource_template_register_systemio[11] = p_blk_lo; // C3 resource_template_register_systemio[12] = p_blk_hi; // C3 aml_add_buffer(tmpl, resource_template_register_systemio, sizeof(resource_template_register_systemio)); - aml_add_byte(tmpl, 0x03); // C3 - aml_add_word(tmpl, 0x0060); // Latency + aml_add_byte(tmpl, 0x03); // C3 + aml_add_word(tmpl, 0x0060); // Latency aml_add_dword(tmpl, 0x0000015e); // Power } } @@ -340,8 +338,8 @@ // C1 resource_template_register_fixedhw[11] = 0x00; // C1 aml_add_buffer(tmpl, resource_template_register_fixedhw, sizeof(resource_template_register_fixedhw)); - aml_add_byte(tmpl, 0x01); // C1 - aml_add_word(tmpl, 0x0001); // Latency + aml_add_byte(tmpl, 0x01); // C1 + aml_add_word(tmpl, 0x0001); // Latency aml_add_dword(tmpl, 0x000003e8); // Power resource_template_register_fixedhw[18] = 0x03; @@ -351,8 +349,8 @@ tmpl = aml_add_package(pack); resource_template_register_fixedhw[11] = 0x10; // C2 aml_add_buffer(tmpl, resource_template_register_fixedhw, sizeof(resource_template_register_fixedhw)); - aml_add_byte(tmpl, 0x02); // C2 - aml_add_word(tmpl, 0x0040); // Latency + aml_add_byte(tmpl, 0x02); // C2 + aml_add_word(tmpl, 0x0040); // Latency aml_add_dword(tmpl, 0x000001f4); // Power } @@ -361,8 +359,8 @@ tmpl = aml_add_package(pack); resource_template_register_fixedhw[11] = 0x30; // C4 aml_add_buffer(tmpl, resource_template_register_fixedhw, sizeof(resource_template_register_fixedhw)); - aml_add_byte(tmpl, 0x04); // C4 - aml_add_word(tmpl, 0x0080); // Latency + aml_add_byte(tmpl, 0x04); // C4 + aml_add_word(tmpl, 0x0080); // Latency aml_add_dword(tmpl, 0x000000C8); // Power } else if (c3_enabled) @@ -370,8 +368,8 @@ tmpl = aml_add_package(pack); resource_template_register_fixedhw[11] = 0x20; // C3 aml_add_buffer(tmpl, resource_template_register_fixedhw, sizeof(resource_template_register_fixedhw)); - aml_add_byte(tmpl, 0x03); // C3 - aml_add_word(tmpl, 0x0060); // Latency + aml_add_byte(tmpl, 0x03); // C3 + aml_add_word(tmpl, 0x0060); // Latency aml_add_dword(tmpl, 0x0000015e); // Power } } @@ -638,16 +636,16 @@ { int i; - struct aml_chunk* root = aml_create_node(NULL); + AML_CHUNK* root = aml_create_node(NULL); aml_add_buffer(root, ssdt_header, sizeof(ssdt_header)); // SSDT header - struct aml_chunk* scop = aml_add_scope(root, "\\_PR_"); - struct aml_chunk* name = aml_add_name(scop, "PSS_"); - struct aml_chunk* pack = aml_add_package(name); + AML_CHUNK* scop = aml_add_scope(root, "\\_PR_"); + AML_CHUNK* name = aml_add_name(scop, "PSS_"); + AML_CHUNK* pack = aml_add_package(name); for (i = 0; i < p_states_count; i++) { - struct aml_chunk* pstt = aml_add_package(pack); + AML_CHUNK* pstt = aml_add_package(pack); aml_add_dword(pstt, p_states[i].Frequency); aml_add_dword(pstt, 0x00000000); // Power @@ -862,11 +860,12 @@ /* Try using the file specified with the DSDT option */ if (getValueForKey(kDSDT, &filename, &len, &bootInfo->chameleonConfig)) { - snprintf(dirSpec, sizeof(dirSpec), filename); + snprintf(dirSpec, sizeof(dirSpec), filename); } else { sprintf(dirSpec, "DSDT.aml"); + //verbose("dirSpec, DSDT.aml"); } // Load replacement DSDT @@ -894,11 +893,11 @@ { int i; - for (i=0; i<30; i++) + for (i = 0; i < 30; i++) { char filename[512]; - sprintf(filename, i>0?"SSDT-%d.aml":"SSDT.aml", i); + sprintf(filename, i > 0?"SSDT-%d.aml":"SSDT.aml", i); if ( (new_ssdt[ssdt_count] = loadACPITable(filename)) ) { @@ -912,7 +911,7 @@ } // Do the same procedure for both versions of ACPI - for (version=0; version<2; version++) { + for (version = 0; version < 2; version++) { struct acpi_2_rsdp *rsdp, *rsdp_mod; struct acpi_2_rsdt *rsdt, *rsdt_mod; int rsdplength; @@ -974,13 +973,14 @@ if (drop_ssdt && tableSign(table, "SSDT")) { + verbose("OEM SSDT tables was dropped\n"); dropoffset++; continue; } if (tableSign(table, "DSDT")) { DBG("DSDT found\n"); - + verbose("Custom DSDT table was found\n"); if(new_dsdt) { rsdt_entries[i-dropoffset]=(uint32_t)new_dsdt; @@ -1094,6 +1094,7 @@ if (drop_ssdt && tableSign(table, "SSDT")) { + verbose("OEM SSDT tables was dropped\n"); dropoffset++; continue; } @@ -1160,7 +1161,7 @@ xsdt_entries=(uint64_t *)(xsdt_mod+1); // Mozodojo: Insert additional SSDTs into XSDT - if(ssdt_count>0) + if(ssdt_count > 0) { int j; Index: trunk/i386/libsaio/device_tree.h =================================================================== --- trunk/i386/libsaio/device_tree.h (revision 2326) +++ trunk/i386/libsaio/device_tree.h (revision 2327) @@ -1,5 +1,25 @@ /* - * Copyright (c) 2005 Apple Computer, Inc. All Rights Reserved. + * Copyright (c) 2005 Apple Computer, Inc. All rights reserved. + * + * @APPLE_LICENSE_HEADER_START@ + * + * Portions Copyright (c) 1999-2003 Apple Computer, Inc. All Rights + * Reserved. This file contains Original Code and/or Modifications of + * Original Code as defined in and that are subject to the Apple Public + * Source License Version 2.0 (the "License"). You may not use this file + * except in compliance with the License. Please obtain a copy of the + * License at http://www.apple.com/publicsource and read it before using + * this file. + * + * The Original Code and all software distributed under the License are + * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON- INFRINGEMENT. Please see the + * License for the specific language governing rights and limitations + * under the License. + * + * @APPLE_LICENSE_HEADER_END@ */ #ifndef __DEVICE_TREE_H @@ -8,21 +28,24 @@ #include #include + +//============================================================================== + typedef struct _Property { - const char * name; - uint32_t length; - void * value; - - struct _Property * next; + const char * name; + uint32_t length; + void * value; + struct _Property * next; } Property; + +//============================================================================== + typedef struct _Node { - struct _Property * properties; - struct _Property * last_prop; - - struct _Node * children; - - struct _Node * next; + struct _Property * properties; + struct _Property * last_prop; + struct _Node * children; + struct _Node * next; } Node; @@ -47,10 +70,9 @@ void DT__Initialize(void); -/* - * Free up memory used by in-memory representation - * of device tree. - */ + +// Free up memory used by in-memory representation of device tree. + extern void DT__Finalize(void); Index: trunk/i386/libsaio/allocate.c =================================================================== --- trunk/i386/libsaio/allocate.c (revision 2326) +++ trunk/i386/libsaio/allocate.c (revision 2327) @@ -33,47 +33,55 @@ #define RoundPage(x) ((((unsigned)(x)) + kPageSize - 1) & ~(kPageSize - 1)) +//============================================================================== + long AllocateMemoryRange(char * rangeName, long start, long length, long type) { - char *nameBuf; - uint32_t *buffer; - - nameBuf = malloc(strlen(rangeName) + 1); - if (nameBuf == 0) return -1; - - buffer = malloc(2 * sizeof(uint32_t)); - if (buffer == 0) { - free(nameBuf); - return -1; - } - - strcpy(nameBuf, rangeName); - buffer[0] = start; - buffer[1] = length; - - DT__AddProperty(gMemoryMapNode, nameBuf, 2 * sizeof(uint32_t), (char *)buffer); - - return 0; + char *nameBuf; + uint32_t *buffer; + + nameBuf = malloc(strlen(rangeName) + 1); + + if (nameBuf == 0) { + return -1; + } + + buffer = malloc(2 * sizeof(uint32_t)); + + if (buffer == 0) { + free(nameBuf); + return -1; + } + + strcpy(nameBuf, rangeName); + buffer[0] = start; + buffer[1] = length; + + DT__AddProperty(gMemoryMapNode, nameBuf, 2 * sizeof(uint32_t), (char *)buffer); + + return 0; } + +//============================================================================== + long -AllocateKernelMemory( long inSize ) +AllocateKernelMemory(long inSize) { - long addr; + long addr; - if (gImageLastKernelAddr == 0) { - gImageLastKernelAddr = RoundPage( bootArgs->kaddr + - bootArgs->ksize ); - } - addr = gImageLastKernelAddr; - gImageLastKernelAddr += RoundPage(inSize); + if (gImageLastKernelAddr == 0) { + gImageLastKernelAddr = RoundPage(bootArgs->kaddr + bootArgs->ksize); + } + addr = gImageLastKernelAddr; + gImageLastKernelAddr += RoundPage(inSize); - if ( gImageLastKernelAddr >= (KERNEL_ADDR + KERNEL_LEN) ) { - stop ("AllocateKernelMemory error"); - } - - bootArgs->ksize = gImageLastKernelAddr - bootArgs->kaddr; + if ( gImageLastKernelAddr >= (KERNEL_ADDR + KERNEL_LEN) ) { + stop ("AllocateKernelMemory error"); + } - return addr; + bootArgs->ksize = gImageLastKernelAddr - bootArgs->kaddr; + + return addr; } Index: trunk/i386/libsaio/bootargs.h =================================================================== --- trunk/i386/libsaio/bootargs.h (revision 2326) +++ trunk/i386/libsaio/bootargs.h (revision 2327) @@ -45,8 +45,8 @@ enum { kEfiReservedMemoryType = 0, - kEfiLoaderCode = 1, - kEfiLoaderData = 2, + kEfiLoaderCode = 1, + kEfiLoaderData = 2, kEfiBootServicesCode = 3, kEfiBootServicesData = 4, kEfiRuntimeServicesCode = 5, @@ -57,7 +57,7 @@ kEfiACPIMemoryNVS = 10, kEfiMemoryMappedIO = 11, kEfiMemoryMappedIOPortSpace = 12, - kEfiPalCode = 13, + kEfiPalCode = 13, kEfiMaxMemoryType = 14 }; @@ -93,15 +93,15 @@ /* Values for v_display */ -#define GRAPHICS_MODE 1 -#define FB_TEXT_MODE 2 +#define GRAPHICS_MODE 1 +#define FB_TEXT_MODE 2 /* Boot argument structure - passed into Mach kernel at boot time. * "Revision" can be incremented for compatible changes */ // Lion -#define kBootArgsRevision 0 -#define kBootArgsVersion 2 +#define kBootArgsRevision 0 +#define kBootArgsVersion 2 // Snow Leopard and older #define kBootArgsPreLionRevision 6 @@ -109,42 +109,42 @@ /* Snapshot constants of previous revisions that are supported */ -#define kBootArgsEfiMode32 32 -#define kBootArgsEfiMode64 64 +#define kBootArgsEfiMode32 32 +#define kBootArgsEfiMode64 64 typedef struct boot_args { uint16_t Revision; /* Revision of boot_args structure */ uint16_t Version; /* Version of boot_args structure */ - + uint8_t efiMode; /* 32 = 32-bit, 64 = 64-bit */ uint8_t debugMode; /* Bit field with behavior changes */ uint8_t __reserved1[2]; - + char CommandLine[BOOT_LINE_LENGTH]; /* Passed in command line */ - + uint32_t MemoryMap; /* Physical address of memory map */ uint32_t MemoryMapSize; uint32_t MemoryMapDescriptorSize; uint32_t MemoryMapDescriptorVersion; - + Boot_Video Video; /* Video Information */ - + uint32_t deviceTreeP; /* Physical address of flattened device tree */ uint32_t deviceTreeLength; /* Length of flattened tree */ - + uint32_t kaddr; /* Physical address of beginning of kernel text */ uint32_t ksize; /* Size of combined kernel text+data+efi */ - + uint32_t efiRuntimeServicesPageStart; /* physical address of defragmented runtime pages */ uint32_t efiRuntimeServicesPageCount; uint64_t efiRuntimeServicesVirtualPageStart; /* virtual address of defragmented runtime pages */ - + uint32_t efiSystemTable; /* physical address of system table in runtime area */ uint32_t __reserved2; - + uint32_t performanceDataStart; /* physical address of log */ uint32_t performanceDataSize; - + uint32_t keyStoreDataStart; /* physical address of key store data */ uint32_t keyStoreDataSize; uint64_t bootMemStart; @@ -152,32 +152,32 @@ uint64_t PhysicalMemorySize; uint64_t FSBFrequency; uint32_t __reserved4[734]; - + } boot_args; typedef struct boot_args_pre_lion { uint16_t Revision; /* Revision of boot_args structure */ uint16_t Version; /* Version of boot_args structure */ - + char CommandLine[BOOT_LINE_LENGTH]; /* Passed in command line */ - + uint32_t MemoryMap; /* Physical address of memory map */ uint32_t MemoryMapSize; uint32_t MemoryMapDescriptorSize; uint32_t MemoryMapDescriptorVersion; - + Boot_Video Video; /* Video Information */ - + uint32_t deviceTreeP; /* Physical address of flattened device tree */ uint32_t deviceTreeLength; /* Length of flattened tree */ - + uint32_t kaddr; /* Physical address of beginning of kernel text */ uint32_t ksize; /* Size of combined kernel text+data+efi */ - + uint32_t efiRuntimeServicesPageStart; /* physical address of defragmented runtime pages */ uint32_t efiRuntimeServicesPageCount; uint32_t efiSystemTable; /* physical address of system table in runtime area */ - + uint8_t efiMode; /* 32 = 32-bit, 64 = 64-bit */ uint8_t __reserved1[3]; uint32_t __reserved2[1]; @@ -185,7 +185,7 @@ uint32_t performanceDataSize; uint64_t efiRuntimeServicesVirtualPageStart; /* virtual address of defragmented runtime pages */ uint32_t __reserved3[2]; - + } boot_args_pre_lion; extern char gMacOSVersion[8]; Index: trunk/i386/libsaio/spd.c =================================================================== --- trunk/i386/libsaio/spd.c (revision 2326) +++ trunk/i386/libsaio/spd.c (revision 2327) @@ -69,43 +69,6 @@ #define SMBHSTDAT 5 #define SBMBLKDAT 7 -/** Read one byte from the intel i2c, used for reading SPD on intel chipsets only. */ -unsigned char smb_read_byte_intel(uint32_t base, uint8_t adr, uint8_t cmd) -{ - int l1, h1, l2, h2; - unsigned long long t; - - outb(base + SMBHSTSTS, 0x1f); // reset SMBus Controller - outb(base + SMBHSTDAT, 0xff); - - rdtsc(l1, h1); - while ( inb(base + SMBHSTSTS) & 0x01) // wait until read - { - rdtsc(l2, h2); - t = ((h2 - h1) * 0xffffffff + (l2 - l1)) / (Platform.CPU.TSCFrequency / 100); - if (t > 5) - return 0xFF; // break - } - - outb(base + SMBHSTCMD, cmd); - outb(base + SMBHSTADD, (adr << 1) | 0x01 ); - outb(base + SMBHSTCNT, 0x48 ); - - rdtsc(l1, h1); - - while (!( inb(base + SMBHSTSTS) & 0x02)) // wait til command finished - { - rdtsc(l2, h2); - t = ((h2 - h1) * 0xffffffff + (l2 - l1)) / (Platform.CPU.TSCFrequency / 100); - if (t > 5) - break; // break after 5ms - } - return inb(base + SMBHSTDAT); -} - -/* SPD i2c read optimization: prefetch only what we need, read non prefetcheable bytes on the fly */ -#define READ_SPD(spd, base, slot, x) spd[x] = smb_read_byte_intel(base, 0x50 + slot, x) - int spd_indexes[] = { SPD_MEMORY_TYPE, SPD_DDR3_MEMORY_BANK, @@ -119,6 +82,49 @@ }; #define SPD_INDEXES_SIZE (sizeof(spd_indexes) / sizeof(int)) +/** Read one byte from the intel i2c, used for reading SPD on intel chipsets only. */ + +unsigned char smb_read_byte_intel(uint32_t base, uint8_t adr, uint8_t cmd) +{ + int l1, h1, l2, h2; + unsigned long long t; + + outb(base + SMBHSTSTS, 0x1f); // reset SMBus Controller + outb(base + SMBHSTDAT, 0xff); + + rdtsc(l1, h1); + while ( inb(base + SMBHSTSTS) & 0x01) // wait until read + { + rdtsc(l2, h2); + t = ((h2 - h1) * 0xffffffff + (l2 - l1)) / (Platform.CPU.TSCFrequency / 100); + if (t > 5) + { + return 0xFF; // break + } + } + + outb(base + SMBHSTCMD, cmd); + outb(base + SMBHSTADD, (adr << 1) | 0x01 ); + outb(base + SMBHSTCNT, 0x48 ); + + rdtsc(l1, h1); + + while (!( inb(base + SMBHSTSTS) & 0x02)) // wait til command finished + { + rdtsc(l2, h2); + t = ((h2 - h1) * 0xffffffff + (l2 - l1)) / (Platform.CPU.TSCFrequency / 100); + if (t > 5) + { + break; // break after 5ms + } + } + return inb(base + SMBHSTDAT); +} + +/* SPD i2c read optimization: prefetch only what we need, read non prefetcheable bytes on the fly */ +#define READ_SPD(spd, base, slot, x) spd[x] = smb_read_byte_intel(base, 0x50 + slot, x) + + /** Read from spd *used* values only*/ static void init_spd(char * spd, uint32_t base, int slot) { @@ -132,115 +138,147 @@ have different formats, always return a valid ptr.*/ const char * getVendorName(RamSlotInfo_t* slot, uint32_t base, int slot_num) { - uint8_t bank = 0; - uint8_t code = 0; - int i = 0; - uint8_t * spd = (uint8_t *) slot->spd; + uint8_t bank = 0; + uint8_t code = 0; + int i = 0; + uint8_t * spd = (uint8_t *) slot->spd; - if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR3) { // DDR3 - bank = (spd[SPD_DDR3_MEMORY_BANK] & 0x07f); // constructors like Patriot use b7=1 - code = spd[SPD_DDR3_MEMORY_CODE]; - for (i=0; i < VEN_MAP_SIZE; i++) - if (bank==vendorMap[i].bank && code==vendorMap[i].code) - return vendorMap[i].name; - } - else if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR2) { - if(spd[64]==0x7f) { - for (i=64; i<72 && spd[i]==0x7f;i++) { - bank++; - READ_SPD(spd, base, slot_num,i+1); // prefetch next spd byte to read for next loop + if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR3) + { // DDR3 + bank = (spd[SPD_DDR3_MEMORY_BANK] & 0x07f); // constructors like Patriot use b7=1 + code = spd[SPD_DDR3_MEMORY_CODE]; + for (i=0; i < VEN_MAP_SIZE; i++) + { + if (bank==vendorMap[i].bank && code==vendorMap[i].code) + { + return vendorMap[i].name; } - READ_SPD(spd, base, slot_num,i); - code = spd[i]; - } else { - code = spd[64]; - bank = 0; - } - for (i=0; i < VEN_MAP_SIZE; i++) - if (bank==vendorMap[i].bank && code==vendorMap[i].code) - return vendorMap[i].name; - } - /* OK there is no vendor id here lets try to match the partnum if it exists */ - if (strstr(slot->PartNo,"GU332") == slot->PartNo) // Unifosa fingerprint - return "Unifosa"; - return "NoName"; + } + } + else if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR2 || spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR) + { + if(spd[64]==0x7f) + { + for (i=64; i<72 && spd[i]==0x7f;i++) + { + bank++; + READ_SPD(spd, base, slot_num, (uint8_t)(i+1)); // prefetch next spd byte to read for next loop + } + READ_SPD(spd, base, slot_num,(uint8_t)i); + code = spd[i]; + } + else + { + code = spd[64]; + bank = 0; + } + for (i=0; i < VEN_MAP_SIZE; i++) + { + if (bank==vendorMap[i].bank && code==vendorMap[i].code) + { + return vendorMap[i].name; + } + } + } + /* OK there is no vendor id here lets try to match the partnum if it exists */ + if (strstr(slot->PartNo,"GU332") == slot->PartNo) // Unifosa fingerprint + { + return "Unifosa"; + } + return "NoName"; } -/** Get Default Memory Module Speed (no overclocking handled) */ +/* Get Default Memory Module Speed (no overclocking handled) */ int getDDRspeedMhz(const char * spd) { - if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR3) { - switch(spd[12]) { - case 0x0f: - return 1066; - case 0x0c: - return 1333; - case 0x0a: - return 1600; - case 0x14: - default: - return 800; - } - } - else if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR2) { - switch(spd[9]) { - case 0x50: - return 400; - case 0x3d: - return 533; - case 0x30: - return 667; - case 0x25: - default: - return 800; - } - } - return 800; // default freq for unknown types + if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR3) + { + switch(spd[12]) + { + case 0x0f: + return 1066; + case 0x0c: + return 1333; + case 0x0a: + return 1600; + case 0x14: + default: + return 800; + } + } + else if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR2 || spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR) + { + switch(spd[9]) + { + case 0x50: + return 400; + case 0x3d: + return 533; + case 0x30: + return 667; + case 0x25: + default: + return 800; + case 0x1E: + return 1066; + } + } + return 800; // default freq for unknown types } #define SMST(a) ((uint8_t)((spd[a] & 0xf0) >> 4)) #define SLST(a) ((uint8_t)(spd[a] & 0x0f)) -/** Get DDR3 or DDR2 serial number, 0 most of the times, always return a valid ptr */ +/* Get DDR3 or DDR2 serial number, 0 most of the times, always return a valid ptr */ const char *getDDRSerial(const char* spd) { - static char asciiSerial[16]; + static char asciiSerial[16]; - if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR3) // DDR3 - { - sprintf(asciiSerial, "%X%X%X%X%X%X%X%X", SMST(122) /*& 0x7*/, SLST(122), SMST(123), SLST(123), SMST(124), SLST(124), SMST(125), SLST(125)); - } - else if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR2) // DDR2 or DDR - { - sprintf(asciiSerial, "%X%X%X%X%X%X%X%X", SMST(95) /*& 0x7*/, SLST(95), SMST(96), SLST(96), SMST(97), SLST(97), SMST(98), SLST(98)); - } + if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR3) // DDR3 + { + sprintf(asciiSerial, "%X%X%X%X%X%X%X%X", SMST(122) /*& 0x7*/, SLST(122), SMST(123), SLST(123), SMST(124), SLST(124), SMST(125), SLST(125)); + } + else if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR2 || spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR) // DDR2 or DDR + { + sprintf(asciiSerial, "%X%X%X%X%X%X%X%X", SMST(95) /*& 0x7*/, SLST(95), SMST(96), SLST(96), SMST(97), SLST(97), SMST(98), SLST(98)); + } else { + sprintf(asciiSerial, "0000000000000000"); + } - return strdup(asciiSerial); + return strdup(asciiSerial); } -/** Get DDR3 or DDR2 Part Number, always return a valid ptr */ +/* Get DDR3 or DDR2 Part Number, always return a valid ptr */ const char * getDDRPartNum(char* spd, uint32_t base, int slot) { static char asciiPartNo[32]; int i, start=0, index = 0; - if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR3) { + if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR3) + { start = 128; } - else if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR2) { + else if (spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR2 || spd[SPD_MEMORY_TYPE]==SPD_MEMORY_TYPE_SDRAM_DDR) + { start = 73; } - // Check that the spd part name is zero terminated and that it is ascii: - bzero(asciiPartNo, sizeof(asciiPartNo)); + // Check that the spd part name is zero terminated and that it is ascii: + bzero(asciiPartNo, sizeof(asciiPartNo)); char c; - for (i=start; i < start + sizeof(asciiPartNo); i++) { + for (i=start; i < start + sizeof(asciiPartNo); i++) + { READ_SPD(spd, base, slot, i); // only read once the corresponding model part (ddr3 or ddr2) c = spd[i]; - if (isalpha(c) || isdigit(c) || ispunct(c)) // It seems that System Profiler likes only letters and digits... + if (isalpha(c) || isdigit(c) || ispunct(c)) + { + // It seems that System Profiler likes only letters and digits... asciiPartNo[index++] = c; + } else if (!isascii(c)) + { break; + } } return strdup(asciiPartNo); @@ -249,82 +287,103 @@ int mapping []= {0,2,1,3,4,6,5,7,8,10,9,11}; -/** Read from smbus the SPD content and interpret it for detecting memory attributes */ +/* Read from smbus the SPD content and interpret it for detecting memory attributes */ static void read_smb_intel(pci_dt_t *smbus_dev) { - int i, speed; - uint8_t spd_size, spd_type; - uint32_t base, mmio, hostc; -// bool dump = false; - RamSlotInfo_t* slot; + uint16_t speed; + uint8_t i, spd_size, spd_type; + uint32_t base, mmio, hostc; +// bool dump = false; + RamSlotInfo_t* slot; uint16_t cmd = pci_config_read16(smbus_dev->dev.addr, 0x04); DBG("SMBus CmdReg: 0x%x\n", cmd); pci_config_write16(smbus_dev->dev.addr, 0x04, cmd | 1); mmio = pci_config_read32(smbus_dev->dev.addr, 0x10);// & ~0x0f; - base = pci_config_read16(smbus_dev->dev.addr, 0x20) & 0xFFFE; + base = pci_config_read16(smbus_dev->dev.addr, 0x20) & 0xFFFE; hostc = pci_config_read8(smbus_dev->dev.addr, 0x40); - verbose("Scanning SMBus [%04x:%04x], mmio: 0x%x, ioport: 0x%x, hostc: 0x%x\n", - smbus_dev->vendor_id, smbus_dev->device_id, mmio, base, hostc); + verbose("Scanning SMBus [%04x:%04x], mmio: 0x%x, ioport: 0x%x, hostc: 0x%x\n", + smbus_dev->vendor_id, smbus_dev->device_id, mmio, base, hostc); -//Azi: no use for this! -// getBoolForKey("DumpSPD", &dump, &bootInfo->chameleonConfig); + //Azi: no use for this! + // getBoolForKey("DumpSPD", &dump, &bootInfo->chameleonConfig); // needed at least for laptops - bool fullBanks = Platform.DMI.MemoryModules == Platform.DMI.CntMemorySlots; + bool fullBanks = Platform.DMI.MemoryModules == Platform.DMI.CntMemorySlots; char spdbuf[MAX_SPD_SIZE]; - // Search MAX_RAM_SLOTS slots - for (i = 0; i < MAX_RAM_SLOTS; i++){ - slot = &Platform.RAM.DIMM[i]; - spd_size = smb_read_byte_intel(base, 0x50 + i, 0); - DBG("SPD[0] (size): %d @0x%x\n", spd_size, 0x50 + i); - // Check spd is present - if (spd_size && (spd_size != 0xff)) - { + // Search MAX_RAM_SLOTS slots + for (i = 0; i < MAX_RAM_SLOTS; i++) + { + // ---- + slot = &Platform.RAM.DIMM[i]; + spd_size = smb_read_byte_intel(base, 0x50 + i, 0); + DBG("SPD[0] (size): 0x%02x @0x%x\n", spd_size, 0x50 + i); + // Check spd is present + if (spd_size && (spd_size != 0xff)) + { slot->spd = spdbuf; - slot->InUse = true; + // ----- + slot->InUse = true; - bzero(slot->spd, spd_size); - - // Copy spd data into buffer - + bzero(slot->spd, spd_size); + + // Copy spd data into buffer + //for (x = 0; x < spd_size; x++) slot->spd[x] = smb_read_byte_intel(base, 0x50 + i, x); - init_spd(slot->spd, base, i); - - switch (slot->spd[SPD_MEMORY_TYPE]) { - case SPD_MEMORY_TYPE_SDRAM_DDR2: - - slot->ModuleSize = ((1 << ((slot->spd[SPD_NUM_ROWS] & 0x0f) + (slot->spd[SPD_NUM_COLUMNS] & 0x0f) - 17)) * - ((slot->spd[SPD_NUM_DIMM_BANKS] & 0x7) + 1) * slot->spd[SPD_NUM_BANKS_PER_SDRAM]); - break; - - case SPD_MEMORY_TYPE_SDRAM_DDR3: - - slot->ModuleSize = ((slot->spd[4] & 0x0f) + 28 ) + ((slot->spd[8] & 0x7) + 3 ); - slot->ModuleSize -= (slot->spd[7] & 0x7) + 25; - slot->ModuleSize = ((1 << slot->ModuleSize) * (((slot->spd[7] >> 3) & 0x1f) + 1)); - - break; - } - - spd_type = (slot->spd[SPD_MEMORY_TYPE] < ((char) 12) ? slot->spd[SPD_MEMORY_TYPE] : 0); - slot->Type = spd_mem_to_smbios[spd_type]; - slot->PartNo = getDDRPartNum(slot->spd, base, i); - slot->Vendor = getVendorName(slot, base, i); - slot->SerialNo = getDDRSerial(slot->spd); + init_spd(slot->spd, base, i); - // determine spd speed - speed = getDDRspeedMhz(slot->spd); - if (slot->FrequencyFrequency = speed; + switch (slot->spd[SPD_MEMORY_TYPE]) + { + case SPD_MEMORY_TYPE_SDRAM_DDR: + + slot->ModuleSize = (((1 << ((slot->spd[SPD_NUM_ROWS] & 0x0f) + + (slot->spd[SPD_NUM_COLUMNS] & 0x0f) - 17)) * + ((slot->spd[SPD_NUM_DIMM_BANKS] & 0x7) + 1) * + slot->spd[SPD_NUM_BANKS_PER_SDRAM])/3)*2; + break; + + case SPD_MEMORY_TYPE_SDRAM_DDR2: + + slot->ModuleSize = ((1 << ((slot->spd[SPD_NUM_ROWS] & 0x0f) + (slot->spd[SPD_NUM_COLUMNS] & 0x0f) - 17)) * + ((slot->spd[SPD_NUM_DIMM_BANKS] & 0x7) + 1) * slot->spd[SPD_NUM_BANKS_PER_SDRAM]); + break; + + case SPD_MEMORY_TYPE_SDRAM_DDR3: + + slot->ModuleSize = ((slot->spd[4] & 0x0f) + 28 ) + ((slot->spd[8] & 0x7) + 3 ); + slot->ModuleSize -= (slot->spd[7] & 0x7) + 25; + slot->ModuleSize = ((1 << slot->ModuleSize) * (((slot->spd[7] >> 3) & 0x1f) + 1)); + + break; + } + + spd_type = (slot->spd[SPD_MEMORY_TYPE] < ((char) 12) ? slot->spd[SPD_MEMORY_TYPE] : 0); + slot->Type = spd_mem_to_smbios[spd_type]; + if (slot->Type == UNKNOWN_MEM_TYPE) + { + continue; + } + slot->PartNo = getDDRPartNum(slot->spd, base, i); + slot->Vendor = getVendorName(slot, base, i); + slot->SerialNo = getDDRSerial(slot->spd); + + // determine spd speed + speed = getDDRspeedMhz(slot->spd); + if (slot->FrequencyFrequency = speed; + } // pci memory controller if available, is more reliable - if (Platform.RAM.Frequency > 0) { + if (Platform.RAM.Frequency > 0) + { uint32_t freq = (uint32_t)Platform.RAM.Frequency / 500000; // now round off special cases uint32_t fmod100 = freq %100; - switch(fmod100) { + switch(fmod100) + { case 1: freq--; break; case 32: freq++; break; case 65: freq++; break; @@ -342,42 +401,47 @@ slot->Frequency, slot->Vendor, slot->PartNo, - slot->SerialNo); - + slot->SerialNo); + slot->InUse = true; + } - } - - // laptops sometimes show slot 0 and 2 with slot 1 empty when only 2 slots are presents so: - Platform.DMI.DIMM[i]= - i>0 && Platform.RAM.DIMM[1].InUse==false && fullBanks && Platform.DMI.CntMemorySlots == 2 ? - mapping[i] : i; // for laptops case, mapping setup would need to be more generic than this - - - + // laptops sometimes show slot 0 and 2 with slot 1 empty when only 2 slots are presents so: + Platform.DMI.DIMM[i]= + (uint32_t)((i>0 && Platform.RAM.DIMM[1].InUse==false && !fullBanks && Platform.DMI.CntMemorySlots == 2) ? + mapping[i] : i); // for laptops case, mapping setup would need to be more generic than this slot->spd = NULL; - } // for + } // for } static struct smbus_controllers_t smbus_controllers[] = { +// Info from here: http://cateee.net/lkddb/web-lkddb/I2C_I801.html - {0x8086, 0x269B, "ESB2", read_smb_intel }, - {0x8086, 0x25A4, "6300ESB", read_smb_intel }, - {0x8086, 0x24C3, "ICH4", read_smb_intel }, - {0x8086, 0x24D3, "ICH5", read_smb_intel }, - {0x8086, 0x266A, "ICH6", read_smb_intel }, - {0x8086, 0x27DA, "ICH7", read_smb_intel }, - {0x8086, 0x283E, "ICH8", read_smb_intel }, - {0x8086, 0x2930, "ICH9", read_smb_intel }, - {0x8086, 0x3A30, "ICH10R", read_smb_intel }, - {0x8086, 0x3A60, "ICH10B", read_smb_intel }, - {0x8086, 0x3B30, "5 Series", read_smb_intel }, - {0x8086, 0x1C22, "6 Series", read_smb_intel }, - {0x8086, 0x1D22, "C600/X79 Series", read_smb_intel }, - {0x8086, 0x1E22, "7 Series", read_smb_intel }, - {0x8086, 0x5032, "EP80579", read_smb_intel }, - {0x8086, 0x8C22, "8 Series", read_smb_intel }, - {0x8086, 0x9C22, "Lynx Point-LP", read_smb_intel } + {0x8086, 0x1C22, "6 Series", read_smb_intel }, + {0x8086, 0x1D22, "C600/X79 Series", read_smb_intel }, + {0x8086, 0x1D70, "C600/X79 Series", read_smb_intel }, + {0x8086, 0x1D71, "C608/C606/X79 Series", read_smb_intel }, + {0x8086, 0x1D72, "C608", read_smb_intel }, + {0x8086, 0x1E22, "7 Series/C210 Series", read_smb_intel }, + {0x8086, 0x2330, "DH89xxCC", read_smb_intel }, + {0x8086, 0x2413, "82801AA", read_smb_intel }, + {0x8086, 0x2423, "82801BA/BAM", read_smb_intel }, + {0x8086, 0x2443, "82801BA/BAM", read_smb_intel }, + {0x8086, 0x2483, "82801CA/CAM", read_smb_intel }, + {0x8086, 0x24C3, "82801DB/DBL/DBM (ICH4/ICH4-L/ICH4-M)", read_smb_intel }, + {0x8086, 0x24D3, "82801EB/ER (ICH5/ICH5R)", read_smb_intel }, + {0x8086, 0x25A4, "6300ESB", read_smb_intel }, + {0x8086, 0x266A, "82801FB/FBM/FR/FW/FRW (ICH6 Family)", read_smb_intel }, + {0x8086, 0x269B, "631xESB/632xESB/3100", read_smb_intel }, + {0x8086, 0x27DA, "N10/ICH 7 Family", read_smb_intel }, + {0x8086, 0x283E, "82801H (ICH8 Family) ", read_smb_intel }, + {0x8086, 0x2930, "82801I (ICH9 Family)", read_smb_intel }, + {0x8086, 0x3A30, "82801JI (ICH10 Family)", read_smb_intel }, + {0x8086, 0x3A60, "82801JD/DO (ICH10 Family)", read_smb_intel }, + {0x8086, 0x3B30, "5 Series/3400 Series", read_smb_intel }, + {0x8086, 0x5032, "EP80579", read_smb_intel }, + {0x8086, 0x8C22, "8 Series/C220", read_smb_intel }, + {0x8086, 0x9C22, "Lynx Point-LP", read_smb_intel } }; @@ -385,33 +449,33 @@ // find_and_read_smbus_controller(root_pci_dev); bool find_and_read_smbus_controller(pci_dt_t* pci_dt) { - pci_dt_t *current = pci_dt; - int i; + pci_dt_t *current = pci_dt; + int i; - while (current) { + while (current) + { #if 0 - printf("%02x:%02x.%x [%04x] [%04x:%04x] :: %s\n", - current->dev.bits.bus, current->dev.bits.dev, current->dev.bits.func, - current->class_id, current->vendor_id, current->device_id, - get_pci_dev_path(current)); + printf("%02x:%02x.%x [%04x] [%04x:%04x] :: %s\n", + current->dev.bits.bus, current->dev.bits.dev, current->dev.bits.func, + current->class_id, current->vendor_id, current->device_id, + get_pci_dev_path(current)); #endif - for ( i = 0; i < sizeof(smbus_controllers) / sizeof(smbus_controllers[0]); i++ ) - { - if (current->vendor_id == smbus_controllers[i].vendor && - current->device_id == smbus_controllers[i].device) - { - smbus_controllers[i].read_smb(current); // read smb - return true; - } - } - find_and_read_smbus_controller(current->children); - current = current->next; - } - return false; // not found + for ( i = 0; i < sizeof(smbus_controllers) / sizeof(smbus_controllers[0]); i++ ) + { + if (current->vendor_id == smbus_controllers[i].vendor && current->device_id == smbus_controllers[i].device) + { + smbus_controllers[i].read_smb(current); // read smb + return true; + } + } + find_and_read_smbus_controller(current->children); + current = current->next; + } + return false; // not found } void scan_spd(PlatformInfo_t *p) { - find_and_read_smbus_controller(root_pci_dev); + find_and_read_smbus_controller(root_pci_dev); } Index: trunk/i386/libsaio/spd.h =================================================================== --- trunk/i386/libsaio/spd.h (revision 2326) +++ trunk/i386/libsaio/spd.h (revision 2327) @@ -16,7 +16,7 @@ uint32_t vendor; uint32_t device; char *name; - void (*read_smb)(pci_dt_t *smbus_dev); + void (*read_smb)(pci_dt_t *smbus_dev); }; @@ -38,6 +38,7 @@ /* Byte numbers. */ #define SPD_NUM_MANUFACTURER_BYTES 0 /* Number of bytes used by module manufacturer */ #define SPD_TOTAL_SPD_MEMORY_SIZE 1 /* Total SPD memory size */ +// (Essentially) common to DDR & DDR2 #define SPD_MEMORY_TYPE 2 /* (Fundamental) memory type */ #define SPD_NUM_ROWS 3 /* Number of row address bits */ #define SPD_NUM_COLUMNS 4 /* Number of column address bits */ @@ -130,6 +131,9 @@ #define ERROR_SCHEME_NONE 0 #define ERROR_SCHEME_PARITY 1 #define ERROR_SCHEME_ECC 2 +#define DDR2_DATA_PARITY (1<<0) +#define DDR2_DATA_ECC (1<<1) +#define DDR2_ADDRESS_PARITY (1<<2) /* SPD_ACCEPTABLE_CAS_LATENCIES values. */ // TODO: Check values. @@ -141,6 +145,7 @@ #define SPD_CAS_LATENCY_3_5 0x20 #define SPD_CAS_LATENCY_4_0 0x40 +#define SPD_CAS_LATENCY_DDR2_2 (1 << 2) #define SPD_CAS_LATENCY_DDR2_3 (1 << 3) #define SPD_CAS_LATENCY_DDR2_4 (1 << 4) #define SPD_CAS_LATENCY_DDR2_5 (1 << 5) Index: trunk/i386/libsaio/bios.h =================================================================== --- trunk/i386/libsaio/bios.h (revision 2326) +++ trunk/i386/libsaio/bios.h (revision 2327) @@ -32,63 +32,63 @@ #include "bootargs.h" typedef union { - unsigned int rx; - unsigned short rr; - struct { - unsigned char l; - unsigned char h; - } r; + unsigned int rx; + unsigned short rr; + struct { + unsigned char l; + unsigned char h; + } r; } machineRegister_t; typedef struct { - unsigned short cf :1; - unsigned short :1; - unsigned short pf :1; - unsigned short :1; - unsigned short af :1; - unsigned short :1; - unsigned short zf :1; - unsigned short sf :1; - unsigned short tf :1; - unsigned short _if :1; - unsigned short df :1; - unsigned short of :1; - unsigned short iopl:2; - unsigned short nt :1; + unsigned short cf :1; + unsigned short :1; + unsigned short pf :1; + unsigned short :1; + unsigned short af :1; + unsigned short :1; + unsigned short zf :1; + unsigned short sf :1; + unsigned short tf :1; + unsigned short _if :1; + unsigned short df :1; + unsigned short of :1; + unsigned short iopl:2; + unsigned short nt :1; } machineFlags_t; typedef struct { - unsigned int intno; - machineRegister_t eax; - machineRegister_t ebx; - machineRegister_t ecx; - machineRegister_t edx; - machineRegister_t edi; - machineRegister_t esi; - machineRegister_t ebp; - unsigned short cs; - unsigned short ds; - unsigned short es; - machineFlags_t flags; + unsigned int intno; + machineRegister_t eax; + machineRegister_t ebx; + machineRegister_t ecx; + machineRegister_t edx; + machineRegister_t edi; + machineRegister_t esi; + machineRegister_t ebp; + unsigned short cs; + unsigned short ds; + unsigned short es; + machineFlags_t flags; } biosBuf_t; -#define EBIOS_FIXED_DISK_ACCESS 0x01 -#define EBIOS_LOCKING_ACCESS 0x02 -#define EBIOS_ENHANCED_DRIVE_INFO 0x04 +#define EBIOS_FIXED_DISK_ACCESS 0x01 +#define EBIOS_LOCKING_ACCESS 0x02 +#define EBIOS_ENHANCED_DRIVE_INFO 0x04 -#define BASE_HD_DRIVE 0x80 +#define BASE_HD_DRIVE 0x80 #if 0 /* * ACPI defined memory range types. */ enum { - kMemoryRangeUsable = 1, // RAM usable by the OS. - kMemoryRangeReserved = 2, // Reserved. (Do not use) - kMemoryRangeACPI = 3, // ACPI tables. Can be reclaimed. - kMemoryRangeNVS = 4, // ACPI NVS memory. (Do not use) + kMemoryRangeUsable = 1, // RAM usable by the OS. + kMemoryRangeReserved = 2, // Reserved. (Do not use) + kMemoryRangeACPI = 3, // ACPI tables. Can be reclaimed. + kMemoryRangeNVS = 4, // ACPI NVS memory. (Do not use) - /* Undefined types should be treated as kMemoryRangeReserved */ + /* Undefined types should be treated as kMemoryRangeReserved */ }; #endif @@ -96,10 +96,10 @@ * Memory range descriptor. */ typedef struct MemoryRange { - unsigned long long base; // 64-bit base address - unsigned long long length; // 64-bit length in bytes - unsigned long type; // type of memory range - unsigned long reserved; + unsigned long long base; // 64-bit base address + unsigned long long length; // 64-bit length in bytes + unsigned long type; // type of memory range + unsigned long reserved; } MemoryRange; #endif /* !__LIBSAIO_BIOS_H */ Index: trunk/i386/libsaio/gma.c =================================================================== --- trunk/i386/libsaio/gma.c (revision 2326) +++ trunk/i386/libsaio/gma.c (revision 2327) @@ -354,7 +354,7 @@ { if (intel_gfx_chipsets[i].model == ((device_id << 16) | vendor_id)) { - snprintf(desc, sizeof(desc), "%s %s", INTEL_NAME, intel_gfx_chipsets[i].label_info); + snprintf(desc, sizeof(desc), "%s %s", INTEL_NAME, intel_gfx_chipsets[i].label_info); return desc; } } @@ -388,14 +388,12 @@ verbose("Class code: [%04x]\n%s [%04x:%04x] (rev %02x)\nSubsystem: [%04x:%04x] :: %s\n", gma_dev->class_id, model, gma_dev->vendor_id, gma_dev->device_id, gma_dev->revision_id, gma_dev->subsys_id.subsys.vendor_id, gma_dev->subsys_id.subsys.device_id, devicepath); - if (!string) - { + if (!string) { string = devprop_create_string(); } struct DevPropDevice *device = devprop_add_device(string, devicepath); - if (!device) - { + if (!device) { printf("Failed initializing dev-prop string dev-entry.\n"); pause(); return false; Index: trunk/i386/libsaio/pci_root.c =================================================================== --- trunk/i386/libsaio/pci_root.c (revision 2326) +++ trunk/i386/libsaio/pci_root.c (revision 2327) @@ -79,7 +79,7 @@ // Try using the file specified with the DSDT option if (getValueForKey(kDSDT, &dsdt_filename, &len, &bootInfo->chameleonConfig)) { - snprintf(dsdt_dirSpec, sizeof(dsdt_dirSpec), dsdt_filename); + snprintf(dsdt_dirSpec, sizeof(dsdt_dirSpec), dsdt_filename); } else { @@ -105,7 +105,7 @@ } if (read (fd, new_dsdt, fsize) != fsize) { verbose("[ERROR] read %s failed\n", dsdt_filename); - free(new_dsdt); + free(new_dsdt); close (fd); goto out; } Index: trunk/i386/libsaio/aml_generator.c =================================================================== --- trunk/i386/libsaio/aml_generator.c (revision 2326) +++ trunk/i386/libsaio/aml_generator.c (revision 2327) @@ -5,11 +5,12 @@ * Created by Mozodojo on 20/07/10. * Copyright 2010 mozo. All rights reserved. * + * additions and corrections by Slice and pcj, 2012. */ #include "aml_generator.h" -bool aml_add_to_parent(struct aml_chunk* parent, struct aml_chunk* node) +bool aml_add_to_parent(AML_CHUNK* parent, AML_CHUNK* node) { if (parent && node) { @@ -24,8 +25,7 @@ verbose("aml_add_to_parent: Node doesn't support child nodes!\n"); return false; case AML_CHUNK_NAME: - if (parent->First) - { + if (parent->First) { verbose("aml_add_to_parent: Name node supports only one child node!\n"); return false; } @@ -35,12 +35,12 @@ break; } - if (!parent->First) + if (!parent->First) { parent->First = node; - - if (parent->Last) + } + if (parent->Last) { parent->Last->Next = node; - + } parent->Last = node; return true; @@ -49,47 +49,47 @@ return false; } -struct aml_chunk* aml_create_node(struct aml_chunk* parent) +AML_CHUNK* aml_create_node(AML_CHUNK* parent) { - struct aml_chunk* node = (struct aml_chunk*)malloc(sizeof(struct aml_chunk)); + AML_CHUNK* node = (AML_CHUNK*)malloc(sizeof(AML_CHUNK)); aml_add_to_parent(parent, node); return node; } -void aml_destroy_node(struct aml_chunk* node) +void aml_destroy_node(AML_CHUNK* node) { // Delete child nodes - struct aml_chunk* child = node->First; + AML_CHUNK* child = node->First; while (child) { - struct aml_chunk* next = child->Next; + AML_CHUNK* next = child->Next; - if (child->Buffer) + if (child->Buffer) { free(child->Buffer); - + } free(child); child = next; } // Free node - if (node->Buffer) + if (node->Buffer) { free(node->Buffer); + } free(node); } -struct aml_chunk* aml_add_buffer(struct aml_chunk* parent, const char* buffer, unsigned int size) +AML_CHUNK* aml_add_buffer(AML_CHUNK* parent, char* buffer, uint32_t size) { - struct aml_chunk* node = aml_create_node(parent); + AML_CHUNK* node = aml_create_node(parent); - if (node) - { + if (node) { node->Type = AML_CHUNK_NONE; - node->Length = size; + node->Length = (uint16_t)size; node->Buffer = malloc(node->Length); memcpy(node->Buffer, buffer, node->Length); } @@ -97,44 +97,38 @@ return node; } -struct aml_chunk* aml_add_byte(struct aml_chunk* parent, unsigned char value) +AML_CHUNK* aml_add_byte(AML_CHUNK* parent, uint8_t value) { - struct aml_chunk* node = aml_create_node(parent); + AML_CHUNK* node = aml_create_node(parent); - if (node) - { + if (node) { node->Type = AML_CHUNK_BYTE; - node->Length = 1; node->Buffer = malloc(node->Length); node->Buffer[0] = value; } - return node; } -struct aml_chunk* aml_add_word(struct aml_chunk* parent, unsigned int value) +AML_CHUNK* aml_add_word(AML_CHUNK* parent, uint16_t value) { - struct aml_chunk* node = aml_create_node(parent); + AML_CHUNK* node = aml_create_node(parent); - if (node) - { + if (node) { node->Type = AML_CHUNK_WORD; node->Length = 2; node->Buffer = malloc(node->Length); node->Buffer[0] = value & 0xff; node->Buffer[1] = value >> 8; } - return node; } -struct aml_chunk* aml_add_dword(struct aml_chunk* parent, unsigned long value) +AML_CHUNK* aml_add_dword(AML_CHUNK* parent, uint32_t value) { - struct aml_chunk* node = aml_create_node(parent); + AML_CHUNK* node = aml_create_node(parent); - if (node) - { + if (node) { node->Type = AML_CHUNK_DWORD; node->Length = 4; node->Buffer = malloc(node->Length); @@ -143,16 +137,14 @@ node->Buffer[2] = (value >> 16) & 0xff; node->Buffer[3] = (value >> 24) & 0xff; } - return node; } -struct aml_chunk* aml_add_qword(struct aml_chunk* parent, unsigned long long value) +AML_CHUNK* aml_add_qword(AML_CHUNK* parent, uint64_t value) { - struct aml_chunk* node = aml_create_node(parent); + AML_CHUNK* node = aml_create_node(parent); - if (node) - { + if (node) { node->Type = AML_CHUNK_QWORD; node->Length = 8; node->Buffer = malloc(node->Length); @@ -165,117 +157,126 @@ node->Buffer[6] = (value >> 48) & 0xff; node->Buffer[7] = (value >> 56) & 0xff; } - return node; } -unsigned int aml_fill_simple_name(char* buffer, const char* name) +uint32_t aml_fill_simple_name(char* buffer, char* name) { - if (strlen(name) < 4) - { + if (strlen(name) < 4) { verbose("aml_fill_simple_name: simple name %s has incorrect lengh! Must be 4.\n", name); return 0; } - memcpy(buffer, name, 4); return 4; } -unsigned int aml_fill_name(struct aml_chunk* node, const char* name) +uint32_t aml_fill_name(AML_CHUNK* node, char* name) { - if (!node) + int len, offset, count; + uint32_t root = 0; + + if (!node) { return 0; + } - int len = strlen(name), offset = 0, count = len / 4; + len = strlen(name); + offset = 0; + count = len >> 2; - if ((len % 4) > 1 || count == 0) - { + if ((len % 4) > 1 || count == 0) { verbose("aml_fill_name: pathname %s has incorrect length! Must be 4, 8, 12, 16, etc...\n", name); return 0; } - - unsigned int root = 0; - if ((len % 4) == 1 && name[0] == '\\') + if (((len % 4) == 1) && (name[0] == '\\')) { root++; - - if (count == 1) - { - node->Length = 4 + root; - node->Buffer = malloc(node->Length); + } + + if (count == 1) { + node->Length = (uint16_t)(4 + root); + node->Buffer = malloc(node->Length+4); memcpy(node->Buffer, name, 4 + root); - return node->Length; + offset += 4 + root; + return (uint32_t)offset; } - if (count == 2) - { + if (count == 2) { node->Length = 2 + 8; - node->Buffer = malloc(node->Length); + node->Buffer = malloc(node->Length+4); node->Buffer[offset++] = 0x5c; // Root Char node->Buffer[offset++] = 0x2e; // Double name memcpy(node->Buffer+offset, name + root, 8); - return node->Length; + offset += 8; + return (uint32_t)offset; } - node->Length = 3 + count*4; - node->Buffer = malloc(node->Length); + node->Length = (uint16_t)(3 + (count << 2)); + node->Buffer = malloc(node->Length+4); node->Buffer[offset++] = 0x5c; // Root Char node->Buffer[offset++] = 0x2f; // Multi name - node->Buffer[offset++] = count; // Names count + node->Buffer[offset++] = (char)count; // Names count memcpy(node->Buffer+offset, name + root, count*4); - - return node->Length; + offset += count*4; + return (uint32_t)offset; } -struct aml_chunk* aml_add_scope(struct aml_chunk* parent, const char* name) +AML_CHUNK* aml_add_scope(AML_CHUNK* parent, char* name) { - struct aml_chunk* node = aml_create_node(parent); + AML_CHUNK* node = aml_create_node(parent); - if (node) - { + if (node) { node->Type = AML_CHUNK_SCOPE; aml_fill_name(node, name); } - return node; } -struct aml_chunk* aml_add_name(struct aml_chunk* parent, const char* name) +AML_CHUNK* aml_add_name(AML_CHUNK* parent, char* name) { - struct aml_chunk* node = aml_create_node(parent); + AML_CHUNK* node = aml_create_node(parent); - if (node) - { + if (node) { node->Type = AML_CHUNK_NAME; aml_fill_name(node, name); } + return node; +} +AML_CHUNK* aml_add_method(AML_CHUNK* parent, char* name, uint8_t args) +{ + AML_CHUNK* node = aml_create_node(parent); + + if (node) { + unsigned int offset = aml_fill_name(node, name); + node->Type = AML_CHUNK_METHOD; + + node->Length++; + node->Buffer[offset] = args; + + } return node; } -struct aml_chunk* aml_add_package(struct aml_chunk* parent) +AML_CHUNK* aml_add_package(AML_CHUNK* parent) { - struct aml_chunk* node = aml_create_node(parent); + AML_CHUNK* node = aml_create_node(parent); - if (node) - { + if (node) { node->Type = AML_CHUNK_PACKAGE; node->Length = 1; node->Buffer = malloc(node->Length); } - return node; } -struct aml_chunk* aml_add_alias(struct aml_chunk* parent, const char* name1, const char* name2) +AML_CHUNK* aml_add_alias(AML_CHUNK* parent, char* name1, char* name2) { - struct aml_chunk* node = aml_create_node(parent); + AML_CHUNK* node = aml_create_node(parent); - if (node) - { + if (node) { node->Type = AML_CHUNK_ALIAS; node->Length = 8; @@ -287,46 +288,177 @@ return node; } -unsigned char aml_get_size_length(unsigned int size) +AML_CHUNK* aml_add_return_name(AML_CHUNK* parent, char* name) { + AML_CHUNK* node = aml_create_node(parent); + + if (node) { + node->Type = AML_CHUNK_RETURN; + aml_fill_name(node, name); + } + + return node; +} + +AML_CHUNK* aml_add_return_byte(AML_CHUNK* parent, uint8_t value) +{ + AML_CHUNK* node = aml_create_node(parent); + + if (node) { + node->Type = AML_CHUNK_RETURN; + aml_add_byte(node, value); + } + + return node; +} + +AML_CHUNK* aml_add_device(AML_CHUNK* parent, char* name) +{ + AML_CHUNK* node = aml_create_node(parent); + + if (node) { + node->Type = AML_CHUNK_DEVICE; + aml_fill_name(node, name); + } + + return node; +} + +AML_CHUNK* aml_add_local0(AML_CHUNK* parent) +{ + AML_CHUNK* node = aml_create_node(parent); + + if (node) { + node->Type = AML_CHUNK_LOCAL0; + node->Length = 1; + } + + return node; +} + +AML_CHUNK* aml_add_store(AML_CHUNK* parent) +{ + AML_CHUNK* node = aml_create_node(parent); + + if (node) { + node->Type = AML_STORE_OP; + node->Length = 1; + } + + return node; +} + +AML_CHUNK* aml_add_byte_buffer(AML_CHUNK* parent, char* data, uint32_t size) +{ + AML_CHUNK* node = aml_create_node(parent); + + if (node) { + int offset = 0; + node->Type = AML_CHUNK_BUFFER; + node->Length = (uint8_t)(size + 2); + node->Buffer = malloc (node->Length); + node->Buffer[offset++] = AML_CHUNK_BYTE; //0x0A + node->Buffer[offset++] = (char)size; + memcpy(node->Buffer+offset,data, node->Length); + } + + return node; +} + +AML_CHUNK* aml_add_string_buffer(AML_CHUNK* parent, char* StringBuf) +{ + AML_CHUNK* node = aml_create_node(parent); + + if (node) { + unsigned int offset = 0; + unsigned int len = strlen(StringBuf)+1; + node->Type = AML_CHUNK_BUFFER; + node->Length = (uint8_t)(len + 3); + node->Buffer = malloc (node->Length); + node->Buffer[offset++] = AML_CHUNK_BYTE; + node->Buffer[offset++] = (char)len; + memcpy(node->Buffer+offset, StringBuf, len); + node->Buffer[offset+len] = '\0'; + } + + return node; +} + +AML_CHUNK* aml_add_string(AML_CHUNK* parent, char* StringBuf) +{ + AML_CHUNK* node = aml_create_node(parent); + + if (node) { + int len = strlen(StringBuf); + node->Type = AML_CHUNK_STRING; + node->Length = (uint8_t)(len + 1); + node->Buffer = malloc (len); + memcpy(node->Buffer, StringBuf, len); + node->Buffer[len] = '\0'; + } + + return node; +} + +AML_CHUNK* aml_add_return(AML_CHUNK* parent) +{ + AML_CHUNK* node = aml_create_node(parent); + + if (node) { + node->Type = AML_CHUNK_RETURN; + //aml_add_byte(node, value); + } + + return node; +} + +uint8_t aml_get_size_length(uint32_t size) +{ if (size + 1 <= 0x3f) return 1; - else if (size + 2 <= 0x3fff) + else if (size + 2 <= 0xfff) /* Encode in 4 bits and 1 byte */ return 2; - else if (size + 3 <= 0x3fffff) + else if (size + 3 <= 0xfffff) /* Encode in 4 bits and 2 bytes */ return 3; - return 4; + return 4; /* Encode 0xfffffff in 4 bits and 2 bytes */ } -unsigned int aml_calculate_size(struct aml_chunk* node) +uint32_t aml_calculate_size(AML_CHUNK* node) { - if (node) - { - node->Size = 0; - + if (node) { // Calculate child nodes size - struct aml_chunk* child = node->First; - unsigned char child_count = 0; + AML_CHUNK* child = node->First; + uint8_t child_count = 0; - while (child) - { + node->Size = 0; + while (child) { child_count++; - node->Size += aml_calculate_size(child); + node->Size += (uint16_t)aml_calculate_size(child); child = child->Next; } - switch (node->Type) - { + switch (node->Type) { case AML_CHUNK_NONE: + case AML_STORE_OP: + case AML_CHUNK_LOCAL0: node->Size += node->Length; break; + + case AML_CHUNK_METHOD: case AML_CHUNK_SCOPE: + case AML_CHUNK_BUFFER: node->Size += 1 + node->Length; node->Size += aml_get_size_length(node->Size); break; + + case AML_CHUNK_DEVICE: + node->Size += 2 + node->Length; + node->Size += aml_get_size_length(node->Size); + break; + case AML_CHUNK_PACKAGE: node->Buffer[0] = child_count; node->Size += 1 + node->Length; @@ -334,15 +466,11 @@ break; case AML_CHUNK_BYTE: - if (node->Buffer[0] == 0x0 || node->Buffer[0] == 0x1) - { + if (node->Buffer[0] == 0x0 || node->Buffer[0] == 0x1) { node->Size += node->Length; - } - else - { + } else { node->Size += 1 + node->Length; } - break; case AML_CHUNK_WORD: @@ -350,24 +478,24 @@ case AML_CHUNK_QWORD: case AML_CHUNK_ALIAS: case AML_CHUNK_NAME: + case AML_CHUNK_RETURN: + case AML_CHUNK_STRING: node->Size += 1 + node->Length; break; } - return node->Size; } - return 0; } -unsigned int aml_write_byte(unsigned char value, char* buffer, unsigned int offset) +uint32_t aml_write_byte(uint8_t value, char* buffer, uint32_t offset) { buffer[offset++] = value; return offset; } -unsigned int aml_write_word(unsigned int value, char* buffer, unsigned int offset) +uint32_t aml_write_word(uint16_t value, char* buffer, uint32_t offset) { buffer[offset++] = value & 0xff; buffer[offset++] = value >> 8; @@ -375,7 +503,7 @@ return offset; } -unsigned int aml_write_dword(unsigned long value, char* buffer, unsigned int offset) +uint32_t aml_write_dword(uint32_t value, char* buffer, uint32_t offset) { buffer[offset++] = value & 0xff; buffer[offset++] = (value >> 8) & 0xff; @@ -385,7 +513,7 @@ return offset; } -unsigned int aml_write_qword(unsigned long long value, char* buffer, unsigned int offset) +uint32_t aml_write_qword(uint64_t value, char* buffer, uint32_t offset) { buffer[offset++] = value & 0xff; buffer[offset++] = (value >> 8) & 0xff; @@ -399,37 +527,29 @@ return offset; } -unsigned int aml_write_buffer(const char* value, unsigned int size, char* buffer, unsigned int offset) +uint32_t aml_write_buffer(const char* value, uint32_t size, char* buffer, uint32_t offset) { - if (size > 0) - { + if (size > 0) { memcpy(buffer + offset, value, size); } return offset + size; } -unsigned int aml_write_size(unsigned int size, char* buffer, unsigned int offset) +uint32_t aml_write_size(uint32_t size, char* buffer, uint32_t offset) { - if (size <= 0x3f) - { - buffer[offset++] = size; - } - else if (size <= 0x3fff) - { - buffer[offset++] = 0x40 | (size & 0xf); - buffer[offset++] = (size >> 4) & 0xff; - } - else if (size <= 0x3fffff) - { - buffer[offset++] = 0x80 | (size & 0xf); - buffer[offset++] = (size >> 4) & 0xff; + if (size <= 0x3f) { /* simple 1 byte length in 6 bits */ + buffer[offset++] = (char)size; + } else if (size <= 0xfff) { + buffer[offset++] = 0x40 | (size & 0xf); /* 0x40 is type, 0x0X is first nibble of length */ + buffer[offset++] = (size >> 4) & 0xff; /* +1 bytes for rest length */ + } else if (size <= 0xfffff) { + buffer[offset++] = 0x80 | (size & 0xf); /* 0x80 is type, 0x0X is first nibble of length */ + buffer[offset++] = (size >> 4) & 0xff; /* +2 bytes for rest length */ buffer[offset++] = (size >> 12) & 0xff; - } - else - { - buffer[offset++] = 0xc0 | (size & 0xf); - buffer[offset++] = (size >> 4) & 0xff; + } else { + buffer[offset++] = 0xc0 | (size & 0xf); /* 0xC0 is type, 0x0X is first nibble of length */ + buffer[offset++] = (size >> 4) & 0xff; /* +3 bytes for rest length */ buffer[offset++] = (size >> 12) & 0xff; buffer[offset++] = (size >> 20) & 0xff; } @@ -437,32 +557,42 @@ return offset; } -unsigned int aml_write_node(struct aml_chunk* node, char* buffer, unsigned int offset) +uint32_t aml_write_node(AML_CHUNK* node, char* buffer, uint32_t offset) { - if (node && buffer) - { - unsigned int old = offset; + if (node && buffer) { + uint32_t old = offset; + AML_CHUNK* child = node->First; - switch (node->Type) - { + switch (node->Type) { case AML_CHUNK_NONE: offset = aml_write_buffer(node->Buffer, node->Length, buffer, offset); break; + case AML_CHUNK_LOCAL0: + case AML_STORE_OP: + offset = aml_write_byte(node->Type, buffer, offset); + break; + + case AML_CHUNK_DEVICE: + offset = aml_write_byte(AML_CHUNK_OP, buffer, offset); + offset = aml_write_byte(node->Type, buffer, offset); + offset = aml_write_size(node->Size-3, buffer, offset); + offset = aml_write_buffer(node->Buffer, node->Length, buffer, offset); + break; + case AML_CHUNK_SCOPE: + case AML_CHUNK_METHOD: case AML_CHUNK_PACKAGE: + case AML_CHUNK_BUFFER: offset = aml_write_byte(node->Type, buffer, offset); offset = aml_write_size(node->Size-1, buffer, offset); offset = aml_write_buffer(node->Buffer, node->Length, buffer, offset); break; case AML_CHUNK_BYTE: - if (node->Buffer[0] == 0x0 || node->Buffer[0] == 0x1) - { + if (node->Buffer[0] == 0x0 || node->Buffer[0] == 0x1) { offset = aml_write_buffer(node->Buffer, node->Length, buffer, offset); - } - else - { + } else { offset = aml_write_byte(node->Type, buffer, offset); offset = aml_write_buffer(node->Buffer, node->Length, buffer, offset); } @@ -473,6 +603,8 @@ case AML_CHUNK_QWORD: case AML_CHUNK_ALIAS: case AML_CHUNK_NAME: + case AML_CHUNK_RETURN: + case AML_CHUNK_STRING: offset = aml_write_byte(node->Type, buffer, offset); offset = aml_write_buffer(node->Buffer, node->Length, buffer, offset); break; @@ -481,18 +613,65 @@ break; } - struct aml_chunk* child = node->First; + while (child) { + offset = aml_write_node(child, buffer, offset); - while (child) - { - offset = aml_write_node(child, buffer, offset); - child = child->Next; } - if (offset - old != node->Size) - verbose("Node size incorrect: 0x%x\n", node->Type); + if (offset - old != node->Size) { + verbose("Node size incorrect: type=0x%x size=%x offset=%x\n", + node->Type, node->Size, (offset - old)); + } } return offset; } + +//the procedure can find array char sizeof N inside part of large array "dsdt" size of len +int32_t FindBin (uint8_t *dsdt, uint32_t len, uint8_t *bin, unsigned int N) +{ + uint32_t i, j; + bool eq; + + for (i=0; ilength; return devprop_generate_string(string); } @@ -56,17 +55,14 @@ /* Use the static "device-properties" boot config key contents if available, * otheriwse use the generated one. */ - if (!getValueForKey(kDeviceProperties, &val, &cnt, &bootInfo->chameleonConfig) && string) - { + if (!getValueForKey(kDeviceProperties, &val, &cnt, &bootInfo->chameleonConfig) && string) { val = (const char*)string; cnt = strlength * 2; } - if (cnt > 1) - { + if (cnt > 1) { binStr = convertHexStr2Binary(val, &cnt2); - if (cnt2 > 0) - { + if (cnt2 > 0) { DT__AddProperty(node, DEVICE_PROPERTIES_PROP, cnt2, binStr); } } @@ -75,15 +71,17 @@ struct DevPropString *devprop_create_string(void) { string = (struct DevPropString*)malloc(sizeof(struct DevPropString)); - if (string == NULL) - return NULL; + + if(string == NULL) { + return NULL; + } memset(string, 0, sizeof(struct DevPropString)); string->length = 12; string->WHAT2 = 0x01000000; return string; } - + struct DevPropDevice *devprop_add_device(struct DevPropString *string, char *path) { struct DevPropDevice *device = NULL; @@ -101,9 +99,9 @@ } if (!(device = malloc(sizeof(struct DevPropDevice)))) { - printf("ERROR malloc failed\n"); - return NULL; - } + printf("ERROR malloc failed\n"); + return NULL; + } memset(device, 0, sizeof(struct DevPropDevice)); device->acpi_dev_path._UID = getPciRootUID(); @@ -117,12 +115,11 @@ x+=strlen(pci_device_string); curr=x; while(path[++x] != ','); - if(x-curr == 2) + if(x-curr == 2) { sprintf(buff, "%c%c", path[curr], path[curr+1]); - else if(x-curr == 1) + } else if(x-curr == 1) { sprintf(buff, "%c", path[curr]); - else - { + } else { printf("ERROR parsing device path\n"); numpaths = 0; break; @@ -132,12 +129,11 @@ x += 3; // 0x curr = x; while(path[++x] != ')'); - if(x-curr == 2) + if(x-curr == 2) { sprintf(buff, "%c%c", path[curr], path[curr+1]); - else if(x-curr == 1) + } else if(x-curr == 1) { sprintf(buff, "%c", path[curr]); - else - { + } else { printf("ERROR parsing device path\n"); numpaths = 0; break; @@ -148,10 +144,10 @@ } } - if (!numpaths) { - free(device); - return NULL; - } + if(!numpaths) { + free(device); + return NULL; + } device->numentries = 0x00; @@ -163,7 +159,7 @@ device->num_pci_devpaths = numpaths; device->length = 24 + (6*numpaths); - int i; + int i; for(i = 0; i < numpaths; i++) { @@ -178,27 +174,28 @@ device->string = string; device->data = NULL; - - if (!string->entries) - if (!(string->entries = (struct DevPropDevice**) malloc(sizeof(device) * DEV_PROP_DEVICE_MAX_ENTRIES))) { - free(device); - return NULL; - } - - /* FIXME: probably needs bounds checking, as well as error handling in event of malloc failure */ + + if(!string->entries) { + if (!(string->entries = (struct DevPropDevice**) malloc(sizeof(device) * DEV_PROP_DEVICE_MAX_ENTRIES))) { + free(device); + return NULL; + } + } + + /* FIXME: probably needs bounds checking, as well as error handling in event of malloc failure */ string->length += device->length; string->entries[string->numentries++] = (struct DevPropDevice*)malloc(sizeof(device)); string->entries[string->numentries-1] = device; - + return device; } int devprop_add_value(struct DevPropDevice *device, char *nm, uint8_t *vl, uint32_t len) { - - if(!nm || !vl || !len) + + if(!nm || !vl || !len) { return 0; - + } uint32_t length = ((strlen(nm) * 2) + len + (2 * sizeof(uint32_t)) + 2); uint8_t *data = (uint8_t*)malloc(length); { @@ -222,13 +219,13 @@ off += 2; l = len; uint32_t *datalength = (uint32_t*)&data[off]; - *datalength = l + 4; + *datalength = (uint32_t)(l + 4); off += 4; for(i = 0 ; i < l ; i++, off++) { data[off] = *vl++; } - } + } uint32_t offset = device->length - (24 + (6 * device->num_pci_devpaths)); @@ -294,7 +291,7 @@ dp_swap32(string->entries[i]->acpi_dev_path._UID)); buffer += 24; - for(x=0;x < string->entries[i]->num_pci_devpaths; x++) + for(x = 0;x < string->entries[i]->num_pci_devpaths; x++) { sprintf(buffer, "%02x%02x%04x%02x%02x", string->entries[i]->pci_dev_path[x].type, string->entries[i]->pci_dev_path[x].subtype, @@ -310,7 +307,7 @@ buffer += 8; uint8_t *dataptr = string->entries[i]->data; - for(x = 0; x < (string->entries[i]->length) - (24 + (6 * string->entries[i]->num_pci_devpaths)) ; x++) + for(x = 0; (uint32_t)x < (string->entries[i]->length) - (24 + (6 * string->entries[i]->num_pci_devpaths)) ; x++) { sprintf(buffer, "%02x", *dataptr++); buffer += 2; @@ -410,17 +407,18 @@ verbose("LAN Controller [%04x:%04x] :: %s\n", eth_dev->vendor_id, eth_dev->device_id, devicepath); - if(!string) - string = devprop_create_string(); + if(!string) { + string = devprop_create_string(); + } - device = devprop_add_device(string, devicepath); + device = devprop_add_device(string, devicepath); if(device) { - verbose("Setting up lan keys\n"); - devprop_add_network_template(device, eth_dev->vendor_id); - stringdata = (uint8_t*)malloc(sizeof(uint8_t) * string->length); - if(stringdata) { - memcpy(stringdata, (uint8_t*)devprop_generate_string(string), string->length); - stringlength = string->length; - } + verbose("Setting up lan keys\n"); + devprop_add_network_template(device, eth_dev->vendor_id); + stringdata = (uint8_t*)malloc(sizeof(uint8_t) * string->length); + if(stringdata) { + memcpy(stringdata, (uint8_t*)devprop_generate_string(string), string->length); + stringlength = string->length; + } } } Index: trunk/i386/libsaio/hda.c =================================================================== --- trunk/i386/libsaio/hda.c (revision 2326) +++ trunk/i386/libsaio/hda.c (revision 2327) @@ -478,40 +478,50 @@ /* get HDA device name */ static char *get_hda_controller_name(uint16_t controller_device_id, uint16_t controller_vendor_id) { - int i; static char desc[128]; - for (i = 0; i < HDAC_DEVICES_LEN; i++) - { - if (know_hda_controller[i].model == ((controller_device_id << 16) | controller_vendor_id)) - { - if(controller_vendor_id == INTEL_VENDORID){ - sprintf(desc, "Intel %s Hight Definition Audio Controller", know_hda_controller[i].desc); - desc[sizeof(desc) - 1] = '\0'; - } else if (controller_vendor_id == NVIDIA_VENDORID) { - sprintf(desc, "nVidia %s HDA Controller (HDMi)", know_hda_controller[i].desc); - desc[sizeof(desc) - 1] = '\0'; - } else if (controller_vendor_id == ATI_VENDORID) { - sprintf(desc, "ATI %s HDA Controller (HDMi)", know_hda_controller[i].desc); - desc[sizeof(desc) - 1] = '\0'; - } else if (controller_vendor_id == RDC_VENDORID) { - sprintf(desc, "RDC %s Hight Definition Audio Controller", know_hda_controller[i].desc); - desc[sizeof(desc) - 1] = '\0'; - } else if (controller_vendor_id == VIA_VENDORID) { - sprintf(desc, "VIA %s HDA Controller", know_hda_controller[i].desc); - desc[sizeof(desc) - 1] = '\0'; - } else if (controller_vendor_id == SIS_VENDORID) { - sprintf(desc, "SiS %s HDA Controller", know_hda_controller[i].desc); - desc[sizeof(desc) - 1] = '\0'; - } else if (controller_vendor_id == ULI_VENDORID) { - sprintf(desc, "ULI %s HDA Controller", know_hda_controller[i].desc); - desc[sizeof(desc) - 1] = '\0'; - } + const char* name_format = "Unknown HD Audio device %s"; + uint32_t controller_model = ((controller_device_id << 16) | controller_vendor_id); + int i; + + /* Get format for vendor ID */ + switch (controller_vendor_id) { + case ATI_VENDORID: + name_format = "ATI %s HDA Controller (HDMi)"; break; + + case INTEL_VENDORID: + name_format = "Intel %s High Definition Audio Controller"; break; + + case NVIDIA_VENDORID: + name_format = "nVidia %s HDA Controller (HDMi)"; break; + + case RDC_VENDORID: + name_format = "RDC %s High Definition Audio Controller"; break; + + case SIS_VENDORID: + name_format = "SiS %s HDA Controller"; break; + + case ULI_VENDORID: + name_format = "ULI %s HDA Controller"; break; + + case VIA_VENDORID: + name_format = "VIA %s HDA Controller"; break; + + default: + break; + } + + for (i = 0; i < HDAC_DEVICES_LEN; i++) { + if (know_hda_controller[i].model == controller_model) { + snprintf(desc, sizeof(desc), name_format, know_hda_controller[i].desc); return desc; } } - sprintf(desc, "Unknown HD Audio device"); - desc[sizeof(desc) - 1] = '\0'; + + /* Not in table */ + snprintf(desc, sizeof(desc), + "Unknown HD Audio device, vendor %04x, model %04x", + controller_vendor_id, controller_device_id); return desc; } Index: trunk/i386/libsaio/device_inject.h =================================================================== --- trunk/i386/libsaio/device_inject.h (revision 2326) +++ trunk/i386/libsaio/device_inject.h (revision 2327) @@ -43,7 +43,7 @@ uint16_t numentries; uint16_t WHAT2; // 0x0000 ? struct ACPIDevPath acpi_dev_path; // = 0x02010c00 0xd041030a - struct PCIDevPath pci_dev_path[MAX_PCI_DEV_PATHS]; // = 0x01010600 func dev + struct PCIDevPath pci_dev_path[MAX_PCI_DEV_PATHS]; // = 0x01010600 func dev struct DevicePathEnd path_end; // = 0x7fff0400 uint8_t *data; Index: trunk/i386/libsaio/base64-decode.c =================================================================== --- trunk/i386/libsaio/base64-decode.c (revision 2326) +++ trunk/i386/libsaio/base64-decode.c (revision 2327) @@ -36,8 +36,7 @@ { /* Wrong base64 string length */ return NULL; - - } + } result = dest = malloc(in_len / 4 * 3 + 1); if (result == NULL) return NULL; /* out of memory */ @@ -68,4 +67,4 @@ } -/* end of base64.c */ \ No newline at end of file +/* end of base64.c */ Index: trunk/i386/libsaio/fdisk.h =================================================================== --- trunk/i386/libsaio/fdisk.h (revision 2326) +++ trunk/i386/libsaio/fdisk.h (revision 2327) @@ -35,58 +35,58 @@ #ifndef __LIBSAIO_FDISK_H #define __LIBSAIO_FDISK_H -#define DISK_BLK0 0 /* blkno of boot block */ -#define DISK_BLK0SZ 512 /* size of boot block */ -#define DISK_BOOTSZ 446 /* size of boot code in boot block */ +#define DISK_BLK0 0 /* blkno of boot block */ +#define DISK_BLK0SZ 512 /* size of boot block */ +#define DISK_BOOTSZ 446 /* size of boot code in boot block */ #define DISK_SIGNATURE 0xAA55 /* signature of the boot record */ -#define FDISK_NPART 4 /* number of entries in fdisk table */ +#define FDISK_NPART 4 /* number of entries in fdisk table */ #define FDISK_ACTIVE 0x80 /* indicator of active partition */ #define FDISK_NEXTNAME 0xA7 /* indicator of NeXT partition */ -#define FDISK_DOS12 0x01 /* 12-bit fat < 10MB dos partition */ +#define FDISK_DOS12 0x01 /* 12-bit fat < 10MB dos partition */ #define FDISK_DOS16S 0x04 /* 16-bit fat < 32MB dos partition */ -#define FDISK_DOSEXT 0x05 /* extended dos partition */ +#define FDISK_DOSEXT 0x05 /* extended DOS partition */ #define FDISK_DOS16B 0x06 /* 16-bit fat >= 32MB dos partition */ -#define FDISK_NTFS 0x07 /* NTFS partition */ -#define FDISK_SMALLFAT32 0x0b /* FAT32 partition */ -#define FDISK_FAT32 0x0c /* FAT32 partition */ -#define FDISK_DOS16SLBA 0x0e -#define FDISK_LINUX 0x83 +#define FDISK_NTFS 0x07 /* NTFS partition */ +#define FDISK_SMALLFAT32 0x0b /* FAT32 partition */ +#define FDISK_FAT32 0x0c /* FAT32 partition */ +#define FDISK_DOS16SLBA 0x0e /* 16-bit FAT, LBA-mapped */ +#define FDISK_LINUX 0x83 /* Linux native */ #define FDISK_OPENBSD 0xa6 /* OpenBSD FFS partition */ #define FDISK_FREEBSD 0xa5 /* FreeBSD UFS2 partition */ #define FDISK_BEFS 0xeb /* Haiku BeFS partition */ -#define FDISK_UFS 0xa8 /* Apple UFS partition */ -#define FDISK_HFS 0xaf /* Apple HFS partition */ +#define FDISK_UFS 0xa8 /* Apple UFS partition */ +#define FDISK_HFS 0xaf /* Apple HFS partition */ #define FDISK_BOOTER 0xab /* Apple booter partition */ /* * Format of fdisk partion entry (if present). */ struct fdisk_part { - unsigned char bootid; /* bootable or not */ - unsigned char beghead; /* begining head, sector, cylinder */ - unsigned char begsect; /* begcyl is a 10-bit number */ - unsigned char begcyl; /* High 2 bits are in begsect */ - unsigned char systid; /* OS type */ - unsigned char endhead; /* ending head, sector, cylinder */ - unsigned char endsect; /* endcyl is a 10-bit number */ - unsigned char endcyl; /* High 2 bits are in endsect */ - unsigned long relsect; /* partion physical offset on disk */ - unsigned long numsect; /* number of sectors in partition */ + unsigned char bootid; /* bootable or not */ + unsigned char beghead; /* begining head, sector, cylinder */ + unsigned char begsect; /* begcyl is a 10-bit number */ + unsigned char begcyl; /* High 2 bits are in begsect */ + unsigned char systid; /* OS type */ + unsigned char endhead; /* ending head, sector, cylinder */ + unsigned char endsect; /* endcyl is a 10-bit number */ + unsigned char endcyl; /* High 2 bits are in endsect */ + unsigned long relsect; /* partion physical offset on disk */ + unsigned long numsect; /* number of sectors in partition */ } __attribute__((packed)); /* * Format of boot block. */ struct disk_blk0 { - unsigned char bootcode[DISK_BOOTSZ]; - unsigned char parts[FDISK_NPART][sizeof (struct fdisk_part)]; - unsigned short signature; + unsigned char bootcode[DISK_BOOTSZ]; + unsigned char parts[FDISK_NPART][sizeof (struct fdisk_part)]; + unsigned short signature; }; struct REAL_disk_blk0 { - unsigned char bootcode[DISK_BOOTSZ]; - struct fdisk_part parts[FDISK_NPART]; - unsigned short signature; + unsigned char bootcode[DISK_BOOTSZ]; + struct fdisk_part parts[FDISK_NPART]; + unsigned short signature; } __attribute__((packed)); #endif /* !__LIBSAIO_FDISK_H */ Index: trunk/i386/libsaio/dram_controllers.c =================================================================== --- trunk/i386/libsaio/dram_controllers.c (revision 2326) +++ trunk/i386/libsaio/dram_controllers.c (revision 2327) @@ -37,7 +37,7 @@ static void setup_p35(pci_dt_t *dram_dev) { uint32_t dev0; - + // Activate MMR I/O dev0 = pci_config_read32(dram_dev->dev.addr, 0x48); if (!(dev0 & 0x1)) @@ -63,7 +63,7 @@ did = pci_config_read16(PCIADDR(possible_nhm_bus[i], 3, 4), PCI_DEVICE_ID); vid &= 0xFFFF; did &= 0xFF00; - + if(vid == 0x8086 && did >= 0x2C00) { nhm_bus = possible_nhm_bus[i]; @@ -82,28 +82,28 @@ uint32_t dev0, mch_ratio, mch_cfg, mch_fsb; long *ptr; - + // Find Ratio dev0 = pci_config_read32(dram_dev->dev.addr, 0x48); dev0 &= 0xFFFFC000; ptr = (long*)(dev0 + 0xC00); mch_cfg = *ptr & 0xFFFF; - + mch_ratio = 100000; - + switch (mch_cfg & 7) { case 0: mch_fsb = 1066; break; case 1: mch_fsb = 533; break; - default: + default: case 2: mch_fsb = 800; break; - case 3: mch_fsb = 667; break; + case 3: mch_fsb = 667; break; case 4: mch_fsb = 1333; break; - case 6: mch_fsb = 1600; break; + case 6: mch_fsb = 1600; break; } - + DBG("mch_fsb %d\n", mch_fsb); - + switch (mch_fsb) { case 533: @@ -114,7 +114,7 @@ case 3: mch_ratio = 300000; break; } break; - + default: case 800: switch ((mch_cfg >> 4) & 7) @@ -127,7 +127,7 @@ case 5: mch_ratio = 333333; break; // 3.333333333 } break; - + case 1066: switch ((mch_cfg >> 4) & 7) { @@ -138,7 +138,7 @@ case 5: mch_ratio = 250000; break; } break; - + case 1333: switch ((mch_cfg >> 4) & 7) { @@ -148,7 +148,7 @@ case 5: mch_ratio = 200000; break; } break; - + case 1600: switch ((mch_cfg >> 4) & 7) { @@ -159,12 +159,12 @@ } break; } - + DBG("mch_ratio %d\n", mch_ratio); // Compute RAM Frequency Platform.RAM.Frequency = (Platform.CPU.FSBFrequency * mch_ratio) / 100000; - + DBG("ram_fsb %d\n", Platform.RAM.Frequency); } @@ -175,24 +175,24 @@ uint32_t dev0, mch_ratio, mch_cfg, mch_fsb; long *ptr; - + // Find Ratio dev0 = pci_config_read32(dram_dev->dev.addr, 0x48); dev0 &= 0xFFFFC000; ptr = (long*)(dev0 + 0xC00); mch_cfg = *ptr & 0xFFFF; - + mch_ratio = 100000; - + switch (mch_cfg & 7) { case 1: mch_fsb = 533; break; default: case 2: mch_fsb = 800; break; - case 3: mch_fsb = 667; break; - case 6: mch_fsb = 1066; break; + case 3: mch_fsb = 667; break; + case 6: mch_fsb = 1066; break; } - + switch (mch_fsb) { case 533: @@ -203,7 +203,7 @@ case 3: mch_ratio = 200000; break; } break; - + case 667: switch ((mch_cfg >> 4)& 7) { @@ -214,7 +214,7 @@ case 5: mch_ratio = 240000; break; } break; - + default: case 800: switch ((mch_cfg >> 4) & 7) @@ -232,9 +232,9 @@ case 5: mch_ratio = 150000; break; case 6: mch_ratio = 200000; break; } - + } - + // Compute RAM Frequency Platform.RAM.Frequency = (Platform.CPU.FSBFrequency * mch_ratio) / 100000; } @@ -244,11 +244,11 @@ static void get_fsb_nhm(pci_dt_t *dram_dev) { uint32_t mch_ratio, mc_dimm_clk_ratio; - + // Get the clock ratio mc_dimm_clk_ratio = pci_config_read16(PCIADDR(nhm_bus, 3, 4), 0x54 ); mch_ratio = (mc_dimm_clk_ratio & 0x1F); - + // Compute RAM Frequency Platform.RAM.Frequency = Platform.CPU.FSBFrequency * mch_ratio / 2; } @@ -259,60 +259,61 @@ // Get i965 Memory Timings static void get_timings_i965(pci_dt_t *dram_dev) -{ +{ // Thanks for CDH optis uint32_t dev0, c0ckectrl, c1ckectrl, offset; uint32_t ODT_Control_Register, Precharge_Register, ACT_Register, Read_Register, Misc_Register; long *ptr; - + // Read MMR Base Address dev0 = pci_config_read32(dram_dev->dev.addr, 0x48); dev0 &= 0xFFFFC000; - + ptr = (long*)(dev0 + 0x260); c0ckectrl = *ptr & 0xFFFFFFFF; - + ptr = (long*)(dev0 + 0x660); c1ckectrl = *ptr & 0xFFFFFFFF; - + // If DIMM 0 not populated, check DIMM 1 ((c0ckectrl) >> 20 & 0xF) ? (offset = 0) : (offset = 0x400); - + ptr = (long*)(dev0 + offset + 0x29C); ODT_Control_Register = *ptr & 0xFFFFFFFF; - + ptr = (long*)(dev0 + offset + 0x250); Precharge_Register = *ptr & 0xFFFFFFFF; - + ptr = (long*)(dev0 + offset + 0x252); ACT_Register = *ptr & 0xFFFFFFFF; - + ptr = (long*)(dev0 + offset + 0x258); Read_Register = *ptr & 0xFFFFFFFF; - + ptr = (long*)(dev0 + offset + 0x244); Misc_Register = *ptr & 0xFFFFFFFF; - + // 965 Series only support DDR2 Platform.RAM.Type = SMB_MEM_TYPE_DDR2; - + // CAS Latency (tCAS) Platform.RAM.CAS = ((ODT_Control_Register >> 17) & 7) + 3; - + // RAS-To-CAS (tRCD) Platform.RAM.TRC = (Read_Register >> 16) & 0xF; - + // RAS Precharge (tRP) Platform.RAM.TRP = (ACT_Register >> 13) & 0xF; - + // RAS Active to precharge (tRAS) Platform.RAM.RAS = (Precharge_Register >> 11) & 0x1F; - - if ((c0ckectrl >> 20 & 0xF) && (c1ckectrl >> 20 & 0xF)) + + if ((c0ckectrl >> 20 & 0xF) && (c1ckectrl >> 20 & 0xF)) { Platform.RAM.Channels = SMB_MEM_CHANNEL_DUAL; - else + } else { Platform.RAM.Channels = SMB_MEM_CHANNEL_SINGLE; + } } // Get im965 Memory Timings @@ -321,127 +322,131 @@ // Thanks for CDH optis uint32_t dev0, c0ckectrl, c1ckectrl, offset, ODT_Control_Register, Precharge_Register; long *ptr; - + // Read MMR Base Address dev0 = pci_config_read32(dram_dev->dev.addr, 0x48); dev0 &= 0xFFFFC000; - + ptr = (long*)(dev0 + 0x1200); c0ckectrl = *ptr & 0xFFFFFFFF; - + ptr = (long*)(dev0 + 0x1300); c1ckectrl = *ptr & 0xFFFFFFFF; - + // If DIMM 0 not populated, check DIMM 1 ((c0ckectrl) >> 20 & 0xF) ? (offset = 0) : (offset = 0x100); - + ptr = (long*)(dev0 + offset + 0x121C); ODT_Control_Register = *ptr & 0xFFFFFFFF; - + ptr = (long*)(dev0 + offset + 0x1214); Precharge_Register = *ptr & 0xFFFFFFFF; - + // Series only support DDR2 Platform.RAM.Type = SMB_MEM_TYPE_DDR2; - + // CAS Latency (tCAS) Platform.RAM.CAS = ((ODT_Control_Register >> 23) & 7) + 3; - + // RAS-To-CAS (tRCD) Platform.RAM.TRC = ((Precharge_Register >> 5) & 7) + 2; - + // RAS Precharge (tRP) Platform.RAM.TRP= (Precharge_Register & 7) + 2; - + // RAS Active to precharge (tRAS) Platform.RAM.RAS = (Precharge_Register >> 21) & 0x1F; - - if ((c0ckectrl >> 20 & 0xF) && (c1ckectrl >> 20 & 0xF)) + + if ((c0ckectrl >> 20 & 0xF) && (c1ckectrl >> 20 & 0xF)) { Platform.RAM.Channels = SMB_MEM_CHANNEL_DUAL; - else + } else { Platform.RAM.Channels = SMB_MEM_CHANNEL_SINGLE; + } } // Get P35 Memory Timings static void get_timings_p35(pci_dt_t *dram_dev) -{ +{ // Thanks for CDH optis unsigned long dev0, Memory_Check, c0ckectrl, c1ckectrl, offset; unsigned long ODT_Control_Register, Precharge_Register, ACT_Register, Read_Register, Misc_Register; long *ptr; - + //Device_ID = pci_config_read16(dram_dev->dev.addr, 0x02); //Device_ID &= 0xFFFF; - + // Now, read MMR Base Address dev0 = pci_config_read32(dram_dev->dev.addr, 0x48); dev0 &= 0xFFFFC000; - + ptr = (long*)(dev0 + 0x260); - c0ckectrl = *ptr & 0xFFFFFFFF; - + c0ckectrl = *ptr & 0xFFFFFFFF; + ptr = (long*)(dev0 + 0x660); c1ckectrl = *ptr & 0xFFFFFFFF; - + // If DIMM 0 not populated, check DIMM 1 ((c0ckectrl) >> 20 & 0xF) ? (offset = 0) : (offset = 0x400); - + ptr = (long*)(dev0 + offset + 0x265); ODT_Control_Register = *ptr & 0xFFFFFFFF; - - ptr = (long*)(dev0 + offset + 0x25D); + + ptr = (long*)(dev0 + offset + 0x25D); Precharge_Register = *ptr & 0xFFFFFFFF; - + ptr = (long*)(dev0 + offset + 0x252); ACT_Register = *ptr & 0xFFFFFFFF; - + ptr = (long*)(dev0 + offset + 0x258); Read_Register = *ptr & 0xFFFFFFFF; - + ptr = (long*)(dev0 + offset + 0x244); Misc_Register = *ptr & 0xFFFFFFFF; - + ptr = (long*)(dev0 + offset + 0x1E8); - Memory_Check = *ptr & 0xFFFFFFFF; - + Memory_Check = *ptr & 0xFFFFFFFF; + // On P45, check 1A8 if(dram_dev->device_id > 0x2E00) { ptr = (long*)(dev0 + offset + 0x1A8); - Memory_Check = *ptr & 0xFFFFFFFF; + Memory_Check = *ptr & 0xFFFFFFFF; Memory_Check >>= 2; Memory_Check &= 1; Memory_Check = !Memory_Check; } else { ptr = (long*)(dev0 + offset + 0x1E8); - Memory_Check = *ptr & 0xFFFFFFFF; + Memory_Check = *ptr & 0xFFFFFFFF; } - + // Determine DDR-II or DDR-III - if (Memory_Check & 1) + if (Memory_Check & 1) { Platform.RAM.Type = SMB_MEM_TYPE_DDR2; - else + } else { Platform.RAM.Type = SMB_MEM_TYPE_DDR3; + } // CAS Latency (tCAS) - if(dram_dev->device_id > 0x2E00) + if(dram_dev->device_id > 0x2E00) { Platform.RAM.CAS = ((ODT_Control_Register >> 8) & 0x3F) - 6; - else + } else { Platform.RAM.CAS = ((ODT_Control_Register >> 8) & 0x3F) - 9; + } // RAS-To-CAS (tRCD) Platform.RAM.TRC = (Read_Register >> 17) & 0xF; - + // RAS Precharge (tRP) Platform.RAM.TRP = (ACT_Register >> 13) & 0xF; - + // RAS Active to precharge (tRAS) Platform.RAM.RAS = Precharge_Register & 0x3F; - + // Channel configuration - if (((c0ckectrl >> 20) & 0xF) && ((c1ckectrl >> 20) & 0xF)) + if (((c0ckectrl >> 20) & 0xF) && ((c1ckectrl >> 20) & 0xF)) { Platform.RAM.Channels = SMB_MEM_CHANNEL_DUAL; - else + } else { Platform.RAM.Channels = SMB_MEM_CHANNEL_SINGLE; + } } // Get Nehalem Memory Timings @@ -449,45 +454,47 @@ { unsigned long mc_channel_bank_timing, mc_control, mc_channel_mrs_value; int fvc_bn = 4; - + // Find which channels are populated mc_control = pci_config_read16(PCIADDR(nhm_bus, 3, 0), 0x48); mc_control = (mc_control >> 8) & 0x7; - + // DDR-III Platform.RAM.Type = SMB_MEM_TYPE_DDR3; - + // Get the first valid channel - if(mc_control & 1) + if(mc_control & 1) { fvc_bn = 4; - else if(mc_control & 2) + } else if(mc_control & 2) { fvc_bn = 5; - else if(mc_control & 7) + } else if(mc_control & 7) { fvc_bn = 6; + } // Now, detect timings mc_channel_bank_timing = pci_config_read32(PCIADDR(nhm_bus, fvc_bn, 0), 0x88); mc_channel_mrs_value = pci_config_read32(PCIADDR(nhm_bus, fvc_bn, 0), 0x70); - + // CAS Latency (tCAS) Platform.RAM.CAS = ((mc_channel_mrs_value >> 4) & 0xF ) + 4; - + // RAS-To-CAS (tRCD) Platform.RAM.TRC = (mc_channel_bank_timing >> 9) & 0xF; - + // RAS Active to precharge (tRAS) Platform.RAM.RAS = (mc_channel_bank_timing >> 4) & 0x1F; - + // RAS Precharge (tRP) Platform.RAM.TRP = mc_channel_bank_timing & 0xF; - + // Single , Dual or Triple Channels - if (mc_control == 1 || mc_control == 2 || mc_control == 4 ) + if (mc_control == 1 || mc_control == 2 || mc_control == 4 ) { Platform.RAM.Channels = SMB_MEM_CHANNEL_SINGLE; - else if (mc_control == 7) + } else if (mc_control == 7) { Platform.RAM.Channels = SMB_MEM_CHANNEL_TRIPLE; - else + } else { Platform.RAM.Channels = SMB_MEM_CHANNEL_DUAL; + } } static struct mem_controller_t dram_controllers[] = { @@ -496,72 +503,100 @@ { 0, 0, "", NULL, NULL, NULL }, // Intel +// { 0x8086, 0x0100, "2rd Gen Core processor", NULL, NULL, NULL }, +// { 0x8086, 0x0104, "2rd Gen Core processor", NULL, NULL, NULL }, +// { 0x8086, 0x010C, "Xeon E3-1200/2rd Gen Core processor", NULL, NULL, NULL }, +// { 0x8086, 0x0150, "Xeon E3-1200 v2/3rd Gen Core processor", NULL, NULL, NULL }, +// { 0x8086, 0x0154, "3rd Gen Core processor", NULL, NULL, NULL }, +// { 0x8086, 0x0158, "Xeon E3-1200 v2/Ivy Bridge", NULL, NULL, NULL }, +// { 0x8086, 0x015C, "Xeon E3-1200 v2/3rd Gen Core processor", NULL, NULL, NULL }, + +// { 0x8086, 0x0BF0, "Atom Processor D2xxx/N2xxx", NULL, NULL, NULL }, +// { 0x8086, 0x0BF1, "Atom Processor D2xxx/N2xxx", NULL, NULL, NULL }, +// { 0x8086, 0x0BF2, "Atom Processor D2xxx/N2xxx", NULL, NULL, NULL }, +// { 0x8086, 0x0BF3, "Atom Processor D2xxx/N2xxx", NULL, NULL, NULL }, +// { 0x8086, 0x0BF4, "Atom Processor D2xxx/N2xxx", NULL, NULL, NULL }, +// { 0x8086, 0x0BF5, "Atom Processor D2xxx/N2xxx", NULL, NULL, NULL }, +// { 0x8086, 0x0BF6, "Atom Processor D2xxx/N2xxx", NULL, NULL, NULL }, +// { 0x8086, 0x0BF7, "Atom Processor D2xxx/N2xxx", NULL, NULL, NULL }, + +// { 0x8086, 0x0C00, "Haswell", NULL, NULL, NULL }, +// { 0x8086, 0x0C04, "Haswell", NULL, NULL, NULL }, +// { 0x8086, 0x0C08, "Haswell", NULL, NULL, NULL }, + { 0x8086, 0x7190, "VMWare", NULL, NULL, NULL }, - { 0x8086, 0x1A30, "i845", NULL, NULL, NULL }, + { 0x8086, 0x1A30, "82845 845 [Brookdale]", NULL, NULL, NULL }, - { 0x8086, 0x2970, "i946PL/GZ", setup_p35, get_fsb_i965, get_timings_i965 }, - { 0x8086, 0x2990, "Q963/Q965", setup_p35, get_fsb_i965, get_timings_i965 }, + { 0x8086, 0x2970, "82946GZ/PL/GL", setup_p35, get_fsb_i965, get_timings_i965 }, + { 0x8086, 0x2990, "82Q963/Q965", setup_p35, get_fsb_i965, get_timings_i965 }, { 0x8086, 0x29A0, "P965/G965", setup_p35, get_fsb_i965, get_timings_i965 }, { 0x8086, 0x2A00, "GM965/GL960", setup_p35, get_fsb_im965, get_timings_im965 }, { 0x8086, 0x2A10, "GME965/GLE960", setup_p35, get_fsb_im965, get_timings_im965 }, { 0x8086, 0x2A40, "PM/GM45/47", setup_p35, get_fsb_im965, get_timings_im965 }, - { 0x8086, 0x29B0, "Q35", setup_p35, get_fsb_i965, get_timings_p35 }, - { 0x8086, 0x29C0, "P35/G33", setup_p35, get_fsb_i965, get_timings_p35 }, - { 0x8086, 0x29D0, "Q33", setup_p35, get_fsb_i965, get_timings_p35 }, - { 0x8086, 0x29E0, "X38/X48", setup_p35, get_fsb_i965, get_timings_p35 }, + { 0x8086, 0x29B0, "82Q35 Express", setup_p35, get_fsb_i965, get_timings_p35 }, + { 0x8086, 0x29C0, "82G33/G31/P35/P31", setup_p35, get_fsb_i965, get_timings_p35 }, + { 0x8086, 0x29D0, "82Q33 Express", setup_p35, get_fsb_i965, get_timings_p35 }, + { 0x8086, 0x29E0, "82X38/X48 Express", setup_p35, get_fsb_i965, get_timings_p35 }, +// { 0x8086, 0x29F0, "3200/3210 Chipset", NULL, NULL, NULL }, + { 0x8086, 0x2E00, "Eaglelake", setup_p35, get_fsb_i965, get_timings_p35 }, { 0x8086, 0x2E10, "Q45/Q43", setup_p35, get_fsb_i965, get_timings_p35 }, { 0x8086, 0x2E20, "P45/G45", setup_p35, get_fsb_i965, get_timings_p35 }, - { 0x8086, 0x2E30, "G41", setup_p35, get_fsb_i965, get_timings_p35 }, + { 0x8086, 0x2E30, "G41", setup_p35, get_fsb_i965, get_timings_p35 }, +// { 0x8086, 0x2E40, "4 Series Chipset", NULL, NULL, NULL }, +// { 0x8086, 0x2E90, "4 Series Chipset", NULL, NULL, NULL }, { 0x8086, 0xD131, "NHM IMC", setup_nhm, get_fsb_nhm, get_timings_nhm }, { 0x8086, 0xD132, "NHM IMC", setup_nhm, get_fsb_nhm, get_timings_nhm }, - { 0x8086, 0x3400, "NHM IMC", setup_nhm, get_fsb_nhm, get_timings_nhm }, - { 0x8086, 0x3401, "NHM IMC", setup_nhm, get_fsb_nhm, get_timings_nhm }, - { 0x8086, 0x3402, "NHM IMC", setup_nhm, get_fsb_nhm, get_timings_nhm }, - { 0x8086, 0x3403, "NHM IMC", setup_nhm, get_fsb_nhm, get_timings_nhm }, - { 0x8086, 0x3404, "NHM IMC", setup_nhm, get_fsb_nhm, get_timings_nhm }, - { 0x8086, 0x3405, "NHM IMC", setup_nhm, get_fsb_nhm, get_timings_nhm }, - { 0x8086, 0x3406, "NHM IMC", setup_nhm, get_fsb_nhm, get_timings_nhm }, - { 0x8086, 0x3407, "NHM IMC", setup_nhm, get_fsb_nhm, get_timings_nhm }, + { 0x8086, 0x3400, "5520/5500/X58", setup_nhm, get_fsb_nhm, get_timings_nhm }, + { 0x8086, 0x3401, "5520/5500/X58", setup_nhm, get_fsb_nhm, get_timings_nhm }, + { 0x8086, 0x3402, "5520/5500/X58", setup_nhm, get_fsb_nhm, get_timings_nhm }, + { 0x8086, 0x3403, "5500", setup_nhm, get_fsb_nhm, get_timings_nhm }, + { 0x8086, 0x3404, "5520/5500/X58", setup_nhm, get_fsb_nhm, get_timings_nhm }, + { 0x8086, 0x3405, "5520/5500/X58", setup_nhm, get_fsb_nhm, get_timings_nhm }, + { 0x8086, 0x3406, "5520", setup_nhm, get_fsb_nhm, get_timings_nhm }, + { 0x8086, 0x3407, "5520/5500/X58", setup_nhm, get_fsb_nhm, get_timings_nhm }, }; static const char *memory_channel_types[] = { "Unknown", "Single", "Dual", "Triple" -}; +}; void scan_dram_controller(pci_dt_t *dram_dev) { int i; for(i = 1; i < sizeof(dram_controllers) / sizeof(dram_controllers[0]); i++) - if ((dram_controllers[i].vendor == dram_dev->vendor_id) - && (dram_controllers[i].device == dram_dev->device_id)) + { + if ((dram_controllers[i].vendor == dram_dev->vendor_id) && (dram_controllers[i].device == dram_dev->device_id)) { verbose("%s%s DRAM Controller [%4x:%4x] at %02x:%02x.%x\n", - (dram_dev->vendor_id == 0x8086) ? "Intel " : "" , - dram_controllers[i].name, dram_dev->vendor_id, dram_dev->device_id, - dram_dev->dev.bits.bus, dram_dev->dev.bits.dev, dram_dev->dev.bits.func); - - if (dram_controllers[i].initialise != NULL) + (dram_dev->vendor_id == 0x8086) ? "Intel Corporation " : "" , + dram_controllers[i].name, dram_dev->vendor_id, dram_dev->device_id, + dram_dev->dev.bits.bus, dram_dev->dev.bits.dev, dram_dev->dev.bits.func); + + if (dram_controllers[i].initialise != NULL) { dram_controllers[i].initialise(dram_dev); + } - if (dram_controllers[i].poll_timings != NULL) + if (dram_controllers[i].poll_timings != NULL) { dram_controllers[i].poll_timings(dram_dev); + } - if (dram_controllers[i].poll_speed != NULL) + if (dram_controllers[i].poll_speed != NULL) { dram_controllers[i].poll_speed(dram_dev); + } verbose("Frequency detected: %d MHz (%d) %s Channel \n\tCAS:%d tRC:%d tRP:%d RAS:%d (%d-%d-%d-%d)\n", - (uint32_t)Platform.RAM.Frequency / 1000000, - (uint32_t)Platform.RAM.Frequency / 500000, - memory_channel_types[Platform.RAM.Channels] - ,Platform.RAM.CAS, Platform.RAM.TRC, Platform.RAM.TRP, Platform.RAM.RAS - ,Platform.RAM.CAS, Platform.RAM.TRC, Platform.RAM.TRP, Platform.RAM.RAS - ); -// getchar(); + (uint32_t)Platform.RAM.Frequency / 1000000, + (uint32_t)Platform.RAM.Frequency / 500000, + memory_channel_types[Platform.RAM.Channels] + ,Platform.RAM.CAS, Platform.RAM.TRC, Platform.RAM.TRP, Platform.RAM.RAS + ,Platform.RAM.CAS, Platform.RAM.TRC, Platform.RAM.TRP, Platform.RAM.RAS); +// getchar(); } + } } Index: trunk/i386/libsaio/ntfs.c =================================================================== --- trunk/i386/libsaio/ntfs.c (revision 2326) +++ trunk/i386/libsaio/ntfs.c (revision 2327) @@ -270,9 +270,8 @@ //verbose("NTFS: lseek to $Volume failed: %s\n", strerror(errno)); goto error; } - if (read(fd, buf, mftRecordSize) != mftRecordSize) - { - //verbose("NTFS: error reading MFT $Volume record: %s\n", strerror(errno)); + if (read(fd, buf, mftRecordSize) != mftRecordSize) { + //verbose("NTFS: error reading MFT $Volume record: %s\n", strerror(errno)); goto error; } #endif @@ -310,8 +309,9 @@ struct bootfile *boot; void *buf = malloc(MAX_BLOCK_SIZE); - if ( !buf ) + if ( !buf ) { return -1; + } /* * Read the boot sector, check signatures, and do some minimal @@ -339,21 +339,21 @@ (unsigned short)boot->bf_volsn & 0xFFFF); return 0; -} +} bool NTFSProbe(const void * buffer) { bool result = false; const struct bootfile * part_bootfile = buffer; // NTFS boot sector structure - + // Looking for NTFS signature. if (strncmp((const char *)part_bootfile->bf_sysid, NTFS_BBID, NTFS_BBIDLEN) == 0) result = true; - + // If not NTFS, maybe it is EXFAT if (!result) result = EXFATProbe(buffer); - + return result; } Index: trunk/i386/libsaio/platform.c =================================================================== --- trunk/i386/libsaio/platform.c (revision 2326) +++ trunk/i386/libsaio/platform.c (revision 2327) @@ -37,30 +37,34 @@ } /** scan mem for memory autodection purpose */ -void scan_mem() { - static bool done = false; - if (done) return; +void scan_mem() +{ + static bool done = false; + if (done) { + return; + } /* our code only works on Intel chipsets so make sure here */ - if (pci_config_read16(PCIADDR(0, 0x00, 0), 0x00) != 0x8086) + if (pci_config_read16(PCIADDR(0, 0x00, 0), 0x00) != 0x8086) { bootInfo->memDetect = false; - else + } else { bootInfo->memDetect = true; + } /* manually */ - getBoolForKey(kUseMemDetect, &bootInfo->memDetect, &bootInfo->chameleonConfig); + getBoolForKey(kUseMemDetect, &bootInfo->memDetect, &bootInfo->chameleonConfig); - if (bootInfo->memDetect) { + if (bootInfo->memDetect) { if (dram_controller_dev != NULL) { scan_dram_controller(dram_controller_dev); // Rek: pci dev ram controller direct and fully informative scan ... } - scan_spd(&Platform); - } - done = true; + scan_spd(&Platform); + } + done = true; } -/** - Scan platform hardware information, called by the main entry point (common_boot() ) - _before_ bootConfig xml parsing settings are loaded +/* + * Scan platform hardware information, called by the main entry point (common_boot() ) + * _before_ bootConfig xml parsing settings are loaded */ void scan_platform(void) { Index: trunk/i386/libsaio/cpu.c =================================================================== --- trunk/i386/libsaio/cpu.c (revision 2326) +++ trunk/i386/libsaio/cpu.c (revision 2327) @@ -310,6 +310,7 @@ p->CPU.Stepping = bitfield(p->CPU.CPUID[CPUID_1][0], 3, 0); p->CPU.Model = bitfield(p->CPU.CPUID[CPUID_1][0], 7, 4); p->CPU.Family = bitfield(p->CPU.CPUID[CPUID_1][0], 11, 8); + p->CPU.Type = bitfield(p->CPU.CPUID[CPUID_1][0], 13, 12); p->CPU.ExtModel = bitfield(p->CPU.CPUID[CPUID_1][0], 19, 16); p->CPU.ExtFamily = bitfield(p->CPU.CPUID[CPUID_1][0], 27, 20); @@ -421,11 +422,9 @@ fsbFrequency = 0; cpuFrequency = 0; - if ((p->CPU.Vendor == CPUID_VENDOR_INTEL) && ((p->CPU.Family == 0x06) || (p->CPU.Family == 0x0f))) - { + if ((p->CPU.Vendor == CPUID_VENDOR_INTEL) && ((p->CPU.Family == 0x06) || (p->CPU.Family == 0x0f))) { int intelCPU = p->CPU.Model; - if ((p->CPU.Family == 0x06 && p->CPU.Model >= 0x0c) || (p->CPU.Family == 0x0f && p->CPU.Model >= 0x03)) - { + if ((p->CPU.Family == 0x06 && p->CPU.Model >= 0x0c) || (p->CPU.Family == 0x0f && p->CPU.Model >= 0x03)) { /* Nehalem CPU model */ if (p->CPU.Family == 0x06 && (p->CPU.Model == CPU_MODEL_NEHALEM || p->CPU.Model == CPU_MODEL_FIELDS || @@ -529,9 +528,7 @@ myfsb = fsbFrequency / 1000000; verbose("Sticking with [BCLK: %dMhz, Bus-Ratio: %d]\n", myfsb, max_ratio/10); currcoef = bus_ratio_max; - } - else - { + } else { msr = rdmsr64(MSR_IA32_PERF_STATUS); DBG("msr(%d): ia32_perf_stat 0x%08x\n", __LINE__, bitfield(msr, 31, 0)); currcoef = bitfield(msr, 12, 8); @@ -576,15 +573,11 @@ } } /* Mobile CPU */ - if (rdmsr64(MSR_IA32_PLATFORM_ID) & (1<<28)) - { + if (rdmsr64(MSR_IA32_PLATFORM_ID) & (1<<28)) { p->CPU.Features |= CPU_FEATURE_MOBILE; } - } - else if ((p->CPU.Vendor == CPUID_VENDOR_AMD) && (p->CPU.Family == 0x0f)) - { - switch(p->CPU.ExtFamily) - { + } else if ((p->CPU.Vendor == CPUID_VENDOR_AMD) && (p->CPU.Family == 0x0f)) { + switch(p->CPU.ExtFamily) { case 0x00: /* K8 */ msr = rdmsr64(K8_FIDVID_STATUS); maxcoef = bitfield(msr, 21, 16) / 2 + 4; @@ -622,47 +615,31 @@ break; } - if (maxcoef) - { - if (currdiv) - { - if (!currcoef) - { + if (maxcoef) { + if (currdiv) { + if (!currcoef) { currcoef = maxcoef; } - if (!cpuFrequency) - { + if (!cpuFrequency) { fsbFrequency = ((tscFrequency * currdiv) / currcoef); - } - else - { + } else { fsbFrequency = ((cpuFrequency * currdiv) / currcoef); } DBG("%d.%d\n", currcoef / currdiv, ((currcoef % currdiv) * 100) / currdiv); - } - else - { - if (!cpuFrequency) - { + } else { + if (!cpuFrequency) { fsbFrequency = (tscFrequency / maxcoef); - } - else - { + } else { fsbFrequency = (cpuFrequency / maxcoef); } DBG("%d\n", currcoef); } - } - else if (currcoef) - { - if (currdiv) - { + } else if (currcoef) { + if (currdiv) { fsbFrequency = ((tscFrequency * currdiv) / currcoef); DBG("%d.%d\n", currcoef / currdiv, ((currcoef % currdiv) * 100) / currdiv); - } - else - { + } else { fsbFrequency = (tscFrequency / currcoef); DBG("%d\n", currcoef); } @@ -689,15 +666,15 @@ // keep formatted with spaces instead of tabs DBG("CPU: Brand String: %s\n", p->CPU.BrandString); - DBG("CPU: Vendor/Family/ExtFamily: 0x%x/0x%x/0x%x\n", p->CPU.Vendor, p->CPU.Family, p->CPU.ExtFamily); - DBG("CPU: Model/ExtModel/Stepping: 0x%x/0x%x/0x%x\n", p->CPU.Model, p->CPU.ExtModel, p->CPU.Stepping); - DBG("CPU: MaxCoef/CurrCoef: 0x%x/0x%x\n", p->CPU.MaxCoef, p->CPU.CurrCoef); - DBG("CPU: MaxDiv/CurrDiv: 0x%x/0x%x\n", p->CPU.MaxDiv, p->CPU.CurrDiv); - DBG("CPU: TSCFreq: %dMHz\n", p->CPU.TSCFrequency / 1000000); - DBG("CPU: FSBFreq: %dMHz\n", p->CPU.FSBFrequency / 1000000); - DBG("CPU: CPUFreq: %dMHz\n", p->CPU.CPUFrequency / 1000000); - DBG("CPU: NoCores/NoThreads: %d/%d\n", p->CPU.NoCores, p->CPU.NoThreads); - DBG("CPU: Features: 0x%08x\n", p->CPU.Features); + DBG("CPU: Vendor/Family/ExtFamily: 0x%x/0x%x/0x%x\n", p->CPU.Vendor, p->CPU.Family, p->CPU.ExtFamily); + DBG("CPU: Model/ExtModel/Stepping: 0x%x/0x%x/0x%x\n", p->CPU.Model, p->CPU.ExtModel, p->CPU.Stepping); + DBG("CPU: MaxCoef/CurrCoef: 0x%x/0x%x\n", p->CPU.MaxCoef, p->CPU.CurrCoef); + DBG("CPU: MaxDiv/CurrDiv: 0x%x/0x%x\n", p->CPU.MaxDiv, p->CPU.CurrDiv); + DBG("CPU: TSCFreq: %dMHz\n", p->CPU.TSCFrequency / 1000000); + DBG("CPU: FSBFreq: %dMHz\n", p->CPU.FSBFrequency / 1000000); + DBG("CPU: CPUFreq: %dMHz\n", p->CPU.CPUFrequency / 1000000); + DBG("CPU: NoCores/NoThreads: %d/%d\n", p->CPU.NoCores, p->CPU.NoThreads); + DBG("CPU: Features: 0x%08x\n", p->CPU.Features); #if DEBUG_CPU pause(); #endif Index: trunk/i386/libsaio/platform.h =================================================================== --- trunk/i386/libsaio/platform.h (revision 2326) +++ trunk/i386/libsaio/platform.h (revision 2327) @@ -129,12 +129,15 @@ uint8_t BankConnCnt; } RamSlotInfo_t; +//============================================================================== + typedef struct _PlatformInfo_t { struct CPU { uint32_t Features; // CPU Features like MMX, SSE2, VT, MobileCPU uint32_t Vendor; // Vendor - uint32_t Signature; // Signature + uint32_t Signature; // Processor Signature uint32_t Stepping; // Stepping + uint32_t Type; // Type uint32_t Model; // Model uint32_t ExtModel; // Extended Model uint32_t Family; // Family @@ -168,10 +171,10 @@ } RAM; struct DMI { - int MaxMemorySlots; // number of memory slots populated by SMBIOS - int CntMemorySlots; // number of memory slots counted - int MemoryModules; // number of memory modules installed - int DIMM[MAX_RAM_SLOTS]; // Information and SPD mapping for each slot + int MaxMemorySlots; // number of memory slots populated by SMBIOS + int CntMemorySlots; // number of memory slots counted + int MemoryModules; // number of memory modules installed + int DIMM[MAX_RAM_SLOTS]; // Information and SPD mapping for each slot } DMI; uint8_t Type; // System Type: 1=Desktop, 2=Portable... according ACPI2.0 (FACP: PM_Profile) Index: trunk/i386/libsaio/disk.c =================================================================== --- trunk/i386/libsaio/disk.c (revision 2326) +++ trunk/i386/libsaio/disk.c (revision 2327) @@ -139,84 +139,103 @@ static int getDriveInfo( int biosdev, struct driveInfo *dip ) { - static struct driveInfo cached_di; - int cc; - - // Real BIOS devices are 8-bit, so anything above that is for internal use. - // Don't cache ramdisk drive info since it doesn't require several BIOS - // calls and is thus not worth it. - if(biosdev >= 0x100) - { - if(p_get_ramdisk_info != NULL) - cc = (*p_get_ramdisk_info)(biosdev, dip); - else - cc = -1; - if(cc < 0) - { - dip->valid = 0; - return -1; - } - else - return 0; - } + static struct driveInfo cached_di; + int cc; - if ( !cached_di.valid || biosdev != cached_di.biosdev ) - { - cc = get_drive_info(biosdev, &cached_di); - if (cc < 0) { - cached_di.valid = 0; - DEBUG_DISK(("get_drive_info returned error\n")); - return (-1); // BIOS call error + // Real BIOS devices are 8-bit, so anything above that is for internal use. + // Don't cache ramdisk drive info since it doesn't require several BIOS + // calls and is thus not worth it. + if (biosdev >= 0x100) + { + if (p_get_ramdisk_info != NULL) + { + cc = (*p_get_ramdisk_info)(biosdev, dip); + } + else + { + cc = -1; + } + if (cc < 0) + { + dip->valid = 0; + return -1; + } + else + { + return 0; + } } - } - bcopy(&cached_di, dip, sizeof(cached_di)); + if (!cached_di.valid || biosdev != cached_di.biosdev) + { + cc = get_drive_info(biosdev, &cached_di); - return 0; + if (cc < 0) + { + cached_di.valid = 0; + DEBUG_DISK(("get_drive_info returned error\n")); + return (-1); // BIOS call error + } + } + + bcopy(&cached_di, dip, sizeof(cached_di)); + + return 0; } //========================================================================== // Maps (E)BIOS return codes to message strings. struct NamedValue { - unsigned char value; - const char * name; + unsigned char value; + const char * name; }; +//========================================================================== + static const char * getNameForValue( const struct NamedValue * nameTable, unsigned char value ) { - const struct NamedValue * np; + const struct NamedValue * np; - for ( np = nameTable; np->value; np++) - if (np->value == value) - return np->name; + for ( np = nameTable; np->value; np++) + { + if (np->value == value) + { + return np->name; + } + } - return NULL; + return NULL; } #define ECC_CORRECTED_ERR 0x11 -static const struct NamedValue bios_errors[] = { - { 0x10, "Media error" }, - { 0x11, "Corrected ECC error" }, - { 0x20, "Controller or device error" }, - { 0x40, "Seek failed" }, - { 0x80, "Device timeout" }, - { 0xAA, "Drive not ready" }, - { 0x00, 0 } +static const struct NamedValue bios_errors[] = +{ + { 0x10, "Media error" }, + { 0x11, "Corrected ECC error" }, + { 0x20, "Controller or device error" }, + { 0x40, "Seek failed" }, + { 0x80, "Device timeout" }, + { 0xAA, "Drive not ready" }, + { 0x00, 0 } }; static const char * bios_error(int errnum) { - static char errorstr[] = "Error 0x00"; - const char * errname; + static char errorstr[] = "Error 0x00"; + const char * errname; - errname = getNameForValue( bios_errors, errnum ); - if ( errname ) return errname; + errname = getNameForValue(bios_errors, errnum); - sprintf(errorstr, "Error 0x%02x", errnum); - return errorstr; // No string, print error code only + if (errname) + { + return errname; + } + + sprintf(errorstr, "Error 0x%02x", errnum); + return errorstr; // No string, print error code only } //========================================================================== @@ -231,272 +250,283 @@ static int Biosread( int biosdev, unsigned long long secno ) { - static int xbiosdev, xcyl, xhead; - static unsigned int xsec, xnsecs; - struct driveInfo di; + static int xbiosdev, xcyl, xhead; + static unsigned int xsec, xnsecs; + struct driveInfo di; - int rc = -1; - int cyl, head, sec; - int tries = 0; - int bps, divisor; + int rc = -1; + int cyl, head, sec; + int tries = 0; + int bps, divisor; - if (getDriveInfo(biosdev, &di) < 0) { - return -1; - } - if (di.no_emulation) { - /* Always assume 2k block size; BIOS may lie about geometry */ - bps = 2048; - } else { - bps = di.di.params.phys_nbps; - if (bps == 0) { - return -1; - } - } - divisor = bps / BPS; + if (getDriveInfo(biosdev, &di) < 0) + { + return -1; + } - DEBUG_DISK(("Biosread dev %x sec %d bps %d\n", biosdev, secno, bps)); + if (di.no_emulation) + { + bps = 2048; /* Always assume 2K block size since the BIOS may lie about the geometry */ + } + else + { + bps = di.di.params.phys_nbps; - // To read the disk sectors, use EBIOS if we can. Otherwise, - // revert to the standard BIOS calls. + if (bps == 0) + { + return -1; + } + } - if ((biosdev >= kBIOSDevTypeHardDrive) && - (di.uses_ebios & EBIOS_FIXED_DISK_ACCESS)) - { - if (cache_valid && - (biosdev == xbiosdev) && - (secno >= xsec) && - ((unsigned int)secno < (xsec + xnsecs))) - { - biosbuf = trackbuf + (BPS * (secno - xsec)); - return 0; - } + divisor = bps / BPS; - xnsecs = N_CACHE_SECS; - xsec = (secno / divisor) * divisor; - cache_valid = false; + DEBUG_DISK(("Biosread dev %x sec %d bps %d\n", biosdev, secno, bps)); - while ((rc = ebiosread(biosdev, secno / divisor, xnsecs / divisor)) && (++tries < 5)) - { - if (rc == ECC_CORRECTED_ERR) { - /* Ignore corrected ECC errors */ - rc = 0; - break; - } - error(" EBIOS read error: %s\n", bios_error(rc), rc); - error(" Block 0x%x Sectors %d\n", secno, xnsecs); - sleep(1); - } - } - else - { - /* spc = spt * heads */ - int spc = (di.di.params.phys_spt * di.di.params.phys_heads); - cyl = secno / spc; - head = (secno % spc) / di.di.params.phys_spt; - sec = secno % di.di.params.phys_spt; + // To read the disk sectors, use EBIOS if we can. Otherwise, + // revert to the standard BIOS calls. - if (cache_valid && - (biosdev == xbiosdev) && - (cyl == xcyl) && - (head == xhead) && - ((unsigned int)sec >= xsec) && - ((unsigned int)sec < (xsec + xnsecs))) - { - // this sector is in trackbuf cache - biosbuf = trackbuf + (BPS * (sec - xsec)); - return 0; - } + if ((biosdev >= kBIOSDevTypeHardDrive) && (di.uses_ebios & EBIOS_FIXED_DISK_ACCESS)) + { + if (cache_valid && (biosdev == xbiosdev) && (secno >= xsec) && ((unsigned int)secno < (xsec + xnsecs))) + { + biosbuf = trackbuf + (BPS * (secno - xsec)); + return 0; + } - // Cache up to a track worth of sectors, but do not cross a - // track boundary. + xnsecs = N_CACHE_SECS; + xsec = (secno / divisor) * divisor; + cache_valid = false; - xcyl = cyl; - xhead = head; - xsec = sec; - xnsecs = ((unsigned int)(sec + N_CACHE_SECS) > di.di.params.phys_spt) ? (di.di.params.phys_spt - sec) : N_CACHE_SECS; - cache_valid = false; + while ((rc = ebiosread(biosdev, secno / divisor, xnsecs / divisor)) && (++tries < 5)) + { + if (rc == ECC_CORRECTED_ERR) + { + rc = 0; /* Ignore corrected ECC errors */ + break; + } - while ((rc = biosread(biosdev, cyl, head, sec, xnsecs)) && - (++tries < 5)) - { - if (rc == ECC_CORRECTED_ERR) { - /* Ignore corrected ECC errors */ - rc = 0; - break; - } - error(" BIOS read error: %s\n", bios_error(rc), rc); - error(" Block %d, Cyl %d Head %d Sector %d\n", - secno, cyl, head, sec); - sleep(1); - } - } + error(" EBIOS read error: %s\n", bios_error(rc), rc); + error(" Block 0x%x Sectors %d\n", secno, xnsecs); + sleep(1); + } + } - // If the BIOS reported success, mark the sector cache as valid. + else + { + /* spc = spt * heads */ + int spc = (di.di.params.phys_spt * di.di.params.phys_heads); + cyl = secno / spc; + head = (secno % spc) / di.di.params.phys_spt; + sec = secno % di.di.params.phys_spt; - if (rc == 0) { - cache_valid = true; - } - biosbuf = trackbuf + (secno % divisor) * BPS; - xbiosdev = biosdev; - - spinActivityIndicator(xnsecs); + if (cache_valid && (biosdev == xbiosdev) && (cyl == xcyl) && + (head == xhead) && ((unsigned int)sec >= xsec) && ((unsigned int)sec < (xsec + xnsecs))) - return rc; + { + // this sector is in trackbuf cache + biosbuf = trackbuf + (BPS * (sec - xsec)); + return 0; + } + + // Cache up to a track worth of sectors, but do not cross a track boundary. + + xcyl = cyl; + xhead = head; + xsec = sec; + xnsecs = ((unsigned int)(sec + N_CACHE_SECS) > di.di.params.phys_spt) ? (di.di.params.phys_spt - sec) : N_CACHE_SECS; + + cache_valid = false; + + while ((rc = biosread(biosdev, cyl, head, sec, xnsecs)) && (++tries < 5)) + { + if (rc == ECC_CORRECTED_ERR) + { + rc = 0; /* Ignore corrected ECC errors */ + break; + } + error(" BIOS read error: %s\n", bios_error(rc), rc); + error(" Block %d, Cyl %d Head %d Sector %d\n", secno, cyl, head, sec); + sleep(1); + } + } + + // If the BIOS reported success, mark the sector cache as valid. + + if (rc == 0) + { + cache_valid = true; + } + + biosbuf = trackbuf + (secno % divisor) * BPS; + xbiosdev = biosdev; + + spinActivityIndicator(xnsecs); + + return rc; } -//========================================================================== -int testBiosread( int biosdev, unsigned long long secno ) +//============================================================================== + +int testBiosread(int biosdev, unsigned long long secno) { return Biosread(biosdev, secno); } -//========================================================================== +//============================================================================== -static int readBytes( int biosdev, unsigned long long blkno, - unsigned int byteoff, - unsigned int byteCount, void * buffer ) +static int readBytes(int biosdev, unsigned long long blkno, unsigned int byteoff, unsigned int byteCount, void * buffer) { - // ramdisks require completely different code for reading. - if(p_ramdiskReadBytes != NULL && biosdev >= 0x100) - return (*p_ramdiskReadBytes)(biosdev, blkno, byteoff, byteCount, buffer); + // ramdisks require completely different code for reading. + if(p_ramdiskReadBytes != NULL && biosdev >= 0x100) + { + return (*p_ramdiskReadBytes)(biosdev, blkno, byteoff, byteCount, buffer); + } - char * cbuf = (char *) buffer; - int error; - int copy_len; + char * cbuf = (char *) buffer; + int error; + int copy_len; - DEBUG_DISK(("%s: dev %x block %x [%d] -> 0x%x...", __FUNCTION__, - biosdev, blkno, byteCount, (unsigned)cbuf)); + DEBUG_DISK(("%s: dev %x block %x [%d] -> 0x%x...", __FUNCTION__, biosdev, blkno, byteCount, (unsigned)cbuf)); - for ( ; byteCount; cbuf += copy_len, blkno++ ) - { - error = Biosread( biosdev, blkno ); - if ( error ) - { - DEBUG_DISK(("error\n")); - return (-1); - } + for (; byteCount; cbuf += copy_len, blkno++) + { + error = Biosread(biosdev, blkno); - copy_len = ((byteCount + byteoff) > BPS) ? (BPS - byteoff) : byteCount; - bcopy( biosbuf + byteoff, cbuf, copy_len ); - byteCount -= copy_len; - byteoff = 0; - } + if (error) + { + DEBUG_DISK(("error\n")); - DEBUG_DISK(("done\n")); + return (-1); + } - return 0; + copy_len = ((byteCount + byteoff) > BPS) ? (BPS - byteoff) : byteCount; + bcopy( biosbuf + byteoff, cbuf, copy_len ); + byteCount -= copy_len; + byteoff = 0; + } + + DEBUG_DISK(("done\n")); + + return 0; } -//========================================================================== +//============================================================================== static int isExtendedFDiskPartition( const struct fdisk_part * part ) { - static unsigned char extParts[] = - { - 0x05, /* Extended */ - 0x0f, /* Win95 extended */ - 0x85, /* Linux extended */ - }; + static unsigned char extParts[] = + { + 0x05, /* Extended */ + 0x0f, /* Win95 extended */ + 0x85, /* Linux extended */ + }; - unsigned int i; + unsigned int i; - for (i = 0; i < sizeof(extParts)/sizeof(extParts[0]); i++) - { - if (extParts[i] == part->systid) return 1; - } - return 0; + for (i = 0; i < sizeof(extParts)/sizeof(extParts[0]); i++) + { + if (extParts[i] == part->systid) + { + return 1; + } + } + return 0; } -//========================================================================== +//============================================================================== static int getNextFDiskPartition( int biosdev, int * partno, const struct fdisk_part ** outPart ) { - static int sBiosdev = -1; - static int sNextPartNo; - static unsigned int sFirstBase; - static unsigned int sExtBase; - static unsigned int sExtDepth; - static struct fdisk_part * sExtPart; - struct fdisk_part * part; + static int sBiosdev = -1; + static int sNextPartNo; + static unsigned int sFirstBase; + static unsigned int sExtBase; + static unsigned int sExtDepth; + static struct fdisk_part * sExtPart; + struct fdisk_part * part; - if ( sBiosdev != biosdev || *partno < 0 ) - { - // Fetch MBR. - if ( readBootSector( biosdev, DISK_BLK0, 0 ) ) return 0; + if ( sBiosdev != biosdev || *partno < 0 ) + { + // Fetch MBR. + if ( readBootSector( biosdev, DISK_BLK0, 0 ) ) + { + return 0; + } - sBiosdev = biosdev; - sNextPartNo = 0; - sFirstBase = 0; - sExtBase = 0; - sExtDepth = 0; - sExtPart = NULL; - } + sBiosdev = biosdev; + sNextPartNo = 0; + sFirstBase = 0; + sExtBase = 0; + sExtDepth = 0; + sExtPart = NULL; + } - while (1) - { - part = NULL; + while (1) + { + part = NULL; - if ( sNextPartNo < FDISK_NPART ) - { - part = (struct fdisk_part *) gBootSector->parts[sNextPartNo]; - } - else if ( sExtPart ) - { - unsigned int blkno = sExtPart->relsect + sFirstBase; + if ( sNextPartNo < FDISK_NPART ) + { + part = (struct fdisk_part *) gBootSector->parts[sNextPartNo]; + } + else if ( sExtPart ) + { + unsigned int blkno = sExtPart->relsect + sFirstBase; - // Save the block offset of the first extended partition. + // Save the block offset of the first extended partition. - if (sExtDepth == 0) { - sFirstBase = blkno; - } - sExtBase = blkno; + if (sExtDepth == 0) + { + sFirstBase = blkno; + } + sExtBase = blkno; - // Load extended partition table. + // Load extended partition table. - if ( readBootSector( biosdev, blkno, 0 ) == 0 ) - { - sNextPartNo = 0; - sExtDepth++; - sExtPart = NULL; - continue; - } - // Fall through to part == NULL - } + if ( readBootSector( biosdev, blkno, 0 ) == 0 ) + { + sNextPartNo = 0; + sExtDepth++; + sExtPart = NULL; + continue; + } + // Fall through to part == NULL + } - if ( part == NULL ) break; // Reached end of partition chain. + if ( part == NULL ) break; // Reached end of partition chain. - // Advance to next partition number. + // Advance to next partition number. - sNextPartNo++; + sNextPartNo++; - if ( isExtendedFDiskPartition(part) ) - { - sExtPart = part; - continue; - } + if ( isExtendedFDiskPartition(part) ) + { + sExtPart = part; + continue; + } - // Skip empty slots. + // Skip empty slots. - if ( part->systid == 0x00 ) - { - continue; - } + if ( part->systid == 0x00 ) + { + continue; + } - // Change relative offset to an absolute offset. - part->relsect += sExtBase; + // Change relative offset to an absolute offset. + part->relsect += sExtBase; - *outPart = part; - *partno = sExtDepth ? (int)(sExtDepth + FDISK_NPART) : sNextPartNo; + *outPart = part; + *partno = sExtDepth ? (int)(sExtDepth + FDISK_NPART) : sNextPartNo; - break; - } + break; + } - return (part != NULL); + return (part != NULL); } -//========================================================================== +//============================================================================== static BVRef newFDiskBVRef( int biosdev, int partno, unsigned int blkoff, const struct fdisk_part * part, @@ -509,63 +539,68 @@ BVFree bvFreeFunc, int probe, int type, unsigned int bvrFlags ) { - BVRef bvr = (BVRef) malloc( sizeof(*bvr) ); - if ( bvr ) - { - bzero(bvr, sizeof(*bvr)); + BVRef bvr = (BVRef) malloc( sizeof(*bvr) ); + if ( bvr ) + { + bzero(bvr, sizeof(*bvr)); - bvr->biosdev = biosdev; - bvr->part_no = partno; - bvr->part_boff = blkoff; - bvr->part_type = part->systid; - bvr->fs_loadfile = loadFunc; - bvr->fs_readfile = readFunc; - bvr->fs_getdirentry = getdirFunc; - bvr->fs_getfileblock= getBlockFunc; - bvr->fs_getuuid = getUUIDFunc; - bvr->description = getDescriptionFunc; - bvr->type = type; - bvr->bv_free = bvFreeFunc; + bvr->biosdev = biosdev; + bvr->part_no = partno; + bvr->part_boff = blkoff; + bvr->part_type = part->systid; + bvr->fs_loadfile = loadFunc; + bvr->fs_readfile = readFunc; + bvr->fs_getdirentry = getdirFunc; + bvr->fs_getfileblock= getBlockFunc; + bvr->fs_getuuid = getUUIDFunc; + bvr->description = getDescriptionFunc; + bvr->type = type; + bvr->bv_free = bvFreeFunc; - if ((part->bootid & FDISK_ACTIVE) && (part->systid == FDISK_HFS)) - bvr->flags |= kBVFlagPrimary; + if ((part->bootid & FDISK_ACTIVE) && (part->systid == FDISK_HFS)) + { + bvr->flags |= kBVFlagPrimary; + } - // Probe the filesystem. + // Probe the filesystem. - if ( initFunc ) - { - bvr->flags |= kBVFlagNativeBoot; + if ( initFunc ) + { + bvr->flags |= kBVFlagNativeBoot; - if ( probe && initFunc( bvr ) != 0 ) - { - // filesystem probe failed. + if ( probe && initFunc( bvr ) != 0 ) + { + // filesystem probe failed. - DEBUG_DISK(("%s: failed probe on dev %x part %d\n", - __FUNCTION__, biosdev, partno)); + DEBUG_DISK(("%s: failed probe on dev %x part %d\n", __FUNCTION__, biosdev, partno)); - (*bvr->bv_free)(bvr); - bvr = NULL; - } - if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 ) - { - bvr->flags |= kBVFlagBootable; - } - } - else if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 ) - { - bvr->flags |= kBVFlagForeignBoot; - } - else - { - (*bvr->bv_free)(bvr); - bvr = NULL; - } - } - if (bvr) bvr->flags |= bvrFlags; - return bvr; + (*bvr->bv_free)(bvr); + bvr = NULL; + } + + if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 ) + { + bvr->flags |= kBVFlagBootable; + } + } + else if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 ) + { + bvr->flags |= kBVFlagForeignBoot; + } + else + { + (*bvr->bv_free)(bvr); + bvr = NULL; + } + } + + if (bvr) bvr->flags |= bvrFlags; + { + return bvr; + } } -//========================================================================== +//============================================================================== BVRef newAPMBVRef( int biosdev, int partno, unsigned int blkoff, const DPME * part, @@ -578,64 +613,68 @@ BVFree bvFreeFunc, int probe, int type, unsigned int bvrFlags ) { - BVRef bvr = (BVRef) malloc( sizeof(*bvr) ); - if ( bvr ) - { - bzero(bvr, sizeof(*bvr)); + BVRef bvr = (BVRef) malloc( sizeof(*bvr) ); + if ( bvr ) + { + bzero(bvr, sizeof(*bvr)); - bvr->biosdev = biosdev; - bvr->part_no = partno; - bvr->part_boff = blkoff; - bvr->fs_loadfile = loadFunc; - bvr->fs_readfile = readFunc; - bvr->fs_getdirentry = getdirFunc; - bvr->fs_getfileblock= getBlockFunc; - bvr->fs_getuuid = getUUIDFunc; - bvr->description = getDescriptionFunc; - bvr->type = type; - bvr->bv_free = bvFreeFunc; - strlcpy(bvr->name, part->dpme_name, DPISTRLEN); - strlcpy(bvr->type_name, part->dpme_type, DPISTRLEN); + bvr->biosdev = biosdev; + bvr->part_no = partno; + bvr->part_boff = blkoff; + bvr->fs_loadfile = loadFunc; + bvr->fs_readfile = readFunc; + bvr->fs_getdirentry = getdirFunc; + bvr->fs_getfileblock= getBlockFunc; + bvr->fs_getuuid = getUUIDFunc; + bvr->description = getDescriptionFunc; + bvr->type = type; + bvr->bv_free = bvFreeFunc; + strlcpy(bvr->name, part->dpme_name, DPISTRLEN); + strlcpy(bvr->type_name, part->dpme_type, DPISTRLEN); - /* - if ( part->bootid & FDISK_ACTIVE ) - bvr->flags |= kBVFlagPrimary; - */ + /* + if ( part->bootid & FDISK_ACTIVE ) + { + bvr->flags |= kBVFlagPrimary; + } + */ - // Probe the filesystem. + // Probe the filesystem. - if ( initFunc ) - { - bvr->flags |= kBVFlagNativeBoot | kBVFlagBootable | kBVFlagSystemVolume; + if ( initFunc ) + { + bvr->flags |= kBVFlagNativeBoot | kBVFlagBootable | kBVFlagSystemVolume; - if ( probe && initFunc( bvr ) != 0 ) - { - // filesystem probe failed. + if ( probe && initFunc( bvr ) != 0 ) + { + // filesystem probe failed. - DEBUG_DISK(("%s: failed probe on dev %x part %d\n", - __FUNCTION__, biosdev, partno)); + DEBUG_DISK(("%s: failed probe on dev %x part %d\n", __FUNCTION__, biosdev, partno)); - (*bvr->bv_free)(bvr); - bvr = NULL; - } - } - /* - else if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 ) - { - bvr->flags |= kBVFlagForeignBoot; - } - */ - else - { - (*bvr->bv_free)(bvr); - bvr = NULL; - } - } - if (bvr) bvr->flags |= bvrFlags; - return bvr; + (*bvr->bv_free)(bvr); + bvr = NULL; + } + } + /* + else if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 ) + { + bvr->flags |= kBVFlagForeignBoot; + } + */ + else + { + (*bvr->bv_free)(bvr); + bvr = NULL; + } + } + if (bvr) + { + bvr->flags |= bvrFlags; + } + return bvr; } -//========================================================================== +//============================================================================== // GUID's in LE form: // HFS+ partition - 48465300-0000-11AA-AA11-00306543ECAC @@ -665,71 +704,65 @@ BVFree bvFreeFunc, int probe, int type, unsigned int bvrFlags ) { - BVRef bvr = (BVRef) malloc( sizeof(*bvr) ); - if ( bvr ) - { - bzero(bvr, sizeof(*bvr)); + BVRef bvr = (BVRef) malloc( sizeof(*bvr) ); + if ( bvr ) { + bzero(bvr, sizeof(*bvr)); - bvr->biosdev = biosdev; - bvr->part_no = partno; - bvr->part_boff = blkoff; - bvr->fs_loadfile = loadFunc; - bvr->fs_readfile = readFunc; - bvr->fs_getdirentry = getdirFunc; - bvr->fs_getfileblock= getBlockFunc; - bvr->fs_getuuid = getUUIDFunc; - bvr->description = getDescriptionFunc; - bvr->type = type; - bvr->bv_free = bvFreeFunc; - // FIXME: UCS-2 -> UTF-8 the name - strlcpy(bvr->name, "----", DPISTRLEN); - if ( (efi_guid_compare(&GPT_BOOT_GUID, (EFI_GUID const*)part->ent_type) == 0) || - (efi_guid_compare(&GPT_HFS_GUID, (EFI_GUID const*)part->ent_type) == 0) ) - strlcpy(bvr->type_name, "GPT HFS+", DPISTRLEN); - else - strlcpy(bvr->type_name, "GPT Unknown", DPISTRLEN); + bvr->biosdev = biosdev; + bvr->part_no = partno; + bvr->part_boff = blkoff; + bvr->fs_loadfile = loadFunc; + bvr->fs_readfile = readFunc; + bvr->fs_getdirentry = getdirFunc; + bvr->fs_getfileblock= getBlockFunc; + bvr->fs_getuuid = getUUIDFunc; + bvr->description = getDescriptionFunc; + bvr->type = type; + bvr->bv_free = bvFreeFunc; + // FIXME: UCS-2 -> UTF-8 the name + strlcpy(bvr->name, "----", DPISTRLEN); + if ( (efi_guid_compare(&GPT_BOOT_GUID, (EFI_GUID const*)part->ent_type) == 0) || (efi_guid_compare(&GPT_HFS_GUID, (EFI_GUID const*)part->ent_type) == 0) ) { + strlcpy(bvr->type_name, "GPT HFS+", DPISTRLEN); + } else { + strlcpy(bvr->type_name, "GPT Unknown", DPISTRLEN); + } - /* - if ( part->bootid & FDISK_ACTIVE ) - bvr->flags |= kBVFlagPrimary; - */ + /* + if ( part->bootid & FDISK_ACTIVE ) { + bvr->flags |= kBVFlagPrimary; + } + */ - // Probe the filesystem. + // Probe the filesystem. - if ( initFunc ) - { - bvr->flags |= kBVFlagNativeBoot; + if ( initFunc ) { + bvr->flags |= kBVFlagNativeBoot; - if ( probe && initFunc( bvr ) != 0 ) - { - // filesystem probe failed. + if ( probe && initFunc( bvr ) != 0 ) { + // filesystem probe failed. - DEBUG_DISK(("%s: failed probe on dev %x part %d\n", - __FUNCTION__, biosdev, partno)); + DEBUG_DISK(("%s: failed probe on dev %x part %d\n", __FUNCTION__, biosdev, partno)); - (*bvr->bv_free)(bvr); - bvr = NULL; - } - if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 ) - { - bvr->flags |= kBVFlagBootable; - } - } - else if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 ) - { - bvr->flags |= kBVFlagForeignBoot; - } - else - { - (*bvr->bv_free)(bvr); - bvr = NULL; - } - } - if (bvr) bvr->flags |= bvrFlags; - return bvr; + (*bvr->bv_free)(bvr); + bvr = NULL; + } + if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 ) { + bvr->flags |= kBVFlagBootable; + } + } else if ( readBootSector( biosdev, blkoff, (void *)0x7e00 ) == 0 ) { + bvr->flags |= kBVFlagForeignBoot; + } else { + (*bvr->bv_free)(bvr); + bvr = NULL; + } + } + if (bvr) { + bvr->flags |= bvrFlags; + } + return bvr; } -//========================================================================== +//============================================================================== /* A note on partition numbers: * IOKit makes the primary partitions numbers 1-4, and then @@ -751,17 +784,22 @@ struct driveInfo di; boot_drive_info_t *dp; - /* Initialize disk info */ - if (getDriveInfo(biosdev, &di) != 0) { - return NULL; - } - dp = &di.di; - spc = (dp->params.phys_spt * dp->params.phys_heads); - if (spc == 0) { - /* This is probably a CD-ROM; punt on the geometry. */ - spc = 1; - } + /* Initialize disk info */ + if (getDriveInfo(biosdev, &di) != 0) + { + return NULL; + } + + dp = &di.di; + spc = (dp->params.phys_spt * dp->params.phys_heads); + + if (spc == 0) + { + /* This is probably a CD-ROM; punt on the geometry. */ + spc = 1; + } + do { // Create a new mapping. @@ -879,7 +917,7 @@ 0, kBIOSDevTypeHardDrive, 0); break; - + case FDISK_NTFS: bvr = newFDiskBVRef( biosdev, partno, @@ -903,7 +941,7 @@ (BVFree)free, 0, kBIOSDevTypeHardDrive, 0); break; - + case FDISK_BEFS: bvr = newFDiskBVRef( biosdev, partno, @@ -936,7 +974,7 @@ (BVFree)free, 0, kBIOSDevTypeHardDrive, 0); break; - + default: bvr = newFDiskBVRef( biosdev, partno, @@ -961,386 +999,451 @@ // Booting from a CD with an UFS filesystem embedded // in a booter partition. - if ( booterUFS ) - { - if ( map->bvrcnt == 0 ) - { - map->bvr = booterUFS; - map->bvrcnt++; - } - else free( booterUFS ); - } + if ( booterUFS ) + { + if ( map->bvrcnt == 0 ) + { + map->bvr = booterUFS; + map->bvrcnt++; + } + else + { + free( booterUFS ); + } + } #endif - } - } while (0); + } + } while (0); - /* - * If no FDisk partition, then we will check for - * an Apple partition map elsewhere. - */ + /* + * If no FDisk partition, then we will check for + * an Apple partition map elsewhere. + */ #if UNUSED - if (map->bvrcnt == 0) { - static struct fdisk_part cdpart; - cdpart.systid = 0xCD; + if (map->bvrcnt == 0) + { + static struct fdisk_part cdpart; + cdpart.systid = 0xCD; - /* Let's try assuming we are on a hybrid HFS/ISO9660 CD. */ - bvr = newFDiskBVRef( - biosdev, 0, - 0, - &cdpart, - HFSInitPartition, - HFSLoadFile, - HFSReadFile, - HFSGetDirEntry, - HFSGetFileBlock, - HFSGetUUID, - 0, - kBIOSDevTypeHardDrive); - bvr->next = map->bvr; - map->bvr = bvr; - map->bvrcnt++; - } + /* Let's try assuming we are on a hybrid HFS/ISO9660 CD. */ + bvr = newFDiskBVRef( + biosdev, 0, + 0, + &cdpart, + HFSInitPartition, + HFSLoadFile, + HFSReadFile, + HFSGetDirEntry, + HFSGetFileBlock, + HFSGetUUID, + 0, + kBIOSDevTypeHardDrive); + bvr->next = map->bvr; + map->bvr = bvr; + map->bvrcnt++; + } #endif - // Actually this should always be true given the above code - if(map == gDiskBVMap) - { - // Don't leave a null map in the chain - if(map->bvrcnt == 0 && map->bvr == NULL) - { - gDiskBVMap = map->next; - free(map); - map = NULL; - } - } + // Actually this should always be true given the above code + if(map == gDiskBVMap) + { + // Don't leave a null map in the chain + if(map->bvrcnt == 0 && map->bvr == NULL) + { + gDiskBVMap = map->next; + free(map); + map = NULL; + } + } - if (countPtr) *countPtr = map ? map->bvrcnt : 0; + if (countPtr) *countPtr = map ? map->bvrcnt : 0; - return map ? map->bvr : NULL; + return map ? map->bvr : NULL; } -//========================================================================== +//============================================================================== static BVRef diskScanAPMBootVolumes( int biosdev, int * countPtr ) { - struct DiskBVMap * map; - struct Block0 *block0_p; - unsigned int blksize; - unsigned int factor; - void *buffer = malloc(BPS); + struct DiskBVMap * map; + struct Block0 *block0_p; + unsigned int blksize; + unsigned int factor; + void *buffer = malloc(BPS); - /* Check for alternate block size */ - if (readBytes( biosdev, 0, 0, BPS, buffer ) != 0) { - return NULL; - } - block0_p = buffer; - if (OSSwapBigToHostInt16(block0_p->sbSig) == BLOCK0_SIGNATURE) { - blksize = OSSwapBigToHostInt16(block0_p->sbBlkSize); - if (blksize != BPS) { - free(buffer); - buffer = malloc(blksize); - } - factor = blksize / BPS; - } else { - blksize = BPS; - factor = 1; - } - - do { - // Create a new mapping. + if (!buffer) + { + return NULL; + } - map = (struct DiskBVMap *) malloc( sizeof(*map) ); - if ( map ) - { - int error; - DPME *dpme_p = (DPME *)buffer; - UInt32 i, npart = UINT_MAX; - BVRef bvr; + /* Check for alternate block size */ + if (readBytes( biosdev, 0, 0, BPS, buffer ) != 0) + { + return NULL; + } + block0_p = buffer; + if (OSSwapBigToHostInt16(block0_p->sbSig) == BLOCK0_SIGNATURE) + { + blksize = OSSwapBigToHostInt16(block0_p->sbBlkSize); + if (blksize != BPS) + { + free(buffer); + buffer = malloc(blksize); + if (!buffer) + { + return NULL; + } + } + factor = blksize / BPS; + } + else + { + blksize = BPS; + factor = 1; + } - map->biosdev = biosdev; - map->bvr = NULL; - map->bvrcnt = 0; - map->next = gDiskBVMap; - gDiskBVMap = map; + do + { + // Create a new mapping. - for (i=0; idpme_signature) != DPME_SIGNATURE) { - break; - } + map->biosdev = biosdev; + map->bvr = NULL; + map->bvrcnt = 0; + map->next = gDiskBVMap; + gDiskBVMap = map; - if (i==0) { - npart = OSSwapBigToHostInt32(dpme_p->dpme_map_entries); - } - /* - printf("name = %s, %s%s %d -> %d [%d -> %d] {%d}\n", - dpme.dpme_name, dpme.dpme_type, (dpme.dpme_flags & DPME_FLAGS_BOOTABLE) ? "(bootable)" : "", - dpme.dpme_pblock_start, dpme.dpme_pblocks, - dpme.dpme_lblock_start, dpme.dpme_lblocks, - dpme.dpme_boot_block); - */ + for (i=0; idpme_type, "Apple_HFS") == 0) { - bvr = newAPMBVRef(biosdev, - i, - OSSwapBigToHostInt32(dpme_p->dpme_pblock_start) * factor, - dpme_p, - HFSInitPartition, - HFSLoadFile, - HFSReadFile, - HFSGetDirEntry, - HFSGetFileBlock, - HFSGetUUID, - HFSGetDescription, - HFSFree, - 0, - kBIOSDevTypeHardDrive, 0); - bvr->next = map->bvr; - map->bvr = bvr; - map->bvrcnt++; - } - } - } - } while (0); + if (error || OSSwapBigToHostInt16(dpme_p->dpme_signature) != DPME_SIGNATURE) + { + break; + } - free(buffer); + if (i==0) + { + npart = OSSwapBigToHostInt32(dpme_p->dpme_map_entries); + } + /* + printf("name = %s, %s%s %d -> %d [%d -> %d] {%d}\n", + dpme.dpme_name, dpme.dpme_type, (dpme.dpme_flags & DPME_FLAGS_BOOTABLE) ? "(bootable)" : "", + dpme.dpme_pblock_start, dpme.dpme_pblocks, + dpme.dpme_lblock_start, dpme.dpme_lblocks, + dpme.dpme_boot_block); + */ - if (countPtr) *countPtr = map ? map->bvrcnt : 0; + if (strcmp(dpme_p->dpme_type, "Apple_HFS") == 0) + { + bvr = newAPMBVRef(biosdev, + i, + OSSwapBigToHostInt32(dpme_p->dpme_pblock_start) * factor, + dpme_p, + HFSInitPartition, + HFSLoadFile, + HFSReadFile, + HFSGetDirEntry, + HFSGetFileBlock, + HFSGetUUID, + HFSGetDescription, + HFSFree, + 0, + kBIOSDevTypeHardDrive, 0); + bvr->next = map->bvr; + map->bvr = bvr; + map->bvrcnt++; + } + } + } + } while (0); - return map ? map->bvr : NULL; + free(buffer); + + if (countPtr) *countPtr = map ? map->bvrcnt : 0; + + return map ? map->bvr : NULL; } -//========================================================================== +//============================================================================== -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /* * Trying to figure out the filsystem type of a given partition. */ static int probeFileSystem(int biosdev, unsigned int blkoff) { - // detected filesystem type; - int result = -1; - int fatbits; + // detected filesystem type; + int result = -1; + int fatbits; - // Allocating buffer for 4 sectors. - const void * probeBuffer = malloc(PROBEFS_SIZE); - if (probeBuffer == NULL) - goto exit; + // Allocating buffer for 4 sectors. + const void * probeBuffer = malloc(PROBEFS_SIZE); + if (probeBuffer == NULL) + { + goto exit; + } - // Reading first 4 sectors of current partition - int error = readBytes(biosdev, blkoff, 0, PROBEFS_SIZE, (void *)probeBuffer); - if (error) - goto exit; + // Reading first 4 sectors of current partition + int error = readBytes(biosdev, blkoff, 0, PROBEFS_SIZE, (void *)probeBuffer); - if (HFSProbe(probeBuffer)) - result = FDISK_HFS; - else if (EX2Probe(probeBuffer)) - result = FDISK_LINUX; - else if (FreeBSDProbe(probeBuffer)) - result = FDISK_FREEBSD; - else if (OpenBSDProbe(probeBuffer)) - result = FDISK_OPENBSD; - else if (NTFSProbe(probeBuffer)) - result = FDISK_NTFS; - else if (BeFSProbe(probeBuffer)) - result = FDISK_BEFS; - else if ( (fatbits = MSDOSProbe(probeBuffer)) ) - { - switch (fatbits) - { - case 32: - default: - result = FDISK_FAT32; - break; - case 16: - result = FDISK_DOS16B; - break; - case 12: - result = FDISK_DOS12; - break; - } - } - else - // Couldn't detect filesystem type - result = 0; - + if (error) + { + goto exit; + } + + if (HFSProbe(probeBuffer)) + { + result = FDISK_HFS; + } + else if (EX2Probe(probeBuffer)) + { + result = FDISK_LINUX; + } + else if (FreeBSDProbe(probeBuffer)) + { + result = FDISK_FREEBSD; + } + + else if (OpenBSDProbe(probeBuffer)) + { + result = FDISK_OPENBSD; + } + + else if (BeFSProbe(probeBuffer)) + { + result = FDISK_BEFS; + } + + else if (NTFSProbe(probeBuffer)) + { + result = FDISK_NTFS; + } + + else if ( (fatbits = MSDOSProbe(probeBuffer)) ) + { + switch (fatbits) + { + case 32: + default: + result = FDISK_FAT32; + break; + case 16: + result = FDISK_DOS16B; + break; + case 12: + result = FDISK_DOS12; + break; + } + } + else + { + // Couldn't detect filesystem type + result = 0; + } + exit: - if (probeBuffer != NULL) free((void *)probeBuffer); - return result; + if (probeBuffer != NULL) free((void *)probeBuffer); + { + return result; + } } +//============================================================================== + static bool isPartitionUsed(gpt_ent * partition) { - // - // Ask whether the given partition is used. - // - return efi_guid_is_null((EFI_GUID const*)partition->ent_type) ? false : true; + // Ask whether the given partition is used. + + return efi_guid_is_null((EFI_GUID const*)partition->ent_type) ? false : true; } -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +//============================================================================== -static BVRef diskScanGPTBootVolumes( int biosdev, int * countPtr ) +static BVRef diskScanGPTBootVolumes(int biosdev, int * countPtr) { - struct DiskBVMap * map = NULL; - void *buffer = malloc(BPS); - int error; - if ( (error = readBytes( biosdev, /*secno*/0, 0, BPS, buffer )) != 0) { - verbose("Failed to read boot sector from BIOS device %02xh. Error=%d\n", biosdev, error); - goto scanErr; - } - struct REAL_disk_blk0 *fdiskMap = buffer; - if ( OSSwapLittleToHostInt16(fdiskMap->signature) != DISK_SIGNATURE ) - { - verbose("Failed to find boot signature on BIOS device %02xh\n", biosdev); - goto scanErr; - } + struct DiskBVMap *map = NULL; - int fdiskID = 0; - unsigned index; - for ( index = 0; index < FDISK_NPART; index++ ) - { - if ( fdiskMap->parts[index].systid ) - { - if ( fdiskMap->parts[index].systid == 0xEE ) - { - // Fail if two 0xEE partitions are present which - // means the FDISK code will wind up parsing it. - if ( fdiskID ) goto scanErr; + void *buffer = malloc(BPS); - fdiskID = index + 1; - } - } - } + int error; + if ( (error = readBytes( biosdev, /*secno*/0, 0, BPS, buffer )) != 0) + { + verbose("Failed to read boot sector from BIOS device %02xh. Error=%d\n", biosdev, error); + goto scanErr; + } + struct REAL_disk_blk0 *fdiskMap = buffer; + if ( OSSwapLittleToHostInt16(fdiskMap->signature) != DISK_SIGNATURE ) + { + verbose("Failed to find boot signature on BIOS device %02xh\n", biosdev); + goto scanErr; + } - if ( fdiskID == 0 ) goto scanErr; - verbose("Attempting to read GPT\n"); + int fdiskID = 0; + unsigned index; + for ( index = 0; index < FDISK_NPART; index++ ) + { + if ( fdiskMap->parts[index].systid ) + { + if ( fdiskMap->parts[index].systid == 0xEE ) + { + // Fail if two 0xEE partitions are present which + // means the FDISK code will wind up parsing it. + if ( fdiskID ) + { + goto scanErr; + } - if(readBytes(biosdev, 1, 0, BPS, buffer) != 0) - goto scanErr; - - gpt_hdr *headerMap = buffer; + fdiskID = index + 1; + } + } + } - // Determine whether the partition header signature is present. + if ( fdiskID == 0 ) + { + goto scanErr; + } - if ( memcmp(headerMap->hdr_sig, GPT_HDR_SIG, strlen(GPT_HDR_SIG)) ) - { - goto scanErr; - } + verbose("Attempting to read GPT\n"); - // Determine whether the partition header size is valid. + if(readBytes(biosdev, 1, 0, BPS, buffer) != 0) + { + goto scanErr; + } - UInt32 headerCheck = OSSwapLittleToHostInt32(headerMap->hdr_crc_self); - UInt32 headerSize = OSSwapLittleToHostInt32(headerMap->hdr_size); + gpt_hdr *headerMap = buffer; - if ( headerSize < offsetof(gpt_hdr, padding) ) - { - goto scanErr; - } + // Determine whether the partition header signature is present. - if ( headerSize > BPS ) - { - goto scanErr; - } + if ( memcmp(headerMap->hdr_sig, GPT_HDR_SIG, strlen(GPT_HDR_SIG)) ) + { + goto scanErr; + } - // Determine whether the partition header checksum is valid. + // Determine whether the partition header size is valid. - headerMap->hdr_crc_self = 0; + UInt32 headerCheck = OSSwapLittleToHostInt32(headerMap->hdr_crc_self); + UInt32 headerSize = OSSwapLittleToHostInt32(headerMap->hdr_size); - if ( crc32(0, headerMap, headerSize) != headerCheck ) - { - goto scanErr; - } + if ( headerSize < offsetof(gpt_hdr, padding) ) + { + goto scanErr; + } - // Determine whether the partition entry size is valid. + if ( headerSize > BPS ) + { + goto scanErr; + } - UInt64 gptBlock = 0; - UInt32 gptCheck = 0; - UInt32 gptCount = 0; - UInt32 gptID = 0; - gpt_ent * gptMap = 0; - UInt32 gptSize = 0; + // Determine whether the partition header checksum is valid. - gptBlock = OSSwapLittleToHostInt64(headerMap->hdr_lba_table); - gptCheck = OSSwapLittleToHostInt32(headerMap->hdr_crc_table); - gptCount = OSSwapLittleToHostInt32(headerMap->hdr_entries); - gptSize = OSSwapLittleToHostInt32(headerMap->hdr_entsz); + headerMap->hdr_crc_self = 0; - if ( gptSize < sizeof(gpt_ent) ) - { - goto scanErr; - } + if ( crc32(0, headerMap, headerSize) != headerCheck ) + { + goto scanErr; + } - // Allocate a buffer large enough to hold one map, rounded to a media block. - free(buffer); - buffer = NULL; + // Determine whether the partition entry size is valid. - UInt32 bufferSize = IORound(gptCount * gptSize, BPS); - if(bufferSize == 0) - goto scanErr; - buffer = malloc(bufferSize); + UInt64 gptBlock = 0; + UInt32 gptCheck = 0; + UInt32 gptCount = 0; + UInt32 gptID = 0; + gpt_ent * gptMap = 0; + UInt32 gptSize = 0; - if(readBytes(biosdev, gptBlock, 0, bufferSize, buffer) != 0) - goto scanErr; + gptBlock = OSSwapLittleToHostInt64(headerMap->hdr_lba_table); + gptCheck = OSSwapLittleToHostInt32(headerMap->hdr_crc_table); + gptCount = OSSwapLittleToHostInt32(headerMap->hdr_entries); + gptSize = OSSwapLittleToHostInt32(headerMap->hdr_entsz); - verbose("Read GPT\n"); + if ( gptSize < sizeof(gpt_ent) ) + { + goto scanErr; + } - // Allocate a new map for this BIOS device and insert it into the chain - map = malloc(sizeof(*map)); - map->biosdev = biosdev; - map->bvr = NULL; - map->bvrcnt = 0; - map->next = gDiskBVMap; - gDiskBVMap = map; + // Allocate a buffer large enough to hold one map, rounded to a media block. + free(buffer); + buffer = NULL; - // fdisk like partition type id. - int fsType = 0; - - for(gptID = 1; gptID <= gptCount; ++gptID) - { - BVRef bvr = NULL; - unsigned int bvrFlags = 0; - - // size on disk can be larger than sizeof(gpt_ent) - gptMap = (gpt_ent *) ( buffer + ( (gptID - 1) * gptSize) ); + UInt32 bufferSize = IORound(gptCount * gptSize, BPS); + if (bufferSize == 0) + { + goto scanErr; + } + buffer = malloc(bufferSize); + if (!buffer) + { + goto scanErr; + } - // NOTE: EFI_GUID's are in LE and we know we're on an x86. - // The IOGUIDPartitionScheme.cpp code uses byte-based UUIDs, we don't. + if (readBytes(biosdev, gptBlock, 0, bufferSize, buffer) != 0) + { + goto scanErr; + } + verbose("Read GPT\n"); - if (isPartitionUsed(gptMap)) - { - char stringuuid[100]; - efi_guid_unparse_upper((EFI_GUID*)gptMap->ent_type, stringuuid); - verbose("Reading GPT partition %d, type %s\n", gptID, stringuuid); + // Allocate a new map for this BIOS device and insert it into the chain + map = malloc(sizeof(*map)); + if (!map) + { + goto scanErr; + } + map->biosdev = biosdev; + map->bvr = NULL; + map->bvrcnt = 0; + map->next = gDiskBVMap; + gDiskBVMap = map; - // Getting fdisk like partition type. - fsType = probeFileSystem(biosdev, gptMap->ent_lba_start); + // fdisk like partition type id. + int fsType = 0; - if ( (efi_guid_compare(&GPT_BOOT_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) || - (efi_guid_compare(&GPT_HFS_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) ) - { - bvrFlags = (efi_guid_compare(&GPT_BOOT_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) ? kBVFlagBooter : 0; - bvr = newGPTBVRef(biosdev, - gptID, - gptMap->ent_lba_start, - gptMap, - HFSInitPartition, - HFSLoadFile, - HFSReadFile, - HFSGetDirEntry, - HFSGetFileBlock, - HFSGetUUID, - HFSGetDescription, - HFSFree, - 0, - kBIOSDevTypeHardDrive, bvrFlags); - } + for(gptID = 1; gptID <= gptCount; ++gptID) { + BVRef bvr = NULL; + unsigned int bvrFlags = 0; + // size on disk can be larger than sizeof(gpt_ent) + gptMap = (gpt_ent *) ( buffer + ( (gptID - 1) * gptSize) ); + + // NOTE: EFI_GUID's are in LE and we know we're on an x86. + // The IOGUIDPartitionScheme.cpp code uses byte-based UUIDs, we don't. + + if (isPartitionUsed(gptMap)) { + char stringuuid[100]; + efi_guid_unparse_upper((EFI_GUID*)gptMap->ent_type, stringuuid); + verbose("Reading GPT partition %d, type %s\n", gptID, stringuuid); + + // Getting fdisk like partition type. + fsType = probeFileSystem(biosdev, gptMap->ent_lba_start); + + if ( (efi_guid_compare(&GPT_BOOT_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) || (efi_guid_compare(&GPT_HFS_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) ) { + bvrFlags = (efi_guid_compare(&GPT_BOOT_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) ? kBVFlagBooter : 0; + bvr = newGPTBVRef(biosdev, + gptID, + gptMap->ent_lba_start, + gptMap, + HFSInitPartition, + HFSLoadFile, + HFSReadFile, + HFSGetDirEntry, + HFSGetFileBlock, + HFSGetUUID, + HFSGetDescription, + HFSFree, + 0, + kBIOSDevTypeHardDrive, bvrFlags); + } + // zef - foreign OS support if ( (efi_guid_compare(&GPT_BASICDATA_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) || - (efi_guid_compare(&GPT_BASICDATA2_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) ) - { + (efi_guid_compare(&GPT_BASICDATA2_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) ) { switch (fsType) { case FDISK_NTFS: @@ -1364,198 +1467,188 @@ } - // turbo - save our booter partition - // zef - only on original boot device - if ( (efi_guid_compare(&GPT_EFISYS_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) ) - { - switch (fsType) - { - case FDISK_HFS: - if (readBootSector( biosdev, gptMap->ent_lba_start, (void *)0x7e00 ) == 0) - { - bvr = newGPTBVRef(biosdev, gptID, gptMap->ent_lba_start, gptMap, - HFSInitPartition, - HFSLoadFile, - HFSReadFile, - HFSGetDirEntry, - HFSGetFileBlock, - HFSGetUUID, - HFSGetDescription, - HFSFree, - 0, kBIOSDevTypeHardDrive, kBVFlagEFISystem); - } - break; + // turbo - save our booter partition + // zef - only on original boot device + if ( (efi_guid_compare(&GPT_EFISYS_GUID, (EFI_GUID const*)gptMap->ent_type) == 0) ) { + switch (fsType) { + case FDISK_HFS: + if (readBootSector( biosdev, gptMap->ent_lba_start, (void *)0x7e00 ) == 0) { + bvr = newGPTBVRef(biosdev, gptID, gptMap->ent_lba_start, gptMap, + HFSInitPartition, + HFSLoadFile, + HFSReadFile, + HFSGetDirEntry, + HFSGetFileBlock, + HFSGetUUID, + HFSGetDescription, + HFSFree, + 0, kBIOSDevTypeHardDrive, kBVFlagEFISystem); + } + break; - case FDISK_FAT32: - if (testFAT32EFIBootSector( biosdev, gptMap->ent_lba_start, (void *)0x7e00 ) == 0) - { - bvr = newGPTBVRef(biosdev, gptID, gptMap->ent_lba_start, gptMap, - MSDOSInitPartition, - MSDOSLoadFile, - MSDOSReadFile, - MSDOSGetDirEntry, - MSDOSGetFileBlock, - MSDOSGetUUID, - MSDOSGetDescription, - MSDOSFree, - 0, kBIOSDevTypeHardDrive, kBVFlagEFISystem); - } - break; + case FDISK_FAT32: + if (testFAT32EFIBootSector( biosdev, gptMap->ent_lba_start, (void *)0x7e00 ) == 0) { + bvr = newGPTBVRef(biosdev, gptID, gptMap->ent_lba_start, gptMap, + MSDOSInitPartition, + MSDOSLoadFile, + MSDOSReadFile, + MSDOSGetDirEntry, + MSDOSGetFileBlock, + MSDOSGetUUID, + MSDOSGetDescription, + MSDOSFree, + 0, kBIOSDevTypeHardDrive, kBVFlagEFISystem); + } + break; - if (biosdev == gBIOSDev) - gBIOSBootVolume = bvr; - } - } + default: + if (biosdev == gBIOSDev) { + gBIOSBootVolume = bvr; + } + break; + } + } - if (bvr) - { - // Fixup bvr with the fake fdisk partition type. - if (fsType > 0) bvr->part_type = fsType; + if (bvr) + { + // Fixup bvr with the fake fdisk partition type. + if (fsType > 0) { + bvr->part_type = fsType; + } - bvr->next = map->bvr; - map->bvr = bvr; - ++map->bvrcnt; - } + bvr->next = map->bvr; + map->bvr = bvr; + ++map->bvrcnt; + } - } - } + } + } -scanErr: - free(buffer); + scanErr: + if (buffer) { + free(buffer); + } - if(map) - { - if(countPtr) *countPtr = map->bvrcnt; - return map->bvr; - } - else - { - if(countPtr) *countPtr = 0; - return NULL; - } + if(map) { + if(countPtr) *countPtr = map->bvrcnt; + { + return map->bvr; + } + + } else { + if(countPtr) *countPtr = 0; + { + return NULL; + } + } } +//============================================================================== + static bool getOSVersion(BVRef bvr, char *str) { bool valid = false; config_file_t systemVersion; char dirSpec[512]; - + sprintf(dirSpec, "hd(%d,%d)/System/Library/CoreServices/SystemVersion.plist", BIOS_DEV_UNIT(bvr), bvr->part_no); - if (!loadConfigFile(dirSpec, &systemVersion)) - { + if (!loadConfigFile(dirSpec, &systemVersion)) { valid = true; - } - else - { + } else { sprintf(dirSpec, "hd(%d,%d)/System/Library/CoreServices/ServerVersion.plist", BIOS_DEV_UNIT(bvr), bvr->part_no); - + if (!loadConfigFile(dirSpec, &systemVersion)) { - bvr->OSisServer = true; + bvr->OSisServer = true; valid = true; - } + } } - if (valid) - { + if (valid) { const char *val; int len; - if (getValueForKey(kProductVersion, &val, &len, &systemVersion)) - { + if (getValueForKey(kProductVersion, &val, &len, &systemVersion)) { // getValueForKey uses const char for val // so copy it and trim *str = '\0'; strncat(str, val, MIN(len, 4)); + } else { + valid = false; } - else - valid = false; } - if(!valid) - { + if(!valid) { int fh = -1; sprintf(dirSpec, "hd(%d,%d)/.PhysicalMediaInstall", BIOS_DEV_UNIT(bvr), bvr->part_no); fh = open(dirSpec, 0); - - if (fh >= 0) - { + + if (fh >= 0) { valid = true; bvr->OSisInstaller = true; strcpy(bvr->OSVersion, "10.7"); // 10.7 + - } - else - { + } else { close(fh); } } - return valid; } -//========================================================================== +//============================================================================== static void scanFSLevelBVRSettings(BVRef chain) { - BVRef bvr; - char dirSpec[512], fileSpec[512]; - char label[BVSTRLEN]; - int ret; - long flags, time; - int fh, fileSize, error; + BVRef bvr; + char dirSpec[512], fileSpec[512]; + char label[BVSTRLEN]; + int ret; + long flags, time; + int fh, fileSize, error; - for (bvr = chain; bvr; bvr = bvr->next) - { - ret = -1; - error = 0; + for (bvr = chain; bvr; bvr = bvr->next) { + ret = -1; + error = 0; - // - // Check for alternate volume label on boot helper partitions. - // - if (bvr->flags & kBVFlagBooter) - { - sprintf(dirSpec, "hd(%d,%d)/System/Library/CoreServices/", BIOS_DEV_UNIT(bvr), bvr->part_no); - strcpy(fileSpec, ".disk_label.contentDetails"); - ret = GetFileInfo(dirSpec, fileSpec, &flags, &time); - if (!ret) - { - fh = open(strcat(dirSpec, fileSpec), 0); - fileSize = file_size(fh); - if (fileSize > 0 && fileSize < BVSTRLEN) - { - if (read(fh, label, fileSize) != fileSize) - error = -1; - } - else - error = -1; + // + // Check for alternate volume label on boot helper partitions. + // + if (bvr->flags & kBVFlagBooter) { + sprintf(dirSpec, "hd(%d,%d)/System/Library/CoreServices/", BIOS_DEV_UNIT(bvr), bvr->part_no); + strcpy(fileSpec, ".disk_label.contentDetails"); + ret = GetFileInfo(dirSpec, fileSpec, &flags, &time); + if (!ret) { + fh = open(strcat(dirSpec, fileSpec), 0); + fileSize = file_size(fh); + if (fileSize > 0 && fileSize < BVSTRLEN) { + if (read(fh, label, fileSize) != fileSize) { + error = -1; + } + } else { + error = -1; + } - close(fh); + close(fh); - if (!error) - { - label[fileSize] = '\0'; - strcpy(bvr->altlabel, label); - } - } - } + if (!error) { + label[fileSize] = '\0'; + strcpy(bvr->altlabel, label); + } + } + } - // - // Check for SystemVersion.plist or ServerVersion.plist - // to determine if a volume hosts an installed system. - // - if (bvr->flags & kBVFlagNativeBoot) - { - if (getOSVersion(bvr,bvr->OSVersion) == true) - { - bvr->flags |= kBVFlagSystemVolume; - } - } + // Check for SystemVersion.plist or ServerVersion.plist to determine if a volume hosts an installed system. - } + if (bvr->flags & kBVFlagNativeBoot) { + if (getOSVersion(bvr,bvr->OSVersion) == true) { + bvr->flags |= kBVFlagSystemVolume; + } + } + } } +//============================================================================== + void rescanBIOSDevice(int biosdev) { struct DiskBVMap *oldMap = diskResetBootVolumes(biosdev); @@ -1565,225 +1658,261 @@ scanBootVolumes(biosdev, 0); } +//============================================================================== + struct DiskBVMap* diskResetBootVolumes(int biosdev) { - struct DiskBVMap * map; - struct DiskBVMap *prevMap = NULL; - for ( map = gDiskBVMap; map; prevMap = map, map = map->next ) { - if ( biosdev == map->biosdev ) { - break; - } - } - if(map != NULL) - { - verbose("Resetting BIOS device %xh\n", biosdev); - // Reset the biosbuf cache - cache_valid = false; - if(map == gDiskBVMap) - gDiskBVMap = map->next; - else if(prevMap != NULL) - prevMap->next = map->next; - else - stop(""); - } - // Return the old map, either to be freed, or reinserted later - return map; + struct DiskBVMap * map; + struct DiskBVMap *prevMap = NULL; + for ( map = gDiskBVMap; map; prevMap = map, map = map->next ) { + if ( biosdev == map->biosdev ) { + break; + } + } + + if(map != NULL) { + verbose("Resetting BIOS device %xh\n", biosdev); + // Reset the biosbuf cache + cache_valid = false; + if(map == gDiskBVMap) { + gDiskBVMap = map->next; + } else if(prevMap != NULL) { + prevMap->next = map->next; + } else { + stop(""); + } + } + // Return the old map, either to be freed, or reinserted later + return map; } +//============================================================================== + // Frees a DiskBVMap and all of its BootVolume's void diskFreeMap(struct DiskBVMap *map) { - if(map != NULL) - { - while(map->bvr != NULL) - { - BVRef bvr = map->bvr; - map->bvr = bvr->next; - (*bvr->bv_free)(bvr); - } - free(map); - } + if(map != NULL) + { + while(map->bvr != NULL) + { + BVRef bvr = map->bvr; + map->bvr = bvr->next; + (*bvr->bv_free)(bvr); + } + + free(map); + } } -BVRef diskScanBootVolumes( int biosdev, int * countPtr ) +//============================================================================== + +BVRef diskScanBootVolumes(int biosdev, int * countPtr) { - struct DiskBVMap * map; - BVRef bvr; - int count = 0; + struct DiskBVMap *map; + BVRef bvr; + int count = 0; - // Find an existing mapping for this device. + // Find an existing mapping for this device. - for ( map = gDiskBVMap; map; map = map->next ) { - if ( biosdev == map->biosdev ) { - count = map->bvrcnt; - break; - } - } + for (map = gDiskBVMap; map; map = map->next) + { + if (biosdev == map->biosdev) + { + count = map->bvrcnt; + break; + } + } - if (map == NULL) { - bvr = diskScanGPTBootVolumes(biosdev, &count); - if (bvr == NULL) { - bvr = diskScanFDiskBootVolumes(biosdev, &count); - } - if (bvr == NULL) { - bvr = diskScanAPMBootVolumes(biosdev, &count); - } - if (bvr) - { - scanFSLevelBVRSettings(bvr); - } - } else { - bvr = map->bvr; - } - if (countPtr) *countPtr += count; - return bvr; + if (map == NULL) + { + bvr = diskScanGPTBootVolumes(biosdev, &count); + if (bvr == NULL) + { + bvr = diskScanFDiskBootVolumes(biosdev, &count); + } + if (bvr == NULL) + { + bvr = diskScanAPMBootVolumes(biosdev, &count); + } + if (bvr) + { + scanFSLevelBVRSettings(bvr); + } + } + else + { + bvr = map->bvr; + } + if (countPtr) + { + *countPtr += count; + } + return bvr; } +//============================================================================== + BVRef getBVChainForBIOSDev(int biosdev) { - BVRef chain = NULL; - struct DiskBVMap * map = NULL; + BVRef chain = NULL; + struct DiskBVMap * map = NULL; - for (map = gDiskBVMap; map; map = map->next) - { - if (map->biosdev == biosdev) - { - chain = map->bvr; - break; - } - } - - return chain; + for (map = gDiskBVMap; map; map = map->next) + { + if (map->biosdev == biosdev) + { + chain = map->bvr; + break; + } + } + + return chain; } +//============================================================================== + BVRef newFilteredBVChain(int minBIOSDev, int maxBIOSDev, unsigned int allowFlags, unsigned int denyFlags, int *count) { - BVRef chain = NULL; - BVRef bvr = NULL; - BVRef newBVR = NULL; - BVRef prevBVR = NULL; + BVRef chain = NULL; + BVRef bvr = NULL; + BVRef newBVR = NULL; + BVRef prevBVR = NULL; - struct DiskBVMap * map = NULL; - int bvCount = 0; + struct DiskBVMap * map = NULL; + int bvCount = 0; - const char *raw = 0; - char* val = 0; - int len; + const char *raw = 0; + char* val = 0; + int len; - getValueForKey(kHidePartition, &raw, &len, &bootInfo->chameleonConfig); - if(raw) - { - val = XMLDecode(raw); - } + getValueForKey(kHidePartition, &raw, &len, &bootInfo->chameleonConfig); + if(raw) + { + val = XMLDecode(raw); + } - /* - * Traverse gDISKBVmap to get references for - * individual bvr chains of each drive. - */ - for (map = gDiskBVMap; map; map = map->next) - { - for (bvr = map->bvr; bvr; bvr = bvr->next) - { - /* - * Save the last bvr. - */ - if (newBVR) prevBVR = newBVR; + /* + * Traverse gDISKBVmap to get references for + * individual bvr chains of each drive. + */ + for (map = gDiskBVMap; map; map = map->next) + { + for (bvr = map->bvr; bvr; bvr = bvr->next) + { + /* + * Save the last bvr. + */ + if (newBVR) + { + prevBVR = newBVR; + } - /* - * Allocate and copy the matched bvr entry into a new one. - */ - newBVR = (BVRef) malloc(sizeof(*newBVR)); - bcopy(bvr, newBVR, sizeof(*newBVR)); + /* + * Allocate and copy the matched bvr entry into a new one. + */ + newBVR = (BVRef) malloc(sizeof(*newBVR)); + if (!newBVR) + { + continue; + } + bcopy(bvr, newBVR, sizeof(*newBVR)); - /* - * Adjust the new bvr's fields. - */ - newBVR->next = NULL; - newBVR->filtered = true; + /* + * Adjust the new bvr's fields. + */ + newBVR->next = NULL; + newBVR->filtered = true; - if ( (!allowFlags || newBVR->flags & allowFlags) - && (!denyFlags || !(newBVR->flags & denyFlags) ) - && (newBVR->biosdev >= minBIOSDev && newBVR->biosdev <= maxBIOSDev) - ) - newBVR->visible = true; - - /* - * Looking for "Hide Partition" entries in 'hd(x,y)|uuid|"label" hd(m,n)|uuid|"label"' format, - * to be able to hide foreign partitions from the boot menu. - * - */ - if ( (newBVR->flags & kBVFlagForeignBoot) ) - { - char *start, *next = val; - long len = 0; - do - { - start = strbreak(next, &next, &len); - if(len && matchVolumeToString(newBVR, start, len) ) - newBVR->visible = false; - } - while ( next && *next ); - } + if ( (!allowFlags || newBVR->flags & allowFlags) + && (!denyFlags || !(newBVR->flags & denyFlags) ) + && (newBVR->biosdev >= minBIOSDev && newBVR->biosdev <= maxBIOSDev) + ) { + newBVR->visible = true; + } - /* - * Use the first bvr entry as the starting chain pointer. - */ - if (!chain) - chain = newBVR; + /* + * Looking for "Hide Partition" entries in 'hd(x,y)|uuid|"label" hd(m,n)|uuid|"label"' format, + * to be able to hide foreign partitions from the boot menu. + * + */ + if ( (newBVR->flags & kBVFlagForeignBoot) ) { + char *start, *next = val; + long len = 0; + do + { + start = strbreak(next, &next, &len); + if(len && matchVolumeToString(newBVR, start, len) ) + { + newBVR->visible = false; + } + } + while ( next && *next ); + } - /* - * Update the previous bvr's link pointer to use the new memory area. - */ - if (prevBVR) - prevBVR->next = newBVR; - - if (newBVR->visible) - bvCount++; - } - } + /* + * Use the first bvr entry as the starting chain pointer. + */ + if (!chain) { + chain = newBVR; + } + /* + * Update the previous bvr's link pointer to use the new memory area. + */ + if (prevBVR) { + prevBVR->next = newBVR; + } + + if (newBVR->visible) { + bvCount++; + } + } + } + #if DEBUG //Azi: warning - too big for boot-log.. far too big.. i mean HUGE!! :P - for (bvr = chain; bvr; bvr = bvr->next) - { - printf(" bvr: %d, dev: %d, part: %d, flags: %d, vis: %d\n", bvr, bvr->biosdev, bvr->part_no, bvr->flags, bvr->visible); - } - printf("count: %d\n", bvCount); - getchar(); + for (bvr = chain; bvr; bvr = bvr->next) + { + printf(" bvr: %d, dev: %d, part: %d, flags: %d, vis: %d\n", bvr, bvr->biosdev, bvr->part_no, bvr->flags, bvr->visible); + } + printf("count: %d\n", bvCount); + getchar(); #endif - *count = bvCount; - - free(val); - return chain; + *count = bvCount; + + free(val); + return chain; } +//============================================================================== + int freeFilteredBVChain(const BVRef chain) { - int ret = 1; - BVRef bvr = chain; - BVRef nextBVR = NULL; + int ret = 1; + BVRef bvr = chain; + BVRef nextBVR = NULL; - while (bvr) - { - nextBVR = bvr->next; + while (bvr) + { + nextBVR = bvr->next; - if (bvr->filtered) - { - free(bvr); - } - else - { - ret = 0; - break; - } + if (bvr->filtered) + { + free(bvr); + } + else + { + ret = 0; + break; + } - bvr = nextBVR; - } - - return ret; + bvr = nextBVR; + } + + return ret; } -//========================================================================== +//============================================================================== static const struct NamedValue fdiskTypes[] = { @@ -1805,41 +1934,53 @@ { 0x00, 0 } /* must be last */ }; -//========================================================================== +//============================================================================== bool matchVolumeToString( BVRef bvr, const char* match, long matchLen) { char testStr[128]; if ( !bvr || !match || !*match) + { return 0; - + } + if ( bvr->biosdev < 0x80 || bvr->biosdev >= 0x100 ) + { return 0; - - // Try to match hd(x,y) first. - sprintf(testStr, "hd(%d,%d)", BIOS_DEV_UNIT(bvr), bvr->part_no); - if ( matchLen ? !strncmp(match, testStr, matchLen) : !strcmp(match, testStr) ) - return true; - - // Try to match volume UUID. - if ( bvr->fs_getuuid && bvr->fs_getuuid(bvr, testStr) == 0) - { - if( matchLen ? !strncmp(match, testStr, matchLen) : !strcmp(match, testStr) ) - return true; - } - - // Try to match volume label (always quoted). - if ( bvr->description ) - { - bvr->description(bvr, testStr, sizeof(testStr)-1); - if( matchLen ? !strncmp(match, testStr, matchLen) : !strcmp(match, testStr) ) - return true; - } - - return false; + } + + // Try to match hd(x,y) first. + sprintf(testStr, "hd(%d,%d)", BIOS_DEV_UNIT(bvr), bvr->part_no); + if ( matchLen ? !strncmp(match, testStr, matchLen) : !strcmp(match, testStr) ) + { + return true; + } + + // Try to match volume UUID. + if ( bvr->fs_getuuid && bvr->fs_getuuid(bvr, testStr) == 0) + { + if ( matchLen ? !strncmp(match, testStr, matchLen) : !strcmp(match, testStr) ) + { + return true; + } + } + + // Try to match volume label (always quoted). + if ( bvr->description ) + { + bvr->description(bvr, testStr, sizeof(testStr)-1); + if ( matchLen ? !strncmp(match, testStr, matchLen) : !strcmp(match, testStr) ) + { + return true; + } + } + + return false; } +//============================================================================== + /* If Rename Partition has defined an alias, then extract it for description purpose. * The format for the rename string is the following: * hd(x,y)|uuid|"label" "alias";hd(m,n)|uuid|"label" "alias"; etc... @@ -1847,225 +1988,273 @@ bool getVolumeLabelAlias(BVRef bvr, char* str, long strMaxLen) { - char *aliasList, *entryStart, *entryNext; + char *aliasList, *entryStart, *entryNext; - if ( !str || strMaxLen <= 0) - return false; - - aliasList = XMLDecode(getStringForKey(kRenamePartition, &bootInfo->chameleonConfig)); - if ( !aliasList ) - return false; - - for ( entryStart = entryNext = aliasList; - entryNext && *entryNext; - entryStart = entryNext ) - { - char *volStart, *volEnd, *aliasStart; - long volLen, aliasLen; + if ( !str || strMaxLen <= 0) + { + return false; + } + + aliasList = XMLDecode(getStringForKey(kRenamePartition, &bootInfo->chameleonConfig)); + if ( !aliasList ) + { + return false; + } + + for ( entryStart = entryNext = aliasList; entryNext && *entryNext; entryStart = entryNext ) + { + char *volStart, *volEnd, *aliasStart; + long volLen, aliasLen; - // Delimit current entry - entryNext = strchr(entryStart, ';'); - if ( entryNext ) - { - *entryNext = '\0'; - entryNext++; - } + // Delimit current entry + entryNext = strchr(entryStart, ';'); + if ( entryNext ) + { + *entryNext = '\0'; + entryNext++; + } - volStart = strbreak(entryStart, &volEnd, &volLen); - if(!volLen) - continue; - - aliasStart = strbreak(volEnd, 0, &aliasLen); - if(!aliasLen) - continue; - - if ( matchVolumeToString(bvr, volStart, volLen) ) - { - strncat(str, aliasStart, MIN(strMaxLen, aliasLen)); - free(aliasList); - - return true; - } - } + volStart = strbreak(entryStart, &volEnd, &volLen); + if(!volLen) + { + continue; + } + + aliasStart = strbreak(volEnd, 0, &aliasLen); + if(!aliasLen) + { + continue; + } + + if ( matchVolumeToString(bvr, volStart, volLen) ) + { + strncat(str, aliasStart, MIN(strMaxLen, aliasLen)); + free(aliasList); + + return true; + } + } - free(aliasList); - return false; + free(aliasList); + return false; } +//============================================================================== + void getBootVolumeDescription( BVRef bvr, char * str, long strMaxLen, bool useDeviceDescription ) { - unsigned char type; - char *p = str; + unsigned char type; + char *p = str; - if(!bvr || !p || strMaxLen <= 0) - return; - - type = (unsigned char) bvr->part_type; - - if (useDeviceDescription) - { - int len = getDeviceDescription(bvr, str); - if(len >= strMaxLen) - return; - - strcpy(str + len, bvr->OSisInstaller ? " (Installer) " : " "); - len += bvr->OSisInstaller ? 13 : 1; - strMaxLen -= len; - p += len; - } - - /* See if a partition rename is preferred */ - if(getVolumeLabelAlias(bvr, p, strMaxLen)) { - strncpy(bvr->label, p, strMaxLen); - return; // we're done here no need to seek for real name - } - - // - // Get the volume label using filesystem specific functions - // or use the alternate volume label if available. - // + if(!bvr || !p || strMaxLen <= 0) + { + return; + } + + type = (unsigned char) bvr->part_type; + + if (useDeviceDescription) + { + int len = getDeviceDescription(bvr, str); + if(len >= strMaxLen) + { + return; + } + + strcpy(str + len, bvr->OSisInstaller ? " (Installer) " : " "); + len += bvr->OSisInstaller ? 13 : 1; + strMaxLen -= len; + p += len; + } + + /* See if a partition rename is preferred */ + if (getVolumeLabelAlias(bvr, p, strMaxLen)) + { + strncpy(bvr->label, p, strMaxLen); + return; // we're done here no need to seek for real name + } + + // Get the volume label using filesystem specific functions or use the alternate volume label if available. + if (*bvr->altlabel != '\0') - strncpy(p, bvr->altlabel, strMaxLen); + { + strncpy(p, bvr->altlabel, strMaxLen); + } else if (bvr->description) - bvr->description(bvr, p, strMaxLen); + { + bvr->description(bvr, p, strMaxLen); + } - if (*p == '\0') { - const char * name = getNameForValue( fdiskTypes, type ); - if (name == NULL) { - name = bvr->type_name; - } - if (name == NULL) { - sprintf(p, "TYPE %02x", type); - } else { - strncpy(p, name, strMaxLen); - } - } - - // Set the devices label - sprintf(bvr->label, p); + if (*p == '\0') + { + const char * name = getNameForValue( fdiskTypes, type ); + + if (name == NULL) + { + name = bvr->type_name; + } + + if (name == NULL) + { + sprintf(p, "TYPE %02x", type); + } + else + { + strncpy(p, name, strMaxLen); + } + } + + // Set the devices label + sprintf(bvr->label, p); } -//========================================================================== -int readBootSector( int biosdev, unsigned int secno, void * buffer ) + +//============================================================================== + +int readBootSector(int biosdev, unsigned int secno, void * buffer) { - struct disk_blk0 * bootSector = (struct disk_blk0 *) buffer; - int error; + int error; + struct disk_blk0 * bootSector = (struct disk_blk0 *) buffer; - if ( bootSector == NULL ) - { - if ( gBootSector == NULL ) - { - gBootSector = (struct disk_blk0 *) malloc(sizeof(*gBootSector)); - if ( gBootSector == NULL ) return -1; - } - bootSector = gBootSector; - } + if (bootSector == NULL) + { + if (gBootSector == NULL) + { + gBootSector = (struct disk_blk0 *) malloc(sizeof(*gBootSector)); - error = readBytes( biosdev, secno, 0, BPS, bootSector ); - if ( error || bootSector->signature != DISK_SIGNATURE ) - return -1; + if (gBootSector == NULL) + { + return -1; + } + } - return 0; + bootSector = gBootSector; + } + + error = readBytes(biosdev, secno, 0, BPS, bootSector); + + if (error || bootSector->signature != DISK_SIGNATURE) + { + return -1; + } + return 0; } +//============================================================================== + /* * Format of boot1f32 block. */ - + #define BOOT1F32_MAGIC "BOOT " #define BOOT1F32_MAGICLEN 11 -struct disk_boot1f32_blk { - unsigned char init[3]; - unsigned char fsheader[87]; - unsigned char magic[BOOT1F32_MAGICLEN]; - unsigned char bootcode[409]; - unsigned short signature; +struct disk_boot1f32_blk +{ + unsigned char init[3]; + unsigned char fsheader[87]; + unsigned char magic[BOOT1F32_MAGICLEN]; + unsigned char bootcode[409]; + unsigned short signature; }; +//============================================================================== + int testFAT32EFIBootSector( int biosdev, unsigned int secno, void * buffer ) { - struct disk_boot1f32_blk * bootSector = (struct disk_boot1f32_blk *) buffer; - int error; + struct disk_boot1f32_blk * bootSector = (struct disk_boot1f32_blk *) buffer; + int error; - if ( bootSector == NULL ) - { - if ( gBootSector == NULL ) - { - gBootSector = (struct disk_blk0 *) malloc(sizeof(*gBootSector)); - if ( gBootSector == NULL ) return -1; - } - bootSector = (struct disk_boot1f32_blk *) gBootSector; - } + if ( bootSector == NULL ) + { + if ( gBootSector == NULL ) + { + gBootSector = (struct disk_blk0 *) malloc(sizeof(*gBootSector)); + if ( gBootSector == NULL ) + { + return -1; + } + } + bootSector = (struct disk_boot1f32_blk *) gBootSector; + } - error = readBytes( biosdev, secno, 0, BPS, bootSector ); - if ( error || bootSector->signature != DISK_SIGNATURE - || strncmp((const char *)bootSector->magic, BOOT1F32_MAGIC, BOOT1F32_MAGICLEN) ) - return -1; - - return 0; + error = readBytes( biosdev, secno, 0, BPS, bootSector ); + if ( error || bootSector->signature != DISK_SIGNATURE || strncmp((const char *)bootSector->magic, BOOT1F32_MAGIC, BOOT1F32_MAGICLEN) ) + { + return -1; + } + return 0; } -//========================================================================== + +//============================================================================== // Handle seek request from filesystem modules. -void diskSeek( BVRef bvr, long long position ) +void diskSeek(BVRef bvr, long long position) { - bvr->fs_boff = position / BPS; - bvr->fs_byteoff = position % BPS; + bvr->fs_boff = position / BPS; + bvr->fs_byteoff = position % BPS; } -//========================================================================== + +//============================================================================== // Handle read request from filesystem modules. -int diskRead( BVRef bvr, long addr, long length ) +int diskRead(BVRef bvr, long addr, long length) { - return readBytes( bvr->biosdev, - bvr->fs_boff + bvr->part_boff, - bvr->fs_byteoff, - length, - (void *) addr ); + return readBytes(bvr->biosdev, bvr->fs_boff + bvr->part_boff, bvr->fs_byteoff, length, (void *) addr); } +//============================================================================== + int rawDiskRead( BVRef bvr, unsigned int secno, void *buffer, unsigned int len ) { - int secs; - unsigned char *cbuf = (unsigned char *)buffer; - unsigned int copy_len; - int rc; + int secs; + unsigned char *cbuf = (unsigned char *)buffer; + unsigned int copy_len; + int rc; - if ((len & (BPS-1)) != 0) { - error("raw disk read not sector aligned"); - return -1; - } - secno += bvr->part_boff; + if ((len & (BPS-1)) != 0) + { + error("raw disk read not sector aligned"); + return -1; + } + secno += bvr->part_boff; - cache_valid = false; + cache_valid = false; - while (len > 0) { - secs = len / BPS; - if (secs > N_CACHE_SECS) secs = N_CACHE_SECS; - copy_len = secs * BPS; + while (len > 0) + { + secs = len / BPS; + if (secs > N_CACHE_SECS) + { + secs = N_CACHE_SECS; + } + copy_len = secs * BPS; - //printf("rdr: ebiosread(%d, %d, %d)\n", bvr->biosdev, secno, secs); - if ((rc = ebiosread(bvr->biosdev, secno, secs)) != 0) { - /* Ignore corrected ECC errors */ - if (rc != ECC_CORRECTED_ERR) { - error(" EBIOS read error: %s\n", bios_error(rc), rc); - error(" Block %d Sectors %d\n", secno, secs); - return rc; - } - } - bcopy( trackbuf, cbuf, copy_len ); - len -= copy_len; - cbuf += copy_len; - secno += secs; - spinActivityIndicator(secs); - } + //printf("rdr: ebiosread(%d, %d, %d)\n", bvr->biosdev, secno, secs); + if ((rc = ebiosread(bvr->biosdev, secno, secs)) != 0) + { + /* Ignore corrected ECC errors */ + if (rc != ECC_CORRECTED_ERR) + { + error(" EBIOS read error: %s\n", bios_error(rc), rc); + error(" Block %d Sectors %d\n", secno, secs); + return rc; + } + } + bcopy( trackbuf, cbuf, copy_len ); + len -= copy_len; + cbuf += copy_len; + secno += secs; + spinActivityIndicator(secs); + } - return 0; + return 0; } +//============================================================================== + int rawDiskWrite( BVRef bvr, unsigned int secno, void *buffer, unsigned int len ) { int secs; @@ -2073,52 +2262,64 @@ unsigned int copy_len; int rc; - if ((len & (BPS-1)) != 0) { - error("raw disk write not sector aligned"); - return -1; - } - secno += bvr->part_boff; + if ((len & (BPS-1)) != 0) + { + error("raw disk write not sector aligned"); + return -1; + } + secno += bvr->part_boff; - cache_valid = false; + cache_valid = false; - while (len > 0) { - secs = len / BPS; - if (secs > N_CACHE_SECS) secs = N_CACHE_SECS; - copy_len = secs * BPS; + while (len > 0) + { + secs = len / BPS; + if (secs > N_CACHE_SECS) + { + secs = N_CACHE_SECS; + } + copy_len = secs * BPS; - bcopy( cbuf, trackbuf, copy_len ); - //printf("rdr: ebioswrite(%d, %d, %d)\n", bvr->biosdev, secno, secs); - if ((rc = ebioswrite(bvr->biosdev, secno, secs)) != 0) { - error(" EBIOS write error: %s\n", bios_error(rc), rc); - error(" Block %d Sectors %d\n", secno, secs); - return rc; - } - len -= copy_len; - cbuf += copy_len; - secno += secs; - spinActivityIndicator(secs); - } + bcopy( cbuf, trackbuf, copy_len ); + //printf("rdr: ebioswrite(%d, %d, %d)\n", bvr->biosdev, secno, secs); + if ((rc = ebioswrite(bvr->biosdev, secno, secs)) != 0) + { + error(" EBIOS write error: %s\n", bios_error(rc), rc); + error(" Block %d Sectors %d\n", secno, secs); + return rc; + } - return 0; + len -= copy_len; + cbuf += copy_len; + secno += secs; + spinActivityIndicator(secs); + } + + return 0; } +//============================================================================== + int diskIsCDROM(BVRef bvr) { - struct driveInfo di; + struct driveInfo di; - if (getDriveInfo(bvr->biosdev, &di) == 0 && di.no_emulation) { - return 1; - } - return 0; + if (getDriveInfo(bvr->biosdev, &di) == 0 && di.no_emulation) + { + return 1; + } + return 0; } +//============================================================================== + int biosDevIsCDROM(int biosdev) { - struct driveInfo di; + struct driveInfo di; - if (getDriveInfo(biosdev, &di) == 0 && di.no_emulation) - { - return 1; - } - return 0; + if (getDriveInfo(biosdev, &di) == 0 && di.no_emulation) + { + return 1; + } + return 0; } Index: trunk/i386/libsaio/cache.c =================================================================== --- trunk/i386/libsaio/cache.c (revision 2326) +++ trunk/i386/libsaio/cache.c (revision 2327) @@ -31,9 +31,9 @@ // #include struct CacheEntry { - CICell ih; - long time; - long long offset; + CICell ih; + long time; + long long offset; }; typedef struct CacheEntry CacheEntry; @@ -48,128 +48,155 @@ static long gCacheTime; #ifdef __i386__ -static CacheEntry *gCacheEntries; -static char *gCacheBuffer; + static CacheEntry *gCacheEntries; + static char *gCacheBuffer; #else -static CacheEntry gCacheEntries[kCacheMaxEntries]; -static char gCacheBuffer[kCacheSize]; + static CacheEntry gCacheEntries[kCacheMaxEntries]; + static char gCacheBuffer[kCacheSize]; #endif #if CACHE_STATS -unsigned long gCacheHits; -unsigned long gCacheMisses; -unsigned long gCacheEvicts; + unsigned long gCacheHits; + unsigned long gCacheMisses; + unsigned long gCacheEvicts; #endif void CacheReset() { - gCacheIH = NULL; + gCacheIH = NULL; } void CacheInit( CICell ih, long blockSize ) { #ifdef __i386__ - if ((ih == gCacheIH) && (blockSize == gCacheBlockSize)) - return; + if ((ih == gCacheIH) && (blockSize == gCacheBlockSize)) + { + return; + } #endif - if ((blockSize < kCacheMinBlockSize) || - (blockSize > kCacheMaxBlockSize)) - return; + if ((blockSize < kCacheMinBlockSize) || (blockSize > kCacheMaxBlockSize)) + { + return; + } - gCacheBlockSize = blockSize; - gCacheNumEntries = kCacheSize / gCacheBlockSize; - gCacheTime = 0; + gCacheBlockSize = blockSize; + gCacheNumEntries = kCacheSize / gCacheBlockSize; + gCacheTime = 0; #if CACHE_STATS - gCacheHits = 0; - gCacheMisses = 0; - gCacheEvicts = 0; + gCacheHits = 0; + gCacheMisses = 0; + gCacheEvicts = 0; #endif gCacheIH = ih; #ifdef __i386__ - if (!gCacheBuffer) gCacheBuffer = (char *) malloc(kCacheSize); - if (!gCacheEntries) gCacheEntries = (CacheEntry *) malloc(kCacheMaxEntries * sizeof(CacheEntry)); - if ( !gCacheBuffer || !gCacheEntries ) - { - gCacheIH = 0; // invalidate cache - return; - } + if (!gCacheBuffer) + { + gCacheBuffer = (char *) malloc(kCacheSize); + } + + if (!gCacheEntries) + { + gCacheEntries = (CacheEntry *) malloc(kCacheMaxEntries * sizeof(CacheEntry)); + } + + if (!gCacheBuffer || !gCacheEntries) + { + gCacheIH = 0; // invalidate cache + return; + } #endif - bzero(gCacheEntries, kCacheMaxEntries * sizeof(CacheEntry)); + bzero(gCacheEntries, kCacheMaxEntries * sizeof(CacheEntry)); } -long CacheRead( CICell ih, char * buffer, long long offset, - long length, long cache ) +long CacheRead(CICell ih, char * buffer, long long offset, long length, long cache) { - long cnt, oldestEntry = 0, oldestTime, loadCache = 0; - CacheEntry *entry; + long cnt, oldestEntry = 0, oldestTime, loadCache = 0; + CacheEntry *entry; - // See if the data can be cached. - if (cache && (gCacheIH == ih) && (length == gCacheBlockSize)) { - // Look for the data in the cache. - for (cnt = 0; cnt < gCacheNumEntries; cnt++) { - entry = &gCacheEntries[cnt]; - if ((entry->ih == ih) && (entry->offset == offset)) { - entry->time = ++gCacheTime; - break; - } - } + // See if the data can be cached. + if (cache && (gCacheIH == ih) && (length == gCacheBlockSize)) + { + // Look for the data in the cache. + for (cnt = 0; cnt < gCacheNumEntries; cnt++) + { + entry = &gCacheEntries[cnt]; - // If the data was found copy it to the caller. - if (cnt != gCacheNumEntries) { - bcopy(gCacheBuffer + cnt * gCacheBlockSize, buffer, gCacheBlockSize); + if ((entry->ih == ih) && (entry->offset == offset)) + { + entry->time = ++gCacheTime; + break; + } + } + + // If the data was found copy it to the caller. + if (cnt != gCacheNumEntries) + { + bcopy(gCacheBuffer + cnt * gCacheBlockSize, buffer, gCacheBlockSize); #if CACHE_STATS - gCacheHits++; + gCacheHits++; #endif - return gCacheBlockSize; - } + return gCacheBlockSize; + } - // Could not find the data in the cache. - loadCache = 1; - } + // Could not find the data in the cache. + loadCache = 1; + } - // Read the data from the disk. - Seek(ih, offset); - Read(ih, (long)buffer, length); + // Read the data from the disk. + Seek(ih, offset); + Read(ih, (long)buffer, length); + #if CACHE_STATS - if (cache) gCacheMisses++; + if (cache) + { + gCacheMisses++; + } #endif - // Put the data from the disk in the cache if needed. - if (loadCache) { - // Find a free entry. - oldestTime = gCacheTime; - for (cnt = 0; cnt < gCacheNumEntries; cnt++) { - entry = &gCacheEntries[cnt]; + // Put the data from the disk in the cache if needed. + if (loadCache) + { + // Find a free entry. + oldestTime = gCacheTime; - // Found a free entry. - if (entry->ih == 0) break; - - if (entry->time < oldestTime) { - oldestTime = entry->time; - oldestEntry = cnt; - } - } + for (cnt = 0; cnt < gCacheNumEntries; cnt++) + { + entry = &gCacheEntries[cnt]; - // If no free entry was found, use the oldest. - if (cnt == gCacheNumEntries) { - cnt = oldestEntry; + // Found a free entry. + if (entry->ih == 0) + { + break; + } + + if (entry->time < oldestTime) + { + oldestTime = entry->time; + oldestEntry = cnt; + } + } + + // If no free entry was found, use the oldest. + if (cnt == gCacheNumEntries) + { + cnt = oldestEntry; #if CACHE_STATS - gCacheEvicts++; + gCacheEvicts++; #endif - } + } - // Copy the data from disk to the new entry. - entry = &gCacheEntries[cnt]; - entry->ih = ih; - entry->time = ++gCacheTime; - entry->offset = offset; - bcopy(buffer, gCacheBuffer + cnt * gCacheBlockSize, gCacheBlockSize); - } + // Copy the data from disk to the new entry. + entry = &gCacheEntries[cnt]; + entry->ih = ih; + entry->time = ++gCacheTime; + entry->offset = offset; + bcopy(buffer, gCacheBuffer + cnt * gCacheBlockSize, gCacheBlockSize); + } - return length; + return length; } Index: trunk/i386/libsaio/pci.c =================================================================== --- trunk/i386/libsaio/pci.c (revision 2326) +++ trunk/i386/libsaio/pci.c (revision 2327) @@ -83,7 +83,11 @@ continue; } new = (pci_dt_t*)malloc(sizeof(pci_dt_t)); + if (!new) { + continue; + } bzero(new, sizeof(pci_dt_t)); + new->dev.addr = pci_addr; new->vendor_id = id & 0xffff; new->device_id = (id >> 16) & 0xffff; @@ -91,6 +95,7 @@ new->revision_id = pci_config_read8(pci_addr, PCI_CLASS_REVISION); new->subsys_id.subsys_id = pci_config_read32(pci_addr, PCI_SUBSYSTEM_VENDOR_ID); new->class_id = pci_config_read16(pci_addr, PCI_CLASS_DEVICE); + //new->subclass_id = pci_config_read16(pci_addr, PCI_SUBCLASS_DEVICE); new->parent = start; header_type = pci_config_read8(pci_addr, PCI_HEADER_TYPE); @@ -102,6 +107,8 @@ scan_pci_bus(new, secondary_bus); } break; + default: + break; } *current = new; current = &new->next; @@ -124,7 +131,7 @@ { return; } - rcba = pci_config_read32(PCIADDR(0, 0x1f, 0), 0xf0) & ~1; + rcba = pci_config_read32(PCIADDR(0, 0x1f, 0), 0xf0) & ~1; //this is LPC host fd = (uint32_t *)(rcba + 0x3418); /* set SMBus Disable (SD) to 0 */ *fd &= ~0x8; @@ -136,6 +143,11 @@ void build_pci_dt(void) { root_pci_dev = malloc(sizeof(pci_dt_t)); + + if (!root_pci_dev) { + return; + } + bzero(root_pci_dev, sizeof(pci_dt_t)); enable_pci_devs(); scan_pci_bus(root_pci_dev, 0); @@ -151,7 +163,7 @@ { pci_dt_t *current; pci_dt_t *end; - int dev_path_len = 0; + int dev_path_len = 0; dev_path[0] = 0; end = root_pci_dev; @@ -159,19 +171,20 @@ int uid = getPciRootUID(); while (end != pci_dt) { - current = pci_dt; - while (current->parent != end) - current = current->parent; - end = current; - if (current->parent == root_pci_dev) { - dev_path_len += - snprintf(dev_path + dev_path_len, sizeof(dev_path) - dev_path_len, "PciRoot(0x%x)/Pci(0x%x,0x%x)", uid, - current->dev.bits.dev, current->dev.bits.func); - } else { - dev_path_len += - snprintf(dev_path + dev_path_len, sizeof(dev_path) - dev_path_len, "/Pci(0x%x,0x%x)", - current->dev.bits.dev, current->dev.bits.func); - } + current = pci_dt; + while (current->parent != end) + current = current->parent; + end = current; + if (current->parent == root_pci_dev) { + dev_path_len += + snprintf(dev_path + dev_path_len, sizeof(dev_path) - dev_path_len, "PciRoot(0x%x)/Pci(0x%x,0x%x)", uid, + current->dev.bits.dev, current->dev.bits.func); + } else { + dev_path_len += + snprintf(dev_path + dev_path_len, sizeof(dev_path) - dev_path_len, "/Pci(0x%x,0x%x)", + current->dev.bits.dev, current->dev.bits.func); + } + } return dev_path; } @@ -184,8 +197,8 @@ while (current) { printf("%02x:%02x.%x [%04x%02x] [%04x:%04x] (subsys [%04x:%04x]):: %s\n", current->dev.bits.bus, current->dev.bits.dev, current->dev.bits.func, - current->class_id, 0 /* FIXME: what should this be? */, - current->vendor_id, current->device_id, + current->class_id, 0 /* FIXME: what should this be? */, + current->vendor_id, current->device_id, current->subsys_id.subsys.vendor_id, current->subsys_id.subsys.device_id, get_pci_dev_path(current)); dump_pci_dt(current->children); Index: trunk/i386/libsaio/biosfn.c =================================================================== --- trunk/i386/libsaio/biosfn.c (revision 2326) +++ trunk/i386/libsaio/biosfn.c (revision 2327) @@ -48,57 +48,70 @@ static biosBuf_t bb; + +//============================================================================== + int bgetc(void) { - /* Poll for the next character. Most real BIOS do not need this as the - INT 16h,AH=0h function will block until one is received. - Unfortunately, Apple's EFI CSM will never wake up. This idea is lifted - from the grub-a20.patch to GRUB's stage2/asm.S file. - */ - while(!readKeyboardStatus()) - ; - bb.intno = 0x16; - bb.eax.r.h = 0x00; - bios(&bb); - return bb.eax.rr; + /* Poll for the next character. Most real BIOS do not need this as the + INT 16h,AH=0h function will block until one is received. + Unfortunately, Apple's EFI CSM will never wake up. This idea is lifted + from the grub-a20.patch to GRUB's stage2/asm.S file. + */ + while(!readKeyboardStatus()); + + bb.intno = 0x16; + bb.eax.r.h = 0x00; + bios(&bb); + + return bb.eax.rr; } + +//============================================================================== + int readKeyboardStatus(void) { - bb.intno = 0x16; - bb.eax.r.h = 0x01; - bios(&bb); - if (bb.flags.zf) { - return 0; - } else { - return bb.eax.rr; - } + bb.intno = 0x16; + bb.eax.r.h = 0x01; + bios(&bb); + + if (bb.flags.zf) { + return 0; + } else { + return bb.eax.rr; + } } int readKeyboardShiftFlags(void) { - bb.intno = 0x16; - bb.eax.r.h = 0x02; - bios(&bb); - return bb.eax.r.l; + bb.intno = 0x16; + bb.eax.r.h = 0x02; + bios(&bb); + return bb.eax.r.l; } + +//============================================================================== + unsigned int time18(void) { - union { - struct { - unsigned int low:16; - unsigned int high:16; - } s; - unsigned int i; - } time; + union { + struct { + unsigned int low:16; + unsigned int high:16; + } s; + + unsigned int i; + } time; - bb.intno = 0x1a; - bb.eax.r.h = 0x00; - bios(&bb); - time.s.low = bb.edx.rr; - time.s.high = bb.ecx.rr; - return time.i; + bb.intno = 0x1a; + bb.eax.r.h = 0x00; + bios(&bb); + time.s.low = bb.edx.rr; + time.s.high = bb.ecx.rr; + + return time.i; } #if 0 @@ -165,311 +178,349 @@ unsigned long * conMemSizePtr, unsigned long * extMemSizePtr ) { - #define kMemoryMapSignature 'SMAP' - #define kDescriptorSizeMin 20 + #define kMemoryMapSignature 'SMAP' + #define kDescriptorSizeMin 20 - MemoryRange * range = (MemoryRange *)BIOS_ADDR; - unsigned long count = 0; - // unsigned long rerangedCount; - unsigned long long conMemSize = 0; - unsigned long long extMemSize = 0; + MemoryRange * range = (MemoryRange *)BIOS_ADDR; + unsigned long count = 0; + // unsigned long rerangedCount; + unsigned long long conMemSize = 0; + unsigned long long extMemSize = 0; - // Prepare for the INT15 E820h call. Each call returns a single - // memory range. A continuation value is returned that must be - // provided on a subsequent call to fetch the next range. - // - // Certain BIOSes (Award 6.00PG) expect the upper word in EAX - // to be cleared on entry, otherwise only a single range will - // be reported. - // - // Some BIOSes will simply ignore the value of ECX on entry. - // Probably best to keep its value at 20 to avoid surprises. + // Prepare for the INT15 E820h call. Each call returns a single + // memory range. A continuation value is returned that must be + // provided on a subsequent call to fetch the next range. + // + // Certain BIOSes (Award 6.00PG) expect the upper word in EAX + // to be cleared on entry, otherwise only a single range will + // be reported. + // + // Some BIOSes will simply ignore the value of ECX on entry. + // Probably best to keep its value at 20 to avoid surprises. - //printf("Get memory map 0x%x, %d\n", rangeArray); getchar(); - if (maxRangeCount > (BIOS_LEN / sizeof(MemoryRange))) { - maxRangeCount = (BIOS_LEN / sizeof(MemoryRange)); - } - bb.ebx.rx = 0; // Initial continuation value must be zero. + //printf("Get memory map 0x%x, %d\n", rangeArray); getchar(); + if (maxRangeCount > (BIOS_LEN / sizeof(MemoryRange))) { + maxRangeCount = (BIOS_LEN / sizeof(MemoryRange)); + } + bb.ebx.rx = 0; // Initial continuation value must be zero. - while ( count < maxRangeCount ) - { - bb.intno = 0x15; - bb.eax.rx = 0xe820; - bb.ecx.rx = kDescriptorSizeMin; - bb.edx.rx = kMemoryMapSignature; - bb.edi.rr = NORMALIZED_OFFSET( (unsigned long) range ); - bb.es = NORMALIZED_SEGMENT( (unsigned long) range ); - bios(&bb); + while (count < maxRangeCount) + { + bb.intno = 0x15; + bb.eax.rx = 0xe820; + bb.ecx.rx = kDescriptorSizeMin; + bb.edx.rx = kMemoryMapSignature; + bb.edi.rr = NORMALIZED_OFFSET( (unsigned long) range ); + bb.es = NORMALIZED_SEGMENT( (unsigned long) range ); + bios(&bb); - // Check for errors. + // Check for errors. - if ( bb.flags.cf - || bb.eax.rx != kMemoryMapSignature - || bb.ecx.rx != kDescriptorSizeMin ) { - //printf("Got an error %x %x %x\n", bb.flags.cf, - // bb.eax.rx, bb.ecx.rx); - break; - } + if ( bb.flags.cf + || bb.eax.rx != kMemoryMapSignature + || bb.ecx.rx != kDescriptorSizeMin ) { + //printf("Got an error %x %x %x\n", bb.flags.cf, + // bb.eax.rx, bb.ecx.rx); + break; + } - // Tally up the conventional/extended memory sizes. + // Tally up the conventional/extended memory sizes. - if ( range->type == kMemoryRangeUsable || - range->type == kMemoryRangeACPI || - range->type == kMemoryRangeNVS ) - { - // Tally the conventional memory ranges. - if ( range->base + range->length <= 0xa0000 ) { - conMemSize += range->length; - } + if ( range->type == kMemoryRangeUsable || + range->type == kMemoryRangeACPI || + range->type == kMemoryRangeNVS ) { + // Tally the conventional memory ranges. + if ( range->base + range->length <= 0xa0000 ) { + conMemSize += range->length; + } - // Record the top of extended memory. - if ( range->base >= EXTENDED_ADDR ) { - extMemSize += range->length; - } - } + // Record the top of extended memory. + if (range->base >= EXTENDED_ADDR) { + extMemSize += range->length; + } + } - range++; - count++; + range++; + count++; - // Is this the last address range? + // Is this the last address range? - if ( bb.ebx.rx == 0 ) { - //printf("last range\n"); - break; - } - } - *conMemSizePtr = conMemSize / 1024; // size in KB - *extMemSizePtr = extMemSize / 1024; // size in KB + if ( bb.ebx.rx == 0 ) { + //printf("last range\n"); + break; + } + } + *conMemSizePtr = conMemSize / 1024; // size in KB + *extMemSizePtr = extMemSize / 1024; // size in KB #if 0 - rerangedCount = rerangeMemoryMap(count); - range += rerangedCount - count; + rerangedCount = rerangeMemoryMap(count); + range += rerangedCount - count; #endif - // Copy out data - bcopy((char *)BIOS_ADDR, rangeArray, ((char *)range - (char *)BIOS_ADDR)); + // Copy out data + bcopy((char *)BIOS_ADDR, rangeArray, ((char *)range - (char *)BIOS_ADDR)); #if DEBUG - { - int i; - printf("%d total ranges\n", count); getchar(); - for (i=0, range = rangeArray; itype, (unsigned int)range->base, (unsigned int)range->length); getchar(); - } - } + { + int i; + printf("%d total ranges\n", count); + + getchar(); + + for (i = 0, range = rangeArray; itype, (unsigned int)range->base, (unsigned int)range->length); + getchar(); + } + } #endif - return count; + return count; } + +//============================================================================== + + unsigned long getExtendedMemorySize() { - // Get extended memory size for large configurations. Not used unless - // the INT15, E820H call (Get System Address Map) failed. - // - // Input: - // - // AX Function Code E801h - // - // Outputs: - // - // CF Carry Flag Carry cleared indicates no error. - // AX Extended 1 Number of contiguous KB between 1 and 16 MB, - // maximum 0x3C00 = 15 MB. - // BX Extended 2 Number of contiguous 64 KB blocks between - // 16 MB and 4 GB. - // CX Configured 1 Number of contiguous KB between 1 and 16 MB, - // maximum 0x3C00 = 15 MB. - // DX Configured 2 Number of contiguous 64 KB blocks between - // 16 MB and 4 GB. + // Get extended memory size for large configurations. Not used unless + // the INT15, E820H call (Get System Address Map) failed. + // + // Input: + // + // AX Function Code E801h + // + // Outputs: + // + // CF Carry Flag Carry cleared indicates no error. + // AX Extended 1 Number of contiguous KB between 1 and 16 MB, + // maximum 0x3C00 = 15 MB. + // BX Extended 2 Number of contiguous 64 KB blocks between + // 16 MB and 4 GB. + // CX Configured 1 Number of contiguous KB between 1 and 16 MB, + // maximum 0x3C00 = 15 MB. + // DX Configured 2 Number of contiguous 64 KB blocks between + // 16 MB and 4 GB. - bb.intno = 0x15; - bb.eax.rx = 0xe801; - bios(&bb); + bb.intno = 0x15; + bb.eax.rx = 0xe801; + bios(&bb); - // Return the size of memory above 1MB (extended memory) in kilobytes. + // Return the size of memory above 1MB (extended memory) in kilobytes. - if ( bb.flags.cf == 0 ) return (bb.ebx.rr * 64 + bb.eax.rr); + if (bb.flags.cf == 0) { + return (bb.ebx.rr * 64 + bb.eax.rr); + } - // Get Extended memory size. Called on last resort since the return - // value is limited to 16-bits (a little less than 64MB max). May - // not be supported by modern BIOSes. - // - // Input: - // - // AX Function Code E801h - // - // Outputs: - // - // CF Carry Flag Carry cleared indicates no error. - // AX Memory Count Number of contiguous KB above 1MB. + // Get Extended memory size. Called on last resort since the return + // value is limited to 16-bits (a little less than 64MB max). May + // not be supported by modern BIOSes. + // + // Input: + // + // AX Function Code E801h + // + // Outputs: + // + // CF Carry Flag Carry cleared indicates no error. + // AX Memory Count Number of contiguous KB above 1MB. - bb.intno = 0x15; - bb.eax.rx = 0x88; - bios(&bb); + bb.intno = 0x15; + bb.eax.rx = 0x88; + bios(&bb); - // Return the size of memory above 1MB (extended memory) in kilobytes. + // Return the size of memory above 1MB (extended memory) in kilobytes. - return bb.flags.cf ? 0 : bb.eax.rr; + return bb.flags.cf ? 0 : bb.eax.rr; } + +//============================================================================== + + unsigned long getConventionalMemorySize() { - bb.intno = 0x12; - bios(&bb); - return bb.eax.rr; // kilobytes + bb.intno = 0x12; + bios(&bb); + + return bb.eax.rr; // kilobytes } + +//============================================================================== + + void video_mode(int mode) { - bb.intno = 0x10; - bb.eax.r.h = 0x00; - bb.eax.r.l = mode; - bios(&bb); + bb.intno = 0x10; + bb.eax.r.h = 0x00; + bb.eax.r.l = mode; + bios(&bb); } + +//============================================================================== + int biosread(int dev, int cyl, int head, int sec, int num) { - int i; + int i; - bb.intno = 0x13; - sec += 1; /* sector numbers start at 1 */ + bb.intno = 0x13; + sec += 1; // sector numbers start at 1. - for (i=0;;) { - bb.ecx.r.h = cyl; - bb.ecx.r.l = ((cyl & 0x300) >> 2) | (sec & 0x3F); - bb.edx.r.h = head; - bb.edx.r.l = dev; - bb.eax.r.l = num; - bb.ebx.rr = OFFSET(ptov(BIOS_ADDR)); - bb.es = SEGMENT(ptov(BIOS_ADDR)); + for (i = 0; ;) { + bb.ecx.r.h = cyl; + bb.ecx.r.l = ((cyl & 0x300) >> 2) | (sec & 0x3F); + bb.edx.r.h = head; + bb.edx.r.l = dev; + bb.eax.r.l = num; + bb.ebx.rr = OFFSET(ptov(BIOS_ADDR)); + bb.es = SEGMENT(ptov(BIOS_ADDR)); - bb.eax.r.h = 0x02; - bios(&bb); + bb.eax.r.h = 0x02; + bios(&bb); - /* In case of a successful call, make sure we set AH (return code) to zero. */ - if (bb.flags.cf == 0) - bb.eax.r.h = 0; + // In case of a successful call, make sure we set AH (return code) to zero. + if (bb.flags.cf == 0) { + bb.eax.r.h = 0; + } - /* Now we can really check for the return code (AH) value. */ - if ((bb.eax.r.h == 0x00) || (i++ >= 5)) - break; + // Now we can really check for the return code (AH) value. + if ((bb.eax.r.h == 0x00) || (i++ >= 5)) { + break; + } - /* reset disk subsystem and try again */ - bb.eax.r.h = 0x00; - bios(&bb); - } - return bb.eax.r.h; + // Reset disk subsystem and try again. + bb.eax.r.h = 0x00; + bios(&bb); + } + return bb.eax.r.h; } + +//============================================================================== + int ebiosread(int dev, unsigned long long sec, int count) { - int i; - static struct { - unsigned char size; - unsigned char reserved; - unsigned char numblocks; - unsigned char reserved2; - unsigned short bufferOffset; - unsigned short bufferSegment; - unsigned long long startblock; - } addrpacket __attribute__((aligned(16))) = {0}; - addrpacket.size = sizeof(addrpacket); + int i; - for (i=0;;) { - bb.intno = 0x13; - bb.eax.r.h = 0x42; - bb.edx.r.l = dev; - bb.esi.rr = NORMALIZED_OFFSET((unsigned)&addrpacket); - bb.ds = NORMALIZED_SEGMENT((unsigned)&addrpacket); - addrpacket.reserved = addrpacket.reserved2 = 0; - addrpacket.numblocks = count; - addrpacket.bufferOffset = OFFSET(ptov(BIOS_ADDR)); - addrpacket.bufferSegment = SEGMENT(ptov(BIOS_ADDR)); - addrpacket.startblock = sec; - bios(&bb); + static struct { + unsigned char size; + unsigned char reserved; + unsigned char numblocks; + unsigned char reserved2; + unsigned short bufferOffset; + unsigned short bufferSegment; + unsigned long long startblock; + } addrpacket __attribute__((aligned(16))) = {0}; + addrpacket.size = sizeof(addrpacket); - /* In case of a successful call, make sure we set AH (return code) to zero. */ - if (bb.flags.cf == 0) - bb.eax.r.h = 0; + for (i = 0; ;) { + bb.intno = 0x13; + bb.eax.r.h = 0x42; + bb.edx.r.l = dev; + bb.esi.rr = NORMALIZED_OFFSET((unsigned)&addrpacket); + bb.ds = NORMALIZED_SEGMENT((unsigned)&addrpacket); + addrpacket.reserved = addrpacket.reserved2 = 0; + addrpacket.numblocks = count; + addrpacket.bufferOffset = OFFSET(ptov(BIOS_ADDR)); + addrpacket.bufferSegment = SEGMENT(ptov(BIOS_ADDR)); + addrpacket.startblock = sec; + bios(&bb); - /* Now we can really check for the return code (AH) value. */ - if ((bb.eax.r.h == 0x00) || (i++ >= 5)) - break; + // In case of a successful call, make sure we set AH (return code) to zero. + if (bb.flags.cf == 0) { + bb.eax.r.h = 0; + } - /* reset disk subsystem and try again */ - bb.eax.r.h = 0x00; - bios(&bb); - } - return bb.eax.r.h; + // Now we can really check for the return code (AH) value. + if ((bb.eax.r.h == 0x00) || (i++ >= 5)) { + break; + } + + // Reset disk subsystem and try again. + bb.eax.r.h = 0x00; + bios(&bb); + } + + return bb.eax.r.h; } +//============================================================================== + int ebioswrite(int dev, long sec, int count) { - int i; - static struct { - unsigned char size; - unsigned char reserved; - unsigned char numblocks; - unsigned char reserved2; - unsigned short bufferOffset; - unsigned short bufferSegment; - unsigned long long startblock; - } addrpacket __attribute__((aligned(16))) = {0}; - addrpacket.size = sizeof(addrpacket); + int i; + static struct { + unsigned char size; + unsigned char reserved; + unsigned char numblocks; + unsigned char reserved2; + unsigned short bufferOffset; + unsigned short bufferSegment; + unsigned long long startblock; + } addrpacket __attribute__((aligned(16))) = {0}; + addrpacket.size = sizeof(addrpacket); - for (i=0;;) { - bb.intno = 0x13; - bb.eax.r.l = 0; /* Don't verify */ - bb.eax.r.h = 0x43; - bb.edx.r.l = dev; - bb.esi.rr = NORMALIZED_OFFSET((unsigned)&addrpacket); - bb.ds = NORMALIZED_SEGMENT((unsigned)&addrpacket); - addrpacket.reserved = addrpacket.reserved2 = 0; - addrpacket.numblocks = count; - addrpacket.bufferOffset = OFFSET(ptov(BIOS_ADDR)); - addrpacket.bufferSegment = SEGMENT(ptov(BIOS_ADDR)); - addrpacket.startblock = sec; - bios(&bb); + for (i=0;;) { + bb.intno = 0x13; + bb.eax.r.l = 0; /* Don't verify */ + bb.eax.r.h = 0x43; + bb.edx.r.l = dev; + bb.esi.rr = NORMALIZED_OFFSET((unsigned)&addrpacket); + bb.ds = NORMALIZED_SEGMENT((unsigned)&addrpacket); + addrpacket.reserved = addrpacket.reserved2 = 0; + addrpacket.numblocks = count; + addrpacket.bufferOffset = OFFSET(ptov(BIOS_ADDR)); + addrpacket.bufferSegment = SEGMENT(ptov(BIOS_ADDR)); + addrpacket.startblock = sec; + bios(&bb); - /* In case of a successful call, make sure we set AH (return code) to zero. */ - if (bb.flags.cf == 0) - bb.eax.r.h = 0; + /* In case of a successful call, make sure we set AH (return code) to zero. */ + if (bb.flags.cf == 0) + bb.eax.r.h = 0; - /* Now we can really check for the return code (AH) value. */ - if ((bb.eax.r.h == 0x00) || (i++ >= 5)) - break; + /* Now we can really check for the return code (AH) value. */ + if ((bb.eax.r.h == 0x00) || (i++ >= 5)) + break; - /* reset disk subsystem and try again */ - bb.eax.r.h = 0x00; - bios(&bb); - } - return bb.eax.r.h; + /* reset disk subsystem and try again */ + bb.eax.r.h = 0x00; + bios(&bb); + } + return bb.eax.r.h; } void bios_putchar(int ch) { - bb.intno = 0x10; - bb.ebx.r.h = 0x00; /* background black */ - bb.ebx.r.l = 0x0F; /* foreground white */ - bb.eax.r.h = 0x0e; - bb.eax.r.l = ch; - bios(&bb); + bb.intno = 0x10; + bb.ebx.r.h = 0x00; /* background black */ + bb.ebx.r.l = 0x0F; /* foreground white */ + bb.eax.r.h = 0x0e; + bb.eax.r.l = ch; + bios(&bb); } + +//============================================================================== + void putca(int ch, int attr, int repeat) { - bb.intno = 0x10; - bb.ebx.r.h = 0x00; /* page number */ - bb.ebx.r.l = attr; /* attribute */ - bb.eax.r.h = 0x9; - bb.eax.r.l = ch; - bb.ecx.rx = repeat; /* repeat count */ - bios(&bb); + bb.intno = 0x10; + bb.ebx.r.h = 0x00; /* page number */ + bb.ebx.r.l = attr; /* attribute */ + bb.eax.r.h = 0x9; + bb.eax.r.l = ch; + bb.ecx.rx = repeat; /* repeat count */ + bios(&bb); } -/* Check to see if the passed-in drive is in El Torito no-emulation mode. */ + +//============================================================================== +// Check to see if the passed-in drive is in El Torito no-emulation mode. + int is_no_emulation(int drive) { struct packet { @@ -488,30 +539,30 @@ unsigned char reseved; } __attribute__((packed)); static struct packet pkt; - + bzero(&pkt, sizeof(pkt)); pkt.packet_size = 0x13; - - bb.intno = 0x13; - bb.eax.r.h = 0x4b; - bb.eax.r.l = 0x01; // subfunc: get info - bb.edx.r.l = drive; - bb.esi.rr = NORMALIZED_OFFSET((unsigned)&pkt); - bb.ds = NORMALIZED_SEGMENT((unsigned)&pkt); - + + bb.intno = 0x13; + bb.eax.r.h = 0x4b; + bb.eax.r.l = 0x01; // subfunc: get info + bb.edx.r.l = drive; + bb.esi.rr = NORMALIZED_OFFSET((unsigned)&pkt); + bb.ds = NORMALIZED_SEGMENT((unsigned)&pkt); + bios(&bb); + #if DEBUG printf("el_torito info drive %x\n", drive); - printf("--> cf %x, eax %x\n", bb.flags.cf, bb.eax.rr); - printf("pkt_size: %x\n", pkt.packet_size); printf("media_type: %x\n", pkt.media_type); printf("drive_num: %x\n", pkt.drive_num); printf("device_spec: %x\n", pkt.device_spec); + pause(); #endif - + /* Some BIOSes erroneously return cf = 1 */ /* Just check to see if the drive number is the same. */ if (pkt.drive_num == drive) { @@ -568,28 +619,34 @@ #endif +//============================================================================== + int get_drive_info(int drive, struct driveInfo *dp) { + int ret = 0; + boot_drive_info_t *di = &dp->di; - int ret = 0; - + #if UNUSED if (maxhd == 0) { bb.intno = 0x13; bb.eax.r.h = 0x08; bb.edx.r.l = 0x80; bios(&bb); - if (bb.flags.cf == 0) + + if (bb.flags.cf == 0) { maxhd = 0x7f + bb.edx.r.l; + } }; - - if (drive > maxhd) + + if (drive > maxhd) { return 0; + } #endif - + bzero(dp, sizeof(struct driveInfo)); dp->biosdev = drive; - + /* Check for El Torito no-emulation mode. */ dp->no_emulation = is_no_emulation(drive); @@ -620,9 +677,7 @@ if (bb.flags.cf != 0 /* || params.phys_sectors < 2097152 */) { dp->uses_ebios = 0; di->params.buf_size = 1; - } - else - { + } else { bcopy(¶ms, &di->params, sizeof(params)); if (drive >= BASE_HD_DRIVE && @@ -684,101 +739,102 @@ return ret; } +//============================================================================== + int ebiosEjectMedia(int biosdev) { - bb.intno = 0x13; - bb.eax.r.h = 0x46; - bb.eax.r.l = 0; - bb.edx.rx = biosdev; - bios(&bb); - return bb.eax.r.h; + bb.intno = 0x13; + bb.eax.r.h = 0x46; + bb.eax.r.l = 0; + bb.edx.rx = biosdev; + bios(&bb); + return bb.eax.r.h; } void setCursorPosition(int x, int y, int page) { - bb.intno = 0x10; - bb.eax.r.h = 0x02; - bb.ebx.r.h = page; /* page 0 for graphics */ - bb.edx.r.l = x; - bb.edx.r.h = y; - bios(&bb); + bb.intno = 0x10; + bb.eax.r.h = 0x02; + bb.ebx.r.h = page; /* page 0 for graphics */ + bb.edx.r.l = x; + bb.edx.r.h = y; + bios(&bb); } void setCursorType(int type) { - bb.intno = 0x10; - bb.eax.r.h = 0x01; - bb.ecx.rr = type; - bios(&bb); + bb.intno = 0x10; + bb.eax.r.h = 0x01; + bb.ecx.rr = type; + bios(&bb); } void getCursorPositionAndType(int * x, int * y, int * type) { - bb.intno = 0x10; - bb.eax.r.h = 0x03; - bios(&bb); - *x = bb.edx.r.l; - *y = bb.edx.r.h; - *type = bb.ecx.rr; + bb.intno = 0x10; + bb.eax.r.h = 0x03; + bios(&bb); + *x = bb.edx.r.l; + *y = bb.edx.r.h; + *type = bb.ecx.rr; } void scollPage(int x1, int y1, int x2, int y2, int attr, int rows, int dir) { - bb.intno = 0x10; - bb.eax.r.h = (dir > 0) ? 0x06 : 0x07; - bb.eax.r.l = rows; - bb.ebx.r.h = attr; - bb.ecx.r.h = y1; - bb.ecx.r.l = x1; - bb.edx.r.h = y2; - bb.edx.r.l = x2; - bios(&bb); + bb.intno = 0x10; + bb.eax.r.h = (dir > 0) ? 0x06 : 0x07; + bb.eax.r.l = rows; + bb.ebx.r.h = attr; + bb.ecx.r.h = y1; + bb.ecx.r.l = x1; + bb.edx.r.h = y2; + bb.edx.r.l = x2; + bios(&bb); } void clearScreenRows( int y1, int y2 ) { - scollPage( 0, y1, 80 - 1, y2, 0x07, y2 - y1 + 1, 1 ); + scollPage( 0, y1, 80 - 1, y2, 0x07, y2 - y1 + 1, 1 ); } void setActiveDisplayPage( int page ) { - bb.intno = 0x10; - bb.eax.r.h = 5; - bb.eax.r.l = page; - bios(&bb); + bb.intno = 0x10; + bb.eax.r.h = 5; + bb.eax.r.l = page; + bios(&bb); } #if DEBUG int terminateDiskEmulation() { - static char cd_spec[0x13]; + static char cd_spec[0x13]; - bb.intno = 0x13; - bb.eax.r.h = 0x4b; - bb.eax.r.l = 0; // subfunc: terminate emulation - bb.esi.rr = NORMALIZED_OFFSET((unsigned)&cd_spec); - bb.ds = NORMALIZED_SEGMENT((unsigned)&cd_spec); - bios(&bb); - return bb.eax.r.h; + bb.intno = 0x13; + bb.eax.r.h = 0x4b; + bb.eax.r.l = 0; // subfunc: terminate emulation + bb.esi.rr = NORMALIZED_OFFSET((unsigned)&cd_spec); + bb.ds = NORMALIZED_SEGMENT((unsigned)&cd_spec); + bios(&bb); + return bb.eax.r.h; } int readDriveParameters(int drive, struct driveParameters *dp) { - bb.intno = 0x13; - bb.edx.r.l = drive; - bb.eax.r.h = 0x08; - bios(&bb); - if (bb.eax.r.h == 0) { - dp->heads = bb.edx.r.h; - dp->sectors = bb.ecx.r.l & 0x3F; - dp->cylinders = bb.ecx.r.h | ((bb.ecx.r.l & 0xC0) << 2); - dp->totalDrives = bb.edx.r.l; - } else { - bzero(dp, sizeof(*dp)); - } - return bb.eax.r.h; - + bb.intno = 0x13; + bb.edx.r.l = drive; + bb.eax.r.h = 0x08; + bios(&bb); + if (bb.eax.r.h == 0) { + dp->heads = bb.edx.r.h; + dp->sectors = bb.ecx.r.l & 0x3F; + dp->cylinders = bb.ecx.r.h | ((bb.ecx.r.l & 0xC0) << 2); + dp->totalDrives = bb.edx.r.l; + } else { + bzero(dp, sizeof(*dp)); + } + return bb.eax.r.h; } #endif @@ -790,49 +846,46 @@ int APMPresent(void) { - bb.intno = APM_INTNO; - bb.eax.r.h = APM_INTCODE; - bb.eax.r.l = 0x00; - bb.ebx.rr = 0x0000; - bios(&bb); - if ((bb.flags.cf == 0) && - (bb.ebx.r.h == 'P') && - (bb.ebx.r.l == 'M')) { - /* Success */ - bootArgs->apmConfig.major_vers = bb.eax.r.h; - bootArgs->apmConfig.minor_vers = bb.eax.r.l; - bootArgs->apmConfig.flags.data = bb.ecx.rr; - return 1; - } - return 0; + bb.intno = APM_INTNO; + bb.eax.r.h = APM_INTCODE; + bb.eax.r.l = 0x00; + bb.ebx.rr = 0x0000; + bios(&bb); + if ((bb.flags.cf == 0) && (bb.ebx.r.h == 'P') && (bb.ebx.r.l == 'M')) { + /* Success */ + bootArgs->apmConfig.major_vers = bb.eax.r.h; + bootArgs->apmConfig.minor_vers = bb.eax.r.l; + bootArgs->apmConfig.flags.data = bb.ecx.rr; + return 1; + } + return 0; } int APMConnect32(void) { - bb.intno = APM_INTNO; - bb.eax.r.h = APM_INTCODE; - bb.eax.r.l = 0x03; - bb.ebx.rr = 0x0000; - bios(&bb); - if (bb.flags.cf == 0) { - /* Success */ - bootArgs->apmConfig.cs32_base = (bb.eax.rr) << 4; - bootArgs->apmConfig.entry_offset = bb.ebx.rx; - bootArgs->apmConfig.cs16_base = (bb.ecx.rr) << 4; - bootArgs->apmConfig.ds_base = (bb.edx.rr) << 4; - if (bootArgs->apmConfig.major_vers >= 1 && - bootArgs->apmConfig.minor_vers >= 1) { - bootArgs->apmConfig.cs_length = bb.esi.rr; - bootArgs->apmConfig.ds_length = bb.edi.rr; - } else { - bootArgs->apmConfig.cs_length = - bootArgs->apmConfig.ds_length = 64 * 1024; - } - bootArgs->apmConfig.connected = 1; - return 1; - } - return 0; + bb.intno = APM_INTNO; + bb.eax.r.h = APM_INTCODE; + bb.eax.r.l = 0x03; + bb.ebx.rr = 0x0000; + bios(&bb); + if (bb.flags.cf == 0) { + /* Success */ + bootArgs->apmConfig.cs32_base = (bb.eax.rr) << 4; + bootArgs->apmConfig.entry_offset = bb.ebx.rx; + bootArgs->apmConfig.cs16_base = (bb.ecx.rr) << 4; + bootArgs->apmConfig.ds_base = (bb.edx.rr) << 4; + if (bootArgs->apmConfig.major_vers >= 1 && bootArgs->apmConfig.minor_vers >= 1) { + bootArgs->apmConfig.cs_length = bb.esi.rr; + bootArgs->apmConfig.ds_length = bb.edi.rr; + } else { + bootArgs->apmConfig.cs_length = + bootArgs->apmConfig.ds_length = 64 * 1024; + } + bootArgs->apmConfig.connected = 1; + return 1; + } + return 0; } #endif /* APM_SUPPORT */ @@ -840,64 +893,65 @@ #ifdef EISA_SUPPORT bool eisa_present(void) { - static bool checked = false; - static bool isEISA; + static bool checked = false; + static bool isEISA; - if (!checked) { - if (strncmp((char *)0xfffd9, "EISA", 4) == 0) - isEISA = true; - - checked = true; - } - - return (isEISA); + if (!checked) { + if (strncmp((char *)0xfffd9, "EISA", 4) == 0) { + isEISA = true; + } + checked = true; + } + return (isEISA); } int ReadEISASlotInfo(EISA_slot_info_t *ep, int slot) { - union { - struct { - unsigned char char2h :2; - unsigned char char1 :5; - unsigned char char3 :5; - unsigned char char2l :3; - unsigned char d2 :4; - unsigned char d1 :4; - unsigned char d4 :4; - unsigned char d3 :4; - } s; - unsigned char data[4]; - } u; - static char hex[0x10] = "0123456789ABCDEF"; + union + { + struct + { + unsigned char char2h :2; + unsigned char char1 :5; + unsigned char char3 :5; + unsigned char char2l :3; + unsigned char d2 :4; + unsigned char d1 :4; + unsigned char d4 :4; + unsigned char d3 :4; + } s; + unsigned char data[4]; + } u; + static char hex[0x10] = "0123456789ABCDEF"; - - bb.intno = 0x15; - bb.eax.r.h = 0xd8; - bb.eax.r.l = 0x00; - bb.ecx.r.l = slot; - bios(&bb); - if (bb.flags.cf) - return bb.eax.r.h; - ep->u_ID.d = bb.eax.r.l; - ep->configMajor = bb.ebx.r.h; - ep->configMinor = bb.ebx.r.l; - ep->checksum = bb.ecx.rr; - ep->numFunctions = bb.edx.r.h; - ep->u_resources.d = bb.edx.r.l; - u.data[0] = bb.edi.r.l; - u.data[1] = bb.edi.r.h; - u.data[2] = bb.esi.r.l; - u.data[3] = bb.esi.r.h; - ep->id[0] = u.s.char1 + ('A' - 1); - ep->id[1] = (u.s.char2l | (u.s.char2h << 3)) + ('A' - 1); - ep->id[2] = u.s.char3 + ('A' - 1); - ep->id[3] = hex[u.s.d1]; - ep->id[4] = hex[u.s.d2]; - ep->id[5] = hex[u.s.d3]; - ep->id[6] = hex[u.s.d4]; - ep->id[7] = 0; - return 0; + + bb.intno = 0x15; + bb.eax.r.h = 0xd8; + bb.eax.r.l = 0x00; + bb.ecx.r.l = slot; + bios(&bb); + if (bb.flags.cf) + return bb.eax.r.h; + ep->u_ID.d = bb.eax.r.l; + ep->configMajor = bb.ebx.r.h; + ep->configMinor = bb.ebx.r.l; + ep->checksum = bb.ecx.rr; + ep->numFunctions = bb.edx.r.h; + ep->u_resources.d = bb.edx.r.l; + u.data[0] = bb.edi.r.l; + u.data[1] = bb.edi.r.h; + u.data[2] = bb.esi.r.l; + u.data[3] = bb.esi.r.h; + ep->id[0] = u.s.char1 + ('A' - 1); + ep->id[1] = (u.s.char2l | (u.s.char2h << 3)) + ('A' - 1); + ep->id[2] = u.s.char3 + ('A' - 1); + ep->id[3] = hex[u.s.d1]; + ep->id[4] = hex[u.s.d2]; + ep->id[5] = hex[u.s.d3]; + ep->id[6] = hex[u.s.d4]; + ep->id[7] = 0; + return 0; } /* @@ -907,18 +961,19 @@ int ReadEISAFuncInfo(EISA_func_info_t *ep, int slot, int function) { - bb.intno = 0x15; - bb.eax.r.h = 0xd8; - bb.eax.r.l = 0x01; - bb.ecx.r.l = slot; - bb.ecx.r.h = function; - bb.esi.rr = (unsigned int)ep->data; - bios(&bb); - if (bb.eax.r.h == 0) { - ep->slot = slot; - ep->function = function; - } - return bb.eax.r.h; + bb.intno = 0x15; + bb.eax.r.h = 0xd8; + bb.eax.r.l = 0x01; + bb.ecx.r.l = slot; + bb.ecx.r.h = function; + bb.esi.rr = (unsigned int)ep->data; + bios(&bb); + if (bb.eax.r.h == 0) + { + ep->slot = slot; + ep->function = function; + } + return bb.eax.r.h; } #endif /* EISA_SUPPORT */ @@ -927,19 +982,20 @@ int ReadPCIBusInfo(PCI_bus_info_t *pp) { - bb.intno = 0x1a; - bb.eax.r.h = 0xb1; - bb.eax.r.l = 0x01; - bios(&bb); - if ((bb.eax.r.h == 0) && (bb.edx.rx == PCI_SIGNATURE)) { - pp->BIOSPresent = 1; - pp->u_bus.d = bb.eax.r.l; - pp->majorVersion = bb.ebx.r.h; - pp->minorVersion = bb.ebx.r.l; - pp->maxBusNum = bb.ecx.r.l; - return 0; - } - return -1; + bb.intno = 0x1a; + bb.eax.r.h = 0xb1; + bb.eax.r.l = 0x01; + bios(&bb); + if ((bb.eax.r.h == 0) && (bb.edx.rx == PCI_SIGNATURE)) + { + pp->BIOSPresent = 1; + pp->u_bus.d = bb.eax.r.l; + pp->majorVersion = bb.ebx.r.h; + pp->minorVersion = bb.ebx.r.l; + pp->maxBusNum = bb.ecx.r.l; + return 0; + } + return -1; } void sleep(int n) @@ -948,6 +1004,9 @@ while (time18() < endtime); } + +//============================================================================== + void delay(int ms) { bb.intno = 0x15; Index: trunk/i386/libsaio/pci.h =================================================================== --- trunk/i386/libsaio/pci.h (revision 2326) +++ trunk/i386/libsaio/pci.h (revision 2327) @@ -105,7 +105,7 @@ uint32_t signature; // 0x24506E50 '$PnP' uint8_t revision; // 1 uint8_t length; - uint16_t offset; + uint16_t offset; uint8_t checksum; uint32_t identifier; uint16_t manufacturer; Index: trunk/i386/libsaio/saio_types.h =================================================================== --- trunk/i386/libsaio/saio_types.h (revision 2326) +++ trunk/i386/libsaio/saio_types.h (revision 2327) @@ -70,8 +70,8 @@ typedef struct { char plist[IO_CONFIG_DATA_SIZE]; // buffer for plist - TagPtr dictionary; // buffer for xml dictionary - bool canOverride; // flag to mark a dictionary can be overriden + TagPtr dictionary; // buffer for xml dictionary + bool canOverride; // flag to mark a dictionary can be overriden } config_file_t; /* @@ -79,48 +79,50 @@ */ struct boot_drive_info { struct drive_params { - unsigned short buf_size; - unsigned short info_flags; - unsigned long phys_cyls; - unsigned long phys_heads; - unsigned long phys_spt; - unsigned long long phys_sectors; - unsigned short phys_nbps; - unsigned short dpte_offset; - unsigned short dpte_segment; - unsigned short key; - unsigned char path_len; - unsigned char reserved1; - unsigned short reserved2; - unsigned char bus_type[4]; - unsigned char interface_type[8]; - unsigned char interface_path[8]; - unsigned char dev_path[8]; - unsigned char reserved3; - unsigned char checksum; + unsigned short buf_size; + unsigned short info_flags; + unsigned long phys_cyls; + unsigned long phys_heads; + unsigned long phys_spt; + unsigned long long phys_sectors; + unsigned short phys_nbps; + unsigned short dpte_offset; + unsigned short dpte_segment; + unsigned short key; + unsigned char path_len; + unsigned char reserved1; + unsigned short reserved2; + unsigned char bus_type[4]; + unsigned char interface_type[8]; + unsigned char interface_path[8]; + unsigned char dev_path[8]; + unsigned char reserved3; + unsigned char checksum; } params; + struct drive_dpte { - unsigned short io_port_base; - unsigned short control_port_base; - unsigned char head_flags; - unsigned char vendor_info; - unsigned char irq : 4; - unsigned char irq_unused : 4; - unsigned char block_count; - unsigned char dma_channel : 4; - unsigned char dma_type : 4; - unsigned char pio_type : 4; - unsigned char pio_unused : 4; - unsigned short option_flags; - unsigned short reserved; - unsigned char revision; - unsigned char checksum; - } dpte; + unsigned short io_port_base; + unsigned short control_port_base; + unsigned char head_flags; + unsigned char vendor_info; + unsigned char irq : 4; + unsigned char irq_unused : 4; + unsigned char block_count; + unsigned char dma_channel : 4; + unsigned char dma_type : 4; + unsigned char pio_type : 4; + unsigned char pio_unused : 4; + unsigned short option_flags; + unsigned short reserved; + unsigned char revision; + unsigned char checksum; + } dpte; } __attribute__((packed)); typedef struct boot_drive_info boot_drive_info_t; struct driveInfo { boot_drive_info_t di; + int uses_ebios; int no_emulation; int biosdev; @@ -131,7 +133,8 @@ unsigned char data[16]; } FinderInfo; -struct BootVolume; + +struct BootVolume; typedef struct BootVolume * BVRef; typedef struct BootVolume * CICell; @@ -172,33 +175,33 @@ #define BVSTRLEN 32 struct BootVolume { - BVRef next; /* list linkage pointer */ - int biosdev; /* BIOS device number */ - int type; /* device type (floppy, hd, network) */ - unsigned int flags; /* attribute flags */ - BVGetDescription description; /* BVGetDescription function */ - int part_no; /* partition number (1 based) */ - unsigned int part_boff; /* partition block offset */ - unsigned int part_type; /* partition type */ - unsigned int fs_boff; /* 1st block # of next read */ - unsigned int fs_byteoff; /* Byte offset for read within block */ - FSLoadFile fs_loadfile; /* FSLoadFile function */ - FSReadFile fs_readfile; /* FSReadFile function */ - FSGetDirEntry fs_getdirentry; /* FSGetDirEntry function */ - FSGetFileBlock fs_getfileblock; /* FSGetFileBlock function */ - FSGetUUID fs_getuuid; /* FSGetUUID function */ - unsigned int bps; /* bytes per sector for this device */ - char name[BVSTRLEN]; /* (name of partition) */ - char type_name[BVSTRLEN]; /* (type of partition, eg. Apple_HFS) */ - BVFree bv_free; /* BVFree function */ - uint32_t modTime; - char label[BVSTRLEN]; /* partition volume label */ - char altlabel[BVSTRLEN]; /* partition volume label */ - bool filtered; /* newFilteredBVChain() will set to TRUE */ - bool visible; /* will shown in the device list */ - char OSVersion[8]; - bool OSisServer; /* 1 = OS X server , 0 = OS X client */ - bool OSisInstaller; /* 1 = OS X Install partition / recover partition , 0 = OS X Install */ + BVRef next; /* list linkage pointer */ + int biosdev; /* BIOS device number */ + int type; /* device type (floppy, hd, network) */ + unsigned int flags; /* attribute flags */ + BVGetDescription description; /* BVGetDescription function */ + int part_no; /* partition number (1 based) */ + unsigned int part_boff; /* partition block offset */ + unsigned int part_type; /* partition type */ + unsigned int fs_boff; /* 1st block # of next read */ + unsigned int fs_byteoff; /* Byte offset for read within block */ + FSLoadFile fs_loadfile; /* FSLoadFile function */ + FSReadFile fs_readfile; /* FSReadFile function */ + FSGetDirEntry fs_getdirentry; /* FSGetDirEntry function */ + FSGetFileBlock fs_getfileblock; /* FSGetFileBlock function */ + FSGetUUID fs_getuuid; /* FSGetUUID function */ + unsigned int bps; /* bytes per sector for this device */ + char name[BVSTRLEN]; /* (name of partition) */ + char type_name[BVSTRLEN]; /* (type of partition, eg. Apple_HFS) */ + BVFree bv_free; /* BVFree function */ + uint32_t modTime; + char label[BVSTRLEN]; /* partition volume label */ + char altlabel[BVSTRLEN]; /* partition volume label */ + bool filtered; /* newFilteredBVChain() will set to TRUE */ + bool visible; /* will shown in the device list */ + char OSVersion[8]; + bool OSisServer; /* 1 = OS X server , 0 = OS X client */ + bool OSisInstaller; /* 1 = OS X Install partition / recover partition , 0 = OS X Install */ }; Index: trunk/i386/libsaio/msdos.c =================================================================== --- trunk/i386/libsaio/msdos.c (revision 2326) +++ trunk/i386/libsaio/msdos.c (revision 2327) @@ -152,14 +152,20 @@ } buf=malloc (512); + if (!buf) + { + return -1; + } + /* - * Read the boot sector of the filesystem, and then check the - * boot signature. If not a dos boot sector then error out. - * - * NOTE: 2048 is a maximum sector size in current... - */ - Seek(ih, 0); - Read(ih, (long)buf, 512); + * Read the boot sector of the filesystem, and then check the + * boot signature. If not a dos boot sector then error out. + * + * NOTE: 2048 is a maximum sector size in current... + */ + + Seek(ih, 0); + Read(ih, (long)buf, 512); bsp = (union bootsector *)buf; b33 = (struct bpb33 *)bsp->bs33.bsBPB; @@ -167,20 +173,24 @@ b710 = (struct bpb710 *)bsp->bs710.bsBPB; - /* We only work with 512, 1024, and 2048 byte sectors */ - msdosbps = OSSwapLittleToHostInt16(b33->bpbBytesPerSec); - if ((msdosbps < 0x200) || (msdosbps & (msdosbps - 1)) || (msdosbps > 0x800)) + /* We only work with 512, 1024, and 2048 byte sectors */ + msdosbps = OSSwapLittleToHostInt16(b33->bpbBytesPerSec); + if ((msdosbps < 0x200) || (msdosbps & (msdosbps - 1)) || (msdosbps > 0x800)) { free (buf); return -1; } - /* Check to make sure valid sectors per cluster */ - spc = b33->bpbSecPerClust; - if ((spc == 0 ) || (spc & (spc - 1))) + /* Check to make sure valid sectors per cluster */ + spc = b33->bpbSecPerClust; + if ((spc == 0 ) || (spc & (spc - 1))) + { + free (buf); return -1; - - if (OSSwapLittleToHostInt16(b50->bpbRootDirEnts) == 0) { /* It's FAT32 */ + } + if (OSSwapLittleToHostInt16(b50->bpbRootDirEnts) == 0) + { + /* It's FAT32 */ if (memcmp(((struct extboot *)bsp->bs710.bsExt)->exFileSysType, "FAT32 ", 8)) { free (buf); @@ -234,6 +244,10 @@ char *cacheBuffer; cacheBuffer = malloc(MSDOS_CACHE_BLOCKSIZE); + if (!cacheBuffer) + { + return -1; + } CacheRead(ih, cacheBuffer, sectorOffset, MSDOS_CACHE_BLOCKSIZE, true); bcopy(cacheBuffer + relOffset, buf, size); free(cacheBuffer); @@ -294,7 +308,7 @@ readOffset += ((uint64_t)*cluster * (uint64_t)msdosfatbits) / 8; /* Read one sector of the FAT */ - readSector(ih, readOffset, tmpbuf, 4); + if (readSector(ih, readOffset, tmpbuf, 4) != 0) return 0; switch (msdosfatbits) { case 32: @@ -382,14 +396,14 @@ st->vfatchecksum = 0; st->vfatnumber = 0; st->nument++; - if ((!st->root16 &&st->nument * sizeof (struct direntry)>=msdosclustersize) - || (st->root16 &&st->nument * sizeof (struct direntry)>=msdosbps)) + if (((int)(!st->root16 &&st->nument * sizeof (struct direntry))>=msdosclustersize) + || ((int)(st->root16 &&st->nument * sizeof (struct direntry))>=msdosbps)) st->nument = 0; return dirp; } st->nument++; - if ((!st->root16 &&st->nument * sizeof (struct direntry)>=msdosclustersize) - || (st->root16 &&st->nument * sizeof (struct direntry)>=msdosbps)) + if (((int)(!st->root16 &&st->nument * sizeof (struct direntry))>=msdosclustersize) + || ((int)(st->root16 &&st->nument * sizeof (struct direntry))>=msdosbps)) st->nument = 0; } } @@ -649,10 +663,19 @@ st = (struct msdosdirstate *)(long) *dirIndex; if (!st) { - st=malloc (sizeof (*st)); + st=malloc (sizeof (struct msdosdirstate)); + if (!st) + { + return -1; + } if (dirPath[0]) { uint8_t *buf=malloc(msdosclustersize); + if (!buf) + { + free (st); + return -1; + } dirp = getdirpfrompath (ih, dirPath, buf); if (!dirp || !(dirp->deAttributes & ATTR_DIRECTORY)) { @@ -685,6 +708,12 @@ int i; for (i=0;vfatname[i];i++); *name = malloc (256); + if (!*name) + { + free (st->buf); + free (st); + return -1; + } utf_encodestr(vfatname, i, (u_int8_t *)*name, 255, OSLittleEndian ); } else @@ -692,6 +721,12 @@ int i, j, k; uint16_t tmp[13]; *name = malloc (26); + if (!*name) + { + free (st->buf); + free (st); + return -1; + } for (i=7;i>=0;i--) if (dirp->deName[i]!=' ') break; @@ -739,7 +774,7 @@ int toread, wastoread; char *ptr = (char *)base; struct direntry *dirp; - int i; + uint64_t i; char devStr[12]; if (MSDOSInitPartition (ih)<0) @@ -747,6 +782,10 @@ if (filePath[0] == '/') filePath++; buf = malloc(msdosclustersize); + if (!buf) + { + return -1; + } dirp = getdirpfrompath (ih, filePath, buf); if (!dirp || (dirp->deAttributes & ATTR_DIRECTORY)) @@ -759,7 +798,10 @@ cluster |= ((uint32_t)OSReadLittleInt16 ((dirp->deHighClust),0)) <<16; size = (uint32_t)OSReadLittleInt32 ((dirp->deFileSize),0); if (size<=offset) + { + free (buf); return -1; + } nskip=offset/msdosclustersize; for (i=0;isize-offset) toread=size-offset; wastoread=toread; - bcopy (buf+(offset%msdosclustersize),ptr,MIN(msdosclustersize-(offset%msdosclustersize), toread)); + bcopy (buf+(offset%msdosclustersize),ptr,MIN((msdosclustersize-(offset%msdosclustersize)),(unsigned)toread)); ptr+=msdosclustersize-(offset%msdosclustersize); toread-=msdosclustersize-(offset%msdosclustersize); while (toread>0 && msdosreadcluster (ih, (uint8_t *)ptr, MIN(msdosclustersize,toread), &cluster)) @@ -798,6 +840,10 @@ if (filePath[0] == '/') filePath++; buf = malloc(msdosclustersize); + if (!buf) + { + return -1; + } dirp = getdirpfrompath (ih, filePath, buf); if (!dirp || (dirp->deAttributes & ATTR_DIRECTORY)) { @@ -847,21 +893,21 @@ static void fixLabel(uint8_t *label, char *str, long strMaxLen) { - int i, len; - uint16_t labelucs[13]; - //unsigned char labelUTF8[LABEL_LENGTH*3]; + int i, len; + uint16_t labelucs[13]; + //unsigned char labelUTF8[LABEL_LENGTH*3]; - /* Convert leading 0x05 to 0xE5 for multibyte languages like Japanese */ - if (label[0] == 0x05) - label[0] = 0xE5; + /* Convert leading 0x05 to 0xE5 for multibyte languages like Japanese */ + if (label[0] == 0x05) + label[0] = 0xE5; - /* Remove any trailing spaces */ - for (i=LABEL_LENGTH-1; i>=0; --i) { - if (label[i] == ' ') + /* Remove any trailing spaces */ + for (i=LABEL_LENGTH-1; i>=0; --i) { + if (label[i] == ' ') label[i] = 0; - else - break; - } + else + break; + } labelucs[i++]=0; len=i; for (;i>=0;--i) @@ -874,8 +920,8 @@ void MSDOSGetDescription(CICell ih, char *str, long strMaxLen) { - struct direntry *dirp; - uint8_t label[LABEL_LENGTH+1]; + struct direntry *dirp; + uint8_t label[LABEL_LENGTH+1]; uint16_t vfatlabel[WIN_MAXLEN+2*WIN_CHARS]; struct msdosdirstate st; int labelfound = 0; @@ -885,11 +931,15 @@ str[0]=0; return; } - + label[0] = '\0'; initRoot (&st); st.buf = malloc(msdosclustersize); + if (!st.buf) + { + return; + } while ((dirp = getnextdirent (ih, vfatlabel, &st))) if (dirp->deAttributes & ATTR_VOLUME) { strncpy((char *)label, (char *)dirp->deName, LABEL_LENGTH); @@ -908,33 +958,46 @@ else if (labelfound) fixLabel(label, str, strMaxLen); - /* else look in the boot blocks */ - if (!labelfound || str[0] == '\0') { + /* else look in the boot blocks */ + if (!labelfound || str[0] == '\0') + { char *buf = malloc (512); + if (!buf) + { + return; + } union bootsector *bsp = (union bootsector *)buf; Seek(ih, 0); Read(ih, (long)buf, 512); - if (msdosfatbits == 32) { /* It's FAT32 */ - strncpy((char *)label, (char *)((struct extboot *)bsp->bs710.bsExt)->exVolumeLabel, LABEL_LENGTH); - } - else if (msdosfatbits == 16) { - strncpy((char *)label, (char *)((struct extboot *)bsp->bs50.bsExt)->exVolumeLabel, LABEL_LENGTH); - } + if (msdosfatbits == 32) + { + /* It's FAT32 */ + strncpy((char *)label, (char *)((struct extboot *)bsp->bs710.bsExt)->exVolumeLabel, LABEL_LENGTH); + } + else if (msdosfatbits == 16) + { + strncpy((char *)label, (char *)((struct extboot *)bsp->bs50.bsExt)->exVolumeLabel, LABEL_LENGTH); + } free (buf); fixLabel(label, str, strMaxLen); - } + } - return; + return; } long MSDOSGetUUID(CICell ih, char *uuidStr) { char *buf = malloc (512); + if (!buf) + { + return -1; + } union bootsector *bsp = (union bootsector *)buf; - + if (MSDOSInitPartition (ih)<0) { + free (buf); return -1; } bzero (uuidStr, 16); @@ -948,5 +1011,5 @@ } free (buf); return 0; - + } Index: trunk/i386/libsaio/saio_internal.h =================================================================== --- trunk/i386/libsaio/saio_internal.h (revision 2326) +++ trunk/i386/libsaio/saio_internal.h (revision 2327) @@ -218,7 +218,7 @@ unsigned int byteoff, unsigned int byteCount, void * buffer ); -/* Base64-decode.c */ +// Base64-decode.c char *BASE64Decode(const char* src, int in_len, int* out_len); #endif /* !__LIBSAIO_SAIO_INTERNAL_H */ Index: trunk/i386/boot2/picopng.c =================================================================== --- trunk/i386/boot2/picopng.c (revision 2326) +++ trunk/i386/boot2/picopng.c (revision 2327) @@ -1104,15 +1104,15 @@ } insize = (uint32_t) statbuf.st_size; inbuf = malloc(insize); - if (!inbuf) { - perror("malloc"); - fclose(infp); - return 1; - } - if (fread(inbuf, 1, insize, infp) != insize) { + if (!inbuf) { + perror("malloc"); + fclose(infp); + return 1; + } + if (fread(inbuf, 1, insize, infp) != insize) { perror("fread"); - free(inbuf); - fclose(infp); + free(inbuf); + fclose(infp); return 1; } fclose(infp); Index: trunk/i386/boot2/graphics.c =================================================================== --- trunk/i386/boot2/graphics.c (revision 2326) +++ trunk/i386/boot2/graphics.c (revision 2327) @@ -84,9 +84,9 @@ return 0; buff = malloc(sizeof(char) * 256); - if (!buff) - return 0; - + if (!buff) { + return 0; + } small = (vbeInfo.TotalMemory < 16); snprintf(buff, 256, @@ -106,107 +106,109 @@ void printVBEModeInfo() { - VBEInfoBlock vbeInfo; - unsigned short * modePtr; - VBEModeInfoBlock modeInfo; - int err; - int line; - char* vbeInfoString = NULL; + VBEInfoBlock vbeInfo; + unsigned short * modePtr; + VBEModeInfoBlock modeInfo; + int err; + int line; + char* vbeInfoString = NULL; bzero( &vbeInfo, sizeof(vbeInfo) ); - strcpy( (char*)&vbeInfo, "VBE2" ); - err = getVBEInfo( &vbeInfo ); - if ( err != errSuccess ) - return; + strcpy( (char*)&vbeInfo, "VBE2" ); + err = getVBEInfo( &vbeInfo ); + if ( err != errSuccess ) { + return; + } - line = 0; + line = 0; - // Activate and clear page 1 - setActiveDisplayPage(1); - clearScreenRows(0, 24); - setCursorPosition( 0, 0, 1 ); + // Activate and clear page 1 + setActiveDisplayPage(1); + clearScreenRows(0, 24); + setCursorPosition( 0, 0, 1 ); - vbeInfoString = getVBEInfoString(); - if (!vbeInfoString) { - printf("Error: getVBEInfoString failed\n"); - return; - } - printf("%s", vbeInfoString); - free(vbeInfoString); - vbeInfoString = NULL; + vbeInfoString = getVBEInfoString(); + if (!vbeInfoString) { + printf("Error: getVBEInfoString failed\n"); + return; + } + printf("%s", vbeInfoString); + free(vbeInfoString); + vbeInfoString = NULL; printf("Video modes supported:\n", VBEDecodeFP(const char *, vbeInfo.OEMStringPtr)); - // Loop through the mode list, and find the matching mode. + // Loop through the mode list, and find the matching mode. - for ( modePtr = VBEDecodeFP( unsigned short *, vbeInfo.VideoModePtr ); + for ( modePtr = VBEDecodeFP( unsigned short *, vbeInfo.VideoModePtr ); *modePtr != modeEndOfList; modePtr++ ) - { - // Get mode information. + { + // Get mode information. - bzero( &modeInfo, sizeof(modeInfo) ); - err = getVBEModeInfo( *modePtr, &modeInfo ); - if ( err != errSuccess ) - { - continue; - } + bzero( &modeInfo, sizeof(modeInfo) ); + err = getVBEModeInfo( *modePtr, &modeInfo ); + if ( err != errSuccess ) + { + continue; + } - printf("Mode %x: %dx%dx%d mm:%d attr:%x\n", - *modePtr, modeInfo.XResolution, modeInfo.YResolution, - modeInfo.BitsPerPixel, modeInfo.MemoryModel, - modeInfo.ModeAttributes); + printf("Mode %x: %dx%dx%d mm:%d attr:%x\n", + *modePtr, modeInfo.XResolution, modeInfo.YResolution, + modeInfo.BitsPerPixel, modeInfo.MemoryModel, + modeInfo.ModeAttributes); - if (line++ >= 20) { - pause(); - line = 0; - clearScreenRows(0, 24); - setCursorPosition( 0, 0, 1 ); - } - } - if (line != 0) { - pause(); - } - setActiveDisplayPage(0); + if (line++ >= 20) { + pause(); + line = 0; + clearScreenRows(0, 24); + setCursorPosition( 0, 0, 1 ); + } + } + if (line != 0) { + pause(); + } + setActiveDisplayPage(0); } char *getVBEModeInfoString() { VBEInfoBlock vbeInfo; - unsigned short * modePtr; - VBEModeInfoBlock modeInfo; - int err; + unsigned short * modePtr; + VBEModeInfoBlock modeInfo; + int err; bzero( &vbeInfo, sizeof(vbeInfo) ); - strcpy( (char*)&vbeInfo, "VBE2" ); - err = getVBEInfo( &vbeInfo ); - if ( err != errSuccess ) - return 0; - + strcpy( (char*)&vbeInfo, "VBE2" ); + err = getVBEInfo( &vbeInfo ); + if ( err != errSuccess ) { + return 0; + } char *buff=malloc(sizeof(char)*3072); - if(!buff) return 0; - int bufflen = 0; + if(!buff) { + return 0; + } + int bufflen = 0; + // Loop through the mode list, and find the matching mode. - for ( modePtr = VBEDecodeFP( unsigned short *, vbeInfo.VideoModePtr ); - (*modePtr != modeEndOfList) && (bufflen < 3072); /* prevent buffer overrun */ - modePtr++ ) - { - // Get mode information. + for ( modePtr = VBEDecodeFP( unsigned short *, vbeInfo.VideoModePtr ); + (*modePtr != modeEndOfList) && (bufflen < 3072); /* prevent buffer overrun */ + modePtr++ ) + { + // Get mode information. - bzero( &modeInfo, sizeof(modeInfo) ); - err = getVBEModeInfo( *modePtr, &modeInfo ); - if ( err != errSuccess ) - { - continue; - } + bzero( &modeInfo, sizeof(modeInfo) ); + err = getVBEModeInfo( *modePtr, &modeInfo ); + if ( err != errSuccess ) { + continue; + } - bufflen += - snprintf(buff+bufflen, 3072-bufflen, "Mode %x: %dx%dx%d mm:%d attr:%x\n", - *modePtr, modeInfo.XResolution, modeInfo.YResolution, - modeInfo.BitsPerPixel, modeInfo.MemoryModel, - modeInfo.ModeAttributes); - - } + bufflen += + snprintf(buff+bufflen, 3072-bufflen, "Mode %x: %dx%dx%d mm:%d attr:%x\n", + *modePtr, modeInfo.XResolution, modeInfo.YResolution, + modeInfo.BitsPerPixel, modeInfo.MemoryModel, + modeInfo.ModeAttributes); + } return buff; } Index: trunk/i386/boot2/drivers.c =================================================================== --- trunk/i386/boot2/drivers.c (revision 2326) +++ trunk/i386/boot2/drivers.c (revision 2327) @@ -43,24 +43,24 @@ //extern char gMacOSVersion[8]; struct Module { - struct Module *nextModule; - long willLoad; - TagPtr dict; - char *plistAddr; - long plistLength; - char *executablePath; - char *bundlePath; - long bundlePathLength; + struct Module *nextModule; + long willLoad; + TagPtr dict; + char *plistAddr; + long plistLength; + char *executablePath; + char *bundlePath; + long bundlePathLength; }; typedef struct Module Module, *ModulePtr; struct DriverInfo { - char *plistAddr; - long plistLength; - void *executableAddr; - long executableLength; - void *bundlePathAddr; - long bundlePathLength; + char *plistAddr; + long plistLength; + void *executableAddr; + long executableLength; + void *bundlePathAddr; + long bundlePathLength; }; typedef struct DriverInfo DriverInfo, *DriverInfoPtr; @@ -80,8 +80,8 @@ typedef struct DriversPackage DriversPackage; enum { - kCFBundleType2, - kCFBundleType3 + kCFBundleType2, + kCFBundleType3 }; long (*LoadExtraDrivers_p)(FileLoadDrivers_t FileLoadDrivers_p); @@ -114,24 +114,24 @@ /*static*/ unsigned long Adler32( unsigned char * buffer, long length ) { - long cnt; - unsigned long result, lowHalf, highHalf; - - lowHalf = 1; - highHalf = 0; - - for ( cnt = 0; cnt < length; cnt++ ) - { - if ((cnt % 5000) == 0) - { - lowHalf %= 65521L; - highHalf %= 65521L; - } - - lowHalf += buffer[cnt]; - highHalf += lowHalf; - } + long cnt; + unsigned long result, lowHalf, highHalf; + lowHalf = 1; + highHalf = 0; + + for (cnt = 0; cnt < length; cnt++) + { + if ((cnt % 5000) == 0) + { + lowHalf %= 65521L; + highHalf %= 65521L; + } + + lowHalf += buffer[cnt]; + highHalf += lowHalf; + } + lowHalf %= 65521L; highHalf %= 65521L; @@ -147,16 +147,17 @@ static long InitDriverSupport( void ) { - gExtensionsSpec = malloc( 4096 ); - gDriverSpec = malloc( 4096 ); - gFileSpec = malloc( 4096 ); - gTempSpec = malloc( 4096 ); - gFileName = malloc( 4096 ); + gExtensionsSpec = malloc( 4096 ); + gDriverSpec = malloc( 4096 ); + gFileSpec = malloc( 4096 ); + gTempSpec = malloc( 4096 ); + gFileName = malloc( 4096 ); - if ( !gExtensionsSpec || !gDriverSpec || !gFileSpec || !gTempSpec || !gFileName ) - stop("InitDriverSupport error"); + if ( !gExtensionsSpec || !gDriverSpec || !gFileSpec || !gTempSpec || !gFileName ) { + stop("InitDriverSupport error"); + } - return 0; + return 0; } //========================================================================== @@ -164,109 +165,98 @@ long LoadDrivers( char * dirSpec ) { - char dirSpecExtra[1024]; + char dirSpecExtra[1024]; - if ( InitDriverSupport() != 0 ) - return 0; + if ( InitDriverSupport() != 0 ) { + return 0; + } - // Load extra drivers if a hook has been installed. - if (LoadExtraDrivers_p != NULL) - { - (*LoadExtraDrivers_p)(&FileLoadDrivers); - } + // Load extra drivers if a hook has been installed. + if (LoadExtraDrivers_p != NULL) + { + (*LoadExtraDrivers_p)(&FileLoadDrivers); + } - if ( gBootFileType == kNetworkDeviceType ) - { - if (NetLoadDrivers(dirSpec) != 0) { - error("Could not load drivers from the network\n"); - return -1; - } - } - else if ( gBootFileType == kBlockDeviceType ) + if ( gBootFileType == kNetworkDeviceType ) { - // First try to load Extra extensions from the ramdisk if isn't aliased as bt(0,0). - if (gRAMDiskVolume && !gRAMDiskBTAliased) - { - strcpy(dirSpecExtra, "rd(0,0)/Extra/"); - FileLoadDrivers(dirSpecExtra, 0); - } + if (NetLoadDrivers(dirSpec) != 0) + { + error("Could not load drivers from the network\n"); + return -1; + } + } + else if ( gBootFileType == kBlockDeviceType ) + { + // First try to load Extra extensions from the ramdisk if isn't aliased as bt(0,0). + if (gRAMDiskVolume && !gRAMDiskBTAliased) + { + strcpy(dirSpecExtra, "rd(0,0)/Extra/"); + FileLoadDrivers(dirSpecExtra, 0); + } - // Next try to load Extra extensions from the selected root partition. - strcpy(dirSpecExtra, "/Extra/"); - if (FileLoadDrivers(dirSpecExtra, 0) != 0) - { - // If failed, then try to load Extra extensions from the boot partition - // in case we have a separate booter partition or a bt(0,0) aliased ramdisk. - if ( !(gBIOSBootVolume->biosdev == gBootVolume->biosdev && gBIOSBootVolume->part_no == gBootVolume->part_no) - || (gRAMDiskVolume && gRAMDiskBTAliased) ) - { - // Next try a specfic OS version folder ie 10.5 - sprintf(dirSpecExtra, "bt(0,0)/Extra/%s/", &gMacOSVersion); - if (FileLoadDrivers(dirSpecExtra, 0) != 0) - { - // Next we'll try the base - strcpy(dirSpecExtra, "bt(0,0)/Extra/"); - FileLoadDrivers(dirSpecExtra, 0); - } - } - } - if(!gHaveKernelCache) - { - // Don't load main driver (from /System/Library/Extentions) if gHaveKernelCache is set. - // since these drivers will already be in the kernel cache. - // NOTE: when gHaveKernelCache, xnu cannot (by default) load *any* extra kexts from the bootloader. - // The /Extra code is not disabled in this case due to a kernel patch that allows for this to happen. - - // Also try to load Extensions from boot helper partitions. - if (gBootVolume->flags & kBVFlagBooter) - { - strcpy(dirSpecExtra, "/com.apple.boot.P/System/Library/"); - if (FileLoadDrivers(dirSpecExtra, 0) != 0) - { - strcpy(dirSpecExtra, "/com.apple.boot.R/System/Library/"); - if (FileLoadDrivers(dirSpecExtra, 0) != 0) - { - strcpy(dirSpecExtra, "/com.apple.boot.S/System/Library/"); - FileLoadDrivers(dirSpecExtra, 0); - } - } - } - - if (gMKextName[0] != '\0') - { - verbose("LoadDrivers: Loading from [%s]\n", gMKextName); - if ( LoadDriverMKext(gMKextName) != 0 ) - { - error("Could not load %s\n", gMKextName); - return -1; - } - } - else - { + // Next try to load Extra extensions from the selected root partition. + strcpy(dirSpecExtra, "/Extra/"); + if (FileLoadDrivers(dirSpecExtra, 0) != 0) { + // If failed, then try to load Extra extensions from the boot partition + // in case we have a separate booter partition or a bt(0,0) aliased ramdisk. + if ( !(gBIOSBootVolume->biosdev == gBootVolume->biosdev && gBIOSBootVolume->part_no == gBootVolume->part_no) + || (gRAMDiskVolume && gRAMDiskBTAliased) ) { + // Next try a specfic OS version folder ie 10.5 + sprintf(dirSpecExtra, "bt(0,0)/Extra/%s/", &gMacOSVersion); + if (FileLoadDrivers(dirSpecExtra, 0) != 0) { + // Next we'll try the base + strcpy(dirSpecExtra, "bt(0,0)/Extra/"); + FileLoadDrivers(dirSpecExtra, 0); + } + } + } + if(!gHaveKernelCache) { + // Don't load main driver (from /System/Library/Extentions) if gHaveKernelCache is set. + // since these drivers will already be in the kernel cache. + // NOTE: when gHaveKernelCache, xnu cannot (by default) load *any* extra kexts from the bootloader. + // The /Extra code is not disabled in this case due to a kernel patch that allows for this to happen. + + // Also try to load Extensions from boot helper partitions. + if (gBootVolume->flags & kBVFlagBooter) { + strcpy(dirSpecExtra, "/com.apple.boot.P/System/Library/"); + if (FileLoadDrivers(dirSpecExtra, 0) != 0) { + strcpy(dirSpecExtra, "/com.apple.boot.R/System/Library/"); + if (FileLoadDrivers(dirSpecExtra, 0) != 0) { + strcpy(dirSpecExtra, "/com.apple.boot.S/System/Library/"); + FileLoadDrivers(dirSpecExtra, 0); + } + } + } + + if (gMKextName[0] != '\0') { + verbose("LoadDrivers: Loading from [%s]\n", gMKextName); + if ( LoadDriverMKext(gMKextName) != 0 ) { + error("Could not load %s\n", gMKextName); + return -1; + } + } else { if (gMacOSVersion[3] == '9') { - strlcpy(gExtensionsSpec, dirSpec, 4087); /* 4096 - sizeof("Library/") */ + strlcpy(gExtensionsSpec, dirSpec, 4087); /* 4096 - sizeof("Library/") */ strcat(gExtensionsSpec, "Library/"); FileLoadDrivers(gExtensionsSpec, 0); } - strlcpy(gExtensionsSpec, dirSpec, 4080); /* 4096 - sizeof("System/Library/") */ - strcat(gExtensionsSpec, "System/Library/"); - FileLoadDrivers(gExtensionsSpec, 0); - } + strlcpy(gExtensionsSpec, dirSpec, 4080); /* 4096 - sizeof("System/Library/") */ + strcat(gExtensionsSpec, "System/Library/"); + FileLoadDrivers(gExtensionsSpec, 0); + } - } - } - else - { - return 0; - } + } + } else { + return 0; + } - MatchPersonalities(); + MatchPersonalities(); - MatchLibraries(); + MatchLibraries(); - LoadMatchedModules(); + LoadMatchedModules(); - return 0; + return 0; } //========================================================================== @@ -289,11 +279,12 @@ || ((flags & kFileTypeMask) != kFileTypeDirectory) || (((gBootMode & kBootModeSafe) == 0) && (time == (time2 + 1)))) { - snprintf(gDriverSpec, sizeof(altDirSpec) + 18, "%sExtensions.mkext", altDirSpec); + snprintf(gDriverSpec, sizeof(altDirSpec) + 18, "%sExtensions.mkext", altDirSpec); verbose("LoadDrivers: Loading from [%s]\n", gDriverSpec); - if (LoadDriverMKext(gDriverSpec) == 0) + if (LoadDriverMKext(gDriverSpec) == 0) { return 0; + } } } return -1; @@ -305,59 +296,73 @@ long FileLoadDrivers( char * dirSpec, long plugin ) { - long ret, length, flags, time, bundleType; - long long index; - long result = -1; - const char * name; - - if ( !plugin ) - { - // First try 10.6's path for loading Extensions.mkext. - if (FileLoadMKext(dirSpec, "Caches/com.apple.kext.caches/Startup/") == 0) - return 0; + long ret, length, flags, time, bundleType; + long long index; + long result = -1; + const char * name; - // Next try the legacy path. - else if (FileLoadMKext(dirSpec, "") == 0) - return 0; + if ( !plugin ) + { + // First try 10.6's path for loading Extensions.mkext. + if (FileLoadMKext(dirSpec, "Caches/com.apple.kext.caches/Startup/") == 0) { + return 0; + } - strcat(dirSpec, "Extensions"); - } + // Next try the legacy path. + else if (FileLoadMKext(dirSpec, "") == 0) { + return 0; + } - index = 0; - while (1) { - ret = GetDirEntry(dirSpec, &index, &name, &flags, &time); - if (ret == -1) break; + strcat(dirSpec, "Extensions"); + } - // Make sure this is a directory. - if ((flags & kFileTypeMask) != kFileTypeDirectory) continue; - - // Make sure this is a kext. - length = strlen(name); - if (strcmp(name + length - 5, ".kext")) continue; + index = 0; + while (1) + { + ret = GetDirEntry(dirSpec, &index, &name, &flags, &time); + if (ret == -1) { + break; + } - // Save the file name. - strlcpy(gFileName, name, 4096); - - // Determine the bundle type. - snprintf(gTempSpec, 4096, "%s/%s", dirSpec, gFileName); - ret = GetFileInfo(gTempSpec, "Contents", &flags, &time); - if (ret == 0) bundleType = kCFBundleType2; - else bundleType = kCFBundleType3; + // Make sure this is a directory. + if ((flags & kFileTypeMask) != kFileTypeDirectory) { + continue; + } - if (!plugin) - snprintf(gDriverSpec, 4096, "%s/%s/%sPlugIns", dirSpec, gFileName, - (bundleType == kCFBundleType2) ? "Contents/" : ""); + // Make sure this is a kext. + length = strlen(name); + if (strcmp(name + length - 5, ".kext")) { + continue; + } - ret = LoadDriverPList(dirSpec, gFileName, bundleType); + // Save the file name. + strlcpy(gFileName, name, 4096); - if (result != 0) - result = ret; + // Determine the bundle type. + snprintf(gTempSpec, 4096, "%s/%s", dirSpec, gFileName); + ret = GetFileInfo(gTempSpec, "Contents", &flags, &time); + if (ret == 0) { + bundleType = kCFBundleType2; + } else { + bundleType = kCFBundleType3; + } - if (!plugin) - FileLoadDrivers(gDriverSpec, 1); - } + if (!plugin) { + snprintf(gDriverSpec, 4096, "%s/%s/%sPlugIns", dirSpec, gFileName, (bundleType == kCFBundleType2) ? "Contents/" : ""); + } - return result; + ret = LoadDriverPList(dirSpec, gFileName, bundleType); + + if (result != 0) { + result = ret; + } + + if (!plugin) { + FileLoadDrivers(gDriverSpec, 1); + } + } + + return result; } @@ -367,32 +372,36 @@ long NetLoadDrivers( char * dirSpec ) { - long tries; + long tries; #if NODEF - long cnt; + long cnt; - // Get the name of the kernel - cnt = strlen(gBootFile); - while (cnt--) { - if ((gBootFile[cnt] == '\\') || (gBootFile[cnt] == ',')) { - cnt++; - break; - } - } + // Get the name of the kernel + cnt = strlen(gBootFile); + while (cnt--) { + if ((gBootFile[cnt] == '\\') || (gBootFile[cnt] == ',')) { + cnt++; + break; + } + } #endif - // INTEL modification - snprintf(gDriverSpec, 4096, "%s%s.mkext", dirSpec, bootInfo->bootFile); + // INTEL modification + snprintf(gDriverSpec, 4096, "%s%s.mkext", dirSpec, bootInfo->bootFile); - verbose("NetLoadDrivers: Loading from [%s]\n", gDriverSpec); + verbose("NetLoadDrivers: Loading from [%s]\n", gDriverSpec); - tries = 3; - while (tries--) - { - if (LoadDriverMKext(gDriverSpec) == 0) break; - } - if (tries == -1) return -1; + tries = 3; + while (tries--) + { + if (LoadDriverMKext(gDriverSpec) == 0) { + break; + } + } + if (tries == -1) { + return -1; + } return 0; } @@ -403,44 +412,45 @@ long LoadDriverMKext( char * fileSpec ) { - unsigned long driversAddr, driversLength; - long length; - char segName[32]; - DriversPackage * package; + unsigned long driversAddr, driversLength; + long length; + char segName[32]; + DriversPackage * package; #define GetPackageElement(e) OSSwapBigToHostInt32(package->e) - // Load the MKext. - length = LoadThinFatFile(fileSpec, (void **)&package); - if (length < sizeof (DriversPackage)) return -1; + // Load the MKext. + length = LoadThinFatFile(fileSpec, (void **)&package); + if (length < sizeof (DriversPackage)) { + return -1; + } // call hook to notify modules that the mkext has been loaded execute_hook("LoadDriverMKext", (void*)fileSpec, (void*)package, (void*) &length, NULL); - // Verify the MKext. - if (( GetPackageElement(signature1) != kDriverPackageSignature1) || - ( GetPackageElement(signature2) != kDriverPackageSignature2) || - ( GetPackageElement(length) > kLoadSize ) || - ( GetPackageElement(adler32) != - Adler32((unsigned char *)&package->version, GetPackageElement(length) - 0x10) ) ) - { - return -1; - } + // Verify the MKext. + if (( GetPackageElement(signature1) != kDriverPackageSignature1) || + ( GetPackageElement(signature2) != kDriverPackageSignature2) || + ( GetPackageElement(length) > kLoadSize ) || + ( GetPackageElement(adler32) != + Adler32((unsigned char *)&package->version, GetPackageElement(length) - 0x10) ) ) + { + return -1; + } - // Make space for the MKext. - driversLength = GetPackageElement(length); - driversAddr = AllocateKernelMemory(driversLength); + // Make space for the MKext. + driversLength = GetPackageElement(length); + driversAddr = AllocateKernelMemory(driversLength); - // Copy the MKext. - memcpy((void *)driversAddr, (void *)package, driversLength); + // Copy the MKext. + memcpy((void *)driversAddr, (void *)package, driversLength); - // Add the MKext to the memory map. - snprintf(segName, sizeof(segName), "DriversPackage-%lx", driversAddr); - AllocateMemoryRange(segName, driversAddr, driversLength, - kBootDriverTypeMKEXT); + // Add the MKext to the memory map. + snprintf(segName, sizeof(segName), "DriversPackage-%lx", driversAddr); + AllocateMemoryRange(segName, driversAddr, driversLength, kBootDriverTypeMKEXT); - return 0; + return 0; } //========================================================================== @@ -449,110 +459,131 @@ long LoadDriverPList( char * dirSpec, char * name, long bundleType ) { - long length, executablePathLength, bundlePathLength; - ModulePtr module; - TagPtr personalities; - char * buffer = 0; - char * tmpExecutablePath = 0; - char * tmpBundlePath = 0; - long ret = -1; + long length, executablePathLength, bundlePathLength; + ModulePtr module; + TagPtr personalities; + char * buffer = 0; + char * tmpExecutablePath = 0; + char * tmpBundlePath = 0; + long ret = -1; - do { - // Save the driver path. + do{ + // Save the driver path. - if(name) - snprintf(gFileSpec, 4096, "%s/%s/%s", dirSpec, name, - (bundleType == kCFBundleType2) ? "Contents/MacOS/" : ""); - else - snprintf(gFileSpec, 4096, "%s/%s", dirSpec, - (bundleType == kCFBundleType2) ? "Contents/MacOS/" : ""); - executablePathLength = strlen(gFileSpec) + 1; + if(name) { + snprintf(gFileSpec, 4096, "%s/%s/%s", dirSpec, name, (bundleType == kCFBundleType2) ? "Contents/MacOS/" : ""); + } else { + snprintf(gFileSpec, 4096, "%s/%s", dirSpec, (bundleType == kCFBundleType2) ? "Contents/MacOS/" : ""); + } + executablePathLength = strlen(gFileSpec) + 1; - tmpExecutablePath = malloc(executablePathLength); - if (tmpExecutablePath == 0) break; - strcpy(tmpExecutablePath, gFileSpec); - - if(name) - snprintf(gFileSpec, 4096, "%s/%s", dirSpec, name); - else - snprintf(gFileSpec, 4096, "%s", dirSpec); - bundlePathLength = strlen(gFileSpec) + 1; + tmpExecutablePath = malloc(executablePathLength); + if (tmpExecutablePath == 0) { + break; + } + strcpy(tmpExecutablePath, gFileSpec); - tmpBundlePath = malloc(bundlePathLength); - if (tmpBundlePath == 0) break; + if(name) { + snprintf(gFileSpec, 4096, "%s/%s", dirSpec, name); + } else { + snprintf(gFileSpec, 4096, "%s", dirSpec); + } + bundlePathLength = strlen(gFileSpec) + 1; - strcpy(tmpBundlePath, gFileSpec); + tmpBundlePath = malloc(bundlePathLength); + if (tmpBundlePath == 0) { + break; + } - // Construct the file spec to the plist, then load it. + strcpy(tmpBundlePath, gFileSpec); - if(name) - snprintf(gFileSpec, 4096, "%s/%s/%sInfo.plist", dirSpec, name, - (bundleType == kCFBundleType2) ? "Contents/" : ""); - else - snprintf(gFileSpec, 4096, "%s/%sInfo.plist", dirSpec, - (bundleType == kCFBundleType2) ? "Contents/" : ""); + // Construct the file spec to the plist, then load it. - length = LoadFile(gFileSpec); - if (length == -1) break; - length = length + 1; - buffer = malloc(length); - if (buffer == 0) break; - strlcpy(buffer, (char *)kLoadAddr, length); + if(name) { + snprintf(gFileSpec, 4096, "%s/%s/%sInfo.plist", dirSpec, name, (bundleType == kCFBundleType2) ? "Contents/" : ""); + } else { + snprintf(gFileSpec, 4096, "%s/%sInfo.plist", dirSpec, (bundleType == kCFBundleType2) ? "Contents/" : ""); + } - // Parse the plist. + length = LoadFile(gFileSpec); + if (length == -1) { + break; + } + length = length + 1; + buffer = malloc(length); + if (buffer == 0) { + break; + } + strlcpy(buffer, (char *)kLoadAddr, length); - ret = ParseXML(buffer, &module, &personalities); - if (ret != 0) { break; } - // Allocate memory for the driver path and the plist. + // Parse the plist. - module->executablePath = tmpExecutablePath; - module->bundlePath = tmpBundlePath; - module->bundlePathLength = bundlePathLength; - module->plistAddr = malloc(length); - - if ((module->executablePath == 0) || (module->bundlePath == 0) || (module->plistAddr == 0)) - break; - // Save the driver path in the module. - //strcpy(module->driverPath, tmpDriverPath); - tmpExecutablePath = 0; - tmpBundlePath = 0; + ret = ParseXML(buffer, &module, &personalities); - // Add the plist to the module. + if (ret != 0) { + break; + } + // Allocate memory for the driver path and the plist. - strlcpy(module->plistAddr, (char *)kLoadAddr, length); - module->plistLength = length; - - // Add the module to the end of the module list. + module->executablePath = tmpExecutablePath; + module->bundlePath = tmpBundlePath; + module->bundlePathLength = bundlePathLength; + module->plistAddr = malloc(length); + + if ((module->executablePath == 0) || (module->bundlePath == 0) || (module->plistAddr == 0)) { + break; + } + + // Save the driver path in the module. + //strcpy(module->driverPath, tmpDriverPath); + tmpExecutablePath = 0; + tmpBundlePath = 0; + + // Add the plist to the module. + + strlcpy(module->plistAddr, (char *)kLoadAddr, length); + module->plistLength = length; + + // Add the module to the end of the module list. - if (gModuleHead == 0) - gModuleHead = module; - else - gModuleTail->nextModule = module; - gModuleTail = module; - - // Add the persionalities to the personality list. - - if (personalities) personalities = personalities->tag; - while (personalities != 0) - { - if (gPersonalityHead == 0) - gPersonalityHead = personalities->tag; - else - gPersonalityTail->tagNext = personalities->tag; - - gPersonalityTail = personalities->tag; - personalities = personalities->tagNext; - } + if (gModuleHead == 0) { + gModuleHead = module; + } else { + gModuleTail->nextModule = module; + } + gModuleTail = module; + + // Add the persionalities to the personality list. + + if (personalities) { + personalities = personalities->tag; + } + while (personalities != 0) + { + if (gPersonalityHead == 0) { + gPersonalityHead = personalities->tag; + } else { + gPersonalityTail->tagNext = personalities->tag; + } + + gPersonalityTail = personalities->tag; + personalities = personalities->tagNext; + } - ret = 0; - } - while (0); + ret = 0; + } + while (0); - if ( buffer ) free( buffer ); - if ( tmpExecutablePath ) free( tmpExecutablePath ); - if ( tmpBundlePath ) free( tmpBundlePath ); - - return ret; + if ( buffer ) { + free( buffer ); + } + if ( tmpExecutablePath ) { + free( tmpExecutablePath ); + } + if ( tmpBundlePath ) { + free( tmpBundlePath ); + } + return ret; } @@ -652,8 +683,8 @@ static long MatchPersonalities( void ) { - /* IONameMatch support not implemented */ - return 0; + /* IONameMatch support not implemented */ + return 0; } //========================================================================== @@ -662,47 +693,54 @@ static long MatchLibraries( void ) { - TagPtr prop, prop2; - ModulePtr module, module2; - long done; + TagPtr prop, prop2; + ModulePtr module, module2; + long done; - do { - done = 1; - module = gModuleHead; + do { + done = 1; + module = gModuleHead; - while (module != 0) - { - if (module->willLoad == 1) - { - prop = XMLGetProperty(module->dict, kPropOSBundleLibraries); - if (prop != 0) - { - prop = prop->tag; - while (prop != 0) - { - module2 = gModuleHead; - while (module2 != 0) - { - prop2 = XMLGetProperty(module2->dict, kPropCFBundleIdentifier); - if ((prop2 != 0) && (!strcmp(prop->string, prop2->string))) - { - if (module2->willLoad == 0) module2->willLoad = 1; - break; - } - module2 = module2->nextModule; - } - prop = prop->tagNext; - } - } - module->willLoad = 2; - done = 0; - } - module = module->nextModule; - } - } - while (!done); + while (module != 0) + { + if (module->willLoad == 1) + { + prop = XMLGetProperty(module->dict, kPropOSBundleLibraries); - return 0; + if (prop != 0) + { + prop = prop->tag; + + while (prop != 0) + { + module2 = gModuleHead; + + while (module2 != 0) + { + prop2 = XMLGetProperty(module2->dict, kPropCFBundleIdentifier); + + if ((prop2 != 0) && (!strcmp(prop->string, prop2->string))) + { + if (module2->willLoad == 0) + { + module2->willLoad = 1; + } + break; + } + module2 = module2->nextModule; + } + prop = prop->tagNext; + } + } + module->willLoad = 2; + done = 0; + } + module = module->nextModule; + } + } + while (!done); + + return 0; } @@ -713,19 +751,23 @@ static ModulePtr FindModule( char * name ) { - ModulePtr module; - TagPtr prop; + ModulePtr module; + TagPtr prop; + + module = gModuleHead; + + while (module != 0) + { + prop = GetProperty(module->dict, kPropCFBundleIdentifier); + + if ((prop != 0) && !strcmp(name, prop->string)) { + break; + } + + module = module->nextModule; + } - module = gModuleHead; - - while (module != 0) - { - prop = GetProperty(module->dict, kPropCFBundleIdentifier); - if ((prop != 0) && !strcmp(name, prop->string)) break; - module = module->nextModule; - } - - return module; + return module; } #endif /* NOTDEF */ @@ -739,23 +781,30 @@ TagPtr moduleDict, required; ModulePtr tmpModule; - pos = 0; + pos = 0; - while (1) - { - length = XMLParseNextTag(buffer + pos, &moduleDict); - if (length == -1) break; - - pos += length; - - if (moduleDict == 0) continue; - if (moduleDict->type == kTagTypeDict) break; - - XMLFreeTag(moduleDict); - } - - if (length == -1) return -1; + while (1) + { + length = XMLParseNextTag(buffer + pos, &moduleDict); + if (length == -1) { + break; + } + pos += length; + + if (moduleDict == 0) { + continue; + } + if (moduleDict->type == kTagTypeDict) { + break; + } + XMLFreeTag(moduleDict); + } + + if (length == -1) { + return -1; + } + required = XMLGetProperty(moduleDict, kPropOSBundleRequired); if ( (required == 0) || (required->type != kTagTypeString) || !strcmp(required->string, "Safe Boot")) @@ -764,32 +813,31 @@ return -2; } - tmpModule = malloc(sizeof(Module)); - if (tmpModule == 0) - { - XMLFreeTag(moduleDict); - return -1; - } - tmpModule->dict = moduleDict; + tmpModule = malloc(sizeof(Module)); + if (tmpModule == 0) { + XMLFreeTag(moduleDict); + return -1; + } + tmpModule->dict = moduleDict; - // For now, load any module that has OSBundleRequired != "Safe Boot". + // For now, load any module that has OSBundleRequired != "Safe Boot". - tmpModule->willLoad = 1; + tmpModule->willLoad = 1; - *module = tmpModule; + *module = tmpModule; - // Get the personalities. + // Get the personalities. - *personalities = XMLGetProperty(moduleDict, kPropIOKitPersonalities); + *personalities = XMLGetProperty(moduleDict, kPropIOKitPersonalities); - return 0; + return 0; } #if NOTDEF static char gPlatformName[64]; #endif -long +long DecodeKernel(void *binary, entry_t *rentry, char **raddr, int *rsize) { long ret; @@ -845,22 +893,21 @@ } ret = ThinFatFile(&binary, &len); - if (ret == 0 && len == 0 && archCpuType==CPU_TYPE_X86_64) - { - archCpuType=CPU_TYPE_I386; - ret = ThinFatFile(&binary, &len); - } - - // Notify modules that the kernel has been decompressed, thinned and is about to be decoded + if (ret == 0 && len == 0 && archCpuType==CPU_TYPE_X86_64) + { + archCpuType=CPU_TYPE_I386; + ret = ThinFatFile(&binary, &len); + } + + // Notify modules that the kernel has been decompressed, thinned and is about to be decoded execute_hook("DecodeKernel", (void*)binary, NULL, NULL, NULL); - - - ret = DecodeMachO(binary, rentry, raddr, rsize); - if (ret<0 && archCpuType==CPU_TYPE_X86_64) - { - archCpuType=CPU_TYPE_I386; - ret = DecodeMachO(binary, rentry, raddr, rsize); - } - - return ret; + + ret = DecodeMachO(binary, rentry, raddr, rsize); + if (ret<0 && archCpuType==CPU_TYPE_X86_64) + { + archCpuType=CPU_TYPE_I386; + ret = DecodeMachO(binary, rentry, raddr, rsize); + } + + return ret; } Index: trunk/i386/boot2/boot.c =================================================================== --- trunk/i386/boot2/boot.c (revision 2326) +++ trunk/i386/boot2/boot.c (revision 2327) @@ -75,7 +75,7 @@ char gRootDevice[ROOT_DEVICE_SIZE]; char gMKextName[512]; char gMacOSVersion[8]; -int bvCount = 0, gDeviceCount = 0; +int bvCount = 0, gDeviceCount = 0; //int menucount = 0; long gBootMode; /* defaults to 0 == kBootModeNormal */ BVRef bvr, menuBVR, bvChain; @@ -96,13 +96,13 @@ static void zeroBSS(void) { extern char bss_start __asm("section$start$__DATA$__bss"); - extern char bss_end __asm("section$end$__DATA$__bss"); - extern char common_start __asm("section$start$__DATA$__common"); - extern char common_end __asm("section$end$__DATA$__common"); - + extern char bss_end __asm("section$end$__DATA$__bss"); + extern char common_start __asm("section$start$__DATA$__common"); + extern char common_end __asm("section$end$__DATA$__common"); + bzero(&bss_start, (&bss_end - &bss_start)); bzero(&common_start, (&common_end - &common_start)); -} +} //========================================================================== // Malloc error function @@ -129,74 +129,73 @@ { int ret; entry_t kernelEntry; - + bootArgs->kaddr = bootArgs->ksize = 0; execute_hook("ExecKernel", (void*)binary, NULL, NULL, NULL); - + ret = DecodeKernel(binary, &kernelEntry, (char **) &bootArgs->kaddr, (int *)&bootArgs->ksize ); - + if ( ret != 0 ) return ret; - + // Reserve space for boot args reserveKernBootStruct(); - + // Notify modules that the kernel has been decoded execute_hook("DecodedKernel", (void*)binary, (void*)bootArgs->kaddr, (void*)bootArgs->ksize, NULL); - + setupFakeEfi(); - + // Load boot drivers from the specifed root path. //if (!gHaveKernelCache) LoadDrivers("/"); - + execute_hook("DriversLoaded", (void*)binary, NULL, NULL, NULL); - + clearActivityIndicator(); - + if (gErrors) { printf("Errors encountered while starting up the computer.\n"); printf("Pausing %d seconds...\n", kBootErrorTimeout); sleep(kBootErrorTimeout); } - + md0Ramdisk(); - + verbose("Starting Darwin %s\n",( archCpuType == CPU_TYPE_I386 ) ? "x86" : "x86_64"); verbose("Boot Args: %s\n", bootArgs->CommandLine); // Cleanup the PXE base code. - + if ( (gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit ) { - if ( (ret = nbpUnloadBaseCode()) != nbpStatusSuccess ) - { + if ( (ret = nbpUnloadBaseCode()) != nbpStatusSuccess ) { printf("nbpUnloadBaseCode error %d\n", (int) ret); sleep(2); } } - + bool dummyVal; if (getBoolForKey(kWaitForKeypressKey, &dummyVal, &bootInfo->chameleonConfig) && dummyVal) { showTextBuffer(msgbuf, strlen(msgbuf)); } - + usb_loop(); // If we were in text mode, switch to graphics mode. // This will draw the boot graphics unless we are in // verbose mode. - if (gVerboseMode) + if (gVerboseMode) { setVideoMode( GRAPHICS_MODE, 0 ); - else + } else { drawBootGraphics(); - + } setupBooterLog(); - + finalizeBootStruct(); - + // Jump to kernel's entry point. There's no going back now. if ((checkOSVersion("10.7")) || (checkOSVersion("10.8")) || (checkOSVersion("10.9"))) { @@ -207,16 +206,15 @@ // Masking out so that Lion doesn't doublefault outb(0x21, 0xff); /* Maskout all interrupts Pic1 */ outb(0xa1, 0xff); /* Maskout all interrupts Pic2 */ - + startprog( kernelEntry, bootArgs ); - } - else { + } else { // Notify modules that the kernel is about to be started execute_hook("Kernel Start", (void*)kernelEntry, (void*)bootArgsPreLion, NULL, NULL); startprog( kernelEntry, bootArgsPreLion ); } - + // Not reached return 0; } @@ -225,17 +223,17 @@ //========================================================================== // LoadKernelCache - Try to load Kernel Cache. // return the length of the loaded cache file or -1 on error -long LoadKernelCache(const char* cacheFile, void **binary) { +long LoadKernelCache(const char* cacheFile, void **binary) +{ char kernelCacheFile[512]; char kernelCachePath[512]; long flags, time, cachetime, kerneltime, exttime, ret=-1; - unsigned long adler32; + unsigned long adler32; - if((gBootMode & kBootModeSafe) != 0) - { + if((gBootMode & kBootModeSafe) != 0) { verbose("Kernel Cache ignored.\n"); return -1; - } + } // Use specify kernel cache file if not empty if (cacheFile[0] != 0) @@ -247,39 +245,38 @@ // Lion, Mountain Lion and Mavericks prelink kernel cache file if ((checkOSVersion("10.7")) || (checkOSVersion("10.8")) || (checkOSVersion("10.9"))) { - snprintf(kernelCacheFile, sizeof(kernelCacheFile), "%skernelcache", kDefaultCachePathSnow); + snprintf(kernelCacheFile, sizeof(kernelCacheFile), "%skernelcache", kDefaultCachePathSnow); } // Snow Leopard prelink kernel cache file else if (checkOSVersion("10.6")) { - snprintf(kernelCacheFile, sizeof(kernelCacheFile), "kernelcache_%s", - (archCpuType == CPU_TYPE_I386) ? "i386" : "x86_64"); - int lnam = strlen(kernelCacheFile) + 9; //with adler32 + snprintf(kernelCacheFile, sizeof(kernelCacheFile), "kernelcache_%s", + (archCpuType == CPU_TYPE_I386) ? "i386" : "x86_64"); + int lnam = strlen(kernelCacheFile) + 9; //with adler32 - char* name; - long prev_time = 0; + char* name; + long prev_time = 0; - struct dirstuff* cacheDir = opendir(kDefaultCachePathSnow); - /* TODO: handle error? */ - if (cacheDir) { - while (readdir(cacheDir, (const char**)&name, &flags, &time) >= 0) { - if (((flags & kFileTypeMask) != kFileTypeDirectory) && time > prev_time - && strstr(name, kernelCacheFile) && (name[lnam] != '.')) { - snprintf(kernelCacheFile, sizeof(kernelCacheFile), "%s%s", kDefaultCachePathSnow, name); - prev_time = time; - } - } - } - closedir(cacheDir); + struct dirstuff* cacheDir = opendir(kDefaultCachePathSnow); + /* TODO: handle error? */ + if (cacheDir) { + while(readdir(cacheDir, (const char**)&name, &flags, &time) >= 0) { + if (((flags & kFileTypeMask) != kFileTypeDirectory) && time > prev_time + && strstr(name, kernelCacheFile) && (name[lnam] != '.')) { + snprintf(kernelCacheFile, sizeof(kernelCacheFile), "%s%s", kDefaultCachePathSnow, name); + prev_time = time; + } + } + } + closedir(cacheDir); + } else { + // Reset cache name. + bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64); + snprintf(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64, + "%s,%s", + gRootDevice, bootInfo->bootFile); + adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler)); + snprintf(kernelCacheFile, sizeof(kernelCacheFile), "%s.%08lX", kDefaultCachePathLeo, adler32); } - else { - // Reset cache name. - bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64); - snprintf(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64, - "%s,%s", - gRootDevice, bootInfo->bootFile); - adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler)); - snprintf(kernelCacheFile, sizeof(kernelCacheFile), "%s.%08lX", kDefaultCachePathLeo, adler32); - } } // Check if the kernel cache file exists @@ -287,25 +284,27 @@ // If boot from a boot helper partition check the kernel cache file on it if (gBootVolume->flags & kBVFlagBooter) { - snprintf(kernelCachePath, sizeof(kernelCachePath), "com.apple.boot.P%s", kernelCacheFile); - ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime); - if ((ret == -1) || ((flags & kFileTypeMask) != kFileTypeFlat)) { - snprintf(kernelCachePath, sizeof(kernelCachePath), "com.apple.boot.R%s", kernelCacheFile); - ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime); - if ((ret == -1) || ((flags & kFileTypeMask) != kFileTypeFlat)) { - snprintf(kernelCachePath, sizeof(kernelCachePath), "com.apple.boot.S%s", kernelCacheFile); - ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime); - if ((flags & kFileTypeMask) != kFileTypeFlat) - ret = -1; - } - } + snprintf(kernelCachePath, sizeof(kernelCachePath), "com.apple.boot.P%s", kernelCacheFile); + ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime); + if ((ret == -1) || ((flags & kFileTypeMask) != kFileTypeFlat)) { + snprintf(kernelCachePath, sizeof(kernelCachePath), "com.apple.boot.R%s", kernelCacheFile); + ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime); + if ((ret == -1) || ((flags & kFileTypeMask) != kFileTypeFlat)) { + snprintf(kernelCachePath, sizeof(kernelCachePath), "com.apple.boot.S%s", kernelCacheFile); + ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime); + if ((flags & kFileTypeMask) != kFileTypeFlat) { + ret = -1; + } + } + } } // If not found, use the original kernel cache path. if (ret == -1) { - strlcpy(kernelCachePath, kernelCacheFile, sizeof(kernelCachePath)); - ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime); - if ((flags & kFileTypeMask) != kFileTypeFlat) - ret = -1; + strlcpy(kernelCachePath, kernelCacheFile, sizeof(kernelCachePath)); + ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime); + if ((flags & kFileTypeMask) != kFileTypeFlat) { + ret = -1; + } } // Exit if kernel cache file wasn't found @@ -373,19 +372,19 @@ int status; unsigned int allowBVFlags = kBVFlagSystemVolume | kBVFlagForeignBoot; unsigned int denyBVFlags = kBVFlagEFISystem; - + // Set reminder to unload the PXE base code. Neglect to unload // the base code will result in a hang or kernel panic. gUnloadPXEOnExit = true; - + // Record the device that the booter was loaded from. gBIOSDev = biosdev & kBIOSDevMask; - + // Initialize boot info structure. initKernBootStruct(); - + initBooterLog(); - + // Setup VGA text mode. // Not sure if it is safe to call setVideoMode() before the // config table has been loaded. Call video_mode() instead. @@ -396,39 +395,39 @@ #if DEBUG printf("after video_mode\n"); #endif - + // Scan and record the system's hardware information. scan_platform(); - + // First get info for boot volume. scanBootVolumes(gBIOSDev, 0); bvChain = getBVChainForBIOSDev(gBIOSDev); setBootGlobals(bvChain); - + // Load boot.plist config file status = loadChameleonConfig(&bootInfo->chameleonConfig); - + if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->chameleonConfig) && quiet) { gBootMode |= kBootModeQuiet; } - + // Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config if (getBoolForKey(kInstantMenuKey, &instantMenu, &bootInfo->chameleonConfig) && instantMenu) { firstRun = false; } - + // Loading preboot ramdisk if exists. loadPrebootRAMDisk(); - + // Disable rescan option by default gEnableCDROMRescan = false; - + // Enable it with Rescan=y in system config if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->chameleonConfig) && gEnableCDROMRescan) { gEnableCDROMRescan = true; } - + // Ask the user for Rescan option by setting "Rescan Prompt"=y in system config. rescanPrompt = false; if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->chameleonConfig) @@ -436,28 +435,28 @@ { gEnableCDROMRescan = promptForRescanOption(); } - + // Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config. if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->chameleonConfig) && gScanSingleDrive) { gScanSingleDrive = true; } - + // Create a list of partitions on device(s). if (gScanSingleDrive) { scanBootVolumes(gBIOSDev, &bvCount); } else { scanDisks(gBIOSDev, &bvCount); } - + // Create a separated bvr chain using the specified filters. bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount); - + gBootVolume = selectBootVolume(bvChain); - + // Intialize module system init_module_system(); - + #if DEBUG printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags); @@ -474,9 +473,9 @@ // initGUI() returned with an error, disabling GUI. useGUI = false; } - + setBootGlobals(bvChain); - + // Parse args, load and start kernel. while (1) { @@ -486,7 +485,7 @@ int len, ret = -1; long flags, sleeptime, time; void *binary = (void *)kLoadAddr; - + char bootFile[sizeof(bootInfo->bootFile)]; char bootFilePath[512]; char kernelCacheFile[512]; @@ -494,11 +493,11 @@ // Initialize globals. sysConfigValid = false; gErrors = false; - + status = getBootOptions(firstRun); firstRun = false; if (status == -1) continue; - + status = processBootOptions(); // Status == 1 means to chainboot if ( status == 1 ) break; @@ -519,9 +518,9 @@ } continue; } - + // Other status (e.g. 0) means that we should proceed with boot. - + // Turn off any GUI elements if ( bootArgs->Video.v_display == GRAPHICS_MODE ) { @@ -533,74 +532,74 @@ drawBackground(); updateVRAM(); } - + // Find out which version mac os we're booting. getOSVersion(); - + if (platformCPUFeature(CPU_FEATURE_EM64T)) { archCpuType = CPU_TYPE_X86_64; } else { archCpuType = CPU_TYPE_I386; } - + if (getValueForKey(karch, &val, &len, &bootInfo->chameleonConfig)) { if (strncmp(val, "i386", 4) == 0) { archCpuType = CPU_TYPE_I386; } } - + if (getValueForKey(kKernelArchKey, &val, &len, &bootInfo->chameleonConfig)) { if (strncmp(val, "i386", 4) == 0) { archCpuType = CPU_TYPE_I386; } } - + // Notify modules that we are attempting to boot execute_hook("PreBoot", NULL, NULL, NULL, NULL); - + if (!getBoolForKey (kWake, &tryresume, &bootInfo->chameleonConfig)) { tryresume = true; tryresumedefault = true; } else { tryresumedefault = false; } - + if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->chameleonConfig)) { forceresume = false; } - + if (forceresume) { tryresume = true; tryresumedefault = false; } - + while (tryresume) { const char *tmp; BVRef bvr; if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->chameleonConfig)) val = "/private/var/vm/sleepimage"; - + // Do this first to be sure that root volume is mounted ret = GetFileInfo(0, val, &flags, &sleeptime); - + if ((bvr = getBootVolumeRef(val, &tmp)) == NULL) break; - + // Can't check if it was hibernation Wake=y is required if (bvr->modTime == 0 && tryresumedefault) break; - + if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)) break; - + if (!forceresume && ((sleeptime+3)modTime)) { -#if DEBUG +#if DEBUG printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n", bvr->modTime-sleeptime); -#endif +#endif break; } - + HibernateBoot((char *)val); break; } @@ -618,7 +617,7 @@ val++; } /* FIXME: check len vs sizeof(kernelCacheFile) */ - strlcpy(kernelCacheFile, val, len + 1); + strlcpy(kernelCacheFile, val, len + 1); } else { kernelCacheFile[0] = 0; // Use default kernel cache file } @@ -639,7 +638,7 @@ useKernelCache = false; } while(0); - + do { if (useKernelCache) { ret = LoadKernelCache(kernelCacheFile, &binary); @@ -680,7 +679,7 @@ // No alternate location found, using the original kernel image path. strlcpy(bootFilePath, bootFile, sizeof(bootFilePath)); } - + verbose("Loading kernel %s\n", bootFilePath); ret = LoadThinFatFile(bootFilePath, &binary); if (ret <= 0 && archCpuType == CPU_TYPE_X86_64) @@ -689,18 +688,18 @@ ret = LoadThinFatFile(bootFilePath, &binary); } } while (0); - + clearActivityIndicator(); - + #if DEBUG printf("Pausing..."); sleep(8); #endif - + if (ret <= 0) { printf("Can't find %s\n", bootFile); sleep(1); - + if (gBootFileType == kNetworkDeviceType) { // Return control back to PXE. Don't unload PXE base code. gUnloadPXEOnExit = false; @@ -775,7 +774,7 @@ unsigned long s2 = 0; // (adler >> 16) & 0xffff; unsigned long result; int k; - + while (len > 0) { k = len < NMAX ? len : NMAX; len -= k; Index: trunk/i386/boot2/boot2.s =================================================================== --- trunk/i386/boot2/boot2.s (revision 2326) +++ trunk/i386/boot2/boot2.s (revision 2327) @@ -64,7 +64,7 @@ # # Returns: # -LABEL(boot2) +LABEL(boot2) # Entry point at 0:BOOTER_ADDR (will be called by boot1) pushl %ecx # Save general purpose registers pushl %ebx pushl %ebp Index: trunk/i386/boot2/boot.h =================================================================== --- trunk/i386/boot2/boot.h (revision 2326) +++ trunk/i386/boot2/boot.h (revision 2327) @@ -193,10 +193,10 @@ * Boot Modes */ enum { - kBootModeNormal = 0, - kBootModeSafe = 1, - kBootModeSecure = 2, - kBootModeQuiet = 4 + kBootModeNormal = 0, + kBootModeSafe = 1, + kBootModeSecure = 2, + kBootModeQuiet = 4 }; extern void initialize_runtime(); @@ -215,16 +215,20 @@ extern int getVideoMode(); extern void spinActivityIndicator(); extern void clearActivityIndicator(); -extern void drawColorRectangle( unsigned short x, - unsigned short y, - unsigned short width, - unsigned short height, - unsigned char colorIndex ); -extern void drawDataRectangle( unsigned short x, - unsigned short y, - unsigned short width, - unsigned short height, - unsigned char * data ); +extern void drawColorRectangle( + unsigned short x, + unsigned short y, + unsigned short width, + unsigned short height, + unsigned char colorIndex + ); +extern void drawDataRectangle( + unsigned short x, + unsigned short y, + unsigned short width, + unsigned short height, + unsigned char * data + ); extern int convertImage( unsigned short width, unsigned short height, @@ -265,8 +269,8 @@ char *getMemoryInfoString(); typedef struct { - char name[80]; - void * param; + char name[80]; + void * param; } MenuItem; /* @@ -275,15 +279,15 @@ extern int decompress_lzss(u_int8_t *dst, u_int8_t *src, u_int32_t srclen); struct compressed_kernel_header { - u_int32_t signature; - u_int32_t compress_type; - u_int32_t adler32; - u_int32_t uncompressed_size; - u_int32_t compressed_size; - u_int32_t reserved[11]; - char platform_name[64]; - char root_path[256]; - u_int8_t data[0]; + u_int32_t signature; + u_int32_t compress_type; + u_int32_t adler32; + u_int32_t uncompressed_size; + u_int32_t compressed_size; + u_int32_t reserved[11]; + char platform_name[64]; + char root_path[256]; + u_int8_t data[0]; }; typedef struct compressed_kernel_header compressed_kernel_header; Index: trunk/i386/boot2/modules.c =================================================================== --- trunk/i386/boot2/modules.c (revision 2326) +++ trunk/i386/boot2/modules.c (revision 2327) @@ -107,13 +107,11 @@ struct dirstuff* moduleDir = opendir("/Extra/modules/"); while (readdir(moduleDir, (const char**)&name, &flags, &time) >= 0) { - if (strcmp(&name[strlen(name) - sizeof("dylib")], ".dylib") == 0) - { + if(strcmp(&name[strlen(name) - sizeof("dylib")], ".dylib") == 0) { char* tmp = malloc(strlen(name) + 1); strcpy(tmp, name); - if (!load_module(tmp)) - { + if(!load_module(tmp)) { // failed to load // free(tmp); } @@ -123,7 +121,7 @@ DBG("Ignoring %s\n", name); } } - closedir(moduleDir); + closedir(moduleDir); } @@ -985,14 +983,14 @@ UInt32 addr = lookup_all_symbols(symbol); if(addr != 0xFFFFFFFF) { - //DBG("Replacing %s to point to 0x%x\n", symbol, newAddress); - UInt32* jumpPointer = malloc(sizeof(UInt32*)); - char* binary = (char*)addr; - *binary++ = 0xFF; // Jump - *binary++ = 0x25; // Long Jump - *((UInt32*)binary) = (UInt32)jumpPointer; - *jumpPointer = (UInt32)newAddress; - return 1; + //DBG("Replacing %s to point to 0x%x\n", symbol, newAddress); + UInt32* jumpPointer = malloc(sizeof(UInt32*)); + char* binary = (char*)addr; + *binary++ = 0xFF; // Jump + *binary++ = 0x25; // Long Jump + *((UInt32*)binary) = (UInt32)jumpPointer; + *jumpPointer = (UInt32)newAddress; + return 1; } return 0; } Index: trunk/i386/boot2/gui.c =================================================================== --- trunk/i386/boot2/gui.c (revision 2326) +++ trunk/i386/boot2/gui.c (revision 2327) @@ -1811,7 +1811,7 @@ currentline = lines - visiblelines; } } - free(text); + free(text); } void animateProgressBar() Index: trunk/i386/boot2/ramdisk.c =================================================================== --- trunk/i386/boot2/ramdisk.c (revision 2326) +++ trunk/i386/boot2/ramdisk.c (revision 2327) @@ -29,17 +29,17 @@ &bootInfo->chameleonConfig)) { // Use user specified md0 file - snprintf(filename, sizeof(filename), "%s", override_filename); + snprintf(filename, sizeof(filename), "%s", override_filename); fh = open(filename, 0); if(fh < 0) { - snprintf(filename, sizeof(filename), "rd(0,0)/Extra/%s", override_filename); + snprintf(filename, sizeof(filename), "rd(0,0)/Extra/%s", override_filename); fh = open(filename, 0); if(fh < 0) { - snprintf(filename, sizeof(filename), "/Extra/%s", override_filename); + snprintf(filename, sizeof(filename), "/Extra/%s", override_filename); fh = open(filename, 0); } } @@ -151,7 +151,7 @@ if (error == 0) { // Save filename in gRAMDiskFile to display information. - strlcpy(gRAMDiskFile, param, sizeof(gRAMDiskFile)); + strlcpy(gRAMDiskFile, param, sizeof(gRAMDiskFile)); // Set gMI as well for the multiboot ramdisk driver hook. gMI = gRAMDiskMI = malloc(sizeof(multiboot_info)); Index: trunk/i386/boot2/options.c =================================================================== --- trunk/i386/boot2/options.c (revision 2326) +++ trunk/i386/boot2/options.c (revision 2327) @@ -641,28 +641,29 @@ char *getMemoryInfoString() { - int i, bufflen; - MemoryRange *mp = bootInfo->memoryMap; - char *buff = malloc(sizeof(char)*1024); - if (!buff) - return 0; - - static const char info[] = "BIOS reported memory ranges:\n"; - bufflen = sprintf(buff, "%s", info); + int i, bufflen; + MemoryRange *mp = bootInfo->memoryMap; + char *buff = malloc(sizeof(char)*1024); + if(!buff) { + return 0; + } - for (i = 0; - (i < bootInfo->memoryMapCount) && (bufflen < 1024); /* prevent buffer overflow */ - i++) { - bufflen += snprintf(buff+bufflen, 1024-bufflen, "Base 0x%08x%08x, ", + static const char info[] = "BIOS reported memory ranges:\n"; + bufflen = sprintf(buff, "%s", info); + + for (i = 0; + (i < bootInfo->memoryMapCount) && (bufflen < 1024); /* prevent buffer overflow */ + i++) { + bufflen += snprintf(buff+bufflen, 1024-bufflen, "Base 0x%08x%08x, ", (unsigned long)(mp->base >> 32), (unsigned long)(mp->base)); - bufflen += snprintf(buff+bufflen, 1024-bufflen, "length 0x%08x%08x, type %d\n", + bufflen += snprintf(buff+bufflen, 1024-bufflen, "length 0x%08x%08x, type %d\n", (unsigned long)(mp->length >> 32), (unsigned long)(mp->length), mp->type); - mp++; - } - return buff; + mp++; + } + return buff; } //========================================================================== Index: trunk/i386/config/symbol.c =================================================================== --- trunk/i386/config/symbol.c (revision 2326) +++ trunk/i386/config/symbol.c (revision 2327) @@ -881,13 +881,13 @@ newlen = strlen(res) + strlen(symval) + strlen(src) + 1; if (newlen > reslen) { - char* newres = NULL; - if (!(newres = realloc(res, newlen))) { - /* TODO: handle error gracefully - for now, punt */ - break; - } - res = newres; - reslen = newlen; + char* newres = NULL; + if (!(newres = realloc(res, newlen))) { + /* TODO: handle error gracefully - for now, punt */ + break; + } + res = newres; + reslen = newlen; } strcat(res, symval); Index: trunk/i386/config/confdata.c =================================================================== --- trunk/i386/config/confdata.c (revision 2326) +++ trunk/i386/config/confdata.c (revision 2327) @@ -902,7 +902,7 @@ } fclose(out); fclose(out_h); - fclose(out_inc); + fclose(out_inc); name = getenv("CCONFIG_AUTOHEADER"); if (!name) name = "autoconf.h"; Index: trunk/i386/libsa/printf.c =================================================================== --- trunk/i386/libsa/printf.c (revision 2326) +++ trunk/i386/libsa/printf.c (revision 2327) @@ -65,16 +65,16 @@ /*VARARGS1*/ int snprintf(char * str, size_t size, const char * fmt, ...) { - va_list ap; - struct putc_info pi; + va_list ap; + struct putc_info pi; - va_start(ap, fmt); - pi.str = str; - pi.last_str = str + size - 1; - prf(fmt, ap, sputc, &pi); - *pi.str = '\0'; - va_end(ap); - return (pi.str - str); + va_start(ap, fmt); + pi.str = str; + pi.last_str = str + size - 1; + prf(fmt, ap, sputc, &pi); + *pi.str = '\0'; + va_end(ap); + return (pi.str - str); } /*VARARGS1*/ Index: trunk/i386/libsa/string.c =================================================================== --- trunk/i386/libsa/string.c (revision 2326) +++ trunk/i386/libsa/string.c (revision 2327) @@ -161,10 +161,11 @@ { register char *ret = s1; while (n && (*s1++ = *s2++)) - --n; - /* while (n--) *s1++ = '\0'; */ - if (n > 0) - bzero(s1, n); + --n; + /* while (n--) *s1++ = '\0'; */ + if (n > 0) { + bzero(s1, n); + } return ret; } @@ -278,7 +279,7 @@ if (*start == '"') { start++; - + end = strchr(start, '"'); if(end) quoted = true; @@ -290,12 +291,12 @@ for ( end = start; *end && !isspace(*end); end++ ) {} } - + *len = end - start; - + if(next) *next = quoted ? end+1 : end; - + return start; }