Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1451855
  • 博文数量: 596
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 173
  • 用 户 组: 普通用户
  • 注册时间: 2016-07-06 15:50
个人简介

在线笔记

文章分类

全部博文(596)

文章存档

2016年(1)

2015年(104)

2014年(228)

2013年(226)

2012年(26)

2011年(11)

分类: Windows平台

2014-04-19 14:17:43

http://www.codeproject.com/KB/system/driverdev6asp.aspx?fid=262328

  1. Introduction

  2. It has been a while since I have updated this series and I have found some free time to write the next version. In this article, we will take a look at how to write a simple display driver. A display driver is a special type of driver which fits into a framework that is unlike what we have talked about so far in this series.

  3. The example driver for this article will show how to write a basic display driver which does not have any hardware associated with it. Instead this display driver will implement graphics to memory and an application will be used to display those graphics. This method was demonstrated in an article I wrote for the C/C++ User



  1. The display miniport

  2. The miniport driver is loaded into system space and is responsible for managing display device resources and enumerating devices. This driver however uses another driver as its framework which is VIDEOPRT.SYS. This driver exports APIs which your driver will link against and use. Surprised a driver can export APIs? Don't be. Drivers use the PE format and have export and import tables. You can export APIs from your driver and allow other drivers to link against them just like a DLL. In fact all the APIs you use you are just linking against the kernel and other drivers.

  3. I will note there is a slight difference between linking against kernel and user mode drivers. If a driver links against a driver that is not currently loaded into memory, that driver will become loaded into memory however the DriverEntry for that driver will not be called. The DriverEntry itself is not called until the driver is directly loaded using ZwLoadDriver, loaded by the system or with the service API as we were shown previously. In any case you can export APIs from one driver and link against and use those APIs from another driver. There is no API to "GetProcAddress" in the kernel so you would need to write one.

  4. In any case, VideoPrt.SYS exports APIs which your miniport driver will call. This driver does a few things one of which is to implement common code so that video driver writers do not need to rewrite the same code. This code includes video device enumeration between the WIN32 subsystem (WIN32K.SYS) and your miniport. The VideoPrt.SYS will also create the device objects for the display and when you call the initialization routine it will thunk your driver object's entry points to point to VideoPrt.

  5. The VideoPrt.SYS APIs all start with "VideoPort" and the first one you call is "VideoPortInitialize". If you notice the first two arguments are the ones passed into your DriverEntry routine however it simply calls them "Context1" and "Context2" as if your video miniport driver is "special". Don't be fooled, this driver entry is the same as what we worked with before and the first "Context1" is actually your driver object. Once you pass your driver object to VideoPortInitialize all your entry points to your driver are thunked to point to VideoPrt.Sys. Instead you pass in different function pointers in "VIDEO_HW_INITIALIZATION_DATA" which VideoPrt.SYS will call instead when it needs to.
  6. Context1driver object

  7. This means that you do not need to directly deal with IRPs in a video miniport. The VideoPrt.SYS will instead handle them, break them down and then determine when you need to be informed about the data. Instead you do deal with what they call "VRP" or "Video Request Packet". This is essentially a mild, broken down version of the IRP in a different data structure. You simply need to return there is no special handling of this data structure as there is with IRPs.
  8. (这意味着你不需要在小端口驱动中直接处理IRPs。VideoPrt.SYS会代为处理IRPs,并适时地通知小端口驱动处理。换言之,你处理的是”VRP“请求。

  9. The documentation specifies that you should only use the "VideoPort" APIs in a miniport however since this is also just a regular system level driver you can still link against any kernel API you wish and I have done this before. This is not the case with the display driver itself as we will see later.

  10. Since we do not have any hardware our miniport driver will be pretty thin and easy. The following code shows how the video miniport DriverEntry is constructed:
  11. Collapse | Copy Code

  12. /**********************************************************************
  13.  *
  14.  * DriverEntry
  15.  *
  16.  * This is the entry point for this video miniport driver
  17.  *
  18.  **********************************************************************/
  19. ULONG DriverEntry(PVOID pContext1, PVOID pContext2)
  20. {
  21.     VIDEO_HW_INITIALIZATION_DATA hwInitData;
  22.     VP_STATUS vpStatus;
  23.     /*
  24.      * The Video Miniport is "technically" restricted to calling
  25.      * "Video*" APIs.
  26.      * There is a driver that encapsulates this driver by setting your
  27.      * driver's entry points to locations in itself. It will then
  28.      * handle your IRP's for you and determine which of the entry
  29.      * points (provided below) into your driver that should be called.
  30.      * This driver however does run in the context of system memory
  31.      * unlike the GDI component.
  32.      */
  33.     VideoPortZeroMemory(&hwInitData,
  34.                                 sizeof(VIDEO_HW_INITIALIZATION_DATA));
  35.     hwInitData.HwInitDataSize = sizeof(VIDEO_HW_INITIALIZATION_DATA);
  36.     hwInitData.HwFindAdapter = FakeGfxCard_FindAdapter;
  37.     hwInitData.HwInitialize = FakeGfxCard_Initialize;
  38.     hwInitData.HwStartIO = FakeGfxCard_StartIO;
  39.     hwInitData.HwResetHw = FakeGfxCard_ResetHW;
  40.     hwInitData.HwInterrupt = FakeGfxCard_VidInterrupt;
  41.     hwInitData.HwGetPowerState = FakeGfxCard_GetPowerState;
  42.     hwInitData.HwSetPowerState = FakeGfxCard_SetPowerState;
  43.     hwInitData.HwGetVideoChildDescriptor =
  44.                                       FakeGfxCard_GetChildDescriptor;
  45.     vpStatus = VideoPortInitialize(pContext1,
  46.                                       pContext2, &hwInitData, NULL);
  47.     return vpStatus;
  48. }

  49. I mentioned before you simply pass the DriverObject directly through to the VideoPrt.SYS driver as shown above. You also fill in a data structure which contains entries into your driver which the VideoPrt.SYS driver will call to perform various actions. The "HwStartIO" is where you would handle IOCTLs and you can use IOCTLs between the display driver and the Video Miniport. The display driver would simply call "EngDeviceIoControl" and this IOCTL will be handled in the miniport's HwStartIO.
  50. (显示驱动调用EngDeviceIoControl,最终由小端口驱动的HwStartIO处理)

  51. The following shows how I have implemented the video miniport functions:
  52. Collapse | Copy Code

  53. /*#pragma alloc_text(PAGE, FakeGfxCard_ResetHW) Cannot be Paged*/
  54. /*#pragma alloc_text(PAGE, FakeGfxCard_VidInterrupt) Cannot be Paged*/
  55. #pragma alloc_text(PAGE, FakeGfxCard_GetPowerState)
  56. #pragma alloc_text(PAGE, FakeGfxCard_SetPowerState)
  57. #pragma alloc_text(PAGE, FakeGfxCard_GetChildDescriptor)
  58. #pragma alloc_text(PAGE, FakeGfxCard_FindAdapter)
  59. #pragma alloc_text(PAGE, FakeGfxCard_Initialize)
  60. #pragma alloc_text(PAGE, FakeGfxCard_StartIO)
  61. /**********************************************************************
  62.  *
  63.  * FakeGfxCard_ResetHW
  64.  *
  65.  * This routine would reset the hardware when a soft reboot is
  66.  * performed. Returning FALSE from this routine would force
  67.  * the HAL to perform an INT 10h and set Mode 3 (Text).
  68.  *
  69.  * We are not real hardware so we will just return TRUE so the HAL
  70.  * does nothing.
  71.  *
  72.  **********************************************************************/
  73. BOOLEAN FakeGfxCard_ResetHW(PVOID HwDeviceExtension,
  74.                                  ULONG Columns, ULONG Rows)
  75. {
  76.    return TRUE;
  77. }
  78. /**********************************************************************
  79.  *
  80.  * FakeGfxCard_VidInterrupt
  81.  *
  82.  * Checks if it's adapter generated an interrupt and dismisses it
  83.  * or returns FALSE if it did not.
  84.  *
  85.  **********************************************************************/
  86. BOOLEAN FakeGfxCard_VidInterrupt(PVOID HwDeviceExtension)
  87. {
  88.    return FALSE;
  89. }
  90. /**********************************************************************
  91.  *
  92.  * FakeGfxCard_GetPowerState
  93.  *
  94.  * Queries if the device can support the requested power state.
  95.  *
  96.  **********************************************************************/
  97. VP_STATUS FakeGfxCard_GetPowerState(PVOID HwDeviceExtension,
  98.           ULONG HwId, PVIDEO_POWER_MANAGEMENT VideoPowerControl)
  99. {
  100.    return NO_ERROR;
  101. }
  102. /**********************************************************************
  103.  *
  104.  * FakeGfxCard_SetPowerState
  105.  *
  106.  * Sets the power state.
  107.  *
  108.  **********************************************************************/
  109. VP_STATUS FakeGfxCard_SetPowerState(PVOID HwDeviceExtension,
  110.           ULONG HwId, PVIDEO_POWER_MANAGEMENT VideoPowerControl)
  111. {
  112.    return NO_ERROR;
  113. }
  114. /**********************************************************************
  115.  *
  116.  * FakeGfxCard_GetChildDescriptor
  117.  *
  118.  * Returns an identifer for any child device supported
  119.  * by the miniport.
  120.  *
  121.  **********************************************************************/
  122. ULONG FakeGfxCard_GetChildDescriptor (PVOID HwDeviceExtension,
  123.       PVIDEO_CHILD_ENUM_INFO ChildEnumInfo, PVIDEO_CHILD_TYPE pChildType,
  124.       PVOID pChildDescriptor, PULONG pUId, PULONG pUnused)
  125. {
  126.    return ERROR_NO_MORE_DEVICES;
  127. }
  128. /**********************************************************************
  129.  *
  130.  * FakeGfxCard_FindAdapter
  131.  *
  132.  * This function performs initialization specific to devices
  133.  * maintained by this miniport driver.
  134.  *
  135.  **********************************************************************/
  136. VP_STATUS FakeGfxCard_FindAdapter(PVOID HwDeviceExtension,
  137.             PVOID HwContext, PWSTR ArgumentString,
  138.             PVIDEO_PORT_CONFIG_INFO ConfigInfo, PUCHAR Again)
  139. {
  140.    return NO_ERROR;
  141. }
  142. /**********************************************************************
  143.  *
  144.  * FakeGfxCard_Initialize
  145.  *
  146.  * This initializes the device.
  147.  *
  148.  **********************************************************************/
  149. BOOLEAN FakeGfxCard_Initialize(PVOID HwDeviceExtension)
  150. {
  151.    return TRUE;
  152. }
  153. /**********************************************************************
  154.  *
  155.  * FakeGfxCard_StartIO
  156.  *
  157.  * This routine executes requests on behalf of the GDI Driver
  158.  * and the system. The GDI driver is allowed to issue IOCTLs
  159.  * which would then be sent to this routine to be performed
  160.  * on it's behalf.
  161.  *
  162.  * We can add our own proprietary IOCTLs here to be processed
  163.  * from the GDI driver.
  164.  *
  165.  **********************************************************************/
  166. BOOLEAN FakeGfxCard_StartIO(PVOID HwDeviceExtension,
  167.                 PVIDEO_REQUEST_PACKET RequestPacket)
  168. {
  169.    RequestPacket->StatusBlock->Status = 0;
  170.    RequestPacket->StatusBlock->Information = 0;
  171.    return TRUE;
  172. }

  173. Since I don't have any hardware I simply implement enough of a miniport to make the system happy. The only possible API I would intend to use would be "StartIO" if I needed to access or perform an operation on the system that the display driver is not capable of doing with its limited API set. However in this implementation there is nothing we need done. Remember, the main purpose of the miniport is to enumerate hardware devices/resources and manage them. If you don't have any then that removes everything but the necessary to keep the driver model happy.
  174. The display driver

  175. The display driver links against WIN32K.SYS and is only allowed to call Eng* APIs. These APIs are actually found in the kernel and in user mode. Prior to NT4 the display drivers were in user mode. In any case the same API set used by display drivers is also used by printer drivers. Conforming to this API set also allows the display driver to be movable to user or kernel with minimal work.

  176. The display driver however is not loaded into system memory but instead session space. Session space is the kernel equivalent of process isolation. In user mode processes have their own virtual memory address space and in the kernel sessions have their own virtual memory address space. System space is the kernel memory which is global to all sessions.

  177. A session is an instance of a logged on user which contains its own Window Manager, Desktop(s), shell and applications. This is most notable in Windows XP "Fast User Switching" in which you can log multiple users onto a single machine. Each user is actually in a unique session with a unique range of kernel memory known as session space.

  178. This can be a problem when designing a video driver. It means you cannot simply pass random memory down to your miniport if your miniport may process that memory outside the context of the current session. This is for example passing this memory to be processed in another thread which could reside in the system process for example.

  179. If the system process is not associated with your session then you will be accessing a different memory range than you think. When this occurs you get the "A driver has not been correctly ported to Terminal Services" blue screen.

  180. The display driver is not anything like the drivers we have worked with so far. It is still in PE format but it is not like the miniport which is a normal kernel driver linking against a different frame work. This driver cannot use kernel APIs by linking directly to them and should not use them for the exact reason specified above. If the API passes the memory outside of session space then you have a blue screen unless you ensure you only pass system memory. This is another reason to only use the Eng* API set however you could request a function pointer table from the miniport driver; nothing actually prevents you from doing so.

  181. In any case the display driver behaves more like a DLL than normal drivers do and it is essentially treated as one. This driver's framework is tied to WIN32K.SYS which implements the Window Manager as well as GDI. This driver is compiled using "-entry:DrvEnableDriver@12 /SUBSYSTEM:NATIVE" where DrvEnableDriver is the entry point for the display driver.
  182. DrvEnableDriver

  183. This is the initial entry point for a display driver and it is not related to DriverEntry in any way. This API passes in a DRVENABLEDATA structure which is to be filled in with a table of functions which are the entries to the driver. The table contains a list which is an index value followed by the function pointer. The index value specifies the function type such as "INDEX_DrvCompletePDEV" which specifies that the function pointer is a pointer to the DrvCompletePDEV handler in the driver. Some APIs are optional and some are required.

  184. This entry point is simply responsible for returning the list of your functions. You may also do any initialization you may need to do here. The following is the code from the sample display driver in this article:
  185. Collapse | Copy Code

  186. /*
  187.  * Display Drivers provide a list of function entry points for specific GDI
  188.  * tasks. These are identified by providing a pre-defined "INDEX" value (pre-
  189.  * defined
  190.  * by microsoft) followed by the function entry point. There are levels of
  191.  * flexibility
  192.  * on which ones you are REQUIRED and which ones are technically OPTIONAL.
  193.  *
  194.  */
  195.                                             
  196. DRVFN g_DrvFunctions[] =
  197. {
  198.     { INDEX_DrvAssertMode, (PFN) GdiExample_DrvAssertMode },
  199.     { INDEX_DrvCompletePDEV, (PFN) GdiExample_DrvCompletePDEV },
  200.     { INDEX_DrvCreateDeviceBitmap, (PFN) GdiExample_DrvCreateDeviceBitmap },
  201.     { INDEX_DrvDeleteDeviceBitmap, (PFN) GdiExample_DrvDeleteDeviceBitmap },
  202.     { INDEX_DrvDestroyFont, (PFN) GdiExample_DrvDestroyFont },
  203.     { INDEX_DrvDisablePDEV, (PFN) GdiExample_DrvDisablePDEV },
  204.     { INDEX_DrvDisableDriver, (PFN) GdiExample_DrvDisableDriver },
  205.     { INDEX_DrvDisableSurface, (PFN) GdiExample_DrvDisableSurface },
  206.     { INDEX_DrvSaveScreenBits, (PFN) GdiExample_DrvSaveScreenBits },
  207.     { INDEX_DrvEnablePDEV, (PFN) GdiExample_DrvEnablePDEV },
  208.     { INDEX_DrvEnableSurface, (PFN) GdiExample_DrvEnableSurface },
  209.     { INDEX_DrvEscape, (PFN) GdiExample_DrvEscape },
  210.     { INDEX_DrvGetModes, (PFN) GdiExample_DrvGetModes },
  211.     { INDEX_DrvMovePointer, (PFN) GdiExample_DrvMovePointer },
  212.     { INDEX_DrvNotify, (PFN) GdiExample_DrvNotify },
  213.   // { INDEX_DrvRealizeBrush, (PFN) GdiExample_DrvRealizeBrush },
  214.     { INDEX_DrvResetPDEV, (PFN) GdiExample_DrvResetPDEV },
  215.     { INDEX_DrvSetPalette, (PFN) GdiExample_DrvSetPalette },
  216.     { INDEX_DrvSetPointerShape, (PFN) GdiExample_DrvSetPointerShape },
  217.     { INDEX_DrvStretchBlt, (PFN) GdiExample_DrvStretchBlt },
  218.     { INDEX_DrvSynchronizeSurface, (PFN) GdiExample_DrvSynchronizeSurface },
  219.     { INDEX_DrvAlphaBlend, (PFN) GdiExample_DrvAlphaBlend },
  220.     { INDEX_DrvBitBlt, (PFN) GdiExample_DrvBitBlt },
  221.     { INDEX_DrvCopyBits, (PFN) GdiExample_DrvCopyBits },
  222.     { INDEX_DrvFillPath, (PFN) GdiExample_DrvFillPath },
  223.     { INDEX_DrvGradientFill, (PFN) GdiExample_DrvGradientFill },
  224.     { INDEX_DrvLineTo, (PFN) GdiExample_DrvLineTo },
  225.     { INDEX_DrvStrokePath, (PFN) GdiExample_DrvStrokePath },
  226.     { INDEX_DrvTextOut, (PFN) GdiExample_DrvTextOut },
  227.     { INDEX_DrvTransparentBlt, (PFN) GdiExample_DrvTransparentBlt },
  228. };
  229.                                             
  230. ULONG g_ulNumberOfFunctions = sizeof(g_DrvFunctions) / sizeof(DRVFN);
  231. /*********************************************************************
  232.  * DrvEnableDriver
  233.  *
  234.  * This is the initial driver entry point. This is the "DriverEntry"
  235.  * equivlent for Display and Printer drivers. This function must
  236.  * return a function table that represents all the supported entry
  237.  * points into this driver.
  238.  *
  239.  *********************************************************************/
  240. BOOL DrvEnableDriver(ULONG ulEngineVersion,
  241.      ULONG ulDataSize, DRVENABLEDATA *pDrvEnableData)
  242. {
  243.     BOOL bDriverEnabled = FALSE;
  244.     /*
  245.      * We only want to support versions > NT 4
  246.      *
  247.      */
  248.     if(HIWORD(ulEngineVersion) >= 0x3 &&
  249.        ulDataSize >= sizeof(DRVENABLEDATA))
  250.     {
  251.        pDrvEnableData->iDriverVersion = DDI_DRIVER_VERSION;
  252.        pDrvEnableData->pdrvfn = g_DrvFunctions;
  253.        pDrvEnableData->c = g_ulNumberOfFunctions;
  254.        bDriverEnabled = TRUE;
  255.     }
  256.     return bDriverEnabled;
  257. }

  258. DrvDisableDriver

  259. This function handler is called when the display driver is being unloaded. In this handler you can perform any clean up necessary for what you have created in the DrvEnableDriver call. The following code is from the sample driver:
  260. Collapse | Copy Code

  261. /*********************************************************************
  262.  * GdiExample_DrvDisableDriver
  263.  *
  264.  * This function is used to notify the driver when the driver is
  265.  * getting ready to be unloaded.
  266.  *
  267.  *********************************************************************/
  268. VOID GdiExample_DrvDisableDriver(VOID)
  269. {
  270.     /*
  271.      * No Clean up To Do
  272.      */
  273. }

  274. DrvGetModes

  275. The API called after the driver is loaded and enabled is DrvGetModes. This API is used to query the modes supported by the device. These modes are used to populate the "Settings" tab in the "Display Properties" dialog. The modes can be cached so the operating system does not think of them as being dynamic and changing. The operating system believes this to be a static list and while there are times and ways that this API may be called more than once for the most part it should not be considered dynamic.

  276. The API is generally called twice the first time it simply asks for the size required to store the modes and the second time it calls with the correct size. The following code fragment is from the sample driver which only supports 640x480x32:
  277. Collapse | Copy Code

  278. /*********************************************************************
  279.  * GdiExample_DrvGetModes
  280.  *
  281.  * This API is used to enumerate display modes.
  282.  *
  283.  * This driver only supports 640x480x32
  284.  *
  285.  *********************************************************************/
  286. ULONG GdiExample_DrvGetModes(HANDLE hDriver,
  287.                                ULONG cjSize, DEVMODEW *pdm)
  288. {
  289.    ULONG ulBytesWritten = 0, ulBytesNeeded = sizeof(DEVMODEW);
  290.    ULONG ulReturnValue;
  291.    ENGDEBUGPRINT(0, "GdiExample_DrvGetModes\r\n", NULL);
  292.    if(pdm == NULL)
  293.    {
  294.        ulReturnValue = ulBytesNeeded;
  295.    }
  296.    else
  297.    {
  298.        
  299.        ulBytesWritten = sizeof(DEVMODEW);
  300.        memset(pdm, 0, sizeof(DEVMODEW));
  301.        memcpy(pdm->dmDeviceName, DLL_NAME, sizeof(DLL_NAME));
  302.        pdm->dmSpecVersion = DM_SPECVERSION;
  303.        pdm->dmDriverVersion = DM_SPECVERSION;
  304.        pdm->dmDriverExtra = 0;
  305.        pdm->dmSize = sizeof(DEVMODEW);
  306.        pdm->dmBitsPerPel = 32;
  307.        pdm->dmPelsWidth = 640;
  308.        pdm->dmPelsHeight = 480;
  309.        pdm->dmDisplayFrequency = 75;
  310.        pdm->dmDisplayFlags = 0;
  311.        
  312.        pdm->dmPanningWidth = pdm->dmPelsWidth;
  313.        pdm->dmPanningHeight = pdm->dmPelsHeight;
  314.        pdm->dmFields = DM_BITSPERPEL | DM_PELSWIDTH |
  315.                                  DM_PELSHEIGHT | DM_DISPLAYFLAGS |
  316.                                  DM_DISPLAYFREQUENCY;
  317.        ulReturnValue = ulBytesWritten;
  318.    }
  319.    return ulReturnValue;
  320. }

  321. DrvEnablePDEV

  322. Once a mode is chosen this API is then called which will allow the driver to enable the "physical device". The purpose of this API is to allow the display driver to create its own private context which will be passed into the other display entry points. The reason for this private context is that a single display driver may handle multiple display devices and as such would need to distinguish one display device from another. The return value for this API is a pointer to the context or instance of the supplied display device.

  323. The selected display setting is passed into this API via the DEVMODE parameter however the sample driver does not use this method since it's hard coded to setup 800x600x32 mode only.

  324. This API aside from creating an instance structure must also initialize the GDIINFO and DEVINFO data structures at a minimum. These parameters are important as if you fill in supporting a certain feature and you really do not you can have graphic corruption as a side effect or even blue screen. The next two parameters that I will mention are the hDev and hDriver parameters. The hDriver parameter is actually the DEVICE_OBJECT for the display driver and can be used with APIs such as EngDeviceIoControl to communicate with the miniport driver.

  325. The hDev is the handle to GDI however since the device is in the process of being created it is actually useless. It is recommended that you wait until the DrvCompletePDEV call before saving and using this handle. The following code is from the sample driver's DrvEnablePDEV:
  326. Collapse | Copy Code

  327. /*********************************************************************
  328.  * GdiExample_DrvEnablePDEV
  329.  *
  330.  * This function will provide a description of the Physical Device.
  331.  * The data returned is a user defined data context to be used as a
  332.  * handle for this display device.
  333.  *
  334.  * The hDriver is a handle to the miniport driver associated with
  335.  * this display device. This handle can be used to communicate to
  336.  * the miniport through APIs to send things like IOCTLs.
  337.  *
  338.  *********************************************************************/
  339. DHPDEV GdiExample_DrvEnablePDEV(DEVMODEW *pdm, PWSTR pwszLogAddr,
  340.        ULONG cPat, HSURF *phsurfPatterns, ULONG cjCaps,
  341.        GDIINFO *pGdiInfo, ULONG cjDevInfo, DEVINFO *pDevInfo,
  342.        HDEV hdev, PWSTR pwszDeviceName, HANDLE hDriver)
  343. {
  344.     PDEVICE_DATA pDeviceData = NULL;
  345.     
  346.     ENGDEBUGPRINT(0, "GdiExample_DrvEnablePDEV Enter \r\n", NULL);
  347.     pDeviceData = (PDEVICE_DATA) EngAllocMem(0,
  348.                                sizeof(DEVICE_DATA), FAKE_GFX_TAG);
  349.     if(pDeviceData)
  350.     {
  351.         memset(pDeviceData, 0, sizeof(DEVICE_DATA));
  352.         memset(pGdiInfo, 0, cjCaps);
  353.         memset(pDevInfo, 0, cjDevInfo);
  354.         {
  355.             pGdiInfo->ulVersion = 0x5000;
  356.             pGdiInfo->ulTechnology = DT_RASDISPLAY;
  357.             pGdiInfo->ulHorzSize = 0;
  358.             pGdiInfo->ulVertSize = 0;
  359.             pGdiInfo->ulHorzRes = RESOLUTION_X;
  360.             pGdiInfo->ulVertRes = RESOLUTION_Y;
  361.             pGdiInfo->ulPanningHorzRes = 0;
  362.             pGdiInfo->ulPanningVertRes = 0;
  363.             pGdiInfo->cBitsPixel = 8;
  364.             pGdiInfo->cPlanes = 4;
  365.             pGdiInfo->ulNumColors = 20;
  366.             pGdiInfo->ulVRefresh = 1;
  367.             pGdiInfo->ulBltAlignment = 1;
  368.             pGdiInfo->ulLogPixelsX = 96;
  369.             pGdiInfo->ulLogPixelsY = 96;
  370.             pGdiInfo->flTextCaps = TC_RA_ABLE;
  371.             pGdiInfo->flRaster = 0;
  372.             pGdiInfo->ulDACRed = 8;
  373.             pGdiInfo->ulDACGreen = 8;
  374.             pGdiInfo->ulDACBlue = 8;
  375.             pGdiInfo->ulAspectX = 0x24;
  376.             pGdiInfo->ulNumPalReg = 256;
  377.             pGdiInfo->ulAspectY = 0x24;
  378.             pGdiInfo->ulAspectXY = 0x33;
  379.             pGdiInfo->xStyleStep = 1;
  380.             pGdiInfo->yStyleStep = 1;
  381.             pGdiInfo->denStyleStep = 3;
  382.             pGdiInfo->ptlPhysOffset.x = 0;
  383.             pGdiInfo->ptlPhysOffset.y = 0;
  384.             pGdiInfo->szlPhysSize.cx = 0;
  385.             pGdiInfo->szlPhysSize.cy = 0;
  386.             pGdiInfo->ciDevice.Red.x = 6700;
  387.             pGdiInfo->ciDevice.Red.y = 3300;
  388.             pGdiInfo->ciDevice.Red.Y = 0;
  389.             pGdiInfo->ciDevice.Green.x = 2100;
  390.             pGdiInfo->ciDevice.Green.y = 7100;
  391.             pGdiInfo->ciDevice.Green.Y = 0;
  392.             pGdiInfo->ciDevice.Blue.x = 1400;
  393.             pGdiInfo->ciDevice.Blue.y = 800;
  394.             pGdiInfo->ciDevice.Blue.Y = 0;
  395.             pGdiInfo->ciDevice.AlignmentWhite.x = 3127;
  396.             pGdiInfo->ciDevice.AlignmentWhite.y = 3290;
  397.             pGdiInfo->ciDevice.AlignmentWhite.Y = 0;
  398.             pGdiInfo->ciDevice.RedGamma = 20000;
  399.             pGdiInfo->ciDevice.GreenGamma = 20000;
  400.             pGdiInfo->ciDevice.BlueGamma = 20000;
  401.             pGdiInfo->ciDevice.Cyan.x = 1750;
  402.             pGdiInfo->ciDevice.Cyan.y = 3950;
  403.             pGdiInfo->ciDevice.Cyan.Y = 0;
  404.             pGdiInfo->ciDevice.Magenta.x = 4050;
  405.             pGdiInfo->ciDevice.Magenta.y = 2050;
  406.             pGdiInfo->ciDevice.Magenta.Y = 0;
  407.             pGdiInfo->ciDevice.Yellow.x = 4400;
  408.             pGdiInfo->ciDevice.Yellow.y = 5200;
  409.             pGdiInfo->ciDevice.Yellow.Y = 0;
  410.             pGdiInfo->ciDevice.MagentaInCyanDye = 0;
  411.             pGdiInfo->ciDevice.YellowInCyanDye = 0;
  412.             pGdiInfo->ciDevice.CyanInMagentaDye = 0;
  413.             pGdiInfo->ciDevice.YellowInMagentaDye = 0;
  414.             pGdiInfo->ciDevice.CyanInYellowDye = 0;
  415.             pGdiInfo->ciDevice.MagentaInYellowDye = 0;
  416.             pGdiInfo->ulDevicePelsDPI = 0;
  417.             pGdiInfo->ulPrimaryOrder = PRIMARY_ORDER_CBA;
  418.             pGdiInfo->ulHTPatternSize = HT_PATSIZE_4x4_M;
  419.             pGdiInfo->flHTFlags = HT_FLAG_ADDITIVE_PRIMS;
  420.             pGdiInfo->ulHTOutputFormat = HT_FORMAT_32BPP;
  421.             
  422.             *pDevInfo = gDevInfoFrameBuffer;
  423.             pDevInfo->iDitherFormat = BMF_32BPP;
  424.         }
  425.         pDeviceData->pVideoMemory = EngMapFile(L"\\??\\c:\\video.dat",
  426.               RESOLUTION_X*RESOLUTION_Y*4, &pDeviceData->pMappedFile);
  427.         pDeviceData->hDriver = hDriver;
  428.         pDevInfo->hpalDefault = EngCreatePalette(PAL_BITFIELDS,
  429.                0, NULL, 0xFF0000, 0xFF00, 0xFF);
  430.     }
  431.     ENGDEBUGPRINT(0, "GdiExample_DrvEnablePDEV Exit \r\n", NULL);
  432.     return (DHPDEV)pDeviceData;
  433. }

  434. DrvCompletePDEV

  435. This call is made after the enable to notify the display driver that the device object is now completed. The only parameters are the private data structure created in the enable call and the completed handle to the GDI device. Unless you have more initialization to do you generally can just save the GDI handle and move on. The following is the code from the sample driver:
  436. Collapse | Copy Code

  437. /*********************************************************************
  438.  * GdiExample_DrvCompletePDEV
  439.  *
  440.  * This is called to complete the process of enabling the device.
  441.  *
  442.  *
  443.  *********************************************************************/
  444. void GdiExample_DrvCompletePDEV(DHPDEV dhpdev, HDEV hdev)
  445. {
  446.     PDEVICE_DATA pDeviceData = (PDEVICE_DATA)dhpdev;
  447.     ENGDEBUGPRINT(0, "GdiExample_DrvCompletePDEV Enter \r\n", NULL);
  448.     pDeviceData->hdev = hdev;
  449.     ENGDEBUGPRINT(0, "GdiExample_DrvCompletePDEV Exit \r\n", NULL);
  450. }

  451. DrvDisablePDEV

  452. This API is called when the PDEV is no longer needed and will be destroyed. This is called after DrvDisableSurface if there is a surface enabled. Our implementation of this API is very simple and will just perform some clean up of what was created during the creation of the private PDEV structure:
  453. Collapse | Copy Code

  454. /*********************************************************************
  455.  * GdiExample_DrvDisablePDEV
  456.  *
  457.  * This is called to disable the PDEV we created.
  458.  *
  459.  *
  460.  *********************************************************************/
  461. void GdiExample_DrvDisablePDEV(DHPDEV dhpdev)
  462. {
  463.     PDEVICE_DATA pDeviceData = (PDEVICE_DATA)dhpdev;
  464.     UINT dwBytesReturned = 0;
  465.     ENGDEBUGPRINT(0, "GdiExample_DrvDisablePDEV\r\n", NULL);
  466.     if(pDeviceData->pMappedFile)
  467.     {
  468.        EngUnmapFile(pDeviceData->pMappedFile);
  469.     }
  470.     EngFreeMem(dhpdev);
  471. }

  472. DrvEnableSurface

  473. This API is called after the PDEV has completed to ask the display driver to create a surface. Also as noted in the comments below you have two choices when creating a surface. You can create a surface in which the display driver will manage it or you can create one in which GDI will manage for you. The following code chose the option of managing its own device surface.

  474. The entire purpose is to define a drawing surface in which GDI will also be able to draw onto. Display drivers have their own device surfaces and thus will generally want to manage its surface. In doing this it must describe the surface in a way which GDI can understand and be able to draw on it. This means defining the start address and even the pitch as display drivers do not generally have linear buffers for all modes. In our case we use the memory mapped file we created to be our video memory:
  475. Collapse | Copy Code

  476. /*********************************************************************
  477.  * GdiExample_DrvEnableSurface
  478.  *
  479.  * This API is used to enable the physical device surface.
  480.  *
  481.  * You have two choices here.
  482.  *
  483.  * 1. Driver Manages it's own surface
  484.  * EngCreateDeviceSurface - Create the handle
  485.  * EngModifySurface - Let GDI Know about the object.
  486.  *
  487.  * 2. GDI Manages the surface
  488.  * EngCreateBitmap - Create a handle in a format that
  489.  * GDI Understands
  490.  * EngAssociateSurface - Let GDI Know about the object.
  491.  *
  492.  *
  493.  *********************************************************************/
  494. HSURF GdiExample_DrvEnableSurface(DHPDEV dhpdev)
  495. {
  496.     HSURF hsurf;
  497.     SIZEL sizl;
  498.     PDEVICE_DATA pDeviceData = (PDEVICE_DATA)dhpdev;
  499.     
  500.     ENGDEBUGPRINT(0, "GdiExample_DrvEnableSurface\r\n", NULL);
  501.     pDeviceData->pDeviceSurface =
  502.       (PDEVICE_SURFACE)EngAllocMem(FL_ZERO_MEMORY,
  503.       sizeof(DEVICE_SURFACE), FAKE_GFX_TAG);
  504.     sizl.cx = 800;
  505.     sizl.cy = 600;
  506.     hsurf = (HSURF)EngCreateDeviceSurface(
  507.             (DHSURF)pDeviceData->pDeviceSurface, sizl, BMF_32BPP);
  508.     
  509.     EngModifySurface(hsurf, pDeviceData->hdev,
  510.            HOOK_FILLPATH | HOOK_STROKEPATH | HOOK_LINETO |
  511.            HOOK_TEXTOUT | HOOK_BITBLT | HOOK_COPYBITS,
  512.            MS_NOTSYSTEMMEMORY, (DHSURF)pDeviceData->pDeviceSurface,
  513.            pDeviceData->pVideoMemory, 800*4, NULL);

  514.     
  515.     return(hsurf);
  516. }

  517. DrvDisableSurface

  518. This API is called to destroy the drawing surface created in the DrvEnableSurface call. This is called before destroying the PDEV. The following is the code from the example program:
  519. Collapse | Copy Code

  520. /*********************************************************************
  521.  * GdiExample_DrvDisableSurface
  522.  *
  523.  * This API is called to disable the GDI Surface.
  524.  *
  525.  *
  526.  *********************************************************************/
  527. void GdiExample_DrvDisableSurface(DHPDEV dhpdev)
  528. {
  529.     PDEVICE_DATA pDeviceData = (PDEVICE_DATA)dhpdev;
  530.     ENGDEBUGPRINT(0, "GdiExample_DrvDisableSurface\r\n", NULL);
  531.     EngDeleteSurface(pDeviceData->hsurf);
  532.     pDeviceData->hsurf = NULL;
  533.     EngFreeMem(pDeviceData->pDeviceSurface);
  534.     pDeviceData->pDeviceSurface = NULL;
  535. }

  536. Sequencing

  537. So, let's go through this one more time for clarity.

  538.     DrvEnableDriver: The driver is loaded.
  539.     DrvGetModes: Get the buffer size to hold all supported display modes.
  540.     DrvGetModes: Get the display modes.
  541.     DrvEnablePDEV: Inform the display driver to initialize to a mode selected in the DEVMODE data structure and return an instance handle.
  542.     DrvCompletePDEV: Inform the driver that the device initialization is complete.
  543.     DrvEnableSurface: Get the driver to supply a drawing surface.

  544.     
  545.     DrvDisableSurface: Destroy the drawing surface.
  546.     DrvDisablePDEV: Destroy the instance structure.
  547.     DrvDisableDriver: Unload the display driver.

  548. So how does the drawing work?

  549. The "GDI Calls" are essentially handling things like "BitBlt" in your display driver which is actually in DrvBitBlt. You may notice that with our driver it doesn't implement any graphical commands itself. This is because we do not have hardware to accelerate drawing features and I decided that it's a lot less work to just call the routines provided to you by Windows that already implement these features in software. As in the example, DrvBitBlt can simply be diverted to EngBitBlt. These will simply render directly to our video buffer which in our case is a memory mapped file.

  550. You may be wondering "how do I get to my PDEV or my surface object from these Drv* calls". Well, the SURFOBJ passed into these APIs does contain a pointer to the surface object. These are found at the dhsurf and dhpdev members of the SURFOBJ structure. The dhsurf member is the handle the device created provided the SURFOBJ represents a device managed surface. This can be determined by checking the STYPE_DEVICE flag set on the SURFOBJ.
  551. Display driver escape codes

  552. In my tutorials on device drivers we learned that it is possible to use "DeviceIoControl" from user mode to implement and communicate our own commands between the application and the driver. This is also possible with display drivers however it is a little different and instead of being called "IOCTLs" they are called "Escape Codes".

  553. In user mode you can send "Escape Codes" to the display driver using one of two methods. The first is ExtEscape which simply sends the data you provide to the driver. Your display driver would then handle this in its DrvEscape routine.

  554. The second method is DrawEscape which can be handled in DrvDrawEscape in your driver. The difference is that DrawEscape allows you to provide a Window DC with your data and the clipping for that window will be provided to your driver. This allows you to easily implement extended drawing commands which can behave correctly in the windowing environment as your driver will be informed of the proper clipping area.
  555. OpenGL support

  556. OpenGL support is done through the use of an "ICD" or "Installable Client Driver". This is a concept originally created by SGI to help improve the performance of OpenGL on Windows by letting the vendor implement the graphics pipeline completely. When OpenGL32.DLL gets loaded it simply asks the video driver for it's ICD and if there is one it's loaded into the process space and OpenGL APIs are serviced by the ICD. The ICD is in full control of the graphics pipeline and thus each vendor and driver version may have a different implementation.

  557. The usual case is to buffer the OpenGL commands and flush them to the card using the ExtEscape API. The ICD kit is now maintained by Microsoft and it is not free if you wish to develop for it.

  558. The other method of supporting OpenGL is through something called a "Mini Client Driver" or "MCD". This is Microsoft's original method for OpenGL support and is similar to an ICD but the MCD lives in the kernel. This method is not used by any driver vendor that I know of and is very slow which is the reason for the ICD implementation.
  559. DirectX support

  560. In XPDM, Direct Draw support is done in the GDI driver. This is through the DrvEnableDirectDraw interface. The user mode portion and some of the kernel for the DirectX graphics pipeline is implemented by Microsoft supplied system components. The API will simply return back a list of callback interfaces the DirectDraw layer in the kernel will use to perform specific actions in the hardware.

  561. Direct3D is initialized through the DrvGetDirectDrawInfo in which the GDI driver will claim to support Direct3D. The supplied callbacks will be called several times to get the appropriate interfaces into the driver which implement the various features of Direct3D. This is described on MSDN.
  562. What is a mirror driver?

  563. A mirror driver is a not well documented feature in which you can load a video driver that will "mirror" another display driver. That is they will receive the same calls as the display driver they are mirroring. A mirror driver is documented to not support DrvGetModes however if you do implement it the returned modes will be cached and you cannot dynamically change the modes. Although I have heard that implementing DrvGetModes can help with loading and unloading the display driver on mode switches I was unable to get this to work.

  564. To load a mirror driver the registry key for this device needs to set the "Attach.ToDesktop" value to 1 and then you call ChangeDisplaySettingsEx with "CDS_UPDATEREGISTRY" on the mirror driver. You then set the mode you wish to switch to and call ChangeDisplaySettingsEx again on the mirror driver.

  565. The mirror driver does not properly unload at mode switch and generally if there are references to a drawing surface the driver will not unload. So, in my experience to get a mirror driver to mode switch you need an application that will detect WM_DISPLAYCHANGE messages. You also need to set "Attach.ToDesktop" to 0 after you load the display driver. This will help unload the display driver and on WM_DISPLAYCHANGE you can then go through the procedure to unload the mirror driver.

  566. If you wish to immediately unload the mirror driver without a display change you simply need to follow the same steps as what loaded it. Set "Attach.ToDesktop" to 0 and then perform the "CDS_UPDATEREGISTRY". You can then call "ChangeDisplaySettingsEx" again with no parameters to force unloading. Although this seems to work again everything is done by referencing the display surface so if there are outstanding references to the display surface the driver will not be unloaded. The mirror driver sample in the DDK does not do all of this and has some missing pieces such as not implementing the WM_DISPLAYCHANGE and not resetting the "Attach.ToDesktop" value after loading the mirror driver.

阅读(1168) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~