repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
dsnet/mario-doorbell
mikroc/hex_convert/hex_convert.c
// Copyright 2009, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <ctype.h> #include <string.h> /* Helper macros */ #define FUNC_RETURN(fn, rc) { fn(); return rc; } #define FUNC_PRINT_RETURN(fn, st, rc) { fn(); printf(st); return rc; } #define IS_POWER_2(d) (((d) & ((d)-1)) == 0) /* Struct definitions */ typedef struct __attribute__((packed)) { char chunk_id[4]; uint32_t chunk_size; char format[4]; } WaveHeader; typedef struct __attribute__((packed)) { char chunk_id[4]; uint32_t chunk_size; uint16_t audio_format; uint16_t num_channels; uint32_t sample_rate; uint32_t byte_rate; uint16_t block_align; uint16_t bits_per_sample; } FormatChunk; typedef struct __attribute__((packed)) { char chunk_id[4]; uint32_t chunk_size; uint8_t* data; } DataChunk; typedef struct { FILE* out; size_t out_cnt; uint8_t buf[16]; size_t buf_cnt; } HexFile; /* Global constants */ const char help_msg[] = ( "This program will generate an Intel Hex file containing the sound data\n" "from a series of wave files. Only monophonic sounds at rates of 8000,\n" "11025, or 22050 samples per second are supported.\n\n" ); int get_input(char*** _wav_files, int* _num_files); int process_wavfile(HexFile* hf, const char* wav_file, int wav_idx); HexFile* hexfile_open(const char* filename); size_t hexfile_tell(HexFile* hf); int hexfile_write(HexFile* hf, void* buf, size_t size); int hexfile_close(HexFile* hf); int main(int argc, char* argv[]) { int scan; int num_files = 0; char** wav_files = NULL; HexFile* hex_file = NULL; void ret_func() { hexfile_close(hex_file); if (argc <= 1) { for (scan = 0; scan < num_files; scan++) free(wav_files[scan]); free(wav_files); } } // Get list of wave files to read if (argc > 1) { wav_files = &argv[1]; num_files = argc-1; } else { if (get_input(&wav_files, &num_files)) FUNC_RETURN(ret_func, -1); } // Open the Intel HEX file hex_file = hexfile_open("eeprom.hex"); if (hex_file == NULL) FUNC_PRINT_RETURN(ret_func, "Could not open hex file\n", -1); // Process each wave file printf("Begin processing...\n\n"); for (scan = 0; scan < num_files; scan++) if (process_wavfile(hex_file, wav_files[scan], scan)) FUNC_RETURN(ret_func, -1); printf("Finish processing...\n"); // Close the Intel HEX file bool fail = hexfile_close(hex_file); hex_file = NULL; if (fail) FUNC_PRINT_RETURN(ret_func, "Could not close hex file\n", -1); FUNC_RETURN(ret_func, 0); } // Read a list wave files to process from stdin. This function // will allocate an array for wav_files and report the number // of filenames present in the array. It is the callee's // responsibility to free the array. int get_input(char*** _wav_files, int* _num_files) { int num_files = 0; char** wav_files = NULL; void ret_func() { (*_wav_files) = wav_files; (*_num_files) = num_files; } num_files = 0; wav_files = malloc(1*sizeof(uintptr_t)); if (wav_files == NULL) FUNC_PRINT_RETURN(ret_func, "Memory error\n", -1); printf(help_msg); while (true) { printf("Enter wave file to convert (empty line to stop): "); // Read line from stdin char* line = NULL; size_t len = 0; if (getline(&line, &len, stdin) == -1) FUNC_PRINT_RETURN(ret_func, "Memory error\n", -1); strtok(line, "\r\n"); // Store the file if not a blank line if (!iscntrl(line[0])) { wav_files[num_files] = line; num_files++; // If num_files is power of two, then expand array if (IS_POWER_2(num_files)) { void* ptr = wav_files; wav_files = realloc(ptr, 2*num_files*sizeof(uintptr_t)); if (wav_files == NULL) { wav_files = ptr; FUNC_PRINT_RETURN(ret_func, "Memory error\n", -1); } } } else { free(line); break; } } printf("\n"); FUNC_RETURN(ret_func, 0); } // Opens wav_file, parses it as a WAVE file, and then dumps the // sound samples into hex_file. int process_wavfile(HexFile* hex_file, const char* wav_file, int wav_idx) { WaveHeader wav_hdr; FormatChunk fmt_chk; DataChunk data_chk; int fsize = 0; FILE* fwave = NULL; void* buf = NULL; void ret_func() { if (fwave != NULL) fclose(fwave); free(buf); } printf("Wave %d: %s\n ", wav_idx, wav_file); // Open wave file fwave = fopen(wav_file, "rb"); if (fwave == NULL) FUNC_PRINT_RETURN(ret_func, "Could not open file\n", -1); // Get the file size if (fseek(fwave, 0, SEEK_END) == -1) FUNC_PRINT_RETURN(ret_func, "Could not fseek in file\n", -1); fsize = ftell(fwave); if (fsize == -1) FUNC_PRINT_RETURN(ret_func, "Could not ftell in file\n", -1); if (fseek(fwave, 0, SEEK_SET) == -1) FUNC_PRINT_RETURN(ret_func, "Could not fseek in file\n", -1); buf = malloc(fsize); if (buf == NULL) FUNC_PRINT_RETURN(ret_func, "Memory error\n", -1); if (fread(buf, fsize, 1, fwave) != 1) FUNC_PRINT_RETURN(ret_func, "Read error\n", -1); int hdr_size = sizeof(wav_hdr) + sizeof(fmt_chk) + sizeof(data_chk); hdr_size -= sizeof(data_chk.data); // Data pointer doesn't count if (fsize < hdr_size) FUNC_PRINT_RETURN(ret_func, "Filesize too small for headers\n", -1); void* _buf = buf; // Process the wave header memcpy(&wav_hdr, _buf, sizeof(wav_hdr)); _buf += sizeof(wav_hdr); if (memcmp(wav_hdr.chunk_id, "RIFF", sizeof(wav_hdr.chunk_id))) FUNC_PRINT_RETURN(ret_func, "Wave header chunk ID mismatch\n", -1); if (wav_hdr.chunk_size != (fsize-8)) FUNC_PRINT_RETURN(ret_func, "Wave filesize mismatch\n", -1); if (memcmp(wav_hdr.format, "WAVE", sizeof(wav_hdr.format))) FUNC_PRINT_RETURN(ret_func, "Wave format mismatch\n", -1); // Process the format chunk memcpy(&fmt_chk, _buf, sizeof(fmt_chk)); _buf += sizeof(fmt_chk); if (memcmp(fmt_chk.chunk_id, "fmt ", sizeof(fmt_chk.chunk_id))) FUNC_PRINT_RETURN(ret_func, "Format chunk ID mismatch\n", -1); if (fmt_chk.chunk_size != sizeof(fmt_chk) - 8) FUNC_PRINT_RETURN(ret_func, "Format chunk size mismatch\n", -1); if (fmt_chk.audio_format != 1) FUNC_PRINT_RETURN(ret_func, "Audio format isn't linear encoding\n", -1); if (fmt_chk.num_channels != 1) FUNC_PRINT_RETURN(ret_func, "Only one channel supported\n", -1); if (fmt_chk.sample_rate != 8000 && fmt_chk.sample_rate != 11025 && fmt_chk.sample_rate != 22050) FUNC_PRINT_RETURN(ret_func, "Invalid sampling rate\n", -1); if (fmt_chk.sample_rate != fmt_chk.byte_rate) FUNC_PRINT_RETURN(ret_func, "Sample rate must equal byte rate\n", -1); if (fmt_chk.block_align != 1) FUNC_PRINT_RETURN(ret_func, "Block alignment must be 1 byte\n", -1); if (fmt_chk.bits_per_sample != 8) FUNC_PRINT_RETURN(ret_func, "Sample resolution must be 8-bits\n", -1); // Process the data chunk memcpy(&data_chk, _buf, sizeof(data_chk) - sizeof(data_chk.data)); _buf += sizeof(data_chk) - sizeof(data_chk.data); data_chk.data = _buf; if (memcmp(data_chk.chunk_id, "data", sizeof(data_chk.chunk_id))) FUNC_PRINT_RETURN(ret_func, "Data chunk ID mismatch\n", -1); if (data_chk.chunk_size != fsize - (_buf - buf)) FUNC_PRINT_RETURN(ret_func, "Data chunk size mismath\n", -1); // Write data to the hex file size_t offset = hexfile_tell(hex_file); if (hexfile_write(hex_file, data_chk.data, data_chk.chunk_size)) FUNC_PRINT_RETURN(ret_func, "Failure to write to hex file\n", -1); printf("Data offset: 0x%08X\n ", (int)offset); printf("Data length: 0x%08X\n ", data_chk.chunk_size); printf("Sample rate: %d\n ", fmt_chk.sample_rate); printf("\n"); FUNC_RETURN(ret_func, 0); } // Allocate a struct to manage writing the hex file. HexFile* hexfile_open(const char* filename) { HexFile* hf = malloc(sizeof(HexFile)); if (hf == NULL) return NULL; FILE* out = fopen(filename, "w"); if (out == NULL) { free(hf); return NULL; } hf->out = out; hf->out_cnt = 0; hf->buf_cnt = 0; return hf; } // Tell the number of bytes written in the hex file. size_t hexfile_tell(HexFile* hf) { return hf->out_cnt + hf->buf_cnt; } // Write a buffer of length size into the hex file. int hexfile_write(HexFile* hf, void* buf, size_t size) { int scan; bool flush = false; char cbuf[sizeof(hf->buf)*2+1]; memset(cbuf, 0, sizeof(cbuf)); // If the internal buffer is used, then flush if (buf == hf->buf) { flush = true; hf->buf_cnt = 0; } // For each byte in the buffer while (size > 0) { hf->buf[hf->buf_cnt] = *((uint8_t*)buf); hf->buf_cnt++; buf++; size--; // Only write out to the hex-file if we have a full line or flushing if ((hf->buf_cnt == sizeof(hf->buf)) || (flush && size == 0)) { uint8_t rec_type = 0x00; uint16_t offset = (hf->out_cnt >> 4) << 4; uint8_t checksum = hf->buf_cnt + rec_type + ((offset >> 0) & 0xFF) + ((offset >> 8) & 0xFF); for (scan = 0; scan < hf->buf_cnt; scan++) checksum += hf->buf[scan]; checksum = ~checksum + 1; for (scan = 0; scan < hf->buf_cnt; scan++) sprintf(&cbuf[scan*2],"%02X", hf->buf[scan]); if (fprintf(hf->out, ":%02X%04X%02X%s%02X\n", (int)hf->buf_cnt, offset, rec_type, cbuf, checksum) < 0) { return -1; } // Update output counter, reset buffer counter hf->out_cnt += hf->buf_cnt; hf->buf_cnt = 0; // Switch banks if (hf->out_cnt % 0x00010000 == 0) { uint8_t rec_type = 0x04; uint16_t offset = (hf->out_cnt >> 8*sizeof(uint16_t)); uint8_t checksum = sizeof(offset) + rec_type + ((offset >> 0) & 0xFF) + ((offset >> 8) & 0xFF); checksum = ~checksum + 1; if (fprintf(hf->out, ":%02X%04X%02X%04X%02X\n", (int)sizeof(offset), 0, rec_type, offset, checksum) < 0) { return -1; } } } } // This is the end-of-file, so flush the buffer if (flush) { const char* eof = ":00000001FF\n"; if (fwrite(eof, strlen(eof), 1, hf->out) != 1) { return -1; } } return 0; } // Close the hex file and free resources. int hexfile_close(HexFile* hf) { int error = 0; if (hf != NULL && hf->out != NULL) { error = hexfile_write(hf, hf->buf, hf->buf_cnt); error |= fclose(hf->out); hf->out = NULL; } free(hf); return error; }
dsnet/mario-doorbell
mikroc/door_ringer/door_ringer.c
<reponame>dsnet/mario-doorbell // Copyright 2009, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. /* Project name: Mario Doorbell Project - Door ringer Description: As the counterpart to the doorbell button part of this project, this module will play the sound clip requested on the USART. In order to play the requested sound file, sound data is first retrieved from a EEPROM chip and then sent to a DAC chip. Unless the MCU is overclocked, the maximum sample rate that can be played is 22050 samples/second. Configuration: Microcontroller: PIC16F687 Oscillator: HS, 20.00 MHz External modules: MCP4822 DAC, 25LC1024 EEPROM Compiler: MikroC 8.0 Notes: A C++ program was written in order to easily convert multiple .wav files into a single Intel Hex file ready to load onto the EEPROM chip. Only 8-bit, monophonic, non-compressed wav files are playable. In addition, only rates of 8000, 11025, and 22050 samples/second are supported. */ /* Helper macros */ #define BYTE0(param) ((char *)&param)[0] #define BYTE1(param) ((char *)&param)[1] #define BYTE2(param) ((char *)&param)[2] #define BYTE3(param) ((char *)&param)[3] /* Global constants */ enum frequency { FREQ_8000, FREQ_11025, FREQ_22050 }; enum sound { COIN, COIN_1UP, COIN_MUSHROOM, ITS_MARIO, OUTTA_TIME, DOWN_PIPE }; /* Global variables */ unsigned short rx_data; unsigned long wave_scan; // Interrupt vector void interrupt() { // If there is an external interrupt if (INTCON.INTF) { delay_ms(25); // Debounce delay // Determine the sound to be played (debugging purposes) rx_data = 0xFF; if (PORTA.F0 && PORTA.F1) { rx_data = ITS_MARIO; } else if (!PORTA.F0 && PORTA.F1) { rx_data = OUTTA_TIME; } else if (PORTA.F0 && !PORTA.F1) { rx_data = DOWN_PIPE; } INTCON.INTF = 0; // Clear interrupt flag } // If there is an unread byte if (PIR1.RCIF) { rx_data = usart_read(); wave_scan = 0x80000000; // Stop on-going sounds } } // Function to play sound from the EEPROM void play_sound(short rate, unsigned long offset, unsigned long length) { unsigned int wave_data; // Wake up EEPROM - with power-up delay PORTC.F0 = 1; PORTC.F0 = 0; spi_write(0xAB); PORTC.F0 = 1; delay_us(100); // Setup the EEPROM PORTC.F0 = 0; PORTC.F2 = 1; // Unhold EEPROM spi_write(0x03); // EEPROM read command spi_write(BYTE2(offset)); spi_write(BYTE1(offset)); spi_write(BYTE0(offset)); // Process all bytes in sound file for (wave_scan = 0x000000; wave_scan < length; wave_scan++) { // Retrieve a byte of audio data PORTC.F2 = 1; // Unhold EEPROM wave_data = (SPI_Read(0x00) << 4); // Read EEPROM byte PORTC.F2 = 0; // Hold EEPROM // Write audio data to DAC PORTC.F1 = 0; spi_write(BYTE1(wave_data) | 0x10); spi_write(BYTE0(wave_data)); PORTC.F1 = 1; // Set delays for different sampling rates switch (rate) { case FREQ_8000: delay_us(0x65); break; case FREQ_11025: delay_us(0x41); break; case FREQ_22050: delay_us(0x12); break; } } // Set DAC voltage output to normalized level PORTC.F1 = 0; spi_write(0x18); spi_write(0x00); PORTC.F1 = 1; // Shutdown EEPROM - with power-down delay PORTC.F0 = 1; PORTC.F0 = 0; spi_write(0xB9); PORTC.F0 = 1; delay_us(100); } // Main routine void main() { unsigned short _rx_data; // Initiate variables rx_data = 0xFF; wave_scan = 0xFFFFFFFF; // Disable ADC modules ANSEL = 0x00; ANSELH = 0x00; OPTION_REG = 0x40; TRISA = 0x07; WPUA = 0x07; // Setup SPI module TRISB = 0x00; TRISC = 0x00; PORTC.F0 = 1; // nCS for EEPROM PORTC.F1 = 1; // nCS for DAC PORTC.F2 = 1; // nHold for EEPROM TRISB.F6 = 0; // SCK is output TRISB.F4 = 1; // SDI is input TRISC.F7 = 0; // SDO is output spi_init_advanced( MASTER_OSC_DIV4, DATA_SAMPLE_MIDDLE, CLK_IDLE_LOW, LOW_2_HIGH ); // Setup USART module with interrupts usart_init(9615); INTCON.PEIE = 1; INTCON.GIE = 1; INTCON.INTE = 1; PIE1.RCIE = 1; // Continue forever while (1) { _rx_data = rx_data; rx_data = 0xFF; // Clear the wave to play switch (_rx_data) { case COIN: play_sound(FREQ_22050, 0x000000, 0x0046BE); break; case COIN_1UP: play_sound(FREQ_22050, 0x000000, 0x000CEC); play_sound(FREQ_22050, 0x0046BE, 0x0042F0); break; case COIN_MUSHROOM: play_sound(FREQ_22050, 0x000000, 0x000CEC); play_sound(FREQ_22050, 0x0089AE, 0x005053); break; case ITS_MARIO: play_sound(FREQ_11025, 0x00DA01, 0x0050C9); break; case OUTTA_TIME: play_sound(FREQ_11025, 0x012ACA, 0x007DC1); break; case DOWN_PIPE: play_sound(FREQ_22050, 0x01A88B, 0x000FD2); delay_ms(85); play_sound(FREQ_22050, 0x01A88B, 0x000FD2); delay_ms(85); play_sound(FREQ_22050, 0x01A88B, 0x000FD2); delay_ms(85); break; } } }
dsnet/mario-doorbell
mikroc/door_button/door_button.c
<gh_stars>1-10 // Copyright 2009, <NAME>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. /* Project name: Mario Doorbell Project - Door button Description: This firmware code implements the button for the doorbell. The idea is to have a button that, when pressed, increments a two digit 7-segment display. Normally, for every press, the Mario coin sound will be played as the doorbell ringer. For every 10 presses, the 1-Up sound will be played, and for every 100 presses, the mushroom power-up sound will be played. The signal to determine which sound to be played is sent using USART. Since this component is placed outside the door as the button interface, as few components as possible were used to reduce cost in the unfortunate event that someone stole the doorbell button. Configuration: Microcontroller: PIC16F628A Oscillator: INT_RC, 4.00 MHz External modules: 7-segment Display Compiler: MikroC 8.0 Notes: The reason why hardware USART was not used is because the sound generator that this device connects to was originally a PIC16F88 which could not support SPI and USART simultaneously. Thus, USART was not originally the planned method of communication between the two. In a freak accident, all the PIC16F88 chips I had were destroyed, so I had to settle with a different chip that happened to support both USART and SPI together. However, by this time, the PCB for this part had already been laid out and made. */ /* Global constants */ const unsigned short LO_SEGMENT[10] = { 0x02, 0xDA, 0x44, 0x50, 0x98, 0x11, 0x01, 0x5A, 0x00, 0x10, }; const unsigned short HI_SEGMENT[10] = { 0xDF, 0xDA, 0x44, 0x50, 0x98, 0x11, 0x01, 0x5A, 0x00, 0x10, }; enum sound { COIN, COIN_1UP, COIN_MUSHROOM, ITS_MARIO, OUTTA_TIME, DOWN_PIPE }; /* Global variables */ unsigned short ring_type; unsigned short lo_num; unsigned short hi_num; unsigned short toggle; unsigned short press; // Interrupt vector void interrupt() { // If timer timeout interrupt if (INTCON.T0IF) { // Toggle between the digits on the 7-segment display if (toggle == 0) { PORTB.F1 = 1; // Disable PMOS PORTB.F2 = 0; // Enable PMOS PORTA = LO_SEGMENT[lo_num]; toggle = 1; } else { PORTB.F2 = 1; // Disable PMOS PORTB.F1 = 0; // Enable PMOS PORTA = HI_SEGMENT[hi_num]; toggle = 0; } INTCON.T0IE = 1; // Enable timer interrupt INTCON.T0IF = 0; // Clear timer interrupt flag } // If external interrupt if (INTCON.INTF) { press = 1; // Set press flag INTCON.INTE = 0; // Disable external interrupt INTCON.INTF = 0; // Clear external interrupt flag } } // Main routine void main() { // Define settings PORTA = 0x00; PORTB = 0x00; TRISA = 0x00; TRISB = 0x21; CMCON = 0x07; // Disable analog comparators OPTION_REG = 0x04; // Initialize variables hi_num = 0; lo_num = 0; toggle = 0; press = 0; // Initialize software UART soft_uart_init(PORTB, 5, 4, 9615, 0); // Set up interrupts INTCON.T0IE = 1; INTCON.T0IF = 0; INTCON.PEIE = 1; INTCON.INTE = 1; INTCON.GIE = 1; // Continue forever while (1) { // Poll for the press flag if (press) { INTCON.INTE = 0; // Disable external interrupt press = 0; // Clear the press flag // Make sure the button is still pressed and not a spurious bounce delay_ms(25); if (PORTB.F0 == 0) { // Increment lo_num++; if (lo_num == 10) { lo_num = 0; hi_num++; if (hi_num == 10) { hi_num = 0; } } // Determine ring type if (lo_num == 0) { if (hi_num == 0) { ring_type = COIN_MUSHROOM; } else { ring_type = COIN_1UP; } } else { ring_type = COIN; } // Send software UART signal INTCON.GIE = 0; soft_uart_write(ring_type); INTCON.GIE = 1; // Set delay until next allowable button press switch (ring_type) { case COIN: delay_ms(125); break; case COIN_1UP: delay_ms(675); break; case COIN_MUSHROOM: delay_ms(875); break; } } // Re-enable external interrupts INTCON.INTF = 0; // Clear external interrupt flag INTCON.INTE = 1; // Enable external interrupt } } }
Tomp0801/Micro-RTSP-Audio
src/RTSPSession.h
/* * Author: <NAME> * github: https://github.com/Tomp0801/Micro-RTSP-Audio * * Based on Micro-RTSP library for video streaming by Kevin Hester: * * https://github.com/geeksville/Micro-RTSP * * Copyright 2018 <NAME>, <EMAIL> (MIT License) */ #pragma once #include "AudioStreamer.h" #include "platglue.h" /// Supported RTSP command types enum RTSP_CMD_TYPES { RTSP_OPTIONS, RTSP_DESCRIBE, RTSP_SETUP, RTSP_PLAY, RTSP_TEARDOWN, RTSP_UNKNOWN }; /// Buffer size for incoming requests, and outgoing responses #define RTSP_BUFFER_SIZE 10000 /// Size of RTSP parameter buffers #define RTSP_PARAM_STRING_MAX 100 /// Buffer size for RTSP host name #define MAX_HOSTNAME_LEN 256 /** * Class for handling an RTSP session * Requires a an AudioStreamer as a source for Streaming */ class RtspSession { private: const char * STD_URL_PRE_SUFFIX = "trackID"; // global session state parameters int m_RtspSessionID; WiFiClient m_Client; SOCKET m_RtspClient; // RTSP socket of that session int m_StreamID; // number of simulated stream of that session IPPORT m_ClientRTPPort; // client port for UDP based RTP transport IPPORT m_ClientRTCPPort; // client port for UDP based RTCP transport AudioStreamer * m_Streamer; // the UDP streamer of that session // parameters of the last received RTSP request RTSP_CMD_TYPES m_RtspCmdType; // command type (if any) of the current request char m_URLPreSuffix[RTSP_PARAM_STRING_MAX]; // stream name pre suffix char m_URLSuffix[RTSP_PARAM_STRING_MAX]; // stream name suffix char m_CSeq[RTSP_PARAM_STRING_MAX]; // RTSP command sequence number char m_URLHostPort[MAX_HOSTNAME_LEN]; // host:port part of the URL unsigned m_ContentLength; // SDP string size uint16_t m_RtpClientPort; // RTP receiver port on client (in host byte order!) uint16_t m_RtcpClientPort; // RTCP receiver port on client (in host byte order!) public: bool m_streaming; bool m_stopped; bool m_sessionOpen = true; char * RecvBuf; char * CurRequest; char CmdName[RTSP_PARAM_STRING_MAX]; public: /** * Creates a new RTSP session object * @param aRtspClient socket to which the RTSP client has connected * @param aStreamer AudioStreamer to be used a source for an RTP stream */ RtspSession(WiFiClient& aRtspClient, AudioStreamer* aStreamer); /** * Closes socket and deletes allocated memory */ ~RtspSession(); /** * Read from the socket and parse commands if possible * @param readTimeoutMs time in milliseconds to wait for incoming data * @return false if the read timed out */ bool handleRequests(uint32_t readTimeoutMs); private: /** * Initializes memory */ void Init(); /** * Parses the an RTSP request and calls the response function depending on the type of command * @param aRequest c string containing the request * @param aRequestSize length of the request * @return the command type of the RTSP request */ RTSP_CMD_TYPES Handle_RtspRequest(char const * aRequest, unsigned aRequestSize); /** * Parses an RTSP request, storing the extracted information in the RTSPSession object * @param aRequest c string containing the request * @param aRequestSize length of the request * @return true if parsing was successful */ bool ParseRtspRequest(char const * aRequest, unsigned aRequestSize); /** * Sends Response to OPTIONS command */ void Handle_RtspOPTION(); /** * Sends Response to DESCRIBE command */ void Handle_RtspDESCRIBE(); /** * Sends Response to SETUP command and prepares RTP stream */ void Handle_RtspSETUP(); /** * Sends Response to PLAY command and starts the RTP stream */ void Handle_RtspPLAY(); /** * Sends Response to TEARDOWN command, stops the RTP stream */ void Handle_RtspTEARDOWN(); /** * Gives the current stream ID * @return ID of current stream or -1 if invalid */ int GetStreamID(); /** * Prepares sockets for RTP stream * @param aRtpPort local port number for RTP connection * @param aRtcpPort local port number for RTCP connection */ void InitTransport(u_short aRtpPort, u_short aRtcpPort); SOCKET& getClient() { return m_RtspClient; } uint16_t getRtpClientPort() { return m_RtpClientPort; } /** * Create the DateHeader string for RTSP responses * @return pointer to Date Header string */ char const * DateHeader(); };
Tomp0801/Micro-RTSP-Audio
src/RTSPServer.h
<gh_stars>1-10 /* * Author: <NAME> * github: https://github.com/Tomp0801/Micro-RTSP-Audio * * Based on Micro-RTSP library for video streaming by Kevin Hester: * * https://github.com/geeksville/Micro-RTSP * * Copyright 2018 <NAME>, <EMAIL> (MIT License) */ #pragma once #include "AudioStreamer.h" /** * Creates an RTSP Server to listen for client connections and start sessions */ class RTSPServer { private: TaskHandle_t serverTaskHandle; TaskHandle_t sessionTaskHandle; SOCKET MasterSocket; // our masterSocket(socket that listens for RTSP client connections) SOCKET ClientSocket; // RTSP socket to handle an client sockaddr_in ServerAddr; // server address parameters sockaddr_in ClientAddr; // address parameters of a new RTSP client int port; // port that the RTSP Server listens on int core; // the ESP32 core number the RTSP runs on (0 or 1) int numClients = 0; // number of connected clients AudioStreamer * streamer; // AudioStreamer object that acts as a source for data streams public: /** * Creates a new RTSP server * @param streamer AudioStreamer object that acts as a source for data streams * @param port port that the RTSP Server should listen on (default 8554) * @param core the ESP32 core number the RTSP runs on (0 or 1, default 1) */ RTSPServer(AudioStreamer * streamer, int port = 8554, int core = 1); /** * Starts running the server in a new asynchronous Task * @return 0 on success, or error number */ int runAsync(); TaskHandle_t getTaskHandle() { return serverTaskHandle; }; private: /** * Routine for main server thread, listens for new clients */ static void serverThread(void* server_obj); /** * Routine for a session if it is started */ static void sessionThread(void* server_obj); };
Tomp0801/Micro-RTSP-Audio
src/AudioStreamer.h
<reponame>Tomp0801/Micro-RTSP-Audio /* * Author: <NAME> * github: https://github.com/Tomp0801/Micro-RTSP-Audio * * Based on Micro-RTSP library for video streaming by Kevin Hester: * * https://github.com/geeksville/Micro-RTSP * * Copyright 2018 <NAME>, <EMAIL> (MIT License) */ #pragma once #include "platglue.h" #include "IAudioSource.h" #include <esp_timer.h> /** * Class for streaming data from a source into an RTP stream */ class AudioStreamer { private: const int STREAMING_BUFFER_SIZE = 2048; unsigned char * RtpBuf; IAudioSource * m_audioSource = NULL; int m_samplingRate = 16000; int m_sampleSizeBytes = 2; int m_fragmentSize; int m_fragmentSizeBytes; const int HEADER_SIZE = 12; // size of the RTP header UDPSOCKET m_RtpSocket; // RTP socket for streaming RTP packets to client UDPSOCKET m_RtcpSocket; // RTCP socket for sending/receiving RTCP packages IPPORT m_RtpServerPort; // RTP sender port on server IPPORT m_RtcpServerPort; // RTCP sender port on server u_short m_SequenceNumber; uint32_t m_Timestamp; int m_SendIdx; IPADDRESS m_ClientIP; IPPORT m_ClientPort; uint32_t m_prevMsec; int m_udpRefCount; esp_timer_handle_t RTP_timer; public: /** * Creates a new AudioStreamer object */ AudioStreamer(); /** * Creates a new AudioStreamer object * @param source Object implementing the IAudioSource interface, used as a source for the RTP stream */ AudioStreamer(IAudioSource * source); /** * Deletes allocated memory */ virtual ~AudioStreamer(); /** * Opens sockets for RTP stream * @param aClientIP IP address of the RTP client * @param aClientPort port of the RTP client * @return true on success */ bool InitUdpTransport(IPADDRESS aClientIP, IPPORT aClientPort); /** * Close sockets used for RTP stream */ void ReleaseUdpTransport(void); /** * Sends an RTP packet using the audio source given. Audio source copies data right into the RTP packet * @return number of samples sent in the packet */ int SendRtpPacketDirect(); /** * Start the RTP stream */ void Start(); /** * Stop the RTP stream */ void Stop(); u_short GetRtpServerPort(); u_short GetRtcpServerPort(); int getSampleRate(); private: /** * Task Routine for RTP stream. Carries out the stream * @param audioStreamObj instance of AudioStreamer */ static void doRTPStream(void * audioStreamerObj); };
Tomp0801/Micro-RTSP-Audio
src/IAudioSource.h
/* * Author: <NAME> * github: https://github.com/Tomp0801/Micro-RTSP-Audio * * Based on Micro-RTSP library for video streaming by Kevin Hester: * * https://github.com/geeksville/Micro-RTSP * * Copyright 2018 <NAME>, <EMAIL> (MIT License) */ #pragma once /** * Interface for an audio source for an RTP stream */ class IAudioSource { public: /** * Returns sample rate at which data is provided * @return the sample rate */ virtual int getSampleRate() = 0; /** * Returns size of a single sample in bytes * @return sample size in bytes */ virtual int getSampleSizeBytes() = 0; /** * (Reads and) Copies up to maxSamples samples into the given buffer * @param dest Buffer into which the samples are to be copied * @param maxSamples maximum number of samples to be copied * @return actual number of samples that were copied */ virtual int readDataTo(void * dest, int maxSamples) = 0; /** * Start preparing data in order to provide it for the stream */ virtual void start() {}; /** * Stop preparing data as the stream has ended */ virtual void stop() {}; };
Tomp0801/Micro-RTSP-Audio
test/AudioTestSource.h
<reponame>Tomp0801/Micro-RTSP-Audio<filename>test/AudioTestSource.h #pragma once #include "IAudioSource.h" #include <stdint.h> class AudioTestSource : public IAudioSource { private: int index = 0; const int testDataSamples = 1024; static bool converted; public: static int16_t testData[]; static const int sampleRate = 16000; public: AudioTestSource(); int getSampleRate(); int getSampleSizeBytes() { return sizeof(int16_t); }; int readDataTo(void * dest, int maxSamples); };
sss22213/hifive1-revb-led-blink
blink.c
<reponame>sss22213/hifive1-revb-led-blink #include <metal/machine.h> #include <metal/led.h> #define DELAY for(int delay = 0; delay < 1000000; delay++); int main() { struct metal_led *led0_blue; // initial cpu struct metal_cpu *cpu = metal_cpu_get(0); struct metal_interrupt *cpu_int = metal_cpu_interrupt_controller(cpu); metal_interrupt_init(cpu_int); // set led pin led0_blue = metal_led_get_rgb("LD0", "blue"); // enable led metal_led_enable(led0_blue); // off led metal_led_on(led0_blue); while(1) { DELAY; metal_led_off(led0_blue); DELAY; metal_led_on(led0_blue); } return 0; }
George-Ayad/TM4C123G-GPIO-library
main.c
#include "gpio.h" /// written by : <NAME> /// void delay_ms(int nCount){ /* Wait function */ nCount=nCount*16000; while (nCount--); } int main() { pinmode(RLED, OUTPUT); pinmode(GLED, OUTPUT); pinmode(BLED, OUTPUT); pinmode(PushButton2, PULLUP); pinmode(PushButton1, PULLUP); while (1){ pinwrite(RLED, HIGH); delay_ms(100); pinwrite(RLED, LOW); delay_ms(100); if(pinread(PushButton1) == LOW)pinwrite(BLED, HIGH); else pinwrite(BLED, LOW); if(pinread(PushButton2) == LOW)pinwrite(GLED, HIGH); else pinwrite(GLED, LOW); } return 0; }
George-Ayad/TM4C123G-GPIO-library
gpio.c
#include "gpio.h" /// Written by : <NAME> /// // Define pin as input, output, input with pullup or input with pulldown void pinmode(uint8_t inPortPin, uint8_t dir){ // GET PORT uint8_t port = inPortPin/10; // GET OFFSET uint32_t offset = port>3 ? port+0x1C : port; offset = offset * 0x1000; // GET PIN uint8_t pin = inPortPin%10; // ENABLE CLK FOR PORT SET_BIT(SYSCTL_RCGCGPIO_R, port); // UNLOCK PORT (*((volatile uint32_t *)(0x40004520+offset))) = 0x4C4F434B; //UNLOCK // ENABLE PIN COMMIT SET_BIT( (*((volatile uint32_t *)(0x40004524+offset))) , pin); //COMMIT // ENABLE PIN AS DIGITAL SET_BIT( (*((volatile uint32_t *)(0x4000451C+offset))) , pin); //DIGITAL ENABLE switch(dir){ case 0: // SET DIRECTION TO OUTPUT SET_BIT( (*((volatile uint32_t *)(0x40004400+offset))) , pin); // DIRECTION break; case 1: // SET DIRECTION TO INPUT CLR_BIT( (*((volatile uint32_t *)(0x40004400+offset))) , pin); // DIRECTION break; case 2: // SET DIRECTION TO INPUT AND SET PULLUP CLR_BIT( (*((volatile uint32_t *)(0x40004400+offset))) , pin); // DIRECTION SET_BIT( (*((volatile uint32_t *)(0x40004510+offset))) , pin); // set PULLUP break; case 3: // SET DIRECTION TO INPUT AND SET PULLDOWN CLR_BIT( (*((volatile uint32_t *)(0x40004400+offset))) , pin); // DIRECTION SET_BIT( (*((volatile uint32_t *)(0x40004514+offset))) , pin); // set PULLDOWN break; } } /// Written by : <NAME> /// // Write to pin void pinwrite(uint8_t inPortPin, uint8_t state){ // GET PORT uint8_t port = inPortPin/10; // GET OFFSET uint32_t offset = port>3 ? port+0x1C : port; offset = offset * 0x1000; // GET PIN uint8_t pin = inPortPin%10; // SET PIN TO HIGH OR LOW if(state == HIGH) SET_BIT( (*((volatile uint32_t *)(0x400043FC +offset))) , pin); //DATA else if(state == LOW) CLR_BIT( (*((volatile uint32_t *)(0x400043FC +offset))) , pin); //DATA } /// Written by : <NAME> /// // read from pin uint8_t pinread(uint8_t inPortPin){ // GET PORT uint8_t port = inPortPin/10; // GET OFFSET uint32_t offset = port>3 ? port+0x1C : port; offset = offset * 0x1000; // GET PIN uint8_t pin = inPortPin%10; // GET BIT FROM REGISTER AND RETURN IT return GET_BIT( (*((volatile uint32_t *)(0x400043FC +offset))) , pin); //DATA }
George-Ayad/TM4C123G-GPIO-library
gpio.h
<reponame>George-Ayad/TM4C123G-GPIO-library<gh_stars>0 #include <stdint.h> #include "tm4c123gh6pm.h" /// Written by : <NAME> - <NAME> - <NAME> - <NAME> /// #define RLED 51 #define BLED 52 #define GLED 53 #define PushButton1 50 #define PushButton2 54 #define PA0 00 #define PA1 01 #define PA2 02 #define PA3 03 #define PA4 04 #define PA5 05 #define PA6 06 #define PA7 07 #define PB0 10 #define PB1 11 #define PB2 12 #define PB3 13 #define PB4 14 #define PB5 15 #define PB6 16 #define PB7 17 #define PC0 20 #define PC1 21 #define PC2 22 #define PC3 23 #define PC4 24 #define PC5 25 #define PC6 26 #define PC7 27 #define PD0 30 #define PD1 31 #define PD2 32 #define PD3 33 #define PD4 34 #define PD5 35 #define PD6 36 #define PD7 37 #define PE0 40 #define PE1 41 #define PE2 42 #define PE3 43 #define PE4 44 #define PE5 45 #define PE6 46 #define PE7 47 #define PF0 50 #define PF1 51 #define PF2 52 #define PF3 53 #define PF4 54 #define INPUT 1 #define OUTPUT 0 #define PULLUP 2 #define PULLDOWN 3 #define HIGH 1 #define LOW 0 #define SET_BIT(reg,bitN) ((reg) |= (1<<bitN)) #define CLR_BIT(reg,bitN) ((reg) &= ~(1<<bitN)) #define GET_BIT(reg,bitN) (1 & ((reg)>>bitN)) void pinmode(uint8_t inPortPin, uint8_t dir); void pinwrite(uint8_t inPortPin, uint8_t state); uint8_t pinread(uint8_t inPortPin);
markedwardmurray/Starlight
Starlight/Pods/Target Support Files/Pods-Starlight/Pods-Starlight-umbrella.h
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_StarlightVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_StarlightVersionString[];
markedwardmurray/Starlight
Starlight/Pods/Target Support Files/Hex/Hex-umbrella.h
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double HexVersionNumber; FOUNDATION_EXPORT const unsigned char HexVersionString[];
markedwardmurray/Starlight
Starlight/Pods/Target Support Files/Pods-StarlightTests/Pods-StarlightTests-umbrella.h
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_StarlightTestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_StarlightTestsVersionString[];
markedwardmurray/Starlight
Starlight/Pods/Target Support Files/Down/Down-umbrella.h
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif #import "Down.h" FOUNDATION_EXPORT double DownVersionNumber; FOUNDATION_EXPORT const unsigned char DownVersionString[];
tehtechguy/tsp
TSP_GA/TSP_GA/ga_cpu.h
/* ga_cpu.h Author : <NAME> Date Created : 11/07/14 Description : Header for GA implementation for the CPU License : MIT License http://opensource.org/licenses/mit-license.php Copyright : (c) 2014 <NAME> */ #ifndef __GA_CPU_H__ #define __GA_CPU_H__ // Program includes #include "world.h" #include "log.h" /* Evaluate the fitness function and calculate the fitness probabilities. pop : The population to create pop_size : The number of elements in the population */ void evaluate(World* pop, int pop_size); /* Perform the selection algorithm on the CPU. This selection algorithm uses Roulette Wheel Selection. Two parents will be selected at a time, from the population. pop : The population to select from pop_size : The number of elements in the population parents : The cities for two worlds rand_nums : The random numbers to use */ void selection(World* pop, int pop_size, City** parents, float* rand_nums); /* Perform the crossover algorithm on the CPU. This crossover algorithm uses the Single Point Crossover method. parents : The cities for two worlds child : The child to create num_cities : The number of cities in the world cross_over : The location to perform crossover */ void crossover(City** parents, City* child, int num_cities, int cross_over); /* Perform the mutation algorithm on the CPU. This mutation algorithm uses the order changing permutation method. child : The child to mutate rand_nums : The random numbers to use */ void mutate(City* child, int* rand_nums); /* Runs the genetic algorithm on the CPU. prob_mutation : The probability of a mutation occurring prob_crossover : The probability of a crossover occurring pop_size : The number of elements in the population max_gen : The number of generations to run for world : The seed world, containing all of the desired cities gen_log : A pointer a logger to be used for logging the generation statistics seed : Seed for all random numbers */ void execute(float prob_mutation, float prob_crossover, int pop_size, int max_gen, World* world, logger* gen_log, int seed); #endif
tehtechguy/tsp
TSP_GA/TSP_GA/log.h
<reponame>tehtechguy/tsp /* log.h Author : <NAME> Date Created : 11/07/14 Description : Header for all logging License : MIT License http://opensource.org/licenses/mit-license.php Copyright : (c) 2014 <NAME> */ #ifndef __LOG_H__ #define __LOG_H__ // Native includes #include <fstream> // Program includes #include "world.h" using namespace std; typedef struct logger { /* Handles all logging operations */ // File operators ofstream timing_data; ofstream generation_data; ofstream stats_data; inline void start(char* timing_path, char* generation_path, char* stats_path) { /* Starts logging timing_path : The full path to where the timing data should be saved. generation_path : The full path to where the generation data should be saved. stats_path : The full path to where the overall details should be saved. */ timing_data.open(timing_path, ofstream::out); generation_data.open(generation_path, ofstream::out); stats_data.open(stats_path, ofstream::out); timing_data << "Generation,Time [ms],Fitness,Distance" << endl; stats_data << "Iteration,Type,Total Time [ms],Probability of " \ << "Mutation,Probability of Crossover,Population Size,Total " \ << "Generations,World Seed,GA Seed,Width of World," \ << "Height of World," << "Number of Cities" << endl; } inline void write_log(int generation, float gen_time, World* leader) { /* Writes to the log file generation : The current generation number gen_time : The execution time for the current generation leader : The leader for the current generation */ // Timing data timing_data << generation << "," << gen_time << "," << \ leader->fitness << "," << leader->calc_distance() << endl; // Generation data for (int i=0; i<leader->num_cities-1; i++) generation_data << leader->cities[i].x << "_" << \ leader->cities[i].y << ","; generation_data << leader->cities[leader->num_cities-1].x << "_" << \ leader->cities[leader->num_cities-1].y << endl; } inline void write_stats(int iteration, char* type, float total_time, float prob_mutation, float prob_crossover, int pop_size, int max_gen, int world_seed, int ga_seed, int world_width, int world_height, int num_cities) { /* Writes the details of this simulation to a log file iteration : The current iteration number type : "CPU" or "GPU" for which data was being measured total_time : The total execution time prob_mutation : The probability of a mutation occurring prob_crossover : The probability of a crossover occurring pop_size : The number of elements in the population max_gen : The number of generations to run for world_seed : The seed used to generate the cities ga_seed : The seed used for everything else world_width : The width of the world world_height : The height of the world num_cities : The number of cities in the world */ stats_data << iteration << "," << type << "," << total_time << "," \ << prob_mutation << "," << prob_crossover << "," << pop_size \ << "," << max_gen << "," << world_seed << "," << ga_seed << "," \ << world_width << "," << world_height << "," << num_cities \ << endl; } inline void end() { /* Closes the log files */ timing_data.close(); generation_data.close(); stats_data.close(); } } logger; /* Prints the current status to stdout generation_leader : The leader for the current generation best_leader : The leader out of all generations generation : The generation index */ void print_status(World* generation_leader, World* best_leader, \ int generation); #endif
tehtechguy/tsp
TSP_GA/TSP_GA/world.h
<gh_stars>10-100 /* world.h Author : <NAME> Date Created : 11/07/14 Description : Header file for dealing with the 2D world. License : MIT License http://opensource.org/licenses/mit-license.php Copyright : (c) 2014 <NAME> */ #ifndef __WORLD_H__ #define __WORLD_H__ // Native Includes #include <iostream> #include <cmath> #include <cuda.h> #include <cuda_runtime_api.h> using namespace std; /////////////////////////////////////////////////////////////////////////////// ////////// Shared /////////////////////////////////////////////////////////////////////////////// struct City { /* Stores the location of a city */ int x, y; }; typedef struct World { /* 2D world for the TSP */ int width, height; // World bounds int num_cities; // Number of cities City* cities; // Pointer to array of all of the cities float fitness; // The current fitness float fit_prob; // The fitness probability inline __host__ void calc_fitness() { /* Evaluates the fitness function */ float distance = 0.0; for (int i=0; i<num_cities-1; i++) distance += (cities[i].x - cities[i + 1].x) * (cities[i].x - \ cities[i +1 ].x) + (cities[i].y - cities[i + 1].y) * \ (cities[i].y - cities[i + 1].y); fitness = (width * height) / distance; } inline __host__ float calc_distance() { /* Calculates the distance travelled */ float distance = 0.0; for (int i=0; i<num_cities-1; i++) distance += (float)sqrt((float)((cities[i].x - cities[i + 1].x) * \ (cities[i].x - cities[i + 1].x) + (cities[i].y - \ cities[i +1 ].y) * (cities[i].y - cities[i + 1].y))); return distance; } } World; /* Makes a new world struct world : Pointer to the world to create width : The width of the world height : The height of the world num_cities : The number of cities in the world seed : The random seed to use to select the cities */ void make_world(World* world, int width, int height, int num_cities, int seed); /////////////////////////////////////////////////////////////////////////////// ////////// CPU functions /////////////////////////////////////////////////////////////////////////////// /* Initialize a world struct world : The world to initialize width : The width of the world height : The height of the world num_cities : The number of cities in the world */ void init_world(World* world, int width, int height, int num_cities); /* Clones one more cities in host memory src : Pointer to source cities dst : Pointer to destination cities num_cities : The number of cities to clone */ void clone_city(City* src, City* dst, int num_cities); /* Clones a single world in host memory src : Pointer to source world dst : Pointer to destination world */ void clone_world(World* src, World* dst); /* Frees the world from host memory world : The world to delete */ void free_world(World* world); /* Frees a population (multiple worlds) from host memory pop : Pointer to worlds pop_size : The number of worlds */ void free_population(World* pop, int pop_size); /////////////////////////////////////////////////////////////////////////////// ////////// GPU functions /////////////////////////////////////////////////////////////////////////////// /* Initialize a world struct in device memory d_world : The world to initialize on the device h_world : The host world to use as a template returns true if an error occurred */ bool g_init_world(World* d_world, World* h_world); /* Clone most of the world in device memory d_world : The world to initialize on the device h_world : The host world to use as a template returns true if an error occurred */ bool g_soft_clone_world(World* d_world, World* h_world); #endif
tehtechguy/tsp
TSP_GA/TSP_GA/ga_gpu.h
<filename>TSP_GA/TSP_GA/ga_gpu.h /* ga_gpu.h Author : <NAME> Date Created : 11/07/14 Description : Header for GA implementation for the GPU License : MIT License http://opensource.org/licenses/mit-license.php Copyright : (c) 2014 <NAME> */ #ifndef __GA_GPU_H__ #define __GA_GPU_H__ // Native includes #include <cuda.h> #include <cuda_runtime_api.h> #include <device_launch_parameters.h> // Program includes #include "world.h" #include "log.h" /* Check for a CUDA error error : The error to check returns true for error and false for no error */ bool checkForError(cudaError_t error); /* Check for a kernel error err_msg : The error message to print returns true for error and false for no error */ bool checkForKernelError(const char *err_msg); /* Get the thread id in a 2D grid with 2D blocks */ __device__ int getGlobalIdx_2D_2D(); /* Perform crossover on the device old_pop : The old population (where the parents are located) new_pop : The new population (where the children will be) sel_ix : The indexes of the parents in the old population cross_loc : The crossover locations tid : The thread id */ __device__ void crossover(World* old_pop, World* new_pop, int* sel_ix, \ int* cross_loc, int tid); /* Perform mutation on the device new_pop : The new population (where the children will be) mutate_loc : The crossover locations tid : The thread id */ __device__ void mutate(World* new_pop, int* mutate_loc, int tid); /* Kernel for evaluating the fitness function pop : The population pop_size : The number of elements in the population */ __global__ void fitness_kernel(World* pop, int pop_size); /* Kernel for evaluating the partial probabilities used for selection pop : The population to create pop_size : The number of elements in the population fit_sum : The sum of all fitnesses */ __global__ void fit_sum_kernel(World* pop, int pop_size, float* fit_sum); /* Kernel for evaluating the probabilities used for selection pop : The population pop_size : The number of elements in the population fit_sum : The sum of all fitnesses */ __global__ void fit_prob_kernel(World* pop, int pop_size, float* fit_sum); /* Kernel for finding the max fitness pop : The population pop_size : The number of elements in the population max : The max fitness ix : The index at which the max fitness was found */ __global__ void max_fit_kernel(World* pop, int pop_size, float* max, int* ix); /* Kernel for finding the indexes of the selected parents pop : The population pop_size : The number of elements in the population rand_nums : The random numbers to use sel_ix : The indexes of the parents in the population */ __global__ void selection_kernel(World* pop, int pop_size, float* rand_nums, \ int* sel_ix); /* Kernel for creating the children for the new population old_pop : The old population (where the parents are located) new_pop : The new population (where the children will be) pop_size : The number of elements in the population sel_ix : The indexes of the parents in the old population prob_crossover : The probability of corssover occuring prob_cross : The probabilities of crossover occuring cross_loc : The crossover locations prob_mutation : The probability of mutation occuring prob_mutate : The probabilities of mutation occuring mutate_loc : The mutation locations */ __global__ void child_kernel(World* old_pop, World* new_pop, int pop_size, \ int* sel_ix, float prob_crossover, float* prob_cross, int* cross_loc, \ float prob_mutation, float* prob_mutate, int* mutate_loc); /* Initialize the population in device memory world : The world to use pop : The population to create pop_size : The number of elements in the population seed : Seed for random number generation returns true if an error occurred */ bool g_initialize(World* world, World* pop, int pop_size, int seed); /* Performs evaluation on the GPU pop : The population to evaluate pop_size : The size of the population Block : CUDA block definition Grid : CUDA grid definition returns true if an error occurs */ bool g_evaluate(World *pop, int pop_size, dim3 Block, dim3 Grid); /* Updates the generation and global best leaders pop : The population to select from pop_size : The number of elements in the population generation_leader : The world with the max fitness for this generation best_leader : The world with the best global fitness across all generations Block : CUDA block definition Grid : CUDA grid definition return 1 if this generation is the best, 0 if not, and -1 for error */ int g_select_leader(World* pop, int pop_size, World* generation_leader, World* best_leader, dim3 Block, dim3 Grid); /* Runs the genetic algorithm on the GPU. prob_mutation : The probability of a mutation occurring prob_crossover : The probability of a crossover occurring pop_size : The number of elements in the population max_gen : The number of generations to run for world : The seed world, containing all of the desired cities gen_log : A pointer a logger to be used for logging the generation statistics seed : Seed for all random numbers returns true if an error occurs */ bool g_execute(float prob_mutation, float prob_crossover, int pop_size, int max_gen, World* world, logger* gen_log, int seed); #endif
tehtechguy/tsp
TSP_GA/TSP_GA/common.h
/* common.h Author : <NAME> Date Created : 11/07/14 Description : Header for all shared functions License : MIT License http://opensource.org/licenses/mit-license.php Copyright : (c) 2014 <NAME> */ #ifndef __COMMON_H__ #define __COMMON_H__ // Native Includes #include <ctime> #include <random> #include <functional> // Program Includes #include "world.h" #include "log.h" /* Check for a CUDA error error : The error to check returns true for error and false for no error */ bool checkForError(cudaError_t error); /* Stops a clocks timer and returns the elapsed time in ms. clk - The clk to work with. */ float end_clock(clock_t clk); /* Initialize the population in host memory world : The world to use pop : The population to create pop_size : The number of elements in the population seed : Seed for random number generation returns true if an error occurred */ void initialize(World* world, World* pop, int pop_size, int seed); /* Updates the generation and global best leaders pop : The population to select from pop_size : The number of elements in the population generation_leader : The world with the max fitness for this generation best_leader : The world with the best global fitness across all generations return 1 if this generation is the best, else 0 */ int select_leader(World* pop, int pop_size, World* generation_leader, World* best_leader); #endif
b593771943/XLLReader
XLLReader/XLLReader/ViewController.h
<gh_stars>0 // // ViewController.h // XLLReader // // Created by xiaoll on 2019/5/15. // Copyright © 2019 iOSCoder. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
laroche/arm-trusted-firmware
plat/arm/css/drivers/scpi/css_scpi.c
/* * Copyright (c) 2014-2018, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <assert.h> #include <string.h> #include <arch_helpers.h> #include <common/debug.h> #include <lib/utils.h> #include <plat/common/platform.h> #include <platform_def.h> #include "../mhu/css_mhu.h" #include "css_scpi.h" #define SCPI_SHARED_MEM_SCP_TO_AP PLAT_CSS_SCP_COM_SHARED_MEM_BASE #define SCPI_SHARED_MEM_AP_TO_SCP (PLAT_CSS_SCP_COM_SHARED_MEM_BASE \ + 0x100) /* Header and payload addresses for commands from AP to SCP */ #define SCPI_CMD_HEADER_AP_TO_SCP \ ((scpi_cmd_t *) SCPI_SHARED_MEM_AP_TO_SCP) #define SCPI_CMD_PAYLOAD_AP_TO_SCP \ ((void *) (SCPI_SHARED_MEM_AP_TO_SCP + sizeof(scpi_cmd_t))) /* Header and payload addresses for responses from SCP to AP */ #define SCPI_RES_HEADER_SCP_TO_AP \ ((scpi_cmd_t *) SCPI_SHARED_MEM_SCP_TO_AP) #define SCPI_RES_PAYLOAD_SCP_TO_AP \ ((void *) (SCPI_SHARED_MEM_SCP_TO_AP + sizeof(scpi_cmd_t))) /* ID of the MHU slot used for the SCPI protocol */ #define SCPI_MHU_SLOT_ID 0 static void scpi_secure_message_start(void) { mhu_secure_message_start(SCPI_MHU_SLOT_ID); } static void scpi_secure_message_send(size_t payload_size) { /* * Ensure that any write to the SCPI payload area is seen by SCP before * we write to the MHU register. If these 2 writes were reordered by * the CPU then SCP would read stale payload data */ dmbst(); mhu_secure_message_send(SCPI_MHU_SLOT_ID); } static void scpi_secure_message_receive(scpi_cmd_t *cmd) { uint32_t mhu_status; assert(cmd != NULL); mhu_status = mhu_secure_message_wait(); /* Expect an SCPI message, reject any other protocol */ if (mhu_status != (1 << SCPI_MHU_SLOT_ID)) { ERROR("MHU: Unexpected protocol (MHU status: 0x%x)\n", mhu_status); panic(); } /* * Ensure that any read to the SCPI payload area is done after reading * the MHU register. If these 2 reads were reordered then the CPU would * read invalid payload data */ dmbld(); memcpy(cmd, (void *) SCPI_SHARED_MEM_SCP_TO_AP, sizeof(*cmd)); } static void scpi_secure_message_end(void) { mhu_secure_message_end(SCPI_MHU_SLOT_ID); } int scpi_wait_ready(void) { scpi_cmd_t scpi_cmd; VERBOSE("Waiting for SCP_READY command...\n"); /* Get a message from the SCP */ scpi_secure_message_start(); scpi_secure_message_receive(&scpi_cmd); scpi_secure_message_end(); /* We are expecting 'SCP Ready', produce correct error if it's not */ scpi_status_t status = SCP_OK; if (scpi_cmd.id != SCPI_CMD_SCP_READY) { ERROR("Unexpected SCP command: expected command #%u, got command #%u\n", SCPI_CMD_SCP_READY, scpi_cmd.id); status = SCP_E_SUPPORT; } else if (scpi_cmd.size != 0) { ERROR("SCP_READY command has incorrect size: expected 0, got %u\n", scpi_cmd.size); status = SCP_E_SIZE; } VERBOSE("Sending response for SCP_READY command\n"); /* * Send our response back to SCP. * We are using the same SCPI header, just update the status field. */ scpi_cmd.status = status; scpi_secure_message_start(); memcpy((void *) SCPI_SHARED_MEM_AP_TO_SCP, &scpi_cmd, sizeof(scpi_cmd)); scpi_secure_message_send(0); scpi_secure_message_end(); return status == SCP_OK ? 0 : -1; } void scpi_set_css_power_state(unsigned int mpidr, scpi_power_state_t cpu_state, scpi_power_state_t cluster_state, scpi_power_state_t css_state) { scpi_cmd_t *cmd; uint32_t state = 0; uint32_t *payload_addr; #if ARM_PLAT_MT /* * The current SCPI driver only caters for single-threaded platforms. * Hence we ignore the thread ID (which is always 0) for such platforms. */ state |= (mpidr >> MPIDR_AFF1_SHIFT) & 0x0f; /* CPU ID */ state |= ((mpidr >> MPIDR_AFF2_SHIFT) & 0x0f) << 4; /* Cluster ID */ #else state |= mpidr & 0x0f; /* CPU ID */ state |= (mpidr & 0xf00) >> 4; /* Cluster ID */ #endif /* ARM_PLAT_MT */ state |= cpu_state << 8; state |= cluster_state << 12; state |= css_state << 16; scpi_secure_message_start(); /* Populate the command header */ cmd = SCPI_CMD_HEADER_AP_TO_SCP; cmd->id = SCPI_CMD_SET_CSS_POWER_STATE; cmd->set = SCPI_SET_NORMAL; cmd->sender = 0; cmd->size = sizeof(state); /* Populate the command payload */ payload_addr = SCPI_CMD_PAYLOAD_AP_TO_SCP; *payload_addr = state; scpi_secure_message_send(sizeof(state)); /* * SCP does not reply to this command in order to avoid MHU interrupts * from the sender, which could interfere with its power state request. */ scpi_secure_message_end(); } /* * Query and obtain CSS power state from SCP. * * In response to the query, SCP returns power states of all CPUs in all * clusters of the system. The returned response is then filtered based on the * supplied MPIDR. Power states of requested cluster and CPUs within are updated * via. supplied non-NULL pointer arguments. * * Returns 0 on success, or -1 on errors. */ int scpi_get_css_power_state(unsigned int mpidr, unsigned int *cpu_state_p, unsigned int *cluster_state_p) { scpi_cmd_t *cmd; scpi_cmd_t response; int power_state, cpu, cluster, rc = -1; /* * Extract CPU and cluster membership of the given MPIDR. SCPI caters * for only up to 0xf clusters, and 8 CPUs per cluster */ #if ARM_PLAT_MT /* * The current SCPI driver only caters for single-threaded platforms. * Hence we ignore the thread ID (which is always 0) for such platforms. */ cpu = (mpidr >> MPIDR_AFF1_SHIFT) & MPIDR_AFFLVL_MASK; cluster = (mpidr >> MPIDR_AFF2_SHIFT) & MPIDR_AFFLVL_MASK; #else cpu = mpidr & MPIDR_AFFLVL_MASK; cluster = (mpidr >> MPIDR_AFF1_SHIFT) & MPIDR_AFFLVL_MASK; #endif /* ARM_PLAT_MT */ if (cpu >= 8 || cluster >= 0xf) return -1; scpi_secure_message_start(); /* Populate request headers */ zeromem(SCPI_CMD_HEADER_AP_TO_SCP, sizeof(*cmd)); cmd = SCPI_CMD_HEADER_AP_TO_SCP; cmd->id = SCPI_CMD_GET_CSS_POWER_STATE; /* * Send message and wait for SCP's response */ scpi_secure_message_send(0); scpi_secure_message_receive(&response); if (response.status != SCP_OK) goto exit; /* Validate SCP response */ if (!CHECK_RESPONSE(response, cluster)) goto exit; /* Extract power states for required cluster */ power_state = *(((uint16_t *) SCPI_RES_PAYLOAD_SCP_TO_AP) + cluster); if (CLUSTER_ID(power_state) != cluster) goto exit; /* Update power state via. pointers */ if (cluster_state_p) *cluster_state_p = CLUSTER_POWER_STATE(power_state); if (cpu_state_p) *cpu_state_p = CPU_POWER_STATE(power_state); rc = 0; exit: scpi_secure_message_end(); return rc; } uint32_t scpi_sys_power_state(scpi_system_state_t system_state) { scpi_cmd_t *cmd; uint8_t *payload_addr; scpi_cmd_t response; scpi_secure_message_start(); /* Populate the command header */ cmd = SCPI_CMD_HEADER_AP_TO_SCP; cmd->id = SCPI_CMD_SYS_POWER_STATE; cmd->set = 0; cmd->sender = 0; cmd->size = sizeof(*payload_addr); /* Populate the command payload */ payload_addr = SCPI_CMD_PAYLOAD_AP_TO_SCP; *payload_addr = system_state & 0xff; scpi_secure_message_send(sizeof(*payload_addr)); scpi_secure_message_receive(&response); scpi_secure_message_end(); return response.status; }
laroche/arm-trusted-firmware
plat/arm/css/sgm/sgm_mmap_config.c
/* * Copyright (c) 2018, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <platform_def.h> #include <common/bl_common.h> #include <common/debug.h> #include <plat_arm.h> #include <sgm_variant.h> /* * Table of regions for different BL stages to map using the MMU. * This doesn't include Trusted RAM as the 'mem_layout' argument passed to * arm_configure_mmu_elx() will give the available subset of that. */ #if IMAGE_BL1 const mmap_region_t plat_arm_mmap[] = { ARM_MAP_SHARED_RAM, V2M_MAP_FLASH0_RO, V2M_MAP_IOFPGA, CSS_MAP_DEVICE, CSS_MAP_GIC_DEVICE, SOC_CSS_MAP_DEVICE, #if TRUSTED_BOARD_BOOT ARM_MAP_NS_DRAM1, #endif {0} }; #endif #if IMAGE_BL2 const mmap_region_t plat_arm_mmap[] = { ARM_MAP_SHARED_RAM, V2M_MAP_FLASH0_RO, V2M_MAP_IOFPGA, CSS_MAP_DEVICE, CSS_MAP_GIC_DEVICE, SOC_CSS_MAP_DEVICE, ARM_MAP_NS_DRAM1, #ifdef SPD_tspd ARM_MAP_TSP_SEC_MEM, #endif #ifdef SPD_opteed ARM_OPTEE_PAGEABLE_LOAD_MEM, #endif #if TRUSTED_BOARD_BOOT && !BL2_AT_EL3 ARM_MAP_BL1_RW, #endif {0} }; #endif #if IMAGE_BL2U const mmap_region_t plat_arm_mmap[] = { ARM_MAP_SHARED_RAM, CSS_MAP_DEVICE, CSS_MAP_GIC_DEVICE, SOC_CSS_MAP_DEVICE, {0} }; #endif #if IMAGE_BL31 const mmap_region_t plat_arm_mmap[] = { ARM_MAP_SHARED_RAM, V2M_MAP_IOFPGA, CSS_MAP_DEVICE, CSS_MAP_GIC_DEVICE, SOC_CSS_MAP_DEVICE, {0} }; #endif #if IMAGE_BL32 const mmap_region_t plat_arm_mmap[] = { V2M_MAP_IOFPGA, CSS_MAP_DEVICE, CSS_MAP_GIC_DEVICE, SOC_CSS_MAP_DEVICE, {0} }; #endif ARM_CASSERT_MMAP const mmap_region_t *plat_arm_get_mmap(void) { return plat_arm_mmap; }
laroche/arm-trusted-firmware
plat/arm/css/drivers/scp/css_pm_scmi.c
<reponame>laroche/arm-trusted-firmware<filename>plat/arm/css/drivers/scp/css_pm_scmi.c /* * Copyright (c) 2017-2018, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <assert.h> #include <string.h> #include <arch_helpers.h> #include <common/debug.h> #include <plat/common/platform.h> #include <platform_def.h> #include <css_pm.h> #include <plat_arm.h> #include "../scmi/scmi.h" #include "css_scp.h" /* * This file implements the SCP helper functions using SCMI protocol. */ /* * SCMI power state parameter bit field encoding for ARM CSS platforms. * * 31 20 19 16 15 12 11 8 7 4 3 0 * +-------------------------------------------------------------+ * | SBZ | Max level | Level 3 | Level 2 | Level 1 | Level 0 | * | | | state | state | state | state | * +-------------------------------------------------------------+ * * `Max level` encodes the highest level that has a valid power state * encoded in the power state. */ #define SCMI_PWR_STATE_MAX_PWR_LVL_SHIFT 16 #define SCMI_PWR_STATE_MAX_PWR_LVL_WIDTH 4 #define SCMI_PWR_STATE_MAX_PWR_LVL_MASK \ ((1 << SCMI_PWR_STATE_MAX_PWR_LVL_WIDTH) - 1) #define SCMI_SET_PWR_STATE_MAX_PWR_LVL(_power_state, _max_level) \ (_power_state) |= ((_max_level) & SCMI_PWR_STATE_MAX_PWR_LVL_MASK)\ << SCMI_PWR_STATE_MAX_PWR_LVL_SHIFT #define SCMI_GET_PWR_STATE_MAX_PWR_LVL(_power_state) \ (((_power_state) >> SCMI_PWR_STATE_MAX_PWR_LVL_SHIFT) \ & SCMI_PWR_STATE_MAX_PWR_LVL_MASK) #define SCMI_PWR_STATE_LVL_WIDTH 4 #define SCMI_PWR_STATE_LVL_MASK \ ((1 << SCMI_PWR_STATE_LVL_WIDTH) - 1) #define SCMI_SET_PWR_STATE_LVL(_power_state, _level, _level_state) \ (_power_state) |= ((_level_state) & SCMI_PWR_STATE_LVL_MASK) \ << (SCMI_PWR_STATE_LVL_WIDTH * (_level)) #define SCMI_GET_PWR_STATE_LVL(_power_state, _level) \ (((_power_state) >> (SCMI_PWR_STATE_LVL_WIDTH * (_level))) & \ SCMI_PWR_STATE_LVL_MASK) /* * The SCMI power state enumeration for a power domain level */ typedef enum { scmi_power_state_off = 0, scmi_power_state_on = 1, scmi_power_state_sleep = 2, } scmi_power_state_t; /* * The global handle for invoking the SCMI driver APIs after the driver * has been initialized. */ static void *scmi_handle; /* The SCMI channel global object */ static scmi_channel_t channel; ARM_SCMI_INSTANTIATE_LOCK; /* * Helper function to suspend a CPU power domain and its parent power domains * if applicable. */ void css_scp_suspend(const struct psci_power_state *target_state) { int ret; /* At least power domain level 0 should be specified to be suspended */ assert(target_state->pwr_domain_state[ARM_PWR_LVL0] == ARM_LOCAL_STATE_OFF); /* Check if power down at system power domain level is requested */ if (css_system_pwr_state(target_state) == ARM_LOCAL_STATE_OFF) { /* Issue SCMI command for SYSTEM_SUSPEND */ ret = scmi_sys_pwr_state_set(scmi_handle, SCMI_SYS_PWR_FORCEFUL_REQ, SCMI_SYS_PWR_SUSPEND); if (ret != SCMI_E_SUCCESS) { ERROR("SCMI system power domain suspend return 0x%x unexpected\n", ret); panic(); } return; } #if !HW_ASSISTED_COHERENCY int lvl; uint32_t scmi_pwr_state = 0; /* * If we reach here, then assert that power down at system power domain * level is running. */ assert(css_system_pwr_state(target_state) == ARM_LOCAL_STATE_RUN); /* For level 0, specify `scmi_power_state_sleep` as the power state */ SCMI_SET_PWR_STATE_LVL(scmi_pwr_state, ARM_PWR_LVL0, scmi_power_state_sleep); for (lvl = ARM_PWR_LVL1; lvl <= PLAT_MAX_PWR_LVL; lvl++) { if (target_state->pwr_domain_state[lvl] == ARM_LOCAL_STATE_RUN) break; assert(target_state->pwr_domain_state[lvl] == ARM_LOCAL_STATE_OFF); /* * Specify `scmi_power_state_off` as power state for higher * levels. */ SCMI_SET_PWR_STATE_LVL(scmi_pwr_state, lvl, scmi_power_state_off); } SCMI_SET_PWR_STATE_MAX_PWR_LVL(scmi_pwr_state, lvl - 1); ret = scmi_pwr_state_set(scmi_handle, plat_css_core_pos_to_scmi_dmn_id_map[plat_my_core_pos()], scmi_pwr_state); if (ret != SCMI_E_SUCCESS) { ERROR("SCMI set power state command return 0x%x unexpected\n", ret); panic(); } #endif } /* * Helper function to turn off a CPU power domain and its parent power domains * if applicable. */ void css_scp_off(const struct psci_power_state *target_state) { int lvl = 0, ret; uint32_t scmi_pwr_state = 0; /* At-least the CPU level should be specified to be OFF */ assert(target_state->pwr_domain_state[ARM_PWR_LVL0] == ARM_LOCAL_STATE_OFF); /* PSCI CPU OFF cannot be used to turn OFF system power domain */ assert(css_system_pwr_state(target_state) == ARM_LOCAL_STATE_RUN); for (; lvl <= PLAT_MAX_PWR_LVL; lvl++) { if (target_state->pwr_domain_state[lvl] == ARM_LOCAL_STATE_RUN) break; assert(target_state->pwr_domain_state[lvl] == ARM_LOCAL_STATE_OFF); SCMI_SET_PWR_STATE_LVL(scmi_pwr_state, lvl, scmi_power_state_off); } SCMI_SET_PWR_STATE_MAX_PWR_LVL(scmi_pwr_state, lvl - 1); ret = scmi_pwr_state_set(scmi_handle, plat_css_core_pos_to_scmi_dmn_id_map[plat_my_core_pos()], scmi_pwr_state); if (ret != SCMI_E_QUEUED && ret != SCMI_E_SUCCESS) { ERROR("SCMI set power state command return 0x%x unexpected\n", ret); panic(); } } /* * Helper function to turn ON a CPU power domain and its parent power domains * if applicable. */ void css_scp_on(u_register_t mpidr) { int lvl = 0, ret, core_pos; uint32_t scmi_pwr_state = 0; for (; lvl <= PLAT_MAX_PWR_LVL; lvl++) SCMI_SET_PWR_STATE_LVL(scmi_pwr_state, lvl, scmi_power_state_on); SCMI_SET_PWR_STATE_MAX_PWR_LVL(scmi_pwr_state, lvl - 1); core_pos = plat_core_pos_by_mpidr(mpidr); assert(core_pos >= 0 && core_pos < PLATFORM_CORE_COUNT); ret = scmi_pwr_state_set(scmi_handle, plat_css_core_pos_to_scmi_dmn_id_map[core_pos], scmi_pwr_state); if (ret != SCMI_E_QUEUED && ret != SCMI_E_SUCCESS) { ERROR("SCMI set power state command return 0x%x unexpected\n", ret); panic(); } } /* * Helper function to get the power state of a power domain node as reported * by the SCP. */ int css_scp_get_power_state(u_register_t mpidr, unsigned int power_level) { int ret, cpu_idx; uint32_t scmi_pwr_state = 0, lvl_state; /* We don't support get power state at the system power domain level */ if ((power_level > PLAT_MAX_PWR_LVL) || (power_level == CSS_SYSTEM_PWR_DMN_LVL)) { WARN("Invalid power level %u specified for SCMI get power state\n", power_level); return PSCI_E_INVALID_PARAMS; } cpu_idx = plat_core_pos_by_mpidr(mpidr); assert(cpu_idx > -1); ret = scmi_pwr_state_get(scmi_handle, plat_css_core_pos_to_scmi_dmn_id_map[cpu_idx], &scmi_pwr_state); if (ret != SCMI_E_SUCCESS) { WARN("SCMI get power state command return 0x%x unexpected\n", ret); return PSCI_E_INVALID_PARAMS; } /* * Find the maximum power level described in the get power state * command. If it is less than the requested power level, then assume * the requested power level is ON. */ if (SCMI_GET_PWR_STATE_MAX_PWR_LVL(scmi_pwr_state) < power_level) return HW_ON; lvl_state = SCMI_GET_PWR_STATE_LVL(scmi_pwr_state, power_level); if (lvl_state == scmi_power_state_on) return HW_ON; assert((lvl_state == scmi_power_state_off) || (lvl_state == scmi_power_state_sleep)); return HW_OFF; } void __dead2 css_scp_system_off(int state) { int ret; /* * Disable GIC CPU interface to prevent pending interrupt from waking * up the AP from WFI. */ plat_arm_gic_cpuif_disable(); /* * Issue SCMI command. First issue a graceful * request and if that fails force the request. */ ret = scmi_sys_pwr_state_set(scmi_handle, SCMI_SYS_PWR_FORCEFUL_REQ, state); if (ret != SCMI_E_SUCCESS) { ERROR("SCMI system power state set 0x%x returns unexpected 0x%x\n", state, ret); panic(); } wfi(); ERROR("CSS set power state: operation not handled.\n"); panic(); } /* * Helper function to shutdown the system via SCMI. */ void __dead2 css_scp_sys_shutdown(void) { css_scp_system_off(SCMI_SYS_PWR_SHUTDOWN); } /* * Helper function to reset the system via SCMI. */ void __dead2 css_scp_sys_reboot(void) { css_scp_system_off(SCMI_SYS_PWR_COLD_RESET); } static int scmi_ap_core_init(scmi_channel_t *ch) { #if PROGRAMMABLE_RESET_ADDRESS uint32_t version; int ret; ret = scmi_proto_version(ch, SCMI_AP_CORE_PROTO_ID, &version); if (ret != SCMI_E_SUCCESS) { WARN("SCMI AP core protocol version message failed\n"); return -1; } if (!is_scmi_version_compatible(SCMI_AP_CORE_PROTO_VER, version)) { WARN("SCMI AP core protocol version 0x%x incompatible with driver version 0x%x\n", version, SCMI_AP_CORE_PROTO_VER); return -1; } INFO("SCMI AP core protocol version 0x%x detected\n", version); #endif return 0; } void __init plat_arm_pwrc_setup(void) { channel.info = plat_css_get_scmi_info(); channel.lock = ARM_SCMI_LOCK_GET_INSTANCE; scmi_handle = scmi_init(&channel); if (scmi_handle == NULL) { ERROR("SCMI Initialization failed\n"); panic(); } if (scmi_ap_core_init(&channel) < 0) { ERROR("SCMI AP core protocol initialization failed\n"); panic(); } } /****************************************************************************** * This function overrides the default definition for ARM platforms. Initialize * the SCMI driver, query capability via SCMI and modify the PSCI capability * based on that. *****************************************************************************/ const plat_psci_ops_t *css_scmi_override_pm_ops(plat_psci_ops_t *ops) { uint32_t msg_attr; int ret; assert(scmi_handle); /* Check that power domain POWER_STATE_SET message is supported */ ret = scmi_proto_msg_attr(scmi_handle, SCMI_PWR_DMN_PROTO_ID, SCMI_PWR_STATE_SET_MSG, &msg_attr); if (ret != SCMI_E_SUCCESS) { ERROR("Set power state command is not supported by SCMI\n"); panic(); } /* * Don't support PSCI NODE_HW_STATE call if SCMI doesn't support * POWER_STATE_GET message. */ ret = scmi_proto_msg_attr(scmi_handle, SCMI_PWR_DMN_PROTO_ID, SCMI_PWR_STATE_GET_MSG, &msg_attr); if (ret != SCMI_E_SUCCESS) ops->get_node_hw_state = NULL; /* Check if the SCMI SYSTEM_POWER_STATE_SET message is supported */ ret = scmi_proto_msg_attr(scmi_handle, SCMI_SYS_PWR_PROTO_ID, SCMI_SYS_PWR_STATE_SET_MSG, &msg_attr); if (ret != SCMI_E_SUCCESS) { /* System power management operations are not supported */ ops->system_off = NULL; ops->system_reset = NULL; ops->get_sys_suspend_power_state = NULL; } else { if (!(msg_attr & SCMI_SYS_PWR_SUSPEND_SUPPORTED)) { /* * System power management protocol is available, but * it does not support SYSTEM SUSPEND. */ ops->get_sys_suspend_power_state = NULL; } if (!(msg_attr & SCMI_SYS_PWR_WARM_RESET_SUPPORTED)) { /* * WARM reset is not available. */ ops->system_reset2 = NULL; } } return ops; } int css_system_reset2(int is_vendor, int reset_type, u_register_t cookie) { if (is_vendor || (reset_type != PSCI_RESET2_SYSTEM_WARM_RESET)) return PSCI_E_INVALID_PARAMS; css_scp_system_off(SCMI_SYS_PWR_WARM_RESET); /* * css_scp_system_off cannot return (it is a __dead function), * but css_system_reset2 has to return some value, even in * this case. */ return 0; } #if PROGRAMMABLE_RESET_ADDRESS void plat_arm_program_trusted_mailbox(uintptr_t address) { int ret; assert(scmi_handle); ret = scmi_ap_core_set_reset_addr(scmi_handle, address, SCMI_AP_CORE_LOCK_ATTR); if (ret != SCMI_E_SUCCESS) { ERROR("CSS: Failed to program reset address: %d\n", ret); panic(); } } #endif
laroche/arm-trusted-firmware
plat/arm/board/fvp/fvp_bl2u_setup.c
/* * Copyright (c) 2013-2018, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <plat/common/platform.h> #include <platform_def.h> #include <plat_arm.h> #include "fvp_private.h" void bl2u_early_platform_setup(struct meminfo *mem_layout, void *plat_info) { arm_bl2u_early_platform_setup(mem_layout, plat_info); /* Initialize the platform config for future decision making */ fvp_config_setup(); }
laroche/arm-trusted-firmware
include/arch/aarch64/arch.h
<gh_stars>1-10 /* * Copyright (c) 2013-2019, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef ARCH_H #define ARCH_H #include <lib/utils_def.h> /******************************************************************************* * MIDR bit definitions ******************************************************************************/ #define MIDR_IMPL_MASK U(0xff) #define MIDR_IMPL_SHIFT U(0x18) #define MIDR_VAR_SHIFT U(20) #define MIDR_VAR_BITS U(4) #define MIDR_VAR_MASK U(0xf) #define MIDR_REV_SHIFT U(0) #define MIDR_REV_BITS U(4) #define MIDR_REV_MASK U(0xf) #define MIDR_PN_MASK U(0xfff) #define MIDR_PN_SHIFT U(0x4) /******************************************************************************* * MPIDR macros ******************************************************************************/ #define MPIDR_MT_MASK (ULL(1) << 24) #define MPIDR_CPU_MASK MPIDR_AFFLVL_MASK #define MPIDR_CLUSTER_MASK (MPIDR_AFFLVL_MASK << MPIDR_AFFINITY_BITS) #define MPIDR_AFFINITY_BITS U(8) #define MPIDR_AFFLVL_MASK ULL(0xff) #define MPIDR_AFF0_SHIFT U(0) #define MPIDR_AFF1_SHIFT U(8) #define MPIDR_AFF2_SHIFT U(16) #define MPIDR_AFF3_SHIFT U(32) #define MPIDR_AFF_SHIFT(_n) MPIDR_AFF##_n##_SHIFT #define MPIDR_AFFINITY_MASK ULL(0xff00ffffff) #define MPIDR_AFFLVL_SHIFT U(3) #define MPIDR_AFFLVL0 ULL(0x0) #define MPIDR_AFFLVL1 ULL(0x1) #define MPIDR_AFFLVL2 ULL(0x2) #define MPIDR_AFFLVL3 ULL(0x3) #define MPIDR_AFFLVL(_n) MPIDR_AFFLVL##_n #define MPIDR_AFFLVL0_VAL(mpidr) \ (((mpidr) >> MPIDR_AFF0_SHIFT) & MPIDR_AFFLVL_MASK) #define MPIDR_AFFLVL1_VAL(mpidr) \ (((mpidr) >> MPIDR_AFF1_SHIFT) & MPIDR_AFFLVL_MASK) #define MPIDR_AFFLVL2_VAL(mpidr) \ (((mpidr) >> MPIDR_AFF2_SHIFT) & MPIDR_AFFLVL_MASK) #define MPIDR_AFFLVL3_VAL(mpidr) \ (((mpidr) >> MPIDR_AFF3_SHIFT) & MPIDR_AFFLVL_MASK) /* * The MPIDR_MAX_AFFLVL count starts from 0. Take care to * add one while using this macro to define array sizes. * TODO: Support only the first 3 affinity levels for now. */ #define MPIDR_MAX_AFFLVL U(2) #define MPID_MASK (MPIDR_MT_MASK | \ (MPIDR_AFFLVL_MASK << MPIDR_AFF3_SHIFT) | \ (MPIDR_AFFLVL_MASK << MPIDR_AFF2_SHIFT) | \ (MPIDR_AFFLVL_MASK << MPIDR_AFF1_SHIFT) | \ (MPIDR_AFFLVL_MASK << MPIDR_AFF0_SHIFT)) #define MPIDR_AFF_ID(mpid, n) \ (((mpid) >> MPIDR_AFF_SHIFT(n)) & MPIDR_AFFLVL_MASK) /* * An invalid MPID. This value can be used by functions that return an MPID to * indicate an error. */ #define INVALID_MPID U(0xFFFFFFFF) /******************************************************************************* * Definitions for CPU system register interface to GICv3 ******************************************************************************/ #define ICC_IGRPEN1_EL1 S3_0_C12_C12_7 #define ICC_SGI1R S3_0_C12_C11_5 #define ICC_SRE_EL1 S3_0_C12_C12_5 #define ICC_SRE_EL2 S3_4_C12_C9_5 #define ICC_SRE_EL3 S3_6_C12_C12_5 #define ICC_CTLR_EL1 S3_0_C12_C12_4 #define ICC_CTLR_EL3 S3_6_C12_C12_4 #define ICC_PMR_EL1 S3_0_C4_C6_0 #define ICC_RPR_EL1 S3_0_C12_C11_3 #define ICC_IGRPEN1_EL3 S3_6_c12_c12_7 #define ICC_IGRPEN0_EL1 S3_0_c12_c12_6 #define ICC_HPPIR0_EL1 S3_0_c12_c8_2 #define ICC_HPPIR1_EL1 S3_0_c12_c12_2 #define ICC_IAR0_EL1 S3_0_c12_c8_0 #define ICC_IAR1_EL1 S3_0_c12_c12_0 #define ICC_EOIR0_EL1 S3_0_c12_c8_1 #define ICC_EOIR1_EL1 S3_0_c12_c12_1 #define ICC_SGI0R_EL1 S3_0_c12_c11_7 /******************************************************************************* * Generic timer memory mapped registers & offsets ******************************************************************************/ #define CNTCR_OFF U(0x000) #define CNTFID_OFF U(0x020) #define CNTCR_EN (U(1) << 0) #define CNTCR_HDBG (U(1) << 1) #define CNTCR_FCREQ(x) ((x) << 8) /******************************************************************************* * System register bit definitions ******************************************************************************/ /* CLIDR definitions */ #define LOUIS_SHIFT U(21) #define LOC_SHIFT U(24) #define CLIDR_FIELD_WIDTH U(3) /* CSSELR definitions */ #define LEVEL_SHIFT U(1) /* Data cache set/way op type defines */ #define DCISW U(0x0) #define DCCISW U(0x1) #define DCCSW U(0x2) /* ID_AA64PFR0_EL1 definitions */ #define ID_AA64PFR0_EL0_SHIFT U(0) #define ID_AA64PFR0_EL1_SHIFT U(4) #define ID_AA64PFR0_EL2_SHIFT U(8) #define ID_AA64PFR0_EL3_SHIFT U(12) #define ID_AA64PFR0_AMU_SHIFT U(44) #define ID_AA64PFR0_AMU_LENGTH U(4) #define ID_AA64PFR0_AMU_MASK ULL(0xf) #define ID_AA64PFR0_ELX_MASK ULL(0xf) #define ID_AA64PFR0_SVE_SHIFT U(32) #define ID_AA64PFR0_SVE_MASK ULL(0xf) #define ID_AA64PFR0_SVE_LENGTH U(4) #define ID_AA64PFR0_MPAM_SHIFT U(40) #define ID_AA64PFR0_MPAM_MASK ULL(0xf) #define ID_AA64PFR0_DIT_SHIFT U(48) #define ID_AA64PFR0_DIT_MASK ULL(0xf) #define ID_AA64PFR0_DIT_LENGTH U(4) #define ID_AA64PFR0_DIT_SUPPORTED U(1) #define ID_AA64PFR0_CSV2_SHIFT U(56) #define ID_AA64PFR0_CSV2_MASK ULL(0xf) #define ID_AA64PFR0_CSV2_LENGTH U(4) /* ID_AA64DFR0_EL1.PMS definitions (for ARMv8.2+) */ #define ID_AA64DFR0_PMS_SHIFT U(32) #define ID_AA64DFR0_PMS_LENGTH U(4) #define ID_AA64DFR0_PMS_MASK ULL(0xf) #define EL_IMPL_NONE ULL(0) #define EL_IMPL_A64ONLY ULL(1) #define EL_IMPL_A64_A32 ULL(2) #define ID_AA64PFR0_GIC_SHIFT U(24) #define ID_AA64PFR0_GIC_WIDTH U(4) #define ID_AA64PFR0_GIC_MASK ((ULL(1) << ID_AA64PFR0_GIC_WIDTH) - ULL(1)) /* ID_AA64ISAR1_EL1 definitions */ #define ID_AA64ISAR1_GPI_SHIFT U(28) #define ID_AA64ISAR1_GPI_WIDTH U(4) #define ID_AA64ISAR1_GPA_SHIFT U(24) #define ID_AA64ISAR1_GPA_WIDTH U(4) #define ID_AA64ISAR1_API_SHIFT U(8) #define ID_AA64ISAR1_API_WIDTH U(4) #define ID_AA64ISAR1_APA_SHIFT U(4) #define ID_AA64ISAR1_APA_WIDTH U(4) #define ID_AA64ISAR1_GPI_MASK \ (((ULL(1) << ID_AA64ISAR1_GPI_WIDTH) - ULL(1)) << ID_AA64ISAR1_GPI_SHIFT) #define ID_AA64ISAR1_GPA_MASK \ (((ULL(1) << ID_AA64ISAR1_GPA_WIDTH) - ULL(1)) << ID_AA64ISAR1_GPA_SHIFT) #define ID_AA64ISAR1_API_MASK \ (((ULL(1) << ID_AA64ISAR1_API_WIDTH) - ULL(1)) << ID_AA64ISAR1_API_SHIFT) #define ID_AA64ISAR1_APA_MASK \ (((ULL(1) << ID_AA64ISAR1_APA_WIDTH) - ULL(1)) << ID_AA64ISAR1_APA_SHIFT) /* ID_AA64MMFR0_EL1 definitions */ #define ID_AA64MMFR0_EL1_PARANGE_SHIFT U(0) #define ID_AA64MMFR0_EL1_PARANGE_MASK ULL(0xf) #define PARANGE_0000 U(32) #define PARANGE_0001 U(36) #define PARANGE_0010 U(40) #define PARANGE_0011 U(42) #define PARANGE_0100 U(44) #define PARANGE_0101 U(48) #define PARANGE_0110 U(52) #define ID_AA64MMFR0_EL1_TGRAN4_SHIFT U(28) #define ID_AA64MMFR0_EL1_TGRAN4_MASK ULL(0xf) #define ID_AA64MMFR0_EL1_TGRAN4_SUPPORTED ULL(0x0) #define ID_AA64MMFR0_EL1_TGRAN4_NOT_SUPPORTED ULL(0xf) #define ID_AA64MMFR0_EL1_TGRAN64_SHIFT U(24) #define ID_AA64MMFR0_EL1_TGRAN64_MASK ULL(0xf) #define ID_AA64MMFR0_EL1_TGRAN64_SUPPORTED ULL(0x0) #define ID_AA64MMFR0_EL1_TGRAN64_NOT_SUPPORTED ULL(0xf) #define ID_AA64MMFR0_EL1_TGRAN16_SHIFT U(20) #define ID_AA64MMFR0_EL1_TGRAN16_MASK ULL(0xf) #define ID_AA64MMFR0_EL1_TGRAN16_SUPPORTED ULL(0x1) #define ID_AA64MMFR0_EL1_TGRAN16_NOT_SUPPORTED ULL(0x0) /* ID_AA64MMFR2_EL1 definitions */ #define ID_AA64MMFR2_EL1 S3_0_C0_C7_2 #define ID_AA64MMFR2_EL1_CNP_SHIFT U(0) #define ID_AA64MMFR2_EL1_CNP_MASK ULL(0xf) /* ID_AA64PFR1_EL1 definitions */ #define ID_AA64PFR1_EL1_SSBS_SHIFT U(4) #define ID_AA64PFR1_EL1_SSBS_MASK ULL(0xf) #define SSBS_UNAVAILABLE ULL(0) /* No architectural SSBS support */ /* ID_PFR1_EL1 definitions */ #define ID_PFR1_VIRTEXT_SHIFT U(12) #define ID_PFR1_VIRTEXT_MASK U(0xf) #define GET_VIRT_EXT(id) (((id) >> ID_PFR1_VIRTEXT_SHIFT) \ & ID_PFR1_VIRTEXT_MASK) /* SCTLR definitions */ #define SCTLR_EL2_RES1 ((U(1) << 29) | (U(1) << 28) | (U(1) << 23) | \ (U(1) << 22) | (U(1) << 18) | (U(1) << 16) | \ (U(1) << 11) | (U(1) << 5) | (U(1) << 4)) #define SCTLR_EL1_RES1 ((U(1) << 29) | (U(1) << 28) | (U(1) << 23) | \ (U(1) << 22) | (U(1) << 20) | (U(1) << 11)) #define SCTLR_AARCH32_EL1_RES1 \ ((U(1) << 23) | (U(1) << 22) | (U(1) << 11) | \ (U(1) << 4) | (U(1) << 3)) #define SCTLR_EL3_RES1 ((U(1) << 29) | (U(1) << 28) | (U(1) << 23) | \ (U(1) << 22) | (U(1) << 18) | (U(1) << 16) | \ (U(1) << 11) | (U(1) << 5) | (U(1) << 4)) #define SCTLR_M_BIT (ULL(1) << 0) #define SCTLR_A_BIT (ULL(1) << 1) #define SCTLR_C_BIT (ULL(1) << 2) #define SCTLR_SA_BIT (ULL(1) << 3) #define SCTLR_SA0_BIT (ULL(1) << 4) #define SCTLR_CP15BEN_BIT (ULL(1) << 5) #define SCTLR_ITD_BIT (ULL(1) << 7) #define SCTLR_SED_BIT (ULL(1) << 8) #define SCTLR_UMA_BIT (ULL(1) << 9) #define SCTLR_I_BIT (ULL(1) << 12) #define SCTLR_V_BIT (ULL(1) << 13) #define SCTLR_DZE_BIT (ULL(1) << 14) #define SCTLR_UCT_BIT (ULL(1) << 15) #define SCTLR_NTWI_BIT (ULL(1) << 16) #define SCTLR_NTWE_BIT (ULL(1) << 18) #define SCTLR_WXN_BIT (ULL(1) << 19) #define SCTLR_UWXN_BIT (ULL(1) << 20) #define SCTLR_E0E_BIT (ULL(1) << 24) #define SCTLR_EE_BIT (ULL(1) << 25) #define SCTLR_UCI_BIT (ULL(1) << 26) #define SCTLR_TRE_BIT (ULL(1) << 28) #define SCTLR_AFE_BIT (ULL(1) << 29) #define SCTLR_TE_BIT (ULL(1) << 30) #define SCTLR_DSSBS_BIT (ULL(1) << 44) #define SCTLR_RESET_VAL SCTLR_EL3_RES1 /* CPACR_El1 definitions */ #define CPACR_EL1_FPEN(x) ((x) << 20) #define CPACR_EL1_FP_TRAP_EL0 U(0x1) #define CPACR_EL1_FP_TRAP_ALL U(0x2) #define CPACR_EL1_FP_TRAP_NONE U(0x3) /* SCR definitions */ #define SCR_RES1_BITS ((U(1) << 4) | (U(1) << 5)) #define SCR_FIEN_BIT (U(1) << 21) #define SCR_API_BIT (U(1) << 17) #define SCR_APK_BIT (U(1) << 16) #define SCR_TWE_BIT (U(1) << 13) #define SCR_TWI_BIT (U(1) << 12) #define SCR_ST_BIT (U(1) << 11) #define SCR_RW_BIT (U(1) << 10) #define SCR_SIF_BIT (U(1) << 9) #define SCR_HCE_BIT (U(1) << 8) #define SCR_SMD_BIT (U(1) << 7) #define SCR_EA_BIT (U(1) << 3) #define SCR_FIQ_BIT (U(1) << 2) #define SCR_IRQ_BIT (U(1) << 1) #define SCR_NS_BIT (U(1) << 0) #define SCR_VALID_BIT_MASK U(0x2f8f) #define SCR_RESET_VAL SCR_RES1_BITS /* MDCR_EL3 definitions */ #define MDCR_SPD32(x) ((x) << 14) #define MDCR_SPD32_LEGACY U(0x0) #define MDCR_SPD32_DISABLE U(0x2) #define MDCR_SPD32_ENABLE U(0x3) #define MDCR_SDD_BIT (U(1) << 16) #define MDCR_NSPB(x) ((x) << 12) #define MDCR_NSPB_EL1 U(0x3) #define MDCR_TDOSA_BIT (U(1) << 10) #define MDCR_TDA_BIT (U(1) << 9) #define MDCR_TPM_BIT (U(1) << 6) #define MDCR_EL3_RESET_VAL U(0x0) /* MDCR_EL2 definitions */ #define MDCR_EL2_TPMS (U(1) << 14) #define MDCR_EL2_E2PB(x) ((x) << 12) #define MDCR_EL2_E2PB_EL1 U(0x3) #define MDCR_EL2_TDRA_BIT (U(1) << 11) #define MDCR_EL2_TDOSA_BIT (U(1) << 10) #define MDCR_EL2_TDA_BIT (U(1) << 9) #define MDCR_EL2_TDE_BIT (U(1) << 8) #define MDCR_EL2_HPME_BIT (U(1) << 7) #define MDCR_EL2_TPM_BIT (U(1) << 6) #define MDCR_EL2_TPMCR_BIT (U(1) << 5) #define MDCR_EL2_RESET_VAL U(0x0) /* HSTR_EL2 definitions */ #define HSTR_EL2_RESET_VAL U(0x0) #define HSTR_EL2_T_MASK U(0xff) /* CNTHP_CTL_EL2 definitions */ #define CNTHP_CTL_ENABLE_BIT (U(1) << 0) #define CNTHP_CTL_RESET_VAL U(0x0) /* VTTBR_EL2 definitions */ #define VTTBR_RESET_VAL ULL(0x0) #define VTTBR_VMID_MASK ULL(0xff) #define VTTBR_VMID_SHIFT U(48) #define VTTBR_BADDR_MASK ULL(0xffffffffffff) #define VTTBR_BADDR_SHIFT U(0) /* HCR definitions */ #define HCR_API_BIT (ULL(1) << 41) #define HCR_APK_BIT (ULL(1) << 40) #define HCR_TGE_BIT (ULL(1) << 27) #define HCR_RW_SHIFT U(31) #define HCR_RW_BIT (ULL(1) << HCR_RW_SHIFT) #define HCR_AMO_BIT (ULL(1) << 5) #define HCR_IMO_BIT (ULL(1) << 4) #define HCR_FMO_BIT (ULL(1) << 3) /* ISR definitions */ #define ISR_A_SHIFT U(8) #define ISR_I_SHIFT U(7) #define ISR_F_SHIFT U(6) /* CNTHCTL_EL2 definitions */ #define CNTHCTL_RESET_VAL U(0x0) #define EVNTEN_BIT (U(1) << 2) #define EL1PCEN_BIT (U(1) << 1) #define EL1PCTEN_BIT (U(1) << 0) /* CNTKCTL_EL1 definitions */ #define EL0PTEN_BIT (U(1) << 9) #define EL0VTEN_BIT (U(1) << 8) #define EL0PCTEN_BIT (U(1) << 0) #define EL0VCTEN_BIT (U(1) << 1) #define EVNTEN_BIT (U(1) << 2) #define EVNTDIR_BIT (U(1) << 3) #define EVNTI_SHIFT U(4) #define EVNTI_MASK U(0xf) /* CPTR_EL3 definitions */ #define TCPAC_BIT (U(1) << 31) #define TAM_BIT (U(1) << 30) #define TTA_BIT (U(1) << 20) #define TFP_BIT (U(1) << 10) #define CPTR_EZ_BIT (U(1) << 8) #define CPTR_EL3_RESET_VAL U(0x0) /* CPTR_EL2 definitions */ #define CPTR_EL2_RES1 ((U(1) << 13) | (U(1) << 12) | (U(0x3ff))) #define CPTR_EL2_TCPAC_BIT (U(1) << 31) #define CPTR_EL2_TAM_BIT (U(1) << 30) #define CPTR_EL2_TTA_BIT (U(1) << 20) #define CPTR_EL2_TFP_BIT (U(1) << 10) #define CPTR_EL2_TZ_BIT (U(1) << 8) #define CPTR_EL2_RESET_VAL CPTR_EL2_RES1 /* CPSR/SPSR definitions */ #define DAIF_FIQ_BIT (U(1) << 0) #define DAIF_IRQ_BIT (U(1) << 1) #define DAIF_ABT_BIT (U(1) << 2) #define DAIF_DBG_BIT (U(1) << 3) #define SPSR_DAIF_SHIFT U(6) #define SPSR_DAIF_MASK U(0xf) #define SPSR_AIF_SHIFT U(6) #define SPSR_AIF_MASK U(0x7) #define SPSR_E_SHIFT U(9) #define SPSR_E_MASK U(0x1) #define SPSR_E_LITTLE U(0x0) #define SPSR_E_BIG U(0x1) #define SPSR_T_SHIFT U(5) #define SPSR_T_MASK U(0x1) #define SPSR_T_ARM U(0x0) #define SPSR_T_THUMB U(0x1) #define SPSR_M_SHIFT U(4) #define SPSR_M_MASK U(0x1) #define SPSR_M_AARCH64 U(0x0) #define SPSR_M_AARCH32 U(0x1) #define DISABLE_ALL_EXCEPTIONS \ (DAIF_FIQ_BIT | DAIF_IRQ_BIT | DAIF_ABT_BIT | DAIF_DBG_BIT) #define DISABLE_INTERRUPTS (DAIF_FIQ_BIT | DAIF_IRQ_BIT) /* * RMR_EL3 definitions */ #define RMR_EL3_RR_BIT (U(1) << 1) #define RMR_EL3_AA64_BIT (U(1) << 0) /* * HI-VECTOR address for AArch32 state */ #define HI_VECTOR_BASE U(0xFFFF0000) /* * TCR defintions */ #define TCR_EL3_RES1 ((ULL(1) << 31) | (ULL(1) << 23)) #define TCR_EL2_RES1 ((ULL(1) << 31) | (ULL(1) << 23)) #define TCR_EL1_IPS_SHIFT U(32) #define TCR_EL2_PS_SHIFT U(16) #define TCR_EL3_PS_SHIFT U(16) #define TCR_TxSZ_MIN ULL(16) #define TCR_TxSZ_MAX ULL(39) /* (internal) physical address size bits in EL3/EL1 */ #define TCR_PS_BITS_4GB ULL(0x0) #define TCR_PS_BITS_64GB ULL(0x1) #define TCR_PS_BITS_1TB ULL(0x2) #define TCR_PS_BITS_4TB ULL(0x3) #define TCR_PS_BITS_16TB ULL(0x4) #define TCR_PS_BITS_256TB ULL(0x5) #define ADDR_MASK_48_TO_63 ULL(0xFFFF000000000000) #define ADDR_MASK_44_TO_47 ULL(0x0000F00000000000) #define ADDR_MASK_42_TO_43 ULL(0x00000C0000000000) #define ADDR_MASK_40_TO_41 ULL(0x0000030000000000) #define ADDR_MASK_36_TO_39 ULL(0x000000F000000000) #define ADDR_MASK_32_TO_35 ULL(0x0000000F00000000) #define TCR_RGN_INNER_NC (ULL(0x0) << 8) #define TCR_RGN_INNER_WBA (ULL(0x1) << 8) #define TCR_RGN_INNER_WT (ULL(0x2) << 8) #define TCR_RGN_INNER_WBNA (ULL(0x3) << 8) #define TCR_RGN_OUTER_NC (ULL(0x0) << 10) #define TCR_RGN_OUTER_WBA (ULL(0x1) << 10) #define TCR_RGN_OUTER_WT (ULL(0x2) << 10) #define TCR_RGN_OUTER_WBNA (ULL(0x3) << 10) #define TCR_SH_NON_SHAREABLE (ULL(0x0) << 12) #define TCR_SH_OUTER_SHAREABLE (ULL(0x2) << 12) #define TCR_SH_INNER_SHAREABLE (ULL(0x3) << 12) #define TCR_TG0_SHIFT U(14) #define TCR_TG0_MASK ULL(3) #define TCR_TG0_4K (ULL(0) << TCR_TG0_SHIFT) #define TCR_TG0_64K (ULL(1) << TCR_TG0_SHIFT) #define TCR_TG0_16K (ULL(2) << TCR_TG0_SHIFT) #define TCR_EPD0_BIT (ULL(1) << 7) #define TCR_EPD1_BIT (ULL(1) << 23) #define MODE_SP_SHIFT U(0x0) #define MODE_SP_MASK U(0x1) #define MODE_SP_EL0 U(0x0) #define MODE_SP_ELX U(0x1) #define MODE_RW_SHIFT U(0x4) #define MODE_RW_MASK U(0x1) #define MODE_RW_64 U(0x0) #define MODE_RW_32 U(0x1) #define MODE_EL_SHIFT U(0x2) #define MODE_EL_MASK U(0x3) #define MODE_EL3 U(0x3) #define MODE_EL2 U(0x2) #define MODE_EL1 U(0x1) #define MODE_EL0 U(0x0) #define MODE32_SHIFT U(0) #define MODE32_MASK U(0xf) #define MODE32_usr U(0x0) #define MODE32_fiq U(0x1) #define MODE32_irq U(0x2) #define MODE32_svc U(0x3) #define MODE32_mon U(0x6) #define MODE32_abt U(0x7) #define MODE32_hyp U(0xa) #define MODE32_und U(0xb) #define MODE32_sys U(0xf) #define GET_RW(mode) (((mode) >> MODE_RW_SHIFT) & MODE_RW_MASK) #define GET_EL(mode) (((mode) >> MODE_EL_SHIFT) & MODE_EL_MASK) #define GET_SP(mode) (((mode) >> MODE_SP_SHIFT) & MODE_SP_MASK) #define GET_M32(mode) (((mode) >> MODE32_SHIFT) & MODE32_MASK) #define SPSR_64(el, sp, daif) \ ((MODE_RW_64 << MODE_RW_SHIFT) | \ (((el) & MODE_EL_MASK) << MODE_EL_SHIFT) | \ (((sp) & MODE_SP_MASK) << MODE_SP_SHIFT) | \ (((daif) & SPSR_DAIF_MASK) << SPSR_DAIF_SHIFT)) #define SPSR_MODE32(mode, isa, endian, aif) \ ((MODE_RW_32 << MODE_RW_SHIFT) | \ (((mode) & MODE32_MASK) << MODE32_SHIFT) | \ (((isa) & SPSR_T_MASK) << SPSR_T_SHIFT) | \ (((endian) & SPSR_E_MASK) << SPSR_E_SHIFT) | \ (((aif) & SPSR_AIF_MASK) << SPSR_AIF_SHIFT)) /* * TTBR Definitions */ #define TTBR_CNP_BIT ULL(0x1) /* * CTR_EL0 definitions */ #define CTR_CWG_SHIFT U(24) #define CTR_CWG_MASK U(0xf) #define CTR_ERG_SHIFT U(20) #define CTR_ERG_MASK U(0xf) #define CTR_DMINLINE_SHIFT U(16) #define CTR_DMINLINE_MASK U(0xf) #define CTR_L1IP_SHIFT U(14) #define CTR_L1IP_MASK U(0x3) #define CTR_IMINLINE_SHIFT U(0) #define CTR_IMINLINE_MASK U(0xf) #define MAX_CACHE_LINE_SIZE U(0x800) /* 2KB */ /* Physical timer control register bit fields shifts and masks */ #define CNTP_CTL_ENABLE_SHIFT U(0) #define CNTP_CTL_IMASK_SHIFT U(1) #define CNTP_CTL_ISTATUS_SHIFT U(2) #define CNTP_CTL_ENABLE_MASK U(1) #define CNTP_CTL_IMASK_MASK U(1) #define CNTP_CTL_ISTATUS_MASK U(1) /* Exception Syndrome register bits and bobs */ #define ESR_EC_SHIFT U(26) #define ESR_EC_MASK U(0x3f) #define ESR_EC_LENGTH U(6) #define EC_UNKNOWN U(0x0) #define EC_WFE_WFI U(0x1) #define EC_AARCH32_CP15_MRC_MCR U(0x3) #define EC_AARCH32_CP15_MRRC_MCRR U(0x4) #define EC_AARCH32_CP14_MRC_MCR U(0x5) #define EC_AARCH32_CP14_LDC_STC U(0x6) #define EC_FP_SIMD U(0x7) #define EC_AARCH32_CP10_MRC U(0x8) #define EC_AARCH32_CP14_MRRC_MCRR U(0xc) #define EC_ILLEGAL U(0xe) #define EC_AARCH32_SVC U(0x11) #define EC_AARCH32_HVC U(0x12) #define EC_AARCH32_SMC U(0x13) #define EC_AARCH64_SVC U(0x15) #define EC_AARCH64_HVC U(0x16) #define EC_AARCH64_SMC U(0x17) #define EC_AARCH64_SYS U(0x18) #define EC_IABORT_LOWER_EL U(0x20) #define EC_IABORT_CUR_EL U(0x21) #define EC_PC_ALIGN U(0x22) #define EC_DABORT_LOWER_EL U(0x24) #define EC_DABORT_CUR_EL U(0x25) #define EC_SP_ALIGN U(0x26) #define EC_AARCH32_FP U(0x28) #define EC_AARCH64_FP U(0x2c) #define EC_SERROR U(0x2f) /* * External Abort bit in Instruction and Data Aborts synchronous exception * syndromes. */ #define ESR_ISS_EABORT_EA_BIT U(9) #define EC_BITS(x) (((x) >> ESR_EC_SHIFT) & ESR_EC_MASK) /* Reset bit inside the Reset management register for EL3 (RMR_EL3) */ #define RMR_RESET_REQUEST_SHIFT U(0x1) #define RMR_WARM_RESET_CPU (U(1) << RMR_RESET_REQUEST_SHIFT) /******************************************************************************* * Definitions of register offsets, fields and macros for CPU system * instructions. ******************************************************************************/ #define TLBI_ADDR_SHIFT U(12) #define TLBI_ADDR_MASK ULL(0x00000FFFFFFFFFFF) #define TLBI_ADDR(x) (((x) >> TLBI_ADDR_SHIFT) & TLBI_ADDR_MASK) /******************************************************************************* * Definitions of register offsets and fields in the CNTCTLBase Frame of the * system level implementation of the Generic Timer. ******************************************************************************/ #define CNTCTLBASE_CNTFRQ U(0x0) #define CNTNSAR U(0x4) #define CNTNSAR_NS_SHIFT(x) (x) #define CNTACR_BASE(x) (U(0x40) + ((x) << 2)) #define CNTACR_RPCT_SHIFT U(0x0) #define CNTACR_RVCT_SHIFT U(0x1) #define CNTACR_RFRQ_SHIFT U(0x2) #define CNTACR_RVOFF_SHIFT U(0x3) #define CNTACR_RWVT_SHIFT U(0x4) #define CNTACR_RWPT_SHIFT U(0x5) /******************************************************************************* * Definitions of register offsets and fields in the CNTBaseN Frame of the * system level implementation of the Generic Timer. ******************************************************************************/ /* Physical Count register. */ #define CNTPCT_LO U(0x0) /* Counter Frequency register. */ #define CNTBASEN_CNTFRQ U(0x10) /* Physical Timer CompareValue register. */ #define CNTP_CVAL_LO U(0x20) /* Physical Timer Control register. */ #define CNTP_CTL U(0x2c) /* PMCR_EL0 definitions */ #define PMCR_EL0_RESET_VAL U(0x0) #define PMCR_EL0_N_SHIFT U(11) #define PMCR_EL0_N_MASK U(0x1f) #define PMCR_EL0_N_BITS (PMCR_EL0_N_MASK << PMCR_EL0_N_SHIFT) #define PMCR_EL0_LC_BIT (U(1) << 6) #define PMCR_EL0_DP_BIT (U(1) << 5) #define PMCR_EL0_X_BIT (U(1) << 4) #define PMCR_EL0_D_BIT (U(1) << 3) /******************************************************************************* * Definitions for system register interface to SVE ******************************************************************************/ #define ZCR_EL3 S3_6_C1_C2_0 #define ZCR_EL2 S3_4_C1_C2_0 /* ZCR_EL3 definitions */ #define ZCR_EL3_LEN_MASK U(0xf) /* ZCR_EL2 definitions */ #define ZCR_EL2_LEN_MASK U(0xf) /******************************************************************************* * Definitions of MAIR encodings for device and normal memory ******************************************************************************/ /* * MAIR encodings for device memory attributes. */ #define MAIR_DEV_nGnRnE ULL(0x0) #define MAIR_DEV_nGnRE ULL(0x4) #define MAIR_DEV_nGRE ULL(0x8) #define MAIR_DEV_GRE ULL(0xc) /* * MAIR encodings for normal memory attributes. * * Cache Policy * WT: Write Through * WB: Write Back * NC: Non-Cacheable * * Transient Hint * NTR: Non-Transient * TR: Transient * * Allocation Policy * RA: Read Allocate * WA: Write Allocate * RWA: Read and Write Allocate * NA: No Allocation */ #define MAIR_NORM_WT_TR_WA ULL(0x1) #define MAIR_NORM_WT_TR_RA ULL(0x2) #define MAIR_NORM_WT_TR_RWA ULL(0x3) #define MAIR_NORM_NC ULL(0x4) #define MAIR_NORM_WB_TR_WA ULL(0x5) #define MAIR_NORM_WB_TR_RA ULL(0x6) #define MAIR_NORM_WB_TR_RWA ULL(0x7) #define MAIR_NORM_WT_NTR_NA ULL(0x8) #define MAIR_NORM_WT_NTR_WA ULL(0x9) #define MAIR_NORM_WT_NTR_RA ULL(0xa) #define MAIR_NORM_WT_NTR_RWA ULL(0xb) #define MAIR_NORM_WB_NTR_NA ULL(0xc) #define MAIR_NORM_WB_NTR_WA ULL(0xd) #define MAIR_NORM_WB_NTR_RA ULL(0xe) #define MAIR_NORM_WB_NTR_RWA ULL(0xf) #define MAIR_NORM_OUTER_SHIFT U(4) #define MAKE_MAIR_NORMAL_MEMORY(inner, outer) \ ((inner) | ((outer) << MAIR_NORM_OUTER_SHIFT)) /* PAR_EL1 fields */ #define PAR_F_SHIFT U(0) #define PAR_F_MASK ULL(0x1) #define PAR_ADDR_SHIFT U(12) #define PAR_ADDR_MASK (BIT(40) - ULL(1)) /* 40-bits-wide page address */ /******************************************************************************* * Definitions for system register interface to SPE ******************************************************************************/ #define PMBLIMITR_EL1 S3_0_C9_C10_0 /******************************************************************************* * Definitions for system register interface to MPAM ******************************************************************************/ #define MPAMIDR_EL1 S3_0_C10_C4_4 #define MPAM2_EL2 S3_4_C10_C5_0 #define MPAMHCR_EL2 S3_4_C10_C4_0 #define MPAM3_EL3 S3_6_C10_C5_0 /******************************************************************************* * Definitions for system register interface to AMU for ARMv8.4 onwards ******************************************************************************/ #define AMCR_EL0 S3_3_C13_C2_0 #define AMCFGR_EL0 S3_3_C13_C2_1 #define AMCGCR_EL0 S3_3_C13_C2_2 #define AMUSERENR_EL0 S3_3_C13_C2_3 #define AMCNTENCLR0_EL0 S3_3_C13_C2_4 #define AMCNTENSET0_EL0 S3_3_C13_C2_5 #define AMCNTENCLR1_EL0 S3_3_C13_C3_0 #define AMCNTENSET1_EL0 S3_3_C13_C3_1 /* Activity Monitor Group 0 Event Counter Registers */ #define AMEVCNTR00_EL0 S3_3_C13_C4_0 #define AMEVCNTR01_EL0 S3_3_C13_C4_1 #define AMEVCNTR02_EL0 S3_3_C13_C4_2 #define AMEVCNTR03_EL0 S3_3_C13_C4_3 /* Activity Monitor Group 0 Event Type Registers */ #define AMEVTYPER00_EL0 S3_3_C13_C6_0 #define AMEVTYPER01_EL0 S3_3_C13_C6_1 #define AMEVTYPER02_EL0 S3_3_C13_C6_2 #define AMEVTYPER03_EL0 S3_3_C13_C6_3 /* Activity Monitor Group 1 Event Counter Registers */ #define AMEVCNTR10_EL0 S3_3_C13_C12_0 #define AMEVCNTR11_EL0 S3_3_C13_C12_1 #define AMEVCNTR12_EL0 S3_3_C13_C12_2 #define AMEVCNTR13_EL0 S3_3_C13_C12_3 #define AMEVCNTR14_EL0 S3_3_C13_C12_4 #define AMEVCNTR15_EL0 S3_3_C13_C12_5 #define AMEVCNTR16_EL0 S3_3_C13_C12_6 #define AMEVCNTR17_EL0 S3_3_C13_C12_7 #define AMEVCNTR18_EL0 S3_3_C13_C13_0 #define AMEVCNTR19_EL0 S3_3_C13_C13_1 #define AMEVCNTR1A_EL0 S3_3_C13_C13_2 #define AMEVCNTR1B_EL0 S3_3_C13_C13_3 #define AMEVCNTR1C_EL0 S3_3_C13_C13_4 #define AMEVCNTR1D_EL0 S3_3_C13_C13_5 #define AMEVCNTR1E_EL0 S3_3_C13_C13_6 #define AMEVCNTR1F_EL0 S3_3_C13_C13_7 /* Activity Monitor Group 1 Event Type Registers */ #define AMEVTYPER10_EL0 S3_3_C13_C14_0 #define AMEVTYPER11_EL0 S3_3_C13_C14_1 #define AMEVTYPER12_EL0 S3_3_C13_C14_2 #define AMEVTYPER13_EL0 S3_3_C13_C14_3 #define AMEVTYPER14_EL0 S3_3_C13_C14_4 #define AMEVTYPER15_EL0 S3_3_C13_C14_5 #define AMEVTYPER16_EL0 S3_3_C13_C14_6 #define AMEVTYPER17_EL0 S3_3_C13_C14_7 #define AMEVTYPER18_EL0 S3_3_C13_C15_0 #define AMEVTYPER19_EL0 S3_3_C13_C15_1 #define AMEVTYPER1A_EL0 S3_3_C13_C15_2 #define AMEVTYPER1B_EL0 S3_3_C13_C15_3 #define AMEVTYPER1C_EL0 S3_3_C13_C15_4 #define AMEVTYPER1D_EL0 S3_3_C13_C15_5 #define AMEVTYPER1E_EL0 S3_3_C13_C15_6 #define AMEVTYPER1F_EL0 S3_3_C13_C15_7 /* AMCGCR_EL0 definitions */ #define AMCGCR_EL0_CG1NC_SHIFT U(8) #define AMCGCR_EL0_CG1NC_LENGTH U(8) #define AMCGCR_EL0_CG1NC_MASK U(0xff) /* MPAM register definitions */ #define MPAM3_EL3_MPAMEN_BIT (ULL(1) << 63) #define MPAMIDR_HAS_HCR_BIT (ULL(1) << 17) /******************************************************************************* * RAS system registers ******************************************************************************/ #define DISR_EL1 S3_0_C12_C1_1 #define DISR_A_BIT U(31) #define ERRIDR_EL1 S3_0_C5_C3_0 #define ERRIDR_MASK U(0xffff) #define ERRSELR_EL1 S3_0_C5_C3_1 /* System register access to Standard Error Record registers */ #define ERXFR_EL1 S3_0_C5_C4_0 #define ERXCTLR_EL1 S3_0_C5_C4_1 #define ERXSTATUS_EL1 S3_0_C5_C4_2 #define ERXADDR_EL1 S3_0_C5_C4_3 #define ERXPFGF_EL1 S3_0_C5_C4_4 #define ERXPFGCTL_EL1 S3_0_C5_C4_5 #define ERXPFGCDN_EL1 S3_0_C5_C4_6 #define ERXMISC0_EL1 S3_0_C5_C5_0 #define ERXMISC1_EL1 S3_0_C5_C5_1 #define ERXCTLR_ED_BIT (U(1) << 0) #define ERXCTLR_UE_BIT (U(1) << 4) #define ERXPFGCTL_UC_BIT (U(1) << 1) #define ERXPFGCTL_UEU_BIT (U(1) << 2) #define ERXPFGCTL_CDEN_BIT (U(1) << 31) /******************************************************************************* * Armv8.3 Pointer Authentication Registers ******************************************************************************/ #define APGAKeyLo_EL1 S3_0_C2_C3_0 /******************************************************************************* * Armv8.4 Data Independent Timing Registers ******************************************************************************/ #define DIT S3_3_C4_C2_5 #define DIT_BIT BIT(24) #endif /* ARCH_H */
laroche/arm-trusted-firmware
plat/arm/common/arm_tzc400.c
/* * Copyright (c) 2014-2018, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <platform_def.h> #include <common/debug.h> #include <drivers/arm/tzc400.h> #include <plat_arm.h> /* Weak definitions may be overridden in specific ARM standard platform */ #pragma weak plat_arm_security_setup /******************************************************************************* * Initialize the TrustZone Controller for ARM standard platforms. * When booting an EL3 payload, this is simplified: we configure region 0 with * secure access only and do not enable any other region. ******************************************************************************/ void arm_tzc400_setup(const arm_tzc_regions_info_t *tzc_regions) { #ifndef EL3_PAYLOAD_BASE unsigned int region_index = 1U; const arm_tzc_regions_info_t *p; const arm_tzc_regions_info_t init_tzc_regions[] = { ARM_TZC_REGIONS_DEF, {0} }; #endif INFO("Configuring TrustZone Controller\n"); tzc400_init(PLAT_ARM_TZC_BASE); /* Disable filters. */ tzc400_disable_filters(); #ifndef EL3_PAYLOAD_BASE if (tzc_regions == NULL) p = init_tzc_regions; else p = tzc_regions; /* Region 0 set to no access by default */ tzc400_configure_region0(TZC_REGION_S_NONE, 0); /* Rest Regions set according to tzc_regions array */ for (; p->base != 0ULL; p++) { tzc400_configure_region(PLAT_ARM_TZC_FILTERS, region_index, p->base, p->end, p->sec_attr, p->nsaid_permissions); region_index++; } INFO("Total %u regions set.\n", region_index); #else /* if defined(EL3_PAYLOAD_BASE) */ /* Allow Secure and Non-secure access to DRAM for EL3 payloads */ tzc400_configure_region0(TZC_REGION_S_RDWR, PLAT_ARM_TZC_NS_DEV_ACCESS); #endif /* EL3_PAYLOAD_BASE */ /* * Raise an exception if a NS device tries to access secure memory * TODO: Add interrupt handling support. */ tzc400_set_action(TZC_ACTION_ERR); /* Enable filters. */ tzc400_enable_filters(); } void plat_arm_security_setup(void) { arm_tzc400_setup(NULL); }
laroche/arm-trusted-firmware
plat/arm/board/fvp/drivers/pwrc/fvp_pwrc.c
/* * Copyright (c) 2013-2018, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <lib/bakery_lock.h> #include <lib/mmio.h> #include <platform_def.h> #include <plat_arm.h> #include "../../fvp_private.h" #include "fvp_pwrc.h" /* * TODO: Someday there will be a generic power controller api. At the moment * each platform has its own pwrc so just exporting functions is fine. */ ARM_INSTANTIATE_LOCK; unsigned int fvp_pwrc_get_cpu_wkr(u_register_t mpidr) { return PSYSR_WK(fvp_pwrc_read_psysr(mpidr)); } unsigned int fvp_pwrc_read_psysr(u_register_t mpidr) { unsigned int rc; arm_lock_get(); mmio_write_32(PWRC_BASE + PSYSR_OFF, (unsigned int) mpidr); rc = mmio_read_32(PWRC_BASE + PSYSR_OFF); arm_lock_release(); return rc; } void fvp_pwrc_write_pponr(u_register_t mpidr) { arm_lock_get(); mmio_write_32(PWRC_BASE + PPONR_OFF, (unsigned int) mpidr); arm_lock_release(); } void fvp_pwrc_write_ppoffr(u_register_t mpidr) { arm_lock_get(); mmio_write_32(PWRC_BASE + PPOFFR_OFF, (unsigned int) mpidr); arm_lock_release(); } void fvp_pwrc_set_wen(u_register_t mpidr) { arm_lock_get(); mmio_write_32(PWRC_BASE + PWKUPR_OFF, (unsigned int) (PWKUPR_WEN | mpidr)); arm_lock_release(); } void fvp_pwrc_clr_wen(u_register_t mpidr) { arm_lock_get(); mmio_write_32(PWRC_BASE + PWKUPR_OFF, (unsigned int) mpidr); arm_lock_release(); } void fvp_pwrc_write_pcoffr(u_register_t mpidr) { arm_lock_get(); mmio_write_32(PWRC_BASE + PCOFFR_OFF, (unsigned int) mpidr); arm_lock_release(); } /* Nothing else to do here apart from initializing the lock */ void __init plat_arm_pwrc_setup(void) { arm_lock_init(); }
laroche/arm-trusted-firmware
plat/arm/board/juno/include/platform_def.h
/* * Copyright (c) 2014-2018, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef PLATFORM_DEF_H #define PLATFORM_DEF_H /* Enable the dynamic translation tables library. */ #ifdef AARCH32 # if defined(IMAGE_BL32) && RESET_TO_SP_MIN # define PLAT_XLAT_TABLES_DYNAMIC 1 # endif #else # if defined(IMAGE_BL31) && RESET_TO_BL31 # define PLAT_XLAT_TABLES_DYNAMIC 1 # endif #endif /* AARCH32 */ #include <drivers/arm/tzc400.h> #if TRUSTED_BOARD_BOOT #include <drivers/auth/mbedtls/mbedtls_config.h> #endif #include <plat/common/common_def.h> #include <arm_def.h> #include <board_css_def.h> #include <css_def.h> #include <soc_css_def.h> #include <v2m_def.h> #include "../juno_def.h" /* Required platform porting definitions */ /* Juno supports system power domain */ #define PLAT_MAX_PWR_LVL ARM_PWR_LVL2 #define PLAT_NUM_PWR_DOMAINS (ARM_SYSTEM_COUNT + \ JUNO_CLUSTER_COUNT + \ PLATFORM_CORE_COUNT) #define PLATFORM_CORE_COUNT (JUNO_CLUSTER0_CORE_COUNT + \ JUNO_CLUSTER1_CORE_COUNT) /* Cryptocell HW Base address */ #define PLAT_CRYPTOCELL_BASE UL(0x60050000) /* * Other platform porting definitions are provided by included headers */ /* * Required ARM standard platform porting definitions */ #define PLAT_ARM_CLUSTER_COUNT JUNO_CLUSTER_COUNT #define PLAT_ARM_TRUSTED_SRAM_SIZE UL(0x00040000) /* 256 KB */ /* Use the bypass address */ #define PLAT_ARM_TRUSTED_ROM_BASE (V2M_FLASH0_BASE + \ BL1_ROM_BYPASS_OFFSET) #define NSRAM_BASE UL(0x2e000000) #define NSRAM_SIZE UL(0x00008000) /* 32KB */ /* virtual address used by dynamic mem_protect for chunk_base */ #define PLAT_ARM_MEM_PROTEC_VA_FRAME UL(0xc0000000) /* * PLAT_ARM_MAX_ROMLIB_RW_SIZE is define to use a full page */ #if USE_ROMLIB #define PLAT_ARM_MAX_ROMLIB_RW_SIZE UL(0x1000) #define PLAT_ARM_MAX_ROMLIB_RO_SIZE UL(0xe000) #else #define PLAT_ARM_MAX_ROMLIB_RW_SIZE UL(0) #define PLAT_ARM_MAX_ROMLIB_RO_SIZE UL(0) #endif /* * Actual ROM size on Juno is 64 KB, but TBB currently requires at least 80 KB * in debug mode. We can test TBB on Juno bypassing the ROM and using 128 KB of * flash */ #if TRUSTED_BOARD_BOOT #define PLAT_ARM_TRUSTED_ROM_SIZE UL(0x00020000) #else #define PLAT_ARM_TRUSTED_ROM_SIZE UL(0x00010000) #endif /* TRUSTED_BOARD_BOOT */ /* * PLAT_ARM_MMAP_ENTRIES depends on the number of entries in the * plat_arm_mmap array defined for each BL stage. */ #ifdef IMAGE_BL1 # define PLAT_ARM_MMAP_ENTRIES 7 # define MAX_XLAT_TABLES 4 #endif #ifdef IMAGE_BL2 #ifdef SPD_opteed # define PLAT_ARM_MMAP_ENTRIES 11 # define MAX_XLAT_TABLES 5 #else # define PLAT_ARM_MMAP_ENTRIES 10 # define MAX_XLAT_TABLES 4 #endif #endif #ifdef IMAGE_BL2U # define PLAT_ARM_MMAP_ENTRIES 5 # define MAX_XLAT_TABLES 3 #endif #ifdef IMAGE_BL31 # define PLAT_ARM_MMAP_ENTRIES 7 # define MAX_XLAT_TABLES 3 #endif #ifdef IMAGE_BL32 # define PLAT_ARM_MMAP_ENTRIES 6 # define MAX_XLAT_TABLES 4 #endif /* * PLAT_ARM_MAX_BL1_RW_SIZE is calculated using the current BL1 RW debug size * plus a little space for growth. */ #if TRUSTED_BOARD_BOOT # define PLAT_ARM_MAX_BL1_RW_SIZE UL(0xB000) #else # define PLAT_ARM_MAX_BL1_RW_SIZE UL(0x6000) #endif /* * PLAT_ARM_MAX_BL2_SIZE is calculated using the current BL2 debug size plus a * little space for growth. */ #if TRUSTED_BOARD_BOOT #if TF_MBEDTLS_KEY_ALG_ID == TF_MBEDTLS_RSA_AND_ECDSA # define PLAT_ARM_MAX_BL2_SIZE UL(0x1F000) #elif TF_MBEDTLS_KEY_ALG_ID == TF_MBEDTLS_ECDSA # define PLAT_ARM_MAX_BL2_SIZE UL(0x1D000) #else # define PLAT_ARM_MAX_BL2_SIZE UL(0x1D000) #endif #else # define PLAT_ARM_MAX_BL2_SIZE UL(0xF000) #endif /* * Since BL31 NOBITS overlays BL2 and BL1-RW, PLAT_ARM_MAX_BL31_SIZE is * calculated using the current BL31 PROGBITS debug size plus the sizes of * BL2 and BL1-RW. SCP_BL2 image is loaded into the space BL31 -> BL2_BASE. * Hence the BL31 PROGBITS size should be >= PLAT_CSS_MAX_SCP_BL2_SIZE. */ #define PLAT_ARM_MAX_BL31_SIZE UL(0x3E000) #if JUNO_AARCH32_EL3_RUNTIME /* * Since BL32 NOBITS overlays BL2 and BL1-RW, PLAT_ARM_MAX_BL32_SIZE is * calculated using the current BL32 PROGBITS debug size plus the sizes of * BL2 and BL1-RW. SCP_BL2 image is loaded into the space BL32 -> BL2_BASE. * Hence the BL32 PROGBITS size should be >= PLAT_CSS_MAX_SCP_BL2_SIZE. */ #define PLAT_ARM_MAX_BL32_SIZE UL(0x3E000) #endif /* * Size of cacheable stacks */ #if defined(IMAGE_BL1) # if TRUSTED_BOARD_BOOT # define PLATFORM_STACK_SIZE UL(0x1000) # else # define PLATFORM_STACK_SIZE UL(0x440) # endif #elif defined(IMAGE_BL2) # if TRUSTED_BOARD_BOOT # define PLATFORM_STACK_SIZE UL(0x1000) # else # define PLATFORM_STACK_SIZE UL(0x400) # endif #elif defined(IMAGE_BL2U) # define PLATFORM_STACK_SIZE UL(0x400) #elif defined(IMAGE_BL31) # if PLAT_XLAT_TABLES_DYNAMIC # define PLATFORM_STACK_SIZE UL(0x800) # else # define PLATFORM_STACK_SIZE UL(0x400) # endif #elif defined(IMAGE_BL32) # define PLATFORM_STACK_SIZE UL(0x440) #endif /* * Since free SRAM space is scant, enable the ASSERTION message size * optimization by fixing the PLAT_LOG_LEVEL_ASSERT to LOG_LEVEL_INFO (40). */ #define PLAT_LOG_LEVEL_ASSERT 40 /* CCI related constants */ #define PLAT_ARM_CCI_BASE UL(0x2c090000) #define PLAT_ARM_CCI_CLUSTER0_SL_IFACE_IX 4 #define PLAT_ARM_CCI_CLUSTER1_SL_IFACE_IX 3 /* System timer related constants */ #define PLAT_ARM_NSTIMER_FRAME_ID U(1) /* TZC related constants */ #define PLAT_ARM_TZC_BASE UL(0x2a4a0000) #define PLAT_ARM_TZC_NS_DEV_ACCESS ( \ TZC_REGION_ACCESS_RDWR(TZC400_NSAID_CCI400) | \ TZC_REGION_ACCESS_RDWR(TZC400_NSAID_PCIE) | \ TZC_REGION_ACCESS_RDWR(TZC400_NSAID_HDLCD0) | \ TZC_REGION_ACCESS_RDWR(TZC400_NSAID_HDLCD1) | \ TZC_REGION_ACCESS_RDWR(TZC400_NSAID_USB) | \ TZC_REGION_ACCESS_RDWR(TZC400_NSAID_DMA330) | \ TZC_REGION_ACCESS_RDWR(TZC400_NSAID_THINLINKS) | \ TZC_REGION_ACCESS_RDWR(TZC400_NSAID_AP) | \ TZC_REGION_ACCESS_RDWR(TZC400_NSAID_GPU) | \ TZC_REGION_ACCESS_RDWR(TZC400_NSAID_CORESIGHT)) /* * Required ARM CSS based platform porting definitions */ /* GIC related constants (no GICR in GIC-400) */ #define PLAT_ARM_GICD_BASE UL(0x2c010000) #define PLAT_ARM_GICC_BASE UL(0x2c02f000) #define PLAT_ARM_GICH_BASE UL(0x2c04f000) #define PLAT_ARM_GICV_BASE UL(0x2c06f000) /* MHU related constants */ #define PLAT_CSS_MHU_BASE UL(0x2b1f0000) /* * Base address of the first memory region used for communication between AP * and SCP. Used by the BOM and SCPI protocols. */ #if !CSS_USE_SCMI_SDS_DRIVER /* * Note that this is located at the same address as SCP_BOOT_CFG_ADDR, which * means the SCP/AP configuration data gets overwritten when the AP initiates * communication with the SCP. The configuration data is expected to be a * 32-bit word on all CSS platforms. On Juno, part of this configuration is * which CPU is the primary, according to the shift and mask definitions below. */ #define PLAT_CSS_SCP_COM_SHARED_MEM_BASE (ARM_TRUSTED_SRAM_BASE + UL(0x80)) #define PLAT_CSS_PRIMARY_CPU_SHIFT 8 #define PLAT_CSS_PRIMARY_CPU_BIT_WIDTH 4 #endif /* * PLAT_CSS_MAX_SCP_BL2_SIZE is calculated using the current * SCP_BL2 size plus a little space for growth. */ #define PLAT_CSS_MAX_SCP_BL2_SIZE UL(0x14000) /* * PLAT_CSS_MAX_SCP_BL2U_SIZE is calculated using the current * SCP_BL2U size plus a little space for growth. */ #define PLAT_CSS_MAX_SCP_BL2U_SIZE UL(0x14000) #define PLAT_ARM_G1S_IRQ_PROPS(grp) \ CSS_G1S_IRQ_PROPS(grp), \ ARM_G1S_IRQ_PROPS(grp), \ INTR_PROP_DESC(JUNO_IRQ_DMA_SMMU, GIC_HIGHEST_SEC_PRIORITY, \ (grp), GIC_INTR_CFG_LEVEL), \ INTR_PROP_DESC(JUNO_IRQ_HDLCD0_SMMU, GIC_HIGHEST_SEC_PRIORITY, \ (grp), GIC_INTR_CFG_LEVEL), \ INTR_PROP_DESC(JUNO_IRQ_HDLCD1_SMMU, GIC_HIGHEST_SEC_PRIORITY, \ (grp), GIC_INTR_CFG_LEVEL), \ INTR_PROP_DESC(JUNO_IRQ_USB_SMMU, GIC_HIGHEST_SEC_PRIORITY, \ (grp), GIC_INTR_CFG_LEVEL), \ INTR_PROP_DESC(JUNO_IRQ_THIN_LINKS_SMMU, GIC_HIGHEST_SEC_PRIORITY, \ (grp), GIC_INTR_CFG_LEVEL), \ INTR_PROP_DESC(JUNO_IRQ_SEC_I2C, GIC_HIGHEST_SEC_PRIORITY, \ (grp), GIC_INTR_CFG_LEVEL), \ INTR_PROP_DESC(JUNO_IRQ_GPU_SMMU_1, GIC_HIGHEST_SEC_PRIORITY, \ (grp), GIC_INTR_CFG_LEVEL), \ INTR_PROP_DESC(JUNO_IRQ_ETR_SMMU, GIC_HIGHEST_SEC_PRIORITY, \ (grp), GIC_INTR_CFG_LEVEL) #define PLAT_ARM_G0_IRQ_PROPS(grp) ARM_G0_IRQ_PROPS(grp) /* * Required ARM CSS SoC based platform porting definitions */ /* CSS SoC NIC-400 Global Programmers View (GPV) */ #define PLAT_SOC_CSS_NIC400_BASE UL(0x2a000000) #define PLAT_ARM_PRIVATE_SDEI_EVENTS ARM_SDEI_PRIVATE_EVENTS #define PLAT_ARM_SHARED_SDEI_EVENTS ARM_SDEI_SHARED_EVENTS /* System power domain level */ #define CSS_SYSTEM_PWR_DMN_LVL ARM_PWR_LVL2 #endif /* PLATFORM_DEF_H */
laroche/arm-trusted-firmware
plat/arm/css/drivers/mhu/css_mhu_doorbell.c
<filename>plat/arm/css/drivers/mhu/css_mhu_doorbell.c /* * Copyright (c) 2014-2019, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <platform_def.h> #include <arch_helpers.h> #include "css_mhu_doorbell.h" #include "../scmi/scmi.h" void mhu_ring_doorbell(struct scmi_channel_plat_info *plat_info) { MHU_RING_DOORBELL(plat_info->db_reg_addr, plat_info->db_modify_mask, plat_info->db_preserve_mask); return; } void mhuv2_ring_doorbell(struct scmi_channel_plat_info *plat_info) { /* wake receiver */ MHU_V2_ACCESS_REQUEST(MHUV2_BASE_ADDR); /* wait for receiver to acknowledge its ready */ while (MHU_V2_IS_ACCESS_READY(MHUV2_BASE_ADDR) == 0) ; MHU_RING_DOORBELL(plat_info->db_reg_addr, plat_info->db_modify_mask, plat_info->db_preserve_mask); /* clear the access request for the receiver */ MHU_V2_CLEAR_REQUEST(MHUV2_BASE_ADDR); return; }
laroche/arm-trusted-firmware
plat/arm/common/arm_image_load.c
<filename>plat/arm/common/arm_image_load.c /* * Copyright (c) 2016-2018, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <assert.h> #include <common/bl_common.h> #include <common/desc_image_load.h> #include <plat/common/platform.h> #include <plat_arm.h> #pragma weak plat_flush_next_bl_params #pragma weak plat_get_bl_image_load_info #pragma weak plat_get_next_bl_params static bl_params_t *next_bl_params_cpy_ptr; /******************************************************************************* * This function flushes the data structures so that they are visible * in memory for the next BL image. ******************************************************************************/ void plat_flush_next_bl_params(void) { assert(next_bl_params_cpy_ptr != NULL); flush_bl_params_desc_args(bl_mem_params_desc_ptr, bl_mem_params_desc_num, next_bl_params_cpy_ptr); } /******************************************************************************* * This function returns the list of loadable images. ******************************************************************************/ struct bl_load_info *plat_get_bl_image_load_info(void) { return get_bl_load_info_from_mem_params_desc(); } /******************************************************************************* * ARM helper function to return the list of executable images.Since the default * descriptors are allocated within BL2 RW memory, this prevents BL31/BL32 * overlay of BL2 memory. Hence this function also copies the descriptors to a * pre-allocated memory indicated by ARM_BL2_MEM_DESC_BASE. ******************************************************************************/ struct bl_params *arm_get_next_bl_params(void) { bl_mem_params_node_t *bl2_mem_params_descs_cpy = (bl_mem_params_node_t *)ARM_BL2_MEM_DESC_BASE; const bl_params_t *next_bl_params; next_bl_params_cpy_ptr = (bl_params_t *)(ARM_BL2_MEM_DESC_BASE + (bl_mem_params_desc_num * sizeof(bl_mem_params_node_t))); /* * Copy the memory descriptors to ARM_BL2_MEM_DESC_BASE area. */ (void) memcpy(bl2_mem_params_descs_cpy, bl_mem_params_desc_ptr, (bl_mem_params_desc_num * sizeof(bl_mem_params_node_t))); /* * Modify the global 'bl_mem_params_desc_ptr' to point to the * copied location. */ bl_mem_params_desc_ptr = bl2_mem_params_descs_cpy; next_bl_params = get_next_bl_params_from_mem_params_desc(); assert(next_bl_params != NULL); /* * Copy 'next_bl_params' to the reserved location after the copied * memory descriptors. */ (void) memcpy(next_bl_params_cpy_ptr, next_bl_params, (sizeof(bl_params_t))); populate_next_bl_params_config(next_bl_params_cpy_ptr); return next_bl_params_cpy_ptr; } /******************************************************************************* * This function returns the list of executable images ******************************************************************************/ struct bl_params *plat_get_next_bl_params(void) { return arm_get_next_bl_params(); }
torsteingrindvik/fw-nrfconnect-zephyr
arch/x86_64/include/kernel_arch_func.h
<reponame>torsteingrindvik/fw-nrfconnect-zephyr /* * Copyright (c) 2018 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef _KERNEL_ARCH_FUNC_H #define _KERNEL_ARCH_FUNC_H #include <irq.h> #include <xuk-switch.h> static inline void z_arch_kernel_init(void) { /* This is a noop, we already took care of things before * z_cstart() is entered */ } static inline struct _cpu *z_arch_curr_cpu(void) { long long ret, off = 0; /* The struct _cpu pointer for the current CPU lives at the * start of the the FS segment */ __asm__("movq %%fs:(%1), %0" : "=r"(ret) : "r"(off)); return (struct _cpu *)(long)ret; } static inline void z_arch_nop(void) { __asm__ volatile("nop"); } static inline bool z_arch_is_in_isr(void) { return z_arch_curr_cpu()->nested != 0U; } static inline u32_t x86_apic_scaled_tsc(void) { u32_t lo, hi; u64_t tsc; __asm__ volatile("rdtsc" : "=a"(lo), "=d"(hi)); tsc = (((u64_t)hi) << 32) | lo; return (u32_t)(tsc >> CONFIG_XUK_APIC_TSC_SHIFT); } static inline void z_arch_switch(void *switch_to, void **switched_from) { xuk_switch(switch_to, switched_from); } void x86_apic_set_timeout(u32_t cyc_from_now); void z_arch_sched_ipi(void); #endif /* _KERNEL_ARCH_FUNC_H */
torsteingrindvik/fw-nrfconnect-zephyr
arch/x86/include/intel64/kernel_arch_func.h
/* * Copyright (c) 2019 Intel Corporation * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_ARCH_X86_INCLUDE_INTEL64_KERNEL_ARCH_FUNC_H_ #define ZEPHYR_ARCH_X86_INCLUDE_INTEL64_KERNEL_ARCH_FUNC_H_ #include <kernel_structs.h> #ifndef _ASMLANGUAGE extern void z_x86_switch(void *switch_to, void **switched_from); static inline void z_arch_switch(void *switch_to, void **switched_from) { z_x86_switch(switch_to, switched_from); } /** * @brief Initialize scheduler IPI vector. * * Called in early BSP boot to set up scheduler IPI handling. */ extern void z_x86_ipi_setup(void); static inline void z_arch_kernel_init(void) { /* nothing */; } static inline struct _cpu *z_arch_curr_cpu(void) { struct _cpu *cpu; __asm__ volatile("movq %%gs:(%c1), %0" : "=r" (cpu) : "i" (offsetof(x86_tss64_t, cpu))); return cpu; } #if defined(CONFIG_SMP) #include <drivers/interrupt_controller/loapic.h> /* * it is not clear exactly how/where/why to abstract this, as it * assumes the use of a local APIC (but there's no other mechanism). */ static inline void z_arch_sched_ipi(void) { z_loapic_ipi(0, LOAPIC_ICR_IPI_OTHERS, CONFIG_SCHED_IPI_VECTOR); } #endif #endif /* _ASMLANGUAGE */ #endif /* ZEPHYR_ARCH_X86_INCLUDE_INTEL64_KERNEL_ARCH_FUNC_H_ */
torsteingrindvik/fw-nrfconnect-zephyr
drivers/sensor/lsm6dso/lsm6dso_trigger.c
<reponame>torsteingrindvik/fw-nrfconnect-zephyr /* ST Microelectronics LSM6DSO 6-axis IMU sensor driver * * Copyright (c) 2019 STMicroelectronics * * SPDX-License-Identifier: Apache-2.0 * * Datasheet: * https://www.st.com/resource/en/datasheet/lsm6dso.pdf */ #include <kernel.h> #include <sensor.h> #include <gpio.h> #include <logging/log.h> #include "lsm6dso.h" LOG_MODULE_DECLARE(LSM6DSO, CONFIG_SENSOR_LOG_LEVEL); #if defined(CONFIG_LSM6DSO_ENABLE_TEMP) /** * lsm6dso_enable_t_int - TEMP enable selected int pin to generate interrupt */ static int lsm6dso_enable_t_int(struct device *dev, int enable) { const struct lsm6dso_config *cfg = dev->config->config_info; struct lsm6dso_data *lsm6dso = dev->driver_data; lsm6dso_pin_int2_route_t int2_route; if (enable) { axis1bit16_t buf; /* dummy read: re-trigger interrupt */ lsm6dso_temperature_raw_get(lsm6dso->ctx, buf.u8bit); } /* set interrupt (TEMP DRDY interrupt is only on INT2) */ if (cfg->int_pin == 1) return -EIO; lsm6dso_read_reg(lsm6dso->ctx, LSM6DSO_INT2_CTRL, (uint8_t *)&int2_route.int2_ctrl, 1); int2_route.int2_ctrl.int2_drdy_temp = enable; return lsm6dso_write_reg(lsm6dso->ctx, LSM6DSO_INT2_CTRL, (uint8_t *)&int2_route.int2_ctrl, 1); } #endif /** * lsm6dso_enable_xl_int - XL enable selected int pin to generate interrupt */ static int lsm6dso_enable_xl_int(struct device *dev, int enable) { const struct lsm6dso_config *cfg = dev->config->config_info; struct lsm6dso_data *lsm6dso = dev->driver_data; if (enable) { axis3bit16_t buf; /* dummy read: re-trigger interrupt */ lsm6dso_acceleration_raw_get(lsm6dso->ctx, buf.u8bit); } /* set interrupt */ if (cfg->int_pin == 1) { lsm6dso_pin_int1_route_t int1_route; lsm6dso_read_reg(lsm6dso->ctx, LSM6DSO_INT1_CTRL, (uint8_t *)&int1_route.int1_ctrl, 1); int1_route.int1_ctrl.int1_drdy_xl = enable; return lsm6dso_write_reg(lsm6dso->ctx, LSM6DSO_INT1_CTRL, (uint8_t *)&int1_route.int1_ctrl, 1); } else { lsm6dso_pin_int2_route_t int2_route; lsm6dso_read_reg(lsm6dso->ctx, LSM6DSO_INT2_CTRL, (uint8_t *)&int2_route.int2_ctrl, 1); int2_route.int2_ctrl.int2_drdy_xl = enable; return lsm6dso_write_reg(lsm6dso->ctx, LSM6DSO_INT2_CTRL, (uint8_t *)&int2_route.int2_ctrl, 1); } } /** * lsm6dso_enable_g_int - Gyro enable selected int pin to generate interrupt */ static int lsm6dso_enable_g_int(struct device *dev, int enable) { const struct lsm6dso_config *cfg = dev->config->config_info; struct lsm6dso_data *lsm6dso = dev->driver_data; if (enable) { axis3bit16_t buf; /* dummy read: re-trigger interrupt */ lsm6dso_angular_rate_raw_get(lsm6dso->ctx, buf.u8bit); } /* set interrupt */ if (cfg->int_pin == 1) { lsm6dso_pin_int1_route_t int1_route; lsm6dso_read_reg(lsm6dso->ctx, LSM6DSO_INT1_CTRL, (uint8_t *)&int1_route.int1_ctrl, 1); int1_route.int1_ctrl.int1_drdy_g = enable; return lsm6dso_write_reg(lsm6dso->ctx, LSM6DSO_INT1_CTRL, (uint8_t *)&int1_route.int1_ctrl, 1); } else { lsm6dso_pin_int2_route_t int2_route; lsm6dso_read_reg(lsm6dso->ctx, LSM6DSO_INT2_CTRL, (uint8_t *)&int2_route.int2_ctrl, 1); int2_route.int2_ctrl.int2_drdy_g = enable; return lsm6dso_write_reg(lsm6dso->ctx, LSM6DSO_INT2_CTRL, (uint8_t *)&int2_route.int2_ctrl, 1); } } /** * lsm6dso_trigger_set - link external trigger to event data ready */ int lsm6dso_trigger_set(struct device *dev, const struct sensor_trigger *trig, sensor_trigger_handler_t handler) { struct lsm6dso_data *lsm6dso = dev->driver_data; if (trig->chan == SENSOR_CHAN_ACCEL_XYZ) { lsm6dso->handler_drdy_acc = handler; if (handler) { return lsm6dso_enable_xl_int(dev, LSM6DSO_EN_BIT); } else { return lsm6dso_enable_xl_int(dev, LSM6DSO_DIS_BIT); } } else if (trig->chan == SENSOR_CHAN_GYRO_XYZ) { lsm6dso->handler_drdy_gyr = handler; if (handler) { return lsm6dso_enable_g_int(dev, LSM6DSO_EN_BIT); } else { return lsm6dso_enable_g_int(dev, LSM6DSO_DIS_BIT); } } #if defined(CONFIG_LSM6DSO_ENABLE_TEMP) else if (trig->chan == SENSOR_CHAN_DIE_TEMP) { lsm6dso->handler_drdy_temp = handler; if (handler) { return lsm6dso_enable_t_int(dev, LSM6DSO_EN_BIT); } else { return lsm6dso_enable_t_int(dev, LSM6DSO_DIS_BIT); } } #endif return -ENOTSUP; } /** * lsm6dso_handle_interrupt - handle the drdy event * read data and call handler if registered any */ static void lsm6dso_handle_interrupt(void *arg) { struct device *dev = arg; struct lsm6dso_data *lsm6dso = dev->driver_data; struct sensor_trigger drdy_trigger = { .type = SENSOR_TRIG_DATA_READY, }; const struct lsm6dso_config *cfg = dev->config->config_info; lsm6dso_status_reg_t status; while (1) { if (lsm6dso_status_reg_get(lsm6dso->ctx, &status) < 0) { LOG_DBG("failed reading status reg"); return; } if ((status.xlda == 0) && (status.gda == 0) #if defined(CONFIG_LSM6DSO_ENABLE_TEMP) && (status.tda == 0) #endif ) { break; } if ((status.xlda) && (lsm6dso->handler_drdy_acc != NULL)) { lsm6dso->handler_drdy_acc(dev, &drdy_trigger); } if ((status.gda) && (lsm6dso->handler_drdy_gyr != NULL)) { lsm6dso->handler_drdy_gyr(dev, &drdy_trigger); } #if defined(CONFIG_LSM6DSO_ENABLE_TEMP) if ((status.tda) && (lsm6dso->handler_drdy_temp != NULL)) { lsm6dso->handler_drdy_temp(dev, &drdy_trigger); } #endif } gpio_pin_enable_callback(lsm6dso->gpio, cfg->int_gpio_pin); } static void lsm6dso_gpio_callback(struct device *dev, struct gpio_callback *cb, u32_t pins) { struct lsm6dso_data *lsm6dso = CONTAINER_OF(cb, struct lsm6dso_data, gpio_cb); const struct lsm6dso_config *cfg = dev->config->config_info; ARG_UNUSED(pins); gpio_pin_disable_callback(dev, cfg->int_gpio_pin); #if defined(CONFIG_LSM6DSO_TRIGGER_OWN_THREAD) k_sem_give(&lsm6dso->gpio_sem); #elif defined(CONFIG_LSM6DSO_TRIGGER_GLOBAL_THREAD) k_work_submit(&lsm6dso->work); #endif /* CONFIG_LSM6DSO_TRIGGER_OWN_THREAD */ } #ifdef CONFIG_LSM6DSO_TRIGGER_OWN_THREAD static void lsm6dso_thread(int dev_ptr, int unused) { struct device *dev = INT_TO_POINTER(dev_ptr); struct lsm6dso_data *lsm6dso = dev->driver_data; ARG_UNUSED(unused); while (1) { k_sem_take(&lsm6dso->gpio_sem, K_FOREVER); lsm6dso_handle_interrupt(dev); } } #endif /* CONFIG_LSM6DSO_TRIGGER_OWN_THREAD */ #ifdef CONFIG_LSM6DSO_TRIGGER_GLOBAL_THREAD static void lsm6dso_work_cb(struct k_work *work) { struct lsm6dso_data *lsm6dso = CONTAINER_OF(work, struct lsm6dso_data, work); lsm6dso_handle_interrupt(lsm6dso->dev); } #endif /* CONFIG_LSM6DSO_TRIGGER_GLOBAL_THREAD */ int lsm6dso_init_interrupt(struct device *dev) { struct lsm6dso_data *lsm6dso = dev->driver_data; const struct lsm6dso_config *cfg = dev->config->config_info; int ret; /* setup data ready gpio interrupt (INT1 or INT2) */ lsm6dso->gpio = device_get_binding(cfg->int_gpio_port); if (lsm6dso->gpio == NULL) { LOG_DBG("Cannot get pointer to %s device", cfg->int_gpio_port); return -EINVAL; } #if defined(CONFIG_LSM6DSO_TRIGGER_OWN_THREAD) k_sem_init(&lsm6dso->gpio_sem, 0, UINT_MAX); k_thread_create(&lsm6dso->thread, lsm6dso->thread_stack, CONFIG_LSM6DSO_THREAD_STACK_SIZE, (k_thread_entry_t)lsm6dso_thread, dev, 0, NULL, K_PRIO_COOP(CONFIG_LSM6DSO_THREAD_PRIORITY), 0, K_NO_WAIT); #elif defined(CONFIG_LSM6DSO_TRIGGER_GLOBAL_THREAD) lsm6dso->work.handler = lsm6dso_work_cb; lsm6dso->dev = dev; #endif /* CONFIG_LSM6DSO_TRIGGER_OWN_THREAD */ ret = gpio_pin_configure(lsm6dso->gpio, cfg->int_gpio_pin, GPIO_DIR_IN | GPIO_INT | GPIO_INT_EDGE | GPIO_INT_ACTIVE_HIGH | GPIO_INT_DEBOUNCE); if (ret < 0) { LOG_DBG("Could not configure gpio"); return ret; } gpio_init_callback(&lsm6dso->gpio_cb, lsm6dso_gpio_callback, BIT(cfg->int_gpio_pin)); if (gpio_add_callback(lsm6dso->gpio, &lsm6dso->gpio_cb) < 0) { LOG_DBG("Could not set gpio callback"); return -EIO; } /* enable interrupt on int1/int2 in pulse mode */ if (lsm6dso_int_notification_set(lsm6dso->ctx, LSM6DSO_ALL_INT_PULSED) < 0) { LOG_DBG("Could not set pulse mode"); return -EIO; } return gpio_pin_enable_callback(lsm6dso->gpio, cfg->int_gpio_pin); }
torsteingrindvik/fw-nrfconnect-zephyr
subsys/net/lib/lwm2m/ipso_accelerometer.c
/* * Copyright (c) 2019 Foundries.io * * SPDX-License-Identifier: Apache-2.0 */ /* * Source material for IPSO Accelerometer object (3313): * http://www.openmobilealliance.org/tech/profiles/lwm2m/3313.xml */ #define LOG_MODULE_NAME net_ipso_accel #define LOG_LEVEL CONFIG_LWM2M_LOG_LEVEL #include <logging/log.h> LOG_MODULE_REGISTER(LOG_MODULE_NAME); #include <stdint.h> #include <init.h> #include "lwm2m_object.h" #include "lwm2m_engine.h" /* Server resource IDs */ #define ACCEL_X_VALUE_ID 5702 #define ACCEL_Y_VALUE_ID 5703 #define ACCEL_Z_VALUE_ID 5704 #define ACCEL_SENSOR_UNITS_ID 5701 #define ACCEL_MIN_RANGE_VALUE_ID 5603 #define ACCEL_MAX_RANGE_VALUE_ID 5604 /* This field is not in spec but can be used to record event time */ #define ACCEL_TIMESTAMP_ID 5518 #define ACCEL_MAX_ID 7 #define MAX_INSTANCE_COUNT CONFIG_LWM2M_IPSO_ACCELEROMETER_INSTANCE_COUNT /* * Calculate resource instances as follows: * start with ACCEL_MAX_ID */ #define RESOURCE_INSTANCE_COUNT (ACCEL_MAX_ID) /* resource state */ struct ipso_accel_data { float32_value_t x_value; float32_value_t y_value; float32_value_t z_value; float32_value_t min_range; float32_value_t max_range; }; static struct ipso_accel_data accel_data[MAX_INSTANCE_COUNT]; static struct lwm2m_engine_obj accel; static struct lwm2m_engine_obj_field fields[] = { OBJ_FIELD_DATA(ACCEL_X_VALUE_ID, R, FLOAT32), OBJ_FIELD_DATA(ACCEL_Y_VALUE_ID, R_OPT, FLOAT32), OBJ_FIELD_DATA(ACCEL_Z_VALUE_ID, R_OPT, FLOAT32), OBJ_FIELD_DATA(ACCEL_SENSOR_UNITS_ID, R_OPT, STRING), OBJ_FIELD_DATA(ACCEL_MIN_RANGE_VALUE_ID, R_OPT, FLOAT32), OBJ_FIELD_DATA(ACCEL_MAX_RANGE_VALUE_ID, R_OPT, FLOAT32), OBJ_FIELD_DATA(ACCEL_TIMESTAMP_ID, RW_OPT, TIME), }; static struct lwm2m_engine_obj_inst inst[MAX_INSTANCE_COUNT]; static struct lwm2m_engine_res res[MAX_INSTANCE_COUNT][ACCEL_MAX_ID]; static struct lwm2m_engine_res_inst res_inst[MAX_INSTANCE_COUNT][RESOURCE_INSTANCE_COUNT]; static struct lwm2m_engine_obj_inst *accel_create(u16_t obj_inst_id) { int index, avail = -1, i = 0, j = 0; /* Check that there is no other instance with this ID */ for (index = 0; index < ARRAY_SIZE(inst); index++) { if (inst[index].obj && inst[index].obj_inst_id == obj_inst_id) { LOG_ERR("Can not create instance - " "already existing: %u", obj_inst_id); return NULL; } /* Save first available slot index */ if (avail < 0 && !inst[index].obj) { avail = index; } } if (avail < 0) { LOG_ERR("Can not create instance - no more room: %u", obj_inst_id); return NULL; } /* Set default values */ (void)memset(&accel_data[avail], 0, sizeof(accel_data[avail])); (void)memset(res[avail], 0, sizeof(res[avail][0]) * ARRAY_SIZE(res[avail])); init_res_instance(res_inst[avail], ARRAY_SIZE(res_inst[avail])); /* initialize instance resource data */ INIT_OBJ_RES_DATA(ACCEL_X_VALUE_ID, res[avail], i, res_inst[avail], j, &accel_data[avail].x_value, sizeof(accel_data[avail].x_value)); INIT_OBJ_RES_DATA(ACCEL_Y_VALUE_ID, res[avail], i, res_inst[avail], j, &accel_data[avail].y_value, sizeof(accel_data[avail].y_value)); INIT_OBJ_RES_DATA(ACCEL_Z_VALUE_ID, res[avail], i, res_inst[avail], j, &accel_data[avail].z_value, sizeof(accel_data[avail].z_value)); INIT_OBJ_RES_OPTDATA(ACCEL_SENSOR_UNITS_ID, res[avail], i, res_inst[avail], j); INIT_OBJ_RES_DATA(ACCEL_MIN_RANGE_VALUE_ID, res[avail], i, res_inst[avail], j, &accel_data[avail].min_range, sizeof(accel_data[avail].min_range)); INIT_OBJ_RES_DATA(ACCEL_MAX_RANGE_VALUE_ID, res[avail], i, res_inst[avail], j, &accel_data[avail].max_range, sizeof(accel_data[avail].max_range)); INIT_OBJ_RES_OPTDATA(ACCEL_TIMESTAMP_ID, res[avail], i, res_inst[avail], j); inst[avail].resources = res[avail]; inst[avail].resource_count = i; LOG_DBG("Create IPSO Accelerometer instance: %d", obj_inst_id); return &inst[avail]; } static int ipso_accel_init(struct device *dev) { accel.obj_id = IPSO_OBJECT_ACCELEROMETER_ID; accel.fields = fields; accel.field_count = ARRAY_SIZE(fields); accel.max_instance_count = ARRAY_SIZE(inst); accel.create_cb = accel_create; lwm2m_register_obj(&accel); return 0; } SYS_INIT(ipso_accel_init, APPLICATION, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
torsteingrindvik/fw-nrfconnect-zephyr
samples/drivers/CAN/src/main.c
<gh_stars>0 /* * Copyright (c) 2018 <NAME> * * SPDX-License-Identifier: Apache-2.0 */ #include <zephyr.h> #include <kernel.h> #include <sys/printk.h> #include <device.h> #include <drivers/can.h> #include <drivers/gpio.h> #include <misc/byteorder.h> #define RX_THREAD_STACK_SIZE 512 #define RX_THREAD_PRIORITY 2 #define LED_MSG_ID 0x10 #define COUNTER_MSG_ID 0x12345 #define SET_LED 1 #define RESET_LED 0 #define SLEEP_TIME K_MSEC(250) K_THREAD_STACK_DEFINE(rx_thread_stack, RX_THREAD_STACK_SIZE); struct k_thread rx_thread_data; struct zcan_work rx_work; CAN_DEFINE_MSGQ(counter_msgq, 2); void tx_irq_callback(u32_t error_flags, void *arg) { char *sender = (char *)arg; if (error_flags) { printk("Callback! error-code: %d\nSender: %s\n", error_flags, sender); } } void rx_thread(void *can_dev_param, void *arg1, void *arg2) { ARG_UNUSED(arg1); ARG_UNUSED(arg2); const struct zcan_filter filter = { .id_type = CAN_EXTENDED_IDENTIFIER, .rtr = CAN_DATAFRAME, .ext_id = COUNTER_MSG_ID, .rtr_mask = 1, .ext_id_mask = CAN_EXT_ID_MASK }; struct device *can_dev = can_dev_param; struct zcan_frame msg; int filter_id; filter_id = can_attach_msgq(can_dev, &counter_msgq, &filter); printk("Counter filter id: %d\n", filter_id); while (1) { k_msgq_get(&counter_msgq, &msg, K_FOREVER); if (msg.dlc != 2U) { printk("Wrong data length: %u\n", msg.dlc); continue; } printk("Counter received: %u\n", sys_be16_to_cpu(UNALIGNED_GET((u16_t *)&msg.data))); } } void change_led(struct zcan_frame *msg, void *led_dev_param) { struct device *led_dev = (struct device *)led_dev_param; #if defined(DT_ALIAS_LED0_GPIOS_PIN) && defined(DT_ALIAS_LED0_GPIOS_CONTROLLER) if (!led_dev_param) { printk("No LED GPIO device\n"); return; } switch (msg->data[0]) { case SET_LED: gpio_pin_write(led_dev, DT_ALIAS_LED0_GPIOS_PIN, 1); break; case RESET_LED: gpio_pin_write(led_dev, DT_ALIAS_LED0_GPIOS_PIN, 0); break; } #else printk("LED %s\n", msg->data[0] == SET_LED ? "ON" : "OFF"); #endif } void main(void) { const struct zcan_filter change_led_filter = { .id_type = CAN_STANDARD_IDENTIFIER, .rtr = CAN_DATAFRAME, .std_id = LED_MSG_ID, .rtr_mask = 1, .std_id_mask = CAN_STD_ID_MASK }; struct zcan_frame change_led_frame = { .id_type = CAN_STANDARD_IDENTIFIER, .rtr = CAN_DATAFRAME, .std_id = LED_MSG_ID, .dlc = 1 }; struct zcan_frame counter_frame = { .id_type = CAN_EXTENDED_IDENTIFIER, .rtr = CAN_DATAFRAME, .ext_id = COUNTER_MSG_ID, .dlc = 2 }; u8_t toggle = 1; u16_t counter = 0; struct device *led_gpio_dev = NULL; struct device *can_dev; k_tid_t rx_tid; int ret; /* Usually the CAN device is either called CAN_0 or CAN_1, depending * on the SOC. Let's check both and take the first valid one. */ can_dev = device_get_binding("CAN_0"); if (!can_dev) { can_dev = device_get_binding("CAN_1"); } if (!can_dev) { printk("CAN: Device driver not found.\n"); return; } #ifdef CONFIG_LOOPBACK_MODE can_configure(can_dev, CAN_LOOPBACK_MODE, 125000); #endif #if defined(DT_ALIAS_LED0_GPIOS_PIN) && defined(DT_ALIAS_LED0_GPIOS_CONTROLLER) led_gpio_dev = device_get_binding(DT_ALIAS_LED0_GPIOS_CONTROLLER); if (!led_gpio_dev) { printk("LED: Device driver not found.\n"); return; } ret = gpio_pin_configure(led_gpio_dev, DT_ALIAS_LED0_GPIOS_PIN, GPIO_DIR_OUT); if (ret < 0) { printk("Error setting LED pin to output mode [%d]", ret); } #endif ret = can_attach_workq(can_dev, &k_sys_work_q, &rx_work, change_led, led_gpio_dev, &change_led_filter); if (ret == CAN_NO_FREE_FILTER) { printk("Error, no filter available!\n"); return; } printk("Change LED filter ID: %d\n", ret); rx_tid = k_thread_create(&rx_thread_data, rx_thread_stack, K_THREAD_STACK_SIZEOF(rx_thread_stack), rx_thread, can_dev, NULL, NULL, RX_THREAD_PRIORITY, 0, K_NO_WAIT); if (!rx_tid) { printk("ERROR spawning rx thread\n"); } printk("Finished init.\n"); while (1) { change_led_frame.data[0] = toggle++ & 0x01 ? SET_LED : RESET_LED; /* This sending call is none blocking. */ can_send(can_dev, &change_led_frame, K_FOREVER, tx_irq_callback, "LED change"); k_sleep(SLEEP_TIME); UNALIGNED_PUT(sys_cpu_to_be16(counter), (u16_t *)&counter_frame.data[0]); counter++; /* This sending call is blocking until the message is sent. */ can_send(can_dev, &counter_frame, K_MSEC(100), NULL, NULL); k_sleep(SLEEP_TIME); } }
torsteingrindvik/fw-nrfconnect-zephyr
drivers/sensor/lps22hh/lps22hh_i2c.c
/* ST Microelectronics LPS22HH pressure and temperature sensor * * Copyright (c) 2019 STMicroelectronics * * SPDX-License-Identifier: Apache-2.0 * * Datasheet: * https://www.st.com/resource/en/datasheet/lps22hh.pdf */ #include <string.h> #include <drivers/i2c.h> #include <logging/log.h> #include "lps22hh.h" #ifdef DT_ST_LPS22HH_BUS_I2C LOG_MODULE_DECLARE(LPS22HH, CONFIG_SENSOR_LOG_LEVEL); static int lps22hh_i2c_read(struct device *dev, u8_t reg_addr, u8_t *value, u16_t len) { struct lps22hh_data *data = dev->driver_data; const struct lps22hh_config *cfg = dev->config->config_info; return i2c_burst_read(data->bus, cfg->i2c_slv_addr, reg_addr, value, len); } static int lps22hh_i2c_write(struct device *dev, u8_t reg_addr, u8_t *value, u16_t len) { struct lps22hh_data *data = dev->driver_data; const struct lps22hh_config *cfg = dev->config->config_info; return i2c_burst_write(data->bus, cfg->i2c_slv_addr, reg_addr, value, len); } int lps22hh_i2c_init(struct device *dev) { struct lps22hh_data *data = dev->driver_data; data->ctx_i2c.read_reg = (lps22hh_read_ptr) lps22hh_i2c_read; data->ctx_i2c.write_reg = (lps22hh_write_ptr) lps22hh_i2c_write; data->ctx = &data->ctx_i2c; data->ctx->handle = dev; return 0; } #endif /* DT_ST_LPS22HH_BUS_I2C */
torsteingrindvik/fw-nrfconnect-zephyr
soc/arm/st_stm32/stm32g4/dts_fixup.h
/* * Copyright (c) 2019 <NAME> <<EMAIL>> * * SPDX-License-Identifier: Apache-2.0 */ /* SoC level DTS fixup file */ #define DT_NUM_IRQ_PRIO_BITS DT_ARM_V7M_NVIC_E000E100_ARM_NUM_IRQ_PRIORITY_BITS #define DT_GPIO_STM32_GPIOA_BASE_ADDRESS DT_ST_STM32_GPIO_48000000_BASE_ADDRESS #define DT_GPIO_STM32_GPIOA_CLOCK_BITS_0 DT_ST_STM32_GPIO_48000000_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOA_CLOCK_BUS_0 DT_ST_STM32_GPIO_48000000_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOA_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48000000_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOA_LABEL DT_ST_STM32_GPIO_48000000_LABEL #define DT_GPIO_STM32_GPIOA_SIZE DT_ST_STM32_GPIO_48000000_SIZE #define DT_GPIO_STM32_GPIOA_CLOCK_BITS DT_ST_STM32_GPIO_48000000_CLOCK_BITS #define DT_GPIO_STM32_GPIOA_CLOCK_BUS DT_ST_STM32_GPIO_48000000_CLOCK_BUS #define DT_GPIO_STM32_GPIOB_BASE_ADDRESS DT_ST_STM32_GPIO_48000400_BASE_ADDRESS #define DT_GPIO_STM32_GPIOB_CLOCK_BITS_0 DT_ST_STM32_GPIO_48000400_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOB_CLOCK_BUS_0 DT_ST_STM32_GPIO_48000400_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOB_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48000400_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOB_LABEL DT_ST_STM32_GPIO_48000400_LABEL #define DT_GPIO_STM32_GPIOB_SIZE DT_ST_STM32_GPIO_48000400_SIZE #define DT_GPIO_STM32_GPIOB_CLOCK_BITS DT_ST_STM32_GPIO_48000400_CLOCK_BITS #define DT_GPIO_STM32_GPIOB_CLOCK_BUS DT_ST_STM32_GPIO_48000400_CLOCK_BUS #define DT_GPIO_STM32_GPIOC_BASE_ADDRESS DT_ST_STM32_GPIO_48000800_BASE_ADDRESS #define DT_GPIO_STM32_GPIOC_CLOCK_BITS_0 DT_ST_STM32_GPIO_48000800_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOC_CLOCK_BUS_0 DT_ST_STM32_GPIO_48000800_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOC_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48000800_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOC_LABEL DT_ST_STM32_GPIO_48000800_LABEL #define DT_GPIO_STM32_GPIOC_SIZE DT_ST_STM32_GPIO_48000800_SIZE #define DT_GPIO_STM32_GPIOC_CLOCK_BITS DT_ST_STM32_GPIO_48000800_CLOCK_BITS #define DT_GPIO_STM32_GPIOC_CLOCK_BUS DT_ST_STM32_GPIO_48000800_CLOCK_BUS #define DT_GPIO_STM32_GPIOD_BASE_ADDRESS DT_ST_STM32_GPIO_48000C00_BASE_ADDRESS #define DT_GPIO_STM32_GPIOD_CLOCK_BITS_0 DT_ST_STM32_GPIO_48000C00_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOD_CLOCK_BUS_0 DT_ST_STM32_GPIO_48000C00_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOD_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48000C00_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOD_LABEL DT_ST_STM32_GPIO_48000C00_LABEL #define DT_GPIO_STM32_GPIOD_SIZE DT_ST_STM32_GPIO_48000C00_SIZE #define DT_GPIO_STM32_GPIOD_CLOCK_BITS DT_ST_STM32_GPIO_48000C00_CLOCK_BITS #define DT_GPIO_STM32_GPIOD_CLOCK_BUS DT_ST_STM32_GPIO_48000C00_CLOCK_BUS #define DT_GPIO_STM32_GPIOE_BASE_ADDRESS DT_ST_STM32_GPIO_48001000_BASE_ADDRESS #define DT_GPIO_STM32_GPIOE_CLOCK_BITS_0 DT_ST_STM32_GPIO_48001000_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOE_CLOCK_BUS_0 DT_ST_STM32_GPIO_48001000_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOE_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48001000_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOE_LABEL DT_ST_STM32_GPIO_48001000_LABEL #define DT_GPIO_STM32_GPIOE_SIZE DT_ST_STM32_GPIO_48001000_SIZE #define DT_GPIO_STM32_GPIOE_CLOCK_BITS DT_ST_STM32_GPIO_48001000_CLOCK_BITS #define DT_GPIO_STM32_GPIOE_CLOCK_BUS DT_ST_STM32_GPIO_48001000_CLOCK_BUS #define DT_GPIO_STM32_GPIOF_BASE_ADDRESS DT_ST_STM32_GPIO_48001400_BASE_ADDRESS #define DT_GPIO_STM32_GPIOF_CLOCK_BITS_0 DT_ST_STM32_GPIO_48001400_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOF_CLOCK_BUS_0 DT_ST_STM32_GPIO_48001400_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOF_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48001400_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOF_LABEL DT_ST_STM32_GPIO_48001400_LABEL #define DT_GPIO_STM32_GPIOF_SIZE DT_ST_STM32_GPIO_48001400_SIZE #define DT_GPIO_STM32_GPIOF_CLOCK_BITS DT_ST_STM32_GPIO_48001400_CLOCK_BITS #define DT_GPIO_STM32_GPIOF_CLOCK_BUS DT_ST_STM32_GPIO_48001400_CLOCK_BUS #define DT_GPIO_STM32_GPIOG_BASE_ADDRESS DT_ST_STM32_GPIO_48001800_BASE_ADDRESS #define DT_GPIO_STM32_GPIOG_CLOCK_BITS_0 DT_ST_STM32_GPIO_48001800_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOG_CLOCK_BUS_0 DT_ST_STM32_GPIO_48001800_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOG_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48001800_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOG_LABEL DT_ST_STM32_GPIO_48001800_LABEL #define DT_GPIO_STM32_GPIOG_SIZE DT_ST_STM32_GPIO_48001800_SIZE #define DT_GPIO_STM32_GPIOG_CLOCK_BITS DT_ST_STM32_GPIO_48001800_CLOCK_BITS #define DT_GPIO_STM32_GPIOG_CLOCK_BUS DT_ST_STM32_GPIO_48001800_CLOCK_BUS #define DT_UART_STM32_USART_1_BASE_ADDRESS DT_ST_STM32_USART_40013800_BASE_ADDRESS #define DT_UART_STM32_USART_1_BAUD_RATE DT_ST_STM32_USART_40013800_CURRENT_SPEED #define DT_UART_STM32_USART_1_IRQ_PRI DT_ST_STM32_USART_40013800_IRQ_0_PRIORITY #define DT_UART_STM32_USART_1_NAME DT_ST_STM32_USART_40013800_LABEL #define DT_USART_1_IRQ DT_ST_STM32_USART_40013800_IRQ_0 #define DT_UART_STM32_USART_1_CLOCK_BITS DT_ST_STM32_USART_40013800_CLOCK_BITS #define DT_UART_STM32_USART_1_CLOCK_BUS DT_ST_STM32_USART_40013800_CLOCK_BUS #define DT_UART_STM32_USART_1_HW_FLOW_CONTROL DT_ST_STM32_USART_40013800_HW_FLOW_CONTROL #define DT_UART_STM32_USART_2_BASE_ADDRESS DT_ST_STM32_USART_40004400_BASE_ADDRESS #define DT_UART_STM32_USART_2_BAUD_RATE DT_ST_STM32_USART_40004400_CURRENT_SPEED #define DT_UART_STM32_USART_2_IRQ_PRI DT_ST_STM32_USART_40004400_IRQ_0_PRIORITY #define DT_UART_STM32_USART_2_NAME DT_ST_STM32_USART_40004400_LABEL #define DT_USART_2_IRQ DT_ST_STM32_USART_40004400_IRQ_0 #define DT_UART_STM32_USART_2_CLOCK_BITS DT_ST_STM32_USART_40004400_CLOCK_BITS #define DT_UART_STM32_USART_2_CLOCK_BUS DT_ST_STM32_USART_40004400_CLOCK_BUS #define DT_UART_STM32_USART_2_HW_FLOW_CONTROL DT_ST_STM32_USART_40004400_HW_FLOW_CONTROL #define DT_UART_STM32_USART_3_BASE_ADDRESS DT_ST_STM32_USART_40004800_BASE_ADDRESS #define DT_UART_STM32_USART_3_BAUD_RATE DT_ST_STM32_USART_40004800_CURRENT_SPEED #define DT_UART_STM32_USART_3_IRQ_PRI DT_ST_STM32_USART_40004800_IRQ_0_PRIORITY #define DT_UART_STM32_USART_3_NAME DT_ST_STM32_USART_40004800_LABEL #define DT_USART_3_IRQ DT_ST_STM32_USART_40004800_IRQ_0 #define DT_UART_STM32_USART_3_CLOCK_BITS DT_ST_STM32_USART_40004800_CLOCK_BITS #define DT_UART_STM32_USART_3_CLOCK_BUS DT_ST_STM32_USART_40004800_CLOCK_BUS #define DT_UART_STM32_USART_3_HW_FLOW_CONTROL DT_ST_STM32_USART_40004800_HW_FLOW_CONTROL #define DT_UART_STM32_UART_4_BASE_ADDRESS DT_ST_STM32_UART_40004C00_BASE_ADDRESS #define DT_UART_STM32_UART_4_BAUD_RATE DT_ST_STM32_UART_40004C00_CURRENT_SPEED #define DT_UART_STM32_UART_4_IRQ_PRI DT_ST_STM32_UART_40004C00_IRQ_0_PRIORITY #define DT_UART_STM32_UART_4_NAME DT_ST_STM32_UART_40004C00_LABEL #define DT_UART_4_IRQ DT_ST_STM32_UART_40004C00_IRQ_0 #define DT_UART_STM32_UART_4_CLOCK_BITS DT_ST_STM32_UART_40004C00_CLOCK_BITS #define DT_UART_STM32_UART_4_CLOCK_BUS DT_ST_STM32_UART_40004C00_CLOCK_BUS #define DT_UART_STM32_UART_4_HW_FLOW_CONTROL DT_ST_STM32_UART_40004C00_HW_FLOW_CONTROL #define DT_UART_STM32_LPUART_1_BASE_ADDRESS DT_ST_STM32_LPUART_40008000_BASE_ADDRESS #define DT_UART_STM32_LPUART_1_BAUD_RATE DT_ST_STM32_LPUART_40008000_CURRENT_SPEED #define DT_UART_STM32_LPUART_1_IRQ_PRI DT_ST_STM32_LPUART_40008000_IRQ_0_PRIORITY #define DT_UART_STM32_LPUART_1_NAME DT_ST_STM32_LPUART_40008000_LABEL #define DT_LPUART_1_IRQ DT_ST_STM32_LPUART_40008000_IRQ_0 #define DT_UART_STM32_LPUART_1_CLOCK_BITS DT_ST_STM32_LPUART_40008000_CLOCK_BITS #define DT_UART_STM32_LPUART_1_CLOCK_BUS DT_ST_STM32_LPUART_40008000_CLOCK_BUS #define DT_UART_STM32_LPUART_1_HW_FLOW_CONTROL DT_ST_STM32_LPUART_40008000_HW_FLOW_CONTROL #define DT_FLASH_DEV_BASE_ADDRESS DT_ST_STM32G4_FLASH_CONTROLLER_40022000_BASE_ADDRESS #define DT_FLASH_DEV_NAME DT_ST_STM32G4_FLASH_CONTROLLER_40022000_LABEL #define DT_I2C_1_BASE_ADDRESS DT_ST_STM32_I2C_V2_40005400_BASE_ADDRESS #define DT_I2C_1_EVENT_IRQ_PRI DT_ST_STM32_I2C_V2_40005400_IRQ_EVENT_PRIORITY #define DT_I2C_1_ERROR_IRQ_PRI DT_ST_STM32_I2C_V2_40005400_IRQ_ERROR_PRIORITY #define CONFIG_I2C_1_NAME DT_ST_STM32_I2C_V2_40005400_LABEL #define DT_I2C_1_EVENT_IRQ DT_ST_STM32_I2C_V2_40005400_IRQ_EVENT #define DT_I2C_1_ERROR_IRQ DT_ST_STM32_I2C_V2_40005400_IRQ_ERROR #define DT_I2C_1_BITRATE DT_ST_STM32_I2C_V2_40005400_CLOCK_FREQUENCY #define DT_I2C_1_CLOCK_BITS DT_ST_STM32_I2C_V2_40005400_CLOCK_BITS #define DT_I2C_1_CLOCK_BUS DT_ST_STM32_I2C_V2_40005400_CLOCK_BUS #define DT_I2C_2_BASE_ADDRESS DT_ST_STM32_I2C_V2_40005800_BASE_ADDRESS #define DT_I2C_2_EVENT_IRQ_PRI DT_ST_STM32_I2C_V2_40005800_IRQ_EVENT_PRIORITY #define DT_I2C_2_ERROR_IRQ_PRI DT_ST_STM32_I2C_V2_40005800_IRQ_ERROR_PRIORITY #define CONFIG_I2C_2_NAME DT_ST_STM32_I2C_V2_40005800_LABEL #define DT_I2C_2_EVENT_IRQ DT_ST_STM32_I2C_V2_40005800_IRQ_EVENT #define DT_I2C_2_ERROR_IRQ DT_ST_STM32_I2C_V2_40005800_IRQ_ERROR #define DT_I2C_2_BITRATE DT_ST_STM32_I2C_V2_40005800_CLOCK_FREQUENCY #define DT_I2C_2_CLOCK_BITS DT_ST_STM32_I2C_V2_40005800_CLOCK_BITS #define DT_I2C_2_CLOCK_BUS DT_ST_STM32_I2C_V2_40005800_CLOCK_BUS #define DT_I2C_3_BASE_ADDRESS DT_ST_STM32_I2C_V2_40007800_BASE_ADDRESS #define DT_I2C_3_EVENT_IRQ_PRI DT_ST_STM32_I2C_V2_40007800_IRQ_EVENT_PRIORITY #define DT_I2C_3_ERROR_IRQ_PRI DT_ST_STM32_I2C_V2_40007800_IRQ_ERROR_PRIORITY #define CONFIG_I2C_3_NAME DT_ST_STM32_I2C_V2_40007800_LABEL #define DT_I2C_3_EVENT_IRQ DT_ST_STM32_I2C_V2_40007800_IRQ_EVENT #define DT_I2C_3_ERROR_IRQ DT_ST_STM32_I2C_V2_40007800_IRQ_ERROR #define DT_I2C_3_BITRATE DT_ST_STM32_I2C_V2_40007800_CLOCK_FREQUENCY #define DT_I2C_3_CLOCK_BITS DT_ST_STM32_I2C_V2_40007800_CLOCK_BITS #define DT_I2C_3_CLOCK_BUS DT_ST_STM32_I2C_V2_40007800_CLOCK_BUS #define DT_RTC_0_BASE_ADDRESS DT_ST_STM32_RTC_40002800_BASE_ADDRESS #define DT_RTC_0_IRQ_PRI DT_ST_STM32_RTC_40002800_IRQ_0_PRIORITY #define DT_RTC_0_IRQ DT_ST_STM32_RTC_40002800_IRQ_0 #define DT_RTC_0_NAME DT_ST_STM32_RTC_40002800_LABEL #define DT_RTC_0_CLOCK_BITS DT_ST_STM32_RTC_40002800_CLOCK_BITS #define DT_RTC_0_CLOCK_BUS DT_ST_STM32_RTC_40002800_CLOCK_BUS #define DT_SPI_1_BASE_ADDRESS DT_ST_STM32_SPI_FIFO_40013000_BASE_ADDRESS #define DT_SPI_1_IRQ_PRI DT_ST_STM32_SPI_FIFO_40013000_IRQ_0_PRIORITY #define DT_SPI_1_NAME DT_ST_STM32_SPI_FIFO_40013000_LABEL #define DT_SPI_1_IRQ DT_ST_STM32_SPI_FIFO_40013000_IRQ_0 #define DT_SPI_1_CLOCK_BITS DT_ST_STM32_SPI_FIFO_40013000_CLOCK_BITS #define DT_SPI_1_CLOCK_BUS DT_ST_STM32_SPI_FIFO_40013000_CLOCK_BUS #define DT_SPI_2_BASE_ADDRESS DT_ST_STM32_SPI_FIFO_40003800_BASE_ADDRESS #define DT_SPI_2_IRQ_PRI DT_ST_STM32_SPI_FIFO_40003800_IRQ_0_PRIORITY #define DT_SPI_2_NAME DT_ST_STM32_SPI_FIFO_40003800_LABEL #define DT_SPI_2_IRQ DT_ST_STM32_SPI_FIFO_40003800_IRQ_0 #define DT_SPI_2_CLOCK_BITS DT_ST_STM32_SPI_FIFO_40003800_CLOCK_BITS #define DT_SPI_2_CLOCK_BUS DT_ST_STM32_SPI_FIFO_40003800_CLOCK_BUS #define DT_SPI_3_BASE_ADDRESS DT_ST_STM32_SPI_FIFO_40003C00_BASE_ADDRESS #define DT_SPI_3_IRQ_PRI DT_ST_STM32_SPI_FIFO_40003C00_IRQ_0_PRIORITY #define DT_SPI_3_NAME DT_ST_STM32_SPI_FIFO_40003C00_LABEL #define DT_SPI_3_IRQ DT_ST_STM32_SPI_FIFO_40003C00_IRQ_0 #define DT_SPI_3_CLOCK_BITS DT_ST_STM32_SPI_FIFO_40003C00_CLOCK_BITS #define DT_SPI_3_CLOCK_BUS DT_ST_STM32_SPI_FIFO_40003C00_CLOCK_BUS #define DT_USB_BASE_ADDRESS DT_ST_STM32_USB_40005C00_BASE_ADDRESS #define DT_USB_IRQ DT_ST_STM32_USB_40005C00_IRQ_USB #define DT_USB_IRQ_PRI DT_ST_STM32_USB_40005C00_IRQ_USB_PRIORITY #define DT_USB_NUM_BIDIR_ENDPOINTS DT_ST_STM32_USB_40005C00_NUM_BIDIR_ENDPOINTS #define DT_USB_RAM_SIZE DT_ST_STM32_USB_40005C00_RAM_SIZE #define DT_USB_CLOCK_BITS DT_ST_STM32_USB_40005C00_CLOCK_BITS #define DT_USB_CLOCK_BUS DT_ST_STM32_USB_40005C00_CLOCK_BUS #define DT_PWM_STM32_1_DEV_NAME DT_ST_STM32_PWM_40012C00_PWM_LABEL #define DT_PWM_STM32_1_PRESCALER DT_ST_STM32_PWM_40012C00_PWM_ST_PRESCALER #define DT_TIM_STM32_1_BASE_ADDRESS DT_ST_STM32_TIMERS_40012C00_BASE_ADDRESS #define DT_TIM_STM32_1_CLOCK_BITS DT_ST_STM32_TIMERS_40012C00_CLOCK_BITS #define DT_TIM_STM32_1_CLOCK_BUS DT_ST_STM32_TIMERS_40012C00_CLOCK_BUS #define DT_PWM_STM32_2_DEV_NAME DT_ST_STM32_PWM_40000000_PWM_LABEL #define DT_PWM_STM32_2_PRESCALER DT_ST_STM32_PWM_40000000_PWM_ST_PRESCALER #define DT_TIM_STM32_2_BASE_ADDRESS DT_ST_STM32_TIMERS_40000000_BASE_ADDRESS #define DT_TIM_STM32_2_CLOCK_BITS DT_ST_STM32_TIMERS_40000000_CLOCK_BITS #define DT_TIM_STM32_2_CLOCK_BUS DT_ST_STM32_TIMERS_40000000_CLOCK_BUS #define DT_PWM_STM32_3_DEV_NAME DT_ST_STM32_PWM_40000400_PWM_LABEL #define DT_PWM_STM32_3_PRESCALER DT_ST_STM32_PWM_40000400_PWM_ST_PRESCALER #define DT_TIM_STM32_3_BASE_ADDRESS DT_ST_STM32_TIMERS_40000400_BASE_ADDRESS #define DT_TIM_STM32_3_CLOCK_BITS DT_ST_STM32_TIMERS_40000400_CLOCK_BITS #define DT_TIM_STM32_3_CLOCK_BUS DT_ST_STM32_TIMERS_40000400_CLOCK_BUS #define DT_PWM_STM32_4_DEV_NAME DT_ST_STM32_PWM_40000800_PWM_LABEL #define DT_PWM_STM32_4_PRESCALER DT_ST_STM32_PWM_40000800_PWM_ST_PRESCALER #define DT_TIM_STM32_4_BASE_ADDRESS DT_ST_STM32_TIMERS_40000800_BASE_ADDRESS #define DT_TIM_STM32_4_CLOCK_BITS DT_ST_STM32_TIMERS_40000800_CLOCK_BITS #define DT_TIM_STM32_4_CLOCK_BUS DT_ST_STM32_TIMERS_40000800_CLOCK_BUS #define DT_PWM_STM32_5_DEV_NAME DT_ST_STM32_PWM_40000C00_PWM_LABEL #define DT_PWM_STM32_5_PRESCALER DT_ST_STM32_PWM_40000C00_PWM_ST_PRESCALER #define DT_TIM_STM32_5_BASE_ADDRESS DT_ST_STM32_TIMERS_40000C00_BASE_ADDRESS #define DT_TIM_STM32_5_CLOCK_BITS DT_ST_STM32_TIMERS_40000C00_CLOCK_BITS #define DT_TIM_STM32_5_CLOCK_BUS DT_ST_STM32_TIMERS_40000C00_CLOCK_BUS #define DT_PWM_STM32_6_DEV_NAME DT_ST_STM32_PWM_40001000_PWM_LABEL #define DT_PWM_STM32_6_PRESCALER DT_ST_STM32_PWM_40001000_PWM_ST_PRESCALER #define DT_TIM_STM32_6_BASE_ADDRESS DT_ST_STM32_TIMERS_40001000_BASE_ADDRESS #define DT_TIM_STM32_6_CLOCK_BITS DT_ST_STM32_TIMERS_40001000_CLOCK_BITS #define DT_TIM_STM32_6_CLOCK_BUS DT_ST_STM32_TIMERS_40001000_CLOCK_BUS #define DT_PWM_STM32_7_DEV_NAME DT_ST_STM32_PWM_40001400_PWM_LABEL #define DT_PWM_STM32_7_PRESCALER DT_ST_STM32_PWM_40001400_PWM_ST_PRESCALER #define DT_TIM_STM32_7_BASE_ADDRESS DT_ST_STM32_TIMERS_40001400_BASE_ADDRESS #define DT_TIM_STM32_7_CLOCK_BITS DT_ST_STM32_TIMERS_40001400_CLOCK_BITS #define DT_TIM_STM32_7_CLOCK_BUS DT_ST_STM32_TIMERS_40001400_CLOCK_BUS #define DT_PWM_STM32_8_DEV_NAME DT_ST_STM32_PWM_40013400_PWM_LABEL #define DT_PWM_STM32_8_PRESCALER DT_ST_STM32_PWM_40013400_PWM_ST_PRESCALER #define DT_TIM_STM32_8_BASE_ADDRESS DT_ST_STM32_TIMERS_40013400_BASE_ADDRESS #define DT_TIM_STM32_8_CLOCK_BITS DT_ST_STM32_TIMERS_40013400_CLOCK_BITS #define DT_TIM_STM32_8_CLOCK_BUS DT_ST_STM32_TIMERS_40013400_CLOCK_BUS #define DT_PWM_STM32_15_DEV_NAME DT_ST_STM32_PWM_40014000_PWM_LABEL #define DT_PWM_STM32_15_PRESCALER DT_ST_STM32_PWM_40014000_PWM_ST_PRESCALER #define DT_TIM_STM32_15_BASE_ADDRESS DT_ST_STM32_TIMERS_40014000_BASE_ADDRESS #define DT_TIM_STM32_15_CLOCK_BITS DT_ST_STM32_TIMERS_40014000_CLOCK_BITS #define DT_TIM_STM32_15_CLOCK_BUS DT_ST_STM32_TIMERS_40014000_CLOCK_BUS #define DT_PWM_STM32_16_DEV_NAME DT_ST_STM32_PWM_40014400_PWM_LABEL #define DT_PWM_STM32_16_PRESCALER DT_ST_STM32_PWM_40014400_PWM_ST_PRESCALER #define DT_TIM_STM32_16_BASE_ADDRESS DT_ST_STM32_TIMERS_40014400_BASE_ADDRESS #define DT_TIM_STM32_16_CLOCK_BITS DT_ST_STM32_TIMERS_40014400_CLOCK_BITS #define DT_TIM_STM32_16_CLOCK_BUS DT_ST_STM32_TIMERS_40014400_CLOCK_BUS #define DT_PWM_STM32_17_DEV_NAME DT_ST_STM32_PWM_40014800_PWM_LABEL #define DT_PWM_STM32_17_PRESCALER DT_ST_STM32_PWM_40014800_PWM_ST_PRESCALER #define DT_TIM_STM32_17_BASE_ADDRESS DT_ST_STM32_TIMERS_40014800_BASE_ADDRESS #define DT_TIM_STM32_17_CLOCK_BITS DT_ST_STM32_TIMERS_40014800_CLOCK_BITS #define DT_TIM_STM32_17_CLOCK_BUS DT_ST_STM32_TIMERS_40014800_CLOCK_BUS #define DT_WDT_0_NAME DT_INST_0_ST_STM32_WATCHDOG_LABEL #define DT_WWDT_0_BASE_ADDRESS DT_INST_0_ST_STM32_WINDOW_WATCHDOG_BASE_ADDRESS #define DT_WWDT_0_NAME DT_INST_0_ST_STM32_WINDOW_WATCHDOG_LABEL #define DT_WWDT_0_IRQ DT_INST_0_ST_STM32_WINDOW_WATCHDOG_IRQ_0 #define DT_WWDT_0_IRQ_PRI DT_INST_0_ST_STM32_WINDOW_WATCHDOG_IRQ_0_PRIORITY #define DT_WWDT_0_CLOCK_BITS DT_INST_0_ST_STM32_WINDOW_WATCHDOG_CLOCK_BITS #define DT_WWDT_0_CLOCK_BUS DT_INST_0_ST_STM32_WINDOW_WATCHDOG_CLOCK_BUS /* End of SoC Level DTS fixup file */
torsteingrindvik/fw-nrfconnect-zephyr
arch/x86/include/ia32/kernel_arch_thread.h
<reponame>torsteingrindvik/fw-nrfconnect-zephyr<filename>arch/x86/include/ia32/kernel_arch_thread.h<gh_stars>0 /* * Copyright (c) 2017 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ /** * @file * @brief Per-arch thread definition * * This file contains definitions for * * struct _thread_arch * struct _callee_saved * * necessary to instantiate instances of struct k_thread. */ #ifndef ZEPHYR_ARCH_X86_INCLUDE_IA32_KERNEL_ARCH_THREAD_H_ #define ZEPHYR_ARCH_X86_INCLUDE_IA32_KERNEL_ARCH_THREAD_H_ /** * Floating point register set alignment. * * If support for SSEx extensions is enabled a 16 byte boundary is required, * since the 'fxsave' and 'fxrstor' instructions require this. In all other * cases a 4 byte boundary is sufficient. */ #ifdef CONFIG_SSE #define FP_REG_SET_ALIGN 16 #else #define FP_REG_SET_ALIGN 4 #endif /* * Bits for _thread_arch.flags, see their use in intstub.S et al. */ #define X86_THREAD_FLAG_INT 0x01 #define X86_THREAD_FLAG_EXC 0x02 #define X86_THREAD_FLAG_ALL (X86_THREAD_FLAG_INT | X86_THREAD_FLAG_EXC) #ifndef _ASMLANGUAGE #include <stdint.h> #include <arch/x86/mmustructs.h> /* * The following structure defines the set of 'non-volatile' integer registers. * These registers must be preserved by a called C function. These are the * only registers that need to be saved/restored when a cooperative context * switch occurs. */ struct _callee_saved { unsigned long esp; /* * The following registers are considered non-volatile, i.e. * callee-save, * but their values are pushed onto the stack rather than stored in the * TCS * structure: * * unsigned long ebp; * unsigned long ebx; * unsigned long esi; * unsigned long edi; */ }; typedef struct _callee_saved _callee_saved_t; /* * The macros CONFIG_{LAZY|EAGER}_FP_SHARING shall be set to indicate that the * saving/restoring of the traditional x87 floating point (and MMX) registers * are supported by the kernel's context swapping code. The macro * CONFIG_SSE shall _also_ be set if saving/restoring of the XMM * registers is also supported in the kernel's context swapping code. */ #if defined(CONFIG_EAGER_FP_SHARING) || defined(CONFIG_LAZY_FP_SHARING) /* definition of a single x87 (floating point / MMX) register */ typedef struct s_FpReg { unsigned char reg[10]; /* 80 bits: ST[0-7] */ } tFpReg; /* * The following is the "normal" floating point register save area, or * more accurately the save area required by the 'fnsave' and 'frstor' * instructions. The structure matches the layout described in the * "Intel(r) 64 and IA-32 Architectures Software Developer's Manual * Volume 1: Basic Architecture": Protected Mode x87 FPU State Image in * Memory, 32-Bit Format. */ typedef struct s_FpRegSet { /* # of bytes: name of register */ unsigned short fcw; /* 2 : x87 FPU control word */ unsigned short pad1; /* 2 : N/A */ unsigned short fsw; /* 2 : x87 FPU status word */ unsigned short pad2; /* 2 : N/A */ unsigned short ftw; /* 2 : x87 FPU tag word */ unsigned short pad3; /* 2 : N/A */ unsigned int fpuip; /* 4 : x87 FPU instruction pointer offset */ unsigned short cs; /* 2 : x87 FPU instruction pointer selector */ unsigned short fop : 11; /* 2 : x87 FPU opcode */ unsigned short pad4 : 5; /* : 5 bits = 00000 */ unsigned int fpudp; /* 4 : x87 FPU instr operand ptr offset */ unsigned short ds; /* 2 : x87 FPU instr operand ptr selector */ unsigned short pad5; /* 2 : N/A */ tFpReg fpReg[8]; /* 80 : ST0 -> ST7 */ } tFpRegSet __aligned(FP_REG_SET_ALIGN); #ifdef CONFIG_SSE /* definition of a single x87 (floating point / MMX) register */ typedef struct s_FpRegEx { unsigned char reg[10]; /* 80 bits: ST[0-7] or MM[0-7] */ unsigned char rsrvd[6]; /* 48 bits: reserved */ } tFpRegEx; /* definition of a single XMM register */ typedef struct s_XmmReg { unsigned char reg[16]; /* 128 bits: XMM[0-7] */ } tXmmReg; /* * The following is the "extended" floating point register save area, or * more accurately the save area required by the 'fxsave' and 'fxrstor' * instructions. The structure matches the layout described in the * "Intel 64 and IA-32 Architectures Software Developer's Manual * Volume 2A: Instruction Set Reference, A-M", except for the bytes from offset * 464 to 511 since these "are available to software use. The processor does * not write to bytes 464:511 of an FXSAVE area". * * This structure must be aligned on a 16 byte boundary when the instructions * fxsave/fxrstor are used to write/read the data to/from the structure. */ typedef struct s_FpRegSetEx /* # of bytes: name of register */ { unsigned short fcw; /* 2 : x87 FPU control word */ unsigned short fsw; /* 2 : x87 FPU status word */ unsigned char ftw; /* 1 : x87 FPU abridged tag word */ unsigned char rsrvd0; /* 1 : reserved */ unsigned short fop; /* 2 : x87 FPU opcode */ unsigned int fpuip; /* 4 : x87 FPU instruction pointer offset */ unsigned short cs; /* 2 : x87 FPU instruction pointer selector */ unsigned short rsrvd1; /* 2 : reserved */ unsigned int fpudp; /* 4 : x87 FPU instr operand ptr offset */ unsigned short ds; /* 2 : x87 FPU instr operand ptr selector */ unsigned short rsrvd2; /* 2 : reserved */ unsigned int mxcsr; /* 4 : MXCSR register state */ unsigned int mxcsrMask; /* 4 : MXCSR register mask */ tFpRegEx fpReg[8]; /* 128 : x87 FPU/MMX registers */ tXmmReg xmmReg[8]; /* 128 : XMM registers */ unsigned char rsrvd3[176]; /* 176 : reserved */ } tFpRegSetEx __aligned(FP_REG_SET_ALIGN); #else /* CONFIG_SSE == 0 */ typedef struct s_FpRegSetEx { } tFpRegSetEx; #endif /* CONFIG_SSE == 0 */ #else /* !CONFIG_LAZY_FP_SHARING && !CONFIG_EAGER_FP_SHARING */ /* empty floating point register definition */ typedef struct s_FpRegSet { } tFpRegSet; typedef struct s_FpRegSetEx { } tFpRegSetEx; #endif /* CONFIG_LAZY_FP_SHARING || CONFIG_EAGER_FP_SHARING */ /* * The following structure defines the set of 'volatile' x87 FPU/MMX/SSE * registers. These registers need not be preserved by a called C function. * Given that they are not preserved across function calls, they must be * save/restored (along with s_coopFloatReg) when a preemptive context * switch occurs. */ typedef struct s_preempFloatReg { union { /* threads with K_FP_REGS utilize this format */ tFpRegSet fpRegs; /* threads with K_SSE_REGS utilize this format */ tFpRegSetEx fpRegsEx; } floatRegsUnion; } tPreempFloatReg; /* * The thread control structure definition. It contains the * various fields to manage a _single_ thread. The TCS will be aligned * to the appropriate architecture specific boundary via the * z_arch_new_thread() call. */ struct _thread_arch { u8_t flags; #if defined(CONFIG_LAZY_FP_SHARING) /* * Nested exception count to maintain setting of EXC_ACTIVE flag across * outermost exception. EXC_ACTIVE is used by z_swap() lazy FP * save/restore and by debug tools. */ unsigned excNestCount; /* nested exception count */ #endif /* CONFIG_LAZY_FP_SHARING */ /* * The location of all floating point related structures/fields MUST be * located at the end of struct k_thread. This way only the * threads that actually utilize non-integer capabilities need to * account for the increased memory required for storing FP state when * sizing stacks. * * Given that stacks "grow down" on IA-32, and the TCS is located * at the start of a thread's "workspace" memory, the stacks of * threads that do not utilize floating point instruction can * effectively consume the memory occupied by the 'tPreempFloatReg' * struct without ill effect. */ tPreempFloatReg preempFloatReg; /* volatile float register storage */ #ifdef CONFIG_USERSPACE /* Per-thread page directory pointer table when a thread is running * in user mode. * * With KPTI enabled, any privilege elevation while that thread is * running, or ISR will switch to the master kernel pdpt at * z_x86_kernel_pdpt; the memory domain policy will not apply at * all. * * With KPTI disabled, this pdpt will be active at all times when * the thread is running. This has implications for memory domain * partitions that are read-only!! * * See #17833 for more discussion. */ __aligned(0x20) struct x86_mmu_pdpt user_pdpt; #endif /* CONFIG_USERSPACE */ }; typedef struct _thread_arch _thread_arch_t; #endif /* _ASMLANGUAGE */ #endif /* ZEPHYR_ARCH_X86_INCLUDE_IA32_KERNEL_ARCH_THREAD_H_ */
torsteingrindvik/fw-nrfconnect-zephyr
lib/updatehub/updatehub.c
<reponame>torsteingrindvik/fw-nrfconnect-zephyr /* * Copyright (c) 2018, 2019 O.S.Systems * * SPDX-License-Identifier: Apache-2.0 */ #include <logging/log.h> LOG_MODULE_REGISTER(updatehub); #include <zephyr.h> #include <logging/log_ctrl.h> #include <net/socket.h> #include <net/net_mgmt.h> #include <net/net_ip.h> #include <net/udp.h> #include <net/coap.h> #include <net/dns_resolve.h> #include <drivers/flash.h> #include <power/reboot.h> #include <tinycrypt/sha256.h> #include <data/json.h> #include <updatehub.h> #include "updatehub_priv.h" #include "updatehub_firmware.h" #include "updatehub_device.h" #if defined(CONFIG_UPDATEHUB_DTLS) #define CA_CERTIFICATE_TAG 1 #include <net/tls_credentials.h> #endif #define NETWORK_TIMEOUT K_SECONDS(2) #define UPDATEHUB_POLL_INTERVAL K_MINUTES(CONFIG_UPDATEHUB_POLL_INTERVAL) #define MAX_PATH_SIZE 255 #define MAX_PAYLOAD_SIZE 500 #define MAX_DOWNLOAD_DATA 1100 #define COAP_MAX_RETRY 3 #define MAX_IP_SIZE 30 #if defined(CONFIG_UPDATEHUB_CE) #define UPDATEHUB_SERVER CONFIG_UPDATEHUB_SERVER #else #define UPDATEHUB_SERVER "coap.updatehub.io" #endif static struct updatehub_context { struct coap_block_context block; struct k_sem semaphore; struct flash_img_context flash_ctx; struct tc_sha256_state_struct sha256sum; enum updatehub_response code_status; u8_t uri_path[MAX_PATH_SIZE]; u8_t payload[MAX_PAYLOAD_SIZE]; int downloaded_size; struct pollfd fds[1]; int sock; int nfds; } ctx; static struct update_info { char package_uid[TC_SHA256_BLOCK_SIZE + 1]; char sha256sum_image[TC_SHA256_BLOCK_SIZE + 1]; int image_size; } update_info; static void wait_fds(void) { if (poll(ctx.fds, ctx.nfds, NETWORK_TIMEOUT) < 0) { LOG_ERR("Error in poll"); } } static void prepare_fds(void) { ctx.fds[ctx.nfds].fd = ctx.sock; ctx.fds[ctx.nfds].events = 1; ctx.nfds++; } static int metadata_hash_get(char *metadata) { struct tc_sha256_state_struct sha256sum; unsigned char hash[TC_SHA256_DIGEST_SIZE]; char buffer[3]; int buffer_len = 0; if (tc_sha256_init(&sha256sum) == 0) { return -1; } if (tc_sha256_update(&sha256sum, metadata, strlen(metadata)) == 0) { return -1; } if (tc_sha256_final(hash, &sha256sum) == 0) { return -1; } memset(update_info.package_uid, 0, TC_SHA256_BLOCK_SIZE + 1); for (int i = 0; i < TC_SHA256_DIGEST_SIZE; i++) { snprintk(buffer, sizeof(buffer), "%02x", hash[i]); buffer_len = buffer_len + strlen(buffer); strncat(&update_info.package_uid[i], buffer, MIN(TC_SHA256_BLOCK_SIZE, buffer_len)); } return 0; } static bool is_compatible_hardware(struct resp_probe_some_boards *metadata_some_boards) { int i; for (i = 0; i < metadata_some_boards->supported_hardware_len; i++) { if (strncmp(metadata_some_boards->supported_hardware[i], CONFIG_BOARD, strlen(CONFIG_BOARD)) == 0) { return true; } } return false; } static bool start_coap_client(void) { struct addrinfo *addr; struct addrinfo hints; int resolve_attempts = 10; int ret = -1; if (IS_ENABLED(CONFIG_NET_IPV6)) { hints.ai_family = AF_INET6; hints.ai_socktype = SOCK_STREAM; } else if (IS_ENABLED(CONFIG_NET_IPV4)) { hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; } #if defined(CONFIG_UPDATEHUB_DTLS) int verify = 0; sec_tag_t sec_list[] = { CA_CERTIFICATE_TAG }; int protocol = IPPROTO_DTLS_1_2; char port[] = "5684"; #else int protocol = IPPROTO_UDP; char port[] = "5683"; #endif while (resolve_attempts--) { ret = getaddrinfo(UPDATEHUB_SERVER, port, &hints, &addr); if (ret == 0) { break; } k_sleep(K_SECONDS(1)); } if (ret < 0) { LOG_ERR("Could not resolve dns"); return false; } ctx.sock = socket(addr->ai_family, SOCK_DGRAM, protocol); if (ctx.sock < 0) { LOG_ERR("Failed to create UDP socket"); return false; } #if defined(CONFIG_UPDATEHUB_DTLS) if (setsockopt(ctx.sock, SOL_TLS, TLS_SEC_TAG_LIST, sec_list, sizeof(sec_list)) < 0) { LOG_ERR("Failed to set TLS_TAG option"); return false; } if (setsockopt(ctx.sock, SOL_TLS, TLS_PEER_VERIFY, &verify, sizeof(int)) < 0) { LOG_ERR("Failed to set TLS_PEER_VERIFY option"); return false; } #endif if (connect(ctx.sock, addr->ai_addr, addr->ai_addrlen) < 0) { LOG_ERR("Cannot connect to UDP remote"); return false; } prepare_fds(); return true; } static void cleanup_connection(void) { if (close(ctx.sock) < 0) { LOG_ERR("Could not close the socket"); } memset(&ctx.fds[1], 0, sizeof(ctx.fds[1])); ctx.nfds = 0; ctx.sock = 0; } static int send_request(enum coap_msgtype msgtype, enum coap_method method, enum updatehub_uri_path type) { struct coap_packet request_packet; int ret = -1; u8_t content_application_json = 50; u8_t *data = k_malloc(MAX_PAYLOAD_SIZE); if (data == NULL) { LOG_ERR("Could not alloc data memory"); goto error; } ret = coap_packet_init(&request_packet, data, MAX_PAYLOAD_SIZE, 1, COAP_TYPE_CON, 8, coap_next_token(), method, coap_next_id()); if (ret < 0) { LOG_ERR("Could not init packet"); goto error; } switch (method) { case COAP_METHOD_GET: snprintk(ctx.uri_path, MAX_PATH_SIZE, "%s/%s/packages/%s/objects/%s", uri_path(type), CONFIG_UPDATEHUB_PRODUCT_UID, update_info.package_uid, update_info.sha256sum_image); ret = coap_packet_append_option(&request_packet, COAP_OPTION_URI_PATH, ctx.uri_path, strlen(ctx.uri_path)); if (ret < 0) { LOG_ERR("Unable add option to request path"); goto error; } ret = coap_append_block2_option(&request_packet, &ctx.block); if (ret < 0) { LOG_ERR("Unable coap append block 2"); goto error; } ret = coap_packet_append_option(&request_packet, 2048, UPDATEHUB_API_HEADER, strlen(UPDATEHUB_API_HEADER)); if (ret < 0) { LOG_ERR("Unable add option to add updatehub header"); goto error; } break; case COAP_METHOD_POST: ret = coap_packet_append_option(&request_packet, COAP_OPTION_URI_PATH, uri_path(type), strlen(uri_path(type))); if (ret < 0) { LOG_ERR("Unable add option to request path"); goto error; } ret = coap_packet_append_option(&request_packet, COAP_OPTION_CONTENT_FORMAT, &content_application_json, sizeof(content_application_json)); if (ret < 0) { LOG_ERR("Unable add option to request format"); goto error; } ret = coap_packet_append_option(&request_packet, 2048, UPDATEHUB_API_HEADER, strlen(UPDATEHUB_API_HEADER)); if (ret < 0) { LOG_ERR("Unable add option to add updatehub header"); goto error; } ret = coap_packet_append_payload_marker(&request_packet); if (ret < 0) { LOG_ERR("Unable to append payload marker"); goto error; } ret = coap_packet_append_payload(&request_packet, &ctx.payload, strlen(ctx.payload)); if (ret < 0) { LOG_ERR("Not able to append payload"); goto error; } break; default: LOG_ERR("Invalid method"); ret = -1; goto error; } ret = send(ctx.sock, request_packet.data, request_packet.offset, 0); if (ret < 0) { LOG_ERR("Could not send request"); goto error; } error: k_free(data); return ret; } static void install_update_cb(void) { struct coap_packet response_packet; char buffer[3], sha256_image_dowloaded[TC_SHA256_BLOCK_SIZE + 1]; u8_t *data = k_malloc(MAX_DOWNLOAD_DATA); int i, buffer_len = 0; int rcvd = -1; if (data == NULL) { LOG_ERR("Could not alloc data memory"); ctx.code_status = UPDATEHUB_DOWNLOAD_ERROR; goto cleanup; } wait_fds(); rcvd = recv(ctx.sock, data, MAX_DOWNLOAD_DATA, MSG_DONTWAIT); if (rcvd <= 0) { ctx.code_status = UPDATEHUB_NETWORKING_ERROR; LOG_ERR("Could not receive data"); goto cleanup; } if (coap_packet_parse(&response_packet, data, rcvd, NULL, 0) < 0) { LOG_ERR("Invalid data received"); ctx.code_status = UPDATEHUB_DOWNLOAD_ERROR; goto cleanup; } ctx.downloaded_size = ctx.downloaded_size + (response_packet.max_len - response_packet.offset); if (tc_sha256_update(&ctx.sha256sum, response_packet.data + response_packet.offset, response_packet.max_len - response_packet.offset) < 1) { LOG_ERR("Could not update sha256sum"); ctx.code_status = UPDATEHUB_DOWNLOAD_ERROR; goto cleanup; } if (flash_img_buffered_write(&ctx.flash_ctx, response_packet.data + response_packet.offset, response_packet.max_len - response_packet.offset, ctx.downloaded_size == ctx.block.total_size) < 0) { LOG_ERR("Error to write on the flash"); ctx.code_status = UPDATEHUB_INSTALL_ERROR; goto cleanup; } if (coap_update_from_block(&response_packet, &ctx.block) < 0) { ctx.code_status = UPDATEHUB_DOWNLOAD_ERROR; goto cleanup; } if (coap_next_block(&response_packet, &ctx.block) == 0) { LOG_ERR("Could not get the next"); ctx.code_status = UPDATEHUB_DOWNLOAD_ERROR; goto cleanup; } if (ctx.downloaded_size == ctx.block.total_size) { u8_t image_hash[TC_SHA256_DIGEST_SIZE]; if (tc_sha256_final(image_hash, &ctx.sha256sum) < 1) { LOG_ERR("Could not finish sha256sum"); ctx.code_status = UPDATEHUB_DOWNLOAD_ERROR; goto cleanup; } memset(&sha256_image_dowloaded, 0, TC_SHA256_BLOCK_SIZE + 1); for (i = 0; i < TC_SHA256_DIGEST_SIZE; i++) { snprintk(buffer, sizeof(buffer), "%02x", image_hash[i]); buffer_len = buffer_len + strlen(buffer); strncat(&sha256_image_dowloaded[i], buffer, MIN(TC_SHA256_BLOCK_SIZE, buffer_len)); } if (strncmp(sha256_image_dowloaded, update_info.sha256sum_image, strlen(update_info.sha256sum_image)) != 0) { LOG_ERR("SHA256SUM of image are not the same"); ctx.code_status = UPDATEHUB_DOWNLOAD_ERROR; goto cleanup; } } ctx.code_status = UPDATEHUB_OK; cleanup: k_free(data); } static enum updatehub_response install_update(void) { int verification_download = 0; int attempts_download = 0; if (boot_erase_img_bank(DT_FLASH_AREA_IMAGE_1_ID) != 0) { LOG_ERR("Failed to init flash and erase second slot"); ctx.code_status = UPDATEHUB_FLASH_INIT_ERROR; goto error; } if (tc_sha256_init(&ctx.sha256sum) < 1) { LOG_ERR("Could not start sha256sum"); ctx.code_status = UPDATEHUB_DOWNLOAD_ERROR; goto error; } if (!start_coap_client()) { ctx.code_status = UPDATEHUB_NETWORKING_ERROR; goto error; } if (coap_block_transfer_init(&ctx.block, COAP_BLOCK_1024, update_info.image_size) < 0) { LOG_ERR("Unable init block transfer"); ctx.code_status = UPDATEHUB_NETWORKING_ERROR; goto cleanup; } flash_img_init(&ctx.flash_ctx); ctx.downloaded_size = 0; while (ctx.downloaded_size != ctx.block.total_size) { verification_download = ctx.downloaded_size; if (send_request(COAP_TYPE_CON, COAP_METHOD_GET, UPDATEHUB_DOWNLOAD) < 0) { ctx.code_status = UPDATEHUB_NETWORKING_ERROR; goto cleanup; } install_update_cb(); if (ctx.code_status != UPDATEHUB_OK) { goto cleanup; } if (verification_download == ctx.downloaded_size) { if (attempts_download == COAP_MAX_RETRY) { LOG_ERR("Could not get the packet"); ctx.code_status = UPDATEHUB_DOWNLOAD_ERROR; goto cleanup; } attempts_download++; } } cleanup: cleanup_connection(); error: ctx.downloaded_size = 0; return ctx.code_status; } static int report(enum updatehub_state state) { struct report report; int ret = -1; const char *exec = state_name(state); char *device_id = k_malloc(DEVICE_ID_MAX_SIZE); char *firmware_version = k_malloc(BOOT_IMG_VER_STRLEN_MAX); if (device_id == NULL || firmware_version == NULL) { LOG_ERR("Could not alloc device_id or firmware_version memory"); goto error; } if (!updatehub_get_device_identity(device_id, DEVICE_ID_MAX_SIZE)) { goto error; } if (!updatehub_get_firmware_version(firmware_version, BOOT_IMG_VER_STRLEN_MAX)) { goto error; } memset(&report, 0, sizeof(report)); report.product_uid = CONFIG_UPDATEHUB_PRODUCT_UID; report.device_identity.id = device_id; report.version = firmware_version; report.hardware = CONFIG_BOARD; report.status = exec; report.package_uid = update_info.package_uid; switch (ctx.code_status) { case UPDATEHUB_INSTALL_ERROR: report.previous_state = state_name(UPDATEHUB_STATE_INSTALLING); break; case UPDATEHUB_DOWNLOAD_ERROR: report.previous_state = state_name(UPDATEHUB_STATE_DOWNLOADING); break; case UPDATEHUB_FLASH_INIT_ERROR: report.previous_state = state_name(UPDATEHUB_FLASH_INIT_ERROR); break; default: report.previous_state = ""; break; } if (strncmp(report.previous_state, "", sizeof("") - 1) != 0) { report.error_message = updatehub_response(ctx.code_status); } else { report.error_message = ""; } memset(&ctx.payload, 0, MAX_PAYLOAD_SIZE); ret = json_obj_encode_buf(send_report_descr, ARRAY_SIZE(send_report_descr), &report, ctx.payload, MAX_PAYLOAD_SIZE - 1); if (ret < 0) { LOG_ERR("Could not encode metadata"); goto error; } if (!start_coap_client()) { goto error; } ret = send_request(COAP_TYPE_NON_CON, COAP_METHOD_POST, UPDATEHUB_REPORT); if (ret < 0) { goto cleanup; } wait_fds(); cleanup: cleanup_connection(); error: k_free(firmware_version); k_free(device_id); return ret; } static void probe_cb(char *metadata) { struct coap_packet reply; char tmp[MAX_PAYLOAD_SIZE]; int rcvd = -1; wait_fds(); rcvd = recv(ctx.sock, metadata, MAX_PAYLOAD_SIZE, MSG_DONTWAIT); if (rcvd <= 0) { LOG_ERR("Could not receive data"); ctx.code_status = UPDATEHUB_NETWORKING_ERROR; return; } if (coap_packet_parse(&reply, metadata, rcvd, NULL, 0) < 0) { LOG_ERR("Invalid data received"); ctx.code_status = UPDATEHUB_DOWNLOAD_ERROR; return; } if (COAP_RESPONSE_CODE_NOT_FOUND == coap_header_get_code(&reply)) { LOG_INF("No update available"); ctx.code_status = UPDATEHUB_NO_UPDATE; return; } memset(&tmp, 0, MAX_PAYLOAD_SIZE); memcpy(tmp, reply.data + reply.offset, reply.max_len - reply.offset); memset(metadata, 0, MAX_PAYLOAD_SIZE); memcpy(metadata, tmp, strlen(tmp)); ctx.code_status = UPDATEHUB_OK; LOG_INF("Probe metadata received"); } enum updatehub_response updatehub_probe(void) { struct probe request; struct resp_probe_some_boards metadata_some_boards; struct resp_probe_any_boards metadata_any_boards; char *metadata = k_malloc(MAX_PAYLOAD_SIZE); char *metadata_copy = k_malloc(MAX_PAYLOAD_SIZE); char *device_id = k_malloc(DEVICE_ID_MAX_SIZE); char *firmware_version = k_malloc(BOOT_IMG_VER_STRLEN_MAX); if (device_id == NULL || firmware_version == NULL || metadata == NULL || metadata_copy == NULL) { LOG_ERR("Could not alloc probe memory"); ctx.code_status = UPDATEHUB_METADATA_ERROR; goto error; } k_sem_init(&ctx.semaphore, 0, 1); if (!boot_is_img_confirmed()) { LOG_ERR("The current image is not confirmed"); ctx.code_status = UPDATEHUB_UNCONFIRMED_IMAGE; goto error; } if (!updatehub_get_firmware_version(firmware_version, BOOT_IMG_VER_STRLEN_MAX)) { ctx.code_status = UPDATEHUB_METADATA_ERROR; goto error; } if (!updatehub_get_device_identity(device_id, DEVICE_ID_MAX_SIZE)) { ctx.code_status = UPDATEHUB_METADATA_ERROR; goto error; } memset(&request, 0, sizeof(request)); request.product_uid = CONFIG_UPDATEHUB_PRODUCT_UID; request.device_identity.id = device_id; request.version = firmware_version; request.hardware = CONFIG_BOARD; memset(&ctx.payload, 0, MAX_PAYLOAD_SIZE); if (json_obj_encode_buf(send_probe_descr, ARRAY_SIZE(send_probe_descr), &request, ctx.payload, MAX_PAYLOAD_SIZE - 1) < 0) { LOG_ERR("Could not encode metadata"); ctx.code_status = UPDATEHUB_METADATA_ERROR; goto error; } if (!start_coap_client()) { ctx.code_status = UPDATEHUB_NETWORKING_ERROR; goto error; } if (send_request(COAP_TYPE_CON, COAP_METHOD_POST, UPDATEHUB_PROBE) < 0) { ctx.code_status = UPDATEHUB_NETWORKING_ERROR; goto cleanup; } memset(metadata, 0, MAX_PAYLOAD_SIZE); probe_cb(metadata); if (ctx.code_status != UPDATEHUB_OK) { goto cleanup; } memset(&update_info, 0, sizeof(update_info)); if (metadata_hash_get(metadata) < 0) { LOG_ERR("Could not get metadata hash"); ctx.code_status = UPDATEHUB_METADATA_ERROR; goto cleanup; } memcpy(metadata_copy, metadata, strlen(metadata)); if (json_obj_parse(metadata, strlen(metadata), recv_probe_sh_array_descr, ARRAY_SIZE(recv_probe_sh_array_descr), &metadata_some_boards) < 0) { if (json_obj_parse(metadata_copy, strlen(metadata_copy), recv_probe_sh_string_descr, ARRAY_SIZE(recv_probe_sh_string_descr), &metadata_any_boards) < 0) { LOG_ERR("Could not parse json"); ctx.code_status = UPDATEHUB_METADATA_ERROR; goto cleanup; } memcpy(update_info.sha256sum_image, metadata_any_boards.objects[1].objects.sha256sum, strlen(metadata_any_boards.objects[1].objects.sha256sum)); update_info.image_size = metadata_any_boards.objects[1].objects.size; } else { if (!is_compatible_hardware(&metadata_some_boards)) { LOG_ERR("Incompatible hardware"); ctx.code_status = UPDATEHUB_INCOMPATIBLE_HARDWARE; goto cleanup; } memcpy(update_info.sha256sum_image, metadata_some_boards.objects[1].objects.sha256sum, strlen(metadata_some_boards.objects[1] .objects.sha256sum)); update_info.image_size = metadata_some_boards.objects[1].objects.size; } ctx.code_status = UPDATEHUB_HAS_UPDATE; cleanup: cleanup_connection(); error: k_free(metadata); k_free(metadata_copy); k_free(firmware_version); k_free(device_id); return ctx.code_status; } enum updatehub_response updatehub_update(void) { if (report(UPDATEHUB_STATE_DOWNLOADING) < 0) { LOG_ERR("Could not reporting downloading state"); goto error; } if (report(UPDATEHUB_STATE_INSTALLING) < 0) { LOG_ERR("Could not reporting installing state"); goto error; } if (install_update() != UPDATEHUB_OK) { goto error; } if (report(UPDATEHUB_STATE_DOWNLOADED) < 0) { LOG_ERR("Could not reporting downloaded state"); goto error; } if (report(UPDATEHUB_STATE_INSTALLED) < 0) { LOG_ERR("Could not reporting installed state"); goto error; } if (report(UPDATEHUB_STATE_REBOOTING) < 0) { LOG_ERR("Could not reporting rebooting state"); goto error; } LOG_INF("Image flashed successfully, you can reboot now"); return ctx.code_status; error: if (ctx.code_status != UPDATEHUB_NETWORKING_ERROR) { if (report(UPDATEHUB_STATE_ERROR) < 0) { LOG_ERR("Could not reporting error state"); } } return ctx.code_status; } static void autohandler(struct k_delayed_work *work) { switch (updatehub_probe()) { case UPDATEHUB_UNCONFIRMED_IMAGE: LOG_ERR("Image is unconfirmed. Rebooting to revert back to previous" "confirmed image."); sys_reboot(SYS_REBOOT_WARM); break; case UPDATEHUB_HAS_UPDATE: switch (updatehub_update()) { case UPDATEHUB_OK: sys_reboot(SYS_REBOOT_WARM); break; default: break; } break; case UPDATEHUB_NO_UPDATE: break; default: break; } k_delayed_work_submit(work, UPDATEHUB_POLL_INTERVAL); } void updatehub_autohandler(void) { static struct k_delayed_work work; k_delayed_work_init(&work, autohandler); k_delayed_work_submit(&work, K_NO_WAIT); }
torsteingrindvik/fw-nrfconnect-zephyr
kernel/include/kernel_internal.h
<gh_stars>0 /* * Copyright (c) 2010-2012, 2014-2015 Wind River Systems, Inc. * * SPDX-License-Identifier: Apache-2.0 */ /** * @file * @brief Architecture-independent private kernel APIs * * This file contains private kernel APIs that are not architecture-specific. */ #ifndef ZEPHYR_KERNEL_INCLUDE_KERNEL_INTERNAL_H_ #define ZEPHYR_KERNEL_INCLUDE_KERNEL_INTERNAL_H_ #include <kernel.h> #include <stdbool.h> #ifndef _ASMLANGUAGE #ifdef __cplusplus extern "C" { #endif /* Early boot functions */ void z_bss_zero(void); #ifdef CONFIG_XIP void z_data_copy(void); #else static inline void z_data_copy(void) { /* Do nothing */ } #endif FUNC_NORETURN void z_cstart(void); extern FUNC_NORETURN void z_thread_entry(k_thread_entry_t entry, void *p1, void *p2, void *p3); /* Implemented by architectures. Only called from z_setup_new_thread. */ extern void z_arch_new_thread(struct k_thread *thread, k_thread_stack_t *pStack, size_t stackSize, k_thread_entry_t entry, void *p1, void *p2, void *p3, int prio, unsigned int options); extern void z_setup_new_thread(struct k_thread *new_thread, k_thread_stack_t *stack, size_t stack_size, k_thread_entry_t entry, void *p1, void *p2, void *p3, int prio, u32_t options, const char *name); #if defined(CONFIG_FLOAT) && defined(CONFIG_FP_SHARING) extern int z_arch_float_disable(struct k_thread *thread); #endif /* CONFIG_FLOAT && CONFIG_FP_SHARING */ #ifdef CONFIG_USERSPACE extern int z_arch_mem_domain_max_partitions_get(void); extern void z_arch_mem_domain_thread_add(struct k_thread *thread); extern void z_arch_mem_domain_thread_remove(struct k_thread *thread); extern void z_arch_mem_domain_partition_remove(struct k_mem_domain *domain, u32_t partition_id); extern void z_arch_mem_domain_partition_add(struct k_mem_domain *domain, u32_t partition_id); extern void z_arch_mem_domain_destroy(struct k_mem_domain *domain); extern int z_arch_buffer_validate(void *addr, size_t size, int write); extern FUNC_NORETURN void z_arch_user_mode_enter(k_thread_entry_t user_entry, void *p1, void *p2, void *p3); extern FUNC_NORETURN void z_arch_syscall_oops(void *ssf); extern size_t z_arch_user_string_nlen(const char *s, size_t maxsize, int *err); /** * @brief Zero out BSS sections for application shared memory * * This isn't handled by any platform bss zeroing, and is called from * z_cstart() if userspace is enabled. */ extern void z_app_shmem_bss_zero(void); #endif /* CONFIG_USERSPACE */ /** * @brief Allocate some memory from the current thread's resource pool * * Threads may be assigned a resource pool, which will be used to allocate * memory on behalf of certain kernel and driver APIs. Memory reserved * in this way should be freed with k_free(). * * @param size Memory allocation size * @return A pointer to the allocated memory, or NULL if there is insufficient * RAM in the pool or the thread has no resource pool assigned */ void *z_thread_malloc(size_t size); /* set and clear essential thread flag */ extern void z_thread_essential_set(void); extern void z_thread_essential_clear(void); /* clean up when a thread is aborted */ #if defined(CONFIG_THREAD_MONITOR) extern void z_thread_monitor_exit(struct k_thread *thread); #else #define z_thread_monitor_exit(thread) \ do {/* nothing */ \ } while (false) #endif /* CONFIG_THREAD_MONITOR */ extern void z_smp_init(void); extern void smp_timer_init(void); extern u32_t z_early_boot_rand32_get(void); #if CONFIG_STACK_POINTER_RANDOM extern int z_stack_adjust_initialized; #endif #if defined(CONFIG_ARCH_HAS_CUSTOM_BUSY_WAIT) extern void z_arch_busy_wait(u32_t usec_to_wait); #endif int z_arch_swap(unsigned int key); extern FUNC_NORETURN void z_arch_system_halt(unsigned int reason); #ifdef CONFIG_EXECUTION_BENCHMARKING extern u64_t z_arch_timing_swap_start; extern u64_t z_arch_timing_swap_end; extern u64_t z_arch_timing_irq_start; extern u64_t z_arch_timing_irq_end; extern u64_t z_arch_timing_tick_start; extern u64_t z_arch_timing_tick_end; extern u64_t z_arch_timing_user_mode_end; extern u32_t z_arch_timing_value_swap_end; extern u64_t z_arch_timing_value_swap_common; extern u64_t z_arch_timing_value_swap_temp; #endif /* CONFIG_EXECUTION_BENCHMARKING */ #ifdef CONFIG_BOOT_TIME_MEASUREMENT extern u32_t z_timestamp_main; /* timestamp when main task starts */ extern u32_t z_timestamp_idle; /* timestamp when CPU goes idle */ #endif extern struct k_thread z_main_thread; extern struct k_thread z_idle_thread; extern K_THREAD_STACK_DEFINE(z_main_stack, CONFIG_MAIN_STACK_SIZE); extern K_THREAD_STACK_DEFINE(z_idle_stack, CONFIG_IDLE_STACK_SIZE); #ifdef __cplusplus } #endif #endif /* _ASMLANGUAGE */ #endif /* ZEPHYR_KERNEL_INCLUDE_KERNEL_INTERNAL_H_ */
torsteingrindvik/fw-nrfconnect-zephyr
tests/lib/timeutil/src/test_s64.c
/* * Copyright (c) 2019 <NAME> * * SPDX-License-Identifier: Apache-2.0 */ /* Tests where time_t requires a 64-bit value */ #include <errno.h> #include <ztest.h> #include "timeutil_test.h" static const struct timeutil_test_data tests[] = { /* 32-bit, but algorithm subtraction underflows */ { .unix = -2147483648, .civil = "1901-12-13 20:45:52 Fri 347", .tm = { .tm_sec = 52, .tm_min = 45, .tm_hour = 20, .tm_mday = 13, .tm_mon = 11, .tm_year = 1, .tm_wday = 5, .tm_yday = 346, } }, { .unix = (time_t)-2147483649, .civil = "1901-12-13 20:45:51 Fri 347", .tm = { .tm_sec = 51, .tm_min = 45, .tm_hour = 20, .tm_mday = 13, .tm_mon = 11, .tm_year = 1, .tm_wday = 5, .tm_yday = 346, } }, { .unix = (time_t)2147483648, .civil = "2038-01-19 03:14:08 Tue 019", .tm = { .tm_sec = 8, .tm_min = 14, .tm_hour = 3, .tm_mday = 19, .tm_mon = 0, .tm_year = 138, .tm_wday = 2, .tm_yday = 18, } }, { .unix = (time_t)64060588799, .civil = "3999-12-31 23:59:59 Fri 365", .tm = { .tm_sec = 59, .tm_min = 59, .tm_hour = 23, .tm_mday = 31, .tm_mon = 11, .tm_year = 2099, .tm_wday = 5, .tm_yday = 364, } }, { .unix = (time_t)64060588800, .civil = "4000-01-01 00:00:00 Sat 001", .tm = { .tm_sec = 0, .tm_min = 0, .tm_hour = 0, .tm_mday = 1, .tm_mon = 0, .tm_year = 2100, .tm_wday = 6, .tm_yday = 0, } }, /* Normal century is a common year */ { .unix = (time_t)-2208988801, .civil = "1899-12-31 23:59:59 Sun 365", .tm = { .tm_sec = 59, .tm_min = 59, .tm_hour = 23, .tm_mday = 31, .tm_mon = 11, .tm_year = -1, .tm_wday = 0, .tm_yday = 364, } }, { .unix = (time_t)-2208988800, .civil = "1900-01-01 00:00:00 Mon 001", .tm = { .tm_sec = 0, .tm_min = 0, .tm_hour = 0, .tm_mday = 1, .tm_mon = 0, .tm_year = 0, .tm_wday = 1, .tm_yday = 0, } }, { .unix = (time_t)-2203977600, .civil = "1900-02-28 00:00:00 Wed 059", .tm = { .tm_sec = 0, .tm_min = 0, .tm_hour = 0, .tm_mday = 28, .tm_mon = 1, .tm_year = 0, .tm_wday = 3, .tm_yday = 58, } }, { .unix = (time_t)-2203891200, .civil = "1900-03-01 00:00:00 Thu 060", .tm = { .tm_sec = 0, .tm_min = 0, .tm_hour = 0, .tm_mday = 1, .tm_mon = 2, .tm_year = 0, .tm_wday = 4, .tm_yday = 59, } }, { .unix = (time_t)-2177539200, .civil = "1900-12-31 00:00:00 Mon 365", .tm = { .tm_sec = 0, .tm_min = 0, .tm_hour = 0, .tm_mday = 31, .tm_mon = 11, .tm_year = 0, .tm_wday = 1, .tm_yday = 364, } }, { .unix = (time_t)-2177452800, .civil = "1901-01-01 00:00:00 Tue 001", .tm = { .tm_sec = 0, .tm_min = 0, .tm_hour = 0, .tm_mday = 1, .tm_mon = 0, .tm_year = 1, .tm_wday = 2, .tm_yday = 0, } }, /* Extrema, check against proleptic Gregorian calendar data: * https://www.timeanddate.com/calendar/?year=1&country=22 */ { .unix = (time_t)-62167305600, .civil = "-1-12-31 00:00:00 Fri 365", .tm = { .tm_sec = 0, .tm_min = 0, .tm_hour = 0, .tm_mday = 31, .tm_mon = 11, .tm_year = -1901, .tm_wday = 5, .tm_yday = 364, } }, { .unix = (time_t)-62167219200, .civil = "0-01-01 00:00:00 Sat 001", .tm = { .tm_sec = 0, .tm_min = 0, .tm_hour = 0, .tm_mday = 1, .tm_mon = 0, .tm_year = -1900, .tm_wday = 6, .tm_yday = 0, } }, { .unix = (time_t)-62135596801, .civil = "0-12-31 23:59:59 Sun 366", .tm = { .tm_sec = 59, .tm_min = 59, .tm_hour = 23, .tm_mday = 31, .tm_mon = 11, .tm_year = -1900, .tm_wday = 0, .tm_yday = 365, } }, { .unix = (time_t)-62135596800, .civil = "1-01-01 00:00:00 Mon 001", .tm = { .tm_sec = 0, .tm_min = 0, .tm_hour = 0, .tm_mday = 1, .tm_mon = 0, .tm_year = -1899, .tm_wday = 1, .tm_yday = 0, } }, { .unix = (time_t)-62135596800, .civil = "1-01-01 00:00:00 Mon 001", .tm = { .tm_sec = 0, .tm_min = 0, .tm_hour = 0, .tm_mday = 1, .tm_mon = 0, .tm_year = -1899, .tm_wday = 1, .tm_yday = 0, } }, }; static void test_time32_errno_clear(void) { const struct timeutil_test_data *tp = &(const struct timeutil_test_data){ .unix = 0, .civil = "1970-01-01 00:00:00 Thu 001", .tm = { .tm_sec = 0, .tm_min = 0, .tm_hour = 0, .tm_mday = 1, .tm_mon = 0, .tm_year = 70, .tm_wday = 4, .tm_yday = 0, }, }; errno = EINVAL; time_t unix = timeutil_timegm(&tp->tm); zassert_equal(unix, tp->unix, "conversion incorrect"); zassert_equal(errno, 0, "errno was not cleared"); } static void test_time32_epochm1(void) { const struct timeutil_test_data *tp = &(const struct timeutil_test_data){ .unix = -1, .civil = "1969-12-31 23:59:59 Wed 365", .tm = { .tm_sec = 59, .tm_min = 59, .tm_hour = 23, .tm_mday = 31, .tm_mon = 11, .tm_year = 69, .tm_wday = 3, .tm_yday = 364, }, }; errno = EINVAL; time_t unix = timeutil_timegm(&tp->tm); zassert_equal(unix, tp->unix, "conversion incorrect"); zassert_equal(errno, 0, "final errno state bad"); } static void test_time32_underflow(void) { const s64_t unix64 = -2147483649; const struct timeutil_test_data *tp = &(const struct timeutil_test_data){ .civil = "1901-12-13 20:45:51 Fri 347", .tm = { .tm_sec = 51, .tm_min = 45, .tm_hour = 20, .tm_mday = 13, .tm_mon = 11, .tm_year = 1, .tm_wday = 5, .tm_yday = 346, }, }; zassert_equal(timeutil_timegm64(&tp->tm), unix64, "fullscale failed"); errno = 0; time_t unix = timeutil_timegm(&tp->tm); zassert_equal(unix, -1, "underflow undetected"); zassert_equal(errno, ERANGE, "final errno state bad"); } static void test_time32_overflow(void) { const s64_t unix64 = 2147483648; const struct timeutil_test_data *tp = &(const struct timeutil_test_data){ .civil = "2038-01-19 03:14:08 Tue 019", .tm = { .tm_sec = 8, .tm_min = 14, .tm_hour = 3, .tm_mday = 19, .tm_mon = 0, .tm_year = 138, .tm_wday = 2, .tm_yday = 18, }, }; zassert_equal(timeutil_timegm64(&tp->tm), unix64, "fullscale failed"); errno = 0; time_t unix = timeutil_timegm(&tp->tm); zassert_equal(unix, -1, "overflow undetected"); zassert_equal(errno, ERANGE, "final errno state bad"); } void test_s64(void) { if (sizeof(time_t) < 8U) { test_time32_errno_clear(); test_time32_epochm1(); test_time32_underflow(); test_time32_overflow(); return; } timeutil_check(tests, sizeof(tests) / sizeof(*tests)); }
torsteingrindvik/fw-nrfconnect-zephyr
drivers/timer/cortex_m_systick.c
<gh_stars>1-10 /* * Copyright (c) 2018 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <drivers/timer/system_timer.h> #include <sys_clock.h> #include <spinlock.h> #include <arch/arm/cortex_m/cmsis.h> void z_arm_exc_exit(void); #define COUNTER_MAX 0x00ffffff #define TIMER_STOPPED 0xff000000 #define CYC_PER_TICK (sys_clock_hw_cycles_per_sec() \ / CONFIG_SYS_CLOCK_TICKS_PER_SEC) #define MAX_TICKS ((COUNTER_MAX / CYC_PER_TICK) - 1) #define MAX_CYCLES (MAX_TICKS * CYC_PER_TICK) /* Minimum cycles in the future to try to program. Note that this is * NOT simply "enough cycles to get the counter read and reprogrammed * reliably" -- it becomes the minimum value of the LOAD register, and * thus reflects how much time we can reliably see expire between * calls to elapsed() to read the COUNTFLAG bit. So it needs to be * set to be larger than the maximum time the interrupt might be * masked. Choosing a fraction of a tick is probably a good enough * default, with an absolute minimum of 1k cyc. */ #define MIN_DELAY MAX(1024, (CYC_PER_TICK/16)) #define TICKLESS (IS_ENABLED(CONFIG_TICKLESS_KERNEL) && \ !IS_ENABLED(CONFIG_QEMU_TICKLESS_WORKAROUND)) /* VAL value above which we assume that a subsequent COUNTFLAG * overflow seen in CTRL is real and not an artifact of wraparound * timing. */ #define VAL_ABOUT_TO_WRAP 8 static struct k_spinlock lock; static u32_t last_load; static u32_t cycle_count; static u32_t announced_cycles; static volatile u32_t overflow_cyc; static u32_t elapsed(void) { u32_t val, ctrl1, ctrl2; /* SysTick is infuriatingly racy. The counter wraps at zero * automatically, setting a 1 in the COUNTFLAG bit of the CTRL * register when it does. But reading the control register * automatically resets that bit, so we need to save it for * future calls. And ordering is critical and race-prone: if * we read CTRL first, then it is possible for VAL to wrap * after that read but before we read VAL and we'll miss the * overflow. If we read VAL first, then it can wrap after we * read it and we'll see an "extra" overflow in CTRL. And we * want to handle multiple overflows, so we effectively must * read CTRL first otherwise there will be no way to detect * the double-overflow if called at the end of a cycle. There * is no safe algorithm here, so we split the difference by * reading CTRL twice, suppressing the second overflow bit if * VAL was "about to overflow". */ ctrl1 = SysTick->CTRL; val = SysTick->VAL & COUNTER_MAX; ctrl2 = SysTick->CTRL; overflow_cyc += (ctrl1 & SysTick_CTRL_COUNTFLAG_Msk) ? last_load : 0; if (val > VAL_ABOUT_TO_WRAP) { int wrap = ctrl2 & SysTick_CTRL_COUNTFLAG_Msk; overflow_cyc += (wrap != 0) ? last_load : 0; } return (last_load - val) + overflow_cyc; } /* Callout out of platform assembly, not hooked via IRQ_CONNECT... */ void z_clock_isr(void *arg) { ARG_UNUSED(arg); u32_t dticks; cycle_count += last_load; dticks = (cycle_count - announced_cycles) / CYC_PER_TICK; announced_cycles += dticks * CYC_PER_TICK; overflow_cyc = SysTick->CTRL; /* Reset overflow flag */ overflow_cyc = 0U; z_clock_announce(TICKLESS ? dticks : 1); z_arm_exc_exit(); } int z_clock_driver_init(struct device *device) { NVIC_SetPriority(SysTick_IRQn, _IRQ_PRIO_OFFSET); last_load = CYC_PER_TICK - 1; overflow_cyc = 0U; SysTick->LOAD = last_load; SysTick->VAL = 0; /* resets timer to last_load */ SysTick->CTRL |= (SysTick_CTRL_ENABLE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_CLKSOURCE_Msk); return 0; } void z_clock_set_timeout(s32_t ticks, bool idle) { /* Fast CPUs and a 24 bit counter mean that even idle systems * need to wake up multiple times per second. If the kernel * allows us to miss tick announcements in idle, then shut off * the counter. (Note: we can assume if idle==true that * interrupts are already disabled) */ if (IS_ENABLED(CONFIG_TICKLESS_IDLE) && idle && ticks == K_FOREVER) { SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; last_load = TIMER_STOPPED; return; } #if defined(CONFIG_TICKLESS_KERNEL) && !defined(CONFIG_QEMU_TICKLESS_WORKAROUND) u32_t delay; ticks = MIN(MAX_TICKS, MAX(ticks - 1, 0)); /* Desired delay in the future */ delay = (ticks == 0) ? MIN_DELAY : ticks * CYC_PER_TICK; k_spinlock_key_t key = k_spin_lock(&lock); cycle_count += elapsed(); /* Round delay up to next tick boundary */ delay = delay + (cycle_count - announced_cycles); delay = ((delay + CYC_PER_TICK - 1) / CYC_PER_TICK) * CYC_PER_TICK; last_load = delay - (cycle_count - announced_cycles); overflow_cyc = 0U; SysTick->LOAD = last_load - 1; SysTick->VAL = 0; /* resets timer to last_load */ k_spin_unlock(&lock, key); #endif } u32_t z_clock_elapsed(void) { if (!TICKLESS) { return 0; } k_spinlock_key_t key = k_spin_lock(&lock); u32_t cyc = elapsed() + cycle_count - announced_cycles; k_spin_unlock(&lock, key); return cyc / CYC_PER_TICK; } u32_t z_timer_cycle_get_32(void) { k_spinlock_key_t key = k_spin_lock(&lock); u32_t ret = elapsed() + cycle_count; k_spin_unlock(&lock, key); return ret; } void z_clock_idle_exit(void) { if (last_load == TIMER_STOPPED) { SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk; } } void sys_clock_disable(void) { SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; }
torsteingrindvik/fw-nrfconnect-zephyr
arch/x86/core/intel64/cpu.c
/* * Copyright (c) 2019 Intel Corporation * SPDX-License-Identifier: Apache-2.0 */ #include <kernel.h> #include <kernel_arch_data.h> #include <kernel_arch_func.h> #include <kernel_structs.h> #include <arch/x86/multiboot.h> #include <drivers/interrupt_controller/loapic.h> /* * Map of CPU logical IDs to CPU local APIC IDs. By default, * we assume this simple identity mapping, as found in QEMU. * The symbol is weak so that boards/SoC files can override. */ __weak u8_t x86_cpu_loapics[] = { 0, 1, 2, 3 }; extern char x86_ap_start[]; /* AP entry point in locore.S */ extern u8_t _exception_stack[]; extern u8_t _exception_stack1[]; extern u8_t _exception_stack2[]; extern u8_t _exception_stack3[]; Z_GENERIC_SECTION(.tss) struct x86_tss64 tss0 = { .ist7 = (u64_t) _exception_stack + CONFIG_EXCEPTION_STACK_SIZE, .iomapb = 0xFFFF, .cpu = &(_kernel.cpus[0]) }; #if CONFIG_MP_NUM_CPUS > 1 Z_GENERIC_SECTION(.tss) struct x86_tss64 tss1 = { .ist7 = (u64_t) _exception_stack1 + CONFIG_EXCEPTION_STACK_SIZE, .iomapb = 0xFFFF, .cpu = &(_kernel.cpus[1]) }; #endif #if CONFIG_MP_NUM_CPUS > 2 Z_GENERIC_SECTION(.tss) struct x86_tss64 tss2 = { .ist7 = (u64_t) _exception_stack2 + CONFIG_EXCEPTION_STACK_SIZE, .iomapb = 0xFFFF, .cpu = &(_kernel.cpus[2]) }; #endif #if CONFIG_MP_NUM_CPUS > 3 Z_GENERIC_SECTION(.tss) struct x86_tss64 tss3 = { .ist7 = (u64_t) _exception_stack3 + CONFIG_EXCEPTION_STACK_SIZE, .iomapb = 0xFFFF, .cpu = &(_kernel.cpus[3]) }; #endif struct x86_cpuboot x86_cpuboot[] = { { .tr = X86_KERNEL_CPU0_TR, .gs = X86_KERNEL_CPU0_GS, .sp = (u64_t) _interrupt_stack + CONFIG_ISR_STACK_SIZE, .fn = z_x86_prep_c }, #if CONFIG_MP_NUM_CPUS > 1 { .tr = X86_KERNEL_CPU1_TR, .gs = X86_KERNEL_CPU1_GS, }, #endif #if CONFIG_MP_NUM_CPUS > 2 { .tr = X86_KERNEL_CPU2_TR, .gs = X86_KERNEL_CPU2_GS, }, #endif #if CONFIG_MP_NUM_CPUS > 3 { .tr = X86_KERNEL_CPU3_TR, .gs = X86_KERNEL_CPU3_GS, }, #endif }; /* * Send the INIT/STARTUP IPI sequence required to start up CPU 'cpu_num', which * will enter the kernel at fn(---, arg), running on the specified stack. */ void z_arch_start_cpu(int cpu_num, k_thread_stack_t *stack, int sz, void (*fn)(int key, void *data), void *arg) { u8_t vector = ((unsigned long) x86_ap_start) >> 12; u8_t apic_id = x86_cpu_loapics[cpu_num]; x86_cpuboot[cpu_num].sp = (u64_t) Z_THREAD_STACK_BUFFER(stack) + sz; x86_cpuboot[cpu_num].fn = fn; x86_cpuboot[cpu_num].arg = arg; z_loapic_ipi(apic_id, LOAPIC_ICR_IPI_INIT, 0); k_busy_wait(10000); z_loapic_ipi(apic_id, LOAPIC_ICR_IPI_STARTUP, vector); while (x86_cpuboot[cpu_num].ready == 0) { } }
torsteingrindvik/fw-nrfconnect-zephyr
drivers/sensor/lis2dw12/lis2dw12_i2c.c
/* ST Microelectronics LIS2DW12 3-axis accelerometer driver * * Copyright (c) 2019 STMicroelectronics * * SPDX-License-Identifier: Apache-2.0 * * Datasheet: * https://www.st.com/resource/en/datasheet/lis2dw12.pdf */ #include <string.h> #include <drivers/i2c.h> #include <logging/log.h> #include "lis2dw12.h" #ifdef DT_ST_LIS2DW12_BUS_I2C static u16_t lis2dw12_i2c_slave_addr = DT_INST_0_ST_LIS2DW12_BASE_ADDRESS; LOG_MODULE_DECLARE(LIS2DW12, CONFIG_SENSOR_LOG_LEVEL); static int lis2dw12_i2c_read(struct lis2dw12_data *data, u8_t reg_addr, u8_t *value, u16_t len) { return i2c_burst_read(data->bus, lis2dw12_i2c_slave_addr, reg_addr, value, len); } static int lis2dw12_i2c_write(struct lis2dw12_data *data, u8_t reg_addr, u8_t *value, u16_t len) { return i2c_burst_write(data->bus, lis2dw12_i2c_slave_addr, reg_addr, value, len); } lis2dw12_ctx_t lis2dw12_i2c_ctx = { .read_reg = (lis2dw12_read_ptr) lis2dw12_i2c_read, .write_reg = (lis2dw12_write_ptr) lis2dw12_i2c_write, }; int lis2dw12_i2c_init(struct device *dev) { struct lis2dw12_data *data = dev->driver_data; data->ctx = &lis2dw12_i2c_ctx; data->ctx->handle = data; return 0; } #endif /* DT_ST_LIS2DW12_BUS_I2C */
torsteingrindvik/fw-nrfconnect-zephyr
drivers/can/can_stm32.c
<filename>drivers/can/can_stm32.c /* * Copyright (c) 2018 <NAME> * * SPDX-License-Identifier: Apache-2.0 */ #include <clock_control/stm32_clock_control.h> #include <drivers/clock_control.h> #include <sys/util.h> #include <string.h> #include <kernel.h> #include <soc.h> #include <errno.h> #include <stdbool.h> #include <drivers/can.h> #include "can_stm32.h" #include <logging/log.h> LOG_MODULE_DECLARE(can_driver, CONFIG_CAN_LOG_LEVEL); #define INIT_TIMEOUT (10 * sys_clock_hw_cycles_per_sec() / MSEC_PER_SEC) /* * Translation tables * filter_in_bank[enum can_filter_type] = number of filters in bank for this type * reg_demand[enum can_filter_type] = how many registers are used for this type */ static const u8_t filter_in_bank[] = {2, 4, 1, 2}; static const u8_t reg_demand[] = {2, 1, 4, 2}; static void can_stm32_signal_tx_complete(struct can_mailbox *mb) { if (mb->tx_callback) { mb->tx_callback(mb->error_flags, mb->callback_arg); } else { k_sem_give(&mb->tx_int_sem); } } static void can_stm32_get_msg_fifo(CAN_FIFOMailBox_TypeDef *mbox, struct zcan_frame *msg) { if (mbox->RIR & CAN_RI0R_IDE) { msg->ext_id = mbox->RIR >> CAN_RI0R_EXID_Pos; msg->id_type = CAN_EXTENDED_IDENTIFIER; } else { msg->std_id = mbox->RIR >> CAN_RI0R_STID_Pos; msg->id_type = CAN_STANDARD_IDENTIFIER; } msg->rtr = mbox->RIR & CAN_RI0R_RTR ? CAN_REMOTEREQUEST : CAN_DATAFRAME; msg->dlc = mbox->RDTR & (CAN_RDT0R_DLC >> CAN_RDT0R_DLC_Pos); msg->data_32[0] = mbox->RDLR; msg->data_32[1] = mbox->RDHR; #ifdef CONFIG_CAN_RX_TIMESTAMP msg->timestamp = ((mbox->RDTR & CAN_RDT0R_TIME) >> CAN_RDT0R_TIME_Pos); #endif } static inline void can_stm32_rx_isr_handler(CAN_TypeDef *can, struct can_stm32_data *data) { CAN_FIFOMailBox_TypeDef *mbox; int filter_match_index; struct zcan_frame msg; can_rx_callback_t callback; while (can->RF0R & CAN_RF0R_FMP0) { mbox = &can->sFIFOMailBox[0]; filter_match_index = ((mbox->RDTR & CAN_RDT0R_FMI) >> CAN_RDT0R_FMI_Pos); if (filter_match_index >= CONFIG_CAN_MAX_FILTER) { break; } LOG_DBG("Message on filter index %d", filter_match_index); can_stm32_get_msg_fifo(mbox, &msg); callback = data->rx_cb[filter_match_index]; if (callback) { callback(&msg, data->cb_arg[filter_match_index]); } /* Release message */ can->RF0R |= CAN_RF0R_RFOM0; } if (can->RF0R & CAN_RF0R_FOVR0) { LOG_ERR("RX FIFO Overflow"); } } static inline void can_stm32_tx_isr_handler(CAN_TypeDef *can, struct can_stm32_data *data) { u32_t bus_off; bus_off = can->ESR & CAN_ESR_BOFF; if ((can->TSR & CAN_TSR_RQCP0) | bus_off) { data->mb0.error_flags = can->TSR & CAN_TSR_TXOK0 ? CAN_TX_OK : can->TSR & CAN_TSR_TERR0 ? CAN_TX_ERR : can->TSR & CAN_TSR_ALST0 ? CAN_TX_ARB_LOST : bus_off ? CAN_TX_BUS_OFF : CAN_TX_UNKNOWN; /* clear the request. */ can->TSR |= CAN_TSR_RQCP0; can_stm32_signal_tx_complete(&data->mb0); } if ((can->TSR & CAN_TSR_RQCP1) | bus_off) { data->mb1.error_flags = can->TSR & CAN_TSR_TXOK1 ? CAN_TX_OK : can->TSR & CAN_TSR_TERR1 ? CAN_TX_ERR : can->TSR & CAN_TSR_ALST1 ? CAN_TX_ARB_LOST : bus_off ? CAN_TX_BUS_OFF : CAN_TX_UNKNOWN; /* clear the request. */ can->TSR |= CAN_TSR_RQCP1; can_stm32_signal_tx_complete(&data->mb1); } if ((can->TSR & CAN_TSR_RQCP2) | bus_off) { data->mb2.error_flags = can->TSR & CAN_TSR_TXOK2 ? CAN_TX_OK : can->TSR & CAN_TSR_TERR2 ? CAN_TX_ERR : can->TSR & CAN_TSR_ALST2 ? CAN_TX_ARB_LOST : bus_off ? CAN_TX_BUS_OFF : CAN_TX_UNKNOWN; /* clear the request. */ can->TSR |= CAN_TSR_RQCP2; can_stm32_signal_tx_complete(&data->mb2); } if (can->TSR & CAN_TSR_TME) { k_sem_give(&data->tx_int_sem); } } #ifdef CONFIG_SOC_SERIES_STM32F0X static void can_stm32_isr(void *arg) { struct device *dev; struct can_stm32_data *data; const struct can_stm32_config *cfg; CAN_TypeDef *can; dev = (struct device *)arg; data = DEV_DATA(dev); cfg = DEV_CFG(dev); can = cfg->can; can_stm32_tx_isr_handler(can, data); can_stm32_rx_isr_handler(can, data); } #else static void can_stm32_rx_isr(void *arg) { struct device *dev; struct can_stm32_data *data; const struct can_stm32_config *cfg; CAN_TypeDef *can; dev = (struct device *)arg; data = DEV_DATA(dev); cfg = DEV_CFG(dev); can = cfg->can; can_stm32_rx_isr_handler(can, data); } static void can_stm32_tx_isr(void *arg) { struct device *dev; struct can_stm32_data *data; const struct can_stm32_config *cfg; CAN_TypeDef *can; dev = (struct device *)arg; data = DEV_DATA(dev); cfg = DEV_CFG(dev); can = cfg->can; can_stm32_tx_isr_handler(can, data); } #endif static int can_enter_init_mode(CAN_TypeDef *can) { u32_t start_time; can->MCR |= CAN_MCR_INRQ; start_time = k_cycle_get_32(); while ((can->MSR & CAN_MSR_INAK) == 0U) { if (k_cycle_get_32() - start_time > INIT_TIMEOUT) { return CAN_TIMEOUT; } } return 0; } static int can_leave_init_mode(CAN_TypeDef *can) { u32_t start_time; can->MCR &= ~CAN_MCR_INRQ; start_time = k_cycle_get_32(); while ((can->MSR & CAN_MSR_INAK) != 0U) { if (k_cycle_get_32() - start_time > INIT_TIMEOUT) { return CAN_TIMEOUT; } } return 0; } static int can_leave_sleep_mode(CAN_TypeDef *can) { u32_t start_time; can->MCR &= ~CAN_MCR_SLEEP; start_time = k_cycle_get_32(); while ((can->MSR & CAN_MSR_SLAK) != 0) { if (k_cycle_get_32() - start_time > INIT_TIMEOUT) { return CAN_TIMEOUT; } } return 0; } int can_stm32_runtime_configure(struct device *dev, enum can_mode mode, u32_t bitrate) { CAN_HandleTypeDef hcan; const struct can_stm32_config *cfg = DEV_CFG(dev); CAN_TypeDef *can = cfg->can; struct device *clock; u32_t clock_rate; u32_t prescaler; u32_t reg_mode; u32_t ts1; u32_t ts2; u32_t sjw; int ret; clock = device_get_binding(STM32_CLOCK_CONTROL_NAME); __ASSERT_NO_MSG(clock); hcan.Instance = can; ret = clock_control_get_rate(clock, (clock_control_subsys_t *) &cfg->pclken, &clock_rate); if (ret != 0) { LOG_ERR("Failed call clock_control_get_rate: return [%d]", ret); return -EIO; } if (!bitrate) { bitrate = cfg->bus_speed; } prescaler = clock_rate / (BIT_SEG_LENGTH(cfg) * bitrate); if (prescaler == 0U || prescaler > 1024) { LOG_ERR("HAL_CAN_Init failed: prescaler > max (%d > 1024)", prescaler); return -EINVAL; } if (clock_rate % (BIT_SEG_LENGTH(cfg) * bitrate)) { LOG_ERR("Prescaler is not a natural number! " "prescaler = clock_rate / ((PROP_SEG1 + SEG2 + 1)" " * bus_speed); " "prescaler = %d / ((%d + %d + 1) * %d)", clock_rate, cfg->prop_ts1, cfg->ts2, bitrate); } __ASSERT(cfg->sjw <= 0x03, "SJW maximum is 3"); __ASSERT(cfg->prop_ts1 <= 0x0F, "PROP_BS1 maximum is 15"); __ASSERT(cfg->ts2 <= 0x07, "BS2 maximum is 7"); ts1 = ((cfg->prop_ts1 & 0x0F) - 1) << CAN_BTR_TS1_Pos; ts2 = ((cfg->ts2 & 0x07) - 1) << CAN_BTR_TS2_Pos; sjw = ((cfg->sjw & 0x07) - 1) << CAN_BTR_SJW_Pos; reg_mode = (mode == CAN_NORMAL_MODE) ? 0U : (mode == CAN_LOOPBACK_MODE) ? CAN_BTR_LBKM : (mode == CAN_SILENT_MODE) ? CAN_BTR_SILM : CAN_BTR_LBKM | CAN_BTR_SILM; ret = can_enter_init_mode(can); if (ret) { LOG_ERR("Failed to enter init mode"); return ret; } can->BTR = reg_mode | sjw | ts1 | ts2 | (prescaler - 1U); ret = can_leave_init_mode(can); if (ret) { LOG_ERR("Failed to leave init mode"); return ret; } LOG_DBG("Runtime configure of %s done", dev->config->name); return 0; } static int can_stm32_init(struct device *dev) { const struct can_stm32_config *cfg = DEV_CFG(dev); struct can_stm32_data *data = DEV_DATA(dev); CAN_TypeDef *can = cfg->can; struct device *clock; int ret; k_mutex_init(&data->tx_mutex); k_mutex_init(&data->set_filter_mutex); k_sem_init(&data->tx_int_sem, 0, 1); k_sem_init(&data->mb0.tx_int_sem, 0, 1); k_sem_init(&data->mb1.tx_int_sem, 0, 1); k_sem_init(&data->mb2.tx_int_sem, 0, 1); data->mb0.tx_callback = NULL; data->mb1.tx_callback = NULL; data->mb2.tx_callback = NULL; data->filter_usage = (1ULL << CAN_MAX_NUMBER_OF_FILTERS) - 1ULL; (void)memset(data->rx_cb, 0, sizeof(data->rx_cb)); (void)memset(data->cb_arg, 0, sizeof(data->cb_arg)); clock = device_get_binding(STM32_CLOCK_CONTROL_NAME); __ASSERT_NO_MSG(clock); ret = clock_control_on(clock, (clock_control_subsys_t *) &cfg->pclken); if (ret != 0) { LOG_ERR("HAL_CAN_Init clock control on failed: %d", ret); return -EIO; } ret = can_leave_sleep_mode(can); if (ret) { LOG_ERR("Failed to exit sleep mode"); return ret; } ret = can_enter_init_mode(can); if (ret) { LOG_ERR("Failed to enter init mode"); return ret; } /* Set TX priority to chronological order */ can->MCR |= CAN_MCR_TXFP; can->MCR &= ~CAN_MCR_TTCM & ~CAN_MCR_TTCM & ~CAN_MCR_ABOM & ~CAN_MCR_AWUM & ~CAN_MCR_NART & ~CAN_MCR_RFLM; #ifdef CONFIG_CAN_RX_TIMESTAMP can->MCR |= CAN_MCR_TTCM; #endif ret = can_stm32_runtime_configure(dev, CAN_NORMAL_MODE, 0); if (ret) { return ret; } /* Leave sleep mode after reset*/ can->MCR &= ~CAN_MCR_SLEEP; cfg->config_irq(can); can->IER |= CAN_IER_TMEIE; LOG_INF("Init of %s done", dev->config->name); return 0; } int can_stm32_send(struct device *dev, const struct zcan_frame *msg, s32_t timeout, can_tx_callback_t callback, void *callback_arg) { const struct can_stm32_config *cfg = DEV_CFG(dev); struct can_stm32_data *data = DEV_DATA(dev); CAN_TypeDef *can = cfg->can; u32_t transmit_status_register = can->TSR; CAN_TxMailBox_TypeDef *mailbox = NULL; struct k_mutex *tx_mutex = &data->tx_mutex; struct can_mailbox *mb = NULL; LOG_DBG("Sending %d bytes on %s. " "Id: 0x%x, " "ID type: %s, " "Remote Frame: %s" , msg->dlc, dev->config->name , msg->id_type == CAN_STANDARD_IDENTIFIER ? msg->std_id : msg->ext_id , msg->id_type == CAN_STANDARD_IDENTIFIER ? "standard" : "extended" , msg->rtr == CAN_DATAFRAME ? "no" : "yes"); __ASSERT(msg->dlc == 0U || msg->data != NULL, "Dataptr is null"); __ASSERT(msg->dlc <= CAN_MAX_DLC, "DLC > 8"); if (can->ESR & CAN_ESR_BOFF) { return CAN_TX_BUS_OFF; } k_mutex_lock(tx_mutex, K_FOREVER); while (!(transmit_status_register & CAN_TSR_TME)) { k_mutex_unlock(tx_mutex); LOG_DBG("Transmit buffer full. Wait with timeout (%dms)", timeout); if (k_sem_take(&data->tx_int_sem, timeout)) { return CAN_TIMEOUT; } k_mutex_lock(tx_mutex, K_FOREVER); transmit_status_register = can->TSR; } if (transmit_status_register & CAN_TSR_TME0) { LOG_DBG("Using mailbox 0"); mailbox = &can->sTxMailBox[0]; mb = &(data->mb0); } else if (transmit_status_register & CAN_TSR_TME1) { LOG_DBG("Using mailbox 1"); mailbox = &can->sTxMailBox[1]; mb = &data->mb1; } else if (transmit_status_register & CAN_TSR_TME2) { LOG_DBG("Using mailbox 2"); mailbox = &can->sTxMailBox[2]; mb = &data->mb2; } mb->tx_callback = callback; mb->callback_arg = callback_arg; k_sem_reset(&mb->tx_int_sem); /* mailbix identifier register setup */ mailbox->TIR &= CAN_TI0R_TXRQ; if (msg->id_type == CAN_STANDARD_IDENTIFIER) { mailbox->TIR |= (msg->std_id << CAN_TI0R_STID_Pos); } else { mailbox->TIR |= (msg->ext_id << CAN_TI0R_EXID_Pos) | CAN_TI0R_IDE; } if (msg->rtr == CAN_REMOTEREQUEST) { mailbox->TIR |= CAN_TI1R_RTR; } mailbox->TDTR = (mailbox->TDTR & ~CAN_TDT1R_DLC) | ((msg->dlc & 0xF) << CAN_TDT1R_DLC_Pos); mailbox->TDLR = msg->data_32[0]; mailbox->TDHR = msg->data_32[1]; mailbox->TIR |= CAN_TI0R_TXRQ; k_mutex_unlock(tx_mutex); if (callback == NULL) { k_sem_take(&mb->tx_int_sem, K_FOREVER); return mb->error_flags; } return 0; } static inline int can_stm32_check_free(void **arr, int start, int end) { int i; for (i = start; i <= end; i++) { if (arr[i] != NULL) { return 0; } } return 1; } static int can_stm32_shift_arr(void **arr, int start, int count) { void **start_ptr = arr + start; size_t cnt; if (start > CONFIG_CAN_MAX_FILTER) { return CAN_NO_FREE_FILTER; } if (count > 0) { void *move_dest; /* Check if nothing used will be overwritten */ if (!can_stm32_check_free(arr, CONFIG_CAN_MAX_FILTER - count, CONFIG_CAN_MAX_FILTER - 1)) { return CAN_NO_FREE_FILTER; } /* No need to shift. Destination is already outside the arr*/ if ((start + count) >= CONFIG_CAN_MAX_FILTER) { return 0; } cnt = (CONFIG_CAN_MAX_FILTER - start - count) * sizeof(void *); move_dest = start_ptr + count; memmove(move_dest, start_ptr, cnt); (void)memset(start_ptr, 0, count * sizeof(void *)); } else if (count < 0) { count = -count; if (start - count < 0) { return CAN_NO_FREE_FILTER; } cnt = (CONFIG_CAN_MAX_FILTER - start) * sizeof(void *); memmove(start_ptr - count, start_ptr, cnt); (void)memset(arr + CONFIG_CAN_MAX_FILTER - count, 0, count * sizeof(void *)); } return 0; } enum can_filter_type can_stm32_get_filter_type(int bank_nr, u32_t mode_reg, u32_t scale_reg) { u32_t mode_masked = (mode_reg >> bank_nr) & 0x01; u32_t scale_masked = (scale_reg >> bank_nr) & 0x01; enum can_filter_type type = (scale_masked << 1) | mode_masked; return type; } static int can_calc_filter_index(int filter_nr, u32_t mode_reg, u32_t scale_reg) { int filter_bank = filter_nr / 4; int cnt = 0; u32_t mode_masked, scale_masked; enum can_filter_type filter_type; /*count filters in the banks before */ for (int i = 0; i < filter_bank; i++) { filter_type = can_stm32_get_filter_type(i, mode_reg, scale_reg); cnt += filter_in_bank[filter_type]; } /* plus the filters in the same bank */ mode_masked = mode_reg & (1U << filter_bank); scale_masked = scale_reg & (1U << filter_bank); cnt += (!scale_masked && mode_masked) ? filter_nr & 0x03 : (filter_nr & 0x03) >> 1; return cnt; } static void can_stm32_set_filter_bank(int filter_nr, CAN_FilterRegister_TypeDef *filter_reg, enum can_filter_type filter_type, u32_t id, u32_t mask) { switch (filter_type) { case CAN_FILTER_STANDARD: switch (filter_nr & 0x03) { case 0: filter_reg->FR1 = (filter_reg->FR1 & 0xFFFF0000) | id; break; case 1: filter_reg->FR1 = (filter_reg->FR1 & 0x0000FFFF) | (id << 16); break; case 2: filter_reg->FR2 = (filter_reg->FR2 & 0xFFFF0000) | id; break; case 3: filter_reg->FR2 = (filter_reg->FR2 & 0x0000FFFF) | (id << 16); break; } break; case CAN_FILTER_STANDARD_MASKED: switch (filter_nr & 0x02) { case 0: filter_reg->FR1 = id | (mask << 16); break; case 2: filter_reg->FR2 = id | (mask << 16); break; } break; case CAN_FILTER_EXTENDED: switch (filter_nr & 0x02) { case 0: filter_reg->FR1 = id; break; case 2: filter_reg->FR2 = id; break; } break; case CAN_FILTER_EXTENDED_MASKED: filter_reg->FR1 = id; filter_reg->FR2 = mask; break; } } static inline void can_stm32_set_mode_scale(enum can_filter_type filter_type, u32_t *mode_reg, u32_t *scale_reg, int bank_nr) { u32_t mode_reg_bit = (filter_type & 0x01) << bank_nr; u32_t scale_reg_bit = (filter_type >> 1) << bank_nr; *mode_reg &= ~(1 << bank_nr); *mode_reg |= mode_reg_bit; *scale_reg &= ~(1 << bank_nr); *scale_reg |= scale_reg_bit; } static inline u32_t can_generate_std_mask(const struct zcan_filter *filter) { return (filter->std_id_mask << CAN_FIRX_STD_ID_POS) | (filter->rtr_mask << CAN_FIRX_STD_RTR_POS) | (1U << CAN_FIRX_STD_IDE_POS); } static inline u32_t can_generate_ext_mask(const struct zcan_filter *filter) { return (filter->ext_id_mask << CAN_FIRX_EXT_EXT_ID_POS) | (filter->rtr_mask << CAN_FIRX_EXT_RTR_POS) | (1U << CAN_FIRX_EXT_IDE_POS); } static inline u32_t can_generate_std_id(const struct zcan_filter *filter) { return (filter->std_id << CAN_FIRX_STD_ID_POS) | (filter->rtr << CAN_FIRX_STD_RTR_POS); } static inline u32_t can_generate_ext_id(const struct zcan_filter *filter) { return (filter->ext_id << CAN_FIRX_EXT_EXT_ID_POS) | (filter->rtr << CAN_FIRX_EXT_RTR_POS) | (1U << CAN_FIRX_EXT_IDE_POS); } static inline int can_stm32_set_filter(const struct zcan_filter *filter, struct can_stm32_data *device_data, CAN_TypeDef *can, int *filter_index) { u32_t mask = 0U; u32_t id = 0U; int filter_nr = 0; int filter_index_new = CAN_NO_FREE_FILTER; int bank_nr; u32_t bank_bit; int register_demand; enum can_filter_type filter_type; enum can_filter_type bank_mode; if (filter->id_type == CAN_STANDARD_IDENTIFIER) { id = can_generate_std_id(filter); filter_type = CAN_FILTER_STANDARD; if (filter->std_id_mask != CAN_STD_ID_MASK) { mask = can_generate_std_mask(filter); filter_type = CAN_FILTER_STANDARD_MASKED; } } else { id = can_generate_ext_id(filter); filter_type = CAN_FILTER_EXTENDED; if (filter->ext_id_mask != CAN_EXT_ID_MASK) { mask = can_generate_ext_mask(filter); filter_type = CAN_FILTER_EXTENDED_MASKED; } } register_demand = reg_demand[filter_type]; LOG_DBG("Setting filter ID: 0x%x, mask: 0x%x", filter->ext_id, filter->ext_id_mask); LOG_DBG("Filter type: %s ID %s mask (%d)", (filter_type == CAN_FILTER_STANDARD || filter_type == CAN_FILTER_STANDARD_MASKED) ? "standard" : "extended", (filter_type == CAN_FILTER_STANDARD_MASKED || filter_type == CAN_FILTER_EXTENDED_MASKED) ? "with" : "without", filter_type); do { u64_t usage_shifted = (device_data->filter_usage >> filter_nr); u64_t usage_demand_mask = (1ULL << register_demand) - 1; bool bank_is_empty; bank_nr = filter_nr / 4; bank_bit = (1U << bank_nr); bank_mode = can_stm32_get_filter_type(bank_nr, can->FM1R, can->FS1R); bank_is_empty = CAN_BANK_IS_EMPTY(device_data->filter_usage, bank_nr); if (!bank_is_empty && bank_mode != filter_type) { filter_nr = (bank_nr + 1) * 4; } else if (usage_shifted & usage_demand_mask) { device_data->filter_usage &= ~(usage_demand_mask << filter_nr); break; } else { filter_nr += register_demand; } if (!usage_shifted) { LOG_INF("No free filter bank found"); return CAN_NO_FREE_FILTER; } } while (filter_nr < CAN_MAX_NUMBER_OF_FILTERS); /* set the filter init mode */ can->FMR |= CAN_FMR_FINIT; can->FA1R &= ~bank_bit; /* TODO fifo balancing */ if (filter_type != bank_mode) { int shift_width, start_index; int res; u32_t mode_reg = can->FM1R; u32_t scale_reg = can->FS1R; can_stm32_set_mode_scale(filter_type, &mode_reg, &scale_reg, bank_nr); shift_width = filter_in_bank[filter_type] - filter_in_bank[bank_mode]; filter_index_new = can_calc_filter_index(filter_nr, mode_reg, scale_reg); start_index = filter_index_new + filter_in_bank[bank_mode]; if (shift_width && start_index <= CAN_MAX_NUMBER_OF_FILTERS) { res = can_stm32_shift_arr((void **)device_data->rx_cb, start_index, shift_width); res |= can_stm32_shift_arr(device_data->cb_arg, start_index, shift_width); if (filter_index_new >= CONFIG_CAN_MAX_FILTER || res) { LOG_INF("No space for a new filter!"); filter_nr = CAN_NO_FREE_FILTER; goto done; } } can->FM1R = mode_reg; can->FS1R = scale_reg; } else { filter_index_new = can_calc_filter_index(filter_nr, can->FM1R, can->FS1R); if (filter_index_new >= CAN_MAX_NUMBER_OF_FILTERS) { filter_nr = CAN_NO_FREE_FILTER; goto done; } } can_stm32_set_filter_bank(filter_nr, &can->sFilterRegister[bank_nr], filter_type, id, mask); done: can->FA1R |= bank_bit; can->FMR &= ~(CAN_FMR_FINIT); LOG_DBG("Filter set! Filter number: %d (index %d)", filter_nr, filter_index_new); *filter_index = filter_index_new; return filter_nr; } static inline int can_stm32_attach(struct device *dev, can_rx_callback_t cb, void *cb_arg, const struct zcan_filter *filter) { const struct can_stm32_config *cfg = DEV_CFG(dev); struct can_stm32_data *data = DEV_DATA(dev); CAN_TypeDef *can = cfg->can; int filter_index = 0; int filter_nr; filter_nr = can_stm32_set_filter(filter, data, can, &filter_index); if (filter_nr != CAN_NO_FREE_FILTER) { data->rx_cb[filter_index] = cb; data->cb_arg[filter_index] = cb_arg; } return filter_nr; } int can_stm32_attach_isr(struct device *dev, can_rx_callback_t isr, void *cb_arg, const struct zcan_filter *filter) { struct can_stm32_data *data = DEV_DATA(dev); int filter_nr; k_mutex_lock(&data->set_filter_mutex, K_FOREVER); filter_nr = can_stm32_attach(dev, isr, cb_arg, filter); k_mutex_unlock(&data->set_filter_mutex); return filter_nr; } void can_stm32_detach(struct device *dev, int filter_nr) { const struct can_stm32_config *cfg = DEV_CFG(dev); struct can_stm32_data *data = DEV_DATA(dev); CAN_TypeDef *can = cfg->can; int bank_nr; int filter_index; u32_t bank_bit; u32_t mode_reg; u32_t scale_reg; enum can_filter_type type; u32_t reset_mask; __ASSERT_NO_MSG(filter_nr >= 0 && filter_nr < CAN_MAX_NUMBER_OF_FILTERS); k_mutex_lock(&data->set_filter_mutex, K_FOREVER); bank_nr = filter_nr / 4; bank_bit = (1U << bank_nr); mode_reg = can->FM1R; scale_reg = can->FS1R; filter_index = can_calc_filter_index(filter_nr, mode_reg, scale_reg); type = can_stm32_get_filter_type(bank_nr, mode_reg, scale_reg); LOG_DBG("Detatch filter number %d (index %d), type %d", filter_nr, filter_index, type); reset_mask = ((1 << (reg_demand[type])) - 1) << filter_nr; data->filter_usage |= reset_mask; can->FMR |= CAN_FMR_FINIT; can->FA1R &= ~bank_bit; can_stm32_set_filter_bank(filter_nr, &can->sFilterRegister[bank_nr], type, 0, 0xFFFFFFFF); if (!CAN_BANK_IS_EMPTY(data->filter_usage, bank_nr)) { can->FA1R |= bank_bit; } else { LOG_DBG("Bank number %d is empty -> deakivate", bank_nr); } can->FMR &= ~(CAN_FMR_FINIT); data->rx_cb[filter_index] = NULL; data->cb_arg[filter_index] = NULL; k_mutex_unlock(&data->set_filter_mutex); } static const struct can_driver_api can_api_funcs = { .configure = can_stm32_runtime_configure, .send = can_stm32_send, .attach_isr = can_stm32_attach_isr, .detach = can_stm32_detach }; #ifdef CONFIG_CAN_1 static void config_can_1_irq(CAN_TypeDef *can); static const struct can_stm32_config can_stm32_cfg_1 = { .can = (CAN_TypeDef *)DT_CAN_1_BASE_ADDRESS, .bus_speed = DT_CAN_1_BUS_SPEED, .sjw = DT_CAN_1_SJW, .prop_ts1 = DT_CAN_1_PROP_SEG + DT_CAN_1_PHASE_SEG1, .ts2 = DT_CAN_1_PHASE_SEG2, .pclken = { .enr = DT_CAN_1_CLOCK_BITS, .bus = DT_CAN_1_CLOCK_BUS, }, .config_irq = config_can_1_irq }; static struct can_stm32_data can_stm32_dev_data_1; DEVICE_AND_API_INIT(can_stm32_1, DT_CAN_1_NAME, &can_stm32_init, &can_stm32_dev_data_1, &can_stm32_cfg_1, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &can_api_funcs); static void config_can_1_irq(CAN_TypeDef *can) { LOG_DBG("Enable CAN1 IRQ"); #ifdef CONFIG_SOC_SERIES_STM32F0X IRQ_CONNECT(DT_CAN_1_IRQ, DT_CAN_1_IRQ_PRIORITY, can_stm32_isr, DEVICE_GET(can_stm32_1), 0); irq_enable(DT_CAN_1_IRQ); #else IRQ_CONNECT(DT_CAN_1_IRQ_RX0, DT_CAN_1_IRQ_PRIORITY, can_stm32_rx_isr, DEVICE_GET(can_stm32_1), 0); irq_enable(DT_CAN_1_IRQ_RX0); IRQ_CONNECT(DT_CAN_1_IRQ_TX, DT_CAN_1_IRQ_PRIORITY, can_stm32_tx_isr, DEVICE_GET(can_stm32_1), 0); irq_enable(DT_CAN_1_IRQ_TX); IRQ_CONNECT(DT_CAN_1_IRQ_SCE, DT_CAN_1_IRQ_PRIORITY, can_stm32_tx_isr, DEVICE_GET(can_stm32_1), 0); irq_enable(DT_CAN_1_IRQ_SCE); #endif can->IER |= CAN_IER_TMEIE | CAN_IER_ERRIE | CAN_IER_FMPIE0 | CAN_IER_FMPIE1 | CAN_IER_BOFIE; } #if defined(CONFIG_NET_SOCKETS_CAN) #include "socket_can_generic.h" static int socket_can_init_1(struct device *dev) { struct device *can_dev = DEVICE_GET(can_stm32_1); struct socket_can_context *socket_context = dev->driver_data; LOG_DBG("Init socket CAN device %p (%s) for dev %p (%s)", dev, dev->config->name, can_dev, can_dev->config->name); socket_context->can_dev = can_dev; socket_context->msgq = &socket_can_msgq; socket_context->rx_tid = k_thread_create(&socket_context->rx_thread_data, rx_thread_stack, K_THREAD_STACK_SIZEOF(rx_thread_stack), rx_thread, socket_context, NULL, NULL, RX_THREAD_PRIORITY, 0, K_NO_WAIT); return 0; } NET_DEVICE_INIT(socket_can_stm32_1, SOCKET_CAN_NAME_1, socket_can_init_1, &socket_can_context_1, NULL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &socket_can_api, CANBUS_RAW_L2, NET_L2_GET_CTX_TYPE(CANBUS_RAW_L2), CAN_MTU); #endif /* CONFIG_NET_SOCKETS_CAN */ #endif /*CONFIG_CAN_1*/
torsteingrindvik/fw-nrfconnect-zephyr
soc/arm/st_stm32/stm32l4/dts_fixup.h
<filename>soc/arm/st_stm32/stm32l4/dts_fixup.h<gh_stars>1-10 /* SPDX-License-Identifier: Apache-2.0 */ /* SoC level DTS fixup file */ #define DT_NUM_IRQ_PRIO_BITS DT_ARM_V7M_NVIC_E000E100_ARM_NUM_IRQ_PRIORITY_BITS #define DT_GPIO_STM32_GPIOA_BASE_ADDRESS DT_ST_STM32_GPIO_48000000_BASE_ADDRESS #define DT_GPIO_STM32_GPIOA_CLOCK_BITS_0 DT_ST_STM32_GPIO_48000000_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOA_CLOCK_BUS_0 DT_ST_STM32_GPIO_48000000_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOA_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48000000_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOA_LABEL DT_ST_STM32_GPIO_48000000_LABEL #define DT_GPIO_STM32_GPIOA_SIZE DT_ST_STM32_GPIO_48000000_SIZE #define DT_GPIO_STM32_GPIOA_CLOCK_BITS DT_ST_STM32_GPIO_48000000_CLOCK_BITS #define DT_GPIO_STM32_GPIOA_CLOCK_BUS DT_ST_STM32_GPIO_48000000_CLOCK_BUS #define DT_GPIO_STM32_GPIOB_BASE_ADDRESS DT_ST_STM32_GPIO_48000400_BASE_ADDRESS #define DT_GPIO_STM32_GPIOB_CLOCK_BITS_0 DT_ST_STM32_GPIO_48000400_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOB_CLOCK_BUS_0 DT_ST_STM32_GPIO_48000400_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOB_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48000400_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOB_LABEL DT_ST_STM32_GPIO_48000400_LABEL #define DT_GPIO_STM32_GPIOB_SIZE DT_ST_STM32_GPIO_48000400_SIZE #define DT_GPIO_STM32_GPIOB_CLOCK_BITS DT_ST_STM32_GPIO_48000400_CLOCK_BITS #define DT_GPIO_STM32_GPIOB_CLOCK_BUS DT_ST_STM32_GPIO_48000400_CLOCK_BUS #define DT_GPIO_STM32_GPIOC_BASE_ADDRESS DT_ST_STM32_GPIO_48000800_BASE_ADDRESS #define DT_GPIO_STM32_GPIOC_CLOCK_BITS_0 DT_ST_STM32_GPIO_48000800_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOC_CLOCK_BUS_0 DT_ST_STM32_GPIO_48000800_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOC_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48000800_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOC_LABEL DT_ST_STM32_GPIO_48000800_LABEL #define DT_GPIO_STM32_GPIOC_SIZE DT_ST_STM32_GPIO_48000800_SIZE #define DT_GPIO_STM32_GPIOC_CLOCK_BITS DT_ST_STM32_GPIO_48000800_CLOCK_BITS #define DT_GPIO_STM32_GPIOC_CLOCK_BUS DT_ST_STM32_GPIO_48000800_CLOCK_BUS #define DT_GPIO_STM32_GPIOD_BASE_ADDRESS DT_ST_STM32_GPIO_48000C00_BASE_ADDRESS #define DT_GPIO_STM32_GPIOD_CLOCK_BITS_0 DT_ST_STM32_GPIO_48000C00_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOD_CLOCK_BUS_0 DT_ST_STM32_GPIO_48000C00_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOD_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48000C00_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOD_LABEL DT_ST_STM32_GPIO_48000C00_LABEL #define DT_GPIO_STM32_GPIOD_SIZE DT_ST_STM32_GPIO_48000C00_SIZE #define DT_GPIO_STM32_GPIOD_CLOCK_BITS DT_ST_STM32_GPIO_48000C00_CLOCK_BITS #define DT_GPIO_STM32_GPIOD_CLOCK_BUS DT_ST_STM32_GPIO_48000C00_CLOCK_BUS #define DT_GPIO_STM32_GPIOE_BASE_ADDRESS DT_ST_STM32_GPIO_48001000_BASE_ADDRESS #define DT_GPIO_STM32_GPIOE_CLOCK_BITS_0 DT_ST_STM32_GPIO_48001000_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOE_CLOCK_BUS_0 DT_ST_STM32_GPIO_48001000_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOE_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48001000_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOE_LABEL DT_ST_STM32_GPIO_48001000_LABEL #define DT_GPIO_STM32_GPIOE_SIZE DT_ST_STM32_GPIO_48001000_SIZE #define DT_GPIO_STM32_GPIOE_CLOCK_BITS DT_ST_STM32_GPIO_48001000_CLOCK_BITS #define DT_GPIO_STM32_GPIOE_CLOCK_BUS DT_ST_STM32_GPIO_48001000_CLOCK_BUS #define DT_GPIO_STM32_GPIOF_BASE_ADDRESS DT_ST_STM32_GPIO_48001400_BASE_ADDRESS #define DT_GPIO_STM32_GPIOF_CLOCK_BITS_0 DT_ST_STM32_GPIO_48001400_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOF_CLOCK_BUS_0 DT_ST_STM32_GPIO_48001400_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOF_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48001400_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOF_LABEL DT_ST_STM32_GPIO_48001400_LABEL #define DT_GPIO_STM32_GPIOF_SIZE DT_ST_STM32_GPIO_48001400_SIZE #define DT_GPIO_STM32_GPIOF_CLOCK_BITS DT_ST_STM32_GPIO_48001400_CLOCK_BITS #define DT_GPIO_STM32_GPIOF_CLOCK_BUS DT_ST_STM32_GPIO_48001400_CLOCK_BUS #define DT_GPIO_STM32_GPIOG_BASE_ADDRESS DT_ST_STM32_GPIO_48001800_BASE_ADDRESS #define DT_GPIO_STM32_GPIOG_CLOCK_BITS_0 DT_ST_STM32_GPIO_48001800_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOG_CLOCK_BUS_0 DT_ST_STM32_GPIO_48001800_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOG_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48001800_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOG_LABEL DT_ST_STM32_GPIO_48001800_LABEL #define DT_GPIO_STM32_GPIOG_SIZE DT_ST_STM32_GPIO_48001800_SIZE #define DT_GPIO_STM32_GPIOG_CLOCK_BITS DT_ST_STM32_GPIO_48001800_CLOCK_BITS #define DT_GPIO_STM32_GPIOG_CLOCK_BUS DT_ST_STM32_GPIO_48001800_CLOCK_BUS #define DT_GPIO_STM32_GPIOH_BASE_ADDRESS DT_ST_STM32_GPIO_48001C00_BASE_ADDRESS #define DT_GPIO_STM32_GPIOH_CLOCK_BITS_0 DT_ST_STM32_GPIO_48001C00_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOH_CLOCK_BUS_0 DT_ST_STM32_GPIO_48001C00_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOH_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48001C00_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOH_LABEL DT_ST_STM32_GPIO_48001C00_LABEL #define DT_GPIO_STM32_GPIOH_SIZE DT_ST_STM32_GPIO_48001C00_SIZE #define DT_GPIO_STM32_GPIOH_CLOCK_BITS DT_ST_STM32_GPIO_48001C00_CLOCK_BITS #define DT_GPIO_STM32_GPIOH_CLOCK_BUS DT_ST_STM32_GPIO_48001C00_CLOCK_BUS #define DT_GPIO_STM32_GPIOI_BASE_ADDRESS DT_ST_STM32_GPIO_48002000_BASE_ADDRESS #define DT_GPIO_STM32_GPIOI_CLOCK_BITS_0 DT_ST_STM32_GPIO_48002000_CLOCK_BITS_0 #define DT_GPIO_STM32_GPIOI_CLOCK_BUS_0 DT_ST_STM32_GPIO_48002000_CLOCK_BUS_0 #define DT_GPIO_STM32_GPIOI_CLOCK_CONTROLLER DT_ST_STM32_GPIO_48002000_CLOCK_CONTROLLER #define DT_GPIO_STM32_GPIOI_LABEL DT_ST_STM32_GPIO_48002000_LABEL #define DT_GPIO_STM32_GPIOI_SIZE DT_ST_STM32_GPIO_48002000_SIZE #define DT_GPIO_STM32_GPIOI_CLOCK_BITS DT_ST_STM32_GPIO_48002000_CLOCK_BITS #define DT_GPIO_STM32_GPIOI_CLOCK_BUS DT_ST_STM32_GPIO_48002000_CLOCK_BUS #define DT_UART_STM32_USART_1_BASE_ADDRESS DT_ST_STM32_USART_40013800_BASE_ADDRESS #define DT_UART_STM32_USART_1_BAUD_RATE DT_ST_STM32_USART_40013800_CURRENT_SPEED #define DT_UART_STM32_USART_1_IRQ_PRI DT_ST_STM32_USART_40013800_IRQ_0_PRIORITY #define DT_UART_STM32_USART_1_NAME DT_ST_STM32_USART_40013800_LABEL #define DT_USART_1_IRQ DT_ST_STM32_USART_40013800_IRQ_0 #define DT_UART_STM32_USART_1_CLOCK_BITS DT_ST_STM32_USART_40013800_CLOCK_BITS #define DT_UART_STM32_USART_1_CLOCK_BUS DT_ST_STM32_USART_40013800_CLOCK_BUS #define DT_UART_STM32_USART_1_HW_FLOW_CONTROL DT_ST_STM32_USART_40013800_HW_FLOW_CONTROL #define DT_UART_STM32_USART_2_BASE_ADDRESS DT_ST_STM32_USART_40004400_BASE_ADDRESS #define DT_UART_STM32_USART_2_BAUD_RATE DT_ST_STM32_USART_40004400_CURRENT_SPEED #define DT_UART_STM32_USART_2_IRQ_PRI DT_ST_STM32_USART_40004400_IRQ_0_PRIORITY #define DT_UART_STM32_USART_2_NAME DT_ST_STM32_USART_40004400_LABEL #define DT_USART_2_IRQ DT_ST_STM32_USART_40004400_IRQ_0 #define DT_UART_STM32_USART_2_CLOCK_BITS DT_ST_STM32_USART_40004400_CLOCK_BITS #define DT_UART_STM32_USART_2_CLOCK_BUS DT_ST_STM32_USART_40004400_CLOCK_BUS #define DT_UART_STM32_USART_2_HW_FLOW_CONTROL DT_ST_STM32_USART_40004400_HW_FLOW_CONTROL #define DT_UART_STM32_USART_3_BASE_ADDRESS DT_ST_STM32_USART_40004800_BASE_ADDRESS #define DT_UART_STM32_USART_3_BAUD_RATE DT_ST_STM32_USART_40004800_CURRENT_SPEED #define DT_UART_STM32_USART_3_IRQ_PRI DT_ST_STM32_USART_40004800_IRQ_0_PRIORITY #define DT_UART_STM32_USART_3_NAME DT_ST_STM32_USART_40004800_LABEL #define DT_USART_3_IRQ DT_ST_STM32_USART_40004800_IRQ_0 #define DT_UART_STM32_USART_3_CLOCK_BITS DT_ST_STM32_USART_40004800_CLOCK_BITS #define DT_UART_STM32_USART_3_CLOCK_BUS DT_ST_STM32_USART_40004800_CLOCK_BUS #define DT_UART_STM32_USART_3_HW_FLOW_CONTROL DT_ST_STM32_USART_40004800_HW_FLOW_CONTROL #define DT_UART_STM32_UART_4_BASE_ADDRESS DT_ST_STM32_UART_40004C00_BASE_ADDRESS #define DT_UART_STM32_UART_4_BAUD_RATE DT_ST_STM32_UART_40004C00_CURRENT_SPEED #define DT_UART_STM32_UART_4_IRQ_PRI DT_ST_STM32_UART_40004C00_IRQ_0_PRIORITY #define DT_UART_STM32_UART_4_NAME DT_ST_STM32_UART_40004C00_LABEL #define DT_UART_4_IRQ DT_ST_STM32_UART_40004C00_IRQ_0 #define DT_UART_STM32_UART_4_CLOCK_BITS DT_ST_STM32_UART_40004C00_CLOCK_BITS #define DT_UART_STM32_UART_4_CLOCK_BUS DT_ST_STM32_UART_40004C00_CLOCK_BUS #define DT_UART_STM32_UART_4_HW_FLOW_CONTROL DT_ST_STM32_UART_40004C00_HW_FLOW_CONTROL #define DT_UART_STM32_UART_5_BASE_ADDRESS DT_ST_STM32_UART_40005000_BASE_ADDRESS #define DT_UART_STM32_UART_5_BAUD_RATE DT_ST_STM32_UART_40005000_CURRENT_SPEED #define DT_UART_STM32_UART_5_IRQ_PRI DT_ST_STM32_UART_40005000_IRQ_0_PRIORITY #define DT_UART_STM32_UART_5_NAME DT_ST_STM32_UART_40005000_LABEL #define DT_UART_5_IRQ DT_ST_STM32_UART_40005000_IRQ_0 #define DT_UART_STM32_UART_5_CLOCK_BITS DT_ST_STM32_UART_40005000_CLOCK_BITS #define DT_UART_STM32_UART_5_CLOCK_BUS DT_ST_STM32_UART_40005000_CLOCK_BUS #define DT_UART_STM32_UART_5_HW_FLOW_CONTROL DT_ST_STM32_UART_40005000_HW_FLOW_CONTROL #define DT_UART_STM32_LPUART_1_BASE_ADDRESS DT_ST_STM32_LPUART_40008000_BASE_ADDRESS #define DT_UART_STM32_LPUART_1_BAUD_RATE DT_ST_STM32_LPUART_40008000_CURRENT_SPEED #define DT_UART_STM32_LPUART_1_IRQ_PRI DT_ST_STM32_LPUART_40008000_IRQ_0_PRIORITY #define DT_UART_STM32_LPUART_1_NAME DT_ST_STM32_LPUART_40008000_LABEL #define DT_LPUART_1_IRQ DT_ST_STM32_LPUART_40008000_IRQ_0 #define DT_UART_STM32_LPUART_1_CLOCK_BITS DT_ST_STM32_LPUART_40008000_CLOCK_BITS #define DT_UART_STM32_LPUART_1_CLOCK_BUS DT_ST_STM32_LPUART_40008000_CLOCK_BUS #define DT_UART_STM32_LPUART_1_HW_FLOW_CONTROL DT_ST_STM32_LPUART_40008000_HW_FLOW_CONTROL #define DT_I2C_1_BASE_ADDRESS DT_ST_STM32_I2C_V2_40005400_BASE_ADDRESS #define DT_I2C_1_EVENT_IRQ_PRI DT_ST_STM32_I2C_V2_40005400_IRQ_EVENT_PRIORITY #define DT_I2C_1_ERROR_IRQ_PRI DT_ST_STM32_I2C_V2_40005400_IRQ_ERROR_PRIORITY #define CONFIG_I2C_1_NAME DT_ST_STM32_I2C_V2_40005400_LABEL #define DT_I2C_1_EVENT_IRQ DT_ST_STM32_I2C_V2_40005400_IRQ_EVENT #define DT_I2C_1_ERROR_IRQ DT_ST_STM32_I2C_V2_40005400_IRQ_ERROR #define DT_I2C_1_BITRATE DT_ST_STM32_I2C_V2_40005400_CLOCK_FREQUENCY #define DT_I2C_1_CLOCK_BITS DT_ST_STM32_I2C_V2_40005400_CLOCK_BITS #define DT_I2C_1_CLOCK_BUS DT_ST_STM32_I2C_V2_40005400_CLOCK_BUS #define DT_I2C_2_BASE_ADDRESS DT_ST_STM32_I2C_V2_40005800_BASE_ADDRESS #define DT_I2C_2_EVENT_IRQ_PRI DT_ST_STM32_I2C_V2_40005800_IRQ_EVENT_PRIORITY #define DT_I2C_2_ERROR_IRQ_PRI DT_ST_STM32_I2C_V2_40005800_IRQ_ERROR_PRIORITY #define CONFIG_I2C_2_NAME DT_ST_STM32_I2C_V2_40005800_LABEL #define DT_I2C_2_EVENT_IRQ DT_ST_STM32_I2C_V2_40005800_IRQ_EVENT #define DT_I2C_2_ERROR_IRQ DT_ST_STM32_I2C_V2_40005800_IRQ_ERROR #define DT_I2C_2_BITRATE DT_ST_STM32_I2C_V2_40005800_CLOCK_FREQUENCY #define DT_I2C_2_CLOCK_BITS DT_ST_STM32_I2C_V2_40005800_CLOCK_BITS #define DT_I2C_2_CLOCK_BUS DT_ST_STM32_I2C_V2_40005800_CLOCK_BUS #define DT_I2C_3_BASE_ADDRESS DT_ST_STM32_I2C_V2_40005C00_BASE_ADDRESS #define DT_I2C_3_EVENT_IRQ_PRI DT_ST_STM32_I2C_V2_40005C00_IRQ_EVENT_PRIORITY #define DT_I2C_3_ERROR_IRQ_PRI DT_ST_STM32_I2C_V2_40005C00_IRQ_ERROR_PRIORITY #define CONFIG_I2C_3_NAME DT_ST_STM32_I2C_V2_40005C00_LABEL #define DT_I2C_3_EVENT_IRQ DT_ST_STM32_I2C_V2_40005C00_IRQ_EVENT #define DT_I2C_3_ERROR_IRQ DT_ST_STM32_I2C_V2_40005C00_IRQ_ERROR #define DT_I2C_3_BITRATE DT_ST_STM32_I2C_V2_40005C00_CLOCK_FREQUENCY #define DT_I2C_3_CLOCK_BITS DT_ST_STM32_I2C_V2_40005C00_CLOCK_BITS #define DT_I2C_3_CLOCK_BUS DT_ST_STM32_I2C_V2_40005C00_CLOCK_BUS #define DT_I2C_4_BASE_ADDRESS DT_ST_STM32_I2C_V2_40008400_BASE_ADDRESS #define DT_I2C_4_EVENT_IRQ_PRI DT_ST_STM32_I2C_V2_40008400_IRQ_EVENT_PRIORITY #define DT_I2C_4_ERROR_IRQ_PRI DT_ST_STM32_I2C_V2_40008400_IRQ_ERROR_PRIORITY #define CONFIG_I2C_4_NAME DT_ST_STM32_I2C_V2_40008400_LABEL #define DT_I2C_4_EVENT_IRQ DT_ST_STM32_I2C_V2_40008400_IRQ_EVENT #define DT_I2C_4_ERROR_IRQ DT_ST_STM32_I2C_V2_40008400_IRQ_ERROR #define DT_I2C_4_BITRATE DT_ST_STM32_I2C_V2_40008400_CLOCK_FREQUENCY #define DT_I2C_4_CLOCK_BITS DT_ST_STM32_I2C_V2_40008400_CLOCK_BITS #define DT_I2C_4_CLOCK_BUS DT_ST_STM32_I2C_V2_40008400_CLOCK_BUS #define DT_RTC_0_BASE_ADDRESS DT_ST_STM32_RTC_40002800_BASE_ADDRESS #define DT_RTC_0_IRQ_PRI DT_ST_STM32_RTC_40002800_IRQ_0_PRIORITY #define DT_RTC_0_IRQ DT_ST_STM32_RTC_40002800_IRQ_0 #define DT_RTC_0_NAME DT_ST_STM32_RTC_40002800_LABEL #define DT_RTC_0_CLOCK_BITS DT_ST_STM32_RTC_40002800_CLOCK_BITS #define DT_RTC_0_CLOCK_BUS DT_ST_STM32_RTC_40002800_CLOCK_BUS #define DT_SPI_1_BASE_ADDRESS DT_ST_STM32_SPI_FIFO_40013000_BASE_ADDRESS #define DT_SPI_1_IRQ_PRI DT_ST_STM32_SPI_FIFO_40013000_IRQ_0_PRIORITY #define DT_SPI_1_NAME DT_ST_STM32_SPI_FIFO_40013000_LABEL #define DT_SPI_1_IRQ DT_ST_STM32_SPI_FIFO_40013000_IRQ_0 #define DT_SPI_1_CLOCK_BITS DT_ST_STM32_SPI_FIFO_40013000_CLOCK_BITS #define DT_SPI_1_CLOCK_BUS DT_ST_STM32_SPI_FIFO_40013000_CLOCK_BUS #define DT_SPI_2_BASE_ADDRESS DT_ST_STM32_SPI_FIFO_40003800_BASE_ADDRESS #define DT_SPI_2_IRQ_PRI DT_ST_STM32_SPI_FIFO_40003800_IRQ_0_PRIORITY #define DT_SPI_2_NAME DT_ST_STM32_SPI_FIFO_40003800_LABEL #define DT_SPI_2_IRQ DT_ST_STM32_SPI_FIFO_40003800_IRQ_0 #define DT_SPI_2_CLOCK_BITS DT_ST_STM32_SPI_FIFO_40003800_CLOCK_BITS #define DT_SPI_2_CLOCK_BUS DT_ST_STM32_SPI_FIFO_40003800_CLOCK_BUS #define DT_SPI_3_BASE_ADDRESS DT_ST_STM32_SPI_FIFO_40003C00_BASE_ADDRESS #define DT_SPI_3_IRQ_PRI DT_ST_STM32_SPI_FIFO_40003C00_IRQ_0_PRIORITY #define DT_SPI_3_NAME DT_ST_STM32_SPI_FIFO_40003C00_LABEL #define DT_SPI_3_IRQ DT_ST_STM32_SPI_FIFO_40003C00_IRQ_0 #define DT_SPI_3_CLOCK_BITS DT_ST_STM32_SPI_FIFO_40003C00_CLOCK_BITS #define DT_SPI_3_CLOCK_BUS DT_ST_STM32_SPI_FIFO_40003C00_CLOCK_BUS #define DT_FLASH_DEV_BASE_ADDRESS DT_ST_STM32L4_FLASH_CONTROLLER_40022000_BASE_ADDRESS #define DT_FLASH_DEV_NAME DT_ST_STM32L4_FLASH_CONTROLLER_40022000_LABEL #if defined(DT_ST_STM32_USB_40006800_BASE_ADDRESS) #define DT_USB_BASE_ADDRESS DT_ST_STM32_USB_40006800_BASE_ADDRESS #define DT_USB_IRQ DT_ST_STM32_USB_40006800_IRQ_USB #define DT_USB_IRQ_PRI DT_ST_STM32_USB_40006800_IRQ_USB_PRIORITY #define DT_USB_NUM_BIDIR_ENDPOINTS DT_ST_STM32_USB_40006800_NUM_BIDIR_ENDPOINTS #define DT_USB_RAM_SIZE DT_ST_STM32_USB_40006800_RAM_SIZE #define DT_USB_CLOCK_BITS DT_ST_STM32_USB_40006800_CLOCK_BITS #define DT_USB_CLOCK_BUS DT_ST_STM32_USB_40006800_CLOCK_BUS #endif #if defined(DT_ST_STM32_OTGFS_50000000_BASE_ADDRESS) #define DT_USB_BASE_ADDRESS DT_ST_STM32_OTGFS_50000000_BASE_ADDRESS #define DT_USB_IRQ DT_ST_STM32_OTGFS_50000000_IRQ_OTGFS #define DT_USB_IRQ_PRI DT_ST_STM32_OTGFS_50000000_IRQ_OTGFS_PRIORITY #define DT_USB_NUM_BIDIR_ENDPOINTS DT_ST_STM32_OTGFS_50000000_NUM_BIDIR_ENDPOINTS #define DT_USB_RAM_SIZE DT_ST_STM32_OTGFS_50000000_RAM_SIZE #define DT_USB_MAXIMUM_SPEED DT_ST_STM32_OTGFS_50000000_MAXIMUM_SPEED #define DT_USB_CLOCK_BITS DT_ST_STM32_OTGFS_50000000_CLOCK_BITS #define DT_USB_CLOCK_BUS DT_ST_STM32_OTGFS_50000000_CLOCK_BUS #endif #define DT_PWM_STM32_1_DEV_NAME DT_ST_STM32_PWM_40012C00_PWM_LABEL #define DT_PWM_STM32_1_PRESCALER DT_ST_STM32_PWM_40012C00_PWM_ST_PRESCALER #define DT_TIM_STM32_1_BASE_ADDRESS DT_ST_STM32_TIMERS_40012C00_BASE_ADDRESS #define DT_TIM_STM32_1_CLOCK_BITS DT_ST_STM32_TIMERS_40012C00_CLOCK_BITS #define DT_TIM_STM32_1_CLOCK_BUS DT_ST_STM32_TIMERS_40012C00_CLOCK_BUS #define DT_PWM_STM32_2_DEV_NAME DT_ST_STM32_PWM_40000000_PWM_LABEL #define DT_PWM_STM32_2_PRESCALER DT_ST_STM32_PWM_40000000_PWM_ST_PRESCALER #define DT_TIM_STM32_2_BASE_ADDRESS DT_ST_STM32_TIMERS_40000000_BASE_ADDRESS #define DT_TIM_STM32_2_CLOCK_BITS DT_ST_STM32_TIMERS_40000000_CLOCK_BITS #define DT_TIM_STM32_2_CLOCK_BUS DT_ST_STM32_TIMERS_40000000_CLOCK_BUS #define DT_PWM_STM32_3_DEV_NAME DT_ST_STM32_PWM_40000400_PWM_LABEL #define DT_PWM_STM32_3_PRESCALER DT_ST_STM32_PWM_40000400_PWM_ST_PRESCALER #define DT_TIM_STM32_3_BASE_ADDRESS DT_ST_STM32_TIMERS_40000400_BASE_ADDRESS #define DT_TIM_STM32_3_CLOCK_BITS DT_ST_STM32_TIMERS_40000400_CLOCK_BITS #define DT_TIM_STM32_3_CLOCK_BUS DT_ST_STM32_TIMERS_40000400_CLOCK_BUS #define DT_PWM_STM32_4_DEV_NAME DT_ST_STM32_PWM_40000800_PWM_LABEL #define DT_PWM_STM32_4_PRESCALER DT_ST_STM32_PWM_40000800_PWM_ST_PRESCALER #define DT_TIM_STM32_4_BASE_ADDRESS DT_ST_STM32_TIMERS_40000800_BASE_ADDRESS #define DT_TIM_STM32_4_CLOCK_BITS DT_ST_STM32_TIMERS_40000800_CLOCK_BITS #define DT_TIM_STM32_4_CLOCK_BUS DT_ST_STM32_TIMERS_40000800_CLOCK_BUS #define DT_PWM_STM32_5_DEV_NAME DT_ST_STM32_PWM_40000C00_PWM_LABEL #define DT_PWM_STM32_5_PRESCALER DT_ST_STM32_PWM_40000C00_PWM_ST_PRESCALER #define DT_TIM_STM32_5_BASE_ADDRESS DT_ST_STM32_TIMERS_40000C00_BASE_ADDRESS #define DT_TIM_STM32_5_CLOCK_BITS DT_ST_STM32_TIMERS_40000C00_CLOCK_BITS #define DT_TIM_STM32_5_CLOCK_BUS DT_ST_STM32_TIMERS_40000C00_CLOCK_BUS #define DT_PWM_STM32_6_DEV_NAME DT_ST_STM32_PWM_40001000_PWM_LABEL #define DT_PWM_STM32_6_PRESCALER DT_ST_STM32_PWM_40001000_PWM_ST_PRESCALER #define DT_TIM_STM32_6_BASE_ADDRESS DT_ST_STM32_TIMERS_40001000_BASE_ADDRESS #define DT_TIM_STM32_6_CLOCK_BITS DT_ST_STM32_TIMERS_40001000_CLOCK_BITS #define DT_TIM_STM32_6_CLOCK_BUS DT_ST_STM32_TIMERS_40001000_CLOCK_BUS #define DT_PWM_STM32_7_DEV_NAME DT_ST_STM32_PWM_40001400_PWM_LABEL #define DT_PWM_STM32_7_PRESCALER DT_ST_STM32_PWM_40001400_PWM_ST_PRESCALER #define DT_TIM_STM32_7_BASE_ADDRESS DT_ST_STM32_TIMERS_40001400_BASE_ADDRESS #define DT_TIM_STM32_7_CLOCK_BITS DT_ST_STM32_TIMERS_40001400_CLOCK_BITS #define DT_TIM_STM32_7_CLOCK_BUS DT_ST_STM32_TIMERS_40001400_CLOCK_BUS #define DT_PWM_STM32_8_DEV_NAME DT_ST_STM32_PWM_40013400_PWM_LABEL #define DT_PWM_STM32_8_PRESCALER DT_ST_STM32_PWM_40013400_PWM_ST_PRESCALER #define DT_TIM_STM32_8_BASE_ADDRESS DT_ST_STM32_TIMERS_40013400_BASE_ADDRESS #define DT_TIM_STM32_8_CLOCK_BITS DT_ST_STM32_TIMERS_40013400_CLOCK_BITS #define DT_TIM_STM32_8_CLOCK_BUS DT_ST_STM32_TIMERS_40013400_CLOCK_BUS #define DT_PWM_STM32_15_DEV_NAME DT_ST_STM32_PWM_40014000_PWM_LABEL #define DT_PWM_STM32_15_PRESCALER DT_ST_STM32_PWM_40014000_PWM_ST_PRESCALER #define DT_TIM_STM32_15_BASE_ADDRESS DT_ST_STM32_TIMERS_40014000_BASE_ADDRESS #define DT_TIM_STM32_15_CLOCK_BITS DT_ST_STM32_TIMERS_40014000_CLOCK_BITS #define DT_TIM_STM32_15_CLOCK_BUS DT_ST_STM32_TIMERS_40014000_CLOCK_BUS #define DT_PWM_STM32_16_DEV_NAME DT_ST_STM32_PWM_40014400_PWM_LABEL #define DT_PWM_STM32_16_PRESCALER DT_ST_STM32_PWM_40014400_PWM_ST_PRESCALER #define DT_TIM_STM32_16_BASE_ADDRESS DT_ST_STM32_TIMERS_40014400_BASE_ADDRESS #define DT_TIM_STM32_16_CLOCK_BITS DT_ST_STM32_TIMERS_40014400_CLOCK_BITS #define DT_TIM_STM32_16_CLOCK_BUS DT_ST_STM32_TIMERS_40014400_CLOCK_BUS #define DT_PWM_STM32_17_DEV_NAME DT_ST_STM32_PWM_40014800_PWM_LABEL #define DT_PWM_STM32_17_PRESCALER DT_ST_STM32_PWM_40014800_PWM_ST_PRESCALER #define DT_TIM_STM32_17_BASE_ADDRESS DT_ST_STM32_TIMERS_40014800_BASE_ADDRESS #define DT_TIM_STM32_17_CLOCK_BITS DT_ST_STM32_TIMERS_40014800_CLOCK_BITS #define DT_TIM_STM32_17_CLOCK_BUS DT_ST_STM32_TIMERS_40014800_CLOCK_BUS #define DT_CAN_1_BASE_ADDRESS DT_ST_STM32_CAN_40006400_BASE_ADDRESS #define DT_CAN_1_BUS_SPEED DT_ST_STM32_CAN_40006400_BUS_SPEED #define DT_CAN_1_NAME DT_ST_STM32_CAN_40006400_LABEL #define DT_CAN_1_IRQ_TX DT_ST_STM32_CAN_40006400_IRQ_TX #define DT_CAN_1_IRQ_RX0 DT_ST_STM32_CAN_40006400_IRQ_RX0 #define DT_CAN_1_IRQ_RX1 DT_ST_STM32_CAN_40006400_IRQ_RX1 #define DT_CAN_1_IRQ_SCE DT_ST_STM32_CAN_40006400_IRQ_SCE #define DT_CAN_1_IRQ_PRIORITY DT_ST_STM32_CAN_40006400_IRQ_0_PRIORITY #define DT_CAN_1_SJW DT_ST_STM32_CAN_40006400_SJW #define DT_CAN_1_PROP_SEG DT_ST_STM32_CAN_40006400_PROP_SEG #define DT_CAN_1_PHASE_SEG1 DT_ST_STM32_CAN_40006400_PHASE_SEG1 #define DT_CAN_1_PHASE_SEG2 DT_ST_STM32_CAN_40006400_PHASE_SEG2 #define DT_CAN_1_CLOCK_BUS DT_ST_STM32_CAN_40006400_CLOCK_BUS #define DT_CAN_1_CLOCK_BITS DT_ST_STM32_CAN_40006400_CLOCK_BITS #define DT_WDT_0_NAME DT_INST_0_ST_STM32_WATCHDOG_LABEL #define DT_WWDT_0_BASE_ADDRESS DT_INST_0_ST_STM32_WINDOW_WATCHDOG_BASE_ADDRESS #define DT_WWDT_0_NAME DT_INST_0_ST_STM32_WINDOW_WATCHDOG_LABEL #define DT_WWDT_0_IRQ DT_INST_0_ST_STM32_WINDOW_WATCHDOG_IRQ_0 #define DT_WWDT_0_IRQ_PRI DT_INST_0_ST_STM32_WINDOW_WATCHDOG_IRQ_0_PRIORITY #define DT_WWDT_0_CLOCK_BITS DT_INST_0_ST_STM32_WINDOW_WATCHDOG_CLOCK_BITS #define DT_WWDT_0_CLOCK_BUS DT_INST_0_ST_STM32_WINDOW_WATCHDOG_CLOCK_BUS #define DT_ADC_1_BASE_ADDRESS DT_ST_STM32_ADC_50040000_BASE_ADDRESS #define DT_ADC_1_IRQ DT_ST_STM32_ADC_50040000_IRQ_0 #define DT_ADC_1_IRQ_PRI DT_ST_STM32_ADC_50040000_IRQ_0_PRIORITY #define DT_ADC_1_NAME DT_ST_STM32_ADC_50040000_LABEL #define DT_ADC_1_CLOCK_BITS DT_ST_STM32_ADC_50040000_CLOCK_BITS_0 #define DT_ADC_1_CLOCK_BUS DT_ST_STM32_ADC_50040000_CLOCK_BUS_0 /* End of SoC Level DTS fixup file */
torsteingrindvik/fw-nrfconnect-zephyr
include/arch/arc/v2/irq.h
<filename>include/arch/arc/v2/irq.h /* * Copyright (c) 2014 Wind River Systems, Inc. * * SPDX-License-Identifier: Apache-2.0 */ /** * @file * @brief ARCv2 public interrupt handling * * ARCv2 kernel interrupt handling interface. Included by arc/arch.h. */ #ifndef ZEPHYR_INCLUDE_ARCH_ARC_V2_IRQ_H_ #define ZEPHYR_INCLUDE_ARCH_ARC_V2_IRQ_H_ #include <arch/arc/v2/aux_regs.h> #include <toolchain/common.h> #include <irq.h> #include <sys/util.h> #include <sw_isr_table.h> #ifdef __cplusplus extern "C" { #endif #ifdef _ASMLANGUAGE GTEXT(_irq_exit); GTEXT(z_arch_irq_enable) GTEXT(z_arch_irq_disable) #else extern void z_arch_irq_enable(unsigned int irq); extern void z_arch_irq_disable(unsigned int irq); extern void _irq_exit(void); extern void z_irq_priority_set(unsigned int irq, unsigned int prio, u32_t flags); extern void _isr_wrapper(void); extern void z_irq_spurious(void *unused); /* Z_ISR_DECLARE will populate the .intList section with the interrupt's * parameters, which will then be used by gen_irq_tables.py to create * the vector table and the software ISR table. This is all done at * build-time. * * We additionally set the priority in the interrupt controller at * runtime. */ #define Z_ARCH_IRQ_CONNECT(irq_p, priority_p, isr_p, isr_param_p, flags_p) \ ({ \ Z_ISR_DECLARE(irq_p, 0, isr_p, isr_param_p); \ z_irq_priority_set(irq_p, priority_p, flags_p); \ irq_p; \ }) static ALWAYS_INLINE unsigned int z_arch_irq_lock(void) { unsigned int key; __asm__ volatile("clri %0" : "=r"(key):: "memory"); return key; } static ALWAYS_INLINE void z_arch_irq_unlock(unsigned int key) { __asm__ volatile("seti %0" : : "ir"(key) : "memory"); } static ALWAYS_INLINE bool z_arch_irq_unlocked(unsigned int key) { /* ARC irq lock uses instruction "clri r0", * r0 == {26’d0, 1’b1, STATUS32.IE, STATUS32.E[3:0] } * bit4 is used to record IE (Interrupt Enable) bit */ return (key & 0x10) == 0x10; } #endif /* _ASMLANGUAGE */ #ifdef __cplusplus } #endif #endif /* ZEPHYR_INCLUDE_ARCH_ARC_V2_IRQ_H_ */
torsteingrindvik/fw-nrfconnect-zephyr
samples/boards/nrf52/mesh/onoff_level_lighting_vnd_app/src/mesh/no_transition_work_handler.c
<filename>samples/boards/nrf52/mesh/onoff_level_lighting_vnd_app/src/mesh/no_transition_work_handler.c /* Bluetooth: Mesh Generic OnOff, Generic Level, Lighting & Vendor Models * * Copyright (c) 2018 <NAME> * * SPDX-License-Identifier: Apache-2.0 */ #include "common.h" #include "ble_mesh.h" #include "device_composition.h" #include "state_binding.h" #include "storage.h" static void unsolicitedly_publish_states_work_handler(struct k_work *work) { gen_onoff_publish(&root_models[2]); gen_level_publish(&root_models[4]); light_lightness_publish(&root_models[11]); light_lightness_linear_publish(&root_models[11]); light_ctl_publish(&root_models[14]); gen_level_publish(&s0_models[0]); light_ctl_temp_publish(&s0_models[2]); } K_WORK_DEFINE(unsolicitedly_publish_states_work, unsolicitedly_publish_states_work_handler); static void unsolicitedly_publish_states_timer_handler(struct k_timer *dummy) { k_work_submit(&unsolicitedly_publish_states_work); } K_TIMER_DEFINE(unsolicitedly_publish_states_timer, unsolicitedly_publish_states_timer_handler, NULL); static void save_lightness_temp_last_values_timer_handler(struct k_timer *dummy) { save_on_flash(LIGHTNESS_TEMP_LAST_STATE); } K_TIMER_DEFINE(save_lightness_temp_last_values_timer, save_lightness_temp_last_values_timer_handler, NULL); static void no_transition_work_handler(struct k_work *work) { bool readjust_light_state; readjust_light_state = false; if (!bt_mesh_is_provisioned()) { return; } if (target_lightness != lightness) { lightness = target_lightness; readjust_lightness(); readjust_light_state = true; } if (target_temperature != temperature) { temperature = target_temperature; readjust_temperature(); readjust_light_state = true; } if (readjust_light_state) { update_led_gpio(); } k_timer_start(&unsolicitedly_publish_states_timer, K_MSEC(5000), K_NO_WAIT); /* If Lightness & Temperature values remains stable for * 10 Seconds then & then only get stored on SoC flash. */ if (gen_power_onoff_srv_user_data.onpowerup == STATE_RESTORE) { k_timer_start(&save_lightness_temp_last_values_timer, K_MSEC(10000), K_NO_WAIT); } } K_WORK_DEFINE(no_transition_work, no_transition_work_handler);
torsteingrindvik/fw-nrfconnect-zephyr
arch/x86/include/kernel_arch_data.h
<gh_stars>1-10 /* * Copyright (c) 2019 Intel Corporation * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_ARCH_X86_INCLUDE_KERNEL_ARCH_DATA_H_ #define ZEPHYR_ARCH_X86_INCLUDE_KERNEL_ARCH_DATA_H_ /* * Exception/interrupt vector definitions: vectors 20 to 31 are reserved * for Intel; vectors 32 to 255 are user defined interrupt vectors. */ #define IV_DIVIDE_ERROR 0 #define IV_DEBUG 1 #define IV_NON_MASKABLE_INTERRUPT 2 #define IV_BREAKPOINT 3 #define IV_OVERFLOW 4 #define IV_BOUND_RANGE 5 #define IV_INVALID_OPCODE 6 #define IV_DEVICE_NOT_AVAILABLE 7 #define IV_DOUBLE_FAULT 8 #define IV_COPROC_SEGMENT_OVERRUN 9 #define IV_INVALID_TSS 10 #define IV_SEGMENT_NOT_PRESENT 11 #define IV_STACK_FAULT 12 #define IV_GENERAL_PROTECTION 13 #define IV_PAGE_FAULT 14 #define IV_RESERVED 15 #define IV_X87_FPU_FP_ERROR 16 #define IV_ALIGNMENT_CHECK 17 #define IV_MACHINE_CHECK 18 #define IV_SIMD_FP 19 #define IV_IRQS 32 /* start of vectors available for IRQs */ #define IV_NR_VECTORS 256 /* total number of vectors */ /* * EFLAGS/RFLAGS definitions. (RFLAGS is just zero-extended EFLAGS.) */ #define EFLAGS_IF 0x00000200U /* interrupts enabled */ #define EFLAGS_INITIAL (EFLAGS_IF) /* * Control register definitions. */ #define CR0_PG 0x80000000 /* enable paging */ #define CR0_WP 0x00010000 /* honor W bit even when supervisor */ #define CR4_PAE 0x00000020 /* enable PAE */ #define CR4_OSFXSR 0x00000200 /* enable SSE (OS FXSAVE/RSTOR) */ #ifdef CONFIG_X86_LONGMODE #include <intel64/kernel_arch_data.h> #else #include <ia32/kernel_arch_data.h> #endif #endif /* ZEPHYR_ARCH_X86_INCLUDE_KERNEL_ARCH_DATA_H_ */
torsteingrindvik/fw-nrfconnect-zephyr
include/arch/x86_64/arch.h
<filename>include/arch/x86_64/arch.h /* * Copyright (c) 2018 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef _X86_64_ARCH_H #define _X86_64_ARCH_H #include <arch/common/sys_io.h> #include <arch/common/ffs.h> #define STACK_ALIGN 8 #define DT_INST_0_INTEL_HPET_BASE_ADDRESS 0xFED00000U #define DT_INST_0_INTEL_HPET_IRQ_0 2 #define DT_INST_0_INTEL_HPET_IRQ_0_PRIORITY 4 typedef struct z_arch_esf_t z_arch_esf_t; static inline u32_t z_arch_k_cycle_get_32(void) { #ifdef CONFIG_HPET_TIMER extern u32_t z_timer_cycle_get_32(void); return z_timer_cycle_get_32(); #else return (u32_t)z_arch_k_cycle_get_64(); #endif } /* Not a standard Zephyr function, but probably will be */ static inline unsigned long long z_arch_k_cycle_get_64(void) { unsigned int hi, lo; __asm__ volatile("rdtsc" : "=d"(hi), "=a"(lo)); return (((unsigned long long)hi) << 32) | lo; } static inline unsigned int z_arch_irq_lock(void) { unsigned long long key; __asm__ volatile("pushfq; cli; popq %0" : "=r"(key)); return (int)key; } static inline void z_arch_irq_unlock(unsigned int key) { if (key & 0x200) { __asm__ volatile("sti"); } } /** * Returns true if interrupts were unlocked prior to the * z_arch_irq_lock() call that produced the key argument. */ static inline bool z_arch_irq_unlocked(unsigned int key) { return (key & 0x200) != 0; } void z_arch_irq_enable(unsigned int irq); void z_arch_irq_disable(unsigned int irq); #define Z_ARCH_IRQ_CONNECT(irq, pri, isr, arg, flags) \ z_arch_irq_connect_dynamic(irq, pri, isr, arg, flags) extern int x86_64_except_reason; /* Vector 5 is the "bounds" exception which is otherwise vestigial * (BOUND is an illegal instruction in long mode) */ #define Z_ARCH_EXCEPT(reason) do { \ x86_64_except_reason = reason; \ __asm__ volatile("int $5"); \ } while (false) #endif /* _X86_64_ARCH_H */
torsteingrindvik/fw-nrfconnect-zephyr
tests/benchmarks/timing_info/src/thread_bench.c
/* * Copyright (c) 2013-2015 Wind River Systems, Inc. * Copyright (c) 2016 Intel Corporation. * * SPDX-License-Identifier: Apache-2.0 */ /** * @file * @brief Measure time * */ #include <kernel.h> #include <zephyr.h> #include <tc_util.h> #include <ksched.h> #include "timing_info.h" char sline[256]; /* FILE *output_file = stdout; */ /* location of the time stamps*/ extern u32_t z_arch_timing_value_swap_end; extern u64_t z_arch_timing_value_swap_temp; extern u64_t z_arch_timing_value_swap_common; volatile u64_t thread_abort_end_time; volatile u64_t thread_abort_start_time; /* Thread suspend*/ volatile u64_t thread_suspend_start_time; volatile u64_t thread_suspend_end_time; /* Thread resume*/ volatile u64_t thread_resume_start_time; volatile u64_t thread_resume_end_time; /* Thread sleep*/ volatile u64_t thread_sleep_start_time; volatile u64_t thread_sleep_end_time; /*For benchmarking msg queues*/ k_tid_t producer_tid; k_tid_t consumer_tid; /* To time thread creation*/ K_THREAD_STACK_DEFINE(my_stack_area, STACK_SIZE); K_THREAD_STACK_DEFINE(my_stack_area_0, STACK_SIZE); struct k_thread my_thread; struct k_thread my_thread_0; u32_t z_arch_timing_value_swap_end_test = 1U; u64_t dummy_time; u64_t start_time; u64_t test_end_time; /* Disable the overhead calculations, this is needed to calculate * the overhead created by the benchmarking code itself. */ #define DISABLE_OVERHEAD_MEASUREMENT #if defined(CONFIG_X86) && !defined(DISABLE_OVERHEAD_MEASUREMENT) u32_t benchmarking_overhead_swap(void) { __asm__ __volatile__ ( "pushl %eax\n\t" "pushl %edx\n\t" "rdtsc\n\t" "mov %eax,start_time\n\t" "mov %edx,start_time+4\n\t" "cmp $0x1,z_arch_timing_value_swap_end_test\n\t" "jne time_read_not_needed_test\n\t" "movw $0x2,z_arch_timing_value_swap_end\n\t" "pushl %eax\n\t" "pushl %edx\n\t" "rdtsc\n\t" "mov %eax,dummy_time\n\t" "mov %edx,dummy_time+4\n\t" "pop %edx\n\t" "pop %eax\n\t" "time_read_not_needed_test:\n\t" "rdtsc\n\t" "mov %eax,test_end_time\n\t" "mov %edx,test_end_time+4\n\t" "pop %edx\n\t" "pop %eax\n\t"); return(test_end_time - start_time); } #endif void test_thread_entry(void *p, void *p1, void *p2) { static int i; i++; } void thread_swap_test(void *p1, void *p2, void *p3) { z_arch_timing_value_swap_end = 1U; TIMING_INFO_PRE_READ(); thread_abort_start_time = TIMING_INFO_OS_GET_TIME(); k_thread_abort(_current); } void thread_suspend_test(void *p1, void *p2, void *p3); void yield_bench(void); void heap_malloc_free_bench(void); void main_sem_bench(void); void main_mutex_bench(void); void main_msg_bench(void); void system_thread_bench(void) { /*Thread create*/ u64_t thread_create_start_time; u64_t thread_create_end_time; DECLARE_VAR(thread, create) /*Thread cancel*/ u64_t thread_cancel_start_time; u64_t thread_cancel_end_time; DECLARE_VAR(thread, cancel) /* Thread Abort*/ DECLARE_VAR(thread, abort) /* Thread Suspend*/ DECLARE_VAR(thread, suspend) /* Thread Resume*/ DECLARE_VAR(thread, resume) /* to measure context switch time */ k_thread_create(&my_thread_0, my_stack_area_0, STACK_SIZE, thread_swap_test, NULL, NULL, NULL, -1 /*priority*/, 0, K_NO_WAIT); k_sleep(K_MSEC(1)); thread_abort_end_time = (z_arch_timing_value_swap_common); z_arch_timing_swap_end = z_arch_timing_value_swap_common; #if defined(CONFIG_X86) || defined(CONFIG_X86_64) z_arch_timing_swap_start = z_arch_timing_value_swap_temp; /* In the rest of ARCHes read_timer_start_of_swap() has already * registered the time-stamp of the start of context-switch in * z_arch_timing_swap_start. */ #endif u32_t total_swap_cycles = z_arch_timing_swap_end - z_arch_timing_swap_start; /* Interrupt latency*/ u64_t local_end_intr_time = z_arch_timing_irq_end; u64_t local_start_intr_time = z_arch_timing_irq_start; /*******************************************************************/ /* thread create*/ TIMING_INFO_PRE_READ(); thread_create_start_time = TIMING_INFO_OS_GET_TIME(); k_tid_t my_tid = k_thread_create(&my_thread, my_stack_area, STACK_SIZE, thread_swap_test, NULL, NULL, NULL, 5 /*priority*/, 0, K_MSEC(10)); TIMING_INFO_PRE_READ(); thread_create_end_time = TIMING_INFO_OS_GET_TIME(); /* thread Termination*/ TIMING_INFO_PRE_READ(); thread_cancel_start_time = TIMING_INFO_OS_GET_TIME(); k_thread_abort(my_tid); TIMING_INFO_PRE_READ(); thread_cancel_end_time = TIMING_INFO_OS_GET_TIME(); /* Thread suspend*/ k_tid_t sus_res_tid = k_thread_create(&my_thread, my_stack_area, STACK_SIZE, thread_suspend_test, NULL, NULL, NULL, -1 /*priority*/, 0, K_NO_WAIT); TIMING_INFO_PRE_READ(); thread_suspend_end_time = TIMING_INFO_OS_GET_TIME(); /* At this point test for resume*/ k_thread_resume(sus_res_tid); /* calculation for creation */ CALCULATE_TIME(, thread, create) /* calculation for cancel */ CALCULATE_TIME(, thread, cancel) /* calculation for abort */ CALCULATE_TIME(, thread, abort) /* calculation for suspend */ CALCULATE_TIME(, thread, suspend) /* calculation for resume */ thread_resume_start_time = thread_suspend_end_time; CALCULATE_TIME(, thread, resume) /*******************************************************************/ /* Only print lower 32bit of time result */ PRINT_STATS("Context switch", (u32_t)(total_swap_cycles & 0xFFFFFFFFULL), (u32_t) CYCLES_TO_NS(total_swap_cycles)); /*TC_PRINT("Swap Overhead:%d cycles\n", benchmarking_overhead_swap());*/ /*Interrupt latency */ u32_t intr_latency_cycles = SUBTRACT_CLOCK_CYCLES(local_end_intr_time) - SUBTRACT_CLOCK_CYCLES(local_start_intr_time); PRINT_STATS("Interrupt latency", (u32_t)(intr_latency_cycles), (u32_t) (CYCLES_TO_NS(intr_latency_cycles))); /*tick overhead*/ u32_t tick_overhead_cycles = SUBTRACT_CLOCK_CYCLES(z_arch_timing_tick_end) - SUBTRACT_CLOCK_CYCLES(z_arch_timing_tick_start); PRINT_STATS("Tick overhead", (u32_t)(tick_overhead_cycles), (u32_t) (CYCLES_TO_NS(tick_overhead_cycles))); /*thread creation*/ PRINT_STATS("Thread Creation", (u32_t)((thread_create_end_time - thread_create_start_time) & 0xFFFFFFFFULL), (u32_t) ((total_thread_create_time) & 0xFFFFFFFFULL)); /*thread cancel*/ PRINT_STATS("Thread cancel", (u32_t)((thread_cancel_end_time - thread_cancel_start_time) & 0xFFFFFFFFULL), (u32_t) (total_thread_cancel_time & 0xFFFFFFFFULL)); /*thread abort*/ PRINT_STATS("Thread abort", (u32_t)((thread_abort_end_time - thread_abort_start_time) & 0xFFFFFFFFULL), (u32_t) (total_thread_abort_time & 0xFFFFFFFFULL)); /*thread suspend*/ PRINT_STATS("Thread Suspend", (u32_t)((thread_suspend_end_time - thread_suspend_start_time) & 0xFFFFFFFFULL), (u32_t) (total_thread_suspend_time & 0xFFFFFFFFULL)); /*thread resume*/ PRINT_STATS("Thread Resume", (u32_t)((thread_resume_end_time - thread_suspend_end_time) & 0xFFFFFFFFULL), (u32_t) (total_thread_resume_time & 0xFFFFFFFFULL)); } void thread_suspend_test(void *p1, void *p2, void *p3) { TIMING_INFO_PRE_READ(); thread_suspend_start_time = TIMING_INFO_OS_GET_TIME(); k_thread_suspend(_current); /* comes to this line once its resumed*/ TIMING_INFO_PRE_READ(); thread_resume_end_time = TIMING_INFO_OS_GET_TIME(); /* k_thread_suspend(_current); */ } void heap_malloc_free_bench(void) { /* heap malloc*/ u64_t heap_malloc_start_time = 0U; u64_t heap_malloc_end_time = 0U; /* heap free*/ u64_t heap_free_start_time = 0U; u64_t heap_free_end_time = 0U; s32_t count = 0; u32_t sum_malloc = 0U; u32_t sum_free = 0U; k_sleep(K_MSEC(10)); while (count++ != 100) { TIMING_INFO_PRE_READ(); heap_malloc_start_time = TIMING_INFO_OS_GET_TIME(); void *allocated_mem = k_malloc(10); TIMING_INFO_PRE_READ(); heap_malloc_end_time = TIMING_INFO_OS_GET_TIME(); if (allocated_mem == NULL) { TC_PRINT("\n Malloc failed at count %d\n", count); break; } TIMING_INFO_PRE_READ(); heap_free_start_time = TIMING_INFO_OS_GET_TIME(); k_free(allocated_mem); TIMING_INFO_PRE_READ(); heap_free_end_time = TIMING_INFO_OS_GET_TIME(); sum_malloc += heap_malloc_end_time - heap_malloc_start_time; sum_free += heap_free_end_time - heap_free_start_time; } PRINT_STATS("Heap Malloc", (u32_t)((sum_malloc / count) & 0xFFFFFFFFULL), (u32_t)(CYCLES_TO_NS(sum_malloc / count))); PRINT_STATS("Heap Free", (u32_t)((sum_free / count) & 0xFFFFFFFFULL), (u32_t)(CYCLES_TO_NS(sum_free / count))); }
torsteingrindvik/fw-nrfconnect-zephyr
tests/subsys/settings/nvs/src/settings_test_nvs.c
/* * Copyright (c) 2019 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #include <stdlib.h> #include <string.h> #include "settings_priv.h" #include "settings_test.h" u8_t val8; u8_t val8_un; u32_t val32; u64_t val64; int test_get_called; int test_set_called; int test_commit_called; int test_export_block; int c2_var_count = 1; int c1_handle_get(const char *name, char *val, int val_len_max); int c1_handle_set(const char *name, size_t len, settings_read_cb read_cb, void *cb_arg); int c1_handle_commit(void); int c1_handle_export(int (*cb)(const char *name, const void *value, size_t val_len)); int c2_handle_get(const char *name, char *val, int val_len_max); int c2_handle_set(const char *name, size_t len, settings_read_cb read_cb, void *cb_arg); int c2_handle_export(int (*cb)(const char *name, const void *value, size_t val_len)); int c3_handle_get(const char *name, char *val, int val_len_max); int c3_handle_set(const char *name, size_t len, settings_read_cb read_cb, void *cb_arg); int c3_handle_export(int (*cb)(const char *name, const void *value, size_t val_len)); struct settings_handler c_test_handlers[] = { { .name = "myfoo", .h_get = c1_handle_get, .h_set = c1_handle_set, .h_commit = c1_handle_commit, .h_export = c1_handle_export }, { .name = "2nd", .h_get = c2_handle_get, .h_set = c2_handle_set, .h_commit = NULL, .h_export = c2_handle_export }, { .name = "3", .h_get = c3_handle_get, .h_set = c3_handle_set, .h_commit = NULL, .h_export = c3_handle_export } }; char val_string[SETTINGS_TEST_NVS_VAL_STR_CNT][SETTINGS_MAX_VAL_LEN]; char test_ref_value[SETTINGS_TEST_NVS_VAL_STR_CNT][SETTINGS_MAX_VAL_LEN]; int c1_handle_get(const char *name, char *val, int val_len_max) { const char *next; test_get_called = 1; if (settings_name_steq(name, "mybar", &next) && !next) { val_len_max = MIN(val_len_max, sizeof(val8)); memcpy(val, &val8, MIN(val_len_max, sizeof(val8))); return val_len_max; } if (settings_name_steq(name, "mybar64", &next) && !next) { val_len_max = MIN(val_len_max, sizeof(val64)); memcpy(val, &val64, MIN(val_len_max, sizeof(val64))); return val_len_max; } return -ENOENT; } int c1_handle_set(const char *name, size_t len, settings_read_cb read_cb, void *cb_arg) { size_t val_len; int rc; const char *next; test_set_called = 1; if (settings_name_steq(name, "mybar", &next) && !next) { rc = read_cb(cb_arg, &val8, sizeof(val8)); zassert_true(rc >= 0, "SETTINGS_VALUE_SET callback"); if (rc == 0) { val8 = VAL8_DELETED; } return 0; } if (settings_name_steq(name, "mybar64", &next) && !next) { rc = read_cb(cb_arg, &val64, sizeof(val64)); zassert_true(rc >= 0, "SETTINGS_VALUE_SET callback"); return 0; } if (settings_name_steq(name, "unaligned", &next) && !next) { val_len = len; zassert_equal(val_len, sizeof(val8_un), "value length: %d, ought equal 1", val_len); rc = read_cb(cb_arg, &val8_un, sizeof(val8_un)); zassert_true(rc >= 0, "SETTINGS_VALUE_SET callback"); return 0; } return -ENOENT; } int c1_handle_commit(void) { test_commit_called = 1; return 0; } int c1_handle_export(int (*cb)(const char *name, const void *value, size_t val_len)) { if (test_export_block) { return 0; } (void)cb("myfoo/mybar", &val8, sizeof(val8)); (void)cb("myfoo/mybar64", &val64, sizeof(val64)); (void)cb("myfoo/unaligned", &val8_un, sizeof(val8_un)); return 0; } void ctest_clear_call_state(void) { test_get_called = 0; test_set_called = 0; test_commit_called = 0; } int ctest_get_call_state(void) { return test_get_called + test_set_called + test_commit_called; } void config_wipe_srcs(void) { sys_slist_init(&settings_load_srcs); settings_save_dst = NULL; } char *c2_var_find(char *name) { int idx = 0; int len; char *eptr; len = strlen(name); zassert_true(len > 6, "string type expected"); zassert_true(!strncmp(name, "string", 6), "string type expected"); idx = strtoul(&name[6], &eptr, 10); zassert_true(*eptr == '\0', "EOF"); zassert_true(idx < c2_var_count, "var index greather than any exporter"); return val_string[idx]; } int c2_handle_get(const char *name, char *val, int val_len_max) { int len; char *valptr; const char *next; char argv[32]; len = settings_name_next(name, &next); if (len && !next) { strncpy(argv, name, len); argv[len] = '\0'; valptr = c2_var_find(argv); if (!valptr) { return -ENOENT; } len = strlen(val_string[0]); if (len > val_len_max) { len = val_len_max; } len = MIN(strlen(valptr), len); memcpy(val, valptr, len); return len; } return -ENOENT; } int c2_handle_set(const char *name, size_t len, settings_read_cb read_cb, void *cb_arg) { char *valptr; const char *next; char argv[32]; int rc; len = settings_name_next(name, &next); if (len && !next) { strncpy(argv, name, len); argv[len] = '\0'; valptr = c2_var_find(argv); if (!valptr) { return -ENOENT; } rc = read_cb(cb_arg, valptr, sizeof(val_string[0])); zassert_true(rc >= 0, "SETTINGS_VALUE_SET callback"); if (rc == 0) { (void)memset(valptr, 0, sizeof(val_string[0])); } return 0; } return -ENOENT; } int c2_handle_export(int (*cb)(const char *name, const void *value, size_t val_len)) { int i; char name[32]; for (i = 0; i < c2_var_count; i++) { snprintf(name, sizeof(name), "2nd/string%d", i); (void)cb(name, val_string[i], strlen(val_string[i])); } return 0; } int c3_handle_get(const char *name, char *val, int val_len_max) { const char *next; if (settings_name_steq(name, "v", &next) && !next) { val_len_max = MIN(val_len_max, sizeof(val32)); memcpy(val, &val32, MIN(val_len_max, sizeof(val32))); return val_len_max; } return -EINVAL; } int c3_handle_set(const char *name, size_t len, settings_read_cb read_cb, void *cb_arg) { int rc; size_t val_len; const char *next; if (settings_name_steq(name, "v", &next) && !next) { val_len = len; zassert_true(val_len == 4, "bad set-value size"); rc = read_cb(cb_arg, &val32, sizeof(val32)); zassert_true(rc >= 0, "SETTINGS_VALUE_SET callback"); return 0; } return -ENOENT; } int c3_handle_export(int (*cb)(const char *name, const void *value, size_t val_len)) { (void)cb("3/v", &val32, sizeof(val32)); return 0; } void config_empty_lookups(void); void test_config_insert(void); void test_config_getset_unknown(void); void test_config_getset_int(void); void test_config_getset_int64(void); void test_config_commit(void); void test_main(void) { ztest_test_suite(test_config_nvs, /* Config tests */ ztest_unit_test(config_empty_lookups), ztest_unit_test(test_config_insert), ztest_unit_test(test_config_getset_unknown), ztest_unit_test(test_config_getset_int), ztest_unit_test(test_config_getset_int64), ztest_unit_test(test_config_commit) ); ztest_run_test_suite(test_config_nvs); }
torsteingrindvik/fw-nrfconnect-zephyr
subsys/net/lib/socks/socks.c
<reponame>torsteingrindvik/fw-nrfconnect-zephyr /* * Copyright (c) 2019 Antmicro Ltd * * Copyright (c) 2019 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <logging/log.h> LOG_MODULE_REGISTER(net_socks, CONFIG_SOCKS_LOG_LEVEL); #include <zephyr.h> #include <net/socket.h> #include <net/socks.h> #include <net/net_pkt.h> #include "socks_internal.h" static void socks5_method_rsp_cb(struct net_context *ctx, struct net_pkt *pkt, union net_ip_header *ip_hdr, union net_proto_header *proto_hdr, int status, void *user_data) { struct socks5_method_response *method_rsp = (struct socks5_method_response *)user_data; if (!pkt || status) { memset(method_rsp, 0, sizeof(struct socks5_method_response)); goto end; } if (net_pkt_read(pkt, (u8_t *)method_rsp, sizeof(struct socks5_method_response))) { memset(method_rsp, 0, sizeof(struct socks5_method_response)); } end: net_pkt_unref(pkt); } static void socks5_cmd_rsp_cb(struct net_context *ctx, struct net_pkt *pkt, union net_ip_header *ip_hdr, union net_proto_header *proto_hdr, int status, void *user_data) { struct socks5_command_response *cmd_rsp = (struct socks5_command_response *)user_data; int size; if (!pkt || status) { memset(cmd_rsp, 0, sizeof(struct socks5_command_request_common)); goto end; } size = sizeof(struct socks5_command_request_common); if (net_pkt_read(pkt, (u8_t *)cmd_rsp, size)) { memset(cmd_rsp, 0, sizeof(struct socks5_command_request_common)); } end: net_pkt_unref(pkt); } static int socks5_tcp_connect(struct net_context *ctx, const struct sockaddr *proxy, socklen_t proxy_len, const struct sockaddr *dest, socklen_t dest_len) { struct socks5_method_request method_req; struct socks5_method_response method_rsp; struct socks5_command_request cmd_req; struct socks5_command_response cmd_rsp; int size; int ret; /* Negotiate authentication method */ method_req.r.ver = SOCKS5_PKT_MAGIC; /* We only support NOAUTH at the moment */ method_req.r.nmethods = 1U; method_req.methods[0] = SOCKS5_AUTH_METHOD_NOAUTH; /* size + 1 because just one method is supported */ size = sizeof(struct socks5_method_request_common) + 1; ret = net_context_sendto(ctx, (u8_t *)&method_req, size, proxy, proxy_len, NULL, K_NO_WAIT, ctx->user_data); if (ret < 0) { LOG_ERR("Could not send negotiation packet"); return ret; } ret = net_context_recv(ctx, socks5_method_rsp_cb, K_MSEC(CONFIG_NET_SOCKETS_CONNECT_TIMEOUT), &method_rsp); if (ret < 0) { LOG_ERR("Could not receive negotiation response"); return ret; } if (method_rsp.ver != SOCKS5_PKT_MAGIC) { LOG_ERR("Invalid negotiation response magic"); return -EINVAL; } if (method_rsp.method != SOCKS5_AUTH_METHOD_NOAUTH) { LOG_ERR("Invalid negotiation response"); return -ENOTSUP; } /* Negotiation complete - now connect to destination */ cmd_req.r.ver = SOCKS5_PKT_MAGIC; cmd_req.r.cmd = SOCKS5_CMD_CONNECT; cmd_req.r.rsv = SOCKS5_PKT_RSV; if (proxy->sa_family == AF_INET) { const struct sockaddr_in *d4 = (struct sockaddr_in *)dest; cmd_req.r.atyp = SOCKS5_ATYP_IPV4; memcpy(&cmd_req.ipv4_addr.addr, (u8_t *)&d4->sin_addr, sizeof(cmd_req.ipv4_addr.addr)); cmd_req.ipv4_addr.port = d4->sin_port; size = sizeof(struct socks5_command_request_common) + sizeof(struct socks5_ipv4_addr); } else if (proxy->sa_family == AF_INET6) { const struct sockaddr_in6 *d6 = (struct sockaddr_in6 *)dest; cmd_req.r.atyp = SOCKS5_ATYP_IPV6; memcpy(&cmd_req.ipv6_addr.addr, (u8_t *)&d6->sin6_addr, sizeof(cmd_req.ipv6_addr.addr)); cmd_req.ipv6_addr.port = d6->sin6_port; size = sizeof(struct socks5_command_request_common) + sizeof(struct socks5_ipv6_addr); } ret = net_context_sendto(ctx, (u8_t *)&cmd_req, size, proxy, proxy_len, NULL, K_NO_WAIT, ctx->user_data); if (ret < 0) { LOG_ERR("Could not send CONNECT command"); return ret; } ret = net_context_recv(ctx, socks5_cmd_rsp_cb, K_MSEC(CONFIG_NET_SOCKETS_CONNECT_TIMEOUT), &cmd_rsp); if (ret < 0) { LOG_ERR("Could not receive CONNECT response"); return ret; } if (cmd_rsp.r.ver != SOCKS5_PKT_MAGIC) { LOG_ERR("Invalid CONNECT response"); return -EINVAL; } if (cmd_rsp.r.rep != SOCKS5_CMD_RESP_SUCCESS) { LOG_ERR("Unable to connect to destination"); return -EINVAL; } /* Verifying the rest is not required */ LOG_DBG("Connection through SOCKS5 proxy successful"); return 0; } int net_socks5_connect(struct net_context *ctx, const struct sockaddr *addr, socklen_t addrlen) { struct sockaddr proxy; socklen_t proxy_len; int type; int ret; type = net_context_get_type(ctx); /* TODO: Only TCP and TLS supported, UDP and DTLS yet to support. */ if (type != SOCK_STREAM) { return -ENOTSUP; } ret = net_context_get_option(ctx, NET_OPT_SOCKS5, &proxy, &proxy_len); if (ret < 0) { return ret; } /* Connect to Proxy Server */ ret = net_context_connect(ctx, &proxy, proxy_len, NULL, K_MSEC(CONFIG_NET_SOCKETS_CONNECT_TIMEOUT), NULL); if (ret < 0) { return ret; } return socks5_tcp_connect(ctx, &proxy, proxy_len, addr, addrlen); }
jnpkrn/wlroots
include/wlr/types/wlr_gtk_primary_selection.h
/* * This an unstable interface of wlroots. No guarantees are made regarding the * future consistency of this API. */ #ifndef WLR_USE_UNSTABLE #error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" #endif #ifndef WLR_TYPES_WLR_GTK_PRIMARY_SELECTION_H #define WLR_TYPES_WLR_GTK_PRIMARY_SELECTION_H #include <wayland-server.h> #include <wlr/types/wlr_seat.h> struct wlr_gtk_primary_selection_device_manager { struct wl_global *global; struct wl_list resources; struct wl_listener display_destroy; struct { struct wl_signal destroy; } events; void *data; }; struct wlr_gtk_primary_selection_source { // source metadata struct wl_array mime_types; // source implementation void (*send)(struct wlr_gtk_primary_selection_source *source, const char *mime_type, int32_t fd); void (*cancel)(struct wlr_gtk_primary_selection_source *source); // source status struct wlr_seat_client *seat_client; struct { struct wl_signal destroy; } events; void *data; }; struct wlr_gtk_primary_selection_offer { struct wl_resource *resource; struct wlr_gtk_primary_selection_source *source; struct wl_listener source_destroy; void *data; }; struct wlr_gtk_primary_selection_device_manager * wlr_gtk_primary_selection_device_manager_create(struct wl_display *display); void wlr_gtk_primary_selection_device_manager_destroy( struct wlr_gtk_primary_selection_device_manager *manager); void wlr_seat_client_send_gtk_primary_selection(struct wlr_seat_client *seat_client); void wlr_seat_set_gtk_primary_selection(struct wlr_seat *seat, struct wlr_gtk_primary_selection_source *source, uint32_t serial); void wlr_gtk_primary_selection_source_init( struct wlr_gtk_primary_selection_source *source); void wlr_gtk_primary_selection_source_finish( struct wlr_gtk_primary_selection_source *source); #endif
jnpkrn/wlroots
include/wlr/types/wlr_seat.h
/* * This an unstable interface of wlroots. No guarantees are made regarding the * future consistency of this API. */ #ifndef WLR_USE_UNSTABLE #error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" #endif #ifndef WLR_TYPES_WLR_SEAT_H #define WLR_TYPES_WLR_SEAT_H #include <time.h> #include <wayland-server.h> #include <wlr/types/wlr_input_device.h> #include <wlr/types/wlr_keyboard.h> #include <wlr/types/wlr_surface.h> /** * Contains state for a single client's bound wl_seat resource and can be used * to issue input events to that client. The lifetime of these objects is * managed by wlr_seat; some may be NULL. */ struct wlr_seat_client { struct wl_client *client; struct wlr_seat *seat; // lists of wl_resource struct wl_list resources; struct wl_list pointers; struct wl_list keyboards; struct wl_list touches; struct wl_list data_devices; struct wl_list primary_selection_devices; struct { struct wl_signal destroy; } events; struct wl_list link; }; struct wlr_touch_point { int32_t touch_id; struct wlr_surface *surface; struct wlr_seat_client *client; struct wlr_surface *focus_surface; struct wlr_seat_client *focus_client; double sx, sy; struct wl_listener surface_destroy; struct wl_listener focus_surface_destroy; struct { struct wl_signal destroy; } events; struct wl_list link; }; struct wlr_seat_pointer_grab; struct wlr_pointer_grab_interface { void (*enter)(struct wlr_seat_pointer_grab *grab, struct wlr_surface *surface, double sx, double sy); void (*motion)(struct wlr_seat_pointer_grab *grab, uint32_t time, double sx, double sy); uint32_t (*button)(struct wlr_seat_pointer_grab *grab, uint32_t time, uint32_t button, uint32_t state); void (*axis)(struct wlr_seat_pointer_grab *grab, uint32_t time, enum wlr_axis_orientation orientation, double value, int32_t value_discrete, enum wlr_axis_source source); void (*cancel)(struct wlr_seat_pointer_grab *grab); }; struct wlr_seat_keyboard_grab; struct wlr_keyboard_grab_interface { void (*enter)(struct wlr_seat_keyboard_grab *grab, struct wlr_surface *surface, uint32_t keycodes[], size_t num_keycodes, struct wlr_keyboard_modifiers *modifiers); void (*key)(struct wlr_seat_keyboard_grab *grab, uint32_t time, uint32_t key, uint32_t state); void (*modifiers)(struct wlr_seat_keyboard_grab *grab, struct wlr_keyboard_modifiers *modifiers); void (*cancel)(struct wlr_seat_keyboard_grab *grab); }; struct wlr_seat_touch_grab; struct wlr_touch_grab_interface { uint32_t (*down)(struct wlr_seat_touch_grab *grab, uint32_t time, struct wlr_touch_point *point); void (*up)(struct wlr_seat_touch_grab *grab, uint32_t time, struct wlr_touch_point *point); void (*motion)(struct wlr_seat_touch_grab *grab, uint32_t time, struct wlr_touch_point *point); void (*enter)(struct wlr_seat_touch_grab *grab, uint32_t time, struct wlr_touch_point *point); // XXX this will conflict with the actual touch cancel which is different so // we need to rename this void (*cancel)(struct wlr_seat_touch_grab *grab); }; /** * Passed to `wlr_seat_touch_start_grab()` to start a grab of the touch device. * The grabber is responsible for handling touch events for the seat. */ struct wlr_seat_touch_grab { const struct wlr_touch_grab_interface *interface; struct wlr_seat *seat; void *data; }; /** * Passed to `wlr_seat_keyboard_start_grab()` to start a grab of the keyboard. * The grabber is responsible for handling keyboard events for the seat. */ struct wlr_seat_keyboard_grab { const struct wlr_keyboard_grab_interface *interface; struct wlr_seat *seat; void *data; }; /** * Passed to `wlr_seat_pointer_start_grab()` to start a grab of the pointer. The * grabber is responsible for handling pointer events for the seat. */ struct wlr_seat_pointer_grab { const struct wlr_pointer_grab_interface *interface; struct wlr_seat *seat; void *data; }; struct wlr_seat_pointer_state { struct wlr_seat *seat; struct wlr_seat_client *focused_client; struct wlr_surface *focused_surface; struct wlr_seat_pointer_grab *grab; struct wlr_seat_pointer_grab *default_grab; uint32_t button_count; uint32_t grab_button; uint32_t grab_serial; uint32_t grab_time; struct wl_listener surface_destroy; struct { struct wl_signal focus_change; // wlr_seat_pointer_focus_change_event } events; }; // TODO: May be useful to be able to simulate keyboard input events struct wlr_seat_keyboard_state { struct wlr_seat *seat; struct wlr_keyboard *keyboard; struct wlr_seat_client *focused_client; struct wlr_surface *focused_surface; struct wl_listener keyboard_destroy; struct wl_listener keyboard_keymap; struct wl_listener keyboard_repeat_info; struct wl_listener surface_destroy; struct wlr_seat_keyboard_grab *grab; struct wlr_seat_keyboard_grab *default_grab; }; struct wlr_seat_touch_state { struct wlr_seat *seat; struct wl_list touch_points; // wlr_touch_point::link uint32_t grab_serial; uint32_t grab_id; struct wlr_seat_touch_grab *grab; struct wlr_seat_touch_grab *default_grab; }; struct wlr_seat { struct wl_global *global; struct wl_display *display; struct wl_list clients; struct wl_list drag_icons; // wlr_drag_icon::link char *name; uint32_t capabilities; struct timespec last_event; struct wlr_data_source *selection_source; uint32_t selection_serial; struct wlr_gtk_primary_selection_source *primary_selection_source; uint32_t primary_selection_serial; // `drag` goes away before `drag_source`, when the implicit grab ends struct wlr_drag *drag; struct wlr_data_source *drag_source; uint32_t drag_serial; struct wlr_seat_pointer_state pointer_state; struct wlr_seat_keyboard_state keyboard_state; struct wlr_seat_touch_state touch_state; struct wl_listener display_destroy; struct wl_listener selection_source_destroy; struct wl_listener primary_selection_source_destroy; struct wl_listener drag_source_destroy; struct { struct wl_signal pointer_grab_begin; struct wl_signal pointer_grab_end; struct wl_signal keyboard_grab_begin; struct wl_signal keyboard_grab_end; struct wl_signal touch_grab_begin; struct wl_signal touch_grab_end; struct wl_signal request_set_cursor; struct wl_signal selection; struct wl_signal primary_selection; struct wl_signal start_drag; struct wl_signal new_drag_icon; struct wl_signal destroy; } events; void *data; }; struct wlr_seat_pointer_request_set_cursor_event { struct wlr_seat_client *seat_client; struct wlr_surface *surface; uint32_t serial; int32_t hotspot_x, hotspot_y; }; struct wlr_seat_pointer_focus_change_event { struct wlr_seat *seat; struct wlr_surface *old_surface, *new_surface; double sx, sy; }; /** * Allocates a new wlr_seat and adds a wl_seat global to the display. */ struct wlr_seat *wlr_seat_create(struct wl_display *display, const char *name); /** * Destroys a wlr_seat and removes its wl_seat global. */ void wlr_seat_destroy(struct wlr_seat *wlr_seat); /** * Gets a wlr_seat_client for the specified client, or returns NULL if no * client is bound for that client. */ struct wlr_seat_client *wlr_seat_client_for_wl_client(struct wlr_seat *wlr_seat, struct wl_client *wl_client); /** * Updates the capabilities available on this seat. * Will automatically send them to all clients. */ void wlr_seat_set_capabilities(struct wlr_seat *wlr_seat, uint32_t capabilities); /** * Updates the name of this seat. * Will automatically send it to all clients. */ void wlr_seat_set_name(struct wlr_seat *wlr_seat, const char *name); /** * Whether or not the surface has pointer focus */ bool wlr_seat_pointer_surface_has_focus(struct wlr_seat *wlr_seat, struct wlr_surface *surface); /** * Send a pointer enter event to the given surface and consider it to be the * focused surface for the pointer. This will send a leave event to the last * surface that was entered. Coordinates for the enter event are surface-local. * Compositor should use `wlr_seat_pointer_notify_enter()` to change pointer * focus to respect pointer grabs. */ void wlr_seat_pointer_enter(struct wlr_seat *wlr_seat, struct wlr_surface *surface, double sx, double sy); /** * Clear the focused surface for the pointer and leave all entered surfaces. */ void wlr_seat_pointer_clear_focus(struct wlr_seat *wlr_seat); /** * Send a motion event to the surface with pointer focus. Coordinates for the * motion event are surface-local. Compositors should use * `wlr_seat_pointer_notify_motion()` to send motion events to respect pointer * grabs. */ void wlr_seat_pointer_send_motion(struct wlr_seat *wlr_seat, uint32_t time, double sx, double sy); /** * Send a button event to the surface with pointer focus. Coordinates for the * button event are surface-local. Returns the serial. Compositors should use * `wlr_seat_pointer_notify_button()` to send button events to respect pointer * grabs. */ uint32_t wlr_seat_pointer_send_button(struct wlr_seat *wlr_seat, uint32_t time, uint32_t button, uint32_t state); /** * Send an axis event to the surface with pointer focus. Compositors should use * `wlr_seat_pointer_notify_axis()` to send axis events to respect pointer * grabs. **/ void wlr_seat_pointer_send_axis(struct wlr_seat *wlr_seat, uint32_t time, enum wlr_axis_orientation orientation, double value, int32_t value_discrete, enum wlr_axis_source source); /** * Start a grab of the pointer of this seat. The grabber is responsible for * handling all pointer events until the grab ends. */ void wlr_seat_pointer_start_grab(struct wlr_seat *wlr_seat, struct wlr_seat_pointer_grab *grab); /** * End the grab of the pointer of this seat. This reverts the grab back to the * default grab for the pointer. */ void wlr_seat_pointer_end_grab(struct wlr_seat *wlr_seat); /** * Notify the seat of a pointer enter event to the given surface and request it * to be the focused surface for the pointer. Pass surface-local coordinates * where the enter occurred. */ void wlr_seat_pointer_notify_enter(struct wlr_seat *wlr_seat, struct wlr_surface *surface, double sx, double sy); /** * Notify the seat of motion over the given surface. Pass surface-local * coordinates where the pointer motion occurred. */ void wlr_seat_pointer_notify_motion(struct wlr_seat *wlr_seat, uint32_t time, double sx, double sy); /** * Notify the seat that a button has been pressed. Returns the serial of the * button press or zero if no button press was sent. */ uint32_t wlr_seat_pointer_notify_button(struct wlr_seat *wlr_seat, uint32_t time, uint32_t button, uint32_t state); /** * Notify the seat of an axis event. */ void wlr_seat_pointer_notify_axis(struct wlr_seat *wlr_seat, uint32_t time, enum wlr_axis_orientation orientation, double value, int32_t value_discrete, enum wlr_axis_source source); /** * Whether or not the pointer has a grab other than the default grab. */ bool wlr_seat_pointer_has_grab(struct wlr_seat *seat); /** * Set this keyboard as the active keyboard for the seat. */ void wlr_seat_set_keyboard(struct wlr_seat *seat, struct wlr_input_device *dev); /** * Get the active keyboard for the seat. */ struct wlr_keyboard *wlr_seat_get_keyboard(struct wlr_seat *seat); /** * Start a grab of the keyboard of this seat. The grabber is responsible for * handling all keyboard events until the grab ends. */ void wlr_seat_keyboard_start_grab(struct wlr_seat *wlr_seat, struct wlr_seat_keyboard_grab *grab); /** * End the grab of the keyboard of this seat. This reverts the grab back to the * default grab for the keyboard. */ void wlr_seat_keyboard_end_grab(struct wlr_seat *wlr_seat); /** * Send the keyboard key to focused keyboard resources. Compositors should use * `wlr_seat_notify_key()` to respect keyboard grabs. */ void wlr_seat_keyboard_send_key(struct wlr_seat *seat, uint32_t time, uint32_t key, uint32_t state); /** * Notify the seat that a key has been pressed on the keyboard. Defers to any * keyboard grabs. */ void wlr_seat_keyboard_notify_key(struct wlr_seat *seat, uint32_t time, uint32_t key, uint32_t state); /** * Send the modifier state to focused keyboard resources. Compositors should use * `wlr_seat_keyboard_notify_modifiers()` to respect any keyboard grabs. */ void wlr_seat_keyboard_send_modifiers(struct wlr_seat *seat, struct wlr_keyboard_modifiers *modifiers); /** * Notify the seat that the modifiers for the keyboard have changed. Defers to * any keyboard grabs. */ void wlr_seat_keyboard_notify_modifiers(struct wlr_seat *seat, struct wlr_keyboard_modifiers *modifiers); /** * Notify the seat that the keyboard focus has changed and request it to be the * focused surface for this keyboard. Defers to any current grab of the seat's * keyboard. */ void wlr_seat_keyboard_notify_enter(struct wlr_seat *seat, struct wlr_surface *surface, uint32_t keycodes[], size_t num_keycodes, struct wlr_keyboard_modifiers *modifiers); /** * Send a keyboard enter event to the given surface and consider it to be the * focused surface for the keyboard. This will send a leave event to the last * surface that was entered. Compositors should use * `wlr_seat_keyboard_notify_enter()` to change keyboard focus to respect * keyboard grabs. */ void wlr_seat_keyboard_enter(struct wlr_seat *seat, struct wlr_surface *surface, uint32_t keycodes[], size_t num_keycodes, struct wlr_keyboard_modifiers *modifiers); /** * Clear the focused surface for the keyboard and leave all entered surfaces. */ void wlr_seat_keyboard_clear_focus(struct wlr_seat *wlr_seat); /** * Whether or not the keyboard has a grab other than the default grab */ bool wlr_seat_keyboard_has_grab(struct wlr_seat *seat); /** * Start a grab of the touch device of this seat. The grabber is responsible for * handling all touch events until the grab ends. */ void wlr_seat_touch_start_grab(struct wlr_seat *wlr_seat, struct wlr_seat_touch_grab *grab); /** * End the grab of the touch device of this seat. This reverts the grab back to * the default grab for the touch device. */ void wlr_seat_touch_end_grab(struct wlr_seat *wlr_seat); /** * Get the active touch point with the given `touch_id`. If the touch point does * not exist or is no longer active, returns NULL. */ struct wlr_touch_point *wlr_seat_touch_get_point(struct wlr_seat *seat, int32_t touch_id); /** * Notify the seat of a touch down on the given surface. Defers to any grab of * the touch device. */ uint32_t wlr_seat_touch_notify_down(struct wlr_seat *seat, struct wlr_surface *surface, uint32_t time, int32_t touch_id, double sx, double sy); /** * Notify the seat that the touch point given by `touch_id` is up. Defers to any * grab of the touch device. */ void wlr_seat_touch_notify_up(struct wlr_seat *seat, uint32_t time, int32_t touch_id); /** * Notify the seat that the touch point given by `touch_id` has moved. Defers to * any grab of the touch device. The seat should be notified of touch motion * even if the surface is not the owner of the touch point for processing by * grabs. */ void wlr_seat_touch_notify_motion(struct wlr_seat *seat, uint32_t time, int32_t touch_id, double sx, double sy); /** * Notify the seat that the touch point given by `touch_id` has entered a new * surface. The surface is required. To clear focus, use * `wlr_seat_touch_point_clear_focus()`. */ void wlr_seat_touch_point_focus(struct wlr_seat *seat, struct wlr_surface *surface, uint32_t time, int32_t touch_id, double sx, double sy); /** * Clear the focused surface for the touch point given by `touch_id`. */ void wlr_seat_touch_point_clear_focus(struct wlr_seat *seat, uint32_t time, int32_t touch_id); /** * Send a touch down event to the client of the given surface. All future touch * events for this point will go to this surface. If the touch down is valid, * this will add a new touch point with the given `touch_id`. The touch down may * not be valid if the surface seat client does not accept touch input. * Coordinates are surface-local. Compositors should use * `wlr_seat_touch_notify_down()` to respect any grabs of the touch device. */ uint32_t wlr_seat_touch_send_down(struct wlr_seat *seat, struct wlr_surface *surface, uint32_t time, int32_t touch_id, double sx, double sy); /** * Send a touch up event for the touch point given by the `touch_id`. The event * will go to the client for the surface given in the cooresponding touch down * event. This will remove the touch point. Compositors should use * `wlr_seat_touch_notify_up()` to respect any grabs of the touch device. */ void wlr_seat_touch_send_up(struct wlr_seat *seat, uint32_t time, int32_t touch_id); /** * Send a touch motion event for the touch point given by the `touch_id`. The * event will go to the client for the surface given in the corresponding touch * down event. Compositors should use `wlr_seat_touch_notify_motion()` to * respect any grabs of the touch device. */ void wlr_seat_touch_send_motion(struct wlr_seat *seat, uint32_t time, int32_t touch_id, double sx, double sy); /** * How many touch points are currently down for the seat. */ int wlr_seat_touch_num_points(struct wlr_seat *seat); /** * Whether or not the seat has a touch grab other than the default grab. */ bool wlr_seat_touch_has_grab(struct wlr_seat *seat); /** * Check whether this serial is valid to start a grab action such as an * interactive move or resize. */ bool wlr_seat_validate_grab_serial(struct wlr_seat *seat, uint32_t serial); struct wlr_seat_client *wlr_seat_client_from_resource( struct wl_resource *resource); struct wlr_seat_client *wlr_seat_client_from_pointer_resource( struct wl_resource *resource); #endif
jnpkrn/wlroots
include/xwayland/selection.h
#ifndef XWAYLAND_SELECTION_H #define XWAYLAND_SELECTION_H #include <xcb/xfixes.h> #define INCR_CHUNK_SIZE (64 * 1024) #define XDND_VERSION 5 struct wlr_xwm_selection; struct wlr_xwm_selection_transfer { struct wlr_xwm_selection *selection; bool incr; bool flush_property_on_delete; bool property_set; struct wl_array source_data; int source_fd; struct wl_event_source *source; // when sending to x11 xcb_selection_request_event_t request; struct wl_list outgoing_link; // when receiving from x11 int property_start; xcb_get_property_reply_t *property_reply; }; struct wlr_xwm_selection { struct wlr_xwm *xwm; xcb_atom_t atom; xcb_window_t window; xcb_window_t owner; xcb_timestamp_t timestamp; struct wlr_xwm_selection_transfer incoming; struct wl_list outgoing; }; void xwm_selection_transfer_remove_source( struct wlr_xwm_selection_transfer *transfer); void xwm_selection_transfer_close_source_fd( struct wlr_xwm_selection_transfer *transfer); void xwm_selection_transfer_destroy_property_reply( struct wlr_xwm_selection_transfer *transfer); xcb_atom_t xwm_mime_type_to_atom(struct wlr_xwm *xwm, char *mime_type); char *xwm_mime_type_from_atom(struct wlr_xwm *xwm, xcb_atom_t atom); struct wlr_xwm_selection *xwm_get_selection(struct wlr_xwm *xwm, xcb_atom_t selection_atom); void xwm_send_incr_chunk(struct wlr_xwm_selection_transfer *transfer); void xwm_handle_selection_request(struct wlr_xwm *xwm, xcb_selection_request_event_t *req); void xwm_get_incr_chunk(struct wlr_xwm_selection_transfer *transfer); void xwm_handle_selection_notify(struct wlr_xwm *xwm, xcb_selection_notify_event_t *event); int xwm_handle_xfixes_selection_notify(struct wlr_xwm *xwm, xcb_xfixes_selection_notify_event_t *event); bool data_source_is_xwayland(struct wlr_data_source *wlr_source); bool primary_selection_source_is_xwayland( struct wlr_gtk_primary_selection_source *wlr_source); void xwm_seat_handle_start_drag(struct wlr_xwm *xwm, struct wlr_drag *drag); void xwm_selection_init(struct wlr_xwm *xwm); void xwm_selection_finish(struct wlr_xwm *xwm); #endif
VladimirDinic/WDSimplexMethod
WDSimplexMethod/WDSimplexMethod/WDSimplexMethod.h
// // WDSimplexMethod.h // WDSimplexMethod // // Created by <NAME> on 10/13/17. // Copyright © 2017 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for WDSimplexMethod. FOUNDATION_EXPORT double WDSimplexMethodVersionNumber; //! Project version string for WDSimplexMethod. FOUNDATION_EXPORT const unsigned char WDSimplexMethodVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <WDSimplexMethod/PublicHeader.h>
thierryH91200/TFDate
TFDate/TFDate.h
// // TFDate.h // TFDate // // Created by <NAME> on 21/01/2020. // Copyright © 2020 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> //! Project version number for TFDate. FOUNDATION_EXPORT double TFDateVersionNumber; //! Project version string for TFDate. FOUNDATION_EXPORT const unsigned char TFDateVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <TFDate/PublicHeader.h> #import <TFDate/TFDatePicker.h> #import <TFDate/TFDatePickerCell.h> #import <TFDate/TFDatePickerPopoverController.h>
thierryH91200/TFDate
TFDate/TFDatePicker.h
// // DatePickerTextField.h // ShootStudio // // Created by <NAME> on 16/06/2010. // Copyright 2010 <NAME>. All rights reserved. // #import <Cocoa/Cocoa.h> @interface TFDatePicker : NSDatePicker <NSDatePickerCellDelegate, NSPopoverDelegate> /*! Class default timezone accessors. - timeZone defaults to this value */ + (void)setDefaultTimeZone:(NSTimeZone *)defaultTimeZone; + (NSTimeZone *)defaultTimeZone; /*! Class default calendar accessors. - calendar defaults to this value */ + (void)setDefaultCalendar:(NSCalendar *)defaultCalendar; + (NSCalendar *)defaultCalendar; /*! Class default locale accessors. - locale defaults to this value */ + (void)setDefaultLocale:(NSLocale *)defaultLocale; + (NSLocale *)defaultLocale; /*! Class default date normalisation selector accessors. - defaultDateNormalisationSelector defaults to this value */ + (void)setDefaultDateNormalisationSelector:(SEL)dateNormalisationSelector; + (SEL)defaultDateNormalisationSelector; /*! Class default reference date accessors. - referenceDate defaults to this value */ + (void)setDefaultReferenceDate:(NSDate *)date; + (NSDate *)defaultReferenceDate; /*! Class default reference date accessors. - minDate defaults to this value */ + (void)setDefaultMinDate:(NSDate *)defaultDate; + (NSDate *)defaultMinDate; /*! Class default reference date accessors. - maxDate defaults to this value */ + (void)setDefaultMaxDate:(NSDate *)defaultDate; + (NSDate *)defaultMaxDate; /*! Class default delegate accessors. - delegate defaults to this value */ + (void)setDefaultDelegate:(id)delegate; + (id)defaultDelegate; /*! Class default delegate accessors. - dateFieldPlaceHolder defaults to this value */ + (void)setDefaultDateFieldPlaceHolder:(NSString *)dateFieldPlaceHolder; + (NSString *)defaultDateFieldPlaceHolder; /*! Returns YES if no date displayed. */ @property (nonatomic, readonly) BOOL empty; /*! If set to YES then a nil dateValue is displayed as an empty date. */ @property (nonatomic, assign) BOOL allowEmptyDate; /*! If set to YES then a visual prompt image is displayed when the represented date is nil. */ @property (nonatomic, assign) BOOL showPromptWhenEmpty; /*! The selector to use for date normalization. Defaults to +defaultDateNormalisationSelector */ @property SEL dateNormalisationSelector; /*! Reference date to use when editing an empty date. */ @property (nonatomic, strong) NSDate *referenceDate; /*! Update the control's value. If the control is bound then the bound object is updated too. */ - (void)updateControlValue:(NSDate *)date; /*! Update the control's value. Date field place holder text. */ @property (strong) NSString *dateFieldPlaceHolder; /*! Show popover when empty control becomes first responder. */ @property (assign) BOOL showPopoverOnFirstResponderWhenEmpty; /*! Show popover when empty control is clicked. */ @property (assign) BOOL showPopoverOnClickWhenEmpty; @end
Jenner4S/Turbo
Turbo/Classes/External/Calendar/KalViewController.h
<filename>Turbo/Classes/External/Calendar/KalViewController.h /* * Copyright (c) 2009 <NAME> * License: http://www.opensource.org/licenses/mit-license.html */ #import "KalView.h" // for the KalViewDelegate protocol #import "KalDataSource.h" // for the KalDataSourceCallbacks protocol @class KalLogic, KalDate; /* * KalViewController * ------------------------ * * KalViewController automatically creates both the calendar view * and the events table view for you. The only thing you need to provide * is a KalDataSource so that the calendar system knows which days to * mark with a dot and which events to list under the calendar when a certain * date is selected (just like in Apple's calendar app). * */ @interface KalViewController : UIViewController <KalViewDelegate, KalDataSourceCallbacks> @property (nonatomic, weak) id<UITableViewDelegate> delegate; @property (nonatomic, weak) id<KalDataSource> dataSource; @property (nonatomic, strong, readonly) NSDate *selectedDate; @property (nonatomic, weak, readonly) KalView * calendarView; - (id)initWithSelectedDate:(NSDate *)selectedDate; // designated initializer. When the calendar is first displayed to the user, the month that contains 'selectedDate' will be shown and the corresponding tile for 'selectedDate' will be automatically selected. - (void)reloadData; // If you change the KalDataSource after the KalViewController has already been displayed to the user, you must call this method in order for the view to reflect the new data. - (void)showAndSelectDate:(NSDate *)date; // Updates the state of the calendar to display the specified date's month and selects the tile for that date. @end
Jenner4S/Turbo
Turbo/Classes/Shared/XML/TRBXMLElement.h
<filename>Turbo/Classes/Shared/XML/TRBXMLElement.h /* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @interface TRBXMLElement : NSObject @property (nonatomic, weak, readonly) TRBXMLElement * parent; @property (atomic, strong, readonly) NSString * name; @property (nonatomic, strong, readonly) NSString * text; @property (nonatomic, strong, readonly) NSDictionary * attributes; @property (nonatomic, strong, readonly) NSArray * children; + (TRBXMLElement *)XMLElementWithContentsOfFile:(NSString *)path; + (TRBXMLElement *)XMLElementWithData:(NSData *)data error:(NSError **)error; - (TRBXMLElement *)elementAtPath:(NSString *)path; - (NSArray *)elementsAtPath:(NSString *)path; - (id)objectAtIndexedSubscript:(NSUInteger)idx; - (id)objectForKeyedSubscript:(id)key; @end
Jenner4S/Turbo
Turbo/Classes/Movies/TRBRottenTomatoesClient.h
<gh_stars>1-10 /* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ typedef NS_ENUM(NSUInteger, TRBRTListType) { TRBRTListTypeBoxOffice = 0, TRBRTListTypeInTheaters, TRBRTListTypeOpening, TRBRTListTypeUpcomingMovies, TRBRTListTypeTopRentals, TRBRTListTypeCurrentReleases, TRBRTListTypeNewReleases, TRBRTListTypeUpcomingDVDs, TRBRTListTypeCount }; @interface TRBRottenTomatoesClient : NSObject + (instancetype)sharedInstance; - (void)fetchMovieList:(TRBRTListType)listType withHandler:(TRBJSONResultBlock)handler; - (void)fetchImageAtURL:(NSString *)url withHandler:(TRBImageResultBlock)handler; - (void)fetchMovieInfoForID:(NSString *)movieID withHandler:(TRBJSONResultBlock)handler; - (void)fetchMovieReviewsForID:(NSString *)movieID page:(NSUInteger)page withHandler:(TRBJSONResultBlock)handler; - (void)fetchCastsInfoForID:(NSString *)movieID withHandler:(TRBJSONResultBlock)handler; - (void)searchWithQuery:(NSString *)query page:(NSUInteger)page andHandler:(TRBJSONResultBlock)handler; @end
Jenner4S/Turbo
Turbo/Classes/Torrents/Shared/TRBHost.h
<reponame>Jenner4S/Turbo<gh_stars>1-10 /* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ typedef NS_ENUM(NSUInteger, HTTPProtocol) { HTTPProtocolHTTP = 0, HTTPProtocolHTTPS, HTTPProtocolCount }; @class TRBTorrentClient; @interface TRBHost : NSObject<NSCoding> @property (nonatomic, strong) NSString * name; @property (nonatomic, strong) NSString * desc; @property (nonatomic, assign) HTTPProtocol protocol; @property (nonatomic, strong) NSString * domain; @property (nonatomic, assign) NSInteger port; @property (nonatomic, strong) NSString * path; @property (nonatomic, strong) NSError * error; @property (nonatomic, strong) UIImage * icon; - (NSURL *)URL; - (TRBTorrentClient *)client; @end @interface TRBTransmissionHost : TRBHost @end @protocol TRBHostListDelegate; @interface TRBHostList : NSObject @property (nonatomic, weak) id<TRBHostListDelegate> delegate; - (void)addHost:(TRBHost *)host; - (void)removeHost:(TRBHost *)host; - (void)removeHostAtIndex:(NSUInteger)index; - (NSUInteger)activeHostCount; - (NSUInteger)inactiveHostCount; - (TRBHost *)activeHostAtIndex:(NSInteger)index; - (TRBHost *)inactiveHostAtIndex:(NSInteger)index; - (void)activateHost:(TRBHost *)host; - (void)deactivateHost:(TRBHost *)host; - (NSArray *)activeHosts; - (NSArray *)inactiveHosts; - (void)save; @end @protocol TRBHostListDelegate<NSObject> - (void)hostListDidChangeActiveHosts:(TRBHostList *)hostList; @end
Jenner4S/Turbo
Turbo/Classes/TVShows/Model/TRBTVShowSeason.h
<gh_stars>1-10 /* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @import CoreData; @class TRBTVShow, TRBTVShowEpisode; @interface TRBTVShowSeason : NSManagedObject @property (nonatomic, retain) NSNumber * number; @property (nonatomic, retain) NSNumber * seriesID; @property (nonatomic, retain) TRBTVShow *series; @property (nonatomic, retain) NSSet *episodes; @end @interface TRBTVShowSeason (CoreDataGeneratedAccessors) - (void)addEpisodesObject:(TRBTVShowEpisode *)value; - (void)removeEpisodesObject:(TRBTVShowEpisode *)value; - (void)addEpisodes:(NSSet *)values; - (void)removeEpisodes:(NSSet *)values; @end
Jenner4S/Turbo
Turbo/Classes/External/Tapku/AlertCenter/TKAlertCenter.h
// // TKAlertCenter.h // Created by <NAME> on 9/29/10. // /* tapku.com || http://github.com/devinross/tapkulibrary Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @class TKAlertView; /** A notification center for displaying quick bursts of alert information to the user. */ @interface TKAlertCenter : NSObject /** Returns the process’s default notification center. @return The current process’s default notification center, which is used for alert notifications. */ + (TKAlertCenter*) defaultCenter; /** Posts a given alert message to the user. @param message The message shown under an image. @param image The image displayed to the user. If image is nil, the message will only be shown. */ - (void) postAlertWithMessage:(NSString*)message image:(UIImage*)image; /** Posts a given alert message to the user. @param message The message shown under an image. */ - (void) postAlertWithMessage:(NSString *)message; @end
Jenner4S/Turbo
Turbo/Classes/Shared/TRBGlobals.h
/* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @import Foundation; @class TRBXMLElement; #define isIdiomPhone ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) #define isIdiomPad ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) // Searches static NSString * const TRBTorrentzSearchNotification = @"TRBTorrentzSearch"; static NSString * const TRBMovieSearchNotification = @"TRBMovieSearch"; static NSString * const TRBTVShowSearchNotification = @"TRBTVShowSearch"; static NSString * const TRBTVShowNotification = @"TRBTVShow"; static NSString * const TRBTVShowEpisodeKey = @"TRBTVShowEpisode"; static NSString * const TRBSearchQueryKey = @"TRBSearchQuery"; // Settings static NSString * const TRBSettingsUpdatedNotification = @"TRBSettingsUpdated"; static NSString * const TRBWiFiRefreshRateKey = @"TRBWiFiRefreshRate"; static NSString * const TRBCellularRefreshRateKey = @"TRBCellularRefreshRate"; static NSString * const TRBIMDbSearchWebOnlyKey = @"TRBIMDbSearchWebOnlyApp"; static NSString * const TRBTVShowInfoRefreshRateKey = @"TRBTVShowInfoRefreshRate"; static NSString * const TRBTVShowNotificationsKey = @"TRBTVShowNotifications"; static NSString * const TRBSynologyHostKey = @"TRBSynologyHost"; static NSString * const TRBSynologyPortKey = @"TRBSynologyPort"; // Common Blocks typedef void(^TRBJSONResultBlock)(NSDictionary * json, NSError * error); typedef void(^TRBXMLResultBlock)(TRBXMLElement * xml, NSError * error); typedef void(^TRBImageResultBlock)(UIImage * image, NSError * error); __attribute__((always_inline)) static inline void _Log(const char * function, int line, id fmt, ...); __attribute__((always_inline)) static inline void _LogC(const char * function, int line, BOOL condition, id fmt, ...); #define _WarningFmt @"\n[WARNING]\n" #define _ErrorFmt @"\n[ERROR]\n" #define _InfoFmt @"\n[INFO]\n" #ifndef TRBDebug # define LogV(fmt, ...) # define LogCV(condition, fmt, ...) # define LogI(fmt, ...) # define LogCI(condition, fmt, ...) # define LogW(fmt, ...) # define LogCW(condition, fmt, ...) # define LogE(fmt, ...) # define LogCE(condition, fmt, ...) #else # define LogV(fmt, ...) _Log(__PRETTY_FUNCTION__, __LINE__, fmt, ##__VA_ARGS__) # define LogCV(condition, fmt, ...) _LogC(__PRETTY_FUNCTION__, __LINE__, condition, fmt, ##__VA_ARGS__) # define LogI(fmt, ...) _Log(__PRETTY_FUNCTION__, __LINE__, [_InfoFmt stringByAppendingString:(fmt)], ##__VA_ARGS__) # define LogCI(condition, fmt, ...) _LogC(__PRETTY_FUNCTION__, __LINE__, condition, [_InfoFmt stringByAppendingString:((fmt) ? [fmt description] : @"")], ##__VA_ARGS__) # define LogW(fmt, ...) _Log(__PRETTY_FUNCTION__, __LINE__, [_WarningFmt stringByAppendingString:(fmt)], ##__VA_ARGS__) # define LogCW(condition, fmt, ...) _LogC(__PRETTY_FUNCTION__, __LINE__, condition, [_WarningFmt stringByAppendingString:((fmt) ? [fmt description] : @"")], ##__VA_ARGS__) # define LogE(fmt, ...) _Log(__PRETTY_FUNCTION__, __LINE__, [_ErrorFmt stringByAppendingString:((fmt) ? [fmt description] : @"")], ##__VA_ARGS__) # define LogCE(condition, fmt, ...) _LogC(__PRETTY_FUNCTION__, __LINE__, condition, [_ErrorFmt stringByAppendingString:((fmt) ? [fmt description] : @"")], ##__VA_ARGS__) #endif __attribute__((always_inline)) static inline void _Log(const char * function, int line, id fmt, ...) { va_list args; va_start(args, fmt); fmt = [NSString stringWithFormat:@"[%s][line %d] %@", function, line, ((fmt) ? [(fmt) description] : @"")]; NSLogv(fmt, args); va_end(args); } __attribute__((always_inline)) static inline void _LogC(const char * function, int line, BOOL condition, id fmt, ...) { if (condition) { va_list args; va_start(args, fmt); fmt = [NSString stringWithFormat:@"[%s][line %d] %@", function, line, ((fmt) ? [(fmt) description] : @"")]; NSLogv(fmt, args); va_end(args); } } __attribute__((always_inline)) static inline NSString * TRBLibraryDir() { NSString * libraryDirectory = nil; NSArray * paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); if ([paths count]) libraryDirectory = paths[0]; return libraryDirectory; } __attribute__((always_inline)) static inline void TRBDumpRequestToConsole(NSURLRequest * request) { NSMutableString * message = [[NSMutableString alloc] initWithString:@"*** REQUEST ***"]; [message appendString:[NSString stringWithFormat:@"\nHTTP Method: %@", [request HTTPMethod]]]; [message appendString:[NSString stringWithFormat:@"\nURL: %@", [[request URL] absoluteString]]]; [message appendString:[NSString stringWithFormat:@"\nHeaders: %@",[request allHTTPHeaderFields]]]; NSData * body = [request HTTPBody]; if ([body length]) { NSString * bodyString = [[NSString alloc] initWithData:body encoding:NSASCIIStringEncoding]; [message appendString:[NSString stringWithFormat:@"\nBody:\n%@", bodyString]]; } LogI(@"%@", message); } __attribute__((always_inline)) static inline void TRBDumpResponseToConsole(NSHTTPURLResponse * response) { if ([response isKindOfClass:[NSHTTPURLResponse class]]) { NSMutableString * message = [[NSMutableString alloc] initWithString:@"*** RESPONSE ***"]; [message appendString:[NSString stringWithFormat:@"\nHTTP Status Code: %ld %@", (long)[response statusCode], [NSHTTPURLResponse localizedStringForStatusCode:[response statusCode]]]]; [message appendString:[NSString stringWithFormat:@"\nURL: %@", [[response URL] absoluteString]]]; [message appendString:[NSString stringWithFormat:@"\nHeaders: %@", [response allHeaderFields]]]; LogI(@"%@", message); } } __attribute__((always_inline)) static inline void TRBDumpResponseDataToConsole(NSData * data) { NSString * responseString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; LogCI([responseString length], @"Response string:\n%@", responseString); }
Jenner4S/Turbo
Turbo/Classes/Shared/TRBPioneerReceiverManager.h
/* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ typedef NS_ENUM(NSUInteger, TRBPRPowerState) { TRBPRPowerStateUnknown = 0, TRBPRPowerStateOn, TRBPRPowerStateOff, }; typedef NS_ENUM(NSUInteger, TRBPRInputSource) { TRBPRInputSourceDVD = 0, TRBPRInputSourceBD, TRBPRInputSourceTVSAT, TRBPRInputSourceDVRBDR, TRBPRInputSourceVideo1, TRBPRInputSourceVideo2, TRBPRInputSourceHDMI1, TRBPRInputSourceHDMI2, TRBPRInputSourceHDMI3, TRBPRInputSourceHDMI4, TRBPRInputSourceHDMI5, TRBPRInputSourceHomeMedia, TRBPRInputSourceUSBiPod, TRBPRInputSourceXMRadio, TRBPRInputSourceCD, TRBPRInputSourceCDRTape, TRBPRInputSourceTuner, TRBPRInputSourcePhono, TRBPRInputSourceMultiChIn, TRBPRInputSourceAdapterPort, TRBPRInputSourceSirius, TRBPRInputSourceHDMICyclic, TRBPRInputSourceUnknown }; @interface TRBPioneerReceiverManager : NSObject @property (nonatomic, readonly) TRBPRPowerState powerState; @property (nonatomic, readonly) TRBPRInputSource inputSource; @property (nonatomic, readonly) BOOL isConnected; + (instancetype)sharedInstance; - (void)connectToAddress:(NSString *)address port:(UInt32)port inputHandler:(void(^)(NSString *))inputHandler onOpen:(void(^)(void))onOpen; - (void)disconnect; - (void)powerOn:(void(^)(void))completion; - (void)powerOff:(void(^)(void))completion; - (void)changeToInput:(TRBPRInputSource)input completion:(void(^)(void))completion; - (void)sendCommand:(NSString *)command; @end
Jenner4S/Turbo
Turbo/Classes/Movies/TMDb/TRBTMDbClient.h
/* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @class TRBMovie; typedef NS_ENUM(NSUInteger, TRBTMDbPosterSize) { TRBTMDbPosterSizeW92 = 0, TRBTMDbPosterSizeW154, TRBTMDbPosterSizeW185, TRBTMDbPosterSizeW342, TRBTMDbPosterSizeW500, TRBTMDbPosterSizeOriginal, }; typedef NS_ENUM(NSUInteger, TRBTMDbBackdropSize) { TRBTMDbBackdropSizeW300 = 0, TRBTMDbBackdropSizeW780, TRBTMDbBackdropSize1280, TRBTMDbBackdropSizeOriginal, }; typedef NS_ENUM(NSUInteger, TRBTMDbListType) { TRBTMDbListTypePopular = 0, TRBTMDbListTypeUpcoming, TRBTMDbListTypeNowPlaying, TRBTMDbListTypeTopRated, TRBTMDbListTypeCount }; typedef NS_ENUM(NSUInteger, TRBTMDbProfileSize) { TRBTMDbProfileSizeW45 = 0, TRBTMDbProfileSizeW185, TRBTMDbProfileSizeH632, TRBTMDbProfileSizeOriginal, }; typedef NS_ENUM(NSUInteger, TRBTMDbImageType) { TRBTMDbImageTypeBackdrop = 0, TRBTMDbImageTypePoster, TRBTMDbImageTypeCount }; @interface TRBTMDbClient : NSObject + (instancetype)sharedInstance; - (void)fetchMovieList:(TRBTMDbListType)listType withPage:(NSUInteger)page completion:(TRBJSONResultBlock)completion; - (void)fetchMovieInfoWithID:(NSNumber *)movieID completion:(TRBJSONResultBlock)completion; - (void)fetchMovieTrailersWithID:(NSNumber *)movieID completion:(TRBJSONResultBlock)completion; - (void)fetchMovieImagesWithID:(NSNumber *)movieID completion:(TRBJSONResultBlock)completion; - (void)fetchMovieCastsWithID:(NSNumber *)movieID completion:(TRBJSONResultBlock)completion; - (void)searchMoviesWithQuery:(NSString *)query page:(NSUInteger)page completion:(TRBJSONResultBlock)completion; - (void)fetchPoster:(NSString *)poster withSize:(TRBTMDbPosterSize)size completion:(TRBImageResultBlock)completion; - (void)fetchBackdrop:(NSString *)backdrop withSize:(TRBTMDbBackdropSize)size completion:(TRBImageResultBlock)completion; - (void)fetchProfileImage:(NSString *)profile withSize:(TRBTMDbProfileSize)size completion:(TRBImageResultBlock)completion; - (void)findMovieWithRTMovie:(TRBMovie *)rtMovie completion:(TRBJSONResultBlock)completion; @end
Jenner4S/Turbo
Turbo/Classes/Shared/XML/TRBRSSFeed.h
/* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @interface TRBRSSFeed : NSObject @property (nonatomic, strong) NSString * title; @property (nonatomic, strong) NSString * link; @property (nonatomic, strong) NSString * desc; @property (nonatomic, strong) NSString * language; @property (nonatomic, strong) NSString * pubDate; @property (nonatomic, strong) NSString * lastBuildDate; @property (nonatomic, strong) NSString * docs; @property (nonatomic, strong) NSString * generator; @property (nonatomic, strong) NSArray * items; - (id)initWithXMLElement:(TRBXMLElement *)element; @end @interface TRBRSSItem : NSObject @property (nonatomic, strong) NSString * title; @property (nonatomic, strong) NSString * link; @property (nonatomic, strong) NSString * comments; @property (nonatomic, strong) NSString * desc; @property (nonatomic, strong) NSString * pubDate; @property (nonatomic, strong) NSString * category; @property (nonatomic, strong) NSString * creator; @property (nonatomic, strong) NSString * guid; @property (nonatomic, strong) NSString * seeders; @property (nonatomic, strong) NSString * leechers; @property (nonatomic, strong) NSString * enclosureURL; @property (nonatomic, strong) NSString * magnetURI; @property (nonatomic, strong) NSString * enclosureType; @property (nonatomic, assign) unsigned long long enclosureLength; - (id)initWithXMLElement:(TRBXMLElement *)element; - (NSDictionary *)infoFromDescription; @end
Jenner4S/Turbo
Turbo/Classes/MainContainer/TRBRevealingViewController.h
<filename>Turbo/Classes/MainContainer/TRBRevealingViewController.h /* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ typedef NS_ENUM(NSUInteger, TRBRevealingViewControllerState) { TRBRevealingViewControllerStateInitial = 0, TRBRevealingViewControllerStateSlidingIn, TRBRevealingViewControllerStateConcealed, TRBRevealingViewControllerStateSlidingOut, TRBRevealingViewControllerStateLeftRevealed, TRBRevealingViewControllerStateRightRevealed, TRBRevealingViewControllerStateTopRevealed, TRBRevealingViewControllerStateBottomRevealed, }; @protocol TRBRevealingViewControllerDelegate; @interface TRBRevealingViewController : UIViewController @property (nonatomic, readonly, assign) TRBRevealingViewControllerState state; @property (nonatomic, weak) id<TRBRevealingViewControllerDelegate> delegate; @property (nonatomic, assign, readonly) UIEdgeInsets edgeInsets; @property (nonatomic, assign) CGFloat friction; @property (nonatomic, strong) UIViewController * mainViewController; @property (nonatomic, strong) UIViewController * leftViewController; @property (nonatomic, strong) UIViewController * rightViewController; @property (nonatomic, strong) UIViewController * topViewController; @property (nonatomic, strong) UIViewController * bottomViewController; @property (nonatomic, strong) NSString * storyboardIDForMainViewController; @property (nonatomic, strong) NSString * storyboardIDForLeftViewController; @property (nonatomic, strong) NSString * storyboardIDForRightViewController; @property (nonatomic, strong) NSString * storyboardIDForTopViewController; @property (nonatomic, strong) NSString * storyboardIDForBottomViewController; - (id)initWithControllers:(NSArray *)controllers; - (void)concealViewControllerAnimated:(BOOL)animated completion:(void (^)(void))completion; - (void)revealLeftViewControllerAnimated:(BOOL)animated completion:(void (^)(void))completion; - (void)revealRightViewControllerAnimated:(BOOL)animated completion:(void (^)(void))completion; - (void)revealTopViewControllerAnimated:(BOOL)animated completion:(void (^)(void))completion; - (void)revealBottomViewControllerAnimated:(BOOL)animated completion:(void (^)(void))completion; - (void)setLeftInset:(CGFloat)leftInset animated:(BOOL)animated; - (void)setRightInset:(CGFloat)rightInset animated:(BOOL)animated; - (void)setTopInset:(CGFloat)topInset animated:(BOOL)animated; - (void)setBottomInset:(CGFloat)bottomInset animated:(BOOL)animated; @end @protocol TRBRevealingViewControllerDelegate <NSObject> @optional - (void)revealingViewController:(TRBRevealingViewController *)revealingViewController willRevealViewController:(UIViewController *)controller andTransitionToState:(TRBRevealingViewControllerState)state; - (void)revealingViewController:(TRBRevealingViewController *)revealingViewController didRevealViewController:(UIViewController *)controller; - (void)revealingViewController:(TRBRevealingViewController *)revealingViewController willConcealViewController:(UIViewController *)controller; - (void)revealingViewController:(TRBRevealingViewController *)revealingViewController didConcealViewController:(UIViewController *)controller; - (void)revealingViewController:(TRBRevealingViewController *)revealingViewController willAdjustToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation; - (void)revealingViewController:(TRBRevealingViewController *)revealingViewController didAdjustFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation; @end @interface UIViewController (TRBRevealingViewControllerAddition) @property (nonatomic, readonly, assign) TRBRevealingViewController * revealingViewController; @end
Jenner4S/Turbo
Turbo/Classes/TVShows/Model/TRBTVShowsStorage.h
<reponame>Jenner4S/Turbo<gh_stars>1-10 /* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @import CoreData; typedef NS_ENUM(NSUInteger, TRBTVShowBannerType) { TRBTVShowBannerTypePoster = 0, TRBTVShowBannerTypeFanart, TRBTVShowBannerTypeSeries, TRBTVShowBannerTypeSeason, TRBTVShowBannerTypeCount }; @class TRBTVShow; @class TRBTVShowEpisode; @class TRBTVShowBanner; @interface TRBTVShowsStorage : NSObject + (instancetype)sharedInstance; #pragma mark - TV Shows - (void)insertNewTVShowWithXML:(TRBXMLElement *)xml overwrite:(BOOL)overwrite andHandler:(void(^)(TRBTVShow * tvShow))handler; - (void)fetchAllTVShowsWithHandler:(void(^)(NSArray * results))handler; - (void)fetchTVShowWithID:(NSUInteger)seriesID andHandler:(void(^)(TRBTVShow * tvShow))handler; - (void)fetchTVShowCountWithHandler:(void(^)(NSUInteger count))handler; - (void)fetchStaleTVShowsWithHandler:(void(^)(NSArray * results))handler; - (void)searchTVShowsWithTitle:(NSString *)title andHandler:(void(^)(NSArray * results))handler; - (void)removeTVShow:(TRBTVShow *)tvShow; - (void)removeTVShowWithID:(NSUInteger)seriesID; - (void)updateTVShowWithRecords:(NSArray *)records andHandler:(void(^)(TRBTVShow * result))handler; #pragma mark - TV Show Episodes - (void)insertNewTVShowEpisodeWithXML:(TRBXMLElement *)xml forTVShow:(TRBTVShow *)tvShow overwrite:(BOOL)overwrite andHandler:(void(^)(TRBTVShowEpisode * episode))handler; - (void)fetchTVShowEpisodeWithID:(NSUInteger)episodeID andHandler:(void(^)(TRBTVShowEpisode * episode))handler; - (void)fetchNextEpisodeForTVShow:(TRBTVShow *)tvShow andHandler:(void(^)(TRBTVShowEpisode * episode))handler; - (void)fetchPreviousEpisodeForTVShow:(TRBTVShow *)tvShow andHandler:(void(^)(TRBTVShowEpisode * episode))handler; - (void)fetchAllNextEpisodesWithHandler:(void(^)(NSArray * results))handler; - (void)fetchAllScheduledEpisodesWithHandler:(void(^)(NSArray * results))handler; - (void)fetchEpisodesAiringFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate withHandler:(void(^)(NSArray * results))handler; #pragma mark - TV Show Banners - (void)insertNewTVShowBannerWithXML:(TRBXMLElement *)xml forTVShow:(TRBTVShow *)tvShow overwrite:(BOOL)overwrite andHandler:(void(^)(TRBTVShowBanner * banner))handler; - (void)fetchTVShowBannerWithID:(NSUInteger)episodeID andHandler:(void(^)(TRBTVShowBanner * tvShowBanner))handler; - (void)fetchTVShowBannerWithType:(TRBTVShowBannerType)type forTVShow:(TRBTVShow *)tvShow mustHaveColors:(BOOL)colors andHandler:(void(^)(NSArray * banners))handler; - (void)updateTVShowBannersWithRecords:(NSArray *)records forTVShow:(NSManagedObjectID *)tvShowID andHandler:(void(^)())handler; #pragma mark - Shared - (void)save; @end
Jenner4S/Turbo
Turbo/Classes/Torrents/Releases/TRBReleaseFilters.h
<filename>Turbo/Classes/Torrents/Releases/TRBReleaseFilters.h /* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ typedef NS_ENUM(NSUInteger, TRBReleaseType) { TRBReleaseTypeMovie = 1, TRBReleaseTypePC, TRBReleaseTypeTVShow, TRBReleaseTypeWii, TRBReleaseTypeXbox360, TRBReleaseTypePS3, TRBReleaseTypeCount = TRBReleaseTypePS3, }; static NSString * const TRBReleaseTypes[TRBReleaseTypeCount] = {@"Movie", @"PC", @"TV Show", @"Wii", @"Xbox 360", @"PS3"}; typedef NS_ENUM(NSUInteger, TRBReleaseSubType) { TRBReleaseSubTypeP2P = 1, TRBReleaseSubTypeScene, TRBReleaseSubTypeCount = TRBReleaseSubTypeScene, }; static NSString * const TRBReleaseSubTypes[TRBReleaseSubTypeCount] = {@"P2P", @"Scene"}; typedef NS_ENUM(NSUInteger, TRBReleaseVideoFormat) { TRBReleaseVideoFormatDVDR = 1, TRBReleaseVideoFormatX264, TRBReleaseVideoFormatXVId, TRBReleaseVideoFormatDLC, TRBReleaseVideoFormatISO, TRBReleaseVideoFormatVC, TRBReleaseVideoFormatWiiware, TRBReleaseVideoFormatXBLA, TRBReleaseVideoFormatLauncher, TRBReleaseVideoFormatUnlocker, TRBReleaseVideoFormatVCD, TRBReleaseVideoFormatSVCD, TRBReleaseVideoFormatVOB, TRBReleaseVideoFormatWMV, TRBReleaseVideoFormatJB, TRBReleaseVideoFormatCount = TRBReleaseVideoFormatJB, }; static NSString * const TRBReleaseVideoFormats[TRBReleaseVideoFormatCount] = {@"DVDR", @"x264", @"Xvid", @"DLC", @"ISO", @"VC", @"Wiiware", @"XBLA", @"Launcher", @"Unlocker", @"VCD", @"SVCD", @"VOB", @"WMV", @"JB"}; typedef NS_ENUM(NSUInteger, TRBReleaseSource) { TRBReleaseSourceUnknown = 1, TRBReleaseSource1080p, TRBReleaseSource720p, TRBReleaseSourceBDRip, TRBReleaseSourceCable, TRBReleaseSourceCAM, TRBReleaseSourceDSR, TRBReleaseSourceDVD, TRBReleaseSourceDVDRip, TRBReleaseSourceDVDSCR, TRBReleaseSourceHDRip, TRBReleaseSourceHDTV, TRBReleaseSourceLaserDisc, TRBReleaseSourceNetwork, TRBReleaseSourceNTSC, TRBReleaseSourcePAL, TRBReleaseSourcePDTV, TRBReleaseSourcePDVD, TRBReleaseSourcePPV, TRBReleaseSourcePreair, TRBReleaseSourceR5, TRBReleaseSourceScreener, TRBReleaseSourceTelecine, TRBReleaseSourceTelesync, TRBReleaseSourceTVRip, TRBReleaseSourceVCDRip, TRBReleaseSourceVHSRip, TRBReleaseSourceWorkprint, TRBReleaseSourceRF, TRBReleaseSourceUSA, TRBReleaseSourceEUR, TRBReleaseSourceWebSCR, TRBReleaseSourceCount = TRBReleaseSourceWebSCR, }; static NSString * const TRBReleaseSources[TRBReleaseSourceCount] = {@"Unknown", @"1080p", @"720p", @"BDRip", @"Cable", @"CAM", @"DSR", @"DVD", @"DVDRip", @"DVDSrc", @"HDRip", @"HDTV", @"LaserDisc", @"Network", @"NTSC", @"PAL", @"PDTV", @"PDVD", @"PPV", @"Preair", @"R5", @"Screener", @"Telecine", @"Telesync", @"TVRip", @"VCDRip", @"VHSRip", @"Workprint", @"RF", @"USA", @"EUR", @"WebScr"}; typedef NS_ENUM(NSUInteger, TRBReleaseGenre) { TRBReleaseGenreUnknown = 1, TRBReleaseGenreAction, TRBReleaseGenreComedy, TRBReleaseGenreThriller, TRBReleaseGenreHorror, TRBReleaseGenreAnimation, TRBReleaseGenreDrama, TRBReleaseGenreFantasy, TRBReleaseGenreDocumentary, TRBReleaseGenreCrime, TRBReleaseGenreFamily, TRBReleaseGenreGameShow, TRBReleaseGenreRealtyTV, TRBReleaseGenreBiography, TRBReleaseGenreAdventure, TRBReleaseGenreMystery, TRBReleaseGenreWestern, TRBReleaseGenreRomance, TRBReleaseGenreShort, TRBReleaseGenreFilmNoir, TRBReleaseGenreMusic, TRBReleaseGenreMusical, TRBReleaseGenreAdult, TRBReleaseGenreSciFi, TRBReleaseGenreWar, TRBReleaseGenreHistory, TRBReleaseGenreTalkShow, TRBReleaseGenreSport, TRBReleaseGenreNews, TRBReleaseGenreCount = TRBReleaseGenreNews, }; static NSString * const TRBReleaseGenres[TRBReleaseGenreCount] = {@"Unknown", @"Action", @"Comedy", @"Thriller", @"Horror", @"Animation", @"Drama", @"Fantasy", @"Documentary", @"Crime", @"Family", @"GameShow", @"RealtyTV", @"Biography", @"Adventure", @"Mystery", @"Western", @"Romance", @"Short", @"FilmNoir", @"Music", @"Musical", @"Adult", @"SciFi", @"War", @"History", @"TalkShow", @"Sport", @"News"}; #define kTRBStaticFiltersCount 5 #define kTRBAllFiltersCount 6 static NSUInteger const TRBStaticFilterCounts[kTRBStaticFiltersCount] = {TRBReleaseTypeCount, TRBReleaseSubTypeCount, TRBReleaseVideoFormatCount, TRBReleaseSourceCount, TRBReleaseGenreCount}; static NSString * const TRBReleaseFilterTitles[kTRBAllFiltersCount] = {@"Type", @"Subtype", @"Video Format", @"Source", @"Genre", @"Year"}; static NSString * const * TRBReleaseStaticFilters[kTRBStaticFiltersCount] = {TRBReleaseTypes, TRBReleaseSubTypes, TRBReleaseVideoFormats, TRBReleaseSources, TRBReleaseGenres}; #define kTRBReleaseStartingYear 1980
Jenner4S/Turbo
Turbo/Classes/Library/TRBLibraryMovieDetailsViewController.h
<reponame>Jenner4S/Turbo /* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @class TRBMovie; @interface TRBLibraryMovieDetailsViewController : UICollectionViewController - (void)showMovie:(TRBMovie *)movie; @end @interface TRBLibraryMovieDetailsCell : UICollectionViewCell @property (weak, nonatomic) IBOutlet UILabel * titleLabel; @property (weak, nonatomic) IBOutlet UILabel * taglineLabel; @property (weak, nonatomic) IBOutlet UILabel * genresLabel; @property (weak, nonatomic) IBOutlet UILabel * actorsLabel; @end @interface TRBLibraryMovieDetailsHeaderView : UICollectionReusableView @property (weak, nonatomic) IBOutlet UIImageView * backdropImageView; @property (weak, nonatomic) IBOutlet UITextView * summaryTextView; @end @interface TRBLibraryFileDetailsCell : UICollectionViewCell @property (weak, nonatomic) IBOutlet UILabel *sizeLabel; @property (weak, nonatomic) IBOutlet UILabel *resolutionLabel; @property (weak, nonatomic) IBOutlet UILabel *videoCodecLabel; @property (weak, nonatomic) IBOutlet UILabel *audioCodecLabel; @property (weak, nonatomic) IBOutlet UILabel *durationLabel; @property (weak, nonatomic) IBOutlet UILabel *pathLabel; - (void)setupWithFileInfo:(NSDictionary *)fileInfo; @end @interface TRBLibraryFileDetailsHeaderView : UICollectionReusableView @end
Jenner4S/Turbo
Turbo/Classes/External/Tapku/Categories/NSDate+TKCategory.h
<reponame>Jenner4S/Turbo<gh_stars>1-10 // // NSDateAdditions.h // Created by <NAME> on 7/28/09. // /* tapku.com || http://github.com/devinross/tapkulibrary Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ struct TKDateInformation { NSInteger day; NSInteger month; NSInteger year; NSInteger weekday; NSInteger minute; NSInteger hour; NSInteger second; }; typedef struct TKDateInformation TKDateInformation; /** Additional functionality for `NSDate`. */ @interface NSDate (TKCategory) + (NSDate *) yesterday; /** Creates and returns a new date set to the current month. @return A `NSDate` object set to the current month. */ + (NSDate *) month; /** Creates and returns a new date set to the first day of the month from the date object. @return A `NSDate` object set to the same month as the date object. The day will be the first of the month. */ - (NSDate *) monthDate; - (BOOL) isSameDay:(NSDate*)anotherDate; - (NSInteger) monthsBetweenDate:(NSDate *)toDate; - (NSInteger) daysBetweenDate:(NSDate*)date; /** Returns a Boolean value that indicates whether the date object is that same date information as the current day. @return YES if the date object represents the current date, otherwise NO. */ - (BOOL) isToday; - (NSDate *) dateByAddingDays:(NSUInteger)days; + (NSDate *) dateWithDatePart:(NSDate *)aDate andTimePart:(NSDate *)aTime; - (NSString *) monthYearString; - (NSString *) monthString; - (NSString *) yearString; - (TKDateInformation) dateInformation; - (TKDateInformation) dateInformationWithTimeZone:(NSTimeZone*)tz; + (NSDate*) dateFromDateInformation:(TKDateInformation)info; + (NSDate*) dateFromDateInformation:(TKDateInformation)info timeZone:(NSTimeZone*)tz; + (NSString*) dateInformationDescriptionWithInformation:(TKDateInformation)info; @end
Jenner4S/Turbo
Turbo/Classes/Movies/TRBMovie.h
<reponame>Jenner4S/Turbo /* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @interface TRBMovie : NSObject @property (nonatomic, strong) NSString * vsID; @property (nonatomic, strong) NSString * rtID; @property (nonatomic, strong) NSNumber * tmdbID; @property (nonatomic, strong) NSString * imdbID; @property (nonatomic, strong) NSString * title; @property (nonatomic, strong) NSString * genres; @property (nonatomic, strong) NSNumber * criticsScore; @property (nonatomic, strong) NSString * criticsRating; @property (nonatomic, strong) NSNumber * audienceScore; @property (nonatomic, strong) NSString * audienceRating; @property (nonatomic, strong) NSString * criticsConsensus; @property (nonatomic, strong) NSString * mpaaRating; @property (nonatomic, strong) NSNumber * year; @property (nonatomic, strong) NSNumber * runtime; @property (nonatomic, strong) NSString * synopsis; @property (nonatomic, strong) NSString * tagline; @property (nonatomic, strong) NSDictionary * posters; @property (nonatomic, strong) UIImage * posterImage; @property (nonatomic, strong) NSString * backdropPath; @property (nonatomic, strong) UIImage * backdropImage; @property (nonatomic, strong) NSDictionary * links; @property (nonatomic, strong) NSString * cast; @property (nonatomic, strong) NSString * studio; @property (nonatomic, strong) NSString * directors; @property (nonatomic, strong) NSString * writers; @property (nonatomic, strong) NSString * releaseDate; @property (nonatomic, strong) NSArray * files; - (instancetype)initWithVSJSON:(NSDictionary *)movie; - (instancetype)initWithRTJSON:(NSDictionary *)movie; - (void)updateWithVSInfo:(NSDictionary *)movie; - (void)updateWithRTInfo:(NSDictionary *)movie; - (void)updateWithTMDbInfo:(NSDictionary *)movie; @end
Jenner4S/Turbo
Turbo/Classes/Torrents/Shared/TRBTorrent.h
<reponame>Jenner4S/Turbo<filename>Turbo/Classes/Torrents/Shared/TRBTorrent.h /* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ typedef NS_ENUM(NSInteger, TRBTorrentStatus) { TRBTorrentStatusUnknown = -1, TRBTorrentStatusStopped = 0, /* Torrent is stopped */ TRBTorrentStatusCheckWait, /* Queued to check files */ TRBTorrentStatusCheck, /* Checking files */ TRBTorrentStatusDownloadWait, /* Queued to download */ TRBTorrentStatusDownload, /* Downloading */ TRBTorrentStatusSeedWait, /* Queued to seed */ TRBTorrentStatusSeed, /* Seeding */ TRBTorrentStatusCount }; @interface TRBTorrent : NSObject @property (assign, nonatomic, readonly) TRBTorrentStatus status; @property (strong, nonatomic, readonly) NSNumber * identifier; @property (strong, nonatomic, readonly) NSString * name; @property (strong, nonatomic, readonly) NSNumber * percentDone; @property (strong, nonatomic, readonly) NSNumber * peersConnected; @property (strong, nonatomic, readonly) NSNumber * peersSendingToUs; @property (strong, nonatomic, readonly) NSNumber * eta; @property (strong, nonatomic, readonly) NSString * errorString; @property (strong, nonatomic, readonly) NSNumber * rateDownload; @property (strong, nonatomic, readonly) NSNumber * rateUpload; @property (strong, nonatomic, readonly) NSNumber * haveValid; @property (strong, nonatomic, readonly) NSNumber * sizeWhenDone; @property (strong, nonatomic, readonly) NSNumber * isFinished; @property (strong, nonatomic, readonly) NSNumber * isPrivate; @property (strong, nonatomic, readonly) NSNumber * isStalled; - (instancetype)initWithTransmissionJSON:(NSDictionary *)json; - (BOOL)isEqualToTorrent:(TRBTorrent *)torrent; @end
Jenner4S/Turbo
Turbo/Classes/Shared/URLSession/TRBHTTPSession.h
/* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @class TRBHTTPSession; @class TRBHTTPRequestBuilder; @class TRBHTTPResponseParser; typedef void(^TRBHTTPSessionAuthenticationChallengeBlock)(NSURLAuthenticationChallenge * challenge, void(^completionHandler)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * credential)); typedef void(^TRBHTTPSessionTaskAuthenticationChallengeBlock)(NSURLSessionTask * task, NSURLAuthenticationChallenge * challenge, void(^completionHandler)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * credential)); @protocol TRBHTTPSessionBackgroundDelegate <NSObject> - (void)HTTPSessionDidFinishEvents:(TRBHTTPSession *)HTTPSession; - (void)HTTPSession:(TRBHTTPSession *)HTTPSession task:(NSURLSessionTask *)task didCompleteWithData:(id)data error:(NSError *)error; @optional - (void)HTTPSession:(TRBHTTPSession *)HTTPSession downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location; @end @interface TRBHTTPSession : NSObject @property (nonatomic, strong) NSIndexSet * acceptedHTTPStatusCodes; @property (nonatomic, weak) id<TRBHTTPSessionBackgroundDelegate> backgroundSessionDelegate; - (instancetype)initWithConfiguration:(NSURLSessionConfiguration *)configuration; - (void)onSessionAuthenticationChallenge:(TRBHTTPSessionAuthenticationChallengeBlock)sessionAuthenticationChallengeBlock; - (void)onSessionTaskAuthenticationChallenge:(TRBHTTPSessionTaskAuthenticationChallengeBlock)sessionTaskAuthenticationChallengeBlock; - (void)startRequest:(NSURLRequest *)request parser:(TRBHTTPResponseParser *)parser completion:(void(^)(id data, NSURLResponse * response, NSError * error))completion; - (void)startRequest:(NSURLRequest *)request parameters:(NSDictionary *)parameters builder:(TRBHTTPRequestBuilder *)builder parser:(TRBHTTPResponseParser *)parser completion:(void(^)(id data, NSURLResponse * response, NSError * error))completion; - (void)GET:(NSString *)URL parameters:(NSDictionary *)parameters builder:(TRBHTTPRequestBuilder *)builder parser:(TRBHTTPResponseParser *)parser completion:(void(^)(id data, NSURLResponse * response, NSError * error))completion; - (void)GETJSON:(NSString *)URL parameters:(NSDictionary *)parameters completion:(void(^)(id data, NSURLResponse * response, NSError * error))completion; - (void)GETXML:(NSString *)URL parameters:(NSDictionary *)parameters completion:(void(^)(id data, NSURLResponse * response, NSError * error))completion; - (void)POST:(NSString *)URL parameters:(NSDictionary *)parameters builder:(TRBHTTPRequestBuilder *)builder parser:(TRBHTTPResponseParser *)parser completion:(void(^)(id data, NSURLResponse * response, NSError * error))completion; - (void)downloadRequest:(NSURLRequest *)request progress:(void (^)(uint64_t bytesWritten, uint64_t totalBytesWritten, uint64_t totalBytesExpectedToWrite))progress completion:(void(^)(NSURL * location, NSURLResponse * response, NSError * error))completion; - (void)resumeDownloadWithData:(NSData *)data progress:(void (^)(uint64_t bytesWritten, uint64_t totalBytesWritten, uint64_t totalBytesExpectedToWrite))progress completion:(void(^)(NSURL * location, NSURLResponse * response, NSError * error))completion; - (void)resetWithCompletion:(void(^)(void))completion; - (void)invalidateAndCancel; @end @interface TRBHTTPRequestBuilder : NSObject @property (nonatomic, assign) BOOL percentEncodeParameters; @property (nonatomic, assign) NSStringEncoding stringEncoding; - (NSURLRequest *)buildRequest:(NSURLRequest *)request parameters:(NSDictionary *)parameters error:(NSError **)error; @end @interface TRBHTTPJSONRequestBuilder : TRBHTTPRequestBuilder @end @interface TRBHTTPResponseParser : NSObject @property (nonatomic, readonly) NSMutableSet * acceptedMIMETypes; - (void)parse:(NSData *)data response:(NSURLResponse *)response completion:(void(^)(id, NSError *))completion; - (BOOL)shouldParseDataForResponse:(NSURLResponse *)response error:(NSError **)error; @end @interface TRBHTTPJSONResponseParser : TRBHTTPResponseParser @end @interface TRBHTTPXMLResponseParser : TRBHTTPResponseParser @end
Jenner4S/Turbo
Turbo/Classes/External/Categories/UIColor-HSVAdditions.h
<gh_stars>1-10 // // UIColor-HSVAdditions.h // // Created by <NAME> (br<EMAIL>) on 12/31/09. // // #import "UIColor-Expanded.h" #define MIN3(x,y,z) ((y) <= (z) ? \ ((x) <= (y) ? (x) : (y)) \ : \ ((x) <= (z) ? (x) : (z))) #define MAX3(x,y,z) ((y) >= (z) ? \ ((x) >= (y) ? (x) : (y)) \ : \ ((x) >= (z) ? (x) : (z))) struct rgb_color { CGFloat r, g, b; }; struct hsv_color { CGFloat hue; CGFloat sat; CGFloat val; }; @interface UIColor (UIColor_HSVAdditions) @property (nonatomic, readonly) CGFloat hue; // Only valid if canProvideRGBComponents is YES @property (nonatomic, readonly) CGFloat saturation; // Only valid if canProvideRGBComponents is YES @property (nonatomic, readonly) CGFloat brightness; // Only valid if canProvideRGBComponents is YES @property (nonatomic, readonly) CGFloat value; // (same as brightness, added for naming consistency) //workhorse method, does conversion: +(struct hsv_color)HSVfromRGB:(struct rgb_color)rgb; //individual value accessors: -(CGFloat)hue; -(CGFloat)saturation; -(CGFloat)brightness; -(CGFloat)value; @end
Jenner4S/Turbo
Turbo/Classes/External/Calendar/KalDataSource.h
<gh_stars>1-10 /* * Copyright (c) 2009 <NAME> * License: http://www.opensource.org/licenses/mit-license.html */ /* * KalDataSource protocol * ---------------------- * * The KalDataSource's protocol has 2 responsibilities: * 1) Vend UITableViewCells as part of the UITableViewDataSource protocol. * 2) Instruct the KalViewController which days should be marked with a dot. * * The protocol is a mix of asynchronous and synchronous methods. * The primary asynchronous method, presentingDatesFrom:to:delegate:, * allows implementations to retrieve data from the network or disk * without causing the UI to hang when the user slides between months. * * --- Asynchronous part of the protocol --- * * presentingDatesFrom:to:delegate: * * This message will be sent to your dataSource whenever the calendar * switches to a different month. Your code should respond by * loading application data for the specified range of dates and sending the * loadedDataSource: callback message as soon as the appplication data * is ready and available in memory. If the lookup of your application * data is expensive, you should perform the lookup using an asynchronous * API (like NSURLConnection for web service resources) or in a background * thread. * * If the application data for the new month is already in-memory, * you must still issue the callback. * * * --- Synchronous part of the protocol --- * * markedDatesFrom:to: * * This message will be sent to your dataSource immediately * after you issue the loadedDataSource: callback message * from the body of your presentingDatesFrom:to:delegate method. * You should respond to this message by returning an array of NSDates * for each day in the specified range which has associated application * data. * * If this message is received but the application data is not yet * ready, your code should immediately return an empty NSArray. * * loadItemsFromDate:toDate: * * This message will be sent to your dataSource every time * that the user taps a day on the calendar. You should respond * to this message by updating the list from which you vend * UITableViewCells. * * If this message is received but the application data is not yet * ready, your code should do nothing. * * removeAllItems * * This message will be sent before loadItemsFromDate:toDate * as well as any time that Kal wants to clear the table view * beneath the calendar (for example, when switching between months). * You should respond to this message by removing all objects * from the list from which you vend UITableViewCells. * */ @protocol KalDataSourceCallbacks; @protocol KalDataSource <NSObject, UITableViewDataSource> - (void)presentingDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate delegate:(id<KalDataSourceCallbacks>)delegate; - (NSArray *)markedDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate; - (void)loadItemsFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate; - (void)removeAllItems; @end @protocol KalDataSourceCallbacks <NSObject> - (void)loadedDataSource:(id<KalDataSource>)dataSource; @end #pragma mark - /* * SimpleKalDataSource * ------------------- * * A null implementation of the KalDataSource protocol. * */ @interface SimpleKalDataSource : NSObject <KalDataSource> { } + (SimpleKalDataSource*)dataSource; @end
Jenner4S/Turbo
Turbo/Classes/Library/TRBLibraryManager.h
<filename>Turbo/Classes/Library/TRBLibraryManager.h /* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ typedef NS_ENUM(NSUInteger, TRBLibraryFilterName) { TRBLibraryFilterNoFilter = 0, TRBLibraryFilterRecentlyAdded, TRBLibraryFilterByYear, TRBLibraryFilterByGenre, TRBLibraryFilterByActor, TRBLibraryFilterByDirector, TRBLibraryFilterByWriter, }; @interface TRBLibraryManager : NSObject @property (nonatomic, strong) NSString * host; @property (nonatomic, assign) NSInteger port; @property (nonatomic, readonly, getter = isAuthenticated) BOOL authenticated; + (instancetype)sharedManager; // Authentication - (void)startAuthenticationCompletion:(void(^)(NSError * error))completion; // Movies - (void)fetchMovieListWithOffest:(NSUInteger)offset limit:(NSUInteger)limit sortBy:(NSString *)sort order:(NSString *)order filters:(NSDictionary *)filters completion:(void(^)(NSDictionary * json, NSError * error))completion; - (void)searchMovietWithKeyword:(NSString *)keyword offest:(NSUInteger)offset limit:(NSUInteger)limit sortBy:(NSString *)sort order:(NSString *)order completion:(void(^)(NSDictionary * json, NSError * error))completion; - (void)fetchMovieDetailsForID:(NSString *)movieID completion:(void(^)(NSDictionary * json, NSError * error))completion; // TVShows - (void)fetchTVShowListWithOffest:(NSUInteger)offset limit:(NSUInteger)limit sortBy:(NSString *)sort order:(NSString *)order completion:(void(^)(NSDictionary * json, NSError * error))completion; - (void)fetchTVShowEpisodeListForID:(NSString *)tvShowID completion:(void(^)(NSDictionary * json, NSError * error))completion; // Posters - (void)fetchPosterForMovieID:(NSString *)movieID completion:(void(^)(UIImage * image, NSError * error))completion; - (void)fetchPosterForTVShowID:(NSString *)tvShowID completion:(void(^)(UIImage * image, NSError * error))completion; - (void)fetchPosterForTVShowEpisodeID:(NSString *)tvShowEpisodeID completion:(void(^)(UIImage * image, NSError * error))completion; // Metadata - (void)fetchMetadataForType:(NSString *)type category:(NSString *)category completion:(void(^)(NSDictionary * json, NSError * error))completion; @end
Jenner4S/Turbo
Turbo/Classes/Categories/NSString+TRBUnits.h
/* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @interface NSString (TRBUnits) + (NSString *)stringWithByteCount:(long long)size; + (NSString *)stringWithTransferRate:(long long)rate; + (NSString *)stringWithDate:(NSDate *)date andOutputStyle:(NSDateFormatterStyle)style; + (NSString *)stringWithDate:(NSDate *)date dateOutputStyle:(NSDateFormatterStyle)style1 andTimeOutputStyle:(NSDateFormatterStyle)style2; - (NSDate *)dateFromInputFormat:(NSString *)format; - (NSDate *)dateFromInputFormat:(NSString *)format withLocale:(NSLocale *)locale; - (NSDate *)dateFromInputFormat:(NSString *)format withLocale:(NSLocale *)locale andTimezone:(NSTimeZone *)timezone; - (NSString *)dateStringFromInputFormat:(NSString *)format andOutputStyle:(NSDateFormatterStyle)style; - (NSString *)dateStringFromInputFormat:(NSString *)format outputStyle:(NSDateFormatterStyle)style inLocale:(NSLocale *)inLocale andOutLocale:(NSLocale *)outLocale; - (NSString *)shortDateFromInputFormat:(NSString *)format; @end
Jenner4S/Turbo
Turbo/Classes/External/Calendar/KalDate.h
<filename>Turbo/Classes/External/Calendar/KalDate.h<gh_stars>1-10 /* * Copyright (c) 2009 <NAME> * License: http://www.opensource.org/licenses/mit-license.html */ @interface KalDate : NSObject { struct { NSUInteger month : 4; NSUInteger day : 5; NSUInteger year : 15; } a; } + (KalDate *)dateForDay:(NSUInteger)day month:(NSUInteger)month year:(NSUInteger)year; + (KalDate *)dateFromNSDate:(NSDate *)date; - (id)initForDay:(NSUInteger)day month:(NSUInteger)month year:(NSUInteger)year; - (NSUInteger)day; - (NSUInteger)month; - (NSUInteger)year; - (NSDate *)NSDate; - (NSComparisonResult)compare:(KalDate *)otherDate; - (BOOL)isToday; @end
Jenner4S/Turbo
Turbo/Classes/Torrents/Shared/TRBTorrentClient.h
<reponame>Jenner4S/Turbo<gh_stars>1-10 /* The MIT License (MIT) Copyright (c) 2014 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ @class TRBTorrent; @interface TRBTorrentClient : NSObject @property (nonatomic, strong, readonly) NSURL * URL; - (instancetype)initWithURL:(NSURL *)URL; - (void)validateRemoteWithCompletion:(void(^)(BOOL valid, NSError * error))completion; - (void)fetchTorrentsWithCompletion:(void(^)(NSArray * torrents, NSError * error))completion; - (void)addTorrentAtURL:(NSString *)URL completion:(void(^)(BOOL valid, NSError * error))completion; - (void)addTorrentWithBase64String:(NSString *)base64Data completion:(void(^)(BOOL valid, NSError * error))completion; - (void)removeTorrent:(TRBTorrent *)torrent completion:(void(^)(BOOL valid, NSError * error))completion; - (void)reset; @end @interface TRBTransmissionClient : TRBTorrentClient @end
Jenner4S/Turbo
Turbo/Classes/External/Categories/NSString+Levenshtein.h
// // NSString+Levenshtein.h // // Created by <NAME> on Sat Aug 09 2003. // <EMAIL> @interface NSString (Levenshtein) // calculate the smallest distance between all words in stringA and stringB - (float) compareWithString: (NSString *) stringB; // calculate the distance between two string treating them each as a // single word - (float) compareWithWord: (NSString *) stringB; // return the minimum of a, b and c - (NSInteger) smallestOf: (NSInteger) a andOf: (NSInteger) b andOf: (NSInteger) c; @end
393385724/DDMISDKDemo
DDMISDK/DDMIDownLoader.h
<gh_stars>1-10 // // DDMIDownLoader.h // HMLoginDemo // // Created by lilingang on 15/8/5. // Copyright (c) 2015年 lilingang. All rights reserved. // #import <Foundation/Foundation.h> typedef void(^DDMIDownLoaderEventHandler) (NSData *data, NSError *error); @interface DDMIDownLoader : NSObject - (void)loadLoginCodeImageWithURLString:(NSString *)urlString account:(NSString *)account completeHandle:(DDMIDownLoaderEventHandler)completeHandle; @end
393385724/DDMISDKDemo
DDMISDK/DDMIBaseViewController.h
// // DDMIBaseViewController.h // HMLoginDemo // // Created by lilingang on 15/8/5. // Copyright (c) 2015年 lilingang. All rights reserved. // #import <UIKit/UIKit.h> #import "DDMIDefines.h" #import "DDMITypeDefines.h" @protocol DDMICancelDelegate <NSObject> - (void)viewControllerCanceled:(UIViewController *)viewController; @end @interface DDMIBaseViewController : UIViewController @property (nonatomic, weak) id<DDMICancelDelegate> cancelDelegate; @end
393385724/DDMISDKDemo
DDMISDK/DDMIRequestHandle.h
// // DDMIRequestHandle.h // HMLoginDemo // // Created by lilingang on 15/8/3. // Copyright (c) 2015年 lilingang. All rights reserved. // #import <Foundation/Foundation.h> typedef NS_ENUM(NSUInteger, DDMIErrorType) { DDMIErrorUnkwon, //**未知错误*/ DDMIErrorNetworkNotConnected, //**网络未连接*/ DDMIErrorTimeOut, //**网络超时*/ DDMIErrorNotReachServer, //**无法连接服务器*/ DDMIErrorOperationFrequent, //**操作频繁*/ DDMIErrorNeedDynamicToken, //**需要动态令牌*/ DDMIErrorAccountOrPassword, //**账号或密码错误*/ DDMIErrorVerificationCode, //**验证码错误*/ }; typedef void (^DDMIRequestBlock) (NSDictionary *responseDict, NSError *connectionError); @class DDMIRequestHandle; @protocol DDMIRequestHandleDelegate <NSObject> - (void)requestHandle:(DDMIRequestHandle *)requestHandle successedNeedDynamicToken:(BOOL)needDynamicToken; - (void)requestHandle:(DDMIRequestHandle *)requestHandle failedWithType:(DDMIErrorType)errorType errorMessage:(NSString *)errorMessage error:(NSError *)error; @end @interface DDMIRequestHandle : NSObject @property (nonatomic, weak) id<DDMIRequestHandleDelegate> delegate; @property (nonatomic, copy, readonly) NSString *account; - (void)loginWithAccount:(NSString *)account password:(<PASSWORD> verifyCode:(NSString *)verifyCode; - (void)checkOTPCode:(NSString *)OTPCode trustDevice:(BOOL)isTrust; - (BOOL)getProfileWithAccessToken:(NSString *)accessToken clientId:(NSString *)clientId completeHandler:(DDMIRequestBlock)completeHandler; @end
393385724/DDMISDKDemo
DDMISDK/DDMIUserInfoItem.h
<reponame>393385724/DDMISDKDemo // // DDMIUserInfoItem.h // midong // // Created by lilingang on 16/2/1. // Copyright © 2016年 HM IOS Team. All rights reserved. // #import <Foundation/Foundation.h> @interface DDMIUserInfoItem : NSObject @property (nonatomic, copy, readonly) NSString *userId; @property (nonatomic, copy, readonly) NSString *miliaoNick; @property (nonatomic, copy, readonly) NSString *miliaoIcon_orig; @property (nonatomic, copy, readonly) NSString *miliaoIcon; @property (nonatomic, copy, readonly) NSString *miliaoIcon_320; @property (nonatomic, copy, readonly) NSString *miliaoIcon_120; @property (nonatomic, copy, readonly) NSString *miliaoIcon_75; @property (nonatomic, copy, readonly) NSString *miliaoIcon_90; - (instancetype)initWithDict:(NSDictionary *)dict; @end
393385724/DDMISDKDemo
DDMISDK/DDMIVerifyLoginViewController.h
<reponame>393385724/DDMISDKDemo // // DDMIVerifyLoginViewController.h // HMLoginDemo // // Created by lilingang on 15/8/5. // Copyright (c) 2015年 lilingang. All rights reserved. // #import "DDMIBaseViewController.h" @class DDMIVerifyLoginViewController; @class DDMIRequestHandle; @protocol DDMIVerifyLoginViewControllerDelegate <NSObject> - (void)viewControllerDidVerifySucess:(DDMIVerifyLoginViewController *)viewController; - (void)viewControllerNeedPop:(DDMIVerifyLoginViewController *)viewController; @end @interface DDMIVerifyLoginViewController : DDMIBaseViewController @property (nonatomic, weak) id<DDMIVerifyLoginViewControllerDelegate> delegate; - (instancetype)initWithRequestHandle:(DDMIRequestHandle *)requestHandle; @end
393385724/DDMISDKDemo
DDMISDK/XMPassport.framework/Headers/MPEnDecryptCoder.h
// // MPEnDecryptCoder.h // MiPassportFoundation // // Created by <NAME> on 13-12-3. // Copyright (c) 2013年 Xiaomi. All rights reserved. // #import <Foundation/Foundation.h> @protocol MPEnDecryptCoder <NSObject> - (NSString *)encryptString:(NSString *)plainString; - (NSString *)decryptString:(NSString *)cipherString; @end
393385724/DDMISDKDemo
DDMISDK/DDMICircleIndicator.h
<gh_stars>1-10 // // DDMICircleIndicator.h // HMLoginDemo // // Created by lilingang on 15/8/5. // Copyright (c) 2015年 lilingang. All rights reserved. // #import <UIKit/UIKit.h> @interface DDMICircleIndicator : UIView - (instancetype)initWithFrame:(CGRect)frame; - (instancetype)initWithFrame:(CGRect)frame imageName:(NSString *)imageName; - (void)startAnimation; - (void)stopAnimation; @end
393385724/DDMISDKDemo
DDMISDK/DDMILoginViewController.h
// // DDMILoginViewController.h // HMLoginDemo // // Created by lilingang on 15/8/4. // Copyright (c) 2015年 lilingang. All rights reserved. // #import "DDMIBaseViewController.h" #import "DDMIRequestHandle.h" typedef NS_ENUM(NSUInteger, DDMILoginType) { DDMILoginTypeDefault, DDMILoginTypeImageVerification, }; @class DDMILoginViewController; @protocol DDMILoginViewControllerDelegate <NSObject> - (void)loginViewController:(DDMILoginViewController *)viewController successNeedDaynamicCode:(BOOL)needDaynamicCode; @end @interface DDMILoginViewController : DDMIBaseViewController<DDMIRequestHandleDelegate> @property (nonatomic, weak) id<DDMILoginViewControllerDelegate> delegate; - (instancetype)initWithRequestHandle:(DDMIRequestHandle *)requestHandle; @end
393385724/DDMISDKDemo
DDMISDK/UIButton+DDHitTestEdgeInsets.h
<reponame>393385724/DDMISDKDemo // // UIButton+DDHitTestEdgeInsets.h // HMLoginDemo // // Created by lilingang on 15/8/6. // Copyright (c) 2015年 lilingang. All rights reserved. // #import <UIKit/UIKit.h> @interface UIButton (DDHitTestEdgeInsets) @property(nonatomic, assign) UIEdgeInsets hitTestEdgeInsets; @end
393385724/DDMISDKDemo
DDMISDK/XMPassport.framework/Headers/XMPassportRequest.h
<reponame>393385724/DDMISDKDemo // // XMPassportRequest.h // MiPassportFoundation // // Created by <NAME> on 13-10-29. // Copyright (c) 2013年 Xiaomi. All rights reserved. // #import <Foundation/Foundation.h> #import "MPEnDecryptCoder.h" @protocol XMPassportRequestDelegate; @interface XMPassportRequest : NSObject{ NSURLConnection *_connection; NSMutableData *_responseData; } @property(nonatomic,assign) id<XMPassportRequestDelegate> delegate; /** * The URL which will be contacted to execute the request. */ @property(nonatomic, strong) NSString *url; /** * The API method which will be called. */ @property(nonatomic, strong) NSString *httpMethod; /** * The cookies which will be setted in the request. */ @property(nonatomic, strong) NSMutableArray *httpCookies; /** * The dictionary of parameters to pass to the method. * * These values in the dictionary will be converted to strings using the * standard Objective-C object-to-string conversion facilities. */ @property(nonatomic,strong) NSMutableDictionary* params; @property(nonatomic, strong) id<MPEnDecryptCoder> cryptCoder; - (id)initWithWithParams:(NSMutableDictionary *) params httpMethod:(NSString *) httpMethod cookies:(NSMutableArray *)cookies delegate:(id<XMPassportRequestDelegate>) delegate requestURL:(NSString *) url; // crypt and sign, call this method if needed - (void)cryptWithCoder:(id<MPEnDecryptCoder>)coder andSignWithSecurity:(NSString *)security; - (void)connect; + (XMPassportRequest *)requestWithParams:(NSMutableDictionary *) params httpMethod:(NSString *) httpMethod cookies:(NSMutableArray *)cookies delegate:(id<XMPassportRequestDelegate>) delegate requestURL:(NSString *) url; + (NSString *)getParamValueFromUrl:(NSString*)url paramName:(NSString *)paramName; + (NSString *)urlEncode:(NSString*)str; + (NSString*)urlDecode:(NSString*)str; + (NSString *)generateSignatureWithMethod:(NSString *)method requestUrl:(NSString *)requestUrl params:(NSDictionary *)params security:(NSString *)security; @end //////////////////////////////////////////////////////////////////////////////// /* *Your application should implement this delegate */ @protocol XMPassportRequestDelegate <NSObject> @optional /** * Called just before the request is sent to the server. */ - (void)requestLoading:(XMPassportRequest *)request; /** * Called when the server responds and begins to send back data. */ - (void)request:(XMPassportRequest *)request didReceiveResponse:(NSURLResponse *)response; /** * Called when an error prevents the request from completing successfully. */ - (void)request:(XMPassportRequest *)request didFailWithError:(NSError *)error; /** * Called when a request returns and its response has been parsed into * an object. * * The resulting object may be a dictionary, an array, a string, or a number, * depending on thee format of the API response. */ - (void)request:(XMPassportRequest *)request didLoad:(id)result; /** * Called when a request returns a response. * * The result object is the raw response from the server of type NSData */ - (void)request:(XMPassportRequest *)request didLoadRawResponse:(NSData *)data; @end
393385724/DDMISDKDemo
DDMISDK/UIView+DDAction.h
// // UIView+DDAction.h // HMLoginDemo // // Created by lilingang on 15/8/5. // Copyright (c) 2015年 lilingang. All rights reserved. // #import <UIKit/UIKit.h> @interface UIView (DDAction) - (void)ddAddTarget:(id)target tapAction:(SEL)action; @end
393385724/DDMISDKDemo
DDMISDK/UIView+DDFrame.h
// // UIView+DDFrame.h // HMLoginDemo // // Created by lilingang on 15/8/4. // Copyright (c) 2015年 lilingang. All rights reserved. // #import <UIKit/UIKit.h> @interface UIView (DDFrame) @property (nonatomic, readwrite) CGFloat ddTop; @property (nonatomic, readwrite) CGFloat ddBottom; @property (nonatomic, readwrite) CGFloat ddLeft; @property (nonatomic, readwrite) CGFloat ddRight; @property (nonatomic, readwrite) CGFloat ddMiddleX; @property (nonatomic, readwrite) CGFloat ddMiddleY; @property (nonatomic, readwrite) CGFloat ddWidth; @property (nonatomic, readwrite) CGFloat ddHeight; @property (nonatomic, readwrite) CGPoint ddLeftTopPoint; @property (nonatomic, readonly) CGSize ddSize; @property (nonatomic, readonly) CGPoint ddBoundsCenter; @end
393385724/DDMISDKDemo
DDMISDK/XMPassport.framework/Headers/XMPassportConstants.h
// // XMPassportConstans.h // MiPassportFoundation // // Created by <NAME> on 13-10-23. // Copyright (c) 2013年 Xiaomi. All rights reserved. // #define kXMPassportErrorDomain @"XMPassportErrorDomain" #define ERROR_CODE @"code" #define ERROR_REASON @"reason" #define ERROR_DESCRIPTION @"description" #define XM_PAS_PARAM_KEY_USER @"user" #define XM_PAS_PARAM_KEY_PWD @"pwd" #define XM_PAS_PARAM_KEY_HASH @"hash" #define XM_PAS_PARAM_KEY_SID @"sid" #define XM_PAS_PARAM_KEY_CALLBACK @"callback" #define XM_PAS_PARAM_KEY_CAPT_CODE @"captCode" #define XM_PAS_PARAM_KEY_CAPT_URL @"captchaUrl" #define XM_PAS_PARAM_KEY_CAPT_IMAGE @"captImage" #define XM_PAS_PARAM_KEY_QUERY_STR @"qs" #define XM_PAS_PARAM_KEY_SIGN @"_sign" #define XM_PAS_PARAM_KEY_RETRUN_JSON @"_json" #define XM_PAS_COOKIE_KEY_PASSTOKEN @"passToken" #define XM_PAS_COOKIE_KEY_USERID @"userId" #define XM_PAS_COOKIE_KEY_DEVICEID @"deviceId" #define XM_PAS_COOKIE_KEY_CAPT_ICK @"ick" // error code #define ACCOUNT_DOMAIN_ONLINE @"https://account.xiaomi.com" #define ACCOUNT_DOMAIN_STAGING @"http://account.preview.n.xiaomi.net" #define XMPassportErrorCode_Success 0 //"成功" #define XMPassportErrorCode_ParamNotBlank -100 //"参数不能为空" #define XMPassportErrorCode_UnknownError -101 //未知错误 #define XMPassportErrorCode_NoServiceToken -102 //没有返回serviceToken #define XMPassportErrorCode_SessionExpired -103 //session 过期 #define XMPassportErrorCode_NoSignature -104 //signature生成失败 #define XMPassportErrorCode_NoConnection -1009 //无连接 #define XMPassportErrorCode_TimeOut -1002 //request time out #define XMPassportErrorCode_HostNotFound -1003 //无法连接服务器 #define XMPassportErrorCode_WrongAuthority 401 //权限错误, 请重新登录 #define XMPassportErrorCode_UpdateVersionRequired 402 //版本太低,强制升级 #define XMPassportErrorCode_AccountIrregularity 403 //帐号违规 #define XMPassportErrorCode_NotFound 404 //“标准的notfound错误” #define XMPassportErrorCode_TemporaryBlocked 405 //用户暂时被屏蔽 #define XMPassportErrorCode_PassportVerifyFailed 70016 //登录验证失败 #define XMPassportErrorCode_PassportNeed2Step 81003 //需要两步登陆 #define XMPassportErrorCode_PassportPwdTooManyRetry 87001 //密码尝试太多次,用户输入验证码 // 系统级错误代码 #define XMPassportErrorCode_RemoteServiceError 10003 //"远程服务错误"
393385724/DDMISDKDemo
DDMISDK/XMPassport.framework/Headers/XMPassport.h
// // XMPassport.h // MiPassportFoundation // // Created by <NAME> on 13-10-23. // Copyright (c) 2013年 Xiaomi. All rights reserved. // #import <Foundation/Foundation.h> #import "XMPassportRequest.h" @protocol MPSessionDelegate; @interface XMPassport : NSObject <XMPassportRequestDelegate> @property (nonatomic, strong) NSString* userId; @property (nonatomic, strong) NSString* sid; @property (nonatomic, strong) NSString* callbackUrl; @property (nonatomic, strong) NSString* deviceId; @property (nonatomic, strong) NSString* passToken; @property (nonatomic, strong) NSString* serviceToken; @property (nonatomic, strong) NSString* sSecurity; @property (nonatomic, assign) long long nonce; @property (nonatomic, weak) id<MPSessionDelegate> sessionDelegate; @property (nonatomic, assign) BOOL forTest; //set TRUE if application wanna connect to staging server /** * Initialize a passport to login or do other requests */ - (id)initWithUserId:(NSString *)userId sid:(NSString *)sid andDelegate:(id<MPSessionDelegate>)delegate; /** * load from and save to local persistence * return all settings are loaded or saved, and none is nil */ - (BOOL)loadFromLocalSettings; - (BOOL)saveToLocalSettings; /** * Call this method if your application tend to use webview to login rather than constructing your own native view */ - (void)showLoginWebView; - (void)showLoginWebViewWithURL:(NSString *)url authParams:(NSMutableDictionary *)authParams; /** * Check if passport is logged in */ - (BOOL)isSessionValid; /** * Login passport with password */ - (void)loginWithPassword:(NSString *)password encryptedOrNot:(BOOL) bEncrypted; /** * Your application call this method to relogin passport, usually for refreshing passtoken and service token. * It is necessary to ensure your passport session is valid */ - (void)reLogin; /** * Call this method to log out passport */ - (void)logOut; /** * Login passport with password and verify code */ - (void)loginWithPassword:(NSString *)password encryptedOrNot:(BOOL) bEncrypted andVerifyCode:(NSString *)verifyCode; /** * If user need two step login, this method is called for check one-time-password in the second step */ - (void)checkOTPCode:(NSString *)OTPCode trustOrNot:(BOOL) bTrust; /** * create a request for xiaomi api, with signature or encryption if needed */ - (XMPassportRequest *)requestWithURL:(NSString *)url params:(NSMutableDictionary *)params httpMethod:(NSString *)httpMethod delegate:(id<XMPassportRequestDelegate>)_delegate needSignature:(BOOL)bNeedSignature coder:(id<MPEnDecryptCoder>)coder; - (BOOL)handleOpenURL:(NSURL *)url; /** * generate signature for request with passport info */ - (NSString *)generateSignatureWithMethod:(NSString *)method requestUrl:(NSString *)requestUrl params:(NSDictionary *)params; @end #pragma mark - MPSesssionDelegate /** * Your application should implement this delegate to receive session callbacks. */ @protocol MPSessionDelegate <NSObject> @optional /** * Called when the user successfully logged in. */ - (void)passportDidLogin:(XMPassport *)passport; /** * Called when the user failed to log in. */ - (void)passport:(XMPassport *)passport failedWithError:(NSError *)error; /** * Called when the user logged out. * */ //- (void)passportDidLogout:(XMPassport *)passport; /** * Called when passport session expired. */ - (void)passport:(XMPassport *)passport passSessionInvalidOrExpired:(NSError *)error; @end