Try Embedded

AUTOSAR Classic for diagnostics engineers

The layered architecture, the path of a diagnostic request through CanIf, CanTp, PduR, Dcm and Dem, and NvM.

What AUTOSAR is, and why you need to know it

In the capstone of this track you write a diagnostic server by hand. At a tier-one supplier you almost never do: the server is a configured, generated and licensed AUTOSAR stack, and your job is to configure it, write the application code it calls, and debug the two together. The protocols are identical; the vocabulary is different, and job adverts and interviewers use the AUTOSAR vocabulary.

AUTOSAR (AUTomotive Open System ARchitecture) is a partnership of car makers, suppliers and tool vendors that standardises ECU software architecture. Its Classic Platform is for microcontroller ECUs with hard real-time needs: statically configured, written in C, running on an OSEK-style operating system. Its Adaptive Platform is for the high-performance computers that run driver assistance and infotainment: POSIX, C++, services discovered at run time. This lesson is about Classic, where diagnostics engineers spend their time.

The idea in one sentence: application software is written against standard interfaces, and everything below those interfaces is configured for the ECU at hand.

The layers

LayerWhat it isWho writes it
ApplicationSoftware components (SWCs): the product's functions, each made of runnables and communicating through portsthe supplier's function developers; often generated from models
RTEGenerated glue: every port access becomes a function or macro. It is the only thing an SWC may callgenerated by a tool from the system description
ServicesThe operating system, communication, diagnostics, memory, mode and network managementbought as a configured stack
ECU abstractionHides where a device is: internal CAN controller or external, internal flash or an SPI EEPROMbought, plus project-specific I/O abstraction
MCALDrivers for the MCU's peripherals, with standard APIsfrom the silicon vendor
Complex driversCode that needs direct, timing-critical hardware access outside the layers: injection control, a motor's current loopthe supplier

Everything below the RTE is the basic software (BSW). A rule you will be asked about: a module calls only the layer below it, and SWCs call only the RTE. The I/O your application reads comes through an I/O hardware abstraction component, never from Dio_ReadChannel directly.

Configuration, not code

None of these modules is used as written. Each is configured in a tool (Vector DaVinci, EB tresos, ETAS ISOLAR), the configuration is stored as ARXML, and generators emit C tables and code from it: which CAN identifiers exist, which DIDs the ECU has and where their data comes from, which events map to which DTCs. A large part of an AUTOSAR engineer's work is in that configuration, and a large part of the debugging is finding out which of 4000 parameters is wrong.

Signs of the style in the code you will read: every function returns Std_ReturnType (E_OK or E_NOT_OK), every module has an <Module>_Init and one or more <Module>_MainFunction called cyclically by the scheduler, and names follow <Module>_<Action> exactly.

The path of a diagnostic request

This is the question: a tester sends ReadDataByIdentifier; name the modules it passes through. Follow one CAN frame up and the response down.

StepModuleJobData unit
1Can (MCAL driver)Reads the frame from the controller's mailbox in its receive interrupt or polling functionhardware object
2CanIf (CAN interface)Maps the CAN identifier to a PDU and decides which upper module gets itL-PDU
3CanTp (CAN transport)ISO 15765-2: reassembles frames, sends flow control, runs the N_ timersN-PDU in, I-PDU out
4PduR (PDU router)A routing table: this I-PDU goes to Dcm. It can also gateway it to another busI-PDU
5Dcm (diagnostic communication manager)ISO 14229: sessions, security, timing, the service handlersthe request bytes
6SWC via the RTE, or Dem / NvMSupplies the data: the application for a sensor value, Dem for trouble codes

The response retraces the path: Dcm → PduR → CanTp (segmentation) → CanIf → Can.

PDU means protocol data unit. Each layer adds its own header to what the layer above hands it (the SDU, service data unit), and AUTOSAR names the result by layer: an I-PDU (interaction layer: a whole message), an N-PDU (network layer: one ISO-TP frame's content), an L-PDU (data link: a CAN frame's identifier and data). Normal signals take a shorter path: Can → CanIf → PduR → Com, which unpacks signals from the I-PDU and hands them to SWCs through the RTE.

Inside the Dcm

The Dcm has three sub-modules, and their names appear in configuration and stack traces:

  • DSL (diagnostic session layer): the session and security state, P2 and S3 timing, response pending.
  • DSD (diagnostic service dispatcher): checks that the service is supported, allowed in the session and security level, has a plausible length, then calls its handler. This is the specified check order from the UDS lesson, implemented once.
  • DSP (diagnostic service processing): the standard services themselves. For ReadDataByIdentifier it looks up the DID in the configuration and calls the configured callback to fetch the data.

Your code appears as callbacks. For a DID read, a function of this shape, generated into the RTE and implemented by you:

Std_ReturnType Rte_Call_DataServices_BatteryVoltage_ReadData(Dcm_OpStatusType OpStatus, uint8 *Data)
{
  uint16 mv = BatteryMonitor_GetMillivolts();
  Data[0] = (uint8)(mv >> 8);
  Data[1] = (uint8)mv;
  return E_OK;
}

If the data is not ready, the callback returns DCM_E_PENDING. The Dcm calls it again on its next main function, and takes care of sending 7F 22 78 before P2 expires. You do not send response-pending yourself; you return pending and the DSL does the timing. Returning E_NOT_OK produces a negative response. Understanding that contract, and never blocking inside the callback, is most of what "experience with Dcm" means.

#include <stdio.h>
#include <stdint.h>

/* A PDU router in miniature: a table from the PDU that arrived to the module that takes it. */
typedef enum { TO_COM, TO_DCM, TO_GATEWAY } dest_t;
typedef struct { uint16_t rx_pdu; dest_t dest; uint16_t tx_pdu; } route_t;

enum { PDU_ENGINE_STATUS = 1, PDU_DIAG_REQUEST = 2, PDU_BODY_TO_CHASSIS = 3, PDU_CHASSIS_OUT = 40 };

static const route_t ROUTES[] = {
  { PDU_ENGINE_STATUS,   TO_COM,     0 },                 /* signals: unpacked by Com for the SWCs */
  { PDU_DIAG_REQUEST,    TO_DCM,     0 },                 /* a reassembled UDS request */
  { PDU_BODY_TO_CHASSIS, TO_GATEWAY, PDU_CHASSIS_OUT },   /* forwarded to another bus, untouched */
};

static void PduR_RxIndication(uint16_t pdu, const uint8_t *data, uint8_t len) {
  for (unsigned i = 0; i < sizeof ROUTES / sizeof ROUTES[0]; i++) {
    if (ROUTES[i].rx_pdu != pdu) continue;
    switch (ROUTES[i].dest) {
      case TO_COM:     printf("PDU %u -> Com: %u bytes of signals\n", pdu, len); break;
      case TO_DCM:     printf("PDU %u -> Dcm: service 0x%02X\n", pdu, data[0]); break;
      case TO_GATEWAY: printf("PDU %u -> CanIf, as PDU %u on the other bus\n", pdu, ROUTES[i].tx_pdu); break;
    }
    return;
  }
  printf("PDU %u: no route, dropped\n", pdu);
}

int main(void) {
  const uint8_t status[8] = { 0x12, 0x34 }, request[3] = { 0x22, 0xF1, 0x90 }, body[2] = { 1, 0 };
  PduR_RxIndication(PDU_ENGINE_STATUS, status, 8);
  PduR_RxIndication(PDU_DIAG_REQUEST, request, 3);
  PduR_RxIndication(PDU_BODY_TO_CHASSIS, body, 2);
  PduR_RxIndication(99, body, 2);
  return 0;
}

The real PduR is exactly this idea with generated tables. It holds no protocol knowledge of its own, which is why the same stack serves CAN, LIN, FlexRay and Ethernet: only the modules under the router change.

The modules a diagnostics engineer meets

ModuleDoesYou touch it when
Dem (diagnostic event manager)The fault memory: debounces events, maps them to DTCs, keeps status bytes, snapshots and ageing, stores them through NvMa monitor calls Dem_SetEventStatus(event, DEM_EVENT_STATUS_PREFAILED) and you configure what follows
Fim (function inhibition manager)Switches functions off while given DTCs are activea fault must disable a feature (no cruise control with a brake switch fault)
NvM (NVRAM manager)Named blocks of non-volatile data with CRC, redundancy and defaults; asynchronous NvM_ReadBlock / NvM_WriteBlocka DID is stored; write-all at shutdown; block corrupt after a brown-out
MemIf → Fee / Ea → Fls / EepThe memory stack under NvM: flash EEPROM emulation or a real EEPROM, then the driverwear levelling, sector switches that take 500 ms at a bad moment
ComPacks and unpacks signals in I-PDUs; transmission modes, timeouts, initial valuesa signal is wrong or late
ComM, CanSM, NmWhether the ECU may communicate: user requests, the bus state machine, network management that keeps the bus awakethe ECU will not sleep, or will not wake
EcuM, BswMStart-up and shutdown phases, and rule-based mode managementinit order bugs; "what must happen before sleep"
OsOSEK-style tasks, alarms, schedule tables, memory and timing protectiona main function is called at the wrong rate
Det / DltDevelopment error tracer and loga module reports an API misuse during integration

NvM deserves a closer look, because diagnostic data lives there. Each block has a RAM copy, a non-volatile copy and optionally a ROM default. Writes are requests that complete later in NvM_MainFunction, so NvM_WriteBlock returning E_OK means accepted, not written: you poll NvM_GetErrorStatus or get a callback. A block can be redundant (two copies, each with a CRC; reading takes the first valid one and repairs the other) and falls back to its defaults when neither is valid. NvM_WriteAll runs at shutdown, which is why an ECU that loses power abruptly loses whatever was not written explicitly, and why trouble codes that must survive a crash are written immediately.

Software components and the RTE

An SWC never includes a BSW header. It declares ports:

  • Sender-receiver ports carry data: "vehicle speed", read or written.
  • Client-server ports carry calls: "read this DID's data", "set this event's status".

Its code is a set of runnables, functions triggered by a period (every 10 ms), a data arrival or a call. Integration maps runnables onto OS tasks and connects ports to each other or to basic software, and the RTE generator turns each access into code: Rte_Read_VehicleSpeed_value(&v) may become a direct read of a global, a copy guarded against interruption, or a signal fetched from Com, depending on where the sender lives. The component's source does not change. That is the portability AUTOSAR promises, and the reason generated RTE code is the first place to look when data arrives stale.

Classic and Adaptive

ClassicAdaptive
Hardwaremicrocontrollersapplication processors
OSOSEK-style, static tasksPOSIX (Linux, QNX) processes
LanguageCC++
Configurationeverything fixed at build timeapplications deployed and updated at run time
Communicationsignals in PDUsservices (SOME/IP, DDS) found at run time
DiagnosticsDcm and Dem; UDS on CANara::diag; UDS on DoIP
Typical ECUdoor, engine, brake, batteryADAS, infotainment, central computer

A vehicle has both, and gateways between them. The diagnostic protocol is the same on each side, which is why what you learned in the UDS lessons transfers.

Interview question: Describe the AUTOSAR Classic layered architecture.

Answer: At the top are application software components, which implement the ECU's functions and communicate only through ports. The runtime environment below them is generated glue that implements those ports and schedules the components' runnables. Under it is the basic software in three layers. The services layer provides the operating system, communication, diagnostics, memory, and mode and network management. The ECU abstraction layer hides where a device is located, for example CanIf for any CAN controller or the memory abstraction for internal flash or an external EEPROM. The microcontroller abstraction layer contains the peripheral drivers with standardised APIs. Complex drivers sit beside these layers for functions that need direct hardware access. Each module is configured, and its tables and code are generated from an ARXML description.

Interview question: Trace a UDS request through the AUTOSAR communication stack.

Answer: The CAN driver receives the frame and passes it to CanIf, which maps the identifier to a PDU and forwards it to CanTp. CanTp implements ISO-TP: it reassembles a segmented request, sending flow control and running its timers, and passes the complete message to the PDU router, which routes it to the Dcm. In the Dcm the session layer handles timing and sessions, the dispatcher checks the service against the session, security level and length, and the service processing calls a configured callback, through the RTE into an application component, or into the Dem for trouble codes. The response goes back down: Dcm, PduR, CanTp for segmentation, CanIf and the CAN driver.

Going deeper

Interview question: NvM_WriteBlock returned E_OK, but after a power cut the value is the old one. Explain.

Answer: NvM_WriteBlock only queues the request. The actual write happens later, in steps, in NvM_MainFunction and the main functions of the memory abstraction and flash driver below it, and can take tens of milliseconds, or much longer if the flash EEPROM emulation has to switch sectors. E_OK means the request was accepted. The caller must wait for the job result, by polling NvM_GetErrorStatus until it is no longer pending or through the configured job-end callback, before treating the data as stored. If power failed before that, the non-volatile copy is still the old one, which the CRC and redundancy keep valid. Data that must survive sudden power loss is written immediately on change rather than left to NvM_WriteAll at shutdown.

Interview question: What is the difference between the Dcm and the Dem?

Answer: The Dcm is the diagnostic protocol: it talks to the tester, implementing UDS services, sessions, security and timing. The Dem is the fault memory: it receives pass and fail reports for diagnostic events from monitors in the application and basic software, debounces them, maintains each DTC's status byte, captures snapshot and extended data, handles operation cycles and ageing, and stores it all through NvM. They meet in the services that read and clear trouble codes: the Dcm receives ReadDTCInformation or ClearDiagnosticInformation and calls Dem interfaces to filter, fetch or clear the data. The Dem would still be collecting faults if no tester ever connected.

Interview question: An engineer wants to read a GPIO directly in a software component to save time. What is wrong with that?

Answer: The component would depend on a specific pin of a specific microcontroller, so it could no longer be reused on another ECU or tested on a PC, which is the point of the architecture. It bypasses the I/O hardware abstraction where the signal's polarity, debouncing, diagnosis and substitute values are handled, so the application sees a raw level instead of a qualified signal. It also escapes the integration's control of timing and data consistency, since the RTE no longer knows about the access, and it will be rejected in review and by architecture checks. The right route is a port to the I/O hardware abstraction component; if the timing truly cannot be met that way, the function belongs in a complex driver with a documented justification.

Explain it: In your own words, explain why a Dcm callback returns DCM_E_PENDING instead of waiting for its data.

Answer: All basic software modules share the processor by taking turns in short main functions; nothing may hold it for long. If a callback waited for slow data, the Dcm's own timers, the transport layer and every other module's main function would stop meanwhile, so the response deadline would be missed and other functions disturbed. Returning DCM_E_PENDING hands control back at once and tells the Dcm the operation is still in progress. The Dcm calls the callback again on later cycles, and its session layer sends the response-pending message before P2 runs out, repeating it as needed, until the callback returns the data or an error.