repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
j00v/ZENZO-Core
src/qt/startoptionsrestore.h
<reponame>j00v/ZENZO-Core // // Created by Kolby on 9/4/2019. // #include <QLineEdit> #include <QWidget> #include <list> #include <QString> namespace Ui { class StartOptionsRestore; } /** Dialog to ask for passphrases. Used for encryption only */ class StartOptionsRestore : public QWidget { Q_OBJECT public: explicit StartOptionsRestore(QStringList wordList, int rows, QWidget *parent = nullptr); ~StartOptionsRestore(); std::vector<std::string> getOrderedStrings(); private Q_SLOTS: void textChanged(const QString &text); private: Ui::StartOptionsRestore *ui; std::list<QLineEdit*> editList; QStringList wordList; };
j00v/ZENZO-Core
src/qt/startoptionsdialog.h
<filename>src/qt/startoptionsdialog.h // Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include <QDialog> class CWallet; namespace Ui { class StartOptionsDialog; } /** Dialog to ask for passphrases. Used for encryption only */ class StartOptionsDialog : public QDialog { Q_OBJECT public: explicit StartOptionsDialog(const QString error_words, QWidget *parent); ~StartOptionsDialog(); void accept() override; private: Ui::StartOptionsDialog *ui; };
Paulther/midterm1
pi_funs.h
#define M_PI 3.14159265358979323846 /* pi */ double pi_leibniz (int n); double pi_bbp (int n);
Paulther/midterm1
pi_leibiniz.c
#include <stdio.h> //Uses the Leibniz series to calculate pi double pi_leibiniz (int n); double pi_leibiniz (int n) { double term = 0.; int s = 1; for (int i = 0; i < n; i++) { double nterm = 4. * s / (2. * i + 1); s = -s; term = term + nterm; } return term; }
Paulther/midterm1
m1.c
<reponame>Paulther/midterm1<gh_stars>0 #include <stdio.h> #include <math.h> #include "timer.h" #include "pi_funs.h" double pi_leibiniz (int n); double pi_bbp (int n); int adjust_rep_count (int n, double z, double x, double y); int main (void) { int i2 = 1; double tol = .000001; double abserr; double pi; printf ("Leibniz Series Method of Calculating Pi:\n\n"); printf (" Terms Value Error\n"); /*Determines the number of terms required to calculate pi within an error of * 10^-6 using the leibniz series method */ do { pi = pi_leibiniz (i2); abserr = fabs (pi - M_PI); printf ("%8d %20.15f %20.15f\n", i2, pi, abserr); i2 *= 2; } while (abserr > tol); printf ("\n\n"); int i1 = 1; double abserr1; double pi1; printf ("Bailey-Borwein-Plouffe Series Method of Calculating Pi:\n\n"); printf (" Terms Value Error\n"); /*Determines the number of terms required to calculate pi within an error of * 10^-6 using the bbp series method */ do { pi1 = pi_bbp (i1); abserr1 = fabs (pi1 - M_PI); printf ("%8d %20.15f %20.15f\n", i1, pi1, abserr1); i1 *= 2; } while (abserr1 > tol); printf ("\n\n"); double time; double time1; double time2; int j; double tmax = 2; double tmin = 1; int count = 1000; printf ("Timing the BBP Series Method:\n\n"); printf (" Time/Iteration Total Time Iterations\n"); do { timer_start (); for (j = 0; j < count; j++) { pi_bbp (i1); } //adjust count such that cpu time is between tmin and tmax time = timer_stop (); time1 = time / ((double) count); printf (" %10.2f usec %10.6f sec %10d\n", time1 * 1.e6, time, count); count = adjust_rep_count ((int) count, time, tmin, tmax); } while ((time > tmax) || (time < tmin)); printf ("\n\n"); count = 1000; printf ("Timing the Leibniz Series Method:\n\n"); printf (" Time/Iteration Total Time Iterations\n"); do { timer_start (); for (j = 0; j < count; j++) { pi_leibiniz (i2); } time = timer_stop (); //adjust count such that cpu time is between tmin and tmax time2 = time / ((double) count); printf (" %10.2f usec %10.6f sec %10d\n", time2 * 1.e6, time, count); count = adjust_rep_count ((int) count, time, tmin, tmax); } while ((time > tmax) || (time < tmin)); printf ("\n\n"); double q = time2 / time1; printf ("Speed up Factor: %10.2f\n\n", q); }
Paulther/midterm1
pi_bbp.c
<gh_stars>0 #include <stdio.h> // Uses the BBP method to calculate pi double pi_bbp (int n); double pi_bbp (int n) { double term = 0.; double nterm; double d = 0; double f = 16; for (int i = 0; i < n; i++) { f = (1. / 16.) * f; d = 8. * ((double) i); nterm = f * ((4. / (d + 1.)) - (2. / (d + 4.)) - (1. / (d + 5.)) - (1. / (d + 6.))); term = nterm + term; } return term; }
nickchops/s3eAndroidFullscreen
h/s3eAndroidFullscreen.h
<gh_stars>0 /* * (C) 2001-2012 Marmalade. All Rights Reserved. * * This document is protected by copyright, and contains information * proprietary to Marmalade. * * This file consists of source code released by Marmalade under * the terms of the accompanying End User License Agreement (EULA). * Please do not use this program/source code before you have read the * EULA and have agreed to be bound by its terms. */ /* * WARNING: this is an autogenerated file and will be overwritten by * the extension interface script. */ #ifndef S3E_EXT_ANDROIDFULLSCREEN_H #define S3E_EXT_ANDROIDFULLSCREEN_H // \cond HIDDEN_DEFINES S3E_BEGIN_C_DECL // \endcond /** * Returns S3E_TRUE if the AndroidFullscreen extension is available. */ s3eBool s3eAndroidFullscreenAvailable(); /* Returns true if OS version supports immersive mode (can hide navigation bar * and wont re-show it on user touches) Should return true only for Android 4.4 or newer. * The extension will fail to load and s3eAndroidFullscreenAvailable() will return * S3E_FALSE if the device doesn't support hiding the nav bar at all - i.e. on devices * running Android versions older than 4.0. */ s3eBool s3eAndroidFullscreenIsImmersiveSupported(); /* Hide navigation bar. Immersive mode will only be set if * s3eAndroidFullscreenIsImmersiveSupported returns true. If immersive is not used, * any touch will cause the nav bar to be displayed again. The user can always re-show the * nav bar by swiping onto the screen from the side where the bar normally is. * stickyNavBar causes the re-shown bar to be semi-transparent and to re-hide itself. In * sticky mode, the bar also re-hides itself when the app gains focus again. The extension * doesn't yet re-hide the bar after other events e.g. after alerts like s3eDialog. You'll * have to re-call s3eAndroidFullscreenOn after these show if possible. * staticLayout causes any native UI to fill the whole screen and not to try and * change its layout if the nav bar then shows or hides. */ void s3eAndroidFullscreenOn(s3eBool immersive S3E_DEFAULT(S3E_TRUE), s3eBool stickyNavBar S3E_DEFAULT(S3E_TRUE), s3eBool staticLayout S3E_DEFAULT(S3E_TRUE)); /* Re-show the nav bar. Optionally use showStatusBar to try and show the status bar if * the app supports it. Optionally set staticLayout to false to make the UI/GL view re-size * to not be under the nav bar anymore. */ void s3eAndroidFullscreenOff(s3eBool showStatusBar S3E_DEFAULT(S3E_FALSE), s3eBool showNavBar S3E_DEFAULT(S3E_TRUE), s3eBool staticLayout S3E_DEFAULT(S3E_TRUE)); // \cond HIDDEN_DEFINES S3E_END_C_DECL // \endcond #endif /* !S3E_EXT_ANDROIDFULLSCREEN_H */
nickchops/s3eAndroidFullscreen
source/h/s3eAndroidFullscreen_autodefs.h
<filename>source/h/s3eAndroidFullscreen_autodefs.h /* * WARNING: this is an autogenerated file and will be overwritten by * the extension interface script. */ #ifndef S3EANDROIDFULLSCREEN_AUTODEFS_H #define S3EANDROIDFULLSCREEN_AUTODEFS_H /** * string name used to locate this extension */ #define S3E_EXT_ANDROIDFULLSCREEN_NAME "s3eAndroidFullscreen" #define S3E_EXT_ANDROIDFULLSCREEN_HASH 0x3bb5b1c4 #ifdef S3E_EXT_REGISTER #ifndef S3E_EXT_REGISTER_KEY #define S3E_EXT_REGISTER_KEY(name, num, key) S3E_EXT_REGISTER(name, num) #endif S3E_EXT_REGISTER("s3eAndroidFullscreen", 3) #else #endif /* S3E_EXT_REGISTER */ #endif /* !S3EANDROIDFULLSCREEN_AUTODEFS_H */
nickchops/s3eAndroidFullscreen
source/h/s3eAndroidFullscreen_internal.h
/* * Internal header for the s3eAndroidFullscreen extension. * * This file should be used for any common function definitions etc that need to * be shared between the platform-dependent and platform-indepdendent parts of * this extension. */ /* * NOTE: This file was originally written by the extension builder, but will not * be overwritten (unless --force is specified) and is intended to be modified. */ #ifndef S3EANDROIDFULLSCREEN_INTERNAL_H #define S3EANDROIDFULLSCREEN_INTERNAL_H #include "s3eTypes.h" #include "s3eAndroidFullscreen.h" #include "s3eAndroidFullscreen_autodefs.h" /** * Initialise the extension. This is called once then the extension is first * accessed by s3eregister. If this function returns S3E_RESULT_ERROR the * extension will be reported as not-existing on the device. */ s3eResult s3eAndroidFullscreenInit(); /** * Platform-specific initialisation, implemented on each platform */ s3eResult s3eAndroidFullscreenInit_platform(); /** * Terminate the extension. This is called once on shutdown, but only if the * extension was loader and Init() was successful. */ void s3eAndroidFullscreenTerminate(); /** * Platform-specific termination, implemented on each platform */ void s3eAndroidFullscreenTerminate_platform(); s3eBool s3eAndroidFullscreenIsImmersiveSupported_platform(); void s3eAndroidFullscreenOn_platform(s3eBool immersive, s3eBool stickyNavBar, s3eBool staticLayout); void s3eAndroidFullscreenOff_platform(s3eBool showStatusBar, s3eBool showNavBar, s3eBool staticLayout); void s3eAndroidFullscreenResume_platform(); #endif /* !S3EANDROIDFULLSCREEN_INTERNAL_H */
nickchops/s3eAndroidFullscreen
example/ExamplesMain/src/ExamplesMain.h
<filename>example/ExamplesMain/src/ExamplesMain.h /* * This file is part of the Marmalade SDK Code Samples. * * (C) 2001-2012 Marmalade. All Rights Reserved. * * This source code is intended only as a supplement to the Marmalade SDK. * * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. */ #ifndef EXAMPLES_MAIN_H #define EXAMPLES_MAIN_H #include "s3e.h" #include <string.h> #include <stdio.h> typedef void (*ButtonCallback)(struct Button* button); /** * Structure to represent an on-screen button which can be * "pressed" using either touch or keyboard controls. * Position values are updated each time the button * is rendered. */ struct Button { Button* m_Next; char* m_Name; bool m_Enabled; bool m_Display; s3eKey m_Key; int m_Index; int m_XPos; int m_YPos; int m_Width; int m_Height; ButtonCallback m_Callback; }; extern bool g_DeviceHasKeyboard; extern bool g_HideDisabledButtons; void ExamplesMainInit(); bool ExamplesMainUpdate(); void ExamplesMainTerm(); // Functions which examples must implement void ExampleInit(); void ExampleTerm(); void ExampleRender(); bool ExampleUpdate(); bool ExampleCheckQuit(); void ButtonsRender(); void DontClearScreen(); void DontDrawCursor(); /** * Create and new button and return a pointer to it. */ Button* NewButton(const char *name, ButtonCallback callback=NULL); /** * Delete all buttons and free memory allocated for them. */ void DeleteButtons(); /** * Return a pointer to whichever button is currently pressed, or NULL * if no button is pressed. */ Button *GetSelectedButton(); /** * Get the first Y coordinate below the bottom of the last button. */ int GetYBelowButtons(); /** * Set the scale factor for the display of all buttons. */ void SetButtonScale(uint scale); /** * Get the scale factor for the display of all buttons. */ uint GetButtonScale(); /** * Set button name safely. * Frees old string and re-allocates memory for the new one. */ void SetButtonName(Button* button, const char *name); /** * Returns true if the touch-screen version of buttons is being used. * This is determined automatically based on the device hardware: * touch screen buttons are used if the device supports them. */ bool IsUsingPointerButtons(); /** * Initialise message printing system. Display last numMessages messages, each of max length * messageLen (including null terminator). */ void InitMessages(int numMessages, int messageLen); /** * Clear all messsages in the queue. */ void ClearMessages(); /** * Add a message to the list of messages to be displayed by PrintMessages(). */ void AppendMessage(const char* src, ...); typedef enum Colour { WHITE, BLACK, BLUE, GREEN, RED, } Colour; void AppendMessageColour(Colour colour, const char* src, ...); /** * Print all messages in list, newest at top. * x and y specify location to print first message at. * Returns y position of last message printed. */ int PrintMessages(int x, int y); /** * Free memory allocated by InitMessages(). */ void TerminateMessages(); /** * Draw a rectangle on the screen. */ void DrawRect(int x, int y, int width, int height, uint8 r, uint8 g, uint8 b); #endif
nickchops/s3eAndroidFullscreen
quick/QAndroidFullscreen.h
#ifndef __Q_ANDROIDFULLSCREEN_H #define __Q_ANDROIDFULLSCREEN_H #include <string> // tolua_begin namespace androidFullscreen { bool isAvailable(); bool isImmersiveSupported(); void turnOn(bool immersive=true, bool stickyNavBar=true, bool staticLayout=true); void turnOff(bool showStatusBar=false, bool showNavBar=true, bool staticLayout=true); } // tolua_end #endif // __Q_ANDROIDFULLSCREEN_H
lqwang521/CocoapodsTestStatic
CocoapodsTestStatic/Classes/LQTestMasonryView.h
<filename>CocoapodsTestStatic/Classes/LQTestMasonryView.h // // LQTestMasonryView.h // CocoapodsTestStatic // // Created by wlq on 2018/8/31. // #import <UIKit/UIKit.h> @interface LQTestMasonryView : UIView @property (nonatomic, strong) UILabel *aLabel; @end
lqwang521/CocoapodsTestStatic
Example/Pods/Target Support Files/Pods-CocoapodsTestStatic_Example/Pods-CocoapodsTestStatic_Example-umbrella.h
<gh_stars>0 #ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif FOUNDATION_EXPORT double Pods_CocoapodsTestStatic_ExampleVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_CocoapodsTestStatic_ExampleVersionString[];
lqwang521/CocoapodsTestStatic
Example/CocoapodsTestStatic/LQAppDelegate.h
<reponame>lqwang521/CocoapodsTestStatic // // LQAppDelegate.h // CocoapodsTestStatic // // Created by lqwang521 on 08/31/2018. // Copyright (c) 2018 lqwang521. All rights reserved. // @import UIKit; @interface LQAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
lqwang521/CocoapodsTestStatic
Example/CocoapodsTestStatic/LQViewController.h
// // LQViewController.h // CocoapodsTestStatic // // Created by lqwang521 on 08/31/2018. // Copyright (c) 2018 lqwang521. All rights reserved. // @import UIKit; @interface LQViewController : UIViewController @end
Manishgithub2021/Career
DoubleLinkedList.c
#include<stdio.h> #include<conio.h> #include<stdlib.h> struct node{ struct node *prev; int data; struct node *next; }; struct node *head; void display(){ struct node *temp; temp=(struct node *)malloc(sizeof(struct node *)); if(!head){ printf("\n\n**********EMPTY***********\n\n"); } else{ temp=head; printf("\n\n**********START PRINTING DATA************\n\n\n"); while(temp){ printf("\n\n%d\n\n",temp->data); temp=temp->next; } printf("\n\n********ALL DATA PRINTED*****************\n\n\n"); } }; void insertAtBegining(int num){ struct node *temp; temp=(struct node *)malloc(sizeof(struct node *)); if(!head){ temp->data=num; temp->next=NULL; temp->prev=NULL; head=temp; }else{ temp->data=num; temp->prev=NULL; temp->next=head; head=temp; } }; void insertAtEnd(int num){ struct node *temp,*last; temp=(struct node *)malloc(sizeof(struct node *)); if(!head){ temp->data=num; temp->next=NULL; temp->prev=NULL; head=temp; }else{ temp->data=num; temp->next=NULL; last=head; while(last->next!=NULL){ last=last->next; } last->next=temp; temp->prev=last; } }; void deleteAtBegining(){ if(!head){ printf("\n\n*******NOTHING TO DELETE**************\n\n"); }else{ printf("\n\ndeleted num is:%d \n\n",head->data); struct node *first; first=head; head=head->next; free(first); } }; void deleteAtEnd(){ if(!head){ printf("\n\n*******NOTHING TO DELETE**************\n\n"); } else if(head->next==NULL){ struct node *temp; temp=head; printf("\n\ndeleted number is %d",temp->data); head=head->next; free(temp); } else{ struct node *last,*secondlast; last=head; secondlast=head; while(last->next!=NULL){ secondlast=last; last=last->next; } printf("\n\n delted number is %d",last->data); secondlast->next=NULL; free(last); } }; void main(){ printf("\n*********WELCOME TO DOUBLE LINKED LIST WORLD**************\n"); printf("\n\nINSERTING AT BEGINING\n\n"); insertAtBegining(5); insertAtBegining(4); insertAtBegining(3); insertAtBegining(2); insertAtBegining(1); display(); printf("\n\nINSERTING AT END\n\n"); insertAtEnd(6); insertAtEnd(7); insertAtEnd(8); display(); printf("\n\n********DELETING AT BEGINING\n\n"); deleteAtBegining(); deleteAtBegining(); deleteAtBegining(); deleteAtBegining(); deleteAtBegining(); deleteAtBegining(); deleteAtBegining(); deleteAtBegining(); deleteAtBegining(); deleteAtBegining(); printf("\n\nINSERTING AT BEGINING\n\n"); insertAtBegining(5); insertAtBegining(4); insertAtBegining(3); insertAtBegining(2); insertAtBegining(1); display(); printf("\n\nINSERTING AT END\n\n"); insertAtEnd(6); insertAtEnd(7); insertAtEnd(8); display(); printf("\n\n********DELETING AT END\n\n"); deleteAtEnd(); deleteAtEnd(); deleteAtEnd(); deleteAtEnd(); deleteAtEnd(); deleteAtEnd(); deleteAtEnd(); deleteAtEnd(); deleteAtEnd(); deleteAtEnd(); }
Manishgithub2021/Career
STACK_IMPLEMENTATION_LINKEDLIST.c
<reponame>Manishgithub2021/Career //STACK IMPLEMENTATION USING SINGLE LINKED LIST #include<conio.h> #include<stdio.h> #include<stdlib.h> // Defining struct struct node{ int data; struct node *next; }; struct node *head; void display(){ if(!head){ printf("\nStack is empty\n"); } else{ struct node *temphead; temphead=head; printf("\n***STARTED PRINTING DATA*********\n\n"); while(temphead){ printf("%d\n",temphead->data); temphead=temphead->next; } printf("\n******ALL DATA PRINTED******\n\n"); } }; void insert(int data){ struct node *temp,*temphead; temp=(struct node *)malloc(sizeof(struct node *)); temp->data=data; temp->next=NULL; if(!head){ head=temp; } else{ temphead=head; while(temphead->next!=NULL){ temphead=temphead->next; } temphead->next=temp; } }; void pop(){ struct node *last,*secondlast; last=head; secondlast=head; if(!last){ printf("\nStack is empty, nothing to delete\n"); } else if(last->next==NULL){ printf("\ndeleted data is:%d\n\n",last->data); free(last); head=NULL; } else{ while(last->next!=NULL){ last=last->next; } while(secondlast->next!=last){ secondlast=secondlast->next; } secondlast->next=NULL; printf("\ndeleted data is:%d",last->data); free(last); } }; void main(){ while(1){ printf("\n**************CHOOSE A OPTION**********************\n"); printf("\n****** 0 : Exit***************"); printf("\n****** 1 : Insert*************"); printf("\n****** 2 : Delete*************"); printf("\n****** 3 : Display************"); printf("\n Type your choice: "); int choice; scanf("%d",&choice); switch(choice){ case 0:printf("\nExiting"); return; case 1: printf("\nWhat to insert? "); int num; scanf("%d",&num); insert(num); printf("\nInserted successfully"); break; case 2:pop(); break; case 3:display(); break; default:printf("\nWrong choice"); return; } } };
Manishgithub2021/Career
SingleLinkedList.c
<filename>SingleLinkedList.c<gh_stars>0 #include<stdio.h> #include<conio.h> #include<stdlib.h> //SINGLE LINKED LIST IMPLEMENTATION struct node{ int data; struct node *next; }; struct node *head; void insertatBegining(int num){ struct node *temp; temp=(struct node *)malloc(sizeof(struct node *)); temp->data=num; if(!head){ temp->next=head; head=temp; }else{ temp->next=head; head=temp; } }; void insertatEnd(int num){ struct node *temp,*last; temp=(struct node *)malloc(sizeof(struct node *)); temp->data=num; if(!head){ temp->next=head; head=temp; }else{ last=head; while(last->next!=NULL){ last=last->next; } last->next=temp; temp->next=NULL; } }; void DeleteAtBegining(){ struct node *first; if(!head){ printf("\n\n****nothing to delete**********\n\n"); }else{ first=head; printf("\n\nDeleted number is %d\n\n",head->data); head=head->next; free(first); } }; void DeleteAtEnd(){ struct node *first,*last,*secondlast; if(!head){ printf("\n\n****nothing to delete**********\n\n"); } else if(head->next==NULL){ first=head; printf("\n\nDeleted item is %d\n\n",head->data); head=NULL; free(first); }else{ last=head; secondlast=head; while(last->next!=NULL){ last=last->next; } while(secondlast->next!=last) secondlast=secondlast->next; secondlast->next=NULL; free(last); } }; void findNumber(int num){ struct node *temp; int counter=-1; temp=head; while(temp){ counter++; if(temp->data==num){ printf("\n\nNumber %d is found at index %d\n\n",num,counter); return; } temp=temp->next; } printf("\n\nNumber is not found\n\n"); }; void display(){ struct node *temp; if(!head){ printf("\n\n******NOTHING TO DISPLAY***********\n\n"); } else{ printf("\n\n***********PRINTING STARTED*****************\n\n"); temp=head; int counter=0; while(temp){ counter++; printf("\n %d\n\n",temp->data); temp=temp->next; } printf("\n\n**************PRINTING FINISHED****************\n\n"); } }; void main(){ printf("\n\n**********WELCOME TO WORLD OF SINGLE LINKED LIST**************\n\n"); //DeleteAtBegining(); insertatBegining(5); insertatBegining(6); insertatBegining(7); //DeleteAtBegining(); display(); //DeleteAtBegining(); //display(); DeleteAtEnd(); display(); DeleteAtEnd(); display(); DeleteAtEnd(); display(); DeleteAtEnd(); display(); };
Manishgithub2021/Career
Queue_using_singleLinkedList.c
<gh_stars>0 #include<conio.h> #include<stdio.h> struct node{ int data; struct node *next; }; struct node *head; void insert(int num){ struct node *last,*temp; if(!head){ temp=(struct node *)malloc(sizeof(struct node *)); temp->data=num; temp->next=NULL; head=temp; } else{ temp=(struct node *)malloc(sizeof(struct node *)); temp->data=num; temp->next=NULL; last=head; while(last->next!=NULL){ last=last->next; } last->next=temp; } }; void display(){ struct node *last; if(!head){ printf("\n\nNothing to display\n\n"); }else{ last=head; printf("\n\n********STARTED PRINTING DATA*******\n\n"); while(last){ printf("%d\n",last->data); last=last->next; } printf("\n\n***********FINISHED PRINTING DATA**********\n\n"); } }; void delete(){ if(!head){ printf("\n\n Queue is empty nothing to delete\n\n"); }else if(head->next==NULL){ struct node *temp; temp=head; printf("\n\nDeleted item is %d\n\n",head->data); head=NULL; free(temp); }else{ struct node *first; first=head; printf("\n\nDeleted item is %d\n\n",head->data); head=head->next; free(first); } } void main(){ printf("\nINSIDE MAIN LOOP\n\n"); display(); delete(); insert(1); delete(); delete(); insert(2); insert(3); insert(4); insert(5); display(); insert(6); insert(7); display(); insert(8); insert(9); display(); delete(); display(); delete(); display(); };
VijayrajS/3d-game
src/cube.h
<filename>src/cube.h #include "main.h" #ifndef CUBE_H #define CUBE_H class Cube { public: Cube() {} Cube(float x, float y, float z, float length, float breadth, float width, color_t color); glm::vec3 position; glm::vec3 speed; float rotation; float breadth; float length; float height; void draw(glm::mat4 VP); void set_position(float x, float y, float z); void tick(); bounding_box_t bounding_box(); private: VAO *object; }; #endif // CUBE_H
VijayrajS/3d-game
src/bomb.h
<filename>src/bomb.h #include "main.h" #ifndef BOMB_H #define BOMB_H class Bomb { public: Bomb() {} Bomb(float x, float y, float z, float rx, float ry, float rz, int flag, float speed); glm::vec3 position; glm::mat4 cannonb; float speed; float rotationx; float rotationy; float rotationz; float width; float height; int bm; // Bomb or missile flag void draw(glm::mat4 VP); void set_position(float x, float y, float z); void tick(); bool sea_coll(); bounding_box_t bounding_box(); private: VAO *object1; VAO *object2; VAO *object3; VAO *object4; }; #endif // BOMB_H
VijayrajS/3d-game
src/ring.h
#include "main.h" #ifndef RING_H #define RING_H class Ring { public: Ring() {} Ring(float x, float y, float z, float rx, float r, color_t color); glm::vec3 position; float speed; float rotation; int smokeon; void draw(glm::mat4 VP); void set_position(float x, float y, float z); void tick(); private: VAO *object; }; #endif // RING_H
VijayrajS/3d-game
src/ball.h
<reponame>VijayrajS/3d-game #include "main.h" #ifndef BALL_H #define BALL_H class Ball { public: Ball() {} Ball(float x, float y); glm::vec3 position; float rotationx; float rotationy; float rotationz; void draw(glm::mat4 VP); void set_position(float x, float y, float z); bool sea_coll(); void tick(); double speed; double fuel; private: VAO *object1; VAO *object2; VAO *object3; VAO *object4; VAO *object5; VAO *object6; VAO *object7; VAO *inner_f; VAO *outer_f; }; #endif // BALL_H
VijayrajS/3d-game
src/volcano.h
<gh_stars>0 #include "main.h" #ifndef VOLCANO_H #define VOLCANO_H class Volcano { public: Volcano() {} Volcano(float x, float y, float z, color_t color); glm::vec3 position; float speed; float rotation; float width; float height; void draw(glm::mat4 VP); void set_position(float x, float y); void tick(); bounding_box_t bounding_box(); private: VAO *mnt; VAO *lava; VAO *smk; VAO *top; }; #endif // ARROW_H
VijayrajS/3d-game
src/enemies.h
#include "main.h" #ifndef ENEMIES_H #define ENEMIES_H class Cannon { public: Cannon() {} Cannon(float x, float y, float zS); glm::vec3 position; float speed; float rotation; void draw(glm::mat4 VP); void set_position(float x, float y, float z); void tick(); int alive; private: VAO *object; VAO *barrel; VAO *land; }; class Para { public: Para() {} Para(float x, float y, float z); glm::vec3 position; float speed; float rotation; void draw(glm::mat4 VP); void set_position(float x, float y, float z); void tick(); private: VAO *object; VAO *object2; VAO *object3; VAO *object4; }; #endif // ENEMIES_H
pretzelhammer/brainfuck-compilers
examples/c/print_eof.c
#include <stdio.h> #include <errno.h> // for the definition of errno #include <stdlib.h> // for exit() #include <string.h> #include <math.h> int main(void) { /* int c; while ((c = getchar()) != EOF) putchar(c); if (feof(stdin)) { printf("end-of-file reached\n"); exit(0); } else if (ferror(stdin)) { printf("An error occurred. errno set to %d\n", errno); perror("Human readable explanation"); exit(1); } else { printf("This should never happen...\n"); exit('?'); } */ //int a=54325; //char str[80]; printf("Value of Pi = %f\n", M_PI); //puts(str); printf("Value of EOF = %d\n", EOF); //puts(str); int pre_eof = 0; int post_eof = 0; int c = getchar(); while (c != EOF) { pre_eof++; c = getchar(); } post_eof++; if (EOF == getchar()) { post_eof++; } if (EOF == getchar()) { post_eof++; } if (EOF == getchar()) { post_eof++; } printf("pre_eof %d, post_eof %d", pre_eof, post_eof); // ugh, getchar *caches* EOF, this creates an infinite // loop for LLVM IR compiled brainfuck programs that // don't handle EOF characters: head.b, tic_tac_toe.b, // and guess_number.b return 0; }
tgifae/tgif
Implementations/software/tgifn2128v1/ref/TGIF_BC.c
<reponame>tgifae/tgif<filename>Implementations/software/tgifn2128v1/ref/TGIF_BC.c<gh_stars>1-10 /* TGIF BC implementation Prepared by: <NAME> Email: <EMAIL> Date: 25 Feb 2019 */ #include <stdint.h> #include "bc.h" const uint16_t RC[] = { /*7-bit LFSR x6,x5,x4,x3,x2,x1,x0 <- x5,x4,x3,x2,x1,x0+x6,x6*/ 0x8001, 0x8002, 0x8004, 0x8008, 0x8010, 0x8020, 0x8040, 0x8003, 0x8006, 0x800C, 0x8018, 0x8030, 0x8060, 0x8043, 0x8005, 0x800A, 0x8014, 0x8028, 0x8050, 0x8023, 0x8046, 0x800F, 0x801E, 0x803C, 0x8078, 0x8073, 0x8065, 0x8049, 0x8011, 0x8022, 0x8044, 0x800B, 0x8016, 0x802C, 0x8058, 0x8033, 0x8066, 0x804F, 0x801D, 0x803A, 0x8074, 0x806B, 0x8055, 0x8029, 0x8052, 0x8027, 0x804E, 0x801F, 0x803E, 0x807C, 0x807B, 0x8075, 0x8069, 0x8051, 0x8021, 0x8042, 0x8007, 0x800E, 0x801C, 0x8038, 0x8070, 0x8063, 0x8045, 0x8009, 0x8012, 0x8024, 0x8048, 0x8013, 0x8026, 0x804C, 0x801B, 0x8036, 0x806C, 0x805B, 0x8035, 0x806A, 0x8057, 0x802D, 0x805A, 0x8037 }; void giftb64_4r(uint16_t P[4], int step, const uint16_t *RK, uint16_t C[4]){ uint16_t S[4],T; S[0] = P[0]; S[1] = P[1]; S[2] = P[2]; S[3] = P[3]; /*fully unroll*/ /*========== round 1 ==========*/ /*R1===AddRoundKey===*/ S[0] ^= RK[8*step + 0]; S[1] ^= RK[8*step + 1]; S[3] ^= RC[4*step + 0]; /*===SubCells===*/ S[1] ^= S[0] & S[2]; S[0] ^= S[1] & S[3]; S[2] ^= S[0] | S[1]; S[3] ^= S[2]; S[1] ^= S[3]; S[3] ^= 0xffff; S[2] ^= S[0] & S[1]; T = S[0]; S[0] = S[3]; S[3] = T; /*===BitPerm1===*/ S[1] = (S[1]&0xeeee)>>1 | (S[1]&0x1111)<<3; S[2] = (S[2]&0xcccc)>>2 | (S[2]&0x3333)<<2; S[3] = (S[3]&0x8888)>>3 | (S[3]&0x7777)<<1; /*========== round 2 ==========*/ /*R2===AddRoundKey===*/ S[0] ^= RK[8*step + 2]; S[1] ^= RK[8*step + 3]; S[3] ^= RC[4*step + 1]; /*===SubCells===*/ S[1] ^= S[0] & S[2]; S[0] ^= S[1] & S[3]; S[2] ^= S[0] | S[1]; S[3] ^= S[2]; S[1] ^= S[3]; S[3] ^= 0xffff; S[2] ^= S[0] & S[1]; T = S[0]; S[0] = S[3]; S[3] = T; /*===BitPerm2===*/ S[1] = (S[1]<<12) | (S[1]>> 4); S[2] = (S[2]<< 8) | (S[2]>> 8); S[3] = (S[3]<< 4) | (S[3]>>12); /*========== round 3 ==========*/ /*R3===AddRoundKey===*/ S[0] ^= RK[8*step + 4]; S[1] ^= RK[8*step + 5]; S[3] ^= RC[4*step + 2]; /*===SubCells===*/ S[1] ^= S[0] & S[2]; S[0] ^= S[1] & S[3]; S[2] ^= S[0] | S[1]; S[3] ^= S[2]; S[1] ^= S[3]; S[3] ^= 0xffff; S[2] ^= S[0] & S[1]; T = S[0]; S[0] = S[3]; S[3] = T; /*===BitPerm3===*/ S[1] = (S[1]&0x8888)>>3 | (S[1]&0x7777)<<1; S[2] = (S[2]&0xcccc)>>2 | (S[2]&0x3333)<<2; S[3] = (S[3]&0xeeee)>>1 | (S[3]&0x1111)<<3; /*========== round 4 ==========*/ /*R4===AddRoundKey===*/ S[0] ^= RK[8*step + 6]; S[1] ^= RK[8*step + 7]; S[3] ^= RC[4*step + 3]; /*===SubCells===*/ S[1] ^= S[0] & S[2]; S[0] ^= S[1] & S[3]; S[2] ^= S[0] | S[1]; S[3] ^= S[2]; S[1] ^= S[3]; S[3] ^= 0xffff; S[2] ^= S[0] & S[1]; T = S[0]; S[0] = S[3]; S[3] = T; /*===BitPerm4===*/ S[1] = (S[1]<< 4) | (S[1]>>12); S[2] = (S[2]<< 8) | (S[2]>> 8); S[3] = (S[3]<<12) | (S[3]>> 4); C[0] = S[0]; C[1] = S[1]; C[2] = S[2]; C[3] = S[3]; return;} void giftb64_4r_inv(uint16_t C[4], int step, const uint16_t *RK, uint16_t P[4]){ uint16_t S[4],T; S[0] = C[0]; S[1] = C[1]; S[2] = C[2]; S[3] = C[3]; /*fully unroll*/ /*========== round 4 ==========*/ /*===BitPerm4_inv===*/ S[1] = (S[1]<<12) | (S[1]>> 4); S[2] = (S[2]<< 8) | (S[2]>> 8); S[3] = (S[3]<< 4) | (S[3]>>12); /*===SubCells_inv===*/ T = S[3]; S[3] = S[0]; S[0] = T; S[2] ^= S[0] & S[1]; S[3] ^= 0xffff; S[1] ^= S[3]; S[3] ^= S[2]; S[2] ^= S[0] | S[1]; S[0] ^= S[1] & S[3]; S[1] ^= S[0] & S[2]; /*R4===AddRoundKey===*/ S[0] ^= RK[8*step + 6]; S[1] ^= RK[8*step + 7]; S[3] ^= RC[4*step + 3]; /*========== round 3 ==========*/ /*===BitPerm3_inv===*/ S[1] = (S[1]&0xeeee)>>1 | (S[1]&0x1111)<<3; S[2] = (S[2]&0xcccc)>>2 | (S[2]&0x3333)<<2; S[3] = (S[3]&0x8888)>>3 | (S[3]&0x7777)<<1; /*===SubCells_inv===*/ T = S[3]; S[3] = S[0]; S[0] = T; S[2] ^= S[0] & S[1]; S[3] ^= 0xffff; S[1] ^= S[3]; S[3] ^= S[2]; S[2] ^= S[0] | S[1]; S[0] ^= S[1] & S[3]; S[1] ^= S[0] & S[2]; /*R3===AddRoundKey===*/ S[0] ^= RK[8*step + 4]; S[1] ^= RK[8*step + 5]; S[3] ^= RC[4*step + 2]; /*========== round 2 ==========*/ /*===BitPerm2_inv===*/ S[1] = (S[1]<< 4) | (S[1]>>12); S[2] = (S[2]<< 8) | (S[2]>> 8); S[3] = (S[3]<<12) | (S[3]>> 4); /*===SubCells_inv===*/ T = S[3]; S[3] = S[0]; S[0] = T; S[2] ^= S[0] & S[1]; S[3] ^= 0xffff; S[1] ^= S[3]; S[3] ^= S[2]; S[2] ^= S[0] | S[1]; S[0] ^= S[1] & S[3]; S[1] ^= S[0] & S[2]; /*R2===AddRoundKey===*/ S[0] ^= RK[8*step + 2]; S[1] ^= RK[8*step + 3]; S[3] ^= RC[4*step + 1]; /*========== round 1 ==========*/ /*===BitPerm1_inv===*/ S[1] = (S[1]&0x8888)>>3 | (S[1]&0x7777)<<1; S[2] = (S[2]&0xcccc)>>2 | (S[2]&0x3333)<<2; S[3] = (S[3]&0xeeee)>>1 | (S[3]&0x1111)<<3; /*===SubCells_inv===*/ T = S[3]; S[3] = S[0]; S[0] = T; S[2] ^= S[0] & S[1]; S[3] ^= 0xffff; S[1] ^= S[3]; S[3] ^= S[2]; S[2] ^= S[0] | S[1]; S[0] ^= S[1] & S[3]; S[1] ^= S[0] & S[2]; /*R1===AddRoundKey===*/ S[0] ^= RK[8*step + 0]; S[1] ^= RK[8*step + 1]; S[3] ^= RC[4*step + 0]; P[0] = S[0]; P[1] = S[1]; P[2] = S[2]; P[3] = S[3]; return;} void TGIF_KS(const uint8_t K[16], int total_step, uint16_t *RK){ int i; uint32_t TK[4], tmp; TK[0] = (K[ 3]<<24) | (K[ 2]<<16) | (K[ 1]<<8) | K[ 0]; TK[1] = (K[ 7]<<24) | (K[ 6]<<16) | (K[ 5]<<8) | K[ 4]; TK[2] = (K[11]<<24) | (K[10]<<16) | (K[ 9]<<8) | K[ 8]; TK[3] = (K[15]<<24) | (K[14]<<16) | (K[13]<<8) | K[12]; for(i=0; i<total_step*4; i++){ RK[2*i + 0] = TK[0]; RK[2*i + 1] = (TK[0]>>16); tmp = TK[0] ^ TK[1] ^ ((TK[3]<<8)|(TK[3]>>24)) ^ 0x00000101; TK[0] = TK[1]; TK[1] = TK[2]; TK[2] = TK[3]; TK[3] = tmp; } return;} void left_rot(uint16_t S[4], int lrot){ uint16_t tmp; while(lrot>16){ tmp = S[0]; S[0] = S[1]; S[1] = S[2]; S[2] = S[3]; S[3] = tmp; lrot -= 16; } tmp = S[0]>>(16-lrot); S[0] = S[0]<<lrot | S[1]>>(16-lrot); S[1] = S[1]<<lrot | S[2]>>(16-lrot); S[2] = S[2]<<lrot | S[3]>>(16-lrot); S[3] = S[3]<<lrot | tmp; return;} void swap_branch(uint16_t A[4], uint16_t B[4]){ uint16_t tmp[4]; int i; for(i=0; i<4; i++){ tmp[i] = A[i]; A[i] = B[i]; B[i] = tmp[i]; } return;} void copy_branch(uint16_t A[4], uint16_t Acopy[4]){ int i; for(i=0; i<4; i++){ Acopy[i] = A[i]; } return;} void XOR_branch(uint16_t A[4], uint16_t BplusA[4]){ int i; for(i=0; i<4; i++){ BplusA[i] ^= A[i]; } return;} void TGIF(uint8_t P[16], int total_step, const uint16_t *RK, int LEFT_ROTATION, uint8_t C[16]){ uint16_t L[4], R[4], tmp[4]; int step; L[0] = P[ 1]<<8 | P[ 0]; L[1] = P[ 3]<<8 | P[ 2]; L[2] = P[ 5]<<8 | P[ 4]; L[3] = P[ 7]<<8 | P[ 6]; R[0] = P[ 9]<<8 | P[ 8]; R[1] = P[11]<<8 | P[10]; R[2] = P[13]<<8 | P[12]; R[3] = P[15]<<8 | P[14]; for(step=0; step<total_step; step++){ giftb64_4r(R,step,RK,R); copy_branch(L, tmp); left_rot(tmp, LEFT_ROTATION); XOR_branch(tmp,R); swap_branch(L,R); } C[ 0] = L[0]; C[ 1] = L[0]>>8; C[ 2] = L[1]; C[ 3] = L[1]>>8; C[ 4] = L[2]; C[ 5] = L[2]>>8; C[ 6] = L[3]; C[ 7] = L[3]>>8; C[ 8] = R[0]; C[ 9] = R[0]>>8; C[10] = R[1]; C[11] = R[1]>>8; C[12] = R[2]; C[13] = R[2]>>8; C[14] = R[3]; C[15] = R[3]>>8; return;} void TGIF_inv(uint8_t C[16], int total_step, const uint16_t *RK, int LEFT_ROTATION, uint8_t P[16]){ uint16_t L[4], R[4], tmp[4]; int step; L[0] = C[ 1]<<8 | C[ 0]; L[1] = C[ 3]<<8 | C[ 2]; L[2] = C[ 5]<<8 | C[ 4]; L[3] = C[ 7]<<8 | C[ 6]; R[0] = C[ 9]<<8 | C[ 8]; R[1] = C[11]<<8 | C[10]; R[2] = C[13]<<8 | C[12]; R[3] = C[15]<<8 | C[14]; for(step=total_step-1; step>=0; step--){ swap_branch(L,R); copy_branch(L, tmp); left_rot(tmp, LEFT_ROTATION); XOR_branch(tmp,R); giftb64_4r_inv(R,step,RK,R); } P[ 0] = L[0]; P[ 1] = L[0]>>8; P[ 2] = L[1]; P[ 3] = L[1]>>8; P[ 4] = L[2]; P[ 5] = L[2]>>8; P[ 6] = L[3]; P[ 7] = L[3]>>8; P[ 8] = R[0]; P[ 9] = R[0]>>8; P[10] = R[1]; P[11] = R[1]>>8; P[12] = R[2]; P[13] = R[2]>>8; P[14] = R[3]; P[15] = R[3]>>8; return;} void TGIF_BC(uint8_t P[16], const uint8_t K[16], uint8_t C[16], int encryption){ int total_step=18; int left_rotation = 55; uint16_t RK[18*8] = {}; TGIF_KS(K,total_step,RK); if(encryption) TGIF(P,total_step,RK,left_rotation,C); else TGIF_inv(C,total_step,RK,left_rotation,P); return;} void block_cipher (unsigned char* input, const unsigned char* userkey){ uint8_t P[16],C[16],K[16]; int i; for(i=0;i<16;i++) { P[i] = input[i]; K[i] = userkey[i]; } TGIF_BC(P,K,C,1); for(i=0;i<16;i++) { input[i] = C[i]; } };
coderfi/toychain-cpp
Block.h
#ifndef TOYCHAIN_BLOCK_H #define TOYCHAIN_BLOCK_H #include <cstdint> #include <iostream> #include <sstream> using namespace std; class Block { private: string _sData; uint32_t _nIdx; uint32_t _nNonce; time_t _tTime; string _hash() const; public: string sHash; string sHashPrev; Block(uint32_t nIdxIn, const string &sDataIn, time_t tTimestampIn); Block(uint32_t nIdxIn, const string &sDataIn); void mine(uint32_t nDifficulty); }; #endif //TOYCHAIN_BLOCK_H
Gkdnz/SfePy
sfepy/terms/extmods/terms_elastic.c
<filename>sfepy/terms/extmods/terms_elastic.c #include "form_sdcc.h" #include "terms_elastic.h" #include "terms.h" #undef __FUNC__ #define __FUNC__ "mat_le_stress" /*! In mixed case, builds only the deviatoric part of stress. @par Revision history: - 17.03.2003, c - 31.01.2006 - 06.02.2006 - 07.03.2006, adopted from mafest1 */ int32 mat_le_stress( FMField *stress, FMField *strain, FMField *lam, FMField *mu ) { int32 iell, iqp; int32 sym, nQP; float64 *pstress, *pstrain; float64 _lam, _mu, mu23, mu43, l2m; nQP = stress->nLev; sym = stress->nRow; if (sym == 6) { for (iell = 0; iell < stress->nCell; iell++) { FMF_SetCell( lam, iell ); FMF_SetCell( mu, iell ); pstress = FMF_PtrCell( stress, iell ); pstrain = FMF_PtrCell( strain, iell ); if (1) { for (iqp = 0; iqp < nQP; iqp++) { _lam = lam->val[iqp]; _mu = mu->val[iqp]; l2m = 2.0 * _mu + _lam; pstress[0] = l2m * pstrain[0] + _lam * (pstrain[1] + pstrain[2]); pstress[1] = l2m * pstrain[1] + _lam * (pstrain[0] + pstrain[2]); pstress[2] = l2m * pstrain[2] + _lam * (pstrain[0] + pstrain[1]); pstress[3] = _mu * pstrain[3]; pstress[4] = _mu * pstrain[4]; pstress[5] = _mu * pstrain[5]; pstress += sym; pstrain += sym; } } else { for (iqp = 0; iqp < nQP; iqp++) { _lam = lam->val[iqp]; _mu = mu->val[iqp]; mu23 = _mu * (2.0/3.0); mu43 = 2.0 * mu23; pstress[0] = mu43 * pstrain[0] - mu23 * (pstrain[1] + pstrain[2]); pstress[1] = mu43 * pstrain[1] - mu23 * (pstrain[0] + pstrain[2]); pstress[2] = mu43 * pstrain[2] - mu23 * (pstrain[0] + pstrain[1]); pstress[3] = _mu * pstrain[3]; pstress[4] = _mu * pstrain[4]; pstress[5] = _mu * pstrain[5]; pstress += sym; pstrain += sym; } } } } else if (sym == 3) { for (iell = 0; iell < stress->nCell; iell++) { FMF_SetCell( lam, iell ); FMF_SetCell( mu, iell ); pstress = FMF_PtrCell( stress, iell ); pstrain = FMF_PtrCell( strain, iell ); if (1) { for (iqp = 0; iqp < nQP; iqp++) { _lam = lam->val[iqp]; _mu = mu->val[iqp]; l2m = 2.0 * _mu + _lam; pstress[0] = l2m * pstrain[0] + _lam * (pstrain[1]); pstress[1] = l2m * pstrain[1] + _lam * (pstrain[0]); pstress[2] = _mu * pstrain[2]; pstress += sym; pstrain += sym; } } else { for (iqp = 0; iqp < nQP; iqp++) { _lam = lam->val[iqp]; _mu = mu->val[iqp]; mu23 = _mu * (2.0/3.0); mu43 = 2.0 * mu23; pstress[0] = mu43 * pstrain[0] - mu23 * pstrain[1]; pstress[1] = mu43 * pstrain[1] - mu23 * pstrain[0]; pstress[2] = _mu * pstrain[2]; pstress += sym; pstrain += sym; } } } } return( RET_OK ); } #undef __FUNC__ #define __FUNC__ "dw_lin_elastic" /*! @par Revision history: - 03.08.2006, c - 29.11.2006 */ int32 dw_lin_elastic( FMField *out, float64 coef, FMField *strain, FMField *mtxD, Mapping *vg, int32 isDiff ) { int32 ii, dim, sym, nQP, nEP, ret = RET_OK; FMField *stress = 0; FMField *res = 0, *gtd = 0, *gtdg = 0; nQP = vg->bfGM->nLev; nEP = vg->bfGM->nCol; dim = vg->bfGM->nRow; sym = (dim + 1) * dim / 2; /* fmf_print( mtxD, stdout, 0 ); */ /* output( "%d %d %d %d %d %d\n", offset, nEl, nEP, nQP, dim, elList_nRow ); */ if (isDiff) { fmf_createAlloc( &gtd, 1, nQP, nEP * dim, sym ); fmf_createAlloc( &gtdg, 1, nQP, nEP * dim, nEP * dim ); for (ii = 0; ii < out->nCell; ii++) { FMF_SetCell( out, ii ); FMF_SetCell( mtxD, ii ); FMF_SetCell( vg->bfGM, ii ); FMF_SetCell( vg->det, ii ); form_sdcc_actOpGT_M3( gtd, vg->bfGM, mtxD ); form_sdcc_actOpG_RM3( gtdg, gtd, vg->bfGM ); fmf_sumLevelsMulF( out, gtdg, vg->det->val ); ERR_CheckGo( ret ); } } else { fmf_createAlloc( &stress, 1, nQP, sym, 1 ); fmf_createAlloc( &res, 1, nQP, dim * nEP, 1 ); for (ii = 0; ii < out->nCell; ii++) { FMF_SetCell( out, ii ); FMF_SetCell( mtxD, ii ); FMF_SetCell( vg->bfGM, ii ); FMF_SetCell( vg->det, ii ); FMF_SetCell( strain, ii ); fmf_mulAB_nn( stress, mtxD, strain ); form_sdcc_actOpGT_VS3( res, vg->bfGM, stress ); fmf_sumLevelsMulF( out, res, vg->det->val ); ERR_CheckGo( ret ); } } // E.g. 1/dt. fmfc_mulC( out, coef ); end_label: if (isDiff) { fmf_freeDestroy( &gtd ); fmf_freeDestroy( &gtdg ); } else { fmf_freeDestroy( &res ); fmf_freeDestroy( &stress ); } return( ret ); } #undef __FUNC__ #define __FUNC__ "d_lin_elastic" /*! @par Revision history: - 02.03.2007, c */ int32 d_lin_elastic( FMField *out, float64 coef, FMField *strainV, FMField *strainU, FMField *mtxD, Mapping *vg ) { int32 ii, sym, nQP, ret = RET_OK; FMField *std = 0, *stds = 0; nQP = vg->bfGM->nLev; sym = mtxD->nRow; fmf_createAlloc( &std, 1, nQP, 1, sym ); fmf_createAlloc( &stds, 1, nQP, 1, 1 ); for (ii = 0; ii < out->nCell; ii++) { FMF_SetCell( out, ii ); FMF_SetCell( mtxD, ii ); FMF_SetCell( vg->det, ii ); FMF_SetCell( strainV, ii ); FMF_SetCell( strainU, ii ); fmf_mulATB_nn( std, strainV, mtxD ); fmf_mulAB_nn( stds, std, strainU ); fmf_sumLevelsMulF( out, stds, vg->det->val ); ERR_CheckGo( ret ); } // E.g. 1/dt. fmfc_mulC( out, coef ); end_label: fmf_freeDestroy( &std ); fmf_freeDestroy( &stds ); return( ret ); } #undef __FUNC__ #define __FUNC__ "d_sd_lin_elastic" int32 d_sd_lin_elastic(FMField *out, float64 coef, FMField *gradV, FMField *gradU, FMField *gradW, FMField *mtxD, Mapping *vg) { int32 ii, i, j, iqp, dim, dim2, nQP, nEL, ret = RET_OK; float64 *pD, *pDf, *pw, *pw2, *divw; FMField *std = 0, *stds = 0, *mtxDf = 0, *dgw = 0, *divw0 = 0; FMField gradu[1], gradv[1]; int32 dtab_2d[4] = {0, 2, 2, 1}, dtab_3d[9] = {0, 3, 4, 3, 1, 5, 4, 5, 2}; nEL = out->nCell; nQP = vg->bfGM->nLev; dim = vg->bfGM->nRow; dim2 = dim * dim; fmf_createAlloc(&std, 1, nQP, 1, dim2); fmf_createAlloc(&stds, 1, nQP, 1, 1); fmf_createAlloc(&dgw, 1, nQP, dim2, dim2); fmf_createAlloc(&mtxDf, 1, nQP, dim2, dim2); fmf_createAlloc(&divw0, 1, 1, vg->bfGM->nLev, 1); divw = divw0->val0; gradv->nAlloc = -1; fmf_pretend(gradv, nEL, nQP, dim2, 1, gradV->val0); gradu->nAlloc = -1; fmf_pretend(gradu, nEL, nQP, dim2, 1, gradU->val0); for (ii = 0; ii < nEL; ii++) { FMF_SetCell(out, ii); FMF_SetCell(mtxD, ii); FMF_SetCell(vg->det, ii); FMF_SetCell(gradv, ii); FMF_SetCell(gradu, ii); FMF_SetCell(gradW, ii); if (dim == 2) { for (iqp = 0; iqp < nQP; iqp++) { pDf = FMF_PtrLevel(mtxDf, iqp); pw = FMF_PtrLevel(gradW, iqp); pw2 = FMF_PtrLevel(dgw, iqp); divw[iqp] = pw[0] + pw[3]; for (j = 0; j < dim2; j++) { pD = FMF_PtrLevel(mtxD, iqp) + dtab_2d[j] * 3; pDf[0] = pD[0]; pDf[1] = pD[2]; pDf[2] = pD[2]; pDf[3] = pD[1]; pw2[0] = pDf[0] * pw[0] + pDf[1] * pw[2]; pw2[2] = pDf[0] * pw[1] + pDf[1] * pw[3]; pw2[1] = pDf[2] * pw[0] + pDf[3] * pw[2]; pw2[3] = pDf[2] * pw[1] + pDf[3] * pw[3]; pDf += dim2; pw2 += dim2; } // for (j) } // for (iqp) } else { for (iqp = 0; iqp < nQP; iqp++) { pDf = FMF_PtrLevel(mtxDf, iqp); pw = FMF_PtrLevel(gradW, iqp); pw2 = FMF_PtrLevel(dgw, iqp); divw[iqp] = pw[0] + pw[4] + pw[8]; for (j = 0; j < dim2; j++) { pD = FMF_PtrLevel(mtxD, iqp) + dtab_3d[j] * 6; pDf[0] = pD[0]; pDf[1] = pD[3]; pDf[2] = pD[4]; pDf[3] = pD[3]; pDf[4] = pD[1]; pDf[5] = pD[5]; pDf[6] = pD[4]; pDf[7] = pD[5]; pDf[8] = pD[2]; pw2[0] = pDf[0] * pw[0] + pDf[1] * pw[3] + pDf[2] * pw[6]; pw2[3] = pDf[0] * pw[1] + pDf[1] * pw[4] + pDf[2] * pw[7]; pw2[6] = pDf[0] * pw[2] + pDf[1] * pw[5] + pDf[2] * pw[8]; pw2[1] = pDf[3] * pw[0] + pDf[4] * pw[3] + pDf[5] * pw[6]; pw2[4] = pDf[3] * pw[1] + pDf[4] * pw[4] + pDf[5] * pw[7]; pw2[7] = pDf[3] * pw[2] + pDf[4] * pw[5] + pDf[5] * pw[8]; pw2[2] = pDf[6] * pw[0] + pDf[7] * pw[3] + pDf[8] * pw[6]; pw2[5] = pDf[6] * pw[1] + pDf[7] * pw[4] + pDf[8] * pw[7]; pw2[8] = pDf[6] * pw[2] + pDf[7] * pw[5] + pDf[8] * pw[8]; pDf += dim2; pw2 += dim2; } // for (j) } // for (iqp) } for (iqp = 0; iqp < nQP; iqp++) { pD = FMF_PtrLevel(mtxDf, iqp); pw = FMF_PtrLevel(dgw, iqp); pw2 = FMF_PtrLevel(dgw, iqp); for (i = 0; i < dim2; i++) { for (j = 0; j < dim2; j++) { pD[j] = pD[j] * divw[iqp] - pw[j] - pw2[j * dim2]; } // for (j) pD += dim2; pw += dim2; pw2 += 1; } // for (i) } // for (iqp) fmf_mulATB_nn(std, gradv, mtxDf); fmf_mulAB_nn(stds, std, gradu); fmf_sumLevelsMulF(out, stds, vg->det->val); ERR_CheckGo(ret); } // E.g. 1/dt. fmfc_mulC(out, coef); end_label: fmf_freeDestroy(&std); fmf_freeDestroy(&stds); fmf_freeDestroy(&dgw); fmf_freeDestroy(&mtxDf); fmf_freeDestroy(&divw0); return(ret); } #undef __FUNC__ #define __FUNC__ "dw_lin_prestress" int32 dw_lin_prestress( FMField *out, FMField *stress, Mapping *vg ) { int32 ii, dim, nQP, nEP, ret = RET_OK; FMField *res = 0; nQP = vg->bfGM->nLev; nEP = vg->bfGM->nCol; dim = vg->bfGM->nRow; fmf_createAlloc( &res, 1, nQP, dim * nEP, 1 ); for (ii = 0; ii < out->nCell; ii++) { FMF_SetCell( out, ii ); FMF_SetCell( vg->bfGM, ii ); FMF_SetCell( vg->det, ii ); FMF_SetCell( stress, ii ); form_sdcc_actOpGT_VS3( res, vg->bfGM, stress ); fmf_sumLevelsMulF( out, res, vg->det->val ); ERR_CheckGo( ret ); } end_label: fmf_freeDestroy( &res ); return( ret ); } #undef __FUNC__ #define __FUNC__ "dw_lin_strain_fib" int32 dw_lin_strain_fib( FMField *out, FMField *mtxD, FMField *mat, Mapping *vg ) { int32 ii, dim, sym, nQP, nEP, ret = RET_OK; FMField *aux1 = 0, *aux2 = 0; nQP = vg->bfGM->nLev; nEP = vg->bfGM->nCol; dim = vg->bfGM->nRow; sym = (dim + 1) * dim / 2; fmf_createAlloc( &aux1, 1, nQP, nEP * dim, sym ); fmf_createAlloc( &aux2, 1, nQP, nEP * dim, 1 ); for (ii = 0; ii < out->nCell; ii++) { FMF_SetCell( out, ii ); FMF_SetCell( mtxD, ii ); FMF_SetCell( mat, ii ); FMF_SetCell( vg->bfGM, ii ); FMF_SetCell( vg->det, ii ); form_sdcc_actOpGT_M3( aux1, vg->bfGM, mtxD ); fmf_mulAB_nn( aux2, aux1, mat ); fmf_sumLevelsMulF( out, aux2, vg->det->val ); ERR_CheckGo( ret ); } end_label: fmf_freeDestroy( &aux1 ); fmf_freeDestroy( &aux2 ); return( ret ); } #undef __FUNC__ #define __FUNC__ "de_cauchy_strain" /*! @par Revision history: - 21.09.2006, c */ int32 de_cauchy_strain( FMField *out, FMField *strain, Mapping *vg, int32 mode ) { int32 ii, ret = RET_OK; for (ii = 0; ii < out->nCell; ii++) { FMF_SetCell( out, ii ); FMF_SetCell( strain, ii ); FMF_SetCell( vg->det, ii ); fmf_sumLevelsMulF( out, strain, vg->det->val ); if (mode == 1) { FMF_SetCell( vg->volume, ii ); fmf_mulC( out, 1.0 / vg->volume->val[0] ); } ERR_CheckGo( ret ); } end_label: return( ret ); } #undef __FUNC__ #define __FUNC__ "de_cauchy_stress" /*! @par Revision history: - c: 25.03.2008 */ int32 de_cauchy_stress( FMField *out, FMField *strain, FMField *mtxD, Mapping *vg, int32 mode ) { int32 ii, dim, sym, nQP, ret = RET_OK; FMField *stress = 0; nQP = vg->bfGM->nLev; dim = vg->bfGM->nRow; sym = (dim + 1) * dim / 2; fmf_createAlloc( &stress, 1, nQP, sym, 1 ); for (ii = 0; ii < out->nCell; ii++) { FMF_SetCell( out, ii ); FMF_SetCell( mtxD, ii ); FMF_SetCell( strain, ii ); FMF_SetCell( vg->det, ii ); fmf_mulAB_nn( stress, mtxD, strain ); fmf_sumLevelsMulF( out, stress, vg->det->val ); if (mode == 1) { FMF_SetCell( vg->volume, ii ); fmf_mulC( out, 1.0 / vg->volume->val[0] ); } ERR_CheckGo( ret ); } end_label: fmf_freeDestroy( &stress ); return( ret ); } #undef __FUNC__ #define __FUNC__ "dq_cauchy_strain" /*! @par Revision history: - 30.07.2007, from dw_hdpm_cache() */ int32 dq_cauchy_strain( FMField *out, FMField *state, int32 offset, Mapping *vg, int32 *conn, int32 nEl, int32 nEP ) { int32 ii, dim, nQP, ret = RET_OK; FMField *st = 0, *disG = 0; state->val = FMF_PtrFirst( state ) + offset; nQP = vg->bfGM->nLev; dim = vg->bfGM->nRow; fmf_createAlloc( &st, 1, 1, nEP, dim ); fmf_createAlloc( &disG, 1, nQP, dim, dim ); for (ii = 0; ii < nEl; ii++) { FMF_SetCell( out, ii ); FMF_SetCell( vg->bfGM, ii ); ele_extractNodalValuesNBN( st, state, conn + nEP * ii ); fmf_mulAB_n1( disG, vg->bfGM, st ); form_sdcc_strainCauchy_VS( out, disG ); /* fmf_print( out, stdout, 0 ); */ /* sys_pause(); */ ERR_CheckGo( ret ); } end_label: fmf_freeDestroy( &st ); fmf_freeDestroy( &disG ); return( ret ); }
Gkdnz/SfePy
sfepy/terms/extmods/terms_op.h
#ifndef _TERMS_OP_H_ #define _TERMS_OP_H_ #include "common.h" BEGIN_C_DECLS #include "fmfield.h" #include "refmaps.h" int32 mulAB_integrate(FMField *out, FMField *A, FMField *B, Mapping *vg, int32 mode); int32 actBfT(FMField *out, FMField *bf, FMField *A); END_C_DECLS #endif /* Header */
Gkdnz/SfePy
sfepy/discrete/common/extmods/common_python.c
#include <stdarg.h> #include "common.h" int32 g_error = 0; static char buf[1024]; /* !!! */ #undef __FUNC__ #define __FUNC__ "output" /*! @par Revision history: - 16.02.2004, c */ void output(const char *what, ...) { va_list ap; va_start(ap, what); vprintf(what, ap); va_end(ap); } #undef __FUNC__ #define __FUNC__ "errput" /*! @par Revision history: - 16.02.2004, c - 20.02.2004 - 26.10.2005 */ void errput(const char *what, ...) { va_list ap; snprintf(buf, 1020, "**ERROR** -> %s", what); va_start(ap, what); vprintf(what, ap); va_end(ap); PyErr_SetString(PyExc_RuntimeError, "ccore error (see above)"); g_error++; } void errset(const char *msg) { PyErr_SetString(PyExc_RuntimeError, msg); g_error++; } #undef __FUNC__ #define __FUNC__ "errclear" /*! @par Revision history: - 07.06.2006, c */ void errclear() { g_error = 0; } /*! @par Revision history: - 17.02.2005, from rcfem2 */ static size_t al_curUsage; static size_t al_maxUsage; static size_t al_frags; static AllocSpace *al_head = 0; size_t mem_get_cur_usage(void) { return al_curUsage; } size_t mem_get_max_usage(void) { return al_maxUsage; } size_t mem_get_n_frags(void) { return al_frags; } void mem_list_new(char *p, size_t size, AllocSpace *al_head, int lineNo, char *funName, char *fileName, char *dirName) { float64 *endptr; size_t hsize = sizeof(AllocSpaceAlign); AllocSpace *head = (AllocSpace *) (p - hsize); if (al_head) al_head->prev = head; head->next = al_head; al_head = head; head->prev = 0; head->size = size; head->id = 1234567; head->lineNo = lineNo; head->fileName = fileName; head->funName = funName; head->dirName = dirName; head->cookie = AL_CookieValue; endptr = (float64 *) (p + size); endptr[0] = (float64) AL_CookieValue; } void mem_list_remove(AllocSpace *head, AllocSpace *al_head) { if (head->prev) head->prev->next = head->next; else al_head = head->next; if (head->next) head->next->prev = head->prev; } int32 mem_check_ptr(char *p, int lineNo, char *funName, char *fileName, char *dirName) { int32 ret = RET_OK; float64 *endptr; size_t hsize = sizeof(AllocSpaceAlign); AllocSpace *head = (AllocSpace *) (p - hsize); if (head->cookie != AL_CookieValue) { errput("%s, %s, %s, %d: ptr: %p, cookie: %d\n", dirName, fileName, funName, lineNo, p, head->cookie); if (head->cookie == AL_AlreadyFreed) { errput("memory was already freed!\n"); } ERR_CheckGo(ret); } endptr = (float64 *) (p + head->size); if (endptr[0] != AL_CookieValue) { errput("%s %s %s %d:\n", dirName, fileName, funName, lineNo); if (endptr[0] == AL_AlreadyFreed) { errput("already freed!\n"); } else { errput("damaged tail!\n"); } ERR_CheckGo(ret); } end_label: return(ret); } #undef __FUNC__ #define __FUNC__ "mem_alloc_mem" /*! @par Revision history: - 17.02.2005, from rcfem2 */ void *mem_alloc_mem(size_t size, int lineNo, char *funName, char *fileName, char *dirName) { char *p; size_t hsize = sizeof(AllocSpaceAlign); size_t tsize, aux; if (size == 0) { errput("%s, %s, %s, %d: zero allocation!\n", dirName, fileName, funName, lineNo); ERR_GotoEnd(1); } aux = size % sizeof(float64); size += (aux) ? sizeof(float64) - aux : 0; tsize = size + hsize + sizeof(float64); if ((p = (char *) PyMem_Malloc(tsize)) == 0) { errput("%s, %s, %s, %d: error allocating %zu bytes (current: %zu).\n", dirName, fileName, funName, lineNo, size, al_curUsage); ERR_GotoEnd(1); } p += hsize; mem_list_new(p, size, al_head, lineNo, funName, fileName, dirName); al_curUsage += size; if (al_curUsage > al_maxUsage) { al_maxUsage = al_curUsage; } al_frags++; memset(p, 0, size); return((void *) p); end_label: if (ERR_Chk) { errput(ErrHead "error exit!\n"); } return(0); } #undef __FUNC__ #define __FUNC__ "mem_realloc_mem" void *mem_realloc_mem(void *pp, size_t size, int lineNo, char *funName, char *fileName, char *dirName) { char *p = (char *) pp; size_t hsize = sizeof(AllocSpaceAlign); size_t tsize, aux; float64 *endptr; AllocSpace *head; char *phead; if (p == 0) return(0); if (size == 0) { errput("%s, %s, %s, %d: zero allocation!\n", dirName, fileName, funName, lineNo); ERR_GotoEnd(1); } // 1. almost as mem_free_mem(). mem_check_ptr(p, lineNo, funName, fileName, dirName); if (ERR_Chk) { ERR_GotoEnd(1); } phead = p - hsize; head = (AllocSpace *) phead; head->cookie = AL_AlreadyFreed; endptr = (float64 *) (p + head->size); endptr[0] = (float64) AL_AlreadyFreed; al_curUsage -= head->size; al_frags--; mem_list_remove(head, al_head); // 2. realloc. aux = size % sizeof(float64); size += (aux) ? sizeof(float64) - aux : 0; tsize = size + hsize + sizeof(float64); if ((p = (char *) PyMem_Realloc(phead, tsize)) == 0) { errput("%s, %s, %s, %d: error re-allocating to %zu bytes (current: %zu).\n", dirName, fileName, funName, lineNo, size, al_curUsage); ERR_GotoEnd(1); } // 3. almost as mem_alloc_mem(). p += hsize; mem_list_new(p, size, al_head, lineNo, funName, fileName, dirName); al_curUsage += size; if (al_curUsage > al_maxUsage) { al_maxUsage = al_curUsage; } al_frags++; return((void *) p); end_label: if (ERR_Chk) { errput(ErrHead "error exit!\n"); } return(0); } #undef __FUNC__ #define __FUNC__ "mem_free_mem" /*! @par Revision history: - 17.02.2005, from rcfem2 */ void mem_free_mem(void *pp, int lineNo, char *funName, char *fileName, char *dirName) { char *p = (char *) pp; size_t hsize = sizeof(AllocSpaceAlign); float64 *endptr; AllocSpace *head; char *phead; if (p == 0) return; mem_check_ptr(p, lineNo, funName, fileName, dirName); if (ERR_Chk) { ERR_GotoEnd(1); } phead = p - hsize; head = (AllocSpace *) phead; head->cookie = AL_AlreadyFreed; endptr = (float64 *) (p + head->size); endptr[0] = (float64) AL_AlreadyFreed; al_curUsage -= head->size; al_frags--; mem_list_remove(head, al_head); PyMem_Free(phead); return; end_label: if (ERR_Chk) { errput(ErrHead "error exit!\n"); } } #undef __FUNC__ #define __FUNC__ "pyalloc" void *pyalloc(size_t size) { return mem_alloc_mem(size, __LINE__, __FUNC__, __FILE__, __SDIR__); } #undef __FUNC__ #define __FUNC__ "pyfree" void pyfree(void *pp) { return mem_free_mem(pp, __LINE__, __FUNC__, __FILE__, __SDIR__); } #undef __FUNC__ #define __FUNC__ "mem_checkIntegrity" /*! @par Revision history: - 17.02.2005, from rcfem2 */ void mem_checkIntegrity(int lineNo, char *funName, char *fileName, char *dirName) { char *p, *pp; size_t cnt, allocated; size_t hsize = sizeof(AllocSpaceAlign); float64 *endptr; AllocSpace *head = al_head; output("checking memory integrity in\n"); output("%s, %s, %s(), %d:\n", dirName, fileName, funName, lineNo, al_maxUsage, al_curUsage); output("allocated memory: %zu records, usage: %zu, max: %zu\n", al_frags, al_curUsage, al_maxUsage); if (head == 0) { goto end_label_ok; } cnt = 0; allocated = 0; while (head) { p = (char *) head; pp = p + hsize; if (head->cookie != AL_CookieValue) { errput("ptr: %p, ptrhead: %p, cookie: %d\n", pp, p , head->cookie); if (head->cookie == AL_AlreadyFreed) { errput("memory was already freed!\n"); } ERR_GotoEnd(1); } endptr = (float64 *) (pp + head->size); if (endptr[0] != AL_CookieValue) { output(" %s, %s, %s, %d: size: %zu, ptr: %p\n", head->dirName, head->fileName, head->funName, head->lineNo, head->size, pp); if (endptr[0] == AL_AlreadyFreed) { errput("already freed!\n"); } else { errput("damaged tail!\n"); } ERR_GotoEnd(1); } cnt++; allocated += head->size; if (cnt > al_frags) { errput("damaged allocation record (overrun)!\n"); ERR_GotoEnd(1); } head = head->next; } if (cnt < al_frags) { errput("damaged allocation record (underrun)!\n"); ERR_GotoEnd(1); } if (allocated != al_curUsage) { errput("memory leak!? (%zu == %zu)\n", allocated, al_curUsage); ERR_GotoEnd(1); } end_label_ok: output("memory OK.\n"); return; end_label: if (ERR_Chk) { errput(ErrHead "error exit!\n"); } } #undef __FUNC__ #define __FUNC__ "mem_statistics" /*! Prints memory usage statistics. @par Revision history: - 17.02.2005, from rcfem2 */ void mem_statistics(int lineNo, char *funName, char *fileName, char *dirName) { output("%s, %s, %s(), %d: memory max: %zu, current: %zu\n", dirName, fileName, funName, lineNo, al_maxUsage, al_curUsage); } #undef __FUNC__ #define __FUNC__ "mem_print" /*! Prints memory usage statistics. @par Revision history: - 17.02.2005, from rcfem2 - 06.10.2005 */ int32 mem_print(FILE *file, int32 mode) { size_t cnt = 0; size_t hsize = sizeof(AllocSpaceAlign); AllocSpace *head = al_head; char *p; mode = 0; fprintf(file, "allocated memory: %zu records, usage: %zu, max: %zu\n", al_frags, al_curUsage, al_maxUsage); if (head == 0) { goto end_label_ok; } while (head) { p = (char *) head; fprintf(file, " %s, %s, %s, %d: size: %zu, ptr: %p\n", head->dirName, head->fileName, head->funName, head->lineNo, head->size, p + hsize); cnt++; if (cnt > al_frags) { errput("damaged allocation record (overrun)!\n"); ERR_GotoEnd(1); } head = head->next; } if (cnt < al_frags) { errput("damaged allocation record (underrun)!\n"); ERR_GotoEnd(1); } end_label_ok: fprintf(file, "done.\n"); return(RET_OK); end_label: if (ERR_Chk) { errput(ErrHead "error exit!\n"); } return(RET_Fail); } #undef __FUNC__ #define __FUNC__ "mem_printSome" /*! Prints memory usage statistics. @par Revision history: - 17.02.2005, from rcfem2 - 06.10.2005 */ int32 mem_printSome(FILE *file, int32 mode, int32 num) { size_t cnt = 0; size_t hsize = sizeof(AllocSpaceAlign); AllocSpace *head = al_head; char *p; mode = 0; fprintf(file, "allocated memory: %zu records, usage: %zu, max: %zu\n", al_frags, al_curUsage, al_maxUsage); fprintf(file, "printing max: %d\n", num); if (head == 0) { goto end_label_ok; } while (head) { p = (char *) head; fprintf(file, " %s, %s, %s, %d: size: %zu, ptr: %p\n", head->dirName, head->fileName, head->funName, head->lineNo, head->size, p + hsize); cnt++; if (cnt > al_frags) { errput("damaged allocation record (overrun)!\n"); ERR_GotoEnd(1); } if (cnt == num) break; head = head->next; } end_label_ok: fprintf(file, "done.\n"); return(RET_OK); end_label: if (ERR_Chk) { errput(ErrHead "error exit!\n"); } return(RET_Fail); } #undef __FUNC__ #define __FUNC__ "mem_freeGarbage" /*! Free all memory records. @par Revision history: - 17.02.2005, from rcfem2 */ int32 mem_freeGarbage() { size_t cnt = 0, frags = al_frags; size_t hsize = sizeof(AllocSpaceAlign); char *p; output("freeing garbage.\n"); while (al_head) { p = (char *) al_head + hsize; free_mem(p); cnt++; if (cnt > frags) { errput("damaged allocation record (overrun)!\n"); ERR_GotoEnd(1); } } if (cnt < frags) { errput("damaged allocation record (underrun)!\n"); ERR_GotoEnd(1); } return(RET_OK); end_label: if (ERR_Chk) { errput(ErrHead "error exit!\n"); } return(RET_Fail); } #if SFEPY_PLATFORM == 0 #include <termios.h> /* tcgetattr(), tcsetattr() */ #include <unistd.h> /* read() */ #endif #undef __FUNC__ #define __FUNC__ "sys_getch" /*! @par Revision history: - 21.05.2002, c */ int sys_getch(void) { char ch = 0; #if SFEPY_PLATFORM == 0 if (read (STDERR_FILENO, &ch, 1) < 0) { return(RET_Fail); } #endif return(ch); } #if SFEPY_PLATFORM == 0 static struct termios term; #endif #undef __FUNC__ #define __FUNC__ "sys_keyboardEnableRaw" /*! Set keyboard to raw mode so getch will work @par Revision history: - 21.05.2002, c */ void sys_keyboardEnableRaw() { #if SFEPY_PLATFORM == 0 // set to non canonical mode, echo off, ignore signals struct termios current; // save current terminal settings tcgetattr (STDERR_FILENO, &current); // set to non canonical mode, echo off, ignore signals term = current; current.c_lflag &= ~(ECHO | ICANON | IEXTEN); current.c_cc[VMIN] = 1; current.c_cc[VTIME] = 0; tcsetattr (STDERR_FILENO, TCSAFLUSH, &current); #endif } #undef __FUNC__ #define __FUNC__ "sys_keyboardDisableRaw" /*! @par Revision history: - 21.05.2002, c */ void sys_keyboardDisableRaw() { #if SFEPY_PLATFORM == 0 // Restore old terminal settings tcsetattr (STDERR_FILENO, TCSAFLUSH, &term); #endif } #undef __FUNC__ #define __FUNC__ "sys_pause()" /*! @par Revision history: - 18.02.2005, c - 28.11.2005 */ void sys_pause() { sys_keyboardEnableRaw(); if (sys_getch() == 'q') { sys_keyboardDisableRaw(); exit(1); } sys_keyboardDisableRaw(); }
Gkdnz/SfePy
sfepy/discrete/common/extmods/mesh.h
<filename>sfepy/discrete/common/extmods/mesh.h #ifndef _MESH_H_ #define _MESH_H_ 1 #ifdef __cplusplus # define BEGIN_C_DECLS extern "C" { # define END_C_DECLS } #else # define BEGIN_C_DECLS # define END_C_DECLS #endif #include "types.h" #include "version.h" // Inspired by <NAME>: Efficient Representation of Computational Meshes. // Entity, dimension, codimension. Max. dimension is D. #define Vertex 0 // 0, D #define Edge 1 // 1, D - 1 #define Face 2 // 2, D - 2 #define Cell 3 // D, 0 #define Facet 4 // D - 1, 1 // Special uint32 values meaning "not set". #define UINT32_None -1 // Pointer to indices + number of items. typedef struct Indices { uint32 *indices; uint32 num; } Indices; // Pointer to mask + number of items. typedef struct Mask { char *mask; uint32 num; uint32 n_true; } Mask; typedef struct MeshGeometry { uint32 num; uint32 dim; float64 *coors; // Shape: (num, dim) by rows. } MeshGeometry; typedef struct MeshConnectivity { uint32 num; // MeshTopology->num[i] - number of entities. uint32 n_incident; // Total number of incident entities. uint32 *indices; // Length: n_incident. uint32 *offsets; // Length: MeshTopology->num[i] + 1. } MeshConnectivity; // Connectivity defines incidence. // conn[IJ[d1, d2]] are entities of dimension d2 incident to entities of // dimension d1. // d1 > d2: // (d2, i2) is incident to (d1, i1) if (d2, i2) is contained in (d1, i1) // d1 < d2: // (d2, i2) is incident to (d1, i1) if (d1, i1) is incident to (d2, i2) // d1 = d2, d1, d2 > 0: // (d2, i2) is incident to (d1, i1) if both are incident to a common vertex // d1 = d2 = 0: // (d2, i2) is incident to (d1, i1) if both are incident to a common cell #define IJ(D, d1, d2) ((D + 1)) * (d1) + (d2) typedef struct MeshTopology { uint32 max_dim; uint32 num[4]; // Number of entities of given dimension. uint32 *cell_types; // Cell types = indices to LocalEntities. uint32 *face_oris; // Face orientations. uint32 *edge_oris; // Edge orientations. MeshConnectivity _conn[16]; MeshConnectivity *conn[16]; } MeshTopology; #define MAX_EL_TYPES 5 #define Bar 0 #define Triangle 1 #define Quadrilateral 2 #define Tetrahedron 3 #define Hexahedron 4 // Facets for various reference element types. typedef struct LocalEntities { uint32 num; // Lengths of edges and faces = MAX_EL_TYPES. MeshConnectivity _edges[MAX_EL_TYPES]; MeshConnectivity *edges[MAX_EL_TYPES]; MeshConnectivity _faces[MAX_EL_TYPES]; MeshConnectivity *faces[MAX_EL_TYPES]; } LocalEntities; typedef struct Mesh { MeshGeometry geometry[1]; MeshTopology topology[1]; LocalEntities entities[1]; } Mesh; typedef struct MeshEntity { uint32 dim; // Topological dimension. uint32 ii; // Local index within entities of the given topological // dimension. Mesh *mesh; } MeshEntity; typedef struct MeshEntityIterator { uint32 it; // Current iteration position. uint32 it_end; // End iteration position. uint32 *ptr; // If given, entity->ii = ptr[it]. MeshEntity entity[1]; } MeshEntityIterator; typedef struct Region { Indices *vertices; Indices *edges; Indices *faces; Indices *cells; } Region; int32 mesh_create(Mesh **p_mesh); int32 mesh_destroy(Mesh **p_mesh); int32 mesh_init(Mesh *mesh); int32 mesh_free(Mesh *mesh); int32 mesh_print(Mesh *mesh, FILE *file, int32 header_only); int32 mei_init(MeshEntityIterator *iter, Mesh *mesh, uint32 dim); int32 mei_init_conn(MeshEntityIterator *iter, MeshEntity *entity, uint32 dim); int32 mei_init_sub(MeshEntityIterator *iter, Mesh *mesh, Indices *entities, uint32 dim); int32 mei_print(MeshEntityIterator *iter, FILE *file); int32 mei_go(MeshEntityIterator *iter); int32 mei_next(MeshEntityIterator *iter); int32 ind_print(Indices *ind, FILE *file); int32 conn_alloc(MeshConnectivity *conn, uint32 num, uint32 n_incident); int32 conn_resize(MeshConnectivity *conn, uint32 num, uint32 n_incident); int32 conn_free(MeshConnectivity *conn); int32 conn_print(MeshConnectivity *conn, FILE *file); int32 conn_set_from(MeshConnectivity *conn, MeshConnectivity *other); int32 conn_set_to_free(MeshConnectivity *conn, uint32 ii, uint32 incident); int32 mesh_set_coors(Mesh *mesh, float64 *coors, int32 num, int32 dim, int32 tdim); int32 mesh_setup_connectivity(Mesh *mesh, int32 d1, int32 d2); int32 mesh_free_connectivity(Mesh *mesh, int32 d1, int32 d2); int32 mesh_build(Mesh *mesh, int32 dim); int32 mesh_transpose(Mesh *mesh, int32 d1, int32 d2); int32 mesh_intersect(Mesh *mesh, int32 d1, int32 d2, int32 d3); // Count non-unique entities of dimension `dim` incident to `entities` of // dimension `dent`. uint32 mesh_count_incident(Mesh *mesh, int32 dim, Indices *entities, int32 dent); // Get non-unique entities `incident` of dimension `dim` incident to `entities` // of dimension `dent`. As each of entities can be in several entities of // dimension `dent`, `incident` is stored in MeshConnectivity structure. // `incident` must be preallocated - use mesh_count_incident(). // Returns a subset of a connectivity - entities may be repeated! int32 mesh_get_incident(Mesh *mesh, MeshConnectivity *incident, int32 dim, Indices *entities, int32 dent); // Get local ids of non-unique entities `incident` of dimension `dim` incident // to `entities` of dimension `dent`, see `mesh_get_incident()`, with respect // to `entities`. `local_ids` must be preallocated to same size as `incident`. int32 mesh_get_local_ids(Mesh *mesh, Indices *local_ids, Indices *entities, int32 dent, MeshConnectivity *incident, int32 dim); // Select entities of dimension `dim` that are completely given by entities of // dimension `dent`. // Example: mesh_select_complete(mesh, mask, 2, vertices, 0) will select all // complete faces, whose vertices are listed in `vertices`. int32 mesh_select_complete(Mesh *mesh, Mask *mask, int32 dim, Indices *entities, int32 dent); // Return the coordinates of centroids of mesh entities with dimension `dim`. // `ccoors` must be preallocated. int32 mesh_get_centroids(Mesh *mesh, float64 *ccoors, int32 dim); // Return the normals of facets for each mesh cell. The normals can be accessed // using the cell-facet connectivity. // If `which` is -1, two normals of each quadrilateral face are averaged. If it // is 0 or 1, the corresponding normal is used. int32 mesh_get_facet_normals(Mesh *mesh, float64 *normals, int32 which); int32 me_get_incident(MeshEntity *entity, Indices *out, int32 dim); int32 me_get_incident2(MeshEntity *entity, Indices *out, MeshConnectivity *conn); int32 contains(Indices *i1, Indices *i2); int32 get_local_connectivity(MeshConnectivity *loc, Indices *cell_vertices, MeshConnectivity *refloc); int32 sort_local_connectivity(MeshConnectivity *loc, uint32 *oris, uint32 num); void uint32_sort234_copy(uint32 *out, uint32 *p, uint32 num); int32 uint32_sort4(uint32 *p); int32 uint32_sort3(uint32 *p); int32 uint32_sort2(uint32 *p); // Mesh entity is given by (dimension, index) or (dim, ii). // Index ii is in [0, num[dim] - 1]. int32 mesh_get_entity(int32 *n_items, int32 dim, int32 ii); // ? int32 mesh_iterate_entities(Mesh *mesh, int32 *entity, int32 dim, Region *reg); #endif /* !MESH_H */
NaohiroTamura/edk2
UefiCpuPkg/Library/CpuTimerLib/PeiCpuTimerLib.c
/** @file CPUID Leaf 0x15 for Core Crystal Clock frequency instance as PEI Timer Library. Copyright (c) 2019 Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <PiPei.h> #include <Library/TimerLib.h> #include <Library/BaseLib.h> #include <Library/HobLib.h> #include <Library/DebugLib.h> extern GUID mCpuCrystalFrequencyHobGuid; /** CPUID Leaf 0x15 for Core Crystal Clock Frequency. The TSC counting frequency is determined by using CPUID leaf 0x15. Frequency in MHz = Core XTAL frequency * EBX/EAX. In newer flavors of the CPU, core xtal frequency is returned in ECX or 0 if not supported. @return The number of TSC counts per second. **/ UINT64 CpuidCoreClockCalculateTscFrequency ( VOID ); /** Internal function to retrieves the 64-bit frequency in Hz. Internal function to retrieves the 64-bit frequency in Hz. @return The frequency in Hz. **/ UINT64 InternalGetPerformanceCounterFrequency ( VOID ) { UINT64 *CpuCrystalCounterFrequency; EFI_HOB_GUID_TYPE *GuidHob; CpuCrystalCounterFrequency = NULL; GuidHob = GetFirstGuidHob (&mCpuCrystalFrequencyHobGuid); if (GuidHob == NULL) { CpuCrystalCounterFrequency = (UINT64*)BuildGuidHob(&mCpuCrystalFrequencyHobGuid, sizeof (*CpuCrystalCounterFrequency)); ASSERT (CpuCrystalCounterFrequency != NULL); *CpuCrystalCounterFrequency = CpuidCoreClockCalculateTscFrequency (); } else { CpuCrystalCounterFrequency = (UINT64*)GET_GUID_HOB_DATA (GuidHob); } return *CpuCrystalCounterFrequency; }
NaohiroTamura/edk2
ArmPlatformPkg/Library/PrePiHobListPointerLib/PrePiHobListPointer.c
<filename>ArmPlatformPkg/Library/PrePiHobListPointerLib/PrePiHobListPointer.c /** @file * * Copyright (c) 2011, ARM Limited. All rights reserved. * * SPDX-License-Identifier: BSD-2-Clause-Patent * **/ #include <PiPei.h> #include <Library/ArmLib.h> #include <Library/PrePiHobListPointerLib.h> #include <Library/DebugLib.h> /** Returns the pointer to the HOB list. This function returns the pointer to first HOB in the list. @return The pointer to the HOB list. **/ VOID * EFIAPI PrePeiGetHobList ( VOID ) { return (VOID *)ArmReadTpidrurw(); } /** Updates the pointer to the HOB list. @param HobList Hob list pointer to store **/ EFI_STATUS EFIAPI PrePeiSetHobList ( IN VOID *HobList ) { ArmWriteTpidrurw((UINTN)HobList); return EFI_SUCCESS; }
NaohiroTamura/edk2
UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.c
/** @file Copyright (c) 2014 - 2020, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "UefiPayloadEntry.h" /** Callback function to build resource descriptor HOB This function build a HOB based on the memory map entry info. @param MemoryMapEntry Memory map entry info got from bootloader. @param Params Not used for now. @retval RETURN_SUCCESS Successfully build a HOB. **/ EFI_STATUS MemInfoCallback ( IN MEMROY_MAP_ENTRY *MemoryMapEntry, IN VOID *Params ) { EFI_PHYSICAL_ADDRESS Base; EFI_RESOURCE_TYPE Type; UINT64 Size; EFI_RESOURCE_ATTRIBUTE_TYPE Attribue; Type = (MemoryMapEntry->Type == 1) ? EFI_RESOURCE_SYSTEM_MEMORY : EFI_RESOURCE_MEMORY_RESERVED; Base = MemoryMapEntry->Base; Size = MemoryMapEntry->Size; Attribue = EFI_RESOURCE_ATTRIBUTE_PRESENT | EFI_RESOURCE_ATTRIBUTE_INITIALIZED | EFI_RESOURCE_ATTRIBUTE_TESTED | EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE; if (Base >= BASE_4GB ) { // Remove tested attribute to avoid DXE core to dispatch driver to memory above 4GB Attribue &= ~EFI_RESOURCE_ATTRIBUTE_TESTED; } BuildResourceDescriptorHob (Type, Attribue, (EFI_PHYSICAL_ADDRESS)Base, Size); DEBUG ((DEBUG_INFO , "buildhob: base = 0x%lx, size = 0x%lx, type = 0x%x\n", Base, Size, Type)); return RETURN_SUCCESS; } /** Find the board related info from ACPI table @param AcpiTableBase ACPI table start address in memory @param AcpiBoardInfo Pointer to the acpi board info strucutre @retval RETURN_SUCCESS Successfully find out all the required information. @retval RETURN_NOT_FOUND Failed to find the required info. **/ RETURN_STATUS ParseAcpiInfo ( IN UINT64 AcpiTableBase, OUT ACPI_BOARD_INFO *AcpiBoardInfo ) { EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_POINTER *Rsdp; EFI_ACPI_DESCRIPTION_HEADER *Rsdt; UINT32 *Entry32; UINTN Entry32Num; EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE *Fadt; EFI_ACPI_DESCRIPTION_HEADER *Xsdt; UINT64 *Entry64; UINTN Entry64Num; UINTN Idx; UINT32 *Signature; EFI_ACPI_MEMORY_MAPPED_CONFIGURATION_BASE_ADDRESS_TABLE_HEADER *MmCfgHdr; EFI_ACPI_MEMORY_MAPPED_ENHANCED_CONFIGURATION_SPACE_BASE_ADDRESS_ALLOCATION_STRUCTURE *MmCfgBase; Rsdp = (EFI_ACPI_3_0_ROOT_SYSTEM_DESCRIPTION_POINTER *)(UINTN)AcpiTableBase; DEBUG ((DEBUG_INFO, "Rsdp at 0x%p\n", Rsdp)); DEBUG ((DEBUG_INFO, "Rsdt at 0x%x, Xsdt at 0x%lx\n", Rsdp->RsdtAddress, Rsdp->XsdtAddress)); // // Search Rsdt First // Fadt = NULL; MmCfgHdr = NULL; Rsdt = (EFI_ACPI_DESCRIPTION_HEADER *)(UINTN)(Rsdp->RsdtAddress); if (Rsdt != NULL) { Entry32 = (UINT32 *)(Rsdt + 1); Entry32Num = (Rsdt->Length - sizeof(EFI_ACPI_DESCRIPTION_HEADER)) >> 2; for (Idx = 0; Idx < Entry32Num; Idx++) { Signature = (UINT32 *)(UINTN)Entry32[Idx]; if (*Signature == EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE) { Fadt = (EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE *)Signature; DEBUG ((DEBUG_INFO, "Found Fadt in Rsdt\n")); } if (*Signature == EFI_ACPI_5_0_PCI_EXPRESS_MEMORY_MAPPED_CONFIGURATION_SPACE_BASE_ADDRESS_DESCRIPTION_TABLE_SIGNATURE) { MmCfgHdr = (EFI_ACPI_MEMORY_MAPPED_CONFIGURATION_BASE_ADDRESS_TABLE_HEADER *)Signature; DEBUG ((DEBUG_INFO, "Found MM config address in Rsdt\n")); } if ((Fadt != NULL) && (MmCfgHdr != NULL)) { goto Done; } } } // // Search Xsdt Second // Xsdt = (EFI_ACPI_DESCRIPTION_HEADER *)(UINTN)(Rsdp->XsdtAddress); if (Xsdt != NULL) { Entry64 = (UINT64 *)(Xsdt + 1); Entry64Num = (Xsdt->Length - sizeof(EFI_ACPI_DESCRIPTION_HEADER)) >> 3; for (Idx = 0; Idx < Entry64Num; Idx++) { Signature = (UINT32 *)(UINTN)Entry64[Idx]; if (*Signature == EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE) { Fadt = (EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE *)Signature; DEBUG ((DEBUG_INFO, "Found Fadt in Xsdt\n")); } if (*Signature == EFI_ACPI_5_0_PCI_EXPRESS_MEMORY_MAPPED_CONFIGURATION_SPACE_BASE_ADDRESS_DESCRIPTION_TABLE_SIGNATURE) { MmCfgHdr = (EFI_ACPI_MEMORY_MAPPED_CONFIGURATION_BASE_ADDRESS_TABLE_HEADER *)Signature; DEBUG ((DEBUG_INFO, "Found MM config address in Xsdt\n")); } if ((Fadt != NULL) && (MmCfgHdr != NULL)) { goto Done; } } } if (Fadt == NULL) { return RETURN_NOT_FOUND; } Done: AcpiBoardInfo->PmCtrlRegBase = Fadt->Pm1aCntBlk; AcpiBoardInfo->PmTimerRegBase = Fadt->PmTmrBlk; AcpiBoardInfo->ResetRegAddress = Fadt->ResetReg.Address; AcpiBoardInfo->ResetValue = Fadt->ResetValue; AcpiBoardInfo->PmEvtBase = Fadt->Pm1aEvtBlk; AcpiBoardInfo->PmGpeEnBase = Fadt->Gpe0Blk + Fadt->Gpe0BlkLen / 2; if (MmCfgHdr != NULL) { MmCfgBase = (EFI_ACPI_MEMORY_MAPPED_ENHANCED_CONFIGURATION_SPACE_BASE_ADDRESS_ALLOCATION_STRUCTURE *)((UINT8*) MmCfgHdr + sizeof (*MmCfgHdr)); AcpiBoardInfo->PcieBaseAddress = MmCfgBase->BaseAddress; AcpiBoardInfo->PcieBaseSize = (MmCfgBase->EndBusNumber + 1 - MmCfgBase->StartBusNumber) * 4096 * 32 * 8; } else { AcpiBoardInfo->PcieBaseAddress = 0; AcpiBoardInfo->PcieBaseSize = 0; } DEBUG ((DEBUG_INFO, "PmCtrl Reg 0x%lx\n", AcpiBoardInfo->PmCtrlRegBase)); DEBUG ((DEBUG_INFO, "PmTimer Reg 0x%lx\n", AcpiBoardInfo->PmTimerRegBase)); DEBUG ((DEBUG_INFO, "Reset Reg 0x%lx\n", AcpiBoardInfo->ResetRegAddress)); DEBUG ((DEBUG_INFO, "Reset Value 0x%x\n", AcpiBoardInfo->ResetValue)); DEBUG ((DEBUG_INFO, "PmEvt Reg 0x%lx\n", AcpiBoardInfo->PmEvtBase)); DEBUG ((DEBUG_INFO, "PmGpeEn Reg 0x%lx\n", AcpiBoardInfo->PmGpeEnBase)); DEBUG ((DEBUG_INFO, "PcieBaseAddr 0x%lx\n", AcpiBoardInfo->PcieBaseAddress)); DEBUG ((DEBUG_INFO, "PcieBaseSize 0x%lx\n", AcpiBoardInfo->PcieBaseSize)); // // Verify values for proper operation // ASSERT(Fadt->Pm1aCntBlk != 0); ASSERT(Fadt->PmTmrBlk != 0); ASSERT(Fadt->ResetReg.Address != 0); ASSERT(Fadt->Pm1aEvtBlk != 0); ASSERT(Fadt->Gpe0Blk != 0); DEBUG_CODE_BEGIN (); BOOLEAN SciEnabled; // // Check the consistency of SCI enabling // // // Get SCI_EN value // if (Fadt->Pm1CntLen == 4) { SciEnabled = (IoRead32 (Fadt->Pm1aCntBlk) & BIT0)? TRUE : FALSE; } else { // // if (Pm1CntLen == 2), use 16 bit IO read; // if (Pm1CntLen != 2 && Pm1CntLen != 4), use 16 bit IO read as a fallback // SciEnabled = (IoRead16 (Fadt->Pm1aCntBlk) & BIT0)? TRUE : FALSE; } if (!(Fadt->Flags & EFI_ACPI_5_0_HW_REDUCED_ACPI) && (Fadt->SmiCmd == 0) && !SciEnabled) { // // The ACPI enabling status is inconsistent: SCI is not enabled but ACPI // table does not provide a means to enable it through FADT->SmiCmd // DEBUG ((DEBUG_ERROR, "ERROR: The ACPI enabling status is inconsistent: SCI is not" " enabled but the ACPI table does not provide a means to enable it through FADT->SmiCmd." " This may cause issues in OS.\n")); } DEBUG_CODE_END (); return RETURN_SUCCESS; } /** It will build HOBs based on information from bootloaders. @retval EFI_SUCCESS If it completed successfully. @retval Others If it failed to build required HOBs. **/ EFI_STATUS BuildHobFromBl ( VOID ) { EFI_STATUS Status; SYSTEM_TABLE_INFO SysTableInfo; SYSTEM_TABLE_INFO *NewSysTableInfo; ACPI_BOARD_INFO AcpiBoardInfo; ACPI_BOARD_INFO *NewAcpiBoardInfo; EFI_PEI_GRAPHICS_INFO_HOB GfxInfo; EFI_PEI_GRAPHICS_INFO_HOB *NewGfxInfo; EFI_PEI_GRAPHICS_DEVICE_INFO_HOB GfxDeviceInfo; EFI_PEI_GRAPHICS_DEVICE_INFO_HOB *NewGfxDeviceInfo; // // Parse memory info and build memory HOBs // Status = ParseMemoryInfo (MemInfoCallback, NULL); if (EFI_ERROR(Status)) { return Status; } // // Create guid hob for frame buffer information // Status = ParseGfxInfo (&GfxInfo); if (!EFI_ERROR (Status)) { NewGfxInfo = BuildGuidHob (&gEfiGraphicsInfoHobGuid, sizeof (GfxInfo)); ASSERT (NewGfxInfo != NULL); CopyMem (NewGfxInfo, &GfxInfo, sizeof (GfxInfo)); DEBUG ((DEBUG_INFO, "Created graphics info hob\n")); } Status = ParseGfxDeviceInfo (&GfxDeviceInfo); if (!EFI_ERROR (Status)) { NewGfxDeviceInfo = BuildGuidHob (&gEfiGraphicsDeviceInfoHobGuid, sizeof (GfxDeviceInfo)); ASSERT (NewGfxDeviceInfo != NULL); CopyMem (NewGfxDeviceInfo, &GfxDeviceInfo, sizeof (GfxDeviceInfo)); DEBUG ((DEBUG_INFO, "Created graphics device info hob\n")); } // // Create guid hob for system tables like acpi table and smbios table // Status = ParseSystemTable(&SysTableInfo); ASSERT_EFI_ERROR (Status); if (!EFI_ERROR (Status)) { NewSysTableInfo = BuildGuidHob (&gUefiSystemTableInfoGuid, sizeof (SYSTEM_TABLE_INFO)); ASSERT (NewSysTableInfo != NULL); CopyMem (NewSysTableInfo, &SysTableInfo, sizeof (SYSTEM_TABLE_INFO)); DEBUG ((DEBUG_INFO, "Detected Acpi Table at 0x%lx, length 0x%x\n", SysTableInfo.AcpiTableBase, SysTableInfo.AcpiTableSize)); DEBUG ((DEBUG_INFO, "Detected Smbios Table at 0x%lx, length 0x%x\n", SysTableInfo.SmbiosTableBase, SysTableInfo.SmbiosTableSize)); } // // Create guid hob for acpi board information // Status = ParseAcpiInfo (SysTableInfo.AcpiTableBase, &AcpiBoardInfo); ASSERT_EFI_ERROR (Status); if (!EFI_ERROR (Status)) { NewAcpiBoardInfo = BuildGuidHob (&gUefiAcpiBoardInfoGuid, sizeof (ACPI_BOARD_INFO)); ASSERT (NewAcpiBoardInfo != NULL); CopyMem (NewAcpiBoardInfo, &AcpiBoardInfo, sizeof (ACPI_BOARD_INFO)); DEBUG ((DEBUG_INFO, "Create acpi board info guid hob\n")); } // // Parse platform specific information. // Status = ParsePlatformInfo (); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Error when parsing platform info, Status = %r\n", Status)); return Status; } return EFI_SUCCESS; } /** This function will build some generic HOBs that doesn't depend on information from bootloaders. **/ VOID BuildGenericHob ( VOID ) { UINT32 RegEax; UINT8 PhysicalAddressBits; EFI_RESOURCE_ATTRIBUTE_TYPE ResourceAttribute; // The UEFI payload FV BuildMemoryAllocationHob (PcdGet32 (PcdPayloadFdMemBase), PcdGet32 (PcdPayloadFdMemSize), EfiBootServicesData); // // Build CPU memory space and IO space hob // AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL); if (RegEax >= 0x80000008) { AsmCpuid (0x80000008, &RegEax, NULL, NULL, NULL); PhysicalAddressBits = (UINT8) RegEax; } else { PhysicalAddressBits = 36; } BuildCpuHob (PhysicalAddressBits, 16); // // Report Local APIC range, cause sbl HOB to be NULL, comment now // ResourceAttribute = ( EFI_RESOURCE_ATTRIBUTE_PRESENT | EFI_RESOURCE_ATTRIBUTE_INITIALIZED | EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE | EFI_RESOURCE_ATTRIBUTE_TESTED ); BuildResourceDescriptorHob (EFI_RESOURCE_MEMORY_MAPPED_IO, ResourceAttribute, 0xFEC80000, SIZE_512KB); BuildMemoryAllocationHob ( 0xFEC80000, SIZE_512KB, EfiMemoryMappedIO); } /** Entry point to the C language phase of UEFI payload. @retval It will not return if SUCCESS, and return error when passing bootloader parameter. **/ EFI_STATUS EFIAPI PayloadEntry ( IN UINTN BootloaderParameter ) { EFI_STATUS Status; PHYSICAL_ADDRESS DxeCoreEntryPoint; EFI_HOB_HANDOFF_INFO_TABLE *HandoffHobTable; UINTN MemBase; UINTN MemSize; UINTN HobMemBase; UINTN HobMemTop; EFI_PEI_HOB_POINTERS Hob; // Call constructor for all libraries ProcessLibraryConstructorList (); DEBUG ((DEBUG_INFO, "GET_BOOTLOADER_PARAMETER() = 0x%lx\n", GET_BOOTLOADER_PARAMETER())); DEBUG ((DEBUG_INFO, "sizeof(UINTN) = 0x%x\n", sizeof(UINTN))); // Initialize floating point operating environment to be compliant with UEFI spec. InitializeFloatingPointUnits (); // HOB region is used for HOB and memory allocation for this module MemBase = PcdGet32 (PcdPayloadFdMemBase); HobMemBase = ALIGN_VALUE (MemBase + PcdGet32 (PcdPayloadFdMemSize), SIZE_1MB); HobMemTop = HobMemBase + FixedPcdGet32 (PcdSystemMemoryUefiRegionSize); // DXE core assumes the memory below HOB region could be used, so include the FV region memory into HOB range. MemSize = HobMemTop - MemBase; HandoffHobTable = HobConstructor ((VOID *)MemBase, MemSize, (VOID *)HobMemBase, (VOID *)HobMemTop); // Build HOB based on information from Bootloader Status = BuildHobFromBl (); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "BuildHobFromBl Status = %r\n", Status)); return Status; } // Build other HOBs required by DXE BuildGenericHob (); // Load the DXE Core Status = LoadDxeCore (&DxeCoreEntryPoint); ASSERT_EFI_ERROR (Status); DEBUG ((DEBUG_INFO, "DxeCoreEntryPoint = 0x%lx\n", DxeCoreEntryPoint)); // // Mask off all legacy 8259 interrupt sources // IoWrite8 (LEGACY_8259_MASK_REGISTER_MASTER, 0xFF); IoWrite8 (LEGACY_8259_MASK_REGISTER_SLAVE, 0xFF); Hob.HandoffInformationTable = HandoffHobTable; HandOffToDxeCore (DxeCoreEntryPoint, Hob); // Should not get here CpuDeadLoop (); return EFI_SUCCESS; }
NaohiroTamura/edk2
DynamicTablesPkg/Include/ArmNameSpaceObjects.h
<filename>DynamicTablesPkg/Include/ArmNameSpaceObjects.h /** @file Copyright (c) 2017 - 2020, Arm Limited. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent @par Glossary: - Cm or CM - Configuration Manager - Obj or OBJ - Object - Std or STD - Standard **/ #ifndef ARM_NAMESPACE_OBJECTS_H_ #define ARM_NAMESPACE_OBJECTS_H_ #include <StandardNameSpaceObjects.h> #pragma pack(1) /** The EARM_OBJECT_ID enum describes the Object IDs in the ARM Namespace */ typedef enum ArmObjectID { EArmObjReserved, ///< 0 - Reserved EArmObjBootArchInfo, ///< 1 - Boot Architecture Info EArmObjCpuInfo, ///< 2 - CPU Info EArmObjPowerManagementProfileInfo, ///< 3 - Power Management Profile Info EArmObjGicCInfo, ///< 4 - GIC CPU Interface Info EArmObjGicDInfo, ///< 5 - GIC Distributor Info EArmObjGicMsiFrameInfo, ///< 6 - GIC MSI Frame Info EArmObjGicRedistributorInfo, ///< 7 - GIC Redistributor Info EArmObjGicItsInfo, ///< 8 - GIC ITS Info EArmObjSerialConsolePortInfo, ///< 9 - Serial Console Port Info EArmObjSerialDebugPortInfo, ///< 10 - Serial Debug Port Info EArmObjGenericTimerInfo, ///< 11 - Generic Timer Info EArmObjPlatformGTBlockInfo, ///< 12 - Platform GT Block Info EArmObjGTBlockTimerFrameInfo, ///< 13 - Generic Timer Block Frame Info EArmObjPlatformGenericWatchdogInfo, ///< 14 - Platform Generic Watchdog EArmObjPciConfigSpaceInfo, ///< 15 - PCI Configuration Space Info EArmObjHypervisorVendorIdentity, ///< 16 - Hypervisor Vendor Id EArmObjFixedFeatureFlags, ///< 17 - Fixed feature flags for FADT EArmObjItsGroup, ///< 18 - ITS Group EArmObjNamedComponent, ///< 19 - Named Component EArmObjRootComplex, ///< 20 - Root Complex EArmObjSmmuV1SmmuV2, ///< 21 - SMMUv1 or SMMUv2 EArmObjSmmuV3, ///< 22 - SMMUv3 EArmObjPmcg, ///< 23 - PMCG EArmObjGicItsIdentifierArray, ///< 24 - GIC ITS Identifier Array EArmObjIdMappingArray, ///< 25 - ID Mapping Array EArmObjSmmuInterruptArray, ///< 26 - SMMU Interrupt Array EArmObjProcHierarchyInfo, ///< 27 - Processor Hierarchy Info EArmObjCacheInfo, ///< 28 - Cache Info EArmObjProcNodeIdInfo, ///< 29 - Processor Node ID Info EArmObjCmRef, ///< 30 - CM Object Reference EArmObjMemoryAffinityInfo, ///< 31 - Memory Affinity Info EArmObjDeviceHandleAcpi, ///< 32 - Device Handle Acpi EArmObjDeviceHandlePci, ///< 33 - Device Handle Pci EArmObjGenericInitiatorAffinityInfo, ///< 34 - Generic Initiator Affinity EArmObjSerialPortInfo, ///< 35 - Generic Serial Port Info EArmObjCmn600Info, ///< 36 - CMN-600 Info EArmObjMax } EARM_OBJECT_ID; /** A structure that describes the ARM Boot Architecture flags. ID: EArmObjBootArchInfo */ typedef struct CmArmBootArchInfo { /** This is the ARM_BOOT_ARCH flags field of the FADT Table described in the ACPI Table Specification. */ UINT16 BootArchFlags; } CM_ARM_BOOT_ARCH_INFO; /** A structure that describes the Power Management Profile Information for the Platform. ID: EArmObjPowerManagementProfileInfo */ typedef struct CmArmPowerManagementProfileInfo { /** This is the Preferred_PM_Profile field of the FADT Table described in the ACPI Specification */ UINT8 PowerManagementProfile; } CM_ARM_POWER_MANAGEMENT_PROFILE_INFO; /** A structure that describes the GIC CPU Interface for the Platform. ID: EArmObjGicCInfo */ typedef struct CmArmGicCInfo { /// The GIC CPU Interface number. UINT32 CPUInterfaceNumber; /** The ACPI Processor UID. This must match the _UID of the CPU Device object information described in the DSDT/SSDT for the CPU. */ UINT32 AcpiProcessorUid; /** The flags field as described by the GICC structure in the ACPI Specification. */ UINT32 Flags; /** The parking protocol version field as described by the GICC structure in the ACPI Specification. */ UINT32 ParkingProtocolVersion; /** The Performance Interrupt field as described by the GICC structure in the ACPI Specification. */ UINT32 PerformanceInterruptGsiv; /** The CPU Parked address field as described by the GICC structure in the ACPI Specification. */ UINT64 ParkedAddress; /** The base address for the GIC CPU Interface as described by the GICC structure in the ACPI Specification. */ UINT64 PhysicalBaseAddress; /** The base address for GICV interface as described by the GICC structure in the ACPI Specification. */ UINT64 GICV; /** The base address for GICH interface as described by the GICC structure in the ACPI Specification. */ UINT64 GICH; /** The GICV maintenance interrupt as described by the GICC structure in the ACPI Specification. */ UINT32 VGICMaintenanceInterrupt; /** The base address for GICR interface as described by the GICC structure in the ACPI Specification. */ UINT64 GICRBaseAddress; /** The MPIDR for the CPU as described by the GICC structure in the ACPI Specification. */ UINT64 MPIDR; /** The Processor Power Efficiency class as described by the GICC structure in the ACPI Specification. */ UINT8 ProcessorPowerEfficiencyClass; /** Statistical Profiling Extension buffer overflow GSIV. Zero if unsupported by this processor. This field was introduced in ACPI 6.3 (MADT revision 5) and is therefore ignored when generating MADT revision 4 or lower. */ UINT16 SpeOverflowInterrupt; /** The proximity domain to which the logical processor belongs. This field is used to populate the GICC affinity structure in the SRAT table. */ UINT32 ProximityDomain; /** The clock domain to which the logical processor belongs. This field is used to populate the GICC affinity structure in the SRAT table. */ UINT32 ClockDomain; /** The GICC Affinity flags field as described by the GICC Affinity structure in the SRAT table. */ UINT32 AffinityFlags; } CM_ARM_GICC_INFO; /** A structure that describes the GIC Distributor information for the Platform. ID: EArmObjGicDInfo */ typedef struct CmArmGicDInfo { /// The Physical Base address for the GIC Distributor. UINT64 PhysicalBaseAddress; /** The global system interrupt number where this GIC Distributor's interrupt inputs start. */ UINT32 SystemVectorBase; /** The GIC version as described by the GICD structure in the ACPI Specification. */ UINT8 GicVersion; } CM_ARM_GICD_INFO; /** A structure that describes the GIC MSI Frame information for the Platform. ID: EArmObjGicMsiFrameInfo */ typedef struct CmArmGicMsiFrameInfo { /// The GIC MSI Frame ID UINT32 GicMsiFrameId; /// The Physical base address for the MSI Frame UINT64 PhysicalBaseAddress; /** The GIC MSI Frame flags as described by the GIC MSI frame structure in the ACPI Specification. */ UINT32 Flags; /// SPI Count used by this frame UINT16 SPICount; /// SPI Base used by this frame UINT16 SPIBase; } CM_ARM_GIC_MSI_FRAME_INFO; /** A structure that describes the GIC Redistributor information for the Platform. ID: EArmObjGicRedistributorInfo */ typedef struct CmArmGicRedistInfo { /** The physical address of a page range containing all GIC Redistributors. */ UINT64 DiscoveryRangeBaseAddress; /// Length of the GIC Redistributor Discovery page range UINT32 DiscoveryRangeLength; } CM_ARM_GIC_REDIST_INFO; /** A structure that describes the GIC Interrupt Translation Service information for the Platform. ID: EArmObjGicItsInfo */ typedef struct CmArmGicItsInfo { /// The GIC ITS ID UINT32 GicItsId; /// The physical address for the Interrupt Translation Service UINT64 PhysicalBaseAddress; /** The proximity domain to which the logical processor belongs. This field is used to populate the GIC ITS affinity structure in the SRAT table. */ UINT32 ProximityDomain; } CM_ARM_GIC_ITS_INFO; /** A structure that describes the Serial Port information for the Platform. ID: EArmObjSerialConsolePortInfo or EArmObjSerialDebugPortInfo or EArmObjSerialPortInfo */ typedef struct CmArmSerialPortInfo { /// The physical base address for the serial port UINT64 BaseAddress; /// The serial port interrupt UINT32 Interrupt; /// The serial port baud rate UINT64 BaudRate; /// The serial port clock UINT32 Clock; /// Serial Port subtype UINT16 PortSubtype; /// The Base address length UINT64 BaseAddressLength; } CM_ARM_SERIAL_PORT_INFO; /** A structure that describes the Generic Timer information for the Platform. ID: EArmObjGenericTimerInfo */ typedef struct CmArmGenericTimerInfo { /// The physical base address for the counter control frame UINT64 CounterControlBaseAddress; /// The physical base address for the counter read frame UINT64 CounterReadBaseAddress; /// The secure PL1 timer interrupt UINT32 SecurePL1TimerGSIV; /// The secure PL1 timer flags UINT32 SecurePL1TimerFlags; /// The non-secure PL1 timer interrupt UINT32 NonSecurePL1TimerGSIV; /// The non-secure PL1 timer flags UINT32 NonSecurePL1TimerFlags; /// The virtual timer interrupt UINT32 VirtualTimerGSIV; /// The virtual timer flags UINT32 VirtualTimerFlags; /// The non-secure PL2 timer interrupt UINT32 NonSecurePL2TimerGSIV; /// The non-secure PL2 timer flags UINT32 NonSecurePL2TimerFlags; /// GSIV for the virtual EL2 timer UINT32 VirtualPL2TimerGSIV; /// Flags for the virtual EL2 timer UINT32 VirtualPL2TimerFlags; } CM_ARM_GENERIC_TIMER_INFO; /** A structure that describes the Platform Generic Block Timer Frame information for the Platform. ID: EArmObjGTBlockTimerFrameInfo */ typedef struct CmArmGTBlockTimerFrameInfo { /// The Generic Timer frame number UINT8 FrameNumber; /// The physical base address for the CntBase block UINT64 PhysicalAddressCntBase; /// The physical base address for the CntEL0Base block UINT64 PhysicalAddressCntEL0Base; /// The physical timer interrupt UINT32 PhysicalTimerGSIV; /** The physical timer flags as described by the GT Block Timer frame Structure in the ACPI Specification. */ UINT32 PhysicalTimerFlags; /// The virtual timer interrupt UINT32 VirtualTimerGSIV; /** The virtual timer flags as described by the GT Block Timer frame Structure in the ACPI Specification. */ UINT32 VirtualTimerFlags; /** The common timer flags as described by the GT Block Timer frame Structure in the ACPI Specification. */ UINT32 CommonFlags; } CM_ARM_GTBLOCK_TIMER_FRAME_INFO; /** A structure that describes the Platform Generic Block Timer information for the Platform. ID: EArmObjPlatformGTBlockInfo */ typedef struct CmArmGTBlockInfo { /// The physical base address for the GT Block Timer structure UINT64 GTBlockPhysicalAddress; /// The number of timer frames implemented in the GT Block UINT32 GTBlockTimerFrameCount; /// Reference token for the GT Block timer frame list CM_OBJECT_TOKEN GTBlockTimerFrameToken; } CM_ARM_GTBLOCK_INFO; /** A structure that describes the SBSA Generic Watchdog information for the Platform. ID: EArmObjPlatformGenericWatchdogInfo */ typedef struct CmArmGenericWatchdogInfo { /// The physical base address of the SBSA Watchdog control frame UINT64 ControlFrameAddress; /// The physical base address of the SBSA Watchdog refresh frame UINT64 RefreshFrameAddress; /// The watchdog interrupt UINT32 TimerGSIV; /** The flags for the watchdog as described by the SBSA watchdog structure in the ACPI specification. */ UINT32 Flags; } CM_ARM_GENERIC_WATCHDOG_INFO; /** A structure that describes the PCI Configuration Space information for the Platform. ID: EArmObjPciConfigSpaceInfo */ typedef struct CmArmPciConfigSpaceInfo { /// The physical base address for the PCI segment UINT64 BaseAddress; /// The PCI segment group number UINT16 PciSegmentGroupNumber; /// The start bus number UINT8 StartBusNumber; /// The end bus number UINT8 EndBusNumber; } CM_ARM_PCI_CONFIG_SPACE_INFO; /** A structure that describes the Hypervisor Vendor ID information for the Platform. ID: EArmObjHypervisorVendorIdentity */ typedef struct CmArmHypervisorVendorId { /// The hypervisor Vendor ID UINT64 HypervisorVendorId; } CM_ARM_HYPERVISOR_VENDOR_ID; /** A structure that describes the Fixed feature flags for the Platform. ID: EArmObjFixedFeatureFlags */ typedef struct CmArmFixedFeatureFlags { /// The Fixed feature flags UINT32 Flags; } CM_ARM_FIXED_FEATURE_FLAGS; /** A structure that describes the ITS Group node for the Platform. ID: EArmObjItsGroup */ typedef struct CmArmItsGroupNode { /// An unique token used to identify this object CM_OBJECT_TOKEN Token; /// The number of ITS identifiers in the ITS node UINT32 ItsIdCount; /// Reference token for the ITS identifier array CM_OBJECT_TOKEN ItsIdToken; } CM_ARM_ITS_GROUP_NODE; /** A structure that describes the GIC ITS Identifiers for an ITS Group node. ID: EArmObjGicItsIdentifierArray */ typedef struct CmArmGicItsIdentifier { /// The ITS Identifier UINT32 ItsId; } CM_ARM_ITS_IDENTIFIER; /** A structure that describes the Named component node for the Platform. ID: EArmObjNamedComponent */ typedef struct CmArmNamedComponentNode { /// An unique token used to identify this object CM_OBJECT_TOKEN Token; /// Number of ID mappings UINT32 IdMappingCount; /// Reference token for the ID mapping array CM_OBJECT_TOKEN IdMappingToken; /// Flags for the named component UINT32 Flags; /// Memory access properties : Cache coherent attributes UINT32 CacheCoherent; /// Memory access properties : Allocation hints UINT8 AllocationHints; /// Memory access properties : Memory access flags UINT8 MemoryAccessFlags; /// Memory access properties : Address size limit UINT8 AddressSizeLimit; /** ASCII Null terminated string with the full path to the entry in the namespace for this object. */ CHAR8* ObjectName; } CM_ARM_NAMED_COMPONENT_NODE; /** A structure that describes the Root complex node for the Platform. ID: EArmObjRootComplex */ typedef struct CmArmRootComplexNode { /// An unique token used to identify this object CM_OBJECT_TOKEN Token; /// Number of ID mappings UINT32 IdMappingCount; /// Reference token for the ID mapping array CM_OBJECT_TOKEN IdMappingToken; /// Memory access properties : Cache coherent attributes UINT32 CacheCoherent; /// Memory access properties : Allocation hints UINT8 AllocationHints; /// Memory access properties : Memory access flags UINT8 MemoryAccessFlags; /// ATS attributes UINT32 AtsAttribute; /// PCI segment number UINT32 PciSegmentNumber; /// Memory address size limit UINT8 MemoryAddressSize; } CM_ARM_ROOT_COMPLEX_NODE; /** A structure that describes the SMMUv1 or SMMUv2 node for the Platform. ID: EArmObjSmmuV1SmmuV2 */ typedef struct CmArmSmmuV1SmmuV2Node { /// An unique token used to identify this object CM_OBJECT_TOKEN Token; /// Number of ID mappings UINT32 IdMappingCount; /// Reference token for the ID mapping array CM_OBJECT_TOKEN IdMappingToken; /// SMMU Base Address UINT64 BaseAddress; /// Length of the memory range covered by the SMMU UINT64 Span; /// SMMU Model UINT32 Model; /// SMMU flags UINT32 Flags; /// Number of context interrupts UINT32 ContextInterruptCount; /// Reference token for the context interrupt array CM_OBJECT_TOKEN ContextInterruptToken; /// Number of PMU interrupts UINT32 PmuInterruptCount; /// Reference token for the PMU interrupt array CM_OBJECT_TOKEN PmuInterruptToken; /// GSIV of the SMMU_NSgIrpt interrupt UINT32 SMMU_NSgIrpt; /// SMMU_NSgIrpt interrupt flags UINT32 SMMU_NSgIrptFlags; /// GSIV of the SMMU_NSgCfgIrpt interrupt UINT32 SMMU_NSgCfgIrpt; /// SMMU_NSgCfgIrpt interrupt flags UINT32 SMMU_NSgCfgIrptFlags; } CM_ARM_SMMUV1_SMMUV2_NODE; /** A structure that describes the SMMUv3 node for the Platform. ID: EArmObjSmmuV3 */ typedef struct CmArmSmmuV3Node { /// An unique token used to identify this object CM_OBJECT_TOKEN Token; /// Number of ID mappings UINT32 IdMappingCount; /// Reference token for the ID mapping array CM_OBJECT_TOKEN IdMappingToken; /// SMMU Base Address UINT64 BaseAddress; /// SMMU flags UINT32 Flags; /// VATOS address UINT64 VatosAddress; /// Model UINT32 Model; /// GSIV of the Event interrupt if SPI based UINT32 EventInterrupt; /// PRI Interrupt if SPI based UINT32 PriInterrupt; /// GERR interrupt if GSIV based UINT32 GerrInterrupt; /// Sync interrupt if GSIV based UINT32 SyncInterrupt; /// Proximity domain flag UINT32 ProximityDomain; /// Index into the array of ID mapping UINT32 DeviceIdMappingIndex; } CM_ARM_SMMUV3_NODE; /** A structure that describes the PMCG node for the Platform. ID: EArmObjPmcg */ typedef struct CmArmPmcgNode { /// An unique token used to identify this object CM_OBJECT_TOKEN Token; /// Number of ID mappings UINT32 IdMappingCount; /// Reference token for the ID mapping array CM_OBJECT_TOKEN IdMappingToken; /// Base Address for performance monitor counter group UINT64 BaseAddress; /// GSIV for the Overflow interrupt UINT32 OverflowInterrupt; /// Page 1 Base address UINT64 Page1BaseAddress; /// Reference token for the IORT node associated with this node CM_OBJECT_TOKEN ReferenceToken; } CM_ARM_PMCG_NODE; /** A structure that describes the ID Mappings for the Platform. ID: EArmObjIdMappingArray */ typedef struct CmArmIdMapping { /// Input base UINT32 InputBase; /// Number of input IDs UINT32 NumIds; /// Output Base UINT32 OutputBase; /// Reference token for the output node CM_OBJECT_TOKEN OutputReferenceToken; /// Flags UINT32 Flags; } CM_ARM_ID_MAPPING; /** A structure that describes the Arm Generic Interrupts. */ typedef struct CmArmGenericInterrupt { /// Interrupt number UINT32 Interrupt; /// Flags UINT32 Flags; } CM_ARM_GENERIC_INTERRUPT; /** A structure that describes the SMMU interrupts for the Platform. Interrupt Interrupt number. Flags Interrupt flags as defined for SMMU node. ID: EArmObjSmmuInterruptArray */ typedef CM_ARM_GENERIC_INTERRUPT CM_ARM_SMMU_INTERRUPT; /** A structure that describes the AML Extended Interrupts. Interrupt Interrupt number. Flags Interrupt flags as defined by the Interrupt Vector Flags (Byte 3) of the Extended Interrupt resource descriptor. See EFI_ACPI_EXTENDED_INTERRUPT_FLAG_xxx in Acpi10.h ID: EArmObjExtendedInterruptInfo */ typedef CM_ARM_GENERIC_INTERRUPT CM_ARM_EXTENDED_INTERRUPT; /** A structure that describes the Processor Hierarchy Node (Type 0) in PPTT ID: EArmObjProcHierarchyInfo */ typedef struct CmArmProcHierarchyInfo { /// A unique token used to identify this object CM_OBJECT_TOKEN Token; /// Processor structure flags (ACPI 6.3 - January 2019, PPTT, Table 5-155) UINT32 Flags; /// Token for the parent CM_ARM_PROC_HIERARCHY_INFO object in the processor /// topology. A value of CM_NULL_TOKEN means this node has no parent. CM_OBJECT_TOKEN ParentToken; /// Token of the associated CM_ARM_GICC_INFO object which has the /// corresponding ACPI Processor ID. A value of CM_NULL_TOKEN means this /// node represents a group of associated processors and it does not have an /// associated GIC CPU interface. CM_OBJECT_TOKEN GicCToken; /// Number of resources private to this Node UINT32 NoOfPrivateResources; /// Token of the array which contains references to the resources private to /// this CM_ARM_PROC_HIERARCHY_INFO instance. This field is ignored if /// the NoOfPrivateResources is 0, in which case it is recommended to set /// this field to CM_NULL_TOKEN. CM_OBJECT_TOKEN PrivateResourcesArrayToken; } CM_ARM_PROC_HIERARCHY_INFO; /** A structure that describes the Cache Type Structure (Type 1) in PPTT ID: EArmObjCacheInfo */ typedef struct CmArmCacheInfo { /// A unique token used to identify this object CM_OBJECT_TOKEN Token; /// Reference token for the next level of cache that is private to the same /// CM_ARM_PROC_HIERARCHY_INFO instance. A value of CM_NULL_TOKEN means this /// entry represents the last cache level appropriate to the processor /// hierarchy node structures using this entry. CM_OBJECT_TOKEN NextLevelOfCacheToken; /// Size of the cache in bytes UINT32 Size; /// Number of sets in the cache UINT32 NumberOfSets; /// Integer number of ways. The maximum associativity supported by /// ACPI Cache type structure is limited to MAX_UINT8. However, /// the maximum number of ways supported by the architecture is /// PPTT_ARM_CCIDX_CACHE_ASSOCIATIVITY_MAX. Therfore this field /// is 32-bit wide. UINT32 Associativity; /// Cache attributes (ACPI 6.3 - January 2019, PPTT, Table 5-156) UINT8 Attributes; /// Line size in bytes UINT16 LineSize; } CM_ARM_CACHE_INFO; /** A structure that describes the ID Structure (Type 2) in PPTT ID: EArmObjProcNodeIdInfo */ typedef struct CmArmProcNodeIdInfo { /// A unique token used to identify this object CM_OBJECT_TOKEN Token; // Vendor ID (as described in ACPI ID registry) UINT32 VendorId; /// First level unique node ID UINT64 Level1Id; /// Second level unique node ID UINT64 Level2Id; /// Major revision of the node UINT16 MajorRev; /// Minor revision of the node UINT16 MinorRev; /// Spin revision of the node UINT16 SpinRev; } CM_ARM_PROC_NODE_ID_INFO; /** A structure that describes a reference to another Configuration Manager object. This is useful for creating an array of reference tokens. The framework can then query the configuration manager for these arrays using the object ID EArmObjCmRef. This can be used is to represent one-to-many relationships between objects. ID: EArmObjCmRef */ typedef struct CmArmObjRef { /// Token of the CM object being referenced CM_OBJECT_TOKEN ReferenceToken; } CM_ARM_OBJ_REF; /** A structure that describes the Memory Affinity Structure (Type 1) in SRAT ID: EArmObjMemoryAffinityInfo */ typedef struct CmArmMemoryAffinityInfo { /// The proximity domain to which the "range of memory" belongs. UINT32 ProximityDomain; /// Base Address UINT64 BaseAddress; /// Length UINT64 Length; /// Flags UINT32 Flags; } CM_ARM_MEMORY_AFFINITY_INFO; /** A structure that describes the ACPI Device Handle (Type 0) in the Generic Initiator Affinity structure in SRAT ID: EArmObjDeviceHandleAcpi */ typedef struct CmArmDeviceHandleAcpi { /// Hardware ID UINT64 Hid; /// Unique Id UINT32 Uid; } CM_ARM_DEVICE_HANDLE_ACPI; /** A structure that describes the PCI Device Handle (Type 1) in the Generic Initiator Affinity structure in SRAT ID: EArmObjDeviceHandlePci */ typedef struct CmArmDeviceHandlePci { /// PCI Segment Number UINT16 SegmentNumber; /// PCI Bus Number - Max 256 busses (Bits 15:8 of BDF) UINT8 BusNumber; /// PCI Device Number - Max 32 devices (Bits 7:3 of BDF) UINT8 DeviceNumber; /// PCI Function Number - Max 8 functions (Bits 2:0 of BDF) UINT8 FunctionNumber; } CM_ARM_DEVICE_HANDLE_PCI; /** A structure that describes the Generic Initiator Affinity structure in SRAT ID: EArmObjGenericInitiatorAffinityInfo */ typedef struct CmArmGenericInitiatorAffinityInfo { /// The proximity domain to which the generic initiator belongs. UINT32 ProximityDomain; /// Flags UINT32 Flags; /// Device Handle Type UINT8 DeviceHandleType; /// Reference Token for the Device Handle CM_OBJECT_TOKEN DeviceHandleToken; } CM_ARM_GENERIC_INITIATOR_AFFINITY_INFO; /** A structure that describes the CMN-600 hardware. ID: EArmObjCmn600Info */ typedef struct CmArmCmn600Info { /// The PERIPHBASE address. /// Corresponds to the Configuration Node Region (CFGR) base address. UINT64 PeriphBaseAddress; /// The PERIPHBASE address length. /// Corresponds to the CFGR base address length. UINT64 PeriphBaseAddressLength; /// The ROOTNODEBASE address. /// Corresponds to the Root node (ROOT) base address. UINT64 RootNodeBaseAddress; /// The Debug and Trace Logic Controller (DTC) count. /// CMN-600 can have maximum 4 DTCs. UINT8 DtcCount; /// DTC Interrupt list. /// The first interrupt resource descriptor pertains to /// DTC[0], the second to DTC[1] and so on. /// DtcCount determines the number of DTC Interrupts that /// are populated. If DTC count is 2 then DtcInterrupt[2] /// and DtcInterrupt[3] are ignored. /// Note: The size of CM_ARM_CMN_600_INFO structure remains /// constant and does not vary with the DTC count. CM_ARM_EXTENDED_INTERRUPT DtcInterrupt[4]; } CM_ARM_CMN_600_INFO; #pragma pack() #endif // ARM_NAMESPACE_OBJECTS_H_
NaohiroTamura/edk2
OvmfPkg/AcpiPlatformDxe/Qemu.c
/** @file OVMF ACPI QEMU support Copyright (c) 2008 - 2014, Intel Corporation. All rights reserved.<BR> Copyright (C) 2012-2014, Red Hat, Inc. SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "AcpiPlatform.h" #include <Library/BaseMemoryLib.h> #include <Library/MemoryAllocationLib.h> #include <Library/QemuFwCfgLib.h> #include <Library/DxeServicesTableLib.h> #include <Library/PcdLib.h> #include <Library/OrderedCollectionLib.h> #include <IndustryStandard/Acpi.h> BOOLEAN QemuDetected ( VOID ) { if (!QemuFwCfgIsAvailable ()) { return FALSE; } return TRUE; } STATIC UINTN CountBits16 ( UINT16 Mask ) { // // For all N >= 1, N bits are enough to represent the number of bits set // among N bits. It's true for N == 1. When adding a new bit (N := N+1), // the maximum number of possibly set bits increases by one, while the // representable maximum doubles. // Mask = ((Mask & 0xAAAA) >> 1) + (Mask & 0x5555); Mask = ((Mask & 0xCCCC) >> 2) + (Mask & 0x3333); Mask = ((Mask & 0xF0F0) >> 4) + (Mask & 0x0F0F); Mask = ((Mask & 0xFF00) >> 8) + (Mask & 0x00FF); return Mask; } STATIC EFI_STATUS EFIAPI QemuInstallAcpiMadtTable ( IN EFI_ACPI_TABLE_PROTOCOL *AcpiProtocol, IN VOID *AcpiTableBuffer, IN UINTN AcpiTableBufferSize, OUT UINTN *TableKey ) { UINTN CpuCount; UINTN PciLinkIsoCount; UINTN NewBufferSize; EFI_ACPI_1_0_MULTIPLE_APIC_DESCRIPTION_TABLE_HEADER *Madt; EFI_ACPI_1_0_PROCESSOR_LOCAL_APIC_STRUCTURE *LocalApic; EFI_ACPI_1_0_IO_APIC_STRUCTURE *IoApic; EFI_ACPI_1_0_INTERRUPT_SOURCE_OVERRIDE_STRUCTURE *Iso; EFI_ACPI_1_0_LOCAL_APIC_NMI_STRUCTURE *LocalApicNmi; VOID *Ptr; UINTN Loop; EFI_STATUS Status; ASSERT (AcpiTableBufferSize >= sizeof (EFI_ACPI_DESCRIPTION_HEADER)); QemuFwCfgSelectItem (QemuFwCfgItemSmpCpuCount); CpuCount = QemuFwCfgRead16 (); ASSERT (CpuCount >= 1); // // Set Level-tiggered, Active High for these identity mapped IRQs. The bitset // corresponds to the union of all possible interrupt assignments for the LNKA, // LNKB, LNKC, LNKD PCI interrupt lines. See the DSDT. // PciLinkIsoCount = CountBits16 (PcdGet16 (Pcd8259LegacyModeEdgeLevel)); NewBufferSize = 1 * sizeof (*Madt) + CpuCount * sizeof (*LocalApic) + 1 * sizeof (*IoApic) + (1 + PciLinkIsoCount) * sizeof (*Iso) + 1 * sizeof (*LocalApicNmi); Madt = AllocatePool (NewBufferSize); if (Madt == NULL) { return EFI_OUT_OF_RESOURCES; } CopyMem (&(Madt->Header), AcpiTableBuffer, sizeof (EFI_ACPI_DESCRIPTION_HEADER)); Madt->Header.Length = (UINT32) NewBufferSize; Madt->LocalApicAddress = PcdGet32 (PcdCpuLocalApicBaseAddress); Madt->Flags = EFI_ACPI_1_0_PCAT_COMPAT; Ptr = Madt + 1; LocalApic = Ptr; for (Loop = 0; Loop < CpuCount; ++Loop) { LocalApic->Type = EFI_ACPI_1_0_PROCESSOR_LOCAL_APIC; LocalApic->Length = sizeof (*LocalApic); LocalApic->AcpiProcessorId = (UINT8) Loop; LocalApic->ApicId = (UINT8) Loop; LocalApic->Flags = 1; // enabled ++LocalApic; } Ptr = LocalApic; IoApic = Ptr; IoApic->Type = EFI_ACPI_1_0_IO_APIC; IoApic->Length = sizeof (*IoApic); IoApic->IoApicId = (UINT8) CpuCount; IoApic->Reserved = EFI_ACPI_RESERVED_BYTE; IoApic->IoApicAddress = 0xFEC00000; IoApic->SystemVectorBase = 0x00000000; Ptr = IoApic + 1; // // IRQ0 (8254 Timer) => IRQ2 (PIC) Interrupt Source Override Structure // Iso = Ptr; Iso->Type = EFI_ACPI_1_0_INTERRUPT_SOURCE_OVERRIDE; Iso->Length = sizeof (*Iso); Iso->Bus = 0x00; // ISA Iso->Source = 0x00; // IRQ0 Iso->GlobalSystemInterruptVector = 0x00000002; Iso->Flags = 0x0000; // Conforms to specs of the bus ++Iso; // // Set Level-triggered, Active High for all possible PCI link targets. // for (Loop = 0; Loop < 16; ++Loop) { if ((PcdGet16 (Pcd8259LegacyModeEdgeLevel) & (1 << Loop)) == 0) { continue; } Iso->Type = EFI_ACPI_1_0_INTERRUPT_SOURCE_OVERRIDE; Iso->Length = sizeof (*Iso); Iso->Bus = 0x00; // ISA Iso->Source = (UINT8) Loop; Iso->GlobalSystemInterruptVector = (UINT32) Loop; Iso->Flags = 0x000D; // Level-triggered, Active High ++Iso; } ASSERT ( (UINTN) (Iso - (EFI_ACPI_1_0_INTERRUPT_SOURCE_OVERRIDE_STRUCTURE *)Ptr) == 1 + PciLinkIsoCount ); Ptr = Iso; LocalApicNmi = Ptr; LocalApicNmi->Type = EFI_ACPI_1_0_LOCAL_APIC_NMI; LocalApicNmi->Length = sizeof (*LocalApicNmi); LocalApicNmi->AcpiProcessorId = 0xFF; // applies to all processors // // polarity and trigger mode of the APIC I/O input signals conform to the // specifications of the bus // LocalApicNmi->Flags = 0x0000; // // Local APIC interrupt input LINTn to which NMI is connected. // LocalApicNmi->LocalApicInti = 0x01; Ptr = LocalApicNmi + 1; ASSERT ((UINTN) ((UINT8 *)Ptr - (UINT8 *)Madt) == NewBufferSize); Status = InstallAcpiTable (AcpiProtocol, Madt, NewBufferSize, TableKey); FreePool (Madt); return Status; } #pragma pack(1) typedef struct { UINT64 Base; UINT64 End; UINT64 Length; } PCI_WINDOW; typedef struct { PCI_WINDOW PciWindow32; PCI_WINDOW PciWindow64; } FIRMWARE_DATA; typedef struct { UINT8 BytePrefix; UINT8 ByteValue; } AML_BYTE; typedef struct { UINT8 NameOp; UINT8 RootChar; UINT8 NameChar[4]; UINT8 PackageOp; UINT8 PkgLength; UINT8 NumElements; AML_BYTE Pm1aCntSlpTyp; AML_BYTE Pm1bCntSlpTyp; AML_BYTE Reserved[2]; } SYSTEM_STATE_PACKAGE; #pragma pack() STATIC EFI_STATUS EFIAPI PopulateFwData( OUT FIRMWARE_DATA *FwData ) { EFI_STATUS Status; UINTN NumDesc; EFI_GCD_MEMORY_SPACE_DESCRIPTOR *AllDesc; Status = gDS->GetMemorySpaceMap (&NumDesc, &AllDesc); if (Status == EFI_SUCCESS) { UINT64 NonMmio32MaxExclTop; UINT64 Mmio32MinBase; UINT64 Mmio32MaxExclTop; UINTN CurDesc; Status = EFI_UNSUPPORTED; NonMmio32MaxExclTop = 0; Mmio32MinBase = BASE_4GB; Mmio32MaxExclTop = 0; for (CurDesc = 0; CurDesc < NumDesc; ++CurDesc) { CONST EFI_GCD_MEMORY_SPACE_DESCRIPTOR *Desc; UINT64 ExclTop; Desc = &AllDesc[CurDesc]; ExclTop = Desc->BaseAddress + Desc->Length; if (ExclTop <= (UINT64) PcdGet32 (PcdOvmfFdBaseAddress)) { switch (Desc->GcdMemoryType) { case EfiGcdMemoryTypeNonExistent: break; case EfiGcdMemoryTypeReserved: case EfiGcdMemoryTypeSystemMemory: if (NonMmio32MaxExclTop < ExclTop) { NonMmio32MaxExclTop = ExclTop; } break; case EfiGcdMemoryTypeMemoryMappedIo: if (Mmio32MinBase > Desc->BaseAddress) { Mmio32MinBase = Desc->BaseAddress; } if (Mmio32MaxExclTop < ExclTop) { Mmio32MaxExclTop = ExclTop; } break; default: ASSERT(0); } } } if (Mmio32MinBase < NonMmio32MaxExclTop) { Mmio32MinBase = NonMmio32MaxExclTop; } if (Mmio32MinBase < Mmio32MaxExclTop) { FwData->PciWindow32.Base = Mmio32MinBase; FwData->PciWindow32.End = Mmio32MaxExclTop - 1; FwData->PciWindow32.Length = Mmio32MaxExclTop - Mmio32MinBase; FwData->PciWindow64.Base = 0; FwData->PciWindow64.End = 0; FwData->PciWindow64.Length = 0; Status = EFI_SUCCESS; } FreePool (AllDesc); } DEBUG (( DEBUG_INFO, "ACPI PciWindow32: Base=0x%08lx End=0x%08lx Length=0x%08lx\n", FwData->PciWindow32.Base, FwData->PciWindow32.End, FwData->PciWindow32.Length )); DEBUG (( DEBUG_INFO, "ACPI PciWindow64: Base=0x%08lx End=0x%08lx Length=0x%08lx\n", FwData->PciWindow64.Base, FwData->PciWindow64.End, FwData->PciWindow64.Length )); return Status; } STATIC VOID EFIAPI GetSuspendStates ( UINTN *SuspendToRamSize, SYSTEM_STATE_PACKAGE *SuspendToRam, UINTN *SuspendToDiskSize, SYSTEM_STATE_PACKAGE *SuspendToDisk ) { STATIC CONST SYSTEM_STATE_PACKAGE Template = { 0x08, // NameOp '\\', // RootChar { '_', 'S', 'x', '_' }, // NameChar[4] 0x12, // PackageOp 0x0A, // PkgLength 0x04, // NumElements { 0x0A, 0x00 }, // Pm1aCntSlpTyp { 0x0A, 0x00 }, // Pm1bCntSlpTyp -- we don't support it { // Reserved[2] { 0x0A, 0x00 }, { 0x0A, 0x00 } } }; RETURN_STATUS Status; FIRMWARE_CONFIG_ITEM FwCfgItem; UINTN FwCfgSize; UINT8 SystemStates[6]; // // configure defaults // *SuspendToRamSize = sizeof Template; CopyMem (SuspendToRam, &Template, sizeof Template); SuspendToRam->NameChar[2] = '3'; // S3 SuspendToRam->Pm1aCntSlpTyp.ByteValue = 1; // PIIX4: STR *SuspendToDiskSize = sizeof Template; CopyMem (SuspendToDisk, &Template, sizeof Template); SuspendToDisk->NameChar[2] = '4'; // S4 SuspendToDisk->Pm1aCntSlpTyp.ByteValue = 2; // PIIX4: POSCL // // check for overrides // Status = QemuFwCfgFindFile ("etc/system-states", &FwCfgItem, &FwCfgSize); if (Status != RETURN_SUCCESS || FwCfgSize != sizeof SystemStates) { DEBUG ((DEBUG_INFO, "ACPI using S3/S4 defaults\n")); return; } QemuFwCfgSelectItem (FwCfgItem); QemuFwCfgReadBytes (sizeof SystemStates, SystemStates); // // Each byte corresponds to a system state. In each byte, the MSB tells us // whether the given state is enabled. If so, the three LSBs specify the // value to be written to the PM control register's SUS_TYP bits. // if (SystemStates[3] & BIT7) { SuspendToRam->Pm1aCntSlpTyp.ByteValue = SystemStates[3] & (BIT2 | BIT1 | BIT0); DEBUG ((DEBUG_INFO, "ACPI S3 value: %d\n", SuspendToRam->Pm1aCntSlpTyp.ByteValue)); } else { *SuspendToRamSize = 0; DEBUG ((DEBUG_INFO, "ACPI S3 disabled\n")); } if (SystemStates[4] & BIT7) { SuspendToDisk->Pm1aCntSlpTyp.ByteValue = SystemStates[4] & (BIT2 | BIT1 | BIT0); DEBUG ((DEBUG_INFO, "ACPI S4 value: %d\n", SuspendToDisk->Pm1aCntSlpTyp.ByteValue)); } else { *SuspendToDiskSize = 0; DEBUG ((DEBUG_INFO, "ACPI S4 disabled\n")); } } STATIC EFI_STATUS EFIAPI QemuInstallAcpiSsdtTable ( IN EFI_ACPI_TABLE_PROTOCOL *AcpiProtocol, IN VOID *AcpiTableBuffer, IN UINTN AcpiTableBufferSize, OUT UINTN *TableKey ) { EFI_STATUS Status; FIRMWARE_DATA *FwData; Status = EFI_OUT_OF_RESOURCES; FwData = AllocateReservedPool (sizeof (*FwData)); if (FwData != NULL) { UINTN SuspendToRamSize; SYSTEM_STATE_PACKAGE SuspendToRam; UINTN SuspendToDiskSize; SYSTEM_STATE_PACKAGE SuspendToDisk; UINTN SsdtSize; UINT8 *Ssdt; GetSuspendStates (&SuspendToRamSize, &SuspendToRam, &SuspendToDiskSize, &SuspendToDisk); SsdtSize = AcpiTableBufferSize + 17 + SuspendToRamSize + SuspendToDiskSize; Ssdt = AllocatePool (SsdtSize); if (Ssdt != NULL) { Status = PopulateFwData (FwData); if (Status == EFI_SUCCESS) { UINT8 *SsdtPtr; SsdtPtr = Ssdt; CopyMem (SsdtPtr, AcpiTableBuffer, AcpiTableBufferSize); SsdtPtr += AcpiTableBufferSize; // // build "OperationRegion(FWDT, SystemMemory, 0x12345678, 0x87654321)" // *(SsdtPtr++) = 0x5B; // ExtOpPrefix *(SsdtPtr++) = 0x80; // OpRegionOp *(SsdtPtr++) = 'F'; *(SsdtPtr++) = 'W'; *(SsdtPtr++) = 'D'; *(SsdtPtr++) = 'T'; *(SsdtPtr++) = 0x00; // SystemMemory *(SsdtPtr++) = 0x0C; // DWordPrefix // // no virtual addressing yet, take the four least significant bytes // CopyMem(SsdtPtr, &FwData, 4); SsdtPtr += 4; *(SsdtPtr++) = 0x0C; // DWordPrefix *(UINT32*) SsdtPtr = sizeof (*FwData); SsdtPtr += 4; // // add suspend system states // CopyMem (SsdtPtr, &SuspendToRam, SuspendToRamSize); SsdtPtr += SuspendToRamSize; CopyMem (SsdtPtr, &SuspendToDisk, SuspendToDiskSize); SsdtPtr += SuspendToDiskSize; ASSERT((UINTN) (SsdtPtr - Ssdt) == SsdtSize); ((EFI_ACPI_DESCRIPTION_HEADER *) Ssdt)->Length = (UINT32) SsdtSize; Status = InstallAcpiTable (AcpiProtocol, Ssdt, SsdtSize, TableKey); } FreePool(Ssdt); } if (Status != EFI_SUCCESS) { FreePool(FwData); } } return Status; } EFI_STATUS EFIAPI QemuInstallAcpiTable ( IN EFI_ACPI_TABLE_PROTOCOL *AcpiProtocol, IN VOID *AcpiTableBuffer, IN UINTN AcpiTableBufferSize, OUT UINTN *TableKey ) { EFI_ACPI_DESCRIPTION_HEADER *Hdr; EFI_ACPI_TABLE_INSTALL_ACPI_TABLE TableInstallFunction; Hdr = (EFI_ACPI_DESCRIPTION_HEADER*) AcpiTableBuffer; switch (Hdr->Signature) { case EFI_ACPI_1_0_APIC_SIGNATURE: TableInstallFunction = QemuInstallAcpiMadtTable; break; case EFI_ACPI_1_0_SECONDARY_SYSTEM_DESCRIPTION_TABLE_SIGNATURE: TableInstallFunction = QemuInstallAcpiSsdtTable; break; default: TableInstallFunction = InstallAcpiTable; } return TableInstallFunction ( AcpiProtocol, AcpiTableBuffer, AcpiTableBufferSize, TableKey ); }
NaohiroTamura/edk2
OvmfPkg/CpuHotplugSmm/QemuCpuhp.h
/** @file Simple wrapper functions and utility functions that access QEMU's modern CPU hotplug register block. These functions manipulate some of the registers described in "docs/specs/acpi_cpu_hotplug.txt" in the QEMU source. IO Ports are accessed via EFI_MM_CPU_IO_PROTOCOL. If a protocol call fails, these functions don't return. Copyright (c) 2020, Red Hat, Inc. SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef QEMU_CPUHP_H_ #define QEMU_CPUHP_H_ #include <Protocol/MmCpuIo.h> // EFI_MM_CPU_IO_PROTOCOL #include <Uefi/UefiBaseType.h> // EFI_STATUS #include "ApicId.h" // APIC_ID UINT32 QemuCpuhpReadCommandData2 ( IN CONST EFI_MM_CPU_IO_PROTOCOL *MmCpuIo ); UINT8 QemuCpuhpReadCpuStatus ( IN CONST EFI_MM_CPU_IO_PROTOCOL *MmCpuIo ); UINT32 QemuCpuhpReadCommandData ( IN CONST EFI_MM_CPU_IO_PROTOCOL *MmCpuIo ); VOID QemuCpuhpWriteCpuSelector ( IN CONST EFI_MM_CPU_IO_PROTOCOL *MmCpuIo, IN UINT32 Selector ); VOID QemuCpuhpWriteCommand ( IN CONST EFI_MM_CPU_IO_PROTOCOL *MmCpuIo, IN UINT8 Command ); EFI_STATUS QemuCpuhpCollectApicIds ( IN CONST EFI_MM_CPU_IO_PROTOCOL *MmCpuIo, IN UINT32 PossibleCpuCount, IN UINT32 ApicIdCount, OUT APIC_ID *PluggedApicIds, OUT UINT32 *PluggedCount, OUT APIC_ID *ToUnplugApicIds, OUT UINT32 *ToUnplugCount ); #endif // QEMU_CPUHP_H_
NaohiroTamura/edk2
NetworkPkg/Include/Library/HttpLib.h
<filename>NetworkPkg/Include/Library/HttpLib.h /** @file This library is used to share code between UEFI network stack modules. It provides the helper routines to parse the HTTP message byte stream. Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR> (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef _HTTP_LIB_H_ #define _HTTP_LIB_H_ #include <Protocol/Http.h> /** Decode a percent-encoded URI component to the ASCII character. Decode the input component in Buffer according to RFC 3986. The caller is responsible to make sure ResultBuffer points to a buffer with size equal or greater than ((AsciiStrSize (Buffer)) in bytes. @param[in] Buffer The pointer to a percent-encoded URI component. @param[in] BufferLength Length of Buffer in bytes. @param[out] ResultBuffer Point to the buffer to store the decode result. @param[out] ResultLength Length of decoded string in ResultBuffer in bytes. @retval EFI_SUCCESS Successfully decoded the URI. @retval EFI_INVALID_PARAMETER Buffer is not a valid percent-encoded string. **/ EFI_STATUS EFIAPI UriPercentDecode ( IN CHAR8 *Buffer, IN UINT32 BufferLength, OUT CHAR8 *ResultBuffer, OUT UINT32 *ResultLength ); /** Create a URL parser for the input URL string. This function will parse and dereference the input HTTP URL into it components. The original content of the URL won't be modified and the result will be returned in UrlParser, which can be used in other functions like NetHttpUrlGetHostName(). It is the caller's responsibility to free the buffer returned in *UrlParser by HttpUrlFreeParser(). @param[in] Url The pointer to a HTTP URL string. @param[in] Length Length of Url in bytes. @param[in] IsConnectMethod Whether the Url is used in HTTP CONNECT method or not. @param[out] UrlParser Pointer to the returned buffer to store the parse result. @retval EFI_SUCCESS Successfully dereferenced the HTTP URL. @retval EFI_INVALID_PARAMETER UrlParser is NULL or Url is not a valid HTTP URL. @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources. **/ EFI_STATUS EFIAPI HttpParseUrl ( IN CHAR8 *Url, IN UINT32 Length, IN BOOLEAN IsConnectMethod, OUT VOID **UrlParser ); /** Get the Hostname from a HTTP URL. This function will return the HostName according to the Url and previous parse result ,and it is the caller's responsibility to free the buffer returned in *HostName. @param[in] Url The pointer to a HTTP URL string. @param[in] UrlParser URL Parse result returned by NetHttpParseUrl(). @param[out] HostName Pointer to a buffer to store the HostName. @retval EFI_SUCCESS Successfully get the required component. @retval EFI_INVALID_PARAMETER Uri is NULL or HostName is NULL or UrlParser is invalid. @retval EFI_NOT_FOUND No hostName component in the URL. @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources. **/ EFI_STATUS EFIAPI HttpUrlGetHostName ( IN CHAR8 *Url, IN VOID *UrlParser, OUT CHAR8 **HostName ); /** Get the IPv4 address from a HTTP URL. This function will return the IPv4 address according to the Url and previous parse result. @param[in] Url The pointer to a HTTP URL string. @param[in] UrlParser URL Parse result returned by NetHttpParseUrl(). @param[out] Ip4Address Pointer to a buffer to store the IP address. @retval EFI_SUCCESS Successfully get the required component. @retval EFI_INVALID_PARAMETER Uri is NULL or Ip4Address is NULL or UrlParser is invalid. @retval EFI_NOT_FOUND No IPv4 address component in the URL. @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources. **/ EFI_STATUS EFIAPI HttpUrlGetIp4 ( IN CHAR8 *Url, IN VOID *UrlParser, OUT EFI_IPv4_ADDRESS *Ip4Address ); /** Get the IPv6 address from a HTTP URL. This function will return the IPv6 address according to the Url and previous parse result. @param[in] Url The pointer to a HTTP URL string. @param[in] UrlParser URL Parse result returned by NetHttpParseUrl(). @param[out] Ip6Address Pointer to a buffer to store the IP address. @retval EFI_SUCCESS Successfully get the required component. @retval EFI_INVALID_PARAMETER Uri is NULL or Ip6Address is NULL or UrlParser is invalid. @retval EFI_NOT_FOUND No IPv6 address component in the URL. @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources. **/ EFI_STATUS EFIAPI HttpUrlGetIp6 ( IN CHAR8 *Url, IN VOID *UrlParser, OUT EFI_IPv6_ADDRESS *Ip6Address ); /** Get the port number from a HTTP URL. This function will return the port number according to the Url and previous parse result. @param[in] Url The pointer to a HTTP URL string. @param[in] UrlParser URL Parse result returned by NetHttpParseUrl(). @param[out] Port Pointer to a buffer to store the port number. @retval EFI_SUCCESS Successfully get the required component. @retval EFI_INVALID_PARAMETER Uri is NULL or Port is NULL or UrlParser is invalid. @retval EFI_NOT_FOUND No port number in the URL. @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources. **/ EFI_STATUS EFIAPI HttpUrlGetPort ( IN CHAR8 *Url, IN VOID *UrlParser, OUT UINT16 *Port ); /** Get the Path from a HTTP URL. This function will return the Path according to the Url and previous parse result,and it is the caller's responsibility to free the buffer returned in *Path. @param[in] Url The pointer to a HTTP URL string. @param[in] UrlParser URL Parse result returned by NetHttpParseUrl(). @param[out] Path Pointer to a buffer to store the Path. @retval EFI_SUCCESS Successfully get the required component. @retval EFI_INVALID_PARAMETER Uri is NULL or HostName is NULL or UrlParser is invalid. @retval EFI_NOT_FOUND No hostName component in the URL. @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources. **/ EFI_STATUS EFIAPI HttpUrlGetPath ( IN CHAR8 *Url, IN VOID *UrlParser, OUT CHAR8 **Path ); /** Release the resource of the URL parser. @param[in] UrlParser Pointer to the parser. **/ VOID EFIAPI HttpUrlFreeParser ( IN VOID *UrlParser ); // // HTTP body parser interface. // typedef enum { // // Part of entity data. // Length of entity body in Data. // BodyParseEventOnData, // // End of message body. // Length is 0 and Data points to next byte after the end of the message. // BodyParseEventOnComplete } HTTP_BODY_PARSE_EVENT; /** A callback function to intercept events during message parser. This function will be invoked during HttpParseMessageBody() with various events type. An error return status of the callback function will cause the HttpParseMessageBody() aborted. @param[in] EventType Event type of this callback call. @param[in] Data A pointer to data buffer. @param[in] Length Length in bytes of the Data. @param[in] Context Callback context set by HttpInitMsgParser(). @retval EFI_SUCCESS Continue to parser the message body. @retval Others Abort the parse. **/ typedef EFI_STATUS (EFIAPI *HTTP_BODY_PARSER_CALLBACK) ( IN HTTP_BODY_PARSE_EVENT EventType, IN CHAR8 *Data, IN UINTN Length, IN VOID *Context ); /** Initialize a HTTP message-body parser. This function will create and initialize a HTTP message parser according to caller provided HTTP message header information. It is the caller's responsibility to free the buffer returned in *UrlParser by HttpFreeMsgParser(). @param[in] Method The HTTP method (e.g. GET, POST) for this HTTP message. @param[in] StatusCode Response status code returned by the remote host. @param[in] HeaderCount Number of HTTP header structures in Headers. @param[in] Headers Array containing list of HTTP headers. @param[in] Callback Callback function that is invoked when parsing the HTTP message-body, set to NULL to ignore all events. @param[in] Context Pointer to the context that will be passed to Callback. @param[out] MsgParser Pointer to the returned buffer to store the message parser. @retval EFI_SUCCESS Successfully initialized the parser. @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources. @retval EFI_INVALID_PARAMETER MsgParser is NULL or HeaderCount is not NULL but Headers is NULL. @retval Others Failed to initialize the parser. **/ EFI_STATUS EFIAPI HttpInitMsgParser ( IN EFI_HTTP_METHOD Method, IN EFI_HTTP_STATUS_CODE StatusCode, IN UINTN HeaderCount, IN EFI_HTTP_HEADER *Headers, IN HTTP_BODY_PARSER_CALLBACK Callback, IN VOID *Context, OUT VOID **MsgParser ); /** Parse message body. Parse BodyLength of message-body. This function can be called repeatedly to parse the message-body partially. @param[in, out] MsgParser Pointer to the message parser. @param[in] BodyLength Length in bytes of the Body. @param[in] Body Pointer to the buffer of the message-body to be parsed. @retval EFI_SUCCESS Successfully parse the message-body. @retval EFI_INVALID_PARAMETER MsgParser is NULL or Body is NULL or BodyLength is 0. @retval EFI_ABORTED Operation aborted. @retval Other Error happened while parsing message body. **/ EFI_STATUS EFIAPI HttpParseMessageBody ( IN OUT VOID *MsgParser, IN UINTN BodyLength, IN CHAR8 *Body ); /** Check whether the message-body is complete or not. @param[in] MsgParser Pointer to the message parser. @retval TRUE Message-body is complete. @retval FALSE Message-body is not complete. **/ BOOLEAN EFIAPI HttpIsMessageComplete ( IN VOID *MsgParser ); /** Get the content length of the entity. Note that in trunk transfer, the entity length is not valid until the whole message body is received. @param[in] MsgParser Pointer to the message parser. @param[out] ContentLength Pointer to store the length of the entity. @retval EFI_SUCCESS Successfully to get the entity length. @retval EFI_NOT_READY Entity length is not valid yet. @retval EFI_INVALID_PARAMETER MsgParser is NULL or ContentLength is NULL. **/ EFI_STATUS EFIAPI HttpGetEntityLength ( IN VOID *MsgParser, OUT UINTN *ContentLength ); /** Release the resource of the message parser. @param[in] MsgParser Pointer to the message parser. **/ VOID EFIAPI HttpFreeMsgParser ( IN VOID *MsgParser ); /** Find a specified header field according to the field name. @param[in] HeaderCount Number of HTTP header structures in Headers list. @param[in] Headers Array containing list of HTTP headers. @param[in] FieldName Null terminated string which describes a field name. @return Pointer to the found header or NULL. **/ EFI_HTTP_HEADER * EFIAPI HttpFindHeader ( IN UINTN HeaderCount, IN EFI_HTTP_HEADER *Headers, IN CHAR8 *FieldName ); /** Set FieldName and FieldValue into specified HttpHeader. @param[in,out] HttpHeader Specified HttpHeader. @param[in] FieldName FieldName of this HttpHeader, a NULL terminated ASCII string. @param[in] FieldValue FieldValue of this HttpHeader, a NULL terminated ASCII string. @retval EFI_SUCCESS The FieldName and FieldValue are set into HttpHeader successfully. @retval EFI_INVALID_PARAMETER The parameter is invalid. @retval EFI_OUT_OF_RESOURCES Failed to allocate resources. **/ EFI_STATUS EFIAPI HttpSetFieldNameAndValue ( IN OUT EFI_HTTP_HEADER *HttpHeader, IN CONST CHAR8 *FieldName, IN CONST CHAR8 *FieldValue ); /** Get one key/value header pair from the raw string. @param[in] String Pointer to the raw string. @param[out] FieldName Points directly to field name within 'HttpHeader'. @param[out] FieldValue Points directly to field value within 'HttpHeader'. @return Pointer to the next raw string. @return NULL if no key/value header pair from this raw string. **/ CHAR8 * EFIAPI HttpGetFieldNameAndValue ( IN CHAR8 *String, OUT CHAR8 **FieldName, OUT CHAR8 **FieldValue ); /** Free existing HeaderFields. @param[in] HeaderFields Pointer to array of key/value header pairs waiting for free. @param[in] FieldCount The number of header pairs in HeaderFields. **/ VOID EFIAPI HttpFreeHeaderFields ( IN EFI_HTTP_HEADER *HeaderFields, IN UINTN FieldCount ); /** Generate HTTP request message. This function will allocate memory for the whole HTTP message and generate a well formatted HTTP Request message in it, include the Request-Line, header fields and also the message body. It is the caller's responsibility to free the buffer returned in *RequestMsg. @param[in] Message Pointer to the EFI_HTTP_MESSAGE structure which contains the required information to generate the HTTP request message. @param[in] Url The URL of a remote host. @param[out] RequestMsg Pointer to the created HTTP request message. NULL if any error occurred. @param[out] RequestMsgSize Size of the RequestMsg (in bytes). @retval EFI_SUCCESS If HTTP request string was created successfully. @retval EFI_OUT_OF_RESOURCES Failed to allocate resources. @retval EFI_INVALID_PARAMETER The input arguments are invalid. **/ EFI_STATUS EFIAPI HttpGenRequestMessage ( IN CONST EFI_HTTP_MESSAGE *Message, IN CONST CHAR8 *Url, OUT CHAR8 **RequestMsg, OUT UINTN *RequestMsgSize ); /** Translate the status code in HTTP message to EFI_HTTP_STATUS_CODE defined in UEFI 2.5 specification. @param[in] StatusCode The status code value in HTTP message. @return Value defined in EFI_HTTP_STATUS_CODE . **/ EFI_HTTP_STATUS_CODE EFIAPI HttpMappingToStatusCode ( IN UINTN StatusCode ); /** Check whether header field called FieldName is in DeleteList. @param[in] DeleteList Pointer to array of key/value header pairs. @param[in] DeleteCount The number of header pairs. @param[in] FieldName Pointer to header field's name. @return TRUE if FieldName is not in DeleteList, that means this header field is valid. @return FALSE if FieldName is in DeleteList, that means this header field is invalid. **/ BOOLEAN EFIAPI HttpIsValidHttpHeader ( IN CHAR8 *DeleteList[], IN UINTN DeleteCount, IN CHAR8 *FieldName ); #endif
NaohiroTamura/edk2
UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h
<reponame>NaohiroTamura/edk2<filename>UefiPayloadPkg/UefiPayloadEntry/UefiPayloadEntry.h /** @file * * Copyright (c) 2020, Intel Corporation. All rights reserved.<BR> * * SPDX-License-Identifier: BSD-2-Clause-Patent * **/ #ifndef __UEFI_PAYLOAD_ENTRY_H__ #define __UEFI_PAYLOAD_ENTRY_H__ #include <PiPei.h> #include <Library/BaseLib.h> #include <Library/BaseMemoryLib.h> #include <Library/MemoryAllocationLib.h> #include <Library/DebugLib.h> #include <Library/PeCoffLib.h> #include <Library/HobLib.h> #include <Library/PcdLib.h> #include <Guid/MemoryAllocationHob.h> #include <Library/IoLib.h> #include <Library/PeCoffLib.h> #include <Library/BlParseLib.h> #include <Library/PlatformSupportLib.h> #include <Library/UefiCpuLib.h> #include <IndustryStandard/Acpi.h> #include <IndustryStandard/MemoryMappedConfigurationSpaceAccessTable.h> #include <Guid/SerialPortInfoGuid.h> #include <Guid/SystemTableInfoGuid.h> #include <Guid/MemoryMapInfoGuid.h> #include <Guid/AcpiBoardInfoGuid.h> #include <Guid/GraphicsInfoHob.h> #define LEGACY_8259_MASK_REGISTER_MASTER 0x21 #define LEGACY_8259_MASK_REGISTER_SLAVE 0xA1 #define GET_OCCUPIED_SIZE(ActualSize, Alignment) \ ((ActualSize) + (((Alignment) - ((ActualSize) & ((Alignment) - 1))) & ((Alignment) - 1))) /** Auto-generated function that calls the library constructors for all of the module's dependent libraries. **/ VOID EFIAPI ProcessLibraryConstructorList ( VOID ); /** Add a new HOB to the HOB List. @param HobType Type of the new HOB. @param HobLength Length of the new HOB to allocate. @return NULL if there is no space to create a hob. @return The address point to the new created hob. **/ VOID * EFIAPI CreateHob ( IN UINT16 HobType, IN UINT16 HobLength ); /** Update the Stack Hob if the stack has been moved @param BaseAddress The 64 bit physical address of the Stack. @param Length The length of the stack in bytes. **/ VOID EFIAPI UpdateStackHob ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length ); /** Build a Handoff Information Table HOB This function initialize a HOB region from EfiMemoryBegin with length EfiMemoryLength. And EfiFreeMemoryBottom and EfiFreeMemoryTop should be inside the HOB region. @param[in] EfiMemoryBegin Total memory start address @param[in] EfiMemoryLength Total memory length reported in handoff HOB. @param[in] EfiFreeMemoryBottom Free memory start address @param[in] EfiFreeMemoryTop Free memory end address. @return The pointer to the handoff HOB table. **/ EFI_HOB_HANDOFF_INFO_TABLE* EFIAPI HobConstructor ( IN VOID *EfiMemoryBegin, IN UINTN EfiMemoryLength, IN VOID *EfiFreeMemoryBottom, IN VOID *EfiFreeMemoryTop ); /** Find DXE core from FV and build DXE core HOBs. @param[out] DxeCoreEntryPoint DXE core entry point @retval EFI_SUCCESS If it completed successfully. @retval EFI_NOT_FOUND If it failed to load DXE FV. **/ EFI_STATUS LoadDxeCore ( OUT PHYSICAL_ADDRESS *DxeCoreEntryPoint ); /** Transfers control to DxeCore. This function performs a CPU architecture specific operations to execute the entry point of DxeCore with the parameters of HobList. @param DxeCoreEntryPoint The entry point of DxeCore. @param HobList The start of HobList passed to DxeCore. **/ VOID HandOffToDxeCore ( IN EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint, IN EFI_PEI_HOB_POINTERS HobList ); #endif
NaohiroTamura/edk2
ArmPkg/Include/Library/ArmSmcLib.h
<reponame>NaohiroTamura/edk2<gh_stars>1-10 /** @file * * Copyright (c) 2012-2014, ARM Limited. All rights reserved. * * SPDX-License-Identifier: BSD-2-Clause-Patent * **/ #ifndef __ARM_SMC_LIB__ #define __ARM_SMC_LIB__ /** * The size of the SMC arguments are different between AArch64 and AArch32. * The native size is used for the arguments. */ typedef struct { UINTN Arg0; UINTN Arg1; UINTN Arg2; UINTN Arg3; UINTN Arg4; UINTN Arg5; UINTN Arg6; UINTN Arg7; } ARM_SMC_ARGS; /** Trigger an SMC call SMC calls can take up to 7 arguments and return up to 4 return values. Therefore, the 4 first fields in the ARM_SMC_ARGS structure are used for both input and output values. **/ VOID ArmCallSmc ( IN OUT ARM_SMC_ARGS *Args ); #endif
NaohiroTamura/edk2
UefiPayloadPkg/Include/Guid/SerialPortInfoGuid.h
/** @file This file defines the hob structure for serial port. Copyright (c) 2014 - 2019, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef __SERIAL_PORT_INFO_GUID_H__ #define __SERIAL_PORT_INFO_GUID_H__ /// /// Serial Port Information GUID /// extern EFI_GUID gUefiSerialPortInfoGuid; #define PLD_SERIAL_TYPE_IO_MAPPED 1 #define PLD_SERIAL_TYPE_MEMORY_MAPPED 2 typedef struct { UINT8 Revision; UINT8 Reserved0[3]; UINT32 Type; UINT32 BaseAddr; UINT32 Baud; UINT32 RegWidth; UINT32 InputHertz; UINT32 UartPciAddr; } SERIAL_PORT_INFO; #endif
NaohiroTamura/edk2
UefiCpuPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLibNoStm.c
/** @file The CPU specific programming for PiSmmCpuDxeSmm module when STM support is not included. Copyright (c) 2010 - 2016, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <PiSmm.h> #include <Library/SmmCpuFeaturesLib.h> /** Internal worker function that is called to complete CPU initialization at the end of SmmCpuFeaturesInitializeProcessor(). **/ VOID FinishSmmCpuFeaturesInitializeProcessor ( VOID ) { } /** Return the size, in bytes, of a custom SMI Handler in bytes. If 0 is returned, then a custom SMI handler is not provided by this library, and the default SMI handler must be used. @retval 0 Use the default SMI handler. @retval > 0 Use the SMI handler installed by SmmCpuFeaturesInstallSmiHandler() The caller is required to allocate enough SMRAM for each CPU to support the size of the custom SMI handler. **/ UINTN EFIAPI SmmCpuFeaturesGetSmiHandlerSize ( VOID ) { return 0; } /** Install a custom SMI handler for the CPU specified by CpuIndex. This function is only called if SmmCpuFeaturesGetSmiHandlerSize() returns a size is greater than zero and is called by the CPU that was elected as monarch during System Management Mode initialization. @param[in] CpuIndex The index of the CPU to install the custom SMI handler. The value must be between 0 and the NumberOfCpus field in the System Management System Table (SMST). @param[in] SmBase The SMBASE address for the CPU specified by CpuIndex. @param[in] SmiStack The stack to use when an SMI is processed by the the CPU specified by CpuIndex. @param[in] StackSize The size, in bytes, if the stack used when an SMI is processed by the CPU specified by CpuIndex. @param[in] GdtBase The base address of the GDT to use when an SMI is processed by the CPU specified by CpuIndex. @param[in] GdtSize The size, in bytes, of the GDT used when an SMI is processed by the CPU specified by CpuIndex. @param[in] IdtBase The base address of the IDT to use when an SMI is processed by the CPU specified by CpuIndex. @param[in] IdtSize The size, in bytes, of the IDT used when an SMI is processed by the CPU specified by CpuIndex. @param[in] Cr3 The base address of the page tables to use when an SMI is processed by the CPU specified by CpuIndex. **/ VOID EFIAPI SmmCpuFeaturesInstallSmiHandler ( IN UINTN CpuIndex, IN UINT32 SmBase, IN VOID *SmiStack, IN UINTN StackSize, IN UINTN GdtBase, IN UINTN GdtSize, IN UINTN IdtBase, IN UINTN IdtSize, IN UINT32 Cr3 ) { }
NaohiroTamura/edk2
CryptoPkg/Test/UnitTest/Library/BaseCryptLib/TestBaseCryptLib.h
/** @file Application for Cryptographic Primitives Validation. Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef __CRYPTEST_H__ #define __CRYPTEST_H__ #include <PiPei.h> #include <Uefi.h> #include <Library/UefiLib.h> #include <Library/DebugLib.h> #include <Library/UnitTestLib.h> #include <Library/PrintLib.h> #include <Library/BaseCryptLib.h> #include <Library/BaseLib.h> #include <Library/BaseMemoryLib.h> #include <Library/MemoryAllocationLib.h> //#include <UnitTestTypes.h> #include <Library/UnitTestLib.h> //#include <Library/UnitTestAssertLib.h> #define UNIT_TEST_NAME "BaseCryptLib Unit Test" #define UNIT_TEST_VERSION "1.0" typedef struct { CHAR8 *Description; CHAR8 *ClassName; UNIT_TEST_FUNCTION Func; UNIT_TEST_PREREQUISITE PreReq; UNIT_TEST_CLEANUP CleanUp; UNIT_TEST_CONTEXT Context; } TEST_DESC; typedef struct { CHAR8 *Title; CHAR8 *Package; UNIT_TEST_SUITE_SETUP Sup; UNIT_TEST_SUITE_TEARDOWN Tdn; UINTN *TestNum; TEST_DESC *TestDesc; } SUITE_DESC; extern UINTN mPkcs7EkuTestNum; extern TEST_DESC mPkcs7EkuTest[]; extern UINTN mHashTestNum; extern TEST_DESC mHashTest[]; extern UINTN mHmacTestNum; extern TEST_DESC mHmacTest[]; extern UINTN mBlockCipherTestNum; extern TEST_DESC mBlockCipherTest[]; extern UINTN mRsaTestNum; extern TEST_DESC mRsaTest[]; extern UINTN mRsaCertTestNum; extern TEST_DESC mRsaCertTest[]; extern UINTN mPkcs7TestNum; extern TEST_DESC mPkcs7Test[]; extern UINTN mPkcs5TestNum; extern TEST_DESC mPkcs5Test[]; extern UINTN mAuthenticodeTestNum; extern TEST_DESC mAuthenticodeTest[]; extern UINTN mImageTimestampTestNum; extern TEST_DESC mImageTimestampTest[]; extern UINTN mDhTestNum; extern TEST_DESC mDhTest[]; extern UINTN mPrngTestNum; extern TEST_DESC mPrngTest[]; extern UINTN mOaepTestNum; extern TEST_DESC mOaepTest[]; /** Creates a framework you can use */ EFI_STATUS EFIAPI CreateUnitTest ( IN CHAR8* UnitTestName, IN CHAR8* UnitTestVersion, IN OUT UNIT_TEST_FRAMEWORK_HANDLE* Framework ); /** Validate UEFI-OpenSSL DH Interfaces. @retval EFI_SUCCESS Validation succeeded. @retval EFI_ABORTED Validation failed. **/ EFI_STATUS ValidateCryptDh ( VOID ); /** Validate UEFI-OpenSSL pseudorandom number generator interfaces. @retval EFI_SUCCESS Validation succeeded. @retval EFI_ABORTED Validation failed. **/ EFI_STATUS ValidateCryptPrng ( VOID ); #endif
NaohiroTamura/edk2
StandaloneMmPkg/Library/StandaloneMmCoreEntryPoint/AArch64/CreateHobList.c
/** @file Creates HOB during Standalone MM Foundation entry point on ARM platforms. Copyright (c) 2017 - 2018, ARM Ltd. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <PiMm.h> #include <PiPei.h> #include <Guid/MmramMemoryReserve.h> #include <Guid/MpInformation.h> #include <Library/AArch64/StandaloneMmCoreEntryPoint.h> #include <Library/ArmMmuLib.h> #include <Library/ArmSvcLib.h> #include <Library/DebugLib.h> #include <Library/HobLib.h> #include <Library/BaseLib.h> #include <Library/BaseMemoryLib.h> #include <Library/SerialPortLib.h> #include <IndustryStandard/ArmStdSmc.h> extern EFI_HOB_HANDOFF_INFO_TABLE* HobConstructor ( IN VOID *EfiMemoryBegin, IN UINTN EfiMemoryLength, IN VOID *EfiFreeMemoryBottom, IN VOID *EfiFreeMemoryTop ); // GUID to identify HOB with whereabouts of communication buffer with Normal // World extern EFI_GUID gEfiStandaloneMmNonSecureBufferGuid; // GUID to identify HOB where the entry point of the CPU driver will be // populated to allow this entry point driver to invoke it upon receipt of an // event extern EFI_GUID gEfiArmTfCpuDriverEpDescriptorGuid; /** Use the boot information passed by privileged firmware to populate a HOB list suitable for consumption by the MM Core and drivers. @param PayloadBootInfo Boot information passed by privileged firmware **/ VOID * CreateHobListFromBootInfo ( IN OUT PI_MM_ARM_TF_CPU_DRIVER_ENTRYPOINT *CpuDriverEntryPoint, IN EFI_SECURE_PARTITION_BOOT_INFO *PayloadBootInfo ) { EFI_HOB_HANDOFF_INFO_TABLE *HobStart; EFI_RESOURCE_ATTRIBUTE_TYPE Attributes; UINT32 Index; UINT32 BufferSize; UINT32 Flags; EFI_MMRAM_HOB_DESCRIPTOR_BLOCK *MmramRangesHob; EFI_MMRAM_DESCRIPTOR *MmramRanges; EFI_MMRAM_DESCRIPTOR *NsCommBufMmramRange; MP_INFORMATION_HOB_DATA *MpInformationHobData; EFI_PROCESSOR_INFORMATION *ProcInfoBuffer; EFI_SECURE_PARTITION_CPU_INFO *CpuInfo; ARM_TF_CPU_DRIVER_EP_DESCRIPTOR *CpuDriverEntryPointDesc; // Create a hoblist with a PHIT and EOH HobStart = HobConstructor ( (VOID *) PayloadBootInfo->SpMemBase, (UINTN) PayloadBootInfo->SpMemLimit - PayloadBootInfo->SpMemBase, (VOID *) PayloadBootInfo->SpHeapBase, (VOID *) (PayloadBootInfo->SpHeapBase + PayloadBootInfo->SpHeapSize) ); // Check that the Hoblist starts at the bottom of the Heap ASSERT (HobStart == (VOID *) PayloadBootInfo->SpHeapBase); // Build a Boot Firmware Volume HOB BuildFvHob (PayloadBootInfo->SpImageBase, PayloadBootInfo->SpImageSize); // Build a resource descriptor Hob that describes the available physical // memory range Attributes = ( EFI_RESOURCE_ATTRIBUTE_PRESENT | EFI_RESOURCE_ATTRIBUTE_INITIALIZED | EFI_RESOURCE_ATTRIBUTE_TESTED | EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE ); BuildResourceDescriptorHob ( EFI_RESOURCE_SYSTEM_MEMORY, Attributes, (UINTN) PayloadBootInfo->SpMemBase, PayloadBootInfo->SpMemLimit - PayloadBootInfo->SpMemBase ); // Find the size of the GUIDed HOB with MP information BufferSize = sizeof (MP_INFORMATION_HOB_DATA); BufferSize += sizeof (EFI_PROCESSOR_INFORMATION) * PayloadBootInfo->NumCpus; // Create a Guided MP information HOB to enable the ARM TF CPU driver to // perform per-cpu allocations. MpInformationHobData = BuildGuidHob (&gMpInformationHobGuid, BufferSize); // Populate the MP information HOB with the topology information passed by // privileged firmware MpInformationHobData->NumberOfProcessors = PayloadBootInfo->NumCpus; MpInformationHobData->NumberOfEnabledProcessors = PayloadBootInfo->NumCpus; ProcInfoBuffer = MpInformationHobData->ProcessorInfoBuffer; CpuInfo = PayloadBootInfo->CpuInfo; for (Index = 0; Index < PayloadBootInfo->NumCpus; Index++) { ProcInfoBuffer[Index].ProcessorId = CpuInfo[Index].Mpidr; ProcInfoBuffer[Index].Location.Package = GET_CLUSTER_ID(CpuInfo[Index].Mpidr); ProcInfoBuffer[Index].Location.Core = GET_CORE_ID(CpuInfo[Index].Mpidr); ProcInfoBuffer[Index].Location.Thread = GET_CORE_ID(CpuInfo[Index].Mpidr); Flags = PROCESSOR_ENABLED_BIT | PROCESSOR_HEALTH_STATUS_BIT; if (CpuInfo[Index].Flags & CPU_INFO_FLAG_PRIMARY_CPU) { Flags |= PROCESSOR_AS_BSP_BIT; } ProcInfoBuffer[Index].StatusFlag = Flags; } // Create a Guided HOB to tell the ARM TF CPU driver the location and length // of the communication buffer shared with the Normal world. NsCommBufMmramRange = (EFI_MMRAM_DESCRIPTOR *) BuildGuidHob ( &gEfiStandaloneMmNonSecureBufferGuid, sizeof (EFI_MMRAM_DESCRIPTOR) ); NsCommBufMmramRange->PhysicalStart = PayloadBootInfo->SpNsCommBufBase; NsCommBufMmramRange->CpuStart = PayloadBootInfo->SpNsCommBufBase; NsCommBufMmramRange->PhysicalSize = PayloadBootInfo->SpNsCommBufSize; NsCommBufMmramRange->RegionState = EFI_CACHEABLE | EFI_ALLOCATED; // Create a Guided HOB to enable the ARM TF CPU driver to share its entry // point and populate it with the address of the shared buffer CpuDriverEntryPointDesc = (ARM_TF_CPU_DRIVER_EP_DESCRIPTOR *) BuildGuidHob ( &gEfiArmTfCpuDriverEpDescriptorGuid, sizeof (ARM_TF_CPU_DRIVER_EP_DESCRIPTOR) ); *CpuDriverEntryPoint = NULL; CpuDriverEntryPointDesc->ArmTfCpuDriverEpPtr = CpuDriverEntryPoint; // Find the size of the GUIDed HOB with SRAM ranges BufferSize = sizeof (EFI_MMRAM_HOB_DESCRIPTOR_BLOCK); BufferSize += PayloadBootInfo->NumSpMemRegions * sizeof (EFI_MMRAM_DESCRIPTOR); // Create a GUIDed HOB with SRAM ranges MmramRangesHob = BuildGuidHob (&gEfiMmPeiMmramMemoryReserveGuid, BufferSize); // Fill up the number of MMRAM memory regions MmramRangesHob->NumberOfMmReservedRegions = PayloadBootInfo->NumSpMemRegions; // Fill up the MMRAM ranges MmramRanges = &MmramRangesHob->Descriptor[0]; // Base and size of memory occupied by the Standalone MM image MmramRanges[0].PhysicalStart = PayloadBootInfo->SpImageBase; MmramRanges[0].CpuStart = PayloadBootInfo->SpImageBase; MmramRanges[0].PhysicalSize = PayloadBootInfo->SpImageSize; MmramRanges[0].RegionState = EFI_CACHEABLE | EFI_ALLOCATED; // Base and size of buffer shared with privileged Secure world software MmramRanges[1].PhysicalStart = PayloadBootInfo->SpSharedBufBase; MmramRanges[1].CpuStart = PayloadBootInfo->SpSharedBufBase; MmramRanges[1].PhysicalSize = PayloadBootInfo->SpPcpuSharedBufSize * PayloadBootInfo->NumCpus; MmramRanges[1].RegionState = EFI_CACHEABLE | EFI_ALLOCATED; // Base and size of buffer used for synchronous communication with Normal // world software MmramRanges[2].PhysicalStart = PayloadBootInfo->SpNsCommBufBase; MmramRanges[2].CpuStart = PayloadBootInfo->SpNsCommBufBase; MmramRanges[2].PhysicalSize = PayloadBootInfo->SpNsCommBufSize; MmramRanges[2].RegionState = EFI_CACHEABLE | EFI_ALLOCATED; // Base and size of memory allocated for stacks for all cpus MmramRanges[3].PhysicalStart = PayloadBootInfo->SpStackBase; MmramRanges[3].CpuStart = PayloadBootInfo->SpStackBase; MmramRanges[3].PhysicalSize = PayloadBootInfo->SpPcpuStackSize * PayloadBootInfo->NumCpus; MmramRanges[3].RegionState = EFI_CACHEABLE | EFI_ALLOCATED; // Base and size of heap memory shared by all cpus MmramRanges[4].PhysicalStart = (EFI_PHYSICAL_ADDRESS) HobStart; MmramRanges[4].CpuStart = (EFI_PHYSICAL_ADDRESS) HobStart; MmramRanges[4].PhysicalSize = HobStart->EfiFreeMemoryBottom - (EFI_PHYSICAL_ADDRESS) HobStart; MmramRanges[4].RegionState = EFI_CACHEABLE | EFI_ALLOCATED; // Base and size of heap memory shared by all cpus MmramRanges[5].PhysicalStart = HobStart->EfiFreeMemoryBottom; MmramRanges[5].CpuStart = HobStart->EfiFreeMemoryBottom; MmramRanges[5].PhysicalSize = HobStart->EfiFreeMemoryTop - HobStart->EfiFreeMemoryBottom; MmramRanges[5].RegionState = EFI_CACHEABLE; return HobStart; }
NaohiroTamura/edk2
OvmfPkg/PlatformPei/Platform.c
<filename>OvmfPkg/PlatformPei/Platform.c /**@file Platform PEI driver Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR> Copyright (c) 2011, <NAME> <<EMAIL>> SPDX-License-Identifier: BSD-2-Clause-Patent **/ // // The package level header files this module uses // #include <PiPei.h> // // The Library classes this module consumes // #include <Library/BaseLib.h> #include <Library/DebugLib.h> #include <Library/HobLib.h> #include <Library/IoLib.h> #include <Library/MemoryAllocationLib.h> #include <Library/PcdLib.h> #include <Library/PciLib.h> #include <Library/PeimEntryPoint.h> #include <Library/PeiServicesLib.h> #include <Library/QemuFwCfgLib.h> #include <Library/QemuFwCfgS3Lib.h> #include <Library/QemuFwCfgSimpleParserLib.h> #include <Library/ResourcePublicationLib.h> #include <Ppi/MasterBootMode.h> #include <IndustryStandard/I440FxPiix4.h> #include <IndustryStandard/Pci22.h> #include <IndustryStandard/Q35MchIch9.h> #include <IndustryStandard/QemuCpuHotplug.h> #include <OvmfPlatforms.h> #include "Platform.h" #include "Cmos.h" EFI_PEI_PPI_DESCRIPTOR mPpiBootMode[] = { { EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST, &gEfiPeiMasterBootModePpiGuid, NULL } }; UINT16 mHostBridgeDevId; EFI_BOOT_MODE mBootMode = BOOT_WITH_FULL_CONFIGURATION; BOOLEAN mS3Supported = FALSE; UINT32 mMaxCpuCount; VOID AddIoMemoryBaseSizeHob ( EFI_PHYSICAL_ADDRESS MemoryBase, UINT64 MemorySize ) { BuildResourceDescriptorHob ( EFI_RESOURCE_MEMORY_MAPPED_IO, EFI_RESOURCE_ATTRIBUTE_PRESENT | EFI_RESOURCE_ATTRIBUTE_INITIALIZED | EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE | EFI_RESOURCE_ATTRIBUTE_TESTED, MemoryBase, MemorySize ); } VOID AddReservedMemoryBaseSizeHob ( EFI_PHYSICAL_ADDRESS MemoryBase, UINT64 MemorySize, BOOLEAN Cacheable ) { BuildResourceDescriptorHob ( EFI_RESOURCE_MEMORY_RESERVED, EFI_RESOURCE_ATTRIBUTE_PRESENT | EFI_RESOURCE_ATTRIBUTE_INITIALIZED | EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE | (Cacheable ? EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE : 0 ) | EFI_RESOURCE_ATTRIBUTE_TESTED, MemoryBase, MemorySize ); } VOID AddIoMemoryRangeHob ( EFI_PHYSICAL_ADDRESS MemoryBase, EFI_PHYSICAL_ADDRESS MemoryLimit ) { AddIoMemoryBaseSizeHob (MemoryBase, (UINT64)(MemoryLimit - MemoryBase)); } VOID AddMemoryBaseSizeHob ( EFI_PHYSICAL_ADDRESS MemoryBase, UINT64 MemorySize ) { BuildResourceDescriptorHob ( EFI_RESOURCE_SYSTEM_MEMORY, EFI_RESOURCE_ATTRIBUTE_PRESENT | EFI_RESOURCE_ATTRIBUTE_INITIALIZED | EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE | EFI_RESOURCE_ATTRIBUTE_TESTED, MemoryBase, MemorySize ); } VOID AddMemoryRangeHob ( EFI_PHYSICAL_ADDRESS MemoryBase, EFI_PHYSICAL_ADDRESS MemoryLimit ) { AddMemoryBaseSizeHob (MemoryBase, (UINT64)(MemoryLimit - MemoryBase)); } VOID MemMapInitialization ( VOID ) { UINT64 PciIoBase; UINT64 PciIoSize; RETURN_STATUS PcdStatus; PciIoBase = 0xC000; PciIoSize = 0x4000; // // Video memory + Legacy BIOS region // AddIoMemoryRangeHob (0x0A0000, BASE_1MB); if (!mXen) { UINT32 TopOfLowRam; UINT64 PciExBarBase; UINT32 PciBase; UINT32 PciSize; TopOfLowRam = GetSystemMemorySizeBelow4gb (); PciExBarBase = 0; if (mHostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) { // // The MMCONFIG area is expected to fall between the top of low RAM and // the base of the 32-bit PCI host aperture. // PciExBarBase = FixedPcdGet64 (PcdPciExpressBaseAddress); ASSERT (TopOfLowRam <= PciExBarBase); ASSERT (PciExBarBase <= MAX_UINT32 - SIZE_256MB); PciBase = (UINT32)(PciExBarBase + SIZE_256MB); } else { ASSERT (TopOfLowRam <= mQemuUc32Base); PciBase = mQemuUc32Base; } // // address purpose size // ------------ -------- ------------------------- // max(top, 2g) PCI MMIO 0xFC000000 - max(top, 2g) // 0xFC000000 gap 44 MB // 0xFEC00000 IO-APIC 4 KB // 0xFEC01000 gap 1020 KB // 0xFED00000 HPET 1 KB // 0xFED00400 gap 111 KB // 0xFED1C000 gap (PIIX4) / RCRB (ICH9) 16 KB // 0xFED20000 gap 896 KB // 0xFEE00000 LAPIC 1 MB // PciSize = 0xFC000000 - PciBase; AddIoMemoryBaseSizeHob (PciBase, PciSize); PcdStatus = PcdSet64S (PcdPciMmio32Base, PciBase); ASSERT_RETURN_ERROR (PcdStatus); PcdStatus = PcdSet64S (PcdPciMmio32Size, PciSize); ASSERT_RETURN_ERROR (PcdStatus); AddIoMemoryBaseSizeHob (0xFEC00000, SIZE_4KB); AddIoMemoryBaseSizeHob (0xFED00000, SIZE_1KB); if (mHostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) { AddIoMemoryBaseSizeHob (ICH9_ROOT_COMPLEX_BASE, SIZE_16KB); // // Note: there should be an // // AddIoMemoryBaseSizeHob (PciExBarBase, SIZE_256MB); // // call below, just like the one above for RCBA. However, Linux insists // that the MMCONFIG area be marked in the E820 or UEFI memory map as // "reserved memory" -- Linux does not content itself with a simple gap // in the memory map wherever the MCFG ACPI table points to. // // This appears to be a safety measure. The PCI Firmware Specification // (rev 3.1) says in 4.1.2. "MCFG Table Description": "The resources can // *optionally* be returned in [...] EFIGetMemoryMap as reserved memory // [...]". (Emphasis added here.) // // Normally we add memory resource descriptor HOBs in // QemuInitializeRam(), and pre-allocate from those with memory // allocation HOBs in InitializeRamRegions(). However, the MMCONFIG area // is most definitely not RAM; so, as an exception, cover it with // uncacheable reserved memory right here. // AddReservedMemoryBaseSizeHob (PciExBarBase, SIZE_256MB, FALSE); BuildMemoryAllocationHob (PciExBarBase, SIZE_256MB, EfiReservedMemoryType); } AddIoMemoryBaseSizeHob (PcdGet32(PcdCpuLocalApicBaseAddress), SIZE_1MB); // // On Q35, the IO Port space is available for PCI resource allocations from // 0x6000 up. // if (mHostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) { PciIoBase = 0x6000; PciIoSize = 0xA000; ASSERT ((ICH9_PMBASE_VALUE & 0xF000) < PciIoBase); } } // // Add PCI IO Port space available for PCI resource allocations. // BuildResourceDescriptorHob ( EFI_RESOURCE_IO, EFI_RESOURCE_ATTRIBUTE_PRESENT | EFI_RESOURCE_ATTRIBUTE_INITIALIZED, PciIoBase, PciIoSize ); PcdStatus = PcdSet64S (PcdPciIoBase, PciIoBase); ASSERT_RETURN_ERROR (PcdStatus); PcdStatus = PcdSet64S (PcdPciIoSize, PciIoSize); ASSERT_RETURN_ERROR (PcdStatus); } #define UPDATE_BOOLEAN_PCD_FROM_FW_CFG(TokenName) \ do { \ BOOLEAN Setting; \ RETURN_STATUS PcdStatus; \ \ if (!RETURN_ERROR (QemuFwCfgParseBool ( \ "opt/ovmf/" #TokenName, &Setting))) { \ PcdStatus = PcdSetBoolS (TokenName, Setting); \ ASSERT_RETURN_ERROR (PcdStatus); \ } \ } while (0) VOID NoexecDxeInitialization ( VOID ) { UPDATE_BOOLEAN_PCD_FROM_FW_CFG (PcdSetNxForStack); } VOID PciExBarInitialization ( VOID ) { union { UINT64 Uint64; UINT32 Uint32[2]; } PciExBarBase; // // We only support the 256MB size for the MMCONFIG area: // 256 buses * 32 devices * 8 functions * 4096 bytes config space. // // The masks used below enforce the Q35 requirements that the MMCONFIG area // be (a) correctly aligned -- here at 256 MB --, (b) located under 64 GB. // // Note that (b) also ensures that the minimum address width we have // determined in AddressWidthInitialization(), i.e., 36 bits, will suffice // for DXE's page tables to cover the MMCONFIG area. // PciExBarBase.Uint64 = FixedPcdGet64 (PcdPciExpressBaseAddress); ASSERT ((PciExBarBase.Uint32[1] & MCH_PCIEXBAR_HIGHMASK) == 0); ASSERT ((PciExBarBase.Uint32[0] & MCH_PCIEXBAR_LOWMASK) == 0); // // Clear the PCIEXBAREN bit first, before programming the high register. // PciWrite32 (DRAMC_REGISTER_Q35 (MCH_PCIEXBAR_LOW), 0); // // Program the high register. Then program the low register, setting the // MMCONFIG area size and enabling decoding at once. // PciWrite32 (DRAMC_REGISTER_Q35 (MCH_PCIEXBAR_HIGH), PciExBarBase.Uint32[1]); PciWrite32 ( DRAMC_REGISTER_Q35 (MCH_PCIEXBAR_LOW), PciExBarBase.Uint32[0] | MCH_PCIEXBAR_BUS_FF | MCH_PCIEXBAR_EN ); } VOID MiscInitialization ( VOID ) { UINTN PmCmd; UINTN Pmba; UINT32 PmbaAndVal; UINT32 PmbaOrVal; UINTN AcpiCtlReg; UINT8 AcpiEnBit; RETURN_STATUS PcdStatus; // // Disable A20 Mask // IoOr8 (0x92, BIT1); // // Build the CPU HOB with guest RAM size dependent address width and 16-bits // of IO space. (Side note: unlike other HOBs, the CPU HOB is needed during // S3 resume as well, so we build it unconditionally.) // BuildCpuHob (mPhysMemAddressWidth, 16); // // Determine platform type and save Host Bridge DID to PCD // switch (mHostBridgeDevId) { case INTEL_82441_DEVICE_ID: PmCmd = POWER_MGMT_REGISTER_PIIX4 (PCI_COMMAND_OFFSET); Pmba = POWER_MGMT_REGISTER_PIIX4 (PIIX4_PMBA); PmbaAndVal = ~(UINT32)PIIX4_PMBA_MASK; PmbaOrVal = PIIX4_PMBA_VALUE; AcpiCtlReg = POWER_MGMT_REGISTER_PIIX4 (PIIX4_PMREGMISC); AcpiEnBit = PIIX4_PMREGMISC_PMIOSE; break; case INTEL_Q35_MCH_DEVICE_ID: PmCmd = POWER_MGMT_REGISTER_Q35 (PCI_COMMAND_OFFSET); Pmba = POWER_MGMT_REGISTER_Q35 (ICH9_PMBASE); PmbaAndVal = ~(UINT32)ICH9_PMBASE_MASK; PmbaOrVal = ICH9_PMBASE_VALUE; AcpiCtlReg = POWER_MGMT_REGISTER_Q35 (ICH9_ACPI_CNTL); AcpiEnBit = ICH9_ACPI_CNTL_ACPI_EN; break; default: DEBUG ((DEBUG_ERROR, "%a: Unknown Host Bridge Device ID: 0x%04x\n", __FUNCTION__, mHostBridgeDevId)); ASSERT (FALSE); return; } PcdStatus = PcdSet16S (PcdOvmfHostBridgePciDevId, mHostBridgeDevId); ASSERT_RETURN_ERROR (PcdStatus); // // If the appropriate IOspace enable bit is set, assume the ACPI PMBA // has been configured (e.g., by Xen) and skip the setup here. // This matches the logic in AcpiTimerLibConstructor (). // if ((PciRead8 (AcpiCtlReg) & AcpiEnBit) == 0) { // // The PEI phase should be exited with fully accessibe ACPI PM IO space: // 1. set PMBA // PciAndThenOr32 (Pmba, PmbaAndVal, PmbaOrVal); // // 2. set PCICMD/IOSE // PciOr8 (PmCmd, EFI_PCI_COMMAND_IO_SPACE); // // 3. set ACPI PM IO enable bit (PMREGMISC:PMIOSE or ACPI_CNTL:ACPI_EN) // PciOr8 (AcpiCtlReg, AcpiEnBit); } if (mHostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) { // // Set Root Complex Register Block BAR // PciWrite32 ( POWER_MGMT_REGISTER_Q35 (ICH9_RCBA), ICH9_ROOT_COMPLEX_BASE | ICH9_RCBA_EN ); // // Set PCI Express Register Range Base Address // PciExBarInitialization (); } } VOID BootModeInitialization ( VOID ) { EFI_STATUS Status; if (CmosRead8 (0xF) == 0xFE) { mBootMode = BOOT_ON_S3_RESUME; } CmosWrite8 (0xF, 0x00); Status = PeiServicesSetBootMode (mBootMode); ASSERT_EFI_ERROR (Status); Status = PeiServicesInstallPpi (mPpiBootMode); ASSERT_EFI_ERROR (Status); } VOID ReserveEmuVariableNvStore ( ) { EFI_PHYSICAL_ADDRESS VariableStore; RETURN_STATUS PcdStatus; // // Allocate storage for NV variables early on so it will be // at a consistent address. Since VM memory is preserved // across reboots, this allows the NV variable storage to survive // a VM reboot. // VariableStore = (EFI_PHYSICAL_ADDRESS)(UINTN) AllocateRuntimePages ( EFI_SIZE_TO_PAGES (2 * PcdGet32 (PcdFlashNvStorageFtwSpareSize)) ); DEBUG ((DEBUG_INFO, "Reserved variable store memory: 0x%lX; size: %dkb\n", VariableStore, (2 * PcdGet32 (PcdFlashNvStorageFtwSpareSize)) / 1024 )); PcdStatus = PcdSet64S (PcdEmuVariableNvStoreReserved, VariableStore); ASSERT_RETURN_ERROR (PcdStatus); } VOID DebugDumpCmos ( VOID ) { UINT32 Loop; DEBUG ((DEBUG_INFO, "CMOS:\n")); for (Loop = 0; Loop < 0x80; Loop++) { if ((Loop % 0x10) == 0) { DEBUG ((DEBUG_INFO, "%02x:", Loop)); } DEBUG ((DEBUG_INFO, " %02x", CmosRead8 (Loop))); if ((Loop % 0x10) == 0xf) { DEBUG ((DEBUG_INFO, "\n")); } } } VOID S3Verification ( VOID ) { #if defined (MDE_CPU_X64) if (FeaturePcdGet (PcdSmmSmramRequire) && mS3Supported) { DEBUG ((DEBUG_ERROR, "%a: S3Resume2Pei doesn't support X64 PEI + SMM yet.\n", __FUNCTION__)); DEBUG ((DEBUG_ERROR, "%a: Please disable S3 on the QEMU command line (see the README),\n", __FUNCTION__)); DEBUG ((DEBUG_ERROR, "%a: or build OVMF with \"OvmfPkgIa32X64.dsc\".\n", __FUNCTION__)); ASSERT (FALSE); CpuDeadLoop (); } #endif } VOID Q35BoardVerification ( VOID ) { if (mHostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) { return; } DEBUG (( DEBUG_ERROR, "%a: no TSEG (SMRAM) on host bridge DID=0x%04x; " "only DID=0x%04x (Q35) is supported\n", __FUNCTION__, mHostBridgeDevId, INTEL_Q35_MCH_DEVICE_ID )); ASSERT (FALSE); CpuDeadLoop (); } /** Fetch the boot CPU count and the possible CPU count from QEMU, and expose them to UefiCpuPkg modules. Set the mMaxCpuCount variable. **/ VOID MaxCpuCountInitialization ( VOID ) { UINT16 BootCpuCount; RETURN_STATUS PcdStatus; // // Try to fetch the boot CPU count. // QemuFwCfgSelectItem (QemuFwCfgItemSmpCpuCount); BootCpuCount = QemuFwCfgRead16 (); if (BootCpuCount == 0) { // // QEMU doesn't report the boot CPU count. (BootCpuCount == 0) will let // MpInitLib count APs up to (PcdCpuMaxLogicalProcessorNumber - 1), or // until PcdCpuApInitTimeOutInMicroSeconds elapses (whichever is reached // first). // DEBUG ((DEBUG_WARN, "%a: boot CPU count unavailable\n", __FUNCTION__)); mMaxCpuCount = PcdGet32 (PcdCpuMaxLogicalProcessorNumber); } else { // // We will expose BootCpuCount to MpInitLib. MpInitLib will count APs up to // (BootCpuCount - 1) precisely, regardless of timeout. // // Now try to fetch the possible CPU count. // UINTN CpuHpBase; UINT32 CmdData2; CpuHpBase = ((mHostBridgeDevId == INTEL_Q35_MCH_DEVICE_ID) ? ICH9_CPU_HOTPLUG_BASE : PIIX4_CPU_HOTPLUG_BASE); // // If only legacy mode is available in the CPU hotplug register block, or // the register block is completely missing, then the writes below are // no-ops. // // 1. Switch the hotplug register block to modern mode. // IoWrite32 (CpuHpBase + QEMU_CPUHP_W_CPU_SEL, 0); // // 2. Select a valid CPU for deterministic reading of // QEMU_CPUHP_R_CMD_DATA2. // // CPU#0 is always valid; it is the always present and non-removable // BSP. // IoWrite32 (CpuHpBase + QEMU_CPUHP_W_CPU_SEL, 0); // // 3. Send a command after which QEMU_CPUHP_R_CMD_DATA2 is specified to // read as zero, and which does not invalidate the selector. (The // selector may change, but it must not become invalid.) // // Send QEMU_CPUHP_CMD_GET_PENDING, as it will prove useful later. // IoWrite8 (CpuHpBase + QEMU_CPUHP_W_CMD, QEMU_CPUHP_CMD_GET_PENDING); // // 4. Read QEMU_CPUHP_R_CMD_DATA2. // // If the register block is entirely missing, then this is an unassigned // IO read, returning all-bits-one. // // If only legacy mode is available, then bit#0 stands for CPU#0 in the // "CPU present bitmap". CPU#0 is always present. // // Otherwise, QEMU_CPUHP_R_CMD_DATA2 is either still reserved (returning // all-bits-zero), or it is specified to read as zero after the above // steps. Both cases confirm modern mode. // CmdData2 = IoRead32 (CpuHpBase + QEMU_CPUHP_R_CMD_DATA2); DEBUG ((DEBUG_VERBOSE, "%a: CmdData2=0x%x\n", __FUNCTION__, CmdData2)); if (CmdData2 != 0) { // // QEMU doesn't support the modern CPU hotplug interface. Assume that the // possible CPU count equals the boot CPU count (precluding hotplug). // DEBUG ((DEBUG_WARN, "%a: modern CPU hotplug interface unavailable\n", __FUNCTION__)); mMaxCpuCount = BootCpuCount; } else { // // Grab the possible CPU count from the modern CPU hotplug interface. // UINT32 Present, Possible, Selected; Present = 0; Possible = 0; // // We've sent QEMU_CPUHP_CMD_GET_PENDING last; this ensures // QEMU_CPUHP_RW_CMD_DATA can now be read usefully. However, // QEMU_CPUHP_CMD_GET_PENDING may have selected a CPU with actual pending // hotplug events; therefore, select CPU#0 forcibly. // IoWrite32 (CpuHpBase + QEMU_CPUHP_W_CPU_SEL, Possible); do { UINT8 CpuStatus; // // Read the status of the currently selected CPU. This will help with a // sanity check against "BootCpuCount". // CpuStatus = IoRead8 (CpuHpBase + QEMU_CPUHP_R_CPU_STAT); if ((CpuStatus & QEMU_CPUHP_STAT_ENABLED) != 0) { ++Present; } // // Attempt to select the next CPU. // ++Possible; IoWrite32 (CpuHpBase + QEMU_CPUHP_W_CPU_SEL, Possible); // // If the selection is successful, then the following read will return // the selector (which we know is positive at this point). Otherwise, // the read will return 0. // Selected = IoRead32 (CpuHpBase + QEMU_CPUHP_RW_CMD_DATA); ASSERT (Selected == Possible || Selected == 0); } while (Selected > 0); // // Sanity check: fw_cfg and the modern CPU hotplug interface should // return the same boot CPU count. // if (BootCpuCount != Present) { DEBUG ((DEBUG_WARN, "%a: QEMU v2.7 reset bug: BootCpuCount=%d " "Present=%u\n", __FUNCTION__, BootCpuCount, Present)); // // The handling of QemuFwCfgItemSmpCpuCount, across CPU hotplug plus // platform reset (including S3), was corrected in QEMU commit // e3cadac073a9 ("pc: fix FW_CFG_NB_CPUS to account for -device added // CPUs", 2016-11-16), part of release v2.8.0. // BootCpuCount = (UINT16)Present; } mMaxCpuCount = Possible; } } DEBUG ((DEBUG_INFO, "%a: BootCpuCount=%d mMaxCpuCount=%u\n", __FUNCTION__, BootCpuCount, mMaxCpuCount)); ASSERT (BootCpuCount <= mMaxCpuCount); PcdStatus = PcdSet32S (PcdCpuBootLogicalProcessorNumber, BootCpuCount); ASSERT_RETURN_ERROR (PcdStatus); PcdStatus = PcdSet32S (PcdCpuMaxLogicalProcessorNumber, mMaxCpuCount); ASSERT_RETURN_ERROR (PcdStatus); } /** Perform Platform PEI initialization. @param FileHandle Handle of the file being invoked. @param PeiServices Describes the list of possible PEI Services. @return EFI_SUCCESS The PEIM initialized successfully. **/ EFI_STATUS EFIAPI InitializePlatform ( IN EFI_PEI_FILE_HANDLE FileHandle, IN CONST EFI_PEI_SERVICES **PeiServices ) { EFI_STATUS Status; DEBUG ((DEBUG_INFO, "Platform PEIM Loaded\n")); DebugDumpCmos (); XenDetect (); if (QemuFwCfgS3Enabled ()) { DEBUG ((DEBUG_INFO, "S3 support was detected on QEMU\n")); mS3Supported = TRUE; Status = PcdSetBoolS (PcdAcpiS3Enable, TRUE); ASSERT_EFI_ERROR (Status); } S3Verification (); BootModeInitialization (); AddressWidthInitialization (); // // Query Host Bridge DID // mHostBridgeDevId = PciRead16 (OVMF_HOSTBRIDGE_DID); MaxCpuCountInitialization (); if (FeaturePcdGet (PcdSmmSmramRequire)) { Q35BoardVerification (); Q35TsegMbytesInitialization (); Q35SmramAtDefaultSmbaseInitialization (); } PublishPeiMemory (); QemuUc32BaseInitialization (); InitializeRamRegions (); if (mXen) { DEBUG ((DEBUG_INFO, "Xen was detected\n")); InitializeXen (); } if (mBootMode != BOOT_ON_S3_RESUME) { if (!FeaturePcdGet (PcdSmmSmramRequire)) { ReserveEmuVariableNvStore (); } PeiFvInitialization (); MemTypeInfoInitialization (); MemMapInitialization (); NoexecDxeInitialization (); } InstallClearCacheCallback (); AmdSevInitialize (); MiscInitialization (); InstallFeatureControlCallback (); return EFI_SUCCESS; }
NaohiroTamura/edk2
RedfishPkg/RedfishHostInterfaceDxe/RedfishHostInterfaceDxe.c
/** @file RedfishHostInterfaceDxe builds up SMBIOS Type 42h host interface record for Redfish service host interface using EFI MBIOS Protocol. RedfishHostInterfacePlatformLib is the platform-level library which provides the content of Redfish host interface type 42h record. Copyright (c) 2019, Intel Corporation. All rights reserved.<BR> (C) Copyright 2020 Hewlett Packard Enterprise Development LP<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <Uefi.h> #include <Library/BaseLib.h> #include <Library/BaseMemoryLib.h> #include <Library/DebugLib.h> #include <Library/MemoryAllocationLib.h> #include <Library/PrintLib.h> #include <Library/RedfishHostInterfaceLib.h> #include <Library/UefiLib.h> #include <Library/UefiBootServicesTableLib.h> #include <Library/UefiRuntimeServicesTableLib.h> /** Create SMBIOS type 42 record for Redfish host interface. @retval EFI_SUCESS SMBIOS type 42 record is created. @retval Others Fail to create SMBIOS 42 record. **/ EFI_STATUS RedfishCreateSmbiosTable42 ( VOID ) { REDFISH_INTERFACE_DATA *DeviceDescriptor; UINT8 DeviceDataLength; UINT8 DeviceType; EFI_STATUS Status; MC_HOST_INTERFACE_PROTOCOL_RECORD *ProtocolRecord; VOID *ProtocolRecords; VOID *NewProtocolRecords; UINT8 ProtocolCount; UINT8 CurrentProtocolsDataLength; UINT8 NewProtocolsDataLength; UINT8 ProtocolDataSize; SMBIOS_TABLE_TYPE42 *Type42Record; EFI_SMBIOS_PROTOCOL *Smbios; EFI_SMBIOS_HANDLE MemArrayMappedAddrSmbiosHandle; // // Get platform Redfish host interface device type descriptor data. // Status = RedfishPlatformHostInterfaceDeviceDescriptor (&DeviceType, &DeviceDescriptor); if (EFI_ERROR (Status)) { if (Status == EFI_NOT_FOUND) { DEBUG ((DEBUG_ERROR, "%a: No Redfish host interface descriptor is provided on this platform.", __FUNCTION__)); return EFI_NOT_FOUND; } DEBUG((DEBUG_ERROR, "%a: Fail to get device descriptor, %r.", __FUNCTION__, Status)); return Status; } if (DeviceType != REDFISH_HOST_INTERFACE_DEVICE_TYPE_USB_V2 && DeviceType != REDFISH_HOST_INTERFACE_DEVICE_TYPE_PCI_PCIE_V2 ) { DEBUG ((DEBUG_ERROR, "%a: Only support either protocol type 04h or 05h as Redfish host interface.", __FUNCTION__)); return EFI_UNSUPPORTED; } if (DeviceType == REDFISH_HOST_INTERFACE_DEVICE_TYPE_PCI_PCIE_V2) { DeviceDataLength = DeviceDescriptor->DeviceDescriptor.PciPcieDeviceV2.Length; } else { DeviceDataLength = DeviceDescriptor->DeviceDescriptor.UsbDeviceV2.Length; } // // Loop to get platform Redfish host interface protocol type data. // ProtocolRecord = NULL; ProtocolRecords = NULL; NewProtocolRecords = NULL; Type42Record = NULL; ProtocolCount = 0; CurrentProtocolsDataLength = 0; NewProtocolsDataLength = 0; while (TRUE) { Status = RedfishPlatformHostInterfaceProtocolData (&ProtocolRecord, ProtocolCount); if (Status == EFI_NOT_FOUND) { break; } if (EFI_ERROR(Status)) { DEBUG ((DEBUG_ERROR, "%a: Fail to get Redfish host interafce protocol type data.", __FUNCTION__)); if (ProtocolRecords != NULL) { FreePool (ProtocolRecords); } if (ProtocolRecord != NULL) { FreePool (ProtocolRecord); } return Status; } ProtocolDataSize = sizeof (MC_HOST_INTERFACE_PROTOCOL_RECORD) - sizeof(ProtocolRecord->ProtocolTypeData) + ProtocolRecord->ProtocolTypeDataLen; NewProtocolsDataLength += ProtocolDataSize; if (ProtocolRecords == NULL) { ProtocolRecords = AllocateZeroPool (NewProtocolsDataLength); if (ProtocolRecords == NULL) { FreePool (ProtocolRecord); return EFI_OUT_OF_RESOURCES; } CopyMem ((VOID *)ProtocolRecords, (VOID *)ProtocolRecord, ProtocolDataSize); NewProtocolRecords = ProtocolRecords; } else { NewProtocolRecords = ReallocatePool(CurrentProtocolsDataLength, NewProtocolsDataLength, (VOID *)ProtocolRecords); if (NewProtocolRecords == NULL) { DEBUG ((DEBUG_ERROR, "%a: Fail to allocate memory for Redfish host interface protocol data.")); FreePool (ProtocolRecords); FreePool (ProtocolRecord); return EFI_OUT_OF_RESOURCES; } CopyMem ( (VOID *)((UINT8 *)NewProtocolRecords + CurrentProtocolsDataLength), (VOID *)ProtocolRecord, ProtocolDataSize ); } FreePool (ProtocolRecord); CurrentProtocolsDataLength = NewProtocolsDataLength; ProtocolCount ++; }; if (ProtocolCount == 0) { goto ON_EXIT; } // // Construct SMBIOS Type 42h for Redfish host inteface. // // SMBIOS type 42 Record for Redfish Interface // 00h Type BYTE 42 Management Controller Host Interface structure indicator // 01h Length BYTE Varies Length of the structure, a minimum of 09h // 02h Handle WORD Varies // 04h Interface Type BYTE Varies Management Controller Interface Type. // 05h Interface Specific Data Length (n) // 06h Interface Specific data // 06h+n number of protocols defined for the host interface (typically 1) // 07h+n Include a Protocol Record for each protocol supported. // Type42Record = (SMBIOS_TABLE_TYPE42 *) AllocateZeroPool ( sizeof (SMBIOS_TABLE_TYPE42) - 4 + DeviceDataLength + 1 /// For Protocol Record Count + CurrentProtocolsDataLength + 2 /// Double NULL terminator/ ); if (Type42Record == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ON_EXIT; } Type42Record->Hdr.Type = EFI_SMBIOS_TYPE_MANAGEMENT_CONTROLLER_HOST_INTERFACE; Type42Record->Hdr.Length = sizeof (SMBIOS_TABLE_TYPE42) - 4 + DeviceDataLength + 1 + CurrentProtocolsDataLength; Type42Record->Hdr.Handle = 0; Type42Record->InterfaceType = MCHostInterfaceTypeNetworkHostInterface; // Network Host Interface // // Fill in InterfaceTypeSpecificDataLength field // Type42Record->InterfaceTypeSpecificDataLength = DeviceDataLength; // // Fill in InterfaceTypeSpecificData field // CopyMem (Type42Record->InterfaceTypeSpecificData, DeviceDescriptor, DeviceDataLength); FreePool (DeviceDescriptor); DeviceDescriptor = NULL; // // Fill in InterfaceTypeSpecificData Protocol Count field // *(Type42Record->InterfaceTypeSpecificData + DeviceDataLength) = ProtocolCount; // // Fill in Redfish Protocol Data // CopyMem ( Type42Record->InterfaceTypeSpecificData + DeviceDataLength + 1, NewProtocolRecords, CurrentProtocolsDataLength ); // // 5. Add Redfish interface data record to SMBIOS table 42 // Status = gBS->LocateProtocol (&gEfiSmbiosProtocolGuid, NULL, (VOID**)&Smbios); if (EFI_ERROR (Status)) { goto ON_EXIT; } MemArrayMappedAddrSmbiosHandle = SMBIOS_HANDLE_PI_RESERVED; Status = Smbios->Add ( Smbios, NULL, &MemArrayMappedAddrSmbiosHandle, (EFI_SMBIOS_TABLE_HEADER*) Type42Record ); DEBUG ((DEBUG_INFO, "RedfishPlatformDxe: Smbios->Add() - %r\n", Status)); if (EFI_ERROR (Status)) { goto ON_EXIT; } Status = EFI_SUCCESS; ON_EXIT: if (DeviceDescriptor != NULL) { FreePool (DeviceDescriptor); } if (NewProtocolRecords != NULL) { FreePool (NewProtocolRecords); } if (Type42Record != NULL) { FreePool (Type42Record); } return Status; } /** Main entry for this driver. @param ImageHandle Image handle this driver. @param SystemTable Pointer to SystemTable. @retval EFI_SUCESS This function always complete successfully. **/ EFI_STATUS EFIAPI RedfishHostInterfaceDxeEntryPoint ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { // // Create SMBIOS type 42 record. // return RedfishCreateSmbiosTable42 (); }
NaohiroTamura/edk2
ArmPkg/Library/ArmExceptionLib/Arm/ArmException.c
<filename>ArmPkg/Library/ArmExceptionLib/Arm/ArmException.c<gh_stars>1-10 /** @file * Exception handling support specific for ARM * * Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR> * Copyright (c) 2014, ARM Limited. All rights reserved.<BR> * Copyright (c) 2016 HP Development Company, L.P.<BR> * * SPDX-License-Identifier: BSD-2-Clause-Patent * **/ #include <Uefi.h> #include <Chipset/ArmV7.h> #include <Library/ArmLib.h> #include <Protocol/DebugSupport.h> // for MAX_ARM_EXCEPTION UINTN gMaxExceptionNumber = MAX_ARM_EXCEPTION; EFI_EXCEPTION_CALLBACK gExceptionHandlers[MAX_ARM_EXCEPTION + 1] = { 0 }; EFI_EXCEPTION_CALLBACK gDebuggerExceptionHandlers[MAX_ARM_EXCEPTION + 1] = { 0 }; PHYSICAL_ADDRESS gExceptionVectorAlignmentMask = ARM_VECTOR_TABLE_ALIGNMENT; // Exception handler contains branch to vector location (jmp $) so no handler // NOTE: This code assumes vectors are ARM and not Thumb code UINTN gDebuggerNoHandlerValue = 0xEAFFFFFE; RETURN_STATUS ArchVectorConfig( IN UINTN VectorBaseAddress ) { // if the vector address corresponds to high vectors if (VectorBaseAddress == 0xFFFF0000) { // set SCTLR.V to enable high vectors ArmSetHighVectors(); } else { // Set SCTLR.V to 0 to enable VBAR to be used ArmSetLowVectors(); } return RETURN_SUCCESS; }
NaohiroTamura/edk2
EmbeddedPkg/Library/AndroidBootImgLib/AndroidBootImgLib.c
<filename>EmbeddedPkg/Library/AndroidBootImgLib/AndroidBootImgLib.c /** @file Copyright (c) 2013-2014, ARM Ltd. All rights reserved.<BR> Copyright (c) 2017, Linaro. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <libfdt.h> #include <Library/AndroidBootImgLib.h> #include <Library/PrintLib.h> #include <Library/UefiBootServicesTableLib.h> #include <Library/UefiLib.h> #include <Protocol/AndroidBootImg.h> #include <Protocol/LoadedImage.h> #include <libfdt.h> #define FDT_ADDITIONAL_ENTRIES_SIZE 0x400 typedef struct { MEMMAP_DEVICE_PATH Node1; EFI_DEVICE_PATH_PROTOCOL End; } MEMORY_DEVICE_PATH; STATIC ANDROID_BOOTIMG_PROTOCOL *mAndroidBootImg; STATIC CONST MEMORY_DEVICE_PATH mMemoryDevicePathTemplate = { { { HARDWARE_DEVICE_PATH, HW_MEMMAP_DP, { (UINT8)(sizeof (MEMMAP_DEVICE_PATH)), (UINT8)((sizeof (MEMMAP_DEVICE_PATH)) >> 8), }, }, // Header 0, // StartingAddress (set at runtime) 0 // EndingAddress (set at runtime) }, // Node1 { END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, { sizeof (EFI_DEVICE_PATH_PROTOCOL), 0 } } // End }; EFI_STATUS AndroidBootImgGetImgSize ( IN VOID *BootImg, OUT UINTN *ImgSize ) { ANDROID_BOOTIMG_HEADER *Header; Header = (ANDROID_BOOTIMG_HEADER *) BootImg; if (AsciiStrnCmp ((CONST CHAR8 *)Header->BootMagic, ANDROID_BOOT_MAGIC, ANDROID_BOOT_MAGIC_LENGTH) != 0) { return EFI_INVALID_PARAMETER; } /* The page size is not specified, but it should be power of 2 at least */ ASSERT (IS_VALID_ANDROID_PAGE_SIZE (Header->PageSize)); /* Get real size of abootimg */ *ImgSize = ALIGN_VALUE (Header->KernelSize, Header->PageSize) + ALIGN_VALUE (Header->RamdiskSize, Header->PageSize) + ALIGN_VALUE (Header->SecondStageBootloaderSize, Header->PageSize) + Header->PageSize; return EFI_SUCCESS; } EFI_STATUS AndroidBootImgGetKernelInfo ( IN VOID *BootImg, OUT VOID **Kernel, OUT UINTN *KernelSize ) { ANDROID_BOOTIMG_HEADER *Header; Header = (ANDROID_BOOTIMG_HEADER *) BootImg; if (AsciiStrnCmp ((CONST CHAR8 *)Header->BootMagic, ANDROID_BOOT_MAGIC, ANDROID_BOOT_MAGIC_LENGTH) != 0) { return EFI_INVALID_PARAMETER; } if (Header->KernelSize == 0) { return EFI_NOT_FOUND; } ASSERT (IS_VALID_ANDROID_PAGE_SIZE (Header->PageSize)); *KernelSize = Header->KernelSize; *Kernel = (VOID *)((UINTN)BootImg + Header->PageSize); return EFI_SUCCESS; } EFI_STATUS AndroidBootImgGetRamdiskInfo ( IN VOID *BootImg, OUT VOID **Ramdisk, OUT UINTN *RamdiskSize ) { ANDROID_BOOTIMG_HEADER *Header; Header = (ANDROID_BOOTIMG_HEADER *)BootImg; if (AsciiStrnCmp ((CONST CHAR8 *)Header->BootMagic, ANDROID_BOOT_MAGIC, ANDROID_BOOT_MAGIC_LENGTH) != 0) { return EFI_INVALID_PARAMETER; } ASSERT (IS_VALID_ANDROID_PAGE_SIZE (Header->PageSize)); *RamdiskSize = Header->RamdiskSize; if (Header->RamdiskSize != 0) { *Ramdisk = (VOID *)((INTN)BootImg + Header->PageSize + ALIGN_VALUE (Header->KernelSize, Header->PageSize)); } return EFI_SUCCESS; } EFI_STATUS AndroidBootImgGetSecondBootLoaderInfo ( IN VOID *BootImg, OUT VOID **Second, OUT UINTN *SecondSize ) { ANDROID_BOOTIMG_HEADER *Header; Header = (ANDROID_BOOTIMG_HEADER *)BootImg; if (AsciiStrnCmp ((CONST CHAR8 *)Header->BootMagic, ANDROID_BOOT_MAGIC, ANDROID_BOOT_MAGIC_LENGTH) != 0) { return EFI_INVALID_PARAMETER; } ASSERT (IS_VALID_ANDROID_PAGE_SIZE (Header->PageSize)); *SecondSize = Header->SecondStageBootloaderSize; if (Header->SecondStageBootloaderSize != 0) { *Second = (VOID *)((UINTN)BootImg + Header->PageSize + ALIGN_VALUE (Header->KernelSize, Header->PageSize) + ALIGN_VALUE (Header->RamdiskSize, Header->PageSize)); } return EFI_SUCCESS; } EFI_STATUS AndroidBootImgGetKernelArgs ( IN VOID *BootImg, OUT CHAR8 *KernelArgs ) { ANDROID_BOOTIMG_HEADER *Header; Header = (ANDROID_BOOTIMG_HEADER *) BootImg; AsciiStrnCpyS (KernelArgs, ANDROID_BOOTIMG_KERNEL_ARGS_SIZE, Header->KernelArgs, ANDROID_BOOTIMG_KERNEL_ARGS_SIZE); return EFI_SUCCESS; } EFI_STATUS AndroidBootImgGetFdt ( IN VOID *BootImg, IN VOID **FdtBase ) { UINTN SecondLoaderSize; EFI_STATUS Status; /* Check whether FDT is located in second boot region as some vendor do so, * because second loader is never used as far as I know. */ Status = AndroidBootImgGetSecondBootLoaderInfo ( BootImg, FdtBase, &SecondLoaderSize ); return Status; } EFI_STATUS AndroidBootImgUpdateArgs ( IN VOID *BootImg, OUT VOID *KernelArgs ) { CHAR8 ImageKernelArgs[ANDROID_BOOTIMG_KERNEL_ARGS_SIZE]; EFI_STATUS Status; // Get kernel arguments from Android boot image Status = AndroidBootImgGetKernelArgs (BootImg, ImageKernelArgs); if (EFI_ERROR (Status)) { return Status; } AsciiStrToUnicodeStrS (ImageKernelArgs, KernelArgs, ANDROID_BOOTIMG_KERNEL_ARGS_SIZE >> 1); // Append platform kernel arguments if(mAndroidBootImg->AppendArgs) { Status = mAndroidBootImg->AppendArgs (KernelArgs, ANDROID_BOOTIMG_KERNEL_ARGS_SIZE); } return Status; } EFI_STATUS AndroidBootImgLocateFdt ( IN VOID *BootImg, IN VOID **FdtBase ) { INTN Err; EFI_STATUS Status; Status = EfiGetSystemConfigurationTable (&gFdtTableGuid, FdtBase); if (!EFI_ERROR (Status)) { return EFI_SUCCESS; } Status = AndroidBootImgGetFdt (BootImg, FdtBase); if (EFI_ERROR (Status)) { return Status; } Err = fdt_check_header (*FdtBase); if (Err != 0) { DEBUG ((DEBUG_ERROR, "ERROR: Device Tree header not valid (Err:%d)\n", Err)); return EFI_INVALID_PARAMETER; } return EFI_SUCCESS; } INTN AndroidBootImgGetChosenNode ( IN INTN UpdatedFdtBase ) { INTN ChosenNode; ChosenNode = fdt_subnode_offset ((CONST VOID *)UpdatedFdtBase, 0, "chosen"); if (ChosenNode < 0) { ChosenNode = fdt_add_subnode((VOID *)UpdatedFdtBase, 0, "chosen"); if (ChosenNode < 0) { DEBUG ((DEBUG_ERROR, "Fail to find fdt node chosen!\n")); return 0; } } return ChosenNode; } EFI_STATUS AndroidBootImgSetProperty64 ( IN INTN UpdatedFdtBase, IN INTN ChosenNode, IN CHAR8 *PropertyName, IN UINT64 Val ) { INTN Err; struct fdt_property *Property; int Len; Property = fdt_get_property_w((VOID *)UpdatedFdtBase, ChosenNode, PropertyName, &Len); if (NULL == Property && Len == -FDT_ERR_NOTFOUND) { Val = cpu_to_fdt64(Val); Err = fdt_appendprop ((VOID *)UpdatedFdtBase, ChosenNode, PropertyName, &Val, sizeof (UINT64)); if (Err) { DEBUG ((DEBUG_ERROR, "fdt_appendprop() fail: %a\n", fdt_strerror (Err))); return EFI_INVALID_PARAMETER; } } else if (Property != NULL) { Err = fdt_setprop_u64((VOID *)UpdatedFdtBase, ChosenNode, PropertyName, Val); if (Err) { DEBUG ((DEBUG_ERROR, "fdt_setprop_u64() fail: %a\n", fdt_strerror (Err))); return EFI_INVALID_PARAMETER; } } else { DEBUG ((DEBUG_ERROR, "Failed to set fdt Property %a\n", PropertyName)); return EFI_INVALID_PARAMETER; } return EFI_SUCCESS; } EFI_STATUS AndroidBootImgUpdateFdt ( IN VOID *BootImg, IN VOID *FdtBase, IN VOID *RamdiskData, IN UINTN RamdiskSize ) { INTN ChosenNode, Err, NewFdtSize; EFI_STATUS Status; EFI_PHYSICAL_ADDRESS UpdatedFdtBase, NewFdtBase; NewFdtSize = (UINTN)fdt_totalsize (FdtBase) + FDT_ADDITIONAL_ENTRIES_SIZE; Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesData, EFI_SIZE_TO_PAGES (NewFdtSize), &UpdatedFdtBase); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_WARN, "Warning: Failed to reallocate FDT, err %d.\n", Status)); return Status; } // Load the Original FDT tree into the new region Err = fdt_open_into(FdtBase, (VOID*)(INTN)UpdatedFdtBase, NewFdtSize); if (Err) { DEBUG ((DEBUG_ERROR, "fdt_open_into(): %a\n", fdt_strerror (Err))); Status = EFI_INVALID_PARAMETER; goto Fdt_Exit; } ChosenNode = AndroidBootImgGetChosenNode(UpdatedFdtBase); if (!ChosenNode) { goto Fdt_Exit; } Status = AndroidBootImgSetProperty64 (UpdatedFdtBase, ChosenNode, "linux,initrd-start", (UINTN)RamdiskData); if (EFI_ERROR (Status)) { goto Fdt_Exit; } Status = AndroidBootImgSetProperty64 (UpdatedFdtBase, ChosenNode, "linux,initrd-end", (UINTN)RamdiskData + RamdiskSize); if (EFI_ERROR (Status)) { goto Fdt_Exit; } if (mAndroidBootImg->UpdateDtb) { Status = mAndroidBootImg->UpdateDtb (UpdatedFdtBase, &NewFdtBase); if (EFI_ERROR (Status)) { goto Fdt_Exit; } Status = gBS->InstallConfigurationTable ( &gFdtTableGuid, (VOID *)(UINTN)NewFdtBase ); } if (!EFI_ERROR (Status)) { return EFI_SUCCESS; } Fdt_Exit: gBS->FreePages (UpdatedFdtBase, EFI_SIZE_TO_PAGES (NewFdtSize)); return Status; } EFI_STATUS AndroidBootImgBoot ( IN VOID *Buffer, IN UINTN BufferSize ) { EFI_STATUS Status; VOID *Kernel; UINTN KernelSize; MEMORY_DEVICE_PATH KernelDevicePath; EFI_HANDLE ImageHandle; VOID *NewKernelArg; EFI_LOADED_IMAGE_PROTOCOL *ImageInfo; VOID *RamdiskData; UINTN RamdiskSize; IN VOID *FdtBase; Status = gBS->LocateProtocol (&gAndroidBootImgProtocolGuid, NULL, (VOID **) &mAndroidBootImg); if (EFI_ERROR (Status)) { return Status; } Status = AndroidBootImgGetKernelInfo ( Buffer, &Kernel, &KernelSize ); if (EFI_ERROR (Status)) { return Status; } NewKernelArg = AllocateZeroPool (ANDROID_BOOTIMG_KERNEL_ARGS_SIZE); if (NewKernelArg == NULL) { DEBUG ((DEBUG_ERROR, "Fail to allocate memory\n")); return EFI_OUT_OF_RESOURCES; } Status = AndroidBootImgUpdateArgs (Buffer, NewKernelArg); if (EFI_ERROR (Status)) { FreePool (NewKernelArg); return Status; } Status = AndroidBootImgGetRamdiskInfo ( Buffer, &RamdiskData, &RamdiskSize ); if (EFI_ERROR (Status)) { return Status; } Status = AndroidBootImgLocateFdt (Buffer, &FdtBase); if (EFI_ERROR (Status)) { FreePool (NewKernelArg); return Status; } Status = AndroidBootImgUpdateFdt (Buffer, FdtBase, RamdiskData, RamdiskSize); if (EFI_ERROR (Status)) { FreePool (NewKernelArg); return Status; } KernelDevicePath = mMemoryDevicePathTemplate; KernelDevicePath.Node1.StartingAddress = (EFI_PHYSICAL_ADDRESS)(UINTN) Kernel; KernelDevicePath.Node1.EndingAddress = (EFI_PHYSICAL_ADDRESS)(UINTN) Kernel + KernelSize; Status = gBS->LoadImage (TRUE, gImageHandle, (EFI_DEVICE_PATH *)&KernelDevicePath, (VOID*)(UINTN)Kernel, KernelSize, &ImageHandle); if (EFI_ERROR (Status)) { // // With EFI_SECURITY_VIOLATION retval, the Image was loaded and an ImageHandle was created // with a valid EFI_LOADED_IMAGE_PROTOCOL, but the image can not be started right now. // If the caller doesn't have the option to defer the execution of an image, we should // unload image for the EFI_SECURITY_VIOLATION to avoid resource leak. // if (Status == EFI_SECURITY_VIOLATION) { gBS->UnloadImage (ImageHandle); } return Status; } // Set kernel arguments Status = gBS->HandleProtocol (ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **) &ImageInfo); ImageInfo->LoadOptions = NewKernelArg; ImageInfo->LoadOptionsSize = StrLen (NewKernelArg) * sizeof (CHAR16); // Before calling the image, enable the Watchdog Timer for the 5 Minute period gBS->SetWatchdogTimer (5 * 60, 0x10000, 0, NULL); // Start the image Status = gBS->StartImage (ImageHandle, NULL, NULL); // Clear the Watchdog Timer if the image returns gBS->SetWatchdogTimer (0, 0x10000, 0, NULL); return EFI_SUCCESS; }
NaohiroTamura/edk2
MdeModulePkg/Universal/RegularExpressionDxe/OnigurumaUefiPort.c
/** @file Module to rewrite stdlib references within Oniguruma (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP<BR> Copyright (c) 2020, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "OnigurumaUefiPort.h" #define ONIGMEM_HEAD_SIGNATURE SIGNATURE_32('o','m','h','d') typedef struct { UINT32 Signature; UINTN Size; } ONIGMEM_HEAD; #define ONIGMEM_OVERHEAD sizeof(ONIGMEM_HEAD) int EFIAPI sprintf_s(char *str, size_t sizeOfBuffer, char const *fmt, ...) { VA_LIST Marker; int NumberOfPrinted; VA_START (Marker, fmt); NumberOfPrinted = (int)AsciiVSPrint (str, sizeOfBuffer, fmt, Marker); VA_END (Marker); return NumberOfPrinted; } int OnigStrCmp (const char* Str1, const char* Str2) { return (int)AsciiStrCmp (Str1, Str2); } int strlen(const char* str) { return strlen_s(str, MAX_STRING_SIZE); } void * malloc (size_t size) { ONIGMEM_HEAD *PoolHdr; UINTN NewSize; VOID *Data; NewSize = (UINTN)(size) + ONIGMEM_OVERHEAD; Data = AllocatePool (NewSize); if (Data != NULL) { PoolHdr = (ONIGMEM_HEAD *)Data; PoolHdr->Signature = ONIGMEM_HEAD_SIGNATURE; PoolHdr->Size = size; return (VOID *)(PoolHdr + 1); } return NULL; } void * realloc (void *ptr, size_t size) { ONIGMEM_HEAD *OldPoolHdr; ONIGMEM_HEAD *NewPoolHdr; UINTN OldSize; UINTN NewSize; VOID *Data; NewSize = (UINTN)size + ONIGMEM_OVERHEAD; Data = AllocatePool (NewSize); if (Data != NULL) { NewPoolHdr = (ONIGMEM_HEAD *)Data; NewPoolHdr->Signature = ONIGMEM_HEAD_SIGNATURE; NewPoolHdr->Size = size; if (ptr != NULL) { OldPoolHdr = (ONIGMEM_HEAD *)ptr - 1; ASSERT (OldPoolHdr->Signature == ONIGMEM_HEAD_SIGNATURE); OldSize = OldPoolHdr->Size; CopyMem ((VOID *)(NewPoolHdr + 1), ptr, MIN (OldSize, size)); FreePool ((VOID *)OldPoolHdr); } return (VOID *)(NewPoolHdr + 1); } return NULL; } void* memcpy (void *dest, const void *src, unsigned int count) { return CopyMem (dest, src, (UINTN)count); } void* memset (void *dest, char ch, unsigned int count) { return SetMem (dest, count, ch); }
NaohiroTamura/edk2
MdePkg/Include/IndustryStandard/PciExpress21.h
/** @file Support for the latest PCI standard. Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR> (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef _PCIEXPRESS21_H_ #define _PCIEXPRESS21_H_ #include <IndustryStandard/Pci30.h> /** Macro that converts PCI Bus, PCI Device, PCI Function and PCI Register to an ECAM (Enhanced Configuration Access Mechanism) address. The unused upper bits of Bus, Device, Function and Register are stripped prior to the generation of the address. @param Bus PCI Bus number. Range 0..255. @param Device PCI Device number. Range 0..31. @param Function PCI Function number. Range 0..7. @param Register PCI Register number. Range 0..4095. @return The encode ECAM address. **/ #define PCI_ECAM_ADDRESS(Bus,Device,Function,Offset) \ (((Offset) & 0xfff) | (((Function) & 0x07) << 12) | (((Device) & 0x1f) << 15) | (((Bus) & 0xff) << 20)) #pragma pack(1) /// /// PCI Express Capability Structure /// typedef union { struct { UINT16 Version : 4; UINT16 DevicePortType : 4; UINT16 SlotImplemented : 1; UINT16 InterruptMessageNumber : 5; UINT16 Undefined : 1; UINT16 Reserved : 1; } Bits; UINT16 Uint16; } PCI_REG_PCIE_CAPABILITY; #define PCIE_DEVICE_PORT_TYPE_PCIE_ENDPOINT 0 #define PCIE_DEVICE_PORT_TYPE_LEGACY_PCIE_ENDPOINT 1 #define PCIE_DEVICE_PORT_TYPE_ROOT_PORT 4 #define PCIE_DEVICE_PORT_TYPE_UPSTREAM_PORT 5 #define PCIE_DEVICE_PORT_TYPE_DOWNSTREAM_PORT 6 #define PCIE_DEVICE_PORT_TYPE_PCIE_TO_PCI_BRIDGE 7 #define PCIE_DEVICE_PORT_TYPE_PCI_TO_PCIE_BRIDGE 8 #define PCIE_DEVICE_PORT_TYPE_ROOT_COMPLEX_INTEGRATED_ENDPOINT 9 #define PCIE_DEVICE_PORT_TYPE_ROOT_COMPLEX_EVENT_COLLECTOR 10 typedef union { struct { UINT32 MaxPayloadSize : 3; UINT32 PhantomFunctions : 2; UINT32 ExtendedTagField : 1; UINT32 EndpointL0sAcceptableLatency : 3; UINT32 EndpointL1AcceptableLatency : 3; UINT32 Undefined : 3; UINT32 RoleBasedErrorReporting : 1; UINT32 Reserved : 2; UINT32 CapturedSlotPowerLimitValue : 8; UINT32 CapturedSlotPowerLimitScale : 2; UINT32 FunctionLevelReset : 1; UINT32 Reserved2 : 3; } Bits; UINT32 Uint32; } PCI_REG_PCIE_DEVICE_CAPABILITY; typedef union { struct { UINT16 CorrectableError : 1; UINT16 NonFatalError : 1; UINT16 FatalError : 1; UINT16 UnsupportedRequest : 1; UINT16 RelaxedOrdering : 1; UINT16 MaxPayloadSize : 3; UINT16 ExtendedTagField : 1; UINT16 PhantomFunctions : 1; UINT16 AuxPower : 1; UINT16 NoSnoop : 1; UINT16 MaxReadRequestSize : 3; UINT16 BridgeConfigurationRetryOrFunctionLevelReset : 1; } Bits; UINT16 Uint16; } PCI_REG_PCIE_DEVICE_CONTROL; #define PCIE_MAX_PAYLOAD_SIZE_128B 0 #define PCIE_MAX_PAYLOAD_SIZE_256B 1 #define PCIE_MAX_PAYLOAD_SIZE_512B 2 #define PCIE_MAX_PAYLOAD_SIZE_1024B 3 #define PCIE_MAX_PAYLOAD_SIZE_2048B 4 #define PCIE_MAX_PAYLOAD_SIZE_4096B 5 #define PCIE_MAX_PAYLOAD_SIZE_RVSD1 6 #define PCIE_MAX_PAYLOAD_SIZE_RVSD2 7 #define PCIE_MAX_READ_REQ_SIZE_128B 0 #define PCIE_MAX_READ_REQ_SIZE_256B 1 #define PCIE_MAX_READ_REQ_SIZE_512B 2 #define PCIE_MAX_READ_REQ_SIZE_1024B 3 #define PCIE_MAX_READ_REQ_SIZE_2048B 4 #define PCIE_MAX_READ_REQ_SIZE_4096B 5 #define PCIE_MAX_READ_REQ_SIZE_RVSD1 6 #define PCIE_MAX_READ_REQ_SIZE_RVSD2 7 typedef union { struct { UINT16 CorrectableError : 1; UINT16 NonFatalError : 1; UINT16 FatalError : 1; UINT16 UnsupportedRequest : 1; UINT16 AuxPower : 1; UINT16 TransactionsPending : 1; UINT16 Reserved : 10; } Bits; UINT16 Uint16; } PCI_REG_PCIE_DEVICE_STATUS; typedef union { struct { UINT32 MaxLinkSpeed : 4; UINT32 MaxLinkWidth : 6; UINT32 Aspm : 2; UINT32 L0sExitLatency : 3; UINT32 L1ExitLatency : 3; UINT32 ClockPowerManagement : 1; UINT32 SurpriseDownError : 1; UINT32 DataLinkLayerLinkActive : 1; UINT32 LinkBandwidthNotification : 1; UINT32 AspmOptionalityCompliance : 1; UINT32 Reserved : 1; UINT32 PortNumber : 8; } Bits; UINT32 Uint32; } PCI_REG_PCIE_LINK_CAPABILITY; #define PCIE_LINK_ASPM_L0S BIT0 #define PCIE_LINK_ASPM_L1 BIT1 typedef union { struct { UINT16 AspmControl : 2; UINT16 Reserved : 1; UINT16 ReadCompletionBoundary : 1; UINT16 LinkDisable : 1; UINT16 RetrainLink : 1; UINT16 CommonClockConfiguration : 1; UINT16 ExtendedSynch : 1; UINT16 ClockPowerManagement : 1; UINT16 HardwareAutonomousWidthDisable : 1; UINT16 LinkBandwidthManagementInterrupt : 1; UINT16 LinkAutonomousBandwidthInterrupt : 1; } Bits; UINT16 Uint16; } PCI_REG_PCIE_LINK_CONTROL; typedef union { struct { UINT16 CurrentLinkSpeed : 4; UINT16 NegotiatedLinkWidth : 6; UINT16 Undefined : 1; UINT16 LinkTraining : 1; UINT16 SlotClockConfiguration : 1; UINT16 DataLinkLayerLinkActive : 1; UINT16 LinkBandwidthManagement : 1; UINT16 LinkAutonomousBandwidth : 1; } Bits; UINT16 Uint16; } PCI_REG_PCIE_LINK_STATUS; typedef union { struct { UINT32 AttentionButton : 1; UINT32 PowerController : 1; UINT32 MrlSensor : 1; UINT32 AttentionIndicator : 1; UINT32 PowerIndicator : 1; UINT32 HotPlugSurprise : 1; UINT32 HotPlugCapable : 1; UINT32 SlotPowerLimitValue : 8; UINT32 SlotPowerLimitScale : 2; UINT32 ElectromechanicalInterlock : 1; UINT32 NoCommandCompleted : 1; UINT32 PhysicalSlotNumber : 13; } Bits; UINT32 Uint32; } PCI_REG_PCIE_SLOT_CAPABILITY; typedef union { struct { UINT16 AttentionButtonPressed : 1; UINT16 PowerFaultDetected : 1; UINT16 MrlSensorChanged : 1; UINT16 PresenceDetectChanged : 1; UINT16 CommandCompletedInterrupt : 1; UINT16 HotPlugInterrupt : 1; UINT16 AttentionIndicator : 2; UINT16 PowerIndicator : 2; UINT16 PowerController : 1; UINT16 ElectromechanicalInterlock : 1; UINT16 DataLinkLayerStateChanged : 1; UINT16 Reserved : 3; } Bits; UINT16 Uint16; } PCI_REG_PCIE_SLOT_CONTROL; typedef union { struct { UINT16 AttentionButtonPressed : 1; UINT16 PowerFaultDetected : 1; UINT16 MrlSensorChanged : 1; UINT16 PresenceDetectChanged : 1; UINT16 CommandCompleted : 1; UINT16 MrlSensor : 1; UINT16 PresenceDetect : 1; UINT16 ElectromechanicalInterlock : 1; UINT16 DataLinkLayerStateChanged : 1; UINT16 Reserved : 7; } Bits; UINT16 Uint16; } PCI_REG_PCIE_SLOT_STATUS; typedef union { struct { UINT16 SystemErrorOnCorrectableError : 1; UINT16 SystemErrorOnNonFatalError : 1; UINT16 SystemErrorOnFatalError : 1; UINT16 PmeInterrupt : 1; UINT16 CrsSoftwareVisibility : 1; UINT16 Reserved : 11; } Bits; UINT16 Uint16; } PCI_REG_PCIE_ROOT_CONTROL; typedef union { struct { UINT16 CrsSoftwareVisibility : 1; UINT16 Reserved : 15; } Bits; UINT16 Uint16; } PCI_REG_PCIE_ROOT_CAPABILITY; typedef union { struct { UINT32 PmeRequesterId : 16; UINT32 PmeStatus : 1; UINT32 PmePending : 1; UINT32 Reserved : 14; } Bits; UINT32 Uint32; } PCI_REG_PCIE_ROOT_STATUS; typedef union { struct { UINT32 CompletionTimeoutRanges : 4; UINT32 CompletionTimeoutDisable : 1; UINT32 AriForwarding : 1; UINT32 AtomicOpRouting : 1; UINT32 AtomicOp32Completer : 1; UINT32 AtomicOp64Completer : 1; UINT32 Cas128Completer : 1; UINT32 NoRoEnabledPrPrPassing : 1; UINT32 LtrMechanism : 1; UINT32 TphCompleter : 2; UINT32 LnSystemCLS : 2; UINT32 TenBitTagCompleterSupported : 1; UINT32 TenBitTagRequesterSupported : 1; UINT32 Obff : 2; UINT32 ExtendedFmtField : 1; UINT32 EndEndTlpPrefix : 1; UINT32 MaxEndEndTlpPrefixes : 2; UINT32 EmergencyPowerReductionSupported : 2; UINT32 EmergencyPowerReductionInitializationRequired : 1; UINT32 Reserved3 : 4; UINT32 FrsSupported : 1; } Bits; UINT32 Uint32; } PCI_REG_PCIE_DEVICE_CAPABILITY2; #define PCIE_COMPLETION_TIMEOUT_NOT_SUPPORTED 0 #define PCIE_COMPLETION_TIMEOUT_RANGE_A_SUPPORTED 1 #define PCIE_COMPLETION_TIMEOUT_RANGE_B_SUPPORTED 2 #define PCIE_COMPLETION_TIMEOUT_RANGE_A_B_SUPPORTED 3 #define PCIE_COMPLETION_TIMEOUT_RANGE_B_C_SUPPORTED 6 #define PCIE_COMPLETION_TIMEOUT_RANGE_A_B_C_SUPPORTED 7 #define PCIE_COMPLETION_TIMEOUT_RANGE_B_C_D_SUPPORTED 14 #define PCIE_COMPLETION_TIMEOUT_RANGE_A_B_C_D_SUPPORTED 15 #define PCIE_DEVICE_CAPABILITY_OBFF_MESSAGE BIT0 #define PCIE_DEVICE_CAPABILITY_OBFF_WAKE BIT1 typedef union { struct { UINT16 CompletionTimeoutValue : 4; UINT16 CompletionTimeoutDisable : 1; UINT16 AriForwarding : 1; UINT16 AtomicOpRequester : 1; UINT16 AtomicOpEgressBlocking : 1; UINT16 IdoRequest : 1; UINT16 IdoCompletion : 1; UINT16 LtrMechanism : 1; UINT16 EmergencyPowerReductionRequest : 1; UINT16 TenBitTagRequesterEnable : 1; UINT16 Obff : 2; UINT16 EndEndTlpPrefixBlocking : 1; } Bits; UINT16 Uint16; } PCI_REG_PCIE_DEVICE_CONTROL2; #define PCIE_COMPLETION_TIMEOUT_50US_50MS 0 #define PCIE_COMPLETION_TIMEOUT_50US_100US 1 #define PCIE_COMPLETION_TIMEOUT_1MS_10MS 2 #define PCIE_COMPLETION_TIMEOUT_16MS_55MS 5 #define PCIE_COMPLETION_TIMEOUT_65MS_210MS 6 #define PCIE_COMPLETION_TIMEOUT_260MS_900MS 9 #define PCIE_COMPLETION_TIMEOUT_1S_3_5S 10 #define PCIE_COMPLETION_TIMEOUT_4S_13S 13 #define PCIE_COMPLETION_TIMEOUT_17S_64S 14 #define PCIE_DEVICE_CONTROL_OBFF_DISABLED 0 #define PCIE_DEVICE_CONTROL_OBFF_MESSAGE_A 1 #define PCIE_DEVICE_CONTROL_OBFF_MESSAGE_B 2 #define PCIE_DEVICE_CONTROL_OBFF_WAKE 3 typedef union { struct { UINT32 Reserved : 1; UINT32 LinkSpeedsVector : 7; UINT32 Crosslink : 1; UINT32 Reserved2 : 23; } Bits; UINT32 Uint32; } PCI_REG_PCIE_LINK_CAPABILITY2; typedef union { struct { UINT16 TargetLinkSpeed : 4; UINT16 EnterCompliance : 1; UINT16 HardwareAutonomousSpeedDisable : 1; UINT16 SelectableDeemphasis : 1; UINT16 TransmitMargin : 3; UINT16 EnterModifiedCompliance : 1; UINT16 ComplianceSos : 1; UINT16 CompliancePresetDeemphasis : 4; } Bits; UINT16 Uint16; } PCI_REG_PCIE_LINK_CONTROL2; typedef union { struct { UINT16 CurrentDeemphasisLevel : 1; UINT16 EqualizationComplete : 1; UINT16 EqualizationPhase1Successful : 1; UINT16 EqualizationPhase2Successful : 1; UINT16 EqualizationPhase3Successful : 1; UINT16 LinkEqualizationRequest : 1; UINT16 Reserved : 10; } Bits; UINT16 Uint16; } PCI_REG_PCIE_LINK_STATUS2; typedef struct { EFI_PCI_CAPABILITY_HDR Hdr; PCI_REG_PCIE_CAPABILITY Capability; PCI_REG_PCIE_DEVICE_CAPABILITY DeviceCapability; PCI_REG_PCIE_DEVICE_CONTROL DeviceControl; PCI_REG_PCIE_DEVICE_STATUS DeviceStatus; PCI_REG_PCIE_LINK_CAPABILITY LinkCapability; PCI_REG_PCIE_LINK_CONTROL LinkControl; PCI_REG_PCIE_LINK_STATUS LinkStatus; PCI_REG_PCIE_SLOT_CAPABILITY SlotCapability; PCI_REG_PCIE_SLOT_CONTROL SlotControl; PCI_REG_PCIE_SLOT_STATUS SlotStatus; PCI_REG_PCIE_ROOT_CONTROL RootControl; PCI_REG_PCIE_ROOT_CAPABILITY RootCapability; PCI_REG_PCIE_ROOT_STATUS RootStatus; PCI_REG_PCIE_DEVICE_CAPABILITY2 DeviceCapability2; PCI_REG_PCIE_DEVICE_CONTROL2 DeviceControl2; UINT16 DeviceStatus2; PCI_REG_PCIE_LINK_CAPABILITY2 LinkCapability2; PCI_REG_PCIE_LINK_CONTROL2 LinkControl2; PCI_REG_PCIE_LINK_STATUS2 LinkStatus2; UINT32 SlotCapability2; UINT16 SlotControl2; UINT16 SlotStatus2; } PCI_CAPABILITY_PCIEXP; #define EFI_PCIE_CAPABILITY_BASE_OFFSET 0x100 #define EFI_PCIE_CAPABILITY_ID_SRIOV_CONTROL_ARI_HIERARCHY 0x10 #define EFI_PCIE_CAPABILITY_DEVICE_CAPABILITIES_2_OFFSET 0x24 #define EFI_PCIE_CAPABILITY_DEVICE_CAPABILITIES_2_ARI_FORWARDING 0x20 #define EFI_PCIE_CAPABILITY_DEVICE_CONTROL_2_OFFSET 0x28 #define EFI_PCIE_CAPABILITY_DEVICE_CONTROL_2_ARI_FORWARDING 0x20 // // for SR-IOV // #define EFI_PCIE_CAPABILITY_ID_ARI 0x0E #define EFI_PCIE_CAPABILITY_ID_ATS 0x0F #define EFI_PCIE_CAPABILITY_ID_SRIOV 0x10 #define EFI_PCIE_CAPABILITY_ID_MRIOV 0x11 typedef struct { UINT32 CapabilityHeader; UINT32 Capability; UINT16 Control; UINT16 Status; UINT16 InitialVFs; UINT16 TotalVFs; UINT16 NumVFs; UINT8 FunctionDependencyLink; UINT8 Reserved0; UINT16 FirstVFOffset; UINT16 VFStride; UINT16 Reserved1; UINT16 VFDeviceID; UINT32 SupportedPageSize; UINT32 SystemPageSize; UINT32 VFBar[6]; UINT32 VFMigrationStateArrayOffset; } SR_IOV_CAPABILITY_REGISTER; #define EFI_PCIE_CAPABILITY_ID_SRIOV_CAPABILITIES 0x04 #define EFI_PCIE_CAPABILITY_ID_SRIOV_CONTROL 0x08 #define EFI_PCIE_CAPABILITY_ID_SRIOV_STATUS 0x0A #define EFI_PCIE_CAPABILITY_ID_SRIOV_INITIALVFS 0x0C #define EFI_PCIE_CAPABILITY_ID_SRIOV_TOTALVFS 0x0E #define EFI_PCIE_CAPABILITY_ID_SRIOV_NUMVFS 0x10 #define EFI_PCIE_CAPABILITY_ID_SRIOV_FUNCTION_DEPENDENCY_LINK 0x12 #define EFI_PCIE_CAPABILITY_ID_SRIOV_FIRSTVF 0x14 #define EFI_PCIE_CAPABILITY_ID_SRIOV_VFSTRIDE 0x16 #define EFI_PCIE_CAPABILITY_ID_SRIOV_VFDEVICEID 0x1A #define EFI_PCIE_CAPABILITY_ID_SRIOV_SUPPORTED_PAGE_SIZE 0x1C #define EFI_PCIE_CAPABILITY_ID_SRIOV_SYSTEM_PAGE_SIZE 0x20 #define EFI_PCIE_CAPABILITY_ID_SRIOV_BAR0 0x24 #define EFI_PCIE_CAPABILITY_ID_SRIOV_BAR1 0x28 #define EFI_PCIE_CAPABILITY_ID_SRIOV_BAR2 0x2C #define EFI_PCIE_CAPABILITY_ID_SRIOV_BAR3 0x30 #define EFI_PCIE_CAPABILITY_ID_SRIOV_BAR4 0x34 #define EFI_PCIE_CAPABILITY_ID_SRIOV_BAR5 0x38 #define EFI_PCIE_CAPABILITY_ID_SRIOV_VF_MIGRATION_STATE 0x3C typedef struct { UINT32 CapabilityId:16; UINT32 CapabilityVersion:4; UINT32 NextCapabilityOffset:12; } PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER; #define PCI_EXP_EXT_HDR PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER #define PCI_EXPRESS_EXTENDED_CAPABILITY_ADVANCED_ERROR_REPORTING_ID 0x0001 #define PCI_EXPRESS_EXTENDED_CAPABILITY_ADVANCED_ERROR_REPORTING_VER1 0x1 #define PCI_EXPRESS_EXTENDED_CAPABILITY_ADVANCED_ERROR_REPORTING_VER2 0x2 typedef union { struct { UINT32 Undefined : 1; UINT32 Reserved : 3; UINT32 DataLinkProtocolError : 1; UINT32 SurpriseDownError : 1; UINT32 Reserved2 : 6; UINT32 PoisonedTlp : 1; UINT32 FlowControlProtocolError : 1; UINT32 CompletionTimeout : 1; UINT32 CompleterAbort : 1; UINT32 UnexpectedCompletion : 1; UINT32 ReceiverOverflow : 1; UINT32 MalformedTlp : 1; UINT32 EcrcError : 1; UINT32 UnsupportedRequestError : 1; UINT32 AcsVoilation : 1; UINT32 UncorrectableInternalError : 1; UINT32 McBlockedTlp : 1; UINT32 AtomicOpEgressBlocked : 1; UINT32 TlpPrefixBlockedError : 1; UINT32 Reserved3 : 6; } Bits; UINT32 Uint32; } PCI_EXPRESS_REG_UNCORRECTABLE_ERROR; typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; PCI_EXPRESS_REG_UNCORRECTABLE_ERROR UncorrectableErrorStatus; PCI_EXPRESS_REG_UNCORRECTABLE_ERROR UncorrectableErrorMask; PCI_EXPRESS_REG_UNCORRECTABLE_ERROR UncorrectableErrorSeverity; UINT32 CorrectableErrorStatus; UINT32 CorrectableErrorMask; UINT32 AdvancedErrorCapabilitiesAndControl; UINT32 HeaderLog[4]; UINT32 RootErrorCommand; UINT32 RootErrorStatus; UINT16 ErrorSourceIdentification; UINT16 CorrectableErrorSourceIdentification; UINT32 TlpPrefixLog[4]; } PCI_EXPRESS_EXTENDED_CAPABILITIES_ADVANCED_ERROR_REPORTING; #define PCI_EXPRESS_EXTENDED_CAPABILITY_VIRTUAL_CHANNEL_ID 0x0002 #define PCI_EXPRESS_EXTENDED_CAPABILITY_VIRTUAL_CHANNEL_MFVC 0x0009 #define PCI_EXPRESS_EXTENDED_CAPABILITY_VIRTUAL_CHANNEL_VER1 0x1 typedef struct { UINT32 VcResourceCapability:24; UINT32 PortArbTableOffset:8; UINT32 VcResourceControl; UINT16 Reserved1; UINT16 VcResourceStatus; } PCI_EXPRESS_EXTENDED_CAPABILITIES_VIRTUAL_CHANNEL_VC; typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; UINT32 ExtendedVcCount:3; UINT32 PortVcCapability1:29; UINT32 PortVcCapability2:24; UINT32 VcArbTableOffset:8; UINT16 PortVcControl; UINT16 PortVcStatus; PCI_EXPRESS_EXTENDED_CAPABILITIES_VIRTUAL_CHANNEL_VC Capability[1]; } PCI_EXPRESS_EXTENDED_CAPABILITIES_VIRTUAL_CHANNEL_CAPABILITY; #define PCI_EXPRESS_EXTENDED_CAPABILITY_SERIAL_NUMBER_ID 0x0003 #define PCI_EXPRESS_EXTENDED_CAPABILITY_SERIAL_NUMBER_VER1 0x1 typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; UINT64 SerialNumber; } PCI_EXPRESS_EXTENDED_CAPABILITIES_SERIAL_NUMBER; #define PCI_EXPRESS_EXTENDED_CAPABILITY_LINK_DECLARATION_ID 0x0005 #define PCI_EXPRESS_EXTENDED_CAPABILITY_LINK_DECLARATION_VER1 0x1 typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; UINT32 ElementSelfDescription; UINT32 Reserved; UINT32 LinkEntry[1]; } PCI_EXPRESS_EXTENDED_CAPABILITIES_LINK_DECLARATION; #define PCI_EXPRESS_EXTENDED_CAPABILITY_LINK_DECLARATION_GET_LINK_COUNT(LINK_DECLARATION) (UINT8)(((LINK_DECLARATION->ElementSelfDescription)&0x0000ff00)>>8) #define PCI_EXPRESS_EXTENDED_CAPABILITY_LINK_CONTROL_ID 0x0006 #define PCI_EXPRESS_EXTENDED_CAPABILITY_LINK_CONTROL_VER1 0x1 typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; UINT32 RootComplexLinkCapabilities; UINT16 RootComplexLinkControl; UINT16 RootComplexLinkStatus; } PCI_EXPRESS_EXTENDED_CAPABILITIES_INTERNAL_LINK_CONTROL; #define PCI_EXPRESS_EXTENDED_CAPABILITY_POWER_BUDGETING_ID 0x0004 #define PCI_EXPRESS_EXTENDED_CAPABILITY_POWER_BUDGETING_VER1 0x1 typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; UINT32 DataSelect:8; UINT32 Reserved:24; UINT32 Data; UINT32 PowerBudgetCapability:1; UINT32 Reserved2:7; UINT32 Reserved3:24; } PCI_EXPRESS_EXTENDED_CAPABILITIES_POWER_BUDGETING; #define PCI_EXPRESS_EXTENDED_CAPABILITY_ACS_EXTENDED_ID 0x000D #define PCI_EXPRESS_EXTENDED_CAPABILITY_ACS_EXTENDED_VER1 0x1 typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; UINT16 AcsCapability; UINT16 AcsControl; UINT8 EgressControlVectorArray[1]; } PCI_EXPRESS_EXTENDED_CAPABILITIES_ACS_EXTENDED; #define PCI_EXPRESS_EXTENDED_CAPABILITY_ACS_EXTENDED_GET_EGRES_CONTROL(ACS_EXTENDED) (UINT8)(((ACS_EXTENDED->AcsCapability)&0x00000020)) #define PCI_EXPRESS_EXTENDED_CAPABILITY_ACS_EXTENDED_GET_EGRES_VECTOR_SIZE(ACS_EXTENDED) (UINT8)(((ACS_EXTENDED->AcsCapability)&0x0000FF00)) #define PCI_EXPRESS_EXTENDED_CAPABILITY_EVENT_COLLECTOR_ENDPOINT_ASSOCIATION_ID 0x0007 #define PCI_EXPRESS_EXTENDED_CAPABILITY_EVENT_COLLECTOR_ENDPOINT_ASSOCIATION_VER1 0x1 typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; UINT32 AssociationBitmap; } PCI_EXPRESS_EXTENDED_CAPABILITIES_EVENT_COLLECTOR_ENDPOINT_ASSOCIATION; #define PCI_EXPRESS_EXTENDED_CAPABILITY_MULTI_FUNCTION_VIRTUAL_CHANNEL_ID 0x0008 #define PCI_EXPRESS_EXTENDED_CAPABILITY_MULTI_FUNCTION_VIRTUAL_CHANNEL_VER1 0x1 typedef PCI_EXPRESS_EXTENDED_CAPABILITIES_VIRTUAL_CHANNEL_CAPABILITY PCI_EXPRESS_EXTENDED_CAPABILITIES_MULTI_FUNCTION_VIRTUAL_CHANNEL_CAPABILITY; #define PCI_EXPRESS_EXTENDED_CAPABILITY_VENDOR_SPECIFIC_ID 0x000B #define PCI_EXPRESS_EXTENDED_CAPABILITY_VENDOR_SPECIFIC_VER1 0x1 typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; UINT32 VendorSpecificHeader; UINT8 VendorSpecific[1]; } PCI_EXPRESS_EXTENDED_CAPABILITIES_VENDOR_SPECIFIC; #define PCI_EXPRESS_EXTENDED_CAPABILITY_VENDOR_SPECIFIC_GET_SIZE(VENDOR) (UINT16)(((VENDOR->VendorSpecificHeader)&0xFFF00000)>>20) #define PCI_EXPRESS_EXTENDED_CAPABILITY_RCRB_HEADER_ID 0x000A #define PCI_EXPRESS_EXTENDED_CAPABILITY_RCRB_HEADER_VER1 0x1 typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; UINT16 VendorId; UINT16 DeviceId; UINT32 RcrbCapabilities; UINT32 RcrbControl; UINT32 Reserved; } PCI_EXPRESS_EXTENDED_CAPABILITIES_RCRB_HEADER; #define PCI_EXPRESS_EXTENDED_CAPABILITY_MULTICAST_ID 0x0012 #define PCI_EXPRESS_EXTENDED_CAPABILITY_MULTICAST_VER1 0x1 typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; UINT16 MultiCastCapability; UINT16 MulticastControl; UINT64 McBaseAddress; UINT64 McReceiveAddress; UINT64 McBlockAll; UINT64 McBlockUntranslated; UINT64 McOverlayBar; } PCI_EXPRESS_EXTENDED_CAPABILITIES_MULTICAST; #define PCI_EXPRESS_EXTENDED_CAPABILITY_RESIZABLE_BAR_ID 0x0015 #define PCI_EXPRESS_EXTENDED_CAPABILITY_RESIZABLE_BAR_VER1 0x1 typedef struct { UINT32 ResizableBarCapability; UINT16 ResizableBarControl; UINT16 Reserved; } PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY; typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY Capability[1]; } PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR; #define GET_NUMBER_RESIZABLE_BARS(x) (((x->Capability[0].ResizableBarControl) & 0xE0) >> 5) #define PCI_EXPRESS_EXTENDED_CAPABILITY_ARI_CAPABILITY_ID 0x000E #define PCI_EXPRESS_EXTENDED_CAPABILITY_ARI_CAPABILITY_VER1 0x1 typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; UINT16 AriCapability; UINT16 AriControl; } PCI_EXPRESS_EXTENDED_CAPABILITIES_ARI_CAPABILITY; #define PCI_EXPRESS_EXTENDED_CAPABILITY_DYNAMIC_POWER_ALLOCATION_ID 0x0016 #define PCI_EXPRESS_EXTENDED_CAPABILITY_DYNAMIC_POWER_ALLOCATION_VER1 0x1 typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; UINT32 DpaCapability; UINT32 DpaLatencyIndicator; UINT16 DpaStatus; UINT16 DpaControl; UINT8 DpaPowerAllocationArray[1]; } PCI_EXPRESS_EXTENDED_CAPABILITIES_DYNAMIC_POWER_ALLOCATION; #define PCI_EXPRESS_EXTENDED_CAPABILITY_DYNAMIC_POWER_ALLOCATION_GET_SUBSTATE_MAX(POWER) (UINT16)(((POWER->DpaCapability)&0x0000000F)) #define PCI_EXPRESS_EXTENDED_CAPABILITY_LATENCE_TOLERANCE_REPORTING_ID 0x0018 #define PCI_EXPRESS_EXTENDED_CAPABILITY_LATENCE_TOLERANCE_REPORTING_VER1 0x1 typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; UINT16 MaxSnoopLatency; UINT16 MaxNoSnoopLatency; } PCI_EXPRESS_EXTENDED_CAPABILITIES_LATENCE_TOLERANCE_REPORTING; #define PCI_EXPRESS_EXTENDED_CAPABILITY_TPH_ID 0x0017 #define PCI_EXPRESS_EXTENDED_CAPABILITY_TPH_VER1 0x1 typedef struct { PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER Header; UINT32 TphRequesterCapability; UINT32 TphRequesterControl; UINT16 TphStTable[1]; } PCI_EXPRESS_EXTENDED_CAPABILITIES_TPH; #define GET_TPH_TABLE_SIZE(x) ((x->TphRequesterCapability & 0x7FF0000)>>16) * sizeof(UINT16) #pragma pack() #endif
NaohiroTamura/edk2
DynamicTablesPkg/Library/Common/AmlLib/AmlEncoding/Aml.c
/** @file AML grammar definitions. Copyright (c) 2010 - 2018, Intel Corporation. All rights reserved. <BR> Copyright (c) 2019 - 2020, Arm Limited. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <AmlEncoding/Aml.h> /** AML grammar encoding table. The ASL language is a description language, used to define abstract objects, like devices, thermal zones, etc. and their place in a hierarchical tree. The following table stores the AML grammar definition. It can be used to parse an AML bytestream. Each line corresponds to the definition of an opcode and what is expected to be found with this opcode. See table 20-440 in the ACPI 6.3 specification s20.3, and the AML grammar definitions in s20.2. - OpCode/SubOpCode: An OpCode/SubOpCode couple allows to identify an object type. The OpCode and SubOpCode are one byte each. The SubOpCode is used when the Opcode value is 0x5B (extended OpCode). Otherwise the SubOpcode is set to 0. If the SubOpCode is 0 in the table below, there is no SubOpCode in the AML bytestream, only the OpCode is used to identify the object. - Fixed arguments: The fixed arguments follow the OpCode and SubOpCode. Their number and type can be found in the table below. There can be at the most 6 fixed arguments for an object. Fixed arguments's type allow to know what is expected in the AML bytestream. Knowing the size of the incoming element, AML bytes can be packed and parsed accordingly. These types can be found in the same table 20-440 in the ACPI 6.3, s20.3 specification. E.g.: An AML object, a UINT8, a NULL terminated string, etc. -Attributes: The attribute field gives additional information on each object. This can be the presence of a variable list of arguments, the presence of a PkgLen, etc. In summary, an AML object is described as: OpCode [SubOpcode] [PkgLen] [FixedArgs] [VarArgs] OpCode {1 byte} [SubOpCode] {1 byte. Only relevant if the OpCode value is 0x5B (extended OpCode prefix). Otherwise 0. Most objects don't have one.} [PkgLen] {Size of the object. It has a special encoding, cf. ACPI 6.3 specification, s20.2.4 "Package Length Encoding". Most objects don't have one.} [FixedArgs[0..X]] {Fixed list of arguments. (where X <= 5) Can be other objects or data (a byte, a string, etc.). They belong to the current AML object. The number of fixed arguments varies according to the object, but it is fixed for each kind of object.} [VarArgs] {Variable list of arguments. They also belong to the current object and can be objects or data. Most objects don't have one.} [ByteList] {This is a sub-type of a variable list of arguments. It can only be found in buffer objects. A ByteList is either a list of bytes or a list of resource data elements. Resource data elements have specific opcodes.} [FieldList] {This is a sub-type of a variable list of arguments. It can only be found in Fields, IndexFields and BankFields. A FieldList is made of FieldElements. FieldElements have specific opcodes.} */ GLOBAL_REMOVE_IF_UNREFERENCED STATIC CONST AML_BYTE_ENCODING mAmlByteEncoding[] = { // Comment Str OpCode SubOpCode MaxIndex NameIndex 0 1 2 3 4 5 Attribute /* 0x00 */ {AML_OPCODE_DEF ("ZeroOp", AML_ZERO_OP), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x01 */ {AML_OPCODE_DEF ("OneOp", AML_ONE_OP), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x06 */ {AML_OPCODE_DEF ("AliasOp", AML_ALIAS_OP), 0, 2, 1, {EAmlName, EAmlName, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IN_NAMESPACE}, /* 0x08 */ {AML_OPCODE_DEF ("NameOp", AML_NAME_OP), 0, 2, 0, {EAmlName, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IN_NAMESPACE}, /* 0x0A */ {AML_OPCODE_DEF ("BytePrefix", AML_BYTE_PREFIX), 0, 1, 0, {EAmlUInt8, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x0B */ {AML_OPCODE_DEF ("WordPrefix", AML_WORD_PREFIX), 0, 1, 0, {EAmlUInt16, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x0C */ {AML_OPCODE_DEF ("DWordPrefix", AML_DWORD_PREFIX), 0, 1, 0, {EAmlUInt32, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x0D */ {AML_OPCODE_DEF ("StringPrefix", AML_STRING_PREFIX), 0, 1, 0, {EAmlString, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x0E */ {AML_OPCODE_DEF ("QWordPrefix", AML_QWORD_PREFIX), 0, 1, 0, {EAmlUInt64, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x10 */ {AML_OPCODE_DEF ("ScopeOp", AML_SCOPE_OP), 0, 1, 0, {EAmlName, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_CHILD_OBJ | AML_IN_NAMESPACE}, /* 0x11 */ {AML_OPCODE_DEF ("BufferOp", AML_BUFFER_OP), 0, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_BYTE_LIST}, /* 0x12 */ {AML_OPCODE_DEF ("PackageOp", AML_PACKAGE_OP), 0, 1, 0, {EAmlUInt8, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_CHILD_OBJ}, /* 0x13 */ {AML_OPCODE_DEF ("VarPackageOp", AML_VAR_PACKAGE_OP), 0, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_CHILD_OBJ}, /* 0x14 */ {AML_OPCODE_DEF ("MethodOp", AML_METHOD_OP), 0, 2, 0, {EAmlName, EAmlUInt8, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_CHILD_OBJ | AML_IN_NAMESPACE}, /* 0x15 */ {AML_OPCODE_DEF ("ExternalOp", AML_EXTERNAL_OP), 0, 3, 0, {EAmlName, EAmlUInt8, EAmlUInt8, EAmlNone, EAmlNone, EAmlNone}, AML_IN_NAMESPACE}, /* 0x2E */ {AML_OPCODE_DEF ("DualNamePrefix", AML_DUAL_NAME_PREFIX), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x2F */ {AML_OPCODE_DEF ("MultiNamePrefix", AML_MULTI_NAME_PREFIX), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x41 */ {AML_OPCODE_DEF ("NameChar_A", 'A'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x42 */ {AML_OPCODE_DEF ("NameChar_B", 'B'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x43 */ {AML_OPCODE_DEF ("NameChar_C", 'C'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x44 */ {AML_OPCODE_DEF ("NameChar_D", 'D'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x45 */ {AML_OPCODE_DEF ("NameChar_E", 'E'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x46 */ {AML_OPCODE_DEF ("NameChar_F", 'F'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x47 */ {AML_OPCODE_DEF ("NameChar_G", 'G'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x48 */ {AML_OPCODE_DEF ("NameChar_H", 'H'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x49 */ {AML_OPCODE_DEF ("NameChar_I", 'I'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x4A */ {AML_OPCODE_DEF ("NameChar_J", 'J'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x4B */ {AML_OPCODE_DEF ("NameChar_K", 'K'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x4C */ {AML_OPCODE_DEF ("NameChar_L", 'L'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x4D */ {AML_OPCODE_DEF ("NameChar_M", 'M'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x4E */ {AML_OPCODE_DEF ("NameChar_N", 'N'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x4F */ {AML_OPCODE_DEF ("NameChar_O", 'O'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x50 */ {AML_OPCODE_DEF ("NameChar_P", 'P'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x51 */ {AML_OPCODE_DEF ("NameChar_Q", 'Q'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x52 */ {AML_OPCODE_DEF ("NameChar_R", 'R'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x53 */ {AML_OPCODE_DEF ("NameChar_S", 'S'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x54 */ {AML_OPCODE_DEF ("NameChar_T", 'T'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x55 */ {AML_OPCODE_DEF ("NameChar_U", 'U'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x56 */ {AML_OPCODE_DEF ("NameChar_V", 'V'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x57 */ {AML_OPCODE_DEF ("NameChar_W", 'W'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x58 */ {AML_OPCODE_DEF ("NameChar_X", 'X'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x59 */ {AML_OPCODE_DEF ("NameChar_Y", 'Y'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x5A */ {AML_OPCODE_DEF ("NameChar_Z", 'Z'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x5B 0x01 */ {AML_OPCODE_DEF ("MutexOp", AML_EXT_OP), AML_EXT_MUTEX_OP, 2, 0, {EAmlName, EAmlUInt8, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IN_NAMESPACE}, /* 0x5B 0x02 */ {AML_OPCODE_DEF ("EventOp", AML_EXT_OP), AML_EXT_EVENT_OP, 1, 0, {EAmlName, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IN_NAMESPACE}, /* 0x5B 0x12 */ {AML_OPCODE_DEF ("CondRefOfOp", AML_EXT_OP), AML_EXT_COND_REF_OF_OP, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x13 */ {AML_OPCODE_DEF ("CreateFieldOp", AML_EXT_OP), AML_EXT_CREATE_FIELD_OP,4, 3, {EAmlObject, EAmlObject, EAmlObject, EAmlName, EAmlNone, EAmlNone}, AML_IN_NAMESPACE}, /* 0x5B 0x1F */ {AML_OPCODE_DEF ("LoadTableOp", AML_EXT_OP), AML_EXT_LOAD_TABLE_OP, 6, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlObject, EAmlObject, EAmlObject}, 0}, /* 0x5B 0x20 */ {AML_OPCODE_DEF ("LoadOp", AML_EXT_OP), AML_EXT_LOAD_OP, 2, 0, {EAmlName, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x21 */ {AML_OPCODE_DEF ("StallOp", AML_EXT_OP), AML_EXT_STALL_OP, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x22 */ {AML_OPCODE_DEF ("SleepOp", AML_EXT_OP), AML_EXT_SLEEP_OP, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x23 */ {AML_OPCODE_DEF ("AcquireOp", AML_EXT_OP), AML_EXT_ACQUIRE_OP, 2, 0, {EAmlObject, EAmlUInt16, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x24 */ {AML_OPCODE_DEF ("SignalOp", AML_EXT_OP), AML_EXT_SIGNAL_OP, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x25 */ {AML_OPCODE_DEF ("WaitOp", AML_EXT_OP), AML_EXT_WAIT_OP, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x26 */ {AML_OPCODE_DEF ("ResetOp", AML_EXT_OP), AML_EXT_RESET_OP, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x27 */ {AML_OPCODE_DEF ("ReleaseOp", AML_EXT_OP), AML_EXT_RELEASE_OP, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x28 */ {AML_OPCODE_DEF ("FromBCDOp", AML_EXT_OP), AML_EXT_FROM_BCD_OP, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x29 */ {AML_OPCODE_DEF ("ToBCDOp", AML_EXT_OP), AML_EXT_TO_BCD_OP, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x2A */ {AML_OPCODE_DEF ("UnloadOp", AML_EXT_OP), AML_EXT_UNLOAD_OP, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x30 */ {AML_OPCODE_DEF ("RevisionOp", AML_EXT_OP), AML_EXT_REVISION_OP, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x31 */ {AML_OPCODE_DEF ("DebugOp", AML_EXT_OP), AML_EXT_DEBUG_OP, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x32 */ {AML_OPCODE_DEF ("FatalOp", AML_EXT_OP), AML_EXT_FATAL_OP, 3, 0, {EAmlUInt8, EAmlUInt32, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x33 */ {AML_OPCODE_DEF ("TimerOp", AML_EXT_OP), AML_EXT_TIMER_OP, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x5B 0x80 */ {AML_OPCODE_DEF ("OpRegionOp", AML_EXT_OP), AML_EXT_REGION_OP, 4, 0, {EAmlName, EAmlUInt8, EAmlObject, EAmlObject, EAmlNone, EAmlNone}, AML_IN_NAMESPACE}, /* 0x5B 0x81 */ {AML_OPCODE_DEF ("FieldOp", AML_EXT_OP), AML_EXT_FIELD_OP, 2, 0, {EAmlName, EAmlUInt8, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_FIELD_LIST}, /* 0x5B 0x82 */ {AML_OPCODE_DEF ("DeviceOp", AML_EXT_OP), AML_EXT_DEVICE_OP, 1, 0, {EAmlName, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_CHILD_OBJ | AML_IN_NAMESPACE}, /* 0x5B 0x83 */ {AML_OPCODE_DEF ("ProcessorOp", AML_EXT_OP), AML_EXT_PROCESSOR_OP, 4, 0, {EAmlName, EAmlUInt8, EAmlUInt32, EAmlUInt8, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_CHILD_OBJ | AML_IN_NAMESPACE}, /* 0x5B 0x84 */ {AML_OPCODE_DEF ("PowerResOp", AML_EXT_OP), AML_EXT_POWER_RES_OP, 3, 0, {EAmlName, EAmlUInt8, EAmlUInt16, EAmlNone, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_CHILD_OBJ | AML_IN_NAMESPACE}, /* 0x5B 0x85 */ {AML_OPCODE_DEF ("ThermalZoneOp", AML_EXT_OP), AML_EXT_THERMAL_ZONE_OP,1, 0, {EAmlName, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_CHILD_OBJ | AML_IN_NAMESPACE}, /* 0x5B 0x86 */ {AML_OPCODE_DEF ("IndexFieldOp", AML_EXT_OP), AML_EXT_INDEX_FIELD_OP, 3, 0, {EAmlName, EAmlName, EAmlUInt8, EAmlNone, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_FIELD_LIST}, /* 0x5B 0x87 */ {AML_OPCODE_DEF ("BankFieldOp", AML_EXT_OP), AML_EXT_BANK_FIELD_OP, 4, 0, {EAmlName, EAmlName, EAmlObject, EAmlUInt8, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_FIELD_LIST}, /* 0x5B 0x88 */ {AML_OPCODE_DEF ("DataRegionOp", AML_EXT_OP), AML_EXT_DATA_REGION_OP, 4, 0, {EAmlName, EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone}, AML_IN_NAMESPACE}, /* 0x5C */ {AML_OPCODE_DEF ("RootChar", AML_ROOT_CHAR), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x5E */ {AML_OPCODE_DEF ("ParentPrefixChar", AML_PARENT_PREFIX_CHAR), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x5F */ {AML_OPCODE_DEF ("NameChar", '_'), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_NAME_CHAR}, /* 0x60 */ {AML_OPCODE_DEF ("Local0Op", AML_LOCAL0), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x61 */ {AML_OPCODE_DEF ("Local1Op", AML_LOCAL1), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x62 */ {AML_OPCODE_DEF ("Local2Op", AML_LOCAL2), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x63 */ {AML_OPCODE_DEF ("Local3Op", AML_LOCAL3), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x64 */ {AML_OPCODE_DEF ("Local4Op", AML_LOCAL4), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x65 */ {AML_OPCODE_DEF ("Local5Op", AML_LOCAL5), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x66 */ {AML_OPCODE_DEF ("Local6Op", AML_LOCAL6), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x67 */ {AML_OPCODE_DEF ("Local7Op", AML_LOCAL7), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x68 */ {AML_OPCODE_DEF ("Arg0Op", AML_ARG0), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x69 */ {AML_OPCODE_DEF ("Arg1Op", AML_ARG1), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x6A */ {AML_OPCODE_DEF ("Arg2Op", AML_ARG2), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x6B */ {AML_OPCODE_DEF ("Arg3Op", AML_ARG3), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x6C */ {AML_OPCODE_DEF ("Arg4Op", AML_ARG4), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x6D */ {AML_OPCODE_DEF ("Arg5Op", AML_ARG5), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x6E */ {AML_OPCODE_DEF ("Arg6Op", AML_ARG6), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x70 */ {AML_OPCODE_DEF ("StoreOp", AML_STORE_OP), 0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x71 */ {AML_OPCODE_DEF ("RefOfOp", AML_REF_OF_OP), 0, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x72 */ {AML_OPCODE_DEF ("AddOp", AML_ADD_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x73 */ {AML_OPCODE_DEF ("ConcatOp", AML_CONCAT_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x74 */ {AML_OPCODE_DEF ("SubtractOp", AML_SUBTRACT_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x75 */ {AML_OPCODE_DEF ("IncrementOp", AML_INCREMENT_OP), 0, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x76 */ {AML_OPCODE_DEF ("DecrementOp", AML_DECREMENT_OP), 0, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x77 */ {AML_OPCODE_DEF ("MultiplyOp", AML_MULTIPLY_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x78 */ {AML_OPCODE_DEF ("DivideOp", AML_DIVIDE_OP), 0, 4, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone}, 0}, /* 0x79 */ {AML_OPCODE_DEF ("ShiftLeftOp", AML_SHIFT_LEFT_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x7A */ {AML_OPCODE_DEF ("ShiftRightOp", AML_SHIFT_RIGHT_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x7B */ {AML_OPCODE_DEF ("AndOp", AML_AND_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x7C */ {AML_OPCODE_DEF ("NAndOp", AML_NAND_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x7D */ {AML_OPCODE_DEF ("OrOp", AML_OR_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x7E */ {AML_OPCODE_DEF ("NorOp", AML_NOR_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x7F */ {AML_OPCODE_DEF ("XOrOp", AML_XOR_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x80 */ {AML_OPCODE_DEF ("NotOp", AML_NOT_OP), 0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x81 */ {AML_OPCODE_DEF ("FindSetLeftBitOp", AML_FIND_SET_LEFT_BIT_OP), 0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x82 */ {AML_OPCODE_DEF ("FindSetRightBitOp", AML_FIND_SET_RIGHT_BIT_OP),0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x83 */ {AML_OPCODE_DEF ("DerefOfOp", AML_DEREF_OF_OP), 0, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x84 */ {AML_OPCODE_DEF ("ConcatResOp", AML_CONCAT_RES_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x85 */ {AML_OPCODE_DEF ("ModOp", AML_MOD_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x86 */ {AML_OPCODE_DEF ("NotifyOp", AML_NOTIFY_OP), 0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x87 */ {AML_OPCODE_DEF ("SizeOfOp", AML_SIZE_OF_OP), 0, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x88 */ {AML_OPCODE_DEF ("IndexOp", AML_INDEX_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x89 */ {AML_OPCODE_DEF ("MatchOp", AML_MATCH_OP), 0, 6, 0, {EAmlObject, EAmlUInt8, EAmlObject, EAmlUInt8, EAmlObject, EAmlObject}, 0}, /* 0x8A */ {AML_OPCODE_DEF ("CreateDWordFieldOp", AML_CREATE_DWORD_FIELD_OP),0, 3, 2, {EAmlObject, EAmlObject, EAmlName, EAmlNone, EAmlNone, EAmlNone}, AML_IN_NAMESPACE}, /* 0x8B */ {AML_OPCODE_DEF ("CreateWordFieldOp", AML_CREATE_WORD_FIELD_OP), 0, 3, 2, {EAmlObject, EAmlObject, EAmlName, EAmlNone, EAmlNone, EAmlNone}, AML_IN_NAMESPACE}, /* 0x8C */ {AML_OPCODE_DEF ("CreateByteFieldOp", AML_CREATE_BYTE_FIELD_OP), 0, 3, 2, {EAmlObject, EAmlObject, EAmlName, EAmlNone, EAmlNone, EAmlNone}, AML_IN_NAMESPACE}, /* 0x8D */ {AML_OPCODE_DEF ("CreateBitFieldOp", AML_CREATE_BIT_FIELD_OP), 0, 3, 2, {EAmlObject, EAmlObject, EAmlName, EAmlNone, EAmlNone, EAmlNone}, AML_IN_NAMESPACE}, /* 0x8E */ {AML_OPCODE_DEF ("ObjectTypeOp", AML_OBJECT_TYPE_OP), 0, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x8F */ {AML_OPCODE_DEF ("CreateQWordFieldOp", AML_CREATE_QWORD_FIELD_OP),0, 3, 2, {EAmlObject, EAmlObject, EAmlName, EAmlNone, EAmlNone, EAmlNone}, AML_IN_NAMESPACE}, /* 0x90 */ {AML_OPCODE_DEF ("LAndOp", AML_LAND_OP), 0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x91 */ {AML_OPCODE_DEF ("LOrOp", AML_LOR_OP), 0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x92 */ {AML_OPCODE_DEF ("LNotOp", AML_LNOT_OP), 0, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x93 */ {AML_OPCODE_DEF ("LEqualOp", AML_LEQUAL_OP), 0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x94 */ {AML_OPCODE_DEF ("LGreaterOp", AML_LGREATER_OP), 0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x95 */ {AML_OPCODE_DEF ("LLessOp", AML_LLESS_OP), 0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x96 */ {AML_OPCODE_DEF ("ToBufferOp", AML_TO_BUFFER_OP), 0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x97 */ {AML_OPCODE_DEF ("ToDecimalStringOp", AML_TO_DEC_STRING_OP), 0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x98 */ {AML_OPCODE_DEF ("ToHexStringOp", AML_TO_HEX_STRING_OP), 0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x99 */ {AML_OPCODE_DEF ("ToIntegerOp", AML_TO_INTEGER_OP), 0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x9C */ {AML_OPCODE_DEF ("ToStringOp", AML_TO_STRING_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x9D */ {AML_OPCODE_DEF ("CopyObjectOp", AML_COPY_OBJECT_OP), 0, 2, 0, {EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x9E */ {AML_OPCODE_DEF ("MidOp", AML_MID_OP), 0, 3, 0, {EAmlObject, EAmlObject, EAmlObject, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0x9F */ {AML_OPCODE_DEF ("ContinueOp", AML_CONTINUE_OP), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0xA0 */ {AML_OPCODE_DEF ("IfOp", AML_IF_OP), 0, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_CHILD_OBJ}, /* 0xA1 */ {AML_OPCODE_DEF ("ElseOp", AML_ELSE_OP), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_CHILD_OBJ}, /* 0xA2 */ {AML_OPCODE_DEF ("WhileOp", AML_WHILE_OP), 0, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_HAS_PKG_LENGTH | AML_HAS_CHILD_OBJ}, /* 0xA3 */ {AML_OPCODE_DEF ("NoopOp", AML_NOOP_OP), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0xA4 */ {AML_OPCODE_DEF ("ReturnOp", AML_RETURN_OP), 0, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0xA5 */ {AML_OPCODE_DEF ("BreakOp", AML_BREAK_OP), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0xCC */ {AML_OPCODE_DEF ("BreakPointOp", AML_BREAK_POINT_OP), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, /* 0xD0 */ {AML_OPCODE_DEF ("MethodInvocOp", AML_METHOD_INVOC_OP), 0, 2, 0, {EAmlName, EAmlUInt8, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_PSEUDO_OPCODE | AML_HAS_CHILD_OBJ}, /* 0xFF */ {AML_OPCODE_DEF ("OnesOp", AML_ONES_OP), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, 0}, }; /** AML grammar encoding for field elements. Some AML objects are expecting a FieldList. They are referred in this library as field nodes. These objects have the following opcodes: - FieldOp; - IndexFieldOp; - BankFieldOp. In the AML grammar encoding table, they have the AML_HAS_FIELD_LIST attribute. A field list is made of field elements. According to the ACPI 6.3 specification, s20.2.5.2 "Named Objects Encoding", field elements can be: - NamedField := NameSeg PkgLength; - ReservedField := 0x00 PkgLength; - AccessField := 0x01 AccessType AccessAttrib; - ConnectField := <0x02 NameString> | <0x02 BufferData>; - ExtendedAccessField := 0x03 AccessType ExtendedAccessAttrib AccessLength. A small set of opcodes describes field elements. They are referred in this library as field opcodes. The NamedField field element doesn't have a field opcode. A pseudo OpCode/SubOpCode couple has been created for it. Field elements: - don't have a SubOpCode; - have at most 3 fixed arguments (6 for object opcodes, 8 for method invocations); - don't have variable list of arguments; - are not part of the AML namespace, except NamedField field elements. */ GLOBAL_REMOVE_IF_UNREFERENCED STATIC CONST AML_BYTE_ENCODING mAmlFieldEncoding[] = { // Comment Str OpCode SubOpCode MaxIndex NameIndex 0 1 2 3 4 5 Attribute /* 0x00 */ {AML_OPCODE_DEF ("FieldReservedOp", AML_FIELD_RESERVED_OP), 0, 0, 0, {EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_FIELD_ELEMENT | AML_HAS_PKG_LENGTH}, /* 0x01 */ {AML_OPCODE_DEF ("FieldAccessOp", AML_FIELD_ACCESS_OP), 0, 2, 0, {EAmlUInt8, EAmlUInt8, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_FIELD_ELEMENT}, /* 0x02 */ {AML_OPCODE_DEF ("FieldConnectionOp", AML_FIELD_CONNECTION_OP), 0, 1, 0, {EAmlObject, EAmlNone, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_FIELD_ELEMENT}, /* 0x03 */ {AML_OPCODE_DEF ("FieldExtAccessOp", AML_FIELD_EXT_ACCESS_OP), 0, 3, 0, {EAmlUInt8, EAmlUInt8, EAmlUInt8, EAmlNone, EAmlNone, EAmlNone}, AML_IS_FIELD_ELEMENT}, /* 0x04 */ {AML_OPCODE_DEF ("FieldNamed", AML_FIELD_NAMED_OP), 0, 2, 0, {EAmlName, EAmlFieldPkgLen, EAmlNone, EAmlNone, EAmlNone, EAmlNone}, AML_IS_FIELD_ELEMENT | AML_IS_PSEUDO_OPCODE | AML_IN_NAMESPACE} }; /** Get the AML_BYTE_ENCODING entry in the AML encoding table. Note: For Pseudo OpCodes this function returns NULL. @param [in] Buffer Pointer to an OpCode/SubOpCode couple. If *Buffer = 0x5b (extended OpCode), Buffer must be at least two bytes long. @return The corresponding AML_BYTE_ENCODING entry. NULL if not found. **/ CONST AML_BYTE_ENCODING * EFIAPI AmlGetByteEncoding ( IN CONST UINT8 * Buffer ) { UINT8 OpCode; UINT8 SubOpCode; UINT32 Index; if (Buffer == NULL) { ASSERT (0); return NULL; } // Get OpCode and SubOpCode. OpCode = Buffer[0]; if (OpCode == AML_EXT_OP) { SubOpCode = Buffer[1]; } else { SubOpCode = 0; } // Search the table. for (Index = 0; Index < (sizeof (mAmlByteEncoding) / sizeof (mAmlByteEncoding[0])); Index++) { if ((mAmlByteEncoding[Index].OpCode == OpCode) && (mAmlByteEncoding[Index].SubOpCode == SubOpCode)) { if ((mAmlByteEncoding[Index].Attribute & AML_IS_PSEUDO_OPCODE) == AML_IS_PSEUDO_OPCODE) { // A pseudo OpCode cannot be parsed as it is internal to this library. // The MethodInvocation encoding can be detected by NameSpace lookup. ASSERT (0); return NULL; } return &mAmlByteEncoding[Index]; } } return NULL; } /** Get the AML_BYTE_ENCODING entry in the AML encoding table by providing an OpCode/SubOpCode couple. @param [in] OpCode OpCode. @param [in] SubOpCode SubOpCode. @return The corresponding AML_BYTE_ENCODING entry. NULL if not found. **/ CONST AML_BYTE_ENCODING * EFIAPI AmlGetByteEncodingByOpCode ( IN UINT8 OpCode, IN UINT8 SubOpCode ) { UINT32 Index; // Search the table. for (Index = 0; Index < (sizeof (mAmlByteEncoding) / sizeof (mAmlByteEncoding[0])); Index++) { if ((mAmlByteEncoding[Index].OpCode == OpCode) && (mAmlByteEncoding[Index].SubOpCode == SubOpCode)) { return &mAmlByteEncoding[Index]; } } return NULL; } /** Get the AML_BYTE_ENCODING entry in the field encoding table. Note: For Pseudo OpCodes this function returns NULL. @param [in] Buffer Pointer to a field OpCode. No SubOpCode is expected. @return The corresponding AML_BYTE_ENCODING entry in the field encoding table. NULL if not found. **/ CONST AML_BYTE_ENCODING * EFIAPI AmlGetFieldEncoding ( IN CONST UINT8 * Buffer ) { UINT8 OpCode; UINT32 Index; if (Buffer == NULL) { ASSERT (0); return NULL; } // Get OpCode. OpCode = *Buffer; // Search in the table. for (Index = 0; Index < (sizeof (mAmlFieldEncoding) / sizeof (mAmlFieldEncoding[0])); Index++) { if (mAmlFieldEncoding[Index].OpCode == OpCode) { if ((mAmlFieldEncoding[Index].Attribute & AML_IS_PSEUDO_OPCODE) == AML_IS_PSEUDO_OPCODE) { // A pseudo OpCode cannot be parsed as it is internal to this library. // The NamedField encoding can be detected because it begins with a // char. ASSERT (0); return NULL; } return &mAmlFieldEncoding[Index]; } } return NULL; } /** Get the AML_BYTE_ENCODING entry in the field encoding table by providing an OpCode/SubOpCode couple. @param [in] OpCode OpCode. @param [in] SubOpCode SubOpCode. @return The corresponding AML_BYTE_ENCODING entry in the field encoding table. NULL if not found. **/ CONST AML_BYTE_ENCODING * EFIAPI AmlGetFieldEncodingByOpCode ( IN UINT8 OpCode, IN UINT8 SubOpCode ) { UINT32 Index; // Search the table. for (Index = 0; Index < (sizeof (mAmlFieldEncoding) / sizeof (mAmlFieldEncoding[0])); Index++) { if ((mAmlFieldEncoding[Index].OpCode == OpCode) && (mAmlFieldEncoding[Index].SubOpCode == SubOpCode)) { return &mAmlFieldEncoding[Index]; } } return NULL; } // Enable this function for debug. #if !defined (MDEPKG_NDEBUG) /** Look for an OpCode/SubOpCode couple in the AML grammar, and return a corresponding string. @param [in] OpCode The OpCode. @param [in] SubOpCode The SubOpCode. @return A string describing the OpCode/SubOpCode couple. NULL if not found. **/ CONST CHAR8 * AmlGetOpCodeStr ( IN UINT8 OpCode, IN UINT8 SubOpCode ) { EAML_PARSE_INDEX Index; // Search the table. for (Index = 0; Index < (sizeof (mAmlByteEncoding) / sizeof (mAmlByteEncoding[0])); Index++) { if ((mAmlByteEncoding[Index].OpCode == OpCode) && (mAmlByteEncoding[Index].SubOpCode == SubOpCode)) { return mAmlByteEncoding[Index].Str; } } ASSERT (0); return NULL; } /** Look for an OpCode/SubOpCode couple in the AML field element grammar, and return a corresponding string. @param [in] OpCode The OpCode. @param [in] SubOpCode The SubOpCode. Must be zero. @return A string describing the OpCode/SubOpCode couple. NULL if not found. **/ CONST CHAR8 * AmlGetFieldOpCodeStr ( IN UINT8 OpCode, IN UINT8 SubOpCode ) { EAML_PARSE_INDEX Index; if (SubOpCode != 0) { ASSERT (0); return NULL; } // Search the table. for (Index = 0; Index < (sizeof (mAmlFieldEncoding) / sizeof (mAmlFieldEncoding[0])); Index++) { if ((mAmlFieldEncoding[Index].OpCode == OpCode)) { return mAmlFieldEncoding[Index].Str; } } ASSERT (0); return NULL; } #endif // MDEPKG_NDEBUG /** Check whether the OpCode/SubOpcode couple is a valid entry in the AML grammar encoding table. @param [in] OpCode OpCode to check. @param [in] SubOpCode SubOpCode to check. @retval TRUE The OpCode/SubOpCode couple is valid. @retval FALSE Otherwise. **/ BOOLEAN EFIAPI AmlIsOpCodeValid ( IN UINT8 OpCode, IN UINT8 SubOpCode ) { EAML_PARSE_INDEX Index; // Search the table. for (Index = 0; Index < (sizeof (mAmlByteEncoding) / sizeof (mAmlByteEncoding[0])); Index++) { if ((mAmlByteEncoding[Index].OpCode == OpCode) && (mAmlByteEncoding[Index].SubOpCode == SubOpCode)) { return TRUE; } } return FALSE; } /** AML_PARSE_FORMAT to EAML_NODE_DATA_TYPE translation table. AML_PARSE_FORMAT describes an internal set of values identifying the types that can be found while parsing an AML bytestream. EAML_NODE_DATA_TYPE describes an external set of values allowing to identify what type of data can be found in data nodes. */ GLOBAL_REMOVE_IF_UNREFERENCED STATIC CONST EAML_NODE_DATA_TYPE mAmlTypeToNodeDataType[] = { EAmlNodeDataTypeNone, // EAmlNone EAmlNodeDataTypeUInt, // EAmlUInt8 EAmlNodeDataTypeUInt, // EAmlUInt16 EAmlNodeDataTypeUInt, // EAmlUInt32 EAmlNodeDataTypeUInt, // EAmlUInt64 EAmlNodeDataTypeReserved5, // EAmlObject EAmlNodeDataTypeNameString, // EAmlName EAmlNodeDataTypeString, // EAmlString EAmlNodeDataTypeFieldPkgLen // EAmlFieldPkgLen }; /** Convert an AML_PARSE_FORMAT to its corresponding EAML_NODE_DATA_TYPE. @param [in] AmlType Input AML Type. @return The corresponding EAML_NODE_DATA_TYPE. EAmlNodeDataTypeNone if not found. **/ EAML_NODE_DATA_TYPE EFIAPI AmlTypeToNodeDataType ( IN AML_PARSE_FORMAT AmlType ) { if (AmlType >= (sizeof (mAmlTypeToNodeDataType) / sizeof (mAmlTypeToNodeDataType[0]))) { ASSERT (0); return EAmlNodeDataTypeNone; } return mAmlTypeToNodeDataType[AmlType]; } /** Get the package length from the buffer. @param [in] Buffer AML buffer. @param [out] PkgLength The interpreted PkgLen value. Length cannot exceed 2^28. @return The number of bytes to represent the package length. 0 if an issue occurred. **/ UINT32 EFIAPI AmlGetPkgLength ( IN CONST UINT8 * Buffer, OUT UINT32 * PkgLength ) { UINT8 LeadByte; UINT8 ByteCount; UINT32 RealLength; UINT32 Offset; if ((Buffer == NULL) || (PkgLength == NULL)) { ASSERT (0); return 0; } /* From ACPI 6.3 specification, s20.2.4 "Package Length Encoding": PkgLength := PkgLeadByte | <PkgLeadByte ByteData> | <PkgLeadByte ByteData ByteData> | <PkgLeadByte ByteData ByteData ByteData> PkgLeadByte := <bit 7-6: ByteData count that follows (0-3)> <bit 5-4: Only used if PkgLength < 63> <bit 3-0: Least significant package length nibble> Note: The high 2 bits of the first byte reveal how many follow bytes are in the PkgLength. If the PkgLength has only one byte, bit 0 through 5 are used to encode the package length (in other words, values 0-63). If the package length value is more than 63, more than one byte must be used for the encoding in which case bit 4 and 5 of the PkgLeadByte are reserved and must be zero. If the multiple bytes encoding is used, bits 0-3 of the PkgLeadByte become the least significant 4 bits of the resulting package length value. The next ByteData will become the next least significant 8 bits of the resulting value and so on, up to 3 ByteData bytes. Thus, the maximum package length is 2**28. */ LeadByte = *Buffer; ByteCount = (LeadByte >> 6) & 0x03U; Offset = ByteCount + 1U; RealLength = 0; // Switch on the number of bytes used to store the PkgLen. switch (ByteCount) { case 0: { RealLength = LeadByte; break; } case 1: { RealLength = *(Buffer + 1); RealLength = (RealLength << 4) | (LeadByte & 0xF); break; } case 2: { RealLength = *(Buffer + 1); RealLength |= ((UINT32)(*(Buffer + 2))) << 8; RealLength = (RealLength << 4) | (LeadByte & 0xF); break; } case 3: { RealLength = *(Buffer + 1); RealLength |= ((UINT32)(*(Buffer + 2))) << 8; RealLength |= ((UINT32)(*(Buffer + 3))) << 16; RealLength = (RealLength << 4) | (LeadByte & 0xF); break; } default: { ASSERT (0); Offset = 0; break; } } // switch *PkgLength = RealLength; return Offset; } /** Convert the Length to the AML PkgLen encoding, then and write it in the Buffer. @param [in] Length Length to convert. Length cannot exceed 2^28. @param [out] Buffer Write the result in this Buffer. @return The number of bytes used to write the Length. **/ UINT8 EFIAPI AmlSetPkgLength ( IN UINT32 Length, OUT UINT8 * Buffer ) { UINT8 LeadByte; UINT8 Offset; UINT8 CurrentOffset; UINT8 CurrentShift; UINT32 ComputedLength; if (Buffer == NULL) { ASSERT (0); return 0; } LeadByte = 0; Offset = 0; if ((Length < (1 << 6))) { // Length < 2^6, only need one byte to encode it. LeadByte = (UINT8)Length; } else { // Need more than one byte to encode it. // Test Length to find how many bytes are needed. if (Length >= (1 << 28)) { // Length >= 2^28, should not be possible. ASSERT (0); return 0; } else if (Length >= (1 << 20)) { // Length >= 2^20 Offset = 3; } else if (Length >= (1 << 12)) { // Length >= 2^12 Offset = 2; } else if (Length >= (1 << 6)) { // Length >= 2^6 Offset = 1; } else { // Should not be possible. ASSERT (0); return 0; } // Set the LeadByte. LeadByte = (UINT8)(Offset << 6); LeadByte = (UINT8)(LeadByte | (Length & 0xF)); } // Write to the Buffer. *Buffer = LeadByte; CurrentOffset = 1; while (CurrentOffset < (Offset + 1)) { CurrentShift = (UINT8)((CurrentOffset - 1) * 8); ComputedLength = Length & (UINT32)(0x00000FF0 << CurrentShift); ComputedLength = (ComputedLength) >> (4 + CurrentShift); LeadByte = (UINT8)(ComputedLength & 0xFF); *(Buffer + CurrentOffset) = LeadByte; CurrentOffset++; } return ++Offset; } /** Compute the number of bytes required to write a package length. @param [in] Length The length to convert in the AML package length encoding style. Length cannot exceed 2^28. @return The number of bytes required to write the Length. **/ UINT8 EFIAPI AmlComputePkgLengthWidth ( IN UINT32 Length ) { // Length >= 2^28, should not be possible. if (Length >= (1 << 28)) { ASSERT (0); return 0; } else if (Length >= (1 << 20)) { // Length >= 2^20 return 4; } else if (Length >= (1 << 12)) { // Length >= 2^12 return 3; } else if (Length >= (1 << 6)) { // Length >= 2^6 return 2; } // Length < 2^6 return 1; }
NaohiroTamura/edk2
ArmPkg/Include/Library/ArmMmuLib.h
<filename>ArmPkg/Include/Library/ArmMmuLib.h /** @file Copyright (c) 2015 - 2016, Linaro Ltd. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef __ARM_MMU_LIB__ #define __ARM_MMU_LIB__ #include <Uefi/UefiBaseType.h> #include <Library/ArmLib.h> EFI_STATUS EFIAPI ArmConfigureMmu ( IN ARM_MEMORY_REGION_DESCRIPTOR *MemoryTable, OUT VOID **TranslationTableBase OPTIONAL, OUT UINTN *TranslationTableSize OPTIONAL ); EFI_STATUS EFIAPI ArmSetMemoryRegionNoExec ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length ); EFI_STATUS EFIAPI ArmClearMemoryRegionNoExec ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length ); EFI_STATUS EFIAPI ArmSetMemoryRegionReadOnly ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length ); EFI_STATUS EFIAPI ArmClearMemoryRegionReadOnly ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length ); VOID EFIAPI ArmReplaceLiveTranslationEntry ( IN UINT64 *Entry, IN UINT64 Value, IN UINT64 RegionStart ); EFI_STATUS ArmSetMemoryAttributes ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length, IN UINT64 Attributes ); #endif
NaohiroTamura/edk2
NetworkPkg/HttpBootDxe/HttpBootClient.c
/** @file Implementation of the boot file download function. Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR> (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "HttpBootDxe.h" /** Update the device path node to include the boot resource information. @param[in] Private The pointer to the driver's private data. @retval EFI_SUCCESS Device patch successfully updated. @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources. @retval Others Unexpected error happened. **/ EFI_STATUS HttpBootUpdateDevicePath ( IN HTTP_BOOT_PRIVATE_DATA *Private ) { EFI_DEV_PATH *Node; EFI_DEVICE_PATH_PROTOCOL *TmpIpDevicePath; EFI_DEVICE_PATH_PROTOCOL *TmpDnsDevicePath; EFI_DEVICE_PATH_PROTOCOL *NewDevicePath; UINTN Length; EFI_STATUS Status; TmpIpDevicePath = NULL; TmpDnsDevicePath = NULL; // // Update the IP node with DHCP assigned information. // if (!Private->UsingIpv6) { Node = AllocateZeroPool (sizeof (IPv4_DEVICE_PATH)); if (Node == NULL) { return EFI_OUT_OF_RESOURCES; } Node->Ipv4.Header.Type = MESSAGING_DEVICE_PATH; Node->Ipv4.Header.SubType = MSG_IPv4_DP; SetDevicePathNodeLength (Node, sizeof (IPv4_DEVICE_PATH)); CopyMem (&Node->Ipv4.LocalIpAddress, &Private->StationIp, sizeof (EFI_IPv4_ADDRESS)); Node->Ipv4.RemotePort = Private->Port; Node->Ipv4.Protocol = EFI_IP_PROTO_TCP; Node->Ipv4.StaticIpAddress = FALSE; CopyMem (&Node->Ipv4.GatewayIpAddress, &Private->GatewayIp, sizeof (EFI_IPv4_ADDRESS)); CopyMem (&Node->Ipv4.SubnetMask, &Private->SubnetMask, sizeof (EFI_IPv4_ADDRESS)); } else { Node = AllocateZeroPool (sizeof (IPv6_DEVICE_PATH)); if (Node == NULL) { return EFI_OUT_OF_RESOURCES; } Node->Ipv6.Header.Type = MESSAGING_DEVICE_PATH; Node->Ipv6.Header.SubType = MSG_IPv6_DP; SetDevicePathNodeLength (Node, sizeof (IPv6_DEVICE_PATH)); Node->Ipv6.PrefixLength = IP6_PREFIX_LENGTH; Node->Ipv6.RemotePort = Private->Port; Node->Ipv6.Protocol = EFI_IP_PROTO_TCP; Node->Ipv6.IpAddressOrigin = 0; CopyMem (&Node->Ipv6.LocalIpAddress, &Private->StationIp.v6, sizeof (EFI_IPv6_ADDRESS)); CopyMem (&Node->Ipv6.RemoteIpAddress, &Private->ServerIp.v6, sizeof (EFI_IPv6_ADDRESS)); CopyMem (&Node->Ipv6.GatewayIpAddress, &Private->GatewayIp.v6, sizeof (EFI_IPv6_ADDRESS)); } TmpIpDevicePath = AppendDevicePathNode (Private->ParentDevicePath, (EFI_DEVICE_PATH_PROTOCOL*) Node); FreePool (Node); if (TmpIpDevicePath == NULL) { return EFI_OUT_OF_RESOURCES; } // // Update the DNS node with DNS server IP list if existed. // if (Private->DnsServerIp != NULL) { Length = sizeof (EFI_DEVICE_PATH_PROTOCOL) + sizeof (Node->Dns.IsIPv6) + Private->DnsServerCount * sizeof (EFI_IP_ADDRESS); Node = AllocatePool (Length); if (Node == NULL) { FreePool (TmpIpDevicePath); return EFI_OUT_OF_RESOURCES; } Node->DevPath.Type = MESSAGING_DEVICE_PATH; Node->DevPath.SubType = MSG_DNS_DP; SetDevicePathNodeLength (Node, Length); Node->Dns.IsIPv6 = Private->UsingIpv6 ? 0x01 : 0x00; CopyMem ((UINT8*) Node + sizeof (EFI_DEVICE_PATH_PROTOCOL) + sizeof (Node->Dns.IsIPv6), Private->DnsServerIp, Private->DnsServerCount * sizeof (EFI_IP_ADDRESS)); TmpDnsDevicePath = AppendDevicePathNode (TmpIpDevicePath, (EFI_DEVICE_PATH_PROTOCOL*) Node); FreePool (Node); FreePool (TmpIpDevicePath); TmpIpDevicePath = NULL; if (TmpDnsDevicePath == NULL) { return EFI_OUT_OF_RESOURCES; } } // // Update the URI node with the boot file URI. // Length = sizeof (EFI_DEVICE_PATH_PROTOCOL) + AsciiStrSize (Private->BootFileUri); Node = AllocatePool (Length); if (Node == NULL) { if (TmpIpDevicePath != NULL) { FreePool (TmpIpDevicePath); } if (TmpDnsDevicePath != NULL) { FreePool (TmpDnsDevicePath); } return EFI_OUT_OF_RESOURCES; } Node->DevPath.Type = MESSAGING_DEVICE_PATH; Node->DevPath.SubType = MSG_URI_DP; SetDevicePathNodeLength (Node, Length); CopyMem ((UINT8*) Node + sizeof (EFI_DEVICE_PATH_PROTOCOL), Private->BootFileUri, AsciiStrSize (Private->BootFileUri)); if (TmpDnsDevicePath != NULL) { NewDevicePath = AppendDevicePathNode (TmpDnsDevicePath, (EFI_DEVICE_PATH_PROTOCOL*) Node); FreePool (TmpDnsDevicePath); } else { ASSERT (TmpIpDevicePath != NULL); NewDevicePath = AppendDevicePathNode (TmpIpDevicePath, (EFI_DEVICE_PATH_PROTOCOL*) Node); FreePool (TmpIpDevicePath); } FreePool (Node); if (NewDevicePath == NULL) { return EFI_OUT_OF_RESOURCES; } if (!Private->UsingIpv6) { // // Reinstall the device path protocol of the child handle. // Status = gBS->ReinstallProtocolInterface ( Private->Ip4Nic->Controller, &gEfiDevicePathProtocolGuid, Private->Ip4Nic->DevicePath, NewDevicePath ); if (EFI_ERROR (Status)) { return Status; } FreePool (Private->Ip4Nic->DevicePath); Private->Ip4Nic->DevicePath = NewDevicePath; } else { // // Reinstall the device path protocol of the child handle. // Status = gBS->ReinstallProtocolInterface ( Private->Ip6Nic->Controller, &gEfiDevicePathProtocolGuid, Private->Ip6Nic->DevicePath, NewDevicePath ); if (EFI_ERROR (Status)) { return Status; } FreePool (Private->Ip6Nic->DevicePath); Private->Ip6Nic->DevicePath = NewDevicePath; } return EFI_SUCCESS; } /** Parse the boot file URI information from the selected Dhcp4 offer packet. @param[in] Private The pointer to the driver's private data. @retval EFI_SUCCESS Successfully parsed out all the boot information. @retval Others Failed to parse out the boot information. **/ EFI_STATUS HttpBootDhcp4ExtractUriInfo ( IN HTTP_BOOT_PRIVATE_DATA *Private ) { HTTP_BOOT_DHCP4_PACKET_CACHE *SelectOffer; HTTP_BOOT_DHCP4_PACKET_CACHE *HttpOffer; UINT32 SelectIndex; UINT32 ProxyIndex; UINT32 DnsServerIndex; EFI_DHCP4_PACKET_OPTION *Option; EFI_STATUS Status; ASSERT (Private != NULL); ASSERT (Private->SelectIndex != 0); SelectIndex = Private->SelectIndex - 1; ASSERT (SelectIndex < HTTP_BOOT_OFFER_MAX_NUM); DnsServerIndex = 0; Status = EFI_SUCCESS; // // SelectOffer contains the IP address configuration and name server configuration. // HttpOffer contains the boot file URL. // SelectOffer = &Private->OfferBuffer[SelectIndex].Dhcp4; if (Private->FilePathUri == NULL) { // // In Corporate environment, we need a HttpOffer. // if ((SelectOffer->OfferType == HttpOfferTypeDhcpIpUri) || (SelectOffer->OfferType == HttpOfferTypeDhcpIpUriDns) || (SelectOffer->OfferType == HttpOfferTypeDhcpNameUriDns)) { HttpOffer = SelectOffer; } else { ASSERT (Private->SelectProxyType != HttpOfferTypeMax); ProxyIndex = Private->OfferIndex[Private->SelectProxyType][0]; HttpOffer = &Private->OfferBuffer[ProxyIndex].Dhcp4; } Private->BootFileUriParser = HttpOffer->UriParser; Private->BootFileUri = (CHAR8*) HttpOffer->OptList[HTTP_BOOT_DHCP4_TAG_INDEX_BOOTFILE]->Data; } else { // // In Home environment the BootFileUri comes from the FilePath. // Private->BootFileUriParser = Private->FilePathUriParser; Private->BootFileUri = Private->FilePathUri; } // // Check the URI scheme. // Status = HttpBootCheckUriScheme (Private->BootFileUri); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "HttpBootDhcp4ExtractUriInfo: %r.\n", Status)); if (Status == EFI_INVALID_PARAMETER) { AsciiPrint ("\n Error: Invalid URI address.\n"); } else if (Status == EFI_ACCESS_DENIED) { AsciiPrint ("\n Error: Access forbidden, only HTTPS connection is allowed.\n"); } return Status; } if ((SelectOffer->OfferType == HttpOfferTypeDhcpNameUriDns) || (SelectOffer->OfferType == HttpOfferTypeDhcpDns) || (SelectOffer->OfferType == HttpOfferTypeDhcpIpUriDns)) { Option = SelectOffer->OptList[HTTP_BOOT_DHCP4_TAG_INDEX_DNS_SERVER]; ASSERT (Option != NULL); // // Record the Dns Server address list. // Private->DnsServerCount = (Option->Length) / sizeof (EFI_IPv4_ADDRESS); Private->DnsServerIp = AllocateZeroPool (Private->DnsServerCount * sizeof (EFI_IP_ADDRESS)); if (Private->DnsServerIp == NULL) { return EFI_OUT_OF_RESOURCES; } for (DnsServerIndex = 0; DnsServerIndex < Private->DnsServerCount; DnsServerIndex++) { CopyMem (&(Private->DnsServerIp[DnsServerIndex].v4), &(((EFI_IPv4_ADDRESS *) Option->Data)[DnsServerIndex]), sizeof (EFI_IPv4_ADDRESS)); } // // Configure the default DNS server if server assigned. // Status = HttpBootRegisterIp4Dns ( Private, Option->Length, Option->Data ); if (EFI_ERROR (Status)) { FreePool (Private->DnsServerIp); Private->DnsServerIp = NULL; return Status; } } // // Extract the port from URL, and use default HTTP port 80 if not provided. // Status = HttpUrlGetPort ( Private->BootFileUri, Private->BootFileUriParser, &Private->Port ); if (EFI_ERROR (Status) || Private->Port == 0) { Private->Port = 80; } // // All boot informations are valid here. // // // Update the device path to include the boot resource information. // Status = HttpBootUpdateDevicePath (Private); if (EFI_ERROR (Status) && Private->DnsServerIp != NULL) { FreePool (Private->DnsServerIp); Private->DnsServerIp = NULL; } return Status; } /** Parse the boot file URI information from the selected Dhcp6 offer packet. @param[in] Private The pointer to the driver's private data. @retval EFI_SUCCESS Successfully parsed out all the boot information. @retval Others Failed to parse out the boot information. **/ EFI_STATUS HttpBootDhcp6ExtractUriInfo ( IN HTTP_BOOT_PRIVATE_DATA *Private ) { HTTP_BOOT_DHCP6_PACKET_CACHE *SelectOffer; HTTP_BOOT_DHCP6_PACKET_CACHE *HttpOffer; UINT32 SelectIndex; UINT32 ProxyIndex; UINT32 DnsServerIndex; EFI_DHCP6_PACKET_OPTION *Option; EFI_IPv6_ADDRESS IpAddr; CHAR8 *HostName; UINTN HostNameSize; CHAR16 *HostNameStr; EFI_STATUS Status; ASSERT (Private != NULL); ASSERT (Private->SelectIndex != 0); SelectIndex = Private->SelectIndex - 1; ASSERT (SelectIndex < HTTP_BOOT_OFFER_MAX_NUM); DnsServerIndex = 0; Status = EFI_SUCCESS; HostName = NULL; // // SelectOffer contains the IP address configuration and name server configuration. // HttpOffer contains the boot file URL. // SelectOffer = &Private->OfferBuffer[SelectIndex].Dhcp6; if (Private->FilePathUri == NULL) { // // In Corporate environment, we need a HttpOffer. // if ((SelectOffer->OfferType == HttpOfferTypeDhcpIpUri) || (SelectOffer->OfferType == HttpOfferTypeDhcpIpUriDns) || (SelectOffer->OfferType == HttpOfferTypeDhcpNameUriDns)) { HttpOffer = SelectOffer; } else { ASSERT (Private->SelectProxyType != HttpOfferTypeMax); ProxyIndex = Private->OfferIndex[Private->SelectProxyType][0]; HttpOffer = &Private->OfferBuffer[ProxyIndex].Dhcp6; } Private->BootFileUriParser = HttpOffer->UriParser; Private->BootFileUri = (CHAR8*) HttpOffer->OptList[HTTP_BOOT_DHCP6_IDX_BOOT_FILE_URL]->Data; } else { // // In Home environment the BootFileUri comes from the FilePath. // Private->BootFileUriParser = Private->FilePathUriParser; Private->BootFileUri = Private->FilePathUri; } // // Check the URI scheme. // Status = HttpBootCheckUriScheme (Private->BootFileUri); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "HttpBootDhcp6ExtractUriInfo: %r.\n", Status)); if (Status == EFI_INVALID_PARAMETER) { AsciiPrint ("\n Error: Invalid URI address.\n"); } else if (Status == EFI_ACCESS_DENIED) { AsciiPrint ("\n Error: Access forbidden, only HTTPS connection is allowed.\n"); } return Status; } // // Set the Local station address to IP layer. // Status = HttpBootSetIp6Address (Private); if (EFI_ERROR (Status)) { return Status; } // // Register the IPv6 gateway address to the network device. // Status = HttpBootSetIp6Gateway (Private); if (EFI_ERROR (Status)) { return Status; } if ((SelectOffer->OfferType == HttpOfferTypeDhcpNameUriDns) || (SelectOffer->OfferType == HttpOfferTypeDhcpDns) || (SelectOffer->OfferType == HttpOfferTypeDhcpIpUriDns)) { Option = SelectOffer->OptList[HTTP_BOOT_DHCP6_IDX_DNS_SERVER]; ASSERT (Option != NULL); // // Record the Dns Server address list. // Private->DnsServerCount = HTONS (Option->OpLen) / sizeof (EFI_IPv6_ADDRESS); Private->DnsServerIp = AllocateZeroPool (Private->DnsServerCount * sizeof (EFI_IP_ADDRESS)); if (Private->DnsServerIp == NULL) { return EFI_OUT_OF_RESOURCES; } for (DnsServerIndex = 0; DnsServerIndex < Private->DnsServerCount; DnsServerIndex++) { CopyMem (&(Private->DnsServerIp[DnsServerIndex].v6), &(((EFI_IPv6_ADDRESS *) Option->Data)[DnsServerIndex]), sizeof (EFI_IPv6_ADDRESS)); } // // Configure the default DNS server if server assigned. // Status = HttpBootSetIp6Dns ( Private, HTONS (Option->OpLen), Option->Data ); if (EFI_ERROR (Status)) { goto Error; } } // // Extract the HTTP server Ip from URL. This is used to Check route table // whether can send message to HTTP Server Ip through the GateWay. // Status = HttpUrlGetIp6 ( Private->BootFileUri, Private->BootFileUriParser, &IpAddr ); if (EFI_ERROR (Status)) { // // The Http server address is expressed by Name Ip, so perform DNS resolution // Status = HttpUrlGetHostName ( Private->BootFileUri, Private->BootFileUriParser, &HostName ); if (EFI_ERROR (Status)) { goto Error; } HostNameSize = AsciiStrSize (HostName); HostNameStr = AllocateZeroPool (HostNameSize * sizeof (CHAR16)); if (HostNameStr == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Error; } AsciiStrToUnicodeStrS (HostName, HostNameStr, HostNameSize); if (HostName != NULL) { FreePool (HostName); } Status = HttpBootDns (Private, HostNameStr, &IpAddr); FreePool (HostNameStr); if (EFI_ERROR (Status)) { AsciiPrint ("\n Error: Could not retrieve the host address from DNS server.\n"); goto Error; } } CopyMem (&Private->ServerIp.v6, &IpAddr, sizeof (EFI_IPv6_ADDRESS)); // // Extract the port from URL, and use default HTTP port 80 if not provided. // Status = HttpUrlGetPort ( Private->BootFileUri, Private->BootFileUriParser, &Private->Port ); if (EFI_ERROR (Status) || Private->Port == 0) { Private->Port = 80; } // // All boot informations are valid here. // // // Update the device path to include the boot resource information. // Status = HttpBootUpdateDevicePath (Private); if (EFI_ERROR (Status)) { goto Error; } return Status; Error: if (Private->DnsServerIp != NULL) { FreePool (Private->DnsServerIp); Private->DnsServerIp = NULL; } return Status; } /** Discover all the boot information for boot file. @param[in, out] Private The pointer to the driver's private data. @retval EFI_SUCCESS Successfully obtained all the boot information . @retval Others Failed to retrieve the boot information. **/ EFI_STATUS HttpBootDiscoverBootInfo ( IN OUT HTTP_BOOT_PRIVATE_DATA *Private ) { EFI_STATUS Status; // // Start D.O.R.A/S.A.R.R exchange to acquire station ip address and // other Http boot information. // Status = HttpBootDhcp (Private); if (EFI_ERROR (Status)) { return Status; } if (!Private->UsingIpv6) { Status = HttpBootDhcp4ExtractUriInfo (Private); } else { Status = HttpBootDhcp6ExtractUriInfo (Private); } return Status; } /** HttpIo Callback function which will be invoked when specified HTTP_IO_CALLBACK_EVENT happened. @param[in] EventType Indicate the Event type that occurs in the current callback. @param[in] Message HTTP message which will be send to, or just received from HTTP server. @param[in] Context The Callback Context pointer. @retval EFI_SUCCESS Tells the HttpIo to continue the HTTP process. @retval Others Tells the HttpIo to abort the current HTTP process. **/ EFI_STATUS EFIAPI HttpBootHttpIoCallback ( IN HTTP_IO_CALLBACK_EVENT EventType, IN EFI_HTTP_MESSAGE *Message, IN VOID *Context ) { HTTP_BOOT_PRIVATE_DATA *Private; EFI_STATUS Status; Private = (HTTP_BOOT_PRIVATE_DATA *) Context; if (Private->HttpBootCallback != NULL) { Status = Private->HttpBootCallback->Callback ( Private->HttpBootCallback, EventType == HttpIoRequest ? HttpBootHttpRequest : HttpBootHttpResponse, EventType == HttpIoRequest ? FALSE : TRUE, sizeof (EFI_HTTP_MESSAGE), (VOID *) Message ); return Status; } return EFI_SUCCESS; } /** Create a HttpIo instance for the file download. @param[in] Private The pointer to the driver's private data. @retval EFI_SUCCESS Successfully created. @retval Others Failed to create HttpIo. **/ EFI_STATUS HttpBootCreateHttpIo ( IN HTTP_BOOT_PRIVATE_DATA *Private ) { HTTP_IO_CONFIG_DATA ConfigData; EFI_STATUS Status; EFI_HANDLE ImageHandle; ASSERT (Private != NULL); ZeroMem (&ConfigData, sizeof (HTTP_IO_CONFIG_DATA)); if (!Private->UsingIpv6) { ConfigData.Config4.HttpVersion = HttpVersion11; ConfigData.Config4.RequestTimeOut = HTTP_BOOT_REQUEST_TIMEOUT; IP4_COPY_ADDRESS (&ConfigData.Config4.LocalIp, &Private->StationIp.v4); IP4_COPY_ADDRESS (&ConfigData.Config4.SubnetMask, &Private->SubnetMask.v4); ImageHandle = Private->Ip4Nic->ImageHandle; } else { ConfigData.Config6.HttpVersion = HttpVersion11; ConfigData.Config6.RequestTimeOut = HTTP_BOOT_REQUEST_TIMEOUT; IP6_COPY_ADDRESS (&ConfigData.Config6.LocalIp, &Private->StationIp.v6); ImageHandle = Private->Ip6Nic->ImageHandle; } Status = HttpIoCreateIo ( ImageHandle, Private->Controller, Private->UsingIpv6 ? IP_VERSION_6 : IP_VERSION_4, &ConfigData, HttpBootHttpIoCallback, (VOID *) Private, &Private->HttpIo ); if (EFI_ERROR (Status)) { return Status; } Private->HttpCreated = TRUE; return EFI_SUCCESS; } /** Release all the resource of a cache item. @param[in] Cache The pointer to the cache item. **/ VOID HttpBootFreeCache ( IN HTTP_BOOT_CACHE_CONTENT *Cache ) { UINTN Index; LIST_ENTRY *Entry; LIST_ENTRY *NextEntry; HTTP_BOOT_ENTITY_DATA *EntityData; if (Cache != NULL) { // // Free the request data // if (Cache->RequestData != NULL) { if (Cache->RequestData->Url != NULL) { FreePool (Cache->RequestData->Url); } FreePool (Cache->RequestData); } // // Free the response header // if (Cache->ResponseData != NULL) { if (Cache->ResponseData->Headers != NULL) { for (Index = 0; Index < Cache->ResponseData->HeaderCount; Index++) { FreePool (Cache->ResponseData->Headers[Index].FieldName); FreePool (Cache->ResponseData->Headers[Index].FieldValue); } FreePool (Cache->ResponseData->Headers); } } // // Free the response body // NET_LIST_FOR_EACH_SAFE (Entry, NextEntry, &Cache->EntityDataList) { EntityData = NET_LIST_USER_STRUCT (Entry, HTTP_BOOT_ENTITY_DATA, Link); if (EntityData->Block != NULL) { FreePool (EntityData->Block); } RemoveEntryList (&EntityData->Link); FreePool (EntityData); } FreePool (Cache); } } /** Clean up all cached data. @param[in] Private The pointer to the driver's private data. **/ VOID HttpBootFreeCacheList ( IN HTTP_BOOT_PRIVATE_DATA *Private ) { LIST_ENTRY *Entry; LIST_ENTRY *NextEntry; HTTP_BOOT_CACHE_CONTENT *Cache; NET_LIST_FOR_EACH_SAFE (Entry, NextEntry, &Private->CacheList) { Cache = NET_LIST_USER_STRUCT (Entry, HTTP_BOOT_CACHE_CONTENT, Link); RemoveEntryList (&Cache->Link); HttpBootFreeCache (Cache); } } /** Get the file content from cached data. @param[in] Private The pointer to the driver's private data. @param[in] Uri Uri of the file to be retrieved from cache. @param[in, out] BufferSize On input the size of Buffer in bytes. On output with a return code of EFI_SUCCESS, the amount of data transferred to Buffer. On output with a return code of EFI_BUFFER_TOO_SMALL, the size of Buffer required to retrieve the requested file. @param[out] Buffer The memory buffer to transfer the file to. IF Buffer is NULL, then the size of the requested file is returned in BufferSize. @param[out] ImageType The image type of the downloaded file. @retval EFI_SUCCESS Successfully created. @retval Others Failed to create HttpIo. **/ EFI_STATUS HttpBootGetFileFromCache ( IN HTTP_BOOT_PRIVATE_DATA *Private, IN CHAR16 *Uri, IN OUT UINTN *BufferSize, OUT UINT8 *Buffer, OUT HTTP_BOOT_IMAGE_TYPE *ImageType ) { LIST_ENTRY *Entry; LIST_ENTRY *Entry2; HTTP_BOOT_CACHE_CONTENT *Cache; HTTP_BOOT_ENTITY_DATA *EntityData; UINTN CopyedSize; if (Uri == NULL || BufferSize == NULL || Buffer == NULL || ImageType == NULL) { return EFI_INVALID_PARAMETER; } NET_LIST_FOR_EACH (Entry, &Private->CacheList) { Cache = NET_LIST_USER_STRUCT (Entry, HTTP_BOOT_CACHE_CONTENT, Link); // // Compare the URI to see whether we already have a cache for this file. // if ((Cache->RequestData != NULL) && (Cache->RequestData->Url != NULL) && (StrCmp (Uri, Cache->RequestData->Url) == 0)) { // // Hit in cache, record image type. // *ImageType = Cache->ImageType; // // Check buffer size. // if (*BufferSize < Cache->EntityLength) { *BufferSize = Cache->EntityLength; return EFI_BUFFER_TOO_SMALL; } // // Fill data to buffer. // CopyedSize = 0; NET_LIST_FOR_EACH (Entry2, &Cache->EntityDataList) { EntityData = NET_LIST_USER_STRUCT (Entry2, HTTP_BOOT_ENTITY_DATA, Link); if (*BufferSize > CopyedSize) { CopyMem ( Buffer + CopyedSize, EntityData->DataStart, MIN (EntityData->DataLength, *BufferSize - CopyedSize) ); CopyedSize += MIN (EntityData->DataLength, *BufferSize - CopyedSize); } } *BufferSize = CopyedSize; return EFI_SUCCESS; } } return EFI_NOT_FOUND; } /** A callback function to intercept events during message parser. This function will be invoked during HttpParseMessageBody() with various events type. An error return status of the callback function will cause the HttpParseMessageBody() aborted. @param[in] EventType Event type of this callback call. @param[in] Data A pointer to data buffer. @param[in] Length Length in bytes of the Data. @param[in] Context Callback context set by HttpInitMsgParser(). @retval EFI_SUCCESS Continue to parser the message body. @retval Others Abort the parse. **/ EFI_STATUS EFIAPI HttpBootGetBootFileCallback ( IN HTTP_BODY_PARSE_EVENT EventType, IN CHAR8 *Data, IN UINTN Length, IN VOID *Context ) { HTTP_BOOT_CALLBACK_DATA *CallbackData; HTTP_BOOT_ENTITY_DATA *NewEntityData; EFI_STATUS Status; EFI_HTTP_BOOT_CALLBACK_PROTOCOL *HttpBootCallback; // // We only care about the entity data. // if (EventType != BodyParseEventOnData) { return EFI_SUCCESS; } CallbackData = (HTTP_BOOT_CALLBACK_DATA *) Context; HttpBootCallback = CallbackData->Private->HttpBootCallback; if (HttpBootCallback != NULL) { Status = HttpBootCallback->Callback ( HttpBootCallback, HttpBootHttpEntityBody, TRUE, (UINT32)Length, Data ); if (EFI_ERROR (Status)) { return Status; } } // // Copy data if caller has provided a buffer. // if (CallbackData->BufferSize > CallbackData->CopyedSize) { CopyMem ( CallbackData->Buffer + CallbackData->CopyedSize, Data, MIN (Length, CallbackData->BufferSize - CallbackData->CopyedSize) ); CallbackData->CopyedSize += MIN (Length, CallbackData->BufferSize - CallbackData->CopyedSize); } // // The caller doesn't provide a buffer, save the block into cache list. // if (CallbackData->Cache != NULL) { NewEntityData = AllocatePool (sizeof (HTTP_BOOT_ENTITY_DATA)); if (NewEntityData == NULL) { return EFI_OUT_OF_RESOURCES; } if (CallbackData->NewBlock) { NewEntityData->Block = CallbackData->Block; CallbackData->Block = NULL; } NewEntityData->DataLength = Length; NewEntityData->DataStart = (UINT8*) Data; InsertTailList (&CallbackData->Cache->EntityDataList, &NewEntityData->Link); } return EFI_SUCCESS; } /** This function download the boot file by using UEFI HTTP protocol. @param[in] Private The pointer to the driver's private data. @param[in] HeaderOnly Only request the response header, it could save a lot of time if the caller only want to know the size of the requested file. @param[in, out] BufferSize On input the size of Buffer in bytes. On output with a return code of EFI_SUCCESS, the amount of data transferred to Buffer. On output with a return code of EFI_BUFFER_TOO_SMALL, the size of Buffer required to retrieve the requested file. @param[out] Buffer The memory buffer to transfer the file to. IF Buffer is NULL, then the size of the requested file is returned in BufferSize. @param[out] ImageType The image type of the downloaded file. @retval EFI_SUCCESS The file was loaded. @retval EFI_INVALID_PARAMETER BufferSize is NULL or Buffer Size is not NULL but Buffer is NULL. @retval EFI_OUT_OF_RESOURCES Could not allocate needed resources @retval EFI_BUFFER_TOO_SMALL The BufferSize is too small to read the current directory entry. BufferSize has been updated with the size needed to complete the request. @retval Others Unexpected error happened. **/ EFI_STATUS HttpBootGetBootFile ( IN HTTP_BOOT_PRIVATE_DATA *Private, IN BOOLEAN HeaderOnly, IN OUT UINTN *BufferSize, OUT UINT8 *Buffer, OUT HTTP_BOOT_IMAGE_TYPE *ImageType ) { EFI_STATUS Status; EFI_HTTP_STATUS_CODE StatusCode; CHAR8 *HostName; EFI_HTTP_REQUEST_DATA *RequestData; HTTP_IO_RESPONSE_DATA *ResponseData; HTTP_IO_RESPONSE_DATA ResponseBody; HTTP_IO *HttpIo; HTTP_IO_HEADER *HttpIoHeader; VOID *Parser; HTTP_BOOT_CALLBACK_DATA Context; UINTN ContentLength; HTTP_BOOT_CACHE_CONTENT *Cache; UINT8 *Block; UINTN UrlSize; CHAR16 *Url; BOOLEAN IdentityMode; UINTN ReceivedSize; ASSERT (Private != NULL); ASSERT (Private->HttpCreated); if (BufferSize == NULL || ImageType == NULL) { return EFI_INVALID_PARAMETER; } if (*BufferSize != 0 && Buffer == NULL) { return EFI_INVALID_PARAMETER; } // // First, check whether we already cached the requested Uri. // UrlSize = AsciiStrSize (Private->BootFileUri); Url = AllocatePool (UrlSize * sizeof (CHAR16)); if (Url == NULL) { return EFI_OUT_OF_RESOURCES; } AsciiStrToUnicodeStrS (Private->BootFileUri, Url, UrlSize); if (!HeaderOnly && Buffer != NULL) { Status = HttpBootGetFileFromCache (Private, Url, BufferSize, Buffer, ImageType); if (Status != EFI_NOT_FOUND) { FreePool (Url); return Status; } } // // Not found in cache, try to download it through HTTP. // // // 1. Create a temp cache item for the requested URI if caller doesn't provide buffer. // Cache = NULL; if ((!HeaderOnly) && (*BufferSize == 0)) { Cache = AllocateZeroPool (sizeof (HTTP_BOOT_CACHE_CONTENT)); if (Cache == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ERROR_1; } Cache->ImageType = ImageTypeMax; InitializeListHead (&Cache->EntityDataList); } // // 2. Send HTTP request message. // // // 2.1 Build HTTP header for the request, 3 header is needed to download a boot file: // Host // Accept // User-Agent // HttpIoHeader = HttpBootCreateHeader (3); if (HttpIoHeader == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ERROR_2; } // // Add HTTP header field 1: Host // HostName = NULL; Status = HttpUrlGetHostName ( Private->BootFileUri, Private->BootFileUriParser, &HostName ); if (EFI_ERROR (Status)) { goto ERROR_3; } Status = HttpBootSetHeader ( HttpIoHeader, HTTP_HEADER_HOST, HostName ); FreePool (HostName); if (EFI_ERROR (Status)) { goto ERROR_3; } // // Add HTTP header field 2: Accept // Status = HttpBootSetHeader ( HttpIoHeader, HTTP_HEADER_ACCEPT, "*/*" ); if (EFI_ERROR (Status)) { goto ERROR_3; } // // Add HTTP header field 3: User-Agent // Status = HttpBootSetHeader ( HttpIoHeader, HTTP_HEADER_USER_AGENT, HTTP_USER_AGENT_EFI_HTTP_BOOT ); if (EFI_ERROR (Status)) { goto ERROR_3; } // // 2.2 Build the rest of HTTP request info. // RequestData = AllocatePool (sizeof (EFI_HTTP_REQUEST_DATA)); if (RequestData == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ERROR_3; } RequestData->Method = HeaderOnly ? HttpMethodHead : HttpMethodGet; RequestData->Url = Url; // // 2.3 Record the request info in a temp cache item. // if (Cache != NULL) { Cache->RequestData = RequestData; } // // 2.4 Send out the request to HTTP server. // HttpIo = &Private->HttpIo; Status = HttpIoSendRequest ( HttpIo, RequestData, HttpIoHeader->HeaderCount, HttpIoHeader->Headers, 0, NULL ); if (EFI_ERROR (Status)) { goto ERROR_4; } // // 3. Receive HTTP response message. // // // 3.1 First step, use zero BodyLength to only receive the response headers. // ResponseData = AllocateZeroPool (sizeof(HTTP_IO_RESPONSE_DATA)); if (ResponseData == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ERROR_4; } Status = HttpIoRecvResponse ( &Private->HttpIo, TRUE, ResponseData ); if (EFI_ERROR (Status) || EFI_ERROR (ResponseData->Status)) { if (EFI_ERROR (ResponseData->Status)) { StatusCode = HttpIo->RspToken.Message->Data.Response->StatusCode; HttpBootPrintErrorMessage (StatusCode); Status = ResponseData->Status; } goto ERROR_5; } // // Check the image type according to server's response. // Status = HttpBootCheckImageType ( Private->BootFileUri, Private->BootFileUriParser, ResponseData->HeaderCount, ResponseData->Headers, ImageType ); if (EFI_ERROR (Status)) { goto ERROR_5; } // // 3.2 Cache the response header. // if (Cache != NULL) { Cache->ResponseData = ResponseData; Cache->ImageType = *ImageType; } // // 3.3 Init a message-body parser from the header information. // Parser = NULL; Context.NewBlock = FALSE; Context.Block = NULL; Context.CopyedSize = 0; Context.Buffer = Buffer; Context.BufferSize = *BufferSize; Context.Cache = Cache; Context.Private = Private; Status = HttpInitMsgParser ( HeaderOnly ? HttpMethodHead : HttpMethodGet, ResponseData->Response.StatusCode, ResponseData->HeaderCount, ResponseData->Headers, HttpBootGetBootFileCallback, (VOID*) &Context, &Parser ); if (EFI_ERROR (Status)) { goto ERROR_6; } // // 3.4 Continue to receive and parse message-body if needed. // Block = NULL; if (!HeaderOnly) { // // 3.4.1, check whether we are in identity transfer-coding. // ContentLength = 0; Status = HttpGetEntityLength (Parser, &ContentLength); if (!EFI_ERROR (Status)) { IdentityMode = TRUE; } else { IdentityMode = FALSE; } // // 3.4.2, start the message-body download, the identity and chunked transfer-coding // is handled in different path here. // ZeroMem (&ResponseBody, sizeof (HTTP_IO_RESPONSE_DATA)); if (IdentityMode) { // // In identity transfer-coding there is no need to parse the message body, // just download the message body to the user provided buffer directly. // ReceivedSize = 0; while (ReceivedSize < ContentLength) { ResponseBody.Body = (CHAR8*) Buffer + ReceivedSize; ResponseBody.BodyLength = *BufferSize - ReceivedSize; Status = HttpIoRecvResponse ( &Private->HttpIo, FALSE, &ResponseBody ); if (EFI_ERROR (Status) || EFI_ERROR (ResponseBody.Status)) { if (EFI_ERROR (ResponseBody.Status)) { Status = ResponseBody.Status; } goto ERROR_6; } ReceivedSize += ResponseBody.BodyLength; if (Private->HttpBootCallback != NULL) { Status = Private->HttpBootCallback->Callback ( Private->HttpBootCallback, HttpBootHttpEntityBody, TRUE, (UINT32)ResponseBody.BodyLength, ResponseBody.Body ); if (EFI_ERROR (Status)) { goto ERROR_6; } } } } else { // // In "chunked" transfer-coding mode, so we need to parse the received // data to get the real entity content. // Block = NULL; while (!HttpIsMessageComplete (Parser)) { // // Allocate a buffer in Block to hold the message-body. // If caller provides a buffer, this Block will be reused in every HttpIoRecvResponse(). // Otherwise a buffer, the buffer in Block will be cached and we should allocate a new before // every HttpIoRecvResponse(). // if (Block == NULL || Context.BufferSize == 0) { Block = AllocatePool (HTTP_BOOT_BLOCK_SIZE); if (Block == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ERROR_6; } Context.NewBlock = TRUE; Context.Block = Block; } else { Context.NewBlock = FALSE; } ResponseBody.Body = (CHAR8*) Block; ResponseBody.BodyLength = HTTP_BOOT_BLOCK_SIZE; Status = HttpIoRecvResponse ( &Private->HttpIo, FALSE, &ResponseBody ); if (EFI_ERROR (Status) || EFI_ERROR (ResponseBody.Status)) { if (EFI_ERROR (ResponseBody.Status)) { Status = ResponseBody.Status; } goto ERROR_6; } // // Parse the new received block of the message-body, the block will be saved in cache. // Status = HttpParseMessageBody ( Parser, ResponseBody.BodyLength, ResponseBody.Body ); if (EFI_ERROR (Status)) { goto ERROR_6; } } } } // // 3.5 Message-body receive & parse is completed, we should be able to get the file size now. // Status = HttpGetEntityLength (Parser, &ContentLength); if (EFI_ERROR (Status)) { goto ERROR_6; } if (*BufferSize < ContentLength) { Status = EFI_BUFFER_TOO_SMALL; } else { Status = EFI_SUCCESS; } *BufferSize = ContentLength; // // 4. Save the cache item to driver's cache list and return. // if (Cache != NULL) { Cache->EntityLength = ContentLength; InsertTailList (&Private->CacheList, &Cache->Link); } if (Parser != NULL) { HttpFreeMsgParser (Parser); } return Status; ERROR_6: if (Parser != NULL) { HttpFreeMsgParser (Parser); } if (Context.Block != NULL) { FreePool (Context.Block); } HttpBootFreeCache (Cache); ERROR_5: if (ResponseData != NULL) { FreePool (ResponseData); } ERROR_4: if (RequestData != NULL) { FreePool (RequestData); } ERROR_3: HttpBootFreeHeader (HttpIoHeader); ERROR_2: if (Cache != NULL) { FreePool (Cache); } ERROR_1: if (Url != NULL) { FreePool (Url); } return Status; }
NaohiroTamura/edk2
ArmPkg/Include/Library/StandaloneMmMmuLib.h
<reponame>NaohiroTamura/edk2<filename>ArmPkg/Include/Library/StandaloneMmMmuLib.h<gh_stars>1-10 /** @file Copyright (c) 2018, ARM Ltd. All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef __STANDALONEMM_MMU_LIB__ #define __STANDALONEMM_MMU_LIB__ EFI_STATUS ArmSetMemoryRegionNoExec ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length ); EFI_STATUS ArmClearMemoryRegionNoExec ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length ); EFI_STATUS ArmSetMemoryRegionReadOnly ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length ); EFI_STATUS ArmClearMemoryRegionReadOnly ( IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length ); #endif /* __STANDALONEMM_MMU_LIB__ */
NaohiroTamura/edk2
ArmPlatformPkg/Library/PL031RealTimeClockLib/PL031RealTimeClock.h
<reponame>NaohiroTamura/edk2<filename>ArmPlatformPkg/Library/PL031RealTimeClockLib/PL031RealTimeClock.h<gh_stars>1-10 /** @file * * Copyright (c) 2011 - 2014, ARM Limited. All rights reserved. * * SPDX-License-Identifier: BSD-2-Clause-Patent * **/ #ifndef __PL031_REAL_TIME_CLOCK_H__ #define __PL031_REAL_TIME_CLOCK_H__ // PL031 Registers #define PL031_RTC_DR_DATA_REGISTER 0x000 #define PL031_RTC_MR_MATCH_REGISTER 0x004 #define PL031_RTC_LR_LOAD_REGISTER 0x008 #define PL031_RTC_CR_CONTROL_REGISTER 0x00C #define PL031_RTC_IMSC_IRQ_MASK_SET_CLEAR_REGISTER 0x010 #define PL031_RTC_RIS_RAW_IRQ_STATUS_REGISTER 0x014 #define PL031_RTC_MIS_MASKED_IRQ_STATUS_REGISTER 0x018 #define PL031_RTC_ICR_IRQ_CLEAR_REGISTER 0x01C #define PL031_RTC_PERIPH_ID0 0xFE0 #define PL031_RTC_PERIPH_ID1 0xFE4 #define PL031_RTC_PERIPH_ID2 0xFE8 #define PL031_RTC_PERIPH_ID3 0xFEC #define PL031_RTC_PCELL_ID0 0xFF0 #define PL031_RTC_PCELL_ID1 0xFF4 #define PL031_RTC_PCELL_ID2 0xFF8 #define PL031_RTC_PCELL_ID3 0xFFC // PL031 Values #define PL031_RTC_ENABLED 0x00000001 #define PL031_SET_IRQ_MASK 0x00000001 #define PL031_IRQ_TRIGGERED 0x00000001 #define PL031_CLEAR_IRQ 0x00000001 #define PL031_COUNTS_PER_SECOND 1 #endif
NaohiroTamura/edk2
ArmPlatformPkg/Drivers/PL061GpioDxe/PL061Gpio.h
<gh_stars>1-10 /** @file * * Copyright (c) 2011-2012, ARM Limited. All rights reserved. * * SPDX-License-Identifier: BSD-2-Clause-Patent * **/ #ifndef __PL061_GPIO_H__ #define __PL061_GPIO_H__ #include <Protocol/EmbeddedGpio.h> // PL061 GPIO Registers #define PL061_GPIO_DATA_REG_OFFSET ((UINTN) 0x000) #define PL061_GPIO_DATA_REG 0x000 #define PL061_GPIO_DIR_REG 0x400 #define PL061_GPIO_IS_REG 0x404 #define PL061_GPIO_IBE_REG 0x408 #define PL061_GPIO_IEV_REG 0x40C #define PL061_GPIO_IE_REG 0x410 #define PL061_GPIO_RIS_REG 0x414 #define PL061_GPIO_MIS_REG 0x410 #define PL061_GPIO_IC_REG 0x41C #define PL061_GPIO_AFSEL_REG 0x420 #define PL061_GPIO_PERIPH_ID0 0xFE0 #define PL061_GPIO_PERIPH_ID1 0xFE4 #define PL061_GPIO_PERIPH_ID2 0xFE8 #define PL061_GPIO_PERIPH_ID3 0xFEC #define PL061_GPIO_PCELL_ID0 0xFF0 #define PL061_GPIO_PCELL_ID1 0xFF4 #define PL061_GPIO_PCELL_ID2 0xFF8 #define PL061_GPIO_PCELL_ID3 0xFFC #define PL061_GPIO_PINS 8 // All bits low except one bit high, native bit length #define GPIO_PIN_MASK(Pin) (1UL << ((UINTN)(Pin))) #endif // __PL061_GPIO_H__
NaohiroTamura/edk2
MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.h
/** @file Internal library declaration for PCI Bus module. Copyright (c) 2006 - 2011, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef _EFI_PCI_LIB_H_ #define _EFI_PCI_LIB_H_ typedef struct { EFI_HANDLE Handle; } EFI_DEVICE_HANDLE_EXTENDED_DATA_PAYLOAD; typedef struct { UINT32 Bar; UINT16 DevicePathSize; UINT16 ReqResSize; UINT16 AllocResSize; UINT8 *DevicePath; UINT8 *ReqRes; UINT8 *AllocRes; } EFI_RESOURCE_ALLOC_FAILURE_ERROR_DATA_PAYLOAD; /** Retrieve the PCI Card device BAR information via PciIo interface. @param PciIoDevice PCI Card device instance. **/ VOID GetBackPcCardBar ( IN PCI_IO_DEVICE *PciIoDevice ); /** Remove rejected pci device from specific root bridge handle. @param RootBridgeHandle Specific parent root bridge handle. @param Bridge Bridge device instance. **/ VOID RemoveRejectedPciDevices ( IN EFI_HANDLE RootBridgeHandle, IN PCI_IO_DEVICE *Bridge ); /** Submits the I/O and memory resource requirements for the specified PCI Host Bridge. @param PciResAlloc Point to protocol instance of EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL. @retval EFI_SUCCESS Successfully finished resource allocation. @retval EFI_NOT_FOUND Cannot get root bridge instance. @retval EFI_OUT_OF_RESOURCES Platform failed to program the resources if no hot plug supported. @retval other Some error occurred when allocating resources for the PCI Host Bridge. @note Feature flag PcdPciBusHotplugDeviceSupport determine whether need support hotplug. **/ EFI_STATUS PciHostBridgeResourceAllocator ( IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc ); /** Allocate NumberOfBuses buses and return the next available PCI bus number. @param Bridge Bridge device instance. @param StartBusNumber Current available PCI bus number. @param NumberOfBuses Number of buses enumerated below the StartBusNumber. @param NextBusNumber Next available PCI bus number. @retval EFI_SUCCESS Available bus number resource is enough. Next available PCI bus number is returned in NextBusNumber. @retval EFI_OUT_OF_RESOURCES Available bus number resource is not enough for allocation. **/ EFI_STATUS PciAllocateBusNumber ( IN PCI_IO_DEVICE *Bridge, IN UINT8 StartBusNumber, IN UINT8 NumberOfBuses, OUT UINT8 *NextBusNumber ); /** Scan pci bus and assign bus number to the given PCI bus system. @param Bridge Bridge device instance. @param StartBusNumber start point. @param SubBusNumber Point to sub bus number. @param PaddedBusRange Customized bus number. @retval EFI_SUCCESS Successfully scanned and assigned bus number. @retval other Some error occurred when scanning pci bus. @note Feature flag PcdPciBusHotplugDeviceSupport determine whether need support hotplug. **/ EFI_STATUS PciScanBus ( IN PCI_IO_DEVICE *Bridge, IN UINT8 StartBusNumber, OUT UINT8 *SubBusNumber, OUT UINT8 *PaddedBusRange ); /** Process Option Rom on the specified root bridge. @param Bridge Pci root bridge device instance. @retval EFI_SUCCESS Success process. @retval other Some error occurred when processing Option Rom on the root bridge. **/ EFI_STATUS PciRootBridgeP2CProcess ( IN PCI_IO_DEVICE *Bridge ); /** Process Option Rom on the specified host bridge. @param PciResAlloc Pointer to instance of EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL. @retval EFI_SUCCESS Success process. @retval EFI_NOT_FOUND Can not find the root bridge instance. @retval other Some error occurred when processing Option Rom on the host bridge. **/ EFI_STATUS PciHostBridgeP2CProcess ( IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc ); /** This function is used to enumerate the entire host bridge in a given platform. @param PciResAlloc A pointer to the PCI Host Resource Allocation protocol. @retval EFI_SUCCESS Successfully enumerated the host bridge. @retval EFI_OUT_OF_RESOURCES No enough memory available. @retval other Some error occurred when enumerating the host bridge. **/ EFI_STATUS PciHostBridgeEnumerator ( IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc ); #endif
NaohiroTamura/edk2
ArmPkg/Library/ArmDisassemblerLib/ArmDisassembler.c
/** @file Default exception handler Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <Base.h> #include <Library/BaseLib.h> #include <Library/PrintLib.h> #include <Library/ArmDisassemblerLib.h> CHAR8 *gCondition[] = { "EQ", "NE", "CS", "CC", "MI", "PL", "VS", "VC", "HI", "LS", "GE", "LT", "GT", "LE", "", "2" }; #define COND(_a) gCondition[((_a) >> 28)] CHAR8 *gReg[] = { "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "sp", "lr", "pc" }; CHAR8 *gLdmAdr[] = { "DA", "IA", "DB", "IB" }; CHAR8 *gLdmStack[] = { "FA", "FD", "EA", "ED" }; #define LDM_EXT(_reg, _off) ((_reg == 13) ? gLdmStack[(_off)] : gLdmAdr[(_off)]) #define SIGN(_U) ((_U) ? "" : "-") #define WRITE(_W) ((_W) ? "!" : "") #define BYTE(_B) ((_B) ? "B":"") #define USER(_B) ((_B) ? "^" : "") CHAR8 mMregListStr[4*15 + 1]; CHAR8 * MRegList ( UINT32 OpCode ) { UINTN Index, Start, End; BOOLEAN First; mMregListStr[0] = '\0'; AsciiStrCatS (mMregListStr, sizeof mMregListStr, "{"); for (Index = 0, First = TRUE; Index <= 15; Index++) { if ((OpCode & (1 << Index)) != 0) { Start = End = Index; for (Index++; ((OpCode & (1 << Index)) != 0) && Index <= 15; Index++) { End = Index; } if (!First) { AsciiStrCatS (mMregListStr, sizeof mMregListStr, ","); } else { First = FALSE; } if (Start == End) { AsciiStrCatS (mMregListStr, sizeof mMregListStr, gReg[Start]); AsciiStrCatS (mMregListStr, sizeof mMregListStr, ", "); } else { AsciiStrCatS (mMregListStr, sizeof mMregListStr, gReg[Start]); AsciiStrCatS (mMregListStr, sizeof mMregListStr, "-"); AsciiStrCatS (mMregListStr, sizeof mMregListStr, gReg[End]); } } } if (First) { AsciiStrCatS (mMregListStr, sizeof mMregListStr, "ERROR"); } AsciiStrCatS (mMregListStr, sizeof mMregListStr, "}"); // BugBug: Make caller pass in buffer it is cleaner return mMregListStr; } CHAR8 * FieldMask ( IN UINT32 Mask ) { return ""; } UINT32 RotateRight ( IN UINT32 Op, IN UINT32 Shift ) { return (Op >> Shift) | (Op << (32 - Shift)); } /** Place a disassembly of **OpCodePtr into buffer, and update OpCodePtr to point to next instruction. We cheat and only decode instructions that access memory. If the instruction is not found we dump the instruction in hex. @param OpCodePtr Pointer to pointer of ARM instruction to disassemble. @param Buf Buffer to sprintf disassembly into. @param Size Size of Buf in bytes. @param Extended TRUE dump hex for instruction too. **/ VOID DisassembleArmInstruction ( IN UINT32 **OpCodePtr, OUT CHAR8 *Buf, OUT UINTN Size, IN BOOLEAN Extended ) { UINT32 OpCode = **OpCodePtr; CHAR8 *Type, *Root; BOOLEAN I, P, U, B, W, L, S, H; UINT32 Rn, Rd, Rm; UINT32 imode, offset_8, offset_12; UINT32 Index; UINT32 shift_imm, shift; I = (OpCode & BIT25) == BIT25; P = (OpCode & BIT24) == BIT24; U = (OpCode & BIT23) == BIT23; B = (OpCode & BIT22) == BIT22; // Also called S W = (OpCode & BIT21) == BIT21; L = (OpCode & BIT20) == BIT20; S = (OpCode & BIT6) == BIT6; H = (OpCode & BIT5) == BIT5; Rn = (OpCode >> 16) & 0xf; Rd = (OpCode >> 12) & 0xf; Rm = (OpCode & 0xf); if (Extended) { Index = AsciiSPrint (Buf, Size, "0x%08x ", OpCode); Buf += Index; Size -= Index; } // LDREX, STREX if ((OpCode & 0x0fe000f0) == 0x01800090) { if (L) { // A4.1.27 LDREX{<cond>} <Rd>, [<Rn>] AsciiSPrint (Buf, Size, "LDREX%a %a, [%a]", COND (OpCode), gReg[Rd], gReg[Rn]); } else { // A4.1.103 STREX{<cond>} <Rd>, <Rm>, [<Rn>] AsciiSPrint (Buf, Size, "STREX%a %a, %a, [%a]", COND (OpCode), gReg[Rd], gReg[Rn], gReg[Rn]); } return; } // LDM/STM if ((OpCode & 0x0e000000) == 0x08000000) { if (L) { // A4.1.20 LDM{<cond>}<addressing_mode> <Rn>{!}, <registers> // A4.1.21 LDM{<cond>}<addressing_mode> <Rn>, <registers_without_pc>^ // A4.1.22 LDM{<cond>}<addressing_mode> <Rn>{!}, <registers_and_pc>^ AsciiSPrint (Buf, Size, "LDM%a%a, %a%a, %a", COND (OpCode), LDM_EXT (Rn ,(OpCode >> 23) & 3), gReg[Rn], WRITE (W), MRegList (OpCode), USER (B)); } else { // A4.1.97 STM{<cond>}<addressing_mode> <Rn>{!}, <registers> // A4.1.98 STM{<cond>}<addressing_mode> <Rn>, <registers>^ AsciiSPrint (Buf, Size, "STM%a%a, %a%a, %a", COND (OpCode), LDM_EXT (Rn ,(OpCode >> 23) & 3), gReg[Rn], WRITE (W), MRegList (OpCode), USER (B)); } return; } // LDR/STR Address Mode 2 if ( ((OpCode & 0x0c000000) == 0x04000000) || ((OpCode & 0xfd70f000 ) == 0xf550f000) ) { offset_12 = OpCode & 0xfff; if ((OpCode & 0xfd70f000 ) == 0xf550f000) { Index = AsciiSPrint (Buf, Size, "PLD"); } else { Index = AsciiSPrint (Buf, Size, "%a%a%a%a %a, ", L ? "LDR" : "STR", COND (OpCode), BYTE (B), (!(P) && W) ? "T":"", gReg[Rd]); } if (P) { if (!I) { // A5.2.2 [<Rn>, #+/-<offset_12>] // A5.2.5 [<Rn>, #+/-<offset_12>] AsciiSPrint (&Buf[Index], Size - Index, "[%a, #%a0x%x]%a", gReg[Rn], SIGN (U), offset_12, WRITE (W)); } else if ((OpCode & 0x03000ff0) == 0x03000000) { // A5.2.3 [<Rn>, +/-<Rm>] // A5.2.6 [<Rn>, +/-<Rm>]! AsciiSPrint (&Buf[Index], Size - Index, "[%a, #%a%a]%a", gReg[Rn], SIGN (U), WRITE (W)); } else { // A5.2.4 [<Rn>, +/-<Rm>, LSL #<shift_imm>] // A5.2.7 [<Rn>, +/-<Rm>, LSL #<shift_imm>]! shift_imm = (OpCode >> 7) & 0x1f; shift = (OpCode >> 5) & 0x3; if (shift == 0x0) { Type = "LSL"; } else if (shift == 0x1) { Type = "LSR"; if (shift_imm == 0) { shift_imm = 32; } } else if (shift == 0x2) { Type = "ASR"; } else if (shift_imm == 0) { AsciiSPrint (&Buf[Index], Size - Index, "[%a, #%a%a, %a, RRX]%a", gReg[Rn], SIGN (U), gReg[Rm], WRITE (W)); return; } else { Type = "ROR"; } AsciiSPrint (&Buf[Index], Size - Index, "[%a, #%a%a, %a, #%d]%a", gReg[Rn], SIGN (U), gReg[Rm], Type, shift_imm, WRITE (W)); } } else { // !P if (!I) { // A5.2.8 [<Rn>], #+/-<offset_12> AsciiSPrint (&Buf[Index], Size - Index, "[%a], #%a0x%x", gReg[Rn], SIGN (U), offset_12); } else if ((OpCode & 0x03000ff0) == 0x03000000) { // A5.2.9 [<Rn>], +/-<Rm> AsciiSPrint (&Buf[Index], Size - Index, "[%a], #%a%a", gReg[Rn], SIGN (U), gReg[Rm]); } else { // A5.2.10 [<Rn>], +/-<Rm>, LSL #<shift_imm> shift_imm = (OpCode >> 7) & 0x1f; shift = (OpCode >> 5) & 0x3; if (shift == 0x0) { Type = "LSL"; } else if (shift == 0x1) { Type = "LSR"; if (shift_imm == 0) { shift_imm = 32; } } else if (shift == 0x2) { Type = "ASR"; } else if (shift_imm == 0) { AsciiSPrint (&Buf[Index], Size - Index, "[%a], #%a%a, %a, RRX", gReg[Rn], SIGN (U), gReg[Rm]); // FIx me return; } else { Type = "ROR"; } AsciiSPrint (&Buf[Index], Size - Index, "[%a], #%a%a, %a, #%d", gReg[Rn], SIGN (U), gReg[Rm], Type, shift_imm); } } return; } if ((OpCode & 0x0e000000) == 0x00000000) { // LDR/STR address mode 3 // LDR|STR{<cond>}H|SH|SB|D <Rd>, <addressing_mode> if (L) { if (!S) { Root = "LDR%aH %a, "; } else if (!H) { Root = "LDR%aSB %a, "; } else { Root = "LDR%aSH %a, "; } } else { if (!S) { Root = "STR%aH %a "; } else if (!H) { Root = "LDR%aD %a "; } else { Root = "STR%aD %a "; } } Index = AsciiSPrint (Buf, Size, Root, COND (OpCode), gReg[Rd]); S = (OpCode & BIT6) == BIT6; H = (OpCode & BIT5) == BIT5; offset_8 = ((OpCode >> 4) | (OpCode * 0xf)) & 0xff; if (P & !W) { // Immediate offset/index if (B) { // A5.3.2 [<Rn>, #+/-<offset_8>] // A5.3.4 [<Rn>, #+/-<offset_8>]! AsciiSPrint (&Buf[Index], Size - Index, "[%a, #%a%d]%a", gReg[Rn], SIGN (U), offset_8, WRITE (W)); } else { // A5.3.3 [<Rn>, +/-<Rm>] // A5.3.5 [<Rn>, +/-<Rm>]! AsciiSPrint (&Buf[Index], Size - Index, "[%a, #%a%]a", gReg[Rn], SIGN (U), gReg[Rm], WRITE (W)); } } else { // Register offset/index if (B) { // A5.3.6 [<Rn>], #+/-<offset_8> AsciiSPrint (&Buf[Index], Size - Index, "[%a], #%a%d", gReg[Rn], SIGN (U), offset_8); } else { // A5.3.7 [<Rn>], +/-<Rm> AsciiSPrint (&Buf[Index], Size - Index, "[%a], #%a%a", gReg[Rn], SIGN (U), gReg[Rm]); } } return; } if ((OpCode & 0x0fb000f0) == 0x01000050) { // A4.1.108 SWP SWP{<cond>}B <Rd>, <Rm>, [<Rn>] // A4.1.109 SWPB SWP{<cond>}B <Rd>, <Rm>, [<Rn>] AsciiSPrint (Buf, Size, "SWP%a%a %a, %a, [%a]", COND (OpCode), BYTE (B), gReg[Rd], gReg[Rm], gReg[Rn]); return; } if ((OpCode & 0xfe5f0f00) == 0xf84d0500) { // A4.1.90 SRS SRS<addressing_mode> #<mode>{!} AsciiSPrint (Buf, Size, "SRS%a #0x%x%a", gLdmStack[(OpCode >> 23) & 3], OpCode & 0x1f, WRITE (W)); return; } if ((OpCode & 0xfe500f00) == 0xf8100500) { // A4.1.59 RFE<addressing_mode> <Rn>{!} AsciiSPrint (Buf, Size, "RFE%a %a", gLdmStack[(OpCode >> 23) & 3], gReg[Rn], WRITE (W)); return; } if ((OpCode & 0xfff000f0) == 0xe1200070) { // A4.1.7 BKPT <immed_16> AsciiSPrint (Buf, Size, "BKPT %x", ((OpCode >> 8) | (OpCode & 0xf)) & 0xffff); return; } if ((OpCode & 0xfff10020) == 0xf1000000) { // A4.1.16 CPS<effect> <iflags> {, #<mode>} if (((OpCode >> 6) & 0x7) == 0) { AsciiSPrint (Buf, Size, "CPS #0x%x", (OpCode & 0x2f)); } else { imode = (OpCode >> 18) & 0x3; Index = AsciiSPrint (Buf, Size, "CPS%a %a%a%a", (imode == 3) ? "ID":"IE", (OpCode & BIT8) ? "A":"", (OpCode & BIT7) ? "I":"", (OpCode & BIT6) ? "F":""); if ((OpCode & BIT17) != 0) { AsciiSPrint (&Buf[Index], Size - Index, ", #0x%x", OpCode & 0x1f); } } return; } if ((OpCode & 0x0f000000) == 0x0f000000) { // A4.1.107 SWI{<cond>} <immed_24> AsciiSPrint (Buf, Size, "SWI%a %x", COND (OpCode), OpCode & 0x00ffffff); return; } if ((OpCode & 0x0fb00000) == 0x01000000) { // A4.1.38 MRS{<cond>} <Rd>, CPSR MRS{<cond>} <Rd>, SPSR AsciiSPrint (Buf, Size, "MRS%a %a, %a", COND (OpCode), gReg[Rd], B ? "SPSR" : "CPSR"); return; } if ((OpCode & 0x0db00000) == 0x01200000) { // A4.1.38 MSR{<cond>} CPSR_<fields>, #<immediate> MSR{<cond>} CPSR_<fields>, <Rm> if (I) { // MSR{<cond>} CPSR_<fields>, #<immediate> AsciiSPrint (Buf, Size, "MRS%a %a_%a, #0x%x", COND (OpCode), B ? "SPSR" : "CPSR", FieldMask ((OpCode >> 16) & 0xf), RotateRight (OpCode & 0xf, ((OpCode >> 8) & 0xf) *2)); } else { // MSR{<cond>} CPSR_<fields>, <Rm> AsciiSPrint (Buf, Size, "MRS%a %a_%a, %a", COND (OpCode), B ? "SPSR" : "CPSR", gReg[Rd]); } return; } if ((OpCode & 0xff000010) == 0xfe000000) { // A4.1.13 CDP{<cond>} <coproc>, <opcode_1>, <CRd>, <CRn>, <CRm>, <opcode_2> AsciiSPrint (Buf, Size, "CDP%a 0x%x, 0x%x, CR%d, CR%d, CR%d, 0x%x", COND (OpCode), (OpCode >> 8) & 0xf, (OpCode >> 20) & 0xf, Rn, Rd, Rm, (OpCode >> 5) &0x7); return; } if ((OpCode & 0x0e000000) == 0x0c000000) { // A4.1.19 LDC and A4.1.96 SDC if ((OpCode & 0xf0000000) == 0xf0000000) { Index = AsciiSPrint (Buf, Size, "%a2 0x%x, CR%d, ", L ? "LDC":"SDC", (OpCode >> 8) & 0xf, Rd); } else { Index = AsciiSPrint (Buf, Size, "%a%a 0x%x, CR%d, ", L ? "LDC":"SDC", COND (OpCode), (OpCode >> 8) & 0xf, Rd); } if (!P) { if (!W) { // A5.5.5.5 [<Rn>], <option> AsciiSPrint (&Buf[Index], Size - Index, "[%a], {0x%x}", gReg[Rn], OpCode & 0xff); } else { // A.5.5.4 [<Rn>], #+/-<offset_8>*4 AsciiSPrint (&Buf[Index], Size - Index, "[%a], #%a0x%x*4", gReg[Rn], SIGN (U), OpCode & 0xff); } } else { // A5.5.5.2 [<Rn>, #+/-<offset_8>*4 ]! AsciiSPrint (&Buf[Index], Size - Index, "[%a, #%a0x%x*4]%a", gReg[Rn], SIGN (U), OpCode & 0xff, WRITE (W)); } } if ((OpCode & 0x0f000010) == 0x0e000010) { // A4.1.32 MRC2, MCR2 AsciiSPrint (Buf, Size, "%a%a 0x%x, 0x%x, %a, CR%d, CR%d, 0x%x", L ? "MRC":"MCR", COND (OpCode), (OpCode >> 8) & 0xf, (OpCode >> 20) & 0xf, gReg[Rd], Rn, Rm, (OpCode >> 5) &0x7); return; } if ((OpCode & 0x0ff00000) == 0x0c400000) { // A4.1.33 MRRC2, MCRR2 AsciiSPrint (Buf, Size, "%a%a 0x%x, 0x%x, %a, %a, CR%d", L ? "MRRC":"MCRR", COND (OpCode), (OpCode >> 4) & 0xf, (OpCode >> 20) & 0xf, gReg[Rd], gReg[Rn], Rm); return; } AsciiSPrint (Buf, Size, "Faulting OpCode 0x%08x", OpCode); *OpCodePtr += 1; return; }
NaohiroTamura/edk2
ArmPlatformPkg/PrePeiCore/Arm/ArchPrePeiCore.c
/** @file * Main file supporting the transition to PEI Core in Normal World for Versatile Express * * Copyright (c) 2012, ARM Limited. All rights reserved. * * SPDX-License-Identifier: BSD-2-Clause-Patent * **/ #include <Library/PrintLib.h> #include <Library/SerialPortLib.h> #include "PrePeiCore.h" VOID PeiCommonExceptionEntry ( IN UINT32 Entry, IN UINTN LR ) { CHAR8 Buffer[100]; UINTN CharCount; switch (Entry) { case 0: CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"Reset Exception at 0x%X\n\r",LR); break; case 1: CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"Undefined Exception at 0x%X\n\r",LR); break; case 2: CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"SWI Exception at 0x%X\n\r",LR); break; case 3: CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"PrefetchAbort Exception at 0x%X\n\r",LR); break; case 4: CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"DataAbort Exception at 0x%X\n\r",LR); break; case 5: CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"Reserved Exception at 0x%X\n\r",LR); break; case 6: CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"IRQ Exception at 0x%X\n\r",LR); break; case 7: CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"FIQ Exception at 0x%X\n\r",LR); break; default: CharCount = AsciiSPrint (Buffer,sizeof (Buffer),"Unknown Exception at 0x%X\n\r",LR); break; } SerialPortWrite ((UINT8 *) Buffer, CharCount); while(1); }
NaohiroTamura/edk2
MdeModulePkg/Application/BootManagerMenuApp/BootManagerMenu.c
/** @file The application to show the Boot Manager Menu. Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "BootManagerMenu.h" EFI_HII_HANDLE gStringPackHandle; BOOLEAN mModeInitialized = FALSE; // // Boot video resolution and text mode. // UINT32 mBootHorizontalResolution = 0; UINT32 mBootVerticalResolution = 0; UINT32 mBootTextModeColumn = 0; UINT32 mBootTextModeRow = 0; // // BIOS setup video resolution and text mode. // UINT32 mSetupTextModeColumn = 0; UINT32 mSetupTextModeRow = 0; UINT32 mSetupHorizontalResolution = 0; UINT32 mSetupVerticalResolution = 0; /** Prints a unicode string to the default console, at the supplied cursor position, using L"%s" format. @param Column The cursor position to print the string at. @param Row The cursor position to print the string at @param String String pointer. @return Length of string printed to the console **/ UINTN PrintStringAt ( IN UINTN Column, IN UINTN Row, IN CHAR16 *String ) { gST->ConOut->SetCursorPosition (gST->ConOut, Column, Row); return Print (L"%s", String); } /** Prints a character to the default console, at the supplied cursor position, using L"%c" format. @param Column The cursor position to print the string at. @param Row The cursor position to print the string at. @param Character Character to print. @return Length of string printed to the console. **/ UINTN PrintCharAt ( IN UINTN Column, IN UINTN Row, CHAR16 Character ) { gST->ConOut->SetCursorPosition (gST->ConOut, Column, Row); return Print (L"%c", Character); } /** Count the storage space of a Unicode string which uses current language to get from input string ID. @param StringId The input string to be counted. @return Storage space for the input string. **/ UINTN GetLineWidth ( IN EFI_STRING_ID StringId ) { UINTN Index; UINTN IncrementValue; EFI_STRING String; UINTN LineWidth; LineWidth = 0; String = HiiGetString (gStringPackHandle, StringId, NULL); if (String != NULL) { Index = 0; IncrementValue = 1; do { // // Advance to the null-terminator or to the first width directive // for (; (String[Index] != NARROW_CHAR) && (String[Index] != WIDE_CHAR) && (String[Index] != 0); Index++, LineWidth = LineWidth + IncrementValue ) ; // // We hit the null-terminator, we now have a count // if (String[Index] == 0) { break; } // // We encountered a narrow directive - strip it from the size calculation since it doesn't get printed // and also set the flag that determines what we increment by.(if narrow, increment by 1, if wide increment by 2) // if (String[Index] == NARROW_CHAR) { // // Skip to the next character // Index++; IncrementValue = 1; } else { // // Skip to the next character // Index++; IncrementValue = 2; } } while (String[Index] != 0); FreePool (String); } return LineWidth; } /** This function uses calculate the boot menu location, size and scroll bar information. @param BootMenuData The boot menu data to be processed. @return EFI_SUCCESS calculate boot menu information successful. @retval EFI_INVALID_PARAMETER Input parameter is invalid **/ EFI_STATUS InitializeBootMenuScreen ( IN OUT BOOT_MENU_POPUP_DATA *BootMenuData ) { UINTN MaxStrWidth; UINTN StrWidth; UINTN Index; UINTN Column; UINTN Row; UINTN MaxPrintRows; UINTN UnSelectableItmes; if (BootMenuData == NULL) { return EFI_INVALID_PARAMETER; } // // Get maximum string width // MaxStrWidth = 0; for (Index = 0; Index < TITLE_TOKEN_COUNT; Index++) { StrWidth = GetLineWidth (BootMenuData->TitleToken[Index]); MaxStrWidth = MaxStrWidth > StrWidth ? MaxStrWidth : StrWidth; } for (Index = 0; Index < BootMenuData->ItemCount; Index++) { StrWidth = GetLineWidth (BootMenuData->PtrTokens[Index]); MaxStrWidth = MaxStrWidth > StrWidth ? MaxStrWidth : StrWidth; } for (Index = 0; Index < HELP_TOKEN_COUNT; Index++) { StrWidth = GetLineWidth (BootMenuData->HelpToken[Index]); MaxStrWidth = MaxStrWidth > StrWidth ? MaxStrWidth : StrWidth; } // // query current row and column to calculate boot menu location // gST->ConOut->QueryMode ( gST->ConOut, gST->ConOut->Mode->Mode, &Column, &Row ); MaxPrintRows = Row - 6; UnSelectableItmes = TITLE_TOKEN_COUNT + 2 + HELP_TOKEN_COUNT + 2; BootMenuData->MenuScreen.Width = MaxStrWidth + 8; if (BootMenuData->ItemCount + UnSelectableItmes > MaxPrintRows) { BootMenuData->MenuScreen.Height = MaxPrintRows; BootMenuData->ScrollBarControl.HasScrollBar = TRUE; BootMenuData->ScrollBarControl.ItemCountPerScreen = MaxPrintRows - UnSelectableItmes; BootMenuData->ScrollBarControl.FirstItem = 0; BootMenuData->ScrollBarControl.LastItem = MaxPrintRows - UnSelectableItmes - 1; } else { BootMenuData->MenuScreen.Height = BootMenuData->ItemCount + UnSelectableItmes; BootMenuData->ScrollBarControl.HasScrollBar = FALSE; BootMenuData->ScrollBarControl.ItemCountPerScreen = BootMenuData->ItemCount; BootMenuData->ScrollBarControl.FirstItem = 0; BootMenuData->ScrollBarControl.LastItem = BootMenuData->ItemCount - 1; } BootMenuData->MenuScreen.StartCol = (Column - BootMenuData->MenuScreen.Width) / 2; BootMenuData->MenuScreen.StartRow = (Row - BootMenuData->MenuScreen.Height) / 2; return EFI_SUCCESS; } /** This function uses check boot option is wheher setup application or no @param BootOption Pointer to EFI_BOOT_MANAGER_LOAD_OPTION array. @retval TRUE This boot option is setup application. @retval FALSE This boot options isn't setup application **/ BOOLEAN IsBootManagerMenu ( IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption ) { EFI_STATUS Status; EFI_BOOT_MANAGER_LOAD_OPTION BootManagerMenu; Status = EfiBootManagerGetBootManagerMenu (&BootManagerMenu); if (!EFI_ERROR (Status)) { EfiBootManagerFreeLoadOption (&BootManagerMenu); } return (BOOLEAN) (!EFI_ERROR (Status) && (BootOption->OptionNumber == BootManagerMenu.OptionNumber)); } /** Return whether to ignore the boot option. @param BootOption Pointer to EFI_BOOT_MANAGER_LOAD_OPTION to check. @retval TRUE Ignore the boot option. @retval FALSE Do not ignore the boot option. **/ BOOLEAN IgnoreBootOption ( IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption ) { EFI_STATUS Status; EFI_DEVICE_PATH_PROTOCOL *ImageDevicePath; // // Ignore myself. // Status = gBS->HandleProtocol (gImageHandle, &gEfiLoadedImageDevicePathProtocolGuid, (VOID **) &ImageDevicePath); ASSERT_EFI_ERROR (Status); if (CompareMem (BootOption->FilePath, ImageDevicePath, GetDevicePathSize (ImageDevicePath)) == 0) { return TRUE; } // // Do not ignore Boot Manager Menu. // if (IsBootManagerMenu (BootOption)) { return FALSE; } // // Ignore the hidden/inactive boot option. // if (((BootOption->Attributes & LOAD_OPTION_HIDDEN) != 0) || ((BootOption->Attributes & LOAD_OPTION_ACTIVE) == 0)) { return TRUE; } return FALSE; } /** This function uses to initialize boot menu data @param BootOption Pointer to EFI_BOOT_MANAGER_LOAD_OPTION array. @param BootOptionCount Number of boot option. @param BootMenuData The Input BootMenuData to be initialized. @retval EFI_SUCCESS Initialize boot menu data successful. @retval EFI_INVALID_PARAMETER Input parameter is invalid. **/ EFI_STATUS InitializeBootMenuData ( IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption, IN UINTN BootOptionCount, OUT BOOT_MENU_POPUP_DATA *BootMenuData ) { UINTN Index; UINTN StrIndex; if (BootOption == NULL || BootMenuData == NULL) { return EFI_INVALID_PARAMETER; } BootMenuData->TitleToken[0] = STRING_TOKEN (STR_BOOT_POPUP_MENU_TITLE_STRING); BootMenuData->PtrTokens = AllocateZeroPool (BootOptionCount * sizeof (EFI_STRING_ID)); ASSERT (BootMenuData->PtrTokens != NULL); // // Skip boot option which created by BootNext Variable // for (StrIndex = 0, Index = 0; Index < BootOptionCount; Index++) { if (IgnoreBootOption (&BootOption[Index])) { continue; } ASSERT (BootOption[Index].Description != NULL); BootMenuData->PtrTokens[StrIndex++] = HiiSetString ( gStringPackHandle, 0, BootOption[Index].Description, NULL ); } BootMenuData->ItemCount = StrIndex; BootMenuData->HelpToken[0] = STRING_TOKEN (STR_BOOT_POPUP_MENU_HELP1_STRING); BootMenuData->HelpToken[1] = STRING_TOKEN (STR_BOOT_POPUP_MENU_HELP2_STRING); BootMenuData->HelpToken[2] = STRING_TOKEN (STR_BOOT_POPUP_MENU_HELP3_STRING); InitializeBootMenuScreen (BootMenuData); BootMenuData->SelectItem = 0; return EFI_SUCCESS; } /** This function uses input select item to highlight selected item and set current selected item in BootMenuData @param WantSelectItem The user wants to select item. @param BootMenuData The boot menu data to be processed @return EFI_SUCCESS Highlight selected item and update current selected item successful @retval EFI_INVALID_PARAMETER Input parameter is invalid **/ EFI_STATUS BootMenuSelectItem ( IN UINTN WantSelectItem, IN OUT BOOT_MENU_POPUP_DATA *BootMenuData ) { INT32 SavedAttribute; EFI_STRING String; UINTN StartCol; UINTN StartRow; UINTN PrintCol; UINTN PrintRow; UINTN TopShadeNum; UINTN LowShadeNum; UINTN FirstItem; UINTN LastItem; UINTN ItemCountPerScreen; UINTN Index; BOOLEAN RePaintItems; if (BootMenuData == NULL || WantSelectItem >= BootMenuData->ItemCount) { return EFI_INVALID_PARAMETER; } ASSERT (BootMenuData->ItemCount != 0); SavedAttribute = gST->ConOut->Mode->Attribute; RePaintItems = FALSE; StartCol = BootMenuData->MenuScreen.StartCol; StartRow = BootMenuData->MenuScreen.StartRow; // // print selectable items again and adjust scroll bar if need // if (BootMenuData->ScrollBarControl.HasScrollBar && (WantSelectItem < BootMenuData->ScrollBarControl.FirstItem || WantSelectItem > BootMenuData->ScrollBarControl.LastItem || WantSelectItem == BootMenuData->SelectItem)) { ItemCountPerScreen = BootMenuData->ScrollBarControl.ItemCountPerScreen; // // Set first item and last item // if (WantSelectItem < BootMenuData->ScrollBarControl.FirstItem) { BootMenuData->ScrollBarControl.FirstItem = WantSelectItem; BootMenuData->ScrollBarControl.LastItem = WantSelectItem + ItemCountPerScreen - 1; } else if (WantSelectItem > BootMenuData->ScrollBarControl.LastItem) { BootMenuData->ScrollBarControl.FirstItem = WantSelectItem - ItemCountPerScreen + 1; BootMenuData->ScrollBarControl.LastItem = WantSelectItem; } gST->ConOut->SetAttribute (gST->ConOut, EFI_WHITE | EFI_BACKGROUND_BLUE); FirstItem = BootMenuData->ScrollBarControl.FirstItem; LastItem = BootMenuData->ScrollBarControl.LastItem; TopShadeNum = 0; if (FirstItem != 0) { TopShadeNum = (FirstItem * ItemCountPerScreen) / BootMenuData->ItemCount; if ((FirstItem * ItemCountPerScreen) % BootMenuData->ItemCount != 0) { TopShadeNum++; } PrintCol = StartCol + BootMenuData->MenuScreen.Width - 2; PrintRow = StartRow + TITLE_TOKEN_COUNT + 2; for (Index = 0; Index < TopShadeNum; Index++, PrintRow++) { PrintCharAt (PrintCol, PrintRow, BLOCKELEMENT_LIGHT_SHADE); } } LowShadeNum = 0; if (LastItem != BootMenuData->ItemCount - 1) { LowShadeNum = ((BootMenuData->ItemCount - 1 - LastItem) * ItemCountPerScreen) / BootMenuData->ItemCount; if (((BootMenuData->ItemCount - 1 - LastItem) * ItemCountPerScreen) % BootMenuData->ItemCount != 0) { LowShadeNum++; } PrintCol = StartCol + BootMenuData->MenuScreen.Width - 2; PrintRow = StartRow + TITLE_TOKEN_COUNT + 2 + ItemCountPerScreen - LowShadeNum; for (Index = 0; Index < LowShadeNum; Index++, PrintRow++) { PrintCharAt (PrintCol, PrintRow, BLOCKELEMENT_LIGHT_SHADE); } } PrintCol = StartCol + BootMenuData->MenuScreen.Width - 2; PrintRow = StartRow + TITLE_TOKEN_COUNT + 2 + TopShadeNum; for (Index = TopShadeNum; Index < ItemCountPerScreen - LowShadeNum; Index++, PrintRow++) { PrintCharAt (PrintCol, PrintRow, BLOCKELEMENT_FULL_BLOCK); } // // Clear selectable items first // PrintCol = StartCol + 1; PrintRow = StartRow + TITLE_TOKEN_COUNT + 2; String = AllocateZeroPool ((BootMenuData->MenuScreen.Width - 2) * sizeof (CHAR16)); ASSERT (String != NULL); for (Index = 0; Index < BootMenuData->MenuScreen.Width - 3; Index++) { String[Index] = 0x20; } for (Index = 0; Index < ItemCountPerScreen; Index++) { PrintStringAt (PrintCol, PrintRow + Index, String); } FreePool (String); // // print selectable items // for (Index = 0; Index < ItemCountPerScreen; Index++, PrintRow++) { String = HiiGetString (gStringPackHandle, BootMenuData->PtrTokens[Index + FirstItem], NULL); PrintStringAt (PrintCol, PrintRow, String); FreePool (String); } RePaintItems = TRUE; } // // if Want Select and selected item isn't the same and doesn't re-draw selectable // items, clear select item // FirstItem = BootMenuData->ScrollBarControl.FirstItem; if (WantSelectItem != BootMenuData->SelectItem && !RePaintItems) { gST->ConOut->SetAttribute (gST->ConOut, EFI_WHITE | EFI_BACKGROUND_BLUE); String = HiiGetString (gStringPackHandle, BootMenuData->PtrTokens[BootMenuData->SelectItem], NULL); PrintCol = StartCol + 1; PrintRow = StartRow + 3 + BootMenuData->SelectItem - FirstItem; PrintStringAt (PrintCol, PrintRow, String); FreePool (String); } // // Print want to select item // gST->ConOut->SetAttribute (gST->ConOut, EFI_WHITE | EFI_BACKGROUND_BLACK); String = HiiGetString (gStringPackHandle, BootMenuData->PtrTokens[WantSelectItem], NULL); PrintCol = StartCol + 1; PrintRow = StartRow + TITLE_TOKEN_COUNT + 2 + WantSelectItem - FirstItem; PrintStringAt (PrintCol, PrintRow, String); FreePool (String); gST->ConOut->SetAttribute (gST->ConOut, SavedAttribute); BootMenuData->SelectItem = WantSelectItem; return EFI_SUCCESS; } /** This function uses to draw boot popup menu @param BootMenuData The Input BootMenuData to be processed. @retval EFI_SUCCESS Draw boot popup menu successful. **/ EFI_STATUS DrawBootPopupMenu ( IN BOOT_MENU_POPUP_DATA *BootMenuData ) { EFI_STRING String; UINTN Index; UINTN Width; UINTN StartCol; UINTN StartRow; UINTN PrintRow; UINTN PrintCol; UINTN LineWidth; INT32 SavedAttribute; UINTN ItemCountPerScreen; gST->ConOut->ClearScreen (gST->ConOut); SavedAttribute = gST->ConOut->Mode->Attribute; gST->ConOut->SetAttribute (gST->ConOut, EFI_WHITE | EFI_BACKGROUND_BLUE); Width = BootMenuData->MenuScreen.Width; StartCol = BootMenuData->MenuScreen.StartCol; StartRow = BootMenuData->MenuScreen.StartRow; ItemCountPerScreen = BootMenuData->ScrollBarControl.ItemCountPerScreen; PrintRow = StartRow; gST->ConOut->EnableCursor (gST->ConOut, FALSE); // // Draw Boot popup menu screen // PrintCharAt (StartCol, PrintRow, BOXDRAW_DOWN_RIGHT); for (Index = 1; Index < Width - 1; Index++) { PrintCharAt (StartCol + Index, PrintRow, BOXDRAW_HORIZONTAL); } PrintCharAt (StartCol + Width - 1, PrintRow, BOXDRAW_DOWN_LEFT); // // Draw the screen for title // String = AllocateZeroPool ((Width - 1) * sizeof (CHAR16)); ASSERT (String != NULL); for (Index = 0; Index < Width - 2; Index++) { String[Index] = 0x20; } for (Index = 0; Index < TITLE_TOKEN_COUNT; Index++) { PrintRow++; PrintCharAt (StartCol, PrintRow, BOXDRAW_VERTICAL); PrintStringAt (StartCol + 1, PrintRow, String); PrintCharAt (StartCol + Width - 1, PrintRow, BOXDRAW_VERTICAL); } PrintRow++; PrintCharAt (StartCol, PrintRow, BOXDRAW_VERTICAL_RIGHT); for (Index = 1; Index < Width - 1; Index++) { PrintCharAt (StartCol + Index, PrintRow, BOXDRAW_HORIZONTAL); } PrintCharAt (StartCol + Width - 1, PrintRow, BOXDRAW_VERTICAL_LEFT); // // Draw screen for selectable items // for (Index = 0; Index < ItemCountPerScreen; Index++) { PrintRow++; PrintCharAt (StartCol, PrintRow, BOXDRAW_VERTICAL); PrintStringAt (StartCol + 1, PrintRow, String); PrintCharAt (StartCol + Width - 1, PrintRow, BOXDRAW_VERTICAL); } PrintRow++; PrintCharAt (StartCol, PrintRow, BOXDRAW_VERTICAL_RIGHT); for (Index = 1; Index < Width - 1; Index++) { PrintCharAt (StartCol + Index, PrintRow, BOXDRAW_HORIZONTAL); } PrintCharAt (StartCol + Width - 1, PrintRow, BOXDRAW_VERTICAL_LEFT); // // Draw screen for Help // for (Index = 0; Index < HELP_TOKEN_COUNT; Index++) { PrintRow++; PrintCharAt (StartCol, PrintRow, BOXDRAW_VERTICAL); PrintStringAt (StartCol + 1, PrintRow, String); PrintCharAt (StartCol + Width - 1, PrintRow, BOXDRAW_VERTICAL); } FreePool (String); PrintRow++; PrintCharAt (StartCol, PrintRow, BOXDRAW_UP_RIGHT); for (Index = 1; Index < Width - 1; Index++) { PrintCharAt (StartCol + Index, PrintRow, BOXDRAW_HORIZONTAL); } PrintCharAt (StartCol + Width - 1, PrintRow, BOXDRAW_UP_LEFT); // // print title strings // PrintRow = StartRow + 1; for (Index = 0; Index < TITLE_TOKEN_COUNT; Index++, PrintRow++) { String = HiiGetString (gStringPackHandle, BootMenuData->TitleToken[Index], NULL); LineWidth = GetLineWidth (BootMenuData->TitleToken[Index]); PrintCol = StartCol + (Width - LineWidth) / 2; PrintStringAt (PrintCol, PrintRow, String); FreePool (String); } // // print selectable items // PrintCol = StartCol + 1; PrintRow = StartRow + TITLE_TOKEN_COUNT + 2; for (Index = 0; Index < ItemCountPerScreen; Index++, PrintRow++) { String = HiiGetString (gStringPackHandle, BootMenuData->PtrTokens[Index], NULL); PrintStringAt (PrintCol, PrintRow, String); FreePool (String); } // // Print Help strings // PrintRow++; for (Index = 0; Index < HELP_TOKEN_COUNT; Index++, PrintRow++) { String = HiiGetString (gStringPackHandle, BootMenuData->HelpToken[Index], NULL); LineWidth = GetLineWidth (BootMenuData->HelpToken[Index]); PrintCol = StartCol + (Width - LineWidth) / 2; PrintStringAt (PrintCol, PrintRow, String); FreePool (String); } // // Print scroll bar if has scroll bar // if (BootMenuData->ScrollBarControl.HasScrollBar) { PrintCol = StartCol + Width - 2; PrintRow = StartRow + 2; PrintCharAt (PrintCol, PrintRow, GEOMETRICSHAPE_UP_TRIANGLE); PrintCharAt (PrintCol + 1, PrintRow, BOXDRAW_VERTICAL); PrintRow += (ItemCountPerScreen + 1); PrintCharAt (PrintCol, PrintRow, GEOMETRICSHAPE_DOWN_TRIANGLE); PrintCharAt (PrintCol + 1, PrintRow, BOXDRAW_VERTICAL); } gST->ConOut->SetAttribute (gST->ConOut, SavedAttribute); // // Print Selected item // BootMenuSelectItem (BootMenuData->SelectItem, BootMenuData); return EFI_SUCCESS; } /** This function uses to boot from selected item @param BootOptions Pointer to EFI_BOOT_MANAGER_LOAD_OPTION array. @param BootOptionCount Number of boot option. @param SelectItem Current selected item. **/ VOID BootFromSelectOption ( IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions, IN UINTN BootOptionCount, IN UINTN SelectItem ) { UINTN ItemNum; UINTN Index; ASSERT (BootOptions != NULL); for (ItemNum = 0, Index = 0; Index < BootOptionCount; Index++) { if (IgnoreBootOption (&BootOptions[Index])) { continue; } if (ItemNum++ == SelectItem) { EfiBootManagerBoot (&BootOptions[Index]); break; } } } /** This function will change video resolution and text mode according to defined setup mode or defined boot mode @param IsSetupMode Indicate mode is changed to setup mode or boot mode. @retval EFI_SUCCESS Mode is changed successfully. @retval Others Mode failed to be changed. **/ EFI_STATUS EFIAPI BdsSetConsoleMode ( BOOLEAN IsSetupMode ) { EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOut; UINTN SizeOfInfo; EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info; UINT32 MaxGopMode; UINT32 MaxTextMode; UINT32 ModeNumber; UINT32 NewHorizontalResolution; UINT32 NewVerticalResolution; UINT32 NewColumns; UINT32 NewRows; UINTN HandleCount; EFI_HANDLE *HandleBuffer; EFI_STATUS Status; UINTN Index; UINTN CurrentColumn; UINTN CurrentRow; MaxGopMode = 0; MaxTextMode = 0; // // Get current video resolution and text mode // Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, (VOID**)&GraphicsOutput ); if (EFI_ERROR (Status)) { GraphicsOutput = NULL; } Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiSimpleTextOutProtocolGuid, (VOID**)&SimpleTextOut ); if (EFI_ERROR (Status)) { SimpleTextOut = NULL; } if ((GraphicsOutput == NULL) || (SimpleTextOut == NULL)) { return EFI_UNSUPPORTED; } if (IsSetupMode) { // // The required resolution and text mode is setup mode. // NewHorizontalResolution = mSetupHorizontalResolution; NewVerticalResolution = mSetupVerticalResolution; NewColumns = mSetupTextModeColumn; NewRows = mSetupTextModeRow; } else { // // The required resolution and text mode is boot mode. // NewHorizontalResolution = mBootHorizontalResolution; NewVerticalResolution = mBootVerticalResolution; NewColumns = mBootTextModeColumn; NewRows = mBootTextModeRow; } if (GraphicsOutput != NULL) { MaxGopMode = GraphicsOutput->Mode->MaxMode; } if (SimpleTextOut != NULL) { MaxTextMode = SimpleTextOut->Mode->MaxMode; } // // 1. If current video resolution is same with required video resolution, // video resolution need not be changed. // 1.1. If current text mode is same with required text mode, text mode need not be changed. // 1.2. If current text mode is different from required text mode, text mode need be changed. // 2. If current video resolution is different from required video resolution, we need restart whole console drivers. // for (ModeNumber = 0; ModeNumber < MaxGopMode; ModeNumber++) { Status = GraphicsOutput->QueryMode ( GraphicsOutput, ModeNumber, &SizeOfInfo, &Info ); if (!EFI_ERROR (Status)) { if ((Info->HorizontalResolution == NewHorizontalResolution) && (Info->VerticalResolution == NewVerticalResolution)) { if ((GraphicsOutput->Mode->Info->HorizontalResolution == NewHorizontalResolution) && (GraphicsOutput->Mode->Info->VerticalResolution == NewVerticalResolution)) { // // Current resolution is same with required resolution, check if text mode need be set // Status = SimpleTextOut->QueryMode (SimpleTextOut, SimpleTextOut->Mode->Mode, &CurrentColumn, &CurrentRow); ASSERT_EFI_ERROR (Status); if (CurrentColumn == NewColumns && CurrentRow == NewRows) { // // If current text mode is same with required text mode. Do nothing // FreePool (Info); return EFI_SUCCESS; } else { // // If current text mode is different from required text mode. Set new video mode // for (Index = 0; Index < MaxTextMode; Index++) { Status = SimpleTextOut->QueryMode (SimpleTextOut, Index, &CurrentColumn, &CurrentRow); if (!EFI_ERROR(Status)) { if ((CurrentColumn == NewColumns) && (CurrentRow == NewRows)) { // // Required text mode is supported, set it. // Status = SimpleTextOut->SetMode (SimpleTextOut, Index); ASSERT_EFI_ERROR (Status); // // Update text mode PCD. // Status = PcdSet32S (PcdConOutColumn, mSetupTextModeColumn); ASSERT_EFI_ERROR (Status); Status = PcdSet32S (PcdConOutRow, mSetupTextModeRow); ASSERT_EFI_ERROR (Status); FreePool (Info); return EFI_SUCCESS; } } } if (Index == MaxTextMode) { // // If required text mode is not supported, return error. // FreePool (Info); return EFI_UNSUPPORTED; } } } else { // // If current video resolution is not same with the new one, set new video resolution. // In this case, the driver which produces simple text out need be restarted. // Status = GraphicsOutput->SetMode (GraphicsOutput, ModeNumber); if (!EFI_ERROR (Status)) { FreePool (Info); break; } } } FreePool (Info); } } if (ModeNumber == MaxGopMode) { // // If the resolution is not supported, return error. // return EFI_UNSUPPORTED; } // // Set PCD to Inform GraphicsConsole to change video resolution. // Set PCD to Inform Consplitter to change text mode. // Status = PcdSet32S (PcdVideoHorizontalResolution, NewHorizontalResolution); ASSERT_EFI_ERROR (Status); Status = PcdSet32S (PcdVideoVerticalResolution, NewVerticalResolution); ASSERT_EFI_ERROR (Status); Status = PcdSet32S (PcdConOutColumn, NewColumns); ASSERT_EFI_ERROR (Status); Status = PcdSet32S (PcdConOutRow, NewRows); ASSERT_EFI_ERROR (Status); // // Video mode is changed, so restart graphics console driver and higher level driver. // Reconnect graphics console driver and higher level driver. // Locate all the handles with GOP protocol and reconnect it. // Status = gBS->LocateHandleBuffer ( ByProtocol, &gEfiSimpleTextOutProtocolGuid, NULL, &HandleCount, &HandleBuffer ); if (!EFI_ERROR (Status)) { for (Index = 0; Index < HandleCount; Index++) { gBS->DisconnectController (HandleBuffer[Index], NULL, NULL); } for (Index = 0; Index < HandleCount; Index++) { gBS->ConnectController (HandleBuffer[Index], NULL, NULL, TRUE); } if (HandleBuffer != NULL) { FreePool (HandleBuffer); } } return EFI_SUCCESS; } /** Display the boot popup menu and allow user select boot item. @param ImageHandle The image handle. @param SystemTable The system table. @retval EFI_SUCCESS Boot from selected boot option, and return success from boot option @retval EFI_NOT_FOUND User select to enter setup or can not find boot option **/ EFI_STATUS EFIAPI BootManagerMenuEntry ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_BOOT_MANAGER_LOAD_OPTION *BootOption; UINTN BootOptionCount; EFI_STATUS Status; BOOT_MENU_POPUP_DATA BootMenuData; UINTN Index; EFI_INPUT_KEY Key; BOOLEAN ExitApplication; UINTN SelectItem; EFI_BOOT_LOGO_PROTOCOL *BootLogo; EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOut; UINTN BootTextColumn; UINTN BootTextRow; // // Set Logo status invalid when boot manager menu is launched // BootLogo = NULL; Status = gBS->LocateProtocol (&gEfiBootLogoProtocolGuid, NULL, (VOID **) &BootLogo); if (!EFI_ERROR (Status) && (BootLogo != NULL)) { Status = BootLogo->SetBootLogo (BootLogo, NULL, 0, 0, 0, 0); ASSERT_EFI_ERROR (Status); } gBS->SetWatchdogTimer (0x0000, 0x0000, 0x0000, NULL); gStringPackHandle = HiiAddPackages ( &gEfiCallerIdGuid, gImageHandle, BootManagerMenuAppStrings, NULL ); ASSERT (gStringPackHandle != NULL); // // Connect all prior to entering the platform setup menu. // EfiBootManagerConnectAll (); EfiBootManagerRefreshAllBootOption (); BootOption = EfiBootManagerGetLoadOptions (&BootOptionCount, LoadOptionTypeBoot); if (!mModeInitialized) { // // After the console is ready, get current video resolution // and text mode before launching setup at first time. // Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, (VOID**)&GraphicsOutput ); if (EFI_ERROR (Status)) { GraphicsOutput = NULL; } Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiSimpleTextOutProtocolGuid, (VOID**)&SimpleTextOut ); if (EFI_ERROR (Status)) { SimpleTextOut = NULL; } if (GraphicsOutput != NULL) { // // Get current video resolution and text mode. // mBootHorizontalResolution = GraphicsOutput->Mode->Info->HorizontalResolution; mBootVerticalResolution = GraphicsOutput->Mode->Info->VerticalResolution; } if (SimpleTextOut != NULL) { Status = SimpleTextOut->QueryMode ( SimpleTextOut, SimpleTextOut->Mode->Mode, &BootTextColumn, &BootTextRow ); mBootTextModeColumn = (UINT32)BootTextColumn; mBootTextModeRow = (UINT32)BootTextRow; } // // Get user defined text mode for setup. // mSetupHorizontalResolution = PcdGet32 (PcdSetupVideoHorizontalResolution); mSetupVerticalResolution = PcdGet32 (PcdSetupVideoVerticalResolution); mSetupTextModeColumn = PcdGet32 (PcdSetupConOutColumn); mSetupTextModeRow = PcdGet32 (PcdSetupConOutRow); mModeInitialized = TRUE; } // // Set back to conventional setup resolution // BdsSetConsoleMode (TRUE); // // Initialize Boot menu data // Status = InitializeBootMenuData (BootOption, BootOptionCount, &BootMenuData); // // According to boot menu data to draw boot popup menu // DrawBootPopupMenu (&BootMenuData); // // check user input to determine want to re-draw or boot from user selected item // ExitApplication = FALSE; while (!ExitApplication) { gBS->WaitForEvent (1, &gST->ConIn->WaitForKey, &Index); Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key); if (!EFI_ERROR (Status)) { switch (Key.UnicodeChar) { case CHAR_NULL: switch (Key.ScanCode) { case SCAN_UP: SelectItem = BootMenuData.SelectItem == 0 ? BootMenuData.ItemCount - 1 : BootMenuData.SelectItem - 1; BootMenuSelectItem (SelectItem, &BootMenuData); break; case SCAN_DOWN: SelectItem = BootMenuData.SelectItem == BootMenuData.ItemCount - 1 ? 0 : BootMenuData.SelectItem + 1; BootMenuSelectItem (SelectItem, &BootMenuData); break; case SCAN_ESC: gST->ConOut->ClearScreen (gST->ConOut); ExitApplication = TRUE; // // Set boot resolution for normal boot // BdsSetConsoleMode (FALSE); break; default: break; } break; case CHAR_CARRIAGE_RETURN: gST->ConOut->ClearScreen (gST->ConOut); // // Set boot resolution for normal boot // BdsSetConsoleMode (FALSE); BootFromSelectOption (BootOption, BootOptionCount, BootMenuData.SelectItem); // // Back to boot manager menu again, set back to setup resolution // BdsSetConsoleMode (TRUE); DrawBootPopupMenu (&BootMenuData); break; default: break; } } } EfiBootManagerFreeLoadOptions (BootOption, BootOptionCount); FreePool (BootMenuData.PtrTokens); HiiRemovePackages (gStringPackHandle); return Status; }
NaohiroTamura/edk2
BaseTools/Source/C/GenFw/Elf32Convert.c
/** @file Elf32 Convert solution Copyright (c) 2010 - 2018, Intel Corporation. All rights reserved.<BR> Portions copyright (c) 2013, ARM Ltd. All rights reserved.<BR> Portions Copyright (c) 2020, Hewlett Packard Enterprise Development LP. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "WinNtInclude.h" #ifndef __GNUC__ #include <windows.h> #include <io.h> #endif #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <ctype.h> #include <Common/UefiBaseTypes.h> #include <IndustryStandard/PeImage.h> #include "PeCoffLib.h" #include "EfiUtilityMsgs.h" #include "GenFw.h" #include "ElfConvert.h" #include "Elf32Convert.h" STATIC VOID ScanSections32 ( VOID ); STATIC BOOLEAN WriteSections32 ( SECTION_FILTER_TYPES FilterType ); STATIC VOID WriteRelocations32 ( VOID ); STATIC VOID WriteDebug32 ( VOID ); STATIC VOID SetImageSize32 ( VOID ); STATIC VOID CleanUp32 ( VOID ); // // Rename ELF32 structures to common names to help when porting to ELF64. // typedef Elf32_Shdr Elf_Shdr; typedef Elf32_Ehdr Elf_Ehdr; typedef Elf32_Rel Elf_Rel; typedef Elf32_Sym Elf_Sym; typedef Elf32_Phdr Elf_Phdr; typedef Elf32_Dyn Elf_Dyn; #define ELFCLASS ELFCLASS32 #define ELF_R_TYPE(r) ELF32_R_TYPE(r) #define ELF_R_SYM(r) ELF32_R_SYM(r) // // Well known ELF structures. // STATIC Elf_Ehdr *mEhdr; STATIC Elf_Shdr *mShdrBase; STATIC Elf_Phdr *mPhdrBase; // // Coff information // STATIC UINT32 mCoffAlignment = 0x20; // // PE section alignment. // STATIC const UINT16 mCoffNbrSections = 4; // // ELF sections to offset in Coff file. // STATIC UINT32 *mCoffSectionsOffset = NULL; // // Offsets in COFF file // STATIC UINT32 mNtHdrOffset; STATIC UINT32 mTextOffset; STATIC UINT32 mDataOffset; STATIC UINT32 mHiiRsrcOffset; STATIC UINT32 mRelocOffset; STATIC UINT32 mDebugOffset; // // Initialization Function // BOOLEAN InitializeElf32 ( UINT8 *FileBuffer, ELF_FUNCTION_TABLE *ElfFunctions ) { // // Initialize data pointer and structures. // mEhdr = (Elf_Ehdr*) FileBuffer; // // Check the ELF32 specific header information. // if (mEhdr->e_ident[EI_CLASS] != ELFCLASS32) { Error (NULL, 0, 3000, "Unsupported", "ELF EI_DATA not ELFCLASS32"); return FALSE; } if (mEhdr->e_ident[EI_DATA] != ELFDATA2LSB) { Error (NULL, 0, 3000, "Unsupported", "ELF EI_DATA not ELFDATA2LSB"); return FALSE; } if ((mEhdr->e_type != ET_EXEC) && (mEhdr->e_type != ET_DYN)) { Error (NULL, 0, 3000, "Unsupported", "ELF e_type not ET_EXEC or ET_DYN"); return FALSE; } if (!((mEhdr->e_machine == EM_386) || (mEhdr->e_machine == EM_ARM) || (mEhdr->e_machine == EM_RISCV))) { Error (NULL, 0, 3000, "Unsupported", "ELF e_machine is not Elf32 machine."); return FALSE; } if (mEhdr->e_version != EV_CURRENT) { Error (NULL, 0, 3000, "Unsupported", "ELF e_version (%u) not EV_CURRENT (%d)", (unsigned) mEhdr->e_version, EV_CURRENT); return FALSE; } // // Update section header pointers // mShdrBase = (Elf_Shdr *)((UINT8 *)mEhdr + mEhdr->e_shoff); mPhdrBase = (Elf_Phdr *)((UINT8 *)mEhdr + mEhdr->e_phoff); // // Create COFF Section offset buffer and zero. // mCoffSectionsOffset = (UINT32 *)malloc(mEhdr->e_shnum * sizeof (UINT32)); if (mCoffSectionsOffset == NULL) { Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!"); return FALSE; } memset(mCoffSectionsOffset, 0, mEhdr->e_shnum * sizeof(UINT32)); // // Fill in function pointers. // ElfFunctions->ScanSections = ScanSections32; ElfFunctions->WriteSections = WriteSections32; ElfFunctions->WriteRelocations = WriteRelocations32; ElfFunctions->WriteDebug = WriteDebug32; ElfFunctions->SetImageSize = SetImageSize32; ElfFunctions->CleanUp = CleanUp32; return TRUE; } // // Header by Index functions // STATIC Elf_Shdr* GetShdrByIndex ( UINT32 Num ) { if (Num >= mEhdr->e_shnum) { Error (NULL, 0, 3000, "Invalid", "GetShdrByIndex: Index %u is too high.", Num); exit(EXIT_FAILURE); } return (Elf_Shdr*)((UINT8*)mShdrBase + Num * mEhdr->e_shentsize); } STATIC Elf_Phdr* GetPhdrByIndex ( UINT32 num ) { if (num >= mEhdr->e_phnum) { Error (NULL, 0, 3000, "Invalid", "GetPhdrByIndex: Index %u is too high.", num); exit(EXIT_FAILURE); } return (Elf_Phdr *)((UINT8*)mPhdrBase + num * mEhdr->e_phentsize); } STATIC UINT32 CoffAlign ( UINT32 Offset ) { return (Offset + mCoffAlignment - 1) & ~(mCoffAlignment - 1); } STATIC UINT32 DebugRvaAlign ( UINT32 Offset ) { return (Offset + 3) & ~3; } // // filter functions // STATIC BOOLEAN IsTextShdr ( Elf_Shdr *Shdr ) { return (BOOLEAN) ((Shdr->sh_flags & (SHF_WRITE | SHF_ALLOC)) == SHF_ALLOC); } STATIC BOOLEAN IsHiiRsrcShdr ( Elf_Shdr *Shdr ) { Elf_Shdr *Namedr = GetShdrByIndex(mEhdr->e_shstrndx); return (BOOLEAN) (strcmp((CHAR8*)mEhdr + Namedr->sh_offset + Shdr->sh_name, ELF_HII_SECTION_NAME) == 0); } STATIC BOOLEAN IsDataShdr ( Elf_Shdr *Shdr ) { if (IsHiiRsrcShdr(Shdr)) { return FALSE; } return (BOOLEAN) (Shdr->sh_flags & (SHF_WRITE | SHF_ALLOC)) == (SHF_ALLOC | SHF_WRITE); } STATIC BOOLEAN IsStrtabShdr ( Elf_Shdr *Shdr ) { Elf_Shdr *Namedr = GetShdrByIndex(mEhdr->e_shstrndx); return (BOOLEAN) (strcmp((CHAR8*)mEhdr + Namedr->sh_offset + Shdr->sh_name, ELF_STRTAB_SECTION_NAME) == 0); } STATIC Elf_Shdr * FindStrtabShdr ( VOID ) { UINT32 i; for (i = 0; i < mEhdr->e_shnum; i++) { Elf_Shdr *shdr = GetShdrByIndex(i); if (IsStrtabShdr(shdr)) { return shdr; } } return NULL; } STATIC const UINT8 * GetSymName ( Elf_Sym *Sym ) { Elf_Shdr *StrtabShdr; UINT8 *StrtabContents; BOOLEAN foundEnd; UINT32 i; if (Sym->st_name == 0) { return NULL; } StrtabShdr = FindStrtabShdr(); if (StrtabShdr == NULL) { return NULL; } assert(Sym->st_name < StrtabShdr->sh_size); StrtabContents = (UINT8*)mEhdr + StrtabShdr->sh_offset; foundEnd = FALSE; for (i = Sym->st_name; (i < StrtabShdr->sh_size) && !foundEnd; i++) { foundEnd = (BOOLEAN)(StrtabContents[i] == 0); } assert(foundEnd); return StrtabContents + Sym->st_name; } // // Elf functions interface implementation // STATIC VOID ScanSections32 ( VOID ) { UINT32 i; EFI_IMAGE_DOS_HEADER *DosHdr; EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr; UINT32 CoffEntry; UINT32 SectionCount; BOOLEAN FoundSection; CoffEntry = 0; mCoffOffset = 0; // // Coff file start with a DOS header. // mCoffOffset = sizeof(EFI_IMAGE_DOS_HEADER) + 0x40; mNtHdrOffset = mCoffOffset; switch (mEhdr->e_machine) { case EM_386: case EM_ARM: mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS32); break; default: VerboseMsg ("%s unknown e_machine type. Assume IA-32", (UINTN)mEhdr->e_machine); mCoffOffset += sizeof (EFI_IMAGE_NT_HEADERS32); break; } mTableOffset = mCoffOffset; mCoffOffset += mCoffNbrSections * sizeof(EFI_IMAGE_SECTION_HEADER); // // Set mCoffAlignment to the maximum alignment of the input sections // we care about // for (i = 0; i < mEhdr->e_shnum; i++) { Elf_Shdr *shdr = GetShdrByIndex(i); if (shdr->sh_addralign <= mCoffAlignment) { continue; } if (IsTextShdr(shdr) || IsDataShdr(shdr) || IsHiiRsrcShdr(shdr)) { mCoffAlignment = (UINT32)shdr->sh_addralign; } } // // Check if mCoffAlignment is larger than MAX_COFF_ALIGNMENT // if (mCoffAlignment > MAX_COFF_ALIGNMENT) { Error (NULL, 0, 3000, "Invalid", "Section alignment is larger than MAX_COFF_ALIGNMENT."); assert (FALSE); } // // Move the PE/COFF header right before the first section. This will help us // save space when converting to TE. // if (mCoffAlignment > mCoffOffset) { mNtHdrOffset += mCoffAlignment - mCoffOffset; mTableOffset += mCoffAlignment - mCoffOffset; mCoffOffset = mCoffAlignment; } // // First text sections. // mCoffOffset = CoffAlign(mCoffOffset); mTextOffset = mCoffOffset; FoundSection = FALSE; SectionCount = 0; for (i = 0; i < mEhdr->e_shnum; i++) { Elf_Shdr *shdr = GetShdrByIndex(i); if (IsTextShdr(shdr)) { if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) { // the alignment field is valid if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) { // if the section address is aligned we must align PE/COFF mCoffOffset = (mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1); } else { Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment."); } } /* Relocate entry. */ if ((mEhdr->e_entry >= shdr->sh_addr) && (mEhdr->e_entry < shdr->sh_addr + shdr->sh_size)) { CoffEntry = mCoffOffset + mEhdr->e_entry - shdr->sh_addr; } // // Set mTextOffset with the offset of the first '.text' section // if (!FoundSection) { mTextOffset = mCoffOffset; FoundSection = TRUE; } mCoffSectionsOffset[i] = mCoffOffset; mCoffOffset += shdr->sh_size; SectionCount ++; } } if (!FoundSection) { Error (NULL, 0, 3000, "Invalid", "Did not find any '.text' section."); assert (FALSE); } mDebugOffset = DebugRvaAlign(mCoffOffset); mCoffOffset = CoffAlign(mCoffOffset); if (SectionCount > 1 && mOutImageType == FW_EFI_IMAGE) { Warning (NULL, 0, 0, NULL, "Multiple sections in %s are merged into 1 text section. Source level debug might not work correctly.", mInImageName); } // // Then data sections. // mDataOffset = mCoffOffset; FoundSection = FALSE; SectionCount = 0; for (i = 0; i < mEhdr->e_shnum; i++) { Elf_Shdr *shdr = GetShdrByIndex(i); if (IsDataShdr(shdr)) { if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) { // the alignment field is valid if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) { // if the section address is aligned we must align PE/COFF mCoffOffset = (mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1); } else { Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment."); } } // // Set mDataOffset with the offset of the first '.data' section // if (!FoundSection) { mDataOffset = mCoffOffset; FoundSection = TRUE; } mCoffSectionsOffset[i] = mCoffOffset; mCoffOffset += shdr->sh_size; SectionCount ++; } } if (SectionCount > 1 && mOutImageType == FW_EFI_IMAGE) { Warning (NULL, 0, 0, NULL, "Multiple sections in %s are merged into 1 data section. Source level debug might not work correctly.", mInImageName); } // // Make room for .debug data in .data (or .text if .data is empty) instead of // putting it in a section of its own. This is explicitly allowed by the // PE/COFF spec, and prevents bloat in the binary when using large values for // section alignment. // if (SectionCount > 0) { mDebugOffset = DebugRvaAlign(mCoffOffset); } mCoffOffset = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY) + sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) + strlen(mInImageName) + 1; mCoffOffset = CoffAlign(mCoffOffset); if (SectionCount == 0) { mDataOffset = mCoffOffset; } // // The HII resource sections. // mHiiRsrcOffset = mCoffOffset; for (i = 0; i < mEhdr->e_shnum; i++) { Elf_Shdr *shdr = GetShdrByIndex(i); if (IsHiiRsrcShdr(shdr)) { if ((shdr->sh_addralign != 0) && (shdr->sh_addralign != 1)) { // the alignment field is valid if ((shdr->sh_addr & (shdr->sh_addralign - 1)) == 0) { // if the section address is aligned we must align PE/COFF mCoffOffset = (mCoffOffset + shdr->sh_addralign - 1) & ~(shdr->sh_addralign - 1); } else { Error (NULL, 0, 3000, "Invalid", "Section address not aligned to its own alignment."); } } if (shdr->sh_size != 0) { mHiiRsrcOffset = mCoffOffset; mCoffSectionsOffset[i] = mCoffOffset; mCoffOffset += shdr->sh_size; mCoffOffset = CoffAlign(mCoffOffset); SetHiiResourceHeader ((UINT8*) mEhdr + shdr->sh_offset, mHiiRsrcOffset); } break; } } mRelocOffset = mCoffOffset; // // Allocate base Coff file. Will be expanded later for relocations. // mCoffFile = (UINT8 *)malloc(mCoffOffset); if (mCoffFile == NULL) { Error (NULL, 0, 4001, "Resource", "memory cannot be allocated!"); } assert (mCoffFile != NULL); memset(mCoffFile, 0, mCoffOffset); // // Fill headers. // DosHdr = (EFI_IMAGE_DOS_HEADER *)mCoffFile; DosHdr->e_magic = EFI_IMAGE_DOS_SIGNATURE; DosHdr->e_lfanew = mNtHdrOffset; NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION*)(mCoffFile + mNtHdrOffset); NtHdr->Pe32.Signature = EFI_IMAGE_NT_SIGNATURE; switch (mEhdr->e_machine) { case EM_386: NtHdr->Pe32.FileHeader.Machine = EFI_IMAGE_MACHINE_IA32; NtHdr->Pe32.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC; break; case EM_ARM: NtHdr->Pe32.FileHeader.Machine = EFI_IMAGE_MACHINE_ARMT; NtHdr->Pe32.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC; break; default: VerboseMsg ("%s unknown e_machine type %hu. Assume IA-32", mInImageName, mEhdr->e_machine); NtHdr->Pe32.FileHeader.Machine = EFI_IMAGE_MACHINE_IA32; NtHdr->Pe32.OptionalHeader.Magic = EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC; } NtHdr->Pe32.FileHeader.NumberOfSections = mCoffNbrSections; NtHdr->Pe32.FileHeader.TimeDateStamp = (UINT32) time(NULL); mImageTimeStamp = NtHdr->Pe32.FileHeader.TimeDateStamp; NtHdr->Pe32.FileHeader.PointerToSymbolTable = 0; NtHdr->Pe32.FileHeader.NumberOfSymbols = 0; NtHdr->Pe32.FileHeader.SizeOfOptionalHeader = sizeof(NtHdr->Pe32.OptionalHeader); NtHdr->Pe32.FileHeader.Characteristics = EFI_IMAGE_FILE_EXECUTABLE_IMAGE | EFI_IMAGE_FILE_LINE_NUMS_STRIPPED | EFI_IMAGE_FILE_LOCAL_SYMS_STRIPPED | EFI_IMAGE_FILE_32BIT_MACHINE; NtHdr->Pe32.OptionalHeader.SizeOfCode = mDataOffset - mTextOffset; NtHdr->Pe32.OptionalHeader.SizeOfInitializedData = mRelocOffset - mDataOffset; NtHdr->Pe32.OptionalHeader.SizeOfUninitializedData = 0; NtHdr->Pe32.OptionalHeader.AddressOfEntryPoint = CoffEntry; NtHdr->Pe32.OptionalHeader.BaseOfCode = mTextOffset; NtHdr->Pe32.OptionalHeader.BaseOfData = mDataOffset; NtHdr->Pe32.OptionalHeader.ImageBase = 0; NtHdr->Pe32.OptionalHeader.SectionAlignment = mCoffAlignment; NtHdr->Pe32.OptionalHeader.FileAlignment = mCoffAlignment; NtHdr->Pe32.OptionalHeader.SizeOfImage = 0; NtHdr->Pe32.OptionalHeader.SizeOfHeaders = mTextOffset; NtHdr->Pe32.OptionalHeader.NumberOfRvaAndSizes = EFI_IMAGE_NUMBER_OF_DIRECTORY_ENTRIES; // // Section headers. // if ((mDataOffset - mTextOffset) > 0) { CreateSectionHeader (".text", mTextOffset, mDataOffset - mTextOffset, EFI_IMAGE_SCN_CNT_CODE | EFI_IMAGE_SCN_MEM_EXECUTE | EFI_IMAGE_SCN_MEM_READ); } else { // Don't make a section of size 0. NtHdr->Pe32.FileHeader.NumberOfSections--; } if ((mHiiRsrcOffset - mDataOffset) > 0) { CreateSectionHeader (".data", mDataOffset, mHiiRsrcOffset - mDataOffset, EFI_IMAGE_SCN_CNT_INITIALIZED_DATA | EFI_IMAGE_SCN_MEM_WRITE | EFI_IMAGE_SCN_MEM_READ); } else { // Don't make a section of size 0. NtHdr->Pe32.FileHeader.NumberOfSections--; } if ((mRelocOffset - mHiiRsrcOffset) > 0) { CreateSectionHeader (".rsrc", mHiiRsrcOffset, mRelocOffset - mHiiRsrcOffset, EFI_IMAGE_SCN_CNT_INITIALIZED_DATA | EFI_IMAGE_SCN_MEM_READ); NtHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = mRelocOffset - mHiiRsrcOffset; NtHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = mHiiRsrcOffset; } else { // Don't make a section of size 0. NtHdr->Pe32.FileHeader.NumberOfSections--; } } STATIC BOOLEAN WriteSections32 ( SECTION_FILTER_TYPES FilterType ) { UINT32 Idx; Elf_Shdr *SecShdr; UINT32 SecOffset; BOOLEAN (*Filter)(Elf_Shdr *); // // Initialize filter pointer // switch (FilterType) { case SECTION_TEXT: Filter = IsTextShdr; break; case SECTION_HII: Filter = IsHiiRsrcShdr; break; case SECTION_DATA: Filter = IsDataShdr; break; default: return FALSE; } // // First: copy sections. // for (Idx = 0; Idx < mEhdr->e_shnum; Idx++) { Elf_Shdr *Shdr = GetShdrByIndex(Idx); if ((*Filter)(Shdr)) { switch (Shdr->sh_type) { case SHT_PROGBITS: /* Copy. */ if (Shdr->sh_offset + Shdr->sh_size > mFileBufferSize) { return FALSE; } memcpy(mCoffFile + mCoffSectionsOffset[Idx], (UINT8*)mEhdr + Shdr->sh_offset, Shdr->sh_size); break; case SHT_NOBITS: memset(mCoffFile + mCoffSectionsOffset[Idx], 0, Shdr->sh_size); break; default: // // Ignore for unknown section type. // VerboseMsg ("%s unknown section type %x. We ignore this unknown section type.", mInImageName, (unsigned)Shdr->sh_type); break; } } } // // Second: apply relocations. // for (Idx = 0; Idx < mEhdr->e_shnum; Idx++) { // // Determine if this is a relocation section. // Elf_Shdr *RelShdr = GetShdrByIndex(Idx); if ((RelShdr->sh_type != SHT_REL) && (RelShdr->sh_type != SHT_RELA)) { continue; } // // Relocation section found. Now extract section information that the relocations // apply to in the ELF data and the new COFF data. // SecShdr = GetShdrByIndex(RelShdr->sh_info); SecOffset = mCoffSectionsOffset[RelShdr->sh_info]; // // Only process relocations for the current filter type. // if (RelShdr->sh_type == SHT_REL && (*Filter)(SecShdr)) { UINT32 RelOffset; // // Determine the symbol table referenced by the relocation data. // Elf_Shdr *SymtabShdr = GetShdrByIndex(RelShdr->sh_link); UINT8 *Symtab = (UINT8*)mEhdr + SymtabShdr->sh_offset; // // Process all relocation entries for this section. // for (RelOffset = 0; RelOffset < RelShdr->sh_size; RelOffset += RelShdr->sh_entsize) { // // Set pointer to relocation entry // Elf_Rel *Rel = (Elf_Rel *)((UINT8*)mEhdr + RelShdr->sh_offset + RelOffset); // // Set pointer to symbol table entry associated with the relocation entry. // Elf_Sym *Sym = (Elf_Sym *)(Symtab + ELF_R_SYM(Rel->r_info) * SymtabShdr->sh_entsize); Elf_Shdr *SymShdr; UINT8 *Targ; UINT16 Address; // // Check section header index found in symbol table and get the section // header location. // if (Sym->st_shndx == SHN_UNDEF || Sym->st_shndx >= mEhdr->e_shnum) { const UINT8 *SymName = GetSymName(Sym); if (SymName == NULL) { SymName = (const UINT8 *)"<unknown>"; } Error (NULL, 0, 3000, "Invalid", "%s: Bad definition for symbol '%s'@%#x or unsupported symbol type. " "For example, absolute and undefined symbols are not supported.", mInImageName, SymName, Sym->st_value); exit(EXIT_FAILURE); } SymShdr = GetShdrByIndex(Sym->st_shndx); // // Convert the relocation data to a pointer into the coff file. // // Note: // r_offset is the virtual address of the storage unit to be relocated. // sh_addr is the virtual address for the base of the section. // Targ = mCoffFile + SecOffset + (Rel->r_offset - SecShdr->sh_addr); // // Determine how to handle each relocation type based on the machine type. // if (mEhdr->e_machine == EM_386) { switch (ELF_R_TYPE(Rel->r_info)) { case R_386_NONE: break; case R_386_32: // // Absolute relocation. // Converts Targ from a absolute virtual address to the absolute // COFF address. // *(UINT32 *)Targ = *(UINT32 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]; break; case R_386_PC32: // // Relative relocation: Symbol - Ip + Addend // *(UINT32 *)Targ = *(UINT32 *)Targ + (mCoffSectionsOffset[Sym->st_shndx] - SymShdr->sh_addr) - (SecOffset - SecShdr->sh_addr); break; default: Error (NULL, 0, 3000, "Invalid", "%s unsupported ELF EM_386 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info)); } } else if (mEhdr->e_machine == EM_ARM) { switch (ELF32_R_TYPE(Rel->r_info)) { case R_ARM_RBASE: // No relocation - no action required // break skipped case R_ARM_PC24: case R_ARM_REL32: case R_ARM_XPC25: case R_ARM_THM_PC22: case R_ARM_THM_JUMP19: case R_ARM_CALL: case R_ARM_JMP24: case R_ARM_THM_JUMP24: case R_ARM_PREL31: case R_ARM_MOVW_PREL_NC: case R_ARM_MOVT_PREL: case R_ARM_THM_MOVW_PREL_NC: case R_ARM_THM_MOVT_PREL: case R_ARM_THM_JMP6: case R_ARM_THM_ALU_PREL_11_0: case R_ARM_THM_PC12: case R_ARM_REL32_NOI: case R_ARM_ALU_PC_G0_NC: case R_ARM_ALU_PC_G0: case R_ARM_ALU_PC_G1_NC: case R_ARM_ALU_PC_G1: case R_ARM_ALU_PC_G2: case R_ARM_LDR_PC_G1: case R_ARM_LDR_PC_G2: case R_ARM_LDRS_PC_G0: case R_ARM_LDRS_PC_G1: case R_ARM_LDRS_PC_G2: case R_ARM_LDC_PC_G0: case R_ARM_LDC_PC_G1: case R_ARM_LDC_PC_G2: case R_ARM_THM_JUMP11: case R_ARM_THM_JUMP8: case R_ARM_TLS_GD32: case R_ARM_TLS_LDM32: case R_ARM_TLS_IE32: // Thease are all PC-relative relocations and don't require modification // GCC does not seem to have the concept of a application that just needs to get relocated. break; case R_ARM_THM_MOVW_ABS_NC: // MOVW is only lower 16-bits of the addres Address = (UINT16)(Sym->st_value - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]); ThumbMovtImmediatePatch ((UINT16 *)Targ, Address); break; case R_ARM_THM_MOVT_ABS: // MOVT is only upper 16-bits of the addres Address = (UINT16)((Sym->st_value - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]) >> 16); ThumbMovtImmediatePatch ((UINT16 *)Targ, Address); break; case R_ARM_ABS32: case R_ARM_RABS32: // // Absolute relocation. // *(UINT32 *)Targ = *(UINT32 *)Targ - SymShdr->sh_addr + mCoffSectionsOffset[Sym->st_shndx]; break; default: Error (NULL, 0, 3000, "Invalid", "WriteSections (): %s unsupported ELF EM_ARM relocation 0x%x.", mInImageName, (unsigned) ELF32_R_TYPE(Rel->r_info)); } } } } } return TRUE; } UINTN gMovwOffset = 0; STATIC VOID WriteRelocations32 ( VOID ) { UINT32 Index; EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr; EFI_IMAGE_DATA_DIRECTORY *Dir; BOOLEAN FoundRelocations; Elf_Dyn *Dyn; Elf_Rel *Rel; UINTN RelElementSize; UINTN RelSize; UINTN RelOffset; UINTN K; Elf32_Phdr *DynamicSegment; for (Index = 0, FoundRelocations = FALSE; Index < mEhdr->e_shnum; Index++) { Elf_Shdr *RelShdr = GetShdrByIndex(Index); if ((RelShdr->sh_type == SHT_REL) || (RelShdr->sh_type == SHT_RELA)) { Elf_Shdr *SecShdr = GetShdrByIndex (RelShdr->sh_info); if (IsTextShdr(SecShdr) || IsDataShdr(SecShdr)) { UINT32 RelIdx; FoundRelocations = TRUE; for (RelIdx = 0; RelIdx < RelShdr->sh_size; RelIdx += RelShdr->sh_entsize) { Rel = (Elf_Rel *)((UINT8*)mEhdr + RelShdr->sh_offset + RelIdx); if (mEhdr->e_machine == EM_386) { switch (ELF_R_TYPE(Rel->r_info)) { case R_386_NONE: case R_386_PC32: // // No fixup entry required. // break; case R_386_32: // // Creates a relative relocation entry from the absolute entry. // CoffAddFixup(mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr), EFI_IMAGE_REL_BASED_HIGHLOW); break; default: Error (NULL, 0, 3000, "Invalid", "%s unsupported ELF EM_386 relocation 0x%x.", mInImageName, (unsigned) ELF_R_TYPE(Rel->r_info)); } } else if (mEhdr->e_machine == EM_ARM) { switch (ELF32_R_TYPE(Rel->r_info)) { case R_ARM_RBASE: // No relocation - no action required // break skipped case R_ARM_PC24: case R_ARM_REL32: case R_ARM_XPC25: case R_ARM_THM_PC22: case R_ARM_THM_JUMP19: case R_ARM_CALL: case R_ARM_JMP24: case R_ARM_THM_JUMP24: case R_ARM_PREL31: case R_ARM_MOVW_PREL_NC: case R_ARM_MOVT_PREL: case R_ARM_THM_MOVW_PREL_NC: case R_ARM_THM_MOVT_PREL: case R_ARM_THM_JMP6: case R_ARM_THM_ALU_PREL_11_0: case R_ARM_THM_PC12: case R_ARM_REL32_NOI: case R_ARM_ALU_PC_G0_NC: case R_ARM_ALU_PC_G0: case R_ARM_ALU_PC_G1_NC: case R_ARM_ALU_PC_G1: case R_ARM_ALU_PC_G2: case R_ARM_LDR_PC_G1: case R_ARM_LDR_PC_G2: case R_ARM_LDRS_PC_G0: case R_ARM_LDRS_PC_G1: case R_ARM_LDRS_PC_G2: case R_ARM_LDC_PC_G0: case R_ARM_LDC_PC_G1: case R_ARM_LDC_PC_G2: case R_ARM_THM_JUMP11: case R_ARM_THM_JUMP8: case R_ARM_TLS_GD32: case R_ARM_TLS_LDM32: case R_ARM_TLS_IE32: // Thease are all PC-relative relocations and don't require modification break; case R_ARM_THM_MOVW_ABS_NC: CoffAddFixup ( mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr), EFI_IMAGE_REL_BASED_ARM_MOV32T ); // PE/COFF treats MOVW/MOVT relocation as single 64-bit instruction // Track this address so we can log an error for unsupported sequence of MOVW/MOVT gMovwOffset = mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr); break; case R_ARM_THM_MOVT_ABS: if ((gMovwOffset + 4) != (mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr))) { Error (NULL, 0, 3000, "Not Supported", "PE/COFF requires MOVW+MOVT instruction sequence %x +4 != %x.", gMovwOffset, mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr)); } break; case R_ARM_ABS32: case R_ARM_RABS32: CoffAddFixup ( mCoffSectionsOffset[RelShdr->sh_info] + (Rel->r_offset - SecShdr->sh_addr), EFI_IMAGE_REL_BASED_HIGHLOW ); break; default: Error (NULL, 0, 3000, "Invalid", "WriteRelocations(): %s unsupported ELF EM_ARM relocation 0x%x.", mInImageName, (unsigned) ELF32_R_TYPE(Rel->r_info)); } } else { Error (NULL, 0, 3000, "Not Supported", "This tool does not support relocations for ELF with e_machine %u (processor type).", (unsigned) mEhdr->e_machine); } } } } } if (!FoundRelocations && (mEhdr->e_machine == EM_ARM)) { /* Try again, but look for PT_DYNAMIC instead of SHT_REL */ for (Index = 0; Index < mEhdr->e_phnum; Index++) { RelElementSize = 0; RelSize = 0; RelOffset = 0; DynamicSegment = GetPhdrByIndex (Index); if (DynamicSegment->p_type == PT_DYNAMIC) { Dyn = (Elf32_Dyn *) ((UINT8 *)mEhdr + DynamicSegment->p_offset); while (Dyn->d_tag != DT_NULL) { switch (Dyn->d_tag) { case DT_REL: RelOffset = Dyn->d_un.d_val; break; case DT_RELSZ: RelSize = Dyn->d_un.d_val; break; case DT_RELENT: RelElementSize = Dyn->d_un.d_val; break; default: break; } Dyn++; } if (( RelOffset == 0 ) || ( RelSize == 0 ) || ( RelElementSize == 0 )) { Error (NULL, 0, 3000, "Invalid", "%s bad ARM dynamic relocations.", mInImageName); } for (Index = 0; Index < mEhdr->e_shnum; Index++) { Elf_Shdr *shdr = GetShdrByIndex(Index); // // The PT_DYNAMIC section contains DT_REL relocations whose r_offset // field is relative to the base of a segment (or the entire image), // and not to the base of an ELF input section as is the case for // SHT_REL sections. This means that we cannot fix up such relocations // unless we cross-reference ELF sections and segments, considering // that the output placement recorded in mCoffSectionsOffset[] is // section based, not segment based. // // Fortunately, there is a simple way around this: we require that the // in-memory layout of the ELF and PE/COFF versions of the binary is // identical. That way, r_offset will retain its validity as a PE/COFF // image offset, and we can record it in the COFF fixup table // unmodified. // if (shdr->sh_addr != mCoffSectionsOffset[Index]) { Error (NULL, 0, 3000, "Invalid", "%s: PT_DYNAMIC relocations require identical ELF and PE/COFF section offsets.", mInImageName); } } for (K = 0; K < RelSize; K += RelElementSize) { if (DynamicSegment->p_paddr == 0) { // Older versions of the ARM ELF (SWS ESPC 0003 B-02) specification define DT_REL // as an offset in the dynamic segment. p_paddr is defined to be zero for ARM tools Rel = (Elf32_Rel *) ((UINT8 *) mEhdr + DynamicSegment->p_offset + RelOffset + K); } else { // This is how it reads in the generic ELF specification Rel = (Elf32_Rel *) ((UINT8 *) mEhdr + RelOffset + K); } switch (ELF32_R_TYPE (Rel->r_info)) { case R_ARM_RBASE: break; case R_ARM_RABS32: CoffAddFixup (Rel->r_offset, EFI_IMAGE_REL_BASED_HIGHLOW); break; default: Error (NULL, 0, 3000, "Invalid", "%s bad ARM dynamic relocations, unknown type %d.", mInImageName, ELF32_R_TYPE (Rel->r_info)); break; } } break; } } } // // Pad by adding empty entries. // while (mCoffOffset & (mCoffAlignment - 1)) { CoffAddFixupEntry(0); } NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset); Dir = &NtHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_BASERELOC]; Dir->Size = mCoffOffset - mRelocOffset; if (Dir->Size == 0) { // If no relocations, null out the directory entry and don't add the .reloc section Dir->VirtualAddress = 0; NtHdr->Pe32.FileHeader.NumberOfSections--; } else { Dir->VirtualAddress = mRelocOffset; CreateSectionHeader (".reloc", mRelocOffset, mCoffOffset - mRelocOffset, EFI_IMAGE_SCN_CNT_INITIALIZED_DATA | EFI_IMAGE_SCN_MEM_DISCARDABLE | EFI_IMAGE_SCN_MEM_READ); } } STATIC VOID WriteDebug32 ( VOID ) { UINT32 Len; EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr; EFI_IMAGE_DATA_DIRECTORY *DataDir; EFI_IMAGE_DEBUG_DIRECTORY_ENTRY *Dir; EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY *Nb10; Len = strlen(mInImageName) + 1; Dir = (EFI_IMAGE_DEBUG_DIRECTORY_ENTRY*)(mCoffFile + mDebugOffset); Dir->Type = EFI_IMAGE_DEBUG_TYPE_CODEVIEW; Dir->SizeOfData = sizeof(EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY) + Len; Dir->RVA = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY); Dir->FileOffset = mDebugOffset + sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY); Nb10 = (EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY*)(Dir + 1); Nb10->Signature = CODEVIEW_SIGNATURE_NB10; strcpy ((char *)(Nb10 + 1), mInImageName); NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset); DataDir = &NtHdr->Pe32.OptionalHeader.DataDirectory[EFI_IMAGE_DIRECTORY_ENTRY_DEBUG]; DataDir->VirtualAddress = mDebugOffset; DataDir->Size = sizeof(EFI_IMAGE_DEBUG_DIRECTORY_ENTRY); } STATIC VOID SetImageSize32 ( VOID ) { EFI_IMAGE_OPTIONAL_HEADER_UNION *NtHdr; // // Set image size // NtHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)(mCoffFile + mNtHdrOffset); NtHdr->Pe32.OptionalHeader.SizeOfImage = mCoffOffset; } STATIC VOID CleanUp32 ( VOID ) { if (mCoffSectionsOffset != NULL) { free (mCoffSectionsOffset); } }
NaohiroTamura/edk2
ArmPlatformPkg/Include/Library/PL011UartClockLib.h
<filename>ArmPlatformPkg/Include/Library/PL011UartClockLib.h /** @file * * Copyright 2018 NXP * * SPDX-License-Identifier: BSD-2-Clause-Patent * **/ #ifndef __PL011UARTCLOCKLIB_H__ #define __PL011UARTCLOCKLIB_H__ /** Return baud clock frequency of PL011. @return return frequency of PL011 in Hz **/ UINT32 EFIAPI PL011UartClockGetFreq ( VOID ); #endif
NaohiroTamura/edk2
ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Pcct/PcctParser.c
<gh_stars>10-100 /** @file PCCT table parser Copyright (c) 2020, Arm Limited. SPDX-License-Identifier: BSD-2-Clause-Patent @par Reference(s): - ACPI 6.3 Specification - January 2019 **/ #include <Library/BaseMemoryLib.h> #include <Library/PrintLib.h> #include <Library/UefiLib.h> #include "AcpiParser.h" #include "AcpiView.h" #include "AcpiViewConfig.h" #include "PcctParser.h" // Local variables STATIC ACPI_DESCRIPTION_HEADER_INFO AcpiHdrInfo; STATIC UINT32* PccGlobalFlags; STATIC UINT8* PccSubspaceLength; STATIC UINT8* PccSubspaceType; STATIC UINT8* ExtendedPccSubspaceInterruptFlags; /** This function validates the length coded on 4 bytes of a shared memory range @param [in] Ptr Pointer to the start of the field data. @param [in] Context Pointer to context specific information e.g. this could be a pointer to the ACPI table header. **/ STATIC VOID EFIAPI ValidateRangeLength4 ( IN UINT8* Ptr, IN VOID* Context ) { if (*(UINT32*)Ptr < MIN_EXT_PCC_SUBSPACE_MEM_RANGE_LEN) { IncrementErrorCount (); Print ( L"\nError: Shared memory range length is too short.\n" L"Length is %u when it should be greater than or equal to %u", *(UINT32*)Ptr, MIN_EXT_PCC_SUBSPACE_MEM_RANGE_LEN ); } } /** This function validates the length coded on 8 bytes of a shared memory range @param [in] Ptr Pointer to the start of the field data. @param [in] Context Pointer to context specific information e.g. this could be a pointer to the ACPI table header. **/ STATIC VOID EFIAPI ValidateRangeLength8 ( IN UINT8* Ptr, IN VOID* Context ) { if (*(UINT64*)Ptr <= MIN_MEMORY_RANGE_LENGTH) { IncrementErrorCount (); Print ( L"\nError: Shared memory range length is too short.\n" L"Length is %u when it should be greater than %u", *(UINT64*)Ptr, MIN_MEMORY_RANGE_LENGTH ); } } /** This function validates address space for type 0 structure. @param [in] Ptr Pointer to the start of the field data. @param [in] Context Pointer to context specific information e.g. this could be a pointer to the ACPI table header. **/ STATIC VOID EFIAPI ValidatePccType0Gas ( IN UINT8* Ptr, IN VOID* Context ) { switch (*(UINT8*)Ptr) { #if !(defined (MDE_CPU_ARM) || defined (MDE_CPU_AARCH64)) case EFI_ACPI_6_3_SYSTEM_IO: #endif //if not (defined (MDE_CPU_ARM) || defined (MDE_CPU_AARCH64)) case EFI_ACPI_6_3_SYSTEM_MEMORY: return; default: IncrementErrorCount (); Print (L"\nError: Invalid address space"); } } /** This function validates address space for structures of types other than 0. @param [in] Ptr Pointer to the start of the field data. @param [in] Context Pointer to context specific information e.g. this could be a pointer to the ACPI table header. **/ STATIC VOID EFIAPI ValidatePccGas ( IN UINT8* Ptr, IN VOID* Context ) { switch (*(UINT8*)Ptr) { #if !(defined (MDE_CPU_ARM) || defined (MDE_CPU_AARCH64)) case EFI_ACPI_6_3_SYSTEM_IO: #endif //if not (defined (MDE_CPU_ARM) || defined (MDE_CPU_AARCH64)) case EFI_ACPI_6_3_FUNCTIONAL_FIXED_HARDWARE: case EFI_ACPI_6_3_SYSTEM_MEMORY: return; default: IncrementErrorCount (); Print (L"\nError: Invalid address space"); } } /** This function validates doorbell address space for type 4 structure. @param [in] Ptr Pointer to the start of the field data. @param [in] Context Pointer to context specific information e.g. this could be a pointer to the ACPI table header. **/ STATIC VOID EFIAPI ValidatePccDoorbellGas ( IN UINT8* Ptr, IN VOID* Context ) { // For slave subspaces this field is optional, if not present the field // should just contain zeros. if (*PccSubspaceType == EFI_ACPI_6_3_PCCT_SUBSPACE_TYPE_4_EXTENDED_PCC) { if (IsZeroBuffer ( Ptr, sizeof (EFI_ACPI_6_3_GENERIC_ADDRESS_STRUCTURE) )) { return; } } ValidatePccGas (Ptr, Context); } /** This function validates interrupt acknowledge address space for type 4 structure. @param [in] Ptr Pointer to the start of the field data. @param [in] Context Pointer to context specific information e.g. this could be a pointer to the ACPI table header. **/ STATIC VOID EFIAPI ValidatePccIntAckGas ( IN UINT8* Ptr, IN VOID* Context ) { // If the subspace does not support interrupts or the interrupt is // edge driven the register may be omitted. A value of 0x0 on all // 12 bytes of the GAS structure indicates the register is not // present. if (((*PccGlobalFlags & EFI_ACPI_6_3_PCCT_FLAGS_PLATFORM_INTERRUPT) != EFI_ACPI_6_3_PCCT_FLAGS_PLATFORM_INTERRUPT) || ((*ExtendedPccSubspaceInterruptFlags & EFI_ACPI_6_3_PCCT_SUBSPACE_PLATFORM_INTERRUPT_FLAGS_MODE) == EFI_ACPI_6_3_PCCT_SUBSPACE_PLATFORM_INTERRUPT_FLAGS_MODE)) { if (IsZeroBuffer ( Ptr, sizeof (EFI_ACPI_6_3_GENERIC_ADDRESS_STRUCTURE) )) { return; } } ValidatePccGas (Ptr, Context); } /** This function validates error status address space for type 4 structure. @param [in] Ptr Pointer to the start of the field data. @param [in] Context Pointer to context specific information e.g. this could be a pointer to the ACPI table header. **/ STATIC VOID EFIAPI ValidatePccErrStatusGas ( IN UINT8* Ptr, IN VOID* Context ) { // This field is ignored by the OSPM on slave channels. if (*PccSubspaceType == EFI_ACPI_6_3_PCCT_SUBSPACE_TYPE_4_EXTENDED_PCC) { return; } ValidatePccGas (Ptr, Context); } /** This function validates platform interrupt flags for type 4 structure. @param [in] Ptr Pointer to the start of the field data. @param [in] Context Pointer to context specific information e.g. this could be a pointer to the ACPI table header. **/ STATIC VOID EFIAPI ValidatePlatInterrupt ( IN UINT8* Ptr, IN VOID* Context ) { // If a slave subspace is present in the PCCT, then the global Platform // Interrupt flag must be set to 1. if ((*PccSubspaceType == EFI_ACPI_6_3_PCCT_SUBSPACE_TYPE_4_EXTENDED_PCC) && ((*PccGlobalFlags & EFI_ACPI_6_3_PCCT_FLAGS_PLATFORM_INTERRUPT) != EFI_ACPI_6_3_PCCT_FLAGS_PLATFORM_INTERRUPT)) { IncrementErrorCount (); Print ( L"\nError: Global Platform interrupt flag must be set to 1" \ L" if a PCC type 4 structure is present in PCCT." ); } } /** An ACPI_PARSER array describing the ACPI PCCT Table. */ STATIC CONST ACPI_PARSER PcctParser[] = { PARSE_ACPI_HEADER (&AcpiHdrInfo), {L"Flags", 4, 36, NULL, NULL, (VOID**)&PccGlobalFlags, NULL, NULL}, {L"Reserved", 8, 40, NULL, NULL, NULL, NULL, NULL} }; /** An ACPI_PARSER array describing the platform communications channel subspace structure header. */ STATIC CONST ACPI_PARSER PccSubspaceHeaderParser[] = { PCC_SUBSPACE_HEADER () // ... Type Specific Fields ... }; /** An ACPI_PARSER array describing the Generic Communications Subspace - Type 0 */ STATIC CONST ACPI_PARSER PccSubspaceType0Parser[] = { PCC_SUBSPACE_HEADER (), {L"Reserved", 6, 2, L"%x %x %x %x %x %x", Dump6Chars, NULL, NULL, NULL}, {L"Base Address", 8, 8, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Memory Range Length", 8, 16, L"0x%lx", NULL, NULL, ValidateRangeLength8, NULL}, {L"Doorbell Register", 12, 24, NULL, DumpGas, NULL, ValidatePccType0Gas, NULL}, {L"Doorbell Preserve", 8, 36, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Doorbell Write", 8, 44, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Nominal Latency", 4, 52, L"%u", NULL, NULL, NULL, NULL}, {L"Maximum Periodic Access Rate", 4, 56, L"%u", NULL, NULL, NULL, NULL}, {L"Minimum Request Turnaround Time", 2, 60, L"%u", NULL, NULL, NULL, NULL} }; /** An ACPI_PARSER array describing the HW-Reduced Communications Subspace - Type 1 */ STATIC CONST ACPI_PARSER PccSubspaceType1Parser[] = { PCC_SUBSPACE_HEADER (), {L"Platform Interrupt", 4, 2, L"0x%x", NULL, NULL, NULL, NULL}, {L"Platform Interrupt Flags", 1, 6, L"0x%x", NULL, NULL, NULL, NULL}, {L"Reserved", 1, 7, L"0x%x", NULL, NULL, NULL, NULL}, {L"Base Address", 8, 8, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Memory Range Length", 8, 16, L"0x%lx", NULL, NULL, ValidateRangeLength8, NULL}, {L"Doorbell Register", 12, 24, NULL, DumpGas, NULL, ValidatePccGas, NULL}, {L"Doorbell Preserve", 8, 36, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Doorbell Write", 8, 44, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Nominal Latency", 4, 52, L"%u", NULL, NULL, NULL, NULL}, {L"Maximum Periodic Access Rate", 4, 56, L"%u", NULL, NULL, NULL, NULL}, {L"Minimum Request Turnaround Time", 2, 60, L"%u", NULL, NULL, NULL, NULL} }; /** An ACPI_PARSER array describing the HW-Reduced Communications Subspace - Type 2 */ STATIC CONST ACPI_PARSER PccSubspaceType2Parser[] = { PCC_SUBSPACE_HEADER (), {L"Platform Interrupt", 4, 2, L"0x%x", NULL, NULL, NULL, NULL}, {L"Platform Interrupt Flags", 1, 6, L"0x%x", NULL, NULL, NULL, NULL}, {L"Reserved", 1, 7, L"0x%x", NULL, NULL, NULL, NULL}, {L"Base Address", 8, 8, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Memory Range Length", 8, 16, L"0x%lx", NULL, NULL, ValidateRangeLength8, NULL}, {L"Doorbell Register", 12, 24, NULL, DumpGas, NULL, ValidatePccGas, NULL}, {L"Doorbell Preserve", 8, 36, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Doorbell Write", 8, 44, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Nominal Latency", 4, 52, L"%u", NULL, NULL, NULL, NULL}, {L"Maximum Periodic Access Rate", 4, 56, L"%u", NULL, NULL, NULL, NULL}, {L"Minimum Request Turnaround Time", 2, 60, L"%u", NULL, NULL, NULL, NULL}, {L"Platform Interrupt Ack Register", 12, 62, NULL, DumpGas, NULL, ValidatePccGas, NULL}, {L"Platform Interrupt Ack Preserve", 8, 74, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Platform Interrupt Ack Write", 8, 82, L"0x%lx", NULL, NULL, NULL, NULL}, }; /** An ACPI_PARSER array describing the Extended PCC Subspaces - Type 3/4 */ STATIC CONST ACPI_PARSER PccSubspaceType3Parser[] = { PCC_SUBSPACE_HEADER (), {L"Platform Interrupt", 4, 2, L"0x%x", NULL, NULL, ValidatePlatInterrupt, NULL}, {L"Platform Interrupt Flags", 1, 6, L"0x%x", NULL, (VOID**)&ExtendedPccSubspaceInterruptFlags, NULL, NULL}, {L"Reserved", 1, 7, L"0x%x", NULL, NULL, NULL, NULL}, {L"Base Address", 8, 8, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Memory Range Length", 4, 16, L"0x%x", NULL, NULL, ValidateRangeLength4, NULL}, {L"Doorbell Register", 12, 20, NULL, DumpGas, NULL, ValidatePccDoorbellGas, NULL}, {L"Doorbell Preserve", 8, 32, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Doorbell Write", 8, 40, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Nominal Latency", 4, 48, L"%u", NULL, NULL, NULL, NULL}, {L"Maximum Periodic Access Rate", 4, 52, L"%u", NULL, NULL, NULL, NULL}, {L"Minimum Request Turnaround Time", 4, 56, L"%u", NULL, NULL, NULL, NULL}, {L"Platform Interrupt Ack Register", 12, 60, NULL, DumpGas, NULL, ValidatePccIntAckGas, NULL}, {L"Platform Interrupt Ack Preserve", 8, 72, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Platform Interrupt Ack Set", 8, 80, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Reserved", 8, 88, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Cmd Complete Check Reg Addr", 12, 96, NULL, DumpGas, NULL, ValidatePccGas, NULL}, {L"Cmd Complete Check Mask", 8, 108, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Cmd Update Reg Addr", 12, 116, NULL, DumpGas, NULL, ValidatePccGas, NULL}, {L"Cmd Update Preserve mask", 8, 128, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Cmd Update Set mask", 8, 136, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Error Status Register", 12, 144, NULL, DumpGas, NULL, ValidatePccErrStatusGas, NULL}, {L"Error Status Mask", 8, 156, L"0x%lx", NULL, NULL, NULL, NULL}, }; /** This function parses the PCC Subspace type 0. @param [in] Ptr Pointer to the start of Subspace Structure. @param [in] Length Length of the Subspace Structure. **/ STATIC VOID DumpPccSubspaceType0 ( IN UINT8* Ptr, IN UINT8 Length ) { ParseAcpi ( TRUE, 2, "Subspace Type 0", Ptr, Length, PARSER_PARAMS (PccSubspaceType0Parser) ); } /** This function parses the PCC Subspace type 1. @param [in] Ptr Pointer to the start of the Subspace Structure. @param [in] Length Length of the Subspace Structure. **/ STATIC VOID DumpPccSubspaceType1 ( IN UINT8* Ptr, IN UINT8 Length ) { ParseAcpi ( TRUE, 2, "Subspace Type 1", Ptr, Length, PARSER_PARAMS (PccSubspaceType1Parser) ); } /** This function parses the PCC Subspace type 2. @param [in] Ptr Pointer to the start of the Subspace Structure. @param [in] Length Length of the Subspace Structure. **/ STATIC VOID DumpPccSubspaceType2 ( IN UINT8* Ptr, IN UINT8 Length ) { ParseAcpi ( TRUE, 2, "Subspace Type 2", Ptr, Length, PARSER_PARAMS (PccSubspaceType2Parser) ); } /** This function parses the PCC Subspace type 3. @param [in] Ptr Pointer to the start of the Subspace Structure. @param [in] Length Length of the Subspace Structure. **/ STATIC VOID DumpPccSubspaceType3 ( IN UINT8* Ptr, IN UINT8 Length ) { ParseAcpi ( TRUE, 2, "Subspace Type 3", Ptr, Length, PARSER_PARAMS (PccSubspaceType3Parser) ); } /** This function parses the PCC Subspace type 4. @param [in] Ptr Pointer to the start of the Subspace Structure. @param [in] Length Length of the Subspace Structure. **/ STATIC VOID DumpPccSubspaceType4 ( IN UINT8* Ptr, IN UINT8 Length ) { ParseAcpi ( TRUE, 2, "Subspace Type 4", Ptr, Length, PARSER_PARAMS (PccSubspaceType3Parser) ); } /** This function parses the ACPI PCCT table including its sub-structures of type 0 through 4. When trace is enabled this function parses the PCCT table and traces the ACPI table fields. This function also performs validation of the ACPI table fields. @param [in] Trace If TRUE, trace the ACPI fields. @param [in] Ptr Pointer to the start of the buffer. @param [in] AcpiTableLength Length of the ACPI table. @param [in] AcpiTableRevision Revision of the ACPI table. **/ VOID EFIAPI ParseAcpiPcct ( IN BOOLEAN Trace, IN UINT8* Ptr, IN UINT32 AcpiTableLength, IN UINT8 AcpiTableRevision ) { UINT32 Offset; UINT8* PccSubspacePtr; UINTN SubspaceCount; if (!Trace) { return; } Offset = ParseAcpi ( TRUE, 0, "PCCT", Ptr, AcpiTableLength, PARSER_PARAMS (PcctParser) ); PccSubspacePtr = Ptr + Offset; SubspaceCount = 0; while (Offset < AcpiTableLength) { // Parse common structure header to obtain Type and Length. ParseAcpi ( FALSE, 0, NULL, PccSubspacePtr, AcpiTableLength - Offset, PARSER_PARAMS (PccSubspaceHeaderParser) ); // Check if the values used to control the parsing logic have been // successfully read. if ((PccSubspaceType == NULL) || (PccSubspaceLength == NULL)) { IncrementErrorCount (); Print ( L"ERROR: Insufficient remaining table buffer length to read the " \ L"structure header. Length = %u.\n", AcpiTableLength - Offset ); return; } // Validate Structure length if ((*PccSubspaceLength == 0) || ((Offset + (*PccSubspaceLength)) > AcpiTableLength)) { IncrementErrorCount (); Print ( L"ERROR: Invalid Structure length. " \ L"Length = %u. Offset = %u. AcpiTableLength = %u.\n", *PccSubspaceLength, Offset, AcpiTableLength ); return; } switch (*PccSubspaceType) { case EFI_ACPI_6_3_PCCT_SUBSPACE_TYPE_GENERIC: DumpPccSubspaceType0 ( PccSubspacePtr, *PccSubspaceLength ); break; case EFI_ACPI_6_3_PCCT_SUBSPACE_TYPE_1_HW_REDUCED_COMMUNICATIONS: DumpPccSubspaceType1 ( PccSubspacePtr, *PccSubspaceLength ); break; case EFI_ACPI_6_3_PCCT_SUBSPACE_TYPE_2_HW_REDUCED_COMMUNICATIONS: DumpPccSubspaceType2 ( PccSubspacePtr, *PccSubspaceLength ); break; case EFI_ACPI_6_3_PCCT_SUBSPACE_TYPE_3_EXTENDED_PCC: DumpPccSubspaceType3 ( PccSubspacePtr, *PccSubspaceLength ); break; case EFI_ACPI_6_3_PCCT_SUBSPACE_TYPE_4_EXTENDED_PCC: DumpPccSubspaceType4 ( PccSubspacePtr, *PccSubspaceLength ); break; default: IncrementErrorCount (); Print ( L"ERROR: Unknown PCC subspace structure:" L" Type = %u, Length = %u\n", PccSubspaceType, *PccSubspaceLength ); } PccSubspacePtr += *PccSubspaceLength; Offset += *PccSubspaceLength; SubspaceCount++; } // while if (SubspaceCount > MAX_PCC_SUBSPACES) { IncrementErrorCount (); Print (L"ERROR: Too many PCC subspaces."); } }
NaohiroTamura/edk2
ArmPkg/Include/Library/ArmGicArchLib.h
/** @file * * Copyright (c) 2015, Linaro Ltd. All rights reserved. * * SPDX-License-Identifier: BSD-2-Clause-Patent * **/ #ifndef __ARM_GIC_ARCH_LIB_H__ #define __ARM_GIC_ARCH_LIB_H__ // // GIC definitions // typedef enum { ARM_GIC_ARCH_REVISION_2, ARM_GIC_ARCH_REVISION_3 } ARM_GIC_ARCH_REVISION; ARM_GIC_ARCH_REVISION EFIAPI ArmGicGetSupportedArchRevision ( VOID ); #endif
NaohiroTamura/edk2
NetworkPkg/IScsiDxe/IScsiCHAP.h
<reponame>NaohiroTamura/edk2<filename>NetworkPkg/IScsiDxe/IScsiCHAP.h /** @file The header file of CHAP configuration. Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef _ISCSI_CHAP_H_ #define _ISCSI_CHAP_H_ #define ISCSI_AUTH_METHOD_CHAP "CHAP" #define ISCSI_KEY_CHAP_ALGORITHM "CHAP_A" #define ISCSI_KEY_CHAP_IDENTIFIER "CHAP_I" #define ISCSI_KEY_CHAP_CHALLENGE "CHAP_C" #define ISCSI_KEY_CHAP_NAME "CHAP_N" #define ISCSI_KEY_CHAP_RESPONSE "CHAP_R" #define ISCSI_CHAP_ALGORITHM_MD5 5 #define ISCSI_CHAP_AUTH_MAX_LEN 1024 /// /// MD5_HASHSIZE /// #define ISCSI_CHAP_RSP_LEN 16 #define ISCSI_CHAP_STEP_ONE 1 #define ISCSI_CHAP_STEP_TWO 2 #define ISCSI_CHAP_STEP_THREE 3 #define ISCSI_CHAP_STEP_FOUR 4 #pragma pack(1) typedef struct _ISCSI_CHAP_AUTH_CONFIG_NVDATA { UINT8 CHAPType; CHAR8 CHAPName[ISCSI_CHAP_NAME_STORAGE]; CHAR8 CHAPSecret[ISCSI_CHAP_SECRET_STORAGE]; CHAR8 ReverseCHAPName[ISCSI_CHAP_NAME_STORAGE]; CHAR8 ReverseCHAPSecret[ISCSI_CHAP_SECRET_STORAGE]; } ISCSI_CHAP_AUTH_CONFIG_NVDATA; #pragma pack() /// /// ISCSI CHAP Authentication Data /// typedef struct _ISCSI_CHAP_AUTH_DATA { ISCSI_CHAP_AUTH_CONFIG_NVDATA *AuthConfig; UINT32 InIdentifier; UINT8 InChallenge[ISCSI_CHAP_AUTH_MAX_LEN]; UINT32 InChallengeLength; // // Calculated CHAP Response (CHAP_R) value. // UINT8 CHAPResponse[ISCSI_CHAP_RSP_LEN]; // // Auth-data to be sent out for mutual authentication. // UINT32 OutIdentifier; UINT8 OutChallenge[ISCSI_CHAP_AUTH_MAX_LEN]; UINT32 OutChallengeLength; } ISCSI_CHAP_AUTH_DATA; /** This function checks the received iSCSI Login Response during the security negotiation stage. @param[in] Conn The iSCSI connection. @retval EFI_SUCCESS The Login Response passed the CHAP validation. @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. @retval EFI_PROTOCOL_ERROR Some kind of protocol error occurred. @retval Others Other errors as indicated. **/ EFI_STATUS IScsiCHAPOnRspReceived ( IN ISCSI_CONNECTION *Conn ); /** This function fills the CHAP authentication information into the login PDU during the security negotiation stage in the iSCSI connection login. @param[in] Conn The iSCSI connection. @param[in, out] Pdu The PDU to send out. @retval EFI_SUCCESS All check passed and the phase-related CHAP authentication info is filled into the iSCSI PDU. @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. @retval EFI_PROTOCOL_ERROR Some kind of protocol error occurred. **/ EFI_STATUS IScsiCHAPToSendReq ( IN ISCSI_CONNECTION *Conn, IN OUT NET_BUF *Pdu ); #endif
NaohiroTamura/edk2
ArmPkg/Library/ArmLib/Arm/ArmV7Lib.h
/** @file Copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef __ARM_V7_LIB_H__ #define __ARM_V7_LIB_H__ #define ID_MMFR0_SHARELVL_SHIFT 12 #define ID_MMFR0_SHARELVL_MASK 0xf #define ID_MMFR0_SHARELVL_ONE 0 #define ID_MMFR0_SHARELVL_TWO 1 #define ID_MMFR0_INNERSHR_SHIFT 28 #define ID_MMFR0_INNERSHR_MASK 0xf #define ID_MMFR0_OUTERSHR_SHIFT 8 #define ID_MMFR0_OUTERSHR_MASK 0xf #define ID_MMFR0_SHR_IMP_UNCACHED 0 #define ID_MMFR0_SHR_IMP_HW_COHERENT 1 #define ID_MMFR0_SHR_IGNORED 0xf typedef VOID (*ARM_V7_CACHE_OPERATION)(UINT32); VOID ArmV7AllDataCachesOperation ( IN ARM_V7_CACHE_OPERATION DataCacheOperation ); VOID EFIAPI ArmInvalidateDataCacheEntryBySetWay ( IN UINTN SetWayFormat ); VOID EFIAPI ArmCleanDataCacheEntryBySetWay ( IN UINTN SetWayFormat ); VOID EFIAPI ArmCleanInvalidateDataCacheEntryBySetWay ( IN UINTN SetWayFormat ); UINTN EFIAPI ArmReadIdPfr0 ( VOID ); UINTN EFIAPI ArmReadIdPfr1 ( VOID ); #endif // __ARM_V7_LIB_H__
NaohiroTamura/edk2
UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c
/** Implement UnitTestLib assert services Copyright (c) Microsoft Corporation.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <Uefi.h> #include <UnitTestFrameworkTypes.h> #include <Library/UnitTestLib.h> #include <Library/BaseLib.h> #include <Library/BaseMemoryLib.h> #include <Library/DebugLib.h> #include <Library/PrintLib.h> extern BASE_LIBRARY_JUMP_BUFFER gUnitTestJumpBuffer; STATIC EFI_STATUS AddUnitTestFailure ( IN OUT UNIT_TEST *UnitTest, IN CONST CHAR8 *FailureMessage, IN FAILURE_TYPE FailureType ) { // // Make sure that you're cooking with gas. // if (UnitTest == NULL || FailureMessage == NULL) { return EFI_INVALID_PARAMETER; } UnitTest->FailureType = FailureType; AsciiStrCpyS ( &UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, FailureMessage ); return EFI_SUCCESS; } STATIC VOID UnitTestLogFailure ( IN FAILURE_TYPE FailureType, IN CONST CHAR8 *Format, ... ) { UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle; CHAR8 LogString[UNIT_TEST_TESTFAILUREMSG_LENGTH]; VA_LIST Marker; // // Get active Framework handle // FrameworkHandle = GetActiveFrameworkHandle (); // // Convert the message to an ASCII String // VA_START (Marker, Format); AsciiVSPrint (LogString, sizeof (LogString), Format, Marker); VA_END (Marker); // // Finally, add the string to the log. // AddUnitTestFailure ( ((UNIT_TEST_FRAMEWORK *)FrameworkHandle)->CurrentTest, LogString, FailureType ); LongJump (&gUnitTestJumpBuffer, 1); } /** If Expression is TRUE, then TRUE is returned. If Expression is FALSE, then an assert is triggered and the location of the assert provided by FunctionName, LineNumber, FileName, and Description are recorded and FALSE is returned. @param[in] Expression The BOOLEAN result of the expression evaluation. @param[in] FunctionName Null-terminated ASCII string of the function executing the assert macro. @param[in] LineNumber The source file line number of the assert macro. @param[in] FileName Null-terminated ASCII string of the filename executing the assert macro. @param[in] Description Null-terminated ASCII string of the expression being evaluated. @retval TRUE Expression is TRUE. @retval FALSE Expression is FALSE. **/ BOOLEAN EFIAPI UnitTestAssertTrue ( IN BOOLEAN Expression, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, IN CONST CHAR8 *FileName, IN CONST CHAR8 *Description ) { if (!Expression) { UT_LOG_ERROR ( "[ASSERT FAIL] %a:%d: Expression (%a) is not TRUE!\n", FileName, LineNumber, Description ); UnitTestLogFailure ( FAILURETYPE_ASSERTTRUE, "%a:%d: Expression (%a) is not TRUE!\n", FileName, LineNumber, Description ); } return Expression; } /** If Expression is FALSE, then TRUE is returned. If Expression is TRUE, then an assert is triggered and the location of the assert provided by FunctionName, LineNumber, FileName, and Description are recorded and FALSE is returned. @param[in] Expression The BOOLEAN result of the expression evaluation. @param[in] FunctionName Null-terminated ASCII string of the function executing the assert macro. @param[in] LineNumber The source file line number of the assert macro. @param[in] FileName Null-terminated ASCII string of the filename executing the assert macro. @param[in] Description Null-terminated ASCII string of the expression being evaluated. @retval TRUE Expression is FALSE. @retval FALSE Expression is TRUE. **/ BOOLEAN EFIAPI UnitTestAssertFalse ( IN BOOLEAN Expression, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, IN CONST CHAR8 *FileName, IN CONST CHAR8 *Description ) { if (Expression) { UT_LOG_ERROR ( "[ASSERT FAIL] %a:%d: Expression (%a) is not FALSE!\n", FileName, LineNumber, Description ); UnitTestLogFailure ( FAILURETYPE_ASSERTFALSE, "%a:%d: Expression(%a) is not FALSE!\n", FileName, LineNumber, Description ); } return !Expression; } /** If Status is not an EFI_ERROR(), then TRUE is returned. If Status is an EFI_ERROR(), then an assert is triggered and the location of the assert provided by FunctionName, LineNumber, FileName, and Description are recorded and FALSE is returned. @param[in] Status The EFI_STATUS value to evaluate. @param[in] FunctionName Null-terminated ASCII string of the function executing the assert macro. @param[in] LineNumber The source file line number of the assert macro. @param[in] FileName Null-terminated ASCII string of the filename executing the assert macro. @param[in] Description Null-terminated ASCII string of the status expression being evaluated. @retval TRUE Status is not an EFI_ERROR(). @retval FALSE Status is an EFI_ERROR(). **/ BOOLEAN EFIAPI UnitTestAssertNotEfiError ( IN EFI_STATUS Status, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, IN CONST CHAR8 *FileName, IN CONST CHAR8 *Description ) { if (EFI_ERROR (Status)) { UT_LOG_ERROR ( "[ASSERT FAIL] %a:%d: Status '%a' is EFI_ERROR (%r)!\n", FileName, LineNumber, Description, Status ); UnitTestLogFailure ( FAILURETYPE_ASSERTNOTEFIERROR, "%a:%d: Status '%a' is EFI_ERROR (%r)!\n", FileName, LineNumber, Description, Status ); } return !EFI_ERROR( Status ); } /** If ValueA is equal ValueB, then TRUE is returned. If ValueA is not equal to ValueB, then an assert is triggered and the location of the assert provided by FunctionName, LineNumber, FileName, DescriptionA, and DescriptionB are recorded and FALSE is returned. @param[in] ValueA 64-bit value. @param[in] ValueB 64-bit value. @param[in] FunctionName Null-terminated ASCII string of the function executing the assert macro. @param[in] LineNumber The source file line number of the assert macro. @param[in] FileName Null-terminated ASCII string of the filename executing the assert macro. @param[in] DescriptionA Null-terminated ASCII string that is a description of ValueA. @param[in] DescriptionB Null-terminated ASCII string that is a description of ValueB. @retval TRUE ValueA is equal to ValueB. @retval FALSE ValueA is not equal to ValueB. **/ BOOLEAN EFIAPI UnitTestAssertEqual ( IN UINT64 ValueA, IN UINT64 ValueB, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, IN CONST CHAR8 *FileName, IN CONST CHAR8 *DescriptionA, IN CONST CHAR8 *DescriptionB ) { if (ValueA != ValueB) { UT_LOG_ERROR ( "[ASSERT FAIL] %a:%d: Value %a != %a (%d != %d)!\n", FileName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB ); UnitTestLogFailure ( FAILURETYPE_ASSERTEQUAL, "%a:%d: Value %a != %a (%d != %d)!\n", FileName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB ); } return (ValueA == ValueB); } /** If the contents of BufferA are identical to the contents of BufferB, then TRUE is returned. If the contents of BufferA are not identical to the contents of BufferB, then an assert is triggered and the location of the assert provided by FunctionName, LineNumber, FileName, DescriptionA, and DescriptionB are recorded and FALSE is returned. @param[in] BufferA Pointer to a buffer for comparison. @param[in] BufferB Pointer to a buffer for comparison. @param[in] Length Number of bytes to compare in BufferA and BufferB. @param[in] FunctionName Null-terminated ASCII string of the function executing the assert macro. @param[in] LineNumber The source file line number of the assert macro. @param[in] FileName Null-terminated ASCII string of the filename executing the assert macro. @param[in] DescriptionA Null-terminated ASCII string that is a description of BufferA. @param[in] DescriptionB Null-terminated ASCII string that is a description of BufferB. @retval TRUE The contents of BufferA are identical to the contents of BufferB. @retval FALSE The contents of BufferA are not identical to the contents of BufferB. **/ BOOLEAN EFIAPI UnitTestAssertMemEqual ( IN VOID *BufferA, IN VOID *BufferB, IN UINTN Length, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, IN CONST CHAR8 *FileName, IN CONST CHAR8 *DescriptionA, IN CONST CHAR8 *DescriptionB ) { if (CompareMem(BufferA, BufferB, Length) != 0) { UT_LOG_ERROR ( "[ASSERT FAIL] %a:%d: Value %a != %a for length %d bytes!\n", FileName, LineNumber, DescriptionA, DescriptionB, Length ); UnitTestLogFailure ( FAILURETYPE_ASSERTEQUAL, "%a:%d: Memory at %a != %a for length %d bytes!\n", FileName, LineNumber, DescriptionA, DescriptionB, Length ); return FALSE; } return TRUE; } /** If ValueA is not equal ValueB, then TRUE is returned. If ValueA is equal to ValueB, then an assert is triggered and the location of the assert provided by FunctionName, LineNumber, FileName, DescriptionA and DescriptionB are recorded and FALSE is returned. @param[in] ValueA 64-bit value. @param[in] ValueB 64-bit value. @param[in] FunctionName Null-terminated ASCII string of the function executing the assert macro. @param[in] LineNumber The source file line number of the assert macro. @param[in] FileName Null-terminated ASCII string of the filename executing the assert macro. @param[in] DescriptionA Null-terminated ASCII string that is a description of ValueA. @param[in] DescriptionB Null-terminated ASCII string that is a description of ValueB. @retval TRUE ValueA is not equal to ValueB. @retval FALSE ValueA is equal to ValueB. **/ BOOLEAN EFIAPI UnitTestAssertNotEqual ( IN UINT64 ValueA, IN UINT64 ValueB, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, IN CONST CHAR8 *FileName, IN CONST CHAR8 *DescriptionA, IN CONST CHAR8 *DescriptionB ) { if (ValueA == ValueB) { UT_LOG_ERROR ( "[ASSERT FAIL] %a:%d: Value %a == %a (%d == %d)!\n", FileName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB ); UnitTestLogFailure ( FAILURETYPE_ASSERTNOTEQUAL, "%a:%d: Value %a == %a (%d == %d)!\n", FileName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB ); } return (ValueA != ValueB); } /** If Status is equal to Expected, then TRUE is returned. If Status is not equal to Expected, then an assert is triggered and the location of the assert provided by FunctionName, LineNumber, FileName, and Description are recorded and FALSE is returned. @param[in] Status EFI_STATUS value returned from an API under test. @param[in] Expected The expected EFI_STATUS return value from an API under test. @param[in] FunctionName Null-terminated ASCII string of the function executing the assert macro. @param[in] LineNumber The source file line number of the assert macro. @param[in] FileName Null-terminated ASCII string of the filename executing the assert macro. @param[in] Description Null-terminated ASCII string that is a description of Status. @retval TRUE Status is equal to Expected. @retval FALSE Status is not equal to Expected. **/ BOOLEAN EFIAPI UnitTestAssertStatusEqual ( IN EFI_STATUS Status, IN EFI_STATUS Expected, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, IN CONST CHAR8 *FileName, IN CONST CHAR8 *Description ) { if (Status != Expected) { UT_LOG_ERROR ( "[ASSERT FAIL] %a:%d: Status '%a' is %r, should be %r!\n", FileName, LineNumber, Description, Status, Expected ); UnitTestLogFailure ( FAILURETYPE_ASSERTSTATUSEQUAL, "%a:%d: Status '%a' is %r, should be %r!\n", FileName, LineNumber, Description, Status, Expected ); } return (Status == Expected); } /** If Pointer is not equal to NULL, then TRUE is returned. If Pointer is equal to NULL, then an assert is triggered and the location of the assert provided by FunctionName, LineNumber, FileName, and PointerName are recorded and FALSE is returned. @param[in] Pointer Pointer value to be checked against NULL. @param[in] Expected The expected EFI_STATUS return value from a function under test. @param[in] FunctionName Null-terminated ASCII string of the function executing the assert macro. @param[in] LineNumber The source file line number of the assert macro. @param[in] FileName Null-terminated ASCII string of the filename executing the assert macro. @param[in] PointerName Null-terminated ASCII string that is a description of Pointer. @retval TRUE Pointer is not equal to NULL. @retval FALSE Pointer is equal to NULL. **/ BOOLEAN EFIAPI UnitTestAssertNotNull ( IN VOID *Pointer, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, IN CONST CHAR8 *FileName, IN CONST CHAR8 *PointerName ) { if (Pointer == NULL) { UT_LOG_ERROR ( "[ASSERT FAIL] %a:%d: Pointer (%a) is NULL!\n", FileName, LineNumber, PointerName ); UnitTestLogFailure ( FAILURETYPE_ASSERTNOTNULL, "%a:%d: Pointer (%a) is NULL!\n", FileName, LineNumber, PointerName ); } return (Pointer != NULL); } /** If UnitTestStatus is UNIT_TEST_PASSED, then log an info message and return TRUE because an ASSERT() was expected when FunctionCall was executed and an ASSERT() was triggered. If UnitTestStatus is UNIT_TEST_SKIPPED, then log a warning message and return TRUE because ASSERT() macros are disabled. If UnitTestStatus is UNIT_TEST_ERROR_TEST_FAILED, then log an error message and return FALSE because an ASSERT() was expected when FunctionCall was executed, but no ASSERT() conditions were triggered. The log messages contain FunctionName, LineNumber, and FileName strings to provide the location of the UT_EXPECT_ASSERT_FAILURE() macro. @param[in] UnitTestStatus The status from UT_EXPECT_ASSERT_FAILURE() that is either pass, skipped, or failed. @param[in] FunctionName Null-terminated ASCII string of the function executing the UT_EXPECT_ASSERT_FAILURE() macro. @param[in] LineNumber The source file line number of the the function executing the UT_EXPECT_ASSERT_FAILURE() macro. @param[in] FileName Null-terminated ASCII string of the filename executing the UT_EXPECT_ASSERT_FAILURE() macro. @param[in] FunctionCall Null-terminated ASCII string of the function call executed by the UT_EXPECT_ASSERT_FAILURE() macro. @param[out] ResultStatus Used to return the UnitTestStatus value to the caller of UT_EXPECT_ASSERT_FAILURE(). This is optional parameter that may be NULL. @retval TRUE UnitTestStatus is UNIT_TEST_PASSED. @retval TRUE UnitTestStatus is UNIT_TEST_SKIPPED. @retval FALSE UnitTestStatus is UNIT_TEST_ERROR_TEST_FAILED. **/ BOOLEAN EFIAPI UnitTestExpectAssertFailure ( IN UNIT_TEST_STATUS UnitTestStatus, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, IN CONST CHAR8 *FileName, IN CONST CHAR8 *FunctionCall, OUT UNIT_TEST_STATUS *ResultStatus OPTIONAL ) { if (ResultStatus != NULL) { *ResultStatus = UnitTestStatus; } if (UnitTestStatus == UNIT_TEST_PASSED) { UT_LOG_INFO ( "[ASSERT PASS] %a:%d: UT_EXPECT_ASSERT_FAILURE(%a) detected expected assert\n", FileName, LineNumber, FunctionCall ); } if (UnitTestStatus == UNIT_TEST_SKIPPED) { UT_LOG_WARNING ( "[ASSERT WARN] %a:%d: UT_EXPECT_ASSERT_FAILURE(%a) disabled\n", FileName, LineNumber, FunctionCall ); } if (UnitTestStatus == UNIT_TEST_ERROR_TEST_FAILED) { UT_LOG_ERROR ( "[ASSERT FAIL] %a:%d: Function call (%a) did not ASSERT()!\n", FileName, LineNumber, FunctionCall ); UnitTestLogFailure ( FAILURETYPE_EXPECTASSERT, "%a:%d: Function call (%a) did not ASSERT()!\n", FileName, LineNumber, FunctionCall ); } return (UnitTestStatus != UNIT_TEST_ERROR_TEST_FAILED); }
NaohiroTamura/edk2
UefiCpuPkg/Library/CpuTimerLib/DxeCpuTimerLib.c
/** @file CPUID Leaf 0x15 for Core Crystal Clock frequency instance of Timer Library. Copyright (c) 2019 Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <PiDxe.h> #include <Library/TimerLib.h> #include <Library/BaseLib.h> #include <Library/HobLib.h> extern GUID mCpuCrystalFrequencyHobGuid; /** CPUID Leaf 0x15 for Core Crystal Clock Frequency. The TSC counting frequency is determined by using CPUID leaf 0x15. Frequency in MHz = Core XTAL frequency * EBX/EAX. In newer flavors of the CPU, core xtal frequency is returned in ECX or 0 if not supported. @return The number of TSC counts per second. **/ UINT64 CpuidCoreClockCalculateTscFrequency ( VOID ); // // Cached CPU Crystal counter frequency // UINT64 mCpuCrystalCounterFrequency = 0; /** Internal function to retrieves the 64-bit frequency in Hz. Internal function to retrieves the 64-bit frequency in Hz. @return The frequency in Hz. **/ UINT64 InternalGetPerformanceCounterFrequency ( VOID ) { return mCpuCrystalCounterFrequency; } /** The constructor function is to initialize CpuCrystalCounterFrequency. @param ImageHandle The firmware allocated handle for the EFI image. @param SystemTable A pointer to the EFI System Table. @retval EFI_SUCCESS The constructor always returns RETURN_SUCCESS. **/ EFI_STATUS EFIAPI DxeCpuTimerLibConstructor ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_HOB_GUID_TYPE *GuidHob; // // Initialize CpuCrystalCounterFrequency // GuidHob = GetFirstGuidHob (&mCpuCrystalFrequencyHobGuid); if (GuidHob != NULL) { mCpuCrystalCounterFrequency = *(UINT64*)GET_GUID_HOB_DATA (GuidHob); } else { mCpuCrystalCounterFrequency = CpuidCoreClockCalculateTscFrequency (); } if (mCpuCrystalCounterFrequency == 0) { return EFI_UNSUPPORTED; } return EFI_SUCCESS; }
NaohiroTamura/edk2
UefiCpuPkg/Library/MpInitLib/Microcode.c
<filename>UefiCpuPkg/Library/MpInitLib/Microcode.c /** @file Implementation of loading microcode on processors. Copyright (c) 2015 - 2020, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "MpLib.h" /** Get microcode update signature of currently loaded microcode update. @return Microcode signature. **/ UINT32 GetCurrentMicrocodeSignature ( VOID ) { MSR_IA32_BIOS_SIGN_ID_REGISTER BiosSignIdMsr; AsmWriteMsr64 (MSR_IA32_BIOS_SIGN_ID, 0); AsmCpuid (CPUID_VERSION_INFO, NULL, NULL, NULL, NULL); BiosSignIdMsr.Uint64 = AsmReadMsr64 (MSR_IA32_BIOS_SIGN_ID); return BiosSignIdMsr.Bits.MicrocodeUpdateSignature; } /** Detect whether specified processor can find matching microcode patch and load it. Microcode Payload as the following format: +----------------------------------------+------------------+ | CPU_MICROCODE_HEADER | | +----------------------------------------+ CheckSum Part1 | | Microcode Binary | | +----------------------------------------+------------------+ | CPU_MICROCODE_EXTENDED_TABLE_HEADER | | +----------------------------------------+ CheckSum Part2 | | CPU_MICROCODE_EXTENDED_TABLE | | | ... | | +----------------------------------------+------------------+ There may by multiple CPU_MICROCODE_EXTENDED_TABLE in this format. The count of CPU_MICROCODE_EXTENDED_TABLE is indicated by ExtendedSignatureCount of CPU_MICROCODE_EXTENDED_TABLE_HEADER structure. When we are trying to verify the CheckSum32 with extended table. We should use the fields of exnteded table to replace the corresponding fields in CPU_MICROCODE_HEADER structure, and recalculate the CheckSum32 with CPU_MICROCODE_HEADER + Microcode Binary. We named it as CheckSum Part3. The CheckSum Part2 is used to verify the CPU_MICROCODE_EXTENDED_TABLE_HEADER and CPU_MICROCODE_EXTENDED_TABLE parts. We should make sure CheckSum Part2 is correct before we are going to verify each CPU_MICROCODE_EXTENDED_TABLE. Only ProcessorSignature, ProcessorFlag and CheckSum are different between CheckSum Part1 and CheckSum Part3. To avoid multiple computing CheckSum Part3. Save an in-complete CheckSum32 from CheckSum Part1 for common parts. When we are going to calculate CheckSum32, just should use the corresponding part of the ProcessorSignature, ProcessorFlag and CheckSum with in-complete CheckSum32. Notes: CheckSum32 is not a strong verification. It does not guarantee that the data has not been modified. CPU has its own mechanism to verify Microcode Binary part. @param[in] CpuMpData The pointer to CPU MP Data structure. @param[in] ProcessorNumber The handle number of the processor. The range is from 0 to the total number of logical processors minus 1. **/ VOID MicrocodeDetect ( IN CPU_MP_DATA *CpuMpData, IN UINTN ProcessorNumber ) { UINT32 ExtendedTableLength; UINT32 ExtendedTableCount; CPU_MICROCODE_EXTENDED_TABLE *ExtendedTable; CPU_MICROCODE_EXTENDED_TABLE_HEADER *ExtendedTableHeader; CPU_MICROCODE_HEADER *MicrocodeEntryPoint; UINTN MicrocodeEnd; UINTN Index; UINT8 PlatformId; CPUID_VERSION_INFO_EAX Eax; CPU_AP_DATA *CpuData; UINT32 CurrentRevision; UINT32 LatestRevision; UINTN TotalSize; UINT32 CheckSum32; UINT32 InCompleteCheckSum32; BOOLEAN CorrectMicrocode; VOID *MicrocodeData; MSR_IA32_PLATFORM_ID_REGISTER PlatformIdMsr; UINT32 ThreadId; BOOLEAN IsBspCallIn; if (CpuMpData->MicrocodePatchRegionSize == 0) { // // There is no microcode patches // return; } CurrentRevision = GetCurrentMicrocodeSignature (); IsBspCallIn = (ProcessorNumber == (UINTN)CpuMpData->BspNumber) ? TRUE : FALSE; GetProcessorLocationByApicId (GetInitialApicId (), NULL, NULL, &ThreadId); if (ThreadId != 0) { // // Skip loading microcode if it is not the first thread in one core. // return; } ExtendedTableLength = 0; // // Here data of CPUID leafs have not been collected into context buffer, so // GetProcessorCpuid() cannot be used here to retrieve CPUID data. // AsmCpuid (CPUID_VERSION_INFO, &Eax.Uint32, NULL, NULL, NULL); // // The index of platform information resides in bits 50:52 of MSR IA32_PLATFORM_ID // PlatformIdMsr.Uint64 = AsmReadMsr64 (MSR_IA32_PLATFORM_ID); PlatformId = (UINT8) PlatformIdMsr.Bits.PlatformId; // // Check whether AP has same processor with BSP. // If yes, direct use microcode info saved by BSP. // if (!IsBspCallIn) { // // Get the CPU data for BSP // CpuData = &(CpuMpData->CpuData[CpuMpData->BspNumber]); if ((CpuData->ProcessorSignature == Eax.Uint32) && (CpuData->PlatformId == PlatformId) && (CpuData->MicrocodeEntryAddr != 0)) { MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *)(UINTN) CpuData->MicrocodeEntryAddr; MicrocodeData = (VOID *) (MicrocodeEntryPoint + 1); LatestRevision = MicrocodeEntryPoint->UpdateRevision; goto Done; } } LatestRevision = 0; MicrocodeData = NULL; MicrocodeEnd = (UINTN) (CpuMpData->MicrocodePatchAddress + CpuMpData->MicrocodePatchRegionSize); MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (UINTN) CpuMpData->MicrocodePatchAddress; do { // // Check if the microcode is for the Cpu and the version is newer // and the update can be processed on the platform // CorrectMicrocode = FALSE; if (MicrocodeEntryPoint->DataSize == 0) { TotalSize = sizeof (CPU_MICROCODE_HEADER) + 2000; } else { TotalSize = sizeof (CPU_MICROCODE_HEADER) + MicrocodeEntryPoint->DataSize; } /// /// 0x0 MicrocodeBegin MicrocodeEntry MicrocodeEnd 0xffffffff /// |--------------|---------------|---------------|---------------| /// valid TotalSize /// TotalSize is only valid between 0 and (MicrocodeEnd - MicrocodeEntry). /// And it should be aligned with 4 bytes. /// If the TotalSize is invalid, skip 1KB to check next entry. /// if ( (UINTN)MicrocodeEntryPoint > (MAX_ADDRESS - TotalSize) || ((UINTN)MicrocodeEntryPoint + TotalSize) > MicrocodeEnd || (TotalSize & 0x3) != 0 ) { MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (((UINTN) MicrocodeEntryPoint) + SIZE_1KB); continue; } // // Save an in-complete CheckSum32 from CheckSum Part1 for common parts. // InCompleteCheckSum32 = CalculateSum32 ( (UINT32 *) MicrocodeEntryPoint, TotalSize ); InCompleteCheckSum32 -= MicrocodeEntryPoint->ProcessorSignature.Uint32; InCompleteCheckSum32 -= MicrocodeEntryPoint->ProcessorFlags; InCompleteCheckSum32 -= MicrocodeEntryPoint->Checksum; if (MicrocodeEntryPoint->HeaderVersion == 0x1) { // // It is the microcode header. It is not the padding data between microcode patches // because the padding data should not include 0x00000001 and it should be the repeated // byte format (like 0xXYXYXYXY....). // if (MicrocodeEntryPoint->ProcessorSignature.Uint32 == Eax.Uint32 && MicrocodeEntryPoint->UpdateRevision > LatestRevision && (MicrocodeEntryPoint->ProcessorFlags & (1 << PlatformId)) ) { // // Calculate CheckSum Part1. // CheckSum32 = InCompleteCheckSum32; CheckSum32 += MicrocodeEntryPoint->ProcessorSignature.Uint32; CheckSum32 += MicrocodeEntryPoint->ProcessorFlags; CheckSum32 += MicrocodeEntryPoint->Checksum; if (CheckSum32 == 0) { CorrectMicrocode = TRUE; } } else if ((MicrocodeEntryPoint->DataSize != 0) && (MicrocodeEntryPoint->UpdateRevision > LatestRevision)) { ExtendedTableLength = MicrocodeEntryPoint->TotalSize - (MicrocodeEntryPoint->DataSize + sizeof (CPU_MICROCODE_HEADER)); if (ExtendedTableLength != 0) { // // Extended Table exist, check if the CPU in support list // ExtendedTableHeader = (CPU_MICROCODE_EXTENDED_TABLE_HEADER *) ((UINT8 *) (MicrocodeEntryPoint) + MicrocodeEntryPoint->DataSize + sizeof (CPU_MICROCODE_HEADER)); // // Calculate Extended Checksum // if ((ExtendedTableLength % 4) == 0) { // // Calculate CheckSum Part2. // CheckSum32 = CalculateSum32 ((UINT32 *) ExtendedTableHeader, ExtendedTableLength); if (CheckSum32 == 0) { // // Checksum correct // ExtendedTableCount = ExtendedTableHeader->ExtendedSignatureCount; ExtendedTable = (CPU_MICROCODE_EXTENDED_TABLE *) (ExtendedTableHeader + 1); for (Index = 0; Index < ExtendedTableCount; Index ++) { // // Calculate CheckSum Part3. // CheckSum32 = InCompleteCheckSum32; CheckSum32 += ExtendedTable->ProcessorSignature.Uint32; CheckSum32 += ExtendedTable->ProcessorFlag; CheckSum32 += ExtendedTable->Checksum; if (CheckSum32 == 0) { // // Verify Header // if ((ExtendedTable->ProcessorSignature.Uint32 == Eax.Uint32) && (ExtendedTable->ProcessorFlag & (1 << PlatformId)) ) { // // Find one // CorrectMicrocode = TRUE; break; } } ExtendedTable ++; } } } } } } else { // // It is the padding data between the microcode patches for microcode patches alignment. // Because the microcode patch is the multiple of 1-KByte, the padding data should not // exist if the microcode patch alignment value is not larger than 1-KByte. So, the microcode // alignment value should be larger than 1-KByte. We could skip SIZE_1KB padding data to // find the next possible microcode patch header. // MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (((UINTN) MicrocodeEntryPoint) + SIZE_1KB); continue; } // // Get the next patch. // if (MicrocodeEntryPoint->DataSize == 0) { TotalSize = 2048; } else { TotalSize = MicrocodeEntryPoint->TotalSize; } if (CorrectMicrocode) { LatestRevision = MicrocodeEntryPoint->UpdateRevision; MicrocodeData = (VOID *) ((UINTN) MicrocodeEntryPoint + sizeof (CPU_MICROCODE_HEADER)); } MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (((UINTN) MicrocodeEntryPoint) + TotalSize); } while (((UINTN) MicrocodeEntryPoint < MicrocodeEnd)); Done: if (LatestRevision != 0) { // // Save the detected microcode patch entry address (including the // microcode patch header) for each processor. // It will be used when building the microcode patch cache HOB. // CpuMpData->CpuData[ProcessorNumber].MicrocodeEntryAddr = (UINTN) MicrocodeData - sizeof (CPU_MICROCODE_HEADER); } if (LatestRevision > CurrentRevision) { // // BIOS only authenticate updates that contain a numerically larger revision // than the currently loaded revision, where Current Signature < New Update // Revision. A processor with no loaded update is considered to have a // revision equal to zero. // ASSERT (MicrocodeData != NULL); AsmWriteMsr64 ( MSR_IA32_BIOS_UPDT_TRIG, (UINT64) (UINTN) MicrocodeData ); // // Get and check new microcode signature // CurrentRevision = GetCurrentMicrocodeSignature (); if (CurrentRevision != LatestRevision) { AcquireSpinLock(&CpuMpData->MpLock); DEBUG ((EFI_D_ERROR, "Updated microcode signature [0x%08x] does not match \ loaded microcode signature [0x%08x]\n", CurrentRevision, LatestRevision)); ReleaseSpinLock(&CpuMpData->MpLock); } } } /** Determine if a microcode patch matchs the specific processor signature and flag. @param[in] CpuMpData The pointer to CPU MP Data structure. @param[in] ProcessorSignature The processor signature field value supported by a microcode patch. @param[in] ProcessorFlags The prcessor flags field value supported by a microcode patch. @retval TRUE The specified microcode patch will be loaded. @retval FALSE The specified microcode patch will not be loaded. **/ BOOLEAN IsProcessorMatchedMicrocodePatch ( IN CPU_MP_DATA *CpuMpData, IN UINT32 ProcessorSignature, IN UINT32 ProcessorFlags ) { UINTN Index; CPU_AP_DATA *CpuData; for (Index = 0; Index < CpuMpData->CpuCount; Index++) { CpuData = &CpuMpData->CpuData[Index]; if ((ProcessorSignature == CpuData->ProcessorSignature) && (ProcessorFlags & (1 << CpuData->PlatformId)) != 0) { return TRUE; } } return FALSE; } /** Check the 'ProcessorSignature' and 'ProcessorFlags' of the microcode patch header with the CPUID and PlatformID of the processors within system to decide if it will be copied into memory. @param[in] CpuMpData The pointer to CPU MP Data structure. @param[in] MicrocodeEntryPoint The pointer to the microcode patch header. @retval TRUE The specified microcode patch need to be loaded. @retval FALSE The specified microcode patch dosen't need to be loaded. **/ BOOLEAN IsMicrocodePatchNeedLoad ( IN CPU_MP_DATA *CpuMpData, CPU_MICROCODE_HEADER *MicrocodeEntryPoint ) { BOOLEAN NeedLoad; UINTN DataSize; UINTN TotalSize; CPU_MICROCODE_EXTENDED_TABLE_HEADER *ExtendedTableHeader; UINT32 ExtendedTableCount; CPU_MICROCODE_EXTENDED_TABLE *ExtendedTable; UINTN Index; // // Check the 'ProcessorSignature' and 'ProcessorFlags' in microcode patch header. // NeedLoad = IsProcessorMatchedMicrocodePatch ( CpuMpData, MicrocodeEntryPoint->ProcessorSignature.Uint32, MicrocodeEntryPoint->ProcessorFlags ); // // If the Extended Signature Table exists, check if the processor is in the // support list // DataSize = MicrocodeEntryPoint->DataSize; TotalSize = (DataSize == 0) ? 2048 : MicrocodeEntryPoint->TotalSize; if ((!NeedLoad) && (DataSize != 0) && (TotalSize - DataSize > sizeof (CPU_MICROCODE_HEADER) + sizeof (CPU_MICROCODE_EXTENDED_TABLE_HEADER))) { ExtendedTableHeader = (CPU_MICROCODE_EXTENDED_TABLE_HEADER *) ((UINT8 *) (MicrocodeEntryPoint) + DataSize + sizeof (CPU_MICROCODE_HEADER)); ExtendedTableCount = ExtendedTableHeader->ExtendedSignatureCount; ExtendedTable = (CPU_MICROCODE_EXTENDED_TABLE *) (ExtendedTableHeader + 1); for (Index = 0; Index < ExtendedTableCount; Index ++) { // // Check the 'ProcessorSignature' and 'ProcessorFlag' of the Extended // Signature Table entry with the CPUID and PlatformID of the processors // within system to decide if it will be copied into memory // NeedLoad = IsProcessorMatchedMicrocodePatch ( CpuMpData, ExtendedTable->ProcessorSignature.Uint32, ExtendedTable->ProcessorFlag ); if (NeedLoad) { break; } ExtendedTable ++; } } return NeedLoad; } /** Actual worker function that shadows the required microcode patches into memory. @param[in, out] CpuMpData The pointer to CPU MP Data structure. @param[in] Patches The pointer to an array of information on the microcode patches that will be loaded into memory. @param[in] PatchCount The number of microcode patches that will be loaded into memory. @param[in] TotalLoadSize The total size of all the microcode patches to be loaded. **/ VOID ShadowMicrocodePatchWorker ( IN OUT CPU_MP_DATA *CpuMpData, IN MICROCODE_PATCH_INFO *Patches, IN UINTN PatchCount, IN UINTN TotalLoadSize ) { UINTN Index; VOID *MicrocodePatchInRam; UINT8 *Walker; ASSERT ((Patches != NULL) && (PatchCount != 0)); MicrocodePatchInRam = AllocatePages (EFI_SIZE_TO_PAGES (TotalLoadSize)); if (MicrocodePatchInRam == NULL) { return; } // // Load all the required microcode patches into memory // for (Walker = MicrocodePatchInRam, Index = 0; Index < PatchCount; Index++) { CopyMem ( Walker, (VOID *) Patches[Index].Address, Patches[Index].Size ); Walker += Patches[Index].Size; } // // Update the microcode patch related fields in CpuMpData // CpuMpData->MicrocodePatchAddress = (UINTN) MicrocodePatchInRam; CpuMpData->MicrocodePatchRegionSize = TotalLoadSize; DEBUG (( DEBUG_INFO, "%a: Required microcode patches have been loaded at 0x%lx, with size 0x%lx.\n", __FUNCTION__, CpuMpData->MicrocodePatchAddress, CpuMpData->MicrocodePatchRegionSize )); return; } /** Shadow the required microcode patches data into memory according to PCD PcdCpuMicrocodePatchAddress and PcdCpuMicrocodePatchRegionSize. @param[in, out] CpuMpData The pointer to CPU MP Data structure. **/ VOID ShadowMicrocodePatchByPcd ( IN OUT CPU_MP_DATA *CpuMpData ) { CPU_MICROCODE_HEADER *MicrocodeEntryPoint; UINTN MicrocodeEnd; UINTN DataSize; UINTN TotalSize; MICROCODE_PATCH_INFO *PatchInfoBuffer; UINTN MaxPatchNumber; UINTN PatchCount; UINTN TotalLoadSize; // // Initialize the microcode patch related fields in CpuMpData as the values // specified by the PCD pair. If the microcode patches are loaded into memory, // these fields will be updated. // CpuMpData->MicrocodePatchAddress = PcdGet64 (PcdCpuMicrocodePatchAddress); CpuMpData->MicrocodePatchRegionSize = PcdGet64 (PcdCpuMicrocodePatchRegionSize); MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (UINTN) CpuMpData->MicrocodePatchAddress; MicrocodeEnd = (UINTN) MicrocodeEntryPoint + (UINTN) CpuMpData->MicrocodePatchRegionSize; if ((MicrocodeEntryPoint == NULL) || ((UINTN) MicrocodeEntryPoint == MicrocodeEnd)) { // // There is no microcode patches // return; } PatchCount = 0; MaxPatchNumber = DEFAULT_MAX_MICROCODE_PATCH_NUM; TotalLoadSize = 0; PatchInfoBuffer = AllocatePool (MaxPatchNumber * sizeof (MICROCODE_PATCH_INFO)); if (PatchInfoBuffer == NULL) { return; } // // Process the header of each microcode patch within the region. // The purpose is to decide which microcode patch(es) will be loaded into memory. // do { if (MicrocodeEntryPoint->HeaderVersion != 0x1) { // // Padding data between the microcode patches, skip 1KB to check next entry. // MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (((UINTN) MicrocodeEntryPoint) + SIZE_1KB); continue; } DataSize = MicrocodeEntryPoint->DataSize; TotalSize = (DataSize == 0) ? 2048 : MicrocodeEntryPoint->TotalSize; if ( (UINTN)MicrocodeEntryPoint > (MAX_ADDRESS - TotalSize) || ((UINTN)MicrocodeEntryPoint + TotalSize) > MicrocodeEnd || (DataSize & 0x3) != 0 || (TotalSize & (SIZE_1KB - 1)) != 0 || TotalSize < DataSize ) { // // Not a valid microcode header, skip 1KB to check next entry. // MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (((UINTN) MicrocodeEntryPoint) + SIZE_1KB); continue; } if (IsMicrocodePatchNeedLoad (CpuMpData, MicrocodeEntryPoint)) { PatchCount++; if (PatchCount > MaxPatchNumber) { // // Current 'PatchInfoBuffer' cannot hold the information, double the size // and allocate a new buffer. // if (MaxPatchNumber > MAX_UINTN / 2 / sizeof (MICROCODE_PATCH_INFO)) { // // Overflow check for MaxPatchNumber // goto OnExit; } PatchInfoBuffer = ReallocatePool ( MaxPatchNumber * sizeof (MICROCODE_PATCH_INFO), 2 * MaxPatchNumber * sizeof (MICROCODE_PATCH_INFO), PatchInfoBuffer ); if (PatchInfoBuffer == NULL) { goto OnExit; } MaxPatchNumber = MaxPatchNumber * 2; } // // Store the information of this microcode patch // PatchInfoBuffer[PatchCount - 1].Address = (UINTN) MicrocodeEntryPoint; PatchInfoBuffer[PatchCount - 1].Size = TotalSize; TotalLoadSize += TotalSize; } // // Process the next microcode patch // MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (((UINTN) MicrocodeEntryPoint) + TotalSize); } while (((UINTN) MicrocodeEntryPoint < MicrocodeEnd)); if (PatchCount != 0) { DEBUG (( DEBUG_INFO, "%a: 0x%x microcode patches will be loaded into memory, with size 0x%x.\n", __FUNCTION__, PatchCount, TotalLoadSize )); ShadowMicrocodePatchWorker (CpuMpData, PatchInfoBuffer, PatchCount, TotalLoadSize); } OnExit: if (PatchInfoBuffer != NULL) { FreePool (PatchInfoBuffer); } return; } /** Shadow the required microcode patches data into memory. @param[in, out] CpuMpData The pointer to CPU MP Data structure. **/ VOID ShadowMicrocodeUpdatePatch ( IN OUT CPU_MP_DATA *CpuMpData ) { EFI_STATUS Status; Status = PlatformShadowMicrocode (CpuMpData); if (EFI_ERROR (Status)) { ShadowMicrocodePatchByPcd (CpuMpData); } } /** Get the cached microcode patch base address and size from the microcode patch information cache HOB. @param[out] Address Base address of the microcode patches data. It will be updated if the microcode patch information cache HOB is found. @param[out] RegionSize Size of the microcode patches data. It will be updated if the microcode patch information cache HOB is found. @retval TRUE The microcode patch information cache HOB is found. @retval FALSE The microcode patch information cache HOB is not found. **/ BOOLEAN GetMicrocodePatchInfoFromHob ( UINT64 *Address, UINT64 *RegionSize ) { EFI_HOB_GUID_TYPE *GuidHob; EDKII_MICROCODE_PATCH_HOB *MicrocodePathHob; GuidHob = GetFirstGuidHob (&gEdkiiMicrocodePatchHobGuid); if (GuidHob == NULL) { DEBUG((DEBUG_INFO, "%a: Microcode patch cache HOB is not found.\n", __FUNCTION__)); return FALSE; } MicrocodePathHob = GET_GUID_HOB_DATA (GuidHob); *Address = MicrocodePathHob->MicrocodePatchAddress; *RegionSize = MicrocodePathHob->MicrocodePatchRegionSize; DEBUG(( DEBUG_INFO, "%a: MicrocodeBase = 0x%lx, MicrocodeSize = 0x%lx\n", __FUNCTION__, *Address, *RegionSize )); return TRUE; }
NaohiroTamura/edk2
OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.h
/** @file This driver installs SMBIOS information for OVMF Copyright (c) 2011, <NAME> <<EMAIL>> Copyright (c) 2011, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef _SMBIOS_PLATFORM_DXE_H_ #define _SMBIOS_PLATFORM_DXE_H_ #include <PiDxe.h> #include <Protocol/Smbios.h> #include <IndustryStandard/SmBios.h> #include <Library/DebugLib.h> #include <Library/BaseLib.h> #include <Library/BaseMemoryLib.h> #include <Library/UefiBootServicesTableLib.h> #include <Library/MemoryAllocationLib.h> /** Locates the Xen SMBIOS data if it exists @return SMBIOS_TABLE_ENTRY_POINT Address of Xen SMBIOS data **/ SMBIOS_TABLE_ENTRY_POINT * GetXenSmbiosTables ( VOID ); /** Locates and extracts the QEMU SMBIOS table data if present in fw_cfg @return Address of extracted QEMU SMBIOS data **/ UINT8 * GetQemuSmbiosTables ( VOID ); #endif
NaohiroTamura/edk2
NetworkPkg/DnsDxe/DnsDhcp.c
/** @file Functions implementation related with DHCPv4/v6 for DNS driver. Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "DnsImpl.h" /** This function initialize the DHCP4 message instance. This function will pad each item of dhcp4 message packet. @param Seed Pointer to the message instance of the DHCP4 packet. @param InterfaceInfo Pointer to the EFI_IP4_CONFIG2_INTERFACE_INFO instance. **/ VOID DnsInitSeedPacket ( OUT EFI_DHCP4_PACKET *Seed, IN EFI_IP4_CONFIG2_INTERFACE_INFO *InterfaceInfo ) { EFI_DHCP4_HEADER *Header; // // Get IfType and HwAddressSize from SNP mode data. // Seed->Size = sizeof (EFI_DHCP4_PACKET); Seed->Length = sizeof (Seed->Dhcp4); Header = &Seed->Dhcp4.Header; ZeroMem (Header, sizeof (EFI_DHCP4_HEADER)); Header->OpCode = DHCP4_OPCODE_REQUEST; Header->HwType = InterfaceInfo->IfType; Header->HwAddrLen = (UINT8) InterfaceInfo->HwAddressSize; CopyMem (Header->ClientHwAddr, &(InterfaceInfo->HwAddress), Header->HwAddrLen); Seed->Dhcp4.Magik = DHCP4_MAGIC; Seed->Dhcp4.Option[0] = DHCP4_TAG_EOP; } /** The common notify function. @param[in] Event The event signaled. @param[in] Context The context. **/ VOID EFIAPI DhcpCommonNotify ( IN EFI_EVENT Event, IN VOID *Context ) { if ((Event == NULL) || (Context == NULL)) { return ; } *((BOOLEAN *) Context) = TRUE; } /** Parse the ACK to get required information @param Dhcp4 The DHCP4 protocol. @param Packet Packet waiting for parse. @param DnsServerInfor The required Dns4 server information. @retval EFI_SUCCESS The DNS information is got from the DHCP ACK. @retval EFI_NO_MAPPING DHCP failed to acquire address and other information. @retval EFI_DEVICE_ERROR Other errors as indicated. @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. **/ EFI_STATUS ParseDhcp4Ack ( IN EFI_DHCP4_PROTOCOL *Dhcp4, IN EFI_DHCP4_PACKET *Packet, IN DNS4_SERVER_INFOR *DnsServerInfor ) { EFI_STATUS Status; UINT32 OptionCount; EFI_DHCP4_PACKET_OPTION **OptionList; UINT32 ServerCount; EFI_IPv4_ADDRESS *ServerList; UINT32 Index; UINT32 Count; ServerCount = 0; ServerList = NULL; OptionCount = 0; OptionList = NULL; Status = Dhcp4->Parse (Dhcp4, Packet, &OptionCount, OptionList); if (Status != EFI_BUFFER_TOO_SMALL) { return EFI_DEVICE_ERROR; } OptionList = AllocatePool (OptionCount * sizeof (EFI_DHCP4_PACKET_OPTION *)); if (OptionList == NULL) { return EFI_OUT_OF_RESOURCES; } Status = Dhcp4->Parse (Dhcp4, Packet, &OptionCount, OptionList); if (EFI_ERROR (Status)) { gBS->FreePool (OptionList); return EFI_DEVICE_ERROR; } Status = EFI_NOT_FOUND; for (Index = 0; Index < OptionCount; Index++) { // // Get DNS server addresses // if (OptionList[Index]->OpCode == DHCP4_TAG_DNS_SERVER) { if (((OptionList[Index]->Length & 0x3) != 0) || (OptionList[Index]->Length == 0)) { Status = EFI_DEVICE_ERROR; break; } ServerCount = OptionList[Index]->Length/4; ServerList = AllocatePool (ServerCount * sizeof (EFI_IPv4_ADDRESS)); if (ServerList == NULL) { return EFI_OUT_OF_RESOURCES; } for(Count=0; Count < ServerCount; Count++){ CopyMem (ServerList + Count, &OptionList[Index]->Data[4 * Count], sizeof (EFI_IPv4_ADDRESS)); } *(DnsServerInfor->ServerCount) = ServerCount; DnsServerInfor->ServerList = ServerList; Status = EFI_SUCCESS; } } gBS->FreePool (OptionList); return Status; } /** EFI_DHCP6_INFO_CALLBACK is provided by the consumer of the EFI DHCPv6 Protocol instance to intercept events that occurs in the DHCPv6 Information Request exchange process. @param This Pointer to the EFI_DHCP6_PROTOCOL instance that is used to configure this callback function. @param Context Pointer to the context that is initialized in the EFI_DHCP6_PROTOCOL.InfoRequest(). @param Packet Pointer to Reply packet that has been received. The EFI DHCPv6 Protocol instance is responsible for freeing the buffer. @retval EFI_SUCCESS The DNS information is got from the DHCP ACK. @retval EFI_DEVICE_ERROR Other errors as indicated. @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. **/ EFI_STATUS EFIAPI ParseDhcp6Ack ( IN EFI_DHCP6_PROTOCOL *This, IN VOID *Context, IN EFI_DHCP6_PACKET *Packet ) { EFI_STATUS Status; UINT32 OptionCount; EFI_DHCP6_PACKET_OPTION **OptionList; DNS6_SERVER_INFOR *DnsServerInfor; UINT32 ServerCount; EFI_IPv6_ADDRESS *ServerList; UINT32 Index; UINT32 Count; OptionCount = 0; ServerCount = 0; ServerList = NULL; Status = This->Parse (This, Packet, &OptionCount, NULL); if (Status != EFI_BUFFER_TOO_SMALL) { return EFI_DEVICE_ERROR; } OptionList = AllocateZeroPool (OptionCount * sizeof (EFI_DHCP6_PACKET_OPTION *)); if (OptionList == NULL) { return EFI_OUT_OF_RESOURCES; } Status = This->Parse (This, Packet, &OptionCount, OptionList); if (EFI_ERROR (Status)) { gBS->FreePool (OptionList); return EFI_DEVICE_ERROR; } DnsServerInfor = (DNS6_SERVER_INFOR *) Context; for (Index = 0; Index < OptionCount; Index++) { OptionList[Index]->OpCode = NTOHS (OptionList[Index]->OpCode); OptionList[Index]->OpLen = NTOHS (OptionList[Index]->OpLen); // // Get DNS server addresses from this reply packet. // if (OptionList[Index]->OpCode == DHCP6_TAG_DNS_SERVER) { if (((OptionList[Index]->OpLen & 0xf) != 0) || (OptionList[Index]->OpLen == 0)) { Status = EFI_DEVICE_ERROR; gBS->FreePool (OptionList); return Status; } ServerCount = OptionList[Index]->OpLen/16; ServerList = AllocatePool (ServerCount * sizeof (EFI_IPv6_ADDRESS)); if (ServerList == NULL) { gBS->FreePool (OptionList); return EFI_OUT_OF_RESOURCES; } for(Count=0; Count < ServerCount; Count++){ CopyMem (ServerList + Count, &OptionList[Index]->Data[16 * Count], sizeof (EFI_IPv6_ADDRESS)); } *(DnsServerInfor->ServerCount) = ServerCount; DnsServerInfor->ServerList = ServerList; } } gBS->FreePool (OptionList); return Status; } /** Parse the DHCP ACK to get Dns4 server information. @param Instance The DNS instance. @param DnsServerCount Retrieved Dns4 server Ip count. @param DnsServerList Retrieved Dns4 server Ip list. @retval EFI_SUCCESS The Dns4 information is got from the DHCP ACK. @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. @retval EFI_NO_MEDIA There was a media error. @retval Others Other errors as indicated. **/ EFI_STATUS GetDns4ServerFromDhcp4 ( IN DNS_INSTANCE *Instance, OUT UINT32 *DnsServerCount, OUT EFI_IPv4_ADDRESS **DnsServerList ) { EFI_STATUS Status; EFI_HANDLE Image; EFI_HANDLE Controller; EFI_STATUS MediaStatus; EFI_HANDLE MnpChildHandle; EFI_MANAGED_NETWORK_PROTOCOL *Mnp; EFI_MANAGED_NETWORK_CONFIG_DATA MnpConfigData; EFI_HANDLE Dhcp4Handle; EFI_DHCP4_PROTOCOL *Dhcp4; EFI_IP4_CONFIG2_PROTOCOL *Ip4Config2; UINTN DataSize; VOID *Data; EFI_IP4_CONFIG2_INTERFACE_INFO *InterfaceInfo; EFI_DHCP4_PACKET SeedPacket; EFI_DHCP4_PACKET_OPTION *ParaList[2]; DNS4_SERVER_INFOR DnsServerInfor; EFI_DHCP4_TRANSMIT_RECEIVE_TOKEN Token; BOOLEAN IsDone; UINTN Index; Image = Instance->Service->ImageHandle; Controller = Instance->Service->ControllerHandle; MnpChildHandle = NULL; Mnp = NULL; Dhcp4Handle = NULL; Dhcp4 = NULL; Ip4Config2 = NULL; DataSize = 0; Data = NULL; InterfaceInfo = NULL; ZeroMem ((UINT8 *) ParaList, sizeof (ParaList)); ZeroMem (&MnpConfigData, sizeof (EFI_MANAGED_NETWORK_CONFIG_DATA)); ZeroMem (&DnsServerInfor, sizeof (DNS4_SERVER_INFOR)); ZeroMem (&Token, sizeof (EFI_DHCP4_TRANSMIT_RECEIVE_TOKEN)); DnsServerInfor.ServerCount = DnsServerCount; IsDone = FALSE; // // Check media. // MediaStatus = EFI_SUCCESS; NetLibDetectMediaWaitTimeout (Controller, DNS_CHECK_MEDIA_GET_DHCP_WAITING_TIME, &MediaStatus); if (MediaStatus != EFI_SUCCESS) { return EFI_NO_MEDIA; } // // Create a Mnp child instance, get the protocol and config for it. // Status = NetLibCreateServiceChild ( Controller, Image, &gEfiManagedNetworkServiceBindingProtocolGuid, &MnpChildHandle ); if (EFI_ERROR (Status)) { return Status; } Status = gBS->OpenProtocol ( MnpChildHandle, &gEfiManagedNetworkProtocolGuid, (VOID **) &Mnp, Image, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER ); if (EFI_ERROR (Status)) { goto ON_EXIT; } MnpConfigData.ReceivedQueueTimeoutValue = 0; MnpConfigData.TransmitQueueTimeoutValue = 0; MnpConfigData.ProtocolTypeFilter = IP4_ETHER_PROTO; MnpConfigData.EnableUnicastReceive = TRUE; MnpConfigData.EnableMulticastReceive = TRUE; MnpConfigData.EnableBroadcastReceive = TRUE; MnpConfigData.EnablePromiscuousReceive = FALSE; MnpConfigData.FlushQueuesOnReset = TRUE; MnpConfigData.EnableReceiveTimestamps = FALSE; MnpConfigData.DisableBackgroundPolling = FALSE; Status = Mnp->Configure(Mnp, &MnpConfigData); if (EFI_ERROR (Status)) { goto ON_EXIT; } // // Create a DHCP4 child instance and get the protocol. // Status = NetLibCreateServiceChild ( Controller, Image, &gEfiDhcp4ServiceBindingProtocolGuid, &Dhcp4Handle ); if (EFI_ERROR (Status)) { goto ON_EXIT; } Status = gBS->OpenProtocol ( Dhcp4Handle, &gEfiDhcp4ProtocolGuid, (VOID **) &Dhcp4, Image, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER ); if (EFI_ERROR (Status)) { goto ON_EXIT; } // // Get Ip4Config2 instance info. // Status = gBS->HandleProtocol (Controller, &gEfiIp4Config2ProtocolGuid, (VOID **) &Ip4Config2); if (EFI_ERROR (Status)) { goto ON_EXIT; } Status = Ip4Config2->GetData (Ip4Config2, Ip4Config2DataTypeInterfaceInfo, &DataSize, Data); if (EFI_ERROR (Status) && Status != EFI_BUFFER_TOO_SMALL) { goto ON_EXIT; } Data = AllocateZeroPool (DataSize); if (Data == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ON_EXIT; } Status = Ip4Config2->GetData (Ip4Config2, Ip4Config2DataTypeInterfaceInfo, &DataSize, Data); if (EFI_ERROR (Status)) { goto ON_EXIT; } InterfaceInfo = (EFI_IP4_CONFIG2_INTERFACE_INFO *)Data; // // Build required Token. // Status = gBS->CreateEvent ( EVT_NOTIFY_SIGNAL, TPL_NOTIFY, DhcpCommonNotify, &IsDone, &Token.CompletionEvent ); if (EFI_ERROR (Status)) { goto ON_EXIT; } SetMem (&Token.RemoteAddress, sizeof (EFI_IPv4_ADDRESS), 0xff); Token.RemotePort = 67; Token.ListenPointCount = 1; Token.ListenPoints = AllocateZeroPool (Token.ListenPointCount * sizeof (EFI_DHCP4_LISTEN_POINT)); if (Token.ListenPoints == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ON_EXIT; } if (Instance->Dns4CfgData.UseDefaultSetting) { CopyMem (&(Token.ListenPoints[0].ListenAddress), &(InterfaceInfo->StationAddress), sizeof (EFI_IPv4_ADDRESS)); CopyMem (&(Token.ListenPoints[0].SubnetMask), &(InterfaceInfo->SubnetMask), sizeof (EFI_IPv4_ADDRESS)); } else { CopyMem (&(Token.ListenPoints[0].ListenAddress), &(Instance->Dns4CfgData.StationIp), sizeof (EFI_IPv4_ADDRESS)); CopyMem (&(Token.ListenPoints[0].SubnetMask), &(Instance->Dns4CfgData.SubnetMask), sizeof (EFI_IPv4_ADDRESS)); } Token.ListenPoints[0].ListenPort = 68; Token.TimeoutValue = DNS_TIME_TO_GETMAP; DnsInitSeedPacket (&SeedPacket, InterfaceInfo); ParaList[0] = AllocateZeroPool (sizeof (EFI_DHCP4_PACKET_OPTION)); if (ParaList[0] == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ON_EXIT; } ParaList[0]->OpCode = DHCP4_TAG_TYPE; ParaList[0]->Length = 1; ParaList[0]->Data[0] = DHCP4_MSG_REQUEST; ParaList[1] = AllocateZeroPool (sizeof (EFI_DHCP4_PACKET_OPTION)); if (ParaList[1] == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ON_EXIT; } ParaList[1]->OpCode = DHCP4_TAG_PARA_LIST; ParaList[1]->Length = 1; ParaList[1]->Data[0] = DHCP4_TAG_DNS_SERVER; Status = Dhcp4->Build (Dhcp4, &SeedPacket, 0, NULL, 2, ParaList, &Token.Packet); Token.Packet->Dhcp4.Header.Xid = HTONL(NET_RANDOM (NetRandomInitSeed ())); Token.Packet->Dhcp4.Header.Reserved = HTONS ((UINT16)0x8000); if (Instance->Dns4CfgData.UseDefaultSetting) { CopyMem (&(Token.Packet->Dhcp4.Header.ClientAddr), &(InterfaceInfo->StationAddress), sizeof (EFI_IPv4_ADDRESS)); } else { CopyMem (&(Token.Packet->Dhcp4.Header.ClientAddr), &(Instance->Dns4CfgData.StationIp), sizeof (EFI_IPv4_ADDRESS)); } CopyMem (Token.Packet->Dhcp4.Header.ClientHwAddr, &(InterfaceInfo->HwAddress), InterfaceInfo->HwAddressSize); Token.Packet->Dhcp4.Header.HwAddrLen = (UINT8)(InterfaceInfo->HwAddressSize); // // TransmitReceive Token // Status = Dhcp4->TransmitReceive (Dhcp4, &Token); if (EFI_ERROR (Status)) { goto ON_EXIT; } // // Poll the packet // do { Status = Mnp->Poll (Mnp); } while (!IsDone); // // Parse the ACK to get required information if received done. // if (IsDone && !EFI_ERROR (Token.Status)) { for (Index = 0; Index < Token.ResponseCount; Index++) { Status = ParseDhcp4Ack (Dhcp4, &Token.ResponseList[Index], &DnsServerInfor); if (!EFI_ERROR (Status)) { break; } } *DnsServerList = DnsServerInfor.ServerList; } else { Status = Token.Status; } ON_EXIT: if (Data != NULL) { FreePool (Data); } for (Index = 0; Index < 2; Index++) { if (ParaList[Index] != NULL) { FreePool (ParaList[Index]); } } if (Token.ListenPoints) { FreePool (Token.ListenPoints); } if (Token.Packet) { FreePool (Token.Packet); } if (Token.ResponseList != NULL) { FreePool (Token.ResponseList); } if (Token.CompletionEvent != NULL) { gBS->CloseEvent (Token.CompletionEvent); } if (Dhcp4 != NULL) { Dhcp4->Stop (Dhcp4); Dhcp4->Configure (Dhcp4, NULL); gBS->CloseProtocol ( Dhcp4Handle, &gEfiDhcp4ProtocolGuid, Image, Controller ); } if (Dhcp4Handle != NULL) { NetLibDestroyServiceChild ( Controller, Image, &gEfiDhcp4ServiceBindingProtocolGuid, Dhcp4Handle ); } if (Mnp != NULL) { Mnp->Configure (Mnp, NULL); gBS->CloseProtocol ( MnpChildHandle, &gEfiManagedNetworkProtocolGuid, Image, Controller ); } NetLibDestroyServiceChild ( Controller, Image, &gEfiManagedNetworkServiceBindingProtocolGuid, MnpChildHandle ); return Status; } /** Parse the DHCP ACK to get Dns6 server information. @param Image The handle of the driver image. @param Controller The handle of the controller. @param DnsServerCount Retrieved Dns6 server Ip count. @param DnsServerList Retrieved Dns6 server Ip list. @retval EFI_SUCCESS The Dns6 information is got from the DHCP ACK. @retval EFI_OUT_OF_RESOURCES Failed to allocate memory. @retval EFI_NO_MEDIA There was a media error. @retval Others Other errors as indicated. **/ EFI_STATUS GetDns6ServerFromDhcp6 ( IN EFI_HANDLE Image, IN EFI_HANDLE Controller, OUT UINT32 *DnsServerCount, OUT EFI_IPv6_ADDRESS **DnsServerList ) { EFI_HANDLE Dhcp6Handle; EFI_DHCP6_PROTOCOL *Dhcp6; EFI_STATUS Status; EFI_STATUS TimerStatus; EFI_DHCP6_PACKET_OPTION *Oro; EFI_DHCP6_RETRANSMISSION InfoReqReXmit; EFI_EVENT Timer; EFI_STATUS MediaStatus; DNS6_SERVER_INFOR DnsServerInfor; Dhcp6Handle = NULL; Dhcp6 = NULL; Oro = NULL; Timer = NULL; ZeroMem (&DnsServerInfor, sizeof (DNS6_SERVER_INFOR)); DnsServerInfor.ServerCount = DnsServerCount; // // Check media status before doing DHCP. // MediaStatus = EFI_SUCCESS; NetLibDetectMediaWaitTimeout (Controller, DNS_CHECK_MEDIA_GET_DHCP_WAITING_TIME, &MediaStatus); if (MediaStatus != EFI_SUCCESS) { return EFI_NO_MEDIA; } // // Create a DHCP6 child instance and get the protocol. // Status = NetLibCreateServiceChild ( Controller, Image, &gEfiDhcp6ServiceBindingProtocolGuid, &Dhcp6Handle ); if (EFI_ERROR (Status)) { return Status; } Status = gBS->OpenProtocol ( Dhcp6Handle, &gEfiDhcp6ProtocolGuid, (VOID **) &Dhcp6, Image, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER ); if (EFI_ERROR (Status)) { goto ON_EXIT; } Oro = AllocateZeroPool (sizeof (EFI_DHCP6_PACKET_OPTION) + 1); if (Oro == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ON_EXIT; } // // Ask the server to reply with DNS options. // All members in EFI_DHCP6_PACKET_OPTION are in network order. // Oro->OpCode = HTONS (DHCP6_TAG_DNS_REQUEST); Oro->OpLen = HTONS (2); Oro->Data[1] = DHCP6_TAG_DNS_SERVER; InfoReqReXmit.Irt = 4; InfoReqReXmit.Mrc = 1; InfoReqReXmit.Mrt = 10; InfoReqReXmit.Mrd = 30; Status = Dhcp6->InfoRequest ( Dhcp6, TRUE, Oro, 0, NULL, &InfoReqReXmit, NULL, ParseDhcp6Ack, &DnsServerInfor ); if (Status == EFI_NO_MAPPING) { Status = gBS->CreateEvent (EVT_TIMER, TPL_CALLBACK, NULL, NULL, &Timer); if (EFI_ERROR (Status)) { goto ON_EXIT; } Status = gBS->SetTimer ( Timer, TimerRelative, DNS_TIME_TO_GETMAP * TICKS_PER_SECOND ); if (EFI_ERROR (Status)) { goto ON_EXIT; } do { TimerStatus = gBS->CheckEvent (Timer); if (!EFI_ERROR (TimerStatus)) { Status = Dhcp6->InfoRequest ( Dhcp6, TRUE, Oro, 0, NULL, &InfoReqReXmit, NULL, ParseDhcp6Ack, &DnsServerInfor ); } } while (TimerStatus == EFI_NOT_READY); } *DnsServerList = DnsServerInfor.ServerList; ON_EXIT: if (Oro != NULL) { FreePool (Oro); } if (Timer != NULL) { gBS->CloseEvent (Timer); } if (Dhcp6 != NULL) { gBS->CloseProtocol ( Dhcp6Handle, &gEfiDhcp6ProtocolGuid, Image, Controller ); } NetLibDestroyServiceChild ( Controller, Image, &gEfiDhcp6ServiceBindingProtocolGuid, Dhcp6Handle ); return Status; }
NaohiroTamura/edk2
MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/CpuArch.h
/* CpuArch.h -- CPU specific code 2017-09-04 : <NAME> : Public domain */ #ifndef __CPU_ARCH_H #define __CPU_ARCH_H #include "7zTypes.h" EXTERN_C_BEGIN /* MY_CPU_LE means that CPU is LITTLE ENDIAN. MY_CPU_BE means that CPU is BIG ENDIAN. If MY_CPU_LE and MY_CPU_BE are not defined, we don't know about ENDIANNESS of platform. MY_CPU_LE_UNALIGN means that CPU is LITTLE ENDIAN and CPU supports unaligned memory accesses. */ #if defined(_M_X64) \ || defined(_M_AMD64) \ || defined(__x86_64__) \ || defined(__AMD64__) \ || defined(__amd64__) #define MY_CPU_AMD64 #ifdef __ILP32__ #define MY_CPU_NAME "x32" #else #define MY_CPU_NAME "x64" #endif #define MY_CPU_64BIT #endif #if defined(_M_IX86) \ || defined(__i386__) #define MY_CPU_X86 #define MY_CPU_NAME "x86" #define MY_CPU_32BIT #endif #if defined(_M_ARM64) \ || defined(__AARCH64EL__) \ || defined(__AARCH64EB__) \ || defined(__aarch64__) #define MY_CPU_ARM64 #define MY_CPU_NAME "arm64" #define MY_CPU_64BIT #endif #if defined(_M_ARM) \ || defined(_M_ARM_NT) \ || defined(_M_ARMT) \ || defined(__arm__) \ || defined(__thumb__) \ || defined(__ARMEL__) \ || defined(__ARMEB__) \ || defined(__THUMBEL__) \ || defined(__THUMBEB__) #define MY_CPU_ARM #define MY_CPU_NAME "arm" #define MY_CPU_32BIT #endif #if defined(_M_IA64) \ || defined(__ia64__) #define MY_CPU_IA64 #define MY_CPU_NAME "ia64" #define MY_CPU_64BIT #endif #if defined(__mips64) \ || defined(__mips64__) \ || (defined(__mips) && (__mips == 64 || __mips == 4 || __mips == 3)) #define MY_CPU_NAME "mips64" #define MY_CPU_64BIT #elif defined(__mips__) #define MY_CPU_NAME "mips" /* #define MY_CPU_32BIT */ #endif #if defined(__ppc64__) \ || defined(__powerpc64__) #ifdef __ILP32__ #define MY_CPU_NAME "ppc64-32" #else #define MY_CPU_NAME "ppc64" #endif #define MY_CPU_64BIT #elif defined(__ppc__) \ || defined(__powerpc__) #define MY_CPU_NAME "ppc" #define MY_CPU_32BIT #endif #if defined(__sparc64__) #define MY_CPU_NAME "sparc64" #define MY_CPU_64BIT #elif defined(__sparc__) #define MY_CPU_NAME "sparc" /* #define MY_CPU_32BIT */ #endif #if defined(MY_CPU_X86) || defined(MY_CPU_AMD64) #define MY_CPU_X86_OR_AMD64 #endif #ifdef _WIN32 #ifdef MY_CPU_ARM #define MY_CPU_ARM_LE #endif #ifdef MY_CPU_ARM64 #define MY_CPU_ARM64_LE #endif #ifdef _M_IA64 #define MY_CPU_IA64_LE #endif #endif #if defined(MY_CPU_X86_OR_AMD64) \ || defined(MY_CPU_ARM_LE) \ || defined(MY_CPU_ARM64_LE) \ || defined(MY_CPU_IA64_LE) \ || defined(__LITTLE_ENDIAN__) \ || defined(__ARMEL__) \ || defined(__THUMBEL__) \ || defined(__AARCH64EL__) \ || defined(__MIPSEL__) \ || defined(__MIPSEL) \ || defined(_MIPSEL) \ || defined(__BFIN__) \ || (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) #define MY_CPU_LE #endif #if defined(__BIG_ENDIAN__) \ || defined(__ARMEB__) \ || defined(__THUMBEB__) \ || defined(__AARCH64EB__) \ || defined(__MIPSEB__) \ || defined(__MIPSEB) \ || defined(_MIPSEB) \ || defined(__m68k__) \ || defined(__s390__) \ || defined(__s390x__) \ || defined(__zarch__) \ || (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)) #define MY_CPU_BE #endif #if defined(MY_CPU_LE) && defined(MY_CPU_BE) #error Stop_Compiling_Bad_Endian #endif #if defined(MY_CPU_32BIT) && defined(MY_CPU_64BIT) #error Stop_Compiling_Bad_32_64_BIT #endif #ifndef MY_CPU_NAME #ifdef MY_CPU_LE #define MY_CPU_NAME "LE" #elif defined(MY_CPU_BE) #define MY_CPU_NAME "BE" #else /* #define MY_CPU_NAME "" */ #endif #endif #ifdef MY_CPU_LE #if defined(MY_CPU_X86_OR_AMD64) \ || defined(MY_CPU_ARM64) \ || defined(__ARM_FEATURE_UNALIGNED) #define MY_CPU_LE_UNALIGN #endif #endif #ifdef MY_CPU_LE_UNALIGN #define GetUi16(p) (*(const UInt16 *)(const void *)(p)) #define GetUi32(p) (*(const UInt32 *)(const void *)(p)) #define GetUi64(p) (*(const UInt64 *)(const void *)(p)) #define SetUi16(p, v) { *(UInt16 *)(p) = (v); } #define SetUi32(p, v) { *(UInt32 *)(p) = (v); } #define SetUi64(p, v) { *(UInt64 *)(p) = (v); } #else #define GetUi16(p) ( (UInt16) ( \ ((const Byte *)(p))[0] | \ ((UInt16)((const Byte *)(p))[1] << 8) )) #define GetUi32(p) ( \ ((const Byte *)(p))[0] | \ ((UInt32)((const Byte *)(p))[1] << 8) | \ ((UInt32)((const Byte *)(p))[2] << 16) | \ ((UInt32)((const Byte *)(p))[3] << 24)) #define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte *)(p)) + 4) << 32)) #define SetUi16(p, v) { Byte *_ppp_ = (Byte *)(p); UInt32 _vvv_ = (v); \ _ppp_[0] = (Byte)_vvv_; \ _ppp_[1] = (Byte)(_vvv_ >> 8); } #define SetUi32(p, v) { Byte *_ppp_ = (Byte *)(p); UInt32 _vvv_ = (v); \ _ppp_[0] = (Byte)_vvv_; \ _ppp_[1] = (Byte)(_vvv_ >> 8); \ _ppp_[2] = (Byte)(_vvv_ >> 16); \ _ppp_[3] = (Byte)(_vvv_ >> 24); } #define SetUi64(p, v) { Byte *_ppp2_ = (Byte *)(p); UInt64 _vvv2_ = (v); \ SetUi32(_ppp2_ , (UInt32)_vvv2_); \ SetUi32(_ppp2_ + 4, (UInt32)(_vvv2_ >> 32)); } #endif #ifdef __has_builtin #define MY__has_builtin(x) __has_builtin(x) #else #define MY__has_builtin(x) 0 #endif #if defined(MY_CPU_LE_UNALIGN) && /* defined(_WIN64) && */ (_MSC_VER >= 1300) /* Note: we use bswap instruction, that is unsupported in 386 cpu */ #include <stdlib.h> #pragma intrinsic(_byteswap_ushort) #pragma intrinsic(_byteswap_ulong) #pragma intrinsic(_byteswap_uint64) /* #define GetBe16(p) _byteswap_ushort(*(const UInt16 *)(const Byte *)(p)) */ #define GetBe32(p) _byteswap_ulong(*(const UInt32 *)(const Byte *)(p)) #define GetBe64(p) _byteswap_uint64(*(const UInt64 *)(const Byte *)(p)) #define SetBe32(p, v) (*(UInt32 *)(void *)(p)) = _byteswap_ulong(v) #elif defined(MY_CPU_LE_UNALIGN) && ( \ (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) \ || (defined(__clang__) && MY__has_builtin(__builtin_bswap16)) ) /* #define GetBe16(p) __builtin_bswap16(*(const UInt16 *)(const Byte *)(p)) */ #define GetBe32(p) __builtin_bswap32(*(const UInt32 *)(const Byte *)(p)) #define GetBe64(p) __builtin_bswap64(*(const UInt64 *)(const Byte *)(p)) #define SetBe32(p, v) (*(UInt32 *)(void *)(p)) = __builtin_bswap32(v) #else #define GetBe32(p) ( \ ((UInt32)((const Byte *)(p))[0] << 24) | \ ((UInt32)((const Byte *)(p))[1] << 16) | \ ((UInt32)((const Byte *)(p))[2] << 8) | \ ((const Byte *)(p))[3] ) #define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4)) #define SetBe32(p, v) { Byte *_ppp_ = (Byte *)(p); UInt32 _vvv_ = (v); \ _ppp_[0] = (Byte)(_vvv_ >> 24); \ _ppp_[1] = (Byte)(_vvv_ >> 16); \ _ppp_[2] = (Byte)(_vvv_ >> 8); \ _ppp_[3] = (Byte)_vvv_; } #endif #ifndef GetBe16 #define GetBe16(p) ( (UInt16) ( \ ((UInt16)((const Byte *)(p))[0] << 8) | \ ((const Byte *)(p))[1] )) #endif #ifdef MY_CPU_X86_OR_AMD64 typedef struct { UInt32 maxFunc; UInt32 vendor[3]; UInt32 ver; UInt32 b; UInt32 c; UInt32 d; } Cx86cpuid; enum { CPU_FIRM_INTEL, CPU_FIRM_AMD, CPU_FIRM_VIA }; void MyCPUID(UInt32 function, UInt32 *a, UInt32 *b, UInt32 *c, UInt32 *d); Bool x86cpuid_CheckAndRead(Cx86cpuid *p); int x86cpuid_GetFirm(const Cx86cpuid *p); #define x86cpuid_GetFamily(ver) (((ver >> 16) & 0xFF0) | ((ver >> 8) & 0xF)) #define x86cpuid_GetModel(ver) (((ver >> 12) & 0xF0) | ((ver >> 4) & 0xF)) #define x86cpuid_GetStepping(ver) (ver & 0xF) Bool CPU_Is_InOrder(); Bool CPU_Is_Aes_Supported(); #endif EXTERN_C_END #endif
NaohiroTamura/edk2
MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEntryPoint.c
/** @file Entry point to a Standalone MM driver. Copyright (c) 2015, Intel Corporation. All rights reserved.<BR> Copyright (c) 2016 - 2018, ARM Ltd. All rights reserved.<BR> Copyright (c) 2018, Linaro, Limited. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <PiMm.h> #include <Library/BaseLib.h> #include <Library/DebugLib.h> #include <Library/MmServicesTableLib.h> #include <Library/StandaloneMmDriverEntryPoint.h> /** The entry point of PE/COFF Image for a Standalone MM Driver. This function is the entry point for a Standalone MM Driver. This function must call ProcessLibraryConstructorList() and ProcessModuleEntryPointList(). If the return status from ProcessModuleEntryPointList() is an error status, then ProcessLibraryDestructorList() must be called. The return value from ProcessModuleEntryPointList() is returned. If _gMmRevision is not zero and SystemTable->Hdr.Revision is less than _gMmRevision, then return EFI_INCOMPATIBLE_VERSION. @param ImageHandle The image handle of the Standalone MM Driver. @param MmSystemTable A pointer to the MM System Table. @retval EFI_SUCCESS The Standalone MM Driver exited normally. @retval EFI_INCOMPATIBLE_VERSION _gMmRevision is greater than MmSystemTable->Hdr.Revision. @retval Other Return value from ProcessModuleEntryPointList(). **/ EFI_STATUS EFIAPI _ModuleEntryPoint ( IN EFI_HANDLE ImageHandle, IN IN EFI_MM_SYSTEM_TABLE *MmSystemTable ) { EFI_STATUS Status; if (_gMmRevision != 0) { // // Make sure that the MM spec revision of the platform // is >= MM spec revision of the driver // if (MmSystemTable->Hdr.Revision < _gMmRevision) { return EFI_INCOMPATIBLE_VERSION; } } // // Call constructor for all libraries // ProcessLibraryConstructorList (ImageHandle, MmSystemTable); // // Call the driver entry point // Status = ProcessModuleEntryPointList (ImageHandle, MmSystemTable); // // If all of the drivers returned errors, then invoke all of the library destructors // if (EFI_ERROR (Status)) { ProcessLibraryDestructorList (ImageHandle, MmSystemTable); } // // Return the cumulative return status code from all of the driver entry points // return Status; }
NaohiroTamura/edk2
MdePkg/Library/BaseLib/CpuDeadLoop.c
/** @file Base Library CPU Functions for all architectures. Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <Base.h> #include <Library/BaseLib.h> /** Executes an infinite loop. Forces the CPU to execute an infinite loop. A debugger may be used to skip past the loop and the code that follows the loop must execute properly. This implies that the infinite loop must not cause the code that follow it to be optimized away. **/ VOID EFIAPI CpuDeadLoop ( VOID ) { volatile UINTN Index; for (Index = 0; Index == 0;); }
daikiclimate/Grid-Anchor-based-Image-Cropping-Pytorch
roi_align/src/roi_align.h
<reponame>daikiclimate/Grid-Anchor-based-Image-Cropping-Pytorch #ifndef ROI_ALIGN_H #define ROI_ALIGN_H #include<torch/extension.h> int roi_align_forward(int aligned_height, int aligned_width, float spatial_scale, torch::Tensor features, torch::Tensor rois, torch::Tensor output); int roi_align_backward(int aligned_height, int aligned_width, float spatial_scale, torch::Tensor top_grad, torch::Tensor rois, torch::Tensor bottom_grad); #endif
daikiclimate/Grid-Anchor-based-Image-Cropping-Pytorch
roi_align/src/roi_align_cuda.h
<reponame>daikiclimate/Grid-Anchor-based-Image-Cropping-Pytorch #ifndef ROI_ALIGN_CUDA_H #define ROI_ALIGN_CUDA_H #include <torch/extension.h> int roi_align_forward_cuda(int aligned_height, int aligned_width, float spatial_scale, torch::Tensor features, torch::Tensor rois, torch::Tensor output); int roi_align_backward_cuda(int aligned_height, int aligned_width, float spatial_scale, torch::Tensor top_grad, torch::Tensor rois, torch::Tensor bottom_grad); #endif
daikiclimate/Grid-Anchor-based-Image-Cropping-Pytorch
rod_align/src/rod_align_cuda.h
<reponame>daikiclimate/Grid-Anchor-based-Image-Cropping-Pytorch #ifndef ROD_ALIGN_CUDA_H #define ROD_ALIGN_CUDA_H #include <torch/extension.h> int rod_align_forward_cuda(int aligned_height, int aligned_width, float spatial_scale, torch::Tensor features, torch::Tensor rois, torch::Tensor output); int rod_align_backward_cuda(int aligned_height, int aligned_width, float spatial_scale, torch::Tensor top_grad, torch::Tensor rois, torch::Tensor bottom_grad); #endif
taqu/BalancingTree
common.h
#ifndef INC_TREE_COMMON_H__ #define INC_TREE_COMMON_H__ /** @file common.h @author t-sakai @date 2017/05/14 create */ #include <cassert> #include <cstring> #include <utility> #include <cstdint> #include <malloc.h> #ifndef NULL #ifdef __cplusplus #define NULL 0 #else #define NULL ((void*)0) #endif #endif #define TASSERT(exp) assert(exp) #define TNEW new #define TPLACEMENT_NEW(ptr) new(ptr) #define TDELETE(ptr) delete (ptr); (ptr)=NULL #define TDELETE_RAW(ptr) delete (ptr) #define TDELETE_ARRAY(ptr) delete[] (ptr); (ptr)=NULL namespace tree { //--------------------------------------------------------- #if defined(_MSC_VER) typedef char Char; typedef unsigned char UChar; typedef __int8 s8; typedef __int16 s16; typedef __int32 s32; typedef __int64 s64; typedef unsigned __int8 u8; typedef unsigned __int16 u16; typedef unsigned __int32 u32; typedef unsigned __int64 u64; typedef float f32; typedef double f64; typedef intptr_t intptr_t; typedef uintptr_t uintptr_t; typedef ptrdiff_t ptrdiff_t; typedef size_t size_t; #elif defined(__GNUC__) typedef char Char; typedef unsigned char UChar; typedef int8_t s8; typedef int16_t s16; typedef int32_t s32; typedef int64_t s64; typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64; typedef float f32; typedef double f64; typedef intptr_t intptr_t; typedef uintptr_t uintptr_t; typedef ptrdiff_t ptrdiff_t; typedef size_t size_t; #else typedef char Char; typedef unsigned char UChar; typedef char s8; typedef short s16; typedef long s32; typedef long long s64; typedef unsigned char u8; typedef unsigned short u16; typedef unsigned long u32; typedef unsigned long long u64; typedef float f32; typedef double f64; typedef intptr_t intptr_t; typedef uintptr_t uintptr_t; typedef ptrdiff_t ptrdiff_t; typedef size_t lsize_t; #endif using std::move; template<class T> void swap(T& x0, T& x1) { T t(move(x0)); x0 = move(x1); x1 = move(t); } //--------------------------------------------------------- struct DefaultAllocator { static inline void* malloc(u32 size) { return ::malloc(size); } static inline void free(void* mem) { ::free(mem); } }; #define TALLOCATOR_MALLOC(allocator, size) allocator::malloc(size) #define TALLOCATOR_FREE(allocator, ptr) allocator::free((ptr));(ptr)=NULL template<class T> struct DefaultComparator { /** v0<v1 : <0 v0==v1 : 0 v0>v1 : >0 */ s32 operator()(const T& v0, const T& v1) const { return (v0==v1)? 0 : ((v0<v1)? -1 : 1); } }; template<class T> struct DefaultTraversal { void operator()(T& v0) { } }; } #endif //INC_TREE_COMMON_H__
taqu/BalancingTree
AVLTree.h
<filename>AVLTree.h #ifndef INC_TREE_AVLTREE_H_ #define INC_TREE_AVLTREE_H_ /** @file AVLTree.h @author t-sakai @date 2008/11/13 create */ #include <functional> #include "common.h" //#define TREE_AVLTREE_ENABLE_DEBUGPRINT namespace tree { enum AVLSub { AVLSub_Left=0, AVLSub_Right=1, }; //--------------------------------------------------------------- //--- //--- AVLNode //--- //--------------------------------------------------------------- template<class T> class AVLNode { public: s32& getSub(s32 s){ return (s==AVLSub_Left)? left_ : right_;} s32 balance_; s32 left_; s32 right_; T value_; }; struct DefaultAVLAllocator { DefaultAVLAllocator() {} template<class T> inline T* malloc(u32 size) { return reinterpret_cast<T*>(DefaultAllocator::malloc(size)); } template<class T> inline void free(T* mem) { return DefaultAllocator::free(mem); } }; //--------------------------------------------------------------- //--- //--- AVLTree //--- //--------------------------------------------------------------- /// AVL木 template<class T, class Allocator=DefaultAVLAllocator, class Comparator=DefaultComparator<T> > class AVLTree { public: static const s32 MaxLevels = 32; typedef u32 size_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; typedef AVLTree this_type; typedef AVLNode<T> node_type; typedef Allocator allocator_type; typedef Comparator comparator_type; typedef s32 iterator_type; AVLTree(); ~AVLTree(); inline s32 size() const; iterator_type find(const value_type& value) const; inline iterator_type find(const value_type& value); iterator_type find(const value_type& value, std::function<s32(const T&, const T&)> comp) const; inline iterator_type find(const value_type& value, std::function<s32(const T&, const T&)> comp); inline iterator_type end() const; inline const value_type& get(iterator_type pos) const; inline value_type& get(iterator_type pos); inline void insert(value_type&& value); void remove(const value_type& value); void clear(); void swap(AVLTree& rhs); #ifdef TREE_AVLTREE_ENABLE_DEBUGPRINT void print(); #endif private: AVLTree(const AVLTree&) = delete; AVLTree& operator=(const AVLTree&) = delete; struct Step { s32 node_; s32 which_; }; void updateBalance(s32 node); s32 insertInternal(s32 node, value_type&& value); s32 balanceInsert(s32 node, Step* path, s32 numLevels); s32 findInternal(s32 node, Step* path, s32& level, const value_type& value); void balanceRemove(Step* path, s32 numLevels); void clearInternal(s32 node); #ifdef TREE_AVLTREE_ENABLE_DEBUGPRINT void printInternal(s32 node, s32 level) const; #endif /// Rotate right s32 rotateRight(s32 node); /// Rotate left s32 rotateLeft(s32 node); s32 create(value_type&& value); void destroy(s32 node); class Array { public: Array() :capacity_(0) ,items_(NULL) {} const node_type& operator[](s32 index) const { TASSERT(0<=index && index<capacity_); return items_[index]; } node_type& operator[](s32 index) { TASSERT(0<=index && index<capacity_); return items_[index]; } s32 capacity_; node_type* items_; }; s32 size_; s32 empty_; Array nodes_; s32 root_; allocator_type allocator_; comparator_type comparator_; }; //--------------------------------------------------------------- template<class T, class Allocator, class Comparator> AVLTree<T,Allocator,Comparator>::AVLTree() :size_(0) ,empty_(-1) ,root_(-1) { } //--------------------------------------------------------------- template<class T, class Allocator, class Comparator> AVLTree<T,Allocator,Comparator>::~AVLTree() { clear(); allocator_.free(nodes_.items_); nodes_.items_ = NULL; nodes_.capacity_ = 0; empty_ = -1; } //--------------------------------------------------------------- template<class T, class Allocator, class Comparator> inline s32 AVLTree<T, Allocator, Comparator>::size() const { return size_; } //--------------------------------------------------------------- template<class T, class Allocator, class Comparator> typename AVLTree<T,Allocator,Comparator>::iterator_type AVLTree<T,Allocator,Comparator>::find(const value_type& value) const { s32 node = root_; while(0 <= node){ s32 cmp = comparator_(nodes_[node].value_, value); if(cmp == 0){ return node; }else if(cmp<0){ node = nodes_[node].right_; }else{ node = nodes_[node].left_; } } return node; } //--------------------------------------------------------------- template<class T, class Allocator, class Comparator> inline typename AVLTree<T, Allocator, Comparator>::iterator_type AVLTree<T, Allocator, Comparator>::find(const value_type& value) { return static_cast<const this_type*>(this)->find(value); } //--------------------------------------------------------------- template<class T, class Allocator, class Comparator> typename AVLTree<T, Allocator, Comparator>::iterator_type AVLTree<T, Allocator, Comparator>::find(const value_type& value, std::function<s32(const T&, const T&)> comp) const { s32 node = root_; while(0 <= node){ s32 cmp = comp(nodes_[node].value_, value); if(cmp == 0){ return node; } else if(cmp<0){ node = nodes_[node].right_; } else{ node = nodes_[node].left_; } } return node; } //--------------------------------------------------------------- template<class T, class Allocator, class Comparator> inline typename AVLTree<T, Allocator, Comparator>::iterator_type AVLTree<T, Allocator, Comparator>::find(const value_type& value, std::function<s32(const T&, const T&)> comp) { return static_cast<const this_type*>(this)->find(value, comp); } //--------------------------------------------------------------- template<class T, class Allocator, class Comparator> inline typename AVLTree<T,Allocator,Comparator>::iterator_type AVLTree<T,Allocator,Comparator>::end() const { return -1; } template<class T, class Allocator, class Comparator> inline const typename AVLTree<T, Allocator, Comparator>::value_type& AVLTree<T, Allocator, Comparator>::get(iterator_type pos) const { return nodes_[pos].value_; } template<class T, class Allocator, class Comparator> inline typename AVLTree<T, Allocator, Comparator>::value_type& AVLTree<T, Allocator, Comparator>::get(iterator_type pos) { return nodes_[pos].value_; } template<class T, class Allocator, class Comparator> void AVLTree<T,Allocator,Comparator>::updateBalance(s32 node) { TASSERT(0 <= node); s32 left = nodes_[node].left_; s32 right = nodes_[node].right_; TASSERT(0 <= left); TASSERT(0 <= right); if(1 == nodes_[node].balance_){ nodes_[left].balance_ = 0; nodes_[right].balance_ = -1; }else if( -1 == nodes_[node].balance_){ nodes_[left].balance_ = 1; nodes_[right].balance_ = 0; }else{ nodes_[left].balance_ = 0; nodes_[right].balance_ = 0; } nodes_[node].balance_ = 0; } template<class T, class Allocator, class Comparator> inline void AVLTree<T,Allocator,Comparator>::insert(value_type&& value) { root_ = insertInternal(root_, tree::move(value)); } template<class T, class Allocator, class Comparator> void AVLTree<T,Allocator,Comparator>::remove(const value_type& value) { s32 numLevels = 0; Step path[MaxLevels]; s32 n = findInternal(root_, path, numLevels, value); if(n<0){ return; } node_type& node = nodes_[n]; s32 left = node.left_; s32 right = node.right_; if(right<0){ if(0 < numLevels) { nodes_[path[numLevels-1].node_].getSub(path[numLevels-1].which_) = left; } else{ root_ = left; } }else{ if(nodes_[right].left_<0){ nodes_[right].left_ = node.left_; nodes_[right].balance_ = node.balance_; if(0 < numLevels) { nodes_[path[numLevels-1].node_].getSub(path[numLevels-1].which_) = right; } else{ root_ = right; } TASSERT(numLevels<MaxLevels); path[numLevels].node_ = right; path[numLevels].which_ = AVLSub_Right; ++numLevels; }else{ s32 l = numLevels++; for(;;){ TASSERT(numLevels<MaxLevels); path[numLevels].which_ = AVLSub_Left; path[numLevels].node_ = right; ++numLevels; left = nodes_[right].left_; if(nodes_[left].left_<0){ break; } right = left; } nodes_[left].left_ = node.left_; nodes_[right].left_ = nodes_[left].right_; nodes_[left].right_ = node.right_; nodes_[left].balance_ = node.balance_; if(0 < l) { nodes_[path[l - 1].node_].getSub(path[l - 1].which_) = left; } else{ root_ = left; } path[l].which_ = AVLSub_Right; path[l].node_ = left; } } destroy(n); balanceRemove(path, numLevels); --size_; } template<class T, class Allocator, class Comparator> void AVLTree<T,Allocator,Comparator>::clear() { clearInternal(root_); root_ = -1; size_ = 0; } template<class T, class Allocator, class Comparator> void AVLTree<T, Allocator, Comparator>::swap(AVLTree& rhs) { tree::swap(size_, rhs.size_); tree::swap(empty_, rhs.empty_); tree::swap(nodes_.capacity_, rhs.nodes_.capacity_); tree::swap(nodes_.items_, rhs.nodes_.items_); tree::swap(root_, rhs.root_); tree::swap(allocator_, rhs.allocator_); tree::swap(comparator_, rhs.comparator_); } //--------------------------------------------------------------- template<class T, class Allocator, class Comparator> void AVLTree<T,Allocator,Comparator>::clearInternal(s32 node) { if(node<0){ return; } s32 left = nodes_[node].left_; s32 right = nodes_[node].right_; destroy(node); clearInternal(left); clearInternal(right); } //--------------------------------------------------------------- template<class T, class Allocator, class Comparator> s32 AVLTree<T,Allocator,Comparator>::insertInternal(s32 node, value_type&& value) { if(node<0){ return create(tree::move(value)); } Step path[MaxLevels]; s32 level = 0; s32 ni = node; for(;;){ node_type& n = nodes_[ni]; s32 cmp = comparator_(n.value_, value); if(0 == cmp){ return node; }else if(0<cmp){ TASSERT(level<MaxLevels); path[level].node_ = ni; path[level].which_ = AVLSub_Left; ++level; if(n.left_<0){ nodes_[ni].left_ = create(tree::move(value)); break; } ni = n.left_; }else{ TASSERT(level<MaxLevels); path[level].node_ = ni; path[level].which_ = AVLSub_Right; ++level; if(n.right_<0){ nodes_[ni].right_ = create(tree::move(value)); break; } ni = n.right_; } } ++size_; return balanceInsert(node, path, level); } //--------------------------------------------------------------- template<class T, class Allocator, class Comparator> s32 AVLTree<T,Allocator,Comparator>::balanceInsert(s32 node, Step* path, s32 numLevels) { s32 newNode = -1; while(0<numLevels){ --numLevels; s32 ni = path[numLevels].node_; node_type& n = nodes_[ni]; s32 which = path[numLevels].which_; if(AVLSub_Left == which){ ++n.balance_; }else{ --n.balance_; } s32 balance = n.balance_; if(0==balance){ return node; } if(1<balance){ if(nodes_[n.left_].balance_<0){ //LR n.left_ = rotateLeft(n.left_); newNode = rotateRight(ni); updateBalance(newNode); }else{ //LL newNode = rotateRight(ni); nodes_[newNode].balance_ = 0; n.balance_ = 0; } break; }else if(balance<-1){ if(0<nodes_[n.right_].balance_){ //RL n.right_ = rotateRight(n.right_); newNode = rotateLeft(ni); updateBalance(newNode); }else{ //RR newNode = rotateLeft(ni); nodes_[newNode].balance_ = 0; n.balance_ = 0; } break; } }//while(0<numLevels) if(0<numLevels){ node_type& n = nodes_[path[numLevels-1].node_]; n.getSub(path[numLevels-1].which_) = newNode; }else if(0<=newNode){ return newNode; } return node; } template<class T, class Allocator, class Comparator> s32 AVLTree<T,Allocator,Comparator>::findInternal(s32 node, Step* path, s32& level, const value_type& value) { while(0 <= node){ s32 cmp = comparator_(nodes_[node].value_, value); if(0 == cmp){ return node; }else if(0<cmp){ TASSERT(level<MaxLevels); path[level].node_ = node; path[level].which_ = AVLSub_Left; ++level; node = nodes_[node].left_; }else{ TASSERT(level<MaxLevels); path[level].node_ = node; path[level].which_ = AVLSub_Right; ++level; node = nodes_[node].right_; } } return node; } template<class T, class Allocator, class Comparator> void AVLTree<T,Allocator,Comparator>::balanceRemove(Step* path, s32 numLevels) { while(0<--numLevels){ s32 newNode = -1; s32 ni = path[numLevels].node_; node_type& n = nodes_[ni]; s32 which = path[numLevels].which_; if(AVLSub_Left == which){ --n.balance_; }else{ ++n.balance_; } s32 balance = n.balance_; if(1<balance){ if(nodes_[n.left_].balance_<0){ //LR n.left_ = rotateLeft(n.left_); newNode = rotateRight(ni); updateBalance(newNode); nodes_[path[numLevels-1].node_].getSub( path[numLevels-1].which_ ) = newNode; }else{ //LL newNode = rotateRight(ni); nodes_[path[numLevels-1].node_].getSub( path[numLevels-1].which_ ) = newNode; if(0==nodes_[newNode].balance_){ nodes_[newNode].balance_ = -1; n.balance_ = 1; break; }else{ nodes_[newNode].balance_ = 0; n.balance_ = 0; } } }else if(balance<-1){ if(0<nodes_[n.right_].balance_){ //RL n.right_ = rotateRight(n.right_); newNode = rotateLeft(ni); updateBalance(newNode); nodes_[path[numLevels-1].node_].getSub( path[numLevels-1].which_ ) = newNode; }else{ //RR newNode = rotateLeft(ni); nodes_[path[numLevels-1].node_].getSub( path[numLevels-1].which_ ) = newNode; if(0 == nodes_[newNode].balance_){ nodes_[newNode].balance_ = 1; n.balance_ = -1; break; }else{ nodes_[newNode].balance_ = 0; n.balance_ = 0; } } }else if(0 != balance){ break; } }//while(0<numLevels) } //--------------------------------------------------------------- // 右回転 template<class T, class Allocator, class Comparator> s32 AVLTree<T,Allocator,Comparator>::rotateRight(s32 node) { TASSERT(0<=node); s32 left = nodes_[node].left_; TASSERT(0<=left); //Left subree should exist nodes_[node].left_ = nodes_[left].right_; nodes_[left].right_ = node; return left; } //--------------------------------------------------------------- // 左回転 template<class T, class Allocator, class Comparator> s32 AVLTree<T,Allocator,Comparator>::rotateLeft(s32 node) { TASSERT(0<=node); s32 right = nodes_[node].right_; TASSERT(0<=right); //Right subree should exist nodes_[node].right_ = nodes_[right].left_; nodes_[right].left_ = node; return right; } template<class T, class Allocator, class Comparator> s32 AVLTree<T, Allocator, Comparator>::create(value_type&& value) { if(empty_<0) { s32 capacity = nodes_.capacity_ + 16; node_type* nodes = allocator_.malloc<node_type>(sizeof(node_type)*capacity); //Copy old nodes to new nodes for(s32 i=0; i<nodes_.capacity_; ++i){ TPLACEMENT_NEW(&nodes[i].value_) value_type(tree::move(nodes_[i].value_)); nodes[i].balance_ = nodes_[i].balance_; nodes[i].left_ = nodes_[i].left_; nodes[i].right_ = nodes_[i].right_; } //Initialize new nodes with default constructor for(s32 i=nodes_.capacity_; i<capacity; ++i){ TPLACEMENT_NEW(&nodes[i].value_) value_type(); nodes[i].balance_ = i+1; } nodes[capacity-1].balance_ = empty_; empty_ = nodes_.capacity_; allocator_.free(nodes_.items_); nodes_.capacity_ = capacity; nodes_.items_ = nodes; } s32 result = empty_; empty_ = nodes_[result].balance_; nodes_[result].balance_ = 0; nodes_[result].left_ = -1; nodes_[result].right_ = -1; nodes_[result].value_ = tree::move(value); return result; } template<class T, class Allocator, class Comparator> void AVLTree<T, Allocator, Comparator>::destroy(s32 node) { nodes_[node].value_.~T(); nodes_[node].balance_ = empty_; nodes_[node].left_ = -1; nodes_[node].right_ = -1; empty_ = node; } #ifdef TREE_AVLTREE_ENABLE_DEBUGPRINT //--------------------------------------------------------------- template<class T, class Allocator, class Comparator> void AVLTree<T,Allocator,Comparator>::print() { printInternal(root_, 0); } //--------------------------------------------------------------- template<class T, class Allocator, class Comparator> void AVLTree<T,Allocator,Comparator>::printInternal(s32 node, s32 level) const { if(node<0){ return; } printInternal(nodes_[node].left_, level+1); for(s32 i=0; i<level; ++i){ std::cout << ' '; } std::cout << nodes_[node].value_ << std::endl; printInternal(nodes_[node].right_, level+1); } #endif } #endif //INC_TREE_AVLTREE_H_
tumdog/electron
atom/browser/atom_browser_context.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ATOM_BROWSER_ATOM_BROWSER_CONTEXT_H_ #define ATOM_BROWSER_ATOM_BROWSER_CONTEXT_H_ #include <string> #include <vector> #include "base/memory/scoped_refptr.h" #include "brightray/browser/browser_context.h" namespace storage { class SpecialStoragePolicy; } namespace atom { class AtomBlobReader; class AtomDownloadManagerDelegate; class AtomPermissionManager; class RequestContextDelegate; class SpecialStoragePolicy; class WebViewManager; class AtomBrowserContext : public brightray::BrowserContext { public: // Get or create the BrowserContext according to its |partition| and // |in_memory|. The |options| will be passed to constructor when there is no // existing BrowserContext. static scoped_refptr<AtomBrowserContext> From( const std::string& partition, bool in_memory, const base::DictionaryValue& options = base::DictionaryValue()); void SetUserAgent(const std::string& user_agent); AtomBlobReader* GetBlobReader(); // content::BrowserContext: content::DownloadManagerDelegate* GetDownloadManagerDelegate() override; content::BrowserPluginGuestManager* GetGuestManager() override; content::PermissionManager* GetPermissionManager() override; storage::SpecialStoragePolicy* GetSpecialStoragePolicy() override; // brightray::BrowserContext: void RegisterPrefs(PrefRegistrySimple* pref_registry) override; std::string GetUserAgent() const override; void OnMainRequestContextCreated( brightray::URLRequestContextGetter* getter) override; RequestContextDelegate* GetRequestContextDelegate() const { return request_context_delegate_.get(); } protected: AtomBrowserContext(const std::string& partition, bool in_memory, const base::DictionaryValue& options); ~AtomBrowserContext() override; private: brightray::URLRequestContextGetter* url_request_context_getter_; std::unique_ptr<AtomDownloadManagerDelegate> download_manager_delegate_; std::unique_ptr<WebViewManager> guest_manager_; std::unique_ptr<AtomPermissionManager> permission_manager_; scoped_refptr<storage::SpecialStoragePolicy> storage_policy_; std::unique_ptr<AtomBlobReader> blob_reader_; std::unique_ptr<RequestContextDelegate> request_context_delegate_; std::string user_agent_; DISALLOW_COPY_AND_ASSIGN(AtomBrowserContext); }; } // namespace atom #endif // ATOM_BROWSER_ATOM_BROWSER_CONTEXT_H_
klantz81/complex
complex.h
#ifndef COMPLEX_H #define COMPLEX_H class complex { private: protected: public: float a, b; complex(); complex(float a, float b); complex conj(); complex operator*(const complex& c) const; complex operator+(const complex& c) const; complex operator-(const complex& c) const; complex operator-() const; complex operator*(const float c) const; complex& operator=(const complex& c); }; #endif
moothyknight/Vulkan-Compute-Example
VulkanAPI/Project1/unused/old/Window.h
<filename>VulkanAPI/Project1/unused/old/Window.h #ifndef WINDOW_H #define WINDOW_H //I used <NAME>'s tutorial and the official tutorial. #include "Platform.h" #include "Render.h" #include <string> class Render; class Window { public: Window(Render * renderer, uint32_t size_x, uint32_t size_y, std::string name); ~Window(); void Close(); bool Update(); void _cleanup(); void BeginRender(); void EndRender(std::vector<VkSemaphore> wait_semaphores); VkRenderPass GetVulkanRenderPass(); VkFramebuffer GetVulkanActiveFramebuffer(); VkSurfaceKHR GetVulkanSurface(); VkExtent2D GetVulkanSurfaceSize(); private: #if USE_FRAMEWORK_GLFW void _initGLFWWindow(); void _deInitGLFWWindow(); void _updateGLFWWindow(); void _initGLFWSurface(); static void _onWindowResized(GLFWwindow* window, int width, int height); #endif void _initSurface(); // Surfaces represent the display area void _deInitSurface(); void _initSwapchain(); // Creates virtual framebuffers to prevent stuttering (similar to vsync) void _deInitSwapchain(); void _initSwapchainImages(); // Defines image properties on swapchain void _deInitSwapchainImages(); void _initDepthStencilImage(); // Enables depth Buffering for 3D void _deInitDepthStencilImage(); void _initRenderPass(); // Attaches images to be added to framebuffer void _deInitRenderPass(); void _initDescriptorSetLayout(); //void _deInitDescriptorSetLayout(); void _initGraphicsPipeline(); //void _deInitGraphicsPipeline(); void _initFramebuffers(); // Framebuffers are the VRAM chunk containing the bitmap to be sent to monitor. void _deInitFramebuffers(); void _initCommandPool(); //void _deInitCommandPool(); void _initTextureImage(); //void _deInitTextureImage(); void _initTextureImageView(); //void _deInitTextureImageView(); void _initTextureSampler(); //void _deInitTextureSampler(); void _initVertexBuffer(); //void _deInitVertexBuffer(); void _initIndexBuffer(); //void _deInitIndexBuffer(); void _initUniformBuffer(); void _updateUniformBuffer(); //void _deInitUniformBuffer(); void _initDescriptorPool(); //void _deInitDescriptorPool(); void _initDescriptorSet(); //void _deInitDescriptorSet(); void _initCommandBuffers(); //void _deInitCommandBuffers(); void _initSemaphores(); //void _deInitSemaphores(); void _initSynchronizations(); // Creates a fence which synchronizes CPU with GPU. void _deInitSynchronizations(); void _reRenderSwapchain(); void _drawFrame(); void _cleanupSwapChain(); VkShaderModule _initShaderModule(const std::vector<char>& code); VkImageView _initImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags); void _initImage( uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage& image, VkDeviceMemory& imageMemory ); void _transitionImageLayout( VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout ); Render * _renderer = nullptr; VkExtent2D _chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities); VkSurfaceFormatKHR _chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats); VkSurfaceKHR _surface = VK_NULL_HANDLE; VkPresentModeKHR _chooseSwapPresentMode(const std::vector<VkPresentModeKHR> availablePresentModes); VkSwapchainKHR _swapchain = VK_NULL_HANDLE; VkRenderPass _render_pass = VK_NULL_HANDLE; VkDescriptorSetLayout _descriptor_set_layout = VK_NULL_HANDLE; VkPipelineLayout _pipeline_layout = VK_NULL_HANDLE; VkPipeline _graphics_pipeline = VK_NULL_HANDLE; VkExtent2D _swapchain_extent; VkBuffer _vertex_buffer; VkDeviceMemory _vertex_buffer_memory; VkBuffer _index_buffer; VkDeviceMemory _index_buffer_memory; VkBuffer _uniform_buffer; VkDeviceMemory _uniform_buffer_memory; VkDescriptorPool _descriptor_pool; VkDescriptorSet _descriptor_set; void _createBuffer( VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory ); void _copyBufferToImage( VkBuffer buffer, VkImage image, uint32_t width, uint32_t height ); void _copyBuffer( VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size ); uint32_t _findMemoryType( uint32_t typeFilter, VkMemoryPropertyFlags properties ); VkCommandBuffer _beginSingleTimeCommands(); void _endSingleTimeCommands(VkCommandBuffer commandBuffer); VkCommandPool _command_pool; std::vector<VkCommandBuffer> _command_buffers; uint32_t _surface_size_x = 512; //Default uint32_t _surface_size_y = 512; std::string _window_name; uint32_t _swapchain_image_count = 2; uint32_t _active_swapchain_image_id = UINT32_MAX; VkSemaphore _image_available_semaphore; VkSemaphore _render_finished_semaphore; VkFence _swapchain_image_available = VK_NULL_HANDLE; std::vector<VkImage> _swapchain_images; std::vector<VkImageView> _swapchain_image_views; std::vector<VkFramebuffer> _framebuffers; bool _hasStencilComponent(VkFormat format); VkImage _depth_stencil_image = VK_NULL_HANDLE; VkDeviceMemory _depth_stencil_image_memory = VK_NULL_HANDLE; VkImageView _depth_stencil_image_view = VK_NULL_HANDLE; VkImage _texture_image = VK_NULL_HANDLE; VkDeviceMemory _texture_image_memory = VK_NULL_HANDLE; VkImageView _texture_image_view = VK_NULL_HANDLE; VkSampler _texture_sampler; VkSurfaceFormatKHR _surface_format = {}; VkSurfaceCapabilitiesKHR _surface_capabilities = {}; VkFormat _depth_stencil_format = VK_FORMAT_UNDEFINED; bool _stencil_available = false; bool _window_should_run = true; GLFWwindow * _glfw_window = nullptr; }; #endif
moothyknight/Vulkan-Compute-Example
VulkanAPI/Project1/Platform.h
<reponame>moothyknight/Vulkan-Compute-Example #ifndef PLATFORM_H #define PLATFORM_H //I used <NAME>'s tutorial //vulkan-1.lib required to be linked from VulkanSDK // You will need to add GLFWs "glfw3.lib" file into the project, this task is up to you. // GLFW version 3.2 or newer is required. #define USE_FRAMEWORK_GLFW 1 #define GLFW_INCLUDE_VULKAN //#include <vulkan/vulkan.h> //GLFW should include this automatically with the above declaration #include <GLFW3.2.1/include/GLFW/glfw3.h>// Extended library to simplify drawing to screen #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/glm.hpp> // Essential linear algebra operations (matrices, vectors, linear algebra (dot,distance,normalize,etc)) #include <glm/gtc/matrix_transform.hpp> #include <stdint.h> #include <vector> //For GLFW void InitPlatform(); void DeInitPlatform(); void AddRequiredPlatformInstanceExtensions(std::vector<const char *> *instance_extensions); void ErrorCheck(VkResult result); uint32_t FindMemoryTypeIndex( const VkPhysicalDeviceMemoryProperties * gpu_memory_properties, const VkMemoryRequirements * memory_requirements, const VkMemoryPropertyFlags required_properties); #endif
moothyknight/Vulkan-Compute-Example
VulkanAPI/Project1/unused/old/Render.h
<reponame>moothyknight/Vulkan-Compute-Example #ifndef RENDER_H #define RENDER_H #include "Platform.h" #include "Window.h" #include <vector> #include <string> #include <stdint.h> #include <assert.h> class Window; class Render { public: Render(); ~Render(); Window * OpenWindow(uint32_t size_x, uint32_t size_y, std::string name); bool Run(); const VkInstance GetVulkanInstance() const; // The connection between your application and the Vulkan library const VkPhysicalDevice GetVulkanPhysicalDevice() const; // Handle for queried physical device properties/features const VkDevice GetVulkanDevice() const; // "Opaque handle to a device object" or the logical device const VkQueue GetVulkanQueue() const; // Instruction call list for GPU const VkQueue GetVulkanPresentQueue() const; // Present instruction call list for GPU const uint32_t GetVulkanGraphicsQueueFamilyIndex() const; // const uint32_t GetVulkanGraphicsPresentFamilyIndex() const; // const VkPhysicalDeviceProperties & GetVulkanPhysicalDeviceProperties() const; // const VkPhysicalDeviceMemoryProperties & GetVulkanPhysicalDeviceMemoryProperties() const; // struct QueueFamilyIndices { int graphicsFamily = -1; int presentFamily = -1; bool isComplete() { return graphicsFamily >= 0; // && presentFamily >= 0; } }; static QueueFamilyIndices _findQueueFamilies(VkPhysicalDevice device, Window *w); private: void _setupLayersAndExtensions(); void _initInstance(); void _deInitInstance(); void _initDevice(); void _deInitDevice(); void _setupDebug(); void _initDebug(); void _deInitDebug(); uint32_t _graphics_family_index = 0; uint32_t _present_family_index = 0; VkInstance _instance = VK_NULL_HANDLE; VkPhysicalDevice _gpu = VK_NULL_HANDLE; VkDevice _device = VK_NULL_HANDLE; VkQueue _queue = VK_NULL_HANDLE; VkQueue _present_queue = VK_NULL_HANDLE; VkPhysicalDeviceProperties _gpu_properties = {}; VkPhysicalDeviceMemoryProperties _gpu_memory_properties = {}; std::vector<const char*> _instance_layers; std::vector<const char*> _instance_extensions; std::vector<const char*> _device_extensions; VkDebugReportCallbackEXT _debug_report = VK_NULL_HANDLE; VkDebugReportCallbackCreateInfoEXT debug_callback_create_info = {}; Window * _window = nullptr; }; /* Here's all the pipeline processes from top to bottom. Assemblers and Operations are fixed functions All shaders are programmable. Tesselation, Geometry, and Compute shaders are optional. Init ------------------------------------------------------------------* | | Draw < -------------------------- Indirect Buffer Binding --- > Dispatch | | Input Assembler < --------------- Index Buffer Binding Compute Assembler | | | | < --- Vertex Buffer Binding Compute Shader (i.e. CUDA) | | Vertex Shader < -------------- > * | | | | < --- Push Constants ------------ > | | Tesselation Assembler | | | | | ..........Descriptor Sets.......... | | Tess. Control Shader < ----- > * < --- Sampled Image ------------- > | | | | | | Tess. Primitive Generator | < --- Uniform Texel Buffer ------ > | | | | | | Tess. Evaluation Shader < -- > * < --- Uniform Buffer ------------ > | | | | | |--| | < - > Storage Image < ----------- > | | Geometry Assembler | | | | | < - > Storage Texel Buffer < ---- > | | Geometry Shader < --------- > * < - > Storage Buffer < ---------- > * *--| | ................................... | | Primitive Assembler | | | Rasterization | | | Per-Fragment Operations < ---- > * | | Fragment Assembler | | | Fragment Shader < ------------ > * -------------------------------* | | ...... Framebuffer ...... | | < ----------- Input Attachment | | | Post-Fragment Operations < ---------- Depth/Stencil Attachment < -* | Color/Blending Operations < --------- Color Attachment ......................... */ #endif
moothyknight/Vulkan-Compute-Example
VulkanAPI/Project1/VulkanBase.h
#ifndef VULKANBASE_H #define VULKANBASE_H // Many files are modified versions of <NAME>'s code (https://github.com/SaschaWillems/Vulkan) // Vulkan Charts: https://docs.google.com/document/d/1qejSErMPXJ3-iVc3WBBTzC2yOBUOoyRdqWEw0bonrOE/edit?usp=sharing // I used these in tandem with a youtube crash course to pull this together. #include <iostream> #include <chrono> #include <sys/stat.h> #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #define GLM_ENABLE_EXPERIMENTAL #include <GLM/glm/glm.hpp> #include <string> #include <array> #include <numeric> #include "vulkan/vulkan.h" #include "keycodes.hpp" #include "VulkanTools.h" #include "VulkanDebug.h" #include "VulkanInitializers.hpp" #include "VulkanDevice.hpp" #include "VulkanSwapChain.hpp" //#include "VulkanUIOverlay.h" #include "VulkanTextOverlay.hpp" #include "camera.hpp" //#include "benchmark.hpp" #include "Platform.h" class VulkanBase { private: // fps timer (one second interval) float fpsTimer = 0.0f; // Get window title with example name, device, et. std::string getWindowTitle(); /** brief Indicates that the view (position, rotation) has changed and */ bool viewUpdated = false; // Destination dimensions for resizing the window uint32_t destWidth; uint32_t destHeight; bool resizing = false; // vks::Benchmark benchmark; // Called if the window is resized and some resources have to be recreatesd void windowResize(); protected: // Frame counter to display fps uint32_t frameCounter = 0; uint32_t lastFPS = 0; // Vulkan instance, stores all per-application states VkInstance instance; // Physical device (GPU) that Vulkan will ise VkPhysicalDevice physicalDevice; // Stores physical device properties (for e.g. checking device limits) VkPhysicalDeviceProperties deviceProperties; // Stores the features available on the selected physical device (for e.g. checking if a feature is available) VkPhysicalDeviceFeatures deviceFeatures; // Stores all available memory (type) properties for the physical device VkPhysicalDeviceMemoryProperties deviceMemoryProperties; /** * Set of physical device features to be enabled for this example (must be set in the derived constructor) * * @note By default no physical device features are enabled */ VkPhysicalDeviceFeatures enabledFeatures{}; /** @brief Set of device extensions to be enabled for this example (must be set in the derived constructor) */ std::vector<const char*> enabledExtensions; /** @brief Logical device, application's view of the physical device (GPU) */ // todo: getter? should always point to VulkanDevice->device VkDevice device; // Handle to the device graphics queue that command buffers are submitted to VkQueue queue; // Depth buffer format (selected during Vulkan initialization) VkFormat depthFormat; // Command buffer pool VkCommandPool cmdPool; /** @brief Pipeline stages used to wait at for graphics queue submissions */ VkPipelineStageFlags submitPipelineStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; // Contains command buffers and semaphores to be presented to the queue VkSubmitInfo submitInfo; // Command buffers used for rendering std::vector<VkCommandBuffer> drawCmdBuffers; // Global render pass for frame buffer writes VkRenderPass renderPass; // List of available frame buffers (same as number of swap chain images) std::vector<VkFramebuffer>frameBuffers; // Active frame buffer index uint32_t currentBuffer = 0; // Descriptor set pool VkDescriptorPool descriptorPool = VK_NULL_HANDLE; // List of shader modules created (stored for cleanup) std::vector<VkShaderModule> shaderModules; // Pipeline cache object VkPipelineCache pipelineCache; // Wraps the swap chain to present images (framebuffers) to the windowing system VulkanSwapChain swapChain; // Synchronization semaphores struct { // Swap chain image presentation VkSemaphore presentComplete; // Command buffer submission and execution VkSemaphore renderComplete; // Text overlay submission and execution VkSemaphore textOverlayComplete; } semaphores; public: bool prepared = false; uint32_t width = 1280; uint32_t height = 720; /** @brief Last frame time measured using a high performance timer (if available) */ float frameTimer = 1.0f; /** @brief Returns os specific base asset path (for shaders, models, textures) */ //const std::string getAssetPath(); /** @brief Encapsulated physical and logical vulkan device */ vks::VulkanDevice *vulkanDevice; /** @brief Example settings that can be changed e.g. by command line arguments */ struct Settings { /** @brief Activates validation layers (and message output) when set to true */ bool validation = false; /** @brief Set to true if fullscreen mode has been requested via command line */ bool fullscreen = false; /** @brief Set to true if v-sync will be forced for the swapchain */ bool vsync = false; //For VulkanUIOverlay.h bool overlay = false; } settings; VkClearColorValue defaultClearColor = { { 0.025f, 0.025f, 0.025f, 1.0f } }; float zoom = 0; static std::vector<const char*> args; // Defines a frame rate independent timer value clamped from -1.0...1.0 // For use in animations, rotations, etc. float timer = 0.0f; // Multiplier for speeding up (or slowing down) the global timer float timerSpeed = 0.25f; bool paused = false; bool enableTextOverlay = false; VulkanTextOverlay *textOverlay; // Use to adjust mouse rotation speed float rotationSpeed = 1.0f; // Use to adjust mouse zoom speed float zoomSpeed = 1.0f; Camera camera; glm::vec3 rotation = glm::vec3(); glm::vec3 cameraPos = glm::vec3(); glm::vec2 mousePos; std::string title = "Vulkan Example"; std::string name = "vulkanExample"; struct { VkImage image; VkDeviceMemory mem; VkImageView view; } depthStencil; // Gamepad state (only one pad supported) struct { glm::vec2 axisLeft = glm::vec2(0.0f); glm::vec2 axisRight = glm::vec2(0.0f); } gamePadState; GLFWwindow * glfw_window; void initGLFWwindow(); void deInitGLFWwindow(); // Default ctor VulkanBase(bool enableValidation); // dtor virtual ~VulkanBase(); // Setup the vulkan instance, enable required extensions and connect to the physical device (GPU) void initVulkan(); /** * Create the application wide Vulkan instance * * @note Virtual, can be overriden by derived example class for custom instance creation */ virtual VkResult createInstance(bool enableValidation); // Pure virtual render function (override in derived class) virtual void render() = 0; // Called when view change occurs // Can be overriden in derived class to e.g. update uniform buffers // Containing view dependant matrices virtual void viewChanged(); // Called if a key is pressed /** @brief (Virtual) Called after a key was pressed, can be used to do custom key handling */ virtual void keyPressed(uint32_t); // Called when the window has been resized // Can be overriden in derived class to recreate or rebuild resources attached to the frame buffer / swapchain virtual void windowResized(); // Pure virtual function to be overriden by the dervice class // Called in case of an event where e.g. the framebuffer has to be rebuild and thus // all command buffers that may reference this virtual void buildCommandBuffers(); // Creates a new (graphics) command pool object storing command buffers void createCommandPool(); // Setup default depth and stencil views virtual void setupDepthStencil(); // Create framebuffers for all requested swap chain images // Can be overriden in derived class to setup a custom framebuffer (e.g. for MSAA) virtual void setupFrameBuffer(); // Setup a default render pass // Can be overriden in derived class to setup a custom render pass (e.g. for MSAA) virtual void setupRenderPass(); /** @brief (Virtual) Called after the physical device features have been read, can be used to set features to enable on the device */ virtual void getEnabledFeatures(); // Connect and prepare the swap chain void initSwapchain(); // Create swap chain images void setupSwapChain(); // Check if command buffers are valid (!= VK_NULL_HANDLE) bool checkCommandBuffers(); // Create command buffers for drawing commands void createCommandBuffers(); // Destroy all command buffers and set their handles to VK_NULL_HANDLE // May be necessary during runtime if options are toggled void destroyCommandBuffers(); // Command buffer creation // Creates and returns a new command buffer VkCommandBuffer createCommandBuffer(VkCommandBufferLevel level, bool begin); // End the command buffer, submit it to the queue and free (if requested) // Note : Waits for the queue to become idle void flushCommandBuffer(VkCommandBuffer commandBuffer, VkQueue queue, bool free); // Create a cache pool for rendering pipelines void createPipelineCache(); // Prepare commonly used Vulkan functions virtual void prepare(); // Load a SPIR-V shader VkPipelineShaderStageCreateInfo loadShader(std::string fileName, VkShaderStageFlagBits stage); // Start the main render loop void renderLoop(); // Render one frame of a render loop on platforms that sync rendering void renderFrame(); void updateTextOverlay(); /** @brief (Virtual) Called when the text overlay is updating, can be used to add custom text to the overlay */ virtual void getOverlayText(VulkanTextOverlay*); // Prepare the frame for workload submission // - Acquires the next image from the swap chain // - Sets the default wait and signal semaphores void prepareFrame(); // Submit the frames' workload // - Submits the text overlay (if enabled) void submitFrame(); }; // Sample main loop for glfw entry point. /* #if defined(USE_FRAMEWORK_GLFW) int main(const int argc, const int *argv[]) { VulkanProgram *vulkanExample; //Derived from VulkanBase in your main program. EX: class VulkanProgram : public VulkanBase {} for (int32_t i = 0; i < __argc; i++) { VulkanBase::args.push_back(__argv[i]); }; vulkanExample = new VulkanProgram(); vulkanExample->initVulkan(); vulkanExample->initGLFWwindow(); vulkanExample->initSwapchain(); vulkanExample->prepare(); vulkanExample->renderLoop(); delete(vulkanExample); return 0; } #endif */ /* Here's all the pipeline processes from top to bottom. Assemblers and Operations are fixed functions All shaders are programmable. Tesselation, Geometry, and Compute shaders are optional. Init ------------------------------------------------------------------* | | Draw < -------------------------- Indirect Buffer Binding --- > Dispatch | | Input Assembler < --------------- Index Buffer Binding Compute Assembler | | | | < --- Vertex Buffer Binding Compute Shader (i.e. CUDA) | | Vertex Shader < -------------- > * | | | | < --- Push Constants ------------ > | | Tesselation Assembler | | | | | ..........Descriptor Sets.......... | | Tess. Control Shader < ----- > * < --- Sampled Image ------------- > | | | | | | Tess. Primitive Generator | < --- Uniform Texel Buffer ------ > | | | | | | Tess. Evaluation Shader < -- > * < --- Uniform Buffer ------------ > | | | | | |--| | < - > Storage Image < ----------- > | | Geometry Assembler | | | | | < - > Storage Texel Buffer < ---- > | | Geometry Shader < --------- > * < - > Storage Buffer < ---------- > * *--| | ................................... | | Primitive Assembler | | | Rasterization | | | Per-Fragment Operations < ---- > * | | Fragment Assembler | | | Fragment Shader < ------------ > * -------------------------------* | | ...... Framebuffer ...... | | < ---------- Input Attachment | | | Post-Fragment Operations < --------- Depth/Stencil Attachment < --* | Color/Blending Operations < -------- Color Attachment ......................... */ #endif
KonradJanica/CircularBuffer
circular_vector.h
<reponame>KonradJanica/CircularBuffer<gh_stars>1-10 /* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** circular_vector.h ** An STL-Compliant Circular Vector Container. Shares similarities to a Circular ** Buffer Data Structure, except allows access to all elements in the container. ** Contains all the same member functions as C++98 std::vector from the STL, ** except for vector::insert and vector::erase. ** Newly introduced member functions include: push_front and pop_front which ** unlike the counterpart operations in std::vector are O(1) time (Constant). ** ** ** Author: <NAME> ** -------------------------------------------------------------------------*/ #ifndef CIRCULAR_VECTOR_HPP_ #define CIRCULAR_VECTOR_HPP_ #include <algorithm> // std::swap, std::max, std::lexicographical_compare, std::equal #include <stdexcept> // std::invalid_argument, std::out_of_range #include <memory> // std::allocator // Forward declaration of iterator class template <typename _T_noconst, typename _T, typename _element_type = typename _T::value_type> class circular_vector_iterator; // An STL Compliant Circular Vector Container // This Data Structure is basically a centered wrapping vector with space at both sides // to allow O(1) (constant time) insert/erase(front) as well as O(1) push_back and pop_back. // Internal structure is an array with an index starting from the center of capacity // and wrapping around to the start of the array. // As elements are added to the front and end, the start and end indices move // accordingly. // When capacity is reached, the storage container will reallocate its storage // increasing its capacity to 1.5 * capacity. // Like vectors, this makes push_back and push_front amortized time O(1) // per insertion. // The Default Capacity should be larger than 1 otherwise a Circular Vector is // pointless. template <typename _T, typename _Alloc = std::allocator<_T> > class circular_vector { public: // TYPEDEFS: typedef circular_vector<_T, _Alloc> self_type; typedef _Alloc allocator_type; typedef typename _Alloc::value_type value_type; typedef typename _Alloc::pointer pointer; typedef typename _Alloc::const_pointer const_pointer; typedef typename _Alloc::reference reference; typedef typename _Alloc::const_reference const_reference; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; // Iterator typedef circular_vector_iterator <self_type, self_type> iterator; // Const Iterator typedef circular_vector_iterator <self_type,const self_type, const value_type> const_iterator; // Reverse Iterator typedef std::reverse_iterator<iterator> reverse_iterator; // Reverse Const Iterator typedef std::reverse_iterator<const_iterator> const_reverse_iterator; // CONSTANTS: static const size_type kDefaultCapacity = 5; enum SelectIndex { kStart = 0, kEnd = 1, }; // CONSTRUCTORS: // @brief Empty container constructor (default constructor). // Constructs an empty container, with no elements. With a specified amount of // reserved space. // @param capacity The starting allocated storage reserve // @throws std::invalid_argument With negative capacity values explicit circular_vector(size_type capacity = kDefaultCapacity, const _Alloc &alloc = _Alloc()) : size_(0), capacity_(capacity), start_idx_(capacity/2), end_idx_(capacity/2), alloc_(alloc), array_(alloc_.allocate(capacity)) { if (capacity <= 0) { throw std::invalid_argument("invalid capacity"); } }; // @brief Fill constructor. Constructs a container with @a n elements. Each element is a copy of @a val. // @param n The size and capacity of the %circular_vector // @param val The data value to fill the %circular_vector // @throws std::invalid_argument With negative size values explicit circular_vector(size_type n, const value_type &val, const _Alloc &alloc = _Alloc()) : size_(0), capacity_(n), start_idx_(n/2), end_idx_(n/2), alloc_(alloc), array_(alloc_.allocate(n)) { if (n <= 0) { throw std::invalid_argument("invalid capacity"); } resize(n, val); }; // @brief Range constructor. Constructs a container with as many elements as the range [first,last), // with each element constructed from its corresponding element in that range, in the same order. // @param first The initial position to start the copy from // @param last The final exclusive position of the copy range template <class InputIterator> circular_vector(InputIterator first, InputIterator last, const _Alloc &alloc = _Alloc()) : size_(0), capacity_(last-first), start_idx_((last-first)/2), end_idx_((last-first)/2), alloc_(alloc), array_(alloc_.allocate(last-first)) { try { assign(first,last); } catch (...) { clear(); alloc_.deallocate(array_, capacity_); throw std::length_error("out of memory"); } } // @brief Copy constructor. Constructs a container with a copy of each of the elements in x, in the same order. // @param x Another vector object of the same type (with the same class template arguments _T and _Alloc), whose contents are copied. // @throws std::length_error Upon catching any exception while assigning memory circular_vector(const circular_vector &x) : size_(0), capacity_(x.capacity()), start_idx_(x.capacity()/2), end_idx_(x.capacity()/2), alloc_(x.get_allocator()), array_(x.get_allocator().allocate(x.capacity())) { try { assign(x.begin(), x.end()); } catch (...) { clear(); alloc_.deallocate(array_, capacity_); throw std::length_error("out of memory"); } } // @brief Move constructor. Assigns new contents to the container, replacing its current contents, and modifying its size accordingly. // @param x A vector object of the same type (i.e., with the same template parameters, _T and _Alloc). circular_vector &operator = (const self_type &x) { size_ = 0; capacity_ = x.capacity(); start_idx_ = x.capacity()/2; end_idx_ = x.capacity()/2; array_ = alloc_.allocate(x.capacity()); assign(x.begin(), x.end()); return *this; } // DECONSTRUCTORS: ~circular_vector() { // clear(); alloc_.deallocate(array_, capacity_); }; // ITERATORS // begin(), An iterator referring to array_[0], i.e. the first element // @warn Iterator should be repositioned upon capacity reallocation or after push_front call iterator begin() { return iterator(this, 0); } const_iterator begin() const { return const_iterator(this, 0); } // end(), An iterator referring to array_[size()], i.e. past-the-end element // @warn Iterator should be repositioned upon capacity reallocation or after push_back call iterator end() { return iterator(this, size()); } const_iterator end() const { return const_iterator(this, size()); } // rbegin() // @warn Iterator should be repositioned upon capacity reallocation or after push_back call reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } // rend() // @warn Iterator should be repositioned upon capacity reallocation or after push_front call reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } // ALLOCATORS: // @brief Returns a copy of the allocator object associated with the @circular_vector // @return Read-only (constant) allocator _Alloc get_allocator() const { return alloc_; }; // CAPACITIES: // @brief Returns the amount of elements in the %circular_vector // @return Read-only (constant) circular size size_type size() const { return size_; }; // @brief Returns the maximum number of elements that the %circular_vector can hold // during dynamic allocation mode // @return Read-only (constant) maximum size size_type max_size() const { return alloc_.max_size(); }; // @brief Resizes the %circular_vector to specified size // @param n Number of elements the %circular_vector should contain. // @param val The value of the element to fill the extra size // @warn This function changes the actual content of the container by inserting or // erasing elements from it (unless @a n = size()). // If the number is smaller than the %circular_vector's current size the // %circular_vector is truncated, otherwise default (or specified) elements // are appended until size reaches @a n size. // If capacity needs to increase => capacity becomes @a n. // Capacity never shrinks. void resize(size_type n, const value_type &val = value_type()) { if (n > size()) { if (n > capacity()) { circular_vector temp(n); // Capacity = n temp.assign(begin(), end()); swap(temp); } // Push new valued elements until size() = n while (n != size()) { push_back(val); } } else if (n < size()) { // A more efficient method of doing this can be used // but must ensure wrapped arrays are addressed properly. while (n != size()) pop_back(); } // else n == size() => do nothing }; // @brief Returns size of allocated storage capacity size_type capacity() const { return capacity_; }; // @brief Returns true if there are elements in the %circular_vector // @return Read-only (constant) True iff end index is in default state bool empty() const { return !size_; }; // @brief Request that the %circular_vector capacity be at least enough to contain // n elements. This function has no effect on the %circular_vector size and // cannot alter its elements. // @warn If @a n is greater than the current %circular_vector capacity, the function // causes the container to reallocate its storage increasing its // capacity to @a n (or greater). O(n) time and space required when this occurs void reserve(size_type n) { if (capacity() < n) { circular_vector temp( std::max<size_type>(n, capacity() * 1.5) ); temp.assign(begin(), end()); swap(temp); } } // MODIFIERS: // @brief Fills a %circular_vector with copies of the elements in the // range [start, last) // @param start An input iterator // @param last An input iterator // @warn The assignment completely changes the %circular_vector and the // resulting %circular_vector's size is the same as the number of // elements assigned. Old data will be lost template <typename iter> void assign(iter start, iter last) { if (size() != 0) clear(); while (start != last) { push_back(*start); ++start; } } // @brief Fills a %circular_vector with the specified value in the // range [0, n) // @param n Number of elements to be assigned // @param val Value to be assigned // @warn The assignment completely changes the %circular_vector and the // resulting %circular_vector's size is the same as the number of // elements assigned. Old data will be lost void assign(size_type n, const value_type &val) { if (size() != 0) clear(); while (n != 0) { push_back(val); --n; } } // @brief Removes the first indexed element // @warn Undefined behaviour when calling on an empty %circular_vector void pop_front() { alloc_.destroy(array_ + start_idx_); increment(kStart); } // @brief Removes the last indexed element // @warn Undefined behaviour when calling on an empty %circular_vector void pop_back() { decrement(kEnd); alloc_.destroy(array_ + end_idx_); } // @brief Adds an element to the head of the %circular_vector // and decrements the start index // @param val Element to be added // @warn If capacity has been reached, the function causes the container to // reallocate its storage increasing its capacity to 1.5 * capacity. // O(n) time and space required when this occurs void push_front(const value_type &val) { if (end_idx_ == start_idx_ && !empty()) { reserve(capacity() * 1.5); } else if (end_idx_ == start_idx_) { // Do a push_back only on empty case push_back(val); return; } decrement(kStart); // array_[start_idx_] = val; alloc_.construct(array_ + start_idx_, val); } // @brief Adds an element to the tail of the %circular_vector // @param val Element to be added // @warn If capacity has been reached, the function causes the container to // reallocate its storage increasing its capacity to 1.5 * capacity. // O(n) time and space required when this occurs void push_back(const value_type &val) { if (end_idx_ == start_idx_ && !empty()) reserve(capacity() * 1.5); alloc_.construct(array_ + end_idx_, val); // array_[end_idx_] = val; increment(kEnd); } // @brief Exchanges the content of the container by the content of x, which is // another %circular_vector object of the same type. Sizes may differ. // @param x The %circular_vector of the same type to swap with. void swap(circular_vector &x) { std::swap(size_, x.size_); std::swap(capacity_, x.capacity_); std::swap(start_idx_, x.start_idx_); std::swap(end_idx_, x.end_idx_); std::swap(array_, x.array_); } // @brief Removes all elements from the @circular_vector (which are destroyed), // leaving the container with a size of 0. // @warn If the elements themselves are pointers, the pointed-to memory is not // touched in any way. Managing the pointer is the user's responsibility. void clear() { for (size_type x = 0; x < size(); ++x) { alloc_.destroy(array_ + (start_idx_ + x) % capacity()); } start_idx_ = capacity() / 2; end_idx_ = capacity() /2; size_ = 0; } // ELEMENT ACCESS: // @brief Provides access to the data contained in %circular_vector // @param n The index of the element for which data should be accessed // @return Read/write reference to data // @warn Calling this function with an argument @a n that is out of range // causes undefined behaviour reference operator [] (size_type n) { return normalize(n); }; // @brief Provides access to the data contained in %circular_vector // @param n The index of the element for which data should be accessed // @return Read/write reference to data // @warn Calling this function with an argument @a n that is out of range // causes undefined behaviour const_reference operator [] (size_type n) const { return normalize(n); }; // @brief Provides access to the data contained in %circular_vector // @param n The index of the element for which data should be accessed // @return Read/write reference to data // @throw std::out_of_range If @a n is an invalid index reference at(size_type n) { if (n > size()-1) throw std::out_of_range("index larger than last index"); if (n < 0) throw std::out_of_range("negative index"); return normalize(n); }; // @brief Provides access to the data contained in %circular_vector // @param n The index of the element for which data should be accessed // @return Read-only (constant) reference to data // @throw std::out_of_range If @a n is an invalid index const_reference at(size_type n) const { if (n > size()-1) throw std::out_of_range("index larger than last index"); if (n < 0) throw std::out_of_range("negative index"); return normalize(n); }; // @return Read/Write reference to the first indexed element // in %circular_vector // @warn Calling this function on an empty container causes undefined // behaviour reference front() { return array_[start_idx_]; }; // @return Read-only (constant) reference to the first indexed element // in %circular_vector // @warn Calling this function on an empty container causes undefined // behaviour const_reference front() const { return array_[start_idx_]; }; // @return Read/Write reference to the last indexed element // in %circular_vector // @warn Calling this function on an empty container causes undefined // behaviour reference back() { return *(end()-1); }; // @return Read-only (constant) reference to the last indexed element // in %circular_vector // @warn Calling this function on an empty container causes undefined // behaviour const_reference back() const { return *(end()-1); }; private: // Number of elements in the %circular_vector size_type size_; // Currently allocatd memory of the %circular_vector size_type capacity_; // Index of the start of the %circular_vector in array_ size_type start_idx_; // Index of the end of the %circular_vector in array_ size_type end_idx_; // Defined Memory Allocator _Alloc alloc_; // The Data Storage Array value_type * array_; // HELPER FUNCTIONS: // @brief Increments the specified index and changes size appropriately // @param index The enum representing 0 - start_idx_ or 1 - end_idx_ void increment(const size_type index) { switch(index) { case kStart: start_idx_ = (start_idx_ + 1) % capacity(); --size_; break; case kEnd: end_idx_ = (end_idx_ + 1) % capacity_; ++size_; break; default: throw std::invalid_argument("invalid enumerator"); } } // @brief Decrements the specified index and changes size appropriately // @param index The enum representing 0 - start_idx_ or 1 - end_idx_ void decrement(const size_type index) { switch(index) { case kStart: if (start_idx_ == 0) start_idx_ = capacity() - 1; else --start_idx_; ++size_; break; case kEnd: if (end_idx_ == 0) end_idx_ = capacity() - 1; else --end_idx_; --size_; break; default: throw std::invalid_argument("invalid enumerator"); } } // @brief Returns the given index normalized to the %circular_vector wrapping // @param n The index of the element for which data should be accessed // @return Read/write reference to data // @warn Calling this function with an argument @a n that is out of range // causes undefined behaviour reference normalize(const size_type n) const { return array_[(start_idx_ + n) % capacity()]; } }; // RELATIONAL OPERATORS: // a==b template <typename _T, typename _Alloc> bool operator==(const circular_vector<_T, _Alloc> &a, const circular_vector<_T, _Alloc> &b) { return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin()); } // a!=b which is equivalent to !(a==b) template <typename _T, typename _Alloc> bool operator != (const circular_vector<_T, _Alloc> &a, const circular_vector<_T, _Alloc> &b) { return !(a==b); } // a<b template <typename _T, typename _Alloc> bool operator < (const circular_vector<_T, _Alloc> &a, const circular_vector<_T, _Alloc> &b) { return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end()); } // a>b template <typename _T, typename _Alloc> bool operator > (const circular_vector<_T, _Alloc> &a, const circular_vector<_T, _Alloc> &b) { return std::lexicographical_compare(b.begin(), b.end(), a.begin(), a.end()); } // a<=b which is equivalent to !(b<a) template <typename _T, typename _Alloc> bool operator <= (const circular_vector<_T, _Alloc> &a, const circular_vector<_T, _Alloc> &b) { return !(b<a); } // a>=b which is equivalent to !(a<b) template <typename _T, typename _Alloc> bool operator >= (const circular_vector<_T, _Alloc> &a, const circular_vector<_T, _Alloc> &b) { return !(a<b); } // The iterator type for the %circular_vector container. // The following template class provides all variants of forward/reverse/const/noconst // iterators using template properties. // It is enough to instantiate it using %circular_vector // @sample usage: circular_vector<int>::iterator it = foo.begin(); // foo++... etc. template <typename _T_noconst, typename _T, typename _element_type> class circular_vector_iterator { public: typedef circular_vector_iterator<_T_noconst,_T,_element_type> self_type; typedef std::random_access_iterator_tag iterator_category; typedef typename _T::value_type value_type; typedef typename _T::size_type size_type; typedef typename _T::pointer pointer; typedef typename _T::const_pointer const_pointer; typedef typename _T::reference reference; typedef typename _T::const_reference const_reference; typedef typename _T::difference_type difference_type; circular_vector_iterator(_T * cbuffer, size_type index) : carray_(cbuffer), index_(index) {}; // Converting a non-const iterator to a const iterator circular_vector_iterator(const circular_vector_iterator<_T_noconst, _T_noconst, typename _T_noconst::value_type> &other) : carray_(other.carray_), index_(other.index_) {}; friend class circular_vector_iterator<_T, const _T, const _element_type>; // Use compiler generated copy constructor, copy assignment operator // and destructor _element_type &operator * () { return (*carray_)[index_]; }; _element_type *operator -> () { return &(operator * ()); }; self_type &operator ++ () { index_++; return *this; } self_type operator ++ (int) { self_type temp(*this); ++(*this); return temp; } self_type &operator -- () { index_--; return *this; } self_type operator -- (int) { self_type temp(*this); --(*this); return temp; } self_type operator + (difference_type n) const { self_type temp(*this); temp.index_ += n; return temp; } self_type &operator += (difference_type n) { index_ += n; return *this; } self_type operator - (difference_type n) const { self_type temp(*this); temp.index_ -= n; return temp; } self_type &operator -= (difference_type n) { index_ -= n; return *this; } difference_type operator - (const self_type &c) const { return index_ - c.index_; } bool operator == (const self_type &other) const { return index_ == other.index_ && carray_ == other.carray_; } bool operator != (const self_type &other) const { return index_ != other.index_ && carray_ == other.carray_; } bool operator >( const self_type &other) const { return index_ > other.index_; } bool operator >= (const self_type &other) const { return index_ >= other.index_; } bool operator <( const self_type &other) const { return index_ < other.index_; } bool operator <= (const self_type &other) const { return index_ <= other.index_; } private: _T * carray_; size_type index_; }; template <typename circular_vector_iterator_t> circular_vector_iterator_t operator + (const typename circular_vector_iterator_t::difference_type &a, const circular_vector_iterator_t &b) { return circular_vector_iterator_t(a) + b; } template <typename circular_vector_iterator_t> circular_vector_iterator_t operator - (const typename circular_vector_iterator_t::difference_type &a, const circular_vector_iterator_t &b) { return circular_vector_iterator_t(a) - b; } #endif
laser-turtle/ogaml
src/core/x11/stubs/utils.h
#ifndef CAML_STUBS_HEADER #define CAML_STUBS_HEADER #define CAML_NAME_SPACE #include <caml/custom.h> #include <caml/fail.h> #include <caml/callback.h> #include <caml/memory.h> #include <caml/alloc.h> #include <caml/mlvalues.h> #include <stdio.h> #include <string.h> #define Val_none Val_int(0) #define Some_val(v) Field(v,0) static struct custom_operations XVisualInfo_custom_ops; #define XVisualInfo_val(v) ((XVisualInfo*) Data_custom_val(v)) #define XVisualInfo_alloc(a) (a = caml_alloc_custom(&XVisualInfo_custom_ops, sizeof(XVisualInfo), 0, 1)) #define XVisualInfo_copy(a,b) (memcpy(Data_custom_val(a), b, sizeof(XVisualInfo))) static struct custom_operations XEvent_custom_ops; #define XEvent_val(v) (*(XEvent*) Data_custom_val(v)) #define XEvent_alloc(a) (a = caml_alloc_custom(&XEvent_custom_ops, sizeof(XEvent), 0, 1)) #define XEvent_copy(a,b) (memcpy(Data_custom_val(a), b, sizeof(XEvent))) static struct custom_operations Window_custom_ops; #define Window_val(v) (*(Window*) Data_custom_val(v)) #define Window_alloc(a) (a = caml_alloc_custom(&Window_custom_ops, sizeof(Window), 0, 1)) #define Window_copy(a,b) (memcpy(Data_custom_val(a), b, sizeof(Window))) #define Val_Display(v) ((value) v) #define Display_val(v) ((Display*) v) #define Val_GLXContext(v) ((value) v) #define GLXContext_val(v) ((GLXContext) v) value Val_some(value v); value Int_pair(int a, int b); #endif
laser-turtle/ogaml
src/graphics/stubs/vbo_stubs.c
#define GL_GLEXT_PROTOTYPES #if defined(_WIN32) #include <windows.h> #include <gl/glew.h> #endif #if defined(__APPLE__) #include <OpenGL/gl3.h> #ifndef GL_TESS_CONTROL_SHADER #define GL_TESS_CONTROL_SHADER 0x00008e88 #endif #ifndef GL_TESS_EVALUATION_SHADER #define GL_TESS_EVALUATION_SHADER 0x00008e87 #endif #ifndef GL_PATCHES #define GL_PATCHES 0x0000000e #endif #else #include <GL/gl.h> #endif #include <caml/bigarray.h> #include <string.h> #include "utils.h" #include "types_stubs.h" #define BUFFER(_a) (*(GLuint*) Data_custom_val(_a)) void finalise_buffer(value v) { glDeleteBuffers(1,&BUFFER(v)); } int compare_buffer(value v1, value v2) { GLuint i1 = BUFFER(v1); GLuint i2 = BUFFER(v2); if(i1 < i2) return -1; else if(i1 == i2) return 0; else return 1; } intnat hash_buffer(value v) { GLuint i = BUFFER(v); return i; } static struct custom_operations buffer_custom_ops = { "buffer gc handling", finalise_buffer, compare_buffer, hash_buffer, custom_serialize_default, custom_deserialize_default }; // INPUT nothing // OUTPUT a buffer name CAMLprim value caml_create_buffer(value unit) { CAMLparam0(); CAMLlocal1(v); GLuint buf[1]; glGenBuffers(1, buf); v = caml_alloc_custom( &buffer_custom_ops, sizeof(GLuint), 0, 1); memcpy( Data_custom_val(v), buf, sizeof(GLuint) ); CAMLreturn(v); } // INPUT a buffer name // OUTPUT nothing, binds the buffer CAMLprim value caml_bind_vbo(value buf) { CAMLparam1(buf); if(buf == Val_none) glBindBuffer(GL_ARRAY_BUFFER, 0); else glBindBuffer(GL_ARRAY_BUFFER, BUFFER(Some_val(buf))); CAMLreturn(Val_unit); } // INPUT a buffer name // OUTPUT nothing, deletes the buffer CAMLprim value caml_destroy_buffer(value buf) { CAMLparam1(buf); glDeleteBuffers(1, &BUFFER(buf)); CAMLreturn(Val_unit); } // INPUT a length, some data (option), a mode // OUTPUT nothing, updates the bound buffer with the data CAMLprim value caml_vbo_data(value len, value opt, value mode) { CAMLparam3(len, opt, mode); if(opt == Val_none) glBufferData(GL_ARRAY_BUFFER, Int_val(len), NULL, VBOKind_val(mode)); else { const GLvoid* c_dat = Caml_ba_data_val(Field(Some_val(opt),0)); glBufferData(GL_ARRAY_BUFFER, Int_val(len), c_dat, VBOKind_val(mode)); } CAMLreturn(Val_unit); } // INPUT an offset, a length, some data // OUTPUT nothing, updates a sub-buffer with the data CAMLprim value caml_vbo_subdata(value off, value len, value data) { CAMLparam3(off, len, data); const GLvoid* c_dat = Caml_ba_data_val(Field(data,0)); glBufferSubData(GL_ARRAY_BUFFER, Int_val(off), Int_val(len), c_dat); CAMLreturn(Val_unit); } // INPUT two buffers, two offsets, a length // OUTPUT nothing, copy length bytes from the first buffer to the second one CAMLprim value caml_vbo_copy_subdata(value bufr, value bufw, value offr, value offw, value length) { CAMLparam5(bufr, bufw, offr, offw, length); glBindBuffer(GL_COPY_READ_BUFFER , BUFFER(bufr)); glBindBuffer(GL_COPY_WRITE_BUFFER, BUFFER(bufw)); glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, Int_val(offr), Int_val(offw), Int_val(length)); glBindBuffer(GL_COPY_READ_BUFFER , 0); glBindBuffer(GL_COPY_WRITE_BUFFER, 0); CAMLreturn(Val_unit); }
laser-turtle/ogaml
src/graphics/stubs/program_stubs.c
<filename>src/graphics/stubs/program_stubs.c #define GL_GLEXT_PROTOTYPES #if defined(_WIN32) #include <windows.h> #include <gl/glew.h> #endif #if defined(__APPLE__) #include <OpenGL/gl3.h> #ifndef GL_TESS_CONTROL_SHADER #define GL_TESS_CONTROL_SHADER 0x00008e88 #endif #ifndef GL_TESS_EVALUATION_SHADER #define GL_TESS_EVALUATION_SHADER 0x00008e87 #endif #ifndef GL_PATCHES #define GL_PATCHES 0x0000000e #endif #else #include <GL/gl.h> #endif #include <string.h> #include "utils.h" #include "types_stubs.h" #define PROGRAM(_a) (*(GLuint*) Data_custom_val(_a)) void finalise_program(value v) { glDeleteProgram(PROGRAM(v)); } int compare_program(value v1, value v2) { GLuint i1 = PROGRAM(v1); GLuint i2 = PROGRAM(v2); if(i1 < i2) return -1; else if(i1 == i2) return 0; else return 1; } intnat hash_program(value v) { GLuint i = PROGRAM(v); return i; } static struct custom_operations program_custom_ops = { "program gc handling", finalise_program, compare_program, hash_program, custom_serialize_default, custom_deserialize_default }; // INPUT nothing // OUTPUT a new gl program CAMLprim value caml_create_program(value unit) { CAMLparam0(); CAMLlocal1(v); GLuint prog = glCreateProgram(); v = caml_alloc_custom( &program_custom_ops, sizeof(GLuint), 0, 1); memcpy( Data_custom_val(v), &prog, sizeof(GLuint) ); CAMLreturn(v); } // INPUT a program // OUTPUT deletes the program CAMLprim value caml_delete_program(value prog) { CAMLparam1(prog); glDeleteProgram(PROGRAM(prog)); CAMLreturn(Val_unit); } // INPUT a program // OUTPUT true iff it is valid CAMLprim value caml_valid_program(value prog) { CAMLparam1(prog); CAMLreturn(Val_bool(PROGRAM(prog) != 0)); } // INPUT a program and a shader // OUTPUT nothing, attaches the shader CAMLprim value caml_attach_shader(value prog, value sh) { CAMLparam2(sh, prog); glAttachShader(PROGRAM(prog), (GLuint)sh); CAMLreturn(Val_unit); } // INPUT a program and a shader // OUTPUT nothing, detaches the shader CAMLprim value caml_detach_shader(value prog, value sh) { CAMLparam2(sh, prog); glDetachShader(PROGRAM(prog), (GLuint)sh); CAMLreturn(Val_unit); } // INPUT a program and an attribute name // OUTPUT returns the location of the attribute CAMLprim value caml_attrib_location(value prog, value str) { CAMLparam2(prog, str); CAMLreturn(Val_int(glGetAttribLocation(PROGRAM(prog),String_val(str)))); } // INPUT a program // OUTPUT returns the number of active uniforms CAMLprim value caml_uniform_count(value prog) { CAMLparam1(prog); GLint tmp; glGetProgramiv(PROGRAM(prog), GL_ACTIVE_UNIFORMS, &tmp); CAMLreturn(Val_int(tmp)); } // INPUT a program // OUTPUT returns the number of active attributes CAMLprim value caml_attribute_count(value prog) { CAMLparam1(prog); GLint tmp; glGetProgramiv(PROGRAM(prog), GL_ACTIVE_ATTRIBUTES, &tmp); CAMLreturn(Val_int(tmp)); } // INPUT a program and a uniform name // OUTPUT returns the location of the uniform CAMLprim value caml_uniform_location(value prog, value str) { CAMLparam2(prog, str); CAMLreturn(Val_int(glGetUniformLocation(PROGRAM(prog),String_val(str)))); } // INPUT a program // OUTPUT nothing, links the program CAMLprim value caml_link_program(value prog) { CAMLparam1(prog); glLinkProgram(PROGRAM(prog)); CAMLreturn(Val_unit); } // INPUT a program // OUTPUT returns true iff the linking was successful CAMLprim value caml_program_status(value prog) { CAMLparam1(prog); GLint tmp; glGetProgramiv(PROGRAM(prog), GL_LINK_STATUS, &tmp); if(tmp == GL_FALSE) CAMLreturn(Val_false); else CAMLreturn(Val_true); } // INPUT a program option // OUTPUT nothing, uses the program (if provided) CAMLprim value caml_use_program(value prog) { CAMLparam1(prog); if(prog == Val_none) glUseProgram(0); else glUseProgram(PROGRAM(Some_val(prog))); CAMLreturn(Val_unit); } // INPUT : a program id // OUTPUT : the log of the program CAMLprim value caml_program_log(value id) { CAMLparam1(id); CAMLlocal1(res); GLint tmp; GLsizei maxl; GLsizei len[1] = {0}; GLchar* log; glGetProgramiv(PROGRAM(id), GL_INFO_LOG_LENGTH, &tmp); maxl = tmp; log = malloc(tmp * sizeof(GLchar)); glGetProgramInfoLog(PROGRAM(id), maxl, len, log); res = caml_copy_string(log); free(log); CAMLreturn(res); } // INPUT : a program id, a uniform index // OUTPUT : the name of the uniform CAMLprim value caml_uniform_name(value id, value index) { CAMLparam2(id,index); CAMLlocal1(res); GLint tmp; GLsizei maxl; GLsizei tmp_len; GLint tmp_size; GLenum tmp_type; GLchar* name; glGetProgramiv(PROGRAM(id), GL_ACTIVE_UNIFORM_MAX_LENGTH, &tmp); maxl = tmp; name = malloc(tmp * sizeof(GLchar)); glGetActiveUniform(PROGRAM(id), Int_val(index), maxl, &tmp_len, &tmp_size, &tmp_type, name); res = caml_copy_string(name); free(name); CAMLreturn(res); } // INPUT : a program id, an attribute index // OUTPUT : the name of the attribute CAMLprim value caml_attribute_name(value id, value index) { CAMLparam2(id,index); CAMLlocal1(res); GLint tmp; GLsizei maxl; GLsizei tmp_len; GLint tmp_size; GLenum tmp_type; GLchar* name; glGetProgramiv(PROGRAM(id), GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &tmp); maxl = tmp; name = malloc(tmp * sizeof(GLchar)); glGetActiveAttrib(PROGRAM(id), Int_val(index), maxl, &tmp_len, &tmp_size, &tmp_type, name); res = caml_copy_string(name); free(name); CAMLreturn(res); } // INPUT : a program id, a uniform index // OUTPUT : the type of the uniform CAMLprim value caml_uniform_type(value id, value index) { CAMLparam2(id,index); CAMLlocal1(res); GLsizei tmp_len; GLint tmp_size; GLenum tmp_type; GLchar tmp_name; glGetActiveUniform(PROGRAM(id), Int_val(index), 0, &tmp_len, &tmp_size, &tmp_type, &tmp_name); CAMLreturn(Val_int(Val_attrib_type(tmp_type))); } // INPUT : a program id, an attribute index // OUTPUT : the type of the attribute CAMLprim value caml_attribute_type(value id, value index) { CAMLparam2(id,index); CAMLlocal1(res); GLsizei tmp_len; GLint tmp_size; GLenum tmp_type; GLchar tmp_name; glGetActiveAttrib(PROGRAM(id), Int_val(index), 0, &tmp_len, &tmp_size, &tmp_type, &tmp_name); CAMLreturn(Val_int(Val_attrib_type(tmp_type))); }
laser-turtle/ogaml
src/graphics/stubs/rbo_stubs.c
#define GL_GLEXT_PROTOTYPES #if defined(_WIN32) #include <windows.h> #include <gl/glew.h> #endif #if defined(__APPLE__) #include <OpenGL/gl3.h> #ifndef GL_TESS_CONTROL_SHADER #define GL_TESS_CONTROL_SHADER 0x00008e88 #endif #ifndef GL_TESS_EVALUATION_SHADER #define GL_TESS_EVALUATION_SHADER 0x00008e87 #endif #ifndef GL_PATCHES #define GL_PATCHES 0x0000000e #endif #else #include <GL/gl.h> #endif #include <caml/bigarray.h> #include <string.h> #include "utils.h" #include "types_stubs.h" #define RBO(_a) (*(GLuint*) Data_custom_val(_a)) void finalise_rbo(value v) { glDeleteRenderbuffers(1,&RBO(v)); } int compare_rbo(value v1, value v2) { GLuint i1 = RBO(v1); GLuint i2 = RBO(v2); if(i1 < i2) return -1; else if(i1 == i2) return 0; else return 1; } intnat hash_rbo(value v) { GLuint i = RBO(v); return i; } static struct custom_operations rbo_custom_ops = { "rbo gc handling", finalise_rbo, compare_rbo, hash_rbo, custom_serialize_default, custom_deserialize_default }; // INPUT nothing // OUTPUT an RBO name CAMLprim value caml_create_rbo(value unit) { CAMLparam0(); CAMLlocal1(v); GLuint buf[1]; glGenRenderbuffers(1, buf); v = caml_alloc_custom( &rbo_custom_ops, sizeof(GLuint), 0, 1); memcpy( Data_custom_val(v), buf, sizeof(GLuint) ); CAMLreturn(v); } // INPUT : an RBO name // OUTPUT : nothing, binds the RBO CAMLprim value caml_bind_rbo(value buf) { CAMLparam1(buf); if(buf == Val_none) glBindRenderbuffer(GL_RENDERBUFFER, 0); else { glBindRenderbuffer(GL_RENDERBUFFER, RBO(Some_val(buf))); } CAMLreturn(Val_unit); } // INPUT : an RBO name // OUTPUT : nothing, deletes the RBO CAMLprim value caml_destroy_rbo(value buf) { CAMLparam1(buf); glDeleteRenderbuffers(1, &RBO(buf)); CAMLreturn(Val_unit); } // INPUT : an internal format, width, height // OUTPUT : nothing, creates a storage for the bound RBO CAMLprim value caml_rbo_storage(value format, value width, value height) { CAMLparam3(format,width,height); glRenderbufferStorage(GL_RENDERBUFFER, TextureFormat_val(format), Int_val(width), Int_val(height)); CAMLreturn(Val_unit); }
laser-turtle/ogaml
src/graphics/stubs/uniform_stubs.c
#define GL_GLEXT_PROTOTYPES #if defined(_WIN32) #include <windows.h> #include <gl/glew.h> #endif #if defined(__APPLE__) #include <OpenGL/gl3.h> #ifndef GL_TESS_CONTROL_SHADER #define GL_TESS_CONTROL_SHADER 0x00008e88 #endif #ifndef GL_TESS_EVALUATION_SHADER #define GL_TESS_EVALUATION_SHADER 0x00008e87 #endif #ifndef GL_PATCHES #define GL_PATCHES 0x0000000e #endif #else #include <GL/gl.h> #endif #include <caml/bigarray.h> #include "utils.h" CAMLprim value caml_uniform1f(value loc, value v) { CAMLparam2(loc,v); glUniform1f((GLuint)Int_val(loc),Double_val(v)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform2f(value loc, value v1, value v2) { CAMLparam3(loc,v1,v2); glUniform2f((GLuint)Int_val(loc),Double_val(v1),Double_val(v2)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform3f(value loc, value v1, value v2, value v3) { CAMLparam4(loc,v1,v2,v3); glUniform3f((GLuint)Int_val(loc),Double_val(v1),Double_val(v2),Double_val(v3)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform4f(value loc, value v1, value v2, value v3, value v4) { CAMLparam5(loc,v1,v2,v3,v4); glUniform4f((GLuint)Int_val(loc),Double_val(v1),Double_val(v2),Double_val(v3),Double_val(v4)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform1i(value loc, value v) { CAMLparam2(loc,v); glUniform1i((GLuint)Int_val(loc),Int_val(v)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform2i(value loc, value v1, value v2) { CAMLparam3(loc,v1,v2); glUniform2i((GLuint)Int_val(loc),Int_val(v1),Int_val(v2)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform3i(value loc, value v1, value v2, value v3) { CAMLparam4(loc,v1,v2,v3); glUniform3i((GLuint)Int_val(loc),Int_val(v1),Int_val(v2),Int_val(v3)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform4i(value loc, value v1, value v2, value v3, value v4) { CAMLparam5(loc,v1,v2,v3,v4); glUniform4i((GLuint)Int_val(loc),Int_val(v1),Int_val(v2),Int_val(v3),Int_val(v4)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform1ui(value loc, value v) { CAMLparam2(loc,v); glUniform1ui((GLuint)Int_val(loc),Int_val(v)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform2ui(value loc, value v1, value v2) { CAMLparam3(loc,v1,v2); glUniform2ui((GLuint)Int_val(loc),Int_val(v1),Int_val(v2)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform3ui(value loc, value v1, value v2, value v3) { CAMLparam4(loc,v1,v2,v3); glUniform3ui((GLuint)Int_val(loc),Int_val(v1),Int_val(v2),Int_val(v3)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform4ui(value loc, value v1, value v2, value v3, value v4) { CAMLparam5(loc,v1,v2,v3,v4); glUniform4ui((GLuint)Int_val(loc),Int_val(v1),Int_val(v2),Int_val(v3),Int_val(v4)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform_mat2(value loc, value dat) { CAMLparam2(loc,dat); glUniformMatrix2fv((GLuint)Int_val(loc), 1, GL_FALSE, (GLfloat*)Caml_ba_data_val(dat)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform_mat3(value loc, value dat) { CAMLparam2(loc,dat); glUniformMatrix3fv((GLuint)Int_val(loc), 1, GL_FALSE, (GLfloat*)Caml_ba_data_val(dat)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform_mat4(value loc, value dat) { CAMLparam2(loc,dat); glUniformMatrix4fv((GLuint)Int_val(loc), 1, GL_FALSE, (GLfloat*)Caml_ba_data_val(dat)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform_mat23(value loc, value dat) { CAMLparam2(loc,dat); glUniformMatrix2x3fv((GLuint)Int_val(loc), 1, GL_FALSE, (GLfloat*)Caml_ba_data_val(dat)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform_mat32(value loc, value dat) { CAMLparam2(loc,dat); glUniformMatrix3x2fv((GLuint)Int_val(loc), 1, GL_FALSE, (GLfloat*)Caml_ba_data_val(dat)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform_mat24(value loc, value dat) { CAMLparam2(loc,dat); glUniformMatrix2x4fv((GLuint)Int_val(loc), 1, GL_FALSE, (GLfloat*)Caml_ba_data_val(dat)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform_mat42(value loc, value dat) { CAMLparam2(loc,dat); glUniformMatrix4x2fv((GLuint)Int_val(loc), 1, GL_FALSE, (GLfloat*)Caml_ba_data_val(dat)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform_mat34(value loc, value dat) { CAMLparam2(loc,dat); glUniformMatrix3x4fv((GLuint)Int_val(loc), 1, GL_FALSE, (GLfloat*)Caml_ba_data_val(dat)); CAMLreturn(Val_unit); } CAMLprim value caml_uniform_mat43(value loc, value dat) { CAMLparam2(loc,dat); glUniformMatrix4x3fv((GLuint)Int_val(loc), 1, GL_FALSE, (GLfloat*)Caml_ba_data_val(dat)); CAMLreturn(Val_unit); }
laser-turtle/ogaml
src/core/x11/stubs/event_stubs.c
<gh_stars>10-100 #include <X11/Xlib.h> #include <X11/Xutil.h> #include "utils.h" #include <memory.h> // INPUT display, window, mask list // OUTPUT nothing, updates the event mask of the window CAMLprim value caml_xselect_input(value disp, value win, value masks) { CAMLparam3(disp, win, masks); CAMLlocal2(hd, tl); Display* dpy = Display_val(disp); Window w = Window_val(win); int mask = 0; tl = masks; while(tl != Val_emptylist) { hd = Field(tl,0); tl = Field(tl,1); mask |= (1L << (Int_val(hd))); } XSelectInput(dpy, w, mask); CAMLreturn(Val_unit); } // Tests if an event happens in the right window Bool checkEvent(Display* disp, XEvent* evt, XPointer window) { return evt->xany.window == (Window)window; } // INPUT display, window // OUTPUT a pointer on an event (if it exists) in the current window CAMLprim value caml_xnext_event(value disp, value win) { CAMLparam1(disp); CAMLlocal2(res, ev); Display* dpy = Display_val(disp); Window w = Window_val(win); XEvent event; if(XCheckIfEvent(dpy, &event, &checkEvent, (XPointer)w) == True) { XEvent_alloc(ev); XEvent_copy(ev, &event); res = Val_some(ev); } else { res = Val_int(0); } CAMLreturn(res); } // Extract the key out of an xkey event value extract_keysym(XEvent* evt) { CAMLparam0(); CAMLlocal1(key); static XComposeStatus keyboard; char buffer[32]; KeySym result; XEvent cpy = *evt; cpy.xkey.state &= (~ShiftMask) & (~ControlMask) & (~LockMask) & (~AnyModifier); XLookupString(&cpy.xkey, buffer, sizeof(buffer), &result, &keyboard); if(result >= 97 && result <= 122) { key = caml_alloc(1,1); Store_field(key, 0, Val_int(result)); } else { key = caml_alloc(1,0); Store_field(key, 0, Val_int(evt->xkey.keycode)); } CAMLreturn(key); } // Extract the event out of an XEvent structure // Warning : event types begin at 2, and one needs to // be careful about the parametric variants // plus there is the Unknown type (0) in Ocaml value extract_event(XEvent* evt) { CAMLparam0(); CAMLlocal3(result, position, modifiers); switch(evt->type) { case KeyPress : result = caml_alloc(2,0); // 1st param. variant modifiers = caml_alloc(4,0); Store_field(modifiers, 0, Val_bool((evt->xkey.state & ShiftMask) != 0)); Store_field(modifiers, 1, Val_bool((evt->xkey.state & ControlMask) != 0)); Store_field(modifiers, 2, Val_bool((evt->xkey.state & LockMask) != 0)); Store_field(modifiers, 3, Val_bool((evt->xkey.state & Mod1Mask) != 0)); Store_field(result, 0, extract_keysym(evt)); Store_field(result, 1, modifiers); break; case KeyRelease : result = caml_alloc(2,1); // 2nd param. variant modifiers = caml_alloc(4,0); Store_field(modifiers, 0, Val_bool((evt->xkey.state & ShiftMask) != 0)); Store_field(modifiers, 1, Val_bool((evt->xkey.state & ControlMask) != 0)); Store_field(modifiers, 2, Val_bool((evt->xkey.state & LockMask) != 0)); Store_field(modifiers, 3, Val_bool((evt->xkey.state & Mod1Mask) != 0)); Store_field(result, 0, extract_keysym(evt)); Store_field(result, 1, modifiers); break; case ButtonPress : result = caml_alloc(3,2); // 3rd param. variant position = caml_alloc(2,0); Store_field(position, 0, Val_int(evt->xbutton.x)); Store_field(position, 1, Val_int(evt->xbutton.y)); modifiers = caml_alloc(4,0); Store_field(modifiers, 0, Val_bool((evt->xbutton.state & ShiftMask) != 0)); Store_field(modifiers, 1, Val_bool((evt->xbutton.state & ControlMask) != 0)); Store_field(modifiers, 2, Val_bool((evt->xbutton.state & LockMask) != 0)); Store_field(modifiers, 3, Val_bool((evt->xbutton.state & AnyModifier) != 0)); Store_field(result, 0, Val_int(evt->xbutton.button)); Store_field(result, 1, position); Store_field(result, 2, modifiers); break; case ButtonRelease : result = caml_alloc(3,3); // 4th param. variant position = caml_alloc(2,0); Store_field(position, 0, Val_int(evt->xbutton.x)); Store_field(position, 1, Val_int(evt->xbutton.y)); modifiers = caml_alloc(4,0); Store_field(modifiers, 0, Val_bool((evt->xbutton.state & ShiftMask) != 0)); Store_field(modifiers, 1, Val_bool((evt->xbutton.state & ControlMask) != 0)); Store_field(modifiers, 2, Val_bool((evt->xbutton.state & LockMask) != 0)); Store_field(modifiers, 3, Val_bool((evt->xbutton.state & AnyModifier) != 0)); Store_field(result, 0, Val_int(evt->xbutton.button)); Store_field(result, 1, position); Store_field(result, 2, modifiers); break; case MotionNotify : result = caml_alloc(1,4); // 5th param. variant position = caml_alloc(2,0); Store_field(position, 0, Val_int(evt->xmotion.x)); Store_field(position, 1, Val_int(evt->xmotion.y)); Store_field(result, 0, position); break; case EnterNotify : result = Val_int(1); break; case LeaveNotify : result = Val_int(2); break; case FocusIn : result = Val_int(3); break; case FocusOut : result = Val_int(4); break; case KeymapNotify : result = Val_int(5); break; case Expose : result = Val_int(6); break; case GraphicsExpose : result = Val_int(7); break; case NoExpose : result = Val_int(8); break; case VisibilityNotify : result = Val_int(9); break; case CreateNotify : result = Val_int(10); break; case DestroyNotify : result = Val_int(11); break; case UnmapNotify : result = Val_int(12); break; case MapNotify : result = Val_int(13); break; case MapRequest : result = Val_int(14); break; case ReparentNotify : result = Val_int(15); break; case ConfigureNotify : result = Val_int(16); break; case ConfigureRequest : result = Val_int(17); break; case GravityNotify : result = Val_int(18); break; case ResizeRequest : result = Val_int(19); break; case CirculateNotify : result = Val_int(20); break; case CirculateRequest : result = Val_int(21); break; case PropertyNotify : result = Val_int(22); break; case SelectionClear : result = Val_int(23); break; case SelectionRequest : result = Val_int(24); break; case SelectionNotify : result = Val_int(25); break; case ColormapNotify : result = Val_int(26); break; // ClientMessage : get the Atom (message_type) case ClientMessage: // 33, 6th parametric variant result = caml_alloc(1,5); Store_field(result, 0, (value)evt->xclient.data.l[0]); break; case MappingNotify : result = Val_int(27); break; case GenericEvent : result = Val_int(28); break; case LASTEvent : result = Val_int(0); break; default: result = Val_int(0); break; } CAMLreturn(result); } // INPUT a pointer on an event // OUTPUT the type of the event CAMLprim value caml_event_type(value evt) { CAMLparam1(evt); CAMLlocal1(result); result = extract_event(&XEvent_val(evt)); CAMLreturn(result); }
laser-turtle/ogaml
src/core/x11/stubs/glx_stubs.c
#include <X11/Xlib.h> #include <GL/gl.h> #include <GL/glx.h> #include <memory.h> #include <stdio.h> #include "utils.h" // INPUT : a display, a screen number, an attribute list // OUTPUT : a visual info satisfying the attribute list CAMLprim value caml_glx_choose_visual(value disp, value scr, value attributes, value len) { CAMLparam4(disp, scr, attributes, len); CAMLlocal3(hd,tl,res); int attrs[Int_val(len)+1]; int i = 0; int fbcount; Display* dpy = Display_val(disp); tl = attributes; while(tl != Val_emptylist) { hd = Field(tl, 0); tl = Field(tl, 1); if(Is_long(hd)) { attrs[i+1] = True; switch(Int_val(hd)) { case 0 : attrs[i] = GLX_DOUBLEBUFFER; break; case 1 : attrs[i] = GLX_STEREO; break; case 2 : attrs[i] = GLX_X_RENDERABLE; break; default: caml_failwith("Variant handling bug in glx_choose_visual"); } i += 2; } else { attrs[i+1] = Int_val(Field(hd,0)); switch(Tag_val(hd)) { case 0 : attrs[i] = GLX_BUFFER_SIZE; break; case 1 : attrs[i] = GLX_LEVEL ; break; case 2 : attrs[i] = GLX_AUX_BUFFERS; break; case 3 : attrs[i] = GLX_RED_SIZE ; break; case 4 : attrs[i] = GLX_GREEN_SIZE ; break; case 5 : attrs[i] = GLX_BLUE_SIZE ; break; case 6 : attrs[i] = GLX_ALPHA_SIZE ; break; case 7 : attrs[i] = GLX_DEPTH_SIZE ; break; case 8 : attrs[i] = GLX_STENCIL_SIZE ; break; case 9 : attrs[i] = GLX_ACCUM_RED_SIZE ; break; case 10 : attrs[i] = GLX_ACCUM_BLUE_SIZE ; break; case 11 : attrs[i] = GLX_ACCUM_ALPHA_SIZE; break; case 12 : attrs[i] = GLX_ACCUM_GREEN_SIZE; break; case 13 : attrs[i] = GLX_SAMPLES; break; case 14 : attrs[i] = GLX_SAMPLE_BUFFERS; break; default: caml_failwith("Variant handling bug in glx_choose_visual"); } i += 2; } } attrs[i] = None; GLXFBConfig* fbc = glXChooseFBConfig(dpy, Int_val(scr), attrs, &fbcount); XVisualInfo* vis = glXGetVisualFromFBConfig(dpy, fbc[0]); XVisualInfo_alloc(res); XVisualInfo_copy(res, vis); CAMLreturn(res); } // INPUT : a display, a visualinfo struct // OUTPUT : creates a context satisfying the visualinfo CAMLprim value caml_glx_create_context(value disp, value vi) { CAMLparam2(disp, vi); Display* dpy = Display_val(disp); XVisualInfo* xvi = XVisualInfo_val(vi); GLXContext tmp = glXCreateContext(dpy, xvi, NULL, True); // a GLXContext is a pointer CAMLreturn(Val_GLXContext(tmp)); } // INPUT : a display, a window // OUTPUT : swaps the buffer of the window CAMLprim value caml_glx_swap_buffers(value disp, value win) { CAMLparam2(disp, win); Display* dpy = Display_val(disp); Window w = Window_val(win); glXSwapBuffers(dpy, w); CAMLreturn(Val_unit); } // INPUT : a display, a window and a GLcontext // OUTPUT : nothing, binds the context to the window CAMLprim value caml_glx_make_current(value disp, value win, value ctx) { CAMLparam3(disp, win, ctx); Display* dpy = Display_val(disp); Window w = Window_val(win); GLXContext glc = GLXContext_val(ctx); glXMakeCurrent(dpy, w, glc); CAMLreturn(Val_unit); } // INPUT : a display, a context // OUTPUT : nothing, frees the context CAMLprim value caml_glx_destroy_context(value disp, value ctx) { CAMLparam2(disp, ctx); Display* dpy = Display_val(disp); GLXContext glc = GLXContext_val(ctx); glXDestroyContext(dpy, glc); CAMLreturn(Val_unit); } CAMLprim value caml_glcontext_debug(value unit) { CAMLparam0(); switch(glGetError()) { case GL_NO_ERROR: printf("No error\n"); break; case GL_INVALID_ENUM: printf("Invalid enum\n"); break; case GL_INVALID_VALUE: printf("Invalid value\n"); break; case GL_INVALID_OPERATION: printf("Invalid operation\n"); break; case GL_INVALID_FRAMEBUFFER_OPERATION: printf("Invalid FBO operation\n"); break; case GL_OUT_OF_MEMORY: printf("Out of memory\n"); break; #ifdef GL_STACK_UNDERFLOW case GL_STACK_UNDERFLOW: printf("Stack underflow\n"); break; #endif #ifdef GL_STACK_OVERFLOW case GL_STACK_OVERFLOW: printf("Stack overflow\n"); break; #endif default: break; } CAMLreturn(Val_unit); }
laser-turtle/ogaml
src/core/x11/stubs/display_stubs.c
#include <X11/Xlib.h> #include "utils.h" Display* current_display = NULL; // INPUT string option // OUTPUT display CAMLprim value caml_xopen_display(value name) { CAMLparam1(name); if(current_display != NULL) {} else if(name == Val_none) { current_display = XOpenDisplay(NULL); } else { current_display = XOpenDisplay(String_val(Some_val(name))); } CAMLreturn(Val_Display(current_display)); } // INPUT display, screen n° // OUTPUT int * int (size in px) CAMLprim value caml_xscreen_size(value disp, value screen) { CAMLparam2(disp, screen); Display* dpy = Display_val(disp); int w = XDisplayWidth (dpy, Int_val(screen)); int h = XDisplayHeight(dpy, Int_val(screen)); CAMLreturn(Int_pair(w,h)); } // INPUT display, screen n° // OUTPUT int * int (size in mm) CAMLprim value caml_xscreen_sizemm(value disp, value screen) { CAMLparam2(disp, screen); Display* dpy = Display_val(disp); int w = XDisplayWidthMM (dpy, Int_val(screen)); int h = XDisplayHeightMM (dpy, Int_val(screen)); CAMLreturn(Int_pair(w,h)); } // INPUT display // OUTPUT int (nb of screens) CAMLprim value caml_xscreen_count(value disp) { CAMLparam1(disp); Display* dpy = Display_val(disp); CAMLreturn(Val_int(XScreenCount(dpy))); } // INPUT display // OUTPUT int (default screen) CAMLprim value caml_xdefault_screen(value disp) { CAMLparam1(disp); Display* dpy = Display_val(disp); CAMLreturn(Val_int(XDefaultScreen(dpy))); } // INPUT display // OUTPUT nothing, flushes display CAMLprim value caml_xflush(value disp) { CAMLparam1(disp); Display* dpy = Display_val(disp); XFlush(dpy); CAMLreturn(Val_unit); }
laser-turtle/ogaml
src/core/x11/stubs/atoms_stubs.c
#include <X11/Xlib.h> #include <X11/Xatom.h> #include "utils.h" // Global atoms CAMLprim value caml_wm_add(value unit) { CAMLparam0(); CAMLreturn((Atom) 1); } CAMLprim value caml_wm_remove(value unit) { CAMLparam0(); CAMLreturn((Atom) 0); } CAMLprim value caml_wm_toggle(value unit) { CAMLparam0(); CAMLreturn((Atom) 2); } // INPUT display, atom name, boolean // OUTPUT returns an atom option, // creates the corresponding atom if the boolean is false CAMLprim value caml_xintern_atom(value disp, value nm, value exists) { CAMLparam3(disp, nm, exists); Display* dpy = Display_val(disp); Atom tmp = XInternAtom(dpy, String_val(nm), Bool_val(exists)); if(tmp == None) CAMLreturn(Val_int(0)); else CAMLreturn(Val_some((value)tmp)); } // INPUT display, window, atom array, length // OUTPUT nothing, applies the atoms to the window CAMLprim value caml_xset_wm_protocols(value disp, value win, value atoms, value size) { CAMLparam4(disp, win, atoms, size); Display* dpy = Display_val(disp); Window w = Window_val(win); Atom tmp[Int_val(size)]; int i = 0; for(i = 0; i < Int_val(size); i++) { tmp[i] = (Atom) Field(atoms, i); } XSetWMProtocols(dpy, w, tmp, Int_val(size)); CAMLreturn(Val_unit); } // INPUT display, window, atom property, atom array, length // OUTPUT nothing applies the properties CAMLprim value caml_xchange_property(value disp, value win, value prop, value atoms, value length) { CAMLparam5(disp, win, prop, atoms, length); Display* dpy = Display_val(disp); Window w = Window_val(win); Atom tmp[Int_val(length)+1]; int i = 0; for(i = 0; i < Int_val(length); i++) { tmp[i] = (Atom) Field(atoms, i); } tmp[Int_val(length)] = None; XChangeProperty(dpy, w, (Atom) prop, XA_ATOM, 32, PropModeReplace, (unsigned char*) tmp, Int_val(length)); CAMLreturn(Val_unit); } // INPUT display, window, property, data, length // OUTPUT nothing, sends an event CAMLprim value caml_xsend_event(value disp, value win, value prop, value atoms, value length) { CAMLparam5(disp, win, prop, atoms, length); Display* dpy = Display_val(disp); Window w = Window_val(win); XEvent xev; int i = 0; for(i = 0; i < Int_val(length); i++) { xev.xclient.data.l[i] = (Atom) Field(atoms, i); } xev.xclient.data.l[Int_val(length)] = None; xev.xclient.type = ClientMessage; xev.xclient.serial = 0; xev.xclient.send_event = True; xev.xclient.window = w; xev.xclient.message_type = (Atom) prop; xev.xclient.format = 32; XSendEvent(dpy, DefaultRootWindow(dpy), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); CAMLreturn(Val_unit); }
laser-turtle/ogaml
src/graphics/stubs/render_stubs.c
<reponame>laser-turtle/ogaml #define GL_GLEXT_PROTOTYPES #if defined(_WIN32) #include <windows.h> #include <gl/glew.h> #endif #if defined(__APPLE__) #include <OpenGL/gl3.h> #ifndef GL_TESS_CONTROL_SHADER #define GL_TESS_CONTROL_SHADER 0x00008e88 #endif #ifndef GL_TESS_EVALUATION_SHADER #define GL_TESS_EVALUATION_SHADER 0x00008e87 #endif #ifndef GL_PATCHES #define GL_PATCHES 0x0000000e #endif #else #include <GL/gl.h> #endif #include <caml/bigarray.h> #include "utils.h" #include "types_stubs.h" // INPUT three booleans (color, depth, stencil) // OUTPUT nothing, clears the corresponding buffers CAMLprim value caml_gl_clear(value c, value d, value s) { CAMLparam3(c,d,s); GLbitfield mask = 0; if (c == Val_true) mask |= GL_COLOR_BUFFER_BIT ; if (d == Val_true) mask |= GL_DEPTH_BUFFER_BIT ; if (s == Val_true) mask |= GL_STENCIL_BUFFER_BIT ; glClear(mask); CAMLreturn(Val_unit); } // INPUT nothing // OUTPUT returns a GL error (option) CAMLprim value caml_gl_error(value unit) { CAMLparam0(); CAMLreturn(Val_error(glGetError())); } // INPUT a parameter // OUTPUT returns the integer value of the parameter CAMLprim value caml_gl_get_integerv(value par) { CAMLparam1(par); int data; int param = Parameter_val(par); if(param == -1) data = -1; else glGetIntegerv(param,&data); CAMLreturn(Val_int(data)); } // INPUT four values r g b a // OUTPUT nothing, sets the clear color CAMLprim value caml_clear_color(value r, value g, value b, value a) { CAMLparam4(r,g,b,a); glClearColor( Double_val(r), Double_val(g), Double_val(b), Double_val(a) ); CAMLreturn(Val_unit); } // INPUT a culling mode // OUTPUT nothing, sets the culling mode CAMLprim value caml_culling_mode(value mode) { CAMLparam1(mode); GLenum val = Cull_val(mode); if(val != -1) { glEnable(GL_CULL_FACE); glFrontFace(val); } else glDisable(GL_CULL_FACE); CAMLreturn(Val_unit); } // INPUT a boolean // OUTPUT nothing, (des)activates MSAA CAMLprim value caml_enable_msaa(value active) { CAMLparam0(); if(Bool_val(active)) glEnable(GL_MULTISAMPLE); else glDisable(GL_MULTISAMPLE); CAMLreturn(Val_unit); } // INPUT a polygon mode // OUTPUT nothing, sets the polygon mode CAMLprim value caml_polygon_mode(value mode) { CAMLparam1(mode); glPolygonMode(GL_FRONT_AND_BACK, Polygon_val(mode)); CAMLreturn(Val_unit); } // INPUT a boolean // OUTPUT nothing, sets the current value of depth testing CAMLprim value caml_depth_test(value b) { CAMLparam1(b); if(Bool_val(b)) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); CAMLreturn(Val_unit); } // INPUT a boolean // OUTPUT nothing, sets the current value of depth writing CAMLprim value caml_depth_mask(value b) { CAMLparam1(b); if(Bool_val(b)) glDepthMask(GL_TRUE); else glDepthMask(GL_FALSE); CAMLreturn(Val_unit); } // INPUT a depth function // OUTPUT nothing, sets the current value of the depth function CAMLprim value caml_depth_fun(value f) { CAMLparam1(f); glDepthFunc(Depthfun_val(f)); CAMLreturn(Val_unit); } // INPUT x, y, width, height // OUTPUT nothing, sets the glViewport CAMLprim value caml_viewport(value x, value y, value w, value h) { CAMLparam4(x,y,w,h); glViewport(Int_val(x), Int_val(y), Int_val(w), Int_val(h)); CAMLreturn(Val_unit); } // INPUT nothing // OUTPUT the current GL version CAMLprim value caml_gl_version(value unit) { CAMLparam0(); CAMLreturn(caml_copy_string(glGetString(GL_VERSION))); } // INPUT nothing // OUTPUT the current GLSL version CAMLprim value caml_glsl_version(value unit) { CAMLparam0(); CAMLreturn(caml_copy_string(glGetString(GL_SHADING_LANGUAGE_VERSION))); } // INPUT nothing // OUTPUT nothing, flushes the current buffer CAMLprim value caml_glflush(value unit) { CAMLparam0(); glFlush(); CAMLreturn(Val_unit); } // INPUT nothing // OUTPUT nothing, finishes the pending actions CAMLprim value caml_glfinish(value unit) { CAMLparam0(); glFinish(); CAMLreturn(Val_unit); } // INPUT top-left corner, size, pixel format // OUTPUT pixel data (bytes) CAMLprim value caml_read_pixels(value topl, value size, value pfmt) { CAMLparam3(topl, size, pfmt); CAMLlocal1(res); int x,y,w,h; x = Int_val(Field(topl,0)); y = Int_val(Field(topl,1)); w = Int_val(Field(size,0)); h = Int_val(Field(size,1)); // TODO: multiply by format size in bytes res = caml_alloc_string((w-x)*(h-y)*4); glReadPixels(x,y,w,h,PixelFormat_val(pfmt),GL_UNSIGNED_BYTE,String_val(res)); CAMLreturn(res); }
laser-turtle/ogaml
src/graphics/stubs/fbo_stubs.c
<reponame>laser-turtle/ogaml<gh_stars>10-100 #define GL_GLEXT_PROTOTYPES #if defined(_WIN32) #include <windows.h> #include <gl/glew.h> #endif #if defined(__APPLE__) #include <OpenGL/gl3.h> #ifndef GL_TESS_CONTROL_SHADER #define GL_TESS_CONTROL_SHADER 0x00008e88 #endif #ifndef GL_TESS_EVALUATION_SHADER #define GL_TESS_EVALUATION_SHADER 0x00008e87 #endif #ifndef GL_PATCHES #define GL_PATCHES 0x0000000e #endif #else #include <GL/gl.h> #endif #include <caml/bigarray.h> #include <string.h> #include "utils.h" #include "types_stubs.h" #define TEX(_a) (*(GLuint*) Data_custom_val(_a)) #define RBO(_a) (*(GLuint*) Data_custom_val(_a)) #define FBO(_a) (*(GLuint*) Data_custom_val(_a)) void finalise_fbo(value v) { glDeleteFramebuffers(1,&FBO(v)); } int compare_fbo(value v1, value v2) { GLuint i1 = FBO(v1); GLuint i2 = FBO(v2); if(i1 < i2) return -1; else if(i1 == i2) return 0; else return 1; } intnat hash_fbo(value v) { GLuint i = FBO(v); return i; } static struct custom_operations fbo_custom_ops = { "fbo gc handling", finalise_fbo, compare_fbo, hash_fbo, custom_serialize_default, custom_deserialize_default }; // INPUT nothing // OUTPUT an FBO name CAMLprim value caml_create_fbo(value unit) { CAMLparam0(); CAMLlocal1(v); GLuint buf[1]; glGenFramebuffers(1, buf); v = caml_alloc_custom( &fbo_custom_ops, sizeof(GLuint), 0, 1); memcpy( Data_custom_val(v), buf, sizeof(GLuint) ); CAMLreturn(v); } // INPUT : an FBO name // OUTPUT : nothing, binds the FBO CAMLprim value caml_bind_fbo(value buf) { CAMLparam1(buf); if(buf == Val_none) glBindFramebuffer(GL_FRAMEBUFFER, 0); else { glBindFramebuffer(GL_FRAMEBUFFER, FBO(Some_val(buf))); } CAMLreturn(Val_unit); } // INPUT : an FBO name // OUTPUT : nothing, deletes the FBO CAMLprim value caml_destroy_fbo(value buf) { CAMLparam1(buf); glDeleteFramebuffers(1, &FBO(buf)); CAMLreturn(Val_unit); } // INPUT : an attachment point, a texture, a layer, a mipmap level // OUTPUT : nothing, attaches the texture to the currently bound FBO CAMLprim value caml_fbo_texture_layer(value atc, value tex, value layer, value level) { CAMLparam4(atc,tex,layer,level); glFramebufferTextureLayer(GL_FRAMEBUFFER, Attachment_val(atc), TEX(tex), Int_val(level), Int_val(layer)); CAMLreturn(Val_unit); } // INPUT : an attachment point, a texture, a mipmap level // OUTPUT : nothing, attaches the texture to the currently bound FBO CAMLprim value caml_fbo_texture2D(value atc, value tex, value level) { CAMLparam3(atc,tex,level); glFramebufferTexture2D(GL_FRAMEBUFFER, Attachment_val(atc), GL_TEXTURE_2D, TEX(tex), Int_val(level)); CAMLreturn(Val_unit); } // INPUT : an attachment point, an RBO // OUTPUT : nothing, attaches the RBO to the currently bound FBO CAMLprim value caml_fbo_renderbuffer(value atc, value rbo) { CAMLparam2(atc,rbo); glFramebufferRenderbuffer(GL_FRAMEBUFFER, Attachment_val(atc), GL_RENDERBUFFER, RBO(rbo)); CAMLreturn(Val_unit); }
laser-turtle/ogaml
src/core/windows/stubs/glew_stubs.c
#include <gl/glew.h> #include <gl/gl.h> #include "utils.h" #include <windows.h> #include <memory.h> CAMLprim value caml_glew_init(value unit) { CAMLparam0(); CAMLlocal1(res); GLenum err; glewExperimental = GL_TRUE; err = glewInit(); if(err != GLEW_OK) res = caml_copy_string(glewGetErrorString(res)); else res = caml_copy_string(""); CAMLreturn(res); }
laser-turtle/ogaml
src/graphics/stubs/shader_stubs.c
<filename>src/graphics/stubs/shader_stubs.c<gh_stars>10-100 #define GL_GLEXT_PROTOTYPES #if defined(_WIN32) #include <windows.h> #include <gl/glew.h> #endif #if defined(__APPLE__) #include <OpenGL/gl3.h> #ifndef GL_TESS_CONTROL_SHADER #define GL_TESS_CONTROL_SHADER 0x00008e88 #endif #ifndef GL_TESS_EVALUATION_SHADER #define GL_TESS_EVALUATION_SHADER 0x00008e87 #endif #ifndef GL_PATCHES #define GL_PATCHES 0x0000000e #endif #else #include <GL/gl.h> #endif #include <caml/bigarray.h> #include "utils.h" #include "types_stubs.h" // INPUT a shader type // OUTPUT a new shader id CAMLprim value caml_create_shader(value type) { CAMLparam1(type); CAMLreturn((value) glCreateShader(Shader_val(type))); } // INPUT a shader // OUTPUT deletes the shader CAMLprim value caml_delete_shader(value shader) { CAMLparam1(shader); glDeleteShader(shader); CAMLreturn(Val_unit); } // INPUT a shader // OUTPUT true iff it is valid CAMLprim value caml_valid_shader(value shader) { CAMLparam1(shader); CAMLreturn(Val_bool((GLuint)shader != 0)); } // INPUT a shader id, a source // OUTPUT nothing, changes the source code of the shader CAMLprim value caml_source_shader(value id, value src) { CAMLparam2(src, id); const GLchar* tmp_src = String_val(src); glShaderSource((GLuint)id, 1, &tmp_src, NULL); CAMLreturn(Val_unit); } // INPUT a shader id // OUTPUT nothing, compiles the shader CAMLprim value caml_compile_shader(value id) { CAMLparam1(id); glCompileShader((GLuint)id); CAMLreturn(Val_unit); } // INPUT a shader id // OUTPUT true iff the shader successfully compiled CAMLprim value caml_shader_status(value id) { CAMLparam1(id); GLint tmp; glGetShaderiv((GLuint)id, GL_COMPILE_STATUS, &tmp); if(tmp == GL_FALSE) CAMLreturn(Val_false); else CAMLreturn(Val_true); } // INPUT : a shader id // OUTPUT : the log of the shader CAMLprim value caml_shader_log(value id) { CAMLparam1(id); CAMLlocal1(res); GLint tmp; GLsizei maxl; GLsizei len[1] = {0}; GLchar* log; glGetShaderiv((GLuint)id, GL_INFO_LOG_LENGTH, &tmp); maxl = tmp; log = malloc(tmp * sizeof(GLchar)); glGetShaderInfoLog((GLuint)id, maxl, len, log); res = caml_copy_string(log); free(log); CAMLreturn(res); }