Groking The Linux SPI Subsystem

2y ago
39 Views
2 Downloads
1.63 MB
47 Pages
Last View : 13d ago
Last Download : 3m ago
Upload by : Halle Mcleod
Transcription

Groking the Linux SPI SubsystemEmbedded Linux Conference 2017Matt Porter

Obligatory geekreferencedeobfuscationgrok (/gräk/)verbto understand intuitively or by empathy, toestablish rapport with.

Overview What is SPI?SPI FundamentalsLinux SPI ConceptsLinux SPI Use cases Add a deviceProtocol driversController driversUserspace drivers Linux SPI Performance Linux SPI Future

What is SPI?

What is SPI? Serial Peripheral InterfaceMotorolade facto standardmaster-slave bus4 wire bus except when it’s not no maximum clock speed “A glorified shift register”http://wikipedia.org/wiki/Serial Peripheral Interface

Common uses of SPI Flash memoryADCsSensors thermocouples, other high data rate devicesLCD controllersChromium Embedded Controller

SPI fundamentals

SPI Signals MOSI - Master Output Slave Input MISO - Master Input Slave Output SIMO, SDI, DI, SDASOMI, SDO, DO, SDASCLK - Serial Clock (Master output) SCK, CLK, SCL S̅S̅ - Slave Select (Master output) CSn, EN, ENB

SPI Master and Slave

Basic SPI Timing Diagram

SPI Modes Modes are composed of two clock characteristicsCPOL - clock polarity 0 clock idle state low 1 clock idle state highCPHA - clock phase 0 data latched falling, output rising 1 data latched rising, output fallingModeCPOLCPHA000101210311

SPI Mode Timing - CPOL 0

SPI Mode Timing - CPOL 1

SPI can be more complicated Multiple SPI Slaves One chip select for each slaveDaisy Chaining Inputs to Outputs Chip SelectsDual or Quad SPI (or more lanes) Implemented in high speed SPI Flash devices Instead of one MISO, have N MISOs N times bandwidth of traditional SPI3 Wire (Microwire) SPI Combined MISO/MOSI signal operates in half duplex

Multiple SPI Slaves

SPI Mode Timing - Multiple Slaves

Linux SPI concepts

Linux SPI drivers Controller and Protocol drivers only (so far) Controller drivers support the SPI master controller Drive hardware to control clock and chip selects, shift data bits on/offwire and configure basic SPI characteristics like clock frequency andmode. e.g. spi-bcm2835aux.c Protocol drivers support the SPI slave specific functionality Based on messages and transfers Relies on controller driver to program SPI master hardware. e.g. MCP3008 ADC

Linux SPI communication Communication is broken up into transfers and messagesTransfers Defines a single operation between master and slave. tx/rx buffer pointers optional chip select behavior after operation optional delay after operationMessages Atomic sequence of transfers Fundamental argument to all SPI subsystem read/write APIs.

SPI Messages and Transfers

Linux SPI use cases

Exploring via use cases I want to hook up a SPI device on my board that alreadyhas a protocol driver in the kernel. I want to write a kernel protocol driver to control my SPIslave. I want to write a kernel controller driver to drive my SPImaster. I want to write a userspace protocol driver to control mySPI slave.

Adding a SPI device to a system Know the characteristics of your slave device! Learn to read datasheetsThree methods Device Tree Ubiquitous Board File Deprecated ACPI Mostly x86

Reading datasheets for SPI details - ST7735

Reading datasheets for SPI details - ST7735

Reading datasheets for SPI details - MCP3008

Reading datasheets for SPI details - MCP3008

MCP3008 via DT - binding* Microchip Analog to Digital Converter (ADC)The node for this driver must be a child node of a SPI controller, henceall mandatory properties described tmust be specified.Required properties:- compatible:Must be one of the following, depending on themodel:."microchip,mcp3008".Examples:spi controller {mcp3x0x@0 {compatible "mcp3002";reg 0 ;spi-max-frequency 1000000 ;};};

MCP3008 via DT - driverstatic const struct of device id mcp320x dt ids[] {/* NOTE: The use of compatibles with no vendor prefix is deprecated. */{.}, {.compatible "mcp3008",.data &mcp320x chip infos[mcp3008],}, {.}};MODULE DEVICE TABLE(of, mcp320x dt ids);.static struct spi driver mcp320x driver {.driver {.name "mcp320x",.of match table of match ptr(mcp320x dt ids),},.probe mcp320x probe,.remove mcp320x remove,.id table mcp320x id,};module spi driver(mcp320x driver);

MCP3008 via DT - DTS overlay fragmentfragment@1 {target &spi0 ;overlay {/* needed to avoid dtc warning */#address-cells 1 ;#size-cells 0 ;mcp3x0x@0 {compatible "mcp3008";reg 0 ;spi-max-frequency 1000000 ;};};};

MCP3008 via board file - C fragmentstatic struct spi board info my board info[] initdata {{.modalias "mcp320x",.max speed hz 4000000,.bus num 0,.chip select 0,},};spi register board info(spi board info, ARRAY SIZE(my board info));

MCP3008 via ACPIScope (\ SB.SPI1){Device (MCP3008){Name ( HID, "PRP0001")Method ( CRS, 0, Serialized) {Name (UBUF, ResourceTemplate () {SpiSerialBus (0x0000, PolarityLow, FourWireMode, 0x08,ControllerInitiated, 0x003D0900, ClockPolarityLow,ClockPhaseFirst, "\\ SB.SPI1", 0x00, ResourceConsumer)})Return (UBUF)}Method ( STA, 0, NotSerialized){Return (0xF)}}}

Protocol Driver Standard LInux driver modelInstantiate a struct spi driver .driver .name “my protocol”, .pm &my protocol pm ops, .probe my protocol probe .remove my protocol removeOnce it probes, SPI I/O may take place using kernel APIs

Kernel APIs spi async() asynchronous message request callback executed upon message complete can be issued in any contextspi sync() synchronous message request may only be issued in a context that can sleep (i.e. not in IRQ context) wrapper around spi async()spi write()/spi read() helper functions wrapping spi sync()

Kernel APIs spi read flash() Optimized call for SPI flash commands Supports controllers that translate MMIO accesses into standard SPIflash commandsspi message init() Initialize empty messagespi message add tail() Add transfers to the message’s transfer list

Controller Driver Standard LInux driver modelAllocate a controller spi alloc master()Set controller fields and methods (just the basics) mode bits - flags e.g. SPI CPOL, SPI CPHA, SPI NO CS,SPI CS HIGH, SPI RX QUAD, SPI LOOP setup() - configure SPI parameters cleanup() - prepare for driver removal transfer one message()/transfer one() - dispatch one msg/transfer(mutually exclusive)Register a controller spi register master()

Userspace Driver - spidev Primarily for development and testDT binding requires use of a supported compatible string or add a new one ifno kernel driver exists for the device rohm,dh2228fv lineartechnology,ltc2488 ge,achcACPI binding requires use of a dummy device ID SPT0001 SPT0002 SPT0003

Userspace Driver - spidev Slave devices bound to the spidev driver yield: /sys/class/spidev/spidev[bus].[cs] /dev/spidev[bus].[cs]Character device open()/close() read()/write() are half duplex ioctl() SPI IOC MESSAGE - raw messages, full duplex and chip selectcontrol SPI IOC [RD WR] * - set SPI parameters

Userspace Help Docs Documentation/spi/spidevExamples tools/spi/spidev fdx.c tools/spi/spidev test.cHelper libaries https://github.com/jackmitch/libsoc https://github.com/doceme/py-spidev

Linux SPIPerformance

Performance considerations Be aware of underlying DMA engine or SPI controller driver behavior. e.g. OMAP McSPI hardcoded to PIO up to 160 byte transfersync versus async API behavior async may be suitable for higher bandwidth where latency is not aconcern (some network drivers) sync will attempt to execute in caller context (as of 4.x kernel) avoidingsleep and reducing latency

Performance considerations Use cs change wisely. Note the details from include/linux/spi/spi.h:*******************All SPI transfers start with the relevant chipselect active. Normallyit stays selected until after the last transfer in a message. Driverscan affect the chipselect signal using cs change.(i) If the transfer isn't the last one in the message, this flag isused to make the chipselect briefly go inactive in the middle of themessage. Toggling chipselect in this way may be needed to terminatea chip command, letting a single spi message perform all of group ofchip transactions together.(ii) When the transfer is the last one in the message, the chip maystay selected until the next transfer. On multi-device SPI busseswith nothing blocking messages going to other devices, this is justa performance hint; starting a message to another device deselectsthis one. But in other cases, this can be used to ensure correctness.Some devices need protocol transactions to be built from a series ofspi message submissions, where the content of one message is determinedby the results of previous messages and where the whole transactionends when the chipselect goes inactive.

Performance tools Debug/visibility tools critical to any hardware focused workLogic analyzer http://elinux.org/Logic Analyzers https://sigrok.org/wiki/Supported hardware#Logic analyzersdrivers/spi/spi-loopback-testSPI subsystem statistics /sys/class/spi master/spiB/spiB.C/statistics messages, transfers, errors, timedout spi sync, spi sync immediate, spi async transfer bytes histo *

Linux SPI Future

Slave Support Hard real time issues on Linux due to full duplex nature of SPI.Useful if considering limited use cases Pre-existing responses Commands sent to slaveRFC v2 patch series https://lkml.org/lkml/2016/9/12/1065Registering a controller works just like a master spi alloc slave()

Slave Support /sys/class/spi slave/spiB/slave for each slave controllerslave protocol drivers can be bound via sysfs echo slave-foo /sys/class/spi slave/spi3/slaveTwo slave protocol drivers provided as an example spi-slave-time (provides latest uptime to master) spi-slave-system-control (power off, reboot, halt system)

Questions?

Controller drivers support the SPI master controller Drive hardware to control clock and chip selects, shift data bits on/off wire and configure basic SPI characteristics like clock frequency and mode. e.g. spi-bcm2835aux.c Protocol drivers support the

Related Documents:

May 02, 2018 · D. Program Evaluation ͟The organization has provided a description of the framework for how each program will be evaluated. The framework should include all the elements below: ͟The evaluation methods are cost-effective for the organization ͟Quantitative and qualitative data is being collected (at Basics tier, data collection must have begun)

Silat is a combative art of self-defense and survival rooted from Matay archipelago. It was traced at thé early of Langkasuka Kingdom (2nd century CE) till thé reign of Melaka (Malaysia) Sultanate era (13th century). Silat has now evolved to become part of social culture and tradition with thé appearance of a fine physical and spiritual .

On an exceptional basis, Member States may request UNESCO to provide thé candidates with access to thé platform so they can complète thé form by themselves. Thèse requests must be addressed to esd rize unesco. or by 15 A ril 2021 UNESCO will provide thé nomineewith accessto thé platform via their émail address.

̶The leading indicator of employee engagement is based on the quality of the relationship between employee and supervisor Empower your managers! ̶Help them understand the impact on the organization ̶Share important changes, plan options, tasks, and deadlines ̶Provide key messages and talking points ̶Prepare them to answer employee questions

Dr. Sunita Bharatwal** Dr. Pawan Garga*** Abstract Customer satisfaction is derived from thè functionalities and values, a product or Service can provide. The current study aims to segregate thè dimensions of ordine Service quality and gather insights on its impact on web shopping. The trends of purchases have

Linux in a Nutshell Linux Network Administrator’s Guide Linux Pocket Guide Linux Security Cookbook Linux Server Hacks Linux Server Security Running Linux SELinux Understanding Linux Network Internals Linux Books Resource Center linux.oreilly.comis a complete catalog of O’Reilly’s books on Linux and Unix and related technologies .

Chính Văn.- Còn đức Thế tôn thì tuệ giác cực kỳ trong sạch 8: hiện hành bất nhị 9, đạt đến vô tướng 10, đứng vào chỗ đứng của các đức Thế tôn 11, thể hiện tính bình đẳng của các Ngài, đến chỗ không còn chướng ngại 12, giáo pháp không thể khuynh đảo, tâm thức không bị cản trở, cái được

224 Communicating in the 21st Century Essay writing ‘The essay is a form of refined torture. Discuss.’ You almost certainly will never encounter such an essay topic, but you might think it.