id
int64
4
16.3M
file_name
stringlengths
3
68
file_path
stringlengths
14
181
content
stringlengths
39
9.06M
size
int64
39
9.06M
language
stringclasses
1 value
extension
stringclasses
2 values
total_lines
int64
1
711k
avg_line_length
float64
3.18
138
max_line_length
int64
10
140
alphanum_fraction
float64
0.02
0.93
repo_name
stringlengths
7
69
repo_stars
int64
2
61.6k
repo_forks
int64
12
7.81k
repo_open_issues
int64
0
1.13k
repo_license
stringclasses
10 values
repo_extraction_date
stringclasses
657 values
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
1 class
exact_duplicates_redpajama
bool
1 class
exact_duplicates_githubcode
bool
2 classes
near_duplicates_stackv2
bool
1 class
near_duplicates_stackv1
bool
1 class
near_duplicates_redpajama
bool
1 class
near_duplicates_githubcode
bool
2 classes
14,398,380
main.c
skyformat99_ametal/board/am116_core/project_example/user_code/main.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief ZLG116 例程工程 * * - 操作步骤: * 1. 取消屏蔽需要使用的例程。 * * \note * 同一时刻只能使用一个例程。 * * \internal * \par Modification history * - 1.00 17-07-07 nwt, first implementation * \endinternal */ #include "ametal.h" #include "am_led.h" #include "am_delay.h" #include "am_vdebug.h" #include "am_board.h" #include "demo_am116_core_entries.h" /** * \brief AMetal 应用程序入口 */ int am_main (void) { AM_DBG_INFO("Start up successful!\r\n"); /* * 以下为所有demo的入口函数,需要运行哪个 demo, 就需求对应函数调用行的注释 * * 默认运行的是LED闪烁 demo。 * * 注意:同一时刻只能运行一个 demo,即只能使某一行处于取消注释状态。 */ demo_am116_core_std_led_entry(); // demo_am116_core_std_delay_entry(); // demo_am116_core_hw_adc_int_entry(); // demo_am116_core_std_adc_entry(); // demo_am116_core_std_adc_ntc_entry(); // demo_am116_core_std_buzzer_entry(); // demo_am116_core_hw_clk_entry(); // demo_am116_core_drv_dma_m2m_entry(); // demo_am116_core_drv_flash_entry(); // demo_am116_core_hw_gpio_entry(); // demo_am116_core_hw_gpio_trigger_entry(); // demo_am116_core_std_gpio_entry(); // demo_am116_core_std_gpio_trigger_entry(); // demo_am116_core_hw_i2c_master_poll_entry(); // demo_am116_core_hw_i2c_slave_poll_entry(); // demo_am116_core_std_i2c_lm75_entry(); // demo_am116_core_std_i2c_master_async_entry(); // demo_am116_core_std_i2c_master_sync_entry(); // demo_am116_core_std_i2c_slave_entry(); // demo_am116_core_std_i2c_slave_subaddr_entry(); // demo_am116_core_std_key_entry(); // demo_am116_core_std_softimer_entry(); // demo_am116_core_hw_spi_master_entry(); // demo_am116_core_std_spi_flash_dma_entry(); // demo_am116_core_std_spi_flash_int_entry(); // demo_am116_core_std_spi_master_dma_entry(); // demo_am116_core_std_spi_master_int_entry(); // demo_am116_core_std_spi_slave_dma_entry(); // demo_am116_core_hw_tim_cap_entry(); // demo_am116_core_hw_tim_cmp_toggle_entry(); // demo_am116_core_hw_tim_pwm_entry(); // demo_am116_core_hw_tim_pwm_dead_entry(); // demo_am116_core_hw_tim_timing_entry(); // demo_am116_core_std_tim14_cap_entry(); // demo_am116_core_std_tim14_pwm_entry(); // demo_am116_core_std_tim14_timing_entry(); // demo_am116_core_std_tim16_cap_entry(); // demo_am116_core_std_tim16_pwm_entry(); // demo_am116_core_std_tim16_timing_entry(); // demo_am116_core_std_tim17_cap_entry(); // demo_am116_core_std_tim17_pwm_entry(); // demo_am116_core_std_tim17_timing_entry(); // demo_am116_core_std_tim1_cap_entry(); // demo_am116_core_std_tim1_pwm_entry(); // demo_am116_core_std_tim1_timing_entry(); // demo_am116_core_std_tim2_cap_entry(); // demo_am116_core_std_tim2_pwm_entry(); // demo_am116_core_std_tim2_timing_entry(); // demo_am116_core_std_tim3_cap_entry(); // demo_am116_core_std_tim3_pwm_entry(); // demo_am116_core_std_tim3_timing_entry(); // demo_am116_core_hw_uart_int_entry(); // demo_am116_core_hw_uart_polling_entry(); // demo_am116_core_hw_uart_rx_dma_entry(); // demo_am116_core_hw_uart_tx_dma_entry(); // demo_am116_core_std_uart_polling_entry(); // demo_am116_core_std_uart_ringbuf_entry(); // demo_am116_core_drv_sleepmode_timer_wake_up_entry(); // demo_am116_core_drv_sleepmode_wake_up_entry(); // demo_am116_core_drv_standbymode_wake_up_entry(); // demo_am116_core_drv_stopmode_wake_up_entry(); // demo_am116_core_hw_iwdg_entry(); // demo_am116_core_hw_wwdg_entry(); // demo_am116_core_std_iwdg_entry(); // demo_am116_core_std_wwdg_entry(); // demo_am116_core_microport_ds1302_entry(); // demo_am116_core_microport_eeprom_entry(); // demo_am116_core_microport_eeprom_nvram_entry(); // demo_am116_core_microport_flash_entry(); // demo_am116_core_microport_flash_ftl_entry(); // demo_am116_core_microport_flash_mtd_entry(); // demo_am116_core_microport_rs485_entry(); // demo_am116_core_microport_rtc_entry(); // demo_am116_core_microport_rx8025t_entry(); // demo_am116_core_microport_usb_entry(); // demo_am116_core_miniport_digitron_entry(); // demo_am116_core_miniport_hc595_digitron_entry(); // demo_am116_core_miniport_hc595_digitron_key_entry(); // demo_am116_core_miniport_hc595_digitron_temp_entry(); // demo_am116_core_miniport_hc595_led_entry(); // demo_am116_core_miniport_key_entry(); // demo_am116_core_miniport_key_digitron_entry(); // demo_am116_core_miniport_led_entry(); // demo_am116_core_miniport_zlg72128_entry(); while (1) { } } /* end of file */
5,263
C
.c
133
36.157895
81
0.615815
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,445
main.c
skyformat99_ametal/board/am116_core/project_template/user_code/main.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief ZLG116 模板工程 * * - 实验现象: * 模板例程:LED0以1秒的频率闪烁; demo例程入口:详见demo入口函数文件介绍 * * \internal * \par Modification history * - 1.00 17-07-07 nwt, first implementation. * \endinternal */ /** * \brief AMetal 应用程序入口 */ #include "ametal.h" #include "am_board.h" #include "am_vdebug.h" #include "am_delay.h" #include "am_led.h" int am_main (void) { AM_DBG_INFO("Start up successful!\r\n"); while (1) { am_led_toggle(LED0); am_mdelay(1000); } } /* end of file */
1,063
C
.c
40
22.2
81
0.45567
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,447
am_bsp_armlib.c
skyformat99_ametal/board/bsp_common/source/am_bsp_armlib.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief ARM LIB * * \internal * \par Modification History * - 1.00 17-08-17 pea, first implementation. * \endinternal */ #ifndef __MICROLIB #include "ametal.h" #include "am_bsp_armlib.h" #include "am_armlib_adapter.h" /** * \brief 输出一个字符 * * \param[in] p_arg UART标准服务操作句柄 * \param[in] ch 需要输出的字符 * * \return 被输出的字符 */ static int __dbg_fputc (void *p_arg, const char ch) { while (-AM_EAGAIN == am_uart_poll_putchar(p_arg, ch)) { ; } return ch; } /** * \brief 输入一个字符 * * \param[in] p_arg UART标准服务操作句柄 * * \return 输入的字符。否则返回EOF */ static int __dbg_fgetc (void *p_arg) { char ch; while (-AM_EAGAIN == am_uart_poll_getchar(p_arg, &ch)) { ; } return ch; } /** * \brief 初始化ARM LIB适配器结构 */ static am_armlib_adapter_ops_t g_armlib_adapter_ops = { __dbg_fputc, __dbg_fgetc }; /** * \brief ARM LIB初始化 * * \param[in] uart_handle UART服务 * * \return AM_OK */ int am_bsp_armlib_init (am_uart_handle_t uart_handle) { return am_armlib_adapter_init(&g_armlib_adapter_ops, uart_handle); } #endif /* __MICROLIB */ /* end of file */
1,735
C
.c
74
19.108108
81
0.509218
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,448
am_bsp_system_heap.c
skyformat99_ametal/board/bsp_common/source/am_bsp_system_heap.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief memory management * * \internal * \par modification history: * - 1.00 14-06-13 zen, first implementation * \endinternal */ #include "ametal.h" #include "am_mem.h" #include "am_memheap.h" #include "am_board.h" #include <string.h> /******************************************************************************* defines *******************************************************************************/ /** \brief SRAM 信息,使用 ARMCC 时需要提供 SRAM 结束地址 */ #ifdef __CC_ARM #define SRAM_SIZE 8 #define SRAM_START 0x20000000 #define SRAM_END (SRAM_START + SRAM_SIZE * 1024) #endif /* __CC_ARM */ /******************************************************************************* locals *******************************************************************************/ static struct am_memheap __g_system_heap; /* system heap object */ /******************************************************************************* implementation *******************************************************************************/ /******************************************************************************/ void am_bsp_system_heap_init (void) { #ifdef __GNUC__ extern char __heap_start__; /* Defined by the linker */ extern char __heap_end__; /* Defined by the linker */ static char *heap_start = &__heap_start__; static char *heap_end = &__heap_end__; #elif defined(__CC_ARM) extern int Image$$RW_IRAM1$$ZI$$Limit; static int *heap_start = (int *)&Image$$RW_IRAM1$$ZI$$Limit; static int *heap_end = (int *)SRAM_END; #endif /* initialize a default heap in the system */ am_memheap_init(&__g_system_heap, "system_heap", (void *)heap_start, (uint32_t)heap_end - (uint32_t)heap_start); } /******************************************************************************/ void *am_mem_align(size_t size, size_t align) { void *align_ptr; void *ptr; size_t align_size; /* align the alignment size to 4 byte */ align = AM_ROUND_UP(align, sizeof(void *)); /* get total aligned size */ align_size = AM_ROUND_UP(size, sizeof(void *)) + align + sizeof(void *); /* allocate memory block from heap */ ptr = am_memheap_alloc(&__g_system_heap, align_size); if (ptr != NULL) { /* round up ptr to align */ align_ptr = (void *)AM_ROUND_UP((uint32_t)ptr + sizeof(void *), align); /* set the pointer before alignment pointer to the real pointer */ *((uint32_t *)((uint32_t)align_ptr - sizeof(void *))) = (uint32_t)ptr; ptr = align_ptr; } return ptr; } /******************************************************************************/ void *am_mem_alloc(size_t size) { /* allocate in the system heap */ return am_mem_align(size, 4); } /******************************************************************************/ void *am_mem_calloc(size_t nelem, size_t size) { void *ptr; size_t total_size; total_size = nelem * size; ptr = am_mem_alloc(total_size); if (ptr != NULL) { memset(ptr, 0, total_size); } return ptr; } /******************************************************************************/ void am_mem_free(void *ptr) { void *real_ptr = NULL; if (ptr != NULL) { real_ptr = (void *)*(uint32_t *)((uint32_t)ptr - sizeof(void *)); } am_memheap_free(real_ptr); } /******************************************************************************/ size_t am_mem_size(void *ptr) { void *real_ptr = NULL; if (ptr != NULL) { real_ptr = (void *)*(uint32_t *)((uint32_t)ptr - sizeof(void *)); } return am_memheap_memsize( &__g_system_heap, real_ptr); } /******************************************************************************/ void *am_mem_realloc(void *ptr, size_t newsize) { void *real_ptr = NULL; void *new_ptr = NULL; if (ptr != NULL) { /* get real pointer */ real_ptr = (void *)*(uint32_t *)((uint32_t)ptr - sizeof(void *)); } else { /* equal malloc when ptr==NULL */ return am_mem_alloc(newsize); } /* allocate newsize plus one more pointer, used for save real pointer */ real_ptr = am_memheap_realloc(&__g_system_heap, real_ptr, newsize + sizeof(void *)); if (real_ptr != NULL) { *(uint32_t *)real_ptr = (uint32_t)real_ptr; new_ptr = (void *)((size_t)real_ptr + sizeof(void *)); } else { new_ptr = NULL; } return new_ptr; } /* end of file */
5,330
C
.c
142
31.71831
81
0.420846
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,449
am_bsp_microlib.c
skyformat99_ametal/board/bsp_common/source/am_bsp_microlib.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief Micro LIB * * \internal * \par Modification History * - 1.00 17-08-17 pea, first implementation. * \endinternal */ #ifdef __MICROLIB #include "ametal.h" #include "am_bsp_microlib.h" #include "am_microlib_adapter.h" /** * \brief 输出一个字符 * * \param[in] p_arg UART标准服务操作句柄 * \param[in] ch 需要输出的字符 * * \return 被输出的字符 */ static int __dbg_fputc (void *p_arg, const char ch) { while (-AM_EAGAIN == am_uart_poll_putchar(p_arg, ch)) { ; } return ch; } /** * \brief 输入一个字符 * * \param[in] p_arg UART标准服务操作句柄 * * \return 输入的字符。否则返回EOF */ static int __dbg_fgetc (void *p_arg) { char ch; while (-AM_EAGAIN == am_uart_poll_getchar(p_arg, &ch)) { ; } return ch; } /** * \brief 初始化Micro LIB适配器结构 */ static am_microlib_adapter_ops_t g_microlib_adapter_ops = { __dbg_fputc, __dbg_fgetc }; /** * \brief Micro LIB初始化 * * \param[in] uart_handle UART服务 * * \return AM_OK */ int am_bsp_microlib_init (am_uart_handle_t uart_handle) { return am_microlib_adapter_init(&g_microlib_adapter_ops, uart_handle); } #endif /* __MICROLIB */ /* end of file */
1,754
C
.c
74
19.364865
81
0.515075
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,450
am_bsp_delay_timer.c
skyformat99_ametal/board/bsp_common/source/am_bsp_delay_timer.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief 基于通用定时器实现的延时函数 * * \internal * \par Modification history * - 1.00 17-11-12 tee, first implementation. * \endinternal */ #include "ametal.h" #include "am_delay.h" #include "am_vdebug.h" #include "am_int.h" #include "am_timer.h" #include "am_bsp_delay_timer.h" /******************************************************************************* Local macro define *******************************************************************************/ /* 低于400us时,使用while(i--)的形式进行延时 */ #define __DELAY_DEC_TIME_US 500 /******************************************************************************* Local struct type define *******************************************************************************/ /** * \brief 延时定时器相关信息定义 */ static struct __delay_timer { am_timer_handle_t handle; /**< \brief 延时定时器操作句柄 */ uint8_t chan; /**< \brief 延时定时器通道 */ uint32_t freq; /**< \brief 延时定时器频率 */ uint32_t max_ticks; /**< \brief 延时定时器最大计数值 */ uint32_t cali_ticks; /**< \brief 延时定时器被调用的次数 */ uint32_t count_get_ticks; /**< \brief count get 所消耗的 tick */ uint32_t dec_factor; /**< \brief 延时因子 */ uint32_t dec_cali_factor1; /**< \brief 递减法延时修正值1 */ uint32_t dec_cali_factor2; /**< \brief 递减法延时修正值2 */ uint32_t dec_cali_us; /**< \brief 递减法延时修正值 */ } __g_delay_timer = {NULL, 0, 0, 0, 0, 0, 0, 0}; /******************************************************************************* Local Functions *******************************************************************************/ /* 获取定时器当前计数值 */ static uint32_t __timer_count_get (void) { uint32_t ticks; am_timer_count_get(__g_delay_timer.handle, __g_delay_timer.chan, &ticks); return ticks; } /******************************************************************************/ /* 计算一段程序段所消耗的 ticks */ static uint32_t __time_ticks_cal (uint32_t start_ticks, uint32_t end_ticks) { uint32_t ticks; if (end_ticks >= start_ticks) { ticks = end_ticks - start_ticks; } else { ticks = end_ticks + (__g_delay_timer.max_ticks - start_ticks); } if (ticks >= __g_delay_timer.count_get_ticks) { ticks -= __g_delay_timer.count_get_ticks; } else { ticks = 0; /* 不应该出现这种情况 */ } return ticks; } /******************************************************************************/ /* 计算am_timer_count_get() 所消耗的时间 */ static void __delay_count_get_ticks_cal (void) { uint32_t start_ticks; uint32_t cur_ticks; __g_delay_timer.count_get_ticks = 0; start_ticks = __timer_count_get(); cur_ticks = __timer_count_get(); __g_delay_timer.count_get_ticks = __time_ticks_cal(start_ticks, cur_ticks); } /******************************************************************************/ /* 计算基于 Ticks 延时的固有偏差 */ static void __delay_cali_ticks_cal (void) { uint32_t start_ticks; uint32_t cur_ticks; __g_delay_timer.cali_ticks = 0xFFFFFFFF; /* set to max */ /* * 粗略评估延时误差, * 对于ARMCC,使用微库时,64位数的计算非常耗时,将导致误差增大 */ start_ticks = __timer_count_get(); /* 修正记录起始位置处 */ am_udelay(__DELAY_DEC_TIME_US + 1); cur_ticks = __timer_count_get(); /* 修正记录结束位置处 */ /* 已经记了多少ticks, 作为延时误差修正值 */ __g_delay_timer.cali_ticks = __time_ticks_cal(start_ticks, cur_ticks); } /******************************************************************************/ /* while(i--), 作为 us 级别延时的核心函数,不可优化,不可被内联处理 */ static void __delay_by_factor (uint32_t dec_factor) __attribute__ ((noinline)); static void __delay_by_factor (uint32_t dec_factor) { volatile uint32_t factor = dec_factor; /* * 增加 ISB 指令,清空流水线,避免分支预测对延时造成影响,进而提高延时精度 */ while(factor--) { __asm volatile ("isb"); } } /******************************************************************************/ static uint32_t __delay_by_factor_ticks_cal (uint32_t dec_factor) { uint32_t start_ticks; uint32_t cur_ticks; start_ticks = __timer_count_get(); __delay_by_factor(dec_factor); cur_ticks = __timer_count_get(); return __time_ticks_cal(start_ticks, cur_ticks); } /******************************************************************************/ /* 计算递减法延时因子 */ static void __delay_by_fator_cal (void) { uint32_t ticks, ticks1, ticks2; uint32_t delay_us; uint32_t dec_factor = 100; while (1) { ticks1 = __delay_by_factor_ticks_cal(dec_factor); /* ticks 超过100 us 对应的ticks 才计算,使计算误差 < 0.01us */ if (ticks1 > __g_delay_timer.freq / 10000) { ticks2 = __delay_by_factor_ticks_cal(dec_factor * 2); /* 增加dec_factor所耗费的ticks即为延时dec_factor所对应的 ticks */ ticks = ticks2 - ticks1; /* * ticks 对应的us数: us = ticks / (__g_delay_timer.freq / 1000000) * 即:us = 1000000 * ticks / __g_delay_timer.freq * * 1us 对应的延时因子 :dec_factor / us * * 256us (便于作移位运算)对应的延时因子: 256 * dec_factor / us * * 即:256 * dec_factor / (1000000 * ticks / __g_delay_timer.freq) * * 即:256 * dec_factor * __g_delay_timer.freq / (1000000 * ticks) * * 避免溢出: * * 即:4 * dec_factor * __g_delay_timer.freq / (15625 * ticks) * 4 * dec_factor * (__g_delay_timer.freq / 15625) / ticks */ __g_delay_timer.dec_factor = 4 * dec_factor * \ (__g_delay_timer.freq / 15625) / ticks; break; } dec_factor *= 2; } /* * 计算 dec_cali_us */ __g_delay_timer.dec_cali_us = 0xFFFFFFFF; /* set to max */ ticks1 = __timer_count_get(); am_udelay(1); ticks2 = __timer_count_get(); ticks1 = __time_ticks_cal(ticks1, ticks2); /* ticks1 对应的us, 四舍五入 */ __g_delay_timer.dec_cali_us = \ (ticks1 * 1000 + (__g_delay_timer.freq / 2000)) / \ (__g_delay_timer.freq / 1000); /* * 计算 delay 函数固有延时1 */ __g_delay_timer.dec_cali_factor1 = 0xFFFFFFFF; /* set to max */ delay_us = __g_delay_timer.dec_cali_us + 1; ticks1 = __timer_count_get(); am_udelay(delay_us); ticks2 = __timer_count_get(); ticks1 = __time_ticks_cal(ticks1, ticks2); /* * 将 ticks1 转换为对应的 延时因子 * * 延时 ticks 对应的延时因子为: dec_factor * * ticks 对应的延时因子即为: ticks1 * dec_factor / ticks * * 也可选择将 ticks 转换为 us: * (ticks * 1000 + (__g_delay_timer.freq / 2000)) * / (__g_delay_timer.freq / 1000); */ __g_delay_timer.dec_cali_factor1 = (ticks1 * dec_factor + ticks / 2) / ticks; /* * 计算 delay 函数固有延时2 */ __g_delay_timer.dec_cali_factor2 = 0xFFFFFFFF; /* set to max */ /* 必须时延时数超过 dec_cali_factor1 */ delay_us = (__g_delay_timer.dec_cali_factor1 + 1) * 256 / \ __g_delay_timer.dec_factor + 1; ticks1 = __timer_count_get(); am_udelay(delay_us); ticks2 = __timer_count_get(); ticks1 = __time_ticks_cal(ticks1, ticks2); /* 将 ticks1 转换为对应的 延时因子 */ __g_delay_timer.dec_cali_factor2 = (ticks1 * dec_factor + ticks / 2) / ticks; } /******************************************************************************/ static void __delay (uint64_t ticks) { uint32_t max_ticks = __g_delay_timer.max_ticks; uint32_t half_count_get_ticks = __g_delay_timer.count_get_ticks / 2; uint32_t start_ticks; /* 记录值 */ uint32_t cur_ticks; /* 当前值 */ uint32_t cnt_ticks; /* 计数值 */ /* 记录当前ticks值 */ start_ticks = __timer_count_get(); /* 至此,可以认为已经消耗了 cali_ticks, 检查是否已经计时结束 */ if (ticks <= __g_delay_timer.cali_ticks) { return; } else { ticks -= __g_delay_timer.cali_ticks; } while (1) { /* 获取当前ticks值 */ cur_ticks = __timer_count_get(); /* 已经记了多少ticks */ if (cur_ticks >= start_ticks) { cnt_ticks = cur_ticks - start_ticks; } else { cnt_ticks = cur_ticks + (max_ticks - start_ticks); } /* * 检查是否已经计时结束, * 特别地,剩余时间不到 count 获取耗时的一半,也结束,减小误差 */ if (cnt_ticks >= ticks) { break; } else { ticks -= cnt_ticks; if (ticks <= half_count_get_ticks) { break; } } start_ticks = cur_ticks; } } /******************************************************************************* Public Functions *******************************************************************************/ /** * \brief 延时函数初始化 */ void am_bsp_delay_timer_init (am_timer_handle_t handle, uint8_t chan) { const am_timer_info_t *p_info = NULL; int key; /* 参数有效性判断 */ if (NULL == handle) { return; } /* 获取当前定时器信息 */ p_info = am_timer_info_get(handle); /* 定时器特性判断 */ if ((!(AM_TIMER_INTERMEDIATE_COUNT & p_info->features)) || /* 不支持读取当前计数值 */ (AM_TIMER_CANNOT_DISABLE & p_info->features) || /* 不能被禁能 */ (AM_TIMER_STOP_WHILE_READ & p_info->features) || /* 读取时会停止 */ (!(AM_TIMER_AUTO_RELOAD & p_info->features))) { /* 不支持自动重载 */ return; } /* 定时器通道合理性判断 */ if (chan >= p_info->chan_num) { return; } /* 对全局__g_delay_timer赋值 */ __g_delay_timer.handle = handle; __g_delay_timer.chan = chan; am_timer_count_freq_get(handle, chan, &__g_delay_timer.freq); am_timer_rollover_get(handle, chan, &__g_delay_timer.max_ticks); /* 若无其它应用使用延时定时器,则设置重载值为最大值 */ if (__g_delay_timer.max_ticks == 0) { __g_delay_timer.max_ticks = (1 << p_info->counter_width) - 1; am_timer_enable(handle, chan, __g_delay_timer.max_ticks); } /* 评估一些重要时间时,关闭中断 */ key = am_int_cpu_lock(); __delay_count_get_ticks_cal(); /* 计算count_get()需要的ticks */ am_int_cpu_unlock(key); key = am_int_cpu_lock(); __delay_cali_ticks_cal(); /* 计算基于ticks延时误差修正值 */ am_int_cpu_unlock(key); key = am_int_cpu_lock(); __delay_by_fator_cal(); /* 计算递减法延时因子 */ am_int_cpu_unlock(key); } /******************************************************************************/ void am_mdelay (uint32_t nms) { __delay((uint64_t)nms * __g_delay_timer.freq / 1000); } /******************************************************************************/ void am_udelay (uint32_t nus) { if (nus < __DELAY_DEC_TIME_US) { uint32_t factor; if (nus <= __g_delay_timer.dec_cali_us) { return; } factor = (__g_delay_timer.dec_factor * nus) >> 8; if (factor <= __g_delay_timer.dec_cali_factor1) { factor -= __g_delay_timer.dec_cali_factor1; } else if (factor <= __g_delay_timer.dec_cali_factor2){ factor -= __g_delay_timer.dec_cali_factor2; __delay_by_factor(0); } else { factor -= __g_delay_timer.dec_cali_factor2; __delay_by_factor(factor); } } else { __delay((uint64_t)nus * __g_delay_timer.freq / 1000000); } } /* end of file */
13,301
C
.c
329
30.951368
82
0.446333
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,451
am_bsp_newlib.c
skyformat99_ametal/board/bsp_common/source/am_bsp_newlib.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief newlib  ≈‰∆˜∞º∂÷ß≥÷ * * \internal * \par modification history * - 1.00 12-10-23 orz, first implementation * \endinternal */ #include "ametal.h" #include "am_vdebug.h" #include "am_newlib_adapter.h" static int __console_send (void *p_cookie, const void *p_buf, size_t cnt) { return am_uart_poll_send(p_cookie, p_buf, cnt); } static int __console_receive (void *p_cookie, void *p_buf, size_t cnt) { return am_uart_poll_receive(p_cookie, p_buf, cnt); } static const am_newlib_adapter_ops_t __g_newlib_adapter_ops = { __console_send, __console_receive }; void am_bsp_newlib_init (am_uart_handle_t handle) { if (handle != NULL) { am_newlib_adapter_init(&__g_newlib_adapter_ops, handle); } else { am_newlib_adapter_init(NULL, NULL); } } /* end of file */
1,342
C
.c
44
27
81
0.510903
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,452
am_bsp_isr_defer_pendsv.c
skyformat99_ametal/board/bsp_common/source/am_bsp_isr_defer_pendsv.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief ISR DEFER 板级支持 * * \internal * \par modification history * - 1.00 12-10-23 orz, first implementation * \endinternal */ #include "ametal.h" #include "am_isr_defer.h" #include "am_bsp_isr_defer_pendsv.h" /******************************************************************************* 内部宏定义 *******************************************************************************/ /** \brief 中断控制和状态寄存器,0xE000ED04,用于触发PendSV中断 */ #define __ICSR_ADDRESS 0xE000ED04 /** \brief 系统异常优先级设置寄存器地址 0xE000ED20 */ #define __SHP2_ADDRESS 0xE000ED20 /******************************************************************************* 内部函数 *******************************************************************************/ static void __isr_defer_trigger (void *p_arg) { /* 触发PendSV中断 */ *(volatile unsigned int *)__ICSR_ADDRESS |= 0x10000000; } /******************************************************************************* 软中断处理函数 *******************************************************************************/ void PendSV_Handler (void) { am_isr_defer_job_process(); } /******************************************************************************* 定义优先级数目 *******************************************************************************/ AM_ISR_DEFER_PRIORITY_NUM_DEF(AM_BSP_ISR_DEFER_PRIORITY_NUM); /******************************************************************************* 公共函数 *******************************************************************************/ void am_bsp_isr_defer_pendsv_init (void) { /* 将PendSV的优先级设置为最低 */ *(volatile unsigned int *)__SHP2_ADDRESS |= (0xC0ul << 16); am_isr_defer_init(__isr_defer_trigger, NULL); } /* end of file */
2,334
C
.c
59
35
81
0.337626
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,458
am_arm_systick.c
skyformat99_ametal/arch/arm/source/am_arm_systick.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief SYSTICK 驱动,服务 Timer 标准接口 * * \note 使用 SYSTICK 服务的 Timer 标准接口,就不能使用标准延时接口 * am_mdelay()和am_udelay() * \internal * \par Modification History * - 1.02 15-12-14 hgo, fix potential bug caused by incorrect p_arg on callback * - 1.00 15-09-22 win, first implementation. * \endinternal */ /******************************************************************************* includes *******************************************************************************/ #include "am_arm_systick.h" #include "hw/amhw_arm_systick.h" #include "am_clk.h" /******************************************************************************* 函数声明 *******************************************************************************/ static const am_timer_info_t * __systick_info_get (void *p_drv); static int __systick_clkin_freq_get (void *p_drv, uint32_t *p_freq); static int __systick_prescale_set (void *p_drv, uint8_t chan, uint32_t prescale); static int __systick_prescale_get (void *p_drv, uint8_t chan, uint32_t *p_prescale); static int __systick_count_get (void *p_drv, uint8_t chan, void *p_count); static int __systick_rollover_get (void *p_drv,uint8_t chan,void *p_rollover); static int __systick_disable (void *p_drv, uint8_t chan); static int __systick_enable (void *p_drv, uint8_t chan, void *p_count); static int __systick_callback_set (void *p_drv, uint8_t chan, void (*pfn_callback)(void *), void *p_arg); /******************************************************************************* 全局变量 *******************************************************************************/ /* 定时器信息 */ static const am_timer_info_t __g_systick_info = { 24, /* 24位定时器 */ 1, /* 单通道 */ AM_TIMER_CAN_INTERRUPT | /* 可以产生中断 */ AM_TIMER_AUTO_RELOAD | /* 支持自动重载 */ AM_TIMER_INTERMEDIATE_COUNT, /* 当前计数器值可读 */ 0 /* 不支持时钟预分频 */ }; /* SYSTICK 驱动函数 */ static const struct am_timer_drv_funcs __g_systick_drv_funcs = { __systick_info_get, __systick_clkin_freq_get, __systick_prescale_set, __systick_prescale_get, __systick_count_get, __systick_rollover_get, __systick_enable, __systick_disable, __systick_callback_set, }; /* * 考虑到 SYSTICK 中断处理函数无法传递参数,使用一个全局变量指针, * 保存 SYSTICK 设备结构体地址 */ static am_arm_systick_dev_t *__gp_systick_dev; /******************************************************************************* 中断处理 *******************************************************************************/ /** * \brief SYSTICK 中断处理函数 * * \return 无 */ void SysTick_Handler (void) { if (__gp_systick_dev->pfn_callback != NULL) { __gp_systick_dev->pfn_callback(__gp_systick_dev->p_arg); } } /******************************************************************************* 标准定时器驱动实现 *******************************************************************************/ /* 获取 SYSTICK 信息 */ static const am_timer_info_t * __systick_info_get (void *p_drv) { return &__g_systick_info; } /******************************************************************************/ static int __systick_clkin_freq_get (void *p_drv, uint32_t *p_freq) { am_arm_systick_dev_t *p_dev = (am_arm_systick_dev_t *)p_drv; if ((p_dev == NULL) || (p_freq == NULL)) { return -AM_EINVAL; } /* 获取当前系统时钟频率,systick 使用的是系统时钟 */ *p_freq = am_clk_rate_get(p_dev->p_devinfo->clk_id); return AM_OK; } /******************************************************************************/ static int __systick_prescale_set (void *p_drv, uint8_t chan, uint32_t prescale) { if (prescale == 1) { return AM_OK; } return -AM_ENOTSUP; } /******************************************************************************/ static int __systick_prescale_get (void *p_drv, uint8_t chan, uint32_t *p_prescale) { am_arm_systick_dev_t *p_dev = (am_arm_systick_dev_t *)p_drv; if (p_dev == NULL || p_prescale == NULL || chan != 0) { return -AM_EINVAL; } /* 无分频器,分频值始终为1 */ *p_prescale = 1; return AM_OK; } /******************************************************************************/ static int __systick_count_get (void *p_drv, uint8_t chan, void *p_count) { am_arm_systick_dev_t *p_dev = (am_arm_systick_dev_t *)p_drv; amhw_arm_systick_t *p_hw_systick = NULL; if (p_dev == NULL || p_count == NULL || chan != 0) { return -AM_EINVAL; } p_hw_systick = (amhw_arm_systick_t *)p_dev->p_devinfo->systick_regbase; *((uint32_t *)p_count) = amhw_arm_systick_reload_val_get(p_hw_systick) - \ amhw_arm_systick_val_get(p_hw_systick); return AM_OK; } /******************************************************************************/ static int __systick_rollover_get (void *p_drv, uint8_t chan, void *p_rollover) { am_arm_systick_dev_t *p_dev = (am_arm_systick_dev_t *)p_drv; amhw_arm_systick_t *p_hw_systick = NULL; if (p_drv == NULL || p_rollover == NULL || chan != 0) { return -AM_EINVAL; } p_hw_systick = (amhw_arm_systick_t *) p_dev->p_devinfo->systick_regbase; *((uint32_t *)p_rollover) = amhw_arm_systick_reload_val_get(p_hw_systick); return AM_OK; } /******************************************************************************/ static int __systick_disable (void *p_drv, uint8_t chan) { am_arm_systick_dev_t *p_dev = NULL; amhw_arm_systick_t *p_hw_systick = NULL; if (p_drv == NULL || chan != 0) { return -AM_EINVAL; } p_dev = (am_arm_systick_dev_t *)p_drv; p_hw_systick = (amhw_arm_systick_t *)p_dev->p_devinfo->systick_regbase; amhw_arm_systick_int_disable(p_hw_systick); amhw_arm_systick_disable(p_hw_systick); return AM_OK; } /******************************************************************************/ static int __systick_enable (void *p_drv, uint8_t chan, void *p_count) { am_arm_systick_dev_t *p_dev = NULL; amhw_arm_systick_t *p_hw_systick = NULL; if ((p_drv == NULL) || (chan != 0) || (p_count == NULL)) { return -AM_EINVAL; } p_dev = (am_arm_systick_dev_t *)p_drv; p_hw_systick = (amhw_arm_systick_t *)p_dev->p_devinfo->systick_regbase; /* 设置重载定时寄存器中的数值 */ amhw_arm_systick_reload_val_set(p_hw_systick, *((uint32_t *)p_count)); /* 清除当前定时计数器中的数值 */ amhw_arm_systick_val_set(p_hw_systick, 0x0); if (p_dev->pfn_callback == NULL) { amhw_arm_systick_int_disable(p_hw_systick); } else { amhw_arm_systick_int_enable(p_hw_systick); } /* 使能 SYSTICK */ amhw_arm_systick_enable(p_hw_systick); return AM_OK; } /******************************************************************************/ static int __systick_callback_set (void *p_drv, uint8_t chan, void (*pfn_callback)(void *), void *p_arg) { am_arm_systick_dev_t *p_dev = NULL; amhw_arm_systick_t *p_hw_systick = NULL; if (p_drv == NULL || chan != 0) { return -AM_EINVAL; } p_dev = (am_arm_systick_dev_t *)p_drv; p_hw_systick = (amhw_arm_systick_t *)p_dev->p_devinfo->systick_regbase; if (pfn_callback == NULL) { amhw_arm_systick_int_disable(p_hw_systick); } else { p_dev->p_arg = p_arg; p_dev->pfn_callback = pfn_callback; amhw_arm_systick_int_enable(p_hw_systick); } return AM_OK; } /******************************************************************************* Public functions *******************************************************************************/ am_timer_handle_t am_arm_systick_init (am_arm_systick_dev_t *p_dev, const am_arm_systick_devinfo_t *p_devinfo) { amhw_arm_systick_t *p_hw_systick = NULL; if (p_dev == NULL || p_devinfo == NULL) { return NULL; } p_hw_systick = (amhw_arm_systick_t *)p_devinfo->systick_regbase; p_dev->p_devinfo = p_devinfo; p_dev->timer_serv.p_funcs = (struct am_timer_drv_funcs *)&__g_systick_drv_funcs; p_dev->timer_serv.p_drv = p_dev; p_dev->pfn_callback = NULL; p_dev->p_arg = NULL; __gp_systick_dev = p_dev; /* 设置定时器时钟频率 */ if ((p_devinfo->clk_freq_src != AMHW_ARM_SYSTICK_CONFIG_CLKSRC_SYSTEM) && (p_devinfo->clk_freq_src != AMHW_ARM_SYSTICK_CONFIG_CLKSRC_SYSTEM_HALF)) { return NULL; } else { amhw_arm_systick_config(p_hw_systick, p_devinfo->clk_freq_src); } return &(p_dev->timer_serv); } /******************************************************************************/ void am_arm_systick_deinit (am_timer_handle_t handle) { am_arm_systick_dev_t *p_dev = NULL; amhw_arm_systick_t *p_hw_systick = NULL; if (handle == NULL) { return ; } p_dev = (am_arm_systick_dev_t *)handle; p_hw_systick = (amhw_arm_systick_t *)p_dev->p_devinfo->systick_regbase; p_dev->timer_serv.p_funcs = NULL; p_dev->timer_serv.p_drv = NULL; p_dev->pfn_callback = NULL; p_dev->p_arg = NULL; amhw_arm_systick_int_disable(p_hw_systick); amhw_arm_systick_disable(p_hw_systick); }
10,852
C
.c
256
34.949219
85
0.445236
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,459
am_arm_nvic.c
skyformat99_ametal/arch/arm/source/am_arm_nvic.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief NVIC实现 * * \internal * \par Modification history * - 1.01 17-04-10 sdy, modified. * - 1.00 14-12-04 hbt, first implementation. * \endinternal */ #include "ametal.h" #include "am_arm_nvic.h" #include "hw/amhw_arm_nvic.h" /******************************************************************************* * 私有定义 *******************************************************************************/ /** \brief 中断未连接标识 */ #define __INT_NOT_CONNECTED 0xFF /******************************************************************************* 全局变量 *******************************************************************************/ /** \brief 指向中断设备的指针 */ static am_arm_nvic_dev_t *__gp_nvic_dev = NULL; /****************************************************************************** 公共函数 *******************************************************************************/ /* 中断初始化 */ int am_arm_nvic_init (am_arm_nvic_dev_t *p_dev, const am_arm_nvic_devinfo_t *p_devinfo) { int i; if (NULL == p_dev || NULL == p_devinfo) { return -AM_EINVAL; } p_dev->p_devinfo = p_devinfo; __gp_nvic_dev = p_dev; p_dev->valid_flg = AM_TRUE; if ((NULL == p_devinfo->p_isrmap) || (NULL == p_devinfo->p_isrinfo)) { p_dev->valid_flg = AM_FALSE; } if (p_dev->valid_flg) { for (i = 0; i < p_devinfo->input_cnt; i++) { p_devinfo->p_isrmap[i] = __INT_NOT_CONNECTED; } for (i = 0; i < p_devinfo->isrinfo_cnt; i++) { p_devinfo->p_isrinfo[i].pfn_isr = NULL; } } amhw_arm_nvic_priority_group_set (p_devinfo->group); return AM_OK; } /* 中断去初始化 */ void am_arm_nvic_deinit (void) { int i; const am_arm_nvic_devinfo_t *p_nvic_devinfo = NULL; if (NULL == __gp_nvic_dev) { return; } p_nvic_devinfo = __gp_nvic_dev->p_devinfo; if (__gp_nvic_dev->valid_flg) { for (i = 0; i < p_nvic_devinfo->input_cnt; i++) { p_nvic_devinfo->p_isrmap[i] = __INT_NOT_CONNECTED; } for (i = 0; i < p_nvic_devinfo->isrinfo_cnt; i++) { p_nvic_devinfo->p_isrinfo[i].pfn_isr = NULL; } } for (i = 0; i < p_nvic_devinfo->input_cnt; i++) { amhw_arm_nvic_disable(p_nvic_devinfo->int_servinfo.inum_start + i); } } /* 中断处理函数 */ void am_exc_eint_handler (void) { const am_arm_nvic_devinfo_t *p_nvic_devinfo = NULL; int inum = 0; int slot; am_pfnvoid_t pfn_isr; void *p_arg; if (NULL == __gp_nvic_dev) { return; } p_nvic_devinfo = __gp_nvic_dev->p_devinfo; inum = amhw_inum_get(); if (!((inum >= p_nvic_devinfo->int_servinfo.inum_start) && (inum <= p_nvic_devinfo->int_servinfo.inum_end))) { return; } slot = p_nvic_devinfo->p_isrmap[inum]; if (slot == __INT_NOT_CONNECTED) { return; } pfn_isr = p_nvic_devinfo->p_isrinfo[slot].pfn_isr; p_arg = p_nvic_devinfo->p_isrinfo[slot].p_arg; if (pfn_isr != NULL) { pfn_isr(p_arg); } } /* 连接中断回调函数 */ int am_int_connect (int inum, am_pfnvoid_t pfn_isr, void *p_arg) { const am_arm_nvic_devinfo_t *p_nvic_devinfo = NULL; int slot = 0; int i; if (NULL == __gp_nvic_dev) { return -AM_EINVAL; } p_nvic_devinfo = __gp_nvic_dev->p_devinfo; if (!((inum >= p_nvic_devinfo->int_servinfo.inum_start) && (inum <= p_nvic_devinfo->int_servinfo.inum_end))) { return -AM_EINVAL; } if (NULL == pfn_isr) { return -AM_EINVAL; } slot = p_nvic_devinfo->p_isrmap[inum]; if (slot == __INT_NOT_CONNECTED) { for (i = 0; i < p_nvic_devinfo->input_cnt; i++) { if (p_nvic_devinfo->p_isrinfo[i].pfn_isr == NULL) { slot = i; break; } } } else { if ((p_nvic_devinfo->p_isrinfo[slot].p_arg == p_arg) && (p_nvic_devinfo->p_isrinfo[slot].pfn_isr == pfn_isr)) { return AM_OK; } slot = __INT_NOT_CONNECTED; } if (slot != __INT_NOT_CONNECTED) { p_nvic_devinfo->p_isrmap[inum] = slot; p_nvic_devinfo->p_isrinfo[slot].p_arg = p_arg; p_nvic_devinfo->p_isrinfo[slot].pfn_isr = pfn_isr; } if (slot == __INT_NOT_CONNECTED) { return -AM_EPERM; /* 没有空的内存映射 */ } return AM_OK; } /* 删除中断回调函数连接 */ int am_int_disconnect (int inum, am_pfnvoid_t pfn_isr, void *p_arg) { const am_arm_nvic_devinfo_t *p_nvic_devinfo = NULL; int slot = 0; if (NULL == __gp_nvic_dev) { return -AM_EINVAL; } p_nvic_devinfo = __gp_nvic_dev->p_devinfo; if (!((inum >= p_nvic_devinfo->int_servinfo.inum_start) && (inum <= p_nvic_devinfo->int_servinfo.inum_end))) { return -AM_EINVAL; } if (NULL == pfn_isr) { return -AM_EINVAL; } slot = p_nvic_devinfo->p_isrmap[inum]; if (slot == __INT_NOT_CONNECTED) { return -AM_EPERM; } p_nvic_devinfo->p_isrmap[inum] = __INT_NOT_CONNECTED; p_nvic_devinfo->p_isrinfo[slot].pfn_isr = NULL; return AM_OK; } /* 使能中断 */ int am_int_enable (int inum) { if (NULL == __gp_nvic_dev) { return -AM_EINVAL; } amhw_arm_nvic_enable(inum); return AM_OK; } /* 禁能中断 */ int am_int_disable (int inum) { if (NULL == __gp_nvic_dev) { return -AM_EINVAL; } amhw_arm_nvic_disable(inum); return AM_OK; } /* 设置中断优先级 */ int am_arm_nvic_priority_set(int inum, uint32_t preempt_priority, uint32_t sub_priority) { uint32_t prio = 0; if (NULL == __gp_nvic_dev) { return -AM_EINVAL; } prio = amhw_arm_nvic_encode_priority (__gp_nvic_dev->p_devinfo->group, preempt_priority, sub_priority, __gp_nvic_dev->p_devinfo->prio_bits); switch (__gp_nvic_dev->p_devinfo->core) { case AM_ARM_NVIC_CORE_M0: case AM_ARM_NVIC_CORE_M0PLUS: amhw_arm_nvic_m0_priority_set (inum, prio, __gp_nvic_dev->p_devinfo->prio_bits); break; case AM_ARM_NVIC_CORE_M3: case AM_ARM_NVIC_CORE_M4: amhw_arm_nvic_m3m4_priority_set (inum, prio, __gp_nvic_dev->p_devinfo->prio_bits); break; default: break; } return AM_OK; } /* end of file */
7,364
C
.c
222
25.418919
91
0.468705
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,475
am_zlg116_clk.c
skyformat99_ametal/soc/zlg/drivers/source/clk/am_zlg116_clk.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief CLK implementation * * 驱动直接使用了 ZLG116 外设寄存器基地址, 因此,该驱动仅适用于 ZLG116 * * \internal * \par Modification history * - 1.00 17-04-12 sdy, first implementation * \endinternal */ #include "ametal.h" #include "am_zlg116_clk.h" #include "zlg116_clk.h" #include "zlg116_periph_map.h" #include "hw/amhw_zlg116_rcc.h" #include "hw/amhw_zlg_flash.h" am_zlg116_clk_dev_t *__gp_dev = NULL; #define __HSI_CLK 48000000ul #define __LSI_CLK 40000ul static void __pllin_hse_init (void) { amhw_zlg116_rcc_hseon_enable(); while (amhw_zlg116_rcc_hserdy_read () == AM_FALSE); // amhw_zlg116_rcc_hseforpll_set (0); __gp_dev->pllin_clk = __gp_dev->p_devinfo->hse_osc; } static void __pllin_hsi_init (void) { amhw_zlg116_rcc_hsion_enable(); while (amhw_zlg116_rcc_hsirdy_read() == AM_FALSE); // amhw_zlg116_rcc_hsiten_enable(); __gp_dev->pllin_clk = __HSI_CLK / 4; } static int __apb2_peri_clk (int peri) { int clk = 0; switch (peri) { case AMHW_ZLG116_RCC_APB2_TIM1: case AMHW_ZLG116_RCC_APB2_TIM14: case AMHW_ZLG116_RCC_APB2_TIM16: case AMHW_ZLG116_RCC_APB2_TIM17: if (amhw_zlg116_rcc_apb2_div_get() < 4) { clk = __gp_dev->apb2_clk; } else { clk = __gp_dev->apb2_clk << 1; } break; case AMHW_ZLG116_RCC_APB2_ADC1: /* ADC内部有分频器 */ clk = __gp_dev->apb2_clk; break; default : clk = __gp_dev->apb2_clk; break; } return clk; } static int __apb1_peri_clk (int peri) { int clk = 0; switch (peri) { case AMHW_ZLG116_RCC_APB1_TIM2: case AMHW_ZLG116_RCC_APB1_TIM3: if (amhw_zlg116_rcc_apb1_div_get() < 4) { clk = __gp_dev->apb1_clk; } else { clk = __gp_dev->apb1_clk << 1; } break; case AMHW_ZLG116_RCC_APB1_USB: clk = __gp_dev->usb_clk; break; default : clk = __gp_dev->apb1_clk; break; } return clk; } static int __other_clk (am_clk_id_t clk_id) { int clk = 0; switch (clk_id) { case CLK_PLLIN: clk = __gp_dev->pllin_clk; break; case CLK_PLLOUT: clk = __gp_dev->pllout_clk; break; case CLK_AHB: clk = __gp_dev->ahb_clk; break; case CLK_APB1: clk = __gp_dev->apb1_clk; break; case CLK_APB2: clk = __gp_dev->apb2_clk; break; case CLK_HSEOSC: clk = __gp_dev->p_devinfo->hse_osc; break; case CLK_LSI: if (amhw_zlg116_rcc_lsirdy_read()) { clk = __LSI_CLK; } else { clk = 0; } break; case CLK_HSI: clk = __HSI_CLK; break; default : clk = 0; break; } return clk; } /** * \brief 获取时钟频率 */ int am_clk_rate_get (am_clk_id_t clk_id) { int clk = 0; int peri, num; num = (clk_id & 0xff00) >> 8; peri = clk_id & 0xff; switch (num) { case 1: clk = __apb1_peri_clk(peri); break; case 2: clk = __apb2_peri_clk(peri); break; case 3: clk = __gp_dev->ahb_clk; break; case 4: clk = __other_clk(clk_id); break; default : break; } return clk; } /** * \brief 使能指定的系统或外设时钟 */ int am_clk_enable (am_clk_id_t clk_id) { int peri, num; num = (clk_id & 0xff00) >> 8; peri = clk_id & 0xff; switch (num) { case 1: amhw_zlg116_rcc_apb1_enable ((amhw_zlg116_apb1_peripheral)peri); break; case 2: amhw_zlg116_rcc_apb2_enable ((amhw_zlg116_apb2_peripheral)peri); break; case 3: amhw_zlg116_rcc_ahb_enable ((amhw_zlg116_ahb_peripheral)peri); break; default : break; } return AM_OK; } /** * \brief 禁能指定的系统或外设时钟 */ int am_clk_disable (am_clk_id_t clk_id) { int peri, num; num = (clk_id & 0xff00) >> 8; peri = clk_id & 0xff; switch (num) { case 1: amhw_zlg116_rcc_apb1_disable ((amhw_zlg116_apb1_peripheral)peri); break; case 2: amhw_zlg116_rcc_apb2_disable ((amhw_zlg116_apb2_peripheral)peri); break; case 3: amhw_zlg116_rcc_ahb_disable ((amhw_zlg116_ahb_peripheral)peri); break; default : break; } return AM_OK; } int am_zlg116_clk_reset (am_clk_id_t clk_id) { int peri, num; num = (clk_id & 0xff00) >> 8; peri = clk_id & 0xff; switch (num) { case 1: amhw_zlg116_rcc_apb1_reset((amhw_zlg116_apb1_peripheral)peri); amhw_zlg116_rcc_apb1_reset_stop((amhw_zlg116_apb1_peripheral)peri); break; case 2: amhw_zlg116_rcc_apb2_reset((amhw_zlg116_apb2_peripheral)peri); amhw_zlg116_rcc_apb2_reset_stop((amhw_zlg116_apb2_peripheral)peri); break; default : break; } return AM_OK; } int am_zlg116_clk_update (am_clk_id_t clk_id, int clk) { switch (clk_id) { case CLK_AHB: __gp_dev->ahb_clk = clk; break; case CLK_APB1: __gp_dev->apb1_clk = clk; break; case CLK_APB2: __gp_dev->apb2_clk = clk; break; default: break; } return AM_OK; } const am_zlg116_clk_dev_t *am_zlg116_clk_devinfo_get (void) { if (__gp_dev == NULL) { return NULL; } return __gp_dev; } int am_zlg116_div_get (am_clk_id_t clk_id) { int div = 0; if (__gp_dev == NULL) { return -AM_EINVAL; } switch (clk_id) { case CLK_AHB: div = __gp_dev->p_devinfo->ahb_div; break; case CLK_APB1: div = __gp_dev->p_devinfo->apb1_div; break; case CLK_APB2: div = __gp_dev->p_devinfo->apb2_div; break; case CLK_USB: div = __gp_dev->p_devinfo->usb_div; break; default: break; } return div; } /** * \brief CLK 初始化 */ int am_zlg116_clk_init (am_zlg116_clk_dev_t *p_dev, const am_zlg116_clk_devinfo_t *p_devinfo) { uint8_t i = 0,div = 1; if (p_dev == NULL || p_devinfo == NULL) { return -AM_EINVAL; } p_dev->p_devinfo = p_devinfo; __gp_dev = p_dev; /* 使用内部hsi时钟 */ amhw_zlg116_rcc_hsion_enable(); /* 等待其稳定 */ while (amhw_zlg116_rcc_hsirdy_read() == AM_FALSE); /* 复位SW, HPRE, PPRE1, PPRE2, and MCO bits */ ZLG116_RCC->cfgr &= (uint32_t)0xF8FFC00C; /* 复位禁能 HSEON, CSSON and PLLON bits */ ZLG116_RCC->cr &= (uint32_t)0xFEF6FFFF; if (p_devinfo->pllin_src == AMHW_ZLG116_PLLCLK_HSE) { /* CLK平台初始化,配置时钟引脚 */ if (p_devinfo->pfn_plfm_init) { p_devinfo->pfn_plfm_init(); } __pllin_hse_init(); } else { __pllin_hsi_init(); } p_dev->pllout_clk = p_dev->pllin_clk * p_devinfo->pll_mul / p_devinfo->pll_div; /* 计算AHB时钟频率 */ if (p_devinfo->ahb_div < 12) { for (i = 0; i < p_devinfo->ahb_div - 7; i++) { div = div << 1; } } else { div = 64; for (i = 0; i < (p_devinfo->ahb_div & 0xf) - 12; i++) { div = div << 1; } } p_dev->ahb_clk = p_dev->pllout_clk / div; p_dev->usb_clk = p_dev->pllout_clk / (div + 1); /* 计算APB1时钟频率 */ div = 1; for (i = 0; i < (p_devinfo->apb1_div & 0x7); i++) { div = div << 1; } p_dev->apb1_clk = p_dev->ahb_clk / div; /* 计算APB2时钟频率 */ div = 1; for (i = 0; i < (p_devinfo->apb2_div & 0x7); i++) { div = div << 1; } p_dev->apb2_clk = p_dev->ahb_clk / div; ZLG116_FLASH->acr |= 0x30; amhw_zlg_flash_latency_set(ZLG116_FLASH, ((p_dev->pllout_clk - 1) / 24000000)); amhw_zlg116_rcc_ahb_div_set(p_devinfo->ahb_div); amhw_zlg116_rcc_apb2_div_set(p_devinfo->apb2_div + 3); amhw_zlg116_rcc_apb1_div_set(p_devinfo->apb1_div + 3); amhw_zlg116_rcc_plldm_set(p_devinfo->pll_div - 1); amhw_zlg116_rcc_plldn_set(p_devinfo->pll_mul - 1); amhw_zlg116_rcc_pll_clk_set(p_devinfo->pllin_src); amhw_zlg116_rcc_pll_enable(); while (amhw_zlg116_rcc_pllrdy_read() == AM_FALSE); /* 等待pll就绪 */ amhw_zlg116_rcc_sys_clk_set (AMHW_ZLG116_SYSCLK_PLL); amhw_zlg116_rcc_pllforusb_set (p_devinfo->usb_div); ZLG116_RCC->apb2enr &= ~0xc; return AM_OK; } /* end of file */
9,517
C
.c
341
20.202346
81
0.513367
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,476
am_zlg_flash.c
skyformat99_ametal/soc/zlg/drivers/source/flash/am_zlg_flash.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief Flash模块的驱动层实现 * * \internal * \par Modification History * - 1.00 17-04-17 ari, first implementation * \endinternal */ #include "am_zlg_flash.h" #include "am_types.h" #include "am_bitops.h" #include "ametal.h" /******************************************************************************* defines *******************************************************************************/ #define UNLOCK_FALSH_KEY1 0x45670123 /**< \brief unlock key word */ #define UNLOCK_FALSH_KEY2 0xCDEF89AB /**< \brief unlock key word */ #define FALSH_ADDRESS_BASE 0x08000000 #define FALSH_ADDRESS_SIZE 0x08000000 + FLASH_SIZE /****************************************************************************** * 函数定义 ******************************************************************************/ /** * \brief Flash模块初始化 * * \param[in] p_hw_gpio 指向FLASH寄存器块的指针 * * \return 无 */ void am_zlg_flash_init (amhw_zlg_flash_t *p_hw_flash) { amhw_zlg_flash_key_set(p_hw_flash, UNLOCK_FALSH_KEY1); amhw_zlg_flash_key_set(p_hw_flash, UNLOCK_FALSH_KEY2); amhw_zlg_flash_status_flag_clr(p_hw_flash, AMHW_ZLG_FLASH_WRPRTERR_FLAG | AMHW_ZLG_FLASH_PGERR_FLAG | AMHW_ZLG_FLASH_BUSY_FLAG); // amhw_zlg_flash_set_prebuff_on(p_hw_flash, FALSE); // amhw_zlg_flash_half_cycle_enable(p_hw_flash, FALSE); return; } /** * \brief 擦除扇区 * * \param[in] p_hw_gpio 指向FLASH寄存器块的指针 * \param[in] start_addr 扇区的起始地址 * * \return > 0: 执行结果, -AM_EINVAL: 输入地址过大 */ int32_t am_zlg_flash_sector_erase (amhw_zlg_flash_t *p_hw_flash, uint32_t start_addr) { if (start_addr < FALSH_ADDRESS_BASE) { start_addr += FALSH_ADDRESS_BASE; } if (FALSH_ADDRESS_SIZE < start_addr) { return -AM_EINVAL; } while (amhw_zlg_flash_status_check(p_hw_flash, AMHW_ZLG_FLASH_BUSY_FLAG)) { ; } amhw_zlg_flash_cs_reg_set(p_hw_flash, AMHW_ZLG_FLASH_PAGE_ERASE_MASK); amhw_zlg_flash_address_set(p_hw_flash, start_addr); amhw_zlg_flash_cs_reg_set(p_hw_flash, AMHW_ZLG_FLASH_START_MASK); while (amhw_zlg_flash_status_check(p_hw_flash, AMHW_ZLG_FLASH_BUSY_FLAG)) { ; } return AM_OK; } /** * \brief 对扇区编程或部分扇区编程 * * \param[in] p_hw_gpio 指向FLASH寄存器块的指针 * \param[in] dst_addr 写入到flash的起始地址 * \param[in] p_src 要写入到flash中的数据的起始地址 * \param[in] size 写入字(32bit)的个数 * * \retval 0 实际成功写入的字数 */ int32_t am_zlg_flash_flash_program (amhw_zlg_flash_t *p_hw_flash, uint32_t dst_addr, uint32_t *p_src, uint32_t size) { uint32_t i; if (dst_addr < FALSH_ADDRESS_BASE) { dst_addr += FALSH_ADDRESS_BASE; } /** size不能大于扇区的大小 */ if (size > SECTOR_SIZE || dst_addr >= FALSH_ADDRESS_SIZE) { return -AM_EINVAL; } if (amhw_zlg_flash_cs_reg_get(p_hw_flash) & AMHW_ZLG_FLASH_LOCK_MASK) { amhw_zlg_flash_key_set(p_hw_flash, UNLOCK_FALSH_KEY1); amhw_zlg_flash_key_set(p_hw_flash, UNLOCK_FALSH_KEY2); } amhw_zlg_flash_cs_reg_set(p_hw_flash, AMHW_ZLG_FLASH_PROGRAM_MASK); /** 对flash编程 */ for (i = 0; i < size; i++) { /** 半字写入 */ *(uint16_t *)(dst_addr + i * 4) = (uint16_t)p_src[i]; *(uint16_t *)(dst_addr + i * 4 + 2) = (uint16_t)(p_src[i] >> 16); } while (amhw_zlg_flash_status_check(p_hw_flash, AMHW_ZLG_FLASH_BUSY_FLAG)) { ; } for (i = 0; i < size; i++) { /** 半字写入 */ if (p_src[i] != *(uint32_t *)(dst_addr + i * 4)) { break; } } return i; } /** * \brief 擦除所有扇区 * * \param[in] p_hw_gpio 指向FLASH寄存器块的指针 * * \return 执行结果 * */ uint32_t am_zlg_flash_all_sector_erase (amhw_zlg_flash_t *p_hw_flash) { while (amhw_zlg_flash_status_check(p_hw_flash, AMHW_ZLG_FLASH_BUSY_FLAG)) { ; } amhw_zlg_flash_cs_reg_set(p_hw_flash, AMHW_ZLG_FLASH_MASS_ERASE_MASK); amhw_zlg_flash_cs_reg_set(p_hw_flash, AMHW_ZLG_FLASH_START_MASK); while (amhw_zlg_flash_status_check(p_hw_flash, AMHW_ZLG_FLASH_BUSY_FLAG)) { ; } return AM_OK; } /* end of file */
5,371
C
.c
154
26.058442
81
0.475649
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,477
am_zlg_wwdg.c
skyformat99_ametal/soc/zlg/drivers/source/wdt/am_zlg_wwdg.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief WWDG驱动层接口 * \internal * \par Modification history * - 1.00 15-07-10 sss, first implementation * \endinternal */ #include "ametal.h" #include "am_zlg_wwdg.h" #include "am_clk.h" #include "hw/amhw_zlg_wwdg.h" /**************************************************************************** * Functions Declaration ***************************************************************************/ static int __wwdg_feed (void *p_drv); static int __wwdg_enable (void *p_drv, uint32_t timeout); static int __wwdg_info_get (void *p_drv, am_wdt_info_t *p_info); /** \brief 看门狗标准服务函数结构体 */ static const struct am_wdt_drv_funcs __g_wwdg_drv_funcs = { __wwdg_info_get, __wwdg_enable, __wwdg_feed }; /** \brief 获取看门狗信息 */ static int __wwdg_info_get (void *p_drv, am_wdt_info_t *p_info) { am_zlg_wwdg_dev_t *p_dev = (am_zlg_wwdg_dev_t *)p_drv; uint32_t wdt_freq = am_clk_rate_get (p_dev->p_devinfo->clk_num) / 4096; uint32_t wdt_freq_max = wdt_freq / 1; uint32_t wdt_freq_min = wdt_freq / 8; p_info->min_timeout_ms = 1 * 1000 / wdt_freq_max + 1; p_info->max_timeout_ms = (uint64_t)(0x40) * 1000 / (uint64_t)wdt_freq_min ; return AM_OK; } /** \brief 喂狗操作 */ static int __wwdg_feed (void *p_drv) { am_zlg_wwdg_dev_t *p_dev = (am_zlg_wwdg_dev_t *)p_drv; amhw_zlg_wwdg_t *p_hw_wwdg = (amhw_zlg_wwdg_t *)p_dev->p_devinfo->wwdg_regbase; amhw_zlg_wwdg_counter_set(p_hw_wwdg, p_dev->count); return AM_OK; } /** \brief 配置超时时间并启动看门狗 */ static int __wwdg_enable (void *p_drv, uint32_t timeout_ms) { am_zlg_wwdg_dev_t *p_dev = (am_zlg_wwdg_dev_t *)p_drv; amhw_zlg_wwdg_t *p_hw_wwdg = (amhw_zlg_wwdg_t *)p_dev->p_devinfo->wwdg_regbase; uint32_t wdt_freq = am_clk_rate_get (p_dev->p_devinfo->clk_num) / 4096; uint32_t ticks; uint32_t div = 1; ticks = (uint64_t) (timeout_ms) * wdt_freq / 1000; div = ticks / 0x40 + 1; amhw_zlg_wwdg_winvalue_set (p_hw_wwdg, 0x7f); if (div <= 1) { amhw_zlg_wwdg_timerbase_set(p_hw_wwdg, 0); p_dev->div = 1; } else if (div <= 2) { amhw_zlg_wwdg_timerbase_set (p_hw_wwdg, 1); p_dev->div = 2; } else if (div <= 4) { amhw_zlg_wwdg_timerbase_set (p_hw_wwdg, 2); p_dev->div = 4; } else if (div <= 8) { amhw_zlg_wwdg_timerbase_set (p_hw_wwdg, 3); p_dev->div = 8; } else { return AM_ERROR; } wdt_freq /= p_dev->div; ticks = (uint64_t) (timeout_ms) * wdt_freq / 1000; p_dev->count = (ticks + 0x3f) % 0x7f; amhw_zlg_wwdg_counter_set (p_hw_wwdg, p_dev->count); /* 启动看门狗 */ amhw_zlg_wwdg_enable(p_hw_wwdg); return AM_OK; } /** \brief 初始化WWDT,获取标准服务句柄 */ am_wdt_handle_t am_zlg_wwdg_init (am_zlg_wwdg_dev_t *p_dev, const am_zlg_wwdg_devinfo_t *p_devinfo) { if (p_devinfo == NULL) { return NULL; } p_dev->p_devinfo = p_devinfo; p_dev->wdt_serv.p_funcs = (struct am_wdt_drv_funcs *)&__g_wwdg_drv_funcs; p_dev->wdt_serv.p_drv = p_dev; p_dev->div = 4; p_dev->count = 0x7f; /* 看门狗平台初始化 */ if (p_devinfo->pfn_plfm_init) { p_devinfo->pfn_plfm_init(); } return &(p_dev->wdt_serv); } /** \brief WWDT解初始化 */ void am_zlg_wwdg_deinit (am_wdt_handle_t handle) { am_zlg_wwdg_dev_t *p_dev = (am_zlg_wwdg_dev_t *)handle; if (NULL == p_dev) { return ; } p_dev->p_devinfo = NULL; p_dev->wdt_serv.p_funcs = NULL; p_dev->wdt_serv.p_drv = NULL; if (p_dev->p_devinfo->pfn_plfm_deinit) { p_dev->p_devinfo->pfn_plfm_deinit(); } } /* end of file */
4,504
C
.c
125
29.536
93
0.497882
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,478
am_zlg_iwdg.c
skyformat99_ametal/soc/zlg/drivers/source/wdt/am_zlg_iwdg.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief IWDG驱动层接口 * \internal * \par Modification history * - 1.00 15-07-10 sss, first implementation * \endinternal */ #include "ametal.h" #include "am_zlg_iwdg.h" #include "hw/amhw_zlg_iwdg.h" /**************************************************************************** * Functions Declaration ***************************************************************************/ static int __iwdg_feed (void *p_drv); static int __iwdg_enable (void *p_drv, uint32_t timeout); static int __iwdg_info_get (void *p_drv, am_wdt_info_t *p_info); /** \brief 看门狗标准服务函数结构体 */ static const struct am_wdt_drv_funcs __g_iwdg_drv_funcs = { __iwdg_info_get, __iwdg_enable, __iwdg_feed }; /** \brief 获取看门狗信息 */ static int __iwdg_info_get (void *p_drv, am_wdt_info_t *p_info) { uint32_t wdt_freq = 40000; uint32_t wdt_freq_max = wdt_freq / 4; uint32_t wdt_freq_min = wdt_freq / 256; p_info->min_timeout_ms = 1 * 1000 / wdt_freq_max + 1; p_info->max_timeout_ms = (uint64_t)(0xFFF + 1) * 1000 / (uint64_t)wdt_freq_min ; return AM_OK; } /** \brief 喂狗操作 */ static int __iwdg_feed (void *p_drv) { am_zlg_iwdg_dev_t *p_dev = (am_zlg_iwdg_dev_t *)p_drv; amhw_zlg_iwdg_t *p_hw_iwdg = (amhw_zlg_iwdg_t *)p_dev->p_devinfo->iwdg_regbase; amhw_zlg_iwdg_keyvalue_set(p_hw_iwdg, 0xAAAA); return AM_OK; } /** \brief 配置超时时间并启动看门狗 */ static int __iwdg_enable (void *p_drv, uint32_t timeout_ms) { am_zlg_iwdg_dev_t *p_dev = (am_zlg_iwdg_dev_t *)p_drv; amhw_zlg_iwdg_t *p_hw_iwdg = (amhw_zlg_iwdg_t *)p_dev->p_devinfo->iwdg_regbase; uint32_t wdt_freq = 40000; uint32_t ticks; uint32_t div = 1; ticks = (uint64_t) (timeout_ms) * wdt_freq / 1000; div = ticks / 0xFFF + 1; amhw_zlg_iwdg_keyvalue_set(p_hw_iwdg, 0x5555); while(amhw_zlg_iwdg_status_get(p_hw_iwdg) & 0x1ul); if (div <= 4) { amhw_zlg_iwdg_div_set (p_hw_iwdg, 0); p_dev->div = 4; } else if (div <= 8) { amhw_zlg_iwdg_div_set (p_hw_iwdg, 1); p_dev->div = 8; } else if (div <= 16) { amhw_zlg_iwdg_div_set (p_hw_iwdg, 2); p_dev->div = 16; } else if (div <= 32) { amhw_zlg_iwdg_div_set (p_hw_iwdg, 3); p_dev->div = 32; } else if (div <= 64) { amhw_zlg_iwdg_div_set (p_hw_iwdg, 4); p_dev->div = 64; } else if (div <= 128) { amhw_zlg_iwdg_div_set (p_hw_iwdg, 5); p_dev->div = 128; } else { amhw_zlg_iwdg_div_set (p_hw_iwdg, 6); p_dev->div = 256; } wdt_freq /= p_dev->div; ticks = (uint64_t) (timeout_ms) * wdt_freq / 1000; amhw_zlg_iwdg_keyvalue_set(p_hw_iwdg, 0x5555); while(amhw_zlg_iwdg_status_get(p_hw_iwdg) & 0x2ul); amhw_zlg_iwdg_reload_set (p_hw_iwdg, ticks); /* 启动看门狗 */ amhw_zlg_iwdg_keyvalue_set(p_hw_iwdg, 0xAAAA); amhw_zlg_iwdg_keyvalue_set(p_hw_iwdg, 0xCCCC); return AM_OK; } /** \brief 初始化IWDG,获取标准服务句柄 */ am_wdt_handle_t am_zlg_iwdg_init (am_zlg_iwdg_dev_t *p_dev, const am_zlg_iwdg_devinfo_t *p_devinfo) { if (p_devinfo == NULL) { return NULL; } p_dev->p_devinfo = p_devinfo; p_dev->wdt_serv.p_funcs = (struct am_wdt_drv_funcs *)&__g_iwdg_drv_funcs; p_dev->wdt_serv.p_drv = p_dev; p_dev->div = 4; /* 看门狗平台初始化 */ if (p_devinfo->pfn_plfm_init) { p_devinfo->pfn_plfm_init(); } return &(p_dev->wdt_serv); } /** \brief IWDG解初始化 */ void am_zlg_iwdg_deinit (am_wdt_handle_t handle) { am_zlg_iwdg_dev_t *p_dev = (am_zlg_iwdg_dev_t *)handle; if (NULL == p_dev) { return ; } p_dev->p_devinfo = NULL; p_dev->wdt_serv.p_funcs = NULL; p_dev->wdt_serv.p_drv = NULL; if (p_dev->p_devinfo->pfn_plfm_deinit) { p_dev->p_devinfo->pfn_plfm_deinit(); } } /* end of file */
4,668
C
.c
131
28.832061
81
0.504993
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,479
am_zlg_adc.c
skyformat99_ametal/soc/zlg/drivers/source/adc/am_zlg_adc.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief ADC驱动实现 * * \internal * \par Modification history * - 1.00 17-04-12 ari, first implementation * \endinternal */ #include "am_zlg_adc.h" #include "ametal.h" #include "am_int.h" #include "am_clk.h" #include "hw/amhw_zlg_adc.h" /******************************************************************************* * 私有定义 *******************************************************************************/ #define __ADC_HW_DECL(p_hw_adc, p_drv) \ amhw_zlg_adc_t *p_hw_adc = \ ((am_zlg_adc_dev_t *)p_drv)->p_devinfo->p_hw_adc #define __ADC_VREF_GET(p_drv) (((am_zlg_adc_dev_t *)p_drv)->p_devinfo->vref) /******************************************************************************* * 函数声明 *******************************************************************************/ /** \brief 启动ADC转换 */ static int __fn_adc_start (void *p_drv, int chan, am_adc_buf_desc_t *p_desc, uint32_t desc_num, uint32_t count, uint32_t flags, am_adc_seq_cb_t pfn_callback, void *p_arg); /** \brief 停止转换 */ static int __fn_adc_stop (void *p_drv, int chan); /** \brief 获取ADC的采样率 */ static int __fn_adc_rate_get (void *p_drv, int chan, uint32_t *p_rate); /** \brief 设置ADC的采样率,实际采样率可能存在差异 */ static int __fn_adc_rate_set (void *p_drv, int chan, uint32_t rate); /** \brief 获取ADC转换精度 */ static uint32_t __fn_bits_get (void *p_drv, int chan); /** \brief 获取ADC参考电压 */ static uint32_t __fn_vref_get (void *p_drv, int chan); /** * \brief ADC服务函数 */ static const struct am_adc_drv_funcs __g_adc_drvfuncs = { __fn_adc_start, __fn_adc_stop, __fn_adc_rate_get, __fn_adc_rate_set, __fn_bits_get, __fn_vref_get }; /******************************************************************************/ /** * \brief ADC数据转换完成中断 */ void __adc_irq_handle (void *p_arg) { am_zlg_adc_dev_t *p_dev = (am_zlg_adc_dev_t *)p_arg; amhw_zlg_adc_t *p_hw_adc = NULL; /* 当前转换的序列描述符 */ am_adc_buf_desc_t *p_desc = &(p_dev->p_desc[p_dev->desc_index]); uint16_t *p_buf16 = (uint16_t *)p_desc->p_buf; uint8_t *p_buf8 = (uint8_t *)p_desc->p_buf; uint16_t adc_dat = 0; if ( p_buf16 == NULL) { return ; } p_hw_adc = (amhw_zlg_adc_t *)(p_dev->p_devinfo->adc_reg_base); /* 判断是否当前数据是有效的 */ if (p_dev->conv_cnt < p_desc->length) { /* 从全局数据寄存器中读取数据,以清除中断标志 */ amhw_zlg_adc_data_get (p_hw_adc, &adc_dat); if (p_dev->p_devinfo->bits_mode == AMHW_ZLG_ADC_DATA_VALID_8BIT) { p_buf8[p_dev->conv_cnt] = adc_dat >> p_dev->right_bit; } else { /* 保存数据 */ if (AM_ADC_DATA_ALIGN_LEFT & p_dev->flags) { p_buf16[p_dev->conv_cnt] = adc_dat << 4; } else { p_buf16[p_dev->conv_cnt] = adc_dat >> p_dev->right_bit; } } p_dev->conv_cnt++; /* 判断当前序列描述符是否已经完成转换 */ if (p_dev->conv_cnt >= p_desc->length) { p_dev->conv_cnt = 0; if (NULL != p_desc->pfn_complete) { p_desc->pfn_complete(p_desc->p_arg, AM_OK); } p_dev->desc_index++; /* 判断整个序列描述符是否完成一轮转换 */ if (p_dev->desc_index == p_dev->desc_num) { p_dev->desc_index = 0; if (NULL != p_dev->pfn_callback) { p_dev->pfn_callback(p_dev->p_arg, AM_OK); } p_dev->seq_cnt++; /* 整个序列转换完成 */ if (p_dev->count != 0 && p_dev->seq_cnt == p_dev->count) { p_dev->seq_cnt = 0; if (amhw_zlg_adc_int_tran_complete_check(p_hw_adc)){ amhw_zlg_adc_int_tran_complete_clr(p_hw_adc); } __fn_adc_stop (p_dev, p_dev->chan); /* 关闭模块 */ return ; /* 返回 */ } } } } else { if (NULL != p_dev->pfn_callback) { p_dev->pfn_callback(p_dev->p_arg, AM_ERROR); } if (amhw_zlg_adc_int_tran_complete_check(p_hw_adc)){ amhw_zlg_adc_int_tran_complete_clr(p_hw_adc); } __fn_adc_stop (p_dev, p_dev->chan); } } /** \brief 指向ADC中断连接函数 */ static int __fn_adc_connect (void *p_drv) { am_zlg_adc_dev_t *p_dev = NULL; amhw_zlg_adc_t *p_hw_adc; if (NULL == p_drv) { return -AM_EINVAL; } p_dev = (am_zlg_adc_dev_t *)p_drv; p_hw_adc = (amhw_zlg_adc_t *)p_dev->p_devinfo->adc_reg_base; amhw_zlg_adc_ctrl_reg_set(p_hw_adc, AMHW_ZLG_ADC_INT_EN_MASK); /* 连接转换完成中断 */ am_int_connect(p_dev->p_devinfo->inum, __adc_irq_handle, (void *)p_dev); am_int_enable(p_dev->p_devinfo->inum); return AM_OK; } /** * \brief ADC 使用中断模式时启动配置 */ static void __adc_int_work_startup (am_zlg_adc_dev_t *p_dev, uint32_t chan) { amhw_zlg_adc_t *p_hw_adc = (amhw_zlg_adc_t *)(p_dev->p_devinfo->adc_reg_base); amhw_zlg_adc_ctrl_reg_set(p_hw_adc, AMHW_ZLG_ADC_INT_EN_MASK); amhw_zlg_adc_input_chan_enable(p_hw_adc, chan); amhw_zlg_adc_data_transfer_set(p_hw_adc, AMHW_ZLG_ADC_DATA_TRANSFER_START); } /** * \brief 启动ADC转换 */ static int __fn_adc_start (void *p_drv, int chan, am_adc_buf_desc_t *p_desc, uint32_t desc_num, uint32_t count, uint32_t flags, am_adc_seq_cb_t pfn_callback, void *p_arg) { am_zlg_adc_dev_t *p_dev = NULL; if (NULL == p_drv) { return -AM_EINVAL; } p_dev = (am_zlg_adc_dev_t *)p_drv; p_dev->p_desc = p_desc; p_dev->chan = chan; p_dev->desc_num = desc_num; p_dev->count = count; p_dev->flags = flags; p_dev->pfn_callback = pfn_callback; p_dev->p_arg = p_arg; p_dev->seq_cnt = 0; p_dev->desc_index = 0; p_dev->conv_cnt = 0; am_int_enable(p_dev->p_devinfo->inum); /* 开启中断 */ __adc_int_work_startup(p_dev,chan); /* 中断工作模式启动配置 */ return AM_OK; } /** * \brief 停止转换 */ static int __fn_adc_stop (void *p_drv, int chan) { am_zlg_adc_dev_t *p_dev = (am_zlg_adc_dev_t *)p_drv; amhw_zlg_adc_t *p_hw_adc = (amhw_zlg_adc_t *)(p_dev->p_devinfo->adc_reg_base); if (NULL == p_drv) { return -AM_EINVAL; } amhw_zlg_adc_ctrl_reg_clr(p_hw_adc, AMHW_ZLG_ADC_INT_EN_MASK); amhw_zlg_adc_data_transfer_set(p_hw_adc,AMHW_ZLG_ADC_DATA_TRANSFER_END); am_int_disable(p_dev->p_devinfo->inum); return AM_OK; } /** * \brief 获取ADC的采样率 */ static int __fn_adc_rate_get (void *p_drv, int chan, uint32_t *p_rate) { am_zlg_adc_dev_t *p_dev; amhw_zlg_adc_t *p_hw_adc; uint32_t sample; uint32_t adc_clkdiv = 1; uint32_t i; uint8_t sample_time[8] = { 15, 21, 27, 42, 55, 69, 85, 253 }; if (NULL == p_drv) { return -AM_EINVAL; } p_dev = (am_zlg_adc_dev_t *)p_drv; p_hw_adc = (amhw_zlg_adc_t *)(p_dev->p_devinfo->adc_reg_base); i = amhw_zlg_adc_chan_sample_time_get(p_hw_adc); sample = sample_time[i]; adc_clkdiv = 2 * (amhw_zlg_adc_prescaler_val_get(p_hw_adc) + 1); *p_rate = am_clk_rate_get(p_dev->p_devinfo->clk_num) / (adc_clkdiv * sample); return AM_OK; } /** * \brief 设置ADC的采样率,实际采样率可能存在差异 */ static int __fn_adc_rate_set (void *p_drv, int chan, uint32_t rate) { uint32_t clk; uint32_t temp_rate = 0; uint8_t i = 0, j = 0; uint8_t sample_time[8] = { 15, 21, 27, 42, 55, 69, 85, 253 }; uint32_t rate_high = 0; uint32_t rate_low = 0; uint32_t rate_err = 0; struct adc_err { uint32_t err ; uint8_t sample_time; uint8_t adc_div; }; struct adc_err adc_rate_err; am_zlg_adc_dev_t *p_dev; amhw_zlg_adc_t *p_hw_adc; if (NULL == p_drv) { return -AM_EINVAL; } p_dev = (am_zlg_adc_dev_t *)p_drv; p_hw_adc = (amhw_zlg_adc_t *)(p_dev->p_devinfo->adc_reg_base); adc_rate_err.err = rate; adc_rate_err.sample_time = 0; adc_rate_err.adc_div = 0; clk = am_clk_rate_get(p_dev->p_devinfo->clk_num); rate_high = clk / 15; rate_low = clk / (8 * 253); if (rate < rate_low || rate > rate_high) { return -AM_EINVAL; } for(i = 1; i < 9; i++) { if (rate >= (clk / (i * 253)) && rate <= (clk / (i * 15))) { for(j = 0; j < 8; j++) { temp_rate = (clk / (i * sample_time[j])); rate_err = temp_rate >= rate ? temp_rate - rate : rate - temp_rate; if (rate_err < adc_rate_err.err) { adc_rate_err.err = rate_err; adc_rate_err.adc_div = i; adc_rate_err.sample_time = j; } if (adc_rate_err.err == 0) { break; } } } } amhw_zlg_adc_prescaler_val(p_hw_adc, adc_rate_err.adc_div / 2 - 1); amhw_zlg_adc_chan_sample_time(p_hw_adc, (amhw_zlg_adc_sample_time_t)adc_rate_err.sample_time); return AM_OK; } /** * \brief 获取ADC转换精度 */ static uint32_t __fn_bits_get (void *p_drv, int chan) { am_zlg_adc_dev_t *p_dev = (am_zlg_adc_dev_t *)p_drv; amhw_zlg_adc_t *p_hw_adc = (amhw_zlg_adc_t *)p_dev->p_devinfo->adc_reg_base; uint8_t adc_bit = 12 - amhw_zlg_adc_data_resolution_get(p_hw_adc); if (adc_bit == p_dev->p_devinfo->bits_mode) { return p_dev->p_devinfo->bits_mode; } else { return 0; } } /** * \brief 获取ADC参考电压 */ static uint32_t __fn_vref_get (void *p_drv, int chan) { if (NULL == p_drv) { return 0; /* 资源已经释放,参考电压未知 */ } return (uint32_t)__ADC_VREF_GET(p_drv); } /** * \brief ADC初始化 */ am_adc_handle_t am_zlg_adc_init (am_zlg_adc_dev_t *p_dev, const am_zlg_adc_devinfo_t *p_devinfo) { uint16_t bit = 12; amhw_zlg_adc_t *p_hw_adc = NULL; if (NULL == p_devinfo || NULL == p_dev ) { return NULL; } p_dev->p_devinfo = p_devinfo; p_dev->adc_serve.p_funcs = &__g_adc_drvfuncs; p_dev->adc_serve.p_drv = p_dev; p_dev->pfn_callback = NULL; p_dev->p_desc = NULL; p_dev->p_arg = NULL; p_dev->desc_num = 0; p_dev->flags = 0; p_dev->count = 0; p_dev->chan = 0; p_dev->seq_cnt = 0; p_dev->desc_index = 0; p_dev->conv_cnt = 0; if (p_devinfo->pfn_plfm_init) { p_devinfo->pfn_plfm_init(); } p_hw_adc = (amhw_zlg_adc_t *)(p_dev->p_devinfo->adc_reg_base); /* 设置分辨率 */ amhw_zlg_adc_data_resolution(p_hw_adc, p_dev->p_devinfo->bits_mode); /* * 经证实芯片对于左右对齐功能无效, * 采样率精度为8,9,10,11,12位,芯片采集的数字值都是从11bit位开始对齐 * 如设置为9位精度数据如下: * |_15_~_12_|___9bit_data__|_2_~_0| */ amhw_zlg_adc_align_way_sel(p_hw_adc, 0); bit = __fn_bits_get(p_dev, 0); p_dev->right_bit = 12 - bit; /* 设置采样率 */ __fn_adc_rate_set(p_dev, 0,100000); /* 注册ADC相关中断 */ __fn_adc_connect(p_dev); /* ADC使能 */ amhw_zlg_adc_cgf_reg_set(p_hw_adc, AMHW_ZLG_ADC_MODULE_EN_MASK); return (am_adc_handle_t)(&(p_dev->adc_serve)); } /** * \brief ADC去初始化 */ void am_zlg_adc_deinit (am_adc_handle_t handle) { am_zlg_adc_dev_t *p_dev = (am_zlg_adc_dev_t *)handle; amhw_zlg_adc_t *p_hw_adc = NULL; if (NULL == p_dev) { return ; } p_hw_adc = (amhw_zlg_adc_t *)(p_dev->p_devinfo->adc_reg_base); am_int_disable(p_dev->p_devinfo->inum); amhw_zlg_adc_cgf_reg_clr(p_hw_adc, AMHW_ZLG_ADC_MODULE_EN_MASK); amhw_zlg_adc_ctrl_reg_clr(p_hw_adc, AMHW_ZLG_ADC_INT_EN_MASK); p_dev->adc_serve.p_drv = NULL; if (p_dev->p_devinfo->pfn_plfm_deinit) { p_dev->p_devinfo->pfn_plfm_deinit(); } } /* end of file */
14,141
C
.c
387
26.868217
88
0.456433
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,480
am_zlg_uart.c
skyformat99_ametal/soc/zlg/drivers/source/uart/am_zlg_uart.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief UART 驱动实现 * * \internal * \par Modification history * - 1.00 17-04-10 ari, first implementation * \endinternal */ #include "am_zlg_uart.h" #include "am_clk.h" #include "am_int.h" /******************************************************************************* * Functions declaration *******************************************************************************/ #define __UART_CLK_RATE 24000000 /** * \brief 串口模式(查询或中断)设置 */ int __uart_mode_set (am_zlg_uart_dev_t *p_dev, uint32_t new_mode); /** * \brief 串口硬件设置 */ int __uart_opt_set (am_zlg_uart_dev_t *p_dev, uint32_t opts); /* ZLG 串口驱动函数声明 */ static int __uart_ioctl (void *p_drv, int, void *); static int __uart_tx_startup (void *p_drv); static int __uart_callback_set (void *p_drv, int callback_type, void *pfn_callback, void *p_arg); static int __uart_poll_getchar (void *p_drv, char *p_char); static int __uart_poll_putchar (void *p_drv, char outchar); #if 0 static int __uart_connect (void *p_drv); #endif static void __uart_irq_handler (void *p_arg); /** \brief 标准层接口函数实现 */ static const struct am_uart_drv_funcs __g_uart_drv_funcs = { __uart_ioctl, __uart_tx_startup, __uart_callback_set, __uart_poll_getchar, __uart_poll_putchar, }; /******************************************************************************/ /** * \brief 设备控制函数 * * 其中包含设置获取波特率,模式设置(中断/查询),获取支持的模式,硬件选项设置等功能。 */ static int __uart_ioctl (void *p_drv, int request, void *p_arg) { am_zlg_uart_dev_t *p_dev = (am_zlg_uart_dev_t *)p_drv; amhw_zlg_uart_t *p_hw_uart = (amhw_zlg_uart_t *)p_dev->p_devinfo->uart_reg_base; int status = AM_OK; switch (request) { /* 波特率设置 */ case AM_UART_BAUD_SET: /* 只有在当前传输完成的基础上才允许修改波特率 */ while (amhw_zlg_uart_status_flag_check(p_hw_uart, AMHW_ZLG_UART_TX_COMPLETE_FALG) == AM_FALSE); status = amhw_zlg_uart_baudrate_set(p_hw_uart, am_clk_rate_get(p_dev->p_devinfo->clk_num), (uint32_t)p_arg); if (status > 0) { p_dev->baud_rate = status; status = AM_OK; } else { status = -AM_EIO; } break; /* 波特率获取 */ case AM_UART_BAUD_GET: *(int *)p_arg = p_dev->baud_rate; break; /* 模式设置 */ case AM_UART_MODE_SET: status = (__uart_mode_set(p_dev, (int)p_arg) == AM_OK) ? AM_OK : -AM_EIO; break; /* 模式获取 */ case AM_UART_MODE_GET: *(int *)p_arg = p_dev->channel_mode; break; /* 获取串口可设置的模式 */ case AM_UART_AVAIL_MODES_GET: *(int *)p_arg = AM_UART_MODE_INT | AM_UART_MODE_POLL; break; /* 串口选项设置 */ case AM_UART_OPTS_SET: status = (__uart_opt_set(p_dev, (int)p_arg) == AM_OK) ? AM_OK : -AM_EIO; break; /* 串口选项获取 */ case AM_UART_OPTS_GET: *(int *)p_arg = p_dev->options; break; case AM_UART_RS485_SET: if (p_dev->rs485_en != (am_bool_t)(int)p_arg) { p_dev->rs485_en = (am_bool_t)(int)p_arg; } break; case AM_UART_RS485_GET: *(int *)p_arg = p_dev->rs485_en; break; default: status = -AM_EIO; break; } return (status); } /** * \brief 启动串口发送(仅限中断模式) */ int __uart_tx_startup (void *p_drv) { char data = 0; am_zlg_uart_dev_t *p_dev = (am_zlg_uart_dev_t *)p_drv; amhw_zlg_uart_t *p_hw_uart = (amhw_zlg_uart_t *)p_dev->p_devinfo->uart_reg_base; /* 使能 485 发送控制引脚 */ if (p_dev->rs485_en && p_dev->p_devinfo->pfn_rs485_dir) { p_dev->p_devinfo->pfn_rs485_dir(AM_TRUE); } /* 等待上一次传输完成 */ while (amhw_zlg_uart_status_flag_check(p_hw_uart, AMHW_ZLG_UART_TX_COMPLETE_FALG) == AM_FALSE); /* 获取发送数据并发送 */ if ((p_dev->pfn_txchar_get(p_dev->txget_arg, &data)) == AM_OK) { amhw_zlg_uart_data_write(p_hw_uart, data); } /* 使能发送中断 */ amhw_zlg_uart_int_enable(p_hw_uart, AMHW_ZLG_UART_INT_TX_EMPTY_ENABLE); return AM_OK; } /** * \brief 配置中断服务回调函数 */ static int __uart_callback_set (void *p_drv, int callback_type, void *pfn_callback, void *p_arg) { am_zlg_uart_dev_t *p_dev = (am_zlg_uart_dev_t *)p_drv; switch (callback_type) { /* 设置发送回调函数中的获取发送字符回调函数 */ case AM_UART_CALLBACK_TXCHAR_GET: p_dev->pfn_txchar_get = (am_uart_txchar_get_t)pfn_callback; p_dev->txget_arg = p_arg; return (AM_OK); /* 设置接收回调函数中的存放接收字符回调函数 */ case AM_UART_CALLBACK_RXCHAR_PUT: p_dev->pfn_rxchar_put = (am_uart_rxchar_put_t)pfn_callback; p_dev->rxput_arg = p_arg; return (AM_OK); /* 设置串口异常回调函数 */ case AM_UART_CALLBACK_ERROR: p_dev->pfn_err = (am_uart_err_t)pfn_callback; p_dev->err_arg = p_arg; return (AM_OK); default: return (-AM_ENOTSUP); } } /** * \brief 轮询模式下发送一个字符 */ static int __uart_poll_putchar (void *p_drv, char outchar) { am_zlg_uart_dev_t *p_dev = (am_zlg_uart_dev_t *)p_drv; amhw_zlg_uart_t *p_hw_uart = (amhw_zlg_uart_t *)p_dev->p_devinfo->uart_reg_base; /* 发送模块是否空闲, AM_FALSE:忙; TURE: 空闲 */ if(amhw_zlg_uart_status_flag_check(p_hw_uart, AMHW_ZLG_UART_TX_EMPTY_FLAG) == AM_FALSE) { return (-AM_EAGAIN); } else { if ((p_dev->rs485_en) && (p_dev->p_devinfo->pfn_rs485_dir != NULL)) { /* 设置 485 为发送模式 */ p_dev->p_devinfo->pfn_rs485_dir(AM_TRUE); } /* 发送一个字符 */ amhw_zlg_uart_data_write(p_hw_uart, outchar); if (p_dev->rs485_en && p_dev->p_devinfo->pfn_rs485_dir) { /* 等待发送完成 */ while (!(p_hw_uart->csr & 0x01)); p_dev->p_devinfo->pfn_rs485_dir(AM_FALSE); } } return (AM_OK); } /** * \brief 轮询模式下接收字符 */ static int __uart_poll_getchar (void *p_drv, char *p_char) { am_zlg_uart_dev_t *p_dev = (am_zlg_uart_dev_t *)p_drv; amhw_zlg_uart_t *p_hw_uart = (amhw_zlg_uart_t *)p_dev->p_devinfo->uart_reg_base; uint8_t *p_inchar = (uint8_t *)p_char; /* 接收模块是否空闲,AM_FALSE:忙,正在接收; TURE: 已经接收到一个字符 */ if(amhw_zlg_uart_status_flag_check(p_hw_uart, AMHW_ZLG_UART_RX_VAL_FLAG) == AM_FALSE) { return (-AM_EAGAIN); } else { /* 接收一个字符 */ *p_inchar = amhw_zlg_uart_data_read(p_hw_uart); } return (AM_OK); } /** * \brief 配置串口模式 */ int __uart_mode_set (am_zlg_uart_dev_t *p_dev, uint32_t new_mode) { amhw_zlg_uart_t *p_hw_uart = (amhw_zlg_uart_t *)p_dev->p_devinfo->uart_reg_base; /* 仅支持以下模式 */ if ((new_mode != AM_UART_MODE_POLL) && (new_mode != AM_UART_MODE_INT)) { return (AM_ERROR); } if (new_mode == AM_UART_MODE_INT) { am_int_connect(p_dev->p_devinfo->inum, __uart_irq_handler, (void *)p_dev); am_int_enable(p_dev->p_devinfo->inum); /* 使能RDRF接收准中断 */ amhw_zlg_uart_int_enable(p_hw_uart, AMHW_ZLG_UART_INT_RX_VAL_ENABLE); } else { /* 关闭所有串口中断 */ amhw_zlg_uart_int_disable(p_hw_uart, AMHW_ZLG_UART_INT_ALL_ENABLE_MASK); } p_dev->channel_mode = new_mode; return (AM_OK); } /** * \brief 串口选项配置 */ int __uart_opt_set (am_zlg_uart_dev_t *p_dev, uint32_t options) { amhw_zlg_uart_t *p_hw_uart = (amhw_zlg_uart_t *)p_dev->p_devinfo->uart_reg_base; uint8_t cfg_flags = 0; if (p_dev == NULL) { return -AM_EINVAL; } /* 在改变UART寄存器值前 接收发送禁能 */ amhw_zlg_uart_disable(p_hw_uart); /* 配置数据长度 */ switch (options & AM_UART_CSIZE) { case AM_UART_CS5: cfg_flags |= AMHW_ZLG_UART_DATA_5BIT; break; case AM_UART_CS6: cfg_flags |= AMHW_ZLG_UART_DATA_6BIT; break; case AM_UART_CS7: cfg_flags |= AMHW_ZLG_UART_DATA_7BIT; break; case AM_UART_CS8: cfg_flags |= AMHW_ZLG_UART_DATA_8BIT; break; default: break; } /* 配置停止位 */ if (options & AM_UART_STOPB) { cfg_flags &= ~(0x1 << 2); cfg_flags |= AMHW_ZLG_UART_STOP_2BIT; } else { cfg_flags &= ~(0x1 << 2); cfg_flags |= AMHW_ZLG_UART_STOP_1BIT; } /* 配置检验方式 */ if (options & AM_UART_PARENB) { cfg_flags &= ~(0x3 << 0); if (options & AM_UART_PARODD) { cfg_flags |= AMHW_ZLG_UART_PARITY_ODD; } else { cfg_flags |= AMHW_ZLG_UART_PARITY_EVEN; } } else { cfg_flags &= ~(0x3 << 0); cfg_flags |= AMHW_ZLG_UART_PARITY_NO; } /* 保存和生效配置 */ amhw_zlg_uart_stop_bit_sel(p_hw_uart, (cfg_flags & 0x4)); amhw_zlg_uart_data_length(p_hw_uart, (cfg_flags & 0x30)); amhw_zlg_uart_parity_bit_sel(p_hw_uart, (cfg_flags & 0x3)); amhw_zlg_uart_enable(p_hw_uart); p_dev->options = options; return (AM_OK); } /******************************************************************************* UART interrupt request handler *******************************************************************************/ /** * \brief 串口接收中断服务 */ void __uart_irq_rx_handler (am_zlg_uart_dev_t *p_dev) { amhw_zlg_uart_t *p_hw_uart = (amhw_zlg_uart_t *)p_dev->p_devinfo->uart_reg_base; char data; /* 是否为接收Rx中断 */ if (amhw_zlg_uart_int_flag_check(p_hw_uart,AMHW_ZLG_UART_INT_RX_VAL_FLAG) == AM_TRUE) { amhw_zlg_uart_int_flag_clr(p_hw_uart, AMHW_ZLG_UART_INT_RX_VAL_FLAG_CLR); /* 获取新接收数据 */ data = amhw_zlg_uart_data_read(p_hw_uart); /* 存放新接收数据 */ p_dev->pfn_rxchar_put(p_dev->rxput_arg, data); } } /** * \brief 串口发送中断服务 */ void __uart_irq_tx_handler (am_zlg_uart_dev_t *p_dev) { amhw_zlg_uart_t *p_hw_uart = (amhw_zlg_uart_t *)p_dev->p_devinfo->uart_reg_base; char data; if (amhw_zlg_uart_int_flag_check(p_hw_uart,AMHW_ZLG_UART_INT_TX_EMPTY_FLAG) == AM_TRUE) { amhw_zlg_uart_int_flag_clr(p_hw_uart, AMHW_ZLG_UART_INT_TX_EMPTY_FLAG_CLR); /* 获取发送数据并发送 */ if ((p_dev->pfn_txchar_get(p_dev->txget_arg, &data)) == AM_OK) { amhw_zlg_uart_data_write(p_hw_uart, data); } else { /* 没有数据传送就关闭发送中断 */ amhw_zlg_uart_int_disable(p_hw_uart, AMHW_ZLG_UART_INT_TX_EMPTY_ENABLE); /* 禁能485发送控制引脚 */ if ((p_dev->rs485_en) && (p_dev->p_devinfo->pfn_rs485_dir)) { /* 设置 485 为接收模式 */ p_dev->p_devinfo->pfn_rs485_dir(AM_FALSE); } } } } /** * \brief 串口中断服务函数 */ void __uart_irq_handler (void *p_arg) { am_zlg_uart_dev_t *p_dev = (am_zlg_uart_dev_t *)p_arg; amhw_zlg_uart_t *p_hw_uart = (amhw_zlg_uart_t *)p_dev->p_devinfo->uart_reg_base; uint32_t uart_int_stat = amhw_zlg_uart_int_flag_get(p_hw_uart); if (amhw_zlg_uart_int_flag_check(p_hw_uart,AMHW_ZLG_UART_INT_RX_VAL_FLAG) == AM_TRUE) { __uart_irq_rx_handler(p_dev); } else if (amhw_zlg_uart_int_flag_check(p_hw_uart,AMHW_ZLG_UART_INT_TX_EMPTY_FLAG) == AM_TRUE) { __uart_irq_tx_handler(p_dev); } else { } /* 其他中断 */ if ((p_dev->other_int_enable & uart_int_stat) != 0) { uart_int_stat &= p_dev->other_int_enable; if (p_dev->pfn_err != NULL) { p_dev->pfn_err(p_dev->err_arg, AM_ZLG_UART_ERRCODE_UART_OTHER_INT, (void *)p_hw_uart, 1); } } } #if 0 /** * \brief UART中断函数连接,仅使用中断模式时需要调用此函数 */ int __uart_connect (void *p_drv) { am_zlg_uart_dev_t *p_dev = (am_zlg_uart_dev_t *)p_drv; /* 关联中断向量号,开启中断 */ am_int_connect(p_dev->p_devinfo->inum, __uart_irq_handler, (void *)p_dev); am_int_enable(p_dev->p_devinfo->inum); amhw_zlg_uart_int_enable(p_dev->p_devinfo->uart_reg_base, p_dev->other_int_enable); return AM_OK; } #endif /* 0 */ /** * \brief 默认回调函数 * * \returns AW_ERROR */ static int __uart_dummy_callback (void *p_arg, char *p_outchar) { return (AM_ERROR); } /** * \brief 串口初始化函数 */ am_uart_handle_t am_zlg_uart_init (am_zlg_uart_dev_t *p_dev, const am_zlg_uart_devinfo_t *p_devinfo) { amhw_zlg_uart_t *p_hw_uart; uint32_t tmp; if (p_devinfo == NULL) { return NULL; } /* 获取配置参数 */ p_hw_uart = (amhw_zlg_uart_t *)p_devinfo->uart_reg_base; p_dev->p_devinfo = p_devinfo; p_dev->uart_serv.p_funcs = (struct am_uart_drv_funcs *)&__g_uart_drv_funcs; p_dev->uart_serv.p_drv = p_dev; p_dev->baud_rate = p_devinfo->baud_rate; p_dev->options = 0; /* 初始化默认回调函数 */ p_dev->pfn_txchar_get = (int (*) (void *, char*))__uart_dummy_callback; p_dev->txget_arg = NULL; p_dev->pfn_rxchar_put = (int (*) (void *, char ))__uart_dummy_callback; p_dev->rxput_arg = NULL; p_dev->pfn_err = (int (*) (void *, int, void*, int))__uart_dummy_callback; p_dev->err_arg = NULL; p_dev->other_int_enable = p_devinfo->other_int_enable & ~(AMHW_ZLG_UART_INT_TX_EMPTY_ENABLE | AMHW_ZLG_UART_INT_RX_VAL_ENABLE); p_dev->rs485_en = AM_FALSE; /* 获取串口数据长度配置选项 */ tmp = p_devinfo->cfg_flags; tmp = (tmp >> 4) & 0x03; switch (tmp) { case 0: p_dev->options |= AM_UART_CS5; break; case 1: p_dev->options |= AM_UART_CS6; break; case 2: p_dev->options |= AM_UART_CS7; break; case 3: p_dev->options |= AM_UART_CS8; break; default: p_dev->options |= AM_UART_CS8; break; } /* 开启UART时钟 */ am_clk_enable(p_devinfo->clk_num); /* 获取串口检验方式配置选项 */ tmp = p_devinfo->cfg_flags; tmp = (tmp >> 0) & 0x03; if (tmp == 1) { p_dev->options |= AM_UART_PARENB | AM_UART_PARODD; } else { } /* 获取串口停止位配置选项 */ if (p_devinfo->cfg_flags & (AMHW_ZLG_UART_STOP_2BIT)) { p_dev->options |= AM_UART_STOPB; } else { } /* 等待上一次传输完成 */ while (amhw_zlg_uart_status_flag_check(p_hw_uart, AMHW_ZLG_UART_TX_COMPLETE_FALG) == AM_FALSE); __uart_opt_set (p_dev, p_dev->options); /* 设置波特率 */ p_dev->baud_rate = amhw_zlg_uart_baudrate_set( p_hw_uart, am_clk_rate_get(p_dev->p_devinfo->clk_num), p_devinfo->baud_rate); /* 默认轮询模式 */ __uart_mode_set(p_dev, AM_UART_MODE_POLL); /* uart使能 */ amhw_zlg_uart_rx_enable(p_hw_uart,AM_TRUE); amhw_zlg_uart_tx_enable(p_hw_uart,AM_TRUE); amhw_zlg_uart_enable(p_hw_uart); if (p_dev->p_devinfo->pfn_plfm_init) { p_dev->p_devinfo->pfn_plfm_init(); } if (p_dev->p_devinfo->pfn_rs485_dir) { /* 初始化 485 为接收模式 */ p_dev->p_devinfo->pfn_rs485_dir(AM_FALSE); } return &(p_dev->uart_serv); } /** * \brief 串口去初始化 */ void am_zlg_uart_deinit (am_zlg_uart_dev_t *p_dev) { amhw_zlg_uart_t *p_hw_uart = (amhw_zlg_uart_t *)p_dev->p_devinfo->uart_reg_base; p_dev->uart_serv.p_funcs = NULL; p_dev->uart_serv.p_drv = NULL; if (p_dev->channel_mode == AM_UART_MODE_INT) { /* 默认为轮询模式 */ __uart_mode_set(p_dev, AM_UART_MODE_POLL); } /* 关闭串口 */ amhw_zlg_uart_disable(p_hw_uart); am_int_disable(p_dev->p_devinfo->inum); if (p_dev->p_devinfo->pfn_plfm_deinit) { p_dev->p_devinfo->pfn_plfm_deinit(); } } /* end of file */
17,578
C
.c
493
26.409736
104
0.509152
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,481
amhw_zlg_uart.c
skyformat99_ametal/soc/zlg/drivers/source/uart/hw/amhw_zlg_uart.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief UART操作接口 * * \internal * \par Modification History * - 1.00 17-04-07 ari, first implementation * \endinternal */ #include "hw/amhw_zlg_uart.h" /** * \brief UART数据发送(查询模式) */ uint32_t amhw_zlg_uart_poll_send (amhw_zlg_uart_t *p_hw_uart, const uint8_t *p_txbuf, uint32_t nbytes) { uint32_t len = nbytes; while (len--) { while(amhw_zlg_uart_status_flag_check( p_hw_uart, AMHW_ZLG_UART_TX_EMPTY_FLAG) == AM_FALSE); amhw_zlg_uart_data_write(p_hw_uart, (uint8_t)(*p_txbuf++)); } return nbytes; } /** * \brief UART数据接收(查询模式) */ uint32_t amhw_zlg_uart_poll_receive (amhw_zlg_uart_t *p_hw_uart, uint8_t *p_rxbuf, uint32_t nbytes) { uint32_t len = nbytes; while (len--) { while(amhw_zlg_uart_status_flag_check(p_hw_uart, AMHW_ZLG_UART_RX_VAL_FLAG) == AM_FALSE); *p_rxbuf++ = (uint8_t)amhw_zlg_uart_data_read(p_hw_uart); } return nbytes; } /** * \brief LPUART(Version 0) baud ratio set */ int amhw_zlg_uart_baudrate_set (amhw_zlg_uart_t *p_hw_uart, uint32_t uart_clk, uint32_t baud) { uint32_t int_val = 0; uint32_t deci_val = 0; /* 确保有效的 clock value */ if ((uart_clk > 96000000)) { //todo uart_clk = 0; /* 初始化异常,由于期望的系统时钟值无效 */ return AM_ERROR; } int_val = (uart_clk /baud)/16; deci_val = (uart_clk /baud)%16; amhw_zlg_uart_br_div_mantissa_set(p_hw_uart, int_val); amhw_zlg_uart_br_div_fraction_set(p_hw_uart, deci_val); /* FRA 寄存器需要重新使能 UART 才能生效 */ if (amhw_zlg_uart_uarten_get(p_hw_uart)) { amhw_zlg_uart_disable(p_hw_uart); amhw_zlg_uart_enable(p_hw_uart); } return baud; } /* end of file */
2,830
C
.c
81
24.209877
81
0.432117
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,482
am_zlg116_pwr.c
skyformat99_ametal/soc/zlg/drivers/source/pwr/am_zlg116_pwr.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief PWR drivers implementation * * \internal * \par Modification history * - 1.00 17-04-18 nwt, first implementation * \endinternal */ #include "am_int.h" #include "am_gpio.h" #include "am_vdebug.h" #include "am_arm_nvic.h" #include "am_zlg116_pwr.h" #include "am_zlg116_clk.h" #include "hw/amhw_zlg_exti.h" #include "hw/amhw_zlg_flash.h" #include "hw/amhw_zlg116_rcc.h" #include "zlg116_periph_map.h" /* for ZLG116_FLASH */ #if defined ( __CC_ARM ) #define __ASM __asm /*!< asm keyword for ARM Compiler */ #define __INLINE __inline /*!< inline keyword for ARM Compiler */ #define __STATIC_INLINE static __inline #endif #if defined ( __GNUC__ ) #define __ASM __asm /*!< asm keyword for GNU Compiler */ #define __INLINE inline /*!< inline keyword for GNU Compiler */ #define __STATIC_INLINE static inline #endif #include "core_cmInstr.h" #define __LSI_CLK (40000UL) /** \brief 指向 PWR 电源管理设备的指针 */ am_zlg116_pwr_dev_t *__gp_pwr_dev; /* 内核睡眠函数 */ static void __pwr_cpu_wif (am_bool_t deep) { if (deep) { AMHW_ARM_SCB->scr |= 0x04; } else { AMHW_ARM_SCB->scr &= ~0x04; } AMHW_ARM_SCB->scr &= ~0x02; #ifdef __CC_ARM __ASM("WFI"); #endif #ifdef __GNUC__ __WFI(); #endif } /** * \brief 默认的中断服务函数 */ static void __dummy_isr (void *p_arg) { ; /* VOID */ } #if 0 /** * \brief 设置AHB 预分频 * * \param[in] div :预分频值 * * - 0-7 : 不分频 * - 8 : 2分频 * - 9 : 4分频 * - 10 : 8分频 * - 11 : 16分频 * - 12 : 64分频 * - 13 : 128分频 * - 14 : 256分频 * - 15 : 512分频 * * \return 返回AHB分频值 * */ static uint8_t ___zlg116_rcc_ahb_div_get (void) { return (uint8_t)((AMHW_ZLG116_RCC->cfgr >> 4) & 0xful); } #endif /* 0 */ /* * \brief AHB 总线时钟频率更新 */ static void __sys_clk_ahbfrq_update (int clk_id, uint32_t clk) { uint32_t div = 0; div = am_zlg116_div_get(clk_id); if (div < 8) { am_zlg116_clk_update(clk_id, clk / 1); } else if (div == 8){ am_zlg116_clk_update(clk_id, clk / 2); } else if(div == 9){ am_zlg116_clk_update(clk_id, clk / 4); } else if (div == 10) { am_zlg116_clk_update(clk_id, clk / 8); } else if (div == 11) { am_zlg116_clk_update(clk_id, clk / 16); } else if (div == 12) { am_zlg116_clk_update(clk_id, clk / 64); } else if (div == 13) { am_zlg116_clk_update(clk_id, clk / 128); } else if (div == 14) { am_zlg116_clk_update(clk_id, clk / 256); } else { am_zlg116_clk_update(clk_id, clk / 512); } } /** * \brief 不同功耗模式下时钟转变,支持停止模式与正常模式的 PLL 时钟源的转换 */ static void __sys_clk_change (uint8_t pwr_mode) { const am_zlg116_clk_dev_t *p_clk_dev = am_zlg116_clk_devinfo_get(); uint32_t apb1_div = 0, apb2_div = 0; uint32_t i = 0; /* 计算 APB1 时钟频率 */ apb1_div = 1; for (i = 0; i < (p_clk_dev->p_devinfo->apb1_div & 0x7); i++) { apb1_div = apb1_div << 1; } /* 计算 APB2 时钟频率 */ apb2_div = 1; for (i = 0; i < (p_clk_dev->p_devinfo->apb2_div & 0x7); i++) { apb2_div = apb2_div << 1; } if (pwr_mode == AM_ZLG116_PWR_MODE_STOP) { /* 停机模式使能 LSI 作为系统时钟 */ amhw_zlg116_rcc_lsi_enable(); /* 等待 LSI 时钟就绪 */ while (amhw_zlg116_rcc_lsirdy_read() == AM_FALSE); /* 切换时钟 */ amhw_zlg116_rcc_sys_clk_set(AMHW_ZLG116_SYSCLK_LSI); /* 更新 AHB、APB1、APB2 总线桥的时钟频率 */ __sys_clk_ahbfrq_update(__gp_pwr_dev->p_pwrdevinfo->ahb_clk_num, __LSI_CLK); am_zlg116_clk_update(__gp_pwr_dev->p_pwrdevinfo->apb1_clk_num, p_clk_dev->ahb_clk / apb1_div); am_zlg116_clk_update(__gp_pwr_dev->p_pwrdevinfo->apb2_clk_num, p_clk_dev->ahb_clk / apb2_div); } if (pwr_mode == AM_ZLG116_PWR_MODE_RUN) { if (p_clk_dev->p_devinfo->pllin_src == AMHW_ZLG116_PLLCLK_HSE) { amhw_zlg116_rcc_hseon_enable (); while (amhw_zlg116_rcc_hserdy_read () == AM_FALSE); } else { amhw_zlg116_rcc_hsion_enable(); while (amhw_zlg116_rcc_hsirdy_read () == AM_FALSE); } /* 设置 FLASH 延迟间隔 */ ZLG116_FLASH->acr &= ~0x07; ZLG116_FLASH->acr |= 0x31; amhw_zlg116_rcc_pll_enable(); while (amhw_zlg116_rcc_pllrdy_read() == AM_FALSE); /* 系统时钟选为 PLL */ amhw_zlg116_rcc_sys_clk_set(AMHW_ZLG116_SYSCLK_PLL); /* 在正常模式下禁能 LSI 作为系统时钟 */ amhw_zlg116_rcc_lsi_disable(); /* 更新 AHB、APB1、APB2 总线桥的时钟频率 */ __sys_clk_ahbfrq_update(__gp_pwr_dev->p_pwrdevinfo->ahb_clk_num, p_clk_dev->pllout_clk); am_zlg116_clk_update(__gp_pwr_dev->p_pwrdevinfo->apb1_clk_num, p_clk_dev->ahb_clk / apb1_div); am_zlg116_clk_update(__gp_pwr_dev->p_pwrdevinfo->apb2_clk_num, p_clk_dev->ahb_clk / apb2_div); } if (pwr_mode == AM_ZLG116_PWR_MODE_STANBY) { /* 待机模式使能 HSI 作为系统时钟 */ amhw_zlg116_rcc_hsion_enable(); /* 等待 HSI 时钟就绪 */ while (amhw_zlg116_rcc_hsirdy_read() == AM_FALSE); /* 系统时钟选为 HSI */ amhw_zlg116_rcc_sys_clk_set(AMHW_ZLG116_SYSCLK_HSI_DIV6); /* 失能 PLL */ amhw_zlg116_rcc_pll_disable(); /* 失能 LSI */ amhw_zlg116_rcc_lsi_disable(); /* 更新 AHB、APB1、APB2 总线桥的时钟频率 */ __sys_clk_ahbfrq_update(__gp_pwr_dev->p_pwrdevinfo->ahb_clk_num, p_clk_dev->ahb_clk); am_zlg116_clk_update(__gp_pwr_dev->p_pwrdevinfo->apb1_clk_num, p_clk_dev->ahb_clk / p_clk_dev->p_devinfo->apb1_div); am_zlg116_clk_update(__gp_pwr_dev->p_pwrdevinfo->apb2_clk_num, p_clk_dev->ahb_clk / p_clk_dev->p_devinfo->apb2_div); } } /** * \brief PWR 初始化 */ am_zlg116_pwr_handle_t am_zlg116_pwr_init (am_zlg116_pwr_dev_t *p_dev, const am_zlg116_pwr_devinfo_t *p_devinfo) { if (p_dev == NULL || p_devinfo == NULL) { return NULL; } /* PWR 平台初始化 */ if (p_devinfo->pfn_plfm_init) { p_devinfo->pfn_plfm_init(); } p_dev->p_pwrdevinfo = p_devinfo; /* 取得当前的 PWR 模式,初始化默认为运行模式 */ p_dev->pwr_mode = AM_ZLG116_PWR_MODE_RUN; __gp_pwr_dev = p_dev; return p_dev; } /** * \brief 解除 PWR 初始化 */ void am_zlg116_pwr_deinit (void) { const am_zlg116_pwr_devinfo_t *p_pwr_devinfo = __gp_pwr_dev->p_pwrdevinfo; if (__gp_pwr_dev == NULL || p_pwr_devinfo== NULL) { return; } __gp_pwr_dev->pwr_mode = AM_ZLG116_PWR_MODE_RUN; __gp_pwr_dev->p_pwrdevinfo = NULL; __gp_pwr_dev = NULL; /* PWR 平台解初始化 */ if (p_pwr_devinfo->pfn_plfm_deinit) { p_pwr_devinfo->pfn_plfm_deinit(); } } /** * \brief 配置系统模式 * * \note 这个唤醒的配置的 PWR 模式必须与 am_zlg116_pwr_mode_into 函数的选择 PWR * 模式相同,在 AM_ZLG116_PWR_MODE_STANBY 模式下,唤醒会复位,注册中断唤醒 * 函数回调函数不起作用 */ void am_zlg116_wake_up_cfg (am_zlg116_pwr_mode_t mode, am_pfnvoid_t pfn_callback, void *p_arg) { am_zlg116_pwr_mode_t cur_mode = am_zlg116_pwr_mode_get(); if (cur_mode == mode) { return ; } switch (mode) { case AM_ZLG116_PWR_MODE_RUN: /* 运行模式 */ __gp_pwr_dev->pwr_mode = AM_ZLG116_PWR_MODE_RUN; break; case AM_ZLG116_PWR_MODE_SLEEP: /* 睡眠运行模式 */ if (pfn_callback != NULL) { /* 连接引脚中断服务函数 */ am_gpio_trigger_connect(__gp_pwr_dev->p_pwrdevinfo->p_pwr_mode[mode - 1].pin, pfn_callback, p_arg); /* 配置引脚中断触发方式 */ am_gpio_trigger_cfg(__gp_pwr_dev->p_pwrdevinfo->p_pwr_mode[mode - 1].pin, AM_GPIO_TRIGGER_RISE); /* 使能引脚触发中断 */ am_gpio_trigger_on(__gp_pwr_dev->p_pwrdevinfo->p_pwr_mode[mode - 1].pin); } break; case AM_ZLG116_PWR_MODE_STOP: /* 停止模式 */ if (pfn_callback != NULL) { /* 连接引脚中断服务函数 */ am_gpio_trigger_connect(__gp_pwr_dev->p_pwrdevinfo->p_pwr_mode[mode - 1].pin, pfn_callback, p_arg); /* 配置引脚中断触发方式 */ am_gpio_trigger_cfg(__gp_pwr_dev->p_pwrdevinfo->p_pwr_mode[mode - 1].pin, AM_GPIO_TRIGGER_RISE); /* 使能引脚触发中断 */ am_gpio_trigger_on(__gp_pwr_dev->p_pwrdevinfo->p_pwr_mode[mode - 1].pin); } break; case AM_ZLG116_PWR_MODE_STANBY: /* 待机模式 */ if (-1 == __gp_pwr_dev->p_pwrdevinfo->p_pwr_mode[mode - 1].pin) { break; } /* 连接引脚中断服务函数 */ am_gpio_trigger_connect(__gp_pwr_dev->p_pwrdevinfo->p_pwr_mode[mode - 1].pin, __dummy_isr, p_arg); /* 配置引脚中断触发方式 */ am_gpio_trigger_cfg(__gp_pwr_dev->p_pwrdevinfo->p_pwr_mode[mode - 1].pin, AM_GPIO_TRIGGER_RISE); /* 使能引脚触发中断 */ am_gpio_trigger_on(__gp_pwr_dev->p_pwrdevinfo->p_pwr_mode[mode - 1].pin); break; default: break; } } /** * \brief 配置系统模式 */ int am_zlg116_pwr_mode_into (am_zlg116_pwr_mode_t mode) { amhw_zlg_pwr_t *p_hw_pwr = NULL; am_zlg116_pwr_mode_t cur_mode = am_zlg116_pwr_mode_get(); int wkup_pin = __gp_pwr_dev->p_pwrdevinfo->p_pwr_mode[mode - 1].pin; if (cur_mode == mode) { return AM_OK; } p_hw_pwr = (amhw_zlg_pwr_t *)__gp_pwr_dev->p_pwrdevinfo->pwr_regbase; switch (mode) { case AM_ZLG116_PWR_MODE_RUN: /* 运行模式 */ __gp_pwr_dev->pwr_mode = AM_ZLG116_PWR_MODE_RUN; break; case AM_ZLG116_PWR_MODE_SLEEP: /* 睡眠模式 */ if (cur_mode != AM_ZLG116_PWR_MODE_RUN) { return -AM_EPERM; } __gp_pwr_dev->pwr_mode = AM_ZLG116_PWR_MODE_SLEEP; AM_DBG_INFO("enter sleep!\r\n"); __pwr_cpu_wif(AM_FALSE); /* 唤醒重置模式 */ __gp_pwr_dev->pwr_mode = AM_ZLG116_PWR_MODE_RUN; break; case AM_ZLG116_PWR_MODE_STOP: /* 停止模式 */ if (cur_mode != AM_ZLG116_PWR_MODE_RUN) { return -AM_EPERM; } __gp_pwr_dev->pwr_mode = AM_ZLG116_PWR_MODE_STOP; /* 注意: 电压调节器可能开启,进入停机状态并没有关停 */ amhw_zlg_pwr_pdds_mode_set(p_hw_pwr, AM_ZLG_PDDS_STOP_MODE); __sys_clk_change(AM_ZLG116_PWR_MODE_STOP); /* CPU进入深度睡眠模式 */ __pwr_cpu_wif(AM_TRUE); /* 停止模式唤醒后恢复时钟 */ __sys_clk_change(AM_ZLG116_PWR_MODE_RUN); /* 唤醒重置模式 */ __gp_pwr_dev->pwr_mode = AM_ZLG116_PWR_MODE_RUN; break; case AM_ZLG116_PWR_MODE_STANBY: /* 待机模式 */ if (cur_mode != AM_ZLG116_PWR_MODE_RUN) { return -AM_EPERM; } __gp_pwr_dev->pwr_mode = AM_ZLG116_PWR_MODE_STANBY; /* 进入待机模式之前 WKUP 引脚必须为低电平 */ if (wkup_pin != -1) { /* 失能 WKUP 引脚 */ amhw_zlg_wake_up_enable(p_hw_pwr, AM_ZLG_WAKEUP_DISABLE); /* 将 WKUP 配置为输入,并检测是否为高电平 */ am_gpio_pin_cfg(wkup_pin, AM_GPIO_INPUT | AM_GPIO_PULLDOWN); if (am_gpio_get(wkup_pin)) { return -AM_ENOTSUP; } /* 使能 WAKE_UP 引脚 */ amhw_zlg_wake_up_enable(p_hw_pwr, AM_ZLG_WAKEUP_ENABLE); } amhw_zlg_pwr_stauts_flag_clear(p_hw_pwr, AM_ZLG_WAKEUP_FLAG_CLEAR); amhw_zlg_pwr_pdds_mode_set(p_hw_pwr, AM_ZLG_PDDS_STANDBY_MODE); /* 待机模式使用 HSI 作为系统时钟 */ __sys_clk_change(AM_ZLG116_PWR_MODE_STANBY); /* CPU 进入待机模式 */ __pwr_cpu_wif(AM_TRUE); /* 恢复时钟源,不应该执行到这里,因为待机模式唤醒之后芯片会直接复位 */ __sys_clk_change(AM_ZLG116_PWR_MODE_RUN); /* 唤醒重置模式 */ __gp_pwr_dev->pwr_mode = AM_ZLG116_PWR_MODE_RUN; break; default: break; } return AM_OK; } /** * \brief 获取 PWR 模式 */ am_zlg116_pwr_mode_t am_zlg116_pwr_mode_get (void) { /* 低功耗运行模式 */ return __gp_pwr_dev->pwr_mode; } /** * \brief 配置 PVD 电压检测信息 */ int am_zlg116_pwr_pvd_cfg (am_zlg116_pwr_handle_t pwr_handle, am_pfnvoid_t pfn_callback, void *p_arg) { amhw_zlg_pwr_t *p_hw_pwr = NULL; amhw_zlg_exti_t *p_hw_exti = NULL; am_zlg116_pwr_mode_t cur_mode = am_zlg116_pwr_mode_get(); if(pwr_handle == NULL) { return -AM_EINVAL; } /* 待机模式及停止模式由 CPU 内核停止不支持 PVD 电压检测 */ if (cur_mode == AM_ZLG116_PWR_MODE_STOP || cur_mode == AM_ZLG116_PWR_MODE_STANBY ) { return AM_ERROR; } p_hw_pwr = (amhw_zlg_pwr_t *)__gp_pwr_dev->p_pwrdevinfo->pwr_regbase; p_hw_exti = (amhw_zlg_exti_t *)__gp_pwr_dev->p_pwrdevinfo->exti_regbase; if (pwr_handle->p_pwrdevinfo->p_pvd_info->enable) { amhw_zlg_pwr_pvd_detect_enable(p_hw_pwr, AM_ZLG_PVDE_ENABLE); amhw_zlg_pvd_lever_set(p_hw_pwr, pwr_handle->p_pwrdevinfo->p_pvd_info->pvd_v_level); /* 清除中断线配置,PVD 对应于 AMHW_ZLG116_LINE_NUM16 */ amhw_zlg_exti_imr_clear(p_hw_exti, AMHW_ZLG_EXTI_LINE_NUM16); amhw_zlg_exti_emr_clear(p_hw_exti, AMHW_ZLG_EXTI_LINE_NUM16); /* 清除中断线触发方式配置,PVD 对应于 AMHW_ZLG116_LINE_NUM16 */ amhw_zlg_exti_rtsr_clear(p_hw_exti, AMHW_ZLG_EXTI_LINE_NUM16); amhw_zlg_exti_ftsr_clear(p_hw_exti, AMHW_ZLG_EXTI_LINE_NUM16); if (pwr_handle->p_pwrdevinfo->p_pvd_info->pvd_mode == 0) { /* 上升沿触发(表示电压从高下降到低于设定阀值时产生中断),PVD 对应于 AMHW_ZLG116_LINE_NUM16 */ amhw_zlg_exti_rtsr_set(p_hw_exti, AMHW_ZLG_EXTI_LINE_NUM16); } else if (pwr_handle->p_pwrdevinfo->p_pvd_info->pvd_mode == 1) { /* 下降沿触发(表示电压从低上升到高于设定阀值时产生中断),PVD 对应于 AMHW_ZLG116_LINE_NUM16 */ amhw_zlg_exti_ftsr_set(p_hw_exti, AMHW_ZLG_EXTI_LINE_NUM16); } else { /* 双边沿触发(表示电压上升或下降越过设定阀值时都产生中断),PVD 对应于 AMHW_ZLG116_LINE_NUM16 */ amhw_zlg_exti_rtsr_set(p_hw_exti, AMHW_ZLG_EXTI_LINE_NUM16); amhw_zlg_exti_ftsr_set(p_hw_exti, AMHW_ZLG_EXTI_LINE_NUM16); } /* 清 PVD 中断线标志位,PVD 对应于 AMHW_ZLG116_LINE_NUM16 */ amhw_zlg_exti_pending_clear(p_hw_exti, AMHW_ZLG_EXTI_LINE_NUM16); /* 设置开放中断线请求 , PVD 对应于 AMHW_ZLG116_LINE_NUM16 */ amhw_zlg_exti_imr_set(p_hw_exti, AMHW_ZLG_EXTI_LINE_NUM16); /* * 连接用户注册的中断回调函数 */ if (pfn_callback != NULL) { /* 中断连接并使能 */ am_int_connect(__gp_pwr_dev->p_pwrdevinfo->inum, pfn_callback, (void *)p_arg); am_int_enable(__gp_pwr_dev->p_pwrdevinfo->inum); } } else { /* 清 PVD 中断线标志位,PVD 对应于 AMHW_ZLG116_LINE_NUM16 */ amhw_zlg_exti_pending_clear(p_hw_exti, AMHW_ZLG_EXTI_LINE_NUM16); /* 设置禁止中断线请求 , PVD 对应于 AMHW_ZLG116_LINE_NUM16 */ amhw_zlg_exti_imr_clear(p_hw_exti, AMHW_ZLG_EXTI_LINE_NUM16); /* 禁能 NVIC 中断 */ am_int_disable(__gp_pwr_dev->p_pwrdevinfo->inum); } return AM_OK; } /* end of file */
17,026
C
.c
434
28.56682
104
0.527159
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,483
amhw_zlg116_rcc.c
skyformat99_ametal/soc/zlg/drivers/source/rcc/hw/amhw_zlg116_rcc.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief RCC * * 驱动直接使用了 ZLG116 外设寄存器基地址, 因此,该驱动仅适用于 ZLG116 * * \internal * \par Modification History * - 1.00 17-04-17 sdy, first implementation * \endinternal */ #include "hw/amhw_zlg116_rcc.h" /* 使能或禁能外设 */ static void __rcc_ahb_cmd (amhw_zlg116_ahb_peripheral peri, uint8_t cmd) { uint32_t tempa = 0; uint32_t tempb = 0; tempa = ZLG116_RCC->ahbenr; tempb = 0x0f000000 & tempa; tempb = tempb >> 7; tempa = 0x000000ff & tempa; tempa = tempa | tempb; if (cmd) { tempa = (1ul << peri) | tempa; } else { tempa = (~(1ul << peri)) & tempa; } ZLG116_RCC->ahbenr = tempa; } /** * \brief 使能AHB外设 * * \param[in] peri :需要使能的外设 * * \return 无 * */ void amhw_zlg116_rcc_ahb_enable (amhw_zlg116_ahb_peripheral peri) { __rcc_ahb_cmd(peri, 1); } /** * \brief 禁能AHB外设 * * \param[in] peri :需要禁能的外设 * * \return 无 * */ void amhw_zlg116_rcc_ahb_disable (amhw_zlg116_ahb_peripheral peri) { __rcc_ahb_cmd(peri, 0); } /* end of file */
1,622
C
.c
65
20.353846
81
0.495946
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,484
am_zlg_crc.c
skyformat99_ametal/soc/zlg/drivers/source/crc/am_zlg_crc.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief CRC驱动实现 * * 只能支持4字节对齐的序列计算 * 即: 序列的字节数 % 4 == 0 * * \internal * \par Modification history * - 1.00 17-08-30 fra, first implementation * \endinternal */ #include "ametal.h" #include "am_zlg_crc.h" #include "hw/amhw_zlg_crc.h" /******************************************************************************* * 模块内函数声明 *******************************************************************************/ /** \biref 按位倒序 10100->00101 */ static uint8_t __rev8bit(uint8_t data); /******************************************************************************* * CRC驱动函数声明 *******************************************************************************/ /** \biref 根据CRC模型初始化CRC,为CRC计算做好准备 */ static int __crc_init (void *p_cookie, am_crc_pattern_t *p_pattern); /** \brief CRC计算 */ static int __crc_cal (void *p_cookie,const uint8_t *p_data, uint32_t nbytes); /** \brief 获取CRC计算结果 */ static int __crc_final (void *p_cookie, uint32_t *p_value); /** * \brief CRC服务函数 */ static const struct am_crc_drv_funcs __g_crc_drvfuncs = { __crc_init, __crc_cal, __crc_final }; /******************************************************************************/ /** * \brief 按位倒序 10100->00101 */ static uint8_t __rev8bit (uint8_t data) { uint8_t revdata = 0; uint8_t index = 0; revdata |= ((data >> index) & 0x01); for (index = 1; index < 8; index++) { revdata <<= 1; revdata |= ((data >> index) & 0x01); } return revdata; } /******************************************************************************/ /** * \brief 初始化CRC */ static int __crc_init (void *p_cookie, am_crc_pattern_t *p_pattern) { am_zlg_crc_dev_t *p_dev = (am_zlg_crc_dev_t *)p_cookie; amhw_zlg_crc_t *p_hw_crc = NULL; if (p_dev == NULL || p_pattern == NULL) { return -AM_EINVAL; } if (p_pattern->poly != 0x04C11DB7 || p_pattern->width != 32 || p_pattern->initvalue != 0xFFFFFFFF ) { return -AM_ENOTSUP; } p_dev->p_pattern = p_pattern; p_hw_crc = (amhw_zlg_crc_t *)(p_dev->p_devinfo->crc_reg_base); /* 重置寄存器CRC_DATA 为0xFFFF FFFF */ amhw_zlg_crc_reset(p_hw_crc); return AM_OK; } /** * \brief CRC计算 */ static int __crc_cal (void *p_cookie, const uint8_t *p_data, uint32_t nbytes) { uint32_t i; uint32_t tdata; am_zlg_crc_dev_t *p_dev = (am_zlg_crc_dev_t *)p_cookie; amhw_zlg_crc_t *p_hw_crc = (amhw_zlg_crc_t *)(p_dev->p_devinfo->crc_reg_base); if (p_dev->p_pattern == NULL || p_data == NULL) { return -AM_EINVAL; } if (nbytes % 4 != 0) { return -AM_ENOTSUP; } for (i = 0; i < nbytes; i+=4) { if (p_dev->p_pattern->refin == AM_TRUE) { /* 输入的每一个字节都进行位倒置 */ tdata = (__rev8bit(p_data[i]) << 24) | (__rev8bit(p_data[i+1]) << 16) | (__rev8bit(p_data[i+2]) << 8) | __rev8bit(p_data[i+3]); } else { tdata = (p_data[i] << 24) | (p_data[i+1] << 16) | (p_data[i+2] << 8) | p_data[i+3]; } amhw_zlg_crc_32bit_write_data(p_hw_crc, tdata); } return AM_OK; } /** * \brief 获取CRC计算结果 */ static int __crc_final (void *p_cookie, uint32_t *p_value) { am_zlg_crc_dev_t *p_dev = (am_zlg_crc_dev_t *)p_cookie; amhw_zlg_crc_t *p_hw_crc = (amhw_zlg_crc_t *)(p_dev->p_devinfo->crc_reg_base); if (p_dev->p_pattern == NULL) { return -AM_EINVAL; } *p_value = amhw_zlg_crc_32bit_read_data(p_hw_crc); if (p_dev->p_pattern->refout == AM_TRUE){ /* 计算结果进行倒置 */ *p_value = (__rev8bit((uint8_t)(*p_value & 0x000000ff)) << 24) | (__rev8bit((uint8_t)((*p_value & 0x0000ff00) >> 8 )) << 16) | (__rev8bit((uint8_t)((*p_value & 0x00ff0000) >> 16)) << 8 ) | __rev8bit((uint8_t)((*p_value & 0xff000000) >> 24)); } /* 计算结果与xorout异或 */ *p_value ^= p_dev->p_pattern->xorout; p_dev->p_pattern = NULL; return AM_OK; } /** * \brief CRC初始化 */ am_crc_handle_t am_zlg_crc_init (am_zlg_crc_dev_t *p_dev, const am_zlg_crc_devinfo_t *p_devinfo) { if (p_dev == NULL || p_devinfo == NULL) { return NULL; } p_dev->p_devinfo = p_devinfo; p_dev->p_pattern = NULL; p_dev->crc_serve.p_funcs = (struct am_crc_drv_funcs *)&__g_crc_drvfuncs; p_dev->crc_serve.p_drv = p_dev; if (p_dev->p_devinfo->pfn_plfm_init) { p_dev->p_devinfo->pfn_plfm_init(); } return &(p_dev->crc_serve); } /** * \brief CRC解初始化 */ void am_zlg_crc_deinit (am_crc_handle_t handle) { am_zlg_crc_dev_t *p_dev = (am_zlg_crc_dev_t *)handle; if (NULL == handle) { return ; } p_dev->p_pattern = NULL; p_dev->crc_serve.p_funcs = NULL; p_dev->crc_serve.p_drv = NULL; if (p_dev->p_devinfo->pfn_plfm_deinit) { p_dev->p_devinfo->pfn_plfm_deinit(); } } /* end of file */
5,807
C
.c
170
27.517647
87
0.464041
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,485
am_zlg116_gpio.c
skyformat99_ametal/soc/zlg/drivers/source/gpio/am_zlg116_gpio.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief GPIO implementation * * - GPIO pins can be configured as input or output by software. * - All GPIO pins default to inputs with interrupt disabled at reset. * - Pin registers allow pins to be sensed and set individually. * * \internal * \par Modification history * - 1.00 17-04-07 nwt,first implementation * \endinternal */ #include "am_zlg116_gpio.h" #include "am_zlg116_gpio_util.h" #include "am_gpio_util.h" #include "am_gpio.h" #include "am_int.h" #include "am_bitops.h" /******************************************************************************* * 私有定义 *******************************************************************************/ /** \brief 中断未连接标识 */ #define AM_ZLG116_GPIO_INVALID_PIN_MAP 0xFF /** \brief 定义指向GPIO设备信息的指针 */ #define __GPIO_DEVINFO_DECL(p_gpio_devinfo, p_dev) \ const am_zlg116_gpio_devinfo_t *p_gpio_devinfo = p_dev->p_devinfo /****************************************************************************** 全局变量 ******************************************************************************/ /** \bruef 指向GPIO设备的指针 */ am_zlg116_gpio_dev_t *__gp_gpio_dev; /******************************************************************************* 公共函数 *******************************************************************************/ /** * \brief 引脚功能配置 * * \param[in] pin : 引脚编号,值为 PIO* (#PIOA_0) * \param[in] flags : 引脚功能 * * \return AM_OK :配置成功 */ int am_gpio_pin_cfg (int pin, uint32_t flags) { __GPIO_DEVINFO_DECL(p_gpio_devinfo, __gp_gpio_dev); /* IO口方向 */ uint8_t dir = 0; uint32_t func = 0, mode = 0; uint32_t iocon_cfg = 0; amhw_zlg_gpio_t *p_hw_gpio = NULL; if (__gp_gpio_dev == NULL) { return -AM_ENXIO; } p_hw_gpio = (amhw_zlg_gpio_t*)p_gpio_devinfo->gpio_regbase; func = AM_GPIO_COM_FUNC_GET(flags); mode = AM_GPIO_COM_MODE_GET(flags) << 3; /* * 共有功能配置 */ if (func != 0x00) { /* 表明不需要再设置方向 */ flags &= ~AM_ZLG116_GPIO_DIR; /* 表明不需要再设置引脚复用功能,仅使用GPIO功能 */ flags &= ~AM_ZLG116_GPIO_FUNEN; if (amhw_zlg_gpio_pin_afr_get(p_hw_gpio, pin) != AMHW_ZLG_GPIO_AF_DEFAULT) { /* 复用功能回到默认状态,表明使用GPIO功能 */ amhw_zlg_gpio_pin_afr_set(p_hw_gpio, AMHW_ZLG_GPIO_AF_DEFAULT, pin); } switch (func) { case AM_GPIO_INPUT: AM_BITS_SET(iocon_cfg, 0, 2, 0X00); break; case AM_GPIO_OUTPUT_INIT_HIGH: amhw_zlg_gpio_pin_out_high(p_hw_gpio, pin); /* 输出时,若未配置管脚速率则默认为 10MHz */ if ((flags & AM_ZLG116_GPIO_OUTRES_RATE) == 0) { AM_BITS_SET(iocon_cfg, 0, 2, AMHW_ZLG_GPIO_SPEED_10MHz); } dir = 1; break; case AM_GPIO_OUTPUT_INIT_LOW: amhw_zlg_gpio_pin_out_low(p_hw_gpio, pin); /* 输出时,若未配置管脚速率则默认为 10MHz */ if ((flags & AM_ZLG116_GPIO_OUTRES_RATE) == 0) { AM_BITS_SET(iocon_cfg, 0, 2, AMHW_ZLG_GPIO_SPEED_10MHz); } dir = 1; break; default: break; } } if (mode != 0x00) { switch (mode) { case AM_GPIO_PULLUP: if (dir != 1) { /* 使OD位置为1, 表明是上拉 */ amhw_zlg_gpio_pin_out_high(p_hw_gpio, pin); AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_IPU); } else { AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_OUT_PP); } break; case AM_GPIO_PULLDOWN: if (dir != 1) { /* 使OD位置为0, 表明是下拉 */ amhw_zlg_gpio_pin_out_low(p_hw_gpio, pin); AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_IPD); } else { AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_OUT_PP); } break; case AM_GPIO_FLOAT: if (dir != 1) { AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_IN_FLOATING); } else { AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_OUT_OD); } break; case AM_GPIO_OPEN_DRAIN: if (dir == 0) { AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_IN_FLOATING); } else { AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_OUT_OD); } break; case AM_GPIO_PUSH_PULL: if (dir == 0) { AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_IPU); } else { AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_OUT_PP); } break; default: return -AM_ENOTSUP; } } /* * 平台相关配置 */ /* 管脚的模式 */ if ((flags & AM_ZLG116_GPIO_MODE) != 0) { switch (AM_ZLG116_GPIO_MODE_GET(flags)) { case 0: AM_BITS_SET(iocon_cfg, 0, 2, 0x00); AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_AIN); break; case 1: AM_BITS_SET(iocon_cfg, 0, 2, 0x00); AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_IN_FLOATING); break; case 2: /* 使OD位置为0, 表明是下拉 */ amhw_zlg_gpio_pin_out_low(p_hw_gpio, pin); AM_BITS_SET(iocon_cfg, 0, 2, 0x00); AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_IPD); break; case 3: /* 使OD位置为1, 表明是上拉 */ amhw_zlg_gpio_pin_out_high(p_hw_gpio, pin); AM_BITS_SET(iocon_cfg, 0, 2, 0x00); AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_IPU); break; case 4: AM_BITS_SET(iocon_cfg, 0, 2, AMHW_ZLG_GPIO_SPEED_10MHz); AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_OUT_PP); break; case 5: AM_BITS_SET(iocon_cfg, 0, 2, AMHW_ZLG_GPIO_SPEED_10MHz); AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_OUT_OD); break; case 6: AM_BITS_SET(iocon_cfg, 0, 2, AMHW_ZLG_GPIO_SPEED_10MHz); AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_AF_PP); break; case 7: AM_BITS_SET(iocon_cfg, 0, 2, AMHW_ZLG_GPIO_SPEED_10MHz); AM_BITS_SET(iocon_cfg, 2, 2, AMHW_ZLG_GPIO_MODE_AF_OD); break; default: return -AM_ENOTSUP; } } /* 设置管脚的输出速率 */ if ((flags & AM_ZLG116_GPIO_OUTRES_RATE) != 0) { AM_BITS_SET(iocon_cfg, 0, 2, AM_ZLG116_GPIO_OUTRES_RATE_GET(flags)); } /* 设置复用功能时管脚模式 */ amhw_zlg_gpio_pin_set(p_hw_gpio, iocon_cfg, pin); /* 设置管脚的复用功能 */ if ((flags & AM_ZLG116_GPIO_FUNEN) != 0) { amhw_zlg_gpio_pin_afr_set(p_hw_gpio, AM_ZLG116_GPIO_FUNC_GET(flags), pin); } return AM_OK; } /** * \brief 获取引脚状态 * * \param[in] pin : 引脚编号,值为 PIO* (#PIOA_0) * * \return 无 */ int am_gpio_get (int pin) { __GPIO_DEVINFO_DECL(p_gpio_devinfo, __gp_gpio_dev); amhw_zlg_gpio_t *p_hw_gpio = (amhw_zlg_gpio_t *)p_gpio_devinfo->gpio_regbase; return amhw_zlg_gpio_pin_get(p_hw_gpio, pin); } /** * \brief 设置输出引脚状态 * * \param[in] pin : 引脚编号,值为 PIO* (#PIOA_0) * \param[in] value : 引脚值 * * \return AM_OK :设置成功 */ int am_gpio_set (int pin, int value) { __GPIO_DEVINFO_DECL(p_gpio_devinfo, __gp_gpio_dev); amhw_zlg_gpio_t *p_hw_gpio = (amhw_zlg_gpio_t *)p_gpio_devinfo->gpio_regbase; if (value == 0) { amhw_zlg_gpio_pin_out_low(p_hw_gpio, pin); } else { amhw_zlg_gpio_pin_out_high(p_hw_gpio, pin); } return AM_OK; } /** * \brief 引脚输出状态反转 */ int am_gpio_toggle (int pin) { __GPIO_DEVINFO_DECL(p_gpio_devinfo, __gp_gpio_dev); amhw_zlg_gpio_t *p_hw_gpio = (amhw_zlg_gpio_t *)p_gpio_devinfo->gpio_regbase; amhw_zlg_gpio_pin_toggle(p_hw_gpio, pin); return AM_OK; } /** * \brief 引脚触发形式设置 */ int am_gpio_trigger_cfg (int pin, uint32_t flag) { __GPIO_DEVINFO_DECL(p_gpio_devinfo, __gp_gpio_dev); int port = 0; int slot = -1; amhw_zlg_gpio_t *p_hw_gpio = NULL; amhw_zlg_syscfg_t *p_hw_syscfg = NULL; amhw_zlg_exti_t *p_hw_exti = NULL; if (__gp_gpio_dev == NULL) { return -AM_ENXIO; } port = pin >> 4; /* 获得引脚对应的端口号 */ if (port > 3) { /* 端口不存在 */ return -AM_EINVAL; } p_hw_gpio = (amhw_zlg_gpio_t *)p_gpio_devinfo->gpio_regbase; p_hw_syscfg = (amhw_zlg_syscfg_t *)p_gpio_devinfo->syscfg_regbase; p_hw_exti = (amhw_zlg_exti_t *)p_gpio_devinfo->exti_regbase; /* 还没有开始配置管脚 */ if ((p_gpio_devinfo->p_infomap)[pin & 0x0f] == pin) { slot = pin & 0x0f; } else { return -AM_ENXIO; } /* 复用功能回到默认状态,表明使用GPIO功能 */ amhw_zlg_gpio_pin_afr_set(p_hw_gpio, AMHW_ZLG_GPIO_AF_DEFAULT, pin); /* 可以添加该中断引脚配置为GPIO功能的函数代码 */ /* 设置管脚为输入方向 */ amhw_zlg_gpio_pin_dir_input(p_hw_gpio, pin); /* 管脚为上拉/下拉模式 */ amhw_zlg_gpio_pin_mode_set(p_hw_gpio, AMHW_ZLG_GPIO_MODE_IPD, pin); /* * 中断线0只能连一个端口编号为0的GPIO引脚,比如说,PIOA_0连接到了中断线0, * PIOB_0、PIOC_0、PIOD_0就不能连到中断线0, 但此时PIOA_1可以连接到中断线1。 */ amhw_zlg_syscfg_exti_line_config(p_hw_syscfg, port, slot); /* 清除中断线配置 */ amhw_zlg_exti_imr_clear(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); amhw_zlg_exti_emr_clear(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); /* 清除中断线触发方式配置 */ amhw_zlg_exti_rtsr_clear(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); amhw_zlg_exti_ftsr_clear(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); switch (flag) { case AM_GPIO_TRIGGER_OFF: /* 关闭触发 */ amhw_zlg_exti_imr_clear(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); amhw_zlg_exti_emr_clear(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); break; case AM_GPIO_TRIGGER_HIGH: /* 高电平触发 */ return -AM_ENOTSUP; case AM_GPIO_TRIGGER_LOW: /* 低电平触发 */ return -AM_ENOTSUP; case AM_GPIO_TRIGGER_RISE: /* 上升沿触发 */ /* 使OD位置为0, 表明是下拉 */ amhw_zlg_gpio_pin_out_low(p_hw_gpio, pin); /* rising edge */ amhw_zlg_exti_rtsr_set(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); break; case AM_GPIO_TRIGGER_FALL: /* 下降沿触发 */ /* 使OD位置为1, 表明是上拉 */ amhw_zlg_gpio_pin_out_high(p_hw_gpio, pin); /* falling edge */ amhw_zlg_exti_ftsr_set(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); break; case AM_GPIO_TRIGGER_BOTH_EDGES: /* 双边沿触发 */ /* 使OD位置为1, 表明是上拉 */ amhw_zlg_gpio_pin_out_high(p_hw_gpio, pin); /* rising falling edge */ amhw_zlg_exti_rtsr_set(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); amhw_zlg_exti_ftsr_set(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); break; default: break; } return AM_OK; } /** * \brief 使能引脚中断。 */ int am_gpio_trigger_on (int pin) { __GPIO_DEVINFO_DECL(p_gpio_devinfo, __gp_gpio_dev); int slot = -1; int port = 0; int err = 0; uint32_t extipinsource = 0; amhw_zlg_exti_t *p_hw_exti = NULL; if (__gp_gpio_dev == NULL) { return -AM_ENXIO; } port = pin >> 4; /* 获得引脚对应的端口号 */ if (port > 3) { /* 端口不存在 */ return -AM_EINVAL; } extipinsource = pin & 0x0f; /* 还没有开始配置管脚 */ if ((p_gpio_devinfo->p_infomap)[extipinsource] == pin) { slot = extipinsource; } else { return -AM_ENXIO; } p_hw_exti = (amhw_zlg_exti_t *)p_gpio_devinfo->exti_regbase; /* 清引脚中断线标志位 */ amhw_zlg_exti_pending_clear(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); /* 设置开放中断线请求 */ amhw_zlg_exti_imr_set(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); return err; } /** * \brief 禁能引脚中断。 */ int am_gpio_trigger_off (int pin) { __GPIO_DEVINFO_DECL(p_gpio_devinfo, __gp_gpio_dev); int slot = -1; int port = 0; uint32_t extipinsource = 0; amhw_zlg_exti_t *p_hw_exti = NULL; if (__gp_gpio_dev == NULL) { return -AM_ENXIO; } port = pin >> 4; /* 获得引脚对应的端口号 */ if (port > 3) { /* 端口不存在 */ return -AM_EINVAL; } extipinsource = pin & 0x0f; /* 还没有开始配置管脚 */ if ((p_gpio_devinfo->p_infomap)[extipinsource] == pin) { slot = extipinsource; } else { return -AM_ENXIO; } p_hw_exti = (amhw_zlg_exti_t *)p_gpio_devinfo->exti_regbase; /* 屏蔽中断线请求 */ amhw_zlg_exti_imr_clear(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); amhw_zlg_exti_emr_clear(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); return AM_OK; } /** * \brief GPIO 中断服务响应函数。 * * \param[in] p_arg : 当前中断映射编号 * * \return 无 */ static void __port_exit0_1_int_isr (void *p_arg) { __GPIO_DEVINFO_DECL(p_gpio_devinfo, __gp_gpio_dev); int slot = 0; am_pfnvoid_t pfn_isr = NULL; void *p_arg_tmp = NULL; amhw_zlg_exti_t *p_hw_exti = NULL; p_hw_exti = (amhw_zlg_exti_t *)p_gpio_devinfo->exti_regbase; /* 获取有关回调函数及参数 */ pfn_isr = p_gpio_devinfo->p_triginfo[slot].pfn_callback; p_arg_tmp = p_gpio_devinfo->p_triginfo[slot].p_arg; /* 判断中断线挂起标志是否置位 */ if (amhw_zlg_exti_pr_read(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)) != 0) { /* 获取有关回调函数及参数 */ pfn_isr = p_gpio_devinfo->p_triginfo[slot].pfn_callback; p_arg_tmp = p_gpio_devinfo->p_triginfo[slot].p_arg; } else { /* 获取有关回调函数及参数 */ pfn_isr = p_gpio_devinfo->p_triginfo[slot + 1].pfn_callback; p_arg_tmp = p_gpio_devinfo->p_triginfo[slot + 1].p_arg; slot = 1; } /* 调用用户的中断处理逻辑 */ if (pfn_isr != NULL) { pfn_isr(p_arg_tmp); } /* 清中断标志 */ amhw_zlg_exti_pending_clear(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); } /** * \brief GPIO 中断服务响应函数 * * \param[in] p_arg : 当前中断映射编号 * * \return 无 */ static void __port_exit2_3_int_isr (void *p_arg) { __GPIO_DEVINFO_DECL(p_gpio_devinfo, __gp_gpio_dev); int slot = 2; am_pfnvoid_t pfn_isr = NULL; void *p_arg_tmp = NULL; amhw_zlg_exti_t *p_hw_exti = NULL; p_hw_exti = (amhw_zlg_exti_t *)p_gpio_devinfo->exti_regbase; /* 获取有关回调函数及参数 */ pfn_isr = p_gpio_devinfo->p_triginfo[slot].pfn_callback; p_arg_tmp = p_gpio_devinfo->p_triginfo[slot].p_arg; /* 判断中断线挂起标志是否置位 */ if (amhw_zlg_exti_pr_read(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)) != 0) { /* 获取有关回调函数及参数 */ pfn_isr = p_gpio_devinfo->p_triginfo[slot].pfn_callback; p_arg_tmp = p_gpio_devinfo->p_triginfo[slot].p_arg; } else { /* 获取有关回调函数及参数 */ pfn_isr = p_gpio_devinfo->p_triginfo[slot + 1].pfn_callback; p_arg_tmp = p_gpio_devinfo->p_triginfo[slot + 1].p_arg; slot = 3; } /* 调用用户的中断处理逻辑 */ if (pfn_isr != NULL) { pfn_isr(p_arg_tmp); } /* 清中断标志 */ amhw_zlg_exti_pending_clear(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); } /** * \brief 根据状态寄存器转换为中断号 */ static int __get_inum (uint32_t int_status) { int i = 0; if (int_status == 0) { return -AM_EINVAL; } for (i = 4; i < 16; ++i) { if (((int_status >> i) & 0x0001) != 0){ break; } } return i; } /** * \brief GPIO 中断服务响应函数 * * \param[in] p_arg : 当前中断映射编号 * * \return 无 */ static void __port_exit4_15_int_isr (void *p_arg) { __GPIO_DEVINFO_DECL(p_gpio_devinfo, __gp_gpio_dev); int slot = 0; am_pfnvoid_t pfn_isr = NULL; void *p_arg_tmp = NULL; amhw_zlg_exti_t *p_hw_exti = NULL; p_hw_exti = (amhw_zlg_exti_t *)p_gpio_devinfo->exti_regbase; slot = __get_inum(p_hw_exti->pr); /* 获取有关回调函数及参数 */ pfn_isr = p_gpio_devinfo->p_triginfo[slot].pfn_callback; p_arg_tmp = p_gpio_devinfo->p_triginfo[slot].p_arg; /* 调用用户的中断处理逻辑 */ if (pfn_isr != NULL) { pfn_isr(p_arg_tmp); } /* 清中断标志 */ amhw_zlg_exti_pending_clear(p_hw_exti, (amhw_zlg_exti_line_num_t)(1UL << slot)); } /** * \brief 连接引脚中断回调函数 */ int am_gpio_trigger_connect (int pin, am_pfnvoid_t pfn_callback, void *p_arg) { __GPIO_DEVINFO_DECL(p_gpio_devinfo, __gp_gpio_dev); int key; int slot = -1; int port = 0; uint32_t extipinsource = 0; am_bool_t already = AM_FALSE; extipinsource = pin & 0x0f; port = pin >> 4; if (port > 3) { return -AM_EINVAL; } /* 关闭CPU中断 */ key = am_int_cpu_lock(); if ((p_gpio_devinfo->p_infomap)[extipinsource] == AM_ZLG116_GPIO_INVALID_PIN_MAP) { slot = extipinsource; } else { already = AM_TRUE; } if (already) { /* 打开CPU中断 */ am_int_cpu_unlock(key); return -AM_EINVAL; } if (-1 != slot) { /* 保存触发引脚及回调函数 */ (p_gpio_devinfo->p_infomap)[slot] = pin; (p_gpio_devinfo->p_triginfo)[slot].pfn_callback = pfn_callback; (p_gpio_devinfo->p_triginfo)[slot].p_arg = p_arg; /* 打开中断 */ am_int_cpu_unlock(key); } return AM_OK; } /** * \brief 删除引脚中断回调函数连接 */ int am_gpio_trigger_disconnect (int pin, am_pfnvoid_t pfn_callback, void *p_arg) { __GPIO_DEVINFO_DECL(p_gpio_devinfo, __gp_gpio_dev); int key; int port = 0; int slot = -1; uint32_t extipinsource = 0; port = pin >> 4; if (port > 3) { return -AM_EINVAL; } extipinsource = pin & 0x0f; /* 关闭CPU中断 */ key = am_int_cpu_lock(); if ((p_gpio_devinfo->p_infomap)[extipinsource] == pin) { slot = extipinsource; } if (slot == -1) { /* 打开CPU中断 */ am_int_cpu_unlock(key); return -AM_EINVAL; } (p_gpio_devinfo->p_infomap)[slot] = AM_ZLG116_GPIO_INVALID_PIN_MAP; (p_gpio_devinfo->p_triginfo)[slot].pfn_callback = NULL; /* 打开CPU中断 */ am_int_cpu_unlock(key); return AM_OK; } /** * \brief GPIO初始化 */ int am_zlg116_gpio_init (am_zlg116_gpio_dev_t *p_dev, const am_zlg116_gpio_devinfo_t *p_devinfo) { int i; if (p_dev == NULL || p_devinfo == NULL) { return -AM_EINVAL; } /* GPIO平台初始化 */ if (p_devinfo->pfn_plfm_init) { p_devinfo->pfn_plfm_init(); } /* GPIO设备结构体初始化 */ p_dev->p_devinfo = p_devinfo; __gp_gpio_dev = p_dev; p_dev->valid_flg = AM_TRUE; if ((p_devinfo->p_triginfo == NULL) || (p_devinfo->p_infomap == NULL)) { p_dev->valid_flg = AM_FALSE; } /* 初始化每个引脚的回调处理函数及触发方式内存映射 */ if (p_dev->valid_flg) { for (i = 0; i < p_devinfo->pint_count; i++) { (p_devinfo->p_infomap)[i] = AM_ZLG116_GPIO_INVALID_PIN_MAP; (p_devinfo->p_triginfo)[i].pfn_callback = NULL; } } /* 连接GPIO引脚的中断处理函数 */ am_int_connect((p_devinfo->inum_pin)[0], /* 写入中断号 */ (am_pfnvoid_t)__port_exit0_1_int_isr, (void *)p_devinfo); am_int_connect((p_devinfo->inum_pin)[1], /* 写入中断号 */ (am_pfnvoid_t)__port_exit2_3_int_isr, (void *)p_devinfo); am_int_connect((p_devinfo->inum_pin)[2], /* 写入中断号 */ (am_pfnvoid_t)__port_exit4_15_int_isr, (void *)p_devinfo); /* 使能GPIO的NVIC中断 */ am_int_enable(p_devinfo->inum_pin[0]); am_int_enable(p_devinfo->inum_pin[1]); am_int_enable(p_devinfo->inum_pin[2]); return AM_OK; } /** * \brief GPIO去初始化 */ void am_zlg116_gpio_deinit (void) { __GPIO_DEVINFO_DECL(p_gpio_devinfo, __gp_gpio_dev); int i = 0; if (__gp_gpio_dev->valid_flg) { for (i = 0; i < p_gpio_devinfo->pint_count; i++) { (p_gpio_devinfo->p_infomap)[i] = AM_ZLG116_GPIO_INVALID_PIN_MAP; (p_gpio_devinfo->p_triginfo)[i].pfn_callback = NULL; } } am_int_disable((p_gpio_devinfo->inum_pin)[0]); am_int_disable((p_gpio_devinfo->inum_pin)[1]); am_int_disable((p_gpio_devinfo->inum_pin)[2]); am_int_disconnect((p_gpio_devinfo->inum_pin)[0], /* 写入中断号 */ (am_pfnvoid_t)__port_exit0_1_int_isr, (void *)p_gpio_devinfo); am_int_disconnect((p_gpio_devinfo->inum_pin)[1], /* 写入中断号 */ (am_pfnvoid_t)__port_exit2_3_int_isr, (void *)p_gpio_devinfo); am_int_disconnect((p_gpio_devinfo->inum_pin)[2], /* 写入中断号 */ (am_pfnvoid_t)__port_exit4_15_int_isr, (void *)p_gpio_devinfo); if (__gp_gpio_dev->p_devinfo->pfn_plfm_deinit) { __gp_gpio_dev->p_devinfo->pfn_plfm_deinit(); } } /* end of file */
23,322
C
.c
651
26.248848
91
0.510218
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,486
am_zlg_dma.c
skyformat99_ametal/soc/zlg/drivers/source/dma/am_zlg_dma.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief DMA 驱动实现 * * \internal * \par Modification history * - 1.00 17-04-11 ari, first implementation * \endinternal */ #include "am_zlg_dma.h" #include "am_int.h" /******************************************************************************* 私有定义 *******************************************************************************/ /** \brief 中断未连接标识 */ #define __INT_NOT_CONNECTED 0xFF /** \brief 通道未连接标识 */ #define __CHAN_NOT_CONNECTED 0xFF /** \brief 定义指向DMA设备信息的指针 */ #define __DMA_DEVINFO_DECL(p_dma_devinfo, p_dev) \ const am_zlg_dma_devinfo_t *p_dma_devinfo = p_dev->p_devinfo /******************************************************************************* 全局变量 *******************************************************************************/ /** \brief 指向DMA设备的指针 */ static am_zlg_dma_dev_t *__gp_dma_dev; /** \brief DMA中断回调函数信息数组 */ static struct am_zlg_dma_int_info __dma_int_info[AMHW_ZLG_DMA_CHAN_CNT]; /** \brief DMA中断回调函数信息映射 */ static uint8_t __dma_int_map[AMHW_ZLG_DMA_CHAN_CNT]; /******************************************************************************* 公共函数 *******************************************************************************/ /* 建立传输描述符 */ int am_zlg_dma_xfer_desc_build (amhw_zlg_dma_xfer_desc_t *p_desc, uint32_t src_addr, uint32_t dst_addr, uint32_t nbytes, uint32_t flags) { if (p_desc == NULL) { return AM_ERROR; } if (nbytes > 0xFFFF) { return AM_ERROR; } p_desc->xfercfg = flags; p_desc->src_addr = src_addr; p_desc->dst_addr = dst_addr; p_desc->nbytes = nbytes; return AM_OK; } /* 开始DMA传输 */ int am_zlg_dma_xfer_desc_chan_cfg (amhw_zlg_dma_xfer_desc_t *p_desc, amhw_zlg_dma_transfer_type_t type, uint8_t chan) { uint32_t per_data_size = 8; uint32_t mem_data_size = 8; uint32_t trans_data_byte = 0; __DMA_DEVINFO_DECL(p_dma_devinfo, __gp_dma_dev); amhw_zlg_dma_t *p_hw_dma = (amhw_zlg_dma_t *)p_dma_devinfo->dma_reg_base; if (p_desc == NULL) { return AM_ERROR; } if (chan > AMHW_ZLG_DMA_CHAN_CNT) { return AM_ERROR; } mem_data_size = 1 << (((p_desc->xfercfg >> 8) & 0x3u) + 3); switch(type) { case AMHW_ZLG_DMA_PER_TO_MER: p_desc->xfercfg |= (AMHW_ZLG_DMA_CHAN_DIR_FROM_PER | AMHW_ZLG_DMA_CHAN_MEM_TO_MEM_DISABLE); per_data_size = 1 << (((p_desc->xfercfg >> 10) & 0x3u) + 3); trans_data_byte = p_desc->nbytes / (per_data_size / 8); amhw_zlg_dma_chan_per_address_set(p_hw_dma, p_desc->src_addr, chan); amhw_zlg_dma_chan_mem_address_set(p_hw_dma, p_desc->dst_addr, chan); break; case AMHW_ZLG_DMA_MER_TO_PER: p_desc->xfercfg |= (AMHW_ZLG_DMA_CHAN_DIR_FROM_MEM | AMHW_ZLG_DMA_CHAN_MEM_TO_MEM_DISABLE); mem_data_size = 1 << (((p_desc->xfercfg >> 10) & 0x3u) + 3); trans_data_byte = p_desc->nbytes / (mem_data_size / 8); amhw_zlg_dma_chan_per_address_set(p_hw_dma, p_desc->dst_addr, chan); amhw_zlg_dma_chan_mem_address_set(p_hw_dma, p_desc->src_addr, chan); break; case AMHW_ZLG_DMA_MER_TO_MER: p_desc->xfercfg |= (AMHW_ZLG_DMA_CHAN_DIR_FROM_MEM | AMHW_ZLG_DMA_CHAN_MEM_TO_MEM_ENABLE); mem_data_size = 1 << (((p_desc->xfercfg >> 10) & 0x3u) + 3); trans_data_byte = p_desc->nbytes / (mem_data_size / 8); amhw_zlg_dma_chan_per_address_set(p_hw_dma, p_desc->dst_addr, chan); amhw_zlg_dma_chan_mem_address_set(p_hw_dma, p_desc->src_addr, chan); break; default: break; } amhw_zlg_dma_chan_tran_data_size(p_hw_dma, trans_data_byte, chan); amhw_zlg_dma_chan_config_set(p_hw_dma, p_desc->xfercfg, chan); return AM_OK; } /* 停止通道传输 */ int am_zlg_dma_chan_start (int chan) { __DMA_DEVINFO_DECL(p_dma_devinfo, __gp_dma_dev); amhw_zlg_dma_t *p_hw_dma = (amhw_zlg_dma_t *)p_dma_devinfo->dma_reg_base; amhw_zlg_dma_chan_int_enable(p_hw_dma, AMHW_ZLG_DMA_CHAN_INT_TX_CMP_MASK, chan); amhw_zlg_dma_chan_enable(p_hw_dma, chan, AM_TRUE); return AM_OK; } /* 停止通道传输 */ int am_zlg_dma_chan_stop (int chan) { __DMA_DEVINFO_DECL(p_dma_devinfo, __gp_dma_dev); amhw_zlg_dma_t *p_hw_dma = (amhw_zlg_dma_t *)p_dma_devinfo->dma_reg_base; amhw_zlg_dma_chan_int_disable(p_hw_dma, AMHW_ZLG_DMA_CHAN_INT_TX_CMP_MASK, chan); amhw_zlg_dma_chan_enable(p_hw_dma, chan, AM_FALSE); return AM_OK; } /* DMA中断处理函数 */ static void __dma_int_handler (void *p_arg) { __DMA_DEVINFO_DECL(p_dma_devinfo, __gp_dma_dev); amhw_zlg_dma_t *p_hw_dma = (amhw_zlg_dma_t *)p_dma_devinfo->dma_reg_base; int i; int chan = 0xFF; uint8_t flag = 0xFF; am_zlg_pfn_dma_isr_t pfn_isr; void *p_isr_arg; for (i = 0 ; i < AMHW_ZLG_DMA_CHAN_CNT ; i++) { if (amhw_zlg_dma_chan_stat_check(p_hw_dma , AMHW_ZLG_DMA_CHAN_TX_COMP_FLAG(i))) { if (amhw_zlg_dma_chan_stat_check(p_hw_dma , AMHW_ZLG_DMA_CHAN_TX_HALF_FLAG(i))) { amhw_zlg_dma_chan_flag_clear(p_hw_dma, AMHW_ZLG_DMA_CHAN_TX_HALF_FLAG(i)); } chan = i; if(amhw_zlg_dma_chan_stat_check(p_hw_dma , AMHW_ZLG_DMA_CHAN_TX_ERR_FLAG(i))) { flag = AM_ZLG_DMA_INT_ERROR ; amhw_zlg_dma_chan_flag_clear(p_hw_dma, AMHW_ZLG_DMA_CHAN_TX_ERR_FLAG(i)); } else { flag = AM_ZLG_DMA_INT_NORMAL ; } amhw_zlg_dma_chan_flag_clear(p_hw_dma, AMHW_ZLG_DMA_CHAN_TX_COMP_FLAG(i)); break; } } if (0xFF != chan) { pfn_isr = __dma_int_info[chan].pfn_isr; p_isr_arg = __dma_int_info[chan].p_arg; if (pfn_isr) { pfn_isr(p_isr_arg , flag); } } } /* 连接DMA中断服务函数 */ int am_zlg_dma_isr_connect (int chan, am_zlg_pfn_dma_isr_t pfn_isr, void *p_arg) { if (__dma_int_map[chan] == __INT_NOT_CONNECTED) { __dma_int_info[chan].pfn_isr = pfn_isr; __dma_int_info[chan].p_arg = p_arg; __dma_int_map[chan] = chan; } else { return -AM_EPERM; } return AM_OK; } /* 删除DMA中断服务函数连接 */ int am_zlg_dma_isr_disconnect (int chan, am_zlg_pfn_dma_isr_t pfn_isr, void *p_arg) { if (__dma_int_map[chan] == chan) { __dma_int_info[chan].pfn_isr = NULL; __dma_int_map[chan] = __INT_NOT_CONNECTED; } else { return -AM_EPERM; } return AM_OK; } /** * \breif 获取某通道当前传输剩余的字节数 */ uint16_t am_zlg_dma_tran_data_get (int chan) { __DMA_DEVINFO_DECL(p_dma_devinfo, __gp_dma_dev); amhw_zlg_dma_t *p_hw_dma = (amhw_zlg_dma_t *)p_dma_devinfo->dma_reg_base; return amhw_zlg_dma_chan_tran_data_get(p_hw_dma, chan); } /** * \brief 设置传输的字节数 */ void am_zlg_dma_tran_data_size (int chan, uint32_t trans_data_byte) { __DMA_DEVINFO_DECL(p_dma_devinfo, __gp_dma_dev); amhw_zlg_dma_t *p_hw_dma = (amhw_zlg_dma_t *)p_dma_devinfo->dma_reg_base; amhw_zlg_dma_chan_tran_data_size(p_hw_dma, trans_data_byte, chan); } /* DMA初始化 */ int am_zlg_dma_init (am_zlg_dma_dev_t *p_dev, const am_zlg_dma_devinfo_t *p_devinfo) { uint32_t i = 0; if (p_dev == NULL || p_devinfo == NULL) { return AM_ERROR; } p_dev->p_devinfo = p_devinfo; __gp_dma_dev = p_dev; if (p_devinfo->pfn_plfm_init) { p_devinfo->pfn_plfm_init(); } for (i = 0; i < AMHW_ZLG_DMA_CHAN_CNT; i++) { __dma_int_info[i].pfn_isr = NULL; __dma_int_map[i] = __INT_NOT_CONNECTED; } for (i = p_devinfo->inum_start; i <= p_devinfo->inum_end; i++) { am_int_connect(i, __dma_int_handler, (void *)0); am_int_enable(i); } return AM_OK; } /* DMA去初始化 */ void am_zlg_dma_deinit (void) { am_zlg_dma_devinfo_t *p_dma_devinfo = NULL; amhw_zlg_dma_t *p_hw_dma; int i = 0; if (NULL == __gp_dma_dev) { return; } p_dma_devinfo = (am_zlg_dma_devinfo_t *)__gp_dma_dev->p_devinfo; p_hw_dma = (amhw_zlg_dma_t *)p_dma_devinfo->dma_reg_base; for (i = 0; i < AMHW_ZLG_DMA_CHAN_CNT; i++) { __dma_int_info[i].pfn_isr = NULL; __dma_int_map[i] = 0; amhw_zlg_dma_chan_enable(p_hw_dma , i, AM_FALSE); } for (i = p_dma_devinfo->inum_start; i <= p_dma_devinfo->inum_end; i++) { am_int_disconnect(i, __dma_int_handler, (void *)0); am_int_disable(i); } if (p_dma_devinfo->pfn_plfm_deinit) { p_dma_devinfo->pfn_plfm_deinit(); } } /* end of file */
11,010
C
.c
281
28.042705
94
0.448917
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,488
am_zlg_spi_slv_dma.c
skyformat99_ametal/soc/zlg/drivers/source/spi/am_zlg_spi_slv_dma.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief SPI 从机驱动层实现函数(DMA 方式) * * \internal * \par Modification History * -1.00 17-09-15 fra, first implementation * \endinternal */ /******************************************************************************* includes *******************************************************************************/ #include "ametal.h" #include "am_int.h" #include "am_clk.h" #include "am_gpio.h" #include "am_zlg_dma.h" #include "am_zlg_spi_slv_dma.h" #include "hw/amhw_zlg_spi.h" /******************************************************************************* 模块内函数声明 *******************************************************************************/ /** \brief SPI 从机硬件初始化 */ static int __spi_slv_hard_init (am_zlg_spi_slv_dma_dev_t *p_dev); /** \brief SPI 从机 DMA 中断处理函数 */ static void __spi_slv_dma_isr (void *p_arg, uint32_t stat); /** \brief SPI 从机 DMA 传输处理函数 */ static int __spi_slv_transfer_data (am_zlg_spi_slv_dma_dev_t *p_dev); /******************************************************************************* SPI 驱动函数声明 *******************************************************************************/ /** \brief 开启 SPI 从机设备 */ static int __spi_slv_setup (void *p_drv, am_spi_slv_device_t *p_dev); /** \brief 关闭 SPI 从机设备 */ static int __spi_slv_shutdown (void *p_drv, am_spi_slv_device_t *p_dev); /** * \brief SPI 从设备驱动函数定义 */ static const struct am_spi_slv_drv_funcs __g_spi_slv_drv_funcs = { __spi_slv_setup, __spi_slv_shutdown, }; /** * \brief SPI 硬件初始化 */ static int __spi_slv_hard_init (am_zlg_spi_slv_dma_dev_t *p_this) { amhw_zlg_spi_t *p_hw_spi = (amhw_zlg_spi_t *)(p_this->p_devinfo->spi_reg_base); if (p_this == NULL) { return -AM_EINVAL; } /* 配置为从机模式 */ amhw_zlg_spi_mode_sel(p_hw_spi, AMHW_ZLG_SPI_MODE_SLAVE); amhw_zlg_spi_nss_ctrl_sel(p_hw_spi,AMHW_ZLG_SPI_NSS_CTRL_BT_HD); /* 使能为 DMA 方式 */ amhw_zlg_spi_dma_enable(p_hw_spi, AM_TRUE); /* DMA 设置 */ amhw_zlg_spi_dma_txtri_level_sel(p_hw_spi, AMHW_ZLG_SPI_DMA_TRIG_ONE_DATA); amhw_zlg_spi_dma_rxtri_level_sel(p_hw_spi, AMHW_ZLG_SPI_DMA_TRIG_ONE_DATA); /* 使能接收和发送 */ amhw_zlg_spi_tx_enable(p_hw_spi, AM_TRUE); amhw_zlg_spi_rx_enable(p_hw_spi, AM_TRUE); return AM_OK; } /** * \brief 从机配置 */ static int __spi_slv_cfg (am_zlg_spi_slv_dma_dev_t *p_this, am_spi_slv_device_t *p_slv_dev) { amhw_zlg_spi_t *p_hw_spi = \ (amhw_zlg_spi_t *) (p_this->p_devinfo->spi_reg_base); /* 默认数据为 8 位,最大不超过 32 位 */ if (p_slv_dev->bits_per_word == 0) { p_slv_dev->bits_per_word = 8; } else if (p_slv_dev->bits_per_word > 32) { return -AM_ENOTSUP; } /* 除8位,1~32 数据收发只支持 LSB 模式 */ if (!(p_slv_dev->mode & AM_SPI_SLV_LSB_FIRST) && (p_slv_dev->bits_per_word != 8) ) { return -AM_ENOTSUP; } /* 配置 LSB 或 MSB */ if (p_slv_dev->mode & AM_SPI_SLV_LSB_FIRST) { amhw_zlg_spi_first_bit_sel(p_hw_spi, AMHW_ZLG_SPI_DATA_LSB); } else { amhw_zlg_spi_first_bit_sel(p_hw_spi, AMHW_ZLG_SPI_DATA_MSB); } /* 配置为 8 位的数据帧 */ amhw_zlg_spi_data_len_sel(p_hw_spi, AMHW_ZLG_SPI_DATA_LEN_8BIT); /* 配置数据宽度 */ amhw_zlg_spi_valid_data_sel(p_hw_spi, AMHW_ZLG_SPI_VALID_DATA_8BIT); if (p_slv_dev->bits_per_word == 32) { amhw_zlg_spi_extlen_set(p_hw_spi, 0); } else { amhw_zlg_spi_extlen_set(p_hw_spi, p_slv_dev->bits_per_word); } /* 配置 SPI 模式,时钟相位和极性(CPHA 和 CPOL)*/ amhw_zlg_spi_module_enable(p_hw_spi, AM_FALSE); amhw_zlg_spi_clk_mode_set(p_hw_spi, (0x3 & p_slv_dev->mode) ^ 0x01); return AM_OK; } /** * \brief 片选中断 */ void __cs_irq_handle (void *p_arg) { am_zlg_spi_slv_dma_dev_t *p_this = ( am_zlg_spi_slv_dma_dev_t *)p_arg; amhw_zlg_spi_t *p_hw_spi = (amhw_zlg_spi_t *) (p_this->p_devinfo->spi_reg_base); am_spi_slv_device_t *p_dev = p_this->p_spi_slv_dev; uint8_t cs_status = am_gpio_get(p_this->p_devinfo->cs_pin); size_t count = 0; /* 片选有效模式 1 高电平有效 0 低电平有效 */ uint8_t cs_mode = p_dev->mode & AM_SPI_SLV_CS_HIGH; if( cs_status ^ cs_mode ) { /* 传输结束 */ count = p_this->sum_nbytes - \ am_zlg_dma_tran_data_get(p_this->p_devinfo->dma_chan_rx); if(p_dev->p_slv_cb_funcs->pfn_cs_inactive) { p_dev->p_slv_cb_funcs->pfn_cs_inactive(p_dev->p_arg, count); } /* 关闭 SPI,同时可以清空缓存区和移位寄存器中的数据 */ /* 关闭发送 DMA 传输 */ am_zlg_dma_chan_stop( p_this->p_devinfo->dma_chan_tx); /* 清空移位寄存器中的数据 */ amhw_zlg_spi_module_enable(p_hw_spi, AM_FALSE); /* 清空发送缓存区的数据 */ amhw_zlg_spi_tx_enable(p_hw_spi, AM_FALSE); amhw_zlg_spi_tx_enable(p_hw_spi, AM_TRUE); /* 模拟一个 DMA 传输完成,SPI 有 8 字节的 FIFO,没有时钟沿也会有 DMA 请求 */ am_zlg_dma_xfer_desc_build(&(p_this->g_desc[0]), /* 通道描述符 */ (uint32_t)(&(p_this->dummy_txbuf)), /* 源缓冲区首地址 */ (uint32_t)(&(p_hw_spi->txreg)), /* 目的缓冲区首地址 */ 1, /* 传输字节数 */ p_this->dummy_dma_flags); /* 传输配置 */ if (am_zlg_dma_xfer_desc_chan_cfg(&(p_this->g_desc[0]), AMHW_ZLG_DMA_MER_TO_PER, /* 内存到外设 */ p_this->p_devinfo->dma_chan_tx) == AM_OK) { am_zlg_dma_chan_start(p_this->p_devinfo->dma_chan_tx); } /* 清除该字节数 ,关闭 SPI,片选无效时不进行传输 */ amhw_zlg_spi_module_enable(p_hw_spi, AM_TRUE); amhw_zlg_spi_module_enable(p_hw_spi, AM_FALSE); } else { /* 传输开始 */ if(p_dev->p_slv_cb_funcs->pfn_cs_active) { p_dev->p_slv_cb_funcs->pfn_cs_active(p_dev->p_arg); } p_this->sum_nbytes = 0; /* 配置 DMA 之前必须关闭 DMA 通道 */ am_zlg_dma_chan_stop(p_this->p_devinfo->dma_chan_tx); am_zlg_dma_chan_stop(p_this->p_devinfo->dma_chan_rx); /* 启动 DMA 传输 */ __spi_slv_transfer_data(p_this); amhw_zlg_spi_module_enable(p_hw_spi, AM_TRUE); } } /** * \brief 使能 CS 引脚外部中断 */ static int __cs_irq_cfg (am_zlg_spi_slv_dma_dev_t *p_this) { if (p_this == NULL) { return -AM_EINVAL; } /* 连接终端回调函数 */ am_gpio_trigger_connect(p_this->p_devinfo->cs_pin, __cs_irq_handle, p_this); /* 配置为双边沿触发 */ am_gpio_trigger_cfg(p_this->p_devinfo->cs_pin, AM_GPIO_TRIGGER_BOTH_EDGES); /* 使能引脚触发 */ am_gpio_trigger_on(p_this->p_devinfo->cs_pin); return AM_OK; } /** * \brief 片选解初始化 */ static int __cs_irq_cfg_deinit (am_zlg_spi_slv_dma_dev_t *p_this) { if (p_this == NULL) { return -AM_EINVAL; } am_gpio_trigger_disconnect(p_this->p_devinfo->cs_pin, __cs_irq_handle, p_this); am_gpio_trigger_off(p_this->p_devinfo->cs_pin); return AM_OK; } /******************************************************************************/ /** * \brief 设置 SPI 从设备 */ static int __spi_slv_setup (void *p_drv, am_spi_slv_device_t *p_dev) { am_zlg_spi_slv_dma_dev_t *p_this = (am_zlg_spi_slv_dma_dev_t *)p_drv; if (p_dev == NULL || p_drv == NULL) { return -AM_EINVAL; } if (p_this->p_spi_slv_dev == NULL) { p_this->p_spi_slv_dev = p_dev; } else { return -AM_ENOTSUP; } /* 配置从 SPI */ if (AM_OK != __spi_slv_cfg(p_this, p_dev) ) { return -AM_ENOTSUP; } /* 配置片选中断 */ __cs_irq_cfg(p_this); return AM_OK; } /** * \brief SPI 从机关闭函数 */ static int __spi_slv_shutdown(void *p_drv, struct am_spi_slv_device *p_dev) { am_zlg_spi_slv_dma_dev_t *p_this; if ( (p_drv == NULL) || (p_dev == NULL)) { return -AM_EINVAL; } p_this = (am_zlg_spi_slv_dma_dev_t *)p_drv; __cs_irq_cfg_deinit(p_this); p_this->p_spi_slv_dev = NULL; return AM_OK; } /******************************************************************************/ /** * \brief SPI 从机 DMA 中断处理 */ static void __spi_slv_dma_isr (void *p_arg, uint32_t stat) { am_zlg_spi_slv_dma_dev_t *p_this = (am_zlg_spi_slv_dma_dev_t *)p_arg; /* 中断发生 */ if (stat == AM_ZLG_DMA_INT_NORMAL) { /* 传输完成回调 */ __spi_slv_transfer_data(p_this); } else { /* 中断源不匹配 */ } } /** * \brief SPI 从机发送数据 */ static int __spi_slv_transfer_data (am_zlg_spi_slv_dma_dev_t *p_dev) { amhw_zlg_spi_t *p_hw_spi; am_spi_slv_device_t *p_slv_dev; if (p_dev == NULL) { return -AM_EINVAL; } p_hw_spi = (amhw_zlg_spi_t *)(p_dev->p_devinfo->spi_reg_base); p_slv_dev = p_dev->p_spi_slv_dev; /* 设置字节数有效性检查 */ if (p_dev->tansfer.bits_per_word > 32) { return -AM_EINVAL; } /* 传输数据回调 */ if (p_slv_dev->p_slv_cb_funcs->pfn_tansfer_get) { if ( p_slv_dev->p_slv_cb_funcs->pfn_tansfer_get(p_slv_dev->p_arg, &(p_dev->tansfer)) != AM_OK ) { return AM_OK; } } else { return -AM_ENODEV; } /* 不需要进行传输 */ if (p_dev->tansfer.nbytes == 0 ) { return AM_OK; } /* 0 默认为从设备的值 */ if (p_dev->tansfer.bits_per_word == 0 ) { p_dev->tansfer.bits_per_word = p_dev->p_spi_slv_dev->bits_per_word; } /* 判断是否有效 */ if (!(p_slv_dev->mode & AM_SPI_SLV_LSB_FIRST) && (p_slv_dev->bits_per_word != 8) ) { return -AM_ENOTSUP; } if (p_slv_dev->bits_per_word == 32) { amhw_zlg_spi_extlen_set(p_hw_spi, 0); } else { amhw_zlg_spi_extlen_set(p_hw_spi, p_slv_dev->bits_per_word); } /* 统计字节数 */ p_dev->sum_nbytes += p_dev->tansfer.nbytes; /* 建立发送通道描述符 */ if (p_dev->tansfer.p_tx_buf) { am_zlg_dma_xfer_desc_build(&(p_dev->g_desc[0]), /* 通道描述符 */ (uint32_t)(p_dev->tansfer.p_tx_buf), /* 源缓冲区首地址 */ (uint32_t)(&(p_hw_spi->txreg)), /* 目的缓冲区首地址 */ p_dev->tansfer.nbytes , /* 传输字节数 */ p_dev->dma_flags); /* 传输配置 */ } else { am_zlg_dma_xfer_desc_build(&(p_dev->g_desc[0]), /* 通道描述符 */ (uint32_t)(&(p_dev->dummy_txbuf)), /* 源缓冲区首地址 */ (uint32_t)(&(p_hw_spi->txreg)), /* 目的缓冲区首地址 */ p_dev->tansfer.nbytes, /* 传输字节数 */ p_dev->dummy_dma_flags); /* 传输配置 */ } /* 建立接收通道描述符 */ if ( p_dev->tansfer.p_rx_buf) { am_zlg_dma_xfer_desc_build(&(p_dev->g_desc[1]), /* 通道描述符 */ (uint32_t)(&(p_hw_spi->rxreg)), /* 源缓冲区首地址 */ (uint32_t)(p_dev->tansfer.p_rx_buf), /* 目的缓冲区首地址 */ p_dev->tansfer.nbytes, /* 传输字节数 */ p_dev->dma_flags); /* 传输配置 */ } else { am_zlg_dma_xfer_desc_build(&(p_dev->g_desc[1]), /* 通道描述符 */ (uint32_t)(&(p_hw_spi->rxreg)), /* 源缓冲区首地址 */ (uint32_t)(&(p_dev->dummy_rxbuf)), /* 目的缓冲区首地址 */ p_dev->tansfer.nbytes , /* 传输字节数 */ p_dev->dummy_dma_flags); /* 传输配置 */ } if (am_zlg_dma_xfer_desc_chan_cfg(&(p_dev->g_desc[1]), AMHW_ZLG_DMA_PER_TO_MER, /* 外设到内存 */ p_dev->p_devinfo->dma_chan_rx) == AM_ERROR) { return AM_ERROR; } if (am_zlg_dma_xfer_desc_chan_cfg(&(p_dev->g_desc[0]), AMHW_ZLG_DMA_MER_TO_PER, /* 内存到外设 */ p_dev->p_devinfo->dma_chan_tx) == AM_ERROR) { return AM_ERROR; } am_zlg_dma_chan_start(p_dev->p_devinfo->dma_chan_rx); am_zlg_dma_chan_start(p_dev->p_devinfo->dma_chan_tx); return AM_OK; } /******************************************************************************/ /** * \brief SPI 初始化 */ am_spi_slv_handle_t am_zlg_spi_slv_dma_init (am_zlg_spi_slv_dma_dev_t *p_dev, const am_zlg_spi_slv_dma_devinfo_t *p_devinfo) { if (NULL == p_devinfo || NULL == p_dev ) { return NULL; } if (p_devinfo->pfn_plfm_init) { p_devinfo->pfn_plfm_init(); } p_dev->spi_slv_serve.p_funcs = (struct am_spi_slv_drv_funcs *)&__g_spi_slv_drv_funcs; p_dev->spi_slv_serve.p_drv = p_dev; p_dev->p_devinfo = p_devinfo; p_dev->p_spi_slv_dev = NULL; p_dev->tansfer.nbytes = 0; p_dev->tansfer.bits_per_word = 0; p_dev->tansfer.p_rx_buf = NULL; p_dev->tansfer.p_tx_buf = NULL; p_dev->sum_nbytes = 0; p_dev->dummy_txbuf = 0; p_dev->dma_flags = AMHW_ZLG_DMA_CHAN_PRIORITY_HIGH | /* 中断优先级高 */ AMHW_ZLG_DMA_CHAN_MEM_SIZE_8BIT | /* 内存数据宽度 1 字节 */ AMHW_ZLG_DMA_CHAN_PER_SIZE_8BIT | /* 外设数据宽度 1 字节 */ AMHW_ZLG_DMA_CHAN_MEM_ADD_INC_ENABLE | /* 内存地址自增 */ AMHW_ZLG_DMA_CHAN_PER_ADD_INC_DISABLE | /* 外设地址不自增 */ AMHW_ZLG_DMA_CHAN_CIRCULAR_MODE_DISABLE; /* 关闭循环模式 */ p_dev->dummy_dma_flags = AMHW_ZLG_DMA_CHAN_PRIORITY_HIGH | /* 中断优先级高 */ AMHW_ZLG_DMA_CHAN_MEM_SIZE_8BIT | /* 内存数据宽度 1 字节 */ AMHW_ZLG_DMA_CHAN_PER_SIZE_8BIT | /* 外设数据宽度 1 字节 */ AMHW_ZLG_DMA_CHAN_MEM_ADD_INC_DISABLE | /* 内存地址自增 */ AMHW_ZLG_DMA_CHAN_PER_ADD_INC_DISABLE | /* 外设地址不自增 */ AMHW_ZLG_DMA_CHAN_CIRCULAR_MODE_DISABLE; /* 关闭循环模式 */ /* 初始化硬件 */ if (__spi_slv_hard_init(p_dev) != AM_OK) { return NULL; } /* 连接 DMA 中断服务函数 */ am_zlg_dma_isr_connect(p_dev->p_devinfo->dma_chan_rx, __spi_slv_dma_isr, (void *)p_dev); return &(p_dev->spi_slv_serve); } /** * \brief SPI 去除初始化 */ void am_zlg_spi_slv_dma_deinit (am_spi_slv_handle_t handle) { am_zlg_spi_slv_dma_dev_t *p_dev = (am_zlg_spi_slv_dma_dev_t *)handle; amhw_zlg_spi_t *p_hw_spi = (amhw_zlg_spi_t *)(p_dev->p_devinfo->spi_reg_base); if (NULL == p_dev) { return ; } p_dev->spi_slv_serve.p_funcs = NULL; p_dev->spi_slv_serve.p_drv = NULL; /* 禁能 SPI */ amhw_zlg_spi_module_enable(p_hw_spi, AM_FALSE); am_zlg_dma_isr_disconnect(p_dev->p_devinfo->dma_chan_rx, __spi_slv_dma_isr, (void *)p_dev); if (p_dev->p_devinfo->pfn_plfm_deinit) { p_dev->p_devinfo->pfn_plfm_deinit(); } } /* end of file */
16,984
C
.c
406
30.522167
96
0.460275
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,492
am_zlg_dac.c
skyformat99_ametal/soc/zlg/drivers/source/dac/am_zlg_dac.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief DAC驱动实现 * * \internal * \par Modification history * - 1.00 17-8-22 fra, first implementation * \endinternal */ #include "am_zlg_dac.h" #include "am_int.h" #include "hw/amhw_zlg_dac.h" /******************************************************************************* * 私有定义 *******************************************************************************/ #define __ZLG_DAC_BITS_GET(p_drv) \ (((am_zlg_dac_dev_t *)p_drv)->p_devinfo->bits) #define __ZLG_DAC_VREF_GET(p_drv) \ (((am_zlg_dac_dev_t *)p_drv)->p_devinfo->vref) /******************************************************************************* * 函数声明 *******************************************************************************/ static uint32_t __zlg_dac_get_bits (void *p_drv); static uint32_t __zlg_dac_get_vref (void *p_drv); static int __zlg_dac_val_set (void *p_drv, int chan, uint32_t value); static int __zlg_dac_enable (void *p_drv, int chan ); static int __zlg_dac_disable (void *p_drv, int chan ); /** * \brief DAC服务函数 */ static const struct am_dac_drv_funcs __g_dac_drvfuncs = { __zlg_dac_get_bits, __zlg_dac_get_vref, __zlg_dac_val_set, __zlg_dac_enable, __zlg_dac_disable }; /******************************************************************************/ /** * \brief 获取DAC转换精度。 */ static uint32_t __zlg_dac_get_bits (void *p_drv) { return (uint32_t)__ZLG_DAC_BITS_GET(p_drv); } /** * \brief 获取DAC参考电压。 */ static uint32_t __zlg_dac_get_vref (void *p_drv) { return (uint32_t)__ZLG_DAC_VREF_GET(p_drv); } /** * \brief 设置通道的DAC转换值。 */ static int __zlg_dac_val_set (void *p_drv, int chan, uint32_t value) { am_zlg_dac_dev_t *p_dev = (am_zlg_dac_dev_t *)p_drv; amhw_zlg_dac_t *p_hw_dac = (amhw_zlg_dac_t *)(p_dev->p_devinfo->dac_reg_base); if (p_dev == NULL ) { return -AM_EINVAL; } if ((chan != AMHW_ZLG_DAC_CHAN_1) && (chan != AMHW_ZLG_DAC_CHAN_2)) { return -AM_ENXIO; /* 无效的通道值 */ } p_dev->chan = chan; if (chan == AMHW_ZLG_DAC_CHAN_1) { if (p_dev->p_devinfo->bits == 8) { amhw_zlg_dac_chan1_8bit_right_aligned_data(p_hw_dac, value); } else { amhw_zlg_dac_chan1_12bit_right_aligned_data(p_hw_dac, value); } } else { if (p_dev->p_devinfo->bits == 8) { amhw_zlg_dac_chan2_8bit_right_aligned_data(p_hw_dac, value); }else { amhw_zlg_dac_chan2_12bit_right_aligned_data(p_hw_dac, value); } } return AM_OK; } /** * \brief 启动DAC转换 */ static int __zlg_dac_enable (void *p_drv, int chan) { am_zlg_dac_dev_t *p_dev = (am_zlg_dac_dev_t *)p_drv; amhw_zlg_dac_t *p_hw_dac = (amhw_zlg_dac_t *)(p_dev->p_devinfo->dac_reg_base); if (p_dev == NULL ) { return -AM_EINVAL; } if ((chan != AMHW_ZLG_DAC_CHAN_1) && (chan != AMHW_ZLG_DAC_CHAN_2)) { return -AM_ENXIO; /* 无效的通道值 */ } p_dev->chan = chan; if (chan == AMHW_ZLG_DAC_CHAN_1) { amhw_zlg_dac_chan1_enable(p_hw_dac); } else { amhw_zlg_dac_chan2_enable(p_hw_dac); } return AM_OK; } /** * \brief 禁止DAC转换 */ static int __zlg_dac_disable (void *p_drv, int chan ) { am_zlg_dac_dev_t *p_dev = (am_zlg_dac_dev_t *)p_drv; amhw_zlg_dac_t *p_hw_dac = (amhw_zlg_dac_t *)(p_dev->p_devinfo->dac_reg_base); if (p_dev == NULL ) { return -AM_EINVAL; } if ((chan != AMHW_ZLG_DAC_CHAN_1) && (chan != AMHW_ZLG_DAC_CHAN_2)) { return -AM_ENXIO; /* 无效的通道值 */ } p_dev->chan = chan; if (chan == AMHW_ZLG_DAC_CHAN_1) { amhw_zlg_dac_chan1_disable(p_hw_dac); } else { amhw_zlg_dac_chan2_disable(p_hw_dac); } return AM_OK; } /** * \brief DAC初始化 */ am_dac_handle_t am_zlg_dac_init (am_zlg_dac_dev_t *p_dev, const am_zlg_dac_devinfo_t *p_devinfo) { amhw_zlg_dac_t *p_hw_dac; if ((p_devinfo == NULL) || (p_dev == NULL)) { return NULL; } p_hw_dac = (amhw_zlg_dac_t *)(p_dev->p_devinfo->dac_reg_base); p_dev->p_devinfo = p_devinfo; p_dev->dac_serve.p_funcs = &__g_dac_drvfuncs; p_dev->dac_serve.p_drv = p_dev; if (p_devinfo->pfn_plfm_init) { p_devinfo->pfn_plfm_init(); } amhw_zlg_dac_disable(p_hw_dac); return (am_dac_handle_t)(&(p_dev->dac_serve)); } /** * \brief DAC去初始化 */ void am_zlg_dac_deinit (am_dac_handle_t handle) { am_zlg_dac_dev_t *p_dev = (am_zlg_dac_dev_t *)handle; amhw_zlg_dac_t *p_hw_dac = (amhw_zlg_dac_t *)(p_dev->p_devinfo->dac_reg_base); p_dev->dac_serve.p_funcs = NULL; p_dev->dac_serve.p_drv = NULL; amhw_zlg_dac_disable(p_hw_dac); if (p_dev->p_devinfo->pfn_plfm_deinit) { p_dev->p_devinfo->pfn_plfm_deinit(); } } /* end of file */
5,647
C
.c
169
27.331361
85
0.484552
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,494
am_zlg_tim_timing.c
skyformat99_ametal/soc/zlg/drivers/source/tim/am_zlg_tim_timing.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief TIM定时功能驱动层实现 * * \note 当发生一个更新事件时,所有的寄存器都被更新,硬件同时(依据 URS 位)设 * 置更新标志位(TIMx_SR寄存器中的 UIF 位)。重复计数器被重新加载为TIMx_RCR 寄存 * 器的值,自动装载影子寄存器被重新置入预装载寄存器的值 预分频器的缓冲区被置入预 * 装载寄存器的值(TIMx_PSC 寄存器的内容) * * \internal * \par Modification history * - 1.00 17-04-21 nwt, first implementation * \endinternal */ #include "am_int.h" #include "am_clk.h" #include "am_zlg_tim_timing.h" #include "am_clk.h" /******************************************************************************* 定时器驱动函数声明 *******************************************************************************/ static const am_timer_info_t * __tim_timing_info_get (void *p_drv); static int __tim_timing_clkin_freq_get (void *, uint32_t *); static int __tim_timing_prescale_set (void *, uint8_t, uint32_t ); static int __tim_timing_prescale_get (void *, uint8_t, uint32_t *); static int __tim_timing_count_get (void *, uint8_t, void *); static int __tim_timing_rollover_get (void *, uint8_t, void *); static int __tim_timing_disable (void *, uint8_t); static int __tim_timing_enable (void *, uint8_t, void *); static int __tim_timing_callback_set (void *, uint8_t, void (*)(void *), void *); static void __tim_irq_handler (void *p_arg); /******************************************************************************* 全局变量 *******************************************************************************/ /* 定时器信息 */ static const am_timer_info_t __g_tim_timing_info = { 16, /* 16位定时器 */ 1, /* 单通道 */ AM_TIMER_CAN_INTERRUPT | /* 可以产生中断 */ AM_TIMER_AUTO_RELOAD | /* 支持自动重载 */ AM_TIMER_INTERMEDIATE_COUNT | /* 当前计数器值可读 */ AM_TIMER_SUPPORT_ALL_PRESCALE_1_TO_MAX, /* 预分频:1 ~ 65536 任意值 */ 65536 /* 预分频最大值:65536 */ }; /* TIM定时器驱动函数 */ static const struct am_timer_drv_funcs __g_tim_timing_drv_funcs = { __tim_timing_info_get, __tim_timing_clkin_freq_get, __tim_timing_prescale_set, __tim_timing_prescale_get, __tim_timing_count_get, __tim_timing_rollover_get, __tim_timing_enable, __tim_timing_disable, __tim_timing_callback_set, }; /******************************************************************************* 中断处理 *******************************************************************************/ void __tim_irq_handler (void *p_arg) { am_zlg_tim_timing_dev_t *p_dev = (am_zlg_tim_timing_dev_t *)p_arg; amhw_zlg_tim_t *p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; /* * 判断是否是定时器溢出中断 */ if (amhw_zlg_tim_status_flg_get(p_hw_tim, AMHW_ZLG_TIM_UIF) != 0 ) { if (p_dev->pfn_callback != NULL) { p_dev->pfn_callback(p_dev->p_arg); } /* 清除溢出标志 */ amhw_zlg_tim_status_flg_clr(p_hw_tim, AMHW_ZLG_TIM_UIF); } } /******************************************************************************* 标准定时器驱动实现 *******************************************************************************/ static const am_timer_info_t * __tim_timing_info_get (void *p_drv) { return &__g_tim_timing_info; } /******************************************************************************/ static int __tim_timing_clkin_freq_get (void *p_drv, uint32_t *p_freq) { am_zlg_tim_timing_dev_t *p_dev = (am_zlg_tim_timing_dev_t *)p_drv; if ((p_dev == NULL) || (p_freq == NULL)) { return -AM_EINVAL; } /* 获取当前系统时钟频率,systick 使用的是系统时钟 */ *p_freq = am_clk_rate_get(p_dev->p_devinfo->clk_num); return AM_OK; } /******************************************************************************/ static int __tim_timing_prescale_set (void *p_drv, uint8_t chan, uint32_t prescale) { am_zlg_tim_timing_dev_t *p_dev = (am_zlg_tim_timing_dev_t *)p_drv; amhw_zlg_tim_t *p_hw_tim; if ((p_drv == NULL) || (chan != 0)) { return -AM_EINVAL; } p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; if ((prescale != 0) && (prescale <= 65536)) { amhw_zlg_tim_prescale_set(p_hw_tim, prescale - 1); /* 设置分频值 */ return AM_OK; } return -AM_ENOTSUP; } /******************************************************************************/ static int __tim_timing_prescale_get (void *p_drv, uint8_t chan, uint32_t *p_prescale) { am_zlg_tim_timing_dev_t *p_dev = (am_zlg_tim_timing_dev_t *)p_drv; amhw_zlg_tim_t *p_hw_tim; if ((p_dev == NULL) || (p_prescale == NULL) || (chan != 0)) { return -AM_EINVAL; } p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; /* 获取分频值 */ *p_prescale = amhw_zlg_tim_prescale_get(p_hw_tim); return AM_OK; } /******************************************************************************/ static int __tim_timing_count_get (void *p_drv, uint8_t chan, void *p_count) { am_zlg_tim_timing_dev_t *p_dev = (am_zlg_tim_timing_dev_t *)p_drv; amhw_zlg_tim_t *p_hw_tim; if ((p_dev == NULL) || (p_count == NULL) || (chan != 0)) { return -AM_EINVAL; } p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; *(uint32_t *)p_count = amhw_zlg_tim_count_get(p_hw_tim); return AM_OK; } /******************************************************************************/ static int __tim_timing_rollover_get (void *p_drv,uint8_t chan,void *p_rollover) { am_zlg_tim_timing_dev_t *p_dev = (am_zlg_tim_timing_dev_t *)p_drv; amhw_zlg_tim_t *p_hw_tim; if ((p_dev == NULL) || (p_rollover == NULL) || (chan != 0)) { return -AM_EINVAL; } p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; *(uint32_t *)p_rollover = amhw_zlg_tim_arr_get(p_hw_tim); return AM_OK; } /******************************************************************************/ static int __tim_timing_disable (void *p_drv, uint8_t chan) { am_zlg_tim_timing_dev_t *p_dev = (am_zlg_tim_timing_dev_t *)p_drv; amhw_zlg_tim_t *p_hw_tim; if ((p_dev == NULL) || (chan != 0)) { return -AM_EINVAL; } p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; amhw_zlg_tim_disable(p_hw_tim); /* 禁能更新中断 */ amhw_zlg_tim_int_disable(p_hw_tim, AMHW_ZLG_TIM_UIE); return AM_OK; } /******************************************************************************/ static int __tim_timing_enable (void *p_drv, uint8_t chan, void *p_count) { am_zlg_tim_timing_dev_t *p_dev = (am_zlg_tim_timing_dev_t *)p_drv; amhw_zlg_tim_t *p_hw_tim; if ((p_dev == NULL) || (chan != 0) || (p_count == NULL)) { return -AM_EINVAL; } p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; /* 设置自动重装寄存器的值 */ amhw_zlg_tim_arr_set(p_hw_tim, *((uint32_t *)p_count)); /* 计数器清0 */ amhw_zlg_tim_count_set(p_hw_tim, 0); /* 产生更新事件,重新初始化Prescaler计数器 及Repetition计数器 */ amhw_zlg_tim_egr_set(p_hw_tim, AMHW_ZLG_TIM_UG); /* 更新定时器时会产生更新事件,清除标志位 */ amhw_zlg_tim_status_flg_clr(p_hw_tim, AMHW_ZLG_TIM_UG); if (p_dev->pfn_callback != NULL) { /* 允许更新中断 */ amhw_zlg_tim_int_enable(p_hw_tim, AMHW_ZLG_TIM_UIE); } /* 使能定时器TIM允许计数 */ amhw_zlg_tim_enable(p_hw_tim); return AM_OK; } /******************************************************************************/ static int __tim_timing_callback_set (void *p_drv, uint8_t chan, void (*pfn_callback)(void *), void *p_arg) { am_zlg_tim_timing_dev_t *p_dev = (am_zlg_tim_timing_dev_t *)p_drv; amhw_zlg_tim_t *p_hw_tim; if ((p_dev == NULL) || (chan != 0)) { return -AM_EINVAL; } p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; /* 不需要开启中断 */ if (pfn_callback == NULL) { amhw_zlg_tim_int_disable(p_hw_tim, AMHW_ZLG_TIM_UIE); } else { p_dev->pfn_callback = pfn_callback; p_dev->p_arg = p_arg; } return AM_OK; } /******************************************************************************* Public functions *******************************************************************************/ am_timer_handle_t am_zlg_tim_timing_init ( am_zlg_tim_timing_dev_t *p_dev, const am_zlg_tim_timing_devinfo_t *p_devinfo) { amhw_zlg_tim_t *p_hw_tim = NULL; if (NULL == p_dev || NULL == p_devinfo ) { return NULL; } if (p_devinfo->pfn_plfm_init) { p_devinfo->pfn_plfm_init(); } p_dev->p_devinfo = p_devinfo; p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; p_dev->timer_serv.p_funcs = (struct am_timer_drv_funcs *)&__g_tim_timing_drv_funcs; p_dev->timer_serv.p_drv = p_dev; p_dev->pfn_callback = NULL; p_dev->p_arg = NULL; if ((p_devinfo->tim_type == AMHW_ZLG_TIM_TYPE0) || (p_devinfo->tim_type == AMHW_ZLG_TIM_TYPE1)) { /* 边沿对齐模式 */ amhw_zlg_tim_cms_set(p_hw_tim, 0); /* 向上计数 */ amhw_zlg_tim_dir_set(p_hw_tim, 0); } /* 设置时钟分割:TDTS = Tck_tin */ amhw_zlg_tim_ckd_set(p_hw_tim, 0); /* 允许更新事件 */ amhw_zlg_tim_udis_enable(p_hw_tim); am_int_connect(p_dev->p_devinfo->inum, __tim_irq_handler, (void *)p_dev); am_int_enable(p_dev->p_devinfo->inum); return &(p_dev->timer_serv); } /******************************************************************************/ void am_zlg_tim_timing_deinit (am_timer_handle_t handle) { am_zlg_tim_timing_dev_t *p_dev = (am_zlg_tim_timing_dev_t *)handle; amhw_zlg_tim_t *p_hw_tim = NULL; if (p_dev == NULL || p_dev->p_devinfo == NULL ) { return ; } p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; /* 关闭更新中断 */ amhw_zlg_tim_int_disable(p_hw_tim, AMHW_ZLG_TIM_UIE); /* 关闭时钟,停止计数 */ amhw_zlg_tim_disable(p_hw_tim); am_int_disconnect(p_dev->p_devinfo->inum, __tim_irq_handler, (void *)p_dev); am_int_disable(p_dev->p_devinfo->inum); p_dev->timer_serv.p_drv = NULL; if (p_dev->p_devinfo->pfn_plfm_deinit) { p_dev->p_devinfo->pfn_plfm_deinit(); } } /* end of file */
11,718
C
.c
275
34.741818
89
0.457675
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,495
am_zlg_tim_pwm.c
skyformat99_ametal/soc/zlg/drivers/source/tim/am_zlg_tim_pwm.c
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief 定时器TIM驱动,PWM驱动层实现 * * \internal * \par Modification history * - 1.00 17-04-21 nwt, first implementation * \endinternal */ #include "am_zlg_tim_pwm.h" #include "am_int.h" #include "am_clk.h" #include "am_gpio.h" /******************************************************************************* * 函数声明 *******************************************************************************/ /** \brief 配置PWM */ static int __tim_pwm_config (void *p_drv, int chan, unsigned long duty_ns, unsigned long period_ns); /** \brief 使能PWM输出 */ static int __tim_pwm_enable (void *p_drv, int chan); /** \brief 禁能PWM输出 */ static int __tim_pwm_disable (void *p_drv, int chan); /** \brief PWM驱动函数 */ static const struct am_pwm_drv_funcs __g_tim_pwm_drv_funcs = { __tim_pwm_config, __tim_pwm_enable, __tim_pwm_disable, }; /******************************************************************************/ /** \brief 配置PWM */ static int __tim_pwm_config (void *p_drv, int chan, unsigned long duty_ns, unsigned long period_ns) { am_zlg_tim_pwm_dev_t *p_dev = (am_zlg_tim_pwm_dev_t *)p_drv; amhw_zlg_tim_t *p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; uint32_t clkfreq; uint32_t period_c, duty_c, temp; uint16_t pre_real = 1, pre_reg = 0; /* 参数不合法 */ if ((period_ns == 0) || (duty_ns > 4294967295UL) || (period_ns > 4294967295UL) || (duty_ns > period_ns)) { return -AM_EINVAL; } /* 有效通道范围 0 ~ (channels_num - 1) */ if (chan >= p_dev->p_devinfo->channels_num) { return -AM_EINVAL; } clkfreq = am_clk_rate_get(p_dev->p_devinfo->clk_num); /* 计算出来得到的是计数值CNT, 公式ns * 10e-9= cnt * (1/clkfrq) */ period_c = (uint64_t)(period_ns) * (clkfreq) / (uint64_t)1000000000; duty_c = (uint64_t)(duty_ns) * (clkfreq) / (uint64_t)1000000000; { /* 当计数小于65536时,不分频(值为1,1代表为1分频) */ temp = period_c / 65536 + 1; /* 16位定时器需要运算取得合适的分频值 */ for (pre_real = 1; pre_real < temp; ) { pre_reg++; /* 计算写入寄存器的分频值0,1,2,... */ pre_real++; /* 分频数 */ } } /* 写入分频值 */ amhw_zlg_tim_prescale_set(p_hw_tim, pre_reg); /* 重新计算PWM的周期及脉冲频率 */ period_c = period_c / pre_real; duty_c = duty_c / pre_real; /* 共用一个重载寄存器,PWM波所有的周期都相同 */ amhw_zlg_tim_arr_set(p_hw_tim, period_c - 1); /* 使能定ARR预装载 */ amhw_zlg_tim_arpe_enable(p_hw_tim); /* Low level time */ duty_c = period_c - duty_c; /* 填充的值为PWM输出低电平的时间 */ amhw_zlg_tim_ccr_ouput_reload_val_set(p_hw_tim, duty_c - 1, chan); /* 选择该通道为输出 */ amhw_zlg_tim_ccs_set(p_hw_tim, 0, chan); /* 选择该通道的PWM模式 */ amhw_zlg_tim_ocm_set(p_hw_tim, p_dev->p_devinfo->pwm_mode, chan); /* PWM输出通道预装载使能 */ amhw_zlg_tim_ccs_ocpe_enable(p_hw_tim, chan); if ((p_dev->p_devinfo->tim_type == AMHW_ZLG_TIM_TYPE0) || (p_dev->p_devinfo->tim_type == AMHW_ZLG_TIM_TYPE2) || (p_dev->p_devinfo->tim_type == AMHW_ZLG_TIM_TYPE3)) { /* 设置CR2寄存器确定N极极性 */ } /* 设置比较输出通道高电平极性有效 */ amhw_zlg_tim_ccp_output_set(p_hw_tim, p_dev->p_devinfo->ocpolarity, chan); return AM_OK; } /** * \brief 使能PWM通道输出 */ static int __tim_pwm_enable (void *p_drv, int chan) { am_zlg_tim_pwm_dev_t *p_dev = (am_zlg_tim_pwm_dev_t *)p_drv; amhw_zlg_tim_t *p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; am_zlg_tim_pwm_ioinfo_t *p_ioinfo = p_dev->p_devinfo->p_ioinfo; /* 有效通道范围 0 ~ (channels_num - 1) */ if (chan >= p_dev->p_devinfo->channels_num) { return -AM_EINVAL; } am_gpio_pin_cfg(p_ioinfo[chan].gpio, p_ioinfo[chan].func); /* 使能通道PWM输出 */ amhw_zlg_tim_cce_output_enable(p_hw_tim, chan); /* 高级定时器使能主输出MOE */ if ((p_dev->p_devinfo->tim_type == AMHW_ZLG_TIM_TYPE0) || (p_dev->p_devinfo->tim_type == AMHW_ZLG_TIM_TYPE2) || (p_dev->p_devinfo->tim_type == AMHW_ZLG_TIM_TYPE3)) { amhw_zlg_tim_bdtr_enable(p_hw_tim, AMHW_ZLG_TIM_MOE); } /* 产生更新事件,重新初始化Prescaler计数器及Repetition计数器 */ amhw_zlg_tim_egr_set(p_hw_tim, AMHW_ZLG_TIM_UG); if (amhw_zlg_tim_status_flg_get(p_hw_tim, AMHW_ZLG_TIM_UG) != 0) { /* 更新定时器时会产生更新事件,清除标志位 */ amhw_zlg_tim_status_flg_clr(p_hw_tim, AMHW_ZLG_TIM_UG); } /* 使能定时器TIM允许计数 */ amhw_zlg_tim_enable(p_hw_tim); return AM_OK; } /** * \brief 禁能PWM通道输出 */ static int __tim_pwm_disable (void *p_drv, int chan) { am_zlg_tim_pwm_dev_t *p_dev = (am_zlg_tim_pwm_dev_t *)p_drv; amhw_zlg_tim_t *p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; am_zlg_tim_pwm_ioinfo_t *p_ioinfo = p_dev->p_devinfo->p_ioinfo; /* 有效通道范围 0 ~ (channels_num - 1) */ if (chan >= p_dev->p_devinfo->channels_num) { return -AM_EINVAL; } am_gpio_pin_cfg(p_ioinfo[chan].gpio, p_ioinfo[chan].dfunc); /* 禁能定时器TIM允许计数 */ amhw_zlg_tim_disable(p_hw_tim); /* 禁能通道PWM输出 */ amhw_zlg_tim_cce_output_disable(p_hw_tim, chan); /* 高级定时器禁能主输出MOE */ if ((p_dev->p_devinfo->tim_type == AMHW_ZLG_TIM_TYPE0) || (p_dev->p_devinfo->tim_type == AMHW_ZLG_TIM_TYPE2) || (p_dev->p_devinfo->tim_type == AMHW_ZLG_TIM_TYPE3)) { amhw_zlg_tim_bdtr_disable(p_hw_tim, AMHW_ZLG_TIM_MOE); } return AM_OK; } /** * \brief pwm初始化 */ void __tim_pwm_init (amhw_zlg_tim_t *p_hw_tim, amhw_zlg_tim_type_t type) { if ((type == AMHW_ZLG_TIM_TYPE0) || (type == AMHW_ZLG_TIM_TYPE1)) { /* 边沿对齐模式 */ amhw_zlg_tim_cms_set(p_hw_tim, 0); /* 向上计数 */ amhw_zlg_tim_dir_set(p_hw_tim, 0); } /* 设置时钟分割(用于确定输入滤波器的输入时钟频率,默认 Fdts = Fck_in */ amhw_zlg_tim_ckd_set(p_hw_tim, 0); /* 清零计数器 */ amhw_zlg_tim_count_set(p_hw_tim, 0); /* 设置分频器 */ amhw_zlg_tim_prescale_set(p_hw_tim, 0x00); /* 允许更新事件 */ amhw_zlg_tim_udis_enable(p_hw_tim); } /** * \brief tim pwm服务初始化 */ am_pwm_handle_t am_zlg_tim_pwm_init (am_zlg_tim_pwm_dev_t *p_dev, const am_zlg_tim_pwm_devinfo_t *p_devinfo) { amhw_zlg_tim_t *p_hw_tim = NULL; if (p_dev == NULL || p_devinfo == NULL) { return NULL; } if (p_devinfo->pfn_plfm_init) { p_devinfo->pfn_plfm_init(); } p_dev->p_devinfo = p_devinfo; p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; p_dev->pwm_serv.p_funcs = (struct am_pwm_drv_funcs *)&__g_tim_pwm_drv_funcs; p_dev->pwm_serv.p_drv = p_dev; __tim_pwm_init(p_hw_tim, p_devinfo->tim_type); return &(p_dev->pwm_serv); } void am_zlg_tim_pwm_deinit (am_pwm_handle_t handle) { am_zlg_tim_pwm_dev_t *p_dev = (am_zlg_tim_pwm_dev_t *)handle; amhw_zlg_tim_t *p_hw_tim = NULL; if (p_dev == NULL ) { return; } p_hw_tim = (amhw_zlg_tim_t *)p_dev->p_devinfo->tim_regbase; /* 清零计数器 */ amhw_zlg_tim_count_set(p_hw_tim, 0); /* 禁能定时器TIM允许计数 */ amhw_zlg_tim_disable(p_hw_tim); p_dev->pwm_serv.p_drv = NULL; if (p_dev->p_devinfo->pfn_plfm_deinit) { p_dev->p_devinfo->pfn_plfm_deinit(); } } /* end of file */
8,572
C
.c
219
30.360731
89
0.514896
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,513
am_usb_hci.h
skyformat99_ametal/interface/am_usb_hci.h
/* * Copyright (c) 2015, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _USB_HOST_HCI_H_ #define _USB_HOST_HCI_H_ #include "am_usbh.h" /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief USB host lock */ #define USB_HostLock() am_usb_osa_mutex_lock(hostInstance->hostMutex) /*! @brief USB host unlock */ #define USB_HostUnlock() am_usb_osa_mutex_unlock(hostInstance->hostMutex) /*! * @addtogroup usb_host_controller_driver * @{ */ /*! @brief USB host controller control code */ typedef enum am_usbh_controller_control { AM_USBH_CANCEL_TRANSFER = 1U, /*!< Cancel transfer code */ AM_USBH_BUS_CONTROL, /*!< Bus control code */ AM_USBH_GET_FRAME_NUMBER, /*!< Get frame number code */ AM_USBH_UPDATE_CONTROL_ENDPOINT_ADDRESS, /*!< Update control endpoint address */ AM_USBH_UPDATE_CONTROL_PACKET_SIZE, /*!< Update control endpoint maximum packet size */ } am_usbh_controller_control_t; /*! @brief USB host controller bus control code */ typedef enum am_usbh_bus_control { AM_USBH_BUS_RESET = 1U, /*!< Reset bus */ AM_USBH_BUS_RESTART, /*!< Restart bus */ AM_USBH_BUS_ENABLE_ATTACH, /*!< Enable attach */ AM_USBH_BUS_DISABLE_ATTACH, /*!< Disable attach*/ } am_usbh_bus_control_t; /*! @brief USB host controller interface structure */ typedef struct am_usbh_controller_interface { am_usb_status_t (*controllerCreate)( am_usbh_controller_handle_t controllerHandle); am_usb_status_t (*controllerDestory)( am_usbh_controller_handle_t controllerHandle); /*!< Destroy a controller instance function prototype*/ am_usb_status_t (*controllerOpenPipe)(am_usbh_controller_handle_t controllerHandle, am_usbh_pipe_handle_t *pipe_handle, am_usbh_pipe_init_t *pipeInit); /*!< Open a controller pipe function prototype*/ am_usb_status_t (*controllerClosePipe)( am_usbh_controller_handle_t controllerHandle, am_usbh_pipe_handle_t pipe_handle); /*!< Close a controller pipe function prototype*/ am_usb_status_t (*controllerWritePipe)(am_usbh_controller_handle_t controllerHandle, am_usbh_pipe_handle_t pipe_handle, am_usbh_transfer_t *transfer); /*!< Write data to a pipe function prototype*/ am_usb_status_t (*controllerReadPipe)(am_usbh_controller_handle_t controllerHandle, am_usbh_pipe_handle_t pipe_handle, am_usbh_transfer_t *transfer); /*!< Read data from a pipe function prototype*/ am_usb_status_t (*controllerIoctl)(am_usbh_controller_handle_t controllerHandle, uint32_t ioctlEvent, void *ioctlParam); /*!< Control a controller function prototype*/ } am_usbh_controller_interface_t; /*! @}*/ /*! * @addtogroup usb_host_drv * @{ */ /*! @brief USB host instance structure */ typedef struct _usb_host_instance { void *controllerHandle; /*!< The low level controller handle*/ pfn_usbh_callback_t deviceCallback; /*!< Device attach/detach callback*/ am_usb_osa_mutex_handle_t hostMutex; /*!< Host layer mutex*/ am_usbh_transfer_t transferList[USB_HOST_CONFIG_MAX_TRANSFERS]; /*!< Transfer resource*/ am_usbh_transfer_t *transferHead; /*!< Idle transfer head*/ const am_usbh_controller_interface_t *controllerTable; /*!< KHCI/EHCI interface*/ void *deviceList; /*!< Device list*/ uint8_t addressBitMap[16]; /*!< Used for address allocation. The first bit is the address 1, second bit is the address 2*/ uint8_t occupied; /*!< 0 - the instance is not occupied; 1 - the instance is occupied*/ uint8_t controllerId; /*!< The controller ID*/ } am_usbh_instance_t; /*! @}*/ #endif /* _USB_HOST_HCI_H_ */
5,931
C
.c
105
49.342857
120
0.628448
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,533
am_zlg600.h
skyformat99_ametal/components/drivers/include/am_zlg600.h
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief ZLG600底层驱动程序 * * \internal * \par Modification history * - 1.01 16-08-03 sky, modified. * - 1.00 15-09-03 tee, first implementation. * \endinternal */ #ifndef __AM_ZLG600_H #define __AM_ZLG600_H #include "am_types.h" #include "am_uart_rngbuf.h" #include "am_i2c.h" /** * @addtogroup am_if_zlg600 * @copydoc am_zlg600.h * @{ */ /** * \name ZLG600的通信模式与主从模式 * @{ */ #define AM_ZLG600_MODE_AUTO_CHECK 0 /**< \brief 自动检测模式 */ #define AM_ZLG600_MODE_I2C 1 /**< \brief I2C模式 */ #define AM_ZLG600_MODE_UART 2 /**< \brief 串口模式 */ #define AM_ZLG600_MODE_MASTER (1 << 4) /**< \brief 主机模式(保留功能) */ #define AM_ZLG600_MODE_SLAVE (0 << 4) /**< \brief 从机模式(默认) */ /** @}*/ /** * \name ZLG600的连接方式 * @{ */ #define AM_ZLG600_CMNT_UART 0 /**< \brief UART连接 */ #define AM_ZLG600_CMNT_I2C 1 /**< \brief I2C连接 */ /** @} */ /** * \name ZLG600的帧格式 * @{ */ #define AM_ZLG600_FRAME_FMT_OLD 0 /**< \brief 旧帧格式 */ #define AM_ZLG600_FRAME_FMT_NEW 1 /**< \brief 新帧格式 */ /** @} */ /** * \name 支持的波特率 * @{ */ #define AM_ZLG600_BAUDRATE_9600 9600 /**< \brief 波特率 9600 */ #define AM_ZLG600_BAUDRATE_19200 19200 /**< \brief 波特率 19200 */ #define AM_ZLG600_BAUDRATE_28800 28800 /**< \brief 波特率 28800 */ #define AM_ZLG600_BAUDRATE_38400 38400 /**< \brief 波特率 38400 */ #define AM_ZLG600_BAUDRATE_57600 57600 /**< \brief 波特率 57600 */ #define AM_ZLG600_BAUDRATE_115200 115200 /**< \brief 波特率 115200 */ #define AM_ZLG600_BAUDRATE_172800 172800 /**< \brief 波特率 172800 */ #define AM_ZLG600_BAUDRATE_230400 230400 /**< \brief 波特率 230400 */ /** @}*/ /** * \brief ZLG600自动检测信息结构体 */ typedef struct am_zlg600_auto_detect_info { /** * \brief 检测模式,配置检测动作,是否产生中断、继续检测、完成动作等 #AM_ZLG600_MIFARE_CARD_AD_HALT */ uint8_t ad_mode; /** * \brief 天线驱动模式,交替驱动、仅其中一种驱动、同时驱动 #AM_ZLG600_MIFARE_CARD_TX_TX1 */ uint8_t tx_mode; /** * \brief 请求模式,请求空闲卡或所有卡 #AM_ZLG600_MIFARE_CARD_REQ_IDLE */ uint8_t req_mode; /** * \brief 验证模式,E2秘钥验证、直接验证或不验证 #AM_ZLG600_MIFARE_CARD_AUTH_E2 */ uint8_t auth_mode; /**< \brief 验证模式 */ /** * \brief 密钥类型,#AM_ZLG600_IC_KEY_TYPE_A 或 #AM_ZLG600_IC_KEY_TYPE_B * 如果auth_mode选择的是AM_ZLG600_MIFARE_CARD_AUTH_NO, * 则key_type可以为任意值 */ uint8_t key_type; /** \brief 密钥 */ uint8_t key[16]; /** \brief 密钥长度 */ uint8_t key_len; /** * \brief 验证块号 * S50( 0~63) * S70( 0~255) * PLUS CPU 2K( 0~127) * PLUS CPU 4K( 0~255) */ uint8_t nblock; } am_zlg600_auto_detect_info_t; /** * \brief 标准的ZLG600设备服务结构体定义 */ typedef struct am_zlg600_serv { void *p_cookie; /**< \brief 参数,仅供内部使用 */ uint32_t timeout_ms; /**< \brief 命令等待时间(毫秒) */ uint8_t frame_seq; /**< \brief 记录包号 */ uint8_t work_mode; /**< \brief 当前使用的工作模式(主从模式) */ uint8_t cur_addr; /**< \brief 当前传输的地址(7bit) */ uint8_t auto_detect; /**< \brief 自动检测模式 */ uint8_t auto_detect_read; /**< \brief 自动检测读标志 */ am_pfnvoid_t pfn_callback; /**< \brief 回调函数 */ void *p_arg; /**< \brief 回调函数的参数 */ am_pfnvoid_t pfn_cmd_timeout_set; /**< \brief 指令超时时间设置 */ am_pfnvoid_t pfn_frame_proc; /**< \brief 帧处理函数 */ am_pfnvoid_t pfn_auto_detect_trigger_set; /**< \brief 自动检测触发设置 */ am_zlg600_auto_detect_info_t *p_auto_detect_info; /**< \brief 自动检测信息 */ } am_zlg600_serv_t; /** * \brief ZLG600标准服务handle定义 */ typedef am_zlg600_serv_t *am_zlg600_handle_t; /** * \brief ZLG600(串口通信)设备定义 */ typedef struct am_zlg600_uart_dev { /** \brief ZLG600 标准服务 */ am_zlg600_serv_t zlg600_serv; /** \brief 串口(带缓冲区)设备 */ am_uart_rngbuf_dev_t uart_ringbuf_dev; /** \brief 串口(带缓冲区)标准服务handle */ am_uart_rngbuf_handle_t uart_ringbuf_handle; /** \brief 帧处理函数 */ am_pfnvoid_t pfn_frame_proc; } am_zlg600_uart_dev_t; /** * \brief ZLG600 (UART通信模式) 信息定义 */ typedef struct am_zlg600_uart_dev_info { /** \brief 用于串口接收的缓冲区,建议大小在64以上 */ uint8_t *p_uart_rxbuf; /** \brief 用于串口发送的缓冲区,建议大小在64以上 */ uint8_t *p_uart_txbuf; /** \brief 用于串口接收的缓冲区大小 */ uint16_t rxbuf_size; /** \brief 用于串口发送的缓冲区大小 */ uint16_t txbuf_size; /** \brief 与ZLG600通信的波特率(UART模式下使用) */ uint32_t baudrate; /** \brief 初始化时使用的模式 #AM_ZLG600_MODE_AUTO_CHECK */ uint8_t now_mode; /** \brief ZLG600的从机地址(7bit) */ uint8_t local_addr; } am_zlg600_uart_dev_info_t; /** * \brief ZLG600(I2C通信)设备定义 */ typedef struct am_zlg600_i2c_dev { /** \brief ZLG600 标准服务 */ am_zlg600_serv_t zlg600_serv; /** \brief I2C标准服务句柄 */ am_i2c_handle_t i2c_handle; /** \brief 中断引脚 */ int pin; /** \brief I2C transfer 缓存地址 */ am_i2c_transfer_t *p_trans; /** \brief I2C transfer 缓存长度 */ uint8_t trans_len; /** \brief 用于等待I2C传输结束 */ am_wait_t wait; /** \brief 帧处理函数 */ am_pfnvoid_t pfn_frame_proc; } am_zlg600_i2c_dev_t; /** * \brief ZLG600 (I2C通信模式) 信息定义 */ typedef struct am_zlg600_i2c_dev_info { /** \brief 中断引脚,使用I2C通信时,需要使用到一个中断引脚 */ int pin; /** \brief ZLG600的从机地址(7bit) */ uint8_t local_addr; /** \brief 初始化时使用的模式 #AM_ZLG600_MODE_AUTO_CHECK */ uint8_t now_mode; /** \brief I2C transfer 缓存地址 */ am_i2c_transfer_t *p_trans; /** \brief I2C transfer 缓存长度(目前最大指令长需要9个trans) */ uint8_t trans_len; } am_zlg600_i2c_dev_info_t; /** * \brief 初始化ZLG600(使用UART旧帧通信模式),获取到操作ZLG600的标准服务handle * * 务必根据实际硬件使用何种通信连接方式选择,如使用UART,则使用该函数初始化 * 以获得handle,否则,请使用am_zlg600_i2c_init()函数获得handle。 * * \param[in] p_dev : 指向ZLG600设备的指针 * \param[in] uart_handle : 与ZLG600关联的UART,后续使用该handle进行UART通信 * \param[in] p_uart_info : UART通信模式相关信息 * * \return 操作 ZLG600 的操作句柄,如果初始化失败,则返回NULL */ am_zlg600_handle_t am_zlg600_uart_old_init (am_zlg600_uart_dev_t *p_dev, am_uart_handle_t uart_handle, const am_zlg600_uart_dev_info_t *p_uart_info); /** * \brief 初始化ZLG600(使用UART新帧通信模式),获取到操作ZLG600的标准服务handle * * 务必根据实际硬件使用何种通信连接方式选择,如使用UART,则使用该函数初始化 * 以获得handle,否则,请使用am_zlg600_i2c_init()函数获得handle。 * * \param[in] p_dev : 指向ZLG600设备的指针 * \param[in] uart_handle : 与ZLG600关联的UART,后续使用该handle进行UART通信 * \param[in] p_uart_info : UART通信模式相关信息 * * \return 操作 ZLG600 的操作句柄,如果初始化失败,则返回NULL */ am_zlg600_handle_t am_zlg600_uart_new_init (am_zlg600_uart_dev_t *p_dev, am_uart_handle_t uart_handle, const am_zlg600_uart_dev_info_t *p_uart_info); /** * \brief 初始化ZLG600(使用I2C旧帧通信模式),获取到操作ZLG600的标准服务handle * * 务必根据实际硬件使用何种通信连接方式选择,如使用I2C,则使用该函数初始化 * 以获得handle,否则,请使用am_zlg600_uart_init()函数获得handle。 * * \param[in] p_dev : 指向ZLG600设备的指针 * \param[in] i2c_handle : 与ZLG600关联的I2C,后续使用该handle进行I2C通信 * \param[in] p_i2c_info : I2C通信模式相关信息 * * \return 操作 ZLG600 的操作句柄,如果初始化失败,则返回NULL */ am_zlg600_handle_t am_zlg600_i2c_old_init (am_zlg600_i2c_dev_t *p_dev, am_i2c_handle_t i2c_handle, const am_zlg600_i2c_dev_info_t *p_i2c_info); /** * \brief 初始化ZLG600(使用I2C新帧通信模式),获取到操作ZLG600的标准服务handle * * 务必根据实际硬件使用何种通信连接方式选择,如使用I2C,则使用该函数初始化 * 以获得handle,否则,请使用am_zlg600_uart_init()函数获得handle。 * * \param[in] p_dev : 指向ZLG600设备的指针 * \param[in] i2c_handle : 与ZLG600关联的I2C,后续使用该handle进行I2C通信 * \param[in] p_i2c_info : I2C通信模式相关信息 * * \return 操作 ZLG600 的操作句柄,如果初始化失败,则返回NULL */ am_zlg600_handle_t am_zlg600_i2c_new_init (am_zlg600_i2c_dev_t *p_dev, am_i2c_handle_t i2c_handle, const am_zlg600_i2c_dev_info_t *p_i2c_info); /** * \brief 读ZLG600的产品、版本信息,如:“ZLG600SP/T V1.00” * * \param[in] handle : ZLG600的操作句柄 * \param[in] p_info : 用于装载获取信息的缓冲区,大小应为 20 字节 * * \retval AM_OK : 读取信息成功 * \retval -AM_EINVAL : 读取信息失败,参数错误 * \retval -AM_EIO : 读取信息失败,数据通信出错 */ int am_zlg600_info_get (am_zlg600_handle_t handle, uint8_t *p_info); /** * \brief 配置IC卡接口,执行成功后,启动IC卡接口,启动后默认支持TypeA卡 * * \param[in] handle : ZLG600的操作句柄 * * \retval AM_OK : 配置成功 * \retval -AM_EINVAL : 配置失败,参数错误 * \retval -AM_EIO : 配置失败,数据通信出错 */ int am_zlg600_ic_port_config (am_zlg600_handle_t handle); /** * \brief 关闭IC卡接口 * * \param[in] handle : ZLG600的操作句柄 * * \retval AM_OK : 关闭成功 * \retval -AM_EINVAL : 关闭失败,参数错误 * \retval -AM_EIO : 关闭失败,数据通信出错 */ int am_zlg600_ic_port_close (am_zlg600_handle_t handle); /** * \name IC卡接口的协议(工作模式) * @{ */ #define AM_ZLG600_IC_ISOTYPE_A 0x00 /**< \brief ISO14443-3A */ #define AM_ZLG600_IC_ISOTYPE_B 0x04 /**< \brief ISO14443-3B */ /** @}*/ /** * \brief 设置IC卡接口协议(工作模式)TypeA 或者 TypeB * * \param[in] handle : ZLG600的操作句柄 * \param[in] isotype : IC卡接口的协议类型,使用下列宏 : * - #AM_ZLG600_IC_ISOTYPE_A * - #AM_ZLG600_IC_ISOTYPE_B * * \retval AM_OK : 设置成功 * \retval -AM_EINVAL : 设置失败,参数错误 * \retval -AM_EIO : 设置失败,数据通信出错 */ int am_zlg600_ic_isotype_set (am_zlg600_handle_t handle, uint8_t isotype); /** * \name IC卡密匙类型 * @{ */ #define AM_ZLG600_IC_KEY_TYPE_A 0x60 /**< \brief 类型 A */ #define AM_ZLG600_IC_KEY_TYPE_B 0x61 /**< \brief 类型 B */ /** @}*/ /** * \brief 装载IC卡密钥 * * 将输入的密钥保存在模块内部,模块掉电后该密钥不丢失,ZLG600SP/T模块共能保存 * A密钥16组、B密钥16组。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] key_type : 密钥类型,可以使用下列值: * - #AM_ZLG600_IC_KEY_TYPE_A * - #AM_ZLG600_IC_KEY_TYPE_B * \param[in] key_sec : 密钥保存的区号,共可保存16组密钥,区号:0 ~ 15 * \param[in] p_key : 密钥缓冲区 * \param[in] key_length : 密钥的长度,只能为6(6字节密钥)或16(16字节密钥) * * \retval AM_OK : 装载密钥成功 * \retval -AM_EINVAL : 装载失败,参数错误 * \retval -AM_EIO : 装载失败,数据通信出错 */ int am_zlg600_ic_key_load (am_zlg600_handle_t handle, uint8_t key_type, uint8_t key_sec, uint8_t *p_key, uint8_t key_length); /** * \brief 设置IC卡接口的寄存器值 * * 用于设置模块上读写卡芯片内部的寄存器值,通过该命令,可以实现很多现有命令 * 不能完成的工作。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] reg_addr : 寄存器地址,范围:0x00 ~ 0x3F * \param[in] reg_val : 设置的寄存器值 * * \retval AM_OK : 设置成功 * \retval -AM_EINVAL : 设置失败,参数错误 * \retval -AM_EIO : 设置失败,数据通信出错 */ int am_zlg600_ic_reg_set (am_zlg600_handle_t handle, uint8_t reg_addr, uint8_t reg_val); /** * \brief 获取IC卡接口的寄存器值 * * 该命令用于设置模块上读写卡芯片内部的寄存器值, * 通过该命令,可以实现很多现有命令不能完成的工作。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] reg_addr : 寄存器地址,范围:0x00 ~ 0x3F * \param[out] p_val : 获取寄存器值的指针 * * \retval AM_OK : 获取成功 * \retval -AM_EINVAL : 获取失败,参数错误 * \retval -AM_EIO : 获取失败,数据通信出错 */ int am_zlg600_ic_reg_get (am_zlg600_handle_t handle, uint8_t reg_addr, uint8_t *p_val); /** * \brief 设置波特率 * * 用于在UART通信过程中改变通信的波特率,掉电后该设置值保留。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] baudrate_flag : 波特率标志,并不支持所有的波特率,应使用宏 * AM_ZLG600_BAUDRATE_* ,如设置波特率为115200, * 则使用宏 #AM_ZLG600_BAUDRATE_115200 * * \retval AM_OK : 设置成功 * \retval -AM_EINVAL : 设置失败,参数错误 * \retval -AM_EIO : 设置失败,数据通信出错 */ int am_zlg600_baudrate_set (am_zlg600_handle_t handle, uint32_t baudrate_flag); /** * \name 天线驱动方式 * @{ */ #define AM_ZLG600_ANT_TX1_ONLY 1 /**< \brief 仅TX1驱动天线 */ #define AM_ZLG600_ANT_TX2_ONLY 2 /**< \brief 仅TX2驱动天线 */ #define AM_ZLG600_ANT_TX1_AND_TX2 3 /**< \brief TX1、TX2同时驱动天线 */ #define AM_ZLG600_ANT_NONE 0 /**< \brief 同时关闭TX1、TX2 */ /** @}*/ /** * \brief 设置天线驱动方式,可以任意打开、关闭某个天线驱动引脚 * * \param[in] handle : ZLG600的操作句柄 * \param[in] antmode_flag : 使用宏 AM_ZLG600_ANT_*,如#AM_ZLG600_ANT_TX1_ONLY * * \retval AM_OK : 设置成功 * \retval -AM_EINVAL : 设置失败,参数错误 * \retval -AM_EIO : 设置失败,数据通信出错 */ int am_zlg600_ant_mode_set (am_zlg600_handle_t handle, uint8_t antmode_flag); /** * \brief 设置帧格式,用于切换新、旧帧格式,设置成功后掉电不丢失 * * \param[in] handle : ZLG600的操作句柄 * \param[in] flag : 帧格式宏标志,可使用下列宏: * - #AM_ZLG600_FRAME_FMT_NEW * - #AM_ZLG600_FRAME_FMT_OLD * * \retval AM_OK : 设置成功 * \retval -AM_EINVAL : 设置失败,参数错误 * \retval -AM_EIO : 设置失败,数据通信出错 * * \note 帧切换成功后需要重新调用目标帧格式的初始化函数。 */ int am_zlg600_frame_fmt_set (am_zlg600_handle_t handle, uint8_t flag); /** * \brief 设置设备工作模式和从机地址 * * \param[in] handle : ZLG600的操作句柄 * \param[in] mode : 模块的工作模式,可以使用下列宏值: * - #AM_ZLG600_MODE_MASTER 主机模式 * - #AM_ZLG600_MODE_SLAVE 从机模式 (默认) * - #AM_ZLG600_MODE_AUTO_CHECK 自动侦测模式 * - #AM_ZLG600_MODE_I2C I2C模式 * - #AM_ZLG600_MODE_UART UART模式 * * \param[in] new_addr : 设置的ZLG600从机地址,最后一位为0,有效值0x02 ~ 0xFE * * \retval AM_OK : 设置成功,设置成功后,后续应该使用新的地址通信 * \retval -AM_EINVAL : 设置失败,参数错误 * \retval -AM_EIO : 设置失败,数据通信出错 */ int am_zlg600_mode_addr_set (am_zlg600_handle_t handle, uint8_t mode, uint8_t new_addr); /** * \brief 获取设备工作模式和从机地址 * * \param[in] handle : ZLG600的操作句柄 * \param[out] p_mode : 用于获取模块工作模式的指针,获取的值各位含义如下: * - bit7 ~ 4:0,从机模式; 1,自动检测卡片模式(主机模式) * - bit3 ~ 0:0,自动侦测模式; 1,I2C通信模式; 2,UART模式 * \param[out] p_addr : 用于获取当前的ZLG600的从机地址的指针 * * \retval AM_OK : 获取成功 * \retval -AM_EINVAL : 获取失败,参数错误 * \retval -AM_EIO : 获取失败,数据通信出错 */ int am_zlg600_mode_addr_get (am_zlg600_handle_t handle, uint8_t *p_mode, uint8_t *p_addr); /** * \brief 装载用户密钥,模块里面提供了2个16字节的存储空间用于保存用户密钥。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] key_sec : 密钥保存的区号,共可保存2组用户密钥,区号:0 ~ 1 * \param[in] p_key : 密钥缓冲区,密钥的长度固定为16字节 * * \retval AM_OK : 装载密钥成功 * \retval -AM_EINVAL : 装载失败,参数错误 * \retval -AM_EIO : 装载失败,数据通信出错 */ int am_zlg600_user_key_load (am_zlg600_handle_t handle, uint8_t key_sec, uint8_t *p_key); /** * \brief 写EEPROM,模块内部拥有一个256Byte的EEPROM * * \param[in] handle : ZLG600的操作句柄 * \param[in] eeprom_addr : EEPROM的片内地址,0 ~ 255 * \param[in] p_buf : 写入数据的缓冲区 * \param[in] nbytes : 写入数据的字节数,最大247字节 * * \retval AM_OK : 写入数据成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 */ int am_zlg600_eeprom_write (am_zlg600_handle_t handle, uint8_t eeprom_addr, uint8_t *p_buf, uint8_t nbytes); /** * \brief 读EEPROM,模块内部拥有一个256Byte的EEPROM * * \param[in] handle : ZLG600的操作句柄 * \param[in] eeprom_addr : EEPROM的片内地址,0 ~ 255 * \param[out] p_buf : 读出数据的缓冲区 * \param[in] nbytes : 读出数据的字节数,最大249字节 * * \retval AM_OK : 读取数据成功 * \retval -AM_EINVAL : 读取失败,参数错误 * \retval -AM_EIO : 读取失败,数据通信出错 */ int am_zlg600_eeprom_read (am_zlg600_handle_t handle, uint8_t eeprom_addr, uint8_t *p_buf, uint8_t nbytes); /** * \name Mifare卡请求模式 * @{ */ #define AM_ZLG600_MIFARE_CARD_REQ_IDLE 0x26 /**< \brief IDLE模式,请求空闲的卡 */ #define AM_ZLG600_MIFARE_CARD_REQ_ALL 0x52 /**< \brief ALL模式,请求所有的卡 */ /** @}*/ /** * \brief Mifare卡请求操作 * * 该函数作为卡的请求操作,只要符合ISO14443A标准的卡都应能发出响应。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] req_mode : 请求模式,可使用下列宏: * - #AM_ZLG600_MIFARE_CARD_REQ_IDLE * - #AM_ZLG600_MIFARE_CARD_REQ_ALL * \param[in] p_atq : 获取请求应答信息(ATQ)的指针,其值为16位,不同卡 * 类型返回的信息不同,常见类型返回的ATQ如下: * * Mifare1 S50 | Mifare1 S70 | Mifare1 Light | Mifare0 UltraLight * --------------------|-------------|---------------|------------------- * 0x0004 | 0x0002 | 0x0010 | 0x0044 * ---------------------------------------------------------------------- * Mifare3 DESFire | SHC1101 | SHC1102 | 11RF32 * --------------------|-------------|---------------|------------------- * 0x0344 | 0x0004 | 0x3300 | 0x0004 * * \retval AM_OK : 请求成功 * \retval -AM_EINVAL : 请求失败,参数错误 * \retval -AM_EIO : 请求失败,数据通信出错 * * \note 卡进入天线后,从射频场中获取能量,从而得电复位,复位后卡处于IDLE模式, * 用两种请求模式的任一种请求时,此时的卡均能响应;若对某一张卡成功进行了挂起 * 操作(Halt命令或DeSelect命令),则进入了Halt模式,此时的卡只响应ALL(0x52) * 模式的请求,除非将卡离开天线感应区后再进入。 */ int am_zlg600_mifare_card_request (am_zlg600_handle_t handle, uint8_t req_mode, uint16_t *p_atq); /** * \name Mifare卡防碰撞等级 * @{ */ #define AM_ZLG600_MIFARE_CARD_ANTICOLL_1 0x93 /**< \brief 第一级防碰撞 */ #define AM_ZLG600_MIFARE_CARD_ANTICOLL_2 0x95 /**< \brief 第二级防碰撞 */ #define AM_ZLG600_MIFARE_CARD_ANTICOLL_3 0x97 /**< \brief 第三级防碰撞 */ /** @}*/ /** * \brief Mifare卡的防碰撞操作 * * 需要成功执行一次请求命令,并返回请求成功,才能进行防碰撞操作,否则返回错误。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] anticoll_level : 防碰撞等级,可使用下列宏: * - #AM_ZLG600_MIFARE_CARD_ANTICOLL_1 * - #AM_ZLG600_MIFARE_CARD_ANTICOLL_2 * - #AM_ZLG600_MIFARE_CARD_ANTICOLL_3 * * \param[in] know_uid : 已知的卡序列号 * \param[in] nbit_cnt : 位计数,表明已知的序列号uid的位数。其值小于32。 * - 若nbit_cnt值为0,则表明没有已知序列号,序列号的所有位 * 都要从本函数获得。 * - 若nbit_cnt不为0,则序列号中有已知的序列号的值,表示 * 序列号的前nbit_cnt位为已知序列号中所示前nbit_cnt位的 * 值,其余位需要本函数获得。 * \param[in] *p_uid : 防碰撞后获取到的卡序列号 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 * * \note 符合ISO14443A标准卡的序列号都是全球唯一的,正是这种唯一性,才能实现防 * 碰撞的算法逻辑,若有若干张卡同时在天线感应区内则这个函数能够找到一张序列号较 * 大的卡来操作。 */ int am_zlg600_mifare_card_anticoll (am_zlg600_handle_t handle, uint8_t anticoll_level, uint32_t know_uid, uint8_t nbit_cnt, uint32_t *p_uid); /** * \brief Mifare卡的选择操作 * * 需要成功执行一次防碰撞命令,并返回成功,才能进行卡选择操作,否则返回错误。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] anticoll_level : 防碰撞等级,可使用下列宏: * - #AM_ZLG600_MIFARE_CARD_ANTICOLL_1 * - #AM_ZLG600_MIFARE_CARD_ANTICOLL_2 * - #AM_ZLG600_MIFARE_CARD_ANTICOLL_3 * \param[in] uid : 前一个防碰撞函数获取的UID * \param[in] p_sak : 返回的信息,若bit2为1,则表明UID不完整 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 * * \note 卡的序列号长度有三种:4字节、7字节和10字节。 4字节的只要用一级选择即可 * 得到完整的序列号,如Mifare1 S50/S70等;7字节的要用二级选择才能得到完整的序列 * 号,前一级所得到的序列号的最低字节为级联标志0x88,在序列号内只有后3字节可用, * 后一级选择能得到4字节序列号,两者按顺序连接即为7字节序列号,如UltraLight * 和DesFire等;10字节的以此类推,但至今还未发现此类卡。 */ int am_zlg600_mifare_card_select (am_zlg600_handle_t handle, uint8_t anticoll_level, uint32_t uid, uint8_t *p_sak); /** * \brief Mifare卡的挂起操作,使所选择的卡进入HALT状态 * * 在HALT状态下,卡将不响应读卡器发出的IDLE模式的请求,除非将卡复位或离开天线感 * 应区后再进入。但它会响应读卡器发出的ALL请求。 * * \param[in] handle : ZLG600的操作句柄 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_mifare_card_halt (am_zlg600_handle_t handle); /** * \brief Mifare卡E2密钥验证 * * 用模块内部已存入的密钥与卡的密钥进行验证,使用该命令前应先用“装载IC卡密钥” * 函数把密钥成功载入模块内。另外,需要验证的卡的扇区号不必与模块内密钥区号相等。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] key_type : 密钥类型,可以使用下列值: * - #AM_ZLG600_IC_KEY_TYPE_A * - #AM_ZLG600_IC_KEY_TYPE_B * \param[in] p_uid : 卡序列号,4字节 * \param[in] key_sec : 密钥区号:0 ~ 7 * \param[in] nblock : 需要验证的卡块号,取值范围与卡类型有关, * - S50:0 ~ 63 * - S70:0 ~ 255 * - PLUS CPU 2K:0 ~ 127 * - PLUS CPU 4K:0 ~ 255 * * \retval AM_OK : 验证成功 * \retval -AM_EINVAL : 验证失败,参数错误 * \retval -AM_EIO : 验证失败,数据通信出错 * * \note PLUS CPU系列的卡的卡号有4字节和7字节之分,对于7字节卡号的卡, * 只需要将卡号的高4字节(等级2防碰撞得到的卡号)作为验证的卡号即可。 */ int am_zlg600_mifare_card_e2_authent (am_zlg600_handle_t handle, uint8_t key_type, uint8_t *p_uid, uint8_t key_sec, uint8_t nblock); /** * \brief Mifare卡直接密钥验证 * * 该命令将密码作为参数传递,因此在此之前不需用“装载IC卡密钥”命令。若当前卡 * 为PLUS CPU卡的等级2或等级3,且输入的密码只有6字节,则模块自动将输入的密码 * 复制2次,取前16字节作为当前验证密钥。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] key_type : 密钥类型,可以使用下列值: * - #AM_ZLG600_IC_KEY_TYPE_A * - #AM_ZLG600_IC_KEY_TYPE_B * \param[in] p_uid : 卡序列号,4字节 * \param[in] p_key : 密钥缓冲区 * \param[in] key_len : 密钥的长度,只能为6(6字节密钥)或16(16字节密钥) * \param[in] nblock : 需要验证的卡块号,取值范围与卡类型有关, * - S50:0 ~ 63 * - S70:0 ~ 255 * - PLUS CPU 2K:0 ~ 127 * - PLUS CPU 4K:0 ~ 255 * * \retval AM_OK : 验证成功 * \retval -AM_EINVAL : 验证失败,参数错误 * \retval -AM_EIO : 验证失败,数据通信出错 * * \note PLUS CPU系列的卡的卡号有4字节和7字节之分,对于7字节卡号的卡, * 只需要将卡号的高4字节(等级2防碰撞得到的卡号)作为验证的卡号即可。 */ int am_zlg600_mifare_card_direct_authent (am_zlg600_handle_t handle, uint8_t key_type, uint8_t *p_uid, uint8_t *p_key, uint8_t key_len, uint8_t nblock); /** * \brief Mifare卡数据读取 * * 在验证成功之后,才能读相应的块数据,所验证的块号与读块号必须在同一个扇区内, * Mifare1卡从块号0开始按顺序每4个块1个扇区,若要对一张卡中的多个扇区进行操作,在 * 对某一扇区操作完毕后,必须进行一条读命令才能对另一个扇区直接进行验证命令,否则 * 必须从请求开始操作。对于PLUS CPU卡,若下一个读扇区的密钥和当前扇区的密钥相同, * 则不需要再次验证密钥,直接读即可。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] nblock : 读取数据的块号 * - S50:0 ~ 63 * - S70:0 ~ 255 * - PLUS CPU 2K:0 ~ 127 * - PLUS CPU 4K:0 ~ 255 * \param[out] p_buf : 存放读取的数据,大小为 16 * * \retval AM_OK : 读取成功 * \retval -AM_EINVAL : 读取失败,参数错误 * \retval -AM_EIO : 读取失败,数据通信出错 */ int am_zlg600_mifare_card_read (am_zlg600_handle_t handle, uint8_t nblock, uint8_t *p_buf); /** * \brief Mifare卡写数据,写之前必需成功进行密钥验证。 * * 对卡内某一块进行验证成功后,即可对同一扇区的各个进行写操作(只要访问条件允许), * 其中包括位于扇区尾的密码块,这是更改密码的唯一方法。对于PLUS CPU卡等级2、3的AES密 * 钥则是在其他位置修改密钥。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] nblock : 读取数据的块号 * - S50:0 ~ 63 * - S70:0 ~ 255 * - PLUS CPU 2K:0 ~ 127 * - PLUS CPU 4K:0 ~ 255 * \param[in] p_buf : 写入数据缓冲区,大小必须为 16 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 */ int am_zlg600_mifare_card_write (am_zlg600_handle_t handle, uint8_t nblock, uint8_t *p_buf); /** * \brief Mifare卡写数据 * * \param[in] handle : ZLG600的操作句柄 * \param[in] nblock : 读取数据的块号, 1 ~ 15 * \param[in] p_buf : 写入数据缓冲区,大小必须为 4 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 * * 此命令只对UltraLight卡有效,对UltraLight卡进行读操作与Mifare1卡一样。 */ int am_zlg600_ultralight_card_write (am_zlg600_handle_t handle, uint8_t nblock, uint8_t *p_buf); /** * \name Mifare卡值操作模式 * @{ */ #define AM_ZLG600_MIFARE_CARD_VALUE_ADD 0xC1 /**< \brief 加 */ #define AM_ZLG600_MIFARE_CARD_VALUE_SUB 0xC0 /**< \brief 减 */ /** @}*/ /** * \brief Mifare值操作,对Mifare卡的值块进行加减操作 * * \param[in] handle : ZLG600的操作句柄 * \param[in] mode : 值操作的模式,可以是加或减,使用下列宏: * - AM_ZLG600_MIFARE_CARD_VALUE_ADD * - AM_ZLG600_MIFARE_CARD_VALUE_SUB * \param[in] nblock : 进行值操作的块号 * - S50:0 ~ 63 * - S70:0 ~ 255 * - PLUS CPU 2K:0 ~ 127 * - PLUS CPU 4K:0 ~ 255 * \param[in] ntransblk : 传输块号,计算结果值存放的块号 * \param[in] value : 4字节有符号数 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 * * \note 要进行此类操作,块数据必须要有值块的格式,可参考NXP的相关文档。若卡块 * 号与传输块号相同,则将操作后的结果写入原来的块内;若卡块号与传输块号不相同, * 则将操作后的结果写入传输块内,结果传输块内的数据被覆盖,原块内的值不变。 * 处于等级2的PLUS CPU卡不支持值块操作,等级1、3支持。 */ int am_zlg600_mifare_card_val_operate (am_zlg600_handle_t handle, uint8_t mode, uint8_t nblock, uint8_t ntransblk, int32_t value); /** * \brief Mifare卡复位,通过将载波信号关闭指定的时间,再开启来实现卡片复位。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] time_ms : 关闭的时间(单位:ms),0为一直关闭 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 * * \note 该函数将天线信号关闭数毫秒,若一直关闭,则等到执行一个请求命令时打开。 */ int am_zlg600_mifare_card_reset (am_zlg600_handle_t handle, uint8_t time_ms); /** * \brief Mifare卡激活,该函数用于激活卡片,是请求、防碰撞和选择三条命令的组合。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] req_mode : 请求模式,可使用下列宏: * - #AM_ZLG600_MIFARE_CARD_REQ_IDLE * - #AM_ZLG600_MIFARE_CARD_REQ_ALL * \param[in] p_atq : 请求应答 * \param[in] p_saq : 最后一级选择应答SAK * \param[in] p_len : 序列号的实际长度,4字节、7字节或10字节 * \param[in] p_uid : 序列号缓冲区,长度应该与序列号长度保持一致, * 如不确定,建议先使用最大长度10。 * \param[in] uid_len : p_uid 所指缓冲区的长度 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 */ int am_zlg600_mifare_card_active (am_zlg600_handle_t handle, uint8_t req_mode, uint16_t *p_atq, uint8_t *p_saq, uint8_t *p_len, uint8_t *p_uid, uint8_t uid_len); /** * \brief Mifare值操作,设置值块的值 * * \param[in] handle : ZLG600的操作句柄 * \param[in] nblock : 读取数据的值块地址 * \param[in] value : 设置的值 * * \retval AM_OK : 设置成功 * \retval -AM_EINVAL : 设置失败,参数错误 * \retval -AM_EIO : 设置失败,数据通信出错 */ int am_zlg600_mifare_card_val_set (am_zlg600_handle_t handle, uint8_t nblock, int32_t value); /** * \brief Mifare值操作,获取值块的值 * * \param[in] handle : ZLG600的操作句柄 * \param[in] nblock : 读取数据的值块地址 * \param[in] p_value : 获取值的指针 * * \retval AM_OK : 读取成功 * \retval -AM_EINVAL : 读取失败,参数错误 * \retval -AM_EIO : 读取失败,数据通信出错 */ int am_zlg600_mifare_card_val_get (am_zlg600_handle_t handle, uint8_t nblock, int32_t *p_value); /** * \brief 命令传输 * * 该函数属于模块扩展功能,用于模块向卡片发送任意长度组合的数据串,例如针对 * NXP新推出的NTAG213F是属于Ultralight C系列卡片,但是该卡片又新添加了扇区数据 * 读写密钥保护功能。而这个密钥验证命令即可利用此命名传输函数来实现。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] p_tx_buf : 发送数据的缓冲区 * \param[in] tx_nbytes : 发送字节数 * \param[in] p_rx_buf : 接收数据的缓冲区 * \param[in] rx_nbytes : 接收字节数 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_mifare_card_cmd_trans (am_zlg600_handle_t handle, uint8_t *p_tx_buf, uint8_t tx_nbytes, uint8_t *p_rx_buf, uint8_t rx_nbytes); /** * \brief 数据交互 * * 该命令用读写器与卡片的数据交互,通过该函数可以实现读写卡器的所有功能。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] p_data_buf : 需要交互发送的数据 * \param[in] len : 交互数据的长度 * \param[in] wtxm_crc : b7~b2,wtxm;b1,RFU(0); b0,0,CRC禁止能,1,CRC使能。 * \param[in] fwi : 超时等待时间编码, 超时时间=((0x01 << fwi*302us) * \param[out] p_rx_buf : 数据交互回应帧信息 * \param[in] buf_size : 接收回应信息的缓冲区大小 * \param[in] p_real_len : 用于获取实际接收的信息长度,如果缓冲区大小小于实际信 * 息长度,则多余部分将丢弃 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_mifare_card_data_exchange (am_zlg600_handle_t handle, uint8_t *p_data_buf, uint8_t len, uint8_t wtxm_crc, uint8_t fwi, uint8_t *p_rx_buf, uint8_t buf_size, uint16_t *p_real_len); /** * \name Mifare卡检测模式 * @{ */ /** \brief 执行完一次自动检测后执行Halt命令 */ #define AM_ZLG600_MIFARE_CARD_AD_HALT 0x08 /** @}*/ /** * \name Mifare卡天线驱动模式 * @{ */ #define AM_ZLG600_MIFARE_CARD_TX_IN_TURN 0x00 /**< \brief TX1、TX2交替运行 */ #define AM_ZLG600_MIFARE_CARD_TX_TX1 0x01 /**< \brief 仅TX1驱动 */ #define AM_ZLG600_MIFARE_CARD_TX_TX2 0x02 /**< \brief 仅TX2驱动 */ #define AM_ZLG600_MIFARE_CARD_TX_ALL 0x03 /**< \brief TX1和TX2同时驱动 */ /** @}*/ /** * \name Mifare卡秘钥验证模式 * @{ */ #define AM_ZLG600_MIFARE_CARD_AUTH_E2 0x45 /**< \brief E2密钥验证(E) */ #define AM_ZLG600_MIFARE_CARD_AUTH_DIRECT 0x46 /**< \brief 直接密钥验证(F) */ #define AM_ZLG600_MIFARE_CARD_AUTH_NO 0x00 /**< \brief 不验证 */ /** @}*/ /** * \brief 启动Mifare卡自动检测 * \note 在自动检测期间,若主机发送任何除读自动检测数据外的,且数据长度小于3 * 的命令,将退出自动检测模式,如请求am_zlg600_mifare_card_active() * 命令,在此期间,模块将不接收数据长度大于2的命令 * * \param[in] handle : ZLG600的操作句柄 * \param[in] p_adinfo : 自动检测信息 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 */ int am_zlg600_mifare_card_auto_detect_start (am_zlg600_handle_t handle, const am_zlg600_auto_detect_info_t *p_adinfo); /** * \brief 关闭Mifare卡自动检测 * * \param[in] handle : ZLG600的操作句柄 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 */ int am_zlg600_mifare_card_auto_detect_stop (am_zlg600_handle_t handle); /** * \brief Mifare卡自动检测回调函数设置 * * \param[in] handle : ZLG600的操作句柄 * \param[in] pfn_callback : 回调函数指针 * \param[in] p_arg : 回调函数入口参数 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 */ int am_zlg600_mifare_card_auto_detect_cb_set (am_zlg600_handle_t handle, am_pfnvoid_t pfn_callback, void *p_arg); /** * \name Mifare卡读自动检测标识 * @{ */ #define AM_ZLG600_MIFARE_CARD_AD_READ_CANCEL 0x00 /**< \brief 取消检测 */ #define AM_ZLG600_MIFARE_CARD_AD_READ_CONTINUE 0x01 /**< \brief 继续检测 */ /** @} */ /** * \brief Mifare卡片信息 */ typedef struct am_zlg600_mifare_card_info { uint8_t tx_mode; /**< \brief 天线驱动模式 */ uint8_t uid_len; /**< \brief UID(卡唯一序列号)长度,4、7、10 */ uint8_t uid[10]; /**< \brief UID */ uint8_t card_data[16]; /**< \brief 卡片数据 */ } am_zlg600_mifare_card_info_t; /** * \brief Mifare卡读取自动检测数据命令 * * \param[in] handle : ZLG600的操作句柄 * \param[out] p_card_info : 指向存放卡片数据的指针 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 */ int am_zlg600_mifare_card_auto_detect_read (am_zlg600_handle_t handle, am_zlg600_mifare_card_info_t *p_card_info); /** * \name IC卡复位后的波特率 * * 注意,该波特率并非主机与ZLG600的通信波特率,而是指ZLG600模块与接触式IC * 卡的通信波特率。 * * @{ */ #define AM_ZLG600_CICC_RST_BAUDRATE_9600 0x11 /**< \brief 波特率 9600 */ #define AM_ZLG600_CICC_RST_BAUDRATE_38400 0x13 /**< \brief 波特率 38400 */ /** @}*/ /** * \brief 接触式IC卡复位(自动处理PPS) * * 该函数是冷复位,执行成功后会自动根据IC卡的复位信息来执行PPS命令,然后再 * 选择am_zlg600_cicc_tpdu()函数使用的传输协议(T = 0 或T = 1)。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] baudrate_flag : IC卡复位后的波特率,使用下列宏: * - AM_ZLG600_CICC_RST_BAUDRATE_9600 * - AM_ZLG600_CICC_RST_BAUDRATE_38400 * \param[out] p_rx_buf : 存放复位信息的缓冲区 * \param[in] rx_bufsize : 缓冲区的长度 * \param[out] p_rx_len : 获取复位信息长度的指针,如果接收缓冲区的长度小于 * 实际长度,则多余部分丢弃。 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_cicc_reset (am_zlg600_handle_t handle, uint8_t baudrate_flag, uint8_t *p_rx_buf, uint8_t rx_bufsize, uint16_t *p_rx_len); /** * \brief 接触式IC卡传输协议 * * 该命令根据接触式IC卡的复位信息,自动选择T = 0或T = 1传输协议,整个过程 * 不需要使用者干预。该命令用于传输APDU数据流。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] p_tx_buf : 发送缓冲区 * \param[in] tx_bufsize : 发送缓冲区的长度, 1 ~ 272 * \param[in] p_rx_buf : 接收缓冲区 * \param[in] rx_bufsize : 接收缓冲区的长度 * \param[in] p_rx_len : 用于获取实际接收信息长度的指针,如果接收缓冲区 * 的长度小于实际长度,则多余部分丢弃。 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_cicc_tpdu (am_zlg600_handle_t handle, uint8_t *p_tx_buf, uint16_t tx_bufsize, uint8_t *p_rx_buf, uint8_t rx_bufsize, uint16_t *p_rx_len); /** * \brief 接触式IC卡冷复位 * * 该函数是冷复位,执行了接触式IC卡上电时序,执行成功后会自动根据IC卡的复位 * 信息来选择am_zlg600_cicc_tpdu()函数使用的传输协议(T = 0 或T = 1)。该函数没 * 有自动执行PPS命令,需要用户根据复位信息来判断是否使用am_zlg600_cicc_pps()来 * 修改协议和参数。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] baudrate_flag : IC卡复位后的波特率,使用下列宏: * - AM_ZLG600_CICC_RST_BAUDRATE_9600 * - AM_ZLG600_CICC_RST_BAUDRATE_38400 * \param[in] p_rx_buf : 存放复位信息的缓冲区 * \param[in] rx_bufsize : 缓冲区的长度 * \param[in] p_rx_len : 获取复位信息长度的指针,如果接收缓冲区的长度小于 * 实际长度,则多余部分丢弃。 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_cicc_coldreset (am_zlg600_handle_t handle, uint8_t baudrate_flag, uint8_t *p_rx_buf, uint8_t rx_bufsize, uint16_t *p_rx_len); /** * \brief 接触式IC卡热复位 * * 该函数是热复位,没有执行了接触式IC卡上电时序,执行成功后会自动根据IC卡的 * 复位信息来选择am_zlg600_cicc_tpdu()函数使用的传输协议(T = 0 或T = 1)。 * 热复位与冷复位唯一的区别是没有执行IC卡上电操作。需要用户根据复位信息来判断 * 是否使用am_zlg600_cicc_pps()来修改协议和参数。该函数必须在IC卡时钟和电源均 * 有效的情况下才能执行。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] baudrate_flag : IC卡复位后的波特率,使用下列宏: * - AM_ZLG600_CICC_RST_BAUDRATE_9600 * - AM_ZLG600_CICC_RST_BAUDRATE_38400 * \param[in] p_rx_buf : 存放复位信息的缓冲区 * \param[in] rx_bufsize : 缓冲区的长度 * \param[in] p_rx_len : 获取复位信息长度的指针,如果接收缓冲区的长度小于 * 实际长度,则多余部分丢弃。 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_cicc_warmreset (am_zlg600_handle_t handle, uint8_t baudrate_flag, uint8_t *p_rx_buf, uint8_t rx_bufsize, uint16_t *p_rx_len); /** * \brief 接触式IC卡停活,关闭接触式IC卡的电源和时钟 * * \param[in] handle : ZLG600的操作句柄 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_cicc_deactive (am_zlg600_handle_t handle); /** * \brief 接触式IC卡协议和参数选择 * * 该函数是冷复位或热复位之后且必须首先执行(协商模式下需要执行,专用模式 * 不需要执行)。若对接触式IC卡不了解,建议使用am_zlg600_cicc_reset()进行复位。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] p_pps : PPS参数缓冲区,大小一定为4字节 * - PPS[0] bit 3 ~ bit0 和 bit7保留 * - PPS[0] bit 4:1 ― PPS1存在;0 ― PPS1不存在 * - PPS[0] bit 5:1 ― PPS2存在;0 ― PPS2不存在 * - PPS[0] bit 6:1 ― PPS3存在;0 ― PPS3不存在 - PPS[1] :F/D - PPS[2] :N - PPS[3] :待定 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_cicc_pps (am_zlg600_handle_t handle, uint8_t *p_pps); /** * \brief 接触式IC卡传输协议(T = 0) * * 该命令用于T = 0传输协议。若接触式IC卡的传输协议为T = 0,该函数等同于 * am_zlg600_cicc_tpdu()。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] p_tx_buf : 发送缓冲区 * \param[in] tx_bufsize : 发送缓冲区的长度, 1 ~ 272 * \param[in] p_rx_buf : 接收缓冲区 * \param[in] rx_bufsize : 接收缓冲区的长度 * \param[in] p_rx_len : 用于获取实际接收信息长度的指针,如果接收缓冲区 * 的长度小于实际长度,则多余部分丢弃。 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_cicc_tpdu_tp0 (am_zlg600_handle_t handle, uint8_t *p_tx_buf, uint16_t tx_bufsize, uint8_t *p_rx_buf, uint8_t rx_bufsize, uint16_t *p_rx_len); /** * \brief 接触式IC卡传输协议(T = 1) * * 该命令用于T = 1传输协议。若接触式IC卡的传输协议为T = 1,该函数等同于 * am_zlg600_cicc_tpdu()。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] p_tx_buf : 发送缓冲区 * \param[in] tx_bufsize : 发送缓冲区的长度, 1 ~ 272 * \param[in] p_rx_buf : 接收缓冲区 * \param[in] rx_bufsize : 接收缓冲区的长度 * \param[in] p_rx_len : 用于获取实际接收信息长度的指针,如果接收缓冲区 * 的长度小于实际长度,则多余部分丢弃。 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_cicc_tpdu_tp1 (am_zlg600_handle_t handle, uint8_t *p_tx_buf, uint16_t tx_bufsize, uint8_t *p_rx_buf, uint8_t rx_bufsize, uint16_t *p_rx_len); /** * \name PICCA卡请求模式 * @{ */ #define AM_ZLG600_PICCA_REQ_IDLE 0x26 /**< \brief IDLE模式,请求空闲的卡 */ #define AM_ZLG600_PICCA_REQ_ALL 0x52 /**< \brief ALL模式,请求所有的卡 */ /** @}*/ /** * \brief PICCA卡请求操作 * * 该函数作为卡的请求操作,只要符合ISO14443A标准的卡都应能发出响应。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] req_mode : 请求模式,可使用下列宏: * - #AM_ZLG600_PICCA_REQ_IDLE * - #AM_ZLG600_PICCA_REQ_ALL * \param[in] p_atq : 获取请求应答信息(ATQ)的指针,其值为16位,不同卡 * 类型返回的信息不同,常见类型返回的ATQ如下: * * Mifare1 S50 | Mifare1 S70 | Mifare1 Light | Mifare0 UltraLight * --------------------|-------------|---------------|------------------- * 0x0004 | 0x0002 | 0x0010 | 0x0044 * ---------------------------------------------------------------------- * Mifare3 DESFire | SHC1101 | SHC1102 | 11RF32 * --------------------|-------------|---------------|------------------- * 0x0344 | 0x0004 | 0x3300 | 0x0004 * * \retval AM_OK : 请求成功 * \retval -AM_EINVAL : 请求失败,参数错误 * \retval -AM_EIO : 请求失败,数据通信出错 * * \note 卡进入天线后,从射频场中获取能量,从而得电复位,复位后卡处于IDLE模式, * 用两种请求模式的任一种请求时,此时的卡均能响应;若对某一张卡成功进行了挂起 * 操作(Halt命令或DeSelect命令),则进入了Halt模式,此时的卡只响应ALL(0x52) * 模式的请求,除非将卡离开天线感应区后再进入。 */ int am_zlg600_picca_request (am_zlg600_handle_t handle, uint8_t req_mode, uint16_t *p_atq); /** * \name PICCA卡防碰撞等级 * @{ */ #define AM_ZLG600_PICCA_ANTICOLL_1 0x93 /**< \brief 第一级防碰撞 */ #define AM_ZLG600_PICCA_ANTICOLL_2 0x95 /**< \brief 第二级防碰撞 */ #define AM_ZLG600_PICCA_ANTICOLL_3 0x97 /**< \brief 第三级防碰撞 */ /** @}*/ /** * \brief PICCA卡的防碰撞操作 * * 需要成功执行一次请求命令,并返回请求成功,才能进行防碰撞操作,否则返回错误。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] anticoll_level : 防碰撞等级,可使用下列宏: * - #AM_ZLG600_MIFARE_CARD_ANTICOLL_1 * - #AM_ZLG600_MIFARE_CARD_ANTICOLL_2 * - #AM_ZLG600_MIFARE_CARD_ANTICOLL_3 * * \param[in] know_uid : 已知的卡序列号 * \param[in] nbit_cnt : 位计数,表明已知的序列号uid的位数。其值小于32。 * - 若nbit_cnt值为0,则表明没有已知序列号,序列号的所有位 * 都要从本函数获得。 * - 若nbit_cnt不为0,则序列号中有已知的序列号的值,表示 * 序列号的前nbit_cnt位为已知序列号中所示前nbit_cnt位的 * 值,其余位需要本函数获得。 * \param[in] *p_uid : 防碰撞后获取到的卡序列号 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 * * \note 符合ISO14443A标准卡的序列号都是全球唯一的,正是这种唯一性,才能实现防 * 碰撞的算法逻辑,若有若干张卡同时在天线感应区内则这个函数能够找到一张序列号较 * 大的卡来操作。 */ int am_zlg600_picca_anticoll (am_zlg600_handle_t handle, uint8_t anticoll_level, uint32_t know_uid, uint8_t nbit_cnt, uint32_t *p_uid); /** * \brief PICC A卡的选择操作 * * 需要成功执行一次防碰撞命令,并返回成功,才能进行卡选择操作,否则返回错误。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] anticoll_level : 防碰撞等级,可使用下列宏: * - #AM_ZLG600_MIFARE_CARD_ANTICOLL_1 * - #AM_ZLG600_MIFARE_CARD_ANTICOLL_2 * - #AM_ZLG600_MIFARE_CARD_ANTICOLL_3 * \param[in] uid : 前一个防碰撞函数获取的UID * \param[in] p_sak : 返回的信息,若bit2为1,则表明UID不完整 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 * * \note 卡的序列号长度有三种:4字节、7字节和10字节。 4字节的只要用一级选择即可 * 得到完整的序列号,如Mifare1 S50/S70等;7字节的要用二级选择才能得到完整的序列 * 号,前一级所得到的序列号的最低字节为级联标志0x88,在序列号内只有后3字节可用, * 后一级选择能得到4字节序列号,两者按顺序连接即为7字节序列号,如UltraLight * 和DesFire等;10字节的以此类推,但至今还未发现此类卡。 */ int am_zlg600_picca_select (am_zlg600_handle_t handle, uint8_t anticoll_level, uint32_t uid, uint8_t *p_sak); /** * \brief PICCA卡的挂起操作,使所选择的卡进入HALT状态 * * 在HALT状态下,卡将不响应读卡器发出的IDLE模式的请求,除非将卡复位或离开天线感 * 应区后再进入。但它会响应读卡器发出的ALL请求。 * * \param[in] handle : ZLG600的操作句柄 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_picca_halt (am_zlg600_handle_t handle); /** * \brief PICC TypeA卡RATS(request for answer to select) * * RATS(request for answer to select)是ISO14443-4协议的命令,模块发送RATS, * 卡片发出ATS(answer to select)作为RATS的应答,在执行该命令前,必需先进行一次 * 卡选择操作,且执行过一次RATS命令后,想再次执行RATS命令,必需先解除激活。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] cid : 卡标识符(card IDentifier,取值范围0x00~0x0E) * \param[in] p_ats_buf : 用于接收回应的信息,不同卡,字节数会有不同 * \param[in] bufsize : 缓冲区大小 * \param[in] p_rx_len : 用于获取实际接收的信息长度,如果缓冲区大小小于实际信 * 息长度,则多余部分将丢弃 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 */ int am_zlg600_picca_rats (am_zlg600_handle_t handle, uint8_t cid, uint8_t *p_ats_buf, uint8_t bufsize, uint16_t *p_rx_len); /** * \brief PICC TypeA卡PPS(request for answer to select) * * PPS(protocal and parameter selection)是ISO14443-4协议的命令,用于改变有 * 关的专用协议参数,该命令不是必需的,命令只支持默认参数,即该命令的参数设置为 * 0即可。在执行该命令前,必需先成功执行一次RATS命令。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] dsi_dri : 模块与卡通信波特率,设置为0(默认)即可 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 */ int am_zlg600_picca_pps (am_zlg600_handle_t handle, uint8_t dsi_dri); /** * \brief PICC TypeA卡解除激活 * * 该命令是ISO14443-4协议的命令,用于将卡片置为挂起(HALT)状态,处于挂起 *(HALT)状态的卡可以用“请求”命令(请求代码为ALL)来重新激活卡,只有执行“RATS” * 命令的卡才用该命令。 * * \param[in] handle : ZLG600的操作句柄 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 */ int am_zlg600_picca_deselect (am_zlg600_handle_t handle); /** * \brief PICC卡T=CL * * T=CL是半双工分组传输协议,ISO14443-4协议命令,用于读写器与卡片之间的数据 * 交互,一般符合ISO14443协议的CPU卡均用该协议与读写器通信。调用该命令时只需要 * 将CPU卡COS命令的数据作为输入即可,其他的如分组类型、卡标识符CID、帧等待时间 * FWT、等待时间扩展倍增因子WTXM(waiting time extensionmultiplier),等等由该 * 命令自动完成。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] p_cos_buf : COS命令 * \param[in] cos_bufsize :COS命令的长度 * \param[in] p_res_buf : 用于接收回应的信息,不同COS命令,字节数会有不同 * \param[in] res_bufsize : 接收回应信息的缓冲区大小 * \param[in] p_rx_len : 用于获取实际接收的信息长度,如果缓冲区大小小于实际信 * 息长度,则多余部分将丢弃 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 */ int am_zlg600_picc_tpcl (am_zlg600_handle_t handle, uint8_t *p_cos_buf, uint8_t cos_bufsize, uint8_t *p_res_buf, uint8_t res_bufsize, uint16_t *p_rx_len); /** * \brief 数据交换 * * 该命令用读写器与卡片的数据交互,通过该函数可以实现读写卡器的所有功能。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] p_data_buf : 需要交互发送的数据(其内容与实际使用的卡有关) * \param[in] len : 交互数据的长度 * \param[in] wtxm_crc : b7~b2,wtxm;b1,RFU(0); b0,0-CRC禁止能,1-CRC使能。 * \param[in] fwi : 超时等待时间编码, 超时时间=((0x01 << fwi*302us) * \param[in] p_rx_buf : 数据交互回应帧信息 * \param[in] bufsize : 接收回应信息的缓冲区大小 * \param[in] p_rx_len : 用于获取实际接收的信息长度,如果缓冲区大小小于实际信 * 息长度,则多余部分将丢弃 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_picc_data_exchange (am_zlg600_handle_t handle, uint8_t *p_data_buf, uint8_t len, uint8_t wtxm_crc, uint8_t fwi, uint8_t *p_rx_buf, uint8_t bufsize, uint16_t *p_rx_len); /** * \brief PICC A卡复位,通过将载波信号关闭指定的时间,再开启来实现卡片复位。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] time_ms : 关闭的时间(单位:ms),0为一直关闭 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 * * \note 该函数将天线信号关闭数毫秒,若一直关闭,则等到执行一个请求命令时打开。 */ int am_zlg600_picca_reset(am_zlg600_handle_t handle, uint8_t time_ms); /** * \brief PICC A卡激活,该函数用于激活卡片,是请求、防碰撞和选择三条命令的组合。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] req_mode : 请求模式,可使用下列宏: * - #AM_ZLG600_PICCA_REQ_IDLE * - #AM_ZLG600_PICCA_REQ_ALL * \param[in] p_atq : 请求应答 * \param[in] p_saq : 最后一级选择应答SAK * \param[in] p_len : 序列号长度,4字节或7字节 * \param[in] p_uid : 序列号缓冲区,长度应该与序列号长度保持一致 * \param[in] uid_len : p_uid 所指缓冲区的长度 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 */ int am_zlg600_picca_active (am_zlg600_handle_t handle, uint8_t req_mode, uint16_t *p_atq, uint8_t *p_saq, uint8_t *p_len, uint8_t *p_uid, uint8_t uid_len); /** * \name PICCB卡请求模式 * @{ */ #define AM_ZLG600_PICCB_REQ_IDLE 0x00 /**< \brief IDLE模式,请求空闲的卡 */ #define AM_ZLG600_PICCB_REQ_ALL 0x08 /**< \brief ALL模式,请求所有的卡 */ /** @}*/ /** * \brief PICC B卡激活 * * 在调用该函数前,需要确保IC工作模式已经配置为TypeB模式。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] req_mode : 请求模式,可使用下列宏: * - #AM_ZLG600_PICCB_REQ_IDLE * - #AM_ZLG600_PICCB_REQ_ALL * \param[in] p_uid : UID相关信息,长度为12 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 */ int am_zlg600_piccb_active (am_zlg600_handle_t handle, uint8_t req_mode, uint8_t *p_uid); /** * \brief PICC B卡复位,通过将载波信号关闭指定的时间,再开启来实现卡片复位。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] time_ms : 关闭的时间(单位:ms),0为一直关闭 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 * * \note 该函数将天线信号关闭数毫秒,若一直关闭,则等到执行一个请求命令时打开。 */ int am_zlg600_piccb_reset (am_zlg600_handle_t handle, uint8_t time_ms); /** * \brief PICCA卡请求操作 * * 该函数作为卡的请求操作,只要符合ISO14443A标准的卡都应能发出响应。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] req_mode : 请求模式,可使用下列宏: * - #AM_ZLG600_PICCB_REQ_IDLE * - #AM_ZLG600_PICCB_REQ_ALL * \param[in] slot_time : 时隙总数,0 ~ 4 * \param[in] p_uid : 返回的UID相关信息,长度为12 * * \retval AM_OK : 请求成功 * \retval -AM_EINVAL : 请求失败,参数错误 * \retval -AM_EIO : 请求失败,数据通信出错 */ int am_zlg600_piccb_request (am_zlg600_handle_t handle, uint8_t req_mode, uint8_t slot_time, uint8_t *p_uid); /** * \brief PICC B 卡的防碰撞操作 * * \param[in] handle : ZLG600的操作句柄 * \param[in] slot_flag : 时隙标记,2 ~ 16,该参数值与请求命令的时隙总数有关 * 系,假如请求命令的时隙总数为n,侧该时隙标记N < 2^n * \param[in] p_uid : 返回的UID相关信息,长度为12 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_piccb_anticoll (am_zlg600_handle_t handle, uint8_t slot_flag, uint8_t *p_uid); /** * \brief PICC B卡的挂起操作,使所选择的卡进入HALT状态 * * 该函数用于B型卡挂起,在执行挂起命令前,必需先执行成功过一次请求命令。执行 * 挂起命令成功后,卡片处于挂起状态,模块必需通过ALL方式请求卡片,而不能用IDLE方 * 式请求。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] p_pupi : PUPI,大小为4字节的标识符 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_piccb_halt (am_zlg600_handle_t handle, uint8_t *p_pupi); /** * \brief 修改B卡的传输属性 * * 该函数用于B型卡挂起,在执行挂起命令前,必需先执行成功过一次请求命令。执行 * 挂起命令成功后,卡片处于挂起状态,模块必需通过ALL方式请求卡片,而不能用IDLE方 * 式请求。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] p_pupi : PUPI,大小为4字节的标识符 * \param[in] cid : 取值范围为 0 - 14, 若不支持CID,则设置为0 * \param[in] protype : 支持的协议 * - bit3 : 1-PCD中止与PICC继续通信,0-PCD与PICC继续通信 * - bit2 ~ bit1 : * - 11 : 10 etu + 512 / fs * - 10 : 10 etu + 256 / fs * - 01 : 10 etu + 128 / fs * - 00 : 10 etu + 32 / fs * - bit0 : 1-遵循ISO14443-4,0-不遵循ISO14443-4 * (二代身份证必须该位必须为1) * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_piccb_attrib_set (am_zlg600_handle_t handle, uint8_t *p_pupi, uint8_t cid, uint8_t protype); /** * \brief PLUS CPU卡个人化更新数据 * * 该命令用于SL0(Security Level 0,安全等级0)的PLUS CPU卡个人化,PLUS CPU * 卡出厂时的安全等级为SL0,该等级下,不需要任何验证就可以向卡里写数据,写入的数 * 据是作为其它安全等级的初始值,例如:向SL0的0x0003块写入:0xA0 0xA1 0xA2 0xA3 * 0xA4 0xA5 0xFF 0x07 0x80 0x69 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF,当卡片升级到SL1 * 后,扇区0的A密钥为0xA0 0xA1 0xA2 0xA3 0xA4 0xA5,而不是默认的0xFF 0xFF 0xFF * 0xFF 0xFF 0xFF,即可以在SL0修改卡片的默认数据和密钥。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] sector_addr : PLUS CPU卡存储器地址 * \param[in] p_buf : 发送缓冲区,数据个数为确定16个 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_pluscpu_persotcl_write (am_zlg600_handle_t handle, uint16_t sector_addr, uint8_t *p_buf); /** * \brief PLUS CPU卡提交个人化 * * am_zlg600_pluscpu_persotcl_write()函数只是更新卡中的数据,但数据还未生效。 * 提交后数据才生效。执行该命令后,PLUS CPU卡的安全等级提高到SL1或者SL3 * (若是支持SL1的卡,则执行该命令后卡片安全等级提高到SL1;若是只支持SL0和SL3的 * 卡,则执行该命令后卡片安全等级提高到SL3)。 * 注意:在SL0中,只有修改了以下地址才能执行提交操作: * ?- 0x9000(主控密钥) * - 0x9001(配置块密钥) * - 0x9002(SL2提升密钥,只有支持SL2的卡才有该密钥) * - 0x9003(SL3主控密钥,只有支持SL3的卡才有该密钥) * * \param[in] handle : ZLG600的操作句柄 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_pluscpu_persotcl_commit (am_zlg600_handle_t handle); /** * \brief PLUS CPU卡首次验证(直接密钥验证) * * \param[in] handle : ZLG600的操作句柄 * \param[in] authent_addr : 待验证的16位密钥地址 * \param[in] p_key : 密钥缓冲区,大小为16字节 * * \retval AM_OK : 验证成功 * \retval -AM_EINVAL : 验证失败,参数错误 * \retval -AM_EIO : 验证失败,数据通信出错 * * \note PLUS CPU卡的密钥A/B是通过地址的奇偶数来区分,AES的密钥地址与数据块的 * 扇区关系对应如下: * 密钥A地址=0x4000 + 扇区 × 2 * 密钥B地址=0x4000 + 扇区 × 2 + 1 * 因此,如验证1扇区的密钥A,则密钥地址为:0x4002 */ int am_zlg600_pluscpu_sl3_first_direct_authent (am_zlg600_handle_t handle, uint16_t authent_addr, uint8_t *p_key); /** * \brief PLUS CPU卡首次验证(E2密钥验证),验证的密钥来自模块内部,掉电不丢失 * * \param[in] handle : ZLG600的操作句柄 * \param[in] authent_addr : 待验证的16位密钥地址 * \param[in] key_sector : 密钥所在扇区 * * \retval AM_OK : 验证成功 * \retval -AM_EINVAL : 验证失败,参数错误 * \retval -AM_EIO : 验证失败,数据通信出错 */ int am_zlg600_pluscpu_sl3_first_e2_authent (am_zlg600_handle_t handle, uint16_t authent_addr, uint8_t key_sector); /** * \brief PLUS CPU卡跟随验证(直接密钥验证) * * 该函数用于SL3 PLUS CPU卡的跟随密钥验证,验证的密钥来自命令参数,只有执行 * 过“首次验证”命令成功后才能使用该命令。两种验证的区别在于使用的时间不同, * “首次验证”所需要的时间比“跟随验证”的时间要长些。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] authent_addr : 待验证的16位密钥地址 * \param[in] p_key : 密钥缓冲区,大小为16字节 * * \retval AM_OK : 验证成功 * \retval -AM_EINVAL : 验证失败,参数错误 * \retval -AM_EIO : 验证失败,数据通信出错 * */ int am_zlg600_pluscpu_sl3_follow_direct_authent (am_zlg600_handle_t handle, uint16_t authent_addr, uint8_t *p_key); /** * \brief PLUS CPU卡跟随验证(E2密钥验证),验证的密钥来自模块内部,掉电不丢失 * * \param[in] handle : ZLG600的操作句柄 * \param[in] authent_addr : 待验证的16位密钥地址 * \param[in] key_sector : 密钥所在扇区 * * \retval AM_OK : 验证成功 * \retval -AM_EINVAL : 验证失败,参数错误 * \retval -AM_EIO : 验证失败,数据通信出错 */ int am_zlg600_pluscpu_sl3_follow_e2_authent (am_zlg600_handle_t handle, uint16_t authent_addr, uint8_t key_sector); /** * \brief PLUS CPU卡SL3复位验证(E2密钥验证),验证的密钥来自模块内部,掉电不丢失 * * 该命令用于PLUS CPU卡通过首次验证后的使用过程中,复位读写计数器和验证等信息。 * * \param[in] handle : ZLG600的操作句柄 * * \retval AM_OK : 验证成功 * \retval -AM_EINVAL : 验证失败,参数错误 * \retval -AM_EIO : 验证失败,数据通信出错 */ int am_zlg600_pluscpu_sl3_reset_authent (am_zlg600_handle_t handle); /** * \name PLUS CPU卡读数据的模式 * @{ */ /** \brief 命令有MAC;数据密文(CIPHER);回应无MAC */ #define AM_ZLG600_PLUSCPU_SL3_READMODE_M_C_NM 0x30 /** \brief 命令有MAC;数据密文(CIPHER);回应有MAC */ #define AM_ZLG600_PLUSCPU_SL3_READMODE_M_C_M 0x31 /** \brief 命令有MAC;数据明文;回应无MAC */ #define AM_ZLG600_PLUSCPU_SL3_READMODE_M_NC_NM 0x32 /** \brief 命令有MAC;数据明文;回应有MAC */ #define AM_ZLG600_PLUSCPU_SL3_READMODE_M_NC_M 0x33 /** \brief 命令无MAC;数据密文;回应无MAC */ #define AM_ZLG600_PLUSCPU_SL3_READMODE_NM_C_NM 0x34 /** \brief 命令无MAC;数据密文;回应有MAC */ #define AM_ZLG600_PLUSCPU_SL3_READMODE_NM_C_M 0x35 /** \brief 命令无MAC;数据明文;回应无MAC */ #define AM_ZLG600_PLUSCPU_SL3_READMODE_NM_NC_NM 0x36 /** \brief 命令无MAC;数据明文;回应有MAC */ #define AM_ZLG600_PLUSCPU_SL3_READMODE_NM_NC_M 0x37 /** @}*/ /** * \brief PLUS CPU卡SL3读数据块 * * 该函数用于读取SL3的数据块,在读数据块之前必需成功执行一次密钥验证。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] read_mode : 读数据模式,使用宏 AM_ZLG600_PLUSCPU_SL3_READMODE_* * (#AM_ZLG600_PLUSCPU_SL3_READMODE_M_C_M) * \param[in] start_block : 读数据的起始块号 * \param[in] block_num : 读的块数,1 ~ 3 * \param[out] p_buf : 读取的数据存放缓冲区,大小应该为:block_num * 16 * * \retval AM_OK : 验证成功 * \retval -AM_EINVAL : 验证失败,参数错误 * \retval -AM_EIO : 验证失败,数据通信出错 */ int am_zlg600_pluscpu_sl3_read (am_zlg600_handle_t handle, uint8_t read_mode, uint16_t start_block, uint8_t block_num, uint8_t *p_buf); /** * \name PLUS CPU卡写数据的模式 * @{ */ /** \brief 命令有MAC;数据密文(CIPHER);回应无MAC */ #define AM_ZLG600_PLUSCPU_SL3_WRITEMODE_M_C_NM 0xA0 /** \brief 命令有MAC;数据密文(CIPHER);回应有MAC */ #define AM_ZLG600_PLUSCPU_SL3_WRITEMODE_M_C_M 0xA1 /** \brief 命令有MAC;数据明文;回应无MAC */ #define AM_ZLG600_PLUSCPU_SL3_WRITEMODE_M_NC_NM 0xA2 /** \brief 命令有MAC;数据明文;回应有MAC */ #define AM_ZLG600_PLUSCPU_SL3_WRITEMODE_M_NC_M 0xA3 /** @}*/ /** * \brief PLUS CPU卡SL3写数据块 * * 该函数用于写SL3的数据块,在写数据块之前必需成功执行一次密钥验证。 * * \param[in] handle : ZLG600的操作句柄 * \param[in] write_mode : 写数据模式,使用宏AM_ZLG600_PLUSCPU_SL3_WRITEMODE_* * (#AM_ZLG600_PLUSCPU_SL3_WRITEMODE_M_C_NM) * \param[in] start_block : 写数据的起始块号 * \param[in] block_num : 写的块数,1 ~ 3 * \param[in] p_buf : 写入数据存放缓冲区,大小应该为:block_num * 16 * * \retval AM_OK : 成功 * \retval -AM_EINVAL : 失败,参数错误 * \retval -AM_EIO : 失败,数据通信出错 */ int am_zlg600_pluscpu_sl3_write (am_zlg600_handle_t handle, uint8_t write_mode, uint16_t start_block, uint8_t block_num, uint8_t *p_buf); /** * \name PLUS CPU 卡值操作模式 * @{ */ #define AM_ZLG600_PLUSCPU_VALUE_ADD 0xB7 /**< \brief 加 */ #define AM_ZLG600_PLUSCPU_VALUE_SUB 0xB9 /**< \brief 减 */ /** @}*/ /** * \brief PLUS CPU卡值块操作 * * \param[in] handle : ZLG600的操作句柄 * \param[in] mode : 值操作的模式,可以是加或减,使用下列宏: * - AM_ZLG600_PLUSCPU_VALUE_ADD * - AM_ZLG600_PLUSCPU_VALUE_SUB * \param[in] src_block : 进行值块操作的数据源块号 * \param[in] dst_block : 值块操作结束后数据存放的目的块号 * \param[in] value : 4字节有符号数 * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 * * \note 要进行此类操作,块数据必须要有值块的格式,可参考NXP的相关文档。若卡块 * 号与传输块号相同,则将操作后的结果写入原来的块内;若卡块号与传输块号不相同, * 则将操作后的结果写入传输块内,结果传输块内的数据被覆盖,原块内的值不变。 * 处于等级2的PLUS CPU卡不支持值块操作,等级1、3支持。 */ int am_zlg600_pluscpu_val_operate (am_zlg600_handle_t handle, uint8_t mode, uint16_t src_block, uint16_t dst_block, int32_t value); /** * \brief 读取身份证信息 * * \param[in] handle : ZLG600的操作句柄 * \param[in] req_mode : 请求模式,可使用下列宏: * - #AM_ZLG600_PICCB_REQ_IDLE * - #AM_ZLG600_PICCB_REQ_ALL * \param[out] p_info : 身份证信息缓冲区(大小应为8字节) * * \retval AM_OK : 写入成功 * \retval -AM_EINVAL : 写入失败,参数错误 * \retval -AM_EIO : 写入失败,数据通信出错 * * \note 要进行读身份证信息操作,需先调用 am_zlg600_ic_isotype_set 接口将卡类型设置为B卡, * 读取完成之后应该视情况调用 am_zlg600_ic_isotype_set 将卡类型还原或不还原。 */ int am_zlg600_id_card_info_get (am_zlg600_handle_t handle, uint8_t req_mode, uint8_t *p_info); /** * \brief 指令超时时间设置 * * \param[in] handle : ZLG600的操作句柄 * \param[in] timeout_ms : 指令超时时间(毫秒) * * \retval AM_OK : 设置成功 * \retval 其他 : 设置失败 */ int am_zlg600_cmd_timeout_set (am_zlg600_handle_t handle, uint32_t timeout_ms); /** * @} */ #endif /* __AM_ZLG600_H */ /* end of file */
77,423
C
.h
1,830
29.621858
95
0.511306
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,398,652
am_board.h
skyformat99_ametal/board/am116_core/project_example/user_config/am_board.h
/******************************************************************************* * AMetal * ---------------------------- * innovating embedded platform * * Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd. * All rights reserved. * * Contact information: * web site: http://www.zlg.cn/ *******************************************************************************/ /** * \file * \brief AM116BLE * * \internal * \par Modification history * - 1.00 14-12-01 tee, first implementation. * \endinternal */ #ifndef __AM_BOARD_H #define __AM_BOARD_H #include "ametal.h" #include "am_prj_config.h" #include "am_delay.h" #include "am_led.h" #include "am_pwm.h" #include "am_timer.h" #include "am_bsp_delay_timer.h" /** \brief LED 索引ID号 */ #define LED0 0 #define LED1 1 /** * \brief 板级初始化 * * \return 无 * * \note 该函数会初始化系统时钟、GPIO、中断、蜂鸣器、LED和延时函数 */ void am_board_init (void); #endif /* __AM_BOARD_H */ /* end of file */
1,126
C
.h
42
23.333333
81
0.472973
skyformat99/ametal
3
282
0
LGPL-2.1
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,399,256
bdroid_buildcfg.h
Haxynox_seals_something_anotherhing/bluetooth/bdroid_buildcfg.h
/* * Copyright (C) 2012 The Android Open Source Project * Copyright (C) 2014 The CyanogenMod Project <http://www.cyanogenmod.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cutils/properties.h> #include <string.h> #ifndef _BDROID_BUILDCFG_H #define _BDROID_BUILDCFG_H static inline const char* getBTName() { char bootloader[PROPERTY_VALUE_MAX]; property_get("ro.bootloader", bootloader, ""); if (!strncmp(bootloader, "G930", 4)) { return "Samsung Galaxy S7"; } if (!strncmp(bootloader, "G935", 4)) { return "Samsung Galaxy S7 Edge"; } return "Samsung Galaxy"; } #define BTM_DEF_LOCAL_NAME getBTName() #define BLE_VND_INCLUDED TRUE #define BTIF_HF_WBS_PREFERRED TRUE /* Use WBS */ #define BTM_WBS_INCLUDED TRUE /* Enable WBS */ #endif
1,344
C
.c
37
33.486486
75
0.712635
Haxynox/seals_something_anotherhing
3
12
0
GPL-3.0
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,406,085
mdloader_win32.c
patrickmt_mdloader/mdloader_win32.c
/* * Copyright (C) 2018 Massdrop Inc. * * This file is part of Massdrop Loader. * * Massdrop Loader is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Massdrop Loader is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Massdrop Loader. If not, see <https://www.gnu.org/licenses/>. */ #include "mdloader_common.h" #define EXAMPLE_PORT "COM23" #define PORT_SEARCH_STRING "COM" HANDLE gport = NULL; //Port of device #define WRITE_SIZE 500 //Maximum bytes to write per call #define READ_SIZE 500 //Maximum bytes to read per call #define READ_RETRIES 10 //Maximum read retries before fail void print_com_example(void) { printf("Example: -p " EXAMPLE_PORT "\n"); } //Read data from device //Must check read_error for a read error after return //Return unsigned word from memory location int read_data(int addr, int readsize) { read_error = 1; //Set read error flag as default int readdata = 0; char wbuf[] = "!XXXXXXXX,#"; //Largest buffer needed DWORD ret; if (readsize == 1) sprintf(wbuf,"%c%02x,%c",CMD_READ_ADDR_8,addr,CMD_END); else if (readsize == 2) sprintf(wbuf,"%c%04x,%c",CMD_READ_ADDR_16,addr,CMD_END); else if (readsize == 4) sprintf(wbuf,"%c%08x,%c",CMD_READ_ADDR_32,addr,CMD_END); else { if (verbose) printf("Error: Invalid read size given (%i)\n",readsize); return 0; } if (verbose > 0) printf("Write: [%s]\n",wbuf); PurgeComm(gport, PURGE_RXCLEAR | PURGE_TXCLEAR); //Flush any remaining data from a bad read int writelen = strlen(wbuf); if (!WriteFile(gport,wbuf,writelen,&ret,0)) { if (verbose) printf("Error writing port [%s](%lu)\n",wbuf,GetLastError()); return 0; } if (ret != writelen) { if (verbose) printf("Error writing %i bytes [%lu]\n",writelen,ret); return 0; } if (!ReadFile(gport, &readdata, readsize, &ret, NULL)) { if (verbose) printf("Error reading port [%i][%lu](%lu)\n",readsize,ret,GetLastError()); return 0; } if (ret != readsize) { if (verbose) printf("Error reading %i bytes! [%lu]\n",readsize,ret); return 0; } read_error = 0; //Clear read error flag return readdata; } //Write data to device //Return 1 on success, 0 on failure int write_data(int addr, int writesize, int data) { if (check_bootloader_write_attempt(addr)) return 0; //Prevent writes to bootloader section char wbuf[] = "!XXXXXXXX,XXXXXXXX#"; //Largest buffer needed DWORD ret; if (writesize == 1) sprintf(wbuf,"%c%08x,%02x%c",CMD_WRITE_ADDR_8,addr,data,CMD_END); else if (writesize == 2) sprintf(wbuf,"%c%08x,%04x%c",CMD_WRITE_ADDR_16,addr,data,CMD_END); else if (writesize == 4) sprintf(wbuf,"%c%08x,%08x%c",CMD_WRITE_ADDR_32,addr,data,CMD_END); else { if (verbose) printf("Error: Invalid write size given (%i)\n",writesize); return 0; } if (verbose) printf("Write %i bytes: [%s]\n",writesize,wbuf); int writelen = strlen(wbuf); if (!WriteFile(gport,wbuf,writelen,&ret,0)) { if (verbose) printf("Error writing port [%s](%lu)\n",wbuf,GetLastError()); return 0; } if (ret != writelen) { if (verbose) printf("Error writing %i bytes! [%lu]\n",writesize,ret); return 0; } return 1; } //Jump to address and run //Return 1 on success, 0 on failure int goto_address(int addr) { char wbuf[] = "!XXXXXXXX#"; DWORD ret; sprintf(wbuf,"%c%08x%c",CMD_GOTO_ADDR,addr,CMD_END); if (verbose) printf("Write: [%s]\n",wbuf); int writelen = strlen(wbuf); if (!WriteFile(gport,wbuf,strlen(wbuf),&ret,0)) { if (verbose) printf("Error writing port [%s](%lu)\n",wbuf,GetLastError()); return 0; } if (ret != writelen) { if (verbose) printf("Error writing goto address! [%lu]\n",ret); return 0; } return 1; } //Read data from device RAM //Return pointer to buffer on success, NULL on failure char *recv_file(int addr, int bytes) { char wbuf[] = "!XXXXXXXX,XXXXXXXX#"; char *data = NULL; data = (char *)calloc(bytes+1,sizeof(char)); if (data == NULL) { printf("Error allocating read buffer memory!\n"); return NULL; } char *pdata = data; DWORD ret; int retries = READ_RETRIES; int readsize = READ_SIZE; //Constrain read size to buffer size if (initparams.argument.outputInit.bufferSize > 0 && initparams.argument.outputInit.bufferSize < readsize) readsize = initparams.argument.outputInit.bufferSize; while (bytes > 0) { if (readsize > bytes) readsize = bytes; sprintf(wbuf,"%c%08x,%08x%c",CMD_RECV_FILE,addr,readsize,CMD_END); if (verbose > 0) printf("Write: [%s]\n",wbuf); PurgeComm(gport, PURGE_RXCLEAR | PURGE_TXCLEAR); //Flush any remaining data from a bad read long writelen = strlen(wbuf); if (!WriteFile(gport,wbuf,writelen,&ret,0)) { if (verbose) printf("Error writing port [%s](%lu)\n",wbuf,GetLastError()); free(data); return NULL; } if (!ReadFile(gport, pdata, bytes, &ret, NULL)) { if (verbose) printf("Error reading port [%i][%lu](%lu)\n",readsize,ret,GetLastError()); free(data); return NULL; } if (ret != readsize) { if (verbose) printf("Error reading %i bytes! [%lu](%lu)\n",readsize,ret,GetLastError()); if (retries <= 0) { if (verbose) printf("No retries remain!\n"); free(data); return NULL; } retries--; if (verbose) printf("Retrying read... (%i)\n",READ_RETRIES - retries); continue; //Attempt read again } if (verbose > 0) printf("Recv: [%lu]\n",ret); retries = READ_RETRIES; //Reset retry limit bytes -= ret; //Decrement remaining bytes addr += ret; //Increment to next address pdata += ret; //Increment pointer in recv buffer } return data; } //Write data to device //Return 1 on sucess, 0 on failure int send_file(int addr, int bytes, char *data) { if (check_bootloader_write_attempt(addr)) return 0; //Prevent writes to bootloader section if (bytes < 1) { printf("Error: No data to send!\n"); return 0; } char wbuf[] = "!XXXXXXXX,XXXXXXXX#"; DWORD ret; char *pdata = data; int writesize = WRITE_SIZE; //Constrain write size to buffer size if (initparams.argument.outputInit.bufferSize > 0 && initparams.argument.outputInit.bufferSize < writesize) writesize = initparams.argument.outputInit.bufferSize; while (bytes > 0) { if (writesize > bytes) writesize = bytes; sprintf(wbuf,"%c%08x,%08x%c",CMD_SEND_FILE,addr,writesize,CMD_END); if (verbose > 0) printf("Write: [%s]\n",wbuf); if (!WriteFile(gport, wbuf, strlen(wbuf), &ret, 0)) { if (verbose) printf("Error writing port [%s](%lu)\n",wbuf,GetLastError()); return 0; } if (ret != strlen(wbuf)) { if (verbose) printf("Error writing port [%s](%lu)\n",wbuf,GetLastError()); return 0; } if (verbose > 0) printf("Write: %i bytes\n",writesize); if (!WriteFile(gport, pdata, writesize, &ret, 0)) { if (verbose) printf("Error writing port [%lu][%i](%lu)\n",ret,writesize,GetLastError()); return 0; } if (ret != writesize) { printf("Error writing port [%lu][%i](%lu)\n",ret,writesize,GetLastError()); return 0; } bytes -= ret; //Decrement remaining bytes addr += ret; //Increment to next address pdata += ret; //Increment pointer in send buffer } return 1; } //Print bootloader version //Return 1 on sucess, 0 on failure int print_bootloader_version(void) { char wbuf[] = "!#"; char readdata[128] = ""; DWORD ret; int readsize = sizeof(readdata) - 1; sprintf(wbuf,"%c%c",CMD_READ_VERSION,CMD_END); if (verbose > 0) printf("Write: [%s]\n",wbuf); int writelen = strlen(wbuf); if (!WriteFile(gport,wbuf,writelen,&ret,0)) { if (verbose) printf("Version: Error writing port [%s](%lu)\n",wbuf,GetLastError()); else printf("Version: Error retrieving!\n"); return 0; } if (!ReadFile(gport, &readdata, readsize, &ret, NULL)) { if (verbose) printf("Version: Error reading port [%i][%lu](%lu)\n",readsize,ret,GetLastError()); else printf("Version: Error retrieving!\n"); return 0; } while (readdata[strlen(readdata)-1] == '\n' || readdata[strlen(readdata)-1] == '\r') readdata[strlen(readdata)-1] = 0; printf("Bootloader version: %s\n",readdata); return 1; } //Set normal command mode //Return 1 on sucess, 0 on failure int set_normal_mode(void) { if (verbose) printf("Setting normal mode... "); int retbuf = 0; char wbuf[] = "!#"; DWORD ret; sprintf(wbuf,"%c%c",CMD_SET_NORMAL_MODE,CMD_END); int writelen = strlen(wbuf); if (!WriteFile(gport,wbuf,writelen,&ret,0)) { if (verbose) printf("Failed! (%lu)\n",GetLastError()); return 0; } if (ret != writelen) { if (verbose) printf("Error writing %i bytes! [%lu](%lu)\n",writelen,ret,GetLastError()); return 0; } int readlen = 2; if (!ReadFile(gport, &retbuf, readlen, &ret, NULL)) { if (verbose) printf("Error reading port [%i][%lu](%lu)\n",readlen,ret,GetLastError()); return 0; } if (ret != readlen) { if (verbose) printf("Error reading %i bytes! [%lu][%04x](%lu)\n",readlen,ret,retbuf,GetLastError()); return 0; } if ((retbuf & 0xFFFF) != 0x0D0A) { if (verbose) printf("Error: Incorrect response! [%lu][%04x](%lu)\n",ret,retbuf,GetLastError()); return 0; } if (verbose) printf("Success!\n"); return 1; } //Jump to loaded application //Return 1 on sucess, 0 on failure int jump_application(void) { printf("Booting device... "); if (testmode) { printf("(test mode disables restart)\n"); return 1; } char wbuf[] = "!#"; DWORD ret; DWORD writelen = strlen(wbuf); sprintf(wbuf,"%c%c",CMD_LOAD_APP,CMD_END); if (!WriteFile(gport,wbuf,writelen,&ret,0)) { printf("Failed! (%lu)\n",GetLastError()); return 0; } printf("Success!\n"); return 1; } //Open port //Return 1 on sucess, 0 on failure int open_port(char *portname, char silent) { char portnamebuf[64] = ""; if (!silent || verbose) printf("Opening port '%s'... ",portname); sprintf(portnamebuf,"\\\\.\\%s",portname); gport = CreateFile(portnamebuf,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL); if (gport == INVALID_HANDLE_VALUE) { if (!silent || verbose) { printf("Failed!"); LPTSTR errstr = NULL; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM| FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_MAX_WIDTH_MASK, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errstr, 0, NULL); if (errstr != NULL) { char *pstr = errstr + strlen(errstr); while (pstr > errstr && *pstr <= 32) { *pstr = 0; pstr--; } //Clean up end of message if (!silent) printf(" (%s)",errstr); LocalFree(errstr); } printf("\n"); } return 0; } if (!silent || verbose) printf("Success!\n"); return 1; } //Close port //Return 1 on sucess, 0 on failure int close_port(char silent) { if (!silent || verbose) printf("Closing port... "); if (CloseHandle(gport) == 0) { if (!silent || verbose) printf("Failed! (%lu)\n",GetLastError()); return 0; } if (!silent || verbose) printf("Success!\n"); return 1; } //Configure port //Return 1 on sucess, 0 on failure int config_port(void) { DCB dcb = {}; if (verbose) printf("Configuring port... \n"); if (verbose) printf(" Get config... "); if (GetCommState(gport,&dcb) == 0) { if (verbose) printf("Failed! (%lu)\n",GetLastError()); return 0; } if (verbose) printf("Success!\n"); dcb.BaudRate = CBR_115200; dcb.StopBits = ONESTOPBIT; dcb.Parity = NOPARITY; dcb.ByteSize = 8; if (verbose) printf(" Set config... "); if (!SetCommState(gport,&dcb)) { if (verbose) printf("Failed! (%lu)\n",GetLastError()); return 0; } if (verbose) printf("Success!\n"); COMMTIMEOUTS comTimeOut; comTimeOut.ReadIntervalTimeout = 1; comTimeOut.ReadTotalTimeoutMultiplier = 1; comTimeOut.ReadTotalTimeoutConstant = 1; comTimeOut.WriteTotalTimeoutMultiplier = 1; comTimeOut.WriteTotalTimeoutConstant = 1; if (verbose) printf(" Set timeouts... "); if (!SetCommTimeouts(gport,&comTimeOut)) { if (verbose) printf("Failed! (%lu)\n",GetLastError()); return 0; } if (verbose) printf("Success!\n"); PurgeComm(gport, PURGE_RXCLEAR | PURGE_TXCLEAR); //Flush port return 1; } //List devices which communicate properly //If first_device is not null, store first found device and return void list_devices(char *first_device) { int portnum = 1; int portmax = 255; //Inclusive int portcount = 0; char portname[] = "COM255"; //Max buffer necessary if (first_device == NULL) { printf("Bootloader port listing\n"); printf("-----------------------------\n"); } while (portnum <= portmax) { sprintf(portname,PORT_SEARCH_STRING "%i",portnum); if (test_port(portname,TRUE)) { if (test_mcu(TRUE)) { if (first_device) printf("\n"); printf("Device port: %s (%s)\n",portname,mcu->name); if (first_device != NULL) { close_port(TRUE); strcpy(first_device,portname); return; } portcount++; } close_port(TRUE); } portnum++; } if (first_device == NULL) { if (portcount == 0) printf("No devices found!\n"); } }
15,266
C
.c
453
26.898455
122
0.592071
patrickmt/mdloader
3
88
4
GPL-3.0
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,406,086
mdloader_parser.c
patrickmt_mdloader/mdloader_parser.c
/* * Copyright (C) 2018 Massdrop Inc. * * This file is part of Massdrop Loader. * * Massdrop Loader is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Massdrop Loader is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Massdrop Loader. If not, see <https://www.gnu.org/licenses/>. */ #include "mdloader_common.h" #include "mdloader_parser.h" void free_data(data_t *data) { if (!data) { printf("Error: Parser: Attempt to free NULL data!\n"); return; } if (data->data) { free(data->data); data->data = NULL; } free(data); data = NULL; } data_t *create_data(uint32_t data_length) { data_t *data = (data_t *)malloc(sizeof(data_t)); if (!data) { printf("ERROR: Parser: Could not allocate parser memory!\n"); return NULL; } data->data = (char *)malloc(data_length); if (!data->data) { printf("ERROR: Parser: Could not allocate parser data memory!\n"); free_data(data); return NULL; } return data; } //Assuming validity checks on incoming variables have been completed prior to call data_t *parse_bin(char *rawdata, uint32_t rawlength) { if (!rawdata) { printf("ERROR: Parser: Bin: Raw data null!\n"); return NULL; } if (!rawlength) { printf("ERROR: Parser: Bin: Raw data length zero!\n"); return NULL; } data_t *data = create_data(rawlength); if (data) { memcpy(data->data, rawdata, rawlength); data->size = rawlength; data->addr = mcu->flash_addr + bootloader_length; } else printf("Error: Parser: Bin: Error creating parser storage!\n"); return data; } char hex_conv_error; //Cleared on conversion attempt and set to 1 if read fails //Must check hex_conv_error != 0 for conversion error after call char ascii_to_hex(char bh, char bl) { hex_conv_error = 0; if (bh >= '0' && bh <= '9') bh -= '0'; else if (bh >= 'A' && bh <= 'F') bh -= 'A' - 0xA; else if (bh >= 'a' && bh <= 'a') bh -= 'a' - 0xA; else { hex_conv_error = 1; return 0; } if (bl >= '0' && bl <= '9') bl -= '0'; else if (bl >= 'A' && bl <= 'F') bl -= 'A' - 0xA; else if (bl >= 'a' && bl <= 'a') bl -= 'a' - 0xA; else { hex_conv_error = 1; return 0; } return (bh << 4) | bl; } //Assuming validity checks on incoming variables have been completed prior to call data_t *parse_hex(char *rawdata, uint32_t rawlength) { if (!rawdata) { printf("ERROR: Parser: Hex: Raw data null!\n"); return NULL; } if (!rawlength) { printf("ERROR: Parser: Hex: Raw data length zero!\n"); return NULL; } uint8_t first_address_set = 0; uint32_t base_address = 0; uint32_t start_offset; uint8_t *rds = (uint8_t *)rawdata; uint8_t *rde = (uint8_t *)rawdata + rawlength; uint8_t *bindata = (uint8_t *)rawdata; hex_record_t *hex; uint8_t *hex_data; uint8_t checksum; uint8_t checksum_given; uint16_t line = 0; uint32_t binlength = 0; uint8_t byte_count; uint32_t next_address = 0; uint32_t start_segment_address = 0; uint8_t start_segment_address_set = 0; while (rds < rde) { line++; if (rde - rds < sizeof(hex_record_t)) { printf("Error: Parser: Hex: Unexpected end of header! (Line %i)\n",line); return NULL; } hex = (hex_record_t *)rds; if (hex->start_code != ':') { printf("Error: Parser: Hex: Invalid start code! (Line %i)\n",line); return NULL; } checksum = 0; //Convert byte count to safe storage byte_count = ascii_to_hex(*hex->byte_count, *(hex->byte_count+1)); if (hex_conv_error) { printf("Error: Parser: Hex: Unexpected ASCII in byte count! (Line %i)\n",line); return NULL; } checksum += byte_count; //Convert record type in place *hex->record_type = ascii_to_hex(*hex->record_type, *(hex->record_type+1)); if (hex_conv_error) { printf("Error: Parser: Hex: Unexpected ASCII in record type! (Line %i)\n",line); return NULL; } checksum += *hex->record_type; //Convert address in place *hex->address.c = ascii_to_hex(*(hex->address.c+0), *(hex->address.c+1)); if (hex_conv_error) { printf("Error: Parser: Hex: Unexpected ASCII in address byte 1! (Line %i)\n",line); return NULL; } checksum += *hex->address.c; *(hex->address.c+1) = ascii_to_hex(*(hex->address.c+2), *(hex->address.c+3)); if (hex_conv_error) { printf("Error: Parser: Hex: Unexpected ASCII in address byte 2! (Line %i)\n",line); return NULL; } checksum += *(hex->address.c+1); hex->address.i = (*hex->address.c << 8) + *(hex->address.c+1); //Check enough data remains to parse if (rde - rds < sizeof(hex_record_t) + (byte_count * 2) + 2) { printf("Error: Parser: Hex: Malformed data! (Line %i)\n",line); return NULL; } hex_data = rds + sizeof(hex_record_t); //Convert data in place for (start_offset = 0; start_offset < byte_count * 2; start_offset += 2) { *(hex_data + start_offset / 2) = ascii_to_hex(*(hex_data + start_offset), *(hex_data + start_offset + 1)); if (hex_conv_error) { printf("Error: Parser: Hex: Unexpected ASCII in data byte! (Line %i)\n",line); return NULL; } checksum += *(hex_data + start_offset / 2); } checksum *= -1; //Convert checksum checksum_given = ascii_to_hex(*(hex_data + start_offset), *(hex_data + start_offset + 1)); if (hex_conv_error) { printf("Error: Parser: Hex: Unexpected ASCII in checksum byte! (Line %i)\n",line); return NULL; } if (checksum != checksum_given) { printf("Error: Parser: Hex: Checksum mismatch! (Line %i)\n",line); return NULL; } //Print hex line //printf("%c ",hex->start_code); //printf("%02X ",byte_count); //printf("%04X ",hex->address.i); //for (start_offset = 0; start_offset < byte_count; start_offset++) // printf("%02X",*(hex_data + start_offset)); //if (byte_count) printf(" "); //printf("%02X\n",checksum); if (*hex->record_type == 0) //Data { if (!first_address_set) { first_address_set = 1; next_address = base_address + hex->address.i; } if (hex->address.i + base_address != next_address) { printf("Error: Parser: Hex: Address not contiguous! (Line %i)\n",line); return NULL; } //Write binary data into rawdata buffer (write position will never reach read position) binlength += byte_count; for (start_offset = 0; start_offset < byte_count; start_offset++) { *bindata = *(hex_data + start_offset); bindata++; } next_address = base_address + ((next_address + byte_count) & 0xFFFF); } else if (*hex->record_type == 1) //EOF { break; //No need to go further } else if (*hex->record_type == 2) //Extended Segment Address { base_address = ((*hex_data << 8) + *(hex_data+1)) << 16; next_address += base_address; } else if (*hex->record_type == 3) //Start Segment Address { start_segment_address = ((*hex_data << 24) + (*(hex_data+1) << 16) + (*(hex_data+2) << 8) + (*(hex_data+3))); start_segment_address_set = 1; } else if (*hex->record_type == 4) //Extended Linear Address { printf("Error: Parser: Hex: 32-bit addressing is not supported! (Line %i)\n",line); return NULL; } else if (*hex->record_type == 5) //Start Linear Address { printf("Error: Parser: Hex: Start linear address is not supported! (Line %i)\n",line); return NULL; } else { printf("Error: Parser: Hex: Unknown record type! (Line %i)\n",line); return NULL; } rds += sizeof(hex_record_t) + (byte_count * 2) + 2; //Bypass header, data, checksum while (rds < rde && (*rds == '\r' || *rds == '\n')) rds++; //Bypass EOL characters } if (!start_segment_address_set) { printf("Error: Parser: Hex: Missing start segment address!\n"); return NULL; } data_t *data = create_data(binlength); if (data) { memcpy(data->data, rawdata, binlength); data->size = binlength; data->addr = start_segment_address; } else printf("Error: Parser: Hex: Error creating parser storage!\n"); return data; } char get_type_by_ext(char *fname) { char *pext = fname + (strlen(fname) - 4); if (!strcmp(pext,EXT_HEX)) return FTYPE_HEX; else if (!strcmp(pext,EXT_BIN)) return FTYPE_BIN; else return FTYPE_NONE; } data_t *load_file(char *fname) { if (!fname) { printf("ERROR: Parser: No file given!\n"); return NULL; } if (strlen(fname) < 5) { printf("ERROR: Parser: File name must end in %s or %s!\n", EXT_HEX, EXT_BIN); return NULL; } char ftype = get_type_by_ext(fname); if (ftype == FTYPE_NONE) { printf("ERROR: Parser: File name must end in %s or %s!\n", EXT_HEX, EXT_BIN); return NULL; } uint32_t fsize = filesize(fname); if (fsize == 0) { printf("ERROR: Parser: File is empty!\n"); return NULL; } FILE *fIn = fopen(fname, "rb"); if (!fIn) { printf("ERROR: Parser: Could not open file for read!\n"); return NULL; } char *rawdata = (char *)malloc(fsize); if (!rawdata) { printf("ERROR: Parser: Could no allocated file memory buffer!\n"); fclose(fIn); return NULL; } uint32_t readbytes = (uint32_t)fread(rawdata, 1, fsize, fIn); fclose(fIn); if (readbytes != fsize) { printf("ERROR: Parser: File read size mismatch!\n"); free(rawdata); return NULL; } if (ftype == FTYPE_HEX) return parse_hex(rawdata, readbytes); else if (ftype == FTYPE_BIN) return parse_bin(rawdata, readbytes); else printf("ERROR: Parser: Unknown file type!\n"); return NULL; }
11,367
C
.c
343
25.565598
121
0.553692
patrickmt/mdloader
3
88
4
GPL-3.0
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,406,087
mdloader_common.h
patrickmt_mdloader/mdloader_common.h
/* * Copyright (C) 2018 Massdrop Inc. * * This file is part of Massdrop Loader. * * Massdrop Loader is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Massdrop Loader is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Massdrop Loader. If not, see <https://www.gnu.org/licenses/>. */ #ifndef _MDLOADER_COMMON_H #define _MDLOADER_COMMON_H #define PROGRAM_NAME "Massdrop Loader" #define VERSION_MAJOR 1 #define VERSION_MINOR 3 //0-99 #ifdef _WIN32 #define INITGUID #include <windows.h> #include <setupapi.h> #include <devguid.h> #include "tchar.h" #include <conio.h> #else #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <termios.h> #include <dirent.h> #endif //_WIN32 #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <getopt.h> //Atmel files #include "./atmel/applet.h" #include "./atmel/status_codes.h" #define FALSE 0 #define TRUE 1 #ifdef _WIN32 #define slp(ms) Sleep(ms) extern HANDLE gport; #else #define slp(ms) usleep(ms * 1000) extern int gport; #endif extern char verbose; extern char testmode; extern int restart_after_program; extern int hex_cols; extern int hex_colw; //These parameters must match the bootloader's #define SERIAL_MAX_LENGTH 20 //SAM-BA Applet commands #define CMD_END '#' #define CMD_SET_NORMAL_MODE 'N' //N# N# done #define CMD_SET_TERMINAL_MODE 'T' //T# T# NOT SUPPORTING #define CMD_WRITE_ADDR_8 'O' //Addr,Value# O00004000,AA# done #define CMD_READ_ADDR_8 'o' //Addr,# o00004000,# done #define CMD_WRITE_ADDR_16 'H' //Addr,Value# H00004000,AABB# done #define CMD_READ_ADDR_16 'h' //Addr,# h00004000,# done #define CMD_WRITE_ADDR_32 'W' //Addr,Value# W00004000,AABBCCDD# done #define CMD_READ_ADDR_32 'w' //Addr,# w00004000,# done #define CMD_SEND_FILE 'S' //Addr,Bytes# S00004000,1000# done #define CMD_RECV_FILE 'R' //Addr,Bytes# R00004000,1000# done #define CMD_GOTO_ADDR 'G' //Addr# G00004000# done #define CMD_READ_VERSION 'V' //V# V# done #define CMD_LOAD_APP 'X' //Load program (Note: Custom to Massdrop Bootloader) done //Applet info consists of 8 32-bit words found at the end of applet binary #pragma pack(push, 1) typedef struct appinfo_s { uint32_t magic; uint32_t load_addr; uint32_t mail_addr; uint32_t unused[5]; } appinfo_t; #pragma pack(pop) //SAM-BA Settings extern mailbox_t initparams; extern mailbox_t appletinfo; extern appinfo_t appinfo; typedef struct mcu_s { char name[20]; //MCU Name int cidr_addr; //Chip ID Address int cidr; //Chip ID int flash_size; //Program Memory (FLASH_SIZE) int ram_size; //Data Memory (HSRAM_SIZE) int flash_addr; //Program Addr (FLASH_ADDR) int ram_addr; //Data Addr (HSRAM_ADDR) } mcu_t; extern mcu_t mcus[]; extern mcu_t *mcu; extern uint32_t bootloader_length; int check_bootloader_write_attempt(int addr); extern int read_error; int print_bootloader_serial(void); int send_mail(mailbox_t *mail); int read_mail(mailbox_t *mail); int print_mail(mailbox_t *mail); #define APPLET_WAIT_MS 10 //Time between retries #define APPLET_RETRY_NORMAL 10 //Normal operation retries #define APPLET_RETRY_ERASE 25 //Erase operation retries int run_applet(mailbox_t *mail); void display_version(void); void display_copyright(void); void display_help(void); enum command { CMD_NONE = 0, CMD_HELP, CMD_VERSION, CMD_LISTDEV, CMD_DOWNLOAD, CMD_UPLOAD, CMD_TEST, CMD_ABORT }; extern struct option long_options[]; #define COLW 4 #define COLS 8 #define TOKCHAR ' ' #define COLCHAR ' ' void print_hex_listing(char *data, int binfilesize, int markbyte, int base_addr); int write_word(int addr, int data); int write_half_word(int addr, int data); int write_byte(int addr, int data); int read_byte(int addr); int read_half_word(int addr); int read_word(int addr); int set_terminal_mode(void); //OS specific commands void print_com_example(void); int goto_address(int addr); char *recv_file(int addr, int bytes); int send_file(int addr, int bytes, char *data); int print_bootloader_version(void); int set_normal_mode(void); int jump_application(void); int open_port(char *portname, char silent); int close_port(char silent); int config_port(void); int test_port(char *portname, char silent); int test_mcu(char silent); int filesize(char *fname); int read_data(int addr, int readsize); int write_data(int addr, int writesize, int data); void list_devices(char *first); void strupper(char *str); void strlower(char *str); #endif //_MDLOADER_COMMON_H
5,589
C
.c
159
33.396226
106
0.662595
patrickmt/mdloader
3
88
4
GPL-3.0
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,406,088
mdloader_unix.c
patrickmt_mdloader/mdloader_unix.c
/* * Copyright (C) 2018 Massdrop Inc. * * This file is part of Massdrop Loader. * * Massdrop Loader is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Massdrop Loader is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Massdrop Loader. If not, see <https://www.gnu.org/licenses/>. */ #include "mdloader_common.h" #if defined(__APPLE__) && defined(__MACH__) #include <TargetConditionals.h> #if TARGET_OS_MAC == 1 #define EXAMPLE_PORT "/dev/cu.usbmodem14221" #define PORT_SEARCH_STRING "cu.usbmodem" #endif #else #define EXAMPLE_PORT "/dev/ttyACM0" #define PORT_SEARCH_STRING "ttyACM" #endif int gport; //Port of device #define SLEEP_W_MIN 1000 //Sleep (us) per write call #define SLEEP_W_CHR 20 //Sleep (us) per byte written #define WRITE_SIZE 250 //Maximum bytes to write per call #define READ_SIZE 250 //Maximum bytes to read per call #define READ_RETRIES 10 //Maximum read retries before fail void print_com_example(void) { printf("Example: -p " EXAMPLE_PORT "\n"); } //Read data from device //Must check read_error for a read error after return //Return unsigned word from memory location int read_data(int addr, int readsize) { read_error = 1; //Set read error flag as default int readdata = 0; char wbuf[] = "!XXXXXXXX,#"; //Largest buffer needed long ret; if (readsize == 1) sprintf(wbuf,"%c%02x,%c",CMD_READ_ADDR_8,addr,CMD_END); else if (readsize == 2) sprintf(wbuf,"%c%04x,%c",CMD_READ_ADDR_16,addr,CMD_END); else if (readsize == 4) sprintf(wbuf,"%c%08x,%c",CMD_READ_ADDR_32,addr,CMD_END); else { if (verbose) printf("Error: Invalid read size given (%i)\n",readsize); return 0; } if (verbose > 0) printf("Write: [%s]\n",wbuf); tcflush(gport,TCIOFLUSH); //Flush any remaining data from a bad read long writelen = strlen(wbuf); if ((ret = write(gport,wbuf,writelen)) == -1) { if (verbose) printf("Error writing port [%s](%s)\n",wbuf,strerror(errno)); return 0; } usleep(SLEEP_W_MIN + SLEEP_W_CHR * (int)writelen); if (ret != writelen) { if (verbose) printf("Error writing %ld bytes [%ld](%s)\n",writelen,ret,strerror(errno)); return 0; } if ((ret = read(gport, &readdata, readsize)) == -1) { if (verbose) printf("Error reading port [%i][%ld](%s)\n",readsize,ret,strerror(errno)); return 0; } if (ret != readsize) { if (verbose) printf("Error reading %i bytes! [%ld]\n",readsize,ret); return 0; } read_error = 0; //Clear read error flag return readdata; } //Write data to device //Return 1 on success, 0 on failure int write_data(int addr, int writesize, int data) { if (check_bootloader_write_attempt(addr)) return 0; //Prevent writes to bootloader section char wbuf[] = "!XXXXXXXX,XXXXXXXX#"; //Largest buffer needed long ret; if (writesize == 1) sprintf(wbuf,"%c%08x,%02x%c",CMD_WRITE_ADDR_8,addr,data,CMD_END); else if (writesize == 2) sprintf(wbuf,"%c%08x,%04x%c",CMD_WRITE_ADDR_16,addr,data,CMD_END); else if (writesize == 4) sprintf(wbuf,"%c%08x,%08x%c",CMD_WRITE_ADDR_32,addr,data,CMD_END); else { if (verbose) printf("Error: Invalid write size given (%i)\n",writesize); return 0; } if (verbose) printf("Write %i bytes: [%s]\n",writesize,wbuf); long writelen = strlen(wbuf); if ((ret = write(gport,wbuf,writelen)) == -1) { if (verbose) printf("Error writing port [%s](%s)\n",wbuf,strerror(errno)); return 0; } usleep(SLEEP_W_MIN + SLEEP_W_CHR * (int)writelen); if (ret != writelen) { if (verbose) printf("Error writing %i bytes! [%ld]\n",writesize,ret); return 0; } return 1; } //Jump to address and run //Return 1 on success, 0 on failure int goto_address(int addr) { char wbuf[] = "!XXXXXXXX#"; long ret; sprintf(wbuf,"%c%08x%c",CMD_GOTO_ADDR,addr,CMD_END); if (verbose) printf("Write: [%s]\n",wbuf); long writelen = strlen(wbuf); if ((ret = write(gport,wbuf,writelen)) == -1) { if (verbose) printf("Error writing port [%s](%s)\n",wbuf,strerror(errno)); return 0; } usleep(SLEEP_W_MIN + SLEEP_W_CHR * (int)writelen); if (ret != writelen) { if (verbose) printf("Error writing goto address! [%ld]\n",ret); return 0; } return 1; } //Read data from device RAM //Return pointer to buffer on success, NULL on failure char *recv_file(int addr, int bytes) { char wbuf[] = "!XXXXXXXX,XXXXXXXX#"; char *data = NULL; data = (char *)calloc(bytes+1,sizeof(char)); if (data == NULL) { printf("Error allocating read buffer memory!\n"); return NULL; } char *pdata = data; long ret; int retries = READ_RETRIES; int readsize = READ_SIZE; //Constrain read size to buffer size if (initparams.argument.outputInit.bufferSize > 0 && initparams.argument.outputInit.bufferSize < readsize) readsize = initparams.argument.outputInit.bufferSize; while (bytes > 0) { if (readsize > bytes) readsize = bytes; sprintf(wbuf,"%c%08x,%08x%c",CMD_RECV_FILE,addr,readsize,CMD_END); if (verbose > 0) printf("Write: [%s]\n",wbuf); tcflush(gport,TCIOFLUSH); //Flush any remaining data from a bad read long writelen = strlen(wbuf); if ((ret = write(gport,wbuf,writelen)) == -1) { if (verbose) printf("Error writing port [%s](%s)\n",wbuf,strerror(errno)); free(data); return NULL; } usleep(SLEEP_W_MIN + SLEEP_W_CHR * (int)writelen); if ((ret = read(gport, pdata, readsize)) == -1) { if (verbose) printf("Error reading port [%i][%ld](%s)\n",readsize,ret,strerror(errno)); free(data); return NULL; } if (ret != readsize) { if (verbose) printf("Error reading %i bytes! [%ld](%s)\n",readsize,ret,strerror(errno)); if (retries <= 0) { if (verbose) printf("No retries remain!\n"); free(data); return NULL; } retries--; if (verbose) printf("Retrying read... (%i)\n",READ_RETRIES - retries); continue; //Attempt read again } if (verbose > 0) printf("Recv: [%ld]\n",ret); retries = READ_RETRIES; //Reset retry limit bytes -= ret; //Decrement remaining bytes addr += ret; //Increment to next address pdata += ret; //Increment pointer in recv buffer } return data; } //Write data to device //Return 1 on sucess, 0 on failure int send_file(int addr, int bytes, char *data) { if (check_bootloader_write_attempt(addr)) return 0; //Prevent writes to bootloader section if (bytes < 1) { printf("Error: No data to send!\n"); return 0; } char wbuf[] = "!XXXXXXXX,XXXXXXXX#"; long ret; char *pdata = data; long writelen; int writesize = WRITE_SIZE; //Constrain write size to buffer size if it has been reported if (initparams.argument.outputInit.bufferSize > 0 && initparams.argument.outputInit.bufferSize < writesize) writesize = initparams.argument.outputInit.bufferSize; while (bytes > 0) { if (writesize > bytes) writesize = bytes; sprintf(wbuf,"%c%08x,%08x%c",CMD_SEND_FILE,addr,writesize,CMD_END); if (verbose > 0) printf("Write: [%s]\n",wbuf); writelen = strlen(wbuf); if ((ret = write(gport,wbuf,writelen)) == -1) { if (verbose) printf("Error writing port [%s](%s)\n",wbuf,strerror(errno)); return 0; } usleep(SLEEP_W_MIN + SLEEP_W_CHR * (int)writelen); if (ret != writelen) { if (verbose) printf("Error writing port [%s](%s)\n",wbuf,strerror(errno)); return 0; } if (verbose > 0) printf("Write: %i bytes\n",writesize); if ((ret = write(gport,pdata,writesize)) == -1) { if (verbose) printf("Error writing port [%ld][%i](%s)\n",ret,writesize,strerror(errno)); return 0; } usleep(SLEEP_W_MIN + SLEEP_W_CHR * writesize); if (ret != writesize) { printf("Error writing port [%ld][%i](%s)\n",ret,writesize,strerror(errno)); return 0; } bytes -= ret; //Decrement remaining bytes addr += ret; //Increment to next address pdata += ret; //Increment pointer in send buffer } return 1; } //Print bootloader version //Return 1 on sucess, 0 on failure int print_bootloader_version(void) { char wbuf[] = "!#"; char readdata[128] = ""; long ret; int readsize = sizeof(readdata) - 1; sprintf(wbuf,"%c%c",CMD_READ_VERSION,CMD_END); if (verbose > 0) printf("Write: [%s]\n",wbuf); long writelen = strlen(wbuf); if ((ret = write(gport,wbuf,writelen)) == -1) { if (verbose) printf("Version: Error writing port [%s](%s)\n",wbuf,strerror(errno)); else printf("Version: Error retrieving!\n"); return 0; } usleep(SLEEP_W_MIN + SLEEP_W_CHR * (int)writelen); if ((ret = read(gport, &readdata, readsize)) == -1) { if (verbose) printf("Version: Error reading port [%i][%ld](%s)\n",readsize,ret,strerror(errno)); else printf("Version: Error retrieving!\n"); return 0; } while (readdata[strlen(readdata)-1] == '\n' || readdata[strlen(readdata)-1] == '\r') readdata[strlen(readdata)-1] = 0; printf("Bootloader version: %s\n",readdata); return 1; } //Set normal command mode //Return 1 on sucess, 0 on failure int set_normal_mode(void) { if (verbose) printf("Setting normal mode... "); int retbuf = 0; char wbuf[] = "!#"; long ret; sprintf(wbuf,"%c%c",CMD_SET_NORMAL_MODE,CMD_END); long writelen = strlen(wbuf); if ((ret = write(gport,wbuf,writelen)) == -1) { if (verbose) printf("Failed! (%s)\n",strerror(errno)); return 0; } usleep(SLEEP_W_MIN + SLEEP_W_CHR * (int)writelen); if (ret != writelen) { if (verbose) printf("Error writing %ld bytes! [%ld](%s)\n",writelen,ret,strerror(errno)); return 0; } int readlen = 2; if ((ret = read(gport, &retbuf, readlen)) == -1) { if (verbose) printf("Error reading port [%i][%ld](%s)\n",readlen,ret,strerror(errno)); return 0; } if (ret != readlen) { if (verbose) printf("Error reading %i bytes! [%ld][%04x](%s)\n",readlen,ret,retbuf,strerror(errno)); return 0; } if ((retbuf & 0xFFFF) != 0x0D0A) { if (verbose) printf("Error: Incorrect response! [%ld][%04x](%s)\n",ret,retbuf,strerror(errno)); return 0; } if (verbose) printf("Success!\n"); return 1; } //Jump to loaded application //Return 1 on sucess, 0 on failure int jump_application(void) { printf("Booting device... "); if (testmode) { printf("(test mode disables restart)\n"); return 1; } char wbuf[] = "!#"; long ret; long writelen = strlen(wbuf); sprintf(wbuf,"%c%c",CMD_LOAD_APP,CMD_END); if ((ret = write(gport,wbuf,writelen)) == -1) { printf("Failed! (%s)\n",strerror(errno)); return 0; } usleep(SLEEP_W_MIN + SLEEP_W_CHR * (int)writelen); printf("Success!\n"); return 1; } //Open port //Return 1 on sucess, 0 on failure int open_port(char *portname, char silent) { if (!silent || verbose) printf("Opening port '%s'... ",portname); gport = open(portname,O_RDWR|O_NOCTTY); if (gport == -1) { if (!silent || verbose) { printf("Failed!"); printf(" (%s)",strerror(errno)); printf("\n"); } return 0; } if (!silent || verbose) printf("Success!\n"); return 1; } //Close port //Return 1 on sucess, 0 on failure int close_port(char silent) { if (!silent || verbose) printf("Closing port... "); if (close(gport) == -1) { if (!silent || verbose) printf("Failed! (%s)\n",strerror(errno)); return 0; } if (!silent || verbose) printf("Success!\n"); return 1; } //Configure port //Return 1 on sucess, 0 on failure int config_port(void) { if (verbose) printf("Configuring port... \n"); struct termios tty; memset(&tty,0,sizeof(tty)); if (verbose) printf(" Get config... "); if (tcgetattr(gport, &tty) != 0) { if (verbose) printf("Failed! (%s)\n",strerror(errno)); return 0; } if (verbose) printf("Success!\n"); cfsetspeed(&tty, (speed_t)B115200); cfmakeraw(&tty); tty.c_cflag = CS8 | CREAD | CLOCAL; tty.c_iflag = IGNBRK; tty.c_lflag = 0; tty.c_oflag = 0; tty.c_cc[VMIN] = 0; tty.c_cc[VTIME] = 5; if (verbose) printf(" Set config... "); if (tcsetattr(gport,TCSANOW,&tty) != 0) { if (verbose) printf("Failed! (%s)\n",strerror(errno)); return 0; } if (verbose) printf("Success!\n"); tcflush(gport,TCIOFLUSH); //Flush port return 1; } #define FNMAX 255 //List devices which communicate properly //If first_device is not null, store first found device and return void list_devices(char *first_device) { char devdir[] = "/dev"; DIR *pdev; pdev = opendir(devdir); if (pdev != NULL) { struct dirent *pdevfile; int portcount = 0; if (first_device == NULL) { printf("Bootloader port listing\n"); printf("-----------------------------\n"); } while ((pdevfile = readdir(pdev)) != NULL) { if (pdevfile->d_type == DT_CHR) { if (strstr(pdevfile->d_name,PORT_SEARCH_STRING) == pdevfile->d_name) { char pathbuf[sizeof(devdir)+1+FNMAX+1] = ""; sprintf(pathbuf,"%s/%s",devdir,pdevfile->d_name); if (test_port(pathbuf,TRUE)) { if (test_mcu(TRUE)) { if (first_device) printf("\n"); printf("Device port: %s (%s)\n",pathbuf,mcu->name); if (first_device != NULL) { close_port(TRUE); strcpy(first_device,pathbuf); return; } portcount++; } close_port(TRUE); } } } } closedir(pdev); if (first_device == NULL) { if (portcount == 0) printf("No devices found!\n"); } } else printf("Error: Could not open dev directory (%s)\n",strerror(errno)); }
15,609
C
.c
463
26.74514
122
0.579231
patrickmt/mdloader
3
88
4
GPL-3.0
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,406,104
mdloader_parser.h
patrickmt_mdloader/mdloader_parser.h
/* * Copyright (C) 2018 Massdrop Inc. * * This file is part of Massdrop Loader. * * Massdrop Loader is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Massdrop Loader is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Massdrop Loader. If not, see <https://www.gnu.org/licenses/>. */ #ifndef _MDLOADER_PARSER_H #define _MDLOADER_PARSER_H #define EXT_HEX ".hex" #define EXT_BIN ".bin" #define FTYPE_NONE 0 //No file type #define FTYPE_HEX 1 //HEX file type detected #define FTYPE_BIN 2 //BIN file type detected typedef struct data_s { uint32_t addr; uint32_t size; char *data; } data_t; void free_data(data_t *data); data_t *create_data(uint32_t data_length); data_t *load_file(char *fname); #pragma pack(push, 1) typedef struct hex_record_s { char start_code; //: char byte_count[2]; //XX union { uint32_t i; uint8_t c[4]; //XXXX } address; char record_type[2]; //XX //<- variable length ASCII data matching byte_count*2 -> //XX checksum } hex_record_t; #pragma pack(pop) #endif //_MDLOADER_PARSER_H
1,569
C
.h
47
30.680851
77
0.69637
patrickmt/mdloader
3
88
4
GPL-3.0
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,406,110
applet.h
patrickmt_mdloader/atmel/applet.h
/* ---------------------------------------------------------------------------- * SAM Software Package License * ---------------------------------------------------------------------------- * Copyright (c) 2013, Atmel Corporation * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the disclaimer below. * * Atmel's name may not be used to endorse or promote products derived from * this software without specific prior written permission. * * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ---------------------------------------------------------------------------- */ #ifndef APPLET_H #define APPLET_H /*---------------------------------------------------------------------------- * Global definitions *----------------------------------------------------------------------------*/ /** Refers to the Version of SAM-BA */ #define SAM_BA_APPLETS_VERSION "2.16" /** Applet initialization command code.*/ #define APPLET_CMD_INIT 0x00 /** Applet full erase command code.*/ #define APPLET_CMD_FULL_ERASE 0x01 /** Applet write command code.*/ #define APPLET_CMD_WRITE 0x02 /** Applet read command code.*/ #define APPLET_CMD_READ 0x03 /** Applet read command code.*/ #define APPLET_CMD_LOCK 0x04 /** Applet read command code.*/ #define APPLET_CMD_UNLOCK 0x05 /** Applet set/clear GPNVM command code.*/ #define APPLET_CMD_GPNVM 0x06 /** Applet set security bit command code.*/ #define APPLET_CMD_SECURITY 0x07 /** Applet buffer erase command code.*/ #define APPLET_CMD_BUFFER_ERASE 0x08 /** Applet binary page command code for Dataflash.*/ #define APPLET_CMD_BINARY_PAGE 0x09 /** List Bad Blocks of a Nandflash*/ #define APPLET_CMD_LIST_BAD_BLOCKS 0x10 /** Tag a Nandflash Block*/ #define APPLET_CMD_TAG_BLOCK 0x11 /** Read the Unique ID bits (on SAM3)*/ #define APPLET_CMD_READ_UNIQUE_ID 0x12 /** Applet blocks erase command code. */ #define APPLET_CMD_ERASE_BLOCKS 0x13 /** Applet batch full erase command code. */ #define APPLET_CMD_BATCH_ERASE 0x14 /** Applet row erase command */ #define APPLET_CMD_ERASE_ROW 0x40 /** Applet read device ID command */ #define APPLET_CMD_READ_DEVICE_ID 0x41 /** Applet read lock bits command */ #define APPLET_CMD_READ_LOCKS 0x42 /** Applet read fuses command */ #define APPLET_CMD_READ_FUSES 0x43 /** Applet erase application section command */ #define APPLET_CMD_ERASE_APP 0x44 /** Applet information command */ //Massdrop Specific #define APPLET_CMD_INFO 0xF0 /** Operation was successful.*/ #define APPLET_SUCCESS 0x00 /** Device unknown.*/ #define APPLET_DEV_UNKNOWN 0x01 /** Write operation failed.*/ #define APPLET_WRITE_FAIL 0x02 /** Read operation failed.*/ #define APPLET_READ_FAIL 0x03 /** Protect operation failed.*/ #define APPLET_PROTECT_FAIL 0x04 /** Unprotect operation failed.*/ #define APPLET_UNPROTECT_FAIL 0x05 /** Erase operation failed.*/ #define APPLET_ERASE_FAIL 0x06 /** No device defined in board.h*/ #define APPLET_NO_DEV 0x07 /** Read / write address is not aligned*/ #define APPLET_ALIGN_ERROR 0x08 /** Read / write found bad block*/ #define APPLET_BAD_BLOCK 0x09 /** Applet failure.*/ #define APPLET_FAIL 0x0f /** Communication link identification*/ #define USB_COM_TYPE 0x00 #define DBGU_COM_TYPE 0x01 #define JTAG_COM_TYPE 0x02 /** \brief Structure for storing parameters for each command that can be * performed by the applet. */ //Note: 9 x 32-bit word in size typedef struct mailbox_s { /** Command send to the monitor to be executed. */ uint32_t command; /** Returned status, updated at the end of the monitor execution.*/ uint32_t status; /** Input Arguments in the argument area. */ union { /** Input arguments for the Init command.*/ struct { /** Communication link used.*/ uint32_t comType; /** Trace level.*/ uint32_t traceLevel; /** Memory Bank to write in.*/ uint32_t bank; } inputInit; /** Output arguments for the Init command.*/ struct { /** Memory size.*/ uint32_t memorySize; /** Buffer address.*/ uint32_t bufferAddress; /** Buffer size.*/ uint32_t bufferSize; struct { /** Lock region size in byte.*/ uint16_t lockRegionSize; /** Number of Lock Bits.*/ uint16_t numbersLockBits; } memoryInfo; /** extended infos.*/ uint32_t pageSize; uint32_t nbPages; uint32_t appStartPage; } outputInit; /** Input arguments for the Write command.*/ struct { /** Buffer address.*/ uint32_t bufferAddr; /** Buffer size.*/ uint32_t bufferSize; /** Memory offset.*/ uint32_t memoryOffset; } inputWrite; /** Output arguments for the Write command.*/ struct { /** Bytes written.*/ uint32_t bytesWritten; } outputWrite; /** Input arguments for the Read command.*/ struct { /** Buffer address.*/ uint32_t bufferAddr; /** Buffer size.*/ uint32_t bufferSize; /** Memory offset.*/ uint32_t memoryOffset; } inputRead; /** Output arguments for the Read command.*/ struct { /** Bytes read.*/ uint32_t bytesRead; } outputRead; /** Input arguments for the Full Erase command.*/ /** NONE*/ /** Input arguments for the Lock row command.*/ struct { /** Row number to be lock.*/ uint32_t row; } inputLock; /** Output arguments for the Lock row command.*/ /** NONE*/ /** Input arguments for the Unlock row command.*/ struct { /** Row number to be unlock.*/ uint32_t row; } inputUnlock; /** Output arguments for the Unlock row command.*/ /** NONE*/ /** Input arguments for the set security bit command.*/ /** NONE*/ /** Output arguments for the set security bit command.*/ /** NONE*/ /** Input arguments for the Read Locks command. */ /** NONE */ /** Output arguments for the Read Locks command. */ struct { /** Buffer address. */ uint32_t bufferAddr; } outputReadLocks; /** Input arguments for the Read Fuses command. */ /** NONE */ /** Output arguments for the Read Fuses command. */ struct { /** Buffer address. */ uint32_t bufferAddr; } outputReadFuses; /** Input arguments for the Read Unique SN command.*/ struct { /** Buffer address.*/ uint32_t bufferAddr; } inputReadUniqueID; /** Output arguments for the Read Unique SN command.*/ /** NONE*/ /** Input arguments for the Security command.*/ struct { /** Activates*/ uint32_t action; } inputSecurity; /** Output arguments for the Security command.*/ /** NONE */ /** Input arguments for the erase row command.*/ struct { /** page.*/ uint32_t row; } inputEraseRow; /** Output arguments for the erase row command.*/ /*NONE*/ /** Input arguments for the erase app command */ struct { /** Starting row number */ uint32_t start_row; /** Ending row number */ uint32_t end_row; } inputEraseApp; /** Output arguments for the erase app command */ /** NONE */ /** Input arguments for information command */ //Massdrop Specific /** NONE */ /** Output arguments for information command */ //Massdrop Specific struct { /** Applet version number */ uint16_t version_number; } outputInfo; } argument; } mailbox_t; #endif /* #ifndef APPLET_H */
9,339
C
.h
243
31.769547
80
0.581444
patrickmt/mdloader
3
88
4
GPL-3.0
9/7/2024, 2:14:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,578,996
sc_args.c
RIOT-OS_RobotFW-tests/utils/sc_args/sc_args.c
/* * Copyright (C) 2019 HAW Hamburg * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup tests * @{ * * @file * @brief Shell helpers * * @author Sebastian Meiling <[email protected]> * * @} */ #include <assert.h> #include <errno.h> #include <inttypes.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include "shell.h" #include "sc_args.h" #define INVALID_ARGS puts("Error: Invalid number of arguments"); int sc_args_check(int argc, char **argv, int c_min, int c_max, char *use) { if (argc - 1 < c_min || argc - 1 > c_max) { printf("Usage: %s %s\n", argv[0], use); INVALID_ARGS; return ARGS_ERROR; } return ARGS_OK; } int sc_arg2long(const char *arg, long *val) { errno = 0; char *end; long res = strtol(arg, &end, 0); if ((*end != '\0') || ((res == LONG_MIN || res == LONG_MAX) && errno == ERANGE)) { return ARGS_ERROR; } *val = res; return ARGS_OK; } int sc_arg2int(const char *arg, int *val) { long lval; int res = sc_arg2long(arg, &lval); if (res == ARGS_OK) { *val = (int)lval; } return res; } int sc_arg2ulong(const char *arg, unsigned long *val) { errno = 0; char *end; unsigned long res = strtoul(arg, &end, 0); if ((*end != '\0') || (res == LONG_MAX && errno == ERANGE)) { return ARGS_ERROR; } *val = res; return ARGS_OK; } int sc_arg2uint(const char *arg, unsigned int *val) { unsigned long lval; int res = sc_arg2ulong(arg, &lval); if (res == ARGS_OK) { *val = (unsigned int)lval; } return res; } int sc_arg2u32(const char *arg, uint32_t *val) { unsigned long lval; int res = sc_arg2ulong(arg, &lval); if (res == ARGS_OK) { *val = (uint32_t)lval; } return res; } int sc_arg2s32(const char *arg, int32_t *val) { unsigned long lval; int res = sc_arg2ulong(arg, &lval); if (res == ARGS_OK) { *val = (int32_t)lval; } return res; } int sc_arg2u16(const char *arg, uint16_t *val) { unsigned long lval; int res = sc_arg2ulong(arg, &lval); if (res == ARGS_OK) { *val = (uint16_t)lval; } return res; } int sc_arg2u8(const char *arg, uint8_t *val) { unsigned long lval; int res = sc_arg2ulong(arg, &lval); if (res == ARGS_OK) { *val = (uint8_t)lval; } return res; } int sc_arg2dev(const char *arg, unsigned maxdev) { int dev = 0; if (sc_arg2int(arg, &dev) != ARGS_OK) { return ARGS_ERROR; } if (dev >= (int)maxdev) { return ARGS_ERROR; } return dev; }
2,756
C
.c
123
18.577236
86
0.589224
RIOT-OS/RobotFW-tests
3
13
16
LGPL-2.1
9/7/2024, 2:15:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,578,998
sc_args.h
RIOT-OS_RobotFW-tests/utils/sc_args/include/sc_args.h
#ifndef SHELL_ARGS_H #define SHELL_ARGS_H #define CONVERT_ERROR (-32768) #define ARGS_OK (0) #define ARGS_ERROR (-1) int sc_args_check(int argc, char **argv, int c_min, int c_max, char *use); int sc_arg2int(const char *arg, int *val); int sc_arg2long(const char *arg, long *val); int sc_arg2uint(const char *arg, unsigned int *val); int sc_arg2ulong(const char *arg, unsigned long *val); int sc_arg2u32(const char *arg, uint32_t *val); int sc_arg2s32(const char *arg, int32_t *val); int sc_arg2u16(const char *arg, uint16_t *val); int sc_arg2u8(const char *arg, uint8_t *val); int sc_arg2dev(const char *arg, unsigned maxdev); #endif /* SHELL_ARGS_H */
673
C
.c
16
40.25
74
0.717391
RIOT-OS/RobotFW-tests
3
13
16
LGPL-2.1
9/7/2024, 2:15:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,579,000
test_helpers.c
RIOT-OS_RobotFW-tests/utils/test_helpers/test_helpers.c
/* * Copyright (C) 2019 HAW Hamburg * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup tests * @{ * * @file * @brief Test helpers for writing tests with standard interfaces. * * @author Kevin Weiss <[email protected]> * * @} */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <inttypes.h> #include "test_helpers.h" #ifdef JSON_SHELL_PARSER static int parser_state[NUM_OF_JSON_SHELL_PARSER] = {0}; #endif #ifdef JSON_SHELL_PARSER static void _start_json(int dev) { if (parser_state[dev] == JSON_STATE_READY) { printf("{"); parser_state[dev] |= JSON_STATE_STARTED; } else { printf(","); } } #endif void print_cmd(int dev, char *cmd) { #ifdef JSON_SHELL_PARSER _start_json(dev); assert(!(parser_state[dev] & JSON_STATE_DATA_STARTED)); printf("\"cmd\":\"%s\"", cmd); #else (void)dev; puts(cmd); #endif } void print_data_dict_str(int dev, char *key, char *val) { #ifdef JSON_SHELL_PARSER _start_json(dev); if (!(parser_state[dev] & JSON_STATE_DATA_STARTED)) { printf("\"data\":["); parser_state[dev] |= JSON_STATE_DATA_STARTED; } printf("{\"%s\":\"%s\"}", key, val); #else (void)dev; printf("%s: %s\n", key, val); #endif } void print_data_int(int dev, int32_t data) { #ifdef JSON_SHELL_PARSER _start_json(dev); if (!(parser_state[dev] & JSON_STATE_DATA_STARTED)) { printf("\"data\":["); parser_state[dev] |= JSON_STATE_DATA_STARTED; } printf("%" PRIi32, data); #else (void)dev; printf("%" PRIi32 "\n", data); #endif } void print_data_str(int dev, char *str) { #ifdef JSON_SHELL_PARSER _start_json(dev); if (!(parser_state[dev] & JSON_STATE_DATA_STARTED)) { printf("\"data\":["); parser_state[dev] |= JSON_STATE_DATA_STARTED; } printf("\"%s\"", str); #else (void)dev; puts(str); #endif } void print_result(int dev, char *res) { #ifdef JSON_SHELL_PARSER if ((parser_state[dev] & JSON_STATE_DATA_STARTED)) { printf("]"); parser_state[dev] &= ~JSON_STATE_DATA_STARTED; } _start_json(dev); printf("\"result\":\"%s\"}\n", res); parser_state[dev] &= ~JSON_STATE_STARTED; #else (void)dev; puts(res); #endif }
2,439
C
.c
109
18.93578
72
0.617241
RIOT-OS/RobotFW-tests
3
13
16
LGPL-2.1
9/7/2024, 2:15:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,579,003
main.c
RIOT-OS_RobotFW-tests/tests/xtimer_benchmarks/main.c
/* * Copyright (C) 2020 HAW Hamburg * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup tests * @{ * * @file * @brief RIOT timer benchmarks * * @author M. Aiman Ismail <[email protected]> * * @} */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "periph/gpio.h" #include "test_utils/expect.h" #include "fmt.h" #include "shell.h" #include "test_helpers.h" #include "sc_args.h" #include "random.h" #include "timex.h" #include "mutex.h" #define ENABLE_DEBUG (0) #include "debug.h" #include "log.h" #ifndef PARSER_DEV_NUM #define PARSER_DEV_NUM 0 #endif #define HIL_TEST_REPEAT (50) #define HIL_MAX_TIMERS (50) #define HIL_TEST_GPIO GPIO_PIN(TIMER_TRACE_PORT, TIMER_TRACE_PIN) #define HIL_START_TIMER() gpio_set(HIL_TEST_GPIO) #define HIL_STOP_TIMER() gpio_clear(HIL_TEST_GPIO) #define HIL_TOGGLE_TIMER() gpio_toggle(HIL_TEST_GPIO) #ifndef MODULE_ZTIMER #include "xtimer.h" #define TIMER_T xtimer_t #define TIMER_NOW() xtimer_now_usec() #define TIMER_SET(timer, duration) xtimer_set(timer, duration) #define TIMER_REMOVE(timer) xtimer_remove(timer) #define TIMER_SLEEP(duration) xtimer_usleep(duration) #else #include "ztimer.h" #define TIMER_T ztimer_t #define ZTIMER_CLOCK ZTIMER_USEC #define TIMER_NOW() ztimer_now(ZTIMER_CLOCK) #define TIMER_SET(timer, duration) ztimer_set(ZTIMER_CLOCK, timer, duration) #define TIMER_REMOVE(timer) ztimer_remove(ZTIMER_CLOCK, timer) #define TIMER_SLEEP(duration) ztimer_sleep(ZTIMER_CLOCK, duration) #endif char printbuf[SHELL_DEFAULT_BUFSIZE] = { 0 }; uint8_t in_buf[64]; uint8_t out_buf[64]; static TIMER_T test_timers[HIL_MAX_TIMERS]; /* Default is whatever, just some small delay if the user forgets to initialize */ static uint32_t spin_max = 64; /************************ * HELPER FUNCTIONS ************************/ /** * @brief Busy wait (spin) for the given number of loop iterations */ static void spin(uint32_t limit) { /* Platform independent busy wait loop, should never be optimized out * because of the volatile asm statement */ while (limit--) { __asm__ volatile (""); } } void spin_random_delay(void) { uint32_t limit = random_uint32_range(0, spin_max); spin(limit); } /************************ * OVERHEAD ************************/ #define OVERHEAD_SPREAD (1000UL) void cleanup_overhead(void) { for (unsigned i = 0; i < HIL_MAX_TIMERS; ++i) { TIMER_REMOVE(&test_timers[i]); } } int overhead_gpio_cmd(int argc, char **argv) { (void)argc; (void)argv; gpio_clear(HIL_TEST_GPIO); sprintf(printbuf, "gpio overhead"); print_cmd(PARSER_DEV_NUM, printbuf); for (int i = 0; i < HIL_TEST_REPEAT; i++) { HIL_START_TIMER(); HIL_STOP_TIMER(); HIL_START_TIMER(); HIL_STOP_TIMER(); TIMER_SLEEP(1000); } print_result(PARSER_DEV_NUM, TEST_RESULT_SUCCESS); return 0; } int overhead_timer_now(int argc, char **argv) { (void)argc; (void)argv; sprintf(printbuf, "overhead timer now"); print_cmd(PARSER_DEV_NUM, printbuf); gpio_clear(HIL_TEST_GPIO); for (unsigned i = 0; i < HIL_TEST_REPEAT; ++i) { spin_random_delay(); HIL_START_TIMER(); TIMER_NOW(); HIL_STOP_TIMER(); } print_result(PARSER_DEV_NUM, TEST_RESULT_SUCCESS); return 0; } static void _overhead_callback(void *arg) { (void)arg; expect(false); } uint32_t _delay(unsigned n) { return 1 * US_PER_SEC + (OVERHEAD_SPREAD * n); } int timer_overhead_timer_cmd(int argc, char **argv) { if (argc < 3) { print_result(PARSER_DEV_NUM, TEST_RESULT_ERROR); return -1; } gpio_clear(HIL_TEST_GPIO); const char *method = argv[1]; const char *pos = argv[2]; sprintf(printbuf, "timer overhead: %s %s timer", method, pos); print_cmd(PARSER_DEV_NUM, printbuf); sprintf(printbuf, "%u", HIL_MAX_TIMERS); print_data_dict_str(PARSER_DEV_NUM, "timer count", printbuf); sprintf(printbuf, "%u", HIL_TEST_REPEAT); print_data_dict_str(PARSER_DEV_NUM, "sample count", printbuf); /* init the timers */ for (unsigned i = 0; i < HIL_MAX_TIMERS; ++i) { test_timers[i].callback = _overhead_callback; } unsigned timer_idx = -1; if (strcmp(pos, "first") == 0) { timer_idx = 0; } else if (strcmp(pos, "middle") == 0) { timer_idx = (HIL_MAX_TIMERS / 2) - 1; } else if (strcmp(pos, "last") == 0) { timer_idx = HIL_MAX_TIMERS - 1; } else { goto error; } if (strcmp(method, "set") == 0) { for (unsigned n = 0; n < HIL_TEST_REPEAT; ++n) { /* set all but the last timer */ for (unsigned i = 0; i < timer_idx; ++i) { TIMER_SET(&test_timers[i], _delay(i)); } spin_random_delay(); /* set the last timer */ HIL_START_TIMER(); TIMER_SET(&test_timers[timer_idx], _delay(timer_idx)); HIL_STOP_TIMER(); cleanup_overhead(); } } else if (strcmp(method, "remove") == 0) { for (unsigned n = 0; n < HIL_TEST_REPEAT; ++n) { /* set timers until timer_idx */ for (unsigned i = 0; i <= timer_idx; ++i) { TIMER_SET(&test_timers[i], _delay(i)); } spin_random_delay(); /* remove the timer at timer_idx */ HIL_START_TIMER(); TIMER_REMOVE(&test_timers[timer_idx]); HIL_STOP_TIMER(); cleanup_overhead(); } } else { error: cleanup_overhead(); print_result(PARSER_DEV_NUM, TEST_RESULT_ERROR); return -1; } cleanup_overhead(); print_result(PARSER_DEV_NUM, TEST_RESULT_SUCCESS); return 0; } int timer_overhead_nth_timer_cmd(int argc, char **argv) { if (argc < 3) { print_result(PARSER_DEV_NUM, TEST_RESULT_ERROR); return -1; } gpio_clear(HIL_TEST_GPIO); const char *method = argv[1]; unsigned timer_idx = atoi(argv[2]) - 1; cleanup_overhead(); /* init the timers */ for (unsigned i = 0; i < HIL_MAX_TIMERS; ++i) { test_timers[i].callback = _overhead_callback; } if (strcmp(method, "set") == 0) { for (unsigned n = 0; n < HIL_TEST_REPEAT; ++n) { /* set all but the last timer */ for (unsigned i = 0; i < timer_idx; ++i) { TIMER_SET(&test_timers[i], _delay(i)); } spin_random_delay(); /* set the last timer */ HIL_START_TIMER(); TIMER_SET(&test_timers[timer_idx], _delay(timer_idx)); HIL_STOP_TIMER(); cleanup_overhead(); } } else if (strcmp(method, "remove") == 0) { for (unsigned n = 0; n < HIL_TEST_REPEAT; ++n) { /* set all timer */ for (unsigned i = 0; i <= timer_idx; ++i) { TIMER_SET(&test_timers[i], _delay(i)); } spin_random_delay(); /* remove the last timer */ HIL_START_TIMER(); TIMER_REMOVE(&test_timers[timer_idx]); HIL_STOP_TIMER(); cleanup_overhead(); } } print_result(PARSER_DEV_NUM, TEST_RESULT_SUCCESS); return 0; } /************************ * ACCURACY ************************/ void _sleep_accuracy_timer_set_cb(void *arg) { HIL_STOP_TIMER(); bool *triggered = (bool *)arg; *triggered = true; } int sleep_accuracy_timer_set_cmd(int argc, char **argv) { if (argc < 2) { print_result(PARSER_DEV_NUM, TEST_RESULT_ERROR); return -1; } gpio_clear(HIL_TEST_GPIO); int sleeptime = strtol(argv[1], NULL, 10); if (sleeptime < 0) { print_result(PARSER_DEV_NUM, TEST_RESULT_ERROR); return -1; } sprintf(printbuf, "sleep_accuracy: timer_sleep(%s)", argv[1]); print_cmd(PARSER_DEV_NUM, printbuf); volatile bool triggered; TIMER_T timer = { .callback = _sleep_accuracy_timer_set_cb, .arg = (void *)&triggered, }; /* measure using PHiLIP */ for (unsigned i = 0; i < HIL_TEST_REPEAT; i++) { spin_random_delay(); triggered = false; HIL_START_TIMER(); TIMER_SET(&timer, sleeptime); while (!triggered) {} } print_result(PARSER_DEV_NUM, TEST_RESULT_SUCCESS); return 0; } int sleep_accuracy_timer_sleep_cmd(int argc, char **argv) { if (argc < 2) { print_result(PARSER_DEV_NUM, TEST_RESULT_ERROR); return -1; } gpio_clear(HIL_TEST_GPIO); sprintf(printbuf, "sleep_accuracy: timer_sleep(%s)", argv[1]); print_cmd(PARSER_DEV_NUM, printbuf); int sleeptime = strtol(argv[1], NULL, 10); if (sleeptime < 0) { print_result(PARSER_DEV_NUM, TEST_RESULT_ERROR); return -1; } /* measure using PHiLIP */ for (unsigned i = 0; i < HIL_TEST_REPEAT; i++) { spin_random_delay(); HIL_START_TIMER(); TIMER_SLEEP(sleeptime); HIL_STOP_TIMER(); } print_result(PARSER_DEV_NUM, TEST_RESULT_SUCCESS); return 0; } /************************ * JITTER ************************/ #define JITTER_TIMER_INTERVAL (10 * MS_PER_SEC) #define JITTER_WAKEUPS (2 * HIL_TEST_REPEAT) #define JITTER_START_RECORD 5 #define JITTER_PARAM_SIZE 25 typedef struct sleep_jitter_params { TIMER_T *timer; uint8_t idx; uint8_t iter; uint8_t recorded; } jitter_params_t; static mutex_t jitter_mutex = MUTEX_INIT_LOCKED; static jitter_params_t jitter_params[JITTER_PARAM_SIZE]; static uint32_t jitter_wakeups[JITTER_WAKEUPS]; static uint32_t jitter_start; static bool start_record = false; static bool jitter_end = false; void cleanup_jitter(unsigned count, jitter_params_t *params) { TIMER_SLEEP(1 * US_PER_SEC); for (unsigned i = 0; i < count; ++i) { TIMER_REMOVE(params[i].timer); } memset(jitter_params, 0, sizeof(jitter_params)); memset(jitter_wakeups, 0, sizeof(jitter_wakeups)); jitter_start = 0; start_record = false; jitter_end = false; HIL_STOP_TIMER(); } static uint32_t _next_target(jitter_params_t *params) { return (++params->iter * JITTER_TIMER_INTERVAL) + jitter_start; } static void jitter_main_cb(void *arg) { jitter_params_t *params = (jitter_params_t *)arg; if (!jitter_end) { uint32_t now = TIMER_NOW(); if (start_record) { HIL_TOGGLE_TIMER(); jitter_wakeups[params->recorded++] = now; } TIMER_SET(params->timer, _next_target(params) - now); if (params->recorded >= JITTER_WAKEUPS) { jitter_end = true; start_record = false; mutex_unlock(&jitter_mutex); } } } static void jitter_cb(void *arg) { if (!jitter_end) { jitter_params_t *params = (jitter_params_t *)arg; TIMER_SET(params->timer, _next_target(params) - TIMER_NOW()); } } int sleep_jitter_cmd(int argc, char **argv) { if (argc < 2) { print_data_str(PARSER_DEV_NUM, "Not enough arguments"); print_result(PARSER_DEV_NUM, TEST_RESULT_ERROR); return -1; } print_cmd(PARSER_DEV_NUM, "sleep_jitter"); unsigned timer_count = atoi(argv[1]); sprintf(printbuf, "%u", timer_count); print_data_dict_str(PARSER_DEV_NUM, "timer-count", printbuf); sprintf(printbuf, "%lu", JITTER_TIMER_INTERVAL); print_data_dict_str(PARSER_DEV_NUM, "timer-interval", printbuf); if (timer_count <= 0 || timer_count > ARRAY_SIZE(jitter_params)) { print_data_str(PARSER_DEV_NUM, "timer count invalid"); print_result(PARSER_DEV_NUM, TEST_RESULT_ERROR); return -1; } jitter_start = TIMER_NOW(); HIL_START_TIMER(); /* setup half of the background timers before the periodic timer */ for (unsigned i = 0; i < timer_count; i++) { jitter_params[i].timer = &test_timers[i]; jitter_params[i].iter = 0; jitter_params[i].idx = i; TIMER_T *timer = jitter_params[i].timer; timer->callback = (i < timer_count - 1) ? jitter_cb : jitter_main_cb; timer->arg = &jitter_params[i]; TIMER_SET(timer, _next_target(&jitter_params[i]) - jitter_start); } start_record = true; mutex_lock(&jitter_mutex); /* Print DUT timer values */ printf(", { \"start-time\": %" PRIu32 "", jitter_start); printf(", \"wakeups\": ["); for (unsigned i = 0; i < JITTER_WAKEUPS; ++i) { printf("%" PRIu32 "%s", jitter_wakeups[i], (i < JITTER_WAKEUPS - 1) ? "," : "]"); } printf(" }"); cleanup_jitter(timer_count, jitter_params); print_result(PARSER_DEV_NUM, TEST_RESULT_SUCCESS); return 0; } /************************ * DRIFT ************************/ int drift_cmd(int argc, char **argv) { if (argc < 2) { print_data_str(PARSER_DEV_NUM, "Not enough arguments"); print_result(PARSER_DEV_NUM, TEST_RESULT_ERROR); return -1; } gpio_clear(HIL_TEST_GPIO); uint32_t duration = atoi(argv[1]); /* duration in microseconds */ sprintf(printbuf, "drift: %" PRIu32 " us", duration); print_cmd(PARSER_DEV_NUM, printbuf); uint32_t start = TIMER_NOW(); HIL_START_TIMER(); TIMER_SLEEP(duration); HIL_STOP_TIMER(); uint32_t diff = TIMER_NOW() - start; uint32_t us = diff % US_PER_SEC; uint32_t sec = diff / US_PER_SEC; sprintf(printbuf, "%" PRIu32 ".%06" PRIu32 "", sec, us); print_data_str(PARSER_DEV_NUM, printbuf); print_result(PARSER_DEV_NUM, TEST_RESULT_SUCCESS); return 0; } /************************ * ETC ************************/ int cmd_get_timer_version(int argc, char **argv) { (void)argv; (void)argc; #ifdef MODULE_ZTIMER sprintf(printbuf, "ztimer"); #else sprintf(printbuf, "xtimer"); #endif print_data_str(PARSER_DEV_NUM, printbuf); print_result(PARSER_DEV_NUM, TEST_RESULT_SUCCESS); return 0; } int cmd_get_metadata(int argc, char **argv) { (void)argv; (void)argc; print_data_str(PARSER_DEV_NUM, RIOT_BOARD); print_data_str(PARSER_DEV_NUM, RIOT_VERSION); print_data_str(PARSER_DEV_NUM, RIOT_APPLICATION); print_result(PARSER_DEV_NUM, TEST_RESULT_SUCCESS); return 0; } int cmd_gpio_clear(int argc, char **argv) { (void)argv; (void)argc; gpio_clear(HIL_TEST_GPIO); return 0; } int cmd_gpio_set(int argc, char **argv) { (void)argv; (void)argc; gpio_set(HIL_TEST_GPIO); return 0; } static const shell_command_t shell_commands[] = { { "overhead_gpio", "Benchmark the gpio toggling overhead", overhead_gpio_cmd }, { "overhead_timer_now", "timer now overhead", overhead_timer_now }, { "overhead_timer", "timer set/remove overhead", timer_overhead_timer_cmd }, { "overhead_timer_list", "timer nth list overhead", timer_overhead_nth_timer_cmd }, { "sleep_accuracy_timer_sleep", "Sleep for specified time", sleep_accuracy_timer_sleep_cmd }, { "sleep_accuracy_timer_set", "Sleep for specified time", sleep_accuracy_timer_set_cmd }, { "sleep_jitter", "sleep jitter", sleep_jitter_cmd }, { "drift", "Drift Simple benchmark", drift_cmd }, { "get_metadata", "Get the metadata of the test firmware", cmd_get_metadata }, { "get_timer_version", "Get timer version", cmd_get_timer_version }, { "gclear", "clear", cmd_gpio_clear }, { "gset", "set", cmd_gpio_set }, { NULL, NULL, NULL } }; int main(void) { (void)puts("Welcome to RIOT!"); gpio_init(HIL_TEST_GPIO, GPIO_OUT); /* clear initial state */ gpio_clear(HIL_TEST_GPIO); random_init(0); char line_buf[SHELL_DEFAULT_BUFSIZE]; shell_run(shell_commands, line_buf, SHELL_DEFAULT_BUFSIZE); return 0; }
16,176
C
.c
516
26.02907
82
0.599833
RIOT-OS/RobotFW-tests
3
13
16
LGPL-2.1
9/7/2024, 2:15:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,579,006
main.c
RIOT-OS_RobotFW-tests/tests/periph_gpio/main.c
/* * Copyright (C) 2019 HAW Hamburg * * This file is subject to the terms and conditions of the GNU Lesser General * Public License v2.1. See the file LICENSE in the top level directory for more * details. */ /** * @ingroup tests * @{ * * @file * @brief Test application for GPIO peripheral drivers * * @author Kevin Weiss <[email protected]> * * @} */ #include <stdio.h> #include <stdlib.h> #include "shell.h" #include "periph/gpio.h" static int set(int argc, char **argv) { if (argc < 3) { printf("usage: %s <port> <pin>\n", argv[0]); return 1; } gpio_init(GPIO_PIN(atoi(argv[1]), atoi(argv[2])), GPIO_OUT); gpio_set(GPIO_PIN(atoi(argv[1]), atoi(argv[2]))); printf("Success: Pin set\n"); return 0; } static int clear(int argc, char **argv) { if (argc < 3) { printf("usage: %s <port> <pin>\n", argv[0]); return 1; } gpio_init(GPIO_PIN(atoi(argv[1]), atoi(argv[2])), GPIO_OUT); gpio_clear(GPIO_PIN(atoi(argv[1]), atoi(argv[2]))); printf("Success: Pin cleared\n"); return 0; } int cmd_get_metadata(int argc, char **argv) { (void)argv; (void)argc; printf("Success: [%s, %s]\n", RIOT_BOARD, RIOT_APPLICATION); return 0; } int cmd_lock(int argc, char **argv) { (void)argv; (void)argc; while(1); return 0; } static const shell_command_t shell_commands[] = { { "gpio_set", "set pin to HIGH", set }, { "gpio_clear", "set pin to LOW", clear }, { "get_metadata", "Get the metadata of the test firmware", cmd_get_metadata }, { "lock", "Lock the device", cmd_lock}, { NULL, NULL, NULL } }; int main(void) { /* start the shell */ char line_buf[SHELL_DEFAULT_BUFSIZE]; shell_run(shell_commands, line_buf, SHELL_DEFAULT_BUFSIZE); return 0; }
1,831
C
.c
72
21.958333
82
0.620057
RIOT-OS/RobotFW-tests
3
13
16
LGPL-2.1
9/7/2024, 2:15:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,579,009
main.c
RIOT-OS_RobotFW-tests/tests/periph_timer/main.c
/* * Copyright (C) 2019 HAW Hamburg * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup tests * @{ * * @file * @brief Test application for periph timer API * * @author Michel Rottleuthner <[email protected]> * * @} */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <stdbool.h> #include "shell.h" #include "periph/timer.h" #include "periph/gpio.h" #include "mutex.h" #include "sc_args.h" #define ARG_ERROR (-1) #define CONVERT_ERROR (-32768) #define RESULT_OK (0) #define RESULT_ERROR (-1) #define INVALID_ARGS puts("Error: Invalid number of arguments") #define PARSE_ERROR puts("Error: unable to parse arguments") #define CB_TOGGLE_STR "cb_toggle" #define CB_HIGH_STR "cb_high" #define CB_LOW_STR "cb_low" static mutex_t cb_mutex; static gpio_t debug_pins[TIMER_NUMOF]; static inline void _debug_toogle(gpio_t pin) { if (pin != GPIO_UNDEF) { gpio_toggle(pin); } } static inline void _debug_set(gpio_t pin) { if (pin != GPIO_UNDEF) { gpio_set(pin); } } static inline void _debug_clear(gpio_t pin) { if (pin != GPIO_UNDEF) { gpio_clear(pin); } } static int _print_cmd_result(const char *cmd, bool success, int ret, bool print_ret) { printf("%s: %s()", success ? "Success" : "Error", cmd); if (print_ret) { printf(": [%d]", ret); } printf("\n"); return success ? RESULT_OK : RESULT_ERROR; } void cb_toggle(void *arg, int channel) { (void)channel; gpio_t pin = (gpio_t)(intptr_t)arg; _debug_toogle(pin); mutex_unlock(&cb_mutex); } void cb_high(void *arg, int channel) { (void)channel; gpio_t pin = (gpio_t)(intptr_t)arg; _debug_set(pin); mutex_unlock(&cb_mutex); } void cb_low(void *arg, int channel) { (void)channel; gpio_t pin = (gpio_t)(intptr_t)arg; _debug_clear(pin); mutex_unlock(&cb_mutex); } /* API calls */ int cmd_timer_init(int argc, char **argv) { if (sc_args_check(argc, argv, 3, 3, "DEV FREQ CALLBACK") != ARGS_OK) { return ARGS_ERROR; } int dev = sc_arg2dev(argv[1], TIMER_NUMOF); if (dev < 0) { return -ENODEV; } long freq = 0; if (sc_arg2long(argv[2], &freq) != ARGS_OK) { return ARGS_ERROR; } timer_cb_t cb = NULL; if (strncmp(CB_TOGGLE_STR, argv[3], strlen(argv[3])) == 0) { cb = cb_toggle; } else if (strncmp(CB_HIGH_STR, argv[3], strlen(argv[3])) == 0) { cb = cb_high; } else if (strncmp(CB_LOW_STR, argv[3], strlen(argv[3])) == 0) { cb = cb_low; } else { printf("no valid callback name given. Valid values are %s, %s or %s\n", CB_TOGGLE_STR, CB_HIGH_STR, CB_LOW_STR); return ARGS_ERROR; } int res = timer_init(dev, freq, cb, (void*)(intptr_t)debug_pins[dev]); return _print_cmd_result("timer_init", res == 0, res, true); } int _timer_set(int argc, char **argv, bool absolute) { if (sc_args_check(argc, argv, 3, 3, "DEV CHANNEL TICKS") != ARGS_OK) { return ARGS_ERROR; } int dev = sc_arg2dev(argv[1], TIMER_NUMOF); if (dev < 0) { return -ENODEV; } int chan = 0; if (sc_arg2int(argv[2], &chan) != ARGS_OK) { return ARGS_ERROR; } unsigned int timeout = 0; if (sc_arg2uint(argv[3], &timeout) != ARGS_OK) { return ARGS_ERROR; } int res = 0; mutex_lock(&cb_mutex); _debug_toogle(debug_pins[dev]); if (absolute) { res = timer_set_absolute(dev, chan, timeout); } else { res = timer_set(dev, chan, timeout); } /* wait for unlock by cb */ mutex_lock(&cb_mutex); /* reset mutex state */ mutex_unlock(&cb_mutex); return res; } int cmd_timer_set(int argc, char **argv) { int res = _timer_set(argc, argv, false); return _print_cmd_result("timer_set", (res == 0), res, true); } int cmd_timer_set_absolute(int argc, char **argv) { int res = _timer_set(argc, argv, true); return _print_cmd_result("timer_set_absolute", (res == 0), res, true); } int cmd_timer_clear(int argc, char **argv) { if (sc_args_check(argc, argv, 2, 2, "DEV CHANNEL") != ARGS_OK) { return ARGS_ERROR; } int dev = sc_arg2dev(argv[1], TIMER_NUMOF); if (dev < 0) { return -ENODEV; } int chan = 0; if (sc_arg2int(argv[2], &chan) != ARGS_OK) { return ARGS_ERROR; } int res = timer_clear(dev, chan); return _print_cmd_result("timer_clear", (res == 0), res, true); } int cmd_timer_read(int argc, char **argv) { if (sc_args_check(argc, argv, 1, 1, "DEV") != ARGS_OK) { return ARGS_ERROR; } int dev = sc_arg2dev(argv[1], TIMER_NUMOF); if (dev < 0) { return -ENODEV; } printf("Success: timer_read(): [%u]\n", timer_read(dev)); return RESULT_OK; } int cmd_timer_start(int argc, char **argv) { if (sc_args_check(argc, argv, 1, 1, "DEV") != ARGS_OK) { return ARGS_ERROR; } int dev = sc_arg2dev(argv[1], TIMER_NUMOF); if (dev < 0) { return -ENODEV; } timer_start(dev); return _print_cmd_result("timer_start", true, 0, false); } int cmd_timer_stop(int argc, char **argv) { if (sc_args_check(argc, argv, 1, 1, "DEV") != ARGS_OK) { return ARGS_ERROR; } int dev = sc_arg2dev(argv[1], TIMER_NUMOF); if (dev < 0) { return -ENODEV; } timer_stop(dev); return _print_cmd_result("timer_stop", true, 0, false); } /* helper calls (non-API) */ int cmd_timer_debug_pin(int argc, char **argv) { if (sc_args_check(argc, argv, 3, 3, "DEV PORT PIN") != ARGS_OK) { return ARGS_ERROR; } int dev = sc_arg2dev(argv[1], TIMER_NUMOF); if (dev < 0) { return -ENODEV; } /* parse and init debug pin */ uint32_t port, pin = 0; if ((sc_arg2u32(argv[2], &port) != ARGS_OK) || (sc_arg2u32(argv[3], &pin) != ARGS_OK)) { return _print_cmd_result("timer_debug_pin", false, 1, false); } debug_pins[dev] = GPIO_PIN(port, pin); gpio_init(debug_pins[dev], GPIO_OUT); return _print_cmd_result("timer_debug_pin", true, 0, false); } int cmd_timer_bench_read(int argc, char **argv) { if (sc_args_check(argc, argv, 2, 2, "DEV REPEAT") != ARGS_OK) { return ARGS_ERROR; } int dev = sc_arg2dev(argv[1], TIMER_NUMOF); if (dev < 0) { return -ENODEV; } unsigned int repeat = 0; if (sc_arg2uint(argv[2], &repeat) != ARGS_OK) { return ARGS_ERROR; } _debug_toogle(debug_pins[dev]); for (unsigned int i = 0; i < repeat; i++) { timer_read(dev); } _debug_toogle(debug_pins[dev]); return _print_cmd_result("cmd_timer_read_bench", true, 0, false); } int cmd_get_metadata(int argc, char **argv) { (void)argv; (void)argc; printf("Success: [%s, %s]\n", RIOT_BOARD, RIOT_APPLICATION); return 0; } static const shell_command_t shell_commands[] = { { "timer_init", "Initialize timer device", cmd_timer_init }, { "timer_set", "set timer to relative value", cmd_timer_set }, { "timer_set_absolute", "set timer to absolute value", cmd_timer_set_absolute }, { "timer_clear", "clear timer", cmd_timer_clear }, { "timer_read", "read timer", cmd_timer_read }, { "timer_start", "start timer", cmd_timer_start }, { "timer_stop", "stop timer", cmd_timer_stop }, { "timer_debug_pin", "config debug pin", cmd_timer_debug_pin }, { "timer_read_bench", "execute multiple reads to determine overhead", cmd_timer_bench_read }, { "get_metadata", "Get the metadata of the test firmware", cmd_get_metadata }, { NULL, NULL, NULL } }; int main(void) { puts("Start: Test for the timer API"); /* set all debug pins to undef */ for (unsigned i = 0; i < TIMER_NUMOF; ++i) { debug_pins[i] = GPIO_UNDEF; } char line_buf[SHELL_DEFAULT_BUFSIZE]; shell_run(shell_commands, line_buf, SHELL_DEFAULT_BUFSIZE); return 0; }
8,247
C
.c
288
24.083333
79
0.6
RIOT-OS/RobotFW-tests
3
13
16
LGPL-2.1
9/7/2024, 2:15:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,579,012
main.c
RIOT-OS_RobotFW-tests/tests/periph_i2c/main.c
/* * Copyright (C) 2014 Freie Universit√§t Berlin * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup tests * @{ * * @file * @brief Test application for the low-level I2C peripheral driver * * @author Hauke Petersen <[email protected]> * @author Kevin Weiss <[email protected]> * * @} */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include "periph_conf.h" #include "periph/i2c.h" #include "shell.h" #include "sc_args.h" #ifndef I2C_ACK #define I2C_ACK (0) #endif #define BUFSIZE (128U) /* i2c_buf is global to reduce stack memory consumtion */ static uint8_t i2c_buf[BUFSIZE]; static inline void _print_i2c_read(i2c_t dev, uint16_t *reg, uint8_t *buf, int len) { printf("Success: i2c_%i read %i byte(s) ", dev, len); if (reg != NULL) { printf("from reg 0x%02x ", *reg); } printf(": ["); for (int i = 0; i < len; i++) { if (i != 0) { printf(", "); } printf("0x%02x", buf[i]); } printf("]\n"); } static int _print_i2c_error(int res) { if (res == -EOPNOTSUPP) { printf("Error: EOPNOTSUPP [%d]\n", -res); return 1; } else if (res == -EINVAL) { printf("Error: EINVAL [%d]\n", -res); return 1; } else if (res == -EAGAIN) { printf("Error: EAGAIN [%d]\n", -res); return 1; } else if (res == -ENXIO) { printf("Error: ENXIO [%d]\n", -res); return 1; } else if (res == -EIO) { printf("Error: EIO [%d]\n", -res); return 1; } else if (res == -ETIMEDOUT) { printf("Error: ETIMEDOUT [%d]\n", -res); return 1; } else if (res == I2C_ACK) { printf("Success: I2C_ACK [%d]\n", res); return 0; } printf("Error: Unknown error [%d]\n", res); return 1; } int cmd_i2c_acquire(int argc, char **argv) { int res = sc_args_check(argc, argv, 1, 1, "DEV"); if (res != ARGS_OK) { return 1; } int dev = sc_arg2dev(argv[1], I2C_NUMOF); if (dev < 0) { return -ENODEV; } printf("Command: i2c_acquire(%i)\n", dev); i2c_acquire(dev); printf("Success: i2c_%i acquired\n", dev); return 0; } int cmd_i2c_release(int argc, char **argv) { int res = sc_args_check(argc, argv, 1, 1, "DEV"); if (res != ARGS_OK) { return 1; } int dev = sc_arg2dev(argv[1], I2C_NUMOF); if (dev < 0) { return -ENODEV; } printf("Command: i2c_release(%i)\n", dev); i2c_release(dev); printf("Success: i2c_%i released\n", dev); return 0; } int cmd_i2c_read_reg(int argc, char **argv) { int res = sc_args_check(argc, argv, 4, 4, "DEV ADDR REG FLAG"); if (res != ARGS_OK) { return 1; } int dev = sc_arg2dev(argv[1], I2C_NUMOF); if (dev < 0) { return -ENODEV; } uint16_t addr = 0; uint16_t reg = 0; uint8_t flags = 0; if (sc_arg2u16(argv[2], &addr) != ARGS_OK || sc_arg2u16(argv[3], &reg) != ARGS_OK || sc_arg2u8(argv[4], &flags) != ARGS_OK) { return 1; } printf("Command: i2c_read_reg(%i, 0x%02x, 0x%02x, 0x%02x)\n", dev, addr, reg, flags); uint8_t data; res = i2c_read_reg(dev, addr, reg, &data, flags); if (res == I2C_ACK) { _print_i2c_read(dev, &reg, &data, 1); return 0; } return _print_i2c_error(res); } int cmd_i2c_read_regs(int argc, char **argv) { int res = sc_args_check(argc, argv, 5, 5, "DEV ADDR REG LEN FLAG"); if (res != ARGS_OK) { return 1; } int dev = sc_arg2dev(argv[1], I2C_NUMOF); if (dev < 0) { return -ENODEV; } uint16_t addr = 0; uint16_t reg = 0; int len = 0; uint8_t flags = 0; if (sc_arg2u16(argv[2], &addr) != ARGS_OK || sc_arg2u16(argv[3], &reg) != ARGS_OK || sc_arg2int(argv[4], &len) != ARGS_OK || sc_arg2u8(argv[5], &flags) != ARGS_OK) { return 1; } if (len < 1 || len > (int)BUFSIZE) { puts("Error: invalid LENGTH parameter given"); return 1; } else { printf("Command: i2c_read_regs(%i, 0x%02x, 0x%02x, %i, 0x%02x)\n", dev, addr, reg, len, flags); res = i2c_read_regs(dev, addr, reg, i2c_buf, len, flags); } if (res == I2C_ACK) { _print_i2c_read(dev, &reg, i2c_buf, len); return 0; } return _print_i2c_error(res); } int cmd_i2c_read_byte(int argc, char **argv) { int res = sc_args_check(argc, argv, 3, 3, "DEV ADDR FLAG"); if (res != ARGS_OK) { return 1; } int dev = sc_arg2dev(argv[1], I2C_NUMOF); if (dev < 0) { return -ENODEV; } uint16_t addr = 0; uint8_t flags = 0; if (sc_arg2u16(argv[2], &addr) != ARGS_OK || sc_arg2u8(argv[3], &flags) != ARGS_OK) { return 1; } printf("Command: i2c_read_byte(%i, 0x%02x, 0x%02x)\n", dev, addr, flags); uint8_t data; res = i2c_read_byte(dev, addr, &data, flags); if (res == I2C_ACK) { _print_i2c_read(dev, NULL, &data, 1); return 0; } return _print_i2c_error(res); } int cmd_i2c_read_bytes(int argc, char **argv) { int res = sc_args_check(argc, argv, 4, 4, "DEV ADDR LENGTH FLAG"); if (res != ARGS_OK) { return 1; } int dev = sc_arg2dev(argv[1], I2C_NUMOF); if (dev < 0) { return -ENODEV; } uint16_t addr = 0; int len = 0; uint8_t flags = 0; if (sc_arg2u16(argv[2], &addr) != ARGS_OK || sc_arg2int(argv[3], &len) != ARGS_OK || sc_arg2u8(argv[4], &flags) != ARGS_OK) { return 1; } if (len < 1 || len > (int)BUFSIZE) { puts("Error: invalid LENGTH parameter given"); return 1; } else { printf("Command: i2c_read_bytes(%i, 0x%02x, %i, 0x%02x)\n", dev, addr, len, flags); res = i2c_read_bytes(dev, addr, i2c_buf, len, flags); } if (res == I2C_ACK) { _print_i2c_read(dev, NULL, i2c_buf, len); return 0; } return _print_i2c_error(res); } int cmd_i2c_write_byte(int argc, char **argv) { int res = sc_args_check(argc, argv, 4, 4, "DEV ADDR BYTE FLAG"); if (res != ARGS_OK) { return 1; } int dev = sc_arg2dev(argv[1], I2C_NUMOF); if (dev < 0) { return -ENODEV; } uint16_t addr = 0; uint8_t data = 0; uint8_t flags = 0; if (sc_arg2u16(argv[2], &addr) != ARGS_OK || sc_arg2u8(argv[3], &data) != ARGS_OK || sc_arg2u8(argv[4], &flags) != ARGS_OK) { return 1; } printf("Command: i2c_write_byte(%i, 0x%02x, 0x%02x, [0x%02x", dev, addr, flags, data); puts("])"); res = i2c_write_byte(dev, addr, data, flags); if (res == I2C_ACK) { printf("Success: i2c_%i wrote 1 byte to the bus\n", dev); return 0; } return _print_i2c_error(res); } int cmd_i2c_write_bytes(int argc, char **argv) { int res = sc_args_check(argc, argv, 4, 3 + BUFSIZE, "DEV ADDR FLAG BYTE0 [BYTE1 [BYTE_n [...]]]"); if (res != ARGS_OK) { return 1; } int dev = sc_arg2dev(argv[1], I2C_NUMOF); if (dev < 0) { return -ENODEV; } uint16_t addr = 0;; uint8_t flags = 0; if (sc_arg2u16(argv[2], &addr) != ARGS_OK || sc_arg2u8(argv[3], &flags) != ARGS_OK) { return 1; } int len = argc - 4; for (int i = 0; i < len; i++) { if (sc_arg2u8(argv[i + 4], &i2c_buf[i]) != ARGS_OK) { return 1; } } printf("Command: i2c_write_bytes(%i, 0x%02x, 0x%02x, [", dev, addr, flags); for (int i = 0; i < (argc - 4); i++) { if (i != 0) { printf(", "); } printf("0x%02x", i2c_buf[i]); } puts("])"); res = i2c_write_bytes(dev, addr, i2c_buf, len, flags); if (res == I2C_ACK) { printf("Success: i2c_%i wrote %i bytes\n", dev, len); return 0; } return _print_i2c_error(res); } int cmd_i2c_write_reg(int argc, char **argv) { int res = sc_args_check(argc, argv, 5, 5, "DEV ADDR REG BYTE FLAG"); if (res != ARGS_OK) { return 1; } int dev = sc_arg2dev(argv[1], I2C_NUMOF); if (dev < 0) { return -ENODEV; } uint16_t addr = 0; uint16_t reg = 0; uint8_t data = 0; uint8_t flags = 0; if (sc_arg2u16(argv[2], &addr) != ARGS_OK || sc_arg2u16(argv[3], &reg) != ARGS_OK || sc_arg2u8(argv[4], &data) != ARGS_OK || sc_arg2u8(argv[5], &flags) != ARGS_OK) { return 1; } printf("Command: i2c_write_reg(%i, 0x%02x, 0x%02x, 0x%02x, [0x%02x", dev, addr, reg, flags, data); puts("])"); res = i2c_write_reg(dev, addr, reg, data, flags); if (res == I2C_ACK) { printf("Success: i2c_%i wrote 1 byte\n", dev); return 0; } return _print_i2c_error(res); } int cmd_i2c_write_regs(int argc, char **argv) { int res = sc_args_check(argc, argv, 5, 4 + BUFSIZE, "DEV ADDR REG FLAG BYTE0 [BYTE1 ...]"); if (res != ARGS_OK) { return 1; } int dev = sc_arg2dev(argv[1], I2C_NUMOF); if (dev < 0) { return -ENODEV; } uint16_t addr = 0; uint16_t reg = 0; uint8_t flags = 0; if (sc_arg2u16(argv[2], &addr) != ARGS_OK || sc_arg2u16(argv[3], &reg) != ARGS_OK || sc_arg2u8(argv[4], &flags) != ARGS_OK) { return 1; } int len = argc - 5; for (int i = 0; i < len; i++) { if (sc_arg2u8(argv[i + 5], &i2c_buf[i]) != ARGS_OK) { return 1; } } printf("Command: i2c_write_regs(%i, 0x%02x, 0x%02x, 0x%02x, [", dev, addr, reg, flags); for (int i = 0; i < len; i++) { if (i != 0) { printf(", "); } printf("0x%02x", i2c_buf[i]); } puts("])"); res = i2c_write_regs(dev, addr, reg, i2c_buf, len, flags); if (res == I2C_ACK) { printf("Success: i2c_%i wrote %i bytes to reg 0x%02x\n", dev, len, reg); return 0; } return _print_i2c_error(res); } int cmd_i2c_get_devs(int argc, char **argv) { (void)argv; (void)argc; printf("Command: return I2C_NUMOF\n"); printf("Success: Amount of i2c devices: [%d]\n", I2C_NUMOF); return 0; } int cmd_get_metadata(int argc, char **argv) { (void)argv; (void)argc; printf("Success: [%s, %s]\n", RIOT_BOARD, RIOT_APPLICATION); return 0; } static const shell_command_t shell_commands[] = { { "i2c_acquire", "Get access to the I2C bus", cmd_i2c_acquire }, { "i2c_release", "Release to the I2C bus", cmd_i2c_release }, { "i2c_read_reg", "Read byte from register", cmd_i2c_read_reg }, { "i2c_read_regs", "Read bytes from registers", cmd_i2c_read_regs }, { "i2c_read_byte", "Read byte from the I2C device", cmd_i2c_read_byte }, { "i2c_read_bytes", "Read bytes from the I2C device", cmd_i2c_read_bytes }, { "i2c_write_byte", "Write byte to the I2C device", cmd_i2c_write_byte }, { "i2c_write_bytes", "Write bytes to the I2C device", cmd_i2c_write_bytes }, { "i2c_write_reg", "Write byte to register", cmd_i2c_write_reg }, { "i2c_write_regs", "Write bytes to registers", cmd_i2c_write_regs }, { "i2c_get_devs", "Gets amount of supported i2c devices", cmd_i2c_get_devs }, { "get_metadata", "Get the metadata of the test firmware", cmd_get_metadata }, { NULL, NULL, NULL } }; int main(void) { puts("Start: Test for the low-level I2C driver"); char line_buf[SHELL_DEFAULT_BUFSIZE]; shell_run(shell_commands, line_buf, SHELL_DEFAULT_BUFSIZE); return 0; }
11,825
C
.c
405
23.520988
95
0.544902
RIOT-OS/RobotFW-tests
3
13
16
LGPL-2.1
9/7/2024, 2:15:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,579,040
test_helpers.h
RIOT-OS_RobotFW-tests/utils/test_helpers/include/test_helpers.h
/* * Copyright (C) 2019 HAW Hamburg * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup tests * @{ * * @file * @brief Test helpers for writing tests with standard interfaces. * * @author Kevin Weiss <[email protected]> * * @} */ #include "shell.h" #ifndef TEST_HELPERS_H #define TEST_HELPERS_H #ifdef JSON_SHELL_PARSER /** * @name JSON_SHELL_PARSER states * * Used to control the state of writing json formatted message. * @{ */ #define JSON_STATE_READY 0 #define JSON_STATE_STARTED 0x01 #define JSON_STATE_DATA_STARTED 0x02 /** @} */ /** * @brief The number of json shell parsed in case using multiple threads * @{ */ #ifndef NUM_OF_JSON_SHELL_PARSER #define NUM_OF_JSON_SHELL_PARSER 1 #endif /** @} */ /** * @brief The version of parser being used */ #define APP_SHELL_FMT "JSON_SHELL_PARSER_v0.0.0" #endif /* JSON_SHELL_PARSER */ /** * @name TEST_RESULT standard states * * The proper message to send when things succeed or fail. * @{ */ #define TEST_RESULT_SUCCESS "Success" #define TEST_RESULT_ERROR "Error" /** @} */ /** * @brief Prints the command that was issued to the console * * The exact output depends on the parser but it will contain information on * the command. * * @param[in] dev parsing instance * @param[in] cmd string of the command */ void print_cmd(int dev, char *cmd); /** * @brief Prints a key value where the value is a string to the console * * The exact output depends on the parser but it will contain information on * both the key and value. * * @param[in] dev parsing instance * @param[in] key string of the key * @param[in] val string of the value */ void print_data_dict_str(int dev, char *key, char *val); /** * @brief Prints a int to the console * * The exact output depends on the parser but it will contain information on * the integer. * * @param[in] dev parsing instance * @param[in] data the integer data */ void print_data_int(int dev, int32_t data); /** * @brief Prints a string to the console * * The exact output depends on the parser but it will contain information on * the string. * * @param[in] dev parsing instance * @param[in] str the string data */ void print_data_str(int dev, char *str); /** * @brief Prints a result to the console * * The exact output depends on the parser but it will contain information on * the string. * * @note This must be used for some parsers to indicate end of command * * @param[in] dev parsing instance * @param[in] res the TEST_RESULT string if SUCCESS or ERROR */ void print_result(int dev, char *res); #endif /* TEST_HELPERS_H */
2,835
C
.h
108
24.435185
76
0.694066
RIOT-OS/RobotFW-tests
3
13
16
LGPL-2.1
9/7/2024, 2:15:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,619,318
xt_SPOOFTCP.h
hippocampi_netfilter-spooftcp/xt_SPOOFTCP.h
#ifndef _XT_SPOOFTCP_TARGET_H #define _XT_SPOOFTCP_TARGET_H #include <linux/types.h> struct xt_spooftcp_info { __u8 ttl; __u8 tcp_flags; __u8 corrupt_chksum; __u8 corrupt_seq; __u8 delay; __u8 payload_len; __u8 md5; __u8 ts; __u8 masq; }; /* MD5 option */ #define OPT_MD5_KIND 19 #define OPT_MD5_SIZE 18 /* TS option */ #define OPT_TS_KIND 8 #define OPT_TS_SIZE 10 #endif /* _XT_SPOOFTCP_TARGET_H */
441
C
.h
21
18.047619
34
0.645783
hippocampi/netfilter-spooftcp
3
24
0
GPL-2.0
9/7/2024, 2:15:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,653,635
External.h
fengjixuchui_ScyllaHideDetector/ScyllaHideDetector/MemoryMaster/External.h
#pragma once namespace MemoryMaster { namespace External { class Injector { public: static InjectStatus InjectDLL(const char* dll, const char* processName); static InjectStatus InjectDLL(const char* dll, DWORD pid); }; } }
241
C
.h
13
16.153846
75
0.762115
fengjixuchui/ScyllaHideDetector
3
12
0
GPL-3.0
9/7/2024, 2:16:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,713,567
prrn.c
power-ras_ppc64-diag/rtas_errd/prrn.c
/** * @file prrn.c * * Copyright (C) IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <ctype.h> #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> #include <time.h> #include <librtas.h> #include "rtas_errd.h" struct pmap_struct { struct pmap_struct *next; /* The fields below are stored in host endian */ uint32_t phandle; uint32_t drc_index; char *name; }; struct drconf_cell { uint64_t base_addr; uint32_t drc_index; uint32_t reserved; uint32_t aa_index; uint32_t flags; }; static struct pmap_struct *plist; static int prrn_log_fd; static char prrn_filename[128]; #define OFDT_BASE "/proc/device-tree" #define OFDTPATH "/proc/ppc64/ofdt" #define DRCONF_PATH "/proc/device-tree/ibm,dynamic-reconfiguration-memory/ibm,dynamic-memory" static int write_prrn_log(const char *buf, int len) { if (prrn_log_fd) return write(prrn_log_fd, buf, len); return -1; } static void open_prrn_log(void) { /* This file will be deleted by drmgr */ snprintf(prrn_filename, 128, "/var/log/prrn_log_%d", (int)time(0)); prrn_log_fd = open(prrn_filename, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR); if (prrn_log_fd == -1) { prrn_log_fd = 0; dbg("Could not open PRRN log file"); return; } } static void close_prrn_log(void) { if (prrn_log_fd) close(prrn_log_fd); } uint32_t get_drc_index(const char *path) { char drc_path[256]; FILE *fp; uint32_t drc_index; int rc; sprintf(drc_path, "%s/%s", path, "ibm,my-drc-index"); fp = fopen(drc_path, "r"); if (!fp) return 0; rc = fread(&drc_index, sizeof(drc_index), 1, fp); if (rc != 1) drc_index = 0; fclose(fp); return be32toh(drc_index); } /** * add_phandle_to_list * * @param name * @param phandle */ static void add_phandle_to_list(char *name, uint32_t phandle, uint32_t drc_index) { struct pmap_struct *pm; pm = calloc(1, sizeof(struct pmap_struct)); if (!pm) return; pm->name = malloc(strlen(name) + 1); if (!pm->name) { free(pm); return; } sprintf(pm->name, "%s", name); pm->phandle = phandle; pm->drc_index = drc_index; pm->next = plist; plist = pm; } /** * phandle_to_name * * @param ph * @returns */ static struct pmap_struct *phandle_to_pms(uint32_t phandle) { struct pmap_struct *pms = plist; while (pms && pms->phandle != phandle) pms = pms->next; return pms; } /** * add_std_phandles * * @param parent * @param p * @returns */ static int add_std_phandles(char *parent, char *p) { DIR *d; struct dirent *de; char path[PATH_MAX]; uint32_t phandle; char *pend; FILE *fd; strncpy(path, parent, PATH_MAX - 1); path[PATH_MAX - 1] = '\0'; if (p) { strcat(path, "/"); strncat(path, p, sizeof(path) - strlen(path) - 1); } pend = path + strlen(path); d = opendir(path); if (!d) { perror(path); return -1; } while ((de = readdir(d))) { if ((de->d_type == DT_DIR) && (strcmp(de->d_name, ".")) && (strcmp(de->d_name, ".."))) add_std_phandles(path, de->d_name); } strcpy(pend, "/ibm,phandle"); fd = fopen(path, "r"); if (fd) { uint32_t drc_index; if (fread(&phandle, sizeof(phandle), 1, fd) != 1) { dbg("Error reading phandle data!"); closedir(d); fclose(fd); return -1; } *pend = '\0'; drc_index = get_drc_index(path); add_phandle_to_list(path + strlen(OFDT_BASE), be32toh(phandle), drc_index); fclose(fd); } closedir(d); return 0; } /** * add_drconf_phandles * * @returns */ static int add_drconf_phandles() { FILE *fd; int *membuf; int i, rc, entries; struct stat sbuf; struct drconf_cell *mem; /* For PRRN Events the LMBs in dynamic-reconfiguration-memory that * will get updated have their drc-index reported instead of the * phandle in the list of phandles to update reported by * rtas_update_nodes(). So we need to build a list of the possible * LMBs. */ rc = stat(DRCONF_PATH, &sbuf); if (rc) return 0; fd = fopen(DRCONF_PATH, "r"); if (!fd) { /* This is fine, older systems don't have this property */ return 0; } membuf = malloc(sbuf.st_size); if (!membuf) { fclose(fd); return -1; } if ((fread(membuf, sbuf.st_size, 1, fd) < sbuf.st_size) && ferror(fd)) { fclose(fd); free(membuf); return -1; } fclose(fd); entries = be32toh(membuf[0]); mem = (struct drconf_cell *)&membuf[1]; for (i = 0; i < entries; i++) { /* See comment above about rtas reporting drc_indexes. */ add_phandle_to_list("LMB", be32toh(mem->drc_index), be32toh(mem->drc_index)); mem++; /* trust your compiler */ } free(membuf); return 0; } /** * free_phandles * */ static void free_phandles() { struct pmap_struct *pm; while (plist) { pm = plist; plist = plist->next; free(pm->name); free(pm); } } /** * add_phandles * * @returns */ static int add_phandles() { int rc; rc = add_std_phandles(OFDT_BASE, NULL); if (rc) { free_phandles(); return rc; } rc = add_drconf_phandles(); if (rc) free_phandles(); return rc; } /** * do_update * * @param cmd * @param len * @returns 0 on success, !0 otherwise */ static int do_update(char *cmd, int len) { int rc; int i, fd; fd = open(OFDTPATH, O_WRONLY); if (fd < 0) { dbg("Failed to open %s: %s", OFDTPATH, strerror(errno)); rc = errno; return rc; } if ((rc = write(fd, cmd, len)) != len) dbg("Error writing to ofdt file! rc %d errno %d", rc, errno); close(fd); /* The reamining code only formats the cmd buffer to make it * human readable when printed via dbg(). */ for (i = 0; i < len; i++) { if (!isprint(cmd[i])) cmd[i] = '.'; if (isspace(cmd[i])) cmd[i] = ' '; } cmd[len-1] = 0x00; dbg("<%s>", cmd); return rc; } /** * update_properties * * @param phandle * @returns 0 on success, !0 otherwise */ static int update_properties(uint32_t phandle) { int rc; char cmd[1024]; char *longcmd = NULL; char *newcmd; int cmdlen = 0; int proplen = 0; unsigned int wa[1024]; unsigned int *op; unsigned int nprop; unsigned int vd; int lenpos = 0; char *pname; unsigned int i; int more = 0; struct pmap_struct *pms = phandle_to_pms(phandle); /* * First call to the udpate-properties call, expects the following : * [phandle (4bytes)] * [ 0x0 (4bytes) ] - Indicates the first call for the phandle * [ 0x0 (8bytes) ] - Reserved */ memset(wa, 0x00, 16); wa[0] = htobe32(phandle); do { dbg("about to call rtas_update_properties.\nphandle: %8.8x," " node: %s\nwork area: %8.8x %8.8x %8.8x %8.8x", phandle, pms->name, wa[0], wa[1], wa[2], wa[3]); rc = rtas_update_properties((char *)wa, 1); if (rc && rc != 1) { dbg("Error %d from rtas_update_properties()", rc); return 1; } dbg("successful rtas_update_properties (more %d)", rc); op = wa+4; nprop = be32toh(*op++); /* Should just be on property to update, the affinity. Except * for reconfig memory, that is a single property for * all possible LMBs on the system. */ /* Layout of the workarea returned from rtas, see PAPR for * detailed explanation: * u32 phandle of node * u32 state variable * u64 reserved * u32 number of updated properties * null terminated property name * vd - u32 len of property * actual property */ for (i = 0; i < nprop; i++) { pname = (char *)op; op = (unsigned int *)(pname + strlen(pname) + 1); vd = be32toh(*op++); switch (vd) { case 0x00000000: dbg("%s - name only property %s", pms->name, pname); break; case 0x80000000: dbg("%s - delete property %s", pms->name, pname); sprintf(cmd,"remove_property %u %s", phandle, pname); do_update(cmd, strlen(cmd)); break; default: /* * A negative value indicates incomplete property * and requires one or more followup calls to read * completely. The current length of the data is the * 2's complement of the value. */ if (vd & 0x80000000) { dbg("partial property!"); /* twos compliment of length */ vd = ~vd + 1; more = 1; } else { more = 0; } dbg("%s - updating property %s length %d", pms->name, pname, vd); /* See if we have a partially completed * command */ if (longcmd) { newcmd = malloc(cmdlen + vd); if (!newcmd) { free(longcmd); return -1; } memcpy(newcmd, longcmd, cmdlen); free(longcmd); longcmd = newcmd; } else { longcmd = malloc(vd+128); if (!longcmd) return -1; /* Build the command with a length * of six zeros */ lenpos = sprintf(longcmd, "update_property %u " "%s ", phandle, pname); strcat(longcmd, "000000 "); cmdlen = strlen(longcmd); } memcpy(longcmd + cmdlen, op, vd); cmdlen += vd; proplen += vd; if (!more) { /* Now update the length to its actual * value and do a hideous fixup of * the new trailing null */ sprintf(longcmd+lenpos,"%06d",proplen); longcmd[lenpos+6] = ' '; do_update(longcmd, cmdlen); free(longcmd); longcmd = NULL; cmdlen = 0; proplen = 0; } op = (unsigned int *)(((char *)op) + vd); } } } while (rc == 1); return 0; } /** * do_node_update * * Not all nodes can be updated via a DLPAR operation, only those with * a valid drc-index. For nodes without a drc-index we just update the * prrn log file indicating that the node was updated in te device tree * but that we cannot do a DLPAR operation. * @param type * @param pms */ static void do_node_update(struct pmap_struct *pms, const char *type) { char buf[128]; int len; if (pms->drc_index != 0) { len = sprintf(buf, "%s %x\n", type, pms->drc_index); write_prrn_log(buf, len); } dbg("Updating property for %s (%08x)", pms->name, pms->phandle); update_properties(pms->phandle); } /** * update_nodes * * @param op * @param n */ static void update_nodes(unsigned int *op, unsigned int n) { int i, len; uint32_t phandle; char buf[128]; struct pmap_struct *pms; for (i = 0; i < n; i++) { phandle = be32toh(*op++); dbg("Updating node with phandle %08x", phandle); pms = phandle_to_pms(phandle); if (!pms) continue; if (!strcmp(pms->name, "LMB")) { len = sprintf(buf, "mem %x\n", pms->drc_index); write_prrn_log(buf, len); } else if (!strncmp(pms->name, "/memory@", 8)) { do_node_update(pms, "mem"); } else { do_node_update(pms, "cpu"); } } } /** * devtree_update * */ static void devtree_update(uint scope) { int rc; unsigned int wa[1024]; unsigned int *op; dbg("Updating device_tree"); if (add_phandles()) return; /* First 16 bytes of work area must be initialized to zero */ memset(wa, 0x00, 16); do { rc = rtas_update_nodes((char *)wa, -scope); if (rc && rc != 1) { dbg("Error %d from rtas_update_nodes()", rc); break; } op = wa+4; /* * The o/p buffer has the following format. * Operation - 1 byte * Number of operands(N) - 3bytes * Operand_1, Operand_2, ... Operand_N - 4bytes each */ while (*(char *)op) { unsigned int n = be32toh(*op) & 0x0FFFFFF; switch (*(char *)op) { case 0x01: dbg("Received unsupported node deletion " "request, trying to continue"); break; case 0x02: update_nodes(op+1, n); break; case 0x03: dbg("Received unsupported node addition " "request, trying to continue"); break; default: dbg("Unknown update_nodes op %8.8x", *(char *)op); } op += 1 + n; } } while (rc == 1); free_phandles(); dbg("Finished devtree update"); } void handle_prrn_event(struct event *re) { pid_t pid; uint scope = re->rtas_hdr->ext_log_length; open_prrn_log(); if (!prrn_log_fd) return; devtree_update(scope); close_prrn_log(); /* Kick off script to do required hotplug add/remove */ pid = fork(); if (pid == -1) { unlink(prrn_filename); dbg("Could not exec drmgr PRRN handler.\n"); return; } if (pid == 0) { /* Child */ dbg("Executing drmgr prrn handler.\n"); execl("/usr/sbin/drmgr", "/usr/sbin/drmgr", "-P", prrn_filename, NULL); unlink(prrn_filename); /* Should not get here */ dbg("Failed PRRN Hotplug exec: %s", strerror(errno)); exit(0); } /* Nothing to do for the parent, just return */ }
13,120
C
.c
557
20.48474
93
0.640067
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,568
extract_platdump.c
power-ras_ppc64-diag/rtas_errd/extract_platdump.c
/** * @file extract_platdump.c * @brief Command to extract a platform dump and copy it to the filesystem * * Copyright (C) 2007 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <getopt.h> #include <stdarg.h> #include <fcntl.h> #include <errno.h> #include <dirent.h> #include <stdint.h> #include <librtas.h> #include <sys/stat.h> #include "rtas_errd.h" #include "platform.h" #define DUMP_HDR_PREFIX_OFFSET 0x16 /* prefix size in dump header */ #define DUMP_HDR_FNAME_OFFSET 0x18 /* suggested filename in dump header */ #define DUMP_MAX_FNAME_LEN 40 #define TOKEN_PLATDUMP_MAXSIZE 32 #define DUMP_BUF_SZ 4096 int flag_v = 0; static struct option long_options[] = { {"help", no_argument, NULL, 'h'}, {"verbose", no_argument, NULL, 'v'}, {0,0,0,0} }; /** * msg * @brief Print message if verbose flag is set * * @param fmt format string a la printf() * @param ... additional args a la printf() */ void msg(char *fmt, ...) { va_list ap; if (flag_v) { va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); } return; } /** * print_usage * @brief Print the usage message for this command * * @param name the name of this executable */ static void print_usage(const char *name) { printf("Usage: %s [-h] [-v] <dump_tag>\n" "\t-h: print this help message\n" "\t-v: verbose output\n" "\t<dump_tag>: the tag of the dump(s) to extract, in hex\n", name); return; } /** * handle_platform_dump_error * @brief Interpret librtas return codes * * Interpret a return code from librtas for any librtas specific messages. * * @param e return code from librtas * @param err_buf buffer to write librtas message to * @param sz size of the err_buf parameter */ static void handle_platform_dump_error(int e, char *err_buf, int sz) { char *err = "Library error during ibm,platform-dump call: "; switch (e) { case RTAS_KERNEL_INT: /* no kernel interface to firmware */ snprintf(err_buf, sz, "%s%s", err, "No kernel interface to firmware"); break; case RTAS_KERNEL_IMP: /* no kernel implementation of function */ snprintf(err_buf, sz, "%s%s", err, "No kernel implementation of function"); break; case RTAS_PERM: /* non-root caller */ snprintf(err_buf, sz, "%s%s", err, "Permission denied (non-root caller)"); break; case RTAS_NO_MEM: /* out of heap memory */ snprintf(err_buf, sz, "%s%s", err, "Out of heap memory"); break; case RTAS_NO_LOWMEM: /* kernel out of low memory */ snprintf(err_buf, sz, "%s%s", err, "Kernel out of low memory"); break; case RTAS_FREE_ERR: /* attempt to free nonexistent rmo buffer */ snprintf(err_buf, sz, "%s%s", err, "Attempt to free nonexistent rmo buffer"); break; case RTAS_IO_ASSERT: /* unexpected I/O error */ snprintf(err_buf, sz, "%s%s", err, "Unexpected I/O error"); break; case RTAS_UNKNOWN_OP: /* no firmware implementation of function */ snprintf(err_buf, sz, "%s%s", err, "No firmware implementation of function"); break; case -1: /* hardware error */ snprintf(err_buf, sz, "%s%s", err, "RTAS call returned a hardware error"); break; case -9002: /* platform has decided to deliver dump elsewhere */ snprintf(err_buf, sz, "%s%s", err, "Not authorized (platform " "will deliver dump elsewhere)"); break; default: snprintf(err_buf, sz, "%sUnknown error (%d)", err, e); break; } } /** * remove_old_dumpfiles * @brief if needed, remove any old dumpfiles * * Users can specify the number of old dumpfiles they wish to save * via the config file PlatformDumpMax entry. This routine will search * through and removeany dump files of the specified type if the count * exceeds the maximum value. * * @param dumpname suggested filename of the platform dump * @param prefix_size length of the prefix */ void remove_old_dumpfiles(char *dumpname, int prefix_size) { struct dirent *entry; DIR *dir; char *pathname = NULL; dir = opendir(d_cfg.platform_dump_path); while ((entry = readdir(dir)) != NULL) { if (strcmp(entry->d_name, "..") == 0) continue; if (strcmp(entry->d_name, ".") == 0) continue; if (strncmp(dumpname, entry->d_name, prefix_size) == 0) { if (asprintf(&pathname, "%s%s", d_cfg.platform_dump_path, entry->d_name) < 0) { msg("%s:%d : Could not allocate memory", __func__, __LINE__); continue; } msg("Deleting file %s", pathname); if (unlink(pathname) < 0) { msg("Could not delete file \"%s\" " "to make room for incoming platform " "dump \"%s\" (%s). The new dump will " "be saved anyways.", pathname, dumpname, strerror(errno)); } free(pathname); } } closedir(dir); } /** * extract_platform_dump * @brief Extract a platform dump with a given tag to the filesystem * * @param dump_tag tag of the platform dump to extract * @return 0 on success, 1 on failure */ int extract_platform_dump(uint64_t dump_tag) { uint64_t seq=0, seq_next, bytes; uint16_t prefix_size = 7; char *dump_buf = NULL; char filename[DUMP_MAX_FNAME_LEN + 1]; char pathname[PATH_MAX]; char dump_err[RTAS_ERROR_LOG_MAX]; char dumpid[5] = ""; int out=-1, rc, librtas_rc, dump_complete=0, ret=0; msg("Dump tag: 0x%016LX", dump_tag); dump_buf = malloc(DUMP_BUF_SZ); if (dump_buf == NULL) { msg("Could not allocate buffer to retrieve dump: %s", strerror(errno)); ret = 1; goto platdump_error_out; } msg("Calling rtas_platform_dump, seq 0x%016LX", seq); librtas_rc = rtas_platform_dump(dump_tag, 0, dump_buf, DUMP_BUF_SZ, &seq_next, &bytes); if (librtas_rc == 0) { dump_complete = 1; } if (librtas_rc < 0) { handle_platform_dump_error(librtas_rc, dump_err, 1024); msg("%s\nThe platform dump header could not be " "retrieved from firmware", dump_err); ret = 1; goto platdump_error_out; } /* If we didn't read enough bytes, handle it */ if (bytes <= 0) { msg("Platform dump with id: 0x%016LX is either invalid " "or empty\n", dump_tag); ret = 1; goto platdump_error_out; } seq = seq_next; /* * Retrieve the prefix size and suggested filename for the dump * from the dump header */ if (bytes >= DUMP_HDR_PREFIX_OFFSET + sizeof(uint16_t)) { prefix_size = *(uint16_t *)(dump_buf + DUMP_HDR_PREFIX_OFFSET); prefix_size = be16toh(prefix_size); } if (bytes >= DUMP_HDR_FNAME_OFFSET + DUMP_MAX_FNAME_LEN) { strncpy(filename, dump_buf + DUMP_HDR_FNAME_OFFSET, DUMP_MAX_FNAME_LEN); } else { strcpy(filename, "dumpid."); strcat(filename, dumpid); } filename[DUMP_MAX_FNAME_LEN - 1] = '\0'; msg("Suggested filename: %s, prefix size: %d", filename, prefix_size); /* Create the platform dump directory if necessary */ if (mkdir(d_cfg.platform_dump_path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) < 0) { if (errno != EEXIST) { msg("Could not create %s: %s.\nThe platform dump " "could not be copied to the platform dump " "directory", d_cfg.platform_dump_path, strerror(errno)); ret = 1; goto platdump_error_out; } } /* Copy the dump off to the filesystem */ pathname[0] = '\0'; strcpy(pathname, d_cfg.platform_dump_path); strcat(pathname, filename); msg("Dump path/filename: %s", pathname); out = creat(pathname, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (out <= 0) { msg("Could not open %s for writing: %s.\nThe platform dump " "could not be retrieved", pathname, strerror(errno)); ret = 1; goto platdump_error_out; } rc = write(out, dump_buf, (size_t)bytes); if (rc < 0) { msg("Could not write to %s: %s.\nThe platform dump " "could not be retrieved", pathname, strerror(errno)); ret = 1; goto platdump_error_out; } while (dump_complete == 0) { msg("Calling rtas_platform_dump, seq 0x%016LX", seq); librtas_rc = rtas_platform_dump(dump_tag, seq, dump_buf, DUMP_BUF_SZ, &seq_next, &bytes); if (librtas_rc < 0) { handle_platform_dump_error(librtas_rc, dump_err, 1024); msg("%s\nThe platform dump could not be " "retrieved from firmware", dump_err); ret = 1; goto platdump_error_out; } if (librtas_rc == 0) { dump_complete = 1; } seq = seq_next; rc = write(out, dump_buf, (size_t)bytes); if (rc < 0) { msg("Could not write to %s: %s\nThe platform " "dump could not be retrieved", pathname, strerror(errno)); ret = 1; goto platdump_error_out; } } /* * Got the dump; signal the platform that it is okay for * them to delete/invalidate their copy */ msg("Sigalling that the dump has been retrieved, seq 0x%016LX", seq); librtas_rc = rtas_platform_dump(dump_tag, seq, NULL, 0, &seq_next, &bytes); if (librtas_rc < 0) { handle_platform_dump_error(librtas_rc, dump_err, 1024); msg("%s\nThe platform could not be notified to " "delete its copy of a platform dump", dump_err); } /* rtas_errd depends on this line being printed */ printf("%s\n", filename); platdump_error_out: if (out != -1) close(out); if (dump_buf != NULL) free(dump_buf); return ret; } int main(int argc, char *argv[]) { int option_index, rc, fail=0; int platform = 0; uint64_t dump_tag; platform = get_platform(); switch (platform) { case PLATFORM_UNKNOWN: case PLATFORM_POWERNV: fprintf(stderr, "%s: is not supported on the %s platform\n", argv[0], __power_platform_name(platform)); return -1; } for (;;) { option_index = 0; rc = getopt_long(argc, argv, "hv", long_options, &option_index); if (rc == -1) break; switch (rc) { case 'h': print_usage(argv[0]); return 0; case 'v': flag_v = 1; break; case '?': print_usage(argv[0]); return -1; break; default: printf("huh?\n"); break; } } if (optind < argc) { /* Parse ppc64-diag config file */ rc = diag_cfg(0, &msg); if (rc) { fprintf(stderr, "Could not parse configuration file " "%s\n", config_file); return -2; } while (optind < argc) { dump_tag = strtoll(argv[optind++], NULL, 16); fail += extract_platform_dump(dump_tag); } } else { fprintf(stderr, "No dump tag specified\n"); print_usage(argv[0]); return -1; } return fail; }
10,924
C
.c
377
26.127321
81
0.672161
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,713,569
hotplug.c
power-ras_ppc64-diag/rtas_errd/hotplug.c
/** * @file hotplug.c * * Copyright (C) 2013 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <sys/wait.h> #include <librtas.h> #include "rtas_errd.h" #define DRMGR_PROGRAM "/usr/sbin/drmgr" #define DRMGR_PROGRAM_NOPATH "drmgr" void handle_hotplug_event(struct event *re) { struct rtas_event_hdr *rtas_hdr = re->rtas_hdr; struct rtas_hotplug_scn *hotplug; pid_t child; int status; char drc_index[11]; char count[4]; char *drmgr_args[] = { DRMGR_PROGRAM_NOPATH, "-c", NULL, NULL, NULL, NULL, NULL, "-d4", "-V", NULL}; /* Retrieve Hotplug section */ if (rtas_hdr->version >= 6) { hotplug = rtas_get_hotplug_scn(re->rtas_event); /* Build drmgr argument list */ dbg("Build drmgr command\n"); switch (hotplug->type) { case RTAS_HP_TYPE_PCI: drmgr_args[2] = "pci"; drmgr_args[6] = "-n"; break; case RTAS_HP_TYPE_CPU: drmgr_args[2] = "cpu"; break; case RTAS_HP_TYPE_MEMORY: drmgr_args[2] = "mem"; break; case RTAS_HP_TYPE_PHB: drmgr_args[2] = "phb"; break; default: dbg("Unknown or unsupported hotplug type %d\n", hotplug->type); return; } switch (hotplug->action) { case RTAS_HP_ACTION_ADD: drmgr_args[3] = "-a"; break; case RTAS_HP_ACTION_REMOVE: drmgr_args[3] = "-r"; break; default: dbg("Unknown hotplug action %d\n", hotplug->action); return; } switch (hotplug->identifier) { case RTAS_HP_ID_DRC_INDEX: drmgr_args[4] = "-s"; snprintf(drc_index, 11, "%#x", hotplug->u1.drc_index); drmgr_args[5] = drc_index; break; case RTAS_HP_ID_DRC_COUNT: drmgr_args[4] = "-q"; snprintf(count, 4, "%u", hotplug->u1.count); drmgr_args[5] = count; break; default: dbg("Unknown or unsupported hotplug identifier %d\n", hotplug->identifier); return; } dbg("run: %s %s %s %s %s %s %s\n", drmgr_args[0], drmgr_args[1], drmgr_args[2], drmgr_args[3], drmgr_args[4], drmgr_args[5], drmgr_args[6]); #ifdef DEBUG if(no_drmgr) return; #endif /* invoke drmgr */ dbg("Invoke drmgr command\n"); child = fork(); if (child == -1) { log_msg(NULL, "%s cannot be run to handle a hotplug event, %s", DRMGR_PROGRAM, strerror(errno)); return; } else if (child == 0) { /* child process */ execv(DRMGR_PROGRAM, drmgr_args); /* shouldn't get here */ log_msg(NULL, "Couldn not exec %s in response to hotplug event, %s", DRMGR_PROGRAM, strerror(errno)); exit(1); } child = waitpid(child, &status, 0); dbg("drmgr call exited with %d\n", WEXITSTATUS(status)); } }
4,640
C
.c
116
25.844828
92
0.478377
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,570
update.c
power-ras_ppc64-diag/rtas_errd/update.c
/** * @file update.c * @brief Routines to update RTAS evetns to the platform log * * In certain cases, we may need to get RTAS events from syslog * and process them to /var/log/platform (i.e. an EPOW event that * allows enough time for the RTAS event(s) to be written to syslog * but not enough time for rtas_errd to run). * * The search implemeted here checks the last RTAS event number in * syslog and /var/log/platform. If they are not equal, we process * RTAS events from syslog until they are equal. * * Copyright (C) 2004 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include "rtas_errd.h" /** * @def BM_ARRAY_SIZE * @brief Array size for Boyer-Moore algorithm */ #define BM_ARRAY_SIZE 256 #define RTAS_START "RTAS event begin" #define RTAS_END "RTAS event end" /** * @var bad_char_start * @brief Boyer-Moore bad character array for finding RTAS event starts. */ int bad_char_start[BM_ARRAY_SIZE] = {-1}; /** * @var bad_char_end * @brief Boyer-Moore bad character array for finding RTAS event ends. */ int bad_char_end[BM_ARRAY_SIZE] = {-1}; /** * @var messages_log * * Used by update_rtas_msgs() to bring the platform log * up to date with current RTAS events. */ char *messages_log = NULL; /** * @var msgs_log_fd * @brief File descriptor for messages_log */ static int msgs_log_fd = -1; /** * setup_bc * @brief Initalize the bad character array for a Boyer-Moore search * * @param str search string to initialize the array with * @param strlen search string length * @param bc bad character array to be initialized */ void setup_bc(char *str, int strlen, int *bc) { int i; for (i = 0; i < BM_ARRAY_SIZE; i++) bc[i] = strlen; for (i = 0; i < (strlen - 1); i++) bc[(int)str[i]] = strlen - i - 1; } /** * find_event * @brief Find an RTAS event * * Search for a RTAS event in the given text. This uses a scaled * down version of the Boyer-Moore algorithm. Since we know the * search strings we also know there really isn't a good suffix worth * looking for. Thus we do not use the good suffix rule for this search. * * @param str string to search for * @param strlen length of search string * @param text text to search for string in * @param textlen length of text to search * @param bad_char bad character array for Boyer-Moore search * @return pointer to string in text on success, NULL on failure */ char * find_event(char *str, int strlen, char *text, int textlen, int bad_char[]) { int i, j = 0; while (j <= (textlen - strlen)) { /* for (i = (strlen - 1); i >= 0 && str[i] == text[i+j]; i--);*/ i = strlen - 1; while ((i >= 0) && (str[i] == text[i+j])) { i--; } if (i < 0) return &text[j]; else /* Since we're not using the good suffix rule * we need to guarantee progress. */ j += MAX(1, bad_char[(int)text[i+j]] - strlen + 1 + i); } return NULL; } /** * find_rtas_start * @brief Find the beginning of a RTAS event. * * @param textstart pointer to starting point of search * @param textend pointer to ending point of search * @return pointer to RTAS event start on success, NULL on failure. */ char * find_rtas_start(char *textstart, char *textend) { if (textstart == NULL) return NULL; if (bad_char_start[0] == -1) setup_bc(RTAS_START, strlen(RTAS_START), bad_char_start); return find_event(RTAS_START, strlen(RTAS_START), textstart, textend - textstart, bad_char_start); } /** * find_rtas_end * @brief Find the ending of a RTAS event. * * @param textstart pointer to starting point of search * @param textend pointer to ending point of search * @return pointer to RTAS event end on success, NULL on failure. */ char * find_rtas_end(char *textstart, char *textend) { if (textstart == NULL) return NULL; if (bad_char_end[0] == -1) setup_bc(RTAS_END, strlen(RTAS_END), bad_char_end); return find_event(RTAS_END, strlen(RTAS_END), textstart, textend - textstart, bad_char_end); } /** * get_rtas_no * @brief Retrieve an RTAS event numnber * * Retrieve the RTAS event number from an RTAS event. NOTE: this * routine assumes the pointer passed in is the result from * a call to find_rtas_start() * * @param ptr pointer to RTAS event * @return event number on success, 0 on failure */ int get_rtas_no(char *ptr) { /* move back until we hit a colon */ while (*ptr != ':') ptr--; /* move to the event number */ ptr += 2; return strtoul(ptr, NULL, 10); } /** * update_rtas_msgs * @brief Update RTAS messages in the platform log * * Update the file /var/log/platform with any RTAS events * found in syslog that have not been handled by rtas_errd. */ void update_rtas_msgs(void) { struct stat log_sbuf, msgs_sbuf; char *log_mmap = NULL, *log_mmap_end; char *msgs_mmap = NULL, *msgs_mmap_end; char *rtas_msgs_end, *rtas_msgs_start, *msgs_p; char *log_p; char *last_p; int last_rtas_log_no, last_rtas_msgs_no, cur_rtas_no; messages_log = "/var/log/messages"; if (access(messages_log, R_OK)) { /* try /var/log/syslog */ if (!access("/var/log/syslog", R_OK)) { messages_log = "/var/log/syslog"; } } if ((msgs_log_fd = open(messages_log, O_RDONLY)) < 0) { log_msg(NULL, "Could not open %s to update RTAS events, %s", messages_log, strerror(errno)); goto cleanup; } if ((fstat(msgs_log_fd, &msgs_sbuf)) < 0) { log_msg(NULL, "Cannot get status of %s to update RTAS events, " "%s", messages_log, strerror(errno)); goto cleanup; } /* abort if file size is zero */ if (msgs_sbuf.st_size == 0) { goto cleanup; } if ((msgs_mmap = mmap(0, msgs_sbuf.st_size, PROT_READ, MAP_PRIVATE, msgs_log_fd, 0)) == (char *)-1) { log_msg(NULL, "Cannot map %s to update RTAS events", messages_log); msgs_mmap = NULL; goto cleanup; } msgs_p = msgs_mmap; msgs_mmap_end = msgs_mmap + msgs_sbuf.st_size; if ((fstat(platform_log_fd, &log_sbuf)) < 0) { log_msg(NULL, "Cannot get status of %s to update RTAS events", platform_log); goto cleanup; } /* nothing to do if file size is zero */ if (log_sbuf.st_size == 0) goto cleanup; if ((log_mmap = mmap(0, log_sbuf.st_size, PROT_READ, MAP_PRIVATE, platform_log_fd, 0)) == (char *)-1) { log_msg(NULL, "Cannot map %s to update RTAS events, %s", platform_log, strerror(errno)); log_mmap = NULL; goto cleanup; } log_p = log_mmap; log_mmap_end = log_mmap + log_sbuf.st_size; /* find the last RTAS event in /var/log/platform */ last_p = NULL; log_p = find_rtas_start(log_p, log_mmap_end); while (log_p != NULL) { last_p = log_p; log_p = find_rtas_start(log_p + sizeof(RTAS_START), log_mmap_end); } if (last_p == NULL) last_rtas_log_no = 0; else last_rtas_log_no = get_rtas_no(last_p); /* We're finished with /var/log/platform; unamp it */ munmap(log_mmap, log_sbuf.st_size); log_mmap = NULL; /* find the last RTAS event in syslog */ last_p = NULL; msgs_p = find_rtas_start(msgs_p, msgs_mmap_end); while (msgs_p != NULL) { last_p = msgs_p; msgs_p = find_rtas_start(msgs_p + strlen(RTAS_START), msgs_mmap_end); } if (last_p == NULL) { dbg("%s does not contain any RTAS events", messages_log); goto cleanup; } last_rtas_msgs_no = get_rtas_no(last_p); if (last_rtas_log_no >= last_rtas_msgs_no) goto cleanup; /* * If we get here we know there are some events that have not * been processed by rtas_errd, process them now. NOTE: There * are scenarios in which we will process events that have * already been processed. There is not much we can do about * this, just accept it and move along. */ /* Move to the first event that has not been handled so we * can process them in order. */ cur_rtas_no = 0; rtas_msgs_start = msgs_mmap; while (cur_rtas_no <= last_rtas_log_no) { rtas_msgs_start = find_rtas_start(rtas_msgs_start + strlen(RTAS_START), msgs_mmap_end); cur_rtas_no = get_rtas_no(rtas_msgs_start); } rtas_msgs_end = find_rtas_end(rtas_msgs_start, msgs_mmap_end); /* Retrieve RTAS events from syslog */ while (rtas_msgs_start != NULL) { struct event event; unsigned long *out_buf; char *tmp = rtas_msgs_start; memset(&event, 0, sizeof(event)); out_buf = (unsigned long *)event.event_buf; /* put event number in first */ cur_rtas_no = get_rtas_no(rtas_msgs_start); /* skip past the "RTAS event begin" message */ tmp += strlen(RTAS_START); while (tmp < rtas_msgs_end) { int i; /* find the word "RTAS" */ for ( ; *tmp != 'R'; tmp++); if (strncmp(tmp++, "RTAS", 4) != 0) continue; /* we found "RTAS", go to the colon */ for( ; *tmp != ':'; tmp++); /* add two to get to the first value */ tmp += 2; /* parse the values */ for (i = 0; i < 4; i++) { *out_buf = strtoul(tmp, NULL, 16); out_buf++; tmp += 9; /* char hex value + space */ } } /* Initializethe fields of the rtas event */ event.seq_num = cur_rtas_no; event.rtas_event = parse_rtas_event(event.event_buf, RTAS_ERROR_LOG_MAX); if (event.rtas_event == NULL) { log_msg(NULL, "Could not update RTAS Event %d to %s", cur_rtas_no, platform_log); } else { log_msg(NULL, "Updating RTAS event %d to %s", cur_rtas_no, platform_log); event.rtas_hdr = rtas_get_event_hdr_scn(event.rtas_event); event.length = event.rtas_hdr->ext_log_length + 8; handle_rtas_event(&event); } rtas_msgs_start = find_rtas_start(rtas_msgs_end, msgs_mmap_end); rtas_msgs_end = find_rtas_end(rtas_msgs_start, msgs_mmap_end); } cleanup: if (msgs_mmap) munmap(msgs_mmap, msgs_sbuf.st_size); if (msgs_log_fd != -1) close(msgs_log_fd); return; }
10,672
C
.c
344
27.936047
81
0.664946
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,571
dchrp.h
power-ras_ppc64-diag/rtas_errd/dchrp.h
/** * @file dchrp.h * * Copyright (C) 2005 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _H_DCHRP #define _H_DCHRP /* * Error log identifiers that are built as follows: * * bit number: * 3322222222221111111111 * 10987654321098765432109876543210 * -------------------------------- * 0000 * ---- * | -------- * | | * | | -------- * | | | -------- * | | | | * | | | if cpu, mem, post or io format * | | | extended log byte 12 * | | | if epow format * | | | extended log byte 15 * | | | if sp format * | | | extended log byte 16 * | | | * | | if mem, post or io format * | | extended log byte 13 * | | if sp format * | | extended log byte 17 * | | if epow format * | | extended log byte 16 * | | * | if sp format * | extended log byte 18 * | if epow format * | extended log byte 17 * | * extended log byte 2, bits 4:7 * * * and each ID is labeled xxxByybz where xxx= format,yy=byte #,z=bit # * and Byybz is repeated as often as necessary * */ #define CPUB12b0 0x01000080 #define CPUB12b1 0x01000040 #define CPUB12b2 0x01000020 #define CPUB12b3 0x01000010 #define CPUB12b4 0x01000008 #define CPUB12b5 0x01000004 #define CPUB12b6 0x01000002 #define CPUB12b7 0x01000001 #define CPUALLZERO 0x01000000 #define MEMB12b0 0x02000080 #define MEMB12b1 0x02000040 #define MEMB12b2 0x02000020 #define MEMB12b3 0x02000010 #define MEMB12b4 0x02000008 #define MEMB12b4B13b3 0x02001008 #define MEMB12b5 0x02000004 #define MEMB12b6 0x02000002 #define MEMB12b7 0x02000001 #define MEMB13b0 0x02008000 #define MEMB13b1 0x02004000 #define MEMB13b2 0x02002000 #define MEMB13b3 0x02001000 #define MEMB13b4 0x02000800 #define MEMALLZERO 0x02000000 #define IOB12b0 0x03000080 #define IOB12b1 0x03000040 #define IOB12b2 0x03000020 #define IOB12b3 0x03000010 #define IOB12b3B13b2 0x03002010 #define IOB12b4 0x03000008 #define IOB12b5 0x03000004 #define IOB12b6 0x03000002 #define IOB12b7 0x03000001 #define IOB12b5B13b0 0x03008004 #define IOB12b6B13b0 0x03008002 #define IOB12b7B13b0 0x03008001 #define IOB12b5B13b1 0x03004004 #define IOB12b6B13b1 0x03004002 #define IOB12b7B13b1 0x03004001 #define IOB12b5B13b2 0x03002004 #define IOB12b6B13b2 0x03002002 #define IOB12b7B13b2 0x03002001 #define IOB12b6B13b3 0x03001002 #define IOB13b4 0x03000800 #define IOB13b5 0x03000400 #define IOB13b6 0x03000200 #define IOB13b7 0x03000100 #define IOALLZERO 0x03000000 #define POSTALLZERO 0x04000000 #define POSTB12b0 0x04000080 #define POSTB12b1 0x04000040 #define POSTB12b2 0x04000020 #define POSTB12b3 0x04000010 #define POSTB12b4 0x04000008 #define POSTB12b5 0x04000004 #define POSTB12b6 0x04000002 #define POSTB12b7 0x04000001 #define POSTB13b0 0x04008000 #define POSTB13b1 0x04004000 #define POSTB13b2 0x04002000 #define POSTB13b3 0x04001000 #define POSTB13b4 0x04000800 #define POSTB13b5 0x04000400 #define POSTB13b7 0x04000100 #define EPOWB1501 0x05000001 #define EPOWB1501B16b2b4 0x05002801 #define EPOWB1502 0x05000002 #define EPOWB1502B16b4 0x05000802 #define EPOWB1503 0x05000003 #define EPOWB1503B16b23 0x05003003 #define EPOWB1503B16b3 0x05001003 #define EPOWB1504 0x05000004 #define EPOWB1505 0x05000005 #define EPOWB1505B16b1B17b1 0x05404005 #define EPOWB1505B16b1B17b2 0x05204005 #define EPOWB1505B16b1B17b3 0x05104005 #define EPOWB1502B16b4B17b2 0x05200802 #define EPOWB1502B16b1b4B17b2 0x05204802 #define EPOWB1507 0x05000007 #define SPB16b0 0x0D000080 #define SPB16b1 0x0D000040 #define SPB16b2 0x0D000020 #define SPB16b3 0x0D000010 #define SPB16b4 0x0D000008 #define SPB16b5 0x0D000004 #define SPB16b6 0x0D000002 #define SPB16b7 0x0D000001 #define SPB17b0 0x0D008000 #define SPB17b1 0x0D004000 #define SPB17b2 0x0D002000 #define SPB17b3 0x0D001000 #define SPB17b4 0x0D000800 #define SPB17b5 0x0D000400 #define SPB17b6 0x0D000200 #define SPB17b7 0x0D000100 #define SPB18b0 0x0D800000 #define SPB18b1 0x0D400000 #define SPB18b2 0x0D200000 #define SPB18b3 0x0D100000 #define SPB18b4 0x0D080000 #define SPB18b5 0x0D040000 #define SPB18b6 0x0D020000 #define SPB18b7 0x0D010000 #define EPOWLOGB16b0 0x05008000 #define LOGB16b4 0x00000800 #define EPOWLOG 0x05000000 #define SPLOG 0x0D000000 /* * Bits analyzed in Version 2 EPOW logs. */ #define EPOWB16b0 0x00008000 #define EPOWB16b1 0x00004000 #define EPOWB16b2 0x00002000 #define EPOWB16b3 0x00001000 #define EPOWB16b2b3 0x00003000 #define EPOWB16b4 0x00000800 #define EPOWB17b0 0x00800000 #define EPOWB17b1 0x00400000 #define EPOWB17b2 0x00200000 #define EPOWB17b3 0x00100000 #define EPOWB17b4 0x00080000 /* * Extened EPOW codes, found after the location codes. The sensor nibble * is ignored. */ #define XEPOW1n11 0x1011 #define XEPOW1n64 0x1064 #define XEPOW2n32 0x2032 #define XEPOW2n52 0x2052 #define XEPOW3n21 0x3021 #define XEPOW3n73 0x3073 #define IGNORE_SENSOR_MASK 0xF0FF /* * PCI EPOW Register values for bits 13:15 */ #define PCIEPOW111 0x00070000 #define PCIEPOW100 0x00040000 #define PCIEPOW011 0x00030000 #define PCIEPOW010 0x00020000 #define PCIEPOW001 0x00010000 #define PCIEPOWMASK 0x00070000 #define CRITHI 13 #define CRITLO 9 #define WARNHI 12 #define WARNLO 10 #define NORMAL 11 #define GS_SUCCESS 0 #define THERM 3 #define POWER 9004 #define VOLT 9002 #define FAN 9001 /* * Offsets into the chrp error log */ #define I_EXTENDED 8 /* index to extended error log */ #define I_BYTE0 0 + I_EXTENDED /* contains predicative error bit */ #define I_BYTE1 1 + I_EXTENDED /* has platform specific error bit */ #define I_FORMAT 2 + I_EXTENDED /* to log format indicator */ #define I_BYTE3 3 + I_EXTENDED /* has modifier bits */ #define I_BYTE12 12+ I_EXTENDED /* to bytes describing error, where */ #define I_BYTE13 13+ I_EXTENDED /* most formats use bytes 12 & 13 */ #define I_BYTE15 15+ I_EXTENDED /* for epow errors */ #define I_BYTE16 16+ I_EXTENDED /* for sp errors */ #define I_BYTE17 17+ I_EXTENDED /* for sp errors */ #define I_BYTE18 18+ I_EXTENDED /* for sp errors */ #define I_BYTE19 19+ I_EXTENDED /* for sp errors */ #define I_BYTE24 24+ I_EXTENDED /* for repair pending bit */ #define I_BYTE28 28+ I_EXTENDED /* for sp errors */ #define I_CPU 13+ I_EXTENDED /* to for physical cpu number */ #define I_POSTCODE 26+ I_EXTENDED /* to post error code */ #define I_FWREV 30+ I_EXTENDED /* to firmware revision level */ #define I_IBM 40+ I_EXTENDED /* to IBM id for location codes */ #define I_TOKEN 20+I_EXTENDED #define I_INDEX 24+I_EXTENDED #define I_STATUS 32+I_EXTENDED #define IGNORE_SENSOR_MASK 0xF0FF /* for extended epow, a 2 byte value */ #define SENSOR_MASK 0x0F00 #define EXT_EPOW_REG_ID 0x3031 /* ascii for 01 */ #define SRC_REG_ID_02 0x3032 /* Ascii for 02 */ #define PCI_EPOW_REG_ID 0x3033 #define SRC_REG_ID_04 0x3034 /* Ascii for 04 */ /* Structure to describe i/o device from i/o detected chrp log */ struct device_ela { int status; /* 0=no data;1=bus only;2=device ok */ char bus; char devfunc; short deviceid; short vendorid; char revisionid; char slot; char name[NAMESIZE]; char busname[NAMESIZE]; char loc[LOCSIZE]; short led; }; #define DEVICE_NONE 0 #define DEVICE_BUS 1 #define DEVICE_OK 2 #define FIRST_LOC 1 /* mode for first location code */ #define NEXT_LOC 2 /* mode for next location code */ #define FIRST_REG 1 /* mode for first register data */ #define NEXT_REG 2 /* mode for next register data */ #define LOC_HIDE_CHAR '>' /* special meaning in location code buffer */ /* Return codes from get_cpu_frus */ #define RC_INVALID 0 #define RC_PLANAR 1 #define RC_PLANAR_CPU 2 #define RC_PLANAR_2CPU 3 #define MAXREFCODES 5 #define REFCODE_REASON_CUST 0x880 /* * The following name is a flag for the diag controller to format * the error description into a "special" SRN, i.e. containing refcodes */ #define REFCODE_FNAME "REF-CODE" #define MAX_MENUGOAL_SIZE 2000 #endif
9,324
C
.c
278
31.81295
81
0.711247
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,573
v6ela.c
power-ras_ppc64-diag/rtas_errd/v6ela.c
/** * @file v6ela.c * * Copyright (C) 2005, 2008 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <malloc.h> #include <string.h> #include <time.h> #include <librtasevent.h> #include <sys/types.h> #include "rtas_errd.h" #include "ela_msg.h" #include "dchrp.h" #define V6_ERROR_MSG 0 #define V6_EVENT_MSG 1 #define NUM_SUBID 12 #define NUM_SEVERITY 14 #define NUM_SUBTYPE 14 /* * Table of V6 Error Messages. Each message, V6_ER_ss_vv, is addressable * by the Subsystem Id ("ss") and the Error Severity ("vv"). */ char *v6_error[NUM_SUBID][NUM_SEVERITY] = { {V6_ER_10_00, V6_ER_10_10, V6_ER_10_20, V6_ER_10_21, V6_ER_10_22, V6_ER_10_23, V6_ER_10_24, V6_ER_10_40, V6_ER_10_41, V6_ER_10_44, V6_ER_10_45, V6_ER_10_48, V6_ER_10_60, V6_ER_10_61}, {V6_ER_20_00, V6_ER_20_10, V6_ER_20_20, V6_ER_20_21, V6_ER_20_22, V6_ER_20_23, V6_ER_20_24, V6_ER_20_40, V6_ER_20_41, V6_ER_20_44, V6_ER_20_45, V6_ER_20_48, V6_ER_20_60, V6_ER_20_61}, {V6_ER_30_00, V6_ER_30_10, V6_ER_30_20, V6_ER_30_21, V6_ER_30_22, V6_ER_30_23, V6_ER_30_24, V6_ER_30_40, V6_ER_30_41, V6_ER_30_44, V6_ER_30_45, V6_ER_30_48, V6_ER_30_60, V6_ER_30_61}, {V6_ER_40_00, V6_ER_40_10, V6_ER_40_20, V6_ER_40_21, V6_ER_40_22, V6_ER_40_23, V6_ER_40_24, V6_ER_40_40, V6_ER_40_41, V6_ER_40_44, V6_ER_40_45, V6_ER_40_48, V6_ER_40_60, V6_ER_40_61}, {V6_ER_50_00, V6_ER_50_10, V6_ER_50_20, V6_ER_50_21, V6_ER_50_22, V6_ER_50_23, V6_ER_50_24, V6_ER_50_40, V6_ER_50_41, V6_ER_50_44, V6_ER_50_45, V6_ER_50_48, V6_ER_50_60, V6_ER_50_61}, {V6_ER_60_00, V6_ER_60_10, V6_ER_60_20, V6_ER_60_21, V6_ER_60_22, V6_ER_60_23, V6_ER_60_24, V6_ER_60_40, V6_ER_60_41, V6_ER_60_44, V6_ER_60_45, V6_ER_60_48, V6_ER_60_60, V6_ER_60_61}, {V6_ER_70_00, V6_ER_70_10, V6_ER_70_20, V6_ER_70_21, V6_ER_70_22, V6_ER_70_23, V6_ER_70_24, V6_ER_70_40, V6_ER_70_41, V6_ER_70_44, V6_ER_70_45, V6_ER_70_48, V6_ER_70_60, V6_ER_70_61}, {V6_ER_7A_00, V6_ER_7A_10, V6_ER_7A_20, V6_ER_7A_21, V6_ER_7A_22, V6_ER_7A_23, V6_ER_7A_24, V6_ER_7A_40, V6_ER_7A_41, V6_ER_7A_44, V6_ER_7A_45, V6_ER_7A_48, V6_ER_7A_60, V6_ER_7A_61}, {V6_ER_80_00, V6_ER_80_10, V6_ER_80_20, V6_ER_80_21, V6_ER_80_22, V6_ER_80_23, V6_ER_80_24, V6_ER_80_40, V6_ER_80_41, V6_ER_80_44, V6_ER_80_45, V6_ER_80_48, V6_ER_80_60, V6_ER_80_61}, {V6_ER_90_00, V6_ER_90_10, V6_ER_90_20, V6_ER_90_21, V6_ER_90_22, V6_ER_90_23, V6_ER_90_24, V6_ER_90_40, V6_ER_90_41, V6_ER_90_44, V6_ER_90_45, V6_ER_90_48, V6_ER_90_60, V6_ER_90_61}, {V6_ER_A0_00, V6_ER_A0_10, V6_ER_A0_20, V6_ER_A0_21, V6_ER_A0_22, V6_ER_A0_23, V6_ER_A0_24, V6_ER_A0_40, V6_ER_A0_41, V6_ER_A0_44, V6_ER_A0_45, V6_ER_A0_48, V6_ER_A0_60, V6_ER_A0_61}, {V6_ER_B0_00, V6_ER_B0_10, V6_ER_B0_20, V6_ER_B0_21, V6_ER_B0_22, V6_ER_B0_23, V6_ER_B0_24, V6_ER_B0_40, V6_ER_B0_41, V6_ER_B0_44, V6_ER_B0_45, V6_ER_B0_48, V6_ER_B0_60, V6_ER_B0_61} }; /* * Table of V6 Event Messages. Each message, V6_EV_ss_tt, is addressable * by the Subsystem Id ("ss") and the Event Subtype ("tt"). */ char *v6_event[NUM_SUBID][NUM_SUBTYPE] = { {V6_EV_10_00, V6_EV_10_01, V6_EV_10_08, V6_EV_10_10, V6_EV_10_20, V6_EV_10_21, V6_EV_10_22, V6_EV_10_30, V6_EV_10_40, V6_EV_10_60, V6_EV_10_70, V6_EV_10_80, V6_EV_10_D0, V6_EV_10_E0}, {V6_EV_20_00, V6_EV_20_01, V6_EV_20_08, V6_EV_20_10, V6_EV_20_20, V6_EV_20_21, V6_EV_20_22, V6_EV_20_30, V6_EV_20_40, V6_EV_20_60, V6_EV_20_70, V6_EV_20_80, V6_EV_20_D0, V6_EV_20_E0}, {V6_EV_30_00, V6_EV_30_01, V6_EV_30_08, V6_EV_30_10, V6_EV_30_20, V6_EV_30_21, V6_EV_30_22, V6_EV_30_30, V6_EV_30_40, V6_EV_30_60, V6_EV_30_70, V6_EV_30_80, V6_EV_30_D0, V6_EV_30_E0}, {V6_EV_40_00, V6_EV_40_01, V6_EV_40_08, V6_EV_40_10, V6_EV_40_20, V6_EV_40_21, V6_EV_40_22, V6_EV_40_30, V6_EV_40_40, V6_EV_40_60, V6_EV_40_70, V6_EV_40_80, V6_EV_40_D0, V6_EV_40_E0}, {V6_EV_50_00, V6_EV_50_01, V6_EV_50_08, V6_EV_50_10, V6_EV_50_20, V6_EV_50_21, V6_EV_50_22, V6_EV_50_30, V6_EV_50_40, V6_EV_50_60, V6_EV_50_70, V6_EV_50_80, V6_EV_50_D0, V6_EV_50_E0}, {V6_EV_60_00, V6_EV_60_01, V6_EV_60_08, V6_EV_60_10, V6_EV_60_20, V6_EV_60_21, V6_EV_60_22, V6_EV_60_30, V6_EV_60_40, V6_EV_60_60, V6_EV_60_70, V6_EV_60_80, V6_EV_60_D0, V6_EV_60_E0}, {V6_EV_70_00, V6_EV_70_01, V6_EV_70_08, V6_EV_70_10, V6_EV_70_20, V6_EV_70_21, V6_EV_70_22, V6_EV_70_30, V6_EV_70_40, V6_EV_70_60, V6_EV_70_70, V6_EV_70_80, V6_EV_70_D0, V6_EV_70_E0}, {V6_EV_7A_00, V6_EV_7A_01, V6_EV_7A_08, V6_EV_7A_10, V6_EV_7A_20, V6_EV_7A_21, V6_EV_7A_22, V6_EV_7A_30, V6_EV_7A_40, V6_EV_7A_60, V6_EV_7A_70, V6_EV_7A_80, V6_EV_7A_D0, V6_EV_7A_E0}, {V6_EV_80_00, V6_EV_80_01, V6_EV_80_08, V6_EV_80_10, V6_EV_80_20, V6_EV_80_21, V6_EV_80_22, V6_EV_80_30, V6_EV_80_40, V6_EV_80_60, V6_EV_80_70, V6_EV_80_80, V6_EV_80_D0, V6_EV_80_E0}, {V6_EV_90_00, V6_EV_90_01, V6_EV_90_08, V6_EV_90_10, V6_EV_90_20, V6_EV_90_21, V6_EV_90_22, V6_EV_90_30, V6_EV_90_40, V6_EV_90_60, V6_EV_90_70, V6_EV_90_80, V6_EV_90_D0, V6_EV_90_E0}, {V6_EV_A0_00, V6_EV_A0_01, V6_EV_A0_08, V6_EV_A0_10, V6_EV_A0_20, V6_EV_A0_21, V6_EV_A0_22, V6_EV_A0_30, V6_EV_A0_40, V6_EV_A0_60, V6_EV_A0_70, V6_EV_A0_80, V6_EV_A0_D0, V6_EV_A0_E0}, {V6_EV_B0_00, V6_EV_B0_01, V6_EV_B0_08, V6_EV_B0_10, V6_EV_B0_20, V6_EV_B0_21, V6_EV_B0_22, V6_EV_B0_30, V6_EV_B0_40, V6_EV_B0_60, V6_EV_B0_70, V6_EV_B0_80, V6_EV_B0_D0, V6_EV_B0_E0} }; /** * get_message_id * * FUNCTION: Look up the message id for the given message type and UH * section. From the UH section, the subsystem id and either * the error severity or the event subtype is used to find * the message id. * * RETURNS: the message id for the dchrp.msg file * */ char * get_message_id(int type, struct rtas_usr_hdr_scn *usrhdr) { int i,j,k; int supported_severity[NUM_SEVERITY] = { 0, 0x10, 0x20, 0x21, 0x22, 0x23, 0x24, 0x40, 0x41, 0x44, 0x45, 0x48, 0x60, 0x61}; int supported_subtype[NUM_SUBTYPE] = { 0, 0x01, 0x08, 0x10, 0x20, 0x21, 0x22, 0x30, 0x40, 0x60, 0x70, 0x80, 0xD0, 0xE0}; /* Subsystem IDs start at 0x10 according to the PAPR. Anything below that is invalid */ if (usrhdr->subsystem_id < 0x10) return (V6_INVALID_SUBID); /* Subsystem IDs in the range 0xB0 to 0xFF are reserved */ if (usrhdr->subsystem_id > 0xAF) return (V6_RESERVED_SUBID); /* Use upper 4 bits for message index */ i = usrhdr->subsystem_id >> 4; if (usrhdr->subsystem_id > 0x79) i++; /* Decrement subsystem ID index into message arrays (index 0 = message for subsystem ID 0x10 - 0x1F, etc) */ i--; if (type == V6_ERROR_MSG) { for (k = 0, j = -1; k < NUM_SEVERITY && j == -1; k++) if (supported_severity[k] == usrhdr->event_severity) j = k; if (j == -1) j = 0; return (v6_error[i][j]); } else { /* V6_EVENT_MSG */ for (k = 0, j = -1; k < NUM_SUBTYPE && j == -1; k++) if (supported_subtype[k] == usrhdr->event_type) j = k; if (j == -1) j = 0; return (v6_event[i][j]); } } /** * report_src * @brief Create the servicelog entry for a v6 event * * @return 0 on success */ static int report_src(struct event *event, struct rtas_priv_hdr_scn *privhdr, struct rtas_usr_hdr_scn *usrhdr) { struct rtas_fru_scn *fru; struct rtas_src_scn *src; struct sl_data_rtas *rtas_data = event->sl_entry->addl_data; int rc = 0; char *msg; src = rtas_get_src_scn(event->rtas_event); if (src == NULL) { log_msg(event, "Could not retrieve SRC section to handle " "event, skipping"); return 1; } event->sl_entry->refcode = malloc(strlen(src->primary_refcode) +1); if (event->sl_entry->refcode == NULL) { log_msg(event, "Memory allocation failed\n"); return 1; } strcpy(event->sl_entry->refcode, src->primary_refcode); msg = get_message_id(V6_ERROR_MSG, usrhdr); event->sl_entry->description = malloc(strlen(msg)+1); if (event->sl_entry->description == NULL) { free(event->sl_entry->refcode); log_msg(event, "Memory allocation failed\n"); return 1; } strcpy(event->sl_entry->description, msg); rtas_data->addl_words[0] = src->ext_refcode2; rtas_data->addl_words[1] = src->ext_refcode3; rtas_data->addl_words[2] = src->ext_refcode4; rtas_data->addl_words[3] = src->ext_refcode5; rtas_data->addl_words[4] = src->ext_refcode6; rtas_data->addl_words[5] = src->ext_refcode7; rtas_data->addl_words[6] = src->ext_refcode8; rtas_data->addl_words[7] = src->ext_refcode9; for (fru = src->fru_scns; fru != NULL; fru = fru->next) { struct rtas_fru_hdr *fruhdr = fru->subscns; struct rtas_fru_id_scn *fru_id; int type; char proc_id[20], loccode[80], frupn[20], frusn[20], ccin[20]; proc_id[0] = '\0'; loccode[0] = '\0'; frupn[0] = '\0'; frusn[0] = '\0'; ccin[0] = '\0'; /* the fru ID section will be first, if present */ if (strncmp(fruhdr->id, "ID", 2) != 0) continue; fru_id = (struct rtas_fru_id_scn *)fruhdr; type = fru_id->fruhdr.flags & RTAS_FRUID_COMP_MASK; if (fru->loc_code_length) strncpy(loccode, fru->loc_code, fru->loc_code_length); if (fruid_has_part_no(fru_id)) { strncpy(frupn, fru_id->part_no, 20); if (fruid_has_ccin(fru_id)) strncpy(ccin, fru_id->ccin, 20); if (fruid_has_serial_no(fru_id)) strncpy(frusn, fru_id->serial_no, 20); } if (fruid_has_proc_id(fru_id)) strncpy(proc_id, fru_id->procedure_id, 20); add_callout(event, fru->priority, type, proc_id, loccode, frupn, frusn, ccin); } if ((usrhdr->action & 0x8000) && (usrhdr->action & 0x0800)) event->sl_entry->call_home_status = SL_CALLHOME_CANDIDATE; return rc; } /** * report_menugoal * * FUNCTION: Report a menugoal from the V6 log data passed as input. The * input data must be analyzed to determine which menugoal is * used. If the log data contains an SRC and a FRU list, they * are included in the menugoal if the log data indicates an * error instead of an event. * * RETURNS: Nothing. * */ #define DISPLAY_SRC_SIZE 8 /* Display 8 digits of the SRC */ static void report_menugoal(struct event *event, struct rtas_priv_hdr_scn *privhdr, struct rtas_usr_hdr_scn *usrhdr) { char buffer[MAX_MENUGOAL_SIZE], menu_num_str[20]; char *msg = NULL; int offset = 0; uint menu_num = 0; long time_loc; struct tm *date = NULL; memset(buffer, 0, sizeof(buffer)); /* Create the menugoal text */ if (usrhdr->event_severity) { struct rtas_epow_scn *epow; struct rtas_src_scn *src; epow = rtas_get_epow_scn(event->rtas_event); /* This menu goal is a result of V6 log marked as an error, */ /* and the action is customer notifiy only. Include any/all */ /* SRC and FRU call outs in the menu goal text. */ if (epow != NULL) { /* Attempt to map this EPOW events to preexisting */ /* menu goals SRC and FRU Lists are added later. */ switch (epow->action_code) { case 0: /* No method to match this reset * to original error */ msg = MSGMENUG203; menu_num = 651203; break; case 1: case 2: msg = MSGMENUG157; menu_num = 651157; break; case 3: if (epow->event_modifier == 1) { msg = MSGMENUG206; menu_num = 651206; } else if (epow->event_modifier == 2) { msg = MSGMENUG205; menu_num = 651205; } else if (epow->event_modifier == 3) { msg = MSGMENUG159; menu_num = 651159; time_loc = time((long *)0); date = localtime(&time_loc); } break; case 4: case 5: case 7: msg = MSGMENUG161; menu_num = 651161; break; } if (date != NULL) { offset += sprintf(buffer + offset, msg, asctime(date)); } else { if (msg) /* msg == NULL if epow->action_code > 7 */ offset += sprintf(buffer + offset, "%s", msg); } } if (menu_num == 0) { /* Not resolved by EPOW section */ menu_num = 651300; msg = get_message_id(V6_ERROR_MSG, usrhdr); offset += sprintf(buffer + offset, "%s%s\n\n", MSGMENUGPEL_ERROR, msg); } src = rtas_get_src_scn(event->rtas_event); if (src != NULL && strlen(src->primary_refcode)) { struct rtas_fru_scn *fru; char tmp_buf[MAX_MENUGOAL_SIZE/2]; char tmp_src[DISPLAY_SRC_SIZE+1]; int tmp_off = 0; memset(tmp_buf, 0, sizeof(tmp_buf)); strncpy(tmp_src, src->primary_refcode, 8); tmp_src[DISPLAY_SRC_SIZE] = '\0'; offset += sprintf(buffer + offset, MSGMENUG_SRC, tmp_src); for (fru = src->fru_scns; fru != NULL; fru = fru->next){ struct rtas_fru_hdr *fruhdr = fru->subscns; struct rtas_fru_id_scn *fru_id; char *fru_msg = NULL; if (strncmp(fruhdr->id, "ID", 2) != 0) continue; fru_id = (struct rtas_fru_id_scn *)fruhdr; switch (fruhdr->flags & RTAS_FRUID_COMP_MASK) { case RTAS_FRUID_COMP_HARDWARE: fru_msg = MSGMENUG_FRU; break; case RTAS_FRUID_COMP_CODE: fru_msg = MSGMENUG_CODEFRU; break; case RTAS_FRUID_COMP_CONFIG_ERROR: fru_msg = MSGMENUG_CFG; break; case RTAS_FRUID_COMP_MAINT_REQUIRED: fru_msg = MSGMENUG_MAINT; break; case RTAS_FRUID_COMP_EXTERNAL: fru_msg = MSGMENUG_EXT_FRU; break; case RTAS_FRUID_COMP_EXTERNAL_CODE: fru_msg = MSGMENUG_EXT_CODEFRU; break; case RTAS_FRUID_COMP_TOOL: fru_msg = MSGMENUG_TOOL_FRU; break; case RTAS_FRUID_COMP_SYMBOLIC: fru_msg = MSGMENUG_SYM_FRU; break; default: fru_msg = MSGMENUG_RESERVED; } if (fruid_has_part_no(fru_id)) { tmp_off += sprintf(tmp_buf + tmp_off, fru_msg, fru_id->part_no); if (fruid_has_ccin(fru_id)) { tmp_off += sprintf(tmp_buf + tmp_off, MSGMENUG_CCIN, fru_id->ccin); } if (fruid_has_serial_no(fru_id)) { tmp_off += sprintf(tmp_buf + tmp_off, MSGMENUG_SERIAL, fru_id->serial_no); } } else if (fruid_has_proc_id(fru_id)) tmp_off += sprintf(tmp_buf + tmp_off, fru_msg, fru_id->procedure_id); /* Add location code if present */ if (fru->loc_code_length) { tmp_off += sprintf(tmp_buf + tmp_off, MSGMENUG_LOCATION, fru->loc_code); } else tmp_off += sprintf(tmp_buf + tmp_off, "\n"); offset += sprintf(buffer + offset, MSGMENUG_PRIORITY, fru->priority, tmp_buf); } } } else { /* This menu goal is a result of V6 log marked as an event, */ /* so don't include any SRC or FRU call outs because it */ /* will appear like an error and cause customer concern. */ menu_num = 651301; msg = get_message_id(V6_EVENT_MSG, usrhdr); offset += sprintf(buffer + offset, "%s%s\n\n", MSGMENUGPEL_EVENT, msg); } event->sl_entry->call_home_status = SL_CALLHOME_NONE; snprintf(menu_num_str, 20, "#%d", menu_num); event->sl_entry->refcode = malloc(strlen(menu_num_str)+1); if (event->sl_entry->refcode == NULL) { log_msg(event, "Memory allocaion failed.\n"); return; } strcpy(event->sl_entry->refcode, menu_num_str); event->sl_entry->description = malloc(strlen(msg)+1); if (event->sl_entry->description == NULL) { free(event->sl_entry->refcode); log_msg(event, "Memory allocaion failed.\n"); return; } strcpy(event->sl_entry->description, msg); dbg("menugoal: number = %d, message = \"%s\"", menu_num, msg); return; } /* * process_v6 * @brief Process events in the version 6 style * * @param event the event to be processed * @return 0 on success; !0 on failure */ int process_v6(struct event *event) { struct rtas_event_exthdr *exthdr; struct rtas_priv_hdr_scn *privhdr; struct rtas_usr_hdr_scn *usrhdr; struct rtas_src_scn *srchdr; struct rtas_mt_scn *mt; struct sl_data_rtas *rtas_data = NULL; dbg("Processing version 6 event"); /* create and populate the servicelog entry */ event->sl_entry = calloc(1, sizeof(struct sl_event)); if (event->sl_entry == NULL) goto sl_entry; rtas_data = calloc(1, sizeof(struct sl_data_rtas)); if (rtas_data == NULL) goto rtas_data; event->sl_entry->addl_data = rtas_data; rtas_data->kernel_id = event->seq_num; event->sl_entry->time_event = get_event_date(event); event->sl_entry->type = SL_TYPE_RTAS; event->sl_entry->severity = servicelog_sev(event->rtas_hdr->severity); mt = rtas_get_mt_scn(event->rtas_event); if (mt != NULL) { event->sl_entry->machine_model = malloc(strlen(mt->mtms.model)+1); if (event->sl_entry->machine_model) strcpy(event->sl_entry->machine_model, mt->mtms.model); else goto machine_model; event->sl_entry->machine_serial = malloc(strlen(mt->mtms.serial_no)+1); if (event->sl_entry->machine_serial) strcpy(event->sl_entry->machine_serial, mt->mtms.serial_no); else goto machine_serial; } /* * refcode, description, serviceable and call_home_status will be * set in either report_src or report_menugoal later */ exthdr = rtas_get_event_exthdr_scn(event->rtas_event); if (exthdr == NULL) { log_msg(event, "Could not retrieve RTAS extended header " "section."); } else { if (exthdr->predictive) event->sl_entry->predictive = 1; if (exthdr->recoverable) event->sl_entry->disposition = SL_DISP_RECOVERABLE; else if (exthdr->unrecoverable_bypassed) event->sl_entry->disposition = SL_DISP_BYPASSED; else if (exthdr->unrecoverable) event->sl_entry->disposition = SL_DISP_UNRECOVERABLE; } event->sl_entry->raw_data_len = event->length; event->sl_entry->raw_data = malloc(event->length); if (event->sl_entry->raw_data == NULL) goto raw_data; memcpy(event->sl_entry->raw_data, event->event_buf, event->length); /* populate the "additional data" section of the servicelog entry */ rtas_data->event_type = event->rtas_hdr->type; privhdr = rtas_get_priv_hdr_scn(event->rtas_event); if (privhdr == NULL) { log_msg(event, "No PH (private header) section in this v6 " "RTAS event; strange, but not an error."); } else { rtas_data->platform_id = privhdr->plid; rtas_data->creator_id = privhdr->creator_id; } usrhdr = rtas_get_usr_hdr_scn(event->rtas_event); if (usrhdr == NULL) { log_msg(event, "No UH (user header) section in this v6 " "RTAS event; strange, but not an error."); goto raw_data; } else { rtas_data->action_flags = usrhdr->action; rtas_data->subsystem_id = usrhdr->subsystem_id; rtas_data->pel_severity = usrhdr->event_severity; rtas_data->event_subtype = usrhdr->event_type; } /* Enable serviceable flag based on "Error Action Flags" */ if (usrhdr->action & RTAS_UH_ACTION_SERVICE) event->sl_entry->serviceable = 1; /* * if a "primary SRC" section exists, this is an SRC; otherwise, it * is a menugoal */ srchdr = rtas_get_src_scn(event->rtas_event); if (srchdr != NULL) report_src(event, privhdr, usrhdr); else report_menugoal(event, privhdr, usrhdr); return 0; raw_data: if (event->sl_entry->machine_serial) free(event->sl_entry->machine_serial); machine_serial: if (event->sl_entry->machine_model) free(event->sl_entry->machine_model); machine_model: free(rtas_data); rtas_data: free(event->sl_entry); sl_entry: log_msg(event, "Memory allocation failed\n"); return -1; }
19,955
C
.c
552
32.298913
81
0.641055
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,574
eeh.c
power-ras_ppc64-diag/rtas_errd/eeh.c
/* * @file eeh.c * @brief Routine to handle EEH notification RTAS events * * Copyright (C) 2004 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <string.h> #include <librtasevent.h> #include "rtas_errd.h" /** * @struct event_desc * @brief Definition for a SRC value and its corresponding description. */ struct event_desc { char *src_code; char *desc; }; /** * @var event_descs * @brief Array of event_desc structs for the SRC values to search * in an EEH related RTAS event. */ struct event_desc event_descs[] = { {"BA188001", "EEH recovered a failing I/O adapter"}, {"BA188002", "EEH could not recover the failed I/O adapter"}, {"BA180010", "PCI probe error, bridge in freeze state"}, {"BA180011", "PCI bridge probe error, bridge is not usable"}, {"BA180012", "PCI device runtime error, bridge in freeze state"}, {NULL, NULL} }; /** * check_eeh * @brief Check a RTAS event for EEH event notification. * * Parse a RTAS event to see if this is an EEH event notification. * If so, then update the platform log file with additional * information about the EEH event. * * @param event pointer to the RTAS event */ void check_eeh(struct event *event) { struct rtas_event_hdr *rtas_hdr = event->rtas_hdr; struct rtas_priv_hdr_scn *privhdr; struct rtas_src_scn *src; int index = 0; if (rtas_hdr->version != 6) { return; } src = rtas_get_src_scn(event->rtas_event); if (src == NULL) { log_msg(event, "Could not retrieve SRC section to check for " "an EEH event, skipping"); return; } /* * Check for a known EEH event described above in the * events description array. */ while (event_descs[index].src_code != NULL) { if (strncmp((char *)src->primary_refcode, event_descs[index].src_code, 8) == 0) break; index++; } if (event_descs[index].src_code == NULL) return; /* * Write the EEH Event notification out to /var/log/platform * Please trust the compiler to get this right */ platform_log_write("EEH Event Notification\n"); privhdr = rtas_get_priv_hdr_scn(event->rtas_event); if (privhdr == NULL) { log_msg(event, "Could not retrieve the RTAS Event information " "to report EEH failure date/time"); platform_log_write("Could not retrieve RTAS Event Date/Time\n"); } else { platform_log_write("%02x/%02x/%04x %02x:%02x:%02x\n", privhdr->date.month, privhdr->date.day, privhdr->date.year, privhdr->time.hour, privhdr->time.minutes, privhdr->time.seconds); } platform_log_write("Event SRC Code: %s\n", event_descs[index].src_code); platform_log_write(" %s\n", event_descs[index].desc); if (src->fru_scns != NULL) { struct rtas_fru_scn *fru = src->fru_scns; platform_log_write(" Device Location Code: %s\n", fru->loc_code); snprintf(event->addl_text, ADDL_TEXT_MAX, "%s, Location %s", event_descs[index].desc, fru->loc_code); } else { platform_log_write(" No Device Location Code provided.\n"); snprintf(event->addl_text, ADDL_TEXT_MAX, "%s, no " "location code provided", event_descs[index].desc); } return; }
3,813
C
.c
117
29.897436
81
0.703261
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,575
convert_dt_node_props.c
power-ras_ppc64-diag/rtas_errd/convert_dt_node_props.c
/** * @file convert_dt_node_props.c * * Copyright (C) 2005 - 2016 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <getopt.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdint.h> #include <dirent.h> #include <fcntl.h> #include "platform.h" #define MAX_IRQ_SERVERS_PER_CPU 16 static struct option long_options[] = { {"context", required_argument, NULL, 'c'}, {"from", required_argument, NULL, 'f'}, {"to", required_argument, NULL, 't'}, {"help", no_argument, NULL, 'h'}, {0,0,0,0} }; /* * The original version of this code processed 4 property arrays whose value * at any specific array index described a single system entity. * * ibm,drc-names: <num entries>; Array of name <encode-string> * ibm,drc-types: <num entries>; Array of entity 'type' <encode-string> * ibm,drc-indexes: <num entries>; Array of <encode-int> values * ibm,drc-power-domains: Array of <encode-int> values * * In a later version of the system firmware, a compressed representation * of this information property was added named 'ibm,drc-info'. Here is * a summary of the representation of the property. * * <int word: num drc-info entries> * Each entry has the following fields in sequential order: * <encode-string: drc-type e.g. "MEM" "PHB" "CPU"> * <encode-string: drc-name-prefix > * <encode-int: drc-index-start > * <encode-int: drc-name-suffix-start > * <encode-int: number-sequential-elements > * <encode-int: sequential-increment > * <encode-int: drc-power-domain > * Each entry describes a subset of all of the 'ibm,drc-info' * values. */ #define DRC_TYPE_LEN 16 #define DRC_NAME_LEN 256 /* Worst case length to expect */ /* * Association between older and newer 'drc info' structions * used to drive search routines. */ struct drc_info_search_config { char *drc_type; /* device kind sought e.g. "MEM" "PHB" "CPU" */ char *v1_tree_address; char *v1_tree_name_address; char *v2_tree_address; }; /* * Configuration of 'drc info' structures for memory-to-name association */ static struct drc_info_search_config mem_to_name = { "MEM", "/proc/device-tree/ibm,drc-indexes", "/proc/device-tree/ibm,drc-names", "/proc/device-tree/ibm,drc-info", }; /* * Configuration of 'drc info' structures for cpu-to-name association */ static struct drc_info_search_config cpu_to_name = { "CPU", "/proc/device-tree/cpus/ibm,drc-indexes", "/proc/device-tree/cpus/ibm,drc-names", "/proc/device-tree/cpus/ibm,drc-info", }; /* * Function prototypes supporting search across the 'drc info' structures */ static int search_drcindex_to_drcname(struct drc_info_search_config *, uint32_t, char *, int); static int search_drcname_to_drcindex(struct drc_info_search_config *, char *, uint32_t *); static int mem_drcindex_to_drcname(uint32_t, char *, int); int cpu_interruptserver_to_drcindex(uint32_t, uint32_t *); int cpu_drcindex_to_drcname(uint32_t, char *, int); int cpu_drcindex_to_interruptserver(uint32_t, uint32_t *, int); int cpu_drcname_to_drcindex(char *, uint32_t *); static void print_usage(char *command) { printf ("Usage: %s --context <x> --from <y> --to <z> <value>\n" "\t--context: currently, <x> must be cpu\n" "\t--from and --to: allowed values for <y> and <z>:\n" "\t\tinterrupt-server\n\t\tdrc-index\n\t\tdrc-name\n" "\tif <value> is a drc-index or interrupt-server, it can be\n" "\tspecified in decimal, hex (with a leading 0x), or octal\n" "\t(with a leading 0); if it is a drc-name, it should be\n" "\tspecified as a string in double quotes\n\n", command); } static int read_char_name(int fd, char *propname, int buf_size) { int offset = 0; uint8_t ch; /* Copy the property string at the current location to the buffer */ while ((read(fd, &ch, 1)) == 1) { if (propname) { if (offset+1 == buf_size) { propname[offset] = '\0'; break; } propname[offset++] = ch; } else { offset++; } if (ch == 0) break; } return offset; } static int read_uint32(int fd, uint32_t *retval) { uint32_t val; int rc = 0; rc = read(fd, &val, 4); if (rc < 4) { perror("Error: read_uint32: "); return -1; } (*retval) = be32toh(val); return 0; } static int search_drcindex_to_drcname_v1(struct drc_info_search_config *sr, uint32_t drc_idx, char *drc_name, int buf_size) { struct stat sbuf; int fd, offset=0, found=0; uint32_t index, num = 0; uint8_t ch; if (stat(sr->v1_tree_address, &sbuf) < 0) { fprintf(stderr, "Error: property %s not found", sr->v1_tree_name_address); return 0; } fd = open(sr->v1_tree_address, O_RDONLY); if (fd < 0) { fprintf(stderr, "Error opening %s:\n%s\n", sr->v1_tree_address, strerror(errno)); return 0; } /* skip this counter value; not needed to process the property here */ if (read_uint32(fd, &num) < 0) goto err; while ((read(fd, &index, 4)) != 0) { if (be32toh(index) == drc_idx) { found = 1; break; } offset++; } close(fd); if (found) { fd = open(sr->v1_tree_name_address, O_RDONLY); if (fd < 0) { fprintf(stderr, "Error opening %s:\n%s\n", sr->v1_tree_name_address, strerror(errno)); return 0; } /* skip the first one; it indicates how many are in the file */ if (read_uint32(fd, &index) < 0) goto err; while (offset > 0) { /* skip to (and one past) the next null char */ do { if ((read(fd, &ch, 1)) != 1) goto err; } while (ch != 0); offset--; } /* copy the drc-name at the current location to the buffer */ if (!read_char_name(fd, drc_name, buf_size)) goto err; } close(fd); return found; err: close(fd); return 0; } static int search_drcindex_to_drcname(struct drc_info_search_config *sr, uint32_t drc_idx, char *drc_name, int buf_size) { struct stat sbuf; int fd, found = 0; uint32_t num; int i; if (stat(sr->v2_tree_address, &sbuf)) return search_drcindex_to_drcname_v1(sr, drc_idx, drc_name, buf_size); fd = open(sr->v2_tree_address, O_RDONLY); if (fd < 0) { fprintf(stderr, "Error opening %s:\n%s\n", sr->v2_tree_address, strerror(errno)); return 0; } /* drc-info: need the first word to iterate over the subsets */ if (read_uint32(fd, &num) < 0) goto err; for (i = 0; i < num; i++) { char drc_type[DRC_TYPE_LEN]; char drc_name_base[DRC_NAME_LEN]; uint32_t drc_start_index, drc_end_index; uint32_t drc_name_start_index; uint32_t num_seq_elems; uint32_t seq_incr; uint32_t power_domain; int ndx_delta; if (!read_char_name(fd, drc_type, sizeof(drc_type))) goto err; if (!read_char_name(fd, drc_name_base, sizeof(drc_name_base))) goto err; if (read_uint32(fd, &drc_start_index) < 0) goto err; if (read_uint32(fd, &drc_name_start_index) < 0) goto err; if (read_uint32(fd, &num_seq_elems) < 0) goto err; if (read_uint32(fd, &seq_incr) < 0) goto err; if (read_uint32(fd, &power_domain) < 0) goto err; /* Drc-type sought match current entry? */ if (strcmp(drc_type, sr->drc_type)) continue; drc_end_index = drc_start_index + ((num_seq_elems-1) * seq_incr); if (drc_idx < drc_start_index) continue; if (drc_idx > drc_end_index) continue; ndx_delta = drc_idx - drc_start_index; snprintf(drc_name, buf_size, "%s%d", drc_name_base, drc_name_start_index + ndx_delta); found = 1; break; } err: close(fd); return found; } /** * mem_drcindex_to_drcname * @brief converts drcindex of mem type to drcname * * @param drc_idx - drc index whose drc name is to be found. * @param drc_name - buffer for drc_name * @param buf_size - size of buffer. */ static int mem_drcindex_to_drcname(uint32_t drc_idx, char *drc_name, int buf_size) { return search_drcindex_to_drcname(&mem_to_name, drc_idx, drc_name, buf_size); } /** * cpu_drcindex_to_drcname * @brief converts drcindex of cpu type to drcname * * @param drc_idx - drc index whose drc name is to be found. * @param drc_name - buffer for drc_name * @param buf_size - size of buffer. */ int cpu_drcindex_to_drcname(uint32_t drc_idx, char *drc_name, int buf_size) { return search_drcindex_to_drcname(&cpu_to_name, drc_idx, drc_name, buf_size); } static int search_drcname_to_drcindex_v1(struct drc_info_search_config *sr, char *drc_name, uint32_t *drc_idx) { struct stat sbuf; int fd, offset = 0, found = 0; uint32_t index, num = 0; char buffer[DRC_NAME_LEN]; if (stat(sr->v1_tree_address, &sbuf) < 0) { fprintf(stderr, "Error: property %s not found", sr->v1_tree_name_address); return 0; } fd = open(sr->v1_tree_name_address, O_RDONLY); if (fd < 0) { fprintf(stderr, "Error opening %s:\n%s\n", sr->v1_tree_name_address, strerror(errno)); return 0; } /* skip the first prop word; it indicates how many are in the file */ if (read(fd, &num, 4) != 4) { close(fd); return 0; } do { if (!read_char_name(fd, buffer, sizeof(buffer))) { close(fd); return 0; } if (!strcmp(buffer, drc_name)) { found = 1; break; } offset++; } while (!found); close(fd); if (found) { fd = open(sr->v1_tree_address, O_RDONLY); if (fd < 0) { fprintf(stderr, "Error opening %s:\n%s\n", sr->v1_tree_address, strerror(errno)); return 0; } /* * skip the first one (indicating the number of entries) * + offset number of indices */ if (lseek(fd, (1 + offset) * 4, SEEK_SET) != (1 + offset) * 4) { close(fd); return 0; } if ((read(fd, &index, 4)) == 4) *drc_idx = be32toh(index); else found = 0; close(fd); } return found; } static int search_drcname_to_drcindex(struct drc_info_search_config *sr, char *drc_name, uint32_t *drc_idx) { struct stat sbuf; int fd, i, found = 0; uint32_t num = 0; if (stat(sr->v2_tree_address, &sbuf) < 0) return search_drcname_to_drcindex_v1(sr, drc_name, drc_idx); fd = open(sr->v2_tree_address, O_RDONLY); if (fd < 0) { fprintf(stderr, "Error: property %s not found", sr->v2_tree_address); return 0; } /* * Now we process the entries of the 'ibm,drc-info' property. */ if (read_uint32(fd, &num) < 0) goto err; for (i = 0; i < num; i++) { char drc_type[DRC_TYPE_LEN]; char drc_name_base[DRC_NAME_LEN]; char name_compare[DRC_NAME_LEN]; uint32_t drc_start_index; uint32_t drc_name_start_index; uint32_t num_seq_elems; uint32_t seq_incr; uint32_t power_domain; uint32_t read_idx, ndx, tst_drc_idx; int rc; if (!read_char_name(fd, drc_type, sizeof(drc_type))) goto err; if (!read_char_name(fd, drc_name_base, sizeof(drc_name_base))) goto err; if (read_uint32(fd, &drc_start_index) < 0) goto err; if (read_uint32(fd, &drc_name_start_index) < 0) goto err; if (read_uint32(fd, &num_seq_elems) < 0) goto err; if (read_uint32(fd, &seq_incr) < 0) goto err; if (read_uint32(fd, &power_domain) < 0) goto err; /* Drc-type sought match current entry? */ if (strcmp(drc_type, sr->drc_type)) continue; strcat(drc_name_base, "%d"); rc = sscanf(drc_name, drc_name_base, &read_idx); if (rc) continue; /* Make sure that we can convert to/from the name */ ndx = ((read_idx - drc_name_start_index) / seq_incr); tst_drc_idx = drc_name_start_index + ((ndx-drc_name_start_index)*seq_incr); snprintf(name_compare, DRC_NAME_LEN, drc_name_base, tst_drc_idx); if (strcmp(drc_name, name_compare)) continue; *drc_idx = drc_start_index + ndx; found = 1; break; } err: close(fd); return found; } /** * cpu_drcname_to_drcindex * @brief converts mem type drcname to drcindex * * @param drc_idx - drc index whose drc name is to be found. * @param drc_name - buffer for drc_name */ int cpu_drcname_to_drcindex(char *drc_name, uint32_t *drc_idx) { return search_drcname_to_drcindex(&cpu_to_name, drc_name, drc_idx); } int main(int argc, char *argv[]) { int option_index, rc, i; int platform = 0; char *context=NULL, *from=NULL, *to=NULL; uint32_t interruptserver, drcindex; unsigned long drc_tmp_idx; uint32_t intservs_array[MAX_IRQ_SERVERS_PER_CPU]; char drcname[DRC_NAME_LEN]; platform = get_platform(); switch (platform) { case PLATFORM_UNKNOWN: case PLATFORM_POWERNV: fprintf(stderr, "%s: is not supported on the %s platform\n", argv[0], __power_platform_name(platform)); return -1; } for (;;) { option_index = 0; rc = getopt_long(argc, argv, "hc:f:t:", long_options, &option_index); if (rc == -1) break; switch (rc) { case 'h': print_usage(argv[0]); return 0; case 'c': /* context */ context = optarg; break; case 'f': /* from */ from = optarg; break; case 't': /* to */ to = optarg; break; case '?': print_usage(argv[0]); return -1; break; default: printf("huh?\n"); break; } } if (!context) { fprintf(stderr, "--context not specified\n"); return 1; } if (!from) { fprintf(stderr, "--from not specified\n"); return 2; } if (!to) { fprintf(stderr, "--to not specified\n"); return 3; } /* * In the cpu context, we can convert between drc name, drc index, * and interrupt server (AKA logical CPU ID). */ if (!strcmp(context, "cpu")) { if (!strcmp(from, "interrupt-server")) { interruptserver = strtol(argv[argc-1], NULL, 0); if (!strcmp(to, "drc-index")) { if (!cpu_interruptserver_to_drcindex( interruptserver, &drcindex)) { fprintf(stderr, "could not find the " "drc-index corresponding to " "interrupt-server 0x%08x\n", interruptserver); return 4; } printf("0x%08x\n", drcindex); } else if (!strcmp(to, "drc-name")) { if (!cpu_interruptserver_to_drcindex( interruptserver, &drcindex)) { fprintf(stderr, "could not find the " "drc-index corresponding to " "interrupt-server 0x%08x\n", interruptserver); return 4; } if (!cpu_drcindex_to_drcname(drcindex, drcname, DRC_NAME_LEN)) { fprintf(stderr, "could not find the " "drc-name corresponding to " "drc-index 0x%08x\n", drcindex); return 4; } printf("%s\n", drcname); } else { fprintf(stderr, "invalid --to flag: %s\n", to); return 3; } } else if (!strcmp(from, "drc-index")) { drcindex = strtol(argv[argc-1], NULL, 0); if (!strcmp(to, "drc-name")) { if (!cpu_drcindex_to_drcname(drcindex, drcname, DRC_NAME_LEN)) { fprintf(stderr, "could not find the " "drc-name corresponding to " "drc-index 0x%08x\n", drcindex); return 4; } printf("%s\n", drcname); } else if (!strcmp(to, "interrupt-server")) { rc = cpu_drcindex_to_interruptserver(drcindex, intservs_array, MAX_IRQ_SERVERS_PER_CPU); if (!rc) { fprintf(stderr, "could not find the " "interrupt-server corresponding" " to drc-index 0x%08x\n", drcindex); return 4; } if (rc > MAX_IRQ_SERVERS_PER_CPU) fprintf(stderr, "warning: only the " "first %d servers in the list " "of %d were returned; increase " "MAX_IRQ_SERVERS_PER_CPU to " "retrieve the entire list\n", MAX_IRQ_SERVERS_PER_CPU, rc); i = 0; while (i < rc) printf("0x%08x\n", intservs_array[i++]); } else { fprintf(stderr, "invalid --to flag: %s\n", to); return 3; } } else if (!strcmp(from, "drc-name")) { strncpy(drcname, argv[argc-1], DRC_NAME_LEN - 1); drcname[DRC_NAME_LEN - 1] = '\0'; if (!strcmp(to, "drc-index")) { if (!cpu_drcname_to_drcindex(drcname, &drcindex)) { fprintf(stderr, "could not find the " "drc-index corresponding to " "drc-name %s\n", drcname); return 4; } printf("0x%08x\n", drcindex); } else if (!strcmp(to, "interrupt-server")) { if (!cpu_drcname_to_drcindex(drcname, &drcindex)) { fprintf(stderr, "could not find the " "drc-index corresponding to " "drc-name %s\n", drcname); return 4; } rc = cpu_drcindex_to_interruptserver(drcindex, intservs_array, MAX_IRQ_SERVERS_PER_CPU); if (!rc) { fprintf(stderr, "could not find the " "interrupt-server corresponding" " to drc-index 0x%08x\n", drcindex); return 4; } if (rc > MAX_IRQ_SERVERS_PER_CPU) fprintf(stderr, "warning: only the " "first %d servers in the list " "of %d were returned; increase " "MAX_IRQ_SERVERS_PER_CPU to " "retrieve the entire list\n", MAX_IRQ_SERVERS_PER_CPU, rc); i = 0; while (i < rc) printf("0x%08x\n", intservs_array[i++]); } else { fprintf(stderr, "invalid --to flag: %s\n", to); return 3; } } else { fprintf(stderr, "invalid --from flag: %s\n", from); return 2; } } else if (!strcmp(context, "mem")) { if (!strcmp(from, "drc-index")) { drc_tmp_idx = strtoul(argv[argc-1], NULL, 0); if (!strcmp(to, "drc-name")) { if (!mem_drcindex_to_drcname(drc_tmp_idx, drcname, DRC_NAME_LEN)) { fprintf(stderr, "could not find the " "drc-name corresponding to " "drc-index 0x%08lx\n", drc_tmp_idx); return 4; } printf("%s\n", drcname); } } else { fprintf(stderr, "invalid --to flag: %s\n", to); return 3; } } else { fprintf(stderr, "invalid --context flag: %s\n", context); return 1; } return 0; } int cpu_interruptserver_to_drcindex(uint32_t int_serv, uint32_t *drc_idx) { DIR *dir; struct dirent *entry; int found=0, fd; char buffer[1024]; uint32_t temp; int rc; dir = opendir("/proc/device-tree/cpus"); while (!found && (entry = readdir(dir)) != NULL) { if (!strncmp(entry->d_name, "PowerPC,POWER", 13)) { rc = snprintf(buffer, 1024, "/proc/device-tree/cpus/%s/ibm" ",ppc-interrupt-server#s", entry->d_name); if (rc < 0 || rc >= 1024) { fprintf(stderr, "%s:%d - Unable to format %s\n", __func__, __LINE__, entry->d_name); goto cleanup; } if ((fd = open(buffer, O_RDONLY)) < 0) { fprintf(stderr, "Error: error opening %s:\n" "%s\n", buffer, strerror(errno)); goto cleanup; } while (read_uint32(fd, &temp) == 0) { if (temp == int_serv) { close(fd); rc = snprintf(buffer, 1024, "/proc/device-tree/cpus/%s/" "ibm,my-drc-index", entry->d_name); if (rc < 0 || rc >= 1024) { fprintf(stderr, "%s:%d - Unable to format %s\n", __func__, __LINE__, entry->d_name); goto cleanup; } if ((fd = open(buffer, O_RDONLY)) < 0) { fprintf(stderr, "Error " "opening %s:\n%s\n", buffer, strerror(errno)); goto cleanup; } if ((read(fd, &temp, 4)) == 4) { *drc_idx = be32toh(temp); found = 1; } /* if read */ break; } /* if be32toh */ } /* while */ close(fd); } } /* readdir */ cleanup: closedir(dir); return found; } /* returns # of interrupt-server numbers found, rather than a boolean value */ int cpu_drcindex_to_interruptserver(uint32_t drc_idx, uint32_t *int_servs, int array_elements) { DIR *dir; struct dirent *entry; int intr_fd, drc_fd, found=0; char buffer[1024]; uint32_t temp; int rc; dir = opendir("/proc/device-tree/cpus"); if (!dir) return 0; while (!found && (entry = readdir(dir)) != NULL) { if (!strncmp(entry->d_name, "PowerPC,POWER", 13)) { rc = snprintf(buffer, 1024, "/proc/device-tree/cpus/%s/ibm,my-drc-index", entry->d_name); if (rc < 0 || rc >= 1024) { fprintf(stderr, "%s:%d - Unable to format %s\n", __func__, __LINE__, entry->d_name); closedir(dir); return 0; } if ((drc_fd = open(buffer, O_RDONLY)) < 0) { fprintf(stderr, "Error opening %s:\n" "%s\n", buffer, strerror(errno)); closedir(dir); return 0; } while (read_uint32(drc_fd, &temp) == 0) { if (temp == drc_idx) { rc = snprintf(buffer, 1024, "/proc/device-tree/cpus/%s/" "ibm,ppc-interrupt-server#s", entry->d_name); if (rc < 0 || rc >= 1024) { fprintf(stderr, "%s:%d - Unable to format %s\n", __func__, __LINE__, entry->d_name); close(drc_fd); closedir(dir); return 0; } if ((intr_fd = open(buffer, O_RDONLY)) < 0) { fprintf(stderr, "Error " "opening %s:\n%s\n", buffer, strerror(errno)); close(drc_fd); closedir(dir); return 0; } while (found < array_elements && (read(intr_fd, &temp, 4)) == 4) int_servs[found++] = temp; close(intr_fd); break; } } close(drc_fd); } } closedir(dir); return found; }
21,287
C
.c
770
24.138961
81
0.637445
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,713,576
servicelog.c
power-ras_ppc64-diag/rtas_errd/servicelog.c
/** * @file servicelog.c * @brief Routines for inserting records into the servicelog database. * * Copyright (C) 2005 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdint.h> #include <errno.h> #include <time.h> #include <librtasevent.h> #include <sys/wait.h> #include "rtas_errd.h" #define bcd_4b_toint(x) ( ((((x) & 0xf000) >> 12) * 1000) + \ ((((x) & 0xf00) >> 8) * 100) + \ ((((x) & 0xf0) >> 4) * 10) + \ ((((x) & 0xf)))) #define bcd_2b_toint(x) ( ((((x) & 0xf0) >> 4) * 10) + \ ((((x) & 0xf)))) /** * get_event_date * @brief Retrieve the timestamp from an event * * @param event the event from which to retrieve the timestamp * @return the timestamp as time since Epoch, or 0 on failure */ time_t get_event_date(struct event *event) { struct rtas_time *time = NULL; struct rtas_date *date = NULL; if (event->rtas_hdr->version == 6) { struct rtas_priv_hdr_scn *privhdr; privhdr = rtas_get_priv_hdr_scn(event->rtas_event); if (privhdr == NULL) { log_msg(event, "Could not parse RTAS event to " "initialize servicelog timestamp."); } else { time = &privhdr->time; date = &privhdr->date; } } else { struct rtas_event_exthdr *exthdr; exthdr = rtas_get_event_exthdr_scn(event->rtas_event); if (exthdr == NULL) { log_msg(event, "Could not parse RTAS event to " "initialize servicelog timestamp."); } else { time = &exthdr->time; date = &exthdr->date; } } if (time != NULL) { struct tm tm = {0}; tm.tm_year = bcd_4b_toint(date->year) - 1900; tm.tm_mon = bcd_2b_toint(date->month) - 1; tm.tm_mday = bcd_2b_toint(date->day); tm.tm_hour = bcd_2b_toint(time->hour); tm.tm_min = bcd_2b_toint(time->minutes); tm.tm_sec = bcd_2b_toint(time->seconds); tm.tm_isdst = -1; return mktime(&tm); } return 0; } /** * servicelog_sev * @brief convert RTAS severity to servicelog severity * * @param rtas_sev RTAS severity to be converted * @return servicelog severity number, SL_SEV_INFO if unknown severity */ int servicelog_sev(int rtas_sev) { switch (rtas_sev) { case 0: /* NO_ERROR */ return SL_SEV_INFO; case 1: /* EVENT */ return SL_SEV_EVENT; case 2: /* WARNING */ return SL_SEV_WARNING; case 3: /* ERROR_SYNC */ return SL_SEV_ERROR; case 4: /* ERROR */ return SL_SEV_ERROR; case 5: /* FATAL */ return SL_SEV_FATAL; case 6: /* ALREADY_REPORTED */ return SL_SEV_INFO; } return SL_SEV_INFO; } /** * add_callout * @brief Add a new FRU callout to the list for this event * * @param event event to which to add the callout * @param pri priority * @param type type * @param proc procedure ID * @param loc location code * @param pn FRU part number * @param sn FRU serial number * @param ccin FRU ccin */ void add_callout(struct event *event, char pri, int type, char *proc, char *loc, char *pn, char *sn, char *ccin) { struct sl_callout *callout = event->sl_entry->callouts; if (!callout) { event->sl_entry->callouts = calloc(1, sizeof(*callout)); callout = event->sl_entry->callouts; } else { while (callout->next) callout = callout->next; callout->next = calloc(1, sizeof(*callout)); callout = callout->next; } if (!callout) return; callout->priority = pri; callout->type = type; if (proc) { callout->procedure = malloc(strlen(proc) + 1); if (callout->procedure == NULL) goto mem_fail; strncpy(callout->procedure, proc, strlen(proc) + 1); } if (loc) { callout->location = malloc(strlen(loc) + 1); if (callout->location == NULL) goto mem_fail; strncpy(callout->location, loc, strlen(loc) + 1); } if (pn) { callout->fru = malloc(strlen(pn) + 1); if (callout->fru == NULL) goto mem_fail; strncpy(callout->fru, pn, strlen(pn) + 1); } if (sn) { callout->serial = malloc(strlen(sn) + 1); if (callout->serial == NULL) goto mem_fail; strncpy(callout->serial, sn, strlen(sn) + 1); } if (ccin) { callout->ccin = malloc(strlen(ccin) + 1); if (callout->ccin == NULL) goto mem_fail; strncpy(callout->ccin, ccin, strlen(ccin) + 1); } return; mem_fail: if (callout->ccin) free(callout->ccin); if (callout->serial) free(callout->serial); if (callout->fru) free(callout->fru); if (callout->location) free(callout->location); if (callout->procedure) free(callout->procedure); free(callout); log_msg(event, "Memory allocation failed"); return; } /** * log_event * @brief log the event in the servicelog DB * * @param event RTAS event structure */ void log_event(struct event *event) { struct rtas_dump_scn *scn_dump; uint64_t key; int rc, txtlen; /* If the DB isn't available, do nothing */ if (slog == NULL) return; if (event->sl_entry == NULL) { log_msg(event, "ELA did not generate any data to be logged " "for this event."); return; } if (event->flags & RE_PLATDUMP_AVAIL) { if ((scn_dump = rtas_get_dump_scn(event->rtas_event)) != NULL) { char filename[41]; uint64_t dump_size = 0; memset(filename, 0, 41); memcpy(filename, scn_dump->os_id, scn_dump->id_len); dump_size = scn_dump->size_hi; dump_size <<= 32; dump_size |= scn_dump->size_lo; snprintf(event->addl_text, ADDL_TEXT_MAX, "A platform " "dump was generated and downloaded to the " "filesystem (%llu bytes):\n%s%s", (long long unsigned int)dump_size, d_cfg.platform_dump_path, filename); } } /* Append any additional text to the output of the analysis */ txtlen = strlen(event->addl_text); if (txtlen > 0) { if (event->sl_entry->description) { char *new_desc; int new_len; new_len = strlen(event->sl_entry->description) + txtlen + 3; new_desc = malloc(new_len); if (new_desc == NULL) { log_msg(event, "Memory allocation failed"); return; } snprintf(new_desc, new_len, "%s\n\n%s", event->sl_entry->description, event->addl_text); free(event->sl_entry->description); event->sl_entry->description = new_desc; } else { event->sl_entry->description = strdup(event->addl_text); if (event->sl_entry->description == NULL) { log_msg(event, "Memory allocation failed"); return; } } } /* Log the event in the servicelog */ rc = servicelog_event_log(slog, event->sl_entry, &key); servicelog_event_free(event->sl_entry); if (rc) log_msg(event, "Could not log event to servicelog.\n%s\n", servicelog_error(slog)); else log_msg(event, "servicelog key %llu", key); }
7,210
C
.c
259
25.096525
81
0.669315
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,713,577
dump.c
power-ras_ppc64-diag/rtas_errd/dump.c
/** * @file dump.c * @brief Routines to handle platform dump and scanlog dump RTAS events * * Copyright (C) 2004 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <librtas.h> #include <librtasevent.h> #include <syslog.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/statvfs.h> #include "utils.h" #include "rtas_errd.h" #define DUMP_MAX_FNAME_LEN 40 #define DUMP_BUF_SZ 4096 #define EXTRACT_PLATDUMP_CMD "/usr/sbin/extract_platdump" #define SCANLOG_DUMP_FILE "/proc/ppc64/scan-log-dump" #define SCANLOG_DUMP_EXISTS "/proc/device-tree/chosen/ibm,scan-log-data" #define SYSID_FILE "/proc/device-tree/system-id" #define SYSID_VENDOR_FILE "/proc/device-tree/ibm,vendor-system-id" #define SCANLOG_MODULE "scanlog" #define MODPROBE_PROGRAM "/sbin/modprobe" /** * get_machine_serial * @brief Retrieve a machines serial number * * Return a string containing the machine's serial number, obtained * from procfs (the file named SYSID_FILE). This routine mallocs a * new string; it is the caller's responsibility to ensure that the * string is freed. * * @return pointer to (allocated) string, NULL on failure */ static char * get_machine_serial() { FILE *fp; char buf[20] = {0,}, *ret = NULL; char *filename = SYSID_VENDOR_FILE; /* * Odds of SYSID_FILE, open failing is almost none. * But, better to catch the odds. */ fp = fopen(filename, "r"); if (!fp) { filename = SYSID_FILE; fp = fopen(filename, "r"); if (!fp) { log_msg(NULL, "%s: Failed to open %s, %s", __func__, filename, strerror(errno)); return ret; } } if (fgets(buf, sizeof(buf), fp) == NULL) { log_msg(NULL, "%s: Reading file %s failed, %s", __func__, filename, strerror(errno)); } else { ret = strdup(buf + 4); if (!ret) { log_msg(NULL, "%s: Memory allocation failed, %s", __func__, strerror(errno)); } /* strdup */ } fclose(fp); return ret; } /** * load_scanlog_module * @brief Load/Unload scanlog module * * Loads or unloads the scanlog module. The load parameter should * be 1 to load the module, or 0 to unload it. * * @param load directive to load/unload module * @return 0 on success, !0 on failure. */ static int load_scanlog_module(int load) { int rc, i = 0; pid_t cpid; /* child pid */ char *system_args[5] = {NULL,}; /* **argv passed to execv */ int status; /* exit status of child */ /* If SCANLOG_DUMP_FILE exists, then the module is either already * loaded, or the procfs interface is built into the kernel rather * than as a module. */ if (load && !access(SCANLOG_DUMP_FILE, F_OK)) return 0; system_args[i++] = MODPROBE_PROGRAM; system_args[i++] = "-q"; if (!load) system_args[i++] = "-r"; system_args[i++] = SCANLOG_MODULE; cpid = fork(); if (cpid == -1) { log_msg(NULL, "Fork failed, while probing for scanlog\n"); return 1; } /* fork */ if (cpid == 0 ) { /* child */ rc = execv(system_args[0], system_args); if (errno != ENOENT) { log_msg(NULL, "%s module could not be %s, could not run " "%s; system call returned %d", SCANLOG_MODULE, (load ? "loaded" : "unloaded"), MODPROBE_PROGRAM, rc); } else { log_msg(NULL, "module %s not found", SCANLOG_MODULE); } exit(-2); } else { /* parent */ rc = waitpid(cpid, &status, 0); if (rc == -1) { log_msg(NULL, "wait failed, while probing for " "scanlog\n"); return 1; } if ((signed char)WEXITSTATUS(status) == -2) /* exit on failure */ return 1; } return 0; } /** * check_scanlog_dump * @brief Check for new scanlog dumps * * This routine checks to see if a new scanlog dump is available, and * if so, copies it to the filesystem. The return value is the filename * of the new scanlog dump, or NULL if one is not copied. This routine * will malloc space for the returned string; it is up to the caller to * free it. * * This routine should be invoked once when the daemon is started. */ void check_scanlog_dump(void) { int rc, in = -1, out = -1, bytes; char *temp = NULL; char *scanlog_file = NULL, *scanlog_file_bak = NULL; char *dump_buf = NULL; rc = load_scanlog_module(1); if (rc || access(SCANLOG_DUMP_EXISTS, F_OK)) goto scanlog_out; /* A dump exists; copy it off to the filesystem */ if ((temp = get_machine_serial()) != 0) { if (asprintf(&scanlog_file, "%sscanoutlog.%s", d_cfg.scanlog_dump_path, temp) < 0) { free(temp); goto scanlog_out; } free(temp); } else { if (asprintf(&scanlog_file, "%sscanoutlog.NOSERIAL", d_cfg.scanlog_dump_path) < 0) goto scanlog_out; } if (!access(scanlog_file, F_OK)) { /* A scanlog dump already exists on the filesystem; * rename it with a .bak extension. */ if (asprintf(&scanlog_file_bak, "%s.bak", scanlog_file) < 0) goto scanlog_out; rc = rename(scanlog_file, scanlog_file_bak); if (rc) { log_msg(NULL, "Could not rename %s, an existing " "scanlog dump will be copied over by a new " "dump, %s", scanlog_file, strerror(errno)); } } free(scanlog_file_bak); in = open(SCANLOG_DUMP_FILE, O_RDONLY); if (in <= 0) { log_msg(NULL, "Could not open %s for reading, %s", SCANLOG_DUMP_FILE, strerror(errno)); goto scanlog_error; } out = open(scanlog_file, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (out <= 0) { log_msg(NULL, "Could not open %s for writing, %s", scanlog_file, strerror(errno)); goto scanlog_error; } dump_buf = malloc(DUMP_BUF_SZ); if (dump_buf == NULL) { log_msg(NULL, "Could not allocate buffer to read in " "scanlog dump, %s", strerror(errno)); goto scanlog_error; } while ((bytes = read(in, dump_buf, DUMP_BUF_SZ)) > 0) { rc = write(out, dump_buf, bytes); if (rc < bytes) { log_msg(NULL, "Could not write to %s, %s", scanlog_file, strerror(errno)); goto scanlog_error; } } if (bytes < 0) log_msg(NULL, "Could not read from %s, %s", SCANLOG_DUMP_FILE, strerror(errno)); temp = scanlog_file + strlen(d_cfg.scanlog_dump_path); scanlog = strdup(temp); if (scanlog == NULL) { log_msg(NULL, "Could not allocate space for scanlog filename, " "%s. A scanlog dump could not be copied to the " "filesystem", strerror(errno)); } /* strdup(scanlog) */ scanlog_out: free(scanlog_file); if (in != -1) close(in); if (out != -1) close(out); if (dump_buf != NULL) free(dump_buf); load_scanlog_module(0); return; scanlog_error: log_msg(NULL, "Due to previous error a scanlog dump could not be" "copied to the filesystem"); goto scanlog_out; } /** * check_platform_dump * @brief Check RTAS event for a platform dump * * Parses error information to determine if it indicates the availability * of a platform dump. The platform dump is copied to the filesystem, * and the error log is updated to indicate the path to the dump. * * This should be invoked _before_ the error information is written to * LOG_FILE, because the error may need to be updated with the path to * the dump. * * @param event pointer to struct event */ void check_platform_dump(struct event *event) { struct rtas_dump_scn *dump_scn; struct statvfs vfs; uint64_t dump_tag; uint64_t dump_size; char filename[DUMP_MAX_FNAME_LEN + 20], *pos; char *pathname = NULL; FILE *f; int rc, bytes; char *system_args[3] = {NULL, }; /* execv arguments */ char tmp_sys_arg[60]; /* tmp sys_args */ pid_t cpid; /* child pid */ dump_scn = rtas_get_dump_scn(event->rtas_event); if (dump_scn == NULL) return; dbg("platform dump found"); snprintf(event->addl_text, ADDL_TEXT_MAX, "Platform Dump " "(could not be retrieved to filesystem)"); if (dump_scn->v6hdr.subtype == 0) { dbg("ignoring platform dump with subtype 0"); return; } /* Retrieve the dump tag */ dump_tag = dump_scn->id; dump_tag |= ((uint64_t)dump_scn->v6hdr.subtype << 32); dbg("Dump ID: 0x%016LX", dump_tag); if (statvfs(d_cfg.platform_dump_path, &vfs) == -1) { log_msg(event, "statvfs() failed on %s: %s", d_cfg.platform_dump_path, strerror(errno)); return; } /* Retrieve the size of the platform dump */ dump_size = dump_scn->size_hi; dump_size <<= 32; dump_size |= dump_scn->size_lo; /* Check if there is sufficient space in the file system to store the dump */ if (vfs.f_bavail * vfs.f_frsize < dump_size) { syslog(LOG_ERR, "Insufficient space in %s to store platform dump for dump ID: " "0x%016lX (required: %lu bytes, available: %lu bytes)", d_cfg.platform_dump_path, dump_tag, dump_size, (vfs.f_bavail * vfs.f_frsize)); syslog(LOG_ERR, "After clearing space, run 'extract_platdump " "0x%016lX'.\n", dump_tag); return; } /* Retrieve the dump */ snprintf(tmp_sys_arg, 60, "0x%016LX", (long long unsigned int)dump_tag); system_args[0] = EXTRACT_PLATDUMP_CMD; system_args[1] = tmp_sys_arg; /* sigchld_handler() messes up pclose(). */ restore_sigchld_default(); f = spopen(system_args, &cpid); if (f == NULL) { log_msg(event, "Failed to open pipe to %s.", EXTRACT_PLATDUMP_CMD); setup_sigchld_handler(); return; } if (!fgets(filename, DUMP_MAX_FNAME_LEN + 20, f)) { dbg("Failed to collect filename info"); spclose(f, cpid); setup_sigchld_handler(); return; } rc = spclose(f, cpid); setup_sigchld_handler(); if (rc) { dbg("%s failed to extract the dump", EXTRACT_PLATDUMP_CMD); return; } if ((pos = strchr(filename, '\n')) != NULL) *pos = '\0'; dbg("Dump Filename: %s", filename); event->flags |= RE_PLATDUMP_AVAIL; /* Update the raw and parsed events with the dump path and length */ update_os_id_scn(event->rtas_event, filename); memcpy(dump_scn->os_id, filename, DUMP_MAX_FNAME_LEN); bytes = strlen(filename); if ((bytes % 4) > 0) bytes += (4 - (bytes % 4)); dump_scn->id_len = bytes; if (asprintf(&pathname, "%s/%s", d_cfg.platform_dump_path, filename) < 0) { dbg("%s: Failed to allocate memory", __func__); return; } platform_log_write("Platform Dump Notification\n"); platform_log_write(" Dump Location: %s\n", pathname); free(pathname); return; }
10,920
C
.c
353
28.388102
81
0.675
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,713,578
epow.c
power-ras_ppc64-diag/rtas_errd/epow.c
/** * @file epow.c * @brief Routines to handle EPOW RTAS events * * Copyright (C) 2004 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdarg.h> #include <errno.h> #include <string.h> #include <time.h> #include <sys/time.h> #include <librtas.h> #include <librtasevent.h> #include "rtas_errd.h" /* Sensor tokens, from RPA section 7.3.7.5 (get-sensor-state) */ #define SENSOR_TOKEN_KEY_SWITCH 1 #define SENSOR_TOKEN_ENCLOSURE_SWITCH 2 #define SENSOR_TOKEN_THERMAL_SENSOR 3 #define SENSOR_TOKEN_POWER_SOURCE 5 #define SENSOR_TOKEN_EPOW_SENSOR 9 /* File paths */ #define EPOW_PROGRAM "/etc/rc.powerfail" #define EPOW_PROGRAM_NOPATH "rc.powerfail" /** * @var time_remaining * @brief Time remaining until a system shutdown. * * The time_remaining variable is used by the epow timer * to track the time remaining until a system shutdown */ static int time_remaining = 0; /** * epow_timer_handler * @brief Routine to handle SIGALRM timer interrupts. * * @param sig unused * @param siginfo unused * @param context unused */ void epow_timer_handler(int sig, siginfo_t siginfo, void *context) { int rc, state; struct itimerval tv; if (time_remaining <= 0) { /* * Time is up; disable the interval timer. * The EPOW_PROGRAM should have already shut the * system down by this point. */ tv.it_interval.tv_sec = 0; tv.it_interval.tv_usec = 0; tv.it_value = tv.it_interval; rc = setitimer(ITIMER_REAL, &tv, NULL); return; } rc = rtas_get_sensor(SENSOR_TOKEN_EPOW_SENSOR, 0, &state); if (!rc && state < RTAS_EPOW_ACTION_SYSTEM_SHUTDOWN) { /* * Problem resolved; disable the interval timer and * update the epow status file. */ tv.it_interval.tv_sec = 0; tv.it_interval.tv_usec = 0; tv.it_value = tv.it_interval; rc = setitimer(ITIMER_REAL, &tv, NULL); if (state == RTAS_EPOW_ACTION_RESET) update_epow_status_file(0); else if (state == RTAS_EPOW_ACTION_WARN_COOLING) update_epow_status_file(8); else if (state == RTAS_EPOW_ACTION_WARN_POWER) update_epow_status_file(9); time_remaining = 0; return; } /* * If we make it this far, the problem (or a worse one) * still exists. If the problem is worse, the system will * probably shut down within 20 seconds. We shouldn't * overwrite the status so that if a worse problem exists, * it can be handled appropriately. */ time_remaining -= 5; return; } static void log_epow(struct event *event, char *fmt, ...) { va_list ap; char buf[1024]; va_start(ap, fmt); vsprintf(buf, fmt, ap); va_end(ap); log_msg(event, buf); snprintf(event->addl_text, ADDL_TEXT_MAX, "%s", buf); } /** * parse_epow * @brief Retrieve the epow status from an RTAS event. * * This routine returns the value that will be written to the epow_status * file. The value will be used by the EPOW_PROGRAM script (which can * be modified by a system administrator) to establish actions to be * taken for certain EPOW conditions. The return value must be 7 digits * or less. * * @param event pointer to the RTAS event * @return * <pre> * Return Value Action * ========================== ===================== * 0 normal state none * 1 loss of primary power 4 ms to shutdown * 2 power supply failure 4 ms to shutdown * 3 manual power-off switch activated 4 ms to shutdown * 4 thermal high 20 seconds to shutdown * 5 primary fan failure 20 seconds to shutdown * 6 secondary fan failure 10 minutes to shutdown * 7 battery backup 10 minutes to shutdown * 8 non-critical cooling problem none * 9 non-critical power problem none * 10 (v6) normal shutdown requested initiate shutdown immediately * 11 (v6) loss of critical system functions initiate shutdown immediately * </pre> * */ static int parse_epow(struct event *event) { struct rtas_event_hdr *rtas_hdr = event->rtas_hdr; struct rtas_epow_scn *epow; struct itimerval tv; char *event_type; int rc, state; /* * Check the sensor state; this will be used to ensure * that the problem in question is current, and isn't being retrieved * from NVRAM after a reboot when there wasn't time to handle the * problem (e.g. the power cable was yanked). */ rc = rtas_get_sensor(SENSOR_TOKEN_EPOW_SENSOR, 0, &state); if (rc) { log_epow(event, "Failed to read EPOW sensor state\n"); return 0; } if (rtas_hdr->extended == 0) { if (state > 0) { /* Assume a system halt */ log_epow(event, "Received shortened EPOW event, " "assuming power failure"); return 10; } else { log_epow(event, "Received shortened EPOW event, EPOW " "sensor not in shutdown mode"); return 0; } } epow = rtas_get_epow_scn(event->rtas_event); if (epow == NULL) { log_msg(event, "Could not retrieve EPOW section to handle " "incoming EPOW event, skipping"); return 0; } switch (epow->action_code) { case RTAS_EPOW_ACTION_RESET: log_epow(event, "Received EPOW action code reset (no action)"); return 0; break; case RTAS_EPOW_ACTION_WARN_COOLING: log_epow(event, "Received non-critical cooling EPOW action " "code (8)"); return 8; break; case RTAS_EPOW_ACTION_WARN_POWER: log_epow(event, "Received non-critical power EPOW action " "code (9)"); return 9; break; case RTAS_EPOW_ACTION_SYSTEM_SHUTDOWN: if (state != RTAS_EPOW_ACTION_SYSTEM_SHUTDOWN) { log_epow(event, "EPOW event: system shutdown " "requested, but the sensor state indicates " "the problem was resolved"); return 0; } /* * We have 10 minutes to shutdown. If we are already running * an interval timer we'll just just increase the length of * time we check for status updates instead of starting a new * timer. */ if (time_remaining <= 0) { /* Set up an interval timer to update the epow * status file every 5 seconds. */ tv.it_interval.tv_sec = 5; tv.it_interval.tv_usec = 0; tv.it_value = tv.it_interval; rc = setitimer(ITIMER_REAL, &tv, NULL); } time_remaining = 600; /* in seconds */ if (epow->fan) { log_epow(event, "EPOW event: system shutdown will " "begin in %d seconds due to a fan failure", time_remaining); return 6; } if (epow->power_fault) { log_epow(event, "EPOW event: system shutdown will " "begin in %d seconds due to a power fault", time_remaining); return 7; } if (epow->event_modifier == RTAS_EPOW_MOD_NORMAL_SHUTDOWN) { log_epow(event, "EPOW event: system shutdown will " "begin in %d seconds due to a normal " "shutdown request", time_remaining); return 10; } if (epow->event_modifier == RTAS_EPOW_MOD_UTILITY_POWER_LOSS) { log_epow(event, "EPOW event: system shutdown will " "begin in %d seconds due to a battery " "failure", time_remaining); return 7; } if (epow->event_modifier == RTAS_EPOW_MOD_CRIT_FUNC_LOSS) { log_epow(event, "EPOW event: system shutdown will " "begin in %d seconds due to a loss of system " "critical functions", time_remaining); return 11; } #ifdef RTAS_EPOW_MOD_AMBIENT_TEMP if (epow->event_modifier == RTAS_EPOW_MOD_AMBIENT_TEMP) { log_epow(event, "EPOW event: system shutdown will " "begin in %d seconds due to ambient " "temperature being too high", time_remaining); return 4; } #endif log_epow(event, "EPOW event: system shutdown will begin in %d " "seconds due to an unknown cause", time_remaining); return 7; break; case RTAS_EPOW_ACTION_SYSTEM_HALT: if (state != RTAS_EPOW_ACTION_SYSTEM_HALT) { log_epow(event, "EPOW event: system halt requested, " "but the sensor state indicates the problem " "was resolved"); return 0; } if (rtas_hdr->version < 6) { if (epow->fan) { log_epow(event, "EPOW event: system halting " "due to a fan failure"); return 5; } if (epow->temp) { log_epow(event, "EPOW event: system halting " "due to a thermal condition"); return 4; } log_epow(event, "EPOW event: system halting due to " "an unknown condition"); return 4; } else { log_epow(event, "EPOW event: system halting due to " "an unspecified condition"); return 4; } break; case RTAS_EPOW_ACTION_MAIN_ENCLOSURE: event_type = "main enclosure"; /* fall through */ case RTAS_EPOW_ACTION_POWER_OFF: event_type = "power off"; if (state != RTAS_EPOW_ACTION_MAIN_ENCLOSURE && state != RTAS_EPOW_ACTION_POWER_OFF) { log_epow(event, "EPOW event: %s requested, but the " "sensor state indicates the problem was " "resolved", event_type); return 0; } /* System will likely lose power before this code is ever run */ if ((rtas_hdr->version < 6) && (epow->power_fault)) { if (epow->power_loss) { log_epow(event, "EPOW event: power loss due " "to a power source fault"); return 1; } if (epow->power_supply) { log_epow(event, "EPOW event: power loss due " "to a power failure"); return 2; } if (epow->power_switch) { log_epow(event, "EPOW event: power loss due " "to a power switch fault"); return 3; } } else { log_epow(event, "EPOW event: power loss due to a %s " "event", event_type); return 1; } if (epow->action_code == RTAS_EPOW_ACTION_MAIN_ENCLOSURE) log_epow(event, "EPOW event: power loss due to an " "unknown main enclosure condition"); else log_epow(event, "EPOW event: power loss due to an " "unknown poer supply condition"); return 2; break; default: /* Unknown action code */ log_epow(event, "EPOW event: unknown action code (%d); " "event cannot be handled", epow->action_code); return 0; break; } return 0; } /** * check_epow * @brief Check an RTAS event for EPOW data. * * Parses error information to determine if it represents an EPOW event. * If it is, the epow_status_file is updated with the appropriate * condition, and EPOW_PROGRAM is invoked to take the appropriate system * action (shutdown, etc). * * @param event pointer to the RTAS event */ int check_epow(struct event *event) { pid_t child; char *childargs[2]; int current_status; /* * Dissect the EPOW extended error information; * if the error is serious enough to warrant further action, * fork and exec the script to handle it */ current_status = parse_epow(event); update_epow_status_file(current_status); if (current_status > 0) { childargs[0] = EPOW_PROGRAM_NOPATH; childargs[1] = NULL; child = fork(); if (child == -1) { log_msg(event, "Fork error, %s cannot be run to handle" "an incoming EPOW event, %s", EPOW_PROGRAM, strerror(errno)); } else if (child == 0) { /* child process */ execv(EPOW_PROGRAM, childargs); /* shouldn't get here */ log_msg(event, "Could not exec %s, %s. Could not " "handle an incoming EPOW event", EPOW_PROGRAM, strerror(errno)); exit(1); } } return current_status; }
11,758
C
.c
386
27.183938
81
0.683207
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,579
dchrp_frus.h
power-ras_ppc64-diag/rtas_errd/dchrp_frus.h
/** * @file dchrp_frus.h * * Copyright (C) 2005, 2008 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _H_DCHRP_FRUS #define _H_DCHRP_FRUS #include "ela_msg.h" /* * In the following #defines, x is the probability (confidence) that this * callout represents the actual failure */ #define FRU_MEMORY_CONTROLLER(x) { x, "", " ", 1} #define FRU_PROCESSOR(x) { x, "procx", " ", 127} #define FRU_L2CACHE(x) { x, "L2Cache0", " ", 33} #define FRU_MISSING_L2(x) { x, "L2Cache0", " ", 33} #define FRU_HOST_BRIDGE(x) { x, "", " ", 2} #define FRU_SYSTEM_BUS_CONNECTOR(x) { x, "", " ", 192} #define FRU_MEMORY_MODULE(x) { x, "Memory module", " ", 4} #define FRU_MEMORY_CARD(x) { x, "", " ", 5} #define FRU_MEZZANINE_BUS(x) { x, "", " ", 7} #define FRU_PCI_DEVICE(x) { x, "", " ", 3} #define FRU_PCI_BUS(x) { x, "", " ", 192} #define FRU_ISA_DEVICE(x) { x, "", " ", 8} #define FRU_ISA_BRIDGE(x) { x, "", " ", 9} #define FRU_ISA_BUS(x) { x, "", " ", 10} #define FRU_MEZZANINE_BUS_ARBITER(x) { x, "", " ", 11} #define FRU_SERVICE_PROCESSOR(x) { x, "", " ", 12} #define FRU_SP_SYSTEM_INTERFACE(x) { x, "", " ", 13} #define FRU_SP_PRIMARY_BUS(x) { x, "", " ", 14} #define FRU_SP_SECONDARY_BUS(x) { x, "", " ", 15} #define FRU_VPD_MODULE(x) { x, "", " ", 16} #define FRU_POWER_CONTROLLER(x) { x, "", " ", 18} #define FRU_FAN_SENSOR(x) { x, "Fan Sensor", " ", 19} #define FRU_THERMAL_SENSOR(x) { x, "Sensor", " ", 20} #define FRU_VOLTAGE_SENSOR(x) { x, "Sensor", " ", 21} #define FRU_POWER_SENSOR(x) { x, "sensor", " ", 179} #define FRU_SERIAL_PORT_CONTROLLER(x) { x, "", " ", 22} #define FRU_NVRAM(x) { x, "", " ", 23} #define FRU_RTC_TOD(x) { x, "", " ", 24} #define FRU_JTAG(x) { x, "", " ", 25} #define FRU_SOFTWARE(x) { x, "", " ", 26} #define FRU_HARDWARE(x) { x, "", " ", 27} #define FRU_FAN(x) { x, "Fan", " ", 28} #define FRU_POWER_SUPPLY(x) { x, "", " ", 29} #define FRU_BATTERY(x) { x, "", " ", 30} #define FRU_IO_EXPANSION_UNIT(x) { x, "", " ", 128} #define FRU_IO_EXPANSION_BUS(x) { x, "", " ", 129} #define FRU_34_POWER_SUPPLY(x) { x, "", " ", 130} #define FRU_14_POWER_SUPPLY(x) { x, "", " ", 131} #define FRU_RIO_BRIDGE(x) { x, "", " ", 185} #define FRU_RTASFRU(x) { x, "", " ", 192} #define FRU_OPERATOR_PANEL(x) { x, "", " ", 213} #define FRU_IO_PLANAR(x) { x, "", " ", 31} /* * If there are two entries for a given failure, the first should be * used in the case of an actual failure, and the second should be used * in the case of a predictive failure (i.e. the repair can be deferred) * * Some of the io??? failures have three entries. */ struct event_description_pre_v6 cpu610[] = /* CPU internal error */ { { "", ERRD1, 0x651, 0x610, MSGCPUB12b0, { FRU_PROCESSOR(100) } }, { "", ERRD1, 0x652, 0x610, DEFER_MSGCPUB12b0, { FRU_PROCESSOR(100) } } }; struct event_description_pre_v6 cpu611[] = /* CPU internal cache error */ { { "", ERRD1, 0x651, 0x611, MSGCPUB12b1, { FRU_PROCESSOR(100) } }, { "", ERRD1, 0x652, 0x611, DEFER_MSGCPUB12b1, { FRU_PROCESSOR(100) } } }; struct event_description_pre_v6 cpu612[] = /* L2 cache parity or mult-bit ecc error */ { { "", ERRD1, 0x651, 0x612, MSGCPUB12b2, { FRU_L2CACHE(100) } }, { "", ERRD1, 0x652, 0x612, DEFER_MSGCPUB12b2, { FRU_L2CACHE(100) } } }; struct event_description_pre_v6 cpu613[] = /* L2 cache ECC single-bit error */ { { "", ERRD1, 0x651, 0x613, MSGCPUB12b3, { FRU_L2CACHE(100) } }, { "", ERRD1, 0x652, 0x613, DEFER_MSGCPUB12b3, { FRU_L2CACHE(100) } } }; struct event_description_pre_v6 cpu614[] = /* Time-out error waiting for mem controller */ { { "", ERRD1, 0x651, 0x614, MSGCPUB12b4, { FRU_MEMORY_CONTROLLER(100) } } }; struct event_description_pre_v6 cpu615[] = /* Time-out error waiting for I/O */ { { "", ERRD1, 0x651, 0x615, MSGCPUB12b5, { FRU_HOST_BRIDGE(100) } } }; struct event_description_pre_v6 cpu619[] = /* Unknown error in CPU Error log */ { { "", ERRD1, 0x651, 0x619, MSGCPUALLZERO, { { 0, "", "", 36}, { 0, "", "", 36}, { 0, "", "", 36}, { 0, "", "", 36} } } }; struct event_description_pre_v6 cpu710[] = /* Address/Data parity error on Processor bus */ { { "", ERRD1, 0x651, 0x710, MSGCPUB12b6, { FRU_RTASFRU(60), FRU_SYSTEM_BUS_CONNECTOR(40) } } }; struct event_description_pre_v6 cpu711[] = /* Address/Data parity error on Processor bus */ { { "", ERRD1, 0x651, 0x711, MSGCPUB12b6, { FRU_RTASFRU(40), FRU_RTASFRU(35), FRU_SYSTEM_BUS_CONNECTOR(25) } } }; struct event_description_pre_v6 cpu712[] = /* Address/Data parity error on Processor bus */ { { "", ERRD1, 0x651, 0x712, MSGCPUB12b6, { FRU_RTASFRU(40), FRU_RTASFRU(25), FRU_RTASFRU(25), FRU_SYSTEM_BUS_CONNECTOR(10) } } }; struct event_description_pre_v6 cpu713[] = /* Transfer error on Processor bus */ { { "", ERRD1, 0x651, 0x713, MSGCPUB12b7, { FRU_RTASFRU(60), FRU_SYSTEM_BUS_CONNECTOR(40) } } }; struct event_description_pre_v6 cpu714[] = /* Transfer error on Processor bus */ { { "", ERRD1, 0x651, 0x714, MSGCPUB12b7, { FRU_RTASFRU(40), FRU_RTASFRU(35), FRU_SYSTEM_BUS_CONNECTOR(25) } } }; struct event_description_pre_v6 cpu715[] = /* Transfer error on Processor bus */ { { "", ERRD1, 0x651, 0x715, MSGCPUB12b7, { FRU_RTASFRU(40), FRU_RTASFRU(25), FRU_RTASFRU(25), FRU_SYSTEM_BUS_CONNECTOR(10) } } }; struct event_description_pre_v6 mem720[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x720, MSGMEMB12b0, { FRU_MEMORY_MODULE(85), FRU_MEMORY_CARD(10), FRU_MEMORY_CONTROLLER(5) } } }; struct event_description_pre_v6 mem721[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x721, MSGMEMB12b0, { FRU_MEMORY_MODULE(85), FRU_MEMORY_CARD(10), FRU_MEMORY_CONTROLLER(5) } } }; struct event_description_pre_v6 mem780[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x780, MSGMEMB12b0, { FRU_MEMORY_MODULE(85), FRU_MEMORY_CARD(10), FRU_MEMORY_CONTROLLER(5) } } }; struct event_description_pre_v6 mem781[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x781, MSGMEMB12b0, { FRU_MEMORY_MODULE(85), FRU_MEMORY_CARD(10), FRU_MEMORY_CONTROLLER(5) } } }; struct event_description_pre_v6 mem782[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x782, MSGMEMB12b0, { FRU_MEMORY_CARD(90), FRU_MEMORY_CONTROLLER(10) } } }; struct event_description_pre_v6 mem783[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x783, MSGMEMB12b0, { FRU_MEMORY_CARD(90), FRU_MEMORY_CONTROLLER(10) } } }; struct event_description_pre_v6 mem784[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x784, MSGMEMB12b0, { FRU_MEMORY_CARD(90), FRU_MEMORY_CONTROLLER(10) } } }; struct event_description_pre_v6 mem785[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x785, MSGMEMB12b0, { FRU_MEMORY_CARD(90), FRU_MEMORY_CONTROLLER(10) } } }; struct event_description_pre_v6 mem786[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x786, MSGMEMB12b0, { FRU_MEMORY_CARD(90), FRU_MEMORY_CONTROLLER(10) } } }; struct event_description_pre_v6 mem787[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x787, MSGMEMB12b0, { FRU_MEMORY_CARD(90), FRU_MEMORY_CONTROLLER(10) } } }; struct event_description_pre_v6 mem788[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x788, MSGMEMB12b0, { FRU_MEMORY_CARD(90), FRU_MEMORY_CONTROLLER(10) } } }; struct event_description_pre_v6 mem789[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x789, MSGMEMB12b0, { FRU_MEMORY_CARD(90), FRU_MEMORY_CONTROLLER(10) } } }; struct event_description_pre_v6 mem78A[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x78A, MSGMEMB12b0, { FRU_MEMORY_CARD(90), FRU_MEMORY_CONTROLLER(10) } } }; struct event_description_pre_v6 mem78B[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x78B, MSGMEMB12b0, { FRU_MEMORY_CARD(90), FRU_MEMORY_CONTROLLER(10) } } }; struct event_description_pre_v6 mem78C[] = /* Uncorrectable Memory Error */ { { "", ERRD1, 0x651, 0x78C, MSGMEMB12b0, { FRU_MEMORY_CARD(90), FRU_MEMORY_CONTROLLER(10) } } }; struct event_description_pre_v6 mem620[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x620, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem621[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x621, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem622[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x622, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x622, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem623[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x623, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x623, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem624[] = /* Memory Controller internal error */ { { "", ERRD1, 0x651, 0x624, MSGMEMB12b3, { FRU_MEMORY_CONTROLLER(100) } } }; struct event_description_pre_v6 mem625[] = /* Memory Address (Bad address to memory) */ { { "", ERRD1, 0x651, 0x625, MSGMEMB12b4, { FRU_MEMORY_CONTROLLER(100) } } }; struct event_description_pre_v6 mem626[] = /* Memory Data error (Bad data to memory) */ { { "", ERRD1, 0x651, 0x626, MSGMEMB12b5, { FRU_MEMORY_CONTROLLER(100) } } }; struct event_description_pre_v6 mem627[] = /* Memory time-out error */ { { "", ERRD1, 0x651, 0x627, MSGMEMB12b7, { FRU_MEMORY_CONTROLLER(100) } } }; struct event_description_pre_v6 mem628[] = /* Processor time-out error */ { { "", ERRD1, 0x651, 0x628, MSGMEMB13b1, { FRU_PROCESSOR(100) } } }; struct event_description_pre_v6 mem629[] = /* Unknown error detected by mem. controller */ { { "", ERRD1, 0x651, 0x629, MSGMEMALLZERO, { { 0, "", "", 36}, { 0, "", "", 36}, { 0, "", "", 36}, { 0, "", "", 36} } } }; struct event_description_pre_v6 io630[] = /* I/O Expansion Bus Parity Error */ { { "", ERRD1, 0x651, 0x630, MSGIOB13b4, { FRU_IO_EXPANSION_UNIT(100) } }, { "", ERRD1, 0x652, 0x630, DEFER_MSGIOB13b4, { FRU_IO_EXPANSION_UNIT(100) } } }; struct event_description_pre_v6 io631[] = /* I/O Expansion Bus Time-out Error */ { { "", ERRD1, 0x651, 0x631, MSGIOB13b5, { FRU_IO_EXPANSION_UNIT(100) } }, { "", ERRD1, 0x652, 0x631, DEFER_MSGIOB13b5, { FRU_IO_EXPANSION_UNIT(100) } } }; struct event_description_pre_v6 io632[] = /* I/O Expansion Bus Connect Failure */ { { "", ERRD1, 0x651, 0x632, MSGIOB13b6, { FRU_IO_EXPANSION_BUS(70), FRU_IO_EXPANSION_UNIT(20), FRU_RIO_BRIDGE(10) } }, { "", ERRD1, 0x652, 0x632, DEFER_MSGIOB13b6, { FRU_IO_EXPANSION_BUS(70), FRU_IO_EXPANSION_UNIT(20), FRU_RIO_BRIDGE(10) } } }; struct event_description_pre_v6 io633[] = /* I/O Expansion Unit not in operationg state.*/ { { "", ERRD1, 0x651, 0x633, MSGIOB13b7, { FRU_IO_EXPANSION_UNIT(70), FRU_IO_EXPANSION_BUS(30) } }, { "", ERRD1, 0x652, 0x633, DEFER_MSGIOB13b7, { FRU_IO_EXPANSION_UNIT(70), FRU_IO_EXPANSION_BUS(30) } } }; struct event_description_pre_v6 io634[] = /* Int Error, bridge conn. to i/o exp. bus */ { { "", ERRD1, 0x651, 0x634, MSGIOB12b3, { FRU_IO_EXPANSION_UNIT(100) } }, { "", ERRD1, 0x652, 0x634, DEFER_MSGIOB12b3, { FRU_IO_EXPANSION_UNIT(100) } } }; struct event_description_pre_v6 mem650[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x650, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem651[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x651, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem652[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x652, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem653[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x653, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem654[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x654, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem655[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x655, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem656[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x656, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem657[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x657, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem658[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x658, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem659[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x659, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem65A[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x65A, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem65B[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x65B, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem65C[] = /* ECC correctable error */ { { "", ERRD1, 0x651, 0x65C, MSGMEMB12b1, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem660[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x660, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x660, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem661[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x661, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x661, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem662[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x662, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x662, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem663[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x663, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x663, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem664[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x664, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x664, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem665[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x665, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x665, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem666[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x666, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x666, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem667[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x667, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x667, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem668[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x668, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x668, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem669[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x669, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x669, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem66A[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x66A, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x66A, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem66B[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x66B, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x66B, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 mem66C[] = /* Correctable error threshold exceeded */ { { "", ERRD1, 0x651, 0x66C, MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } }, { "", ERRD1, 0x652, 0x66C, DEFER_MSGMEMB12b2, { FRU_MEMORY_MODULE(100), /* Pct to be adjusted later */ FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0), FRU_MEMORY_MODULE(0) } } }; struct event_description_pre_v6 memtest670[] = /* Missing or bad memory */ { { "", ERRD1, 0x651, 0x670, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(90), FRU_MEMORY_CARD(10) } } }; struct event_description_pre_v6 memtest671[] = /* Missing or bad memory */ { { "", ERRD1, 0x651, 0x671, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(90), FRU_MEMORY_CARD(10) } } }; struct event_description_pre_v6 memtest672[] = /* Missing or bad memory */ { { "", ERRD1, 0x651, 0x672, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(100) } } }; struct event_description_pre_v6 memtest673[] = /* Missing or bad memory */ { { "", ERRD1, 0x651, 0x673, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(100) } } }; struct event_description_pre_v6 memtest674[] = /* Missing or bad memory */ { { "", ERRD1, 0x651, 0x674, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(100) } } }; struct event_description_pre_v6 memtest675[] = /* Missing or bad memory */ { { "", ERRD1, 0x651, 0x675, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(100) } } }; struct event_description_pre_v6 memtest676[] = /* Missing or bad memory */ { { "", ERRD1, 0x651, 0x676, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(100) } } }; struct event_description_pre_v6 memtest677[] = /* Missing or bad memory */ { { "", ERRD1, 0x651, 0x677, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(100) } } }; struct event_description_pre_v6 memtest678[] = /* Missing or bad memory */ { { "", ERRD1, 0x651, 0x678, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(100) } } }; struct event_description_pre_v6 memtest679[] = /* Missing or bad memory */ { { "", ERRD1, 0x651, 0x679, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(90), FRU_MEMORY_CARD(10) } } }; struct event_description_pre_v6 memtest67A[] = /* Missing or bad memory */ { { "", ERRD1, 0x651, 0x67A, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(90), FRU_MEMORY_CARD(10) } } }; struct event_description_pre_v6 mem67B[] = /* Failed memory module */ { { "", ERRD1, 0x651, 0x67B, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(90), FRU_MEMORY_CARD(10) } } }; struct event_description_pre_v6 mem67C[] = /* Failed memory module */ { { "", ERRD1, 0x651, 0x67C, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(90), FRU_MEMORY_CARD(10) } } }; struct event_description_pre_v6 mem722[] = /* Processor Bus parity error */ { { "", ERRD1, 0x651, 0x722, MSGMEMB13b0, { FRU_PROCESSOR(40), FRU_SYSTEM_BUS_CONNECTOR(35), FRU_MEMORY_CONTROLLER(25) } } }; struct event_description_pre_v6 mem723[] = /* Processor bus Transfer error */ { { "", ERRD1, 0x651, 0x723, MSGMEMB13b2, { FRU_PROCESSOR(40), FRU_SYSTEM_BUS_CONNECTOR(35), FRU_MEMORY_CONTROLLER(25) } } }; struct event_description_pre_v6 mem724[] = /* I/O Host Bridge time-out error */ { { "", ERRD1, 0x651, 0x724, MSGMEMB13b3, { FRU_HOST_BRIDGE(40), FRU_MEZZANINE_BUS(35), FRU_MEMORY_CONTROLLER(25) } } }; struct event_description_pre_v6 mem725[] = /* I/O Host Bridge address/data parity error */ { { "", ERRD1, 0x651, 0x725, MSGMEMB13b4, { FRU_HOST_BRIDGE(40), FRU_MEZZANINE_BUS(35), FRU_MEMORY_CONTROLLER(25) } } }; struct event_description_pre_v6 mem726[] = /* I/O Host Bridge and Bad Memory Address */ { { "", ERRD1, 0x651, 0x726, MSGMEMB12b4B13b3, } }; struct event_description_pre_v6 io833[] = { { "", ERRD1, 0x833, 0x0, MSGIOB12b0, /* I/O Bus Address Parity Error */ { { 40, "", " ", 192}, /* the fru name will be inserted, as will the */ /* reason code, which will be the led of the device */ FRU_PCI_DEVICE(35), FRU_PCI_BUS(25) } }, { "", ERRD1, 0x833, 0x0, MSGIOB12b1, /* I/O Bus Data Parity Error */ { { 40, "", " ", 192}, /* the fru name will be inserted, as will the */ /* reason code, which will be the led of the device */ FRU_PCI_DEVICE(35), FRU_PCI_BUS(25) } }, { "", ERRD1, 0x833, 0x0, MSGIOB12b2, /* I/O Time-out error */ { { 40, "", " ", 192}, /* the fru name will be inserted, as will the */ /* reason code, which will be the led of the device */ FRU_PCI_DEVICE(35), FRU_PCI_BUS(25) } } }; #define SN9CC 0x9aa /* 9CC was assigned, so internally I must */ /* use 9AA. The DIMB should read 9CC-xxx */ struct event_description_pre_v6 io9CC[] = { { "", ERRD1, SN9CC, 0x0, MSGIOB12b0, /* I/O Bus Address Parity Error */ { { 60, "", " ", 192}, /* the fru name will be inserted, as will the */ /* reason code, which will be the led of the device */ FRU_PCI_BUS(40) } }, { "", ERRD1, SN9CC, 0x0, MSGIOB12b1, /* I/O Bus Data Parity Error */ { { 60, "", " ", 192}, /* the fru name will be inserted, as will the */ /* reason code, which will be the led of the device */ FRU_PCI_BUS(40) } }, { "", ERRD1, SN9CC, 0x0, MSGIOB12b2, /* I/O Time-out error */ { { 60, "", " ", 192}, /* the fru name will be inserted, as will the */ /* reason code, which will be the led of the device */ FRU_PCI_BUS(40) } } }; struct event_description_pre_v6 iobusonly[] = { { "", ERRD1, SN9CC, 0x0, MSGIOB12b0, /* I/O Bus Address Parity Error */ { FRU_PCI_BUS(100) } }, { "", ERRD1, SN9CC, 0x0, MSGIOB12b1, /* I/O Bus Data Parity Error */ { FRU_PCI_BUS(100) } }, { "", ERRD1, SN9CC, 0x0, MSGIOB12b2, /* I/O Time-out error */ { FRU_PCI_BUS(100) } } }; struct event_description_pre_v6 io832[] = /* I/O Device Internal Error */ { { "", ERRD1, 0x832, 0x0, MSGIOB12b3, { { 100, "", " ", 192} /* the fru name will be inserted, as will the */ /* reason code, which will be the led of the device */ } } }; struct event_description_pre_v6 io639[] = /* Unknown error detected by I/O device */ { { "", ERRD1, 0x651, 0x639, MSGIOALLZERO, { { 0, "", "", 36}, { 0, "", "", 36}, { 0, "", "", 36}, { 0, "", "", 36} } } }; struct event_description_pre_v6 io730[] = /* I/O Error on non-PCI bus */ { { "", ERRD1, 0x651, 0x730, MSGIOB12b4, { FRU_ISA_BUS(100) } } }; struct event_description_pre_v6 io731[] = /* Mezzanine/Processor Bus Addr. Parity Error */ { { "", ERRD1, 0x651, 0x731, MSGIOB12b5, { FRU_MEZZANINE_BUS(60), FRU_HOST_BRIDGE(40) } }, { "", ERRD1, 0x652, 0x731, DEFER_MSGIOB12b5, { FRU_MEZZANINE_BUS(60), FRU_HOST_BRIDGE(40) } } }; struct event_description_pre_v6 io732[] = /* Mezzanine/Processor Bus Data Parity Error */ { { "", ERRD1, 0x651, 0x732, MSGIOB12b6, { FRU_MEZZANINE_BUS(60), FRU_HOST_BRIDGE(40) } }, { "", ERRD1, 0x652, 0x732, DEFER_MSGIOB12b6, { FRU_MEZZANINE_BUS(60), FRU_HOST_BRIDGE(40) } } }; struct event_description_pre_v6 io733[] = /* Mezzanine/Processor Bus Addr. Parity Error */ { { "", ERRD1, 0x651, 0x733, MSGIOB12b5, { FRU_MEMORY_CONTROLLER(40), FRU_MEZZANINE_BUS(35), FRU_HOST_BRIDGE(25) } }, { "", ERRD1, 0x652, 0x733, DEFER_MSGIOB12b5, { FRU_MEMORY_CONTROLLER(40), FRU_MEZZANINE_BUS(35), FRU_HOST_BRIDGE(25) } } }; struct event_description_pre_v6 io734[] = /* Mezzanine/Processor Bus Data Parity Error */ { { "", ERRD1, 0x651, 0x734, MSGIOB12b6, { FRU_MEMORY_CONTROLLER(40), FRU_MEZZANINE_BUS(35), FRU_HOST_BRIDGE(25) } }, { "", ERRD1, 0x652, 0x734, DEFER_MSGIOB12b6, { FRU_MEMORY_CONTROLLER(40), FRU_MEZZANINE_BUS(35), FRU_HOST_BRIDGE(25) } } }; struct event_description_pre_v6 io735[] = /* Mezzanine/Processor Bus Time-out Error */ { { "", ERRD1, 0x651, 0x735, MSGIOB12b7, { FRU_MEZZANINE_BUS_ARBITER(60), FRU_HOST_BRIDGE(40) } }, { "", ERRD1, 0x652, 0x735, DEFER_MSGIOB12b7, { FRU_MEZZANINE_BUS_ARBITER(60), FRU_HOST_BRIDGE(40) } } }; struct event_description_pre_v6 io736[] = /* Mezzanine/Processor Bus Time-out Error */ { { "", ERRD1, 0x651, 0x736, MSGIOB12b7, { FRU_MEZZANINE_BUS_ARBITER(40), FRU_HOST_BRIDGE(35), FRU_MEMORY_CONTROLLER(25) } }, { "", ERRD1, 0x652, 0x736, DEFER_MSGIOB12b7, { FRU_MEZZANINE_BUS_ARBITER(40), FRU_HOST_BRIDGE(35), FRU_MEMORY_CONTROLLER(25) } } }; struct event_description_pre_v6 sp740[] = /* T.O. on communication response from SP */ { { "", ERRD1, 0x651, 0x740, MSGSPB16b0, { FRU_SERVICE_PROCESSOR(60), FRU_SP_SYSTEM_INTERFACE(40) } } }; struct event_description_pre_v6 sp640[] = /* I/O (I2C) general bus error */ { { "", ERRD1, 0x651, 0x640, MSGSPB16b1, { FRU_SP_PRIMARY_BUS(100) } } }; struct event_description_pre_v6 sp641[] = /* Secondary I/O (I2C) general bus error */ { { "", ERRD1, 0x651, 0x641, MSGSPB16b2, { FRU_SP_SECONDARY_BUS(100) } } }; struct event_description_pre_v6 sp642[] = /* Internal Service Processor memory error */ { { "", ERRD1, 0x651, 0x642, MSGSPB16b3, { FRU_SERVICE_PROCESSOR(100) } } }; struct event_description_pre_v6 sp741[] = /* SP error accessing special registers */ { { "", ERRD1, 0x651, 0x741, MSGSPB16b4, { FRU_SERVICE_PROCESSOR(60), FRU_SP_SYSTEM_INTERFACE(40) } } }; struct event_description_pre_v6 sp742[] = /* SP reports unknown communication error */ { { "", ERRD1, 0x651, 0x742, MSGSPB16b5, { FRU_SERVICE_PROCESSOR(60), FRU_SP_SYSTEM_INTERFACE(40) } } }; struct event_description_pre_v6 sp643[] = /* Internal Service Processor firmware error */ { { "", ERRD1, 0x651, 0x643, MSGSPB16b6, { FRU_SERVICE_PROCESSOR(100) } } }; struct event_description_pre_v6 sp644[] = /* Other internal SP hardware error */ { { "", ERRD1, 0x651, 0x644, MSGSPB16b7, { FRU_SERVICE_PROCESSOR(100) } } }; struct event_description_pre_v6 sp743[] = /* SP error accessing VPD EEPROM */ { { "", ERRD1, 0x651, 0x743, MSGSPB17b0, { FRU_VPD_MODULE(75), FRU_SP_PRIMARY_BUS(25) } } }; struct event_description_pre_v6 sp744[] = /* SP error accessing Operator Panel */ { { "", ERRD1, 0x651, 0x744, MSGSPB17b1, { FRU_OPERATOR_PANEL(75), FRU_SP_PRIMARY_BUS(25) } } }; struct event_description_pre_v6 sp745[] = /* SP error accessing Power Controller */ { { "", ERRD1, 0x651, 0x745, MSGSPB17b2, { FRU_POWER_CONTROLLER(75), FRU_SP_PRIMARY_BUS(25) } } }; struct event_description_pre_v6 sp746[] = /* SP error accessing Fan Sensor */ { { "", ERRD1, 0x651, 0x746, MSGSPB17b3, { FRU_FAN_SENSOR(75), FRU_SP_PRIMARY_BUS(25) } } }; struct event_description_pre_v6 sp747[] = /* SP error accessing Thermal Sensor */ { { "", ERRD1, 0x651, 0x747, MSGSPB17b4, { FRU_THERMAL_SENSOR(75), FRU_SP_PRIMARY_BUS(25) } } }; struct event_description_pre_v6 sp748[] = /* SP error accessing Voltage Sensor */ { { "", ERRD1, 0x651, 0x748, MSGSPB17b5, { FRU_VOLTAGE_SENSOR(75), FRU_SP_PRIMARY_BUS(25) } } }; struct event_description_pre_v6 sp749[] = /* SP error accessing serial port */ { { "", ERRD1, 0x651, 0x749, MSGSPB18b0, { FRU_SERIAL_PORT_CONTROLLER(75), FRU_SP_SYSTEM_INTERFACE(25) } } }; struct event_description_pre_v6 sp750[] = /* SP error accessing NVRAM */ { { "", ERRD1, 0x651, 0x750, MSGSPB18b1, { FRU_NVRAM(75), FRU_SP_SYSTEM_INTERFACE(25) } } }; struct event_description_pre_v6 sp751[] = /* SP error accessing RTC/TOD clock */ { { "", ERRD1, 0x651, 0x751, MSGSPB18b2, { FRU_RTC_TOD(75), FRU_SP_SYSTEM_INTERFACE(25) } } }; struct event_description_pre_v6 sp752[] = /* SP error accessing JTAG/COP controller */ { { "", ERRD1, 0x651, 0x752, MSGSPB18b3, { FRU_JTAG(75), FRU_SP_SYSTEM_INTERFACE(25) } } }; struct event_description_pre_v6 sp753[] = /* SP detect error with tod battery */ { { "", ERRD1, 0x651, 0x753, MSGSPB18b4, { FRU_BATTERY(75), FRU_SP_SYSTEM_INTERFACE(25) } } }; struct event_description_pre_v6 sp754[] = /* SP detect SPCN link failure */ { { "", ERRD1, 0x651, 0x754, MSGSPB19b0, } }; struct event_description_pre_v6 sp760[] = /* SP reboot system due to surveillance T.O. */ { { "", ERRD1, 0x651, 0x760, MSGSPB18b7, { FRU_SOFTWARE(60), FRU_HARDWARE(40) } } }; struct event_description_pre_v6 io770[] = /* Mezzanine/Processor Bus Addr. Parity Error */ { { "", ERRD1, 0x651, 0x770, MSGIOB12b5, { FRU_MEZZANINE_BUS(40), FRU_HOST_BRIDGE(35), FRU_IO_EXPANSION_BUS(25) } }, { "", ERRD1, 0x652, 0x770, DEFER_MSGIOB12b5, { FRU_MEZZANINE_BUS(40), FRU_HOST_BRIDGE(35), FRU_IO_EXPANSION_BUS(25) } } }; struct event_description_pre_v6 io771[] = /* Mezzanine/Processor Bus Data Parity Error */ { { "", ERRD1, 0x651, 0x771, MSGIOB12b6, { FRU_MEZZANINE_BUS(40), FRU_HOST_BRIDGE(35), FRU_IO_EXPANSION_BUS(25) } }, { "", ERRD1, 0x652, 0x771, DEFER_MSGIOB12b6, { FRU_MEZZANINE_BUS(40), FRU_HOST_BRIDGE(35), FRU_IO_EXPANSION_BUS(25) } } }; struct event_description_pre_v6 io772[] = /* Mezzanine/Processor Bus Time-out Error */ { { "", ERRD1, 0x651, 0x772, MSGIOB12b7, { FRU_MEZZANINE_BUS(40), FRU_HOST_BRIDGE(35), FRU_MEZZANINE_BUS_ARBITER(25) } }, { "", ERRD1, 0x652, 0x772, DEFER_MSGIOB12b7, { FRU_MEZZANINE_BUS(40), FRU_HOST_BRIDGE(35), FRU_MEZZANINE_BUS_ARBITER(25) } } }; struct event_description_pre_v6 io773[] = /* Err detected by i/o exp. bus controller */ { { "", ERRD1, 0x651, 0x773, MSGIOB12b6, { FRU_RIO_BRIDGE(100) } }, { "", ERRD1, 0x652, 0x773, DEFER_MSGIOB12b6, { FRU_RIO_BRIDGE(100) } } }; struct event_description_pre_v6 epow800[] = /* Fan is turning slower than expected */ { { "", ERRD1, 0x651, 0x800, MSGXEPOW1n11, { FRU_FAN(60), FRU_FAN_SENSOR(40) } } }; struct event_description_pre_v6 epow801[] = /* Fan stop was detected */ { { "", ERRD1, 0x651, 0x801, MSGXEPOW1n64, { FRU_FAN(60), FRU_FAN_SENSOR(40) } } }; struct event_description_pre_v6 epow802[] = /* Fan failure */ { { "", ERRD1, 0x651, 0x802, MSGEPOWB16b2C12 } }; struct event_description_pre_v6 epow809[] = /* Power fault due to unspecified cause */ { { "", ERRD1, 0x651, 0x809, MSGEPOWB17b0C12 } }; struct event_description_pre_v6 epow810[] = /* Over voltage condition was detected */ { { "", ERRD1, 0x651, 0x810, MSGXEPOW2n32, { FRU_POWER_SUPPLY(60), FRU_VOLTAGE_SENSOR(40) } } }; struct event_description_pre_v6 epow811[] = /* Under voltage condition was detected */ { { "", ERRD1, 0x651, 0x811, MSGXEPOW2n52, { FRU_POWER_SUPPLY(60), FRU_VOLTAGE_SENSOR(40) } } }; struct event_description_pre_v6 epow812[] = /* System shutdown due to loss of power */ { { "", ERRD1, 0x651, 0x812, MSGEPOWB1505, { FRU_POWER_SUPPLY(100) } } }; struct event_description_pre_v6 epow813[] = /* System shutdown due to loss of power to site*/ { { "", ERRD1, 0x651, 0x813, MSGEPOWPCI111 } }; struct event_description_pre_v6 epow814[] = /* System shutdown due to loss of power to CEC */ { { "", ERRD1, 0x651, 0x814, MSGEPOWPCI100 } }; struct event_description_pre_v6 epow815[] = /* System shutdown due to loss of power to I/O Rack */ { { "", ERRD1, 0x651, 0x815, MSGEPOWPCI011, { FRU_34_POWER_SUPPLY(50), FRU_14_POWER_SUPPLY(50) } } }; struct event_description_pre_v6 epow816[] = /* Power fault due to internal power supply */ { { "", ERRD1, 0x651, 0x816, MSGEPOWPCI001, { FRU_34_POWER_SUPPLY(100) } } }; struct event_description_pre_v6 epow817[] = /* Power fault due to internal power supply */ { { "", ERRD1, 0x651, 0x817, MSGEPOWPCI010, { FRU_14_POWER_SUPPLY(100) } } }; struct event_description_pre_v6 epow818[] = /* Power fault due to power-off request */ { { "", ERRD1, 0x651, 0x818, MSGEPOWB16b1B17b3 } }; struct event_description_pre_v6 epow819[] = /* Power fault due to internal power supply */ { { "", ERRD1, 0x651, 0x819, MSGEPOWPCI001, { FRU_RTASFRU(100) } } }; struct event_description_pre_v6 epow819red[] = /* Power fault due to internal redundant PS */ { { "", ERRD1, 0x652, 0x819, MSGEPOWB17b2RED } }; struct event_description_pre_v6 epow820[] = /* Over temperature condition was detected */ { { "", ERRD1, 0x651, 0x820, MSGXEPOW3n21, { FRU_THERMAL_SENSOR(100) } } }; struct event_description_pre_v6 epow821[] = /* System shutdown due to over max temp. */ { { "", ERRD1, 0x651, 0x821, MSGXEPOW3n73, { FRU_THERMAL_SENSOR(100) } } }; struct event_description_pre_v6 epow822[] = /* System shutdown due to thermal and fan fail */ { { "", ERRD1, 0x651, 0x822, MSGEPOWB16b23 } }; struct event_description_pre_v6 epow823[] = /* System shutdown due to fan failure */ { { "", ERRD1, 0x651, 0x823, MSGEPOWB16b2C37 } }; struct event_description_pre_v6 epow824[] = /* System shutdown:Power fault-unspecified cause*/ { { "", ERRD1, 0x651, 0x824, MSGEPOWB17b0C37 } }; struct event_description_pre_v6 epow652810[] = /* Loss of redundant power supply. */ { { "", ERRD1, 0x652, 0x810, MSGEPOW1502B16b4 } }; struct event_description_pre_v6 epow652820[] = /* Loss of redundant cec blower. */ { { "", ERRD1, 0x652, 0x820, MSGEPOW1501B16b4 } }; struct event_description_pre_v6 post[] = /* POST 8 digit code */ { { "", ERRD1, -2, 0x0, MSGPOSTALL, /* -2 = DAVars has 8 digit hex code */ { { 0, "", "", 36}, { 0, "", "", 36}, { 0, "", "", 36}, { 0, "", "", 36} } } }; struct event_description_pre_v6 postfw[] = /* POST 8 digit code that is fw error*/ { { "", ERRD1, -2, 0x0, MSGPOSTALL, /* -2 = DAVars has 8 digit hex code */ { { 50, " ", " ", 35}, { 50, " ", " ", 34} } } }; struct event_description_pre_v6 memtest600[] = /* Uncorrectable/unsupported memory */ { { "", ERRD1, 0x651, 0x600, MSG_UNSUPPORTED_MEM, { FRU_MEMORY_MODULE(100) } }, { "", ERRD1, 0x652, 0x600, DEFER_MSG_UNSUPPORTED_MEM, { FRU_MEMORY_MODULE(100) } } }; struct event_description_pre_v6 memtest601[] = /* Missing or bad memory */ { { "", ERRD1, 0x651, 0x601, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(100) } } }; struct event_description_pre_v6 memtest602[] = /* Missing or bad memory */ { { "", ERRD1, 0x651, 0x602, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(90), FRU_MEMORY_CARD(10) } } }; struct event_description_pre_v6 memtest603[] = /* Missing or bad memory */ { { "", ERRD1, 0x651, 0x603, MSG_MISSING_MEM, { FRU_MEMORY_MODULE(90), FRU_MEMORY_CARD(10) } } }; struct event_description_pre_v6 l2test608[] = /* Bad L2 Cache */ { { "", ERRD1, 0x651, 0x608, MSG_BAD_L2, { FRU_L2CACHE(100) } } }; struct event_description_pre_v6 l2test609[] = /* Missing L2 Cache */ { { "", ERRD1, 0x651, 0x609, MSG_MISSING_L2, { FRU_MISSING_L2(100) } } }; /* * Source Number to match dresid and DIMB */ struct event_description_pre_v6 optest140[] = /* Op panel display test failed */ { { "", ERRD1, 0x651, 0x140, MSG_OP_PANEL_FAIL, { FRU_OPERATOR_PANEL(95), FRU_IO_PLANAR(5) } } }; /* * Event that is filled with ref. codes (in conf. field) and location * codes. The SRN will be formatted differently because the conf. * value is greater than 100. */ struct event_description_pre_v6 cec_src[] = /* SRC and ref. codes from CEC */ { { "", ERRD1, 0x651, 0, "", { { 0, "", "", 0}, { 0, "", "", 0}, { 0, "", "", 0}, { 0, "", "", 0} } } }; struct event_description_pre_v6 fan_epow[] = /* SRN for fan epow */ { { "", ERRD1, 0x651, 0, "", { FRU_FAN(60), FRU_FAN_SENSOR(40) } } }; struct event_description_pre_v6 volt_epow[] = /* SRN for voltage sensor epow */ { { "", ERRD1, 0x651, 0, "", { FRU_POWER_SUPPLY(60), FRU_VOLTAGE_SENSOR(40) } } }; struct event_description_pre_v6 therm_epow[] = /* SRN for thermal sensor epow */ { { "", ERRD1, 0x651, 0, "", { FRU_THERMAL_SENSOR(100) } } }; struct event_description_pre_v6 pow_epow[] = /* SRN for power epow */ { { "", ERRD1, 0x651, 0, "", { FRU_POWER_SUPPLY(60), FRU_POWER_SENSOR(40) } } }; struct event_description_pre_v6 unknown_epow[] = /* SRN for unknown epow */ { { "", ERRD1, 0x651, 0, "", { { 100, "", "", 180} } } }; /* Version 3 error descriptions */ struct event_description_pre_v6 platform_error[] = /* SRN for platform specific error */ { { "", ERRD1, 0x651, 0x900, MSG_PLATFORM_ERROR, { { 0, "", "", 0}, { 0, "", "", 0}, { 0, "", "", 0}, { 0, "", "", 0} } } }; #define SN_V3ELA 0xA00 /* source number for V3 ELA */ struct event_description_pre_v6 v3_errdscr[] = /* SRN for V3 error logs */ { { "", ERRD1, SN_V3ELA, 0, "", { { 0, "", "", 0}, { 0, "", "", 0}, { 0, "", "", 0}, { 0, "", "", 0} } } }; struct event_description_pre_v6 dt_errdscr[] = /* SRN for deconfig resources in device tree */ { { "", ERRD1, 0xA10, 0x200, FAIL_BY_PLATFORM, { { 100, "", "", 0}, } } }; struct event_description_pre_v6 bypass_errdscr[] = /* SRN for deconfig resource from error log */ { { "", ERRD1, 0xA10, 0x100, MSG_BYPASS, { { 100, "", "", 0}, } } }; #endif
45,066
C
.c
1,940
19.73866
82
0.616153
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,580
signal.c
power-ras_ppc64-diag/rtas_errd/signal.c
/** * @file signal.c * @brief rtas_errd signal handler * * Copyright (C) 2012 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <string.h> #include <signal.h> #include <errno.h> #include <sys/types.h> #include <sys/wait.h> #include "rtas_errd.h" /** * sighup_handler * @brief signal handler for SIGHUP * * The SIGHUP signal will cause the rtas_errd daemon to re-read * the configuration file. If it is currently safe to re-configure * ourselves we do, otherwise we set a flag to indicate that a * re-configuration needs to occur at the next "safe" place */ void sighup_handler(int sig, siginfo_t siginfo, void *context) { if (d_cfg.flags & RE_CFG_RECFG_SAFE) diag_cfg(1, &cfg_log); else d_cfg.flags |= RE_CFG_RECEIVED_SIGHUP; } /** * sigchld_handler * @brief SIGCHLD handler. * * Cleanup child process when it exited. */ static void sigchld_handler(int sig) { /* Wait for all dead processes. * We use a non-blocking call to be sure this signal handler will not * block if a child was cleaned up in another part of the program. */ while (waitpid(-1, NULL, WNOHANG) > 0) { } } /** * restore_sigchld_default * @brief restore child signal handler * * Restores child signal handler to default action. */ void restore_sigchld_default(void) { struct sigaction old_sigact; struct sigaction sigact; sigaction(SIGCHLD, NULL, &old_sigact); if (old_sigact.sa_handler != SIG_DFL ) { sigact.sa_handler = SIG_DFL; sigemptyset(&sigact.sa_mask); sigact.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sigact, NULL)) { log_msg(NULL, "Could not restore SIGCHLD signal " "handler to default action, %s", strerror(errno)); } } } /** * setup_sigchld_handler * @brief setup child signal handler * * Setup custom child signal handler to cleanup * child processes when it exited. */ void setup_sigchld_handler(void) { struct sigaction sigact; sigact.sa_handler = (void *)sigchld_handler; sigemptyset(&sigact.sa_mask); sigact.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sigact, NULL)) { log_msg(NULL, "Could not initialize signal handler for" "cleaning up child processes, %s", strerror(errno)); } }
2,883
C
.c
102
26.264706
81
0.736482
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,581
guard.c
power-ras_ppc64-diag/rtas_errd/guard.c
/** * @file guard.c * @brief Routines to handle CPU guard RTAS events * * Copyright (C) 2004 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <string.h> #include <sys/stat.h> #include <sys/wait.h> #include <dirent.h> #include "utils.h" #include "rtas_errd.h" #define DRMGR_PROGRAM "/usr/sbin/drmgr" #define DRMGR_PROGRAM_NOPATH "drmgr" #define CONVERT_DT_PROPS_PROGRAM "/usr/sbin/convert_dt_node_props" #define RTAS_V6_TYPE_RESOURCE_DEALLOC 0xE3 enum resource_dealloc_type {CPU_GUARD, SP_CPU_GUARD, MEM_PAGE, MEM_LMB}; enum event_type {CPUTYPE, MEMTYPE}; /** * run_drmgr * @brief build correct options followed by fork and exec drmgr * * @param resource type to deallocate. * @param specific drc_name to be de-allocted. * @param either quatity or capacity to be deallocated. * @param wait do we do a waitpid? */ void run_drmgr(enum resource_dealloc_type resource_type, char *drc_name, unsigned int value, int wait) { pid_t child; int status; char capacity[6], quant_str[5]; char *drmgr_args[] = {DRMGR_PROGRAM_NOPATH, "-r", "-c", NULL, NULL, NULL, NULL, NULL, NULL}; dbg("in run_drmgr command: %d %s %d %d", resource_type, drc_name, value, wait); if (resource_type == CPU_GUARD) { drmgr_args[3] = "cpu"; if (drc_name != NULL) { drmgr_args[4] = "-s"; drmgr_args[5] = drc_name; } else { drmgr_args[4] = "-q"; snprintf(quant_str, 5, "%d", value); drmgr_args[5] = quant_str; } /* end else */ } else if (resource_type == SP_CPU_GUARD) { drmgr_args[3] = "cpu"; drmgr_args[4] = "-p"; drmgr_args[5] = "ent_capacity"; drmgr_args[6] = "-q"; snprintf(capacity, 5, "%d", value); drmgr_args[7] = capacity; } else if (resource_type == MEM_PAGE) { log_msg(NULL, "We should not reach this code path " "error in handling of MEM_PAGE"); /* place holder for future expansion */ } else if (resource_type == MEM_LMB) { drmgr_args[3] = "mem"; drmgr_args[4] = "-s"; drmgr_args[5] = drc_name; }/* end building of drmgr command */ dbg("Running: %s %s %s %s %s %s %s %s", drmgr_args[0], drmgr_args[1], drmgr_args[2], drmgr_args[3], drmgr_args[4], drmgr_args[5], drmgr_args[6], drmgr_args[7]); #ifdef DEBUG if (no_drmgr) return; #endif child = fork(); if (child == -1) { log_msg(NULL, "%s cannot be run to handle a predictive CPU " "failure, %s", DRMGR_PROGRAM, strerror(errno)); return; } else if (child == 0) { /* child process */ execv(DRMGR_PROGRAM, drmgr_args); /* shouldn't get here */ log_msg(NULL, "Could not exec %s to in response to a " "predictive CPU failure, %s", DRMGR_PROGRAM, strerror(errno)); exit(1); } if (wait) { child = waitpid(child, &status, 0); } } /** * can_delete_lmb * @brief Counts the number of lmb's and returns an appropriate value * * This function returns true or false. It counts the lmb's in the system * and returns true if there is more than one lmb in the system. Which allows * us to call the appropriate delete function. * @return true if deletion can occur or false if it is the last lmb. */ static int can_delete_lmb(void) { DIR *dir; struct dirent *entry; int ret_val, fd, ctr=0; char buffer[1024], state[7]; int rc; ret_val = 0; /* default state is false, unless count is positive */ dir = opendir("/sys/devices/system/memory"); if (!dir) return 0; while ((entry = readdir(dir)) != NULL) { /* ignore memory@0 situation */ if (!strncmp(entry->d_name, "memory@0", 8)) continue; if (!strncmp(entry->d_name, "memory", 6)) { rc = snprintf(buffer, 1024, "/sys/devices/system/memory/%s/" "state", entry->d_name); if (rc < 0 || rc >= 1024) { log_msg(NULL, "%s:%d - Unable to format %s\n", __func__, __LINE__, entry->d_name); continue; } if ((fd = open(buffer, O_RDONLY)) < 0 ) { log_msg(NULL, "Could not open %s, %s", buffer, strerror(errno)); continue; } if ((read(fd, state, 6)) == 6) { if(!strncmp(state, "online", 6)) ctr++; /* make sure its not the last lmb */ if (ctr >= 2) { ret_val = 1; close(fd); break; } } close(fd); } } closedir(dir); return ret_val; } /** * retrieve_drc_name * @brief retrieve the drc-name of a cpu * * Retrieves a string containing the drc-name of the CPU specified by the ID * passed as a parameter. Returns 1 on success, 0 on failure. * * @param event rtas event pointer * @param id interrupt server number of the cpu * @param buffer storeage for drc-name * @param bufsize size of buffer * @return 1 on success, 0 on failure */ static int retrieve_drc_name(enum event_type type, struct event *event, unsigned int id, char *buffer, size_t bufsize) { struct stat sbuf; int rc, ret=1; FILE *fp; uint8_t status; char *system_args[9] = {NULL,}; /* execv arguments */ char tmp_sys_arg[100]; /* tmp sys_arg for snprintf */ pid_t cpid; /* child pid */ if (stat(CONVERT_DT_PROPS_PROGRAM, &sbuf) < 0) { log_msg(event, "The command \"%s\" does not exist, %s", CONVERT_DT_PROPS_PROGRAM, strerror(errno)); return 0; } system_args[0] = CONVERT_DT_PROPS_PROGRAM; system_args[1] = "--context"; if (type == CPUTYPE) { system_args[2] = "cpu"; system_args[3] = "--from"; system_args[4] = "interrupt-server"; system_args[5] = "--to"; system_args[6] = "drc-name"; snprintf(tmp_sys_arg, 100, "%u", id); system_args[7] = tmp_sys_arg; } else { /* event type is mem */ system_args[2] = "mem"; system_args[3] = "--from"; system_args[4] = "drc-index"; system_args[5] = "--to"; system_args[6] = "drc-name"; snprintf(tmp_sys_arg, 100, "0x%08x", id); system_args[7] = tmp_sys_arg; } /* Note : * rtas_errd sets up child signal handler * (setup_sigchld_handler()) which cleanup child process when it * exited. This caused pclose() to return non-zero value always * (No child process ). Resulted this function to return 0 * (failure) always. To overcome this issue we will restore * SIGCHLD handler to default action before doing popen() and * setup again after completing pclose(). */ restore_sigchld_default(); fp = spopen(system_args, &cpid); if (fp == NULL) { if (type == CPUTYPE) { log_msg(event, "Cannot obtain the drc-name for the " "CPU with ID %u; Could not run %s. %s", id, CONVERT_DT_PROPS_PROGRAM, strerror(errno)); } else { log_msg(event, "Cannot obtain the drc-name for the " "Memory with ID %u; Could not run %s. %s", id, CONVERT_DT_PROPS_PROGRAM, strerror(errno)); } setup_sigchld_handler(); return 0; } /* fp == NULL */ rc = fread(buffer, 1, bufsize, fp); if (rc == bufsize) { log_msg(event, "Cannot obtain the drc-name for the " "%s with ID %u; Buffer overflow in " "retrieve_drc_name", (type == CPUTYPE) ? "CPU" : "MEMORY", id); buffer[bufsize-1] = '\0'; ret = 0; } else if (rc > 0) { buffer[rc-1] = '\0'; /* overwrite the newline at the end */ } else buffer[0] = '\0'; status = spclose(fp, cpid); setup_sigchld_handler(); if (status != 0) { log_msg(event, "Cannot obtain the drc-name for the " "%s with ID %u; %s returned %d", (type == CPUTYPE) ? "CPU" : "MEMORY", id, CONVERT_DT_PROPS_PROGRAM, rc); ret = 0; } return ret; } /** * parse_lparcfg * @brief Retrieves the value of the specified parameter from the lparcfg file. * * @param param lparcfg parameter * @return value of param from lparcfg, -1 on error */ static long parse_lparcfg(char *param) { FILE *fp; int len; char buffer[128], *pos; if ((fp = fopen("/proc/ppc64/lparcfg", "r")) == NULL) { log_msg(NULL, "Could not open /proc/ppc64/lparcfg, %s", strerror(errno)); return -1; } len = strlen(param); while ((fgets(buffer, 128, fp)) != NULL) { if (!strncmp(param, buffer, len)) { if ((pos = strchr(buffer, '=')) == NULL) { log_msg(NULL, "Could not retrieve the value " "for %s from /proc/ppc64/lparcfg", param); fclose(fp); return -1; } pos++; buffer[strlen(buffer)-1] = '\0'; fclose(fp); return strtol(pos, NULL, 0); } } fclose(fp); log_msg(NULL, "Could not find the parameter %s in /proc/ppc64/lparcfg", param); return -1; } /** * guard_cpu * @brief Parse RTAS event for CPU guard information. * * Parses error information to determine if it represents a predictive CPU * failure, which should cause a CPU Guard operation. DRMGR_PROGRAM is * forked to actually remove the CPU from the system. * * @param event rtas event * @param cpu id to locate drc_name */ static void guard_cpu(struct event *event, int cpu_id) { char drc_name[30]; int n_cpus; if (! retrieve_drc_name(CPUTYPE, event, cpu_id, drc_name, 30)) { log_msg(event, "A CPU could not be guarded off in " "response to a received predictive CPU " "failure event %d", cpu_id); return; } /* check to make sure this isn't the last CPU */ n_cpus = parse_lparcfg("partition_active_processors"); if (n_cpus == 1) { log_msg(event, "A request was received to deallocate a " "processor due to a predictive CPU failure. " "The request cannot be carried out because " "there is only one CPU on this system"); return; } else if (n_cpus <= d_cfg.min_processors) { log_msg(event, "A request was received to deallocate a " "processor due to a predictive CPU failure. " "The request is not being carried out because " "ppc64-diag is configured to keep a minimum of " "%d processors", d_cfg.min_processors); return; } run_drmgr(CPU_GUARD, drc_name, 0, 0); log_msg(event, "The following CPU has been offlined due to the " "reporting of a predictive CPU failure: logical ID " "%d, drc-name %s", cpu_id, drc_name); platform_log_write("CPU Deallocation Notification\n"); platform_log_write("(resulting from a predictive CPU failure)\n"); platform_log_write(" Logical ID: %d\n", cpu_id); platform_log_write(" drc-name: %s\n", drc_name); snprintf(event->addl_text, ADDL_TEXT_MAX, "Predictive CPU Failure: deallocated CPU ID %d " "(drc-name \"%s\")", cpu_id, drc_name); return; } /** * guard_spcpu * @brief Parse RTAS event for SP_CPU guard information. * * Parses error information to determine if it represents a predictive SPCPU * failure, which should cause a SPCPU Guard operation. DRMGR_PROGRAM is * forked to actually remove the virtual cpu from the system. * * @param event rtas event * @param entitiled shared processor loss. */ static void guard_spcpu(struct event *event, int ent_loss) { int n_cpus, quant, ent_cap; int min_ent_cap = d_cfg.min_entitled_capacity; /* * Ensure that this event will not cause the entitled * capacity to drop below 10 per CPU. If so, we need to * start dropping virtual CPUs to accommodate the reduced * entitled capacity. System minimum is one virtual CPU * with 10 units of entitled capacity. */ ent_cap = parse_lparcfg("partition_entitled_capacity"); if (ent_cap <= min_ent_cap) { log_msg(event, "A request was received to deallocate " "entitled capacity due to a predictive CPU " "failure. The request cannot be carried out " "because this partition is already at the " "minimum allowable entitled capacity"); return; } n_cpus = parse_lparcfg("partition_active_processors"); if ((ent_cap - ent_loss) < min_ent_cap) { ent_loss = ent_cap - min_ent_cap; } if ((ent_cap - ent_loss) < (n_cpus * min_ent_cap)) { /* need to deallocate virtual CPUs */ quant = (ent_cap - ent_loss)/10; run_drmgr(CPU_GUARD, NULL, quant, 1); log_msg(event, "A request was received to deallocate " "entitled capacity due to a predictive CPU " "failure. %d virtual CPUs were deallocated " "in order to fulfill this request", quant); platform_log_write("CPU Deallocation Notification\n"); platform_log_write("(resulting from a predictive CPU " "failure)\n"); platform_log_write(" number of virtual CPUs " "offlined: %d\n", quant); platform_log_write(" number of virtual CPUs " "remaining: %d\n", n_cpus - quant); snprintf(event->addl_text, ADDL_TEXT_MAX, "Predictive CPU Failure: deallocated %d " "virtual CPUs", quant); } run_drmgr(SP_CPU_GUARD, NULL, ent_loss, 0); log_msg(event, "Entitled capacity in the amount of %d has been " "offlined due to the reporting of a predictive CPU " "failure", ent_loss); platform_log_write("Entitled Capacity Deallocation " "Notification\n"); platform_log_write("(resulting from a predictive CPU failure)\n"); platform_log_write(" entitled capacity units offlined: " "%d\n", ent_loss); platform_log_write(" entitled capacity units remaining: " "%d\n", ent_cap - ent_loss); snprintf(event->addl_text, ADDL_TEXT_MAX, "Predictive CPU Failure: deallocated %d entitled " "capacity units", ent_loss); return; } /** * guard_mempage * @brief Perform mempage guard operation. Currently not supported. * * A placeholder function. This dealloc type operation is currently * not supported. MEMPAGE events cannot be guarded at present. * * @param event rtas event. * @param memory address page that needs to be de-allocated. */ static void guard_mempage( struct event *event, uint64_t memory_address) { log_msg(event, "A request was received to deallocate a memory page, " "which is not currently a supported operation."); return; } /** * guard_memlmb * @brief Perform lmb guard operation after proper validation * * parses error information to determine the lmb that requires * guarding operation. At this time only MEMLMB operations may * be guarded. DRMGR_PROGRAM is forked to actually remove * the LMB from the system. * * @param event rtas event * @param drc index to be guarded. */ static void guard_memlmb(struct event *event, unsigned int drc_index) { char drc_name[30]; /* check to make sure there is more than one lmb to delete */ if (can_delete_lmb()==FALSE) { log_msg(event, "A request was received to deallocate a " "LMB partition due to a predictive MEM failure " "The request cannot be carried out because " "there is only one LMB on this system"); return; } if (!retrieve_drc_name(MEMTYPE, event, drc_index, drc_name, 30)) { log_msg(event, "A LMB could not be guarded off in " "response to a received predictive MEM " "failure event 0x%08x", drc_index); return; } run_drmgr(MEM_LMB, drc_name, 0,0); log_msg(event, "The following LMB has been offlined due to the " "reporting of a predictive memory failure:" "0x%08x, drc-name %s", drc_index, drc_name); platform_log_write("MEM Deallocation Notification\n"); platform_log_write("(resulting from a predictive MEM failure)\n"); platform_log_write(" Logical ID: 0x%08x\n", drc_index); platform_log_write(" drc-name: %s\n", drc_name); snprintf(event->addl_text, ADDL_TEXT_MAX, "Predictive MEM Failure: deallocated LMB ID %u " "(drc-name \"%s\")", drc_index, drc_name); return; } /** * handle_resource_dealloc * @brief Parse RTAS event for CPU guard information. * * Parses error information to determine if it represents a predictive CPU * failure, which should cause a CPU Guard operation. DRMGR_PROGRAM is * forked to actually remove the CPU from the system. * * @param event rtas event */ void handle_resource_dealloc(struct event *event) { struct rtas_event_hdr *rtas_hdr = event->rtas_hdr; struct rtas_event_exthdr *exthdr; struct rtas_cpu_scn *cpu; struct rtas_lri_scn *lri; uint64_t address_range; /* * The following conditional is to handle pre-v6 predictive CPU * failure events; it has been designed to specification, but has * not been tested. version 1 to 5. */ if (rtas_hdr->severity == RTAS_HDR_SEV_WARNING && rtas_hdr->disposition == RTAS_HDR_DISP_FULLY_RECOVERED && rtas_hdr->extended && rtas_hdr->initiator == RTAS_HDR_INIT_CPU && rtas_hdr->type == RTAS_HDR_TYPE_CACHE_PARITY && rtas_hdr->version < 6) { /* Check extended error information */ exthdr = rtas_get_event_exthdr_scn(event->rtas_event); cpu = rtas_get_cpu_scn(event->rtas_event); if (cpu == NULL) { log_msg(event, "Could not retrieve CPU section to " "check for a CPU guard event"); return; } if (exthdr->unrecoverable_bypassed && exthdr->predictive && exthdr->power_pc && cpu->extcache_ecc) { guard_cpu(event, cpu->id); } } if (rtas_hdr->version >= 6) { if (rtas_hdr->type == RTAS_V6_TYPE_RESOURCE_DEALLOC) { lri = rtas_get_lri_scn(event->rtas_event); if (lri == NULL) { log_msg(event, "Could not retrieve a Logical " "Resource Identification section from " "a v6 event to determine the resource " "to be deallocated"); return; } switch (lri->resource) { case RTAS_LRI_RES_PROC: /* invoke a CPU guard operation */ guard_cpu(event, lri->lri_cpu_id); break; case RTAS_LRI_RES_SHARED_PROC: /* shared processor CPU guard operation */ guard_spcpu(event, lri->capacity); break; case RTAS_LRI_RES_MEM_PAGE: /* Mem page remove operation */ address_range = lri->lri_mem_addr_hi; address_range <<= 32; address_range |= lri->lri_mem_addr_lo; guard_mempage(event, address_range); break; case RTAS_LRI_RES_MEM_LMB: /* LMB remove operation */ guard_memlmb(event, lri->lri_drc_index); break; } } } }
18,184
C
.c
563
29.323268
81
0.677868
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,713,582
config.c
power-ras_ppc64-diag/rtas_errd/config.c
/** * @file config.c * @brief Routines for parsing the ppc64-diag.config file * * Copyright (C) 2004 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <time.h> #include <stdarg.h> #include <string.h> #include <ctype.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/wait.h> #include <librtas.h> #include "config.h" #define RTAS_PARAM_AUTO_RESTART 21 /** * @var config_file * @brief default ppc64-diag configuration file */ char *config_file = "/etc/ppc64-diag/ppc64-diag.config"; /** * @var d_cfg * @brief ppc64-diag configuration structure */ struct ppc64_diag_config d_cfg; /** * get_token * @brief return the next token from the provided buffer. * * This routine is modified parser/tokenizer for interpreting the * ppc64-diag config file. * * @param str point at which to began looking for tokens * @param str_end end of token buffer * @param tok buffer to be filled in with the found token * @param line_no reference to line number in the config file * @return pointer to where the tokenizer stopped in 'str' */ static char * get_token(char *str, char *str_end, char *tok, int *line_no) { char *start = NULL; while (str < str_end) { switch (*str) { case '#': /* A '#' denotes the beginning of a comment that * continues to the end of the line ('\n') * character. Skip ahead to the next line and * continue searching. */ while ((str < str_end) && (*str++ != '\n')); (*line_no)++; break; case '\\': /* A '\' denotes a multi-line string. If we haven't * started a string yet simply skip ahead to the next * line and continue searching... */ if (start == NULL) { while ((str < str_end) && (*str++ != '\n')); (*line_no)++; break; } /* ...Otherwise, return the token we have already * started then skip ahead to the next line and * return that point as the end of the search. */ snprintf(tok, str - start + 1, "%s", start); while ((str < str_end) && (*str++ != '\n')); (*line_no)++; return str; break; case ' ': case '\t': /* Whitespace is either is token delimiter if we * have started reading a token, or it is igored. */ if (start == NULL) { str++; break; } snprintf(tok, str - start + 1, "%s", start); return str + 1; break; case '\n': /* Newlines are either token delimiters if we * have started reading a token, or a separate token * on its own. */ if (start == NULL) { tok[0] = '\n'; tok[1] = '\0'; (*line_no)++; str++; } else { snprintf(tok, str - start + 1, "%s", start); } return str; break; case '{': case '}': case '=': /* All three ('{', '}', and '=') are both token * delimiters if we have started reading a token or * a token on their own. */ if (start == NULL) { snprintf(tok, 2, "%s", str); str++; } else { snprintf(tok, str - start + 1, "%s", start); } return str; break; case '"': /* A quoted string is returned as a single token * containing everything in quotes, or a token * delimiter if we have begun reading in a token. * NOTE, we do not allow quoted strings the span * multiple lines. */ if (start == NULL) { start = str++; while ((str < str_end) && (*str != '"')) { if (*str == '\n') return NULL; else str++; } snprintf(tok, str - start + 1, "%s", start); str++; } else { snprintf(tok, str - start + 1, "%s", start); } return str; break; default: /* By default everything else is part of a token */ if (start == NULL) start = str; str++; break; } } return (char *)EOF; } /** * get_config_string * @brief retrieve a string associated with a configuration entry * * For the purposes of parsing the ppc64-diag config file a string is * considered everything that comes after the '=' character up to * the newline ('\n') character. Strings can span multiple lines * if they end in a '\', but this is handled by get_token() and we * only need to look for the newline character here. * * @param start should point to the '=' following an entry name * @param end end of buffer containing the string * @param buf buffer into which the string is copied * @param line_no reference to the line number in the config file * @return pointer to where we stopped parsing or NULL on failure */ static char * get_config_string(char *start, char *end, char *buf, int *line_no) { char tok[1024]; int offset = 0; /* The first token token should be '=' */ start = get_token(start, end, tok, line_no); if ((start == NULL) || (tok[0] != '=')) return NULL; /* Next token should be the string, this string can be a series * of tokens or one string in quotes. We just get everything up * to the newline. The code looks a bit odd here, but that is so * we can add in spaces between tokens which are ignored by the * tokenizer. */ start = get_token(start, end, tok, line_no); if (start == NULL) return NULL; offset += sprintf(buf, "%s", tok); start = get_token(start, end, tok, line_no); while ((start != NULL) && (tok[0] != '\n')) { offset += sprintf(buf + offset, " %s", tok); start = get_token(start, end, tok, line_no); } return start; } /** * get_config_num * @brief Retrieve a numeric value for a configuration entry * * @param start should point to the '=' following an entry name * @param end end of buffer containing thevalue * @param val int reference into which the value is copied * @param line_no reference to the line number in the config file * @return pointer to where we stopped parsing or NULL on failure */ static char * get_config_num(char *start, char *end, int *val, int *line_no) { char tok[1024]; /* The first token should be '=' */ start = get_token(start, end, tok, line_no); if ((start == NULL) || (tok[0] != '=')) return NULL; /* Next token should be the value */ start = get_token(start, end, tok, line_no); if (start != NULL) *val = ((int)strtol(tok, NULL, 10) > 1 ? (int)strtol(tok, NULL, 10) : 1); return start; } /** * get_restart_policy_value * @brief Retrieve Auto Restart Policy value * * Same as get_config_num(), except we handle 0 and negative * values here. */ static char * get_restart_policy_value(char *start, char *end, int *val, int *line_no) { char tok[1024]; char *next_char; /* The first token should be '=' */ start = get_token(start, end, tok, line_no); if ((start == NULL) || (tok[0] != '=')) return NULL; /* Next token should be the value */ start = get_token(start, end, tok, line_no); if (start != NULL) { *val = (int)strtol(tok, &next_char, 10); if (*next_char != '\0') *val = -1; } return start; } /** * config_restart_policy * @brief Configure the Auto Restart Policy for this machine, if present. * * Users can specify an AutoRestartPolicy=X entry in the ppc64-diag * configuration file. This will read in that 'X' value and set the * corresponding service policy. This is done either by setting the * ibm,os-auto-restart parameter in NVRAM (older systems), or by setting * the partition_auto_restart system parameter (more recent systems). * * @param start place to start loking * @param end pointer to end of 'start' buffer * @param line_no refernece to the current line number * @param update_param if zero, the param will not actually be updated * @returns pointer to current position in the config file, or NULL on failure */ static char * config_restart_policy(char *start, char *end, int *line_no, int update_param) { struct stat sbuf; char *cur; char param[3]; pid_t cpid; /* Pid of child */ int rc; /* Holds return value */ int status; /* exit value of child */ cur = get_restart_policy_value(start, end, &d_cfg.restart_policy, line_no); if (cur == NULL) { d_cfg.log_msg("Parsing error for configuration file " "entry \"AutoRestartPolicy\", " "line %d", line_no); return cur; } /* Validate the restart value */ if (! (d_cfg.restart_policy == 0 || d_cfg.restart_policy == 1)) { d_cfg.log_msg("Invalid parameter (%d) specified for the " "AutoRestartPolicy (line %d) in config file " "(%s), expecting a 0 or a 1. The Auto Restart " "Policy has not been configured", d_cfg.restart_policy, *line_no, config_file); d_cfg.restart_policy = -1; return cur; } if (!update_param) return cur; /* Try to set the system parameter with the ibm,set-sysparm RTAS call */ *(uint16_t *)param = htobe16(1); param[2] = (uint8_t)d_cfg.restart_policy; rc = rtas_set_sysparm(RTAS_PARAM_AUTO_RESTART, param); switch (rc) { case 0: /* success */ d_cfg.log_msg("Configuring the Auto Restart Policy to %d", d_cfg.restart_policy); return cur; case -1: /* hardware error */ d_cfg.log_msg("Hardware error while attempting to set the " "Auto Restart Policy via RTAS; attempting " "to set in NVRAM..."); break; case RTAS_UNKNOWN_OP: /* RTAS call not available */ break; case -3: /* system parameter not supported */ break; case -9002: /* not authorized */ d_cfg.log_msg("Not authorized to set the Auto Restart Policy " "via RTAS; attempting to set in NVRAM..."); break; case -9999: /* parameter error */ d_cfg.log_msg("Parameter error setting the Auto Restart Policy " "via RTAS; attempting to set in NVRAM..."); break; default: d_cfg.log_msg("Unknown error (%d) setting the Auto Restart " "Policy via RTAS; attempting to set in NVRAM...", rc); } /* If the auto_partition_restart system parameter does not * exist, check if the nvram command exists */ if (stat("/usr/sbin/nvram", &sbuf) < 0) { d_cfg.log_msg("Could not configure the Auto Restart Policy " "due to a missing requisite (nvram command)"); d_cfg.restart_policy = -1; return cur; } /* See if the ibm,os-auto-restart config variable is in * nvram on this machine */ cpid = fork(); if (cpid == -1) { d_cfg.log_msg("Fork failed, while collecting ibm,os-auto-restart\n"); d_cfg.restart_policy = -1; return cur; } /* fork */ if (cpid == 0) { /* child */ char *system_arg[3]= {NULL, }; system_arg[0] = "/usr/sbin/nvram"; system_arg[1] = "--print-config=ibm,os-auto-restart"; rc = execv(system_arg[0], system_arg); d_cfg.log_msg("The current system does not support the " "Auto Restart Policy; the AutoRestartPolicy " "configuration entry (line %d) is being skipped", line_no); d_cfg.restart_policy = -1; exit(-2); } else {/* parent */ /* * Use wait to make sure we do not update ibm,os-restart-policy, * before reading ibm,os-auto-restart. */ rc = waitpid(cpid, &status, 0); if (rc == -1) { d_cfg.log_msg("wait failed, while collecting" " ibm,os-auto-restart\n"); d_cfg.restart_policy = -1; return cur; } if ((signed char)WEXITSTATUS(status) == -2) return cur; } cpid = fork(); if (cpid == -1) { d_cfg.log_msg("Fork failed, on updating ibm,os-restart-policy\n"); d_cfg.restart_policy = -1; return cur; } /* fork */ if (cpid == 0) { /* child */ char *system_arg[6]= {NULL,}; char tmp_sys_arg[50]; system_arg[0] = "/usr/sbin/nvram"; system_arg[1] = "-p"; system_arg[2] = "common"; system_arg[3] = "--update-config"; sprintf(tmp_sys_arg, "ibm,os-restart-policy=%d", d_cfg.restart_policy); system_arg[4] = tmp_sys_arg; rc = execv(system_arg[0], system_arg); d_cfg.log_msg("The Auto Restart Policy could not be configured " "due to a failure in running the nvram command", d_cfg.restart_policy); d_cfg.restart_policy = -1; exit(-2); } else { /* parent */ rc = waitpid(cpid, &status, 0); if (rc == -1) { d_cfg.log_msg("wait failed, on updating ibm,os-restart-policy\n"); d_cfg.restart_policy = -1; return cur; } /* Return on EXIT_FAILURE */ if ((signed char)WEXITSTATUS(status) == -2) return cur; } d_cfg.log_msg("Configuring the Auto Restart Policy to %d (in NVRAM)", d_cfg.restart_policy); return cur; } /** * parse_config_entries * @brief Parse the ppc64-diag config file entries * * @param buf buffer containg the ppc64-diag config file contents * @param buf_end pointer to the end of 'buf' * @param update_sysconfig if 0, configuration params (in NVRAM) will not update * @returns 0 on success, -1 on error */ static int parse_config_entries(char *buf, char *buf_end, int update_sysconfig) { char *cur = buf; char tok[1024]; int line_no = 1; int rc = 0; do { cur = get_token(cur, buf_end, tok, &line_no); if (cur == (char *)EOF) break; if (cur == NULL) { d_cfg.log_msg("Parsing error in configuration " "file near line %d", line_no); rc = -1; break; } /* Ignore newlines */ if (tok[0] == '\n') { continue; } /* MinProcessors */ if (strcmp(tok, "MinProcessors") == 0) { cur = get_config_num(cur, buf_end, &d_cfg.min_processors, &line_no); if (cur == NULL) { d_cfg.log_msg("Parsing error for " "configuration file entry " "\"MinProcessors\", line %d", line_no); rc = -1; break; } else { d_cfg.log_msg("Configuring Minimum " "Processors to %d", d_cfg.min_processors); } /* MinEntitledCapacity */ } else if (strcmp(tok, "MinEntitledCapacity") == 0) { cur = get_config_num(cur, buf_end, &d_cfg.min_entitled_capacity, &line_no); if (cur == NULL) { d_cfg.log_msg("Parsing error for " "configuration file entry " "\"MinEntitledCapacity\", " "line %d", line_no); rc = -1; break; } else { d_cfg.log_msg("Configuring Minimum " "Entitled Capacity to %d", d_cfg.min_entitled_capacity); } /* ScanlogDumpPath */ } else if (strcmp(tok, "ScanlogDumpPath") == 0) { int len; cur = get_config_string(cur, buf_end, d_cfg.scanlog_dump_path, &line_no); if (cur == NULL) { d_cfg.log_msg("Parsing error for " "configuration file entry " "\"ScanlogDumpPath\", line %d", line_no); rc = -1; break; } /* We need to ensure the path specified ends in a '/' */ len = strlen(d_cfg.scanlog_dump_path); if (d_cfg.scanlog_dump_path[len-1] != '/') { d_cfg.scanlog_dump_path[len] = '/'; d_cfg.scanlog_dump_path[len + 1] = '\0'; } d_cfg.log_msg("Configuring Scanlog Dump Path to " "\"%s\"", d_cfg.scanlog_dump_path); /* PlaformDumpPath */ } else if (strcmp(tok, "PlatformDumpPath") == 0) { int len; cur = get_config_string(cur, buf_end, d_cfg.platform_dump_path, &line_no); if (cur == NULL) { d_cfg.log_msg("Parsing error for " "configuration file entry " "\"PlatformDumpPath\", line %d", line_no); rc = -1; break; } /* We need to ensure the path specified ends in a '/' */ len = strlen(d_cfg.platform_dump_path); if (d_cfg.platform_dump_path[len-1] != '/') { d_cfg.platform_dump_path[len] = '/'; d_cfg.platform_dump_path[len + 1] = '\0'; } d_cfg.log_msg("Configuring Platform Dump Path to " "\"%s\"", d_cfg.platform_dump_path); /* AutoRestartPolicy */ } else if (strcmp(tok, "AutoRestartPolicy") == 0) { cur = config_restart_policy(cur, buf_end, &line_no, update_sysconfig); if (cur == NULL) { rc = -1; break; } } else { d_cfg.log_msg("Configuration error: \"%s\", line %d, " "is not a valid configuration name", tok, line_no); rc = -1; break; } } while ((cur != NULL) && (cur < buf_end)); return rc; } /** * init_d_cfg * @brief initialize the ppc64-diag config structure */ static void init_d_cfg(void (*log_msg)(char *, ...)) { d_cfg.min_processors = 1; d_cfg.min_entitled_capacity = 5; strcpy(d_cfg.scanlog_dump_path, "/var/log/"); strcpy(d_cfg.platform_dump_path, "/var/log/dump/"); d_cfg.restart_policy = -1; d_cfg.log_msg = log_msg; }; /** * diag_cfg * @brief read config components from ppc64-diag config file * * The config file is in the format of variable=data. Comments * in the file are lines beginning with '#' or everything after a '#' * character in a line. * * @param update_sysconfig if 0, NVRAM will not be updated */ int diag_cfg(int update_sysconfig, void (*log_msg)(char *, ...)) { struct stat cfg_sbuf; char *cfg_mmap = NULL; char *cur = NULL, *end; int cfg_fd; /* initialize the configuration variables */ init_d_cfg(log_msg); /* open and map the configuration file */ if ((cfg_fd = open(config_file, O_RDONLY)) < 0) { d_cfg.log_msg("Could not open the ppc64-diag configuration " "file \"%s\", %s", config_file, strerror(errno)); return 0; } if ((fstat(cfg_fd, &cfg_sbuf)) < 0) { d_cfg.log_msg("Could not get status of the ppc64-diag " "configuration file \"%s\", %s. No configuration " "data has been read, using default ppc64-diag " "settings", config_file, strerror(errno)); close(cfg_fd); return 0; } /* If this is a zero-length file, do nothing */ if (cfg_sbuf.st_size == 0) { close(cfg_fd); return 0; } if ((cfg_mmap = mmap(0, cfg_sbuf.st_size, PROT_READ, MAP_PRIVATE, cfg_fd, 0)) == (char *)-1) { d_cfg.log_msg("Could not map ppc64-diag configuration file " "\"%s\", %s. No configuration data has been " "read, using default ppc64-diag settings", config_file, strerror(errno)); close(cfg_fd); return 0; } cur = cfg_mmap; end = cfg_mmap + cfg_sbuf.st_size; if (parse_config_entries(cur, end, update_sysconfig)) { d_cfg.log_msg("Due to an error parsing the ppc64-diag " "configuration file, The default configuration " "settings will be used"); init_d_cfg(log_msg); } munmap(cfg_mmap, cfg_sbuf.st_size); close(cfg_fd); return 0; }
18,843
C
.c
616
26.800325
81
0.637773
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,583
diag_support.c
power-ras_ppc64-diag/rtas_errd/diag_support.c
/** * @file diag_support.c * * Copyright (C) 2005, 2008 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <errno.h> #include <ctype.h> #include <librtas.h> #include <sys/types.h> #include <sys/wait.h> #include "utils.h" #include "rtas_errd.h" #define CMD_LSVPD "/usr/sbin/lsvpd" char target_status[80]; void free_diag_vpd(struct event *event) { if (event->diag_vpd.ds != NULL) { free(event->diag_vpd.ds); event->diag_vpd.ds = NULL; } if (event->diag_vpd.yl != NULL) { free(event->diag_vpd.yl); event->diag_vpd.yl = NULL; } if (event->diag_vpd.fn != NULL) { free(event->diag_vpd.fn); event->diag_vpd.fn = NULL; } if (event->diag_vpd.sn != NULL) { free(event->diag_vpd.sn); event->diag_vpd.sn = NULL; } if (event->diag_vpd.se != NULL) { free(event->diag_vpd.se); event->diag_vpd.se = NULL; } if (event->diag_vpd.tm != NULL) { free(event->diag_vpd.tm); event->diag_vpd.tm = NULL; } } /* * Execute the 'lsvpd' command and open a pipe to read the data */ static int lsvpd_init(FILE **fp, pid_t *cpid) { char *system_args[2] = {CMD_LSVPD, NULL,}; /* execv arguments */ dbg("start lsvpd_init"); *fp = spopen(system_args, cpid); if (!*fp) { perror("popen"); dbg("lsvpd_init failed popen (%s)", CMD_LSVPD); return -1; } dbg("end lsvpd_init"); return 0; } /* * Close the open a pipe on 'lsvpd'. */ static int lsvpd_term(FILE *fp, pid_t *cpid) { int rc = 0; char line[512]; /* If pipe was opened read all vpd */ /* entries until pipe is empty. */ if (fp) { while (fgets(line, sizeof(line), fp)); rc = spclose(fp, *cpid); } return rc; } /* * Read the next lsvpd keyword, value pair */ static int lsvpd_read(struct event *event, FILE *fp) { int rc = 1; char line[512]; dbg("start lsvpd_read"); if (!fp) return rc; /* clear all residual data */ free_diag_vpd(event); while (fgets(line, sizeof(line), fp)) { if (line[strlen(line) - 1] == '\n') line[strlen(line) - 1] = '\0'; if (! strncmp(line, "*DS", 3)) { event->diag_vpd.ds = malloc(strlen (line) + 1); if (event->diag_vpd.ds == NULL) return rc; strcpy(event->diag_vpd.ds, &line[4]); dbg("found DS: \"%s\"", event->diag_vpd.ds); } if (! strncmp(line, "*YL", 3)) { event->diag_vpd.yl = malloc(strlen (line) + 1); if (event->diag_vpd.yl == NULL) return rc; strcpy(event->diag_vpd.yl, &line[4]); dbg("found YL: \"%s\"", event->diag_vpd.yl); } if (! strncmp(line, "*FN", 3)) { event->diag_vpd.fn = malloc(strlen (line) + 1); if (event->diag_vpd.fn == NULL) return rc; strcpy(event->diag_vpd.fn, &line[4]); dbg("found FN: \"%s\"", event->diag_vpd.fn); } if (! strncmp(line, "*SN", 3)) { event->diag_vpd.sn = malloc(strlen (line) + 1); if (event->diag_vpd.sn == NULL) return rc; strcpy(event->diag_vpd.sn, &line[4]); dbg("found SN: \"%s\"", event->diag_vpd.sn); } if (! strncmp(line, "*SE", 3)) { event->diag_vpd.se = malloc(strlen (line) + 1); if (event->diag_vpd.se == NULL) return rc; strcpy(event->diag_vpd.se, &line[4]); dbg("found SE: \"%s\"", event->diag_vpd.se); } if (! strncmp(line, "*TM", 3)) { event->diag_vpd.tm = malloc(strlen (line) + 1); if (event->diag_vpd.tm == NULL) return rc; strcpy(event->diag_vpd.tm, &line[4]); dbg("found TM: \"%s\"", event->diag_vpd.tm); } if (! strncmp(line, "*FC", 3)) { /* start of next record */ dbg("found FC - start next record"); return 0; } } dbg("end lsvpd_read"); return 1; } int get_diag_vpd(struct event *event, char *phyloc) { int rc = 0; FILE *fp = NULL; pid_t cpid; /* child pid */ dbg("start get_diag_vpd"); if (event->diag_vpd.yl != NULL) free_diag_vpd(event); /* sigchld_handler() messes up pclose(). */ restore_sigchld_default(); if (lsvpd_init(&fp, &cpid) != 0) { setup_sigchld_handler(); return 1; } while (event->diag_vpd.yl == NULL || strcmp(event->diag_vpd.yl, phyloc)) { if (lsvpd_read(event, fp)) { dbg("end get_diag_vpd, failure"); rc = lsvpd_term(fp, &cpid); setup_sigchld_handler(); return 1; } } rc = lsvpd_term(fp, &cpid); if (rc) dbg("end get_diag_vpd, pclose failure"); else dbg("end get_diag_vpd, success"); setup_sigchld_handler(); return rc; } char * get_dt_status(char *dev) { FILE *fp1 = NULL, *fp2 = NULL; char loc_file[80]; char target[80]; char *ptr; char *system_args[6] = {NULL, }; /* execv args */ char tmp_file[] = "/tmp/get_dt_files-XXXXXX"; int fd; pid_t cpid; /* child pid */ int rc; /* return value */ int status; /* child exit status */ int len = 0; system_args[0] = "/usr/bin/find"; system_args[1] = "/proc/device-tree"; system_args[2] = "-name"; system_args[3] = "status"; system_args[4] = "-print"; fd = mkstemp(tmp_file); if (fd == -1) { log_msg(NULL, "tmp file creation failed, at " "get_dt_status\n"); exit (-2); } /* open */ cpid = fork(); if (cpid == -1) { close(fd); log_msg(NULL, "Fork failed, at get_dt_status\n"); return NULL; } /* fork */ if (cpid == 0) { /* child */ int fd = open(tmp_file, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR); if (fd == -1) { log_msg(NULL, "tmp file creation failed, at " "get_dt_status\n"); exit (-2); } /* open */ rc = dup2(fd, STDOUT_FILENO); if (rc == -1) { log_msg(NULL, "STDOUT redirection failed, at " "get_dt_status\n"); close(fd); exit (-2); } rc = execv(system_args[0], system_args); log_msg(NULL, "get_dt_status find command failed\n"); close(fd); exit (-2); } else { /* parent */ close(fd); rc = waitpid(cpid, &status, 0); if (rc == -1) { log_msg(NULL, "wait on child failed at, " "get_dt_status\n"); return NULL; } /* waitpid */ /* Return on EXIT_FAILURE */ if ((signed char)WEXITSTATUS(status) == -2) return NULL; } /* results of the find command */ fp1 = fopen(tmp_file, "r"); if (fp1 == NULL) { fprintf(stderr, "open failed on %s\n", tmp_file); return NULL; } while (fscanf (fp1, "%s", loc_file) != EOF) { dbg("read from /%s, \"%s\"", tmp_file, loc_file); /* read the status in case this is the one */ fp2 = fopen(loc_file, "r"); if (fp2 == NULL) { fprintf(stderr, "open failed on %s\n", loc_file); goto out; } if (fscanf(fp2, "%s", target_status) != EOF) { dbg("target_status = \"%s\", loc_file = \"%s\"", target_status, loc_file); } else { fprintf(stderr, "read failed on %s\n", loc_file); goto out; } fclose(fp2); fp2 = NULL; /* read the loc-code file to determine if found dev */ ptr = strstr(loc_file, "status"); if (!ptr) continue; len = strlen("ibm,loc-code"); if ((ptr - loc_file + len + 1) > sizeof(loc_file)) continue; strncpy(ptr, "ibm,loc-code", len); ptr[len] = '\0'; fp2 = fopen(loc_file, "r"); if (fp2 == NULL) { fprintf(stderr, "open failed on %s\n", loc_file); goto out; } if (fscanf(fp2, "%s", target) != EOF) { dbg("target = \"%s\", loc_file = \"%s\"", target, loc_file); if (strcmp(dev, target) == 0) { dbg("status = \"%s\"", target_status); fclose (fp2); fclose (fp1); return target_status; } } else { fprintf(stderr, "read failed on %s\n", loc_file); goto out; } fclose(fp2); fp2 = NULL; } fprintf(stderr, "error: status NOT FOUND\n"); out: if (fp2) fclose(fp2); if (fp1) fclose(fp1); return NULL; } /** * is_integrated * @brief This function determines if the device is an integrated device or not. * * RETURNS: * 0 - Not integrated * 1 - Is integrated * -1 - System error obtaining data * */ int is_integrated(char *phy_loc) { int rc; int index = -1; dbg("phy_loc = \"%s\"", phy_loc); rc = 0; index = strlen(phy_loc); /* Start at the end of the location code looking for */ /* a slash or a dash. If the beginning of the */ /* location code is reached without finding either, */ /* then the resource is not integrated. */ while (index > 0) { if (phy_loc[index] == '/') { dbg("found slash, resource may be integrated"); index--; /* Now find planar. Only allowable */ /* characters between here and 'P' */ /* are numerics and '.' */ while (index >= 0) { if (phy_loc[index] == 'P') { rc = 1; break; } else if (phy_loc[index] == '.') index--; else if (phy_loc[index] >= '0' && phy_loc[index] <= '9') index--; else { rc = 0; break; } } break; } if (phy_loc[index] == '-') { dbg("found dash, so resource is not integrated"); rc = 0; break; } index--; } /* while index > 0 */ return rc; } /** * get_base_loc * * FUNCTION: Reduce the given location code to the base physical FRU, thus * removing the extended functional location information. Currently * this works for CHRP physical location codes, but will need to * updated for converged location codes. */ void get_base_loc(char *phyloc, char *base) { /* Char by char copy until reaching a slash ('/) or the end */ while (*phyloc != 0 && *phyloc != '/') { *base = *phyloc; base++; phyloc++; } /* Now the terminating null */ *base = 0; } /** * diag_fru_pn_by_ploc * * Returns the FRU part number from VPD, as defined by the "FN" vpd keyword, * for the FRU given by the physical location code * * RETURNS: * 0 if not found information. * 1 if found information. * -1 if error found during search */ char * diag_get_fru_pn(struct event *event, char *phyloc) { char baseloc[80]; if (is_integrated(phyloc)) { /* Use the base location code */ get_base_loc(phyloc, baseloc); if (get_diag_vpd(event, baseloc)) return NULL; if (event->diag_vpd.fn == NULL) /* not found for base loc. code */ return NULL; } else { /* not integrated */ if (get_diag_vpd(event, phyloc)) return NULL; if (event->diag_vpd.fn == NULL) /* not found */ return NULL; } /* found for given location code */ return event->diag_vpd.fn; }
10,937
C
.c
426
22.584507
81
0.609934
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,604
files.c
power-ras_ppc64-diag/lpd/files.c
/** * @file files.c * @brief File manipulation routines * * Copyright (C) 2012 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @author Vasant Hegde <[email protected]> */ #include <stdio.h> #include <stdint.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <stdarg.h> #include <stdlib.h> #include <limits.h> #include <libgen.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <time.h> #include "indicator.h" /* Program name */ char *program_name; /* Indicator event log file/descriptor */ char *lp_event_log_file = "/var/log/indicators"; int lp_event_log_fd = -1; /* Log file/descriptor */ char *lp_error_log_file = "/var/log/lp_diag.log"; int lp_error_log_fd = -1; /** * reformat_msg - Re-format a log message to wrap at 80 characters * * In order to ease the formatting of messages in the lp_diag this * will automatically format the messages to wrap at 80 characters. * * @msg buffer containing the message to re-format * @size message size * * Returns : * new buffer length */ static int reformat_msg(char *msg, int size) { char buf[LP_ERROR_LOG_MAX]; char *pos; char *next; char temp; char temp2; int len = strlen(msg); if (len >= LP_ERROR_LOG_MAX) /* Insufficient temporary buffer size */ return len; if (len > (size - size / 80 + 1)) /* Worst case target size */ return len; if (len < 80) { /* no need to reformat */ msg[len++] = '\n'; return len; } memset(buf, 0, LP_ERROR_LOG_MAX); /* first copy the msg into our buffer */ memcpy(buf, msg, len); /* zero out the old buffer */ msg[0] = '\0'; pos = buf; while (strlen(pos) > 80) { next = pos + 80; do { if (*next == ' ') *next = '\n'; if (*next == '\n') { temp = *(next + 1); *(next + 1) = '\0'; strcat(msg, pos); *(next + 1) = temp; pos = next + 1; break; } next--; } while (next > pos); if (next == pos) { /* word is longer than line length */ next = pos + 79; temp = *next; temp2 = *(next + 1); *next = '\n'; *(next + 1) = '\0'; strcat(msg, pos); *next = temp; *(next + 1) = temp2; pos = next; } } /* while loop end */ strcat(msg, pos); len = strlen(msg); msg[len++] = '\n'; return len; } /** * insert_time - Insert current date and time */ static int insert_time(char *buf, int size) { int len; time_t cal; cal = time(NULL); len = snprintf(buf, size, "%s", ctime(&cal)); len--; /* remove new line character */ return len; } /** * _dbg - Write debug messages to stdout * * Provide utility to print debug statements if the debug flag * is specified. * * @fmt format string to printf() * @... additional argument */ void _dbg(const char *fmt, ...) { int len = 0; char buf[LP_ERROR_LOG_MAX]; va_list ap; /* * If LPD_DEBUG is set at compile time (e.g., make CFLAGS='-DLPD_DEBUG'), * then always write the messages at runtime. * If it's not (default), check if the LPD_DEBUG environment variable * is set at runtime (e.g., export LPD_DEBUG=1), and only write if it is. */ #ifndef LPD_DEBUG if (!getenv("LPD_DEBUG")) return; #endif va_start(ap, fmt); len = snprintf(buf, LP_ERROR_LOG_MAX, "DEBUG: "); len += vsnprintf(buf + len, LP_ERROR_LOG_MAX - len, fmt, ap); va_end(ap); if (len < 0 || len >= LP_ERROR_LOG_MAX) return; /* Insufficient buffer size */ fprintf(stdout, "%s", buf); fprintf(stdout, "\n"); fflush(stdout); } /** * log_msg - Write log message into lp_diag log file * * @fmt format string to printf() * @... additional argument */ void log_msg(const char *fmt, ...) { int rc; int len = 0; char buf[LP_ERROR_LOG_MAX]; va_list ap; #ifndef LPD_DEBUG /* In order to make testing easier we will not print time in * debug version of lp_diag. */ if (lp_error_log_fd != STDOUT_FILENO) { len = insert_time(buf, LP_ERROR_LOG_MAX); len += snprintf(buf + len, LP_ERROR_LOG_MAX - len, ": "); } #endif /* Add the actual message */ va_start(ap, fmt); len += vsnprintf(buf + len, LP_ERROR_LOG_MAX - len, fmt, ap); if (len < 0 || len >= LP_ERROR_LOG_MAX) { dbg("Insufficient buffer size"); va_end(ap); return; } va_end(ap); /* Add ending punctuation */ len += snprintf(buf + len, LP_ERROR_LOG_MAX - len, "."); if (lp_error_log_fd == -1) { dbg("Log file \"%s\" is not available", lp_error_log_file); _dbg(buf); return; } _dbg(buf); /* reformat the new message */ len = reformat_msg(buf, LP_ERROR_LOG_MAX); rc = write(lp_error_log_fd, buf, len); if (rc == -1) dbg("Write to log file \"%s\" failed", lp_error_log_file); } /** * indicator_log_write - write indicate events to log file * * @fmt format string to printf() * @... additional argument to printf() * * Returns : * return code from write() call */ int indicator_log_write(const char *fmt, ...) { int len; int rc = 0; char buf[LP_ERROR_LOG_MAX]; va_list ap; if (lp_event_log_fd == -1) { log_msg("Indicator event log file \"%s\" is not available", lp_event_log_file); return -1; } /* Add time */ len = insert_time(buf, LP_ERROR_LOG_MAX); len += snprintf(buf + len, LP_ERROR_LOG_MAX - len, ": %s : ", program_name); va_start(ap, fmt); len += vsnprintf(buf + len, LP_ERROR_LOG_MAX - len, fmt, ap); if (len < 0 || len >= LP_ERROR_LOG_MAX) { log_msg("Insufficient buffer size"); va_end(ap); return -1; } va_end(ap); /* Add ending punctuation */ len += snprintf(buf + len, LP_ERROR_LOG_MAX - len, "\n"); rc = write(lp_event_log_fd, buf, len); if (rc == -1) log_msg("Write to indicator event log file \"%s\" failed", lp_event_log_file); return rc; } /** * rotate_log_file - Check log file size and rotate if required. * * @lp_log_file log file name * * Returns : * nothing */ static void rotate_log_file(char *lp_log_file) { int rc; int dir_fd; char *dir_name; char lp_log_file0[PATH_MAX]; struct stat sbuf; rc = stat(lp_log_file, &sbuf); if (rc == -1) { dbg("Cannot stat log file to rotate logs"); return; } if (sbuf.st_size <= LP_ERRD_LOGSZ) return; _dbg("Rotating log file : %s", lp_log_file); snprintf(lp_log_file0, PATH_MAX, "%s0", lp_log_file); /* Remove old files */ rc = stat(lp_log_file0, &sbuf); if (rc == 0) { if (unlink(lp_log_file0)) { dbg("Could not delete archive file %s " "(%d: %s) to make a room for new archive." " The new logs will be logged anyway.", lp_log_file0, errno, strerror(errno)); return; } } rc = rename(lp_log_file, lp_log_file0); if (rc == -1) { dbg("Could not archive log file %s to %s (%d: %s)", lp_log_file, lp_log_file0, errno, strerror(errno)); return; } dir_name = dirname(lp_log_file0); dir_fd = open(dir_name, O_RDONLY | O_DIRECTORY); if (dir_fd == -1) { dbg("Could not open log directory %s (%d: %s)", dir_name, errno, strerror(errno)); return; } /* sync log directory */ rc = fsync(dir_fd); if (rc == -1) dbg("Could not sync log directory %s (%d: %s)", dir_name, errno, strerror(errno)); close(dir_fd); } /** * init_files - Open log files * * Returns : * 0 on success, !0 on failure */ int init_files(void) { int rc = 0; /* lp_diag log file */ if (lp_error_log_fd != STDOUT_FILENO) { /* 1 = stdout */ rotate_log_file(lp_error_log_file); lp_error_log_fd = open(lp_error_log_file, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR | S_IRGRP); if (lp_error_log_fd == -1) dbg("Could not open log file \"%s\"", lp_error_log_file); } /* open event log file */ rotate_log_file(lp_event_log_file); lp_event_log_fd = open(lp_event_log_file, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR | S_IRGRP); if (lp_event_log_fd == -1) { log_msg("Could not open indicator event log file \"%s\"", lp_event_log_file); return -1; } return rc; } /** * close_files - Close all the files used by lp_diag * * Perform any file cleanup (i.e. close()) and possibly free()'ing * buffers needed by log_diag before exiting. * * Returns : * nothing */ void close_files(void) { if (lp_error_log_fd > STDOUT_FILENO) /* don't close stdout */ close(lp_error_log_fd); if (lp_event_log_fd != -1) close(lp_event_log_fd); }
8,946
C
.c
352
22.9375
81
0.641143
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,607
indicator_marvell.h
power-ras_ppc64-diag/lpd/indicator_marvell.h
/** * Copyright (C) 2016 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef INDICATOR_MARVELL_H #define INDICATOR_MARVELL_H /* Marvell HDD LEDs (indicators) support */ extern void get_mv_indices(int, struct loc_code **); extern int get_mv_indicator(int, struct loc_code *, int *); extern int set_mv_indicator(int, struct loc_code *, int); #endif /* INDICATOR_MARVELL_H */
1,074
C
.c
24
42.958333
81
0.756447
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,608
indicator_ses.c
power-ras_ppc64-diag/lpd/indicator_ses.c
/** * @file indicator_ses.c * @brief SES indicator manipulation routines * * Copyright (C) 2012 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @author Vasant Hegde <[email protected]> */ #define _GNU_SOURCE #define _GNU_SOURCE #include <unistd.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <dirent.h> #include <limits.h> #include <sys/types.h> #include <sys/wait.h> #include "utils.h" #include "indicator.h" #include "lp_util.h" /* SES LED command name */ #define SCSI_INDICATOR_CMD "/usr/sbin/encl_led" /* SES sys path */ #define SCSI_SES_PATH "/sys/class/enclosure" /* * Some versions of iprconfig/lscfg report the location code of the ESM/ERM * -- e.g., UEDR1.001.G12W34S-P1-C1. For our purposes, we usually don't want * the -P1-C1. (Don't trim location codes for disks and such.) * * TODO: This adjustment is appropriate for Bluehawks. Need to understand * what, if anything, needs to be done for other (e.g. Pearl) enclosures. */ static void trim_location_code(struct dev_vpd *vpd) { char *hyphen; hyphen = strchr(vpd->location, '-'); if (hyphen && (!strcmp(hyphen, "-P1-C1") || !strcmp(hyphen, "-P1-C2"))) *hyphen = '\0'; } /** * read_ses_vpd - Read SES device vpd data * * Returns : * vpd structure on success, NULL on failure */ static struct dev_vpd * read_ses_vpd(void) { char *path = NULL; DIR *dir; struct dirent *dirent; struct dev_vpd *vpd = NULL; struct dev_vpd *v1; /* get enclosure vpd data */ vpd = read_device_vpd(SCSI_SES_PATH); if (!vpd) return NULL; for (v1 = vpd; v1; v1 = v1->next) { /* remove ESM/ERM part of location code */ trim_location_code(v1); /* read sg name */ if (asprintf(&path, "%s/%s/device/scsi_generic", SCSI_SES_PATH, v1->dev) < 0) return NULL; dir = opendir(path); if (!dir) { log_msg("Unable to open directory : %s", path); free(path); continue; } free(path); /* fill sg device name */ while ((dirent = readdir(dir)) != NULL) { if (!strcmp(dirent->d_name, ".") || !strcmp(dirent->d_name, "..")) continue; strncpy(v1->dev, dirent->d_name, DEV_LENGTH - 1); v1->dev[DEV_LENGTH - 1] = '\0'; } closedir(dir); } return vpd; } /** * Helper functions to parse encl_led command output SES LED's. * * Ex : * Listing the particular enclosure indicator list: * encl_led -v -l sgN [component] : * fault ident location description * off off P1-E1 left power supply * off off P1-E2 right power supply * * Modify fault/identify indicator. * encl_led -{i|f} {on|off} sgN [component] */ /** * get_relative_fru_location - split location code * * Get FRU location code relative to the enclosure location code. * Ex : If an enclosure has location code U5888.001.G123789, and one * of its diks has a full location code U5888.001.G123789-P1-D1, * then relatvie FRU location code would be P1-D1. * */ static char * get_relative_fru_location(const char *loccode) { char *fru_loc; fru_loc = strchr(loccode, '-'); if (!fru_loc) return NULL; fru_loc++; /* skip - */ return fru_loc; } /** * get_ses_fru_desc - Parse SES FRU description * * Returns : * FRU description on success, NULL on failure */ static char * get_ses_fru_desc(char *buf) { if (!buf) return NULL; while (*buf == ' ') buf++; return buf; } /** * get_ses_fru_location - Parse SES FRU location * * Returns : * Relative FRU location code on success, NULL on failure */ static char * get_ses_fru_location(char *buf) { char *fru; char *space; fru = strchr(buf, 'P'); if (!fru) { fru = strchr(buf, '-'); /* Enclosure location code */ if (!fru) return NULL; } space = strchr(fru, ' '); if (!space) return NULL; *space = '\0'; return fru; } /** * get_ses_fru_identify_state - Get FRU identify indicator state * * Returns : * Indicator state on success, -1 on failure */ static int get_ses_fru_identify_state(const char *buf) { char *fault; char *ident; fault = strchr(buf, 'o'); if (!fault) return -1; fault++; ident = strchr(fault, 'o'); if (!ident) return -1; return !strncmp(ident, "on", 2); } /** * get_ses_fru_fault_state - Get FRU fault indicator state * * Returns : * Indicator state on success, -1 on failure */ static int get_ses_fru_fault_state(const char *buf) { char *fault; fault = strchr(buf, 'o'); if (!fault) return -1; return !strncmp(fault, "on", 2); } /** * ses_indicator_list - Build SES indicator list for the given enclosure * * @list loc_code structure * @vpd dev_vpd structure * * Returns : * 0 on success, !0 on failure */ static int ses_indicator_list(struct loc_code **list, struct dev_vpd *vpd) { char buf[128]; char *desc; char *loc_desc; char *fru_loc; char *args[] = {SCSI_INDICATOR_CMD, "-v", "-l", (char *const)vpd->dev, NULL}; int rc; pid_t cpid; FILE *fp; struct loc_code *curr = *list; fp = spopen(args, &cpid); if (fp == NULL) { log_msg("Unable to get enclosure indicator list. " "Ensure that encl_led command is installed."); return -1; } if (curr) while (curr->next) curr = curr->next; while (fgets_nonl(buf, 128, fp) != NULL) { fru_loc = get_ses_fru_location(buf); if (!fru_loc) continue; /* Advance buffer to parse description field */ desc = get_ses_fru_desc(fru_loc + strlen(fru_loc) + 1); if (!curr) { curr = calloc(1, sizeof(struct loc_code)); *list = curr; } else { curr->next = calloc(1, sizeof(struct loc_code)); curr = curr->next; } if (!curr) { log_msg("Out of memory"); /* Read until pipe becomes empty */ while (fgets_nonl(buf, 128, fp) != NULL) ; rc = spclose(fp, cpid); if (rc) log_msg("%s: spclose failed [rc=%d]\n", __func__, rc); return -1; } /* fill loc_code structure */ strncpy(curr->code, vpd->location, LOCATION_LENGTH -1); curr->code[LOCATION_LENGTH - 1] = '\0'; if (strcmp(fru_loc, "-")) { /* Components */ strncat(curr->code, "-", LOCATION_LENGTH - strlen(curr->code) - 1); strncat(curr->code, fru_loc, LOCATION_LENGTH - strlen(curr->code) - 1); } curr->length = strlen(curr->code) + 1; curr->type = TYPE_SES; /* We need to keep track of the sg device. */ strncpy(curr->dev, vpd->dev, DEV_LENGTH - 1); curr->dev[DEV_LENGTH - 1] = '\0'; /* lsvpd does not provide vpd data for components like power * supply inside enclosure. Lets keep the display name. */ if (desc) { if (asprintf(&loc_desc, "Enclosure %s : %s", vpd->dev, desc) < 0) { log_msg("%s: Out of memory\n", __func__); return -1; } strncpy(curr->ds, loc_desc, VPD_LENGTH - 1); free(loc_desc); } } rc = spclose(fp, cpid); if (rc) { log_msg("%s: spclose failed [rc=%d]\n", __func__, rc); return -1; } return 0; } /** * get_ses_indices - Get SES indicator list * * @loc loc_code structure * * Returns : * none */ void get_ses_indices(int indicator, struct loc_code **list) { int vpd_matched; struct dev_vpd *vpd; struct dev_vpd *v1; struct dev_vpd *v2; vpd = read_ses_vpd(); if (!vpd) return; /* Some of the enclosures can be represented by multiple sg devices. * Make sure we don't duplicate the location code for such devices. * Ex: A Bluehawk can be represented by 4 different sg devices. */ for (v1 = vpd; v1; v1 = v1->next) { if (!enclosure_supported(v1->mtm)) continue; vpd_matched = 0; for (v2 = v1->next; v2; v2 = v2->next) { if (!enclosure_supported(v2->mtm)) continue; if (!strcmp(v1->location, v2->location)) { vpd_matched = 1; break; } } if (!vpd_matched && v1->location[0] != '\0') if (ses_indicator_list(list, v1)) { free_device_vpd(vpd); return; } } free_device_vpd(vpd); return; } /** * get_ses_indicator - get SES indicator state * * @loc loc_code structure * @state return ses indicator state of given loc * * Returns * 0 on success / -1 on failure */ int get_ses_indicator(int indicator, struct loc_code *loc, int *state) { int fru_found = 0; char buf[128]; char *fru_loc; char *fru; char *args[] = {SCSI_INDICATOR_CMD, "-l", (char *const)loc->dev, /* FRU loc */ NULL, NULL}; int rc; pid_t cpid; FILE *fp; fru_loc = get_relative_fru_location(loc->code); if (!fru_loc) /* Enclosure location code */ fru_loc = "-"; args[3] = (char *const)fru_loc; fp = spopen(args, &cpid); if (fp == NULL) { log_msg("Unable to get enclosure LED status. " "Ensure that encl_led command is installed."); return -1; } while (fgets_nonl(buf, 128, fp) != NULL) { if (fru_found) /* read until pipe becomes empty*/ continue; fru = get_ses_fru_location(buf); if (fru && !strcmp(fru_loc, fru)) { fru_found = 1; if (indicator == LED_TYPE_IDENT) *state = get_ses_fru_identify_state(buf); else *state = get_ses_fru_fault_state(buf); } } rc = spclose(fp, cpid); if (rc) { log_msg("%s: spclose failed [rc=%d]\n", __func__, rc); return -1; } if (!fru_found) return -1; return 0; } /** * set_ses_indicator - Set SES indicators * * @loc loc_code structure * @state value to update indicator to * * Returns : * ioctl call return code */ int set_ses_indicator(int indicator, struct loc_code *loc, int new_value) { char *fru_loc; pid_t fork_pid; int status; fru_loc = get_relative_fru_location(loc->code); if (!fru_loc) /* Enclosure location code */ fru_loc = "-"; if (loc->dev[0] == '\0') return -1; if (access(SCSI_INDICATOR_CMD, X_OK) != 0) { log_msg("The command \"%s\" is not executable.\n", SCSI_INDICATOR_CMD); return -1; } fork_pid = fork(); if (fork_pid == -1) { log_msg("Couldn't fork() (%d:%s)\n", errno, strerror(errno)); return -1; } else if (fork_pid == 0) { /* Child */ char *args[6]; args[0] = (char *)SCSI_INDICATOR_CMD; args[1] = indicator == LED_TYPE_IDENT ? "-i" : "-f"; args[2] = new_value == LED_STATE_ON ? "on" : "off"; args[3] = loc->dev; args[4] = fru_loc; args[5] = NULL; execv(SCSI_INDICATOR_CMD, args); log_msg("Couldn't execv() into: %s (%d:%s)\n", SCSI_INDICATOR_CMD, errno, strerror(errno)); exit(EXIT_FAILURE); } /* Wait for set SES indicator command to complete */ if (waitpid(fork_pid, &status, 0) == -1) { log_msg("Wait failed, while running set SES indicator " "command\n"); return -1; } status = (int8_t)WEXITSTATUS(status); if (status) { log_msg("%s command execution failed\n", SCSI_INDICATOR_CMD); return -1; } return 0; }
11,213
C
.c
448
22.459821
81
0.653153
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,713,609
servicelog.c
power-ras_ppc64-diag/lpd/servicelog.c
/** * @file servicelog.c * @brief Read servicelog database * * Copyright (C) 2012 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @author Vasant Hegde <[email protected]> */ #include <stdio.h> #include <string.h> #include <servicelog-1/servicelog.h> #include "indicator.h" /* Query string should be same as "match" field in notification script. * see scripts/lp_diag_setup script. */ #define SERVICELOG_QUERY_LEN 128 #define SERVICELOG_QUERY_STRING "disposition>=1 and severity>=4 and " \ "serviceable=1" /** * get_servicelog_event - Retrieve servicelog event(s) * * @query servicelog event query * @event servicelog event structure * * Returns : * 0 on success, !0 on failure */ static int get_servicelog_event(char *query, struct sl_event **event) { int rc; struct servicelog *slog; rc = servicelog_open(&slog, 0); if (rc) { log_msg("Error opening servicelog db: %s", strerror(rc)); return rc; } rc = servicelog_event_query(slog, query, event); if (rc) log_msg("Error reading servicelog db :%s", servicelog_error(slog)); /* close database */ servicelog_close(slog); return rc; } /** * get_service_event - Get service event */ int get_service_event(int event_id, struct sl_event **event) { char query[SERVICELOG_QUERY_LEN]; snprintf(query, SERVICELOG_QUERY_LEN, "id=%d", event_id); return get_servicelog_event(query, event); } /** * get_all_open_service_event - Get all open serviceable event */ int get_all_open_service_event(struct sl_event **event) { int len; char query[SERVICELOG_QUERY_LEN]; len = snprintf(query, SERVICELOG_QUERY_LEN, SERVICELOG_QUERY_STRING); snprintf(query + len, SERVICELOG_QUERY_LEN - len, " and closed=0"); return get_servicelog_event(query, event); } /** * get_repair_event - Get repair event */ int get_repair_event(int repair_id, struct sl_event **event) { int len; char query[SERVICELOG_QUERY_LEN]; len = snprintf(query, SERVICELOG_QUERY_LEN, SERVICELOG_QUERY_STRING); snprintf(query + len, SERVICELOG_QUERY_LEN - len, " and repair=%d", repair_id); return get_servicelog_event(query, event); } /** * print_service_event - Print servicelog event */ int print_service_event(struct sl_event *event) { return servicelog_event_print(stdout, event, 1); }
2,971
C
.c
102
27.176471
81
0.740793
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,610
indicator_rtas.c
power-ras_ppc64-diag/lpd/indicator_rtas.c
/** * @file indicator_rtas.c * @brief RTAS indicator manipulation routines * * Copyright (C) 2012 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @author Vasant Hegde <[email protected]> */ #include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <librtas.h> #include "indicator.h" #include "indicator_ses.h" /* Device tree property for indicator list */ #define RTAS_INDICATOR_DT_PATH "/proc/device-tree/rtas/ibm,get-indices" /* Token defination for indicator */ #define RTAS_INDICATOR_IDENT 9007 #define RTAS_INDICATOR_ATTN 9006 /* Defination for type of indicator call */ #define DYNAMIC_INDICATOR 0xFFFFFFFF /* RTAS error buffer size */ #define RTAS_ERROR_BUF_SIZE 64 /* Get RTAS token number for given LED type */ static inline int get_rtas_token(int indicator) { switch(indicator) { /* We use same token number for fault and checklog indicator */ case LED_TYPE_ATTN: case LED_TYPE_FAULT: return RTAS_INDICATOR_ATTN; case LED_TYPE_IDENT: return RTAS_INDICATOR_IDENT; } return -1; } /** * parse_work_area - Parse the working buffer * * @loc list to add new data to * @buf working area to parse * * Returns : * pointer to new loc_code list */ static struct loc_code * parse_rtas_workarea(struct loc_code *loc, const char *buf) { int i; uint32_t num = be32toh(*(uint32_t *)buf); struct loc_code *curr = loc; if (curr) while (curr->next) curr = curr->next; buf += sizeof(uint32_t); for (i = 0; i < num; i++) { if (!curr) { curr = calloc(1, sizeof(struct loc_code)); loc = curr; } else { curr->next = calloc(1, sizeof(struct loc_code)); curr = curr->next; } if (!curr) { log_msg("Out of memory"); /* free up previously allocated memory */ free_indicator_list(loc); return NULL; } /* * NOTE: Location code length and location code string combined * is given as the input to LED indicator related rtas calls. So * the buffer representation of the location code length and * location code string must be PAPR compliant and big endian at * all times. Convert the location code length to host format when * ever required on the need basis. */ curr->index = be32toh(*(uint32_t *)buf); buf += sizeof(uint32_t); /* Includes NULL char */ curr->length = be32toh(*(uint32_t *)buf); buf += sizeof(uint32_t); /* Corrupted work area */ if (curr->length > LOCATION_LENGTH) { free_indicator_list(loc); return NULL; } strncpy(curr->code, buf, curr->length); buf += curr->length; curr->code[curr->length] = '\0'; curr->length = strlen(curr->code) + 1; curr->length = htobe32(curr->length); curr->type = TYPE_RTAS; curr->next = NULL; } return loc; } /** * librtas_error - Check for librtas specific return codes * * @Note: * librtas_error is based on librtas_error.c in powerpc-util package. * @author Nathan Fontenot <[email protected]> * * This will check the error value for a librtas specific return code * and fill in the buffer with the appropriate error message. * * @error return code from librtas * @buf buffer to fill with error string * @size size of "buffer" * * Returns : * nothing */ static void librtas_error(int error, char *buf, size_t size) { switch (error) { case RTAS_KERNEL_INT: snprintf(buf, size, "No kernel interface to firmware"); break; case RTAS_KERNEL_IMP: snprintf(buf, size, "No kernel implementation of function"); break; case RTAS_PERM: snprintf(buf, size, "Non-root caller"); break; case RTAS_NO_MEM: snprintf(buf, size, "Out of heap memory"); break; case RTAS_NO_LOWMEM: snprintf(buf, size, "Kernel out of low memory"); break; case RTAS_FREE_ERR: snprintf(buf, size, "Attempt to free nonexistent RMO buffer"); break; case RTAS_TIMEOUT: snprintf(buf, size, "RTAS delay exceeded specified timeout"); break; case RTAS_IO_ASSERT: snprintf(buf, size, "Unexpected librtas I/O error"); break; case RTAS_UNKNOWN_OP: snprintf(buf, size, "No firmware implementation of function"); break; default: snprintf(buf, size, "Unknown librtas error %d", error); } } /** * get_rtas_list - Gets rtas indicator list * * @indicator identification or attention indicator * @loc pointer to loc_code structure * * Returns : * rtas call return value */ static int get_rtas_indices(int indicator, struct loc_code **loc) { int rc; int index = 1; int next_index; int rtas_token; char workarea[BUF_SIZE]; char err_buf[RTAS_ERROR_BUF_SIZE]; struct loc_code *list = NULL; rtas_token = get_rtas_token(indicator); if (rtas_token == -1) return -3; /* Indicator type not supported */ do { rc = rtas_get_indices(0, rtas_token, workarea, BUF_SIZE, index, &next_index); switch (rc) { case 1: /* more data available */ index = next_index; /* fall through */ case 0: /* success */ list = parse_rtas_workarea(list, workarea); if (!list) return -99; /* Out of heap memory */ break; case -1: /* hardware error */ log_msg("Hardware error retrieving indicator indices"); free_indicator_list(list); break; case RTAS_UNKNOWN_OP: /* Yes, this is a librtas return code but it should * be treated the same as a -3 return code, both * indicate that functionality is not supported */ librtas_error(rc, err_buf, RTAS_ERROR_BUF_SIZE); /* fall through */ case -3: /* indicator type not supported. */ log_msg("The %s indicators are not supported on this " "system", get_indicator_desc(indicator)); if (rc == RTAS_UNKNOWN_OP) log_msg(",\n%s", err_buf); free_indicator_list(list); break; case -4: /* list changed; start over */ free_indicator_list(list); list = NULL; index = 1; break; default: librtas_error(rc, err_buf, RTAS_ERROR_BUF_SIZE); log_msg("Could not retrieve data for %s " "indicators,\n%s", get_indicator_desc(indicator), err_buf); free_indicator_list(list); break; } } while ((rc == 1) || (rc == -4)); *loc = list; return rc; } /** * get_rtas_sensor - Retrieve a sensor value from rtas * * Call the rtas_get_sensor or rtas_get_dynamic_sensor librtas calls, * depending on whether the index indicates that the sensor is dynamic. * * @indicator identification or attention indicator * @loc location code of the sensor * @state return sensor state for the given loc * * Returns : * rtas call return code */ static int get_rtas_sensor(int indicator, struct loc_code *loc, int *state) { int rc; int rtas_token; char err_buf[RTAS_ERROR_BUF_SIZE]; rtas_token = get_rtas_token(indicator); if (rtas_token == -1) return -3; /* No such sensor implemented */ if (loc->index == DYNAMIC_INDICATOR) rc = rtas_get_dynamic_sensor(rtas_token, (void *)loc, state); else rc = rtas_get_sensor(rtas_token, loc->index, state); switch (rc) { case 0: /*success */ break; case -1: log_msg("Hardware error retrieving the indicator at %s", loc->code); break; case -2: log_msg("Busy while retrieving indicator at %s. " "Try again later", loc->code); break; case -3: log_msg("The indicator at %s is not implemented", loc->code); break; default: librtas_error(rc, err_buf, RTAS_ERROR_BUF_SIZE); log_msg("Could not get %ssensor %s indicators,\n%s", (loc->index == DYNAMIC_INDICATOR) ? "dynamic " : "", get_indicator_desc(indicator), err_buf); break; } return rc; } /** * set_rtas_indicator - Set rtas indicator * * Call the rtas_set_indicator or rtas_set_dynamic_indicator librtas calls, * depending on whether the index indicates that the indicator is dynamic. * * @indicator identification or attention indicator * @loc location code of rtas indicator * @new_value value to update indicator to * * Returns : * rtas call return code */ static int set_rtas_indicator(int indicator, struct loc_code *loc, int new_value) { int rc; int rtas_token; char err_buf[RTAS_ERROR_BUF_SIZE]; rtas_token = get_rtas_token(indicator); if (rtas_token == -1) return -3; /* No such sensor implemented */ if (loc->index == DYNAMIC_INDICATOR) rc = rtas_set_dynamic_indicator(rtas_token, new_value, (void *)loc); else rc = rtas_set_indicator(rtas_token, loc->index, new_value); switch (rc) { case 0: /*success */ break; case -1: log_msg("Hardware error while setting the indicator at %s", loc->code); break; case -2: log_msg("Busy while setting the indicator at %s. " "Try again later", loc->code); break; case -3: log_msg("The indicator at %s is not implemented", loc->code); break; default: librtas_error(rc, err_buf, RTAS_ERROR_BUF_SIZE); log_msg("Could not set %ssensor %s indicators,\n%s", (loc->index == DYNAMIC_INDICATOR) ? "dynamic " : "", get_indicator_desc(indicator), err_buf); break; } return rc; } /* * rtas_indicator_probe - Probe indicator support on RTAS based platform * * Returns: * 0 if indicator is supported, else -1 */ static int rtas_indicator_probe(bool platform_only) { if (platform_only) system_scan_flag = 1 << TYPE_RTAS; else system_scan_flag = 1 << TYPE_ALL | 1 << TYPE_RTAS | 1 << TYPE_SES; return 0; } /** * get_rtas_indicator_mode - Gets the service indicator operating mode * * Note: There is no defined property in PAPR+ to determine the indicator * operating mode. There is some work being done to get property * into PAPR. When that is done we will check for that property. * * At present, we will query RTAS fault indicators. It should return * at least one fault indicator, that is check log indicator. If only * one indicator is returned, then Guiding Light mode else Light Path * mode. * * Returns : * operating mode value */ static int get_rtas_indicator_mode(void) { int rc; struct loc_code *list = NULL; rc = get_rtas_indices(LED_TYPE_FAULT, &list); if (rc) return -1; if (!list) /* failed */ return -1; else if (!list->next) operating_mode = LED_MODE_GUIDING_LIGHT; else operating_mode = LED_MODE_LIGHT_PATH; free_indicator_list(list); return 0; } /** * get_rtas_indicator_list - Build indicator list of given type * * @indicator identification or attention indicator * @list loc_code structure * * Returns : * 0 on success, !0 otherwise */ static int get_rtas_indicator_list(int indicator, struct loc_code **list) { int rc; /* * Get RTAS indicator list * NB: Check the system_scan_flag if the scanning of platform * indicators needs to be prevented. */ rc = get_rtas_indices(indicator, list); if (rc) return rc; /* FRU fault indicators are not supported in Guiding Light mode */ if (indicator == LED_TYPE_FAULT && operating_mode == LED_MODE_GUIDING_LIGHT) return rc; /* SES indicators */ if (system_scan_flag & (1 << TYPE_SES)) get_ses_indices(indicator, list); return rc; } /** * get_rtas_indicator_state - Retrieve the current state for an indicator * * Call the appropriate routine for retrieving indicator values based on the * type of indicator. * * @indicator identification or attention indicator * @loc location code of the sensor * @state return location for the sensor state * * Returns : * indicator return code */ static int get_rtas_indicator_state(int indicator, struct loc_code *loc, int *state) { switch (loc->type) { case TYPE_RTAS: return get_rtas_sensor(indicator, loc, state); case TYPE_SES: return get_ses_indicator(indicator, loc, state); default: break; } return -1; } /** * set_rtas_indicator_state - Set an indicator to a new state (on or off) * * Call the appropriate routine for setting indicators based on the type * of indicator. * * @indicator identification or attention indicator * @loc location code of rtas indicator * @new_value value to update indicator to * * Returns : * indicator return code */ static int set_rtas_indicator_state(int indicator, struct loc_code *loc, int new_value) { switch (loc->type) { case TYPE_RTAS: return set_rtas_indicator(indicator, loc, new_value); case TYPE_SES: return set_ses_indicator(indicator, loc, new_value); default: break; } return -1; } struct platform rtas_platform = { .name = "rtas", .probe = rtas_indicator_probe, .get_indicator_mode = get_rtas_indicator_mode, .get_indicator_list = get_rtas_indicator_list, .get_indicator_state = get_rtas_indicator_state, .set_indicator_state = set_rtas_indicator_state, };
13,143
C
.c
470
25.4
82
0.70598
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,611
indicator.c
power-ras_ppc64-diag/lpd/indicator.c
/** * @file indicator.c * @brief Indicator manipulation routines * * Copyright (C) 2012 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @author Vasant Hegde <[email protected]> */ #include <unistd.h> #include <stdio.h> #include <string.h> #include <stdbool.h> #include <stdlib.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #include "platform.h" #include "indicator.h" #include "lp_util.h" /* Indicator operating mode */ uint32_t operating_mode; uint32_t system_scan_flag; /* points to platform structure of running platform */ struct platform platform; /* Map LED type to description. */ struct led_type_map { const int type; const char *desc; }; static struct led_type_map led_type_map[] = { {LED_TYPE_IDENT, LED_DESC_IDENT}, {LED_TYPE_FAULT, LED_DESC_FAULT}, {LED_TYPE_ATTN, LED_DESC_ATTN}, {-1, NULL}, }; /* Returns LED type */ int get_indicator_type(const char *indicator_desc) { int i; for (i = 0; led_type_map[i].desc != NULL; i++) if (!strcmp(led_type_map[i].desc, indicator_desc)) return led_type_map[i].type; return -1; } /* Returns LED description */ const char * get_indicator_desc(int indicator) { int i; for (i = 0; led_type_map[i].type != -1; i++) if (led_type_map[i].type == indicator) return led_type_map[i].desc; return "Unknown"; } /** * is_enclosure_loc_code - */ int is_enclosure_loc_code(struct loc_code *loc) { if (strchr(loc->code, '-') == NULL) return 1; return 0; } /** * truncate_loc_code - Truncate the last few characters of a location code * * Truncates the last few characters off of a location code; if an * indicator doesn't exist at the orignal location, perhaps one exists * at a location closer to the CEC. * * @loccode location code to truncate * * Returns : * 1 - successful truncation / 0 - could not be truncated further */ int truncate_loc_code(char *loccode) { int i; for (i = strlen(loccode) - 1; i >= 0; i--) { if (loccode[i] == '-') { loccode[i] = '\0'; return 1; /* successfully truncated */ } } return 0; } /** * get_indicator_for_loc_code - Compare device location code with indicator list * * @list indicator list * @location device location code * * Returns : * on success, loc_code structure * on failure, NULL */ struct loc_code * get_indicator_for_loc_code(struct loc_code *list, const char *location) { while (list) { if (!strcmp(list->code, location)) return list; list = list->next; } return NULL; } /** * probe_indicator - probes for indicators on running platform * * Returns : * 0 on success, -1 on failure */ int probe_indicator(bool platform_only) { if (!platform.name) { fprintf(stderr, "%s internal error: platform not initialized\n", program_name); return -1; } if (platform.probe) return platform.probe(platform_only); return 0; } /** * platform_initialize - Check supportability on the running platform * * Returns : * 0 on success, -1 on failure */ int platform_initialize() { int p; p = get_platform(); switch (p) { case PLATFORM_PSERIES_LPAR: platform = rtas_platform; break; case PLATFORM_POWERNV: platform = opal_platform; break; case PLATFORM_POWERKVM_GUEST: default: fprintf(stderr, "%s is not supported on the %s platform\n", program_name, __power_platform_name(p)); return -1; } return 0; } /** * get_indicator_mode - Gets the service indicator operating mode * * Returns : * operating mode value */ int get_indicator_mode(void) { if (!platform.get_indicator_mode) return -1; return platform.get_indicator_mode(); } /** * get_indicator_list - Build indicator list of given type * * @indicator identification or attention indicator * @list loc_code structure * * Returns : * 0 on success, !0 otherwise */ int get_indicator_list(int indicator, struct loc_code **list) { if (!platform.get_indicator_list) return -1; return platform.get_indicator_list(indicator, list); } /** * get_indicator_state - Retrieve the current state for an indicator * * Call the appropriate routine for retrieving indicator values based on the * type of indicator. * * @indicator identification or attention indicator * @loc location code of the sensor * @state return location for the sensor state * * Returns : * indicator return code */ int get_indicator_state(int indicator, struct loc_code *loc, int *state) { if (!platform.get_indicator_state) return -1; return platform.get_indicator_state(indicator, loc, state); } /** * set_indicator_state - Set an indicator to a new state (on or off) * * Call the appropriate routine for setting indicators based on the type * of indicator. * * @indicator identification or attention indicator * @loc location code of rtas indicator * @new_value value to update indicator to * * Returns : * indicator return code */ int set_indicator_state(int indicator, struct loc_code *loc, int new_value) { if (!platform.set_indicator_state) return -1; return platform.set_indicator_state(indicator, loc, new_value); } /** * get_all_indicator_state - Get all indicators current state * * @indicator identification or attention indicator * @loc location code structure * * Returns : * nothing */ void get_all_indicator_state(int indicator, struct loc_code *loc) { int rc; int state; while (loc) { rc = get_indicator_state(indicator, loc, &state); if (rc) /* failed to get indicator state */ loc->state = -1; else loc->state = state; loc = loc->next; } } /** * set_all_indicator_state - Sets all indicators state * * @indicator identification or attention indicator * @loc location code structure * @new_value LED_STATE_ON/LED_STATE_OFF * * Returns : * 0 on success, !0 on failure */ void set_all_indicator_state(int indicator, struct loc_code *loc, int new_value) { int state; int rc; struct loc_code *encl = &loc[0]; while (loc) { rc = get_indicator_state(indicator, loc, &state); if (rc || state != new_value) set_indicator_state(indicator, loc, new_value); loc = loc->next; } /* If enclosure identify indicator is turned ON explicitly, * then turning OFF all components identify indicator inside * enclosure does not turn OFF enclosure identify indicator. */ if (encl && indicator == LED_TYPE_IDENT && new_value == LED_STATE_OFF) set_indicator_state(indicator, encl, new_value); } /** * enable_check_log_indicator - Enable check log indicator * * Returns : * 0 on success, !0 on failure */ int enable_check_log_indicator(void) { int rc; struct loc_code *list = NULL; struct loc_code *clocation; rc = get_indicator_list(LED_TYPE_FAULT, &list); if (rc) return rc; /** * The first location code returned by get_rtas_indices RTAS call * is check log indicator. */ clocation = &list[0]; rc = set_indicator_state(LED_TYPE_FAULT, clocation, LED_STATE_ON); free_indicator_list(list); return rc; } /** * disable_check_log_indicator - Disable check log indicator * * Returns : * 0 on success, !0 on failure */ int disable_check_log_indicator(void) { int rc; struct loc_code *list = NULL; struct loc_code *clocation; rc = get_indicator_list(LED_TYPE_FAULT, &list); if (rc) return rc; /** * The first location code returned by get_rtas_indices RTAS call * is check log indicator. */ clocation = &list[0]; rc = set_indicator_state(LED_TYPE_FAULT, clocation, LED_STATE_OFF); free_indicator_list(list); return rc; } /** * free_indicator_list - Free loc_code structure * * @loc list to free * * Return : * nothing */ void free_indicator_list(struct loc_code *loc) { struct loc_code *tmp = loc; while (loc) { tmp = loc; loc = loc->next; free(tmp); } }
8,426
C
.c
356
21.603933
81
0.716958
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,612
indicator_marvell.c
power-ras_ppc64-diag/lpd/indicator_marvell.c
/** * @file indicator_marvell.c * @brief Marvell HDD LEDs (indicators) manipulation routines * * Copyright (C) 2016 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @author Mauricio Faria de Oliveira <[email protected]> * @author Douglas Miller <[email protected]> */ #define _GNU_SOURCE #include <ctype.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include "indicator.h" #include "lp_util.h" #include "utils.h" /* * Path to block devices in sysfs */ #define SYS_BLOCK_PATH "/sys/block" /* * PCI IDs of the Marvell 9235 SATA controller in * IBM Power System S822LC for HPC (Garrison/Minsky). */ #define MV_PCI_VID "0x1b4b" #define MV_PCI_DID "0x9235" #define MV_PCI_SVID "0x1014" #define MV_PCI_SSID "0x0612" #define MV_PCI_ID_BUF_LEN 7 /* "0x3456" and '\0' */ /* * Vendor-Specific Registers (VSR) are accessed indirectly * through a pair of registers in PCI BAR5. * * First, set the VSR address in VSR_ADDR; * Then, read/write data from/to VSR_DATA. */ static const uint32_t mv_pci_bar5_vsr_addr = 0xa8; static const uint32_t mv_pci_bar5_vsr_data = 0xac; static const uint32_t mv_pci_bar5_length = 2048; /* * The LEDs are controlled via GPIO pins or SATA link/activity status (default). * * This involves 3 VSRs: * - The LED mode of a SATA port is set in the PORT_ACTIVE_SEL register. * (either GPIO pin state or SATA link/activity status for all/one SATA port) * - The GPIO pin state is set in the DATA_OUT register. * - The GPIO pin state output is enabled in the DATA_OUT_ENABLE register. * * On Garrison/Minsky the identification LED of the SATA port 'N' is wired * to the GPIO pin of the SATA port 'N + 2' (the max. number of disks is 2). * The PORT_ACTIVE_SEL and DATA_OUT_ENABLE registers are set by default so * that SATA ports 3 and 4 (that is, the identification LEDs of SATA ports * 1 and 2) are GPIO-pin based, and only the DATA_OUT register needs to be * modified to (un)light the identification LEDs (a.k.a. fault LEDs). * * Register information: * * GPIO Data Out: * - 1 bit per GPIO pin (31-0) * - default: 0x00000018 (all low, except for pins 3 and 4) * - The LEDs are ON on low and OFF on high. * * GPIO Data Out Enable: * - 1 bit per GPIO bin (31-0) * - default: 0xffffffe7 (all high, except for pins 3 and 4) * - active low (data output enabled on bit value 0) * * Port Active Enable (or Port GPIOx Active Select) * - bits 31-30: reserved (zero) * - bits 29-00: 10x 3-bit mode (SATA ports 9-0) * - default: 0x2db6da8d */ static const uint32_t mv_gpio_data_out = 0x07071020; static const uint32_t mv_gpio_data_out_enable = 0x07071024; static const uint32_t mv_gpio_port_active_sel = 0x07071058; static const uint32_t mv_port_number_offset = 2; static const uint32_t mv_port_number_max = 9; static char *mv_port_mode[] = { "All SATAx LINK and ACT", // 0x0 "SATA0 LINK and ACT", // 0x1 "SATA1 LINK and ACT", // 0x2 "SATA2 LINK and ACT", // 0x3 "SATA3 LINK and ACT", // 0x4 "GPIO_DATA_OUT[n]", // 0x5 "Invalid (6)", // 0x6 "Invalid (7)" // 0x7 }; /** * mv_mmap_bar5 - open() and mmap() a PCI BAR5 (resource5) file. * the caller should unmap/close (see mv_munmap_bar5()). * * @path path to the 'resource5' file * @fd pointer to a file descriptor * * Return: * - success: pointer to the mmap()'ed PCI BAR5 * - failure: NULL */ static void * mv_mmap_bar5(const char* path, int *fd) { void *bar5; /* open and mmap PCI BAR5 */ *fd = open(path, O_RDWR); if (*fd < 0) { log_msg("Unable to open file '%s'", path); return NULL; } bar5 = mmap(NULL, mv_pci_bar5_length, PROT_READ | PROT_WRITE, MAP_SHARED, *fd, 0); if (bar5 == MAP_FAILED) { log_msg("Unable to mmap file '%s'", path); close(*fd); return NULL; } return bar5; } /** * mv_munmap_bar5 - munmap() and close() a PCI BAR5 (resource5) file. * (release resources from mv_mmap_bar5()). * * @bar5 pointer to the mmap()'ed PCI BAR5 * @fd file descriptor of the open()'ed/mmap()'ed PCI BAR5 * * Return: * - nothing */ static void mv_munmap_bar5(void *bar5, int fd) { /* munmap() and close PCI BAR5 */ if (munmap(bar5, mv_pci_bar5_length)) log_msg("Unable to munmap file"); if (close(fd)) log_msg("Unable to close file"); } /** * mv_vsr_read - read a VSR * * @bar5 pointer to mmap()'ed PCI BAR5 (see mv_mmap_bar5()) * @vsr_addr VSR address to read from * * Return: * - VSR data read */ static uint32_t mv_vsr_read(void* bar5, uint32_t vsr_addr) { volatile uint32_t *addr = (uint32_t *)(bar5 + mv_pci_bar5_vsr_addr); volatile uint32_t *data = (uint32_t *)(bar5 + mv_pci_bar5_vsr_data); /* set address and read data */ *addr = vsr_addr; return *data; } /** * mv_vsr_write - write a VSR * * @bar5 pointer to mmap()'ed PCI BAR5 (see mv_mmap_bar5()) * @vsr_addr VSR address to write to * @vsr_data VSR data to write * * Return: * - nothing */ static void mv_vsr_write(void* bar5, uint32_t vsr_addr, uint32_t vsr_data) { volatile uint32_t *addr = (uint32_t *)(bar5 + mv_pci_bar5_vsr_addr); volatile uint32_t *data = (uint32_t *)(bar5 + mv_pci_bar5_vsr_data); /* set address and write data */ *addr = vsr_addr; *data = vsr_data; } /** * mv_get_port_mode - get the LED mode of a SATA port (from register copy) * * @port_number number of the SATA port (0-9) * @port_mode pointer to the LED mode (result) (see mv_port_mode[]) * @port_active_sel copy of the PORT_ACTIVE_SEL register * * Return: * - -1 on failure * - 0 on success */ static int mv_get_port_mode(uint32_t port_number, uint32_t *port_mode, uint32_t port_active_sel) { uint32_t shift, mask; if (port_number > mv_port_number_max) { log_msg("Invalid port number: '%u'", port_number); return -1; } /* get the 3-bit mode of SATA port N */ shift = 3 * port_number; mask = 0x7 << shift; *port_mode = (port_active_sel & mask) >> shift; return 0; } /** * check_pci_id() - checks the value of a PCI ID file. * * Return: * - 0 on success (open/read file, and match value) * - -1 on failure * - +1 on different values */ static int check_pci_id(char *path, char *pci_id) { FILE *f; char *pci_id_rc, pci_id_buf[MV_PCI_ID_BUF_LEN]; f = fopen(path, "r"); if (!f) { log_msg("Unable to open file '%s'", path); return -1; } pci_id_rc = fgets(pci_id_buf, MV_PCI_ID_BUF_LEN, f); if (!pci_id_rc) { log_msg("Unable to read file '%s'", path); fclose(f); return -1; } fclose(f); return !!strncmp(pci_id, pci_id_buf, MV_PCI_ID_BUF_LEN); } /** * mv_indicator_list - Build Marvell HDD LED (indicator) list for the given disk vpd * * @list loc_code structure * @vpd dev_vpd structure * * Return: * - 0 on success or skip vpd (not a Marvell SATA disk) * - -1 on failure */ static int mv_indicator_list(struct loc_code **list, struct dev_vpd *vpd) { struct loc_code *list_curr, *list_new; char *block_path, path[PATH_MAX], symlink[PATH_MAX]; char *ata_device, *host; ssize_t len; /* check for an 'sdX' device name */ if (strncmp(vpd->dev, "sd", 2)) return 0; /* read the '/sys/block/sdX' symlink to '../device/pci.../sdX' */ if (asprintf(&block_path, "%s/%s", SYS_BLOCK_PATH, vpd->dev) < 0) { log_msg("Out of memory"); return -1; } len = readlink(block_path, symlink, PATH_MAX); if (len < 0) { log_msg("Unable to read the contents of symbolic link '%s'", block_path); free(block_path); return -1; } free(block_path); symlink[len] = '\0'; /* * check for an 'ataX' subdir (w/ trailing 'X' digit); for example 'ata1' in * '../devices/pci<...>/0001:08:00.0/ata1/host3/target3:0:0/3:0:0:0/block/sdj' */ ata_device = strstr(symlink, "/ata"); if (!ata_device || !isdigit(ata_device[4])) return 0; host = strstr(symlink, "/host"); if (!host || !isdigit(host[5])) return 0; /* split symlink into relative path for PCI device dir and ataX device */ ata_device[0] = '\0'; /* end symlink on leading '/' of '/ataX/' */ ata_device++; /* skip the leading '/' of '/ataX/' */ host[0] = '\0'; /* end ata_device on trailing '/' of '/ataX/', * which is the leading '/' of '/hostY/' */ /* * get the absolute path for the PCI device dir from symlink, * which is relative to /sys/block (e.g., '../devices/pci...'), * so skip the leading '../' (3 chars) */ len = snprintf(path, PATH_MAX, "%s/%s", "/sys", &symlink[3]); if (len < 0) { log_msg("Unable to format absolute pathname of '%s'", symlink); return -1; } /* * check for the PCI IDs of the Marvell 9235 SATA controller. * * concatenate the PCI ID files' basename after the dirname * with strncpy() (string length + 1 for '\0'). */ strncpy(&path[len], "/vendor", 8); if (check_pci_id(path, MV_PCI_VID)) return 0; strncpy(&path[len], "/device", 8); if (check_pci_id(path, MV_PCI_DID)) return 0; strncpy(&path[len], "/subsystem_vendor", 18); if (check_pci_id(path, MV_PCI_SVID)) return 0; strncpy(&path[len], "/subsystem_device", 18); if (check_pci_id(path, MV_PCI_SSID)) return 0; path[len] = '\0'; /* restore path as dirname of PCI device dir */ /* Allocate one loc_code element, and insert/append it to the list */ list_new = calloc(1, sizeof(struct loc_code)); if (!list_new) { log_msg("Out of memory"); return 1; } if (*list) { /* position list_curr in the last element of the list */ list_curr = *list; while (list_curr->next) list_curr = list_curr->next; /* append the new element to the list */ list_curr->next = list_new; } else { /* null list; insert the new element at the list head */ *list = list_new; } /* set the new element's properties */ list_new->type = TYPE_MARVELL; strncpy(list_new->code, vpd->location, LOCATION_LENGTH); /* loc. code */ strncpy(list_new->devname, vpd->dev, DEV_LENGTH); /* sdX device name */ /* PCI BAR5 */ len = snprintf(list_new->dev, DEV_LENGTH, "%s/resource5", path); if (len < 0 || len >= DEV_LENGTH) { log_msg("'%s':'%d' - Unable to format '%s'", __func__, __LINE__, path); return -1; } list_new->index = (uint32_t)atoi(&ata_device[3]); /* use for ATA index */ dbg("Marvell HDD LED:"); dbg("- location code: '%s'", list_new->code); dbg("- device name (disk): '%s'", list_new->devname); dbg("- device name (pci bar5): '%s'", list_new->dev); dbg("- ata index: '%u'", list_new->index); return 0; } /** * get_mv_indices - Get Marvell HDD LEDs (indicators) list * * @indicator led type * @loc_list loc_code structure * * Return: * - nothing */ void get_mv_indices(int indicator, struct loc_code **loc_list) { struct dev_vpd *vpd_list, *vpd_curr; /* support for identification LEDs only */ if (indicator != LED_TYPE_IDENT) return; /* get block devices' vpd information */ vpd_list = read_device_vpd(SYS_BLOCK_PATH); if (!vpd_list) return; /* search for Marvell HDDs, and append to the list */ for (vpd_curr = vpd_list; vpd_curr; vpd_curr = vpd_curr->next) if (vpd_curr->location[0] != '\0') if (mv_indicator_list(loc_list, vpd_curr)) break; free_device_vpd(vpd_list); } /** * get_mv_indicator - get Marvell HDD LED/indicator state * * @loc loc_code structure * @state return indicator state of given loc * * Return: * - 0 on success * - -1 on failure */ int get_mv_indicator(int indicator, struct loc_code *loc, int *state) { int fd; void *bar5; uint32_t data_out, data_out_enable, active_sel; uint32_t port_number, port_mode; /* support for identification LEDs only */ if (indicator != LED_TYPE_IDENT) return -1; /* read registers from PCI BAR5 */ bar5 = mv_mmap_bar5(loc->dev, &fd); if (!bar5) return -1; /* log_msg() done */ /* for debugging, read the 3 VSRs; only DATA_OUT is required */ data_out = mv_vsr_read(bar5, mv_gpio_data_out); data_out_enable = mv_vsr_read(bar5, mv_gpio_data_out_enable); active_sel = mv_vsr_read(bar5, mv_gpio_port_active_sel); /* for debugging, get the LED mode of the SATA port 'N + offset' */ port_number = loc->index + mv_port_number_offset; if (mv_get_port_mode(port_number, &port_mode, active_sel)) return -1; /* log_msg() done */ dbg("SATA disk '%s'", (loc->devname) ? loc->devname : "(null)"); dbg("Data Out: '0x%08x'", data_out); dbg("Data Out Enable: '0x%08x'", data_out_enable); dbg("Port Active Select: '0x%08x'", active_sel); dbg("ATA Index: '%u', Port Number: '%u', Port Mode: '%u' ('%s')", loc->index, port_number, port_mode, mv_port_mode[port_mode]); /* LED state: ON on low (bit 0) and OFF on high (bit 1) */ *state = (data_out & (1 << port_number)) ? LED_STATE_OFF : LED_STATE_ON; mv_munmap_bar5(bar5, fd); return 0; } /** * set_mv_indicator - set Marvell HDD LED/indicator state * * @loc loc_code structure * @state value to update indicator to * * Return: * - 0 on success * - -1 on failure */ int set_mv_indicator(int indicator, struct loc_code *loc, int new_value) { int fd; void *bar5; uint32_t data_out, port_number; /* support for identification LEDs only */ if (indicator != LED_TYPE_IDENT) return -1; /* sanity check */ if (new_value != LED_STATE_ON && new_value != LED_STATE_OFF) return -1; /* read/write registers from/to PCI BAR5 */ bar5 = mv_mmap_bar5(loc->dev, &fd); if (!bar5) return -1; /* log_msg() done */ /* * only changes to the DATA_OUT register are required with the default * values for the DATA_OUT_ENABLE and PORT_ACTIVE_SEL registers on the * Garrison/Minsky system (see header comments). */ data_out = mv_vsr_read(bar5, mv_gpio_data_out); /* set the LED state of the SATA port 'N + offset' */ port_number = loc->index + mv_port_number_offset; /* set/clear the bit in the DATA_OUT register; * LED state: ON on low (bit 0) and OFF on high (bit 1) */ if (new_value == LED_STATE_ON) data_out &= ~(1 << port_number); else data_out |= 1 << port_number; /* update the register */ mv_vsr_write(bar5, mv_gpio_data_out, data_out); /* for debugging, read the register again after writing */ dbg("Data Out (written to): '0x%08x'", data_out); data_out = mv_vsr_read(bar5, mv_gpio_data_out); dbg("Data Out (read again): '0x%08x'", data_out); mv_munmap_bar5(bar5, fd); return 0; }
14,987
C
.c
480
29.0625
84
0.66863
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,713,613
usysident.c
power-ras_ppc64-diag/lpd/usysident.c
/** * @file usysident.c * @brief usysident/usysattn/usysfault * * Copyright (C) 2012 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @author Vasant Hegde <[email protected]> * * @Note: * This file is the re-implementation of original usysident.c * file in powerpc-utils package. * @author Michael Strosaker <[email protected]> * **/ #include <unistd.h> #include <stdio.h> #include <getopt.h> #include <ctype.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include "indicator.h" #include "lp_util.h" #define CMD_LINE_OPTIONS "d:l:s:-:thVP" #define CMD_IDENTIFY "usysident" #define CMD_FAULT "usysfault" #define CMD_ATTN "usysattn" /* print indicator state */ #define print_indicator_state(loc) \ fprintf(stdout, "%s\t [%s]\n", loc->code, loc->state ? "on" : "off") /* Log indicator status */ #define indicator_log_state(indicator, loc, state) \ if (indicator == LED_TYPE_FAULT && !strchr(loc, '-')) \ indicator_log_write("System Attention Indicator : %s", \ state == LED_STATE_ON ? "ON" : "OFF"); \ else \ indicator_log_write("%s : %s : %s", loc, \ get_indicator_desc(LED_TYPE_IDENT), \ state == LED_STATE_ON ? "ON" : "OFF"); /** * print_usage - Print the usage statement */ static void print_usage(const char *cmd) { if (strstr(cmd, CMD_IDENTIFY)) { fprintf(stdout, "Usage:\n" " %s [-P] [-l <loc_code> [-s {identify|normal}][-t]]\n" " %s [-d <dev_name> [-s {identify|normal}][-t]]\n" " %s [-P]\n" " %s [-V]\n" " %s [-h]\n\n", cmd, cmd, cmd, cmd, cmd); fprintf(stdout, "Options:\n" " -l <loc_code> Indicator location code\n" " -d <dev_name> Device name\n" " -s identify Turn on device/location identify indicator\n" " -s normal Turn off device/location identify indicator\n" " -P Limit the operation to only the platform indicators\n" " -t Truncate loc code if necessary\n" " -V Print the version of the command\n" " -h Print this message and exit\n"); } else { fprintf(stdout, "Usage:\n" " %s [-P] [-l <loc_code> [-s normal][-t]]\n" " %s [-P]\n" " %s [-V]\n" " %s [-h]\n\n", cmd, cmd, cmd, cmd); fprintf(stdout, "Options:\n" " -l <loc_code> Indicator location code\n" " -s normal Turn off location fault indicator\n" " -P Limit the operation to only the platform indicators\n" " -t Truncate loc code if necessary\n" " -V Print the version of the command\n" " -h Print this message\n"); } } /** * main - */ int main(int argc, char **argv) { int c; int state; int indicator; int rc = 0; int trunc = 0; int truncated = 0; bool platformonly = false; bool printonly = false; char temp[LOCATION_LENGTH]; char dloc[LOCATION_LENGTH]; char *dvalue = NULL; char *lvalue = NULL; char *svalue = NULL; char *othervalue = NULL; struct loc_code *current; struct loc_code *list = NULL; struct loc_code *list_start = NULL; program_name = argv[0]; if (platform_initialize() != 0) { fprintf(stderr, "%s is not supported on this platform\n", argv[0]); return 0; } opterr = 0; while ((c = getopt(argc, argv, CMD_LINE_OPTIONS)) != -1) { switch (c) { case 'd': /* Device name */ dvalue = optarg; break; case 'l': /* Location code */ lvalue = optarg; if (strlen(lvalue) >= LOCATION_LENGTH) { fprintf(stderr, "\nLocation code length cannot" " be > %d (including NULL char).\n\n", LOCATION_LENGTH); return 1; } break; case 's': /* Enable/disable */ svalue = optarg; break; case '-': /* All location code */ othervalue = optarg; break; case 't': /* truncate location code */ trunc = 1; break; case 'P': platformonly = true; break; case 'V': fprintf(stdout, "%s %s\n", argv[0], VERSION); fflush(stdout); return 0; case 'h': print_usage(argv[0]); return 0; case '?': if (isprint(optopt)) fprintf(stderr, "Unrecognized option: -%c\n\n", optopt); else fprintf(stderr, "Unrecognized option character %x\n\n", optopt); print_usage(argv[0]); return 1; default: print_usage(argv[0]); return 1; } } if (probe_indicator(platformonly) != 0) { fprintf(stderr, "%s is not supported on this platform\n", argv[0]); return 0; } /* Option checking */ if (optind < argc) { fprintf(stderr, "Unrecognized argument : %s\n\n", argv[optind]); print_usage(argv[0]); return 1; } if (dvalue && !strstr(argv[0], CMD_IDENTIFY)) { fprintf(stderr, "Unrecognized option: -d\n\n"); print_usage(argv[0]); return 1; } if (dvalue && lvalue) { fprintf(stderr, "The -d and -l options cannot be used together.\n\n"); print_usage(argv[0]); return 1; } if (dvalue && platformonly) { fprintf(stderr, "The -d and -P options cannot be used together.\n\n"); print_usage(argv[0]); return 1; } if (svalue && strstr(argv[0], CMD_IDENTIFY)) { if (!strcmp(svalue, "identify")) c = LED_STATE_ON; else if (!strcmp(svalue, "normal")) c = LED_STATE_OFF; else { fprintf(stderr, "The -s option must be either " "\"identify\" or \"normal\".\n\n"); print_usage(argv[0]); return 1; } } if (svalue && (strstr(argv[0], CMD_FAULT) || strstr(argv[0], CMD_ATTN))) { if (!strcmp(svalue, "normal")) c = LED_STATE_OFF; else { fprintf(stderr, "The -s option must be \"normal\".\n\n"); print_usage(argv[0]); return 1; } } if (svalue && !(dvalue || lvalue)) { if (strstr(argv[0], CMD_IDENTIFY)) fprintf(stderr, "The -s option requires the -d or -l " "option to also be used.\n\n"); else fprintf(stderr, "The -s option requires the -l " "option to also be used.\n\n"); print_usage(argv[0]); return 1; } if (svalue && geteuid() != 0) { fprintf(stderr, "%s: Turning indicator on/off requires " "superuser privileges.\n\n", argv[0]); return 1; } if (trunc && !(dvalue || lvalue)) { if (strstr(argv[0], CMD_IDENTIFY)) fprintf(stderr, "The -t option requires the -d or -l " "option to also be used.\n\n"); else fprintf(stderr, "The -t option requires the -l " "option to also be used.\n\n"); print_usage(argv[0]); return 1; } if (othervalue && strstr(argv[0], CMD_IDENTIFY)) { if (!strcmp(othervalue, "all-on")) c = LED_STATE_ON; else if (!strcmp(othervalue, "all-off")) c = LED_STATE_OFF; else { fprintf(stderr, "Unrecognized option: --%s\n\n", othervalue); print_usage(argv[0]); return 1; } } if (othervalue && (strstr(argv[0], CMD_ATTN) || strstr(argv[0], CMD_FAULT))) { if (!strcmp(othervalue, "all-off")) c = LED_STATE_OFF; else { fprintf(stderr, "Unrecognized option: --%s\n\n", othervalue); print_usage(argv[0]); return 1; } } if (othervalue && argc > 2) { fprintf(stderr, "\"--%s\" cannot be used with any other options.\n\n", othervalue); print_usage(argv[0]); return 1; } if (strstr(argv[0], CMD_IDENTIFY)) indicator = LED_TYPE_IDENT; else if (strstr(argv[0], CMD_FAULT) || strstr(argv[0], CMD_ATTN)) indicator = LED_TYPE_FAULT; else return 1; if (argc == 1 || ((argc == 2) && platformonly)) printonly = true; /* initialize */ lp_error_log_fd = STDOUT_FILENO; /* log message to stdout */ rc = init_files(); if (rc) { fprintf(stderr, "Unable to open log file.\n"); return 1; } /* Light Path operating mode */ if (indicator == LED_TYPE_FAULT) { rc = get_indicator_mode(); if (rc) return rc; } /* get indicator list */ rc = get_indicator_list(indicator, &list); if (rc) goto file_cleanup; if (printonly) { current = list; while (current) { /* get and print all indicators current state */ rc = get_indicator_state(indicator, current, &state); if (rc) /* failed to get indicator state */ current->state = -1; else current->state = state; print_indicator_state(current); current = current->next; } } /* Turn on/off indicator based on device name */ if (dvalue) { if (get_loc_code_for_dev(dvalue, dloc, LOCATION_LENGTH) != 0) { fprintf(stderr, "\"%s\" is not a valid device or " "it does not have location code.\n", dvalue); rc = 2; } else { lvalue = dloc; fprintf(stdout, "%s is at location code %s.\n", dvalue, lvalue); } } /* Turn on/off indicator based on location code */ if (lvalue) { strncpy(temp, lvalue, LOCATION_LENGTH); temp[LOCATION_LENGTH - 1] = '\0'; list_start = list; retry: current = get_indicator_for_loc_code(list_start, lvalue); if (!current) { if (trunc) { if (truncate_loc_code(lvalue)) { truncated = 1; list_start = list; /* start again */ goto retry; } } fprintf(stdout, "There is no %s indicator at location " "code %s.\n", get_indicator_desc(indicator), temp); rc = 1; } else { /* Found location code */ if (truncated) fprintf(stdout, "Truncated location code : " "%s\n", lvalue); if (current->type == TYPE_MARVELL) { /* * On some systems... * The Marvell SATA HDD controller may have one location code * for all disks. So, in order to uniquely identify a disk in * the list, the -d <dev_name> (dvalue) option must be used. * * eg, if the -l <loc_code> (lvalue) option is used then the * first disk in that location code will match, and it might * be the wrong disk! * * So, check if there is another list entry in this system * with the same location code as the current entry; if so, * only handle Marvell devices if '-d <dev_name>' is used. */ if (!dvalue && get_indicator_for_loc_code(current->next, lvalue)) { fprintf(stdout, "The Marvell HDD LEDs must be " "specified by device name (-d option);" " non-unique location codes found.\n"); rc = 1; goto no_retry; } /* * At this point, after the check for "if (dvalue && lvalue)", * if dvalue is non-NULL then lvalue is from get_loc_code_dev() * (based on device name: dvalue), and dvalue is from cmdline. * * So, if dvalue is non-NULL and doesn't match the device name * specified in 'current' (found location code), let's try the * next elements in the list (which may match the device name); * for this we need to retry, re-starting on the next element. */ if (dvalue && current->devname[0] != '\0' && strncmp(dvalue, current->devname, DEV_LENGTH)) { list_start = current->next; goto retry; } } if (svalue) { rc = get_indicator_state(indicator, current, &state); if (rc || state != c) { rc = set_indicator_state(indicator, current, c); if (rc) goto indicator_cleanup; indicator_log_state(indicator, current->code, c); } } rc = get_indicator_state(indicator, current, &state); if (!rc) { if (dvalue) fprintf(stdout, "%s\t[%s]\n", lvalue, state ? "on" : "off"); else fprintf(stdout, "%s\n", state ? "on" : "off"); } } /* if-else end */ } /* lvalue end */ no_retry: /* Turn on/off all indicators */ if (othervalue) { current = list; while (current) { rc = get_indicator_state(indicator, current, &state); if (rc) /* failed to get indicator state */ current->state = -1; else current->state = state; if (state != c) { set_indicator_state(indicator, current, c); rc = get_indicator_state(indicator, current, &state); if (rc) /* failed to get indicator state */ current->state = -1; else current->state = state; } print_indicator_state(current); current = current->next; } /* If enclosure ident indicator is turned ON explicitly, * then turning OFF all components ident indicator inside * enclosure does not turn OFF enclosure ident indicator. */ if (indicator == LED_TYPE_IDENT && c == LED_STATE_OFF) set_indicator_state(indicator, &list[0], c); indicator_log_write("All %s Indicators : %s", get_indicator_desc(indicator), c == LED_STATE_ON ? "ON" : "OFF"); } indicator_cleanup: free_indicator_list(list); file_cleanup: close_files(); return rc; }
13,152
C
.c
462
24.489177
82
0.622509
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,713,614
indicator_ses.h
power-ras_ppc64-diag/lpd/indicator_ses.h
/** * Copyright (C) 2012 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef INDICATOR_SES_H #define INDICATOR_SES_H /* SES support */ extern void get_ses_indices(int, struct loc_code **); extern int get_ses_indicator(int, struct loc_code *, int *); extern int set_ses_indicator(int, struct loc_code *, int); #endif /* INDICATOR_SES_H */
1,039
C
.c
24
41.5
81
0.752964
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,615
lp_util.c
power-ras_ppc64-diag/lpd/lp_util.c
/** * @file lp_util.c * @brief Light Path utility * * Copyright (C) 2012 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @author Vasant Hegde <[email protected]> */ #include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <dirent.h> #include <errno.h> #include <sys/types.h> #include "indicator.h" #include "utils.h" #define LSVPD_PATH "/usr/sbin/lsvpd" /* Note: * At present, we do not support all SES enclosures/devices. Consider * removing device_supported() and enclosure_supported() once we * have Light Path support for all enclosures/devices. */ /* List of all Light Path supported enclosures */ static struct { char *model; } supported_ses_enclosure[] = { {"5888"}, /* Bluehawk */ {"EDR1"}, /* Bluehawk */ {"5887"}, /* Homerun */ {"ESLL"}, /* Slider - LFF */ {"ESLS"}, /* Slider - SFF */ {NULL} }; /* List of all Light Path supported devices */ static struct { char *subsystem; char *driver; } os_supported_device[] = { {"net", "cxgb3"}, /* Chelsio network card*/ {"net", "e1000e"}, /* Intel network card*/ {NULL, NULL} }; /** * device_supported - Check Light Path support for device * * @subsystem subsystem * @driver kernel driver * * Returns : * 1 if device is supported / 0 if device is not supported */ int device_supported(const char *subsystem, const char *driver) { int i; if (!subsystem || !driver) return 0; for (i = 0; os_supported_device[i].driver; i++) if (!strcmp(os_supported_device[i].subsystem, subsystem) && !strcmp(os_supported_device[i].driver, driver)) return 1; return 0; } /** * enclosure_supported - Check Light Path support for enclosure * * @model enclosure model * * Returns : * 1 if enclosure is supported / 0 if enclosure is not supported */ int enclosure_supported(const char *model) { int i; if (!model) return 0; for (i = 0; supported_ses_enclosure[i].model; i++) if (!strcmp(supported_ses_enclosure[i].model, model)) return 1; return 0; } /** * fgets_nonl - Read a line and strip the newline. */ char * fgets_nonl(char *buf, int size, FILE *s) { char *nl; if (!fgets(buf, size, s)) return NULL; nl = strchr(buf, '\n'); if (nl == NULL) return NULL; *nl = '\0'; return buf; } /** * skip_space - */ static char * skip_space(const char *pos) { pos = strchr(pos, ' '); if (!pos) return NULL; while (*pos == ' ') pos++; return (char *)pos; } /** * read_vpd_from_lsvpd - Retrieve vpd data * * Returns : * 0 on success, !0 on failure */ int read_vpd_from_lsvpd(struct dev_vpd *vpd, const char *device) { char buf[128]; char *pos; char *args[] = {LSVPD_PATH, "-l", (char *const)device, NULL}; pid_t cpid; int rc; FILE *fp; /* use lsvpd to find the device vpd */ fp = spopen(args, &cpid); if (fp == NULL) { log_msg("Unable to retrieve the vpd for \"%s\". " "Ensure that lsvpd package is installed.", device); return -1; } while (fgets_nonl(buf, 128, fp) != NULL) { if ((pos = strstr(buf, "*TM")) != NULL) { if (!(pos = skip_space(pos))) continue; strncpy(vpd->mtm, pos, VPD_LENGTH - 1); vpd->mtm[VPD_LENGTH - 1] = '\0'; } else if ((pos = strstr(buf, "*YL")) != NULL) { if (!(pos = skip_space(pos))) continue; strncpy(vpd->location, pos, LOCATION_LENGTH - 1); vpd->location[LOCATION_LENGTH - 1] = '\0'; } else if ((pos = strstr(buf, "*DS")) != NULL) { if (!(pos = skip_space(pos))) continue; strncpy(vpd->ds, pos, VPD_LENGTH - 1); vpd->ds[VPD_LENGTH - 1] = '\0'; } else if ((pos = strstr(buf, "*SN")) != NULL) { if (!(pos = skip_space(pos))) continue; strncpy(vpd->sn, pos, VPD_LENGTH - 1); vpd->sn[VPD_LENGTH - 1] = '\0'; } else if ((pos = strstr(buf, "PN")) != NULL) { if (!(pos = skip_space(pos))) continue; strncpy(vpd->pn, pos, VPD_LENGTH - 1); vpd->pn[VPD_LENGTH - 1] = '\0'; } else if ((pos = strstr(buf, "*FN")) != NULL) { if (!(pos = skip_space(pos))) continue; strncpy(vpd->fru, pos, VPD_LENGTH - 1); vpd->fru[VPD_LENGTH - 1] = '\0'; } } rc = spclose(fp, cpid); if (rc) { log_msg("%s: spclose() failed [rc=%d]\n", __func__, rc); return -1; } return 0; } /** * free_device_vpd - free vpd structure */ void free_device_vpd(struct dev_vpd *vpd) { struct dev_vpd *tmp; while (vpd) { tmp = vpd; vpd = vpd->next; free(tmp); } } /** * read_device_vpd - * * @path /sys path * * Returns : * vpd structure on success / NULL on failure */ struct dev_vpd * read_device_vpd(const char *path) { DIR *dir; struct dirent *dirent; struct dev_vpd *vpd = NULL; struct dev_vpd *curr = NULL; dir = opendir(path); if (!dir) { if (errno != ENOENT) log_msg("Unable to open directory : %s", path); return NULL; } while ((dirent = readdir(dir)) != NULL) { if (!strcmp(dirent->d_name, ".") || !strcmp(dirent->d_name, "..")) continue; if (!curr) { curr = calloc(1, sizeof(struct dev_vpd)); vpd = curr; } else { curr->next = calloc(1, sizeof(struct dev_vpd)); curr = curr->next; } if (!curr) { log_msg("Out of memory"); free_device_vpd(vpd); closedir(dir); return NULL; } /* device name */ strncpy(curr->dev, dirent->d_name, DEV_LENGTH - 1); curr->dev[DEV_LENGTH - 1] = '\0'; if (read_vpd_from_lsvpd(curr, dirent->d_name)) { free_device_vpd(vpd); closedir(dir); return NULL; } } closedir(dir); return vpd; } /** * fill_indicators_vpd - Fill indicators vpd data */ void fill_indicators_vpd(struct loc_code *list) { struct dev_vpd vpd; struct loc_code *curr; for (curr = list; curr; curr = curr->next) { /* zero out the vpd structure */ memset(&vpd, 0, sizeof(struct dev_vpd)); if (read_vpd_from_lsvpd(&vpd, curr->code)) return; strncpy(curr->devname, vpd.dev, DEV_LENGTH); strncpy(curr->mtm, vpd.mtm, VPD_LENGTH); strncpy(curr->sn, vpd.sn, VPD_LENGTH); strncpy(curr->pn, vpd.pn, VPD_LENGTH); strncpy(curr->fru, vpd.fru, VPD_LENGTH); /* retain existing DS */ if (curr->ds[0] == '\0') strncpy(curr->ds, vpd.ds, VPD_LENGTH); } } /** * get_loc_code_for_dev - Get location code for the given device * * @device device name * @location output location code * @locsize location code size * * Returns : * 0 on success / -1 on failure */ int get_loc_code_for_dev(const char *device, char *location, int locsize) { struct dev_vpd vpd; memset(&vpd, 0, sizeof(struct dev_vpd)); if (device && !read_vpd_from_lsvpd(&vpd, device)) { if (location && vpd.location[0] != '\0') { strncpy(location, vpd.location, locsize); location[locsize - 1] = '\0'; return 0; } } return -1; }
7,313
C
.c
297
22.208754
81
0.648761
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,616
indicator_opal.c
power-ras_ppc64-diag/lpd/indicator_opal.c
/** * @file indicator_opal.c * @brief OPAL indicator manipulation routines * * Copyright (C) 2015 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @author Vasant Hegde <[email protected]> */ #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "indicator.h" #include "indicator_ses.h" #include "indicator_marvell.h" /* LED directory */ #define OPAL_LED_SYSFS_PATH "/sys/class/leds" #define OPAL_LED_FILE "brightness" /* LED Mode */ #define OPAL_LED_MODE_PROPERTY "/proc/device-tree/ibm,opal/leds/led-mode" #define OPAL_LED_MODE_LIGHT_PATH "lightpath" #define OPAL_LED_MODE_GUIDING_LIGHT "guidinglight" /* * LEDs are available under /sys/class/leds directory. Open this * dir for various LED operations. */ static DIR * open_sysfs_led_dir(void) { int rc; DIR *dir; rc = access(OPAL_LED_SYSFS_PATH, R_OK); if (rc != 0) { log_msg("%s : Error accessing led sysfs dir: %s (%d: %s)", __func__, OPAL_LED_SYSFS_PATH, errno, strerror(errno)); return NULL; } dir = opendir(OPAL_LED_SYSFS_PATH); if (!dir) log_msg("%s : Failed to open led sysfs dir : %s (%d: %s)", __func__, OPAL_LED_SYSFS_PATH, errno, strerror(errno)); return dir; } /* Close LED class dir */ static inline void close_sysfs_led_dir(DIR *dir) { closedir(dir); } /* Parse LED location code */ static struct loc_code * opal_parse_loc_code(int indicator, struct loc_code *loc, const char *dirname) { char *colon; int loc_len; struct loc_code *curr = loc; colon = strstr(dirname, ":"); if (!colon) { log_msg("%s : Invalid location code", __func__); return loc; } loc_len = colon - dirname; if (loc_len <= 0 || loc_len >= LOCATION_LENGTH) { log_msg("%s : Invalid location code length", __func__); return loc; } if (!curr) { curr = malloc(sizeof(struct loc_code)); loc = curr; } else { while (curr->next) curr = curr->next; curr->next = malloc(sizeof(struct loc_code)); curr = curr->next; } if (!curr) { log_msg("%s : Out of memory", __func__); return loc; } memset(curr, 0, sizeof(struct loc_code)); strncpy(curr->code, dirname, loc_len); curr->code[loc_len] = '\0'; curr->length = loc_len + 1; /* Including NULL */ curr->type = TYPE_OPAL; curr->index = indicator; /* LED_TYPE_{ATTN/IDENT/FAULT} */ curr->next = NULL; return loc; } /** * Get OPAL platform related indicator list * * @indicator identification or attention/fault indicator * @loc pointer to loc_code structure * * Returns : * 0 on success, !0 on failure */ static int opal_get_indices(int indicator, struct loc_code **loc) { const char *indicator_desc; int i; int rc = -1; int nleds; struct loc_code *list = *loc; struct dirent **dirlist; struct dirent *dirent; indicator_desc = get_indicator_desc(indicator); if (!indicator_desc) return rc; nleds = scandir(OPAL_LED_SYSFS_PATH, &dirlist, NULL, alphasort); if (nleds == -1) { log_msg("%s : Failed to read led sysfs dir : %s", __func__, OPAL_LED_SYSFS_PATH); return rc; } for (i = 0; i < nleds; i++) { dirent = dirlist[i]; if (dirent->d_type != DT_DIR && dirent->d_type != DT_LNK) { free(dirlist[i]); continue; } if (strstr(dirent->d_name, indicator_desc)) list = opal_parse_loc_code(indicator, list, dirent->d_name); free(dirlist[i]); } *loc = list; free(dirlist); return 0; } /* Open /sys/class/leds/<loc_code>:<led_type>/brightnes file */ static int open_led_brightness_file(struct loc_code *loc, int mode) { const char *indicator_desc; char filename[PATH_MAX]; int len; int fd; int rc = -1; indicator_desc = get_indicator_desc(loc->index); if (!indicator_desc) return rc; len = snprintf(filename, PATH_MAX, "%s/%s:%s/%s", OPAL_LED_SYSFS_PATH, loc->code, indicator_desc, OPAL_LED_FILE); if (len >= PATH_MAX) { log_msg("%s : Path to LED brightness file is too big", __func__); return rc; } fd = open(filename, mode); if (fd == -1) log_msg("%s : Failed to open %s file", __func__, filename); return fd; } static inline void close_led_brightness_file(int fd) { close(fd); } /** * opal_get_indicator - Get OPAL LED state * * @indicator identification or attention indicator * @loc location code of the sensor * @state return sensor state for the given loc * * Returns : * 0 on success, !0 on failure */ static int opal_get_indicator(struct loc_code *loc, int *state) { int fd; int rc = -1; char buf[4]; fd = open_led_brightness_file(loc, O_RDONLY); if (fd == -1) return rc; rc = read(fd, buf, 4); if (rc == -1) { log_msg("%s : Failed to read LED state. (%d : %s)", __func__, errno, strerror(errno)); close_led_brightness_file(fd); return rc; } *state = atoi(buf); close_led_brightness_file(fd); return 0; } /** * opal_set_indicator - Set OPAL indicator * * @indicator identification or attention indicator * @loc location code of OPAL indicator * @new_value value to update indicator to * * Returns : * 0 on success, !0 on failure */ static int opal_set_indicator(struct loc_code *loc, int new_value) { char buf = '0'; int fd; int rc = -1; if (new_value) buf = '1'; fd = open_led_brightness_file(loc, O_WRONLY); if (fd == -1) return rc; rc = write(fd, &buf, 1); if (rc == -1) { log_msg("%s : Failed to modify LED state. (%d : %s)", __func__, errno, strerror(errno)); close_led_brightness_file(fd); return rc; } close_led_brightness_file(fd); return 0; } /* * opal_indicator_probe_led_class - Probe LED class (/sys/class/leds) * indicator support on OPAL based platform * * Returns: * 0 if indicator is supported, else -1 */ static int opal_indicator_probe_led_class(void) { int rc = -1; DIR *led_dir; struct dirent *dirent; led_dir = open_sysfs_led_dir(); if (!led_dir) return rc; /* * LED is supported if we have at least directory * under /sys/class/leds */ while ((dirent = readdir(led_dir)) != NULL) { if (!strcmp(dirent->d_name, ".") || !strcmp(dirent->d_name, "..")) continue; if (dirent->d_type != DT_DIR && dirent->d_type != DT_LNK) continue; close_sysfs_led_dir(led_dir); return 0; } close_sysfs_led_dir(led_dir); return rc; } /* * opal_indicator_probe_marvell - Probe Marvell indicator support on * OPAL based platform * * Returns: * 0 if indicator is supported, else -1 */ static int opal_indicator_probe_marvell(void) { struct loc_code *list = NULL; get_mv_indices(LED_TYPE_IDENT, &list); if (list) { free_indicator_list(list); return 0; } return -1; } /* * opal_indicator_probe - Probe indicator support on OPAL based platform * * Returns: * 0 if indicator is supported, else -1 */ static int opal_indicator_probe(bool platform_only) { int rc = -1; if (platform_only) system_scan_flag = 1 << TYPE_OPAL; else system_scan_flag = 1 << TYPE_ALL | 1 << TYPE_OPAL | 1 << TYPE_SES | 1 << TYPE_MARVELL; if (!opal_indicator_probe_led_class()) rc = 0; /* * Marvell HDD LEDs are not presented/controlled via kernel LEDs * (i.e., /sys/class/leds), and some OPAL systems might not have * any kernel LEDs (e.g., modules not loaded) but still have the * Marvell SATA controller with LEDs available, and able to work. */ if ((system_scan_flag & (1 << TYPE_MARVELL)) && !opal_indicator_probe_marvell()) rc = 0; return rc; } /** * opal_get_indicator_mode - Gets the service indicator operating mode * * Returns : * operating mode value */ static int opal_get_indicator_mode(void) { char buf[128]; int rc = 0; int fd; int readsz; struct stat sbuf; rc = stat(OPAL_LED_MODE_PROPERTY, &sbuf); if (rc) { operating_mode = LED_MODE_LIGHT_PATH; return 0; } fd = open(OPAL_LED_MODE_PROPERTY, O_RDONLY); if (fd == -1) { log_msg("%s : Failed to open led mode DT file : %s (%d : %s)", __func__, OPAL_LED_MODE_PROPERTY, errno, strerror(errno)); return -1; } readsz = read(fd, buf, 128); if (readsz == -1) { log_msg("%s : Failed to read led mode : %s (%d : %s)", __func__, OPAL_LED_MODE_PROPERTY, errno, strerror(errno)); close(fd); return -1; } if (!strcmp(buf, OPAL_LED_MODE_LIGHT_PATH)) operating_mode = LED_MODE_LIGHT_PATH; else if (!strcmp(buf, OPAL_LED_MODE_GUIDING_LIGHT)) operating_mode = LED_MODE_GUIDING_LIGHT; else { log_msg("%s : Unknown LED operating mode\n", __func__); rc = -1; } close(fd); return rc; } /** * opal_get_indicator_list - Build indicator list of given type * * @indicator identification or fault indicator * @list loc_code structure * * Returns : * 0 on success, !0 otherwise */ static int opal_get_indicator_list(int indicator, struct loc_code **list) { /* * We treat first indicator in fault indicator list as * check log indicator. Hence parse attention indicator. */ if (indicator == LED_TYPE_FAULT) opal_get_indices(LED_TYPE_ATTN, list); /* FRU fault indicators are not supported in Guiding Light mode */ if (indicator == LED_TYPE_FAULT && operating_mode == LED_MODE_GUIDING_LIGHT) return 0; /* * Get OPAL indicator list * NB: Check the system_scan_flag if scanning needs to be * prevented for platform indicators */ opal_get_indices(indicator, list); /* SES indicators */ if (system_scan_flag & (1 << TYPE_SES)) get_ses_indices(indicator, list); /* Marvell HDD LEDs (indicators) */ if (system_scan_flag & (1 << TYPE_MARVELL)) get_mv_indices(indicator, list); if (*list == NULL) { log_msg("The %s indicators are not supported on this system", get_indicator_desc(indicator)); } /* * The list pointer (*list) is initially NULL. * If it's not-NULL here, we found indicators. */ return !(*list); } /** * opal_get_indicator_state - Retrieve the current state for an indicator * * @indicator identification or attention indicator * @loc location code of the sensor * @state return location for the sensor state * * Returns : * indicator return code */ static int opal_get_indicator_state(int indicator, struct loc_code *loc, int *state) { switch (loc->type) { case TYPE_OPAL: return opal_get_indicator(loc, state); case TYPE_SES: return get_ses_indicator(indicator, loc, state); case TYPE_MARVELL: return get_mv_indicator(indicator, loc, state); default: break; } return -1; } /** * opal_set_indicator_state - Set an indicator to a new state (on or off) * * Call the appropriate routine for setting indicators based on the type * of indicator. * * @indicator identification or attention indicator * @loc location code of opal indicator * @new_value value to update indicator to * * Returns : * indicator return code */ static int opal_set_indicator_state(int indicator, struct loc_code *loc, int new_value) { switch (loc->type) { case TYPE_OPAL: return opal_set_indicator(loc, new_value); case TYPE_SES: return set_ses_indicator(indicator, loc, new_value); case TYPE_MARVELL: return set_mv_indicator(indicator, loc, new_value); default: break; } return -1; } struct platform opal_platform = { .name = "opal", .probe = opal_indicator_probe, .get_indicator_mode = opal_get_indicator_mode, .get_indicator_list = opal_get_indicator_list, .get_indicator_state = opal_get_indicator_state, .set_indicator_state = opal_set_indicator_state, };
12,126
C
.c
469
23.560768
81
0.685455
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,617
servicelog.h
power-ras_ppc64-diag/lpd/servicelog.h
/** * Copyright (C) 2015 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef SERVICELOG_H #define SERVICELOG_H #include <servicelog-1/servicelog.h> /* servicelog.c */ extern int get_service_event(int, struct sl_event **); extern int get_all_open_service_event(struct sl_event **); extern int get_repair_event(int, struct sl_event **); extern int print_service_event(struct sl_event *); #endif /* SERVICELOG_H */
1,114
C
.c
26
41.076923
81
0.759225
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,618
ledtool.c
power-ras_ppc64-diag/lpd/test/ledtool.c
/** * @file ledtool.c * @brief Light Path Diagnostics testing tool * * Copyright (C) 2012 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @author Vasant Hegde <[email protected]> */ #include <stdio.h> #include <unistd.h> #include <getopt.h> #include <stdlib.h> #include "indicator.h" /** * enable_fault_indicator - Enable fault indicator for the given loc code */ int enable_fault_indicator(char *loccode, int truncate) { int rc = 0; int truncated = 0; struct loc_code *list = NULL; struct loc_code *loc_led = NULL; rc = get_indicator_list(LED_TYPE_FAULT, &list); if (!list) return -1; if (loccode == NULL) { /* attn indicator */ loc_led = &list[0]; } else { retry: loc_led = get_indicator_for_loc_code(list, loccode); if (!loc_led) { if (truncate && truncate_loc_code(loccode)) { truncated = 1; goto retry; } fprintf(stderr, "There is no fault indicator at " "location code %s\n", loccode); free_indicator_list(list); return 0; } } if (truncated) fprintf(stderr, "Truncated location code = %s\n", loccode); rc = set_indicator_state(LED_TYPE_FAULT, loc_led, 1); if (rc == 0) { if (loccode == NULL) indicator_log_write("System Attention Indicator : ON"); else indicator_log_write("%s : Fault : ON", loc_led->code); fprintf(stderr, "%s : \[on]\n", loc_led->code); } else fprintf(stderr, "Unable to enable fault indicator\n"); free_indicator_list(list); return rc; } void print_usage(char *progname) { fprintf(stdout, "Enable system attention/fault indicators.\n" "\nUsage : %s -f [<loc_code>]\n" "\t-f : Fault indicator\n" "\t-t : Truncate location code if necessary\n" "\t-h : Print this message and exit\n" "\n\tloc_code : Location code\n", progname); } /* ledtool command line arguments */ #define LED_TOOL_ARGS "fht" /* main */ int main(int argc, char **argv) { char *loccode = NULL; int rc = 0; int c; int fault = 0; int truncate = 0; opterr = 0; while ((c = getopt(argc, argv, LED_TOOL_ARGS)) != -1) { switch (c) { case 'f': fault = 1; break; case 'h': print_usage(argv[0]); exit(0); case 't': truncate = 1; break; default: print_usage(argv[0]); exit(1); } } if (optind < argc) loccode = argv[optind++]; if (optind < argc) { print_usage(argv[0]); exit(1); } if (!fault) { print_usage(argv[0]); exit(1); } program_name = argv[0]; lp_error_log_fd = STDOUT_FILENO; /* log message to stdout */ rc = init_files(); if (rc) { fprintf(stderr, "Unable to open log file.\n"); exit(1); } if ((platform_initialize() != 0) || (probe_indicator(false) != 0)) { close_files(); exit(1); } /* Light Path operating mode */ if (get_indicator_mode() != 0) { close_files(); exit(1); } /* enable fault indicator */ rc = enable_fault_indicator(loccode, truncate); close_files(); exit(rc); }
3,579
C
.c
138
23.391304
81
0.674759
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,619
sesdevices.c
power-ras_ppc64-diag/lpd/test/sesdevices.c
/** * @file sesdevices.c * @brief List all Light Path Daignostics supported SES enclosures * * Copyright (C) 2012 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @author Vasant Hegde <[email protected]> */ #define _GNU_SOURCE #include <stdio.h> #include <string.h> #include <stdlib.h> #include <dirent.h> #include <sys/types.h> #include "indicator.h" #include "lp_util.h" /* SES sys path */ #define SCSI_SES_PATH "/sys/class/enclosure" /* List of all Light Path supported enclosures */ static struct { char *mtm; } supported_enclosure[] = { {"5888"}, /* Bluehawk */ {"EDR1"}, /* Bluehawk */ {NULL} }; /* trim ESM/ERM part */ static void trim_location_code(struct dev_vpd *vpd) { char *hyphen; hyphen = strchr(vpd->location, '-'); if (hyphen && (!strcmp(hyphen, "-P1-C1") || !strcmp(hyphen, "-P1-C2"))) *hyphen = '\0'; } int main() { int i; int count = 0; char *path = NULL; DIR *dir; struct dirent *dirent; struct dev_vpd *vpd = NULL; struct dev_vpd *v1; vpd = read_device_vpd(SCSI_SES_PATH); if (!vpd) return 0; for (v1 = vpd; v1; v1 = v1->next) { /* remove ESM/ERM part of location code */ trim_location_code(v1); /* read sg name */ if (asprintf(&path, "%s/%s/device/scsi_generic", SCSI_SES_PATH, v1->dev) < 0) { fprintf(stderr, "Unable to allocate memory\n"); continue; } dir = opendir(path); if (!dir) { fprintf(stderr, "Unable to open directory : %s\n", path); free(path); continue; } free(path); /* fill sg device name */ while ((dirent = readdir(dir)) != NULL) { if (!strcmp(dirent->d_name, ".") || !strcmp(dirent->d_name, "..")) continue; strncpy(v1->dev, dirent->d_name, DEV_LENGTH); } closedir(dir); } for (v1 = vpd; v1; v1 = v1->next) for (i = 0; supported_enclosure[i].mtm; i++) if (!strcmp(v1->mtm, supported_enclosure[i].mtm)) { count++; fprintf(stdout, "\n"); fprintf(stdout, "SCSI Device : %s\n", v1->dev); fprintf(stdout, "Model : %s\n", v1->mtm); fprintf(stdout, "Location Code : %s\n", v1->location); fprintf(stdout, "Serial Number : %s\n", v1->sn); } if (count == 0) fprintf(stderr, "System does not have Light Path supported " "SES enclosure(s).\n"); free_device_vpd(vpd); return 0; }
3,015
C
.c
103
26.31068
81
0.658832
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,621
extract_opal_dump.c
power-ras_ppc64-diag/opal_errd/extract_opal_dump.c
/** * @file extract_opal_dump.c * @brief Command to extract a platform dump on PowerNV platform * and copy it to the filesystem * * Copyright (C) 2014 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdint.h> #include <sys/stat.h> #include <errno.h> #include <string.h> #include <limits.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <dirent.h> #include <endian.h> #include <syslog.h> #include <libgen.h> #include "platform.c" #define DEFAULT_SYSFS_PATH "/sys" #define DEFAULT_DUMP_PATH "firmware/opal/dump" #define DEFAULT_OUTPUT_DIR "/var/log/dump" #define DUMP_TYPE_LEN 7 /* Retention policy : default maximum dumps of each type */ #define DEFAULT_MAX_DUMP 4 int opt_ack_dump = 1; int opt_wait = 0; int opt_max_dump = DEFAULT_MAX_DUMP; char *opt_sysfs = DEFAULT_SYSFS_PATH; char *opt_output_dir = DEFAULT_OUTPUT_DIR; static void help(const char* argv0) { fprintf(stderr, "%s help:\n", argv0); fprintf(stderr, "\n"); fprintf(stderr, "-A - Don't acknowledge dump\n"); fprintf(stderr, "-s dir - sysfs directory (default %s)\n", DEFAULT_SYSFS_PATH); fprintf(stderr, "-o dir - directory to save dumps (default %s)\n", DEFAULT_OUTPUT_DIR); fprintf(stderr, "-m max - maximum number of dumps of a specific type" " to be saved\n"); fprintf(stderr, "-w - wait for a dump\n"); fprintf(stderr, "-h - help (this message)\n"); } #define DUMP_HDR_PREFIX_OFFSET 0x16 /* Prefix size in dump header */ #define DUMP_HDR_FNAME_OFFSET 0x18 /* Suggested filename in dump header */ #define DUMP_MAX_FNAME_LEN 48 /* Including .PARTIAL */ static void dump_get_file_name(char *buf, int bsize, char *dfile, int dfile_size, uint16_t *prefix_size) { if (bsize >= DUMP_HDR_PREFIX_OFFSET + sizeof(uint16_t)) *prefix_size = be16toh(*(uint16_t *)(buf + DUMP_HDR_PREFIX_OFFSET)); if (bsize >= DUMP_HDR_FNAME_OFFSET + DUMP_MAX_FNAME_LEN) { strncpy(dfile, buf + DUMP_HDR_FNAME_OFFSET, dfile_size - 1); dfile[dfile_size - 1] = '\0'; } else strncpy(dfile, "platform.dumpid.PARTIAL", dfile_size); dfile[dfile_size - 1] = '\0'; } static void ack_dump(const char* dump_dir_path) { char ack_file[PATH_MAX]; int fd; int rc; rc = snprintf(ack_file, sizeof(ack_file), "%s/acknowledge", dump_dir_path); if (rc < 0 || rc >= sizeof(ack_file)) { syslog(LOG_ERR, "%s:%d - Unable to format %s\n", __func__, __LINE__, dump_dir_path); return; } fd = open(ack_file, O_WRONLY); if (fd == -1) { syslog(LOG_ERR, "Failed to acknowledge platform dump: %s" " (%d:%s)\n", ack_file, errno, strerror(errno)); return; } rc = write(fd, "ack\n", 4); if (rc != 4) { syslog(LOG_ERR, "Failed to acknowledge platform dump: %s" " (%d:%s)\n", ack_file, errno, strerror(errno)); } close(fd); } /** * Check for duplicate file */ static void check_dup_dump_file(char *dumpname) { char dump_path[PATH_MAX]; int rc; rc = snprintf(dump_path, PATH_MAX, "%s/%s", opt_output_dir, dumpname); if (rc >= PATH_MAX) { syslog(LOG_NOTICE, "Path to dump file (%s) is too big", dumpname); return; } if (access(dump_path, R_OK) == -1) return; if (unlink(dump_path) < 0) syslog(LOG_NOTICE, "Could not delete file \"%s\" " "(%s) to make room for incoming platform dump." " The new dump will be saved anyways.\n", dump_path, strerror(errno)); } static int timesort(const struct dirent **file1, const struct dirent **file2) { struct stat sbuf1, sbuf2; char dump_path1[PATH_MAX]; char dump_path2[PATH_MAX]; int rc; rc = snprintf(dump_path1, PATH_MAX, "%s/%s", opt_output_dir, (*file1)->d_name); if (rc < 0 || rc >= PATH_MAX) { syslog(LOG_ERR, "%s:%d - Unable to format %s\n", __func__, __LINE__, (*file1)->d_name); return -1; } rc = snprintf(dump_path2, PATH_MAX, "%s/%s", opt_output_dir, (*file2)->d_name); if (rc < 0 || rc >= PATH_MAX) { syslog(LOG_ERR, "%s:%d - Unable to format %s\n", __func__, __LINE__, (*file2)->d_name); return -1; } rc = stat(dump_path1, &sbuf1); if (rc < 0) return rc; rc = stat(dump_path2, &sbuf2); if (rc < 0) return rc; return (sbuf2.st_mtime - sbuf1.st_mtime); } /** * remove_dump_files * @brief if needed, remove any old dump files * * Users can specify the number of old dumpfiles they wish to save * via command line option. This routine will search through and remove * any dump files of the specified type if the count exceeds the maximum value. * */ static void remove_dump_files(char *dumpname) { struct dirent **namelist; struct dirent *dirent; char dump_path[PATH_MAX]; int i; int n; int count = 0; int rc; check_dup_dump_file(dumpname); n = scandir(opt_output_dir, &namelist, NULL, timesort); if (n < 0) return; for (i = 0; i < n; i++) { dirent = namelist[i]; /* Skip dump files of different type */ if (dirent->d_name[0] == '.' || strncmp(dumpname, dirent->d_name, DUMP_TYPE_LEN)) { free(namelist[i]); continue; } count++; rc = snprintf(dump_path, PATH_MAX, "%s/%s", opt_output_dir, dirent->d_name); if (rc < 0 || rc >= PATH_MAX) { syslog(LOG_ERR, "%s:%d - Unable to format %s\n", __func__, __LINE__, dirent->d_name); free(namelist[i]); continue; } free(namelist[i]); if (count < opt_max_dump) continue; if (unlink(dump_path) < 0) syslog(LOG_NOTICE, "Could not delete file \"%s\" " "(%s) to make room for incoming platform dump." " The new dump will be saved anyways.\n", dump_path, strerror(errno)); } free(namelist); } static int process_dump(const char* dump_dir_path, const char *output_dir) { int in_fd = -1; int out_fd = -1; int dir_fd = -1; char dump_path[PATH_MAX]; char final_dump_path[PATH_MAX]; char *buf; size_t bufsz; struct stat sbuf; int ret = -1; ssize_t sz = 0; ssize_t readsz = 0; char outfname[DUMP_MAX_FNAME_LEN]; uint16_t prefix_size; int rc; rc = snprintf(dump_path, sizeof(dump_path), "%s/dump", dump_dir_path); if (rc < 0 || rc >= sizeof(dump_path)) { syslog(LOG_ERR, "%s:%d - Unable to format %s\n", __func__, __LINE__, dump_dir_path); return -1; } if (stat(dump_path,&sbuf) == -1) return -1; bufsz = sbuf.st_size; buf = malloc(bufsz); if (!buf) { syslog(LOG_ERR, "Failed to allocate memory for dump\n"); return -1; } in_fd = open(dump_path, O_RDONLY); if (in_fd == -1) { syslog(LOG_ERR, "Failed to open platform dump: %s (%d:%s)\n", dump_path, errno, strerror(errno)); goto err; } do { readsz = read(in_fd, buf+sz, bufsz-sz); if (readsz == -1) { syslog(LOG_ERR, "Failed to read platform dump: %s " "(%d:%s)\n", dump_path, errno, strerror(errno)); goto err; } sz += readsz; } while(sz != bufsz); dump_get_file_name(buf, bufsz, outfname, DUMP_MAX_FNAME_LEN, &prefix_size); snprintf(dump_path, sizeof(dump_path), "%s/%s.tmp", output_dir, outfname); snprintf(final_dump_path, sizeof(dump_path), "%s/%s", output_dir, outfname); remove_dump_files(outfname); out_fd = open(dump_path, O_WRONLY|O_CREAT|O_EXCL, S_IRUSR|S_IRGRP); if (out_fd == -1) { syslog(LOG_ERR, "Failed to write platform dump: %s (%d:%s)\n", dump_path, errno, strerror(errno)); goto err; } sz = write(out_fd, buf, bufsz); if (sz != bufsz) { syslog(LOG_ERR, "Failed to write platform dump: %s (%d:%s)\n", dump_path, errno, strerror(errno)); unlink(dump_path); goto err; } rc = fsync(out_fd); if (rc == -1) { syslog(LOG_ERR, "Failed to sync platform dump: %s (%d:%s)\n", dump_path, errno, strerror(errno)); goto err; } rc = rename(dump_path, final_dump_path); if (rc == -1) { syslog(LOG_ERR, "Failed to rename platform dump %s to %s" "(%d: %s)\n", dump_path, final_dump_path, errno, strerror(errno)); goto err; } dir_fd = open(output_dir, O_RDONLY|O_DIRECTORY); if (dir_fd == -1) { syslog(LOG_ERR, "Failed to open platform dump directory: %s" " (%d:%s)\n", output_dir, errno, strerror(errno)); goto err; } rc = fsync(dir_fd); if (rc == -1) { syslog(LOG_ERR, "Failed to sync platform dump directory: %s" " (%d:%s)\n", output_dir, errno, strerror(errno)); } syslog(LOG_NOTICE, "New platform dump available. File: %s/%s\n", output_dir, outfname); ret = 0; err: if (in_fd != -1) close(in_fd); if (out_fd != -1) close(out_fd); if (dir_fd != -1) close(dir_fd); free(buf); return ret; } static int find_and_process_dumps(const char *opal_dump_dir, const char *output_dir) { int rc; int retval= 0; struct dirent **namelist; struct dirent *dirent; char dump_path[PATH_MAX]; int is_dir= 0; struct stat sbuf; int n; int i; n = scandir(opal_dump_dir, &namelist, NULL, alphasort); if (n < 0) return -1; for (i = 0; i < n; i++) { dirent = namelist[i]; if (dirent->d_name[0] == '.') { free(namelist[i]); continue; } rc = snprintf(dump_path, sizeof(dump_path), "%s/%s", opal_dump_dir, dirent->d_name); if (rc < 0 || rc >= sizeof(dump_path)) { syslog(LOG_ERR, "%s:%d - Unable to format %s\n", __func__, __LINE__, dirent->d_name); free(namelist[i]); continue; } is_dir = 0; if (dirent->d_type == DT_DIR) { is_dir = 1; } else { /* Fall back to stat() */ rc = stat(dump_path, &sbuf); if (rc == -1) { /* skip on stat error */ free(namelist[i]); continue; } if (S_ISDIR(sbuf.st_mode)) { is_dir = 1; } } if (is_dir) { rc = process_dump(dump_path, output_dir); if (rc != 0 && retval == 0) retval = -1; if (rc == 0 && retval >= 0) retval++; if (opt_ack_dump) ack_dump(dump_path); } free(namelist[i]); } free(namelist); return retval; } int main(int argc, char *argv[]) { int opt; char sysfs_path[PATH_MAX]; int rc; int fd; int platform = 0; fd_set exceptfds; platform = get_platform(); if (platform != PLATFORM_POWERNV) { fprintf(stderr, "%s is not supported on the %s platform\n", basename(argv[0]), __power_platform_name(platform)); exit(0); } setlogmask(LOG_UPTO(LOG_NOTICE)); openlog("OPAL_DUMP", LOG_CONS | LOG_PID | LOG_NDELAY | LOG_PERROR, LOG_LOCAL1); while ((opt = getopt(argc, argv, "As:o:m:wh")) != -1) { switch (opt) { case 'A': opt_ack_dump = 0; break; case 's': opt_sysfs = optarg; break; case 'o': opt_output_dir = optarg; break; case 'm': opt_max_dump = atoi(optarg); if (opt_max_dump <= 0) { syslog(LOG_ERR, "Invalid value specified for " "-m option (%d), using default value %d\n", opt_max_dump, DEFAULT_MAX_DUMP); opt_max_dump = DEFAULT_MAX_DUMP; } break; case 'w': opt_wait = 1; break; case 'h': help(argv[0]); closelog(); exit(EXIT_SUCCESS); default: help(argv[0]); closelog(); exit(EXIT_FAILURE); } } snprintf(sysfs_path, sizeof(sysfs_path), "%s/%s", opt_sysfs, DEFAULT_DUMP_PATH); rc = access(sysfs_path, R_OK); if (rc != 0) { syslog(LOG_ERR, "Error accessing sysfs: %s (%d: %s)\n", sysfs_path, errno, strerror(errno)); goto err_out; } rc = access(opt_output_dir, W_OK); if (rc != 0) { if (errno == ENOENT) { rc = mkdir(opt_output_dir, S_IRGRP | S_IRUSR | S_IWGRP | S_IWUSR | S_IXUSR); if (rc != 0) { syslog(LOG_ERR, "Error creating output directory:" "%s (%d: %s)\n", opt_output_dir, errno, strerror(errno)); goto err_out; } } else { syslog(LOG_ERR, "Error accessing output dir: %s (%d: %s)\n", opt_output_dir, errno, strerror(errno)); goto err_out; } } start: rc = find_and_process_dumps(sysfs_path, opt_output_dir); if (rc == 0 && opt_wait) { fd = open(sysfs_path, O_RDONLY|O_DIRECTORY); if (fd < 0) { rc = -1; goto err_out; } FD_ZERO(&exceptfds); FD_SET(fd, &exceptfds); rc = select(fd+1, NULL, NULL, &exceptfds, NULL); close(fd); if (rc == -1) goto err_out; goto start; } err_out: closelog(); if (rc < 0) exit(EXIT_FAILURE); return 0; }
12,746
C
.c
459
24.662309
81
0.63649
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,713,622
opal_errd.c
power-ras_ppc64-diag/opal_errd/opal_errd.c
/** * @file opal_errd.c * @brief Daemon to read/parse OPAL error/events * * Copyright (C) 2014-2019 IBM Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * This file supports * 1. Reading OPAL platform logs from sysfs * 2. Writing OPAL platform logs to individual files under /var/log/opal-elog * 3. ACK platform log * 4. Parsing required fields from log and write to syslog */ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <syslog.h> #include <signal.h> #include <sys/stat.h> #include <limits.h> #include <poll.h> #include <dirent.h> #include <libgen.h> #include <sys/inotify.h> #include <assert.h> #include <endian.h> #include <inttypes.h> #include <time.h> #include <libudev.h> #include <sys/wait.h> #include "opal-elog-parse/opal-elog.h" #include "opal-elog-parse/opal-event-data.h" #include "opal-elog-parse/opal-esel-parse.h" #define INOTIFY_FD 0 #define UDEV_FD 1 #define POLL_TIMEOUT 1000 /* In milliseconds */ #define DEFAULT_SYSFS_PATH "/sys" #define DEFAULT_DUMP_PATH "firmware/opal/dump" #define DEFAULT_OUTPUT_DIR "/var/log/opal-elog" #define DEFAULT_EXTRACT_DUMP_CMD "/usr/sbin/extract_opal_dump" #define DEFAULT_EXTRACT_DUMP_FNAME "extract_opal_dump" /** * Length of elog ID string (including the null) * eg: 0x12345678 */ #define ELOG_STR_SIZE 11 /** * ELOG retention policy */ #define DEFAULT_MAX_ELOGS 1000 volatile int terminate; enum { OPAL_ELOG_INVALID = -1, OPAL_ELOG_INFORMATIONAL, OPAL_ELOG_SERVICEABLE }; /* NB: All suffixes to be of same length */ #define ELOG_FILE_SUFFIX_SRVC "srvc" #define ELOG_FILE_SUFFIX_INFO "info" #define ELOG_FILE_SUFFIX_INVALID "invl" #define ELOG_TYPE_STR(etype) \ ((etype) == OPAL_ELOG_SERVICEABLE) ? \ ELOG_FILE_SUFFIX_SRVC : ELOG_FILE_SUFFIX_INFO static bool rotate_info_logs = false; static bool rotate_srvc_logs = false; /* Safe to ignore sig, this only gets called on SIGTERM */ static void term_handler(int sig) { terminate = 1; } /* may move this into header to avoid code duplication */ static bool is_regular_file(const struct dirent *d) { struct stat sbuf; if (d->d_type == DT_DIR) return 0; if (d->d_type == DT_REG) return 1; if (stat(d->d_name,&sbuf)) return 0; if (S_ISDIR(sbuf.st_mode)) return 0; if (d->d_type == DT_UNKNOWN) return 1; return 0; } /* Your job to free the return value */ static char *find_opal_errd_dir(void) { struct stat sb; ssize_t r; char *errd_path; char *path_end; if (lstat("/proc/self/exe", &sb) == -1) return NULL; errd_path = malloc(sb.st_size + 1); if (!errd_path) return NULL; r = readlink ("/proc/self/exe", errd_path, sb.st_size); if (r <= 0 || r > sb.st_size) goto out; /* Just interested in the path, trim fname */ path_end = strrchr (errd_path, '/'); if (path_end == NULL) goto out; /* + 1 to ensure the trailing / stays in */ *(path_end + 1) = '\0'; return errd_path; out: free(errd_path); return NULL; } /* Your job to free the returned path */ static int find_extract_opal_dump_cmd(char **r_dump_path) { char *errd_path; char *dump_path; *r_dump_path = NULL; /* Check default location */ if (access(DEFAULT_EXTRACT_DUMP_CMD, X_OK) == 0) { /* Exists */ *r_dump_path = strdup(DEFAULT_EXTRACT_DUMP_CMD); if (*r_dump_path == NULL) return -1; return 0; } errd_path = find_opal_errd_dir(); if (!errd_path) return -1; /* Look in where ever errd was executed from */ dump_path = malloc(strlen(errd_path) + strlen(DEFAULT_EXTRACT_DUMP_FNAME) + 1); if (!dump_path) { free(errd_path); return -1; } strcpy(dump_path, errd_path); strcat(dump_path, DEFAULT_EXTRACT_DUMP_FNAME); free(errd_path); if (access(dump_path, X_OK) == 0) { *r_dump_path = dump_path; return 0; } free(dump_path); return -1; } /* * The filetype is determined by the filename format. * The format is <timestamp>-<logid>-<elog_type> * - The timestamp was earlier used for determining how old the log is, * and is no longer used by the purging logic, retained for backward * compatibility reasons. * - logid of the particular error log. * - elog_type = (srvc|info) * - srvc : indicates the error log is serviceable log. * - info : indicates the error log is an informational log. */ static int get_elog_filetype(const char *name) { int ret = OPAL_ELOG_INVALID; int name_len= strlen(name); int suffix_len = strlen(ELOG_FILE_SUFFIX_SRVC); int file_type_offset = name_len - suffix_len; if (name_len < suffix_len) return ret; if (!strcmp(name + file_type_offset, ELOG_FILE_SUFFIX_SRVC)) ret = OPAL_ELOG_SERVICEABLE; else if (!strcmp(name + file_type_offset, ELOG_FILE_SUFFIX_INFO)) ret = OPAL_ELOG_INFORMATIONAL; return ret; } static int is_serviceable_elog_file(const struct dirent *d) { if (is_regular_file(d) && (get_elog_filetype(d->d_name) == OPAL_ELOG_SERVICEABLE)) return 1; return 0; } static int is_informational_elog_file(const struct dirent *d) { if (is_regular_file(d) && (get_elog_filetype(d->d_name) == OPAL_ELOG_INFORMATIONAL)) return 1; return 0; } static int is_suffixless_elog_filename(const struct dirent *d) { if (strstr(d->d_name, "-0x") && is_regular_file(d) && (get_elog_filetype(d->d_name) == OPAL_ELOG_INVALID)) return 1; return 0; } static int get_elog_type_from_file_data(char *path) { struct stat sbuf; struct esel_header eselhdr; void *buf = &eselhdr; uint16_t action; int elog_type = OPAL_ELOG_INVALID; int fd = -1; size_t bufsz, readsz; off_t seek_loc; if (stat(path, &sbuf) == -1) return elog_type; bufsz = sbuf.st_size; if (bufsz > OPAL_ERROR_LOG_MAX) return elog_type; fd = open(path, O_RDONLY); if (fd < 0) return elog_type; readsz = read(fd, &eselhdr, sizeof(eselhdr)); if (readsz < sizeof(eselhdr)) goto out; seek_loc = ELOG_ACTION_OFFSET; if(is_esel_header(buf)) seek_loc += sizeof(eselhdr); if(lseek(fd, seek_loc, SEEK_SET) < 0) goto out; readsz = read(fd, &action, sizeof(uint16_t)); if ((be16toh(action) & ELOG_ACTION_FLAG_SERVICE) || (be16toh(action) & ELOG_ACTION_FLAG_CALL_HOME)) elog_type = OPAL_ELOG_SERVICEABLE; else elog_type = OPAL_ELOG_INFORMATIONAL; out: if (fd != -1) close(fd); return elog_type; } /* * The pruning logic depends on the file name formatting to determine the log * type before considering them for pruning. The old log files which are in * the naming format of <timestamp>-<logid> are renamed here to * <timestamp>-<logid>-<elog_type>. */ static void rename_old_logs(const char *output_dir) { int n; int dir_fd = -1; size_t i; char oldname[PATH_MAX]; char newname[PATH_MAX]; int elog_type; char *out_dir = NULL; struct dirent **namelist; struct dirent *dirent; int rc; n = scandir(output_dir, &namelist, is_suffixless_elog_filename, alphasort); if (n < 0) return; for (i = 0; i < n; i++) { dirent = namelist[i]; if (dirent->d_name[0] == '.') { free(namelist[i]); continue; } rc = snprintf(oldname, sizeof(oldname), "%s/%s", output_dir, dirent->d_name); if (rc < 0 || rc >= sizeof(oldname)) { syslog(LOG_ERR, "%s:%d - Unable to format %s\n", __func__, __LINE__, dirent->d_name); free(namelist[i]); continue; } elog_type = get_elog_type_from_file_data(oldname); if (elog_type == OPAL_ELOG_INVALID) { free(namelist[i]); continue; /* Delete the file here ? */ } rc = snprintf(newname, sizeof(newname), "%s-%s", oldname, ELOG_TYPE_STR(elog_type)); if (rc < 0 || rc >= sizeof(newname)) { syslog(LOG_ERR, "%s:%d - Unable to format %s\n", __func__, __LINE__, ELOG_TYPE_STR(elog_type)); free(namelist[i]); continue; } if (rename(oldname, newname) < 0) { syslog(LOG_WARNING, "Couldn't rename logfile %s to " "%s : %s\n", oldname, newname, strerror(errno)); } free(namelist[i]); } free(namelist); out_dir = strdup(output_dir); if (!out_dir) return; dir_fd = open(dirname(out_dir), O_RDONLY|O_DIRECTORY); if (dir_fd == -1) { syslog(LOG_NOTICE, "Failed to open platform elog directory: %s" " (%d:%s)\n", out_dir, errno, strerror(errno)); } else { if (fsync(dir_fd) == -1) syslog(LOG_NOTICE, "Failed to sync platform elog " "directory: %s (%d:%s)\n", out_dir, errno, strerror(errno)); close(dir_fd); } free(out_dir); } static void rotate_logs(const char *elog_dir, int max_logs, int elog_type) { int i; int nfiles; int ret = 0; int trim = 1; struct dirent **filelist; int (* filter)(const struct dirent *); if (elog_type == OPAL_ELOG_SERVICEABLE) filter = &is_serviceable_elog_file; else filter = &is_informational_elog_file; /* Retrieve file list */ if (chdir(elog_dir) < 0) { syslog(LOG_NOTICE, "chdir failed\n"); return; } nfiles = scandir(elog_dir, &filelist, filter, alphasort); if (nfiles < 0) { syslog(LOG_NOTICE, "Error scanning the log directory %s\n", elog_dir); return; } for (i = 0; i < nfiles; i++) { if (!trim){ free(filelist[i]); continue; } /* Names are ordered 'oldest first' from scandir */ if (i >= (nfiles - max_logs)) trim = 0; if (trim) { ret = remove(filelist[i]->d_name); if(ret) syslog(LOG_NOTICE, "Error removing %s\n", filelist[i]->d_name); } free(filelist[i]); } free(filelist); return; } /* Parse required fields from error log */ static int parse_log(char *buffer, size_t bufsz, int *elog_type) { uint32_t logid; char src[ELOG_SRC_SIZE+1]; uint8_t severity; uint8_t subsysid; uint16_t action; const char *parse; char *parse_action = "NONE"; const char *failingsubsys = "Not Applicable"; if (bufsz < ELOG_MIN_READ_OFFSET) { syslog(LOG_NOTICE, "Insufficient data, cannot parse elog.\n"); return -1; } logid = be32toh(*(uint32_t*)(buffer + ELOG_ID_OFFSET)); memcpy(src, (buffer + ELOG_SRC_OFFSET), ELOG_SRC_SIZE); src[ELOG_SRC_SIZE] = '\0'; subsysid = buffer[ELOG_SUBSYSTEM_OFFSET]; severity = buffer[ELOG_SEVERITY_OFFSET]; /* Every category has a generic entry at 0x?0 */ parse = get_severity_desc(severity & 0xF0); action = be16toh(*(uint16_t *)(buffer + ELOG_ACTION_OFFSET)); if ((action & ELOG_ACTION_FLAG_SERVICE) && (action & ELOG_ACTION_FLAG_CALL_HOME)) parse_action = "Service action and call home required"; else if ((action & ELOG_ACTION_FLAG_SERVICE)) parse_action = "Service action required"; else parse_action = "No service action required"; /* Every category has a generic entry at 0x?0 */ failingsubsys = get_subsystem_name(subsysid & 0xF0); syslog(LOG_NOTICE, "LID[%x]::SRC[%s]::%s::%s::%s\n", logid, src, failingsubsys, parse, parse_action); if ((action & ELOG_ACTION_FLAG_SERVICE) && !(action & ELOG_ACTION_FLAG_CALL_HOME)) syslog(LOG_NOTICE, "Run \'opal-elog-parse -d 0x%x\' " "for the details.\n", logid); if ((action & ELOG_ACTION_FLAG_SERVICE) || (action & ELOG_ACTION_FLAG_CALL_HOME)) { *elog_type = OPAL_ELOG_SERVICEABLE; rotate_srvc_logs = true; } else { *elog_type = OPAL_ELOG_INFORMATIONAL; rotate_info_logs = true; } return 0; } /** * Check platform dump */ static void check_platform_dump(const char *extract_opal_dump_cmd, const char *sysfs_path, const char *max_dump) { int status; pid_t fork_pid; if (!extract_opal_dump_cmd || !sysfs_path) return; if (access(extract_opal_dump_cmd, X_OK) != 0) { syslog(LOG_NOTICE, "The command \"%s\" is not executable.\n", extract_opal_dump_cmd); return; } fork_pid = fork(); if (fork_pid == -1) { syslog(LOG_NOTICE, "Couldn't fork() (%d:%s)\n", errno, strerror(errno)); return; } else if (fork_pid == 0) { /* Child */ char *args[] = { (char *)extract_opal_dump_cmd, "-s", (char *)sysfs_path, /* space for -m */(char *) NULL, /* space for max_dump */(char *) NULL, (char *) NULL }; char *envs[] = { NULL }; if (max_dump) { args[3] = "-m"; args[4] = (char *)max_dump; } execve(extract_opal_dump_cmd, args, envs); syslog(LOG_ERR, "Couldn't execv() into: %s (%d:%s)\n", extract_opal_dump_cmd, errno, strerror(errno)); exit(EXIT_FAILURE); } /* Parent - wait for child process to complete */ if (waitpid(fork_pid, &status, 0) == -1) { syslog(LOG_ERR, "Wait failed, while running %s command\n", extract_opal_dump_cmd); return; } status = (int8_t)WEXITSTATUS(status); if (status) { syslog(LOG_ERR, "%s command execution failed\n", extract_opal_dump_cmd); return; } } static int ack_elog(const char *elog_path) { char ack_file[PATH_MAX]; int fd; int rc; rc = snprintf(ack_file, sizeof(ack_file), "%s/acknowledge", elog_path); if (rc >= PATH_MAX) { syslog(LOG_ERR, "Path to elog ack file is too big\n"); return -1; } fd = open(ack_file, O_WRONLY); if (fd == -1) { syslog(LOG_ERR, "Failed to acknowledge elog: %s" " (%d:%s)\n", ack_file, errno, strerror(errno)); return -1; } rc = write(fd, "ack\n", 4); if (rc != 4) { syslog(LOG_ERR, "Failed to acknowledge elog: %s" " (%d:%s)\n", ack_file, errno, strerror(errno)); close(fd); return -1; } close(fd); return 0; } static int process_elog(const char *elog_path, const char *output) { int in_fd = -1; int out_fd = -1; int dir_fd = -1; char elog_raw_path[PATH_MAX]; char *name; size_t bufsz; struct stat sbuf; int ret = -1; ssize_t sz = 0; ssize_t readsz = 0; int rc; char *output_dir = NULL; char *buf = NULL; char output_file[PATH_MAX]; int elog_type; rc = snprintf(elog_raw_path, sizeof(elog_raw_path), "%s/raw", elog_path); if (rc >= PATH_MAX) { syslog(LOG_ERR, "Path to elog file is too big\n"); goto err; } if (stat(elog_raw_path, &sbuf) == -1) goto err; bufsz = sbuf.st_size; buf = malloc(bufsz); if (!buf) { syslog(LOG_ERR, "Failed to allocate memory\n"); goto err; } in_fd = open(elog_raw_path, O_RDONLY); if (in_fd == -1) { syslog(LOG_ERR, "Failed to open elog: %s (%d:%s)\n", elog_raw_path, errno, strerror(errno)); goto err; } do { readsz = read(in_fd, buf+sz, bufsz-sz); if (readsz == -1) { syslog(LOG_ERR, "Failed to read elog: %s (%d:%s)\n", elog_raw_path, errno, strerror(errno)); goto err; } sz += readsz; } while(sz != bufsz); if (parse_log(buf, bufsz, &elog_type)) { goto err; } /* Parse elog filename */ name = basename(dirname(elog_raw_path)); /* Suffix the elog type, used by purging logic */ rc = snprintf(output_file, sizeof(output_file), "%s/%d-%s-%s", output, (int)time(NULL), name, ELOG_TYPE_STR(elog_type)); if (rc >= PATH_MAX) { syslog(LOG_ERR, "Path to elog output file is too big\n"); goto err; } out_fd = open(output_file, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP); if (out_fd == -1) { syslog(LOG_ERR, "Failed to create elog output file: %s (%d:%s)\n", output_file, errno, strerror(errno)); goto err; } sz = write(out_fd, buf, bufsz); if (sz != bufsz) { syslog(LOG_ERR, "Failed to write elog output file: %s (%d:%s)\n", output_file, errno, strerror(errno)); goto err; } rc = fsync(out_fd); if (rc == -1) { syslog(LOG_ERR, "Failed to sync elog output file: %s (%d:%s)\n", output_file, errno, strerror(errno)); goto err; } output_dir = strdup(output); if (!output_dir) goto err; dir_fd = open(dirname(output_dir), O_RDONLY|O_DIRECTORY); if (dir_fd == -1) { syslog(LOG_ERR, "Failed to open platform elog directory: %s" " (%d:%s)\n", output_dir, errno, strerror(errno)); } else { rc = fsync(dir_fd); if (rc == -1) syslog(LOG_ERR, "Failed to sync platform elog " "directory: %s (%d:%s)\n", output_dir, errno, strerror(errno)); } ret = 0; err: if (in_fd != -1) close(in_fd); if (out_fd != -1) close(out_fd); if (dir_fd != -1) close(dir_fd); free(output_dir); free(buf); return ret; } /* Read logs from opal sysfs interface */ static int find_and_read_elog_events(const char *elog_dir, const char *output_path) { int rc = 0; struct dirent **namelist; struct dirent *dirent; char elog_path[PATH_MAX]; int is_dir = 0; struct stat sbuf; int retval = 0; int n; int i; n = scandir(elog_dir, &namelist, NULL, alphasort); if (n < 0) return -1; for (i = 0; i < n; i++) { dirent = namelist[i]; if (dirent->d_name[0] == '.') { free(namelist[i]); continue; } rc = snprintf(elog_path, sizeof(elog_path), "%s/%s", elog_dir, dirent->d_name); if (rc < 0 || rc >= sizeof(elog_path)) { syslog(LOG_ERR, "%s:%d - Unable to format %s\n", __func__, __LINE__, dirent->d_name); free(namelist[i]); continue; } is_dir = 0; if (dirent->d_type == DT_DIR) { is_dir = 1; } else { /* Fall back to stat() */ rc = stat(elog_path, &sbuf); if (rc == -1) { /* skip on stat error */ free(namelist[i]); continue; } if (S_ISDIR(sbuf.st_mode)) { is_dir = 1; } } if (is_dir) { rc = process_elog(elog_path, output_path); if (rc != 0 && retval == 0) retval = -1; if (rc == 0 && retval >= 0) retval++; ack_elog(elog_path); } free(namelist[i]); } free(namelist); return retval; } static char *validate_extract_opal_dump(const char *cmd) { char *extract_opal_dump_cmd = NULL; /* User didn't specify an extract_opal_dump command */ if (!cmd) { if (find_extract_opal_dump_cmd(&extract_opal_dump_cmd) != 0) syslog(LOG_WARNING, "Could not find an opal dump extractor tool\n"); } else { if (access(cmd, X_OK) == 0) { extract_opal_dump_cmd = strdup(cmd); if (!extract_opal_dump_cmd) syslog(LOG_ERR, "Memory allocation error, extract_opal_dump " "will not be called\n"); } else { syslog(LOG_WARNING, "Couldn't execute extract_opal_dump " "command: %s (%d, %s), dumps will not be extracted\n", cmd, errno, strerror(errno)); } } return extract_opal_dump_cmd; } static int opal_init_udev(struct udev **r_udev, struct udev_monitor **r_udev_mon, int *r_fd) { struct udev *udev = NULL; struct udev_monitor *udev_mon = NULL; int fd = -1; int rc = -1; udev = udev_new(); if (!udev) { syslog(LOG_ERR, "Error creating udev object"); goto init_udev_exit; } udev_mon = udev_monitor_new_from_netlink(udev, "udev"); if (!udev_mon) { syslog(LOG_ERR, "Error creating udev monitor object"); goto init_udev_exit; } rc = udev_monitor_filter_add_match_subsystem_devtype(udev_mon, "dump", NULL); if (rc < 0) { syslog(LOG_ERR, "Error (%d) adding udev match to dump", rc); goto init_udev_exit; } rc = udev_monitor_filter_add_match_subsystem_devtype(udev_mon, "elog", NULL); if (rc < 0) { syslog(LOG_ERR, "Error (%d) adding udev match to elog", rc); goto init_udev_exit; } rc = udev_monitor_enable_receiving(udev_mon); if (rc < 0) { syslog(LOG_ERR, "Error (%d) enabling receiving on udev", rc); goto init_udev_exit; } fd = udev_monitor_get_fd(udev_mon); init_udev_exit: if (rc != 0) { if (udev_mon) udev_monitor_unref(udev_mon); if (udev) udev_unref(udev); udev = NULL; udev_mon = NULL; } *r_udev = udev; *r_udev_mon = udev_mon; *r_fd = fd; return rc; } static void help(const char* argv0) { fprintf(stderr, "%s help:\n\n", argv0); fprintf(stderr, "-e cmd - path to extract_opal_dump (default %s)\n", DEFAULT_EXTRACT_DUMP_CMD); fprintf(stderr, "-o dir - output log entries to directory (default %s)\n", DEFAULT_OUTPUT_DIR); fprintf(stderr, "-s dir - path to sysfs (default %s)\n", DEFAULT_SYSFS_PATH); fprintf(stderr, "-D - don't daemonize, just run once.\n"); fprintf(stderr, "-w - watch for new events (default when daemon)\n"); fprintf(stderr, "-m max - maximum number of dumps of a specific type" " to be saved\n"); fprintf(stderr, "-n max - maximum number of elogs to keep (default %d)\n", DEFAULT_MAX_ELOGS); fprintf(stderr, "-c max - maximum number of serviceable elogs to keep (default %d)\n", (int) 0.2 * DEFAULT_MAX_ELOGS); fprintf(stderr, "-a days - maximum age in days of elogs to keep. This option is deprecated\n"); fprintf(stderr, "-h - help (this message)\n"); } int main(int argc, char *argv[]) { int rc = 0; int opt; char sysfs_path[PATH_MAX]; char elog_path[PATH_MAX]; char dump_path[PATH_MAX]; char *extract_opal_dump_cmd = NULL; int log_options; struct udev *udev = NULL; struct udev_monitor *udev_mon = NULL; struct udev_device *udev_dev = NULL; struct pollfd fds[2]; fds[INOTIFY_FD].fd = -1; char inotifybuf[sizeof(struct inotify_event) + NAME_MAX + 1]; const char *devpath; char elog_str_name[ELOG_STR_SIZE]; struct sigaction siga; int opt_daemon = 1; int opt_watch = 1; int opt_max_logs = DEFAULT_MAX_ELOGS; int max_info_logs = 0; int max_serviceable_logs = 0; int opt_max_age = 0; /* Deprecated, so doesnt matter */ const char *opt_extract_opal_dump_cmd = NULL; const char *opt_max_dump = NULL; const char *opt_sysfs = DEFAULT_SYSFS_PATH; const char *opt_output_dir = DEFAULT_OUTPUT_DIR; while ((opt = getopt(argc, argv, "De:ho:s:m:wn:a:c:")) != -1) { switch (opt) { case 'D': opt_daemon = 0; opt_watch = 0; break; case 'w': opt_daemon = 0; opt_watch = 1; break; case 'o': opt_output_dir = optarg; break; case 'e': opt_extract_opal_dump_cmd = optarg; break; case 's': opt_sysfs = optarg; break; case 'm': opt_max_dump = optarg; break; case 'n': errno = 0; opt_max_logs = strtol(optarg,0,0); if(errno || opt_max_logs < 0){ fprintf(stderr,"Invalid input for -n\n"); exit(EXIT_FAILURE); } break; case 'c': errno = 0; max_serviceable_logs = strtol(optarg, 0, 0); if(errno || max_serviceable_logs < 0) { fprintf(stderr,"Invalid input for -c\n"); exit(EXIT_FAILURE); } break; case 'a': errno = 0; opt_max_age = strtol(optarg,0,0); if(errno || opt_max_age < 0){ fprintf(stderr,"Invalid input for -a\n"); exit(EXIT_FAILURE); } break; case 'h': help(argv[0]); exit(EXIT_SUCCESS); default: help(argv[0]); exit(EXIT_FAILURE); } } /* syslog initialization */ setlogmask(LOG_UPTO(LOG_NOTICE)); log_options = LOG_CONS | LOG_PID | LOG_NDELAY; if (!opt_daemon) log_options |= LOG_PERROR; openlog("ELOG", log_options, LOG_LOCAL1); /* * By default 20% of the log counts are reserved for serviceable * logs, if the user has not specified explicitly */ max_info_logs = opt_max_logs; if (!max_serviceable_logs) { max_serviceable_logs = 0.2 * opt_max_logs; max_info_logs = 0.8 * opt_max_logs; } /* Do we have a valid extract_opal_dump? * Confirm that what the user entered is valid * If not, try to locate a valid extract_opal_dump binary */ extract_opal_dump_cmd = validate_extract_opal_dump(opt_extract_opal_dump_cmd); /* Validate dump sysfs path */ snprintf(dump_path, sizeof(dump_path), "%s/%s", opt_sysfs, DEFAULT_DUMP_PATH); if (access(dump_path, R_OK)) { free(extract_opal_dump_cmd); extract_opal_dump_cmd = NULL; } /* Use PATH_MAX but admit that it may be insufficient */ rc = snprintf(sysfs_path, sizeof(sysfs_path), "%s/firmware/opal", opt_sysfs); if (rc >= PATH_MAX) { syslog(LOG_ERR, "sysfs_path for opal dir is too big\n"); rc = EXIT_FAILURE; goto exit; } /* elog log path */ rc = snprintf(elog_path, sizeof(elog_path), "%s/elog", sysfs_path); if (rc >= PATH_MAX) { syslog(LOG_ERR, "sysfs_path for elogs too big\n"); rc = EXIT_FAILURE; goto exit; } rc = access(sysfs_path, R_OK); if (rc != 0) { syslog(LOG_ERR, "Error accessing sysfs: %s (%d: %s)\n", sysfs_path, errno, strerror(errno)); goto exit; } rc = access(opt_output_dir, W_OK); if (rc != 0) { if (errno == ENOENT) { rc = mkdir(opt_output_dir, S_IRGRP | S_IRUSR | S_IWGRP | S_IWUSR | S_IXUSR); if (rc != 0) { syslog(LOG_ERR, "Error creating output directory:" " %s (%d: %s)\n", opt_output_dir, errno, strerror(errno)); goto exit; } } else { syslog(LOG_ERR, "Error accessing directory: %s (%d: %s)\n", opt_output_dir, errno, strerror(errno)); goto exit; } } fds[INOTIFY_FD].fd = inotify_init(); if (fds[INOTIFY_FD].fd == -1) { syslog(LOG_ERR, "Error setting up inotify (%d:%s)\n", errno, strerror(errno)); rc = EXIT_FAILURE; goto exit; } rc = inotify_add_watch(fds[INOTIFY_FD].fd, sysfs_path, IN_CREATE); if (rc == -1) { syslog(LOG_ERR, "Error adding inotify watch for %s (%d: %s)\n", sysfs_path, errno, strerror(errno)); goto exit; } rc = opal_init_udev(&udev, &udev_mon, &(fds[UDEV_FD].fd)); if (rc != 0) goto exit; /* Convert the opal_errd process to a daemon. */ if (opt_daemon) { rc = daemon(0, 0); if (rc) { syslog(LOG_NOTICE, "Cannot daemonize opal_errd, " "opal_errd cannot continue.\n"); goto exit; } siga.sa_handler = SIG_IGN; sigemptyset(&siga.sa_mask); siga.sa_flags = 0; sigaction(SIGHUP, &siga, NULL); /* Setup a signal handler for SIGTERM */ siga.sa_handler = &term_handler; rc = sigaction(SIGTERM, &siga, NULL); if (rc) { syslog(LOG_NOTICE, "Could not initialize signal handler" " for termination signal (SIGTERM), %s\n", strerror(errno)); goto exit; } } rename_old_logs(opt_output_dir); fds[INOTIFY_FD].events = POLLIN; fds[UDEV_FD].events = POLLIN; /* Read error/event log until we get termination signal */ while (!terminate) { rotate_srvc_logs = rotate_info_logs = false; find_and_read_elog_events(elog_path, opt_output_dir); if (rotate_srvc_logs) { rotate_logs(opt_output_dir, max_serviceable_logs, OPAL_ELOG_SERVICEABLE); } if (rotate_info_logs) { rotate_logs(opt_output_dir, max_info_logs, OPAL_ELOG_INFORMATIONAL); } if (extract_opal_dump_cmd) check_platform_dump(extract_opal_dump_cmd, opt_sysfs, opt_max_dump); if (!opt_watch) { terminate = 1; } else { /* We don't care about the content of the inotify * event, we'll just scan the directory anyway */ rc = poll(fds, sizeof(fds)/sizeof(struct pollfd), POLL_TIMEOUT); if (rc > 0 && fds[INOTIFY_FD].revents) { if (read(fds[INOTIFY_FD].fd, inotifybuf, sizeof(inotifybuf)) == -1) { syslog(LOG_WARNING, "Can not read platform log directory:" " (%d:%s)\n", errno, strerror(errno)); goto exit; } } if (rc > 0 && fds[UDEV_FD].revents) { udev_dev = udev_monitor_receive_device(udev_mon); devpath = udev_device_get_devpath(udev_dev); if (devpath && strrchr(devpath, '/')) { strncpy(elog_str_name, strrchr(devpath, '/'), ELOG_STR_SIZE); elog_str_name[sizeof(elog_str_name) - 1] = '\0'; } udev_device_unref(udev_dev); /* The id of the elog should be in elog_str_name * Perhaps more can be done with the udev information */ } } rc = 0; } exit: syslog(LOG_NOTICE, "Terminating\n"); if (udev_mon) udev_monitor_unref(udev_mon); if (udev) udev_unref(udev); if (fds[INOTIFY_FD].fd >= 0) close(fds[INOTIFY_FD].fd); free(extract_opal_dump_cmd); closelog(); return rc; }
27,797
C
.c
977
25.447288
96
0.656153
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
true
14,713,623
opal-ud-scn.h
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-ud-scn.h
#ifndef _H_OPAL_UD_SCN #define _H_OPAL_UD_SCN #include "opal-v6-hdr.h" /* User defined data header section */ struct opal_ud_scn { struct opal_v6_hdr v6hdr; uint8_t data[0]; /* variable sized */ } __attribute__((packed)); int parse_ud_scn(struct opal_ud_scn **r_ud, const struct opal_v6_hdr *hdr, const char *buf, int buflen); int print_ud_scn(const struct opal_ud_scn *ud); #endif /* _H_OPAL_UD_SCN */
444
C
.c
13
30
47
0.647887
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,624
opal-src-fru-scn.h
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-src-fru-scn.h
#ifndef _H_OPAL_SRC_FRU_SCN #define _H_OPAL_SRC_FRU_SCN #include <inttypes.h> #include "opal-mtms-scn.h" struct opal_fru_hdr { uint16_t type; uint8_t length; uint8_t flags; } __attribute__((packed)); #define OPAL_FRU_ID_TYPE 0x4944 /* 'ID' in hex */ #define OPAL_FRU_ID_PART 0x08 #define OPAL_FRU_ID_PROC 0x02 #define OPAL_FRU_ID_PART_MAX 8 #define OPAL_FRU_ID_CCIN 0x04 /* OPAL_FRU_ID_PART must be set */ #define OPAL_FRU_ID_CCIN_MAX 4 #define OPAL_FRU_ID_SERIAL_MAX 12 #define OPAL_FRU_ID_SERIAL 0x1 /* OPAL_FRU_ID_PART must be set */ struct opal_fru_id_sub_scn { struct opal_fru_hdr hdr; char part[OPAL_FRU_ID_PART_MAX]; char ccin[OPAL_FRU_ID_CCIN_MAX]; char serial[OPAL_FRU_ID_SERIAL_MAX]; /* not null terminated */ } __attribute__((packed)); #define OPAL_FRU_MR_TYPE 0x4d52 /* 'MR" in hex */ #define OPAL_FRU_MR_MRU_MAX 15 struct opal_fru_mr_mru_scn { uint8_t reserved0; uint8_t reserved1; uint8_t reserved2; uint8_t priority; uint32_t id; } __attribute__((packed)); struct opal_fru_mr_sub_scn { struct opal_fru_hdr hdr; uint32_t reserved; struct opal_fru_mr_mru_scn mru[OPAL_FRU_MR_MRU_MAX]; /* Max 15 */ } __attribute__((packed)); #define OPAL_FRU_PE_TYPE 0x5045 /* 'PE' in hex */ #define OPAL_FRU_PE_PCE_MAX 32 struct opal_fru_pe_sub_scn { struct opal_fru_hdr hdr; struct opal_mtms_struct mtms; char pce[OPAL_FRU_PE_PCE_MAX]; } __attribute__((packed)); #define OPAL_FRU_SCN_STATIC_SIZE (4 * sizeof(uint8_t)) #define OPAL_FRU_SCN_ID 0xc0 #define OPAL_FRU_LOC_CODE_MAX 80 #define OPAL_FRU_ID_SUB 0x08 #define OPAL_FRU_PE_SUB 0x03 #define OPAL_FRU_MR_SUB 0x04 struct opal_fru_scn { uint8_t length; /* Length of everything below including this */ uint8_t type; uint8_t priority; uint8_t loc_code_len; /* Must be a multiple of 4 */ char location_code[OPAL_FRU_LOC_CODE_MAX]; /* Variable length indicated my loc_code_len max 80 */ struct opal_fru_id_sub_scn id; /* Optional */ struct opal_fru_pe_sub_scn pe; /* Optional */ struct opal_fru_mr_sub_scn mr; /* Optional */ } __attribute__((packed)); int parse_fru_scn(struct opal_fru_scn *fru_scn, const char *buf, int buflen); int print_fru_scn(const struct opal_fru_scn *fru); #endif /* _H_OPAL_SRC_FRU_SCN */
2,232
C
.c
64
32.75
98
0.713551
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,625
opal-ei-scn.h
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-ei-scn.h
#ifndef _H_OPAL_EI_SCN #define _H_OPAL_EI_SCN #include "opal-v6-hdr.h" struct opal_ei_env_scn { uint32_t corrosion; uint16_t temperature; uint16_t rate; } __attribute__((packed)); #define CORROSION_RATE_NORM 0x00 #define CORROSION_RATE_ABOVE 0x01 struct opal_ei_scn { struct opal_v6_hdr v6hdr; uint64_t g_timestamp; struct opal_ei_env_scn genesis; uint8_t status; uint8_t user_data_scn; uint16_t read_count; struct opal_ei_env_scn readings[0]; /* variable length */ } __attribute__((packed)); int parse_ei_scn(struct opal_ei_scn **r_ei, struct opal_v6_hdr *hdr, const char *buf, int buflen); int print_ei_scn(const struct opal_ei_scn *ei); #endif /* _H_OPAL_EI_SCN */
720
C
.c
24
26.875
58
0.696662
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,626
opal-lp-scn.c
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-lp-scn.c
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include "opal-lp-scn.h" #include "print_helpers.h" int parse_lp_scn(struct opal_lp_scn **r_lp, struct opal_v6_hdr *hdr, const char *buf, int buflen) { struct opal_lp_scn *lp; struct opal_lp_scn *lpbuf = (struct opal_lp_scn *)buf; uint16_t *lps; uint16_t *lpsbuf; if (buflen < sizeof(struct opal_lp_scn) || hdr->length < sizeof(struct opal_lp_scn)) { fprintf(stderr, "%s: corrupted, expected length => %lu, got %u\n", __func__, sizeof(struct opal_lp_scn), buflen < hdr->length ? buflen : hdr->length); return -EINVAL; } *r_lp = malloc(hdr->length); if (!*r_lp) { fprintf(stderr, "%s: out of memory\n", __func__); return -ENOMEM; } lp = *r_lp; lp->v6hdr = *hdr; lp->primary = be16toh(lpbuf->primary); lp->length_name = lpbuf->length_name; lp->lp_count = lpbuf->lp_count; lp->partition_id = be32toh(lpbuf->partition_id); lp->name[0] = '\0'; int expected_len = sizeof(struct opal_lp_scn) + lp->length_name; if (buflen < expected_len || hdr->length < expected_len) { fprintf(stderr, "%s: corrupted, expected length => %u, got %u", __func__, expected_len, buflen < hdr->length ? buflen : hdr->length); free(lp); return -EINVAL; } memcpy(lp->name, lpbuf->name, lp->length_name); expected_len += lp->lp_count * sizeof(uint16_t); if (buflen < expected_len || hdr->length < expected_len) { fprintf(stderr, "%s: corrupted, expected length => %u, got %u", __func__, expected_len, buflen < hdr->length ? buflen : hdr->length); free(lp); return -EINVAL; } lpsbuf = (uint16_t *)(lpbuf->name + lpbuf->length_name); lps = (uint16_t *)(lp->name + lp->length_name); int i; for(i = 0; i < lp->lp_count; i++) lps[i] = be16toh(lpsbuf[i]); return 0; } int print_lp_scn(const struct opal_lp_scn *lp) { print_header("Logical Partition"); print_opal_v6_hdr(lp->v6hdr); print_line("Primary Partition ID", "0x%04x", lp->primary); print_line("Logical Partition Log ID", "0x%08x", lp->partition_id); print_line("Length of LP Name", "0x%02x", lp->length_name); print_line("Primary Partition Name", "%s", lp->name); int i; uint16_t *lps = (uint16_t *) (lp->name + lp->length_name); print_line("Target LP Count", "0x%02x", lp->lp_count); for(i = 0; i < lp->lp_count; i+=2) { if (i + 1 < lp->lp_count) print_line("Target LP", "0x%04x 0x%04x", lps[i], lps[i+1]); else print_line("Target LP", "0x%04X", lps[i]); } print_bar(); return 0; }
2,546
C
.c
76
30.355263
70
0.631707
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,627
opal-esel-parse.c
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-esel-parse.c
#include "opal-esel-parse.h" bool is_esel_header(const char *buf) { const struct esel_header* bufhdr = (struct esel_header*)buf; if (bufhdr->record_type == ESEL_RECORD_TYPE && bufhdr->signature == ESEL_SIGNATURE) return 1; return 0; }
249
C
.c
9
25.111111
61
0.716102
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,628
opal-priv-hdr-scn.c
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-priv-hdr-scn.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include "opal-priv-hdr-scn.h" #include "opal-datetime.h" #include "opal-event-data.h" #include "print_helpers.h" int parse_priv_hdr_scn(struct opal_priv_hdr_scn **r_privhdr, const struct opal_v6_hdr *hdr, const char *buf, int buflen) { struct opal_priv_hdr_scn *bufhdr = (struct opal_priv_hdr_scn*)buf; struct opal_priv_hdr_scn *privhdr; if (buflen < sizeof(struct opal_priv_hdr_scn)) { fprintf(stderr, "%s: corrupted, expected length %lu, got %u\n", __func__, sizeof(struct opal_priv_hdr_scn), buflen); return -EINVAL; } if (hdr->length != sizeof(struct opal_priv_hdr_scn)) { fprintf(stderr, "%s: section header length disagrees with spec" ". section header length %u, spec: %lu\n", __func__, hdr->length, sizeof(struct opal_priv_hdr_scn)); return -EINVAL; } *r_privhdr = malloc(sizeof(struct opal_priv_hdr_scn)); if (!*r_privhdr) return -ENOMEM; privhdr = *r_privhdr; privhdr->v6hdr = *hdr; privhdr->create_datetime = parse_opal_datetime(bufhdr->create_datetime); privhdr->commit_datetime = parse_opal_datetime(bufhdr->commit_datetime); privhdr->creator_id = bufhdr->creator_id; privhdr->scn_count = bufhdr->scn_count; if (privhdr->scn_count < 1) { fprintf(stderr, "%s: section header has an invalid section count %u, " "should be greater than 0, setting section count to 1 " "to attempt recovery\n", __func__, privhdr->scn_count); privhdr->scn_count = 1; } // FIXME: are these ASCII? Need spec clarification privhdr->creator_subid_hi = bufhdr->creator_subid_hi; privhdr->creator_subid_lo = bufhdr->creator_subid_lo; privhdr->plid = be32toh(bufhdr->plid); privhdr->log_entry_id = be32toh(bufhdr->log_entry_id); return 0; } int print_opal_priv_hdr_scn(const struct opal_priv_hdr_scn *privhdr) { print_bar(); print_header("Private Header"); print_opal_v6_hdr(privhdr->v6hdr); print_line("Created at", "%4u-%02u-%02u | %02u:%02u:%02u", privhdr->create_datetime.year, privhdr->create_datetime.month, privhdr->create_datetime.day, privhdr->create_datetime.hour, privhdr->create_datetime.minutes, privhdr->create_datetime.seconds); print_line("Committed at", "%4u-%02u-%02u | %02u:%02u:%02u", privhdr->commit_datetime.year, privhdr->commit_datetime.month, privhdr->commit_datetime.day, privhdr->commit_datetime.hour, privhdr->commit_datetime.minutes, privhdr->commit_datetime.seconds); print_line("Created by", "%s", get_creator_name(privhdr->creator_id)); print_line("Creator Sub Id", "0x%x (%u), 0x%x (%u)", privhdr->creator_subid_hi, privhdr->creator_subid_hi, privhdr->creator_subid_lo, privhdr->creator_subid_lo); print_line("Platform Log Id", "0x%x", privhdr->plid); print_line("Entry ID", "0x%x", privhdr->log_entry_id); print_line("Section Count","%u",privhdr->scn_count); print_bar(); return 0; }
3,100
C
.c
80
33.7625
73
0.666113
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,629
opal-sw-scn.c
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-sw-scn.c
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include "opal-v6-hdr.h" #include "opal-sw-scn.h" #include "print_helpers.h" int parse_sw_v1_scn(struct opal_sw_v1_scn *swv1, const char *buf, int buflen) { struct opal_sw_v1_scn *swv1buf = (struct opal_sw_v1_scn *)buf; if (buflen < sizeof(struct opal_sw_v1_scn)) { fprintf(stderr, "%s: corrupted buffer, expecting length > %lu " "got %d", __func__, sizeof(struct opal_sw_v1_scn), buflen); return -EINVAL; } swv1->rc = be32toh(swv1buf->rc); swv1->line_num = be32toh(swv1buf->line_num); swv1->object_id = be32toh(swv1buf->object_id); swv1->id_length = swv1buf->id_length; if(buflen < sizeof(struct opal_sw_v1_scn) + swv1->id_length) { fprintf(stderr, "%s: corrupted buffer, expecting length > %lu " "got %d", __func__, sizeof(struct opal_sw_v1_scn) + swv1->id_length, buflen); return -EINVAL; } memset(swv1->file_id, 0, swv1->id_length); memcpy(swv1->file_id, swv1buf->file_id, swv1->id_length); swv1->file_id[swv1->id_length - 1] = '\0'; return 0; } int parse_sw_v2_scn(struct opal_sw_v2_scn *swv2, const char *buf, int buflen) { struct opal_sw_v2_scn *swv2buf = (struct opal_sw_v2_scn *)buf; if (buflen < sizeof(struct opal_sw_v2_scn)) { fprintf(stderr, "%s: corrupted buffer, expected length == %lu, " "got %u\n", __func__, sizeof(struct opal_sw_v2_scn), buflen); return -EINVAL; } swv2->rc = be32toh(swv2buf->rc); swv2->file_id = be16toh(swv2buf->file_id); swv2->location_id = be16toh(swv2buf->location_id); swv2->object_id = be32toh(swv2buf->object_id); return 0; } int parse_sw_scn(struct opal_sw_scn **r_sw, struct opal_v6_hdr *hdr, const char *buf, int buflen) { struct opal_sw_scn *sw; int rc = 0; *r_sw = malloc(hdr->length); if(!*r_sw) return -ENOMEM; sw = *r_sw; if (buflen < sizeof(struct opal_v6_hdr)) { free(sw); return -EINVAL; } sw->v6hdr = *hdr; if (hdr->version == 1) { if (hdr->length > sizeof(struct opal_sw_v1_scn) + sizeof(struct opal_v6_hdr)) { rc = parse_sw_v1_scn(&(sw->version.v1), buf, buflen - sizeof(struct opal_v6_hdr)); } else { fprintf(stderr, "%s: corrupted section header, expected length > %lu, " "got %u\n", __func__, sizeof(struct opal_sw_v1_scn) + sizeof(struct opal_v6_hdr), hdr->length); rc = -EINVAL; } } else if (hdr->version == 2) { if (hdr->length == sizeof(struct opal_sw_v2_scn) + sizeof(struct opal_v6_hdr)) { rc = parse_sw_v2_scn(&(sw->version.v2), buf, buflen - sizeof(struct opal_v6_hdr)); } else { fprintf(stderr, "%s: corrupted section header, expected length == %lu, " "got %u\n", __func__, sizeof(struct opal_sw_v2_scn) + sizeof(struct opal_v6_hdr), hdr->length); rc = -EINVAL; } } else { fprintf(stderr, "ERROR %s: unknown version 0x%x\n", __func__, hdr->version); rc = -EINVAL; } if(rc != 0) { free(sw); return rc; } return 0; } int print_sw_scn(const struct opal_sw_scn *sw) { print_header("Firmware Error Description"); print_opal_v6_hdr(sw->v6hdr); if (sw->v6hdr.version == 1) { print_line("Return Code", "0x%08x", sw->version.v1.rc); print_line("Line Number", "%08d", sw->version.v1.line_num); print_line("Object Identifier", "0x%08x", sw->version.v1.object_id); print_line("File ID Length", "0x%x", sw->version.v1.id_length); print_line("File Identifier", "%s", sw->version.v1.file_id); } else if (sw->v6hdr.version == 2) { print_line("File Identifier", "0x%04x", sw->version.v2.file_id); print_line("Code Location", "0x%04x", sw->version.v2.location_id); print_line("Return Code", "0x%08x", sw->version.v2.rc); print_line("Object Identifier", "0x%08x", sw->version.v2.object_id); } else { print_line("Parse error", "Incompatible version - 0x%x", sw->v6hdr.version); } print_bar(); return 0; }
3,925
C
.c
111
31.738739
86
0.641086
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,630
opal-mtms-struct.c
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-mtms-struct.c
#include <stdio.h> #include <string.h> #include "opal-mtms-struct.h" #include "print_helpers.h" int print_mtms_struct(const struct opal_mtms_struct mtms) { char model[OPAL_SYS_MODEL_LEN+1]; char serial_no[OPAL_SYS_SERIAL_LEN+1]; memcpy(model, mtms.model, OPAL_SYS_MODEL_LEN); model[OPAL_SYS_MODEL_LEN] = '\0'; memcpy(serial_no, mtms.serial_no, OPAL_SYS_SERIAL_LEN); serial_no[OPAL_SYS_SERIAL_LEN] = '\0'; print_line("Machine Type Model", "%s", model); print_line("Serial Number", "%s", serial_no); return 0; }
524
C
.c
16
30.875
57
0.717694
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,631
opal-priv-hdr-scn.h
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-priv-hdr-scn.h
#ifndef _H_OPAL_PRIV_HEADER #define _H_OPAL_PRIV_HEADER #include "opal-v6-hdr.h" #include "opal-datetime.h" #define OPAL_PH_CREAT_SERVICE_PROC 'E' #define OPAL_PH_CREAT_HYPERVISOR 'H' #define OPAL_PH_CREAT_POWER_CONTROL 'W' #define OPAL_PH_CREAT_PARTITION_FW 'L' /* Private Header section */ struct opal_priv_hdr_scn { struct opal_v6_hdr v6hdr; struct opal_datetime create_datetime; struct opal_datetime commit_datetime; uint8_t creator_id; /* subsystem component id */ uint8_t reserved0; uint8_t reserved1; uint8_t scn_count; /* number of sections in log */ uint32_t reserved2; uint32_t creator_subid_hi; uint32_t creator_subid_lo; uint32_t plid; /* platform log id */ uint32_t log_entry_id; /* Unique log entry id */ } __attribute__((packed)); int parse_priv_hdr_scn(struct opal_priv_hdr_scn **r_privhdr, const struct opal_v6_hdr *hdr, const char *buf, int buflen); int print_opal_priv_hdr_scn(const struct opal_priv_hdr_scn *privhdr); #endif /* _H_OPAL_PRIV_HEADER */
1,063
C
.c
28
34.678571
70
0.692906
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,632
opal-ed-scn.h
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-ed-scn.h
#ifndef _H_OPAL_ED_SCN #define _H_OPAL_ED_SCN #include "opal-v6-hdr.h" struct opal_ed_scn { struct opal_v6_hdr v6hdr; uint8_t creator_id; uint8_t reserved[3]; uint8_t user_data[0]; /* variable length */ } __attribute__((packed)); int parse_ed_scn(struct opal_ed_scn **r_ed, struct opal_v6_hdr *hdr, const char *buf, int buflen); int print_ed_scn(const struct opal_ed_scn *ed); #endif /* _H_OPAL_ED_SCN */
448
C
.c
14
27.928571
47
0.648019
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,633
print-esel-header.c
power-ras_ppc64-diag/opal_errd/opal-elog-parse/print-esel-header.c
#include <stdio.h> #include <endian.h> #include "opal-esel-parse.h" #include "print_helpers.h" int print_esel_header(const char *buf) { const struct esel_header* bufhdr = (struct esel_header*)buf; print_bar(); print_header("eSEL Header"); print_line("ID", "%x", le16toh(bufhdr->id)); print_line("Record Type", "0x%x", bufhdr->record_type); print_line("Timestamp", "%u", le32toh(bufhdr->timestamp)); print_line("GENID", "0x%x", le16toh(bufhdr->genid)); print_line("EvMRev", "0x%x", bufhdr->evmrev); print_line("Sensor Type", "0x%x", bufhdr->sensor_type); print_line("Sensor No.", "0x%x", bufhdr->sensor_num); print_line("Dir Type", "0x%x", bufhdr->dir_type); print_line("Signature", "0x%x", bufhdr->signature); return 0; }
742
C
.c
20
35.1
61
0.688112
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,634
opal-ei-scn.c
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-ei-scn.c
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include "opal-ei-scn.h" #include "parse_helpers.h" #include "print_helpers.h" int parse_ei_scn(struct opal_ei_scn **r_ei, struct opal_v6_hdr *hdr, const char *buf, int buflen) { struct opal_ei_scn *ei; struct opal_ei_scn *eibuf = (struct opal_ei_scn *)buf; if (check_buflen(buflen, sizeof(struct opal_ei_scn), __func__) < 0 || check_buflen(hdr->length, sizeof(struct opal_ei_scn), __func__) < 0) return -EINVAL; *r_ei = malloc(hdr->length); if (!*r_ei) return -ENOMEM; ei = *r_ei; ei->v6hdr = *hdr; ei->g_timestamp = be64toh(eibuf->g_timestamp); ei->genesis.corrosion = be32toh(eibuf->genesis.corrosion); ei->genesis.temperature = be16toh(eibuf->genesis.temperature); ei->genesis.rate = be16toh(eibuf->genesis.rate); ei->status = eibuf->status; ei->user_data_scn = eibuf->user_data_scn; ei->read_count = be16toh(eibuf->read_count); if (check_buflen(hdr->length, sizeof(struct opal_ei_scn) + (ei->read_count * sizeof(struct opal_ei_env_scn)), __func__) < 0 || check_buflen(buflen, sizeof(struct opal_ei_scn) + (ei->read_count * sizeof(struct opal_ei_env_scn)), __func__)) { free(ei); return -EINVAL; } int i; for (i = 0; i < ei->read_count; i++) { ei->readings[i].corrosion = be32toh(eibuf->readings[i].corrosion); ei->readings[i].temperature = be16toh(eibuf->readings[i].temperature); ei->readings[i].rate = be16toh(eibuf->readings[i].rate); } return 0; } static int print_ei_env_scn(const struct opal_ei_env_scn *ei_env) { print_line("Avg Norm corrosion", "0x%08x", ei_env->corrosion); print_line("Avg Norm temp", "0x%04x", ei_env->temperature); print_line("Corrosion rate", "0x%04x", ei_env->rate); return 0; } int print_ei_scn(const struct opal_ei_scn *ei) { print_header("Environmental Information"); print_opal_v6_hdr(ei->v6hdr); print_center("Genesis Readings"); print_line("Timestamp", "0x%016lx", ei->g_timestamp); print_ei_env_scn(&(ei->genesis)); print_center(" "); if (ei->status == CORROSION_RATE_NORM) print_line("Corrosion Rate Status", "Normal"); else if (ei->status == CORROSION_RATE_ABOVE) print_line("Corrosion Rate Status", "Above Normal"); else print_line("Corrosion Rate Status", "Unknown"); print_line("User Data Section", "%s", ei->user_data_scn ? "Present" : "Absent"); print_line("Sensor Reading Count", "0x%04x", ei->read_count); int i; for(i = 0; i < ei->read_count; i++) print_ei_env_scn(ei->readings + i); return 0; }
2,546
C
.c
73
31.958904
72
0.673586
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,635
opal-usr-scn.h
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-usr-scn.h
#ifndef _H_OPAL_USR_SCN #define _H_OPAL_USR_SCN #include "opal-v6-hdr.h" #define OPAL_UH_TYPE_NA 0x00 #define OPAL_UH_TYPE_INFO_ONLY 0x01 #define OPAL_UH_TYPE_DUMP_NOTIFICATION 0x08 #define OPAL_UH_TYPE_PREVIOUSLY_REPORTED 0x10 #define OPAL_UH_TYPE_DECONFIG_USER 0x20 #define OPAL_UH_TYPE_DECONFIG_SYSTEM 0x21 #define OPAL_UH_TYPE_DECONFIG_NOTICE 0x22 #define OPAL_UH_TYPE_RETURN_TO_NORMAL 0x30 #define OPAL_UH_TYPE_CONCURRENT_MAINT 0x40 #define OPAL_UH_TYPE_CAPACITY_UPGRADE 0x60 #define OPAL_UH_TYPE_RESOURCE_SPARING 0x70 #define OPAL_UH_TYPE_DYNAMIC_RECONFIG 0x80 #define OPAL_UH_TYPE_NORMAL_SHUTDOWN 0xD0 #define OPAL_UH_TYPE_ABNORMAL_SHUTDOWN 0xE0 #define OPAL_UH_ACTION_SERVICE 0x8000 #define OPAL_UH_ACTION_HEALTH 0x4000 #define OPAL_UH_ACTION_REPORT_EXTERNALLY 0x2000 #define OPAL_UH_ACTION_HMC_ONLY 0x1000 #define OPAL_UH_ACTION_CALL_HOME 0x0800 #define OPAL_UH_ACTION_ISO_INCOMPLETE 0x0400 #define OPAL_UH_ACTION_TERMINATION 0x0100 struct opal_usr_hdr_scn { struct opal_v6_hdr v6hdr; uint8_t subsystem_id; /**< subsystem id */ uint8_t event_data; uint8_t event_severity; uint8_t event_type; /**< error/event severity */ uint32_t reserved1; uint8_t problem_domain; uint8_t problem_vector; uint16_t action; /**< erro action code */ uint32_t reserved2; } __attribute__((packed)); int parse_usr_hdr_scn(struct opal_usr_hdr_scn **r_usrhdr, const struct opal_v6_hdr *hdr, const char *buf, int buflen, int *is_error); int print_opal_usr_hdr_scn(const struct opal_usr_hdr_scn *usrhdr); #endif /* _H_OPAL_USR_SCN */
1,746
C
.c
41
40.097561
66
0.686101
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,636
opal-lr-scn.h
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-lr-scn.h
#ifndef _H_OPAL_LR_SCN #define _H_OPAL_LR_SCN #include "opal-v6-hdr.h" #define LR_RES_TYPE_PROC 0x10 #define LR_RES_TYPE_SHARED_PROC 0x11 #define LR_RES_TYPE_MEMORY_PAGE 0x40 #define LR_RES_TYPE_MEMORY_LMB 0x41 struct opal_lr_scn { struct opal_v6_hdr v6hdr; uint8_t res_type; uint8_t reserved; uint16_t capacity; uint32_t shared; uint32_t memory_addr; } __attribute__((packed)); int parse_lr_scn(struct opal_lr_scn **r_lr, struct opal_v6_hdr *hdr, const char *buf, int buflen); int print_lr_scn(const struct opal_lr_scn *lr); #endif /* _H_OPAL_LR_SCN */
583
C
.c
19
28.157895
71
0.716846
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,637
opal-sw-v1-scn.h
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-sw-v1-scn.h
#ifndef _H_OPAL_SW_V1_SCN #define _H_OPAL_SW_V1_SCN #include <inttypes.h> struct opal_sw_v1_scn { uint32_t rc; uint32_t line_num; uint32_t object_id; uint8_t id_length; char file_id[0]; /* Variable length, NULL terminated, padded to 4 bytes */ } __attribute__((packed)); #endif /* _H_OPAL_SW_V1_SCN */
310
C
.c
11
26.454545
75
0.695946
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,638
opal-ud-scn.c
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-ud-scn.c
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include "opal-ud-scn.h" #include "print_helpers.h" int parse_ud_scn(struct opal_ud_scn **r_ud, const struct opal_v6_hdr *hdr, const char *buf, int buflen) { struct opal_ud_scn *ud; struct opal_ud_scn *bufud = (struct opal_ud_scn *)buf; if (buflen < sizeof(struct opal_ud_scn)) { fprintf(stderr, "%s: corrupted, expected length >= %lu, got %u\n", __func__, sizeof(struct opal_ud_scn), buflen); return -EINVAL; } *r_ud = malloc(hdr->length); if (!*r_ud) return -ENOMEM; ud = *r_ud; ud->v6hdr = *hdr; memcpy(ud->data, bufud->data, hdr->length - sizeof(struct opal_v6_hdr)); return 0; } int print_ud_scn(const struct opal_ud_scn *ud) { print_header("User Defined Data"); print_opal_v6_hdr(ud->v6hdr); /*FIXME this data should be parsable if documentation appears/exists * In the mean time, just dump it in hex */ print_line("User data hex","length %d",ud->v6hdr.length - 8); print_hex(ud->data, ud->v6hdr.length - 8); print_bar(); return 0; }
1,096
C
.c
37
26.513514
73
0.661597
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,639
opal-dh-scn.c
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-dh-scn.c
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include "opal-dh-scn.h" #include "parse_helpers.h" #include "opal-event-data.h" #include "print_helpers.h" int parse_dh_scn(struct opal_dh_scn **r_dh, struct opal_v6_hdr *hdr, const char *buf, int buflen) { struct opal_dh_scn *dhbuf = (struct opal_dh_scn *)buf; struct opal_dh_scn *dh; if (check_buflen(buflen, sizeof(struct opal_dh_scn) - DH_DUMP_STR_MAX, __func__) < 0) return -EINVAL; *r_dh = malloc(sizeof(struct opal_dh_scn)); if(!*r_dh) return -ENOMEM; dh = *r_dh; dh->v6hdr = *hdr; dh->dump_id = be32toh(dhbuf->dump_id); dh->flags = dhbuf->flags; dh->length_dump_os = dhbuf->length_dump_os; dh->dump_size = be64toh(dhbuf->dump_size); if (dh->flags & DH_FLAG_DUMP_HEX) { if (check_buflen(buflen, sizeof(struct opal_dh_scn) + sizeof(uint32_t), __func__) < 0) { free(dh); return -EINVAL; } dh->shared.dump_hex = be32toh(dh->shared.dump_hex); } else { /* therefore it is in ascii */ if (check_buflen(buflen, sizeof(struct opal_dh_scn) + dh->length_dump_os, __func__) < 0) { free(dh); return -EINVAL; } memcpy(dh->shared.dump_str, dhbuf->shared.dump_str, dh->length_dump_os); } return 0; } int print_dh_scn(const struct opal_dh_scn *dh) { print_header("Dump Locator"); print_opal_v6_hdr(dh->v6hdr); print_line("Dump Type", "%s", get_dh_type_desc(dh->v6hdr.subtype)); print_line("Dump Identifier", "0x%08x", dh->dump_id); print_line("Dump Flags", "0x%02x", dh->flags); print_line("OS Dump Length", "0x%02x", dh->length_dump_os); print_line("Dump Size", "0x%016lx", dh->dump_size); if (dh->flags & DH_FLAG_DUMP_HEX) print_line("OS Assigned Dump ID", "0x%08x", dh->shared.dump_hex); else /* therefore ascii */ print_line("OS Assigned Dump File", "%s", dh->shared.dump_str); print_bar(); return 0; }
1,893
C
.c
59
29.118644
75
0.65353
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,640
opal-datetime.c
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-datetime.c
#include <endian.h> #include "opal-datetime.h" #include "parse_helpers.h" struct opal_datetime parse_opal_datetime(const struct opal_datetime in) { struct opal_datetime out; out.year = from_bcd16(be16toh(in.year)); out.month = from_bcd8(in.month); out.day = from_bcd8(in.day); out.hour = from_bcd8(in.hour); out.minutes = from_bcd8(in.minutes); out.seconds = from_bcd8(in.seconds); out.hundredths = from_bcd8(in.hundredths); return out; }
482
C
.c
15
30.266667
71
0.697624
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,641
opal-sw-scn.h
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-sw-scn.h
#ifndef _H_OPAL_SW_SCN #define _H_OPAL_SW_SCN #include "opal-v6-hdr.h" #include "opal-sw-v1-scn.h" #include "opal-sw-v2-scn.h" struct opal_sw_scn { struct opal_v6_hdr v6hdr; union { struct opal_sw_v1_scn v1; struct opal_sw_v2_scn v2; } version; } __attribute__((packed)); int parse_sw_scn(struct opal_sw_scn **r_sw, struct opal_v6_hdr *hdr, const char *buf, int buflen); int print_sw_scn(const struct opal_sw_scn *sw); #endif /* _H_OPAL_SW_SCN */
476
C
.c
16
26.9375
71
0.674725
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,642
opal-hm-scn.h
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-hm-scn.h
#ifndef _H_OPAL_HM_SCN #define _H_OPAL_HM_SCN #include "opal-v6-hdr.h" #include "opal-mtms-struct.h" struct opal_hm_scn { struct opal_v6_hdr v6hdr; struct opal_mtms_struct mtms; } __attribute__((packed)); int parse_hm_scn(struct opal_hm_scn **r_hm, const struct opal_v6_hdr *hdr, const char *buf, int buflen); int print_hm_scn(const struct opal_hm_scn *hm); #endif /* _H_OPAL_HM_SCN */
427
C
.c
13
28.692308
47
0.660147
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,643
opal-mtms-scn.c
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-mtms-scn.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include "opal-mtms-scn.h" #include "print_helpers.h" int parse_mtms_scn(struct opal_mtms_scn **r_mtms, const struct opal_v6_hdr *hdr, const char *buf, int buflen) { struct opal_mtms_scn *bufmtms = (struct opal_mtms_scn*)buf; struct opal_mtms_scn *mtms; if (buflen < sizeof(struct opal_mtms_scn)) { fprintf(stderr, "%s: corrupted, expected length %lu, got %u\n", __func__, sizeof(struct opal_mtms_scn), buflen); return -EINVAL; } if (hdr->length != sizeof(struct opal_mtms_scn)) { fprintf(stderr, "%s: section header length disagrees with spec" ". section header length %u, spec: %lu\n", __func__, hdr->length, sizeof(struct opal_mtms_scn)); return -EINVAL; } *r_mtms = malloc(sizeof(struct opal_mtms_scn)); if(!*r_mtms) return -ENOMEM; mtms = *r_mtms; mtms->v6hdr = *hdr; copy_mtms_struct(&(mtms->mtms), &(bufmtms->mtms)); return 0; } int print_mtms_scn(const struct opal_mtms_scn *mtms) { /* * This is a workaround for a known gcc bug where passing packed structs by * value to functions requires an intermediate otherwise gcc will read past * the end of the struct during the copy. */ struct opal_mtms_struct tmp = mtms->mtms; print_header("Machine Type/Model & Serial Number"); print_opal_v6_hdr(mtms->v6hdr); print_mtms_struct(tmp); print_bar(); return 0; }
1,419
C
.c
42
30.928571
80
0.694952
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
14,713,644
opal-dh-scn.h
power-ras_ppc64-diag/opal_errd/opal-elog-parse/opal-dh-scn.h
#ifndef _H_OPAL_DH_SCN #define _H_OPAL_DH_SCN #include "opal-v6-hdr.h" #define DH_FLAG_DUMP_HEX 0x40 #define DH_DUMP_STR_MAX 40 struct opal_dh_scn { struct opal_v6_hdr v6hdr; uint32_t dump_id; uint8_t flags; uint8_t reserved[2]; uint8_t length_dump_os; uint64_t dump_size; union { char dump_str[DH_DUMP_STR_MAX]; uint32_t dump_hex; } shared; } __attribute__((packed)); int parse_dh_scn(struct opal_dh_scn **r_dh, struct opal_v6_hdr *hdr, const char *buf, int buflen); int print_dh_scn(const struct opal_dh_scn *dh); #endif /* _H_OPAL_DH_SCN */
597
C
.c
22
23.727273
47
0.672535
power-ras/ppc64-diag
3
20
5
GPL-2.0
9/7/2024, 2:16:54 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true