1 / 73

Writing EPICS Drivers

Writing EPICS Drivers. (and Device Support). Contents. Introduction A simple example driver Tips and tricks Example device support Multi-threading I/O Intr. Introduction. Required knowledge about EPICS. Records and fields Standard records (ai, ao, mbbi, stringout, …)

billy
Download Presentation

Writing EPICS Drivers

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Writing EPICS Drivers (and Device Support) Dirk Zimoch, 2007

  2. Contents • Introduction • A simple example driver • Tips and tricks • Example device support • Multi-threading • I/O Intr Dirk Zimoch, 2007

  3. Introduction Dirk Zimoch, 2007

  4. Required knowledge about EPICS • Records and fields • Standard records (ai, ao, mbbi, stringout, …) • Probably specialized records (motor, …) • Record processing • Scan methods (periodic, I/O Intr, …) • Links that cause processing (PP links, CP links, forward links) • Channel Access clients (medm, caget, …) • These are topics of a basic EPICS training • See also: IOC Application Developper's Guide. Dirk Zimoch, 2007

  5. Required knowledge about programming • C • Variable flavours (global, local, static, volatile) • struct, union, array [], typedef, enum • Memory allocation (malloc, calloc) and pointers • Pointers to functions • Macros (#define) and conditional compilation (#ifdef) • Data structures • Integer representations (2's complement, hex, byte order) • Bit fields (masking, shifting, …) • Linked lists Dirk Zimoch, 2007

  6. Important knowledge about hardware I/O • I/O registers • Side effects of reading and writing • Fifo registers • Busses • VME address spaces A16, A24, A32 • Memory mapped access • Out-of-order execution / pipelining • Interrupts • Interrupt levels and vectors • Interrupt handlers Dirk Zimoch, 2007

  7. Driver and Device support Dirk Zimoch, 2007

  8. What is an EPICS driver? • Software interface between EPICS records and hardware(or 3rd party software) • Usually split in 2 parts for better maintainability • Device support • Interfaces to records • Does not care about hardware • Files: devXXX.c, XXX.dbd • Driver • Does low-level hardware (register) access • Does not care about records • Files: drvXXX.c, drvXXX.h, (sometimes XXX.dbd) Dirk Zimoch, 2007

  9. Layers: Record - Device Support – Driver - Hardware Does not know about drivers Record Records Device support function table Record specific s devXXX.c Device Support The "glue" Driver API functions Driver specific drvXXX.h Does not know about records Driver drvXXX.c Register access Hardware specific Hardware Dirk Zimoch, 2007

  10. Splitting functionality: device support vs. driver • Device support is the "glue" between record and driver • Parses INP or OUT link • Reads / writes / initializes record fields • Calls driver API functions • Driver does the real work • Initializes the hardware • Creates work thread if necessary • Register access • Interrupt handling • Resource handling (semaphores, etc) Dirk Zimoch, 2007

  11. A simple example driver Dirk Zimoch, 2007

  12. In this chapter • Example hardware "myDac" • Interface (API) in drvMyDac.h • Implementation in drvMyDac.c • Configuration function • open() function • I/O funtions • Report function • Register to EPICS with drvMyDac.dbd • Registering variables • Registering functions Dirk Zimoch, 2007

  13. Example: 8 channel DAC • The card is a VME board in A16 address space • One DAC "card" has 8 "signals". • Each signal is 16 bit (0x0000 = -10 V, 0xFFFF = +10 V) • The 8 signals are registers at offsets 0x10, 0x12, 0x14, 0x16 • It is possible to read back the current register setting. • The card does not use interrupts. • The card has an identifier at offset 0x00 • String: "MYDAC"+nullbyte Dirk Zimoch, 2007

  14. How to start? • Decide what the driver should be able to do • Define one function for each functionality of the hardware • Don't think about records at this time • Think of "cards" or "boards", "signals" and functionality • Model a "card" as a structure • It contains hardware register address, internal states, etc… • Define a function which returns a pointer to this structure(like open() for a file) • Other functions take this "handle" as an argument • Define a configuration function to initialize one "card" Dirk Zimoch, 2007

  15. What to put into the header file • This file defines the interface to the driver • All public (API) driver functions • Maybe error codes if used as return values • Typedefs for used function parameters • This file does not contain implementation details • No card structure details • No internal functions (e.g. interrupt handler) • No macros etc. used only internally in driver • No register layout Dirk Zimoch, 2007

  16. Example drvMyDac.h file #ifndef drvMyDac_h #define drvMyDac_h #include <devLib.h> /* Initialize the card (called from startup script) */ int myDacConfigure (int cardnumber, unsigned int vmeAddress); /* Define a type for the card handle */ typedef struct myDacCard myDacCard; /* Get card handle from card number */ myDacCard*myDacOpen (int cardnumber); /* Set and read back values */ int myDacSet (myDacCard* card, int signal, epicsUInt16 value); int myDacGet (myDacCard* card, int signal, epicsUInt16* pvalue); #endif Configuration for one card Type definition for card handle (no details) Get handle for card Public driver functions What can the card do? Dirk Zimoch, 2007

  17. What to avoid • Do not use void* for driver handle. • This allows the compiler to warn about wrong arguments. • Do not define the card handle structure in the header file. • This is an implementation detail and not of interest to the user. • Do not list internal functions in the header file. • Interrupt handlers etc. are implementation details. • Do not define the register layout in the header file. • You don't want anyone else but the driver to access registers. Dirk Zimoch, 2007

  18. Implementing the driver (part 1) • Define "card" structure. • Contains at least register base address. • May contain thread ID, semaphores, etc. • Build a container of "cards" (linked list). • Define macros for register access. • Mark all registers volatile. • This prevents the compiler from "optimizing" and reordering register access. • Avoid global variables whenever possible. • At least use static for any private global variable. • Prefix every non-static global variable with driver name. Dirk Zimoch, 2007

  19. Includes, card structure and macros in devMyDac.c #include <stdio.h> #include <string.h> #include <devLib.h> #include <drvSup.h> #include <epicsExport.h> #include "drvMyDac.h" /* linked list of card structures */ struct myDacCard { myDacCard *next; int cardnumber; int vmeAddress; char* baseaddress; }; static myDacCard *firstCard = NULL; /* 8 DACs (16 bit) at offset 0x10 and following */ #define DAC(card,signal) ((volatileepicsUInt16*)(card->baseaddress+0x10))[signal] /* Other internally used macros */ #define VME_SIZE 0x100 /* Debugging switch */ int myDacDebug = 0; epicsExportAddress (int, myDacDebug); EPICS headers Define card structure here (as linked list element) Make private global variables static Macros for register access Use compiler independent volatile type Must be non-static and exported to EPICS. Prefix it properly. Dirk Zimoch, 2007

  20. What to avoid • Do not use a structure to map registers. • Structures are compiler dependent. • Compiler may insert pad bytes to align elements. • Compiler may reorder elements to "optimize" access. • Use macros to calculate address offset. • Do not use compiler dependent data types for registers. • Not all compilers use 2 bytes for unsigned short. • Use compiler independent types like epicsUInt16 instead. • Do not use global variables to store any card details. • You may have more than one card. Make a list of structures. Dirk Zimoch, 2007

  21. Implementing the driver (part 2) • Configuration function • Configure one and only one card per function call. • Give each card an individual id (number or string). • Do not use auto-numbering of cards. • This avoids problems when you have to remove a card (temporarily) • open() function • Return a card handle from a card id • Input/Output functions • Report function • (Interrupt handler) Dirk Zimoch, 2007

  22. What to do in the configuration function • Check parameters for sanity. • Calculate local (memory mapped) address of registers. • Check if the hardware is installed. • Create "card" structure. • Allocate memory. • Fill in values. • Put into linked list. • Give good error messages if anything goes wrong. • Don't forget driver name and parameters in error message. • Write error messages to stderr, not to stdout. Dirk Zimoch, 2007

  23. Example configuration function in drvMyDac.c /* The configure function is called from the startup script */ int myDacConfigure (int cardnumber, unsigned int vmeAddress) { long status; volatile void* baseaddress; char id[6]; myDacCard **pcard; /* Check card number for sanity */ if (cardnumber < 0) { fprintf (stderr, "myDacConfigure: cardnumber %d must be > 0\n", cardnumber); return S_dev_noDevice; } /* Find end of card list and check for duplicates */ for (pcard = &firstCard; *pcard; pcard=&(*pcard)->next) { if ((*pcard)->cardnumber == cardnumber) { fprintf (stderr, "myDacConfigure: cardnumber %d already in use\n", cardnumber); return S_dev_identifyOverlap; } } Check all parametes Write clear error messages to stderr Return error codes (from devLib.h or drvMyDac.h) Check for duplicate configuration Remember: now *pcard points to the end of the list Dirk Zimoch, 2007

  24. Configuration function continued More parameter checks /* Check vmeAddress for sanity */ if (vmeAddress % VME_SIZE != 0) { fprintf (stderr, "myDacConfigure: " "vmeAddress 0x%04x must be a multiple of 0x%x\n", vmeAddress, VME_SIZE); return S_dev_badA16; } /* Translate vme to local address and check for overlap */ status = devRegisterAddress ("myDac", atVMEA16, vmeAddress, VME_SIZE, &baseaddress); if (status) { fprintf (stderr, "myDacConfigure: " "cannot register vmeAddress 0x%04x\n", vmeAddress); return status; } Use devRegisterAddress (from devLib.h) to register VME address and to translate to local memory mapped address. This fails if the address overlaps with another registered address. Dirk Zimoch, 2007

  25. Configuration function continued Check that hardware is installed before using it. /* Check that correct hardware is installed */ status = (devReadProbe (2, (char*) baseaddress, id) || devReadProbe (2, (char*) baseaddress+2, id+2) || devReadProbe (2, (char*) baseaddress+4, id+4)); if (status) { fprintf (stderr, "myDacConfigure: " "no card found at vmeAddress 0x%04x (local:%p)\n", vmeAddress, baseaddress); return status; } if (strcmp(id, "MYDAC") != 0) { fprintf (stderr, "myDacConfigure: " "card at vmeAddress 0x%04x (local:%p) is not a MYDAC\n", vmeAddress, baseaddress); return S_dev_wrongDevice; } Use devReadProbe (from devLib.h) to access hardware safely. If hardware is not installed, it does not crash but just fails. Check that you have really the hardware you expect Dirk Zimoch, 2007

  26. Configuration function finished /* Create new card structure */ *pcard = malloc (sizeof (myDacCard)); if (!*pcard) { fprintf (stderr, "myDacConfigure: " "out of memory\n"); return S_dev_noMemory; } (*pcard)->next = NULL; (*pcard)->cardnumber = cardnumber; (*pcard)->baseaddress = baseaddress; return 0; } Allocate card structure (malloc or calloc) Remember? *pcard points to end of list Success Fill card structure with values Dirk Zimoch, 2007

  27. What to avoid • Do not use other parameter types than int or char*. • double does not work on vxWorks shell on PPC architecture • Other types are not supported by iocsh. • Do not use too many parameters. • vxWorks supports only 10 parameters for shell functions. • Do not crash if card is absent. • Check card before use. • Do not give meaningless messages like "driver init failed". • The user needs information. What failed where and why? • Provide driver/function name, failing parameter and error reason. Dirk Zimoch, 2007

  28. Hardware registers • A hardware register is not just a variable! • Write or read access may have side effects on the hardware. • Reading may get a different value than the last written one. • FIFO registers provide different values every time they are read, giving sequential access to an array through a scalar. • Reading or writing in pieces (e.g. low and high 16bit word to a 32bit register) may be invalid, may have unexpected effects, or may require a certain order. • Always use volatile to access registers • This tells the compiler not to try "optimization" on hardware registers. Dirk Zimoch, 2007

  29. What to do in the API functions • Open • Check card id (number or string) • Find card in list of configured cards. • Return pointer to card structure (handle) or NULL. • I/O functions • Check handle for validity. • Read or write registers. • Return error code on failure or 0 on success. • No need to print error messages here (device support should do that) • Put in switchable debug messages. Dirk Zimoch, 2007

  30. Example API functions Translate card id to handle myDacCard* myDacOpen (int cardnumber) { myDacCard* card; for (card = firstCard; card; card = card->next) if (card->cardnumber == cardnumber) return card; return NULL; } int myDacSet (myDacCard*card, int signal, epicsUInt16 value) { if (!card) return S_dev_noDevice; if (signal < 0 || signal > 7) return S_dev_badSignalNumber; if (myDacDebug>0) printf("myDacSet card %d signal %d @%p = %x\n", card->cardnumber, signal, &DAC(card, signal), (unsigned int)value); DAC (card, signal) = value; return 0; } Use handle in all other functions Check handle for NULL Check other parameters Return error codes on failure. Switchable debug message Success Access registers Dirk Zimoch, 2007

  31. Example API functions continued int myDacGet (myDacCard*card, int signal, epicsUInt16* pvalue) { if (!card) return S_dev_noDevice; if (signal < 0 || signal > 7) return S_dev_badSignalNumber; *pvalue = DAC(card, signal); if (myDacDebug>1) printf ("myDacGet card %d signal %d @%p = %x\n", card->cardnumber, signal, &DAC(card, signal), (unsigned int)*pvalue); return 0; } Never forget the checks. Stability is more important than speed. Dirk Zimoch, 2007

  32. What to avoid • Do not translate card id to structure in each API function call. • Get card handle once and use it in all other API functions. • Do not use card when configuration failed. • When configuration fails return NULL from open() call. • Check for NULL in all other functions. • Do not assume anything about records. • Do not use function names like write_ao(). • The driver only cares about the features of the hardware. • Records are the business of device support. Dirk Zimoch, 2007

  33. Reporting hardware and driver status • Write a report function. • Print driver and register information to stdout. • Provide multiple levels of detail. • In lowest level (0) print only one line per card. • In higher levels print more details about configuration, registers, etc. • Register report function to EPICS. • Create a driver support structure. • Fill in a pointer to report function. • Export driver support structure to EPICS. Dirk Zimoch, 2007

  34. Example report function long myDacReport (int detail) { myDacCard *card; for (card = firstCard; card; card = card->next) { printf (" card %d at address %p\n", card->cardnumber, card->baseaddress); if (detail >= 1) { int signal; unsigned short value; for (signal = 0; signal < 4; signal++) { value = DAC (card, signal); printf(" DAC %d = 0x%04x = %+8.4f V\n", signal, value, value*20.0/0xffff-10.0); } } } return 0; } drvet myDac = { 2, myDacReport, NULL }; epicsExportAddress (drvet, myDac); Print card information in any detail level Print register contents only for higher detail level Driver support structure contains report function Export driver support structure function to EPICS Dirk Zimoch, 2007

  35. Report function call • The dbior shell function calls driver report functions. • Example: • dbiorDriver: myDac card 1 @0xfbff1000 • dbior "myDac",1Driver: myDac card 1 @0xfbff1000 DAC 0 @0xfbff1010 = 0x0000 = -10.0000 V DAC 1 @0xfbff1012 = 0x0000 = -10.0000 V DAC 2 @0xfbff1014 = 0x0000 = -10.0000 V DAC 3 @0xfbff1016 = 0x0000 = -10.0000 V DAC 4 @0xfbff1018 = 0x0000 = -10.0000 V DAC 5 @0xfbff101a = 0x0000 = -10.0000 V DAC 6 @0xfbff101c = 0x0000 = -10.0000 V DAC 7 @0xfbff101e = 0x0000 = -10.0000 V Dirk Zimoch, 2007

  36. Exporting variables and functions to EPICS • VxWorks shell can access C functions and variables directly • Other architectures must run iocsh • Shell must know about functions, variables, driver support • Export variables and driver support from C • epicsExportAddress (int, myDacDebug); • epicsExportAddress (drvet, myDac); • Much more complicated for functions • Write parameter description • Write wrapper function • Write registrar function • Very ugly and error-prone Dirk Zimoch, 2007

  37. Wrapper and registrar for shell functions Parameter description #include <iocsh.h> static const iocshArg myDacConfigureArg0 = { "cardNumber", iocshArgInt }; static const iocshArg myDacConfigureArg1 = { "vmeA16Address", iocshArgInt }; static const iocshArg * const myDacConfigureArgs[] = { &myDacConfigureArg0, &myDacConfigureArg1 }; static const iocshFuncDef myDacConfigureDef = { "myDacConfigure", 2, myDacConfigureArgs }; static void myDacConfigureFunc (const iocshArgBuf *args) { myDacConfigure (args[0].ival, args[1].ival); } static void myDacRegister () { iocshRegister (&myDacConfigureDef, myDacConfigureFunc); /* iocshRegister (other shell functions) */ } epicsExportRegistrar (myDacRegister); Array of all parameters Parameter count for each function Function description Wrapper function Unwrap parameters Real function call Register functions to iocsh Export registrar to EPICS Dirk Zimoch, 2007

  38. Importing variables and functions to EPICS • Make exported C variables and functions known to EPICS • Write MyDac.dbd file with references to exported entities • Driver support structure • driver(myDac) • Variables • variable(myDacDebug, int) • Registrar • registrar(myDacRegister) • Coming soon: Device support • device(…) Dirk Zimoch, 2007

  39. Tips and Tricks From Dirk's Code Kitchen Dirk Zimoch, 2007

  40. A bit more safety / paranoia • Even if card != NULL, it may be invalid • E.g. user calls myDacGet() with cardnumber instead of handle. • Accessing wrong hardware address is bad. • A cheap way to check the card handle is a "magic number" • Add magic number to card structure. • Insert magic number when card is configured. • Check magic number in every API function. • A good magic number is CRC checksum of driver name • echo -n myDac | cksum2191717791 5 Dirk Zimoch, 2007

  41. Example usage of magic numbers #define MYMAGIC 2191717791U /* crc("myDac") */ struct myDacCard { epicsUInt32 magic; myDacCard *next; int cardnumber; int vmeAddress; volatile char* baseaddress; }; int myDacConfigure (int cardnumber, unsigned int vmeAddress) { … (*pcard)->magic = MYMAGIC; (*pcard)->next = NULL; (*pcard)->cardnumber = cardnumber; (*pcard)->baseaddress = baseaddress; return 0; } int myDacSet (myDac* card, int signal, epicsUInt16 value) { if (!card) return S_dev_noDevice; if (card->magic != MYMAGIC) return S_dev_wrongDevice; … Store magic number in card structure. Initialize magic number in configure function. Check magic number in every call. Dirk Zimoch, 2007

  42. Simulation Mode • EPICS does not support VME on Unix (or Windows) • devRegisterAddress() fails on softioc • devReadProbe() fails on softioc • Implement "simulation mode" on Unix for driver test • Work on allocated memory instead of registers#ifdef UNIX/* UNIX has no VME. Use a simulation for tests */#include <malloc.h>#define devRegisterAddress(name, type, addr, size, pbase) \ ((*(pbase)=memalign (0x10000, size))? \ strncpy ((void*)*(pbase), "MYDAC", size), 0 : S_dev_noMemory)#define devReadProbe (size, ptr, buff) \ (memcpy (buff, (void*)ptr, size), 0)#endif Dirk Zimoch, 2007

  43. Example (synchronous) device support Dirk Zimoch, 2007

  44. In this chapter • Device support structure • Record initialization • Parse INP/OUT link • Connect to driver • Fill record private data structure • Initialize record from hardware • Read or write (record processing) • Transfer data between record and driver • Linear scaling Dirk Zimoch, 2007

  45. How to start? • Decide what record types to support • Write one device support for each record type • Find out what record expects in device support • See record reference manual / record source code • Unfortunately no header file defines the device support • Choose synchronous or asynchronous support • If driver never blocks: synchronous • e.g. register access • If driver may block or driver has callback functions: asynchronous • e.g. field bus access • Maybe "I/O Intr" support if possible Dirk Zimoch, 2007

  46. The device support structure • One device support structure for each supported record type. • Contains pointers to device support functions. • Depends on record type. • Usually:struct { long number; /* of functions below */ DEVSUPFUN report; DEVSUPFUN init; DEVSUPFUN init_record; DEVSUPFUN get_ioint_info; DEVSUPFUN read_or_write;} • Additional functions for some record types(see record reference manual) Dirk Zimoch, 2007

  47. Typical device support functions • report (can be NULL) • Report function similar to driver report function, but per record type • init (can be NULL) • Initialization of device support per record type • init_record • Initialization of device support per record • get_ioint_info (can be NULL) • For records scanned in "I/O Intr" mode • read or write (depending on record type) • Actual I/O during record processing Dirk Zimoch, 2007

  48. Example: synchronous ao support for myDac • Device support structure of ao: • Additional function special_linconv. struct { long number; /* must be 6 */ DEVSUPFUN report; /* can be NULL */ DEVSUPFUN init; /* can be NULL */ DEVSUPFUN init_record; DEVSUPFUN get_ioint_info; /* can be NULL */ DEVSUPFUN write; DEVSUPFUN special_linconv;} • Implement 3 functions • long myDacInitRecordAo(aoRecord *record) • long myDacWriteAo(aoRecord *record) • long myDacSpecialLinconvAo(aoRecord *record, int after) • Store record private data in record->dpvt. Dirk Zimoch, 2007

  49. Analog out device support (includes, private data) #include <stdio.h> #include <stdlib.h> #include <devSup.h> #include <recGbl.h> #include <alarm.h> #include <aoRecord.h> #include <epicsExport.h> #include "drvMyDac.h" typedef struct { myDacCard* card; int signal; } myDacAoPrivate; Include header(s) of supported record type(s) Include driver header Store record specific data (e.g. driver handle) in private structure Dirk Zimoch, 2007

  50. Analog out device support (device support structure) • Implement at least 3 functions for ai/ao: • init_record • read/write • special_linconv long myDacInitRecordAo (aoRecord *record); long myDacWriteAo (aoRecord *record); long myDacSpecialLinconvAo (aoRecord *record, int after); struct { long number; DEVSUPFUN report; DEVSUPFUN init; DEVSUPFUN init_record; DEVSUPFUN get_ioint_info; DEVSUPFUN write; DEVSUPFUN special_linconv; } myDacAo = { 6, NULL, NULL, myDacInitRecordAo, NULL, myDacWriteAo, myDacSpecialLinconvAo }; epicsExportAddress(dset, myDacAo); Put functions into device support structure. Use NULL for unimplemented functions. Export device support structure to EPICS. Dirk Zimoch, 2007

More Related