blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
721
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
5
91
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
321 values
visit_date
timestamp[ns]date
2016-08-12 09:31:09
2023-09-06 10:45:07
revision_date
timestamp[ns]date
2010-09-28 14:01:40
2023-09-06 06:22:19
committer_date
timestamp[ns]date
2010-09-28 14:01:40
2023-09-06 06:22:19
github_id
int64
426
681M
star_events_count
int64
101
243k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[ns]date
2012-06-28 18:51:49
2023-09-14 21:59:16
gha_created_at
timestamp[ns]date
2008-02-11 22:55:26
2023-08-10 11:14:58
gha_language
stringclasses
147 values
src_encoding
stringclasses
26 values
language
stringclasses
2 values
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
6
10.2M
extension
stringclasses
115 values
filename
stringlengths
3
113
content
stringlengths
6
10.2M
8a44385b24f35b479a22e85fa905856c94391cf6
3934cdf17301219728a967e8913237284ae57bd3
/src/subgraph/fully-connected.c
b2f6be29db24984df2c01ec6c851fe8b1d063c26
[ "LicenseRef-scancode-generic-cla", "BSD-3-Clause" ]
permissive
google/XNNPACK
c1a709b570460dd9e352300b18ba75025ace34ac
c758a4a6601513736ae520dd87206c76e8f5f05a
refs/heads/master
2023-08-30T10:43:28.569336
2023-08-30T07:46:17
2023-08-30T07:47:37
208,364,128
1,565
313
NOASSERTION
2023-09-14T19:47:21
2019-09-13T23:48:37
C
UTF-8
C
false
false
31,756
c
fully-connected.c
// Copyright 2020 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <assert.h> #include <math.h> #include <stddef.h> #include <stdint.h> #include <xnnpack.h> #include <xnnpack/log.h> #include <xnnpack/node-type.h> #include <xnnpack/operator.h> #include <xnnpack/operator-type.h> #include <xnnpack/params.h> #include <xnnpack/requantization.h> #include <xnnpack/subgraph.h> #include <xnnpack/subgraph-validation.h> static enum xnn_status create_fully_connected_operator( const struct xnn_node* node, const struct xnn_value* values, size_t num_values, struct xnn_operator_data* opdata, struct xnn_code_cache* code_cache, struct xnn_weights_cache* weights_cache) { assert(node->num_inputs >= 2); assert(node->num_inputs <= 3); const uint32_t input_id = node->inputs[0]; assert(input_id != XNN_INVALID_VALUE_ID); assert(input_id < num_values); const uint32_t filter_id = node->inputs[1]; assert(filter_id != XNN_INVALID_VALUE_ID); assert(filter_id < num_values); assert(node->num_outputs == 1); const uint32_t output_id = node->outputs[0]; assert(output_id != XNN_INVALID_VALUE_ID); assert(output_id < num_values); size_t output_channels, input_channels; if (node->flags & XNN_FLAG_TRANSPOSE_WEIGHTS) { input_channels = values[node->inputs[1]].shape.dim[0]; output_channels = values[node->inputs[1]].shape.dim[1]; } else { output_channels = values[node->inputs[1]].shape.dim[0]; input_channels = values[node->inputs[1]].shape.dim[1]; } const void* kernel_data = values[filter_id].fp32_data != NULL ? values[filter_id].fp32_data : values[filter_id].data; bool has_non_static_weights = (kernel_data == NULL); const void* bias_data = NULL; if (node->num_inputs > 2) { const uint32_t bias_id = node->inputs[2]; assert(bias_id != XNN_INVALID_VALUE_ID); assert(bias_id < num_values); bias_data = values[bias_id].fp32_data != NULL ? values[bias_id].fp32_data : values[bias_id].data; has_non_static_weights |= (bias_data == NULL); } enum xnn_status status; switch (node->compute_type) { case xnn_compute_type_fp16: if (has_non_static_weights) { status = xnn_create_dynamic_fully_connected_nc_f16( node->activation.output_min, node->activation.output_max, /*flags=*/node->flags, &opdata->operator_objects[0]); } else { status = xnn_create_fully_connected_nc_f16( input_channels, output_channels, /*input_stride=*/input_channels, /*output_stride=*/output_channels, kernel_data, bias_data, node->activation.output_min, node->activation.output_max, node->flags | XNN_FLAG_FP32_STATIC_WEIGHTS, code_cache, weights_cache, &opdata->operator_objects[0]); } break; case xnn_compute_type_fp32: if (has_non_static_weights) { status = xnn_create_dynamic_fully_connected_nc_f32( node->activation.output_min, node->activation.output_max, /*flags=*/node->flags, &opdata->operator_objects[0]); } else { switch (values[filter_id].datatype) { case xnn_datatype_qcint4: status = xnn_create_fully_connected_nc_f32_qc4w( input_channels, output_channels, /*input_stride=*/input_channels, /*output_stride=*/output_channels, values[filter_id].quantization.zero_point, values[filter_id].quantization.channelwise_scale, kernel_data, bias_data, node->activation.output_min, node->activation.output_max, /*flags=*/node->flags, code_cache, weights_cache, &opdata->operator_objects[0]); break; case xnn_datatype_qcint8: status = xnn_create_fully_connected_nc_f32_qc8w( input_channels, output_channels, /*input_stride=*/input_channels, /*output_stride=*/output_channels, values[filter_id].quantization.channelwise_scale, kernel_data, bias_data, node->activation.output_min, node->activation.output_max, /*flags=*/node->flags, code_cache, weights_cache, &opdata->operator_objects[0]); break; case xnn_datatype_fp32: status = xnn_create_fully_connected_nc_f32( input_channels, output_channels, /*input_stride=*/input_channels, /*output_stride=*/output_channels, kernel_data, bias_data, node->activation.output_min, node->activation.output_max, /*flags=*/node->flags, code_cache, weights_cache, &opdata->operator_objects[0]); break; default: XNN_UNREACHABLE; } } break; case xnn_compute_type_qd8_to_fp32: { assert(!has_non_static_weights); assert(kernel_data != NULL); status = xnn_create_fully_connected_nc_qd8_f32_qc8w( input_channels, output_channels, /*input_stride=*/input_channels, /*output_stride=*/output_channels, values[filter_id].quantization.channelwise_scale, kernel_data, bias_data, node->activation.output_min, node->activation.output_max, node->flags, code_cache, weights_cache, &opdata->operator_objects[0]); break; } case xnn_compute_type_qs8: { assert(!has_non_static_weights); assert(kernel_data != NULL); const float output_scale = values[output_id].quantization.scale; const int32_t output_zero_point = values[output_id].quantization.zero_point; const int8_t output_min = xnn_qs8_quantize(node->activation.output_min, output_scale, output_zero_point); const int8_t output_max = xnn_qs8_quantize(node->activation.output_max, output_scale, output_zero_point); status = xnn_create_fully_connected_nc_qs8( input_channels, output_channels, /*input_stride=*/input_channels, /*output_stride=*/output_channels, (int8_t) values[input_id].quantization.zero_point, values[input_id].quantization.scale, values[filter_id].quantization.scale, kernel_data, bias_data, (int8_t) output_zero_point, output_scale, output_min, output_max, /*flags=*/node->flags, code_cache, weights_cache, &opdata->operator_objects[0]); break; } case xnn_compute_type_qu8: { assert(!has_non_static_weights); assert(kernel_data != NULL); const float output_scale = values[output_id].quantization.scale; const int32_t output_zero_point = values[output_id].quantization.zero_point; const uint8_t output_min = xnn_qu8_quantize(node->activation.output_min, output_scale, output_zero_point); const uint8_t output_max = xnn_qu8_quantize(node->activation.output_max, output_scale, output_zero_point); status = xnn_create_fully_connected_nc_qu8( input_channels, output_channels, /*input_stride=*/input_channels, /*output_stride=*/output_channels, (uint8_t) values[input_id].quantization.zero_point, values[input_id].quantization.scale, (uint8_t) values[filter_id].quantization.zero_point, values[filter_id].quantization.scale, kernel_data, bias_data, (uint8_t) output_zero_point, output_scale, output_min, output_max, /*flags=*/node->flags, code_cache, weights_cache, &opdata->operator_objects[0]); break; } default: XNN_UNREACHABLE; } return status; } static enum xnn_status reshape_fully_connected_operator( struct xnn_operator_data* opdata, const struct xnn_value* values, size_t num_values, pthreadpool_t threadpool) { const uint32_t input_id = opdata->inputs[0]; assert(input_id < num_values); const uint32_t filter_id = opdata->inputs[1]; assert(filter_id < num_values); const size_t num_input_elements = xnn_shape_multiply_all_dims(&values[input_id].shape); size_t output_channels, input_channels; if (opdata->flags & XNN_FLAG_TRANSPOSE_WEIGHTS) { input_channels = values[filter_id].shape.dim[0]; output_channels = values[filter_id].shape.dim[1]; } else { output_channels = values[filter_id].shape.dim[0]; input_channels = values[filter_id].shape.dim[1]; } const size_t batch_size = num_input_elements / input_channels; switch (opdata->operator_objects[0]->type) { case xnn_operator_type_dynamic_fully_connected_nc_f16: return xnn_reshape_dynamic_fully_connected_nc_f16( opdata->operator_objects[0], batch_size, input_channels, output_channels, input_channels, output_channels, &opdata->workspace_size, &opdata->workspace_alignment, threadpool); case xnn_operator_type_dynamic_fully_connected_nc_f32: return xnn_reshape_dynamic_fully_connected_nc_f32( opdata->operator_objects[0], batch_size, input_channels, output_channels, input_channels, output_channels, &opdata->workspace_size, &opdata->workspace_alignment, threadpool); case xnn_operator_type_fully_connected_nc_f16: return xnn_reshape_fully_connected_nc_f16( opdata->operator_objects[0], batch_size, threadpool); case xnn_operator_type_fully_connected_nc_f32: return xnn_reshape_fully_connected_nc_f32( opdata->operator_objects[0], batch_size, threadpool); case xnn_operator_type_fully_connected_nc_f32_qc4w: return xnn_reshape_fully_connected_nc_f32_qc4w( opdata->operator_objects[0], batch_size, threadpool); case xnn_operator_type_fully_connected_nc_f32_qc8w: return xnn_reshape_fully_connected_nc_f32_qc8w( opdata->operator_objects[0], batch_size, threadpool); case xnn_operator_type_fully_connected_nc_qd8_f32_qc8w: return xnn_reshape_fully_connected_nc_qd8_f32_qc8w( opdata->operator_objects[0], batch_size, threadpool); case xnn_operator_type_fully_connected_nc_qs8: return xnn_reshape_fully_connected_nc_qs8( opdata->operator_objects[0], batch_size, threadpool); case xnn_operator_type_fully_connected_nc_qu8: return xnn_reshape_fully_connected_nc_qu8( opdata->operator_objects[0], batch_size, threadpool); default: XNN_UNREACHABLE; } } static enum xnn_status setup_fully_connected_operator( const struct xnn_operator_data* opdata, const struct xnn_value* values, size_t num_values, pthreadpool_t threadpool) { const uint32_t input_id = opdata->inputs[0]; assert(input_id != XNN_INVALID_VALUE_ID); assert(input_id < num_values); const uint32_t filter_id = opdata->inputs[1]; assert(filter_id != XNN_INVALID_VALUE_ID); assert(filter_id < num_values); const uint32_t bias_id = opdata->inputs[2]; const uint32_t output_id = opdata->outputs[0]; assert(output_id != XNN_INVALID_VALUE_ID); assert(output_id < num_values); const struct xnn_value* input_value = values + input_id; const void* input_data = input_value->data; assert(input_data != NULL); const struct xnn_value* kernel_value = values + filter_id; bool has_dynamic_weights = kernel_value->allocation_type != xnn_allocation_type_static; const void* kernel_data = kernel_value->allocation_type == xnn_allocation_type_static ? NULL : kernel_value->data; const void* bias_data = NULL; if (opdata->num_inputs > 2) { assert(bias_id != XNN_INVALID_VALUE_ID); assert(bias_id < num_values); const struct xnn_value* bias_value = values + bias_id; has_dynamic_weights |= bias_value->allocation_type != xnn_allocation_type_static; if (has_dynamic_weights) { kernel_data = kernel_value->data; bias_data = bias_value->data; } } const struct xnn_value* output_value = values + output_id; void* output_data = output_value->data; assert(output_data != NULL); switch (opdata->operator_objects[0]->type) { case xnn_operator_type_dynamic_fully_connected_nc_f16: assert(kernel_data != NULL); return xnn_setup_dynamic_fully_connected_nc_f16( opdata->operator_objects[0], opdata->workspace, input_data, kernel_data, bias_data, output_data); case xnn_operator_type_dynamic_fully_connected_nc_f32: assert(kernel_data != NULL); return xnn_setup_dynamic_fully_connected_nc_f32( opdata->operator_objects[0], opdata->workspace, input_data, kernel_data, bias_data, output_data); case xnn_operator_type_fully_connected_nc_f16: assert(kernel_data == NULL); assert(bias_data == NULL); return xnn_setup_fully_connected_nc_f16( opdata->operator_objects[0], input_data, output_data); case xnn_operator_type_fully_connected_nc_f32: assert(kernel_data == NULL); assert(bias_data == NULL); return xnn_setup_fully_connected_nc_f32( opdata->operator_objects[0], input_data, output_data); case xnn_operator_type_fully_connected_nc_f32_qc4w: assert(kernel_data == NULL); assert(bias_data == NULL); return xnn_setup_fully_connected_nc_f32_qc4w( opdata->operator_objects[0], input_data, output_data); case xnn_operator_type_fully_connected_nc_f32_qc8w: assert(kernel_data == NULL); assert(bias_data == NULL); return xnn_setup_fully_connected_nc_f32_qc8w( opdata->operator_objects[0], input_data, output_data); case xnn_operator_type_fully_connected_nc_qd8_f32_qc8w: { const void* quantization_params = input_value->quantization.dynamic_params; assert(kernel_data == NULL); assert(bias_data == NULL); assert(quantization_params != NULL); return xnn_setup_fully_connected_nc_qd8_f32_qc8w( opdata->operator_objects[0], input_data, output_data, quantization_params); } case xnn_operator_type_fully_connected_nc_qs8: assert(kernel_data == NULL); assert(bias_data == NULL); return xnn_setup_fully_connected_nc_qs8( opdata->operator_objects[0], input_data, output_data); case xnn_operator_type_fully_connected_nc_qu8: assert(kernel_data == NULL); assert(bias_data == NULL); return xnn_setup_fully_connected_nc_qu8( opdata->operator_objects[0], input_data, output_data); default: XNN_UNREACHABLE; } } static enum xnn_shape_inference_status infer_shape_forward( const struct xnn_node* node, struct xnn_value* values) { // Assert that filter tensor has static shape. const uint32_t filter_id = node->inputs[1]; const struct xnn_value* filter = &values[filter_id]; assert(xnn_tensor_shape_is_static(filter)); enum xnn_shape_inference_status status = xnn_shape_inference_status_no_change; // Infer output channels. const uint32_t output_channel_index = (node->flags & XNN_FLAG_TRANSPOSE_WEIGHTS) ? 1 : 0; const uint32_t output_id = node->outputs[0]; struct xnn_value* output = &values[output_id]; status = xnn_tensor_propagate_dimension(output, output->shape.num_dims - 1, filter, output_channel_index); if (status == xnn_shape_inference_status_error) { return status; } if (node->flags & XNN_FLAG_TENSORFLOW_RESHAPE_2D) { // No inference for input/output shape possible. return status; } // Propagate input shape to output. const struct xnn_value* input = &values[node->inputs[0]]; for (size_t cur_dim = 0; cur_dim < input->shape.num_dims - 1; cur_dim++) { const enum xnn_shape_inference_status changed = xnn_tensor_propagate_dimension(output, cur_dim, input, cur_dim); if (changed == xnn_shape_inference_status_error) { return changed; } else if (changed == xnn_shape_inference_status_changed) { // Only overwrite status if inference on this dimension changed. We could have changed something above, and not // changed anything here, then overwriting status to be no_change will be incorrect. status = changed; } } return status; } static enum xnn_shape_inference_status infer_shape_backward( const struct xnn_node* node, struct xnn_value* values) { // Assert that filter tensor has static shape. const uint32_t filter_id = node->inputs[1]; const struct xnn_value* filter = &values[filter_id]; assert(xnn_tensor_shape_is_static(filter)); enum xnn_shape_inference_status status = xnn_shape_inference_status_no_change; // Infer input channels. const uint32_t input_channel_index = (node->flags & XNN_FLAG_TRANSPOSE_WEIGHTS) ? 0 : 1; const uint32_t input_id = node->inputs[0]; struct xnn_value* input = &values[input_id]; status = xnn_tensor_propagate_dimension(input, input->shape.num_dims - 1, filter, input_channel_index); if (status == xnn_shape_inference_status_error) { return status; } if (node->flags & XNN_FLAG_TENSORFLOW_RESHAPE_2D) { // No inference for input/output shape possible. return status; } // Propagate output shape to input. const struct xnn_value* output = &values[node->outputs[0]]; for (size_t cur_dim = 0; cur_dim < output->shape.num_dims - 1; cur_dim++) { const enum xnn_shape_inference_status changed = xnn_tensor_propagate_dimension(input, cur_dim, output, cur_dim); if (changed == xnn_shape_inference_status_error) { return changed; } else if (changed == xnn_shape_inference_status_changed) { // Only overwrite status if inference on this dimension changed. We could have changed something above, and not // changed anything here, then overwriting status to be no_change will be incorrect. status = changed; } } return status; } static inline enum xnn_compute_type validate_datatypes_with_bias( enum xnn_datatype input_datatype, enum xnn_datatype kernel_datatype, enum xnn_datatype bias_datatype, enum xnn_datatype output_datatype) { switch (kernel_datatype) { case xnn_datatype_fp32: if (input_datatype == xnn_datatype_fp32 && bias_datatype == xnn_datatype_fp32 && output_datatype == xnn_datatype_fp32) { return xnn_compute_type_fp32; } break; case xnn_datatype_qcint4: case xnn_datatype_qcint8: if (input_datatype == xnn_datatype_fp32 && bias_datatype == xnn_datatype_fp32 && output_datatype == xnn_datatype_fp32) { return xnn_compute_type_fp32; } else if (input_datatype == xnn_datatype_qdint8 && bias_datatype == xnn_datatype_fp32 && output_datatype == xnn_datatype_fp32) { return xnn_compute_type_qd8_to_fp32; } case xnn_datatype_qint8: if (input_datatype == xnn_datatype_qint8 && bias_datatype == xnn_datatype_qint32 && output_datatype == xnn_datatype_qint8) { return xnn_compute_type_qs8; } break; case xnn_datatype_quint8: if (input_datatype == xnn_datatype_quint8 && bias_datatype == xnn_datatype_qint32 && output_datatype == xnn_datatype_quint8) { return xnn_compute_type_qu8; } break; default: XNN_UNREACHABLE; } return xnn_compute_type_invalid; } static inline enum xnn_compute_type validate_datatypes_without_bias( enum xnn_datatype input_datatype, enum xnn_datatype kernel_datatype, enum xnn_datatype output_datatype) { switch (kernel_datatype) { case xnn_datatype_fp32: if (input_datatype == xnn_datatype_fp32 && output_datatype == xnn_datatype_fp32) { return xnn_compute_type_fp32; } break; case xnn_datatype_qcint4: case xnn_datatype_qcint8: if (input_datatype == xnn_datatype_fp32 && output_datatype == xnn_datatype_fp32) { return xnn_compute_type_fp32; } else if (input_datatype == xnn_datatype_qdint8 && output_datatype == xnn_datatype_fp32) { return xnn_compute_type_qd8_to_fp32; } case xnn_datatype_qint8: if (input_datatype == xnn_datatype_qint8 && output_datatype == xnn_datatype_qint8) { return xnn_compute_type_qs8; } break; case xnn_datatype_quint8: if (input_datatype == xnn_datatype_quint8 && output_datatype == xnn_datatype_quint8) { return xnn_compute_type_qu8; } break; default: XNN_UNREACHABLE; } return xnn_compute_type_invalid; } enum xnn_status xnn_define_fully_connected( xnn_subgraph_t subgraph, float output_min, float output_max, uint32_t input_id, uint32_t filter_id, uint32_t bias_id, uint32_t output_id, uint32_t flags) { enum xnn_status status; if ((status = xnn_subgraph_check_xnnpack_initialized(xnn_node_type_fully_connected)) != xnn_status_success) { return status; } status = xnn_subgraph_check_output_min_max(xnn_node_type_fully_connected, output_min, output_max); if (status != xnn_status_success) { return status; } if ((status = xnn_subgraph_check_input_node_id(xnn_node_type_fully_connected, input_id, subgraph->num_values)) != xnn_status_success) { return status; } const struct xnn_value* input_value = &subgraph->values[input_id]; status = xnn_subgraph_check_input_type_dense(xnn_node_type_fully_connected, input_id, input_value); if (status != xnn_status_success) { return status; } switch (input_value->datatype) { case xnn_datatype_fp32: case xnn_datatype_qint8: case xnn_datatype_quint8: break; case xnn_datatype_qdint8: if (input_value->quantization.num_nonbatch_dims >= input_value->shape.num_dims) { xnn_log_error( "failed to define %s operator with input ID #%" PRIu32 ": num_nonbatch_dims (%zu) must be " "< num_dims (%zu)", xnn_node_type_to_string(xnn_node_type_fully_connected), input_id, input_value->quantization.num_nonbatch_dims, input_value->shape.num_dims); return xnn_status_invalid_parameter; } break; default: xnn_log_error( "failed to define %s operator with input ID #%" PRIu32 ": unsupported Value datatype %s (%d)", xnn_node_type_to_string(xnn_node_type_fully_connected), input_id, xnn_datatype_to_string(input_value->datatype), input_value->datatype); return xnn_status_invalid_parameter; } if (filter_id >= subgraph->num_values) { xnn_log_error( "failed to define %s operator with filter ID #%" PRIu32 ": invalid Value ID", xnn_node_type_to_string(xnn_node_type_fully_connected), filter_id); return xnn_status_invalid_parameter; } const struct xnn_value* kernel_value = &subgraph->values[filter_id]; if (kernel_value->type != xnn_value_type_dense_tensor) { xnn_log_error( "failed to define %s operator with filter ID #%" PRIu32 ": unsupported Value type %d (expected dense tensor)", xnn_node_type_to_string(xnn_node_type_fully_connected), filter_id, kernel_value->type); return xnn_status_invalid_parameter; } // Check that filter shape is fully known. if (!xnn_tensor_shape_is_static(kernel_value)) { xnn_log_error( "failed to define %s operator with filter ID #%" PRIu32 ": filter must have static dimensions.", xnn_node_type_to_string(xnn_node_type_fully_connected), filter_id); return xnn_status_invalid_parameter; } // Non-static kernel is supported, but only for some data types switch (kernel_value->datatype) { case xnn_datatype_fp32: break; // non-static kernel is supported default: if (kernel_value->data == NULL) { xnn_log_error( "failed to define %s operator with filter ID #%" PRIu32 ": non-static Value", xnn_node_type_to_string(xnn_node_type_fully_connected), filter_id); return xnn_status_invalid_parameter; } break; } switch (kernel_value->datatype) { case xnn_datatype_fp32: break; case xnn_datatype_qcint4: break; case xnn_datatype_qcint8: break; case xnn_datatype_qint8: if (kernel_value->quantization.zero_point != 0) { xnn_log_error( "failed to define %s operator with filter ID #%" PRIu32 ": unsupported quantization zero point %" PRId32 " for datatype %s", xnn_node_type_to_string(xnn_node_type_fully_connected), filter_id, kernel_value->quantization.zero_point, xnn_datatype_to_string(kernel_value->datatype)); } break; case xnn_datatype_quint8: break; default: xnn_log_error( "failed to define %s operator with filter ID #%" PRIu32 ": unsupported Value datatype %s (%d)", xnn_node_type_to_string(xnn_node_type_fully_connected), filter_id, xnn_datatype_to_string(kernel_value->datatype), kernel_value->datatype); return xnn_status_invalid_parameter; } const bool is_channelwise_quantized = kernel_value->datatype == xnn_datatype_qcint8 || kernel_value->datatype == xnn_datatype_qcint4; if (is_channelwise_quantized) { const size_t output_channels_dim = ((flags & XNN_FLAG_TRANSPOSE_WEIGHTS) != 0) ? 1 : 0; if (kernel_value->quantization.channel_dimension != output_channels_dim) { xnn_log_error( "failed to define %s operator with filter ID #%" PRIu32 ": invalid channel dimension %zu", xnn_node_type_to_string(xnn_node_type_fully_connected), input_id, kernel_value->quantization.channel_dimension); return xnn_status_invalid_parameter; } } const struct xnn_value* bias_value = NULL; if (bias_id != XNN_INVALID_VALUE_ID) { if (bias_id >= subgraph->num_values) { xnn_log_error( "failed to define %s operator with bias ID #%" PRIu32 ": invalid Value ID", xnn_node_type_to_string(xnn_node_type_fully_connected), bias_id); return xnn_status_invalid_parameter; } bias_value = &subgraph->values[bias_id]; if (bias_value->type != xnn_value_type_dense_tensor) { xnn_log_error( "failed to define %s operator with bias ID #%" PRIu32 ": unsupported Value type %d (expected dense tensor)", xnn_node_type_to_string(xnn_node_type_fully_connected), bias_id, bias_value->type); return xnn_status_invalid_parameter; } // Check that bias shape is fully known. if (!xnn_tensor_shape_is_static(bias_value)) { xnn_log_error( "failed to define %s operator with bias ID #%" PRIu32 ": bias must have static dimensions.", xnn_node_type_to_string(xnn_node_type_fully_connected), bias_id); return xnn_status_invalid_parameter; } // Non-static bias is supported, but only for some data types switch (bias_value->datatype) { case xnn_datatype_fp32: if (is_channelwise_quantized && bias_value->data == NULL) { xnn_log_error( "failed to define %s operator with bias ID #%" PRIu32 ": non-static Value", xnn_node_type_to_string(xnn_node_type_fully_connected), bias_id); return xnn_status_invalid_parameter; } break; // non-static bias is supported default: if (bias_value->data == NULL) { xnn_log_error( "failed to define %s operator with bias ID #%" PRIu32 ": non-static Value", xnn_node_type_to_string(xnn_node_type_fully_connected), bias_id); return xnn_status_invalid_parameter; } break; } switch (bias_value->datatype) { case xnn_datatype_fp32: case xnn_datatype_qint32: break; default: xnn_log_error( "failed to define %s operator with bias ID #%" PRIu32 ": unsupported Value datatype %s (%d)", xnn_node_type_to_string(xnn_node_type_fully_connected), bias_id, xnn_datatype_to_string(bias_value->datatype), bias_value->datatype); return xnn_status_invalid_parameter; } } status = xnn_subgraph_check_output_node_id(xnn_node_type_fully_connected, output_id, subgraph->num_values); if (status != xnn_status_success) { return status; } const struct xnn_value* output_value = &subgraph->values[output_id]; status = xnn_subgraph_check_output_type_dense(xnn_node_type_fully_connected, output_id, output_value); if (status != xnn_status_success) { return status; } switch (output_value->datatype) { case xnn_datatype_fp32: case xnn_datatype_qint8: case xnn_datatype_quint8: break; default: xnn_log_error( "failed to define %s operator with output ID #%" PRIu32 ": unsupported Value datatype %s (%d)", xnn_node_type_to_string(xnn_node_type_fully_connected), output_id, xnn_datatype_to_string(output_value->datatype), output_value->datatype); return xnn_status_invalid_parameter; } enum xnn_compute_type compute_type = xnn_compute_type_invalid; if (bias_value != NULL) { compute_type = validate_datatypes_with_bias( input_value->datatype, kernel_value->datatype, bias_value->datatype, output_value->datatype); if (compute_type == xnn_compute_type_invalid) { xnn_log_error( "failed to define %s operator with input ID #%" PRIu32 ", filter ID #%" PRIu32 ", bias ID #%" PRIu32 ", and output ID #%" PRIu32 ": mismatching datatypes across input (%s), filter (%s), bias (%s), and output (%s)", xnn_node_type_to_string(xnn_node_type_fully_connected), input_id, filter_id, bias_id, output_id, xnn_datatype_to_string(input_value->datatype), xnn_datatype_to_string(kernel_value->datatype), xnn_datatype_to_string(bias_value->datatype), xnn_datatype_to_string(output_value->datatype)); return xnn_status_invalid_parameter; } } else { compute_type = validate_datatypes_without_bias( input_value->datatype, kernel_value->datatype, output_value->datatype); if (compute_type == xnn_compute_type_invalid) { xnn_log_error( "failed to define %s operator with input ID #%" PRIu32 ", filter ID #%" PRIu32 ", and output ID #%" PRIu32 ": mismatching datatypes across input (%s), filter (%s), and output (%s)", xnn_node_type_to_string(xnn_node_type_fully_connected), input_id, filter_id, output_id, xnn_datatype_to_string(input_value->datatype), xnn_datatype_to_string(kernel_value->datatype), xnn_datatype_to_string(output_value->datatype)); return xnn_status_invalid_parameter; } } struct xnn_node* node = xnn_subgraph_new_node(subgraph); if (node == NULL) { return xnn_status_out_of_memory; } node->type = xnn_node_type_fully_connected; node->compute_type = compute_type; node->activation.output_min = output_min; node->activation.output_max = output_max; node->num_inputs = 2 + (size_t) (bias_id != XNN_INVALID_VALUE_ID); node->inputs[0] = input_id; node->inputs[1] = filter_id; node->inputs[2] = bias_id; node->num_outputs = 1; node->outputs[0] = output_id; node->flags = flags; node->create = create_fully_connected_operator; node->reshape = reshape_fully_connected_operator; node->setup = setup_fully_connected_operator; node->infer_shape_forward = infer_shape_forward; node->infer_shape_backward = infer_shape_backward; return xnn_status_success; }
e02d6af0db7664a2b1259b57827cd1fe0d53b65f
5e4913b3d7b6dfd9f35d9e5f24486bb6b6145125
/src/plugins/toml/toml.c
e276b2c44079c9321812b26291a4dcaadd429de9
[ "BSD-3-Clause" ]
permissive
ElektraInitiative/libelektra
ff5d5cfc4bf91d704f58405b14ea694aad3a2edd
dbbe4ae4f669c322a8f95f59112d3f5fc370bbd9
refs/heads/master
2023-08-05T14:54:48.081359
2023-08-04T12:40:00
2023-08-04T12:40:00
21,063,580
215
170
BSD-3-Clause
2023-09-07T13:34:30
2014-06-21T08:01:04
C
UTF-8
C
false
false
1,658
c
toml.c
/** * @file * * @brief Source for the toml plugin * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ #include <kdb.h> #include <kdberrors.h> #include <kdblogger.h> #include <kdbmacros.h> #include "driver.h" #include "toml.h" #include "write.h" KeySet * getContract (void) { return ksNew (30, keyNew ("system:/elektra/modules/toml", KEY_VALUE, "toml plugin waits for your orders", KEY_END), keyNew ("system:/elektra/modules/toml/exports", KEY_END), keyNew ("system:/elektra/modules/toml/exports/get", KEY_FUNC, elektraTomlGet, KEY_END), keyNew ("system:/elektra/modules/toml/exports/set", KEY_FUNC, elektraTomlSet, KEY_END), #include ELEKTRA_README keyNew ("system:/elektra/modules/toml/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END); } int elektraTomlGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey) { if (strcmp (keyName (parentKey), "system:/elektra/modules/toml") == 0) { KeySet * contract = getContract (); ksAppend (returned, contract); ksDel (contract); return ELEKTRA_PLUGIN_STATUS_SUCCESS; } else { int result = tomlRead (returned, parentKey); return result == 0 ? ELEKTRA_PLUGIN_STATUS_SUCCESS : ELEKTRA_PLUGIN_STATUS_ERROR; } } int elektraTomlSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey) { int result = tomlWrite (returned, parentKey); return result == 0 ? ELEKTRA_PLUGIN_STATUS_SUCCESS : ELEKTRA_PLUGIN_STATUS_ERROR; } Plugin * ELEKTRA_PLUGIN_EXPORT { return elektraPluginExport ("toml", ELEKTRA_PLUGIN_GET, &elektraTomlGet, ELEKTRA_PLUGIN_SET, &elektraTomlSet, ELEKTRA_PLUGIN_END); }
c5c955cfe3e725570d521a483d93b24e4687dfd4
581bdcc078d282e388f1b655d4cfc4e08152d117
/plugins/ExtendedTools/thrdact.c
15d6e87d7f8b0a3f2783bdde5392126bd64ad012
[ "MIT", "BSD-3-Clause", "LGPL-2.0-or-later", "Zlib", "LGPL-2.1-or-later", "GPL-2.0-only", "LicenseRef-scancode-public-domain" ]
permissive
winsiderss/systeminformer
774928be871f0055263ac5e62ae0a598b098486b
5a6b442acd45d681f699a133d476a3211d072871
refs/heads/master
2023-08-28T15:43:41.074679
2023-08-27T20:59:20
2023-08-27T20:59:20
50,824,485
2,137
292
MIT
2023-09-10T22:35:12
2016-02-01T08:10:21
C
UTF-8
C
false
false
1,149
c
thrdact.c
/* * Copyright (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved. * * This file is part of System Informer. * * Authors: * * wj32 2010 * */ #include "exttools.h" BOOLEAN EtUiCancelIoThread( _In_ HWND hWnd, _In_ PPH_THREAD_ITEM Thread ) { NTSTATUS status; BOOLEAN cont = FALSE; HANDLE threadHandle; IO_STATUS_BLOCK isb; if (!PhGetIntegerSetting(L"EnableWarnings") || PhShowConfirmMessage( hWnd, L"end", L"I/O for the selected thread", NULL, FALSE )) cont = TRUE; if (!cont) return FALSE; if (NT_SUCCESS(status = PhOpenThread(&threadHandle, THREAD_TERMINATE, Thread->ThreadId))) { status = NtCancelSynchronousIoFile(threadHandle, NULL, &isb); NtClose(threadHandle); } if (status == STATUS_NOT_FOUND) { PhShowInformation(hWnd, L"%s", L"There is no synchronous I/O to cancel."); return FALSE; } else if (!NT_SUCCESS(status)) { PhShowStatus(hWnd, L"Unable to cancel synchronous I/O", status, 0); return FALSE; } return TRUE; }
9902db62a11c246794d48d639baf624632dff6d3
af777935080dd963960f44561f25b0ae59f373a3
/Example/Pods/Headers/Public/JXCategoryView/JXCategoryIndicatorParamsModel.h
b2d49405d2b79434811e44e17fc431bbab53c583
[ "MIT" ]
permissive
pujiaxin33/JXCategoryView
2a3684461988cc1de8cf1e6190225d16af7816e3
8865907e0d5e7fd5af8ae847c309056a8a478315
refs/heads/master
2023-07-07T08:36:44.520235
2022-07-17T10:30:35
2022-07-17T10:30:35
126,299,577
6,223
1,179
MIT
2023-06-30T08:49:22
2018-03-22T07:54:35
Objective-C
UTF-8
C
false
false
62
h
JXCategoryIndicatorParamsModel.h
../../../../../Sources/Common/JXCategoryIndicatorParamsModel.h
7acaa6c50652ef93d71707f65f43900f0dc23a9d
5eff7a36d9a9917dce9111f0c3074375fe6f7656
/lib/mesa/src/gallium/auxiliary/driver_ddebug/dd_pipe.h
b880a80453681dfa140553e7ceb71cbfaf6da7b6
[]
no_license
openbsd/xenocara
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
a012b5de33ea0b977095d77316a521195b26cc6b
refs/heads/master
2023-08-25T12:16:58.862008
2023-08-12T16:16:25
2023-08-12T16:16:25
66,967,384
177
66
null
2023-07-22T18:12:37
2016-08-30T18:36:01
C
UTF-8
C
false
false
9,704
h
dd_pipe.h
/************************************************************************** * * Copyright 2015 Advanced Micro Devices, Inc. * Copyright 2008 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * on the rights to use, copy, modify, merge, publish, distribute, sub * license, and/or sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #ifndef DD_H_ #define DD_H_ #include "pipe/p_context.h" #include "pipe/p_state.h" #include "pipe/p_screen.h" #include "dd_util.h" #include "os/os_thread.h" #include "util/list.h" #include "util/u_log.h" #include "util/u_queue.h" struct dd_context; enum dd_dump_mode { DD_DUMP_ONLY_HANGS, DD_DUMP_ALL_CALLS, DD_DUMP_APITRACE_CALL, }; struct dd_screen { struct pipe_screen base; struct pipe_screen *screen; unsigned timeout_ms; enum dd_dump_mode dump_mode; bool flush_always; bool transfers; bool verbose; unsigned skip_count; unsigned apitrace_dump_call; }; enum call_type { CALL_FLUSH, CALL_DRAW_VBO, CALL_LAUNCH_GRID, CALL_RESOURCE_COPY_REGION, CALL_BLIT, CALL_FLUSH_RESOURCE, CALL_CLEAR, CALL_CLEAR_BUFFER, CALL_CLEAR_TEXTURE, CALL_CLEAR_RENDER_TARGET, CALL_CLEAR_DEPTH_STENCIL, CALL_GENERATE_MIPMAP, CALL_GET_QUERY_RESULT_RESOURCE, CALL_TRANSFER_MAP, CALL_TRANSFER_FLUSH_REGION, CALL_TRANSFER_UNMAP, CALL_BUFFER_SUBDATA, CALL_TEXTURE_SUBDATA, }; struct call_resource_copy_region { struct pipe_resource *dst; unsigned dst_level; unsigned dstx, dsty, dstz; struct pipe_resource *src; unsigned src_level; struct pipe_box src_box; }; struct call_clear { unsigned buffers; struct pipe_scissor_state scissor_state; union pipe_color_union color; double depth; unsigned stencil; }; struct call_clear_buffer { struct pipe_resource *res; unsigned offset; unsigned size; const void *clear_value; int clear_value_size; }; struct call_generate_mipmap { struct pipe_resource *res; enum pipe_format format; unsigned base_level; unsigned last_level; unsigned first_layer; unsigned last_layer; }; struct call_flush { unsigned flags; }; struct call_draw_info { struct pipe_draw_info info; unsigned drawid_offset; struct pipe_draw_indirect_info indirect; struct pipe_draw_start_count_bias draw; }; struct call_get_query_result_resource { struct pipe_query *query; enum pipe_query_type query_type; enum pipe_query_flags flags; enum pipe_query_value_type result_type; int index; struct pipe_resource *resource; unsigned offset; }; struct call_transfer_map { struct pipe_transfer *transfer_ptr; struct pipe_transfer transfer; void *ptr; }; struct call_transfer_flush_region { struct pipe_transfer *transfer_ptr; struct pipe_transfer transfer; struct pipe_box box; }; struct call_transfer_unmap { struct pipe_transfer *transfer_ptr; struct pipe_transfer transfer; }; struct call_buffer_subdata { struct pipe_resource *resource; unsigned usage; unsigned offset; unsigned size; const void *data; }; struct call_texture_subdata { struct pipe_resource *resource; unsigned level; unsigned usage; struct pipe_box box; const void *data; unsigned stride; unsigned layer_stride; }; struct dd_call { enum call_type type; union { struct call_flush flush; struct call_draw_info draw_vbo; struct pipe_grid_info launch_grid; struct call_resource_copy_region resource_copy_region; struct pipe_blit_info blit; struct pipe_resource *flush_resource; struct call_clear clear; struct call_clear_buffer clear_buffer; struct call_generate_mipmap generate_mipmap; struct call_get_query_result_resource get_query_result_resource; struct call_transfer_map transfer_map; struct call_transfer_flush_region transfer_flush_region; struct call_transfer_unmap transfer_unmap; struct call_buffer_subdata buffer_subdata; struct call_texture_subdata texture_subdata; } info; }; struct dd_query { unsigned type; struct pipe_query *query; }; struct dd_state { void *cso; union { struct pipe_blend_state blend; struct pipe_depth_stencil_alpha_state dsa; struct pipe_rasterizer_state rs; struct pipe_sampler_state sampler; struct { struct pipe_vertex_element velems[PIPE_MAX_ATTRIBS]; unsigned count; } velems; struct pipe_shader_state shader; } state; }; struct dd_draw_state { struct { struct dd_query *query; bool condition; unsigned mode; } render_cond; struct pipe_vertex_buffer vertex_buffers[PIPE_MAX_ATTRIBS]; unsigned num_so_targets; struct pipe_stream_output_target *so_targets[PIPE_MAX_SO_BUFFERS]; unsigned so_offsets[PIPE_MAX_SO_BUFFERS]; struct dd_state *shaders[PIPE_SHADER_TYPES]; struct pipe_constant_buffer constant_buffers[PIPE_SHADER_TYPES][PIPE_MAX_CONSTANT_BUFFERS]; struct pipe_sampler_view *sampler_views[PIPE_SHADER_TYPES][PIPE_MAX_SAMPLERS]; struct dd_state *sampler_states[PIPE_SHADER_TYPES][PIPE_MAX_SAMPLERS]; struct pipe_image_view shader_images[PIPE_SHADER_TYPES][PIPE_MAX_SHADER_IMAGES]; struct pipe_shader_buffer shader_buffers[PIPE_SHADER_TYPES][PIPE_MAX_SHADER_BUFFERS]; struct dd_state *velems; struct dd_state *rs; struct dd_state *dsa; struct dd_state *blend; struct pipe_blend_color blend_color; struct pipe_stencil_ref stencil_ref; unsigned sample_mask; unsigned min_samples; struct pipe_clip_state clip_state; struct pipe_framebuffer_state framebuffer_state; struct pipe_poly_stipple polygon_stipple; struct pipe_scissor_state scissors[PIPE_MAX_VIEWPORTS]; struct pipe_viewport_state viewports[PIPE_MAX_VIEWPORTS]; float tess_default_levels[6]; unsigned apitrace_call_number; }; struct dd_draw_state_copy { struct dd_draw_state base; /* dd_draw_state_copy does not reference real CSOs. Instead, it points to * these variables, which serve as storage. */ struct dd_query render_cond; struct dd_state shaders[PIPE_SHADER_TYPES]; struct dd_state sampler_states[PIPE_SHADER_TYPES][PIPE_MAX_SAMPLERS]; struct dd_state velems; struct dd_state rs; struct dd_state dsa; struct dd_state blend; }; struct dd_draw_record { struct list_head list; struct dd_context *dctx; int64_t time_before; int64_t time_after; unsigned draw_call; /* The fence pointers are guaranteed to be valid once driver_finished is signalled */ struct pipe_fence_handle *prev_bottom_of_pipe; struct pipe_fence_handle *top_of_pipe; struct pipe_fence_handle *bottom_of_pipe; struct dd_call call; struct dd_draw_state_copy draw_state; struct util_queue_fence driver_finished; struct u_log_page *log_page; }; struct dd_context { struct pipe_context base; struct pipe_context *pipe; struct dd_draw_state draw_state; unsigned num_draw_calls; struct u_log_context log; /* Pipelined hang detection. * * Before each draw call, a new dd_draw_record is created that contains * a copy of all states. After each draw call, the driver's log is added * to this record. Additionally, deferred fences are associated to each * record both before and after the draw. * * The records are handed off to a separate thread which waits on the * records' fences. Records with signalled fences are freed. When a timeout * is detected, the thread dumps the records of in-flight draws. */ thrd_t thread; mtx_t mutex; cnd_t cond; struct list_head records; /* oldest record first */ unsigned num_records; bool kill_thread; bool api_stalled; }; struct pipe_context * dd_context_create(struct dd_screen *dscreen, struct pipe_context *pipe); void dd_init_draw_functions(struct dd_context *dctx); void dd_thread_join(struct dd_context *dctx); int dd_thread_main(void *input); FILE * dd_get_file_stream(struct dd_screen *dscreen, unsigned apitrace_call_number); static inline struct dd_context * dd_context(struct pipe_context *pipe) { return (struct dd_context *)pipe; } static inline struct dd_screen * dd_screen(struct pipe_screen *screen) { return (struct dd_screen*)screen; } static inline struct dd_query * dd_query(struct pipe_query *query) { return (struct dd_query *)query; } static inline struct pipe_query * dd_query_unwrap(struct pipe_query *query) { if (query) { return dd_query(query)->query; } else { return NULL; } } #define CTX_INIT(_member) \ dctx->base._member = dctx->pipe->_member ? dd_context_##_member : NULL #endif /* DD_H_ */
0b0454306c43c41b0c8444e4ebe32a57340f1634
85ccd32aa73eecf274a937f1fc3b6f4d484b77da
/test cases/unit/66 static link/test4.c
7c281e02610e80a4f2a244ad02b6c254a7f000d2
[ "Apache-2.0" ]
permissive
mesonbuild/meson
48321cf4235dfcc0194fed90ff43a57367592bf7
cf5adf0c646474f0259d123fad60ca5ed38ec891
refs/heads/master
2023-09-01T05:58:50.807952
2023-03-17T20:27:37
2023-08-31T11:52:41
19,784,232
5,122
1,848
Apache-2.0
2023-09-14T15:47:23
2014-05-14T15:08:16
Python
UTF-8
C
false
false
82
c
test4.c
int func9(); int main(int argc, char *argv[]) { return func9() == 3 ? 0 : 1; }
d2151527ea0618bbcb591d0d4ab7fb7d93cdbaba
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/compat/linux32/common/linux32_ioctl.c
7ff3269d0732615901f56f9079a5495b3a5399f1
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
5,103
c
linux32_ioctl.c
/* $NetBSD: linux32_ioctl.c,v 1.15 2021/09/19 23:51:37 thorpej Exp $ */ /*- * Copyright (c) 2006 Emmanuel Dreyfus, all rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Emmanuel Dreyfus * 4. The name of the author may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE THE AUTHOR 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 AUTHOR 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. */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: linux32_ioctl.c,v 1.15 2021/09/19 23:51:37 thorpej Exp $"); #include <sys/types.h> #include <sys/param.h> #include <sys/time.h> #include <sys/ucred.h> #include <sys/ioctl.h> #include <sys/file.h> #include <sys/filedesc.h> #include <compat/netbsd32/netbsd32.h> #include <compat/netbsd32/netbsd32_syscallargs.h> #include <compat/linux/common/linux_types.h> #include <compat/linux/common/linux_signal.h> #include <compat/linux/common/linux_ipc.h> #include <compat/linux/common/linux_ioctl.h> #include <compat/linux/common/linux_sem.h> #include <compat/linux/linux_syscallargs.h> #include <compat/linux32/common/linux32_types.h> #include <compat/linux32/common/linux32_signal.h> #include <compat/linux32/common/linux32_ioctl.h> #include <compat/linux32/common/linux32_termios.h> #include <compat/linux32/common/linux32_sysctl.h> #include <compat/linux32/linux32_syscallargs.h> #include <compat/ossaudio/ossaudio.h> #include <compat/ossaudio/ossaudiovar.h> int linux32_sys_ioctl(struct lwp *l, const struct linux32_sys_ioctl_args *uap, register_t *retval) { /* { syscallarg(int) fd; syscallarg(netbsd32_u_long) com; syscallarg(netbsd32_charp) data; } */ struct oss_sys_ioctl_args ossuap; int group; int error; group = LINUX32_IOCGROUP((int)SCARG(uap, com)); #ifdef DEBUG_LINUX printf("linux32_sys_ioctl(%d, 0x%x/\'%c\', %p)\n", SCARG(uap, fd), SCARG(uap, com), (char)group, SCARG_P32(uap, data)); #endif switch(group) { case 'T': { /* * Termios, the MIDI sequencer, and timerfd use 'T' to * identify the ioctl, so we have to differentiate them * in another way. * * (XXX We don't bother with MIDI here.) */ struct file *fp; if ((fp = fd_getfile(SCARG(uap, fd))) == NULL) return EBADF; if (fp->f_type == DTYPE_TIMERFD) { struct linux_sys_ioctl_args ua; SCARG(&ua, fd) = SCARG(uap, fd); SCARG(&ua, com) = SCARG(uap, com); SCARG(&ua, data) = SCARG_P32(uap, data); error = linux_ioctl_timerfd(l, &ua, retval); } else { error = linux32_ioctl_termios(l, uap, retval); } fd_putfile(SCARG(uap, fd)); break; } case 'M': case 'Q': case 'P': SCARG(&ossuap, fd) = SCARG(uap, fd); SCARG(&ossuap, com) = (u_long)SCARG(uap, com); SCARG(&ossuap, data) = SCARG_P32(uap, data); switch (group) { case 'M': error = oss_ioctl_mixer(l, &ossuap, retval); break; case 'Q': error = oss_ioctl_sequencer(l, &ossuap, retval); break; case 'P': error = oss_ioctl_audio(l, &ossuap, retval); break; default: error = EINVAL; /* shutup gcc */ break; } break; case 'V': /* video4linux2 */ case 'd': /* drm */ { struct sys_ioctl_args ua; u_long com = 0; if (SCARG(uap, com) & IOC_IN) com |= IOC_OUT; if (SCARG(uap, com) & IOC_OUT) com |= IOC_IN; SCARG(&ua, fd) = SCARG(uap, fd); SCARG(&ua, com) = SCARG(uap, com); SCARG(&ua, com) &= ~IOC_DIRMASK; SCARG(&ua, com) |= com; SCARG(&ua, data) = SCARG_P32(uap, data); error = sys_ioctl(l, (const void *)&ua, retval); break; } case 0x89: error = linux32_ioctl_socket(l, uap, retval); break; default: #ifdef DEBUG_LINUX printf("Not yet implemented ioctl group \'%c\'\n", group); #endif error = EINVAL; break; } if (error == EPASSTHROUGH) error = EINVAL; return error; }
75241353473e9c04fe74d741b92abdb2a379df20
e90671c6b1cb69eaf57bd0ab4bbd1bd92ba9aea9
/android/vendored/unversioned/@shopify/react-native-skia/cpp/skia/include/private/base/SkPathEnums.h
642bbb3489f7e41ae6d0e0d0e4de7bcd80a633e9
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
expo/expo
72fc802e3b6806789225bdd856031a8d150dd6f5
40f087fc0c0ab22270cfef2673bced44af170c34
refs/heads/main
2023-08-17T01:38:28.442098
2023-08-16T21:43:11
2023-08-16T21:43:11
65,750,241
23,742
5,421
MIT
2023-09-14T21:37:37
2016-08-15T17:14:25
TypeScript
UTF-8
C
false
false
505
h
SkPathEnums.h
/* * Copyright 2022 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. * * This file contains private enums related to paths. See also skbug.com/10670 */ #ifndef SkPathEnums_DEFINED #define SkPathEnums_DEFINED enum class SkPathConvexity { kConvex, kConcave, kUnknown, }; enum class SkPathFirstDirection { kCW, // == SkPathDirection::kCW kCCW, // == SkPathDirection::kCCW kUnknown, }; #endif
d373362711978ef53bf151fd10a3786ffdfaf61d
c0bfd93cd7f26a271268e504959256f1e02c6806
/components/esp8266/driver/i2c.c
1de5eb36a2ba18c5a6bd2e318aa63c8eefd41f47
[ "Apache-2.0" ]
permissive
espressif/ESP8266_RTOS_SDK
606f396e92d2675d9854f0fabd88587fbbbaf267
af0cdc36fa2600033d0a09301c754008cf1503c1
refs/heads/master
2023-08-24T22:40:15.373553
2023-05-06T02:04:24
2023-05-06T02:04:24
27,584,181
3,163
1,749
Apache-2.0
2023-08-09T10:48:13
2014-12-05T09:27:12
C
UTF-8
C
false
false
22,057
c
i2c.c
// Copyright 2018-2025 Espressif Systems (Shanghai) PTE LTD // // 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 <stdint.h> #include <stdlib.h> #include <string.h> #include "esp_err.h" #include "esp_log.h" #include "esp_heap_caps.h" #include "driver/i2c.h" #include "driver/gpio.h" // Temporary use the FreeRTOS critical function #include "FreeRTOS.h" #define ENTER_CRITICAL() portENTER_CRITICAL() #define EXIT_CRITICAL() portEXIT_CRITICAL() static const char *I2C_TAG = "i2c"; #define I2C_CHECK(a, str, ret) if(!(a)) { \ ESP_LOGE(I2C_TAG,"%s:%d (%s):%s", __FILE__, __LINE__, __FUNCTION__, str); \ return (ret); \ } #define I2C_DRIVER_ERR_STR "i2c driver install error" #define I2C_DRIVER_MALLOC_ERR_STR "i2c driver malloc error" #define I2C_NUM_ERROR_STR "i2c number error" #define I2C_TIMEING_VAL_ERR_STR "i2c timing value error" #define I2C_ADDR_ERROR_STR "i2c null address error" #define I2C_DRIVER_NOT_INSTALL_ERR_STR "i2c driver not installed" #define I2C_MASTER_MODE_ERR_STR "Only allowed in master mode" #define I2C_CMD_MALLOC_ERR_STR "i2c command link malloc error" #define I2C_TRANS_MODE_ERR_STR "i2c trans mode error" #define I2C_MODE_ERR_STR "i2c mode error" #define I2C_SDA_IO_ERR_STR "sda gpio number error" #define I2C_SCL_IO_ERR_STR "scl gpio number error" #define I2C_CMD_LINK_INIT_ERR_STR "i2c command link error" #define I2C_GPIO_PULLUP_ERR_STR "this i2c pin does not support internal pull-up" #define I2C_ACK_TYPE_ERR_STR "i2c ack type error" #define I2C_DATA_LEN_ERR_STR "i2c data read length error" #define I2C_IO_INIT_LEVEL (1) #define I2C_CMD_ALIVE_INTERVAL_TICK (1000 / portTICK_PERIOD_MS) #define I2C_ACKERR_CNT_MAX (10) #define i2c_master_wait os_delay_us typedef struct { uint8_t byte_num; /*!< cmd byte number */ struct { uint8_t en: 1; /*!< ack check enable */ uint8_t exp: 1; /*!< expected ack level to get */ uint8_t val: 1; /*!< ack value to send */ } ack; uint8_t *data; /*!< data address */ uint8_t byte_cmd; /*!< to save cmd for one byte command mode */ i2c_opmode_t op_code; /*!< cmd type */ } i2c_cmd_t; typedef struct i2c_cmd_link { i2c_cmd_t cmd; /*!< command in current cmd link */ struct i2c_cmd_link *next; /*!< next cmd link */ } i2c_cmd_link_t; typedef struct { i2c_cmd_link_t *head; /*!< head of the command link */ i2c_cmd_link_t *cur; /*!< last node of the command link */ i2c_cmd_link_t *free; /*!< the first node to free of the command link */ } i2c_cmd_desc_t; typedef enum { I2C_STATUS_READ, /*!< read status for current master command */ I2C_STATUS_WRITE, /*!< write status for current master command */ I2C_STATUS_IDLE, /*!< idle status for current master command */ I2C_STATUS_ACK_ERROR, /*!< ack error status for current master command */ I2C_STATUS_DONE, /*!< I2C command done */ I2C_STATUS_TIMEOUT, /*!< I2C bus status error, and operation timeout */ } i2c_status_t; typedef struct { i2c_port_t i2c_num; /*!< I2C port number */ i2c_mode_t mode; /*!< I2C mode, master */ int status; /*!< record current command status, for master mode */ i2c_cmd_desc_t cmd_link; /*!< I2C command link */ } i2c_obj_t; typedef union { struct { uint8_t scl: 1; uint8_t sda: 1; }; uint8_t val; } i2c_last_state_t; static i2c_obj_t *p_i2c_obj[I2C_NUM_MAX] = {0}; static i2c_config_t *i2c_config[I2C_NUM_MAX] = {NULL}; static i2c_last_state_t *i2c_last_state[I2C_NUM_MAX] = {NULL}; static inline void i2c_master_set_dc(i2c_port_t i2c_num, uint8_t sda, uint8_t scl) { uint32_t i = 0; uint32_t clk_stretch_tick = i2c_config[i2c_num]->clk_stretch_tick; gpio_set_level(i2c_config[i2c_num]->sda_io_num, sda & 0x1); gpio_set_level(i2c_config[i2c_num]->scl_io_num, scl & 0x1); if ((i2c_last_state[i2c_num]->scl == 0) && ((scl & 0x1) == 1)) { // An I2C slave is allowed to hold down the clock if it needs to reduce the bus speed. The master, on the other hand, is required to read back the clock signal after releasing it to the high state and wait until the line has actually gone high. while (gpio_get_level(i2c_config[i2c_num]->scl_io_num) == 0 && (i++) < clk_stretch_tick); // Clock stretching } i2c_last_state[i2c_num]->val = ((sda & 0x1) << 1) | (scl & 0x1); } static inline uint8_t i2c_master_get_dc(i2c_port_t i2c_num) { uint8_t sda_out; sda_out = gpio_get_level(i2c_config[i2c_num]->sda_io_num); return sda_out; } /* For i2c master mode, we don't need to use a buffer for the data, the APIs will execute the master commands and return after all of the commands have been sent out or when error occurs. So when we send master commands, we should free or modify the source data only after the i2c_master_cmd_begin function returns. */ esp_err_t i2c_driver_install(i2c_port_t i2c_num, i2c_mode_t mode) { I2C_CHECK((i2c_num >= 0) && (i2c_num < I2C_NUM_MAX), I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG); I2C_CHECK(mode < I2C_MODE_MAX, I2C_MODE_ERR_STR, ESP_ERR_INVALID_ARG); if (p_i2c_obj[i2c_num] == NULL) { p_i2c_obj[i2c_num] = (i2c_obj_t *) heap_caps_calloc(1, sizeof(i2c_obj_t), MALLOC_CAP_8BIT); if (p_i2c_obj[i2c_num] == NULL) { ESP_LOGE(I2C_TAG, I2C_DRIVER_MALLOC_ERR_STR); return ESP_FAIL; } i2c_obj_t *p_i2c = p_i2c_obj[i2c_num]; p_i2c->i2c_num = i2c_num; p_i2c->mode = mode; p_i2c->status = I2C_STATUS_IDLE; p_i2c->cmd_link.cur = NULL; p_i2c->cmd_link.head = NULL; p_i2c->cmd_link.free = NULL; } else { ESP_LOGE(I2C_TAG, I2C_DRIVER_ERR_STR); return ESP_FAIL; } if (i2c_config[i2c_num] == NULL) { i2c_config[i2c_num] = (i2c_config_t *) heap_caps_calloc(1, sizeof(i2c_config_t), MALLOC_CAP_8BIT); if (i2c_config[i2c_num] == NULL) { ESP_LOGE(I2C_TAG, I2C_DRIVER_MALLOC_ERR_STR); heap_caps_free(p_i2c_obj[i2c_num]); p_i2c_obj[i2c_num] = NULL; return ESP_FAIL; } memset(i2c_config[i2c_num], 0, sizeof(i2c_config_t)); } else { ESP_LOGE(I2C_TAG, I2C_DRIVER_ERR_STR); return ESP_FAIL; } if (i2c_last_state[i2c_num] == NULL) { i2c_last_state[i2c_num] = (i2c_last_state_t *) heap_caps_calloc(1, sizeof(i2c_last_state_t), MALLOC_CAP_8BIT); if (i2c_last_state[i2c_num] == NULL) { ESP_LOGE(I2C_TAG, I2C_DRIVER_MALLOC_ERR_STR); heap_caps_free(p_i2c_obj[i2c_num]); p_i2c_obj[i2c_num] = NULL; heap_caps_free(i2c_config[i2c_num]); i2c_config[i2c_num] = NULL; return ESP_FAIL; } memset(i2c_last_state[i2c_num], 0, sizeof(i2c_last_state_t)); } else { ESP_LOGE(I2C_TAG, I2C_DRIVER_ERR_STR); return ESP_FAIL; } return ESP_OK; } esp_err_t i2c_driver_delete(i2c_port_t i2c_num) { I2C_CHECK((i2c_num >= 0) && (i2c_num < I2C_NUM_MAX), I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG); I2C_CHECK(i2c_last_state[i2c_num] != NULL, I2C_DRIVER_ERR_STR, ESP_FAIL); I2C_CHECK(i2c_config[i2c_num] != NULL, I2C_DRIVER_ERR_STR, ESP_FAIL); I2C_CHECK(p_i2c_obj[i2c_num] != NULL, I2C_DRIVER_ERR_STR, ESP_FAIL); heap_caps_free(i2c_last_state[i2c_num]); i2c_last_state[i2c_num] = NULL; heap_caps_free(i2c_config[i2c_num]); i2c_config[i2c_num] = NULL; heap_caps_free(p_i2c_obj[i2c_num]); p_i2c_obj[i2c_num] = NULL; return ESP_OK; } esp_err_t i2c_set_pin(i2c_port_t i2c_num, int sda_io_num, int scl_io_num, gpio_pullup_t sda_pullup_en, gpio_pullup_t scl_pullup_en, i2c_mode_t mode) { I2C_CHECK((i2c_num >= 0) && (i2c_num < I2C_NUM_MAX), I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG); I2C_CHECK(mode < I2C_MODE_MAX, I2C_MODE_ERR_STR, ESP_ERR_INVALID_ARG); gpio_config_t io_conf; if (sda_io_num >= 0) { // disable interrupt io_conf.intr_type = GPIO_INTR_DISABLE; // set as output mode io_conf.mode = GPIO_MODE_OUTPUT_OD; // bit mask of the pins that you want to set io_conf.pin_bit_mask = (1ULL << sda_io_num); // disable pull-down mode io_conf.pull_down_en = 0; // disable pull-up mode io_conf.pull_up_en = sda_pullup_en; // configure GPIO with the given settings ESP_ERROR_CHECK(gpio_config(&io_conf)); ESP_ERROR_CHECK(gpio_set_level(sda_io_num, 1)); } if (scl_io_num >= 0) { // disable interrupt io_conf.intr_type = GPIO_INTR_DISABLE; // set as output mode io_conf.mode = GPIO_MODE_OUTPUT_OD; // bit mask of the pins that you want to set io_conf.pin_bit_mask = (1ULL << scl_io_num); // disable pull-down mode io_conf.pull_down_en = 0; // disable pull-up mode io_conf.pull_up_en = scl_pullup_en; // configure GPIO with the given settings ESP_ERROR_CHECK(gpio_config(&io_conf)); ESP_ERROR_CHECK(gpio_set_level(scl_io_num, 1)); } return ESP_OK; } esp_err_t i2c_param_config(i2c_port_t i2c_num, const i2c_config_t *i2c_conf) { I2C_CHECK((i2c_num >= 0) && (i2c_num < I2C_NUM_MAX), I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG); I2C_CHECK(i2c_conf != NULL, I2C_ADDR_ERROR_STR, ESP_ERR_INVALID_ARG); I2C_CHECK(i2c_conf->mode < I2C_MODE_MAX, I2C_MODE_ERR_STR, ESP_ERR_INVALID_ARG); esp_err_t ret = i2c_set_pin(i2c_num, i2c_conf->sda_io_num, i2c_conf->scl_io_num, i2c_conf->sda_pullup_en, i2c_conf->scl_pullup_en, i2c_conf->mode); if (ret != ESP_OK) { return ret; } memcpy((i2c_config_t *)(i2c_config[i2c_num]), (i2c_config_t *)i2c_conf, sizeof(i2c_config_t)); return ESP_OK; } i2c_cmd_handle_t i2c_cmd_link_create() { i2c_cmd_desc_t *cmd_desc = (i2c_cmd_desc_t *) heap_caps_calloc(1, sizeof(i2c_cmd_desc_t), MALLOC_CAP_8BIT); return (i2c_cmd_handle_t) cmd_desc; } void i2c_cmd_link_delete(i2c_cmd_handle_t cmd_handle) { if (cmd_handle == NULL) { return; } i2c_cmd_desc_t *cmd = (i2c_cmd_desc_t *) cmd_handle; while (cmd->free) { i2c_cmd_link_t *ptmp = cmd->free; cmd->free = cmd->free->next; heap_caps_free(ptmp); } cmd->cur = NULL; cmd->free = NULL; cmd->head = NULL; heap_caps_free(cmd_handle); return; } static esp_err_t i2c_cmd_link_append(i2c_cmd_handle_t cmd_handle, i2c_cmd_t *cmd) { i2c_cmd_desc_t *cmd_desc = (i2c_cmd_desc_t *) cmd_handle; if (cmd_desc->head == NULL) { cmd_desc->head = (i2c_cmd_link_t *) heap_caps_calloc(1, sizeof(i2c_cmd_link_t), MALLOC_CAP_8BIT); if (cmd_desc->head == NULL) { ESP_LOGE(I2C_TAG, I2C_CMD_MALLOC_ERR_STR); goto err; } cmd_desc->cur = cmd_desc->head; cmd_desc->free = cmd_desc->head; } else { cmd_desc->cur->next = (i2c_cmd_link_t *) heap_caps_calloc(1, sizeof(i2c_cmd_link_t), MALLOC_CAP_8BIT); if (cmd_desc->cur->next == NULL) { ESP_LOGE(I2C_TAG, I2C_CMD_MALLOC_ERR_STR); goto err; } cmd_desc->cur = cmd_desc->cur->next; } memcpy((uint8_t *) &cmd_desc->cur->cmd, (uint8_t *) cmd, sizeof(i2c_cmd_t)); cmd_desc->cur->next = NULL; return ESP_OK; err: return ESP_FAIL; } esp_err_t i2c_master_start(i2c_cmd_handle_t cmd_handle) { I2C_CHECK(cmd_handle != NULL, I2C_CMD_LINK_INIT_ERR_STR, ESP_ERR_INVALID_ARG); i2c_cmd_t cmd; cmd.ack.en = 0; cmd.ack.exp = 0; cmd.ack.val = 0; cmd.byte_num = 0; cmd.data = NULL; cmd.op_code = I2C_CMD_RESTART; return i2c_cmd_link_append(cmd_handle, &cmd); } esp_err_t i2c_master_stop(i2c_cmd_handle_t cmd_handle) { I2C_CHECK(cmd_handle != NULL, I2C_CMD_LINK_INIT_ERR_STR, ESP_ERR_INVALID_ARG); i2c_cmd_t cmd; cmd.ack.en = 0; cmd.ack.exp = 0; cmd.ack.val = 0; cmd.byte_num = 0; cmd.data = NULL; cmd.op_code = I2C_CMD_STOP; return i2c_cmd_link_append(cmd_handle, &cmd); } esp_err_t i2c_master_write_byte(i2c_cmd_handle_t cmd_handle, uint8_t data, bool ack_en) { I2C_CHECK(cmd_handle != NULL, I2C_CMD_LINK_INIT_ERR_STR, ESP_ERR_INVALID_ARG); i2c_cmd_t cmd; cmd.ack.en = ack_en; cmd.ack.exp = 0; cmd.ack.val = 0; cmd.byte_num = 1; cmd.op_code = I2C_CMD_WRITE; cmd.data = NULL; cmd.byte_cmd = data; return i2c_cmd_link_append(cmd_handle, &cmd); } esp_err_t i2c_master_write(i2c_cmd_handle_t cmd_handle, uint8_t *data, size_t data_len, bool ack_en) { I2C_CHECK((data != NULL), I2C_ADDR_ERROR_STR, ESP_ERR_INVALID_ARG); I2C_CHECK(cmd_handle != NULL, I2C_CMD_LINK_INIT_ERR_STR, ESP_ERR_INVALID_ARG); uint8_t len_tmp; int data_offset = 0; esp_err_t ret; while (data_len > 0) { len_tmp = data_len > 0xff ? 0xff : data_len; data_len -= len_tmp; i2c_cmd_t cmd; cmd.ack.en = ack_en; cmd.ack.exp = 0; cmd.ack.val = 0; cmd.byte_num = len_tmp; cmd.op_code = I2C_CMD_WRITE; cmd.data = data + data_offset; ret = i2c_cmd_link_append(cmd_handle, &cmd); data_offset += len_tmp; if (ret != ESP_OK) { return ret; } } return ESP_OK; } static esp_err_t i2c_master_read_static(i2c_cmd_handle_t cmd_handle, uint8_t *data, size_t data_len, i2c_ack_type_t ack) { int len_tmp; int data_offset = 0; esp_err_t ret; while (data_len > 0) { len_tmp = data_len > 0xff ? 0xff : data_len; data_len -= len_tmp; i2c_cmd_t cmd; cmd.ack.en = 0; cmd.ack.exp = 0; cmd.ack.val = ack & 0x1; cmd.byte_num = len_tmp; cmd.op_code = I2C_CMD_READ; cmd.data = data + data_offset; ret = i2c_cmd_link_append(cmd_handle, &cmd); data_offset += len_tmp; if (ret != ESP_OK) { return ret; } } return ESP_OK; } esp_err_t i2c_master_read_byte(i2c_cmd_handle_t cmd_handle, uint8_t *data, i2c_ack_type_t ack) { I2C_CHECK((data != NULL), I2C_ADDR_ERROR_STR, ESP_ERR_INVALID_ARG); I2C_CHECK(cmd_handle != NULL, I2C_CMD_LINK_INIT_ERR_STR, ESP_ERR_INVALID_ARG); I2C_CHECK(ack < I2C_MASTER_ACK_MAX, I2C_ACK_TYPE_ERR_STR, ESP_ERR_INVALID_ARG); i2c_cmd_t cmd; cmd.ack.en = 0; cmd.ack.exp = 0; cmd.ack.val = ((ack == I2C_MASTER_LAST_NACK) ? I2C_MASTER_NACK : (ack & 0x1)); cmd.byte_num = 1; cmd.op_code = I2C_CMD_READ; cmd.data = data; return i2c_cmd_link_append(cmd_handle, &cmd); } esp_err_t i2c_master_read(i2c_cmd_handle_t cmd_handle, uint8_t *data, size_t data_len, i2c_ack_type_t ack) { I2C_CHECK((data != NULL), I2C_ADDR_ERROR_STR, ESP_ERR_INVALID_ARG); I2C_CHECK(cmd_handle != NULL, I2C_CMD_LINK_INIT_ERR_STR, ESP_ERR_INVALID_ARG); I2C_CHECK(ack < I2C_MASTER_ACK_MAX, I2C_ACK_TYPE_ERR_STR, ESP_ERR_INVALID_ARG); I2C_CHECK(data_len > 0, I2C_DATA_LEN_ERR_STR, ESP_ERR_INVALID_ARG); if (ack != I2C_MASTER_LAST_NACK) { return i2c_master_read_static(cmd_handle, data, data_len, ack); } else { if (data_len == 1) { return i2c_master_read_byte(cmd_handle, data, I2C_MASTER_NACK); } else { esp_err_t ret; // first read (data_len - 1) byte data with ACK,than read the end byte with NACK. if ((ret = i2c_master_read_static(cmd_handle, data, data_len - 1, I2C_MASTER_ACK)) != ESP_OK) { return ret; } return i2c_master_read_byte(cmd_handle, data + data_len - 1, I2C_MASTER_NACK); } } } static void i2c_master_cmd_begin_static(i2c_port_t i2c_num) { i2c_obj_t *p_i2c = p_i2c_obj[i2c_num]; i2c_cmd_t *cmd; uint8_t dat; uint8_t len; int8_t i, k; uint8_t retVal; // This should never happen if (p_i2c->mode != I2C_MODE_MASTER) { return; } while (p_i2c->cmd_link.head) { cmd = &p_i2c->cmd_link.head->cmd; switch (cmd->op_code) { case (I2C_CMD_RESTART): { i2c_master_set_dc(i2c_num, 1, i2c_last_state[i2c_num]->scl); i2c_master_set_dc(i2c_num, 1, 1); i2c_master_wait(1); // sda 1, scl 1 i2c_master_set_dc(i2c_num, 0, 1); i2c_master_wait(1); // sda 0, scl 1 } break; case (I2C_CMD_WRITE): { p_i2c->status = I2C_STATUS_WRITE; for (len = 0; len < cmd->byte_num; len++) { dat = 0; retVal = 0; i2c_master_set_dc(i2c_num, i2c_last_state[i2c_num]->sda, 0); for (i = 7; i >= 0; i--) { if (cmd->byte_num == 1 && cmd->data == NULL) { dat = (cmd->byte_cmd) >> i; } else { dat = ((uint8_t) * (cmd->data + len)) >> i; } i2c_master_set_dc(i2c_num, dat, 0); i2c_master_wait(1); i2c_master_set_dc(i2c_num, dat, 1); i2c_master_wait(2); if (i == 0) { i2c_master_wait(1); // wait slaver ack } i2c_master_set_dc(i2c_num, dat, 0); } i2c_master_set_dc(i2c_num, i2c_last_state[i2c_num]->sda, 0); i2c_master_set_dc(i2c_num, 1, 0); i2c_master_set_dc(i2c_num, 1, 1); i2c_master_wait(1); retVal = i2c_master_get_dc(i2c_num); i2c_master_wait(1); i2c_master_set_dc(i2c_num, 1, 0); if (cmd->ack.en == 1) { if ((retVal & 0x01) != cmd->ack.exp) { p_i2c->status = I2C_STATUS_ACK_ERROR; return ; } } } } break; case (I2C_CMD_READ): { p_i2c->status = I2C_STATUS_READ; for (len = 0; len < cmd->byte_num; len++) { retVal = 0; i2c_master_set_dc(i2c_num, i2c_last_state[i2c_num]->sda, 0); for (i = 0; i < 8; i++) { i2c_master_set_dc(i2c_num, 1, 0); i2c_master_wait(2); i2c_master_set_dc(i2c_num, 1, 1); i2c_master_wait(1); // sda 1, scl 1 k = i2c_master_get_dc(i2c_num); i2c_master_wait(1); if (i == 7) { i2c_master_wait(1); } k <<= (7 - i); retVal |= k; } i2c_master_set_dc(i2c_num, 1, 0); memcpy((uint8_t *)(cmd->data + len), (uint8_t *)&retVal, 1); i2c_master_set_dc(i2c_num, i2c_last_state[i2c_num]->sda, 0); i2c_master_set_dc(i2c_num, cmd->ack.val, 0); i2c_master_set_dc(i2c_num, cmd->ack.val, 1); i2c_master_wait(4); // sda level, scl 1 i2c_master_set_dc(i2c_num, cmd->ack.val, 0); i2c_master_set_dc(i2c_num, 1, 0); i2c_master_wait(1); } } break; case (I2C_CMD_STOP): { i2c_master_wait(1); i2c_master_set_dc(i2c_num, 0, i2c_last_state[i2c_num]->scl); i2c_master_set_dc(i2c_num, 0, 1); i2c_master_wait(2); // sda 0, scl 1 i2c_master_set_dc(i2c_num, 1, 1); i2c_master_wait(2); // sda 1, scl 1 } break; } p_i2c->cmd_link.head = p_i2c->cmd_link.head->next; } p_i2c->status = I2C_STATUS_DONE; return; } esp_err_t i2c_master_cmd_begin(i2c_port_t i2c_num, i2c_cmd_handle_t cmd_handle, TickType_t ticks_to_wait) { I2C_CHECK((i2c_num >= 0) && (i2c_num < I2C_NUM_MAX), I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG); I2C_CHECK(p_i2c_obj[i2c_num] != NULL, I2C_DRIVER_NOT_INSTALL_ERR_STR, ESP_ERR_INVALID_STATE); I2C_CHECK(p_i2c_obj[i2c_num]->mode == I2C_MODE_MASTER, I2C_MASTER_MODE_ERR_STR, ESP_ERR_INVALID_STATE); I2C_CHECK(cmd_handle != NULL, I2C_CMD_LINK_INIT_ERR_STR, ESP_ERR_INVALID_ARG); i2c_obj_t *p_i2c = p_i2c_obj[i2c_num]; i2c_cmd_desc_t *cmd = (i2c_cmd_desc_t *) cmd_handle; p_i2c->cmd_link.free = cmd->free; p_i2c->cmd_link.cur = cmd->cur; p_i2c->cmd_link.head = cmd->head; p_i2c->status = I2C_STATUS_IDLE; ENTER_CRITICAL(); // start send commands, at most 32 bytes one time, isr handler will process the remaining commands. i2c_master_cmd_begin_static(i2c_num); EXIT_CRITICAL(); // TODO: Timeout check if (p_i2c->status == I2C_STATUS_DONE) { return ESP_OK; } else { return ESP_FAIL; } }
89d715e773d9206fa5cac1d8114b19624df4d7bc
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/sound/drivers/virmidi.c
cc4be88d73184a6e538a4eb961c3f47c182abdd0
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
5,718
c
virmidi.c
/* * Dummy soundcard for virtual rawmidi devices * * Copyright (c) 2000 by Takashi Iwai <tiwai@suse.de> * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* * VIRTUAL RAW MIDI DEVICE CARDS * * This dummy card contains up to 4 virtual rawmidi devices. * They are not real rawmidi devices but just associated with sequencer * clients, so that any input/output sources can be connected as a raw * MIDI device arbitrary. * Also, multiple access is allowed to a single rawmidi device. * * Typical usage is like following: * - Load snd-virmidi module. * # modprobe snd-virmidi index=2 * Then, sequencer clients 72:0 to 75:0 will be created, which are * mapped from /dev/snd/midiC1D0 to /dev/snd/midiC1D3, respectively. * * - Connect input/output via aconnect. * % aconnect 64:0 72:0 # keyboard input redirection 64:0 -> 72:0 * % aconnect 72:0 65:0 # output device redirection 72:0 -> 65:0 * * - Run application using a midi device (eg. /dev/snd/midiC1D0) */ #include <linux/init.h> #include <linux/wait.h> #include <linux/err.h> #include <linux/platform_device.h> #include <linux/module.h> #include <sound/core.h> #include <sound/seq_kernel.h> #include <sound/seq_virmidi.h> #include <sound/initval.h> /* hack: OSS defines midi_devs, so undefine it (versioned symbols) */ #undef midi_devs MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>"); MODULE_DESCRIPTION("Dummy soundcard for virtual rawmidi devices"); MODULE_LICENSE("GPL"); MODULE_SUPPORTED_DEVICE("{{ALSA,Virtual rawmidi device}}"); #define MAX_MIDI_DEVICES 4 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */ static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */ static bool enable[SNDRV_CARDS] = {1, [1 ... (SNDRV_CARDS - 1)] = 0}; static int midi_devs[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 4}; module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for virmidi soundcard."); module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for virmidi soundcard."); module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable this soundcard."); module_param_array(midi_devs, int, NULL, 0444); MODULE_PARM_DESC(midi_devs, "MIDI devices # (1-4)"); struct snd_card_virmidi { struct snd_card *card; struct snd_rawmidi *midi[MAX_MIDI_DEVICES]; }; static struct platform_device *devices[SNDRV_CARDS]; static int snd_virmidi_probe(struct platform_device *devptr) { struct snd_card *card; struct snd_card_virmidi *vmidi; int idx, err; int dev = devptr->id; err = snd_card_create(index[dev], id[dev], THIS_MODULE, sizeof(struct snd_card_virmidi), &card); if (err < 0) return err; vmidi = card->private_data; vmidi->card = card; if (midi_devs[dev] > MAX_MIDI_DEVICES) { snd_printk(KERN_WARNING "too much midi devices for virmidi %d: " "force to use %d\n", dev, MAX_MIDI_DEVICES); midi_devs[dev] = MAX_MIDI_DEVICES; } for (idx = 0; idx < midi_devs[dev]; idx++) { struct snd_rawmidi *rmidi; struct snd_virmidi_dev *rdev; if ((err = snd_virmidi_new(card, idx, &rmidi)) < 0) goto __nodev; rdev = rmidi->private_data; vmidi->midi[idx] = rmidi; strcpy(rmidi->name, "Virtual Raw MIDI"); rdev->seq_mode = SNDRV_VIRMIDI_SEQ_DISPATCH; } strcpy(card->driver, "VirMIDI"); strcpy(card->shortname, "VirMIDI"); sprintf(card->longname, "Virtual MIDI Card %i", dev + 1); snd_card_set_dev(card, &devptr->dev); if ((err = snd_card_register(card)) == 0) { platform_set_drvdata(devptr, card); return 0; } __nodev: snd_card_free(card); return err; } static int snd_virmidi_remove(struct platform_device *devptr) { snd_card_free(platform_get_drvdata(devptr)); platform_set_drvdata(devptr, NULL); return 0; } #define SND_VIRMIDI_DRIVER "snd_virmidi" static struct platform_driver snd_virmidi_driver = { .probe = snd_virmidi_probe, .remove = snd_virmidi_remove, .driver = { .name = SND_VIRMIDI_DRIVER, .owner = THIS_MODULE, }, }; static void snd_virmidi_unregister_all(void) { int i; for (i = 0; i < ARRAY_SIZE(devices); ++i) platform_device_unregister(devices[i]); platform_driver_unregister(&snd_virmidi_driver); } static int __init alsa_card_virmidi_init(void) { int i, cards, err; if ((err = platform_driver_register(&snd_virmidi_driver)) < 0) return err; cards = 0; for (i = 0; i < SNDRV_CARDS; i++) { struct platform_device *device; if (! enable[i]) continue; device = platform_device_register_simple(SND_VIRMIDI_DRIVER, i, NULL, 0); if (IS_ERR(device)) continue; if (!platform_get_drvdata(device)) { platform_device_unregister(device); continue; } devices[i] = device; cards++; } if (!cards) { #ifdef MODULE printk(KERN_ERR "Card-VirMIDI soundcard not found or device busy\n"); #endif snd_virmidi_unregister_all(); return -ENODEV; } return 0; } static void __exit alsa_card_virmidi_exit(void) { snd_virmidi_unregister_all(); } module_init(alsa_card_virmidi_init) module_exit(alsa_card_virmidi_exit)
7bb15deaf2f7881628301b52ebc47a44047232f0
de21f9075f55640514c29ef0f1fe3f0690845764
/regression/goto-instrument/nondet-volatile-model-01/test.c
ad937de7b1ca9851b71d7c2ef050c0549d08298f
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-4-Clause" ]
permissive
diffblue/cbmc
975a074ac445febb3b5715f8792beb545522dc18
decd2839c2f51a54b2ad0f3e89fdc1b4bf78cd16
refs/heads/develop
2023-08-31T05:52:05.342195
2023-08-30T13:31:51
2023-08-30T13:31:51
51,877,056
589
309
NOASSERTION
2023-09-14T18:49:17
2016-02-16T23:03:52
C++
UTF-8
C
false
false
221
c
test.c
#include <assert.h> volatile int a; volatile int b; int model() { int value; __CPROVER_assume(value >= 0); return value; } void main() { assert(a == 0); assert(b >= 0); assert(b == 0); assert(b != 0); }
468b038fb579dbf134b9108330ca8611c0c50a71
c932ace996f06f96e8b07fdbf4a688d1c8292909
/pam/pam.h
3cb609a8cea475ebd1e6761ee1169b3aa5e87c3a
[ "Apache-2.0" ]
permissive
google/fscrypt
6f6bcd9c6a6ac2ff0d89133b8a3800a85ebb3f87
f91f8e4fcb59d6db80e5150530a65fe39a836eb2
refs/heads/master
2023-08-16T14:36:44.255324
2023-01-31T06:59:20
2023-01-31T06:59:20
97,037,205
828
118
Apache-2.0
2023-09-09T23:01:15
2017-07-12T17:52:15
Go
UTF-8
C
false
false
1,691
h
pam.h
/* * pam.h - Functions to let us call into libpam from Go. * * Copyright 2017 Google Inc. * Author: Joe Richey (joerichey@google.com) * * 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. */ #ifndef FSCRYPT_PAM_H #define FSCRYPT_PAM_H #include <security/pam_appl.h> // Conversation that will call back into Go code when appropriate. extern const struct pam_conv *goConv; // CleaupFuncs are used to cleanup specific PAM data. typedef void (*CleanupFunc)(pam_handle_t *pamh, void *data, int error_status); // CleaupFunc that calls free() on data. void freeData(pam_handle_t *pamh, void *data, int error_status); // CleaupFunc that frees each item in a null terminated array of pointers and // then frees the array itself. void freeArray(pam_handle_t *pamh, void **array, int error_status); // Creates a copy of a C string, which resides in a locked buffer. void *copyIntoSecret(void *data); // CleaupFunc that Zeros wipes a C string and unlocks and frees its memory. void freeSecret(pam_handle_t *pamh, char *data, int error_status); // Sends a message to the application using pam_info(). void infoMessage(pam_handle_t *pamh, const char *message); #endif // FSCRYPT_PAM_H
3802cbb88fc422adfe40810a91509529274d1917
83372fce92c9088ee5c1e1c13bc67385a3b02a36
/test/val/lib_common_strncat.c
54cf0e3e515f2df65ea05346fb40a05dec8d2390
[ "Zlib", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
permissive
cc65/cc65
2cd1b20b61ddd0691cd4601b4da37a9200a50afb
16e90187e8e80c6e2fcfcc04f068ac865d2290e5
refs/heads/master
2023-09-03T17:16:46.027934
2023-09-02T22:30:44
2023-09-02T22:30:44
8,932,489
2,103
526
Zlib
2023-09-13T06:19:01
2013-03-21T15:56:48
C
UTF-8
C
false
false
1,727
c
lib_common_strncat.c
#include <string.h> #include "unittest.h" #define SourceStringSize 384 // test correct page passing (>256, multiple of 128 here) static char SourceString[SourceStringSize+1]; // +1 room for terminating null static char DestinationString[2*SourceStringSize+1]; // will contain two times the source buffer TEST { unsigned i; char* p; for (i=0; i < SourceStringSize; ++i) SourceString[i] = (i%128)+1; SourceString[i] = 0; ASSERT_AreEqual(SourceStringSize, strlen(SourceString), "%u", "Source string initialization or 'strlen()' problem!"); /* Ensure empty destination string */ DestinationString[0] = 0; ASSERT_AreEqual(0, strlen(DestinationString), "%u", "Destination string initialization or 'strlen()' problem!"); /* Test "unlimted" concatenation to empty buffer */ strncat(DestinationString, SourceString, 1024); ASSERT_AreEqual(SourceStringSize, strlen(DestinationString), "%u", "Unexpected string length while string concatenation to empty buffer!"); /* Test limited concatenation to non empty buffer */ p = strncat(DestinationString, SourceString, 128); ASSERT_AreEqual(SourceStringSize+128, strlen(DestinationString), "%u", "Unexpected string length while string concatenation to non-empty buffer!"); /* Test return value */ ASSERT_IsTrue(p == DestinationString, "Invalid return value!"); /* Test contents */ for(i=0; i < strlen(DestinationString); ++i) { unsigned current = DestinationString[i]; unsigned expected = (i%128)+1; ASSERT_AreEqual(expected, current, "%u", "Unexpected destination buffer contents at position %u!\n" COMMA i); } } ENDTEST
1db014dd92a38d81d78d9e82897c2c696385493e
984bc4181baec6e5a4b05a657e666b0e9f89f3f3
/3rdparty/mongo-c-driver-1.21.2/src/libbson/examples/hello_bson.c
5bb1ea54913b58c8c0006c098a6966baffaed904
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
treefrogframework/treefrog-framework
0173245ff92162d2107af79861505981980d1eca
a1df97793e8cc628779378e5adae9af6987460c1
refs/heads/master
2023-08-22T03:57:58.891846
2023-05-18T14:00:42
2023-05-18T14:00:42
7,067,532
1,152
263
BSD-3-Clause
2023-08-08T20:25:03
2012-12-08T13:17:01
C++
UTF-8
C
false
false
911
c
hello_bson.c
/* Copyright 2017 MongoDB Inc. * * 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. */ /* -- sphinx-include-start -- */ #include <stdio.h> #include <bson/bson.h> int main (int argc, const char **argv) { bson_t *b; char *j; b = BCON_NEW ("hello", BCON_UTF8 ("bson!")); j = bson_as_canonical_extended_json (b, NULL); printf ("%s\n", j); bson_free (j); bson_destroy (b); return 0; }
051a68e9a75d8ca9ed28d18871451ffaa4c86a83
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
/PWGHF/vertexingHF/macros/AddTaskCharmDecayTracks.C
cf7a9b914cec55bc27a6197e8bb7c489a30e8729
[]
permissive
alisw/AliPhysics
91bf1bd01ab2af656a25ff10b25e618a63667d3e
5df28b2b415e78e81273b0d9bf5c1b99feda3348
refs/heads/master
2023-08-31T20:41:44.927176
2023-08-31T14:51:12
2023-08-31T14:51:12
61,661,378
129
1,150
BSD-3-Clause
2023-09-14T18:48:45
2016-06-21T19:31:29
C++
UTF-8
C
false
false
2,467
c
AddTaskCharmDecayTracks.C
AliAnalysisTaskCharmDecayTracks* AddTaskCharmDecayTracks(Int_t pdgCode=421, Bool_t decayV0bachelor=kFALSE, TString optMeth="kine", Int_t filterMask = 16){ AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskCharmDecayTracks", "No analysis manager to connect to."); } AliAnalysisTaskCharmDecayTracks *dTask = new AliAnalysisTaskCharmDecayTracks(); dTask->SetReadMC(kTRUE); dTask->SetFilterMask(filterMask); dTask->SetSelectedHadron(pdgCode); optMeth.ToLower(); if(optMeth.Contains("cand") || optMeth.Contains("delta")) dTask->SetUseCandidatesFromDeltaAOD(); else dTask->SetUseCharmedHadronsFromKine(); if(pdgCode==4122 && decayV0bachelor) dTask->SelectLcpK0s(); // Create containers for input/output TString baseName="CharmDecayTracks"; baseName.Append(Form("_%s",optMeth.Data())); TString containerStr=""; if(pdgCode==421) containerStr="Dzero"; else if(pdgCode==411) containerStr="Dplus"; else if(pdgCode==431) containerStr="Ds"; else if(pdgCode==4122 && !decayV0bachelor) containerStr="LcpKpi"; else if(pdgCode==4122 && decayV0bachelor) containerStr="LcpK0s"; TString inname = Form("cinput%s%s",baseName.Data(),containerStr.Data()); TString outname = Form("coutput%s%s",baseName.Data(),containerStr.Data()); TString treename = Form("coutput%sTree%s",baseName.Data(),containerStr.Data()); AliAnalysisDataContainer *cinput = mgr->CreateContainer(inname,TChain::Class(), AliAnalysisManager::kInputContainer); TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += Form(":%s%s",baseName.Data(),containerStr.Data()); AliAnalysisDataContainer *coutput = mgr->CreateContainer(outname,TList::Class(), AliAnalysisManager::kOutputContainer, outputfile.Data()); AliAnalysisDataContainer *coutputTree = mgr->CreateContainer(treename,TTree::Class(), AliAnalysisManager::kOutputContainer, outputfile.Data()); coutputTree->SetSpecialOutput(); mgr->ConnectInput(dTask,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(dTask,1,coutput); mgr->ConnectOutput(dTask,2,coutputTree); return dTask; }
b0b1b8fdab42d0370772490f76c6fd2d2ff6adc4
35ece1a78314060ee6f815745db24f85012a6c77
/texlive/texk/xdvik/dvi.h
392712138fa788376c2b2ea8a0d0b1a939a6bfdc
[ "LicenseRef-scancode-other-permissive" ]
permissive
clerkma/ptex-ng
dabc12a3df48aef6107efd1b4555f0141f858e12
a646d1cfe835712601b7edcfa96ad90c2549778b
refs/heads/master
2023-08-16T23:10:11.143532
2023-08-13T06:52:31
2023-08-13T06:52:31
24,095,177
260
46
null
2022-06-22T04:57:30
2014-09-16T10:25:01
C
UTF-8
C
false
false
1,140
h
dvi.h
/* * Mnemonics for bytes in dvi file. */ #define SETCHAR0 0 #define SET1 128 #define SET2 129 #define SETRULE 132 #define PUT1 133 #define PUT2 134 #define PUTRULE 137 #define NOP 138 #define BOP 139 #define EOP 140 #define PUSH 141 #define POP 142 #define RIGHT1 143 #define RIGHT2 144 #define RIGHT3 145 #define RIGHT4 146 #define W0 147 #define W1 148 #define W2 149 #define W3 150 #define W4 151 #define X0 152 #define X1 153 #define X2 154 #define X3 155 #define X4 156 #define DOWN1 157 #define DOWN2 158 #define DOWN3 159 #define DOWN4 160 #define Y0 161 #define Y1 162 #define Y2 163 #define Y3 164 #define Y4 165 #define Z0 166 #define Z1 167 #define Z2 168 #define Z3 169 #define Z4 170 #define FNTNUM0 171 #define FNT1 235 #define FNT2 236 #define FNT3 237 #define FNT4 238 #define XXX1 239 #define XXX2 240 #define XXX3 241 #define XXX4 242 #define FNTDEF1 243 #define FNTDEF2 244 #define FNTDEF3 245 #define FNTDEF4 246 #define PRE 247 #define POST 248 #define POSTPOST 249 #define SREFL 250 #define EREFL 251 #define TRAILER 223 /* Trailing bytes at end of file */
3a27b62351010255f570d559dd2d23561153b1a1
6cbc9ef86318b4cfcbe32fc27dc997eea5d0ae94
/cii/src/except.c
1cd2c61fbbd56d5e95fa3a0005fa48fc4b4b28b8
[ "MIT", "BSD-2-Clause" ]
permissive
sasagawa888/eisl
c60c8307cf4ba1be20be15a4d59005f04b2b348e
450e09dbb59139621981f1104eefcad19957de2a
refs/heads/master
2023-09-03T17:48:38.297684
2023-09-02T05:42:40
2023-09-02T05:42:40
168,798,493
200
25
NOASSERTION
2023-06-17T21:16:28
2019-02-02T05:35:38
Common Lisp
UTF-8
C
false
false
1,550
c
except.c
static char rcsid[] = "$Id$" "\n$Id$"; #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include "assert.h" #include "except.h" #define T Except_T Except_Frame *Except_stack = NULL; void Except_raise(const T *e, const char *file, int line) { #ifdef WIN32 Except_Frame *p; if (Except_index == -1) Except_init(); p = TlsGetValue(Except_index); #else Except_Frame *p = Except_stack; #endif assert(e); if (p == NULL) { fprintf(stderr, "Uncaught exception"); if (e->reason) fprintf(stderr, " %s", e->reason); else fprintf(stderr, " at 0x%p", e); if (file && line > 0) fprintf(stderr, " raised at %s:%d\n", file, line); fprintf(stderr, "aborting...\n"); fflush(stderr); abort(); } p->exception = e; p->file = file; p->line = line; #ifdef WIN32 Except_pop(); #else Except_stack = Except_stack->prev; #endif longjmp(p->env, Except_raised); } #ifdef WIN32 _CRTIMP void __cdecl _assert(void *, void *, unsigned); #undef assert #define assert(e) ((e) || (_assert(#e, __FILE__, __LINE__), 0)) int Except_index = -1; void Except_init(void) { BOOL cond; Except_index = TlsAlloc(); assert(Except_index != TLS_OUT_OF_INDEXES); cond = TlsSetValue(Except_index, NULL); assert(cond == TRUE); } void Except_push(Except_Frame *fp) { BOOL cond; fp->prev = TlsGetValue(Except_index); cond = TlsSetValue(Except_index, fp); assert(cond == TRUE); } void Except_pop(void) { BOOL cond; Except_Frame *tos = TlsGetValue(Except_index); cond = TlsSetValue(Except_index, tos->prev); assert(cond == TRUE); } #endif
6efd3e7d6b187bec6a5295f04ec029e8d0c5b4d3
05a4d2bf45b32798d2f6820c4ec001dd8ef13e4a
/tests/unit/ep/ep-common.h
6baa5d3456c3d6314e994cea57aa52986bc56394
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
pmem/rpma
207ee08f465a22341f92c80b15132a9617e57596
93d31224fd69786d4b1ace0084108aa270e4c263
refs/heads/main
2023-09-01T05:29:34.609582
2023-06-13T12:12:10
2023-06-13T12:12:10
240,216,867
115
63
NOASSERTION
2023-09-05T14:31:33
2020-02-13T08:59:31
C
UTF-8
C
false
false
945
h
ep-common.h
/* SPDX-License-Identifier: BSD-3-Clause */ /* Copyright 2020, Intel Corporation */ /* * ep-common.h -- header of the common part of the endpoint unit tests */ #ifndef EP_COMMON_H #define EP_COMMON_H 1 #include <rdma/rdma_cma.h> #define MOCK_CONN_REQ (struct rpma_conn_req *)0xCFEF #define MOCK_FD 0x00FD /* mock control entities */ #define MOCK_CTRL_DEFER 1 #define MOCK_CTRL_NO_DEFER 0 extern const struct rdma_cm_id Cmid_zero; extern const struct rdma_event_channel Evch_zero; extern int Mock_ctrl_defer_destruction; int setup__ep_listen(void **estate_ptr); int teardown__ep_shutdown(void **estate_ptr); /* * All the resources used between setup__ep_listen and teardown__ep_shutdown. */ struct ep_test_state { struct rdma_event_channel evch; struct rdma_cm_id cmid; struct rpma_ep *ep; struct rpma_conn_cfg *cfg; }; void prestate_init(struct ep_test_state *prestate, struct rpma_conn_cfg *cfg); #endif /* EP_COMMON_H */
18130c896329cc0a1e3edc9cd0370d02cd2de4cd
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/sh/boards/mach-sh03/rtc.c
f83ac7995d0ff88e1bfecc017c538e93427e2deb
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
3,987
c
rtc.c
/* * linux/arch/sh/boards/sh03/rtc.c -- CTP/PCI-SH03 on-chip RTC support * * Copyright (C) 2004 Saito.K & Jeanne(ksaito@interface.co.jp) * */ #include <linux/init.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/time.h> #include <linux/bcd.h> #include <linux/rtc.h> #include <linux/spinlock.h> #include <asm/io.h> #include <asm/rtc.h> #define RTC_BASE 0xb0000000 #define RTC_SEC1 (RTC_BASE + 0) #define RTC_SEC10 (RTC_BASE + 1) #define RTC_MIN1 (RTC_BASE + 2) #define RTC_MIN10 (RTC_BASE + 3) #define RTC_HOU1 (RTC_BASE + 4) #define RTC_HOU10 (RTC_BASE + 5) #define RTC_WEE1 (RTC_BASE + 6) #define RTC_DAY1 (RTC_BASE + 7) #define RTC_DAY10 (RTC_BASE + 8) #define RTC_MON1 (RTC_BASE + 9) #define RTC_MON10 (RTC_BASE + 10) #define RTC_YEA1 (RTC_BASE + 11) #define RTC_YEA10 (RTC_BASE + 12) #define RTC_YEA100 (RTC_BASE + 13) #define RTC_YEA1000 (RTC_BASE + 14) #define RTC_CTL (RTC_BASE + 15) #define RTC_BUSY 1 #define RTC_STOP 2 static DEFINE_SPINLOCK(sh03_rtc_lock); unsigned long get_cmos_time(void) { unsigned int year, mon, day, hour, min, sec; spin_lock(&sh03_rtc_lock); again: do { sec = (__raw_readb(RTC_SEC1) & 0xf) + (__raw_readb(RTC_SEC10) & 0x7) * 10; min = (__raw_readb(RTC_MIN1) & 0xf) + (__raw_readb(RTC_MIN10) & 0xf) * 10; hour = (__raw_readb(RTC_HOU1) & 0xf) + (__raw_readb(RTC_HOU10) & 0xf) * 10; day = (__raw_readb(RTC_DAY1) & 0xf) + (__raw_readb(RTC_DAY10) & 0xf) * 10; mon = (__raw_readb(RTC_MON1) & 0xf) + (__raw_readb(RTC_MON10) & 0xf) * 10; year = (__raw_readb(RTC_YEA1) & 0xf) + (__raw_readb(RTC_YEA10) & 0xf) * 10 + (__raw_readb(RTC_YEA100 ) & 0xf) * 100 + (__raw_readb(RTC_YEA1000) & 0xf) * 1000; } while (sec != (__raw_readb(RTC_SEC1) & 0xf) + (__raw_readb(RTC_SEC10) & 0x7) * 10); if (year == 0 || mon < 1 || mon > 12 || day > 31 || day < 1 || hour > 23 || min > 59 || sec > 59) { printk(KERN_ERR "SH-03 RTC: invalid value, resetting to 1 Jan 2000\n"); printk("year=%d, mon=%d, day=%d, hour=%d, min=%d, sec=%d\n", year, mon, day, hour, min, sec); __raw_writeb(0, RTC_SEC1); __raw_writeb(0, RTC_SEC10); __raw_writeb(0, RTC_MIN1); __raw_writeb(0, RTC_MIN10); __raw_writeb(0, RTC_HOU1); __raw_writeb(0, RTC_HOU10); __raw_writeb(6, RTC_WEE1); __raw_writeb(1, RTC_DAY1); __raw_writeb(0, RTC_DAY10); __raw_writeb(1, RTC_MON1); __raw_writeb(0, RTC_MON10); __raw_writeb(0, RTC_YEA1); __raw_writeb(0, RTC_YEA10); __raw_writeb(0, RTC_YEA100); __raw_writeb(2, RTC_YEA1000); __raw_writeb(0, RTC_CTL); goto again; } spin_unlock(&sh03_rtc_lock); return mktime(year, mon, day, hour, min, sec); } void sh03_rtc_gettimeofday(struct timespec *tv) { tv->tv_sec = get_cmos_time(); tv->tv_nsec = 0; } static int set_rtc_mmss(unsigned long nowtime) { int retval = 0; int real_seconds, real_minutes, cmos_minutes; int i; /* gets recalled with irq locally disabled */ spin_lock(&sh03_rtc_lock); for (i = 0 ; i < 1000000 ; i++) /* may take up to 1 second... */ if (!(__raw_readb(RTC_CTL) & RTC_BUSY)) break; cmos_minutes = (__raw_readb(RTC_MIN1) & 0xf) + (__raw_readb(RTC_MIN10) & 0xf) * 10; real_seconds = nowtime % 60; real_minutes = nowtime / 60; if (((abs(real_minutes - cmos_minutes) + 15)/30) & 1) real_minutes += 30; /* correct for half hour time zone */ real_minutes %= 60; if (abs(real_minutes - cmos_minutes) < 30) { __raw_writeb(real_seconds % 10, RTC_SEC1); __raw_writeb(real_seconds / 10, RTC_SEC10); __raw_writeb(real_minutes % 10, RTC_MIN1); __raw_writeb(real_minutes / 10, RTC_MIN10); } else { printk_once(KERN_NOTICE "set_rtc_mmss: can't update from %d to %d\n", cmos_minutes, real_minutes); retval = -1; } spin_unlock(&sh03_rtc_lock); return retval; } int sh03_rtc_settimeofday(const time_t secs) { unsigned long nowtime = secs; return set_rtc_mmss(nowtime); } void sh03_time_init(void) { rtc_sh_get_time = sh03_rtc_gettimeofday; rtc_sh_set_time = sh03_rtc_settimeofday; }
c4480d230c6a3ee5f4cd9beaa0251464429208c3
0cc06b1b769f1eb39b198b70338ec84359eedfdc
/pasa-plugins/seqclean/mdust/fastafile.c
8879e16783daf294e0483c4f25bfdce0a0b5a603
[ "LicenseRef-scancode-unknown-license-reference", "Artistic-1.0" ]
permissive
PASApipeline/PASApipeline
0d113fcd8f6a0ab20395ebd777f0eb3438fd57c6
d5fdc30ddcfe08950faf91cbb68d0451cd0bf3a9
refs/heads/master
2023-08-07T22:54:34.047102
2023-06-01T13:41:18
2023-06-01T13:41:18
30,616,207
155
77
NOASSERTION
2023-01-05T20:02:46
2015-02-10T21:44:46
Perl
UTF-8
C
false
false
5,030
c
fastafile.c
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include "fastafile.h" #define TMPNAME "tmp.seg" void myabort(char* mess) { fprintf(stderr, "Error: %s.\n", mess); exit(1); } void *mymalloc(int size) { void *buf; if ((buf = malloc(size)) == NULL) { myabort("Not enough memory"); } return buf; } void *myrealloc(void* buf, int size) { void *result; if ((result = realloc(buf, size)) == NULL) { myabort("Not enough memory"); } return result; } /* allocates a FastaSeq structure on the heap and initializes it*/ FastaSeq* newFastaSeq(void) { FastaSeq* r=(FastaSeq*)mymalloc(sizeof(FastaSeq)); initFastaSeq(r); return r; } void freeFastaSeq(FastaSeq* seq) { doneFastaSeq(seq); free(seq); } /* initializes a static FastaSeq structure */ void initFastaSeq(FastaSeq* seq) { seq->id=(char*)mymalloc(CAPINC); seq->id_len=CAPINC; seq->id[0]='\0'; seq->descr=(char*)mymalloc(CAPINC); seq->descr[0]='\0'; seq->d_len=CAPINC; seq->seq=(char*)mymalloc(CAPINC<<1); seq->seq[0]='\0'; seq->len=0; seq->s_len=CAPINC<<1; } /* clears (frees) internal strings of a FastaSeq structure */ void doneFastaSeq(FastaSeq* seq) { free(seq->id); seq->id=NULL; seq->id_len=0; free(seq->descr); seq->descr=NULL; seq->d_len=0; free(seq->seq); seq->seq=NULL; seq->s_len=0;seq->len=0; } /* initializes a static FastaSeq structure */ void initFastaSeq(FastaSeq* seq); /* clears (frees) internal strings of a FastaSeq structure */ void doneFastaSeq(FastaSeq* seq); FILE *myfopen(char* name, char* mode) { FILE *fp; if (name == NULL) { return (mode != NULL && *mode == 'r') ? stdin : stdout; } if ((fp = fopen(name, mode)) == NULL) { if (mode != NULL && *mode == 'r') { fprintf(stderr, "No such file: \"%s\"\n", name); } else { fprintf(stderr, "Failed to open file: \"%s\"\n", name); } exit(1); } return fp; } void bad_fastafmt() { myabort("Not a FastaSeq file"); } void check_eof(int c) { if (c == EOF) bad_fastafmt(); } /* the first character must be '>' for each call seq must be an initialized FastaSeq structure */ FastaSeq *getfasta(FILE* fp, FastaSeq* seq, int* is_last) { int c, len; int* buflen; char** buf; int before; /* fp = myfopen(name, "r"); */ c = getc(fp); if (c==EOF) return NULL; if (c != '>') bad_fastafmt(); len = 0; //chars accumulated so far /* -------- read the defline first */ buflen=&seq->id_len; buf=&seq->id; before=1; while ((c = getc(fp)) != EOF && c != '\n') { if (len >= *buflen-1) { *buf=(char*)myrealloc(*buf, *buflen + CAPINC); *buflen+=CAPINC; } if (before && isspace(c)) { /* space encountered => seq_name finished */ before=0; (*buf)[len]='\0'; buf=&seq->descr; buflen=&seq->d_len; len=0; continue; /* skip this space */ } (*buf)[len]=c; len++; } (*buf)[len]='\0'; /* terminate the comment string */ check_eof(c); /* it's wrong to have eof here */ /*----- read the sequence now: */ len=0; before=1; //newline before indicator while ((c = getc(fp)) != EOF && c != '>') { if (isspace(c)) { before = (c=='\n')?1:0; continue; /* skip spaces */ } if (len >= seq->s_len-1) { seq->seq = (char*)myrealloc(seq->seq, seq->s_len + CAPINC); seq->s_len+=CAPINC; } seq->seq[len] = c; before=0; len++; } seq->seq[len] = '\0'; seq->len=len; if (c=='>') { if (!before) bad_fastafmt(); /* '>' must only be at start of line, never within the sequence ! */ *is_last=0; /* FALSE - not the last one */ ungetc(c, fp); } else *is_last=1; /* TRUE - eof() here */ return seq; } void putfasta(FastaSeq *fa, char* name) { FILE *fp; char *s; int i, i60; fp = myfopen(name, "w"); s = (fa->id == NULL) ? (char*)"ANONYMOUS" : fa->id; if (*s != '>') putc('>', fp); fwrite(s, 1, strlen(s), fp); i=strlen(fa->descr); if (i>0) { putc(' ',fp); fwrite(fa->descr, 1, i, fp); } i60 = 60; for (i=0, s = fa->seq; i < fa->len; i++, s++, i60++) { if (i60 == 60) { putc('\n', fp); i60 = 0; } putc(*s, fp); } putc('\n', fp); if (fp != stdout) { fclose(fp); } }
4c05b3287c15f4966bfbd1fa02f6fc21104d7b16
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/hppa/hppa/pim.h
f1e6574c52ed90a3968152d28231d81779bb6572
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
12,219
h
pim.h
/* $NetBSD: pim.h,v 1.2 2019/04/15 20:45:08 skrll Exp $ */ /*- * Copyright (c) 2002 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Matthew Fredette. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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. */ /* * This describes the Processor Internal Memory data for various checks. * * References: * * "PA/RISC 1.1 I/O Firmware Architecture Reference Specification", * Version 1.0, August 22, 2001. * * "PA/RISC 2.0 I/O Firmware Architecture Reference Specification", * Version 1.0, August 22, 2001. */ /* The PIM data for HPMC and TOC contains these register arrays. */ struct hppa_pim_regs { /* The general registers. */ uint32_t pim_regs_r0; uint32_t pim_regs_r1; uint32_t pim_regs_r2; uint32_t pim_regs_r3; uint32_t pim_regs_r4; uint32_t pim_regs_r5; uint32_t pim_regs_r6; uint32_t pim_regs_r7; uint32_t pim_regs_r8; uint32_t pim_regs_r9; uint32_t pim_regs_r10; uint32_t pim_regs_r11; uint32_t pim_regs_r12; uint32_t pim_regs_r13; uint32_t pim_regs_r14; uint32_t pim_regs_r15; uint32_t pim_regs_r16; uint32_t pim_regs_r17; uint32_t pim_regs_r18; uint32_t pim_regs_r19; uint32_t pim_regs_r20; uint32_t pim_regs_r21; uint32_t pim_regs_r22; uint32_t pim_regs_r23; uint32_t pim_regs_r24; uint32_t pim_regs_r25; uint32_t pim_regs_r26; uint32_t pim_regs_r27; uint32_t pim_regs_r28; uint32_t pim_regs_r29; uint32_t pim_regs_r30; uint32_t pim_regs_r31; /* The control registers. */ uint32_t pim_regs_cr0; uint32_t pim_regs_cr1; uint32_t pim_regs_cr2; uint32_t pim_regs_cr3; uint32_t pim_regs_cr4; uint32_t pim_regs_cr5; uint32_t pim_regs_cr6; uint32_t pim_regs_cr7; uint32_t pim_regs_cr8; uint32_t pim_regs_cr9; uint32_t pim_regs_cr10; uint32_t pim_regs_cr11; uint32_t pim_regs_cr12; uint32_t pim_regs_cr13; uint32_t pim_regs_cr14; uint32_t pim_regs_cr15; uint32_t pim_regs_cr16; uint32_t pim_regs_cr17; uint32_t pim_regs_cr18; uint32_t pim_regs_cr19; uint32_t pim_regs_cr20; uint32_t pim_regs_cr21; uint32_t pim_regs_cr22; uint32_t pim_regs_cr23; uint32_t pim_regs_cr24; uint32_t pim_regs_cr25; uint32_t pim_regs_cr26; uint32_t pim_regs_cr27; uint32_t pim_regs_cr28; uint32_t pim_regs_cr29; uint32_t pim_regs_cr30; uint32_t pim_regs_cr31; /* The space registers. */ uint32_t pim_regs_sr0; uint32_t pim_regs_sr1; uint32_t pim_regs_sr2; uint32_t pim_regs_sr3; uint32_t pim_regs_sr4; uint32_t pim_regs_sr5; uint32_t pim_regs_sr6; uint32_t pim_regs_sr7; /* The back entries of the instruction address queues. */ uint32_t pim_regs_iisq_tail; uint32_t pim_regs_iioq_tail; }; /* The PIM data for HPMC and LPMC contains this check information. */ struct hppa_pim_checks { /* The Check Type. */ uint32_t pim_check_type; #define PIM_CHECK_CACHE (1 << 31) #define PIM_CHECK_TLB (1 << 30) #define PIM_CHECK_BUS (1 << 29) #define PIM_CHECK_ASSISTS (1 << 28) #define PIM_CHECK_BITS \ "\177\020" /* New bitmask format */ \ "b\040cache\0" /* bit 31 */ \ "b\037tlb\0" /* bit 30 */ \ "b\036bus\0" /* bit 29 */ \ "b\035assists\0" /* bit 28 */ /* * The CPU State. In addition to the common PIM_CPU_ * bits defined below, some fields are HPMC-specific. */ uint32_t pim_check_cpu_state; #define PIM_CPU_IQV (1 << 31) #define PIM_CPU_IQF (1 << 30) #define PIM_CPU_IPV (1 << 29) #define PIM_CPU_GRV (1 << 28) #define PIM_CPU_CRV (1 << 27) #define PIM_CPU_SRV (1 << 26) #define PIM_CPU_TRV (1 << 25) #define PIM_CPU_BITS \ "\177\020" /* New bitmask format */ \ "b\040iqv\0" /* bit 31 */ \ "b\037iqf\0" /* bit 30 */ \ "b\036ipv\0" /* bit 29 */ \ "b\035grv\0" /* bit 28 */ \ "b\034crv\0" /* bit 27 */ \ "b\033srv\0" /* bit 26 */ \ "b\032trv\0" /* bit 25 */ #define PIM_CPU_HPMC_TL(cs) (((cs) >> 4) & 0x3) #define PIM_CPU_HPMC_HD (1 << 3) #define PIM_CPU_HPMC_SIS (1 << 2) #define PIM_CPU_HPMC_CS(cs) ((cs) & 0x3) #define PIM_CPU_HPMC_BITS \ PIM_CPU_BITS \ "f\004\002tl\0" /* bit 4 .. 5 */ \ "b\003hd\0" /* bit 3 */ \ "b\002sis\0" /* bit 2 */ \ "f\000\002cs\0" /* bit 0 .. 1 */ uint32_t pim_check_reserved_0; /* The Cache Check word. */ uint32_t pim_check_cache; #define PIM_CACHE_ICC (1 << 31) #define PIM_CACHE_DCC (1 << 30) #define PIM_CACHE_TC (1 << 29) #define PIM_CACHE_DC (1 << 28) #define PIM_CACHE_CRG (1 << 27) #define PIM_CACHE_LC (1 << 26) #define PIM_CACHE_RCC (1 << 25) #define PIM_CACHE_PADD(cc) ((cc) & 0x000fffff) #define PIM_CACHE_BITS \ "\177\020" /* New bitmask format */ \ "b\040icc\0" /* bit 31 */ \ "b\039dcc\0" /* bit 30 */ \ "b\038tc\0" /* bit 29 */ \ "b\037dc\0" /* bit 28 */ \ "b\036crg\0" /* bit 27 */ \ "b\035lc\0" /* bit 26 */ \ "b\034rcc\0" /* bit 25 */ \ "f\000\032paddr\0" /* bit 0 .. 23 */ /* The TLB Check word. */ uint32_t pim_check_tlb; #define PIM_TLB_ITC (1 << 31) #define PIM_TLB_DTC (1 << 30) #define PIM_TLB_TRG (1 << 29) #define PIM_TLB_TUC (1 << 28) #define PIM_TLB_TNF (1 << 27) #define PIM_TLB_BITS \ "\177\020" /* New bitmask format */ \ "b\040itc\0" /* bit 31 */ \ "b\039dtc\0" /* bit 30 */ \ "b\038trg\0" /* bit 29 */ \ "b\037tuc\0" /* bit 28 */ \ "b\036tnf\0" /* bit 27 */ \ /* The Bus Check word. */ uint32_t pim_check_bus; #define PIM_BUS_RSV (1 << 21) #define PIM_BUS_RQV (1 << 20) #define PIM_BUS_VAR(bc) (((bc) >> 16) & 0xf) #define PIM_BUS_TYPE(bc) (((bc) >> 12) & 0xf) #define PIM_BUS_SIZE(bc) (((bc) >> 8) & 0xf) #define PIM_BUS_PIV (1 << 7) #define PIM_BUS_BSV (1 << 6) #define PIM_BUS_STAT(bc) ((bc) & 0x3f) #define PIM_BUS_BITS \ "\177\020" /* New bitmask format */ \ "b\025rsv\0" /* bit 21 */ \ "b\024rqv\0" /* bit 20 */ \ "f\020\004var\0" /* bit 16 .. 19 */ \ "f\014\004type\0" /* bit 12 .. 15 */ \ "f\010\004size\0" /* bit 8 .. 11 */ \ "b\007piv\0" /* bit 7 */ \ "b\006bsv\0" /* bit 6 */ \ "f\000\006stat\0" /* bit 0 .. 5 */ /* The Assist Check word. */ uint32_t pim_check_assist; #define PIM_ASSIST_COC (1 << 31) #define PIM_ASSIST_SC (1 << 30) #define PIM_ASSIST_BITS "\020\040COC\037SC" uint32_t pim_check_reserved_1; /* Additional information about the check. */ uint32_t pim_check_assist_state; uint32_t pim_check_responder; uint32_t pim_check_requestor; uint32_t pim_check_path_info; }; /* The PIM data for HPMC and LPMC contains this register array. */ struct hppa_pim_fpregs { /* The FPU state. */ uint64_t pim_fpregs_fp0; uint64_t pim_fpregs_fp1; uint64_t pim_fpregs_fp2; uint64_t pim_fpregs_fp3; uint64_t pim_fpregs_fp4; uint64_t pim_fpregs_fp5; uint64_t pim_fpregs_fp6; uint64_t pim_fpregs_fp7; uint64_t pim_fpregs_fp8; uint64_t pim_fpregs_fp9; uint64_t pim_fpregs_fp10; uint64_t pim_fpregs_fp11; uint64_t pim_fpregs_fp12; uint64_t pim_fpregs_fp13; uint64_t pim_fpregs_fp14; uint64_t pim_fpregs_fp15; uint64_t pim_fpregs_fp16; uint64_t pim_fpregs_fp17; uint64_t pim_fpregs_fp18; uint64_t pim_fpregs_fp19; uint64_t pim_fpregs_fp20; uint64_t pim_fpregs_fp21; uint64_t pim_fpregs_fp22; uint64_t pim_fpregs_fp23; uint64_t pim_fpregs_fp24; uint64_t pim_fpregs_fp25; uint64_t pim_fpregs_fp26; uint64_t pim_fpregs_fp27; uint64_t pim_fpregs_fp28; uint64_t pim_fpregs_fp29; uint64_t pim_fpregs_fp30; uint64_t pim_fpregs_fp31; }; /* The HPMC PIM data. */ struct hppa_pim_hpmc { struct hppa_pim_regs pim_hpmc_regs; struct hppa_pim_checks pim_hpmc_checks; struct hppa_pim_fpregs pim_hpmc_fpregs; }; /* The LPMC PIM data. */ struct hppa_pim_lpmc { uint32_t pim_lpmc_hversion_dep[74]; struct hppa_pim_checks pim_lpmc_checks; struct hppa_pim_fpregs pim_lpmc_fpregs; }; /* The TOC PIM data. */ struct hppa_pim_toc { struct hppa_pim_regs pim_toc_regs; uint32_t pim_toc_hversion_dep; uint32_t pim_toc_cpu_state; }; struct hppa_pim64_regs { /* The general registers. */ uint64_t pim_regs_r0; uint64_t pim_regs_r1; uint64_t pim_regs_r2; uint64_t pim_regs_r3; uint64_t pim_regs_r4; uint64_t pim_regs_r5; uint64_t pim_regs_r6; uint64_t pim_regs_r7; uint64_t pim_regs_r8; uint64_t pim_regs_r9; uint64_t pim_regs_r10; uint64_t pim_regs_r11; uint64_t pim_regs_r12; uint64_t pim_regs_r13; uint64_t pim_regs_r14; uint64_t pim_regs_r15; uint64_t pim_regs_r16; uint64_t pim_regs_r17; uint64_t pim_regs_r18; uint64_t pim_regs_r19; uint64_t pim_regs_r20; uint64_t pim_regs_r21; uint64_t pim_regs_r22; uint64_t pim_regs_r23; uint64_t pim_regs_r24; uint64_t pim_regs_r25; uint64_t pim_regs_r26; uint64_t pim_regs_r27; uint64_t pim_regs_r28; uint64_t pim_regs_r29; uint64_t pim_regs_r30; uint64_t pim_regs_r31; /* The control registers. */ uint64_t pim_regs_cr0; uint64_t pim_regs_cr1; uint64_t pim_regs_cr2; uint64_t pim_regs_cr3; uint64_t pim_regs_cr4; uint64_t pim_regs_cr5; uint64_t pim_regs_cr6; uint64_t pim_regs_cr7; uint64_t pim_regs_cr8; uint64_t pim_regs_cr9; uint64_t pim_regs_cr10; uint64_t pim_regs_cr11; uint64_t pim_regs_cr12; uint64_t pim_regs_cr13; uint64_t pim_regs_cr14; uint64_t pim_regs_cr15; uint64_t pim_regs_cr16; uint64_t pim_regs_cr17; uint64_t pim_regs_cr18; uint64_t pim_regs_cr19; uint64_t pim_regs_cr20; uint64_t pim_regs_cr21; uint64_t pim_regs_cr22; uint64_t pim_regs_cr23; uint64_t pim_regs_cr24; uint64_t pim_regs_cr25; uint64_t pim_regs_cr26; uint64_t pim_regs_cr27; uint64_t pim_regs_cr28; uint64_t pim_regs_cr29; uint64_t pim_regs_cr30; uint64_t pim_regs_cr31; /* The space registers. */ uint64_t pim_regs_sr0; uint64_t pim_regs_sr1; uint64_t pim_regs_sr2; uint64_t pim_regs_sr3; uint64_t pim_regs_sr4; uint64_t pim_regs_sr5; uint64_t pim_regs_sr6; uint64_t pim_regs_sr7; /* The back entries of the instruction address queues. */ uint64_t pim_regs_iisq_tail; uint64_t pim_regs_iioq_tail; }; struct hppa_pim64_checks { /* The Check Type. */ uint32_t pim_check_type; /* * The CPU State. In addition to the common PIM_CPU_ * bits defined below, some fields are HPMC-specific. */ uint32_t pim_check_cpu_state; /* The Cache Check word. */ uint32_t pim_check_cache; /* The TLB Check word. */ uint32_t pim_check_tlb; /* The Bus Check word. */ uint32_t pim_check_bus; /* The Assist Check word. */ uint32_t pim_check_assist; /* Additional information about the check. */ uint32_t pim_check_assist_state; uint32_t pim_check_path_info; uint64_t pim_check_responder; uint64_t pim_check_requestor; }; /* The PARISC 2.0 HPMC PIM data. */ struct hppa_pim64_hpmc { struct hppa_pim64_regs pim_hpmc_regs; struct hppa_pim64_checks pim_hpmc_checks; struct hppa_pim_fpregs pim_hpmc_fpregs; }; /* The PARISC 2.0 LPMC PIM data. */ struct hppa_pim64_lpmc { uint64_t pim_lmpc_hversion_dep[74]; struct hppa_pim64_checks pim_lpmc_checks; struct hppa_pim_fpregs pim_lpmc_fpregs; }; /* The PARISC 2.0 TOC PIM data. */ struct hppa_pim64_toc { struct hppa_pim64_regs pim_toc_regs; uint32_t pim_toc_hversion_dep; uint32_t pim_toc_cpu_state; };
ac189fc1abe8e3f501cdb6e9f64f41d7593461ff
ef2d4ed65259b3f614426664939e9fb938715299
/darknet/src/cuda.c
48aba6e40120d22ad0ad4f1d53c22e32fd12740c
[ "LicenseRef-scancode-yolo-1.0", "WTFPL", "LicenseRef-scancode-yolo-2.0", "MIT", "GPL-3.0-only", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
guanshuicheng/invoice
292ab7bd20ab07d4bdf9ca0f60ae2cf0e3bb06a4
bd201ed8e977421277775075a107a475bce0490d
refs/heads/master
2023-06-24T05:20:37.849072
2023-06-16T02:56:09
2023-06-16T02:56:09
200,155,602
1,399
379
MIT
2023-03-25T01:35:03
2019-08-02T03:06:41
C
UTF-8
C
false
false
4,095
c
cuda.c
int gpu_index = 0; #ifdef GPU #include "cuda.h" #include "utils.h" #include "blas.h" #include <assert.h> #include <stdlib.h> #include <time.h> void cuda_set_device(int n) { gpu_index = n; cudaError_t status = cudaSetDevice(n); check_error(status); } int cuda_get_device() { int n = 0; cudaError_t status = cudaGetDevice(&n); check_error(status); return n; } void check_error(cudaError_t status) { //cudaDeviceSynchronize(); cudaError_t status2 = cudaGetLastError(); if (status != cudaSuccess) { const char *s = cudaGetErrorString(status); char buffer[256]; printf("CUDA Error: %s\n", s); assert(0); snprintf(buffer, 256, "CUDA Error: %s", s); error(buffer); } if (status2 != cudaSuccess) { const char *s = cudaGetErrorString(status); char buffer[256]; printf("CUDA Error Prev: %s\n", s); assert(0); snprintf(buffer, 256, "CUDA Error Prev: %s", s); error(buffer); } } dim3 cuda_gridsize(size_t n){ size_t k = (n-1) / BLOCK + 1; size_t x = k; size_t y = 1; if(x > 65535){ x = ceil(sqrt(k)); y = (n-1)/(x*BLOCK) + 1; } dim3 d = {x, y, 1}; //printf("%ld %ld %ld %ld\n", n, x, y, x*y*BLOCK); return d; } #ifdef CUDNN cudnnHandle_t cudnn_handle() { static int init[16] = {0}; static cudnnHandle_t handle[16]; int i = cuda_get_device(); if(!init[i]) { cudnnCreate(&handle[i]); init[i] = 1; } return handle[i]; } #endif cublasHandle_t blas_handle() { static int init[16] = {0}; static cublasHandle_t handle[16]; int i = cuda_get_device(); if(!init[i]) { cublasCreate(&handle[i]); init[i] = 1; } return handle[i]; } float *cuda_make_array(float *x, size_t n) { float *x_gpu; size_t size = sizeof(float)*n; cudaError_t status = cudaMalloc((void **)&x_gpu, size); check_error(status); if(x){ status = cudaMemcpy(x_gpu, x, size, cudaMemcpyHostToDevice); check_error(status); } else { fill_gpu(n, 0, x_gpu, 1); } if(!x_gpu) error("Cuda malloc failed\n"); return x_gpu; } void cuda_random(float *x_gpu, size_t n) { static curandGenerator_t gen[16]; static int init[16] = {0}; int i = cuda_get_device(); if(!init[i]){ curandCreateGenerator(&gen[i], CURAND_RNG_PSEUDO_DEFAULT); curandSetPseudoRandomGeneratorSeed(gen[i], time(0)); init[i] = 1; } curandGenerateUniform(gen[i], x_gpu, n); check_error(cudaPeekAtLastError()); } float cuda_compare(float *x_gpu, float *x, size_t n, char *s) { float *tmp = calloc(n, sizeof(float)); cuda_pull_array(x_gpu, tmp, n); //int i; //for(i = 0; i < n; ++i) printf("%f %f\n", tmp[i], x[i]); axpy_cpu(n, -1, x, 1, tmp, 1); float err = dot_cpu(n, tmp, 1, tmp, 1); printf("Error %s: %f\n", s, sqrt(err/n)); free(tmp); return err; } int *cuda_make_int_array(int *x, size_t n) { int *x_gpu; size_t size = sizeof(int)*n; cudaError_t status = cudaMalloc((void **)&x_gpu, size); check_error(status); if(x){ status = cudaMemcpy(x_gpu, x, size, cudaMemcpyHostToDevice); check_error(status); } if(!x_gpu) error("Cuda malloc failed\n"); return x_gpu; } void cuda_free(float *x_gpu) { cudaError_t status = cudaFree(x_gpu); check_error(status); } void cuda_push_array(float *x_gpu, float *x, size_t n) { size_t size = sizeof(float)*n; cudaError_t status = cudaMemcpy(x_gpu, x, size, cudaMemcpyHostToDevice); check_error(status); } void cuda_pull_array(float *x_gpu, float *x, size_t n) { size_t size = sizeof(float)*n; cudaError_t status = cudaMemcpy(x, x_gpu, size, cudaMemcpyDeviceToHost); check_error(status); } float cuda_mag_array(float *x_gpu, size_t n) { float *temp = calloc(n, sizeof(float)); cuda_pull_array(x_gpu, temp, n); float m = mag_array(temp, n); free(temp); return m; } #else void cuda_set_device(int n){} #endif
0a2ca97b55638793305054d92f38eb0b02117223
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/u-boot_new/board/freescale/mpc8540ads/mpc8540ads.c
93288c7e9ce0252f8a7ee1ecdaa3b2e9f9153919
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "GPL-2.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
5,242
c
mpc8540ads.c
/* * Copyright 2004 Freescale Semiconductor. * (C) Copyright 2002,2003, Motorola Inc. * Xianghua Xiao, (X.Xiao@motorola.com) * * (C) Copyright 2002 Scott McNutt <smcnutt@artesyncp.com> * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <pci.h> #include <asm/processor.h> #include <asm/mmu.h> #include <asm/immap_85xx.h> #include <fsl_ddr_sdram.h> #include <libfdt.h> #include <fdt_support.h> #if defined(CONFIG_DDR_ECC) && !defined(CONFIG_ECC_INIT_VIA_DDRCONTROLLER) extern void ddr_enable_ecc(unsigned int dram_size); #endif void local_bus_init(void); int checkboard (void) { puts("Board: ADS\n"); #ifdef CONFIG_PCI printf("PCI1: 32 bit, %d MHz (compiled)\n", CONFIG_SYS_CLK_FREQ / 1000000); #else printf("PCI1: disabled\n"); #endif /* * Initialize local bus. */ local_bus_init(); return 0; } /* * Initialize Local Bus */ void local_bus_init(void) { volatile ccsr_gur_t *gur = (void *)(CONFIG_SYS_MPC85xx_GUTS_ADDR); volatile fsl_lbc_t *lbc = LBC_BASE_ADDR; uint clkdiv; uint lbc_hz; sys_info_t sysinfo; /* * Errata LBC11. * Fix Local Bus clock glitch when DLL is enabled. * * If localbus freq is < 66MHz, DLL bypass mode must be used. * If localbus freq is > 133MHz, DLL can be safely enabled. * Between 66 and 133, the DLL is enabled with an override workaround. */ get_sys_info(&sysinfo); clkdiv = lbc->lcrr & LCRR_CLKDIV; lbc_hz = sysinfo.freq_systembus / 1000000 / clkdiv; if (lbc_hz < 66) { lbc->lcrr = CONFIG_SYS_LBC_LCRR | LCRR_DBYP; /* DLL Bypass */ } else if (lbc_hz >= 133) { lbc->lcrr = CONFIG_SYS_LBC_LCRR & (~LCRR_DBYP); /* DLL Enabled */ } else { /* * On REV1 boards, need to change CLKDIV before enable DLL. * Default CLKDIV is 8, change it to 4 temporarily. */ uint pvr = get_pvr(); uint temp_lbcdll = 0; if (pvr == PVR_85xx_REV1) { /* FIXME: Justify the high bit here. */ lbc->lcrr = 0x10000004; } lbc->lcrr = CONFIG_SYS_LBC_LCRR & (~LCRR_DBYP); /* DLL Enabled */ udelay(200); /* * Sample LBC DLL ctrl reg, upshift it to set the * override bits. */ temp_lbcdll = gur->lbcdllcr; gur->lbcdllcr = (((temp_lbcdll & 0xff) << 16) | 0x80000000); asm("sync;isync;msync"); } } /* * Initialize SDRAM memory on the Local Bus. */ void lbc_sdram_init(void) { volatile fsl_lbc_t *lbc = LBC_BASE_ADDR; uint *sdram_addr = (uint *)CONFIG_SYS_LBC_SDRAM_BASE; puts("LBC SDRAM: "); print_size(CONFIG_SYS_LBC_SDRAM_SIZE * 1024 * 1024, "\n "); /* * Setup SDRAM Base and Option Registers */ set_lbc_or(2, CONFIG_SYS_OR2_PRELIM); set_lbc_br(2, CONFIG_SYS_BR2_PRELIM); lbc->lbcr = CONFIG_SYS_LBC_LBCR; asm("msync"); lbc->lsrt = CONFIG_SYS_LBC_LSRT; lbc->mrtpr = CONFIG_SYS_LBC_MRTPR; asm("sync"); /* * Configure the SDRAM controller. */ lbc->lsdmr = CONFIG_SYS_LBC_LSDMR_1; asm("sync"); *sdram_addr = 0xff; ppcDcbf((unsigned long) sdram_addr); udelay(100); lbc->lsdmr = CONFIG_SYS_LBC_LSDMR_2; asm("sync"); *sdram_addr = 0xff; ppcDcbf((unsigned long) sdram_addr); udelay(100); lbc->lsdmr = CONFIG_SYS_LBC_LSDMR_3; asm("sync"); *sdram_addr = 0xff; ppcDcbf((unsigned long) sdram_addr); udelay(100); lbc->lsdmr = CONFIG_SYS_LBC_LSDMR_4; asm("sync"); *sdram_addr = 0xff; ppcDcbf((unsigned long) sdram_addr); udelay(100); lbc->lsdmr = CONFIG_SYS_LBC_LSDMR_5; asm("sync"); *sdram_addr = 0xff; ppcDcbf((unsigned long) sdram_addr); udelay(100); } #if !defined(CONFIG_SPD_EEPROM) /************************************************************************* * fixed sdram init -- doesn't use serial presence detect. ************************************************************************/ phys_size_t fixed_sdram(void) { #ifndef CONFIG_SYS_RAMBOOT struct ccsr_ddr __iomem *ddr = (struct ccsr_ddr __iomem *)(CONFIG_SYS_FSL_DDR_ADDR); ddr->cs0_bnds = CONFIG_SYS_DDR_CS0_BNDS; ddr->cs0_config = CONFIG_SYS_DDR_CS0_CONFIG; ddr->timing_cfg_1 = CONFIG_SYS_DDR_TIMING_1; ddr->timing_cfg_2 = CONFIG_SYS_DDR_TIMING_2; ddr->sdram_mode = CONFIG_SYS_DDR_MODE; ddr->sdram_interval = CONFIG_SYS_DDR_INTERVAL; #if defined (CONFIG_DDR_ECC) ddr->err_disable = 0x0000000D; ddr->err_sbe = 0x00ff0000; #endif asm("sync;isync;msync"); udelay(500); #if defined (CONFIG_DDR_ECC) /* Enable ECC checking */ ddr->sdram_cfg = (CONFIG_SYS_DDR_CONTROL | 0x20000000); #else ddr->sdram_cfg = CONFIG_SYS_DDR_CONTROL; #endif asm("sync; isync; msync"); udelay(500); #endif return CONFIG_SYS_SDRAM_SIZE * 1024 * 1024; } #endif /* !defined(CONFIG_SPD_EEPROM) */ #if defined(CONFIG_PCI) /* * Initialize PCI Devices, report devices found. */ static struct pci_controller hose; #endif /* CONFIG_PCI */ void pci_init_board(void) { #ifdef CONFIG_PCI pci_mpc85xx_init(&hose); #endif /* CONFIG_PCI */ } #if defined(CONFIG_OF_BOARD_SETUP) void ft_board_setup(void *blob, bd_t *bd) { int node, tmp[2]; const char *path; ft_cpu_setup(blob, bd); node = fdt_path_offset(blob, "/aliases"); tmp[0] = 0; if (node >= 0) { #ifdef CONFIG_PCI path = fdt_getprop(blob, node, "pci0", NULL); if (path) { tmp[1] = hose.last_busno - hose.first_busno; do_fixup_by_path(blob, path, "bus-range", &tmp, 8, 1); } #endif } } #endif
d3135f9711fff015346eb8d4c76a18be421bf5e4
f8cc1dd4b1378490386def2e0571561fab10b275
/src/libstddjb/tain_now_set_stopwatch.c
fd31950f757c40dc52716497e838317f624132ec
[ "ISC" ]
permissive
skarnet/skalibs
b1eb2a0e38663cbfa918ee0a7916f56227bd7c2d
1f2d5f95684e93f8523e369ef1fed7a75c444082
refs/heads/master
2023-08-23T07:33:20.996016
2023-08-08T09:39:15
2023-08-08T09:39:15
31,461,366
104
32
ISC
2021-04-11T10:10:54
2015-02-28T12:01:41
C
UTF-8
C
false
false
761
c
tain_now_set_stopwatch.c
/* ISC license. */ /* MT-unsafe */ #include <skalibs/sysdeps.h> #include <skalibs/tai.h> #if defined(SKALIBS_HASCLOCKRT) && (defined(SKALIBS_HASCLOCKMON) || defined(SKALIBS_HASCLOCKBOOT)) #include <time.h> #ifdef SKALIBS_HASCLOCKMON # define SKALIBS_STOPWATCH CLOCK_MONOTONIC #else # define SKALIBS_STOPWATCH CLOCK_BOOTTIME #endif static tain offset ; static int tain_now_stopwatch (tain *now) { return tain_stopwatch_read(now, SKALIBS_STOPWATCH, &offset) ; } int tain_now_set_stopwatch (tain *now) { if (!tain_stopwatch_init(now, SKALIBS_STOPWATCH, &offset)) return tain_now_set_wallclock(now) ; tain_now = &tain_now_stopwatch ; return 1 ; } #else int tain_now_set_stopwatch (tain *now) { return tain_now_set_wallclock(now) ; } #endif
05772b938b8574abba01e421b2969bf1482f1ef1
8e9b21f8b0e8bae10e333b2cdc45c0c70df361fe
/external/libm/src/b_log.c
b5b2bb62588b7c44808999554e3c1919eb5c94d0
[ "GPL-3.0-only", "BSD-3-Clause", "MIT-CMU", "SunPro", "CMU-Mach", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-other-permissive" ]
permissive
tyler569/nightingale
6173abf28d1e5399d77ec3d9977ab7c9562d0913
ea07ccb768105d942b4391c79fde2089c06dcea7
refs/heads/master
2023-08-04T20:49:28.852042
2023-07-27T16:31:20
2023-07-27T17:06:43
80,633,386
147
13
MIT
2019-04-12T01:31:33
2017-02-01T15:28:03
C
UTF-8
C
false
false
12,387
c
b_log.c
/* $NetBSD: b_log.c,v 1.1.2.2 2012/05/09 18:22:36 riz Exp $ */ /* * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. */ /* @(#)log.c 8.2 (Berkeley) 11/30/93 */ #include <sys/cdefs.h> #if 0 __FBSDID("$FreeBSD: release/9.0.0/lib/msun/bsdsrc/b_log.c 176449 2008-02-22 02:26:51Z das $"); #else __RCSID("$NetBSD: b_log.c,v 1.1.2.2 2012/05/09 18:22:36 riz Exp $"); #endif #include <errno.h> #include "math.h" #include "math_private.h" /* Table-driven natural logarithm. * * This code was derived, with minor modifications, from: * Peter Tang, "Table-Driven Implementation of the * Logarithm in IEEE Floating-Point arithmetic." ACM Trans. * Math Software, vol 16. no 4, pp 378-400, Dec 1990). * * Calculates log(2^m*F*(1+f/F)), |f/j| <= 1/256, * where F = j/128 for j an integer in [0, 128]. * * log(2^m) = log2_hi*m + log2_tail*m * since m is an integer, the dominant term is exact. * m has at most 10 digits (for subnormal numbers), * and log2_hi has 11 trailing zero bits. * * log(F) = logF_hi[j] + logF_lo[j] is in tabular form in log_table.h * logF_hi[] + 512 is exact. * * log(1+f/F) = 2*f/(2*F + f) + 1/12 * (2*f/(2*F + f))**3 + ... * the leading term is calculated to extra precision in two * parts, the larger of which adds exactly to the dominant * m and F terms. * There are two cases: * 1. when m, j are non-zero (m | j), use absolute * precision for the leading term. * 2. when m = j = 0, |1-x| < 1/256, and log(x) ~= (x-1). * In this case, use a relative precision of 24 bits. * (This is done differently in the original paper) * * Special cases: * 0 return signalling -Inf * neg return signalling NaN * +Inf return +Inf */ #define N 128 /* Table of log(Fj) = logF_head[j] + logF_tail[j], for Fj = 1+j/128. * Used for generation of extend precision logarithms. * The constant 35184372088832 is 2^45, so the divide is exact. * It ensures correct reading of logF_head, even for inaccurate * decimal-to-binary conversion routines. (Everybody gets the * right answer for integers less than 2^53.) * Values for log(F) were generated using error < 10^-57 absolute * with the bc -l package. */ static const double A1 = .08333333333333178827; static const double A2 = .01250000000377174923; static const double A3 = .002232139987919447809; static const double A4 = .0004348877777076145742; static const double logF_head[N+1] = { 0., .007782140442060381246, .015504186535963526694, .023167059281547608406, .030771658666765233647, .038318864302141264488, .045809536031242714670, .053244514518837604555, .060624621816486978786, .067950661908525944454, .075223421237524235039, .082443669210988446138, .089612158689760690322, .096729626458454731618, .103796793681567578460, .110814366340264314203, .117783035656430001836, .124703478501032805070, .131576357788617315236, .138402322859292326029, .145182009844575077295, .151916042025732167530, .158605030176659056451, .165249572895390883786, .171850256926518341060, .178407657472689606947, .184922338493834104156, .191394852999565046047, .197825743329758552135, .204215541428766300668, .210564769107350002741, .216873938300523150246, .223143551314024080056, .229374101064877322642, .235566071312860003672, .241719936886966024758, .247836163904594286577, .253915209980732470285, .259957524436686071567, .265963548496984003577, .271933715484010463114, .277868451003087102435, .283768173130738432519, .289633292582948342896, .295464212893421063199, .301261330578199704177, .307025035294827830512, .312755710004239517729, .318453731118097493890, .324119468654316733591, .329753286372579168528, .335355541920762334484, .340926586970454081892, .346466767346100823488, .351976423156884266063, .357455888922231679316, .362905493689140712376, .368325561158599157352, .373716409793814818840, .379078352934811846353, .384411698910298582632, .389716751140440464951, .394993808240542421117, .400243164127459749579, .405465108107819105498, .410659924985338875558, .415827895143593195825, .420969294644237379543, .426084395310681429691, .431173464818130014464, .436236766774527495726, .441274560805140936281, .446287102628048160113, .451274644139630254358, .456237433481874177232, .461175715122408291790, .466089729924533457960, .470979715219073113985, .475845904869856894947, .480688529345570714212, .485507815781602403149, .490303988045525329653, .495077266798034543171, .499827869556611403822, .504556010751912253908, .509261901790523552335, .513945751101346104405, .518607764208354637958, .523248143765158602036, .527867089620485785417, .532464798869114019908, .537041465897345915436, .541597282432121573947, .546132437597407260909, .550647117952394182793, .555141507540611200965, .559615787935399566777, .564070138285387656651, .568504735352689749561, .572919753562018740922, .577315365035246941260, .581691739635061821900, .586049045003164792433, .590387446602107957005, .594707107746216934174, .599008189645246602594, .603290851438941899687, .607555250224322662688, .611801541106615331955, .616029877215623855590, .620240409751204424537, .624433288012369303032, .628608659422752680256, .632766669570628437213, .636907462236194987781, .641031179420679109171, .645137961373620782978, .649227946625615004450, .653301272011958644725, .657358072709030238911, .661398482245203922502, .665422632544505177065, .669430653942981734871, .673422675212350441142, .677398823590920073911, .681359224807238206267, .685304003098281100392, .689233281238557538017, .693147180560117703862 }; static const double logF_tail[N+1] = { 0., -.00000000000000543229938420049, .00000000000000172745674997061, -.00000000000001323017818229233, -.00000000000001154527628289872, -.00000000000000466529469958300, .00000000000005148849572685810, -.00000000000002532168943117445, -.00000000000005213620639136504, -.00000000000001819506003016881, .00000000000006329065958724544, .00000000000008614512936087814, -.00000000000007355770219435028, .00000000000009638067658552277, .00000000000007598636597194141, .00000000000002579999128306990, -.00000000000004654729747598444, -.00000000000007556920687451336, .00000000000010195735223708472, -.00000000000017319034406422306, -.00000000000007718001336828098, .00000000000010980754099855238, -.00000000000002047235780046195, -.00000000000008372091099235912, .00000000000014088127937111135, .00000000000012869017157588257, .00000000000017788850778198106, .00000000000006440856150696891, .00000000000016132822667240822, -.00000000000007540916511956188, -.00000000000000036507188831790, .00000000000009120937249914984, .00000000000018567570959796010, -.00000000000003149265065191483, -.00000000000009309459495196889, .00000000000017914338601329117, -.00000000000001302979717330866, .00000000000023097385217586939, .00000000000023999540484211737, .00000000000015393776174455408, -.00000000000036870428315837678, .00000000000036920375082080089, -.00000000000009383417223663699, .00000000000009433398189512690, .00000000000041481318704258568, -.00000000000003792316480209314, .00000000000008403156304792424, -.00000000000034262934348285429, .00000000000043712191957429145, -.00000000000010475750058776541, -.00000000000011118671389559323, .00000000000037549577257259853, .00000000000013912841212197565, .00000000000010775743037572640, .00000000000029391859187648000, -.00000000000042790509060060774, .00000000000022774076114039555, .00000000000010849569622967912, -.00000000000023073801945705758, .00000000000015761203773969435, .00000000000003345710269544082, -.00000000000041525158063436123, .00000000000032655698896907146, -.00000000000044704265010452446, .00000000000034527647952039772, -.00000000000007048962392109746, .00000000000011776978751369214, -.00000000000010774341461609578, .00000000000021863343293215910, .00000000000024132639491333131, .00000000000039057462209830700, -.00000000000026570679203560751, .00000000000037135141919592021, -.00000000000017166921336082431, -.00000000000028658285157914353, -.00000000000023812542263446809, .00000000000006576659768580062, -.00000000000028210143846181267, .00000000000010701931762114254, .00000000000018119346366441110, .00000000000009840465278232627, -.00000000000033149150282752542, -.00000000000018302857356041668, -.00000000000016207400156744949, .00000000000048303314949553201, -.00000000000071560553172382115, .00000000000088821239518571855, -.00000000000030900580513238244, -.00000000000061076551972851496, .00000000000035659969663347830, .00000000000035782396591276383, -.00000000000046226087001544578, .00000000000062279762917225156, .00000000000072838947272065741, .00000000000026809646615211673, -.00000000000010960825046059278, .00000000000002311949383800537, -.00000000000058469058005299247, -.00000000000002103748251144494, -.00000000000023323182945587408, -.00000000000042333694288141916, -.00000000000043933937969737844, .00000000000041341647073835565, .00000000000006841763641591466, .00000000000047585534004430641, .00000000000083679678674757695, -.00000000000085763734646658640, .00000000000021913281229340092, -.00000000000062242842536431148, -.00000000000010983594325438430, .00000000000065310431377633651, -.00000000000047580199021710769, -.00000000000037854251265457040, .00000000000040939233218678664, .00000000000087424383914858291, .00000000000025218188456842882, -.00000000000003608131360422557, -.00000000000050518555924280902, .00000000000078699403323355317, -.00000000000067020876961949060, .00000000000016108575753932458, .00000000000058527188436251509, -.00000000000035246757297904791, -.00000000000018372084495629058, .00000000000088606689813494916, .00000000000066486268071468700, .00000000000063831615170646519, .00000000000025144230728376072, -.00000000000017239444525614834 }; /* * Extra precision variant, returning struct {double a, b;}; * log(x) = a+b to 63 bits, with a rounded to 26 bits. */ struct Double __log__D(double x) { int m, j; double F, f, g, q, u, v, u2; volatile double u1; struct Double r; /* Argument reduction: 1 <= g < 2; x/2^m = g; */ /* y = F*(1 + f/F) for |f| <= 2^-8 */ m = logb(x); g = ldexp(x, -m); if (m == -1022) { j = logb(g), m += j; g = ldexp(g, -j); } j = N*(g-1) + .5; F = (1.0/N) * j + 1; f = g - F; g = 1/(2*F+f); u = 2*f*g; v = u*u; q = u*v*(A1 + v*(A2 + v*(A3 + v*A4))); if (m | j) u1 = u + 513, u1 -= 513; else u1 = u, TRUNC(u1); u2 = (2.0*(f - F*u1) - u1*f) * g; u1 += m*logF_head[N] + logF_head[j]; u2 += logF_tail[j]; u2 += q; u2 += logF_tail[N]*m; r.a = u1 + u2; /* Only difference is here */ TRUNC(r.a); r.b = (u1 - r.a) + u2; return (r); }
1578d689e8426c1c82140127eb43ddbbb5e0e566
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/sound/pci/ac97/ac97_patch.c
66a3bc95fb844c3f1b311b227622aacbb680a50c
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
130,499
c
ac97_patch.c
/* * Copyright (c) by Jaroslav Kysela <perex@perex.cz> * Universal interface for Audio Codec '97 * * For more details look to AC '97 component specification revision 2.2 * by Intel Corporation (http://developer.intel.com) and to datasheets * for specific codecs. * * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include "ac97_local.h" #include "ac97_patch.h" /* * Forward declarations */ static struct snd_kcontrol *snd_ac97_find_mixer_ctl(struct snd_ac97 *ac97, const char *name); static int snd_ac97_add_vmaster(struct snd_ac97 *ac97, char *name, const unsigned int *tlv, const char **slaves); /* * Chip specific initialization */ static int patch_build_controls(struct snd_ac97 * ac97, const struct snd_kcontrol_new *controls, int count) { int idx, err; for (idx = 0; idx < count; idx++) if ((err = snd_ctl_add(ac97->bus->card, snd_ac97_cnew(&controls[idx], ac97))) < 0) return err; return 0; } /* replace with a new TLV */ static void reset_tlv(struct snd_ac97 *ac97, const char *name, const unsigned int *tlv) { struct snd_ctl_elem_id sid; struct snd_kcontrol *kctl; memset(&sid, 0, sizeof(sid)); strcpy(sid.name, name); sid.iface = SNDRV_CTL_ELEM_IFACE_MIXER; kctl = snd_ctl_find_id(ac97->bus->card, &sid); if (kctl && kctl->tlv.p) kctl->tlv.p = tlv; } /* set to the page, update bits and restore the page */ static int ac97_update_bits_page(struct snd_ac97 *ac97, unsigned short reg, unsigned short mask, unsigned short value, unsigned short page) { unsigned short page_save; int ret; mutex_lock(&ac97->page_mutex); page_save = snd_ac97_read(ac97, AC97_INT_PAGING) & AC97_PAGE_MASK; snd_ac97_update_bits(ac97, AC97_INT_PAGING, AC97_PAGE_MASK, page); ret = snd_ac97_update_bits(ac97, reg, mask, value); snd_ac97_update_bits(ac97, AC97_INT_PAGING, AC97_PAGE_MASK, page_save); mutex_unlock(&ac97->page_mutex); /* unlock paging */ return ret; } /* * shared line-in/mic controls */ static int ac97_enum_text_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo, const char **texts, unsigned int nums) { uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = nums; if (uinfo->value.enumerated.item > nums - 1) uinfo->value.enumerated.item = nums - 1; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int ac97_surround_jack_mode_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static const char *texts[] = { "Shared", "Independent" }; return ac97_enum_text_info(kcontrol, uinfo, texts, 2); } static int ac97_surround_jack_mode_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); ucontrol->value.enumerated.item[0] = ac97->indep_surround; return 0; } static int ac97_surround_jack_mode_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned char indep = !!ucontrol->value.enumerated.item[0]; if (indep != ac97->indep_surround) { ac97->indep_surround = indep; if (ac97->build_ops->update_jacks) ac97->build_ops->update_jacks(ac97); return 1; } return 0; } static int ac97_channel_mode_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static const char *texts[] = { "2ch", "4ch", "6ch", "8ch" }; return ac97_enum_text_info(kcontrol, uinfo, texts, kcontrol->private_value); } static int ac97_channel_mode_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); ucontrol->value.enumerated.item[0] = ac97->channel_mode; return 0; } static int ac97_channel_mode_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned char mode = ucontrol->value.enumerated.item[0]; if (mode >= kcontrol->private_value) return -EINVAL; if (mode != ac97->channel_mode) { ac97->channel_mode = mode; if (ac97->build_ops->update_jacks) ac97->build_ops->update_jacks(ac97); return 1; } return 0; } #define AC97_SURROUND_JACK_MODE_CTL \ { \ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \ .name = "Surround Jack Mode", \ .info = ac97_surround_jack_mode_info, \ .get = ac97_surround_jack_mode_get, \ .put = ac97_surround_jack_mode_put, \ } /* 6ch */ #define AC97_CHANNEL_MODE_CTL \ { \ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \ .name = "Channel Mode", \ .info = ac97_channel_mode_info, \ .get = ac97_channel_mode_get, \ .put = ac97_channel_mode_put, \ .private_value = 3, \ } /* 4ch */ #define AC97_CHANNEL_MODE_4CH_CTL \ { \ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \ .name = "Channel Mode", \ .info = ac97_channel_mode_info, \ .get = ac97_channel_mode_get, \ .put = ac97_channel_mode_put, \ .private_value = 2, \ } /* 8ch */ #define AC97_CHANNEL_MODE_8CH_CTL \ { \ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \ .name = "Channel Mode", \ .info = ac97_channel_mode_info, \ .get = ac97_channel_mode_get, \ .put = ac97_channel_mode_put, \ .private_value = 4, \ } static inline int is_surround_on(struct snd_ac97 *ac97) { return ac97->channel_mode >= 1; } static inline int is_clfe_on(struct snd_ac97 *ac97) { return ac97->channel_mode >= 2; } /* system has shared jacks with surround out enabled */ static inline int is_shared_surrout(struct snd_ac97 *ac97) { return !ac97->indep_surround && is_surround_on(ac97); } /* system has shared jacks with center/lfe out enabled */ static inline int is_shared_clfeout(struct snd_ac97 *ac97) { return !ac97->indep_surround && is_clfe_on(ac97); } /* system has shared jacks with line in enabled */ static inline int is_shared_linein(struct snd_ac97 *ac97) { return !ac97->indep_surround && !is_surround_on(ac97); } /* system has shared jacks with mic in enabled */ static inline int is_shared_micin(struct snd_ac97 *ac97) { return !ac97->indep_surround && !is_clfe_on(ac97); } static inline int alc850_is_aux_back_surround(struct snd_ac97 *ac97) { return is_surround_on(ac97); } /* The following snd_ac97_ymf753_... items added by David Shust (dshust@shustring.com) */ /* Modified for YMF743 by Keita Maehara <maehara@debian.org> */ /* It is possible to indicate to the Yamaha YMF7x3 the type of speakers being used. */ static int snd_ac97_ymf7x3_info_speaker(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[3] = { "Standard", "Small", "Smaller" }; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 3; if (uinfo->value.enumerated.item > 2) uinfo->value.enumerated.item = 2; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_ac97_ymf7x3_get_speaker(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; val = ac97->regs[AC97_YMF7X3_3D_MODE_SEL]; val = (val >> 10) & 3; if (val > 0) /* 0 = invalid */ val--; ucontrol->value.enumerated.item[0] = val; return 0; } static int snd_ac97_ymf7x3_put_speaker(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; if (ucontrol->value.enumerated.item[0] > 2) return -EINVAL; val = (ucontrol->value.enumerated.item[0] + 1) << 10; return snd_ac97_update(ac97, AC97_YMF7X3_3D_MODE_SEL, val); } static const struct snd_kcontrol_new snd_ac97_ymf7x3_controls_speaker = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "3D Control - Speaker", .info = snd_ac97_ymf7x3_info_speaker, .get = snd_ac97_ymf7x3_get_speaker, .put = snd_ac97_ymf7x3_put_speaker, }; /* It is possible to indicate to the Yamaha YMF7x3 the source to direct to the S/PDIF output. */ static int snd_ac97_ymf7x3_spdif_source_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[2] = { "AC-Link", "A/D Converter" }; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 2; if (uinfo->value.enumerated.item > 1) uinfo->value.enumerated.item = 1; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_ac97_ymf7x3_spdif_source_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; val = ac97->regs[AC97_YMF7X3_DIT_CTRL]; ucontrol->value.enumerated.item[0] = (val >> 1) & 1; return 0; } static int snd_ac97_ymf7x3_spdif_source_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; if (ucontrol->value.enumerated.item[0] > 1) return -EINVAL; val = ucontrol->value.enumerated.item[0] << 1; return snd_ac97_update_bits(ac97, AC97_YMF7X3_DIT_CTRL, 0x0002, val); } static int patch_yamaha_ymf7x3_3d(struct snd_ac97 *ac97) { struct snd_kcontrol *kctl; int err; kctl = snd_ac97_cnew(&snd_ac97_controls_3d[0], ac97); err = snd_ctl_add(ac97->bus->card, kctl); if (err < 0) return err; strcpy(kctl->id.name, "3D Control - Wide"); kctl->private_value = AC97_SINGLE_VALUE(AC97_3D_CONTROL, 9, 7, 0); snd_ac97_write_cache(ac97, AC97_3D_CONTROL, 0x0000); err = snd_ctl_add(ac97->bus->card, snd_ac97_cnew(&snd_ac97_ymf7x3_controls_speaker, ac97)); if (err < 0) return err; snd_ac97_write_cache(ac97, AC97_YMF7X3_3D_MODE_SEL, 0x0c00); return 0; } static const struct snd_kcontrol_new snd_ac97_yamaha_ymf743_controls_spdif[3] = { AC97_SINGLE(SNDRV_CTL_NAME_IEC958("", PLAYBACK, SWITCH), AC97_YMF7X3_DIT_CTRL, 0, 1, 0), { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, NONE) "Source", .info = snd_ac97_ymf7x3_spdif_source_info, .get = snd_ac97_ymf7x3_spdif_source_get, .put = snd_ac97_ymf7x3_spdif_source_put, }, AC97_SINGLE(SNDRV_CTL_NAME_IEC958("", NONE, NONE) "Mute", AC97_YMF7X3_DIT_CTRL, 2, 1, 1) }; static int patch_yamaha_ymf743_build_spdif(struct snd_ac97 *ac97) { int err; err = patch_build_controls(ac97, &snd_ac97_controls_spdif[0], 3); if (err < 0) return err; err = patch_build_controls(ac97, snd_ac97_yamaha_ymf743_controls_spdif, 3); if (err < 0) return err; /* set default PCM S/PDIF params */ /* PCM audio,no copyright,no preemphasis,PCM coder,original */ snd_ac97_write_cache(ac97, AC97_YMF7X3_DIT_CTRL, 0xa201); return 0; } static const struct snd_ac97_build_ops patch_yamaha_ymf743_ops = { .build_spdif = patch_yamaha_ymf743_build_spdif, .build_3d = patch_yamaha_ymf7x3_3d, }; static int patch_yamaha_ymf743(struct snd_ac97 *ac97) { ac97->build_ops = &patch_yamaha_ymf743_ops; ac97->caps |= AC97_BC_BASS_TREBLE; ac97->caps |= 0x04 << 10; /* Yamaha 3D enhancement */ ac97->rates[AC97_RATES_SPDIF] = SNDRV_PCM_RATE_48000; /* 48k only */ ac97->ext_id |= AC97_EI_SPDIF; /* force the detection of spdif */ return 0; } /* The AC'97 spec states that the S/PDIF signal is to be output at pin 48. The YMF753 will output the S/PDIF signal to pin 43, 47 (EAPD), or 48. By default, no output pin is selected, and the S/PDIF signal is not output. There is also a bit to mute S/PDIF output in a vendor-specific register. */ static int snd_ac97_ymf753_spdif_output_pin_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[3] = { "Disabled", "Pin 43", "Pin 48" }; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 3; if (uinfo->value.enumerated.item > 2) uinfo->value.enumerated.item = 2; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_ac97_ymf753_spdif_output_pin_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; val = ac97->regs[AC97_YMF7X3_DIT_CTRL]; ucontrol->value.enumerated.item[0] = (val & 0x0008) ? 2 : (val & 0x0020) ? 1 : 0; return 0; } static int snd_ac97_ymf753_spdif_output_pin_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; if (ucontrol->value.enumerated.item[0] > 2) return -EINVAL; val = (ucontrol->value.enumerated.item[0] == 2) ? 0x0008 : (ucontrol->value.enumerated.item[0] == 1) ? 0x0020 : 0; return snd_ac97_update_bits(ac97, AC97_YMF7X3_DIT_CTRL, 0x0028, val); /* The following can be used to direct S/PDIF output to pin 47 (EAPD). snd_ac97_write_cache(ac97, 0x62, snd_ac97_read(ac97, 0x62) | 0x0008); */ } static const struct snd_kcontrol_new snd_ac97_ymf753_controls_spdif[3] = { { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source", .info = snd_ac97_ymf7x3_spdif_source_info, .get = snd_ac97_ymf7x3_spdif_source_get, .put = snd_ac97_ymf7x3_spdif_source_put, }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Output Pin", .info = snd_ac97_ymf753_spdif_output_pin_info, .get = snd_ac97_ymf753_spdif_output_pin_get, .put = snd_ac97_ymf753_spdif_output_pin_put, }, AC97_SINGLE(SNDRV_CTL_NAME_IEC958("", NONE, NONE) "Mute", AC97_YMF7X3_DIT_CTRL, 2, 1, 1) }; static int patch_yamaha_ymf753_post_spdif(struct snd_ac97 * ac97) { int err; if ((err = patch_build_controls(ac97, snd_ac97_ymf753_controls_spdif, ARRAY_SIZE(snd_ac97_ymf753_controls_spdif))) < 0) return err; return 0; } static const struct snd_ac97_build_ops patch_yamaha_ymf753_ops = { .build_3d = patch_yamaha_ymf7x3_3d, .build_post_spdif = patch_yamaha_ymf753_post_spdif }; static int patch_yamaha_ymf753(struct snd_ac97 * ac97) { /* Patch for Yamaha YMF753, Copyright (c) by David Shust, dshust@shustring.com. This chip has nonstandard and extended behaviour with regard to its S/PDIF output. The AC'97 spec states that the S/PDIF signal is to be output at pin 48. The YMF753 will ouput the S/PDIF signal to pin 43, 47 (EAPD), or 48. By default, no output pin is selected, and the S/PDIF signal is not output. There is also a bit to mute S/PDIF output in a vendor-specific register. */ ac97->build_ops = &patch_yamaha_ymf753_ops; ac97->caps |= AC97_BC_BASS_TREBLE; ac97->caps |= 0x04 << 10; /* Yamaha 3D enhancement */ return 0; } /* * May 2, 2003 Liam Girdwood <lrg@slimlogic.co.uk> * removed broken wolfson00 patch. * added support for WM9705,WM9708,WM9709,WM9710,WM9711,WM9712 and WM9717. */ static const struct snd_kcontrol_new wm97xx_snd_ac97_controls[] = { AC97_DOUBLE("Front Playback Volume", AC97_WM97XX_FMIXER_VOL, 8, 0, 31, 1), AC97_SINGLE("Front Playback Switch", AC97_WM97XX_FMIXER_VOL, 15, 1, 1), }; static int patch_wolfson_wm9703_specific(struct snd_ac97 * ac97) { /* This is known to work for the ViewSonic ViewPad 1000 * Randolph Bentson <bentson@holmsjoen.com> * WM9703/9707/9708/9717 */ int err, i; for (i = 0; i < ARRAY_SIZE(wm97xx_snd_ac97_controls); i++) { if ((err = snd_ctl_add(ac97->bus->card, snd_ac97_cnew(&wm97xx_snd_ac97_controls[i], ac97))) < 0) return err; } snd_ac97_write_cache(ac97, AC97_WM97XX_FMIXER_VOL, 0x0808); return 0; } static const struct snd_ac97_build_ops patch_wolfson_wm9703_ops = { .build_specific = patch_wolfson_wm9703_specific, }; static int patch_wolfson03(struct snd_ac97 * ac97) { ac97->build_ops = &patch_wolfson_wm9703_ops; return 0; } static const struct snd_kcontrol_new wm9704_snd_ac97_controls[] = { AC97_DOUBLE("Front Playback Volume", AC97_WM97XX_FMIXER_VOL, 8, 0, 31, 1), AC97_SINGLE("Front Playback Switch", AC97_WM97XX_FMIXER_VOL, 15, 1, 1), AC97_DOUBLE("Rear Playback Volume", AC97_WM9704_RMIXER_VOL, 8, 0, 31, 1), AC97_SINGLE("Rear Playback Switch", AC97_WM9704_RMIXER_VOL, 15, 1, 1), AC97_DOUBLE("Rear DAC Volume", AC97_WM9704_RPCM_VOL, 8, 0, 31, 1), AC97_DOUBLE("Surround Volume", AC97_SURROUND_MASTER, 8, 0, 31, 1), }; static int patch_wolfson_wm9704_specific(struct snd_ac97 * ac97) { int err, i; for (i = 0; i < ARRAY_SIZE(wm9704_snd_ac97_controls); i++) { if ((err = snd_ctl_add(ac97->bus->card, snd_ac97_cnew(&wm9704_snd_ac97_controls[i], ac97))) < 0) return err; } /* patch for DVD noise */ snd_ac97_write_cache(ac97, AC97_WM9704_TEST, 0x0200); return 0; } static const struct snd_ac97_build_ops patch_wolfson_wm9704_ops = { .build_specific = patch_wolfson_wm9704_specific, }; static int patch_wolfson04(struct snd_ac97 * ac97) { /* WM9704M/9704Q */ ac97->build_ops = &patch_wolfson_wm9704_ops; return 0; } static int patch_wolfson05(struct snd_ac97 * ac97) { /* WM9705, WM9710 */ ac97->build_ops = &patch_wolfson_wm9703_ops; #ifdef CONFIG_TOUCHSCREEN_WM9705 /* WM9705 touchscreen uses AUX and VIDEO for touch */ ac97->flags |= AC97_HAS_NO_VIDEO | AC97_HAS_NO_AUX; #endif return 0; } static const char* wm9711_alc_select[] = {"None", "Left", "Right", "Stereo"}; static const char* wm9711_alc_mix[] = {"Stereo", "Right", "Left", "None"}; static const char* wm9711_out3_src[] = {"Left", "VREF", "Left + Right", "Mono"}; static const char* wm9711_out3_lrsrc[] = {"Master Mix", "Headphone Mix"}; static const char* wm9711_rec_adc[] = {"Stereo", "Left", "Right", "Mute"}; static const char* wm9711_base[] = {"Linear Control", "Adaptive Boost"}; static const char* wm9711_rec_gain[] = {"+1.5dB Steps", "+0.75dB Steps"}; static const char* wm9711_mic[] = {"Mic 1", "Differential", "Mic 2", "Stereo"}; static const char* wm9711_rec_sel[] = {"Mic 1", "NC", "NC", "Master Mix", "Line", "Headphone Mix", "Phone Mix", "Phone"}; static const char* wm9711_ng_type[] = {"Constant Gain", "Mute"}; static const struct ac97_enum wm9711_enum[] = { AC97_ENUM_SINGLE(AC97_PCI_SVID, 14, 4, wm9711_alc_select), AC97_ENUM_SINGLE(AC97_VIDEO, 10, 4, wm9711_alc_mix), AC97_ENUM_SINGLE(AC97_AUX, 9, 4, wm9711_out3_src), AC97_ENUM_SINGLE(AC97_AUX, 8, 2, wm9711_out3_lrsrc), AC97_ENUM_SINGLE(AC97_REC_SEL, 12, 4, wm9711_rec_adc), AC97_ENUM_SINGLE(AC97_MASTER_TONE, 15, 2, wm9711_base), AC97_ENUM_DOUBLE(AC97_REC_GAIN, 14, 6, 2, wm9711_rec_gain), AC97_ENUM_SINGLE(AC97_MIC, 5, 4, wm9711_mic), AC97_ENUM_DOUBLE(AC97_REC_SEL, 8, 0, 8, wm9711_rec_sel), AC97_ENUM_SINGLE(AC97_PCI_SVID, 5, 2, wm9711_ng_type), }; static const struct snd_kcontrol_new wm9711_snd_ac97_controls[] = { AC97_SINGLE("ALC Target Volume", AC97_CODEC_CLASS_REV, 12, 15, 0), AC97_SINGLE("ALC Hold Time", AC97_CODEC_CLASS_REV, 8, 15, 0), AC97_SINGLE("ALC Decay Time", AC97_CODEC_CLASS_REV, 4, 15, 0), AC97_SINGLE("ALC Attack Time", AC97_CODEC_CLASS_REV, 0, 15, 0), AC97_ENUM("ALC Function", wm9711_enum[0]), AC97_SINGLE("ALC Max Volume", AC97_PCI_SVID, 11, 7, 1), AC97_SINGLE("ALC ZC Timeout", AC97_PCI_SVID, 9, 3, 1), AC97_SINGLE("ALC ZC Switch", AC97_PCI_SVID, 8, 1, 0), AC97_SINGLE("ALC NG Switch", AC97_PCI_SVID, 7, 1, 0), AC97_ENUM("ALC NG Type", wm9711_enum[9]), AC97_SINGLE("ALC NG Threshold", AC97_PCI_SVID, 0, 31, 1), AC97_SINGLE("Side Tone Switch", AC97_VIDEO, 15, 1, 1), AC97_SINGLE("Side Tone Volume", AC97_VIDEO, 12, 7, 1), AC97_ENUM("ALC Headphone Mux", wm9711_enum[1]), AC97_SINGLE("ALC Headphone Volume", AC97_VIDEO, 7, 7, 1), AC97_SINGLE("Out3 Switch", AC97_AUX, 15, 1, 1), AC97_SINGLE("Out3 ZC Switch", AC97_AUX, 7, 1, 0), AC97_ENUM("Out3 Mux", wm9711_enum[2]), AC97_ENUM("Out3 LR Mux", wm9711_enum[3]), AC97_SINGLE("Out3 Volume", AC97_AUX, 0, 31, 1), AC97_SINGLE("Beep to Headphone Switch", AC97_PC_BEEP, 15, 1, 1), AC97_SINGLE("Beep to Headphone Volume", AC97_PC_BEEP, 12, 7, 1), AC97_SINGLE("Beep to Side Tone Switch", AC97_PC_BEEP, 11, 1, 1), AC97_SINGLE("Beep to Side Tone Volume", AC97_PC_BEEP, 8, 7, 1), AC97_SINGLE("Beep to Phone Switch", AC97_PC_BEEP, 7, 1, 1), AC97_SINGLE("Beep to Phone Volume", AC97_PC_BEEP, 4, 7, 1), AC97_SINGLE("Aux to Headphone Switch", AC97_CD, 15, 1, 1), AC97_SINGLE("Aux to Headphone Volume", AC97_CD, 12, 7, 1), AC97_SINGLE("Aux to Side Tone Switch", AC97_CD, 11, 1, 1), AC97_SINGLE("Aux to Side Tone Volume", AC97_CD, 8, 7, 1), AC97_SINGLE("Aux to Phone Switch", AC97_CD, 7, 1, 1), AC97_SINGLE("Aux to Phone Volume", AC97_CD, 4, 7, 1), AC97_SINGLE("Phone to Headphone Switch", AC97_PHONE, 15, 1, 1), AC97_SINGLE("Phone to Master Switch", AC97_PHONE, 14, 1, 1), AC97_SINGLE("Line to Headphone Switch", AC97_LINE, 15, 1, 1), AC97_SINGLE("Line to Master Switch", AC97_LINE, 14, 1, 1), AC97_SINGLE("Line to Phone Switch", AC97_LINE, 13, 1, 1), AC97_SINGLE("PCM Playback to Headphone Switch", AC97_PCM, 15, 1, 1), AC97_SINGLE("PCM Playback to Master Switch", AC97_PCM, 14, 1, 1), AC97_SINGLE("PCM Playback to Phone Switch", AC97_PCM, 13, 1, 1), AC97_SINGLE("Capture 20dB Boost Switch", AC97_REC_SEL, 14, 1, 0), AC97_ENUM("Capture to Phone Mux", wm9711_enum[4]), AC97_SINGLE("Capture to Phone 20dB Boost Switch", AC97_REC_SEL, 11, 1, 1), AC97_ENUM("Capture Select", wm9711_enum[8]), AC97_SINGLE("3D Upper Cut-off Switch", AC97_3D_CONTROL, 5, 1, 1), AC97_SINGLE("3D Lower Cut-off Switch", AC97_3D_CONTROL, 4, 1, 1), AC97_ENUM("Bass Control", wm9711_enum[5]), AC97_SINGLE("Bass Cut-off Switch", AC97_MASTER_TONE, 12, 1, 1), AC97_SINGLE("Tone Cut-off Switch", AC97_MASTER_TONE, 4, 1, 1), AC97_SINGLE("Playback Attenuate (-6dB) Switch", AC97_MASTER_TONE, 6, 1, 0), AC97_SINGLE("ADC Switch", AC97_REC_GAIN, 15, 1, 1), AC97_ENUM("Capture Volume Steps", wm9711_enum[6]), AC97_DOUBLE("Capture Volume", AC97_REC_GAIN, 8, 0, 63, 1), AC97_SINGLE("Capture ZC Switch", AC97_REC_GAIN, 7, 1, 0), AC97_SINGLE("Mic 1 to Phone Switch", AC97_MIC, 14, 1, 1), AC97_SINGLE("Mic 2 to Phone Switch", AC97_MIC, 13, 1, 1), AC97_ENUM("Mic Select Source", wm9711_enum[7]), AC97_SINGLE("Mic 1 Volume", AC97_MIC, 8, 31, 1), AC97_SINGLE("Mic 2 Volume", AC97_MIC, 0, 31, 1), AC97_SINGLE("Mic 20dB Boost Switch", AC97_MIC, 7, 1, 0), AC97_SINGLE("Master Left Inv Switch", AC97_MASTER, 6, 1, 0), AC97_SINGLE("Master ZC Switch", AC97_MASTER, 7, 1, 0), AC97_SINGLE("Headphone ZC Switch", AC97_HEADPHONE, 7, 1, 0), AC97_SINGLE("Mono ZC Switch", AC97_MASTER_MONO, 7, 1, 0), }; static int patch_wolfson_wm9711_specific(struct snd_ac97 * ac97) { int err, i; for (i = 0; i < ARRAY_SIZE(wm9711_snd_ac97_controls); i++) { if ((err = snd_ctl_add(ac97->bus->card, snd_ac97_cnew(&wm9711_snd_ac97_controls[i], ac97))) < 0) return err; } snd_ac97_write_cache(ac97, AC97_CODEC_CLASS_REV, 0x0808); snd_ac97_write_cache(ac97, AC97_PCI_SVID, 0x0808); snd_ac97_write_cache(ac97, AC97_VIDEO, 0x0808); snd_ac97_write_cache(ac97, AC97_AUX, 0x0808); snd_ac97_write_cache(ac97, AC97_PC_BEEP, 0x0808); snd_ac97_write_cache(ac97, AC97_CD, 0x0000); return 0; } static const struct snd_ac97_build_ops patch_wolfson_wm9711_ops = { .build_specific = patch_wolfson_wm9711_specific, }; static int patch_wolfson11(struct snd_ac97 * ac97) { /* WM9711, WM9712 */ ac97->build_ops = &patch_wolfson_wm9711_ops; ac97->flags |= AC97_HAS_NO_REC_GAIN | AC97_STEREO_MUTES | AC97_HAS_NO_MIC | AC97_HAS_NO_PC_BEEP | AC97_HAS_NO_VIDEO | AC97_HAS_NO_CD; return 0; } static const char* wm9713_mic_mixer[] = {"Stereo", "Mic 1", "Mic 2", "Mute"}; static const char* wm9713_rec_mux[] = {"Stereo", "Left", "Right", "Mute"}; static const char* wm9713_rec_src[] = {"Mic 1", "Mic 2", "Line", "Mono In", "Headphone Mix", "Master Mix", "Mono Mix", "Zh"}; static const char* wm9713_rec_gain[] = {"+1.5dB Steps", "+0.75dB Steps"}; static const char* wm9713_alc_select[] = {"None", "Left", "Right", "Stereo"}; static const char* wm9713_mono_pga[] = {"Vmid", "Zh", "Mono Mix", "Inv 1"}; static const char* wm9713_spk_pga[] = {"Vmid", "Zh", "Headphone Mix", "Master Mix", "Inv", "NC", "NC", "NC"}; static const char* wm9713_hp_pga[] = {"Vmid", "Zh", "Headphone Mix", "NC"}; static const char* wm9713_out3_pga[] = {"Vmid", "Zh", "Inv 1", "NC"}; static const char* wm9713_out4_pga[] = {"Vmid", "Zh", "Inv 2", "NC"}; static const char* wm9713_dac_inv[] = {"Off", "Mono Mix", "Master Mix", "Headphone Mix L", "Headphone Mix R", "Headphone Mix Mono", "NC", "Vmid"}; static const char* wm9713_base[] = {"Linear Control", "Adaptive Boost"}; static const char* wm9713_ng_type[] = {"Constant Gain", "Mute"}; static const struct ac97_enum wm9713_enum[] = { AC97_ENUM_SINGLE(AC97_LINE, 3, 4, wm9713_mic_mixer), AC97_ENUM_SINGLE(AC97_VIDEO, 14, 4, wm9713_rec_mux), AC97_ENUM_SINGLE(AC97_VIDEO, 9, 4, wm9713_rec_mux), AC97_ENUM_DOUBLE(AC97_VIDEO, 3, 0, 8, wm9713_rec_src), AC97_ENUM_DOUBLE(AC97_CD, 14, 6, 2, wm9713_rec_gain), AC97_ENUM_SINGLE(AC97_PCI_SVID, 14, 4, wm9713_alc_select), AC97_ENUM_SINGLE(AC97_REC_GAIN, 14, 4, wm9713_mono_pga), AC97_ENUM_DOUBLE(AC97_REC_GAIN, 11, 8, 8, wm9713_spk_pga), AC97_ENUM_DOUBLE(AC97_REC_GAIN, 6, 4, 4, wm9713_hp_pga), AC97_ENUM_SINGLE(AC97_REC_GAIN, 2, 4, wm9713_out3_pga), AC97_ENUM_SINGLE(AC97_REC_GAIN, 0, 4, wm9713_out4_pga), AC97_ENUM_DOUBLE(AC97_REC_GAIN_MIC, 13, 10, 8, wm9713_dac_inv), AC97_ENUM_SINGLE(AC97_GENERAL_PURPOSE, 15, 2, wm9713_base), AC97_ENUM_SINGLE(AC97_PCI_SVID, 5, 2, wm9713_ng_type), }; static const struct snd_kcontrol_new wm13_snd_ac97_controls[] = { AC97_DOUBLE("Line In Volume", AC97_PC_BEEP, 8, 0, 31, 1), AC97_SINGLE("Line In to Headphone Switch", AC97_PC_BEEP, 15, 1, 1), AC97_SINGLE("Line In to Master Switch", AC97_PC_BEEP, 14, 1, 1), AC97_SINGLE("Line In to Mono Switch", AC97_PC_BEEP, 13, 1, 1), AC97_DOUBLE("PCM Playback Volume", AC97_PHONE, 8, 0, 31, 1), AC97_SINGLE("PCM Playback to Headphone Switch", AC97_PHONE, 15, 1, 1), AC97_SINGLE("PCM Playback to Master Switch", AC97_PHONE, 14, 1, 1), AC97_SINGLE("PCM Playback to Mono Switch", AC97_PHONE, 13, 1, 1), AC97_SINGLE("Mic 1 Volume", AC97_MIC, 8, 31, 1), AC97_SINGLE("Mic 2 Volume", AC97_MIC, 0, 31, 1), AC97_SINGLE("Mic 1 to Mono Switch", AC97_LINE, 7, 1, 1), AC97_SINGLE("Mic 2 to Mono Switch", AC97_LINE, 6, 1, 1), AC97_SINGLE("Mic Boost (+20dB) Switch", AC97_LINE, 5, 1, 0), AC97_ENUM("Mic to Headphone Mux", wm9713_enum[0]), AC97_SINGLE("Mic Headphone Mixer Volume", AC97_LINE, 0, 7, 1), AC97_SINGLE("Capture Switch", AC97_CD, 15, 1, 1), AC97_ENUM("Capture Volume Steps", wm9713_enum[4]), AC97_DOUBLE("Capture Volume", AC97_CD, 8, 0, 15, 0), AC97_SINGLE("Capture ZC Switch", AC97_CD, 7, 1, 0), AC97_ENUM("Capture to Headphone Mux", wm9713_enum[1]), AC97_SINGLE("Capture to Headphone Volume", AC97_VIDEO, 11, 7, 1), AC97_ENUM("Capture to Mono Mux", wm9713_enum[2]), AC97_SINGLE("Capture to Mono Boost (+20dB) Switch", AC97_VIDEO, 8, 1, 0), AC97_SINGLE("Capture ADC Boost (+20dB) Switch", AC97_VIDEO, 6, 1, 0), AC97_ENUM("Capture Select", wm9713_enum[3]), AC97_SINGLE("ALC Target Volume", AC97_CODEC_CLASS_REV, 12, 15, 0), AC97_SINGLE("ALC Hold Time", AC97_CODEC_CLASS_REV, 8, 15, 0), AC97_SINGLE("ALC Decay Time ", AC97_CODEC_CLASS_REV, 4, 15, 0), AC97_SINGLE("ALC Attack Time", AC97_CODEC_CLASS_REV, 0, 15, 0), AC97_ENUM("ALC Function", wm9713_enum[5]), AC97_SINGLE("ALC Max Volume", AC97_PCI_SVID, 11, 7, 0), AC97_SINGLE("ALC ZC Timeout", AC97_PCI_SVID, 9, 3, 0), AC97_SINGLE("ALC ZC Switch", AC97_PCI_SVID, 8, 1, 0), AC97_SINGLE("ALC NG Switch", AC97_PCI_SVID, 7, 1, 0), AC97_ENUM("ALC NG Type", wm9713_enum[13]), AC97_SINGLE("ALC NG Threshold", AC97_PCI_SVID, 0, 31, 0), AC97_DOUBLE("Master ZC Switch", AC97_MASTER, 14, 6, 1, 0), AC97_DOUBLE("Headphone ZC Switch", AC97_HEADPHONE, 14, 6, 1, 0), AC97_DOUBLE("Out3/4 ZC Switch", AC97_MASTER_MONO, 14, 6, 1, 0), AC97_SINGLE("Master Right Switch", AC97_MASTER, 7, 1, 1), AC97_SINGLE("Headphone Right Switch", AC97_HEADPHONE, 7, 1, 1), AC97_SINGLE("Out3/4 Right Switch", AC97_MASTER_MONO, 7, 1, 1), AC97_SINGLE("Mono In to Headphone Switch", AC97_MASTER_TONE, 15, 1, 1), AC97_SINGLE("Mono In to Master Switch", AC97_MASTER_TONE, 14, 1, 1), AC97_SINGLE("Mono In Volume", AC97_MASTER_TONE, 8, 31, 1), AC97_SINGLE("Mono Switch", AC97_MASTER_TONE, 7, 1, 1), AC97_SINGLE("Mono ZC Switch", AC97_MASTER_TONE, 6, 1, 0), AC97_SINGLE("Mono Volume", AC97_MASTER_TONE, 0, 31, 1), AC97_SINGLE("Beep to Headphone Switch", AC97_AUX, 15, 1, 1), AC97_SINGLE("Beep to Headphone Volume", AC97_AUX, 12, 7, 1), AC97_SINGLE("Beep to Master Switch", AC97_AUX, 11, 1, 1), AC97_SINGLE("Beep to Master Volume", AC97_AUX, 8, 7, 1), AC97_SINGLE("Beep to Mono Switch", AC97_AUX, 7, 1, 1), AC97_SINGLE("Beep to Mono Volume", AC97_AUX, 4, 7, 1), AC97_SINGLE("Voice to Headphone Switch", AC97_PCM, 15, 1, 1), AC97_SINGLE("Voice to Headphone Volume", AC97_PCM, 12, 7, 1), AC97_SINGLE("Voice to Master Switch", AC97_PCM, 11, 1, 1), AC97_SINGLE("Voice to Master Volume", AC97_PCM, 8, 7, 1), AC97_SINGLE("Voice to Mono Switch", AC97_PCM, 7, 1, 1), AC97_SINGLE("Voice to Mono Volume", AC97_PCM, 4, 7, 1), AC97_SINGLE("Aux to Headphone Switch", AC97_REC_SEL, 15, 1, 1), AC97_SINGLE("Aux to Headphone Volume", AC97_REC_SEL, 12, 7, 1), AC97_SINGLE("Aux to Master Switch", AC97_REC_SEL, 11, 1, 1), AC97_SINGLE("Aux to Master Volume", AC97_REC_SEL, 8, 7, 1), AC97_SINGLE("Aux to Mono Switch", AC97_REC_SEL, 7, 1, 1), AC97_SINGLE("Aux to Mono Volume", AC97_REC_SEL, 4, 7, 1), AC97_ENUM("Mono Input Mux", wm9713_enum[6]), AC97_ENUM("Master Input Mux", wm9713_enum[7]), AC97_ENUM("Headphone Input Mux", wm9713_enum[8]), AC97_ENUM("Out 3 Input Mux", wm9713_enum[9]), AC97_ENUM("Out 4 Input Mux", wm9713_enum[10]), AC97_ENUM("Bass Control", wm9713_enum[12]), AC97_SINGLE("Bass Cut-off Switch", AC97_GENERAL_PURPOSE, 12, 1, 1), AC97_SINGLE("Tone Cut-off Switch", AC97_GENERAL_PURPOSE, 4, 1, 1), AC97_SINGLE("Playback Attenuate (-6dB) Switch", AC97_GENERAL_PURPOSE, 6, 1, 0), AC97_SINGLE("Bass Volume", AC97_GENERAL_PURPOSE, 8, 15, 1), AC97_SINGLE("Tone Volume", AC97_GENERAL_PURPOSE, 0, 15, 1), }; static const struct snd_kcontrol_new wm13_snd_ac97_controls_3d[] = { AC97_ENUM("Inv Input Mux", wm9713_enum[11]), AC97_SINGLE("3D Upper Cut-off Switch", AC97_REC_GAIN_MIC, 5, 1, 0), AC97_SINGLE("3D Lower Cut-off Switch", AC97_REC_GAIN_MIC, 4, 1, 0), AC97_SINGLE("3D Depth", AC97_REC_GAIN_MIC, 0, 15, 1), }; static int patch_wolfson_wm9713_3d (struct snd_ac97 * ac97) { int err, i; for (i = 0; i < ARRAY_SIZE(wm13_snd_ac97_controls_3d); i++) { if ((err = snd_ctl_add(ac97->bus->card, snd_ac97_cnew(&wm13_snd_ac97_controls_3d[i], ac97))) < 0) return err; } return 0; } static int patch_wolfson_wm9713_specific(struct snd_ac97 * ac97) { int err, i; for (i = 0; i < ARRAY_SIZE(wm13_snd_ac97_controls); i++) { if ((err = snd_ctl_add(ac97->bus->card, snd_ac97_cnew(&wm13_snd_ac97_controls[i], ac97))) < 0) return err; } snd_ac97_write_cache(ac97, AC97_PC_BEEP, 0x0808); snd_ac97_write_cache(ac97, AC97_PHONE, 0x0808); snd_ac97_write_cache(ac97, AC97_MIC, 0x0808); snd_ac97_write_cache(ac97, AC97_LINE, 0x00da); snd_ac97_write_cache(ac97, AC97_CD, 0x0808); snd_ac97_write_cache(ac97, AC97_VIDEO, 0xd612); snd_ac97_write_cache(ac97, AC97_REC_GAIN, 0x1ba0); return 0; } #ifdef CONFIG_PM static void patch_wolfson_wm9713_suspend (struct snd_ac97 * ac97) { snd_ac97_write_cache(ac97, AC97_EXTENDED_MID, 0xfeff); snd_ac97_write_cache(ac97, AC97_EXTENDED_MSTATUS, 0xffff); } static void patch_wolfson_wm9713_resume (struct snd_ac97 * ac97) { snd_ac97_write_cache(ac97, AC97_EXTENDED_MID, 0xda00); snd_ac97_write_cache(ac97, AC97_EXTENDED_MSTATUS, 0x3810); snd_ac97_write_cache(ac97, AC97_POWERDOWN, 0x0); } #endif static const struct snd_ac97_build_ops patch_wolfson_wm9713_ops = { .build_specific = patch_wolfson_wm9713_specific, .build_3d = patch_wolfson_wm9713_3d, #ifdef CONFIG_PM .suspend = patch_wolfson_wm9713_suspend, .resume = patch_wolfson_wm9713_resume #endif }; static int patch_wolfson13(struct snd_ac97 * ac97) { /* WM9713, WM9714 */ ac97->build_ops = &patch_wolfson_wm9713_ops; ac97->flags |= AC97_HAS_NO_REC_GAIN | AC97_STEREO_MUTES | AC97_HAS_NO_PHONE | AC97_HAS_NO_PC_BEEP | AC97_HAS_NO_VIDEO | AC97_HAS_NO_CD | AC97_HAS_NO_TONE | AC97_HAS_NO_STD_PCM; ac97->scaps &= ~AC97_SCAP_MODEM; snd_ac97_write_cache(ac97, AC97_EXTENDED_MID, 0xda00); snd_ac97_write_cache(ac97, AC97_EXTENDED_MSTATUS, 0x3810); snd_ac97_write_cache(ac97, AC97_POWERDOWN, 0x0); return 0; } /* * Tritech codec */ static int patch_tritech_tr28028(struct snd_ac97 * ac97) { snd_ac97_write_cache(ac97, 0x26, 0x0300); snd_ac97_write_cache(ac97, 0x26, 0x0000); snd_ac97_write_cache(ac97, AC97_SURROUND_MASTER, 0x0000); snd_ac97_write_cache(ac97, AC97_SPDIF, 0x0000); return 0; } /* * Sigmatel STAC97xx codecs */ static int patch_sigmatel_stac9700_3d(struct snd_ac97 * ac97) { struct snd_kcontrol *kctl; int err; if ((err = snd_ctl_add(ac97->bus->card, kctl = snd_ac97_cnew(&snd_ac97_controls_3d[0], ac97))) < 0) return err; strcpy(kctl->id.name, "3D Control Sigmatel - Depth"); kctl->private_value = AC97_SINGLE_VALUE(AC97_3D_CONTROL, 2, 3, 0); snd_ac97_write_cache(ac97, AC97_3D_CONTROL, 0x0000); return 0; } static int patch_sigmatel_stac9708_3d(struct snd_ac97 * ac97) { struct snd_kcontrol *kctl; int err; if ((err = snd_ctl_add(ac97->bus->card, kctl = snd_ac97_cnew(&snd_ac97_controls_3d[0], ac97))) < 0) return err; strcpy(kctl->id.name, "3D Control Sigmatel - Depth"); kctl->private_value = AC97_SINGLE_VALUE(AC97_3D_CONTROL, 0, 3, 0); if ((err = snd_ctl_add(ac97->bus->card, kctl = snd_ac97_cnew(&snd_ac97_controls_3d[0], ac97))) < 0) return err; strcpy(kctl->id.name, "3D Control Sigmatel - Rear Depth"); kctl->private_value = AC97_SINGLE_VALUE(AC97_3D_CONTROL, 2, 3, 0); snd_ac97_write_cache(ac97, AC97_3D_CONTROL, 0x0000); return 0; } static const struct snd_kcontrol_new snd_ac97_sigmatel_4speaker = AC97_SINGLE("Sigmatel 4-Speaker Stereo Playback Switch", AC97_SIGMATEL_DAC2INVERT, 2, 1, 0); /* "Sigmatel " removed due to excessive name length: */ static const struct snd_kcontrol_new snd_ac97_sigmatel_phaseinvert = AC97_SINGLE("Surround Phase Inversion Playback Switch", AC97_SIGMATEL_DAC2INVERT, 3, 1, 0); static const struct snd_kcontrol_new snd_ac97_sigmatel_controls[] = { AC97_SINGLE("Sigmatel DAC 6dB Attenuate", AC97_SIGMATEL_ANALOG, 1, 1, 0), AC97_SINGLE("Sigmatel ADC 6dB Attenuate", AC97_SIGMATEL_ANALOG, 0, 1, 0) }; static int patch_sigmatel_stac97xx_specific(struct snd_ac97 * ac97) { int err; snd_ac97_write_cache(ac97, AC97_SIGMATEL_ANALOG, snd_ac97_read(ac97, AC97_SIGMATEL_ANALOG) & ~0x0003); if (snd_ac97_try_bit(ac97, AC97_SIGMATEL_ANALOG, 1)) if ((err = patch_build_controls(ac97, &snd_ac97_sigmatel_controls[0], 1)) < 0) return err; if (snd_ac97_try_bit(ac97, AC97_SIGMATEL_ANALOG, 0)) if ((err = patch_build_controls(ac97, &snd_ac97_sigmatel_controls[1], 1)) < 0) return err; if (snd_ac97_try_bit(ac97, AC97_SIGMATEL_DAC2INVERT, 2)) if ((err = patch_build_controls(ac97, &snd_ac97_sigmatel_4speaker, 1)) < 0) return err; if (snd_ac97_try_bit(ac97, AC97_SIGMATEL_DAC2INVERT, 3)) if ((err = patch_build_controls(ac97, &snd_ac97_sigmatel_phaseinvert, 1)) < 0) return err; return 0; } static const struct snd_ac97_build_ops patch_sigmatel_stac9700_ops = { .build_3d = patch_sigmatel_stac9700_3d, .build_specific = patch_sigmatel_stac97xx_specific }; static int patch_sigmatel_stac9700(struct snd_ac97 * ac97) { ac97->build_ops = &patch_sigmatel_stac9700_ops; return 0; } static int snd_ac97_stac9708_put_bias(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); int err; mutex_lock(&ac97->page_mutex); snd_ac97_write(ac97, AC97_SIGMATEL_BIAS1, 0xabba); err = snd_ac97_update_bits(ac97, AC97_SIGMATEL_BIAS2, 0x0010, (ucontrol->value.integer.value[0] & 1) << 4); snd_ac97_write(ac97, AC97_SIGMATEL_BIAS1, 0); mutex_unlock(&ac97->page_mutex); return err; } static const struct snd_kcontrol_new snd_ac97_stac9708_bias_control = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Sigmatel Output Bias Switch", .info = snd_ac97_info_volsw, .get = snd_ac97_get_volsw, .put = snd_ac97_stac9708_put_bias, .private_value = AC97_SINGLE_VALUE(AC97_SIGMATEL_BIAS2, 4, 1, 0), }; static int patch_sigmatel_stac9708_specific(struct snd_ac97 *ac97) { int err; /* the register bit is writable, but the function is not implemented: */ snd_ac97_remove_ctl(ac97, "PCM Out Path & Mute", NULL); snd_ac97_rename_vol_ctl(ac97, "Headphone Playback", "Sigmatel Surround Playback"); if ((err = patch_build_controls(ac97, &snd_ac97_stac9708_bias_control, 1)) < 0) return err; return patch_sigmatel_stac97xx_specific(ac97); } static const struct snd_ac97_build_ops patch_sigmatel_stac9708_ops = { .build_3d = patch_sigmatel_stac9708_3d, .build_specific = patch_sigmatel_stac9708_specific }; static int patch_sigmatel_stac9708(struct snd_ac97 * ac97) { unsigned int codec72, codec6c; ac97->build_ops = &patch_sigmatel_stac9708_ops; ac97->caps |= 0x10; /* HP (sigmatel surround) support */ codec72 = snd_ac97_read(ac97, AC97_SIGMATEL_BIAS2) & 0x8000; codec6c = snd_ac97_read(ac97, AC97_SIGMATEL_ANALOG); if ((codec72==0) && (codec6c==0)) { snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC1, 0xabba); snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC2, 0x1000); snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS1, 0xabba); snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS2, 0x0007); } else if ((codec72==0x8000) && (codec6c==0)) { snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC1, 0xabba); snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC2, 0x1001); snd_ac97_write_cache(ac97, AC97_SIGMATEL_DAC2INVERT, 0x0008); } else if ((codec72==0x8000) && (codec6c==0x0080)) { /* nothing */ } snd_ac97_write_cache(ac97, AC97_SIGMATEL_MULTICHN, 0x0000); return 0; } static int patch_sigmatel_stac9721(struct snd_ac97 * ac97) { ac97->build_ops = &patch_sigmatel_stac9700_ops; if (snd_ac97_read(ac97, AC97_SIGMATEL_ANALOG) == 0) { // patch for SigmaTel snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC1, 0xabba); snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC2, 0x4000); snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS1, 0xabba); snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS2, 0x0002); } snd_ac97_write_cache(ac97, AC97_SIGMATEL_MULTICHN, 0x0000); return 0; } static int patch_sigmatel_stac9744(struct snd_ac97 * ac97) { // patch for SigmaTel ac97->build_ops = &patch_sigmatel_stac9700_ops; snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC1, 0xabba); snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC2, 0x0000); /* is this correct? --jk */ snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS1, 0xabba); snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS2, 0x0002); snd_ac97_write_cache(ac97, AC97_SIGMATEL_MULTICHN, 0x0000); return 0; } static int patch_sigmatel_stac9756(struct snd_ac97 * ac97) { // patch for SigmaTel ac97->build_ops = &patch_sigmatel_stac9700_ops; snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC1, 0xabba); snd_ac97_write_cache(ac97, AC97_SIGMATEL_CIC2, 0x0000); /* is this correct? --jk */ snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS1, 0xabba); snd_ac97_write_cache(ac97, AC97_SIGMATEL_BIAS2, 0x0002); snd_ac97_write_cache(ac97, AC97_SIGMATEL_MULTICHN, 0x0000); return 0; } static int snd_ac97_stac9758_output_jack_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[5] = { "Input/Disabled", "Front Output", "Rear Output", "Center/LFE Output", "Mixer Output" }; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 5; if (uinfo->value.enumerated.item > 4) uinfo->value.enumerated.item = 4; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_ac97_stac9758_output_jack_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); int shift = kcontrol->private_value; unsigned short val; val = ac97->regs[AC97_SIGMATEL_OUTSEL] >> shift; if (!(val & 4)) ucontrol->value.enumerated.item[0] = 0; else ucontrol->value.enumerated.item[0] = 1 + (val & 3); return 0; } static int snd_ac97_stac9758_output_jack_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); int shift = kcontrol->private_value; unsigned short val; if (ucontrol->value.enumerated.item[0] > 4) return -EINVAL; if (ucontrol->value.enumerated.item[0] == 0) val = 0; else val = 4 | (ucontrol->value.enumerated.item[0] - 1); return ac97_update_bits_page(ac97, AC97_SIGMATEL_OUTSEL, 7 << shift, val << shift, 0); } static int snd_ac97_stac9758_input_jack_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[7] = { "Mic2 Jack", "Mic1 Jack", "Line In Jack", "Front Jack", "Rear Jack", "Center/LFE Jack", "Mute" }; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 7; if (uinfo->value.enumerated.item > 6) uinfo->value.enumerated.item = 6; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_ac97_stac9758_input_jack_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); int shift = kcontrol->private_value; unsigned short val; val = ac97->regs[AC97_SIGMATEL_INSEL]; ucontrol->value.enumerated.item[0] = (val >> shift) & 7; return 0; } static int snd_ac97_stac9758_input_jack_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); int shift = kcontrol->private_value; return ac97_update_bits_page(ac97, AC97_SIGMATEL_INSEL, 7 << shift, ucontrol->value.enumerated.item[0] << shift, 0); } static int snd_ac97_stac9758_phonesel_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[3] = { "None", "Front Jack", "Rear Jack" }; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 3; if (uinfo->value.enumerated.item > 2) uinfo->value.enumerated.item = 2; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_ac97_stac9758_phonesel_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); ucontrol->value.enumerated.item[0] = ac97->regs[AC97_SIGMATEL_IOMISC] & 3; return 0; } static int snd_ac97_stac9758_phonesel_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); return ac97_update_bits_page(ac97, AC97_SIGMATEL_IOMISC, 3, ucontrol->value.enumerated.item[0], 0); } #define STAC9758_OUTPUT_JACK(xname, shift) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \ .info = snd_ac97_stac9758_output_jack_info, \ .get = snd_ac97_stac9758_output_jack_get, \ .put = snd_ac97_stac9758_output_jack_put, \ .private_value = shift } #define STAC9758_INPUT_JACK(xname, shift) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \ .info = snd_ac97_stac9758_input_jack_info, \ .get = snd_ac97_stac9758_input_jack_get, \ .put = snd_ac97_stac9758_input_jack_put, \ .private_value = shift } static const struct snd_kcontrol_new snd_ac97_sigmatel_stac9758_controls[] = { STAC9758_OUTPUT_JACK("Mic1 Jack", 1), STAC9758_OUTPUT_JACK("LineIn Jack", 4), STAC9758_OUTPUT_JACK("Front Jack", 7), STAC9758_OUTPUT_JACK("Rear Jack", 10), STAC9758_OUTPUT_JACK("Center/LFE Jack", 13), STAC9758_INPUT_JACK("Mic Input Source", 0), STAC9758_INPUT_JACK("Line Input Source", 8), { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Headphone Amp", .info = snd_ac97_stac9758_phonesel_info, .get = snd_ac97_stac9758_phonesel_get, .put = snd_ac97_stac9758_phonesel_put }, AC97_SINGLE("Exchange Center/LFE", AC97_SIGMATEL_IOMISC, 4, 1, 0), AC97_SINGLE("Headphone +3dB Boost", AC97_SIGMATEL_IOMISC, 8, 1, 0) }; static int patch_sigmatel_stac9758_specific(struct snd_ac97 *ac97) { int err; err = patch_sigmatel_stac97xx_specific(ac97); if (err < 0) return err; err = patch_build_controls(ac97, snd_ac97_sigmatel_stac9758_controls, ARRAY_SIZE(snd_ac97_sigmatel_stac9758_controls)); if (err < 0) return err; /* DAC-A direct */ snd_ac97_rename_vol_ctl(ac97, "Headphone Playback", "Front Playback"); /* DAC-A to Mix = PCM */ /* DAC-B direct = Surround */ /* DAC-B to Mix */ snd_ac97_rename_vol_ctl(ac97, "Video Playback", "Surround Mix Playback"); /* DAC-C direct = Center/LFE */ return 0; } static const struct snd_ac97_build_ops patch_sigmatel_stac9758_ops = { .build_3d = patch_sigmatel_stac9700_3d, .build_specific = patch_sigmatel_stac9758_specific }; static int patch_sigmatel_stac9758(struct snd_ac97 * ac97) { static unsigned short regs[4] = { AC97_SIGMATEL_OUTSEL, AC97_SIGMATEL_IOMISC, AC97_SIGMATEL_INSEL, AC97_SIGMATEL_VARIOUS }; static unsigned short def_regs[4] = { /* OUTSEL */ 0xd794, /* CL:CL, SR:SR, LO:MX, LI:DS, MI:DS */ /* IOMISC */ 0x2001, /* INSEL */ 0x0201, /* LI:LI, MI:M1 */ /* VARIOUS */ 0x0040 }; static unsigned short m675_regs[4] = { /* OUTSEL */ 0xfc70, /* CL:MX, SR:MX, LO:DS, LI:MX, MI:DS */ /* IOMISC */ 0x2102, /* HP amp on */ /* INSEL */ 0x0203, /* LI:LI, MI:FR */ /* VARIOUS */ 0x0041 /* stereo mic */ }; unsigned short *pregs = def_regs; int i; /* Gateway M675 notebook */ if (ac97->pci && ac97->subsystem_vendor == 0x107b && ac97->subsystem_device == 0x0601) pregs = m675_regs; // patch for SigmaTel ac97->build_ops = &patch_sigmatel_stac9758_ops; /* FIXME: assume only page 0 for writing cache */ snd_ac97_update_bits(ac97, AC97_INT_PAGING, AC97_PAGE_MASK, AC97_PAGE_VENDOR); for (i = 0; i < 4; i++) snd_ac97_write_cache(ac97, regs[i], pregs[i]); ac97->flags |= AC97_STEREO_MUTES; return 0; } /* * Cirrus Logic CS42xx codecs */ static const struct snd_kcontrol_new snd_ac97_cirrus_controls_spdif[2] = { AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",PLAYBACK,SWITCH), AC97_CSR_SPDIF, 15, 1, 0), AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "AC97-SPSA", AC97_CSR_ACMODE, 0, 3, 0) }; static int patch_cirrus_build_spdif(struct snd_ac97 * ac97) { int err; /* con mask, pro mask, default */ if ((err = patch_build_controls(ac97, &snd_ac97_controls_spdif[0], 3)) < 0) return err; /* switch, spsa */ if ((err = patch_build_controls(ac97, &snd_ac97_cirrus_controls_spdif[0], 1)) < 0) return err; switch (ac97->id & AC97_ID_CS_MASK) { case AC97_ID_CS4205: if ((err = patch_build_controls(ac97, &snd_ac97_cirrus_controls_spdif[1], 1)) < 0) return err; break; } /* set default PCM S/PDIF params */ /* consumer,PCM audio,no copyright,no preemphasis,PCM coder,original,48000Hz */ snd_ac97_write_cache(ac97, AC97_CSR_SPDIF, 0x0a20); return 0; } static const struct snd_ac97_build_ops patch_cirrus_ops = { .build_spdif = patch_cirrus_build_spdif }; static int patch_cirrus_spdif(struct snd_ac97 * ac97) { /* Basically, the cs4201/cs4205/cs4297a has non-standard sp/dif registers. WHY CAN'T ANYONE FOLLOW THE BLOODY SPEC? *sigh* - sp/dif EA ID is not set, but sp/dif is always present. - enable/disable is spdif register bit 15. - sp/dif control register is 0x68. differs from AC97: - valid is bit 14 (vs 15) - no DRS - only 44.1/48k [00 = 48, 01=44,1] (AC97 is 00=44.1, 10=48) - sp/dif ssource select is in 0x5e bits 0,1. */ ac97->build_ops = &patch_cirrus_ops; ac97->flags |= AC97_CS_SPDIF; ac97->rates[AC97_RATES_SPDIF] &= ~SNDRV_PCM_RATE_32000; ac97->ext_id |= AC97_EI_SPDIF; /* force the detection of spdif */ snd_ac97_write_cache(ac97, AC97_CSR_ACMODE, 0x0080); return 0; } static int patch_cirrus_cs4299(struct snd_ac97 * ac97) { /* force the detection of PC Beep */ ac97->flags |= AC97_HAS_PC_BEEP; return patch_cirrus_spdif(ac97); } /* * Conexant codecs */ static const struct snd_kcontrol_new snd_ac97_conexant_controls_spdif[1] = { AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",PLAYBACK,SWITCH), AC97_CXR_AUDIO_MISC, 3, 1, 0), }; static int patch_conexant_build_spdif(struct snd_ac97 * ac97) { int err; /* con mask, pro mask, default */ if ((err = patch_build_controls(ac97, &snd_ac97_controls_spdif[0], 3)) < 0) return err; /* switch */ if ((err = patch_build_controls(ac97, &snd_ac97_conexant_controls_spdif[0], 1)) < 0) return err; /* set default PCM S/PDIF params */ /* consumer,PCM audio,no copyright,no preemphasis,PCM coder,original,48000Hz */ snd_ac97_write_cache(ac97, AC97_CXR_AUDIO_MISC, snd_ac97_read(ac97, AC97_CXR_AUDIO_MISC) & ~(AC97_CXR_SPDIFEN|AC97_CXR_COPYRGT|AC97_CXR_SPDIF_MASK)); return 0; } static const struct snd_ac97_build_ops patch_conexant_ops = { .build_spdif = patch_conexant_build_spdif }; static int patch_conexant(struct snd_ac97 * ac97) { ac97->build_ops = &patch_conexant_ops; ac97->flags |= AC97_CX_SPDIF; ac97->ext_id |= AC97_EI_SPDIF; /* force the detection of spdif */ ac97->rates[AC97_RATES_SPDIF] = SNDRV_PCM_RATE_48000; /* 48k only */ return 0; } static int patch_cx20551(struct snd_ac97 *ac97) { snd_ac97_update_bits(ac97, 0x5c, 0x01, 0x01); return 0; } /* * Analog Device AD18xx, AD19xx codecs */ #ifdef CONFIG_PM static void ad18xx_resume(struct snd_ac97 *ac97) { static unsigned short setup_regs[] = { AC97_AD_MISC, AC97_AD_SERIAL_CFG, AC97_AD_JACK_SPDIF, }; int i, codec; for (i = 0; i < (int)ARRAY_SIZE(setup_regs); i++) { unsigned short reg = setup_regs[i]; if (test_bit(reg, ac97->reg_accessed)) { snd_ac97_write(ac97, reg, ac97->regs[reg]); snd_ac97_read(ac97, reg); } } if (! (ac97->flags & AC97_AD_MULTI)) /* normal restore */ snd_ac97_restore_status(ac97); else { /* restore the AD18xx codec configurations */ for (codec = 0; codec < 3; codec++) { if (! ac97->spec.ad18xx.id[codec]) continue; /* select single codec */ snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, ac97->spec.ad18xx.unchained[codec] | ac97->spec.ad18xx.chained[codec]); ac97->bus->ops->write(ac97, AC97_AD_CODEC_CFG, ac97->spec.ad18xx.codec_cfg[codec]); } /* select all codecs */ snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, 0x7000); /* restore status */ for (i = 2; i < 0x7c ; i += 2) { if (i == AC97_POWERDOWN || i == AC97_EXTENDED_ID) continue; if (test_bit(i, ac97->reg_accessed)) { /* handle multi codecs for AD18xx */ if (i == AC97_PCM) { for (codec = 0; codec < 3; codec++) { if (! ac97->spec.ad18xx.id[codec]) continue; /* select single codec */ snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, ac97->spec.ad18xx.unchained[codec] | ac97->spec.ad18xx.chained[codec]); /* update PCM bits */ ac97->bus->ops->write(ac97, AC97_PCM, ac97->spec.ad18xx.pcmreg[codec]); } /* select all codecs */ snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, 0x7000); continue; } else if (i == AC97_AD_TEST || i == AC97_AD_CODEC_CFG || i == AC97_AD_SERIAL_CFG) continue; /* ignore */ } snd_ac97_write(ac97, i, ac97->regs[i]); snd_ac97_read(ac97, i); } } snd_ac97_restore_iec958(ac97); } static void ad1888_resume(struct snd_ac97 *ac97) { ad18xx_resume(ac97); snd_ac97_write_cache(ac97, AC97_CODEC_CLASS_REV, 0x8080); } #endif static const struct snd_ac97_res_table ad1819_restbl[] = { { AC97_PHONE, 0x9f1f }, { AC97_MIC, 0x9f1f }, { AC97_LINE, 0x9f1f }, { AC97_CD, 0x9f1f }, { AC97_VIDEO, 0x9f1f }, { AC97_AUX, 0x9f1f }, { AC97_PCM, 0x9f1f }, { } /* terminator */ }; static int patch_ad1819(struct snd_ac97 * ac97) { unsigned short scfg; // patch for Analog Devices scfg = snd_ac97_read(ac97, AC97_AD_SERIAL_CFG); snd_ac97_write_cache(ac97, AC97_AD_SERIAL_CFG, scfg | 0x7000); /* select all codecs */ ac97->res_table = ad1819_restbl; return 0; } static unsigned short patch_ad1881_unchained(struct snd_ac97 * ac97, int idx, unsigned short mask) { unsigned short val; // test for unchained codec snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, mask); snd_ac97_write_cache(ac97, AC97_AD_CODEC_CFG, 0x0000); /* ID0C, ID1C, SDIE = off */ val = snd_ac97_read(ac97, AC97_VENDOR_ID2); if ((val & 0xff40) != 0x5340) return 0; ac97->spec.ad18xx.unchained[idx] = mask; ac97->spec.ad18xx.id[idx] = val; ac97->spec.ad18xx.codec_cfg[idx] = 0x0000; return mask; } static int patch_ad1881_chained1(struct snd_ac97 * ac97, int idx, unsigned short codec_bits) { static int cfg_bits[3] = { 1<<12, 1<<14, 1<<13 }; unsigned short val; snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, cfg_bits[idx]); snd_ac97_write_cache(ac97, AC97_AD_CODEC_CFG, 0x0004); // SDIE val = snd_ac97_read(ac97, AC97_VENDOR_ID2); if ((val & 0xff40) != 0x5340) return 0; if (codec_bits) snd_ac97_write_cache(ac97, AC97_AD_CODEC_CFG, codec_bits); ac97->spec.ad18xx.chained[idx] = cfg_bits[idx]; ac97->spec.ad18xx.id[idx] = val; ac97->spec.ad18xx.codec_cfg[idx] = codec_bits ? codec_bits : 0x0004; return 1; } static void patch_ad1881_chained(struct snd_ac97 * ac97, int unchained_idx, int cidx1, int cidx2) { // already detected? if (ac97->spec.ad18xx.unchained[cidx1] || ac97->spec.ad18xx.chained[cidx1]) cidx1 = -1; if (ac97->spec.ad18xx.unchained[cidx2] || ac97->spec.ad18xx.chained[cidx2]) cidx2 = -1; if (cidx1 < 0 && cidx2 < 0) return; // test for chained codecs snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, ac97->spec.ad18xx.unchained[unchained_idx]); snd_ac97_write_cache(ac97, AC97_AD_CODEC_CFG, 0x0002); // ID1C ac97->spec.ad18xx.codec_cfg[unchained_idx] = 0x0002; if (cidx1 >= 0) { if (cidx2 < 0) patch_ad1881_chained1(ac97, cidx1, 0); else if (patch_ad1881_chained1(ac97, cidx1, 0x0006)) // SDIE | ID1C patch_ad1881_chained1(ac97, cidx2, 0); else if (patch_ad1881_chained1(ac97, cidx2, 0x0006)) // SDIE | ID1C patch_ad1881_chained1(ac97, cidx1, 0); } else if (cidx2 >= 0) { patch_ad1881_chained1(ac97, cidx2, 0); } } static const struct snd_ac97_build_ops patch_ad1881_build_ops = { #ifdef CONFIG_PM .resume = ad18xx_resume #endif }; static int patch_ad1881(struct snd_ac97 * ac97) { static const char cfg_idxs[3][2] = { {2, 1}, {0, 2}, {0, 1} }; // patch for Analog Devices unsigned short codecs[3]; unsigned short val; int idx, num; val = snd_ac97_read(ac97, AC97_AD_SERIAL_CFG); snd_ac97_write_cache(ac97, AC97_AD_SERIAL_CFG, val); codecs[0] = patch_ad1881_unchained(ac97, 0, (1<<12)); codecs[1] = patch_ad1881_unchained(ac97, 1, (1<<14)); codecs[2] = patch_ad1881_unchained(ac97, 2, (1<<13)); if (! (codecs[0] || codecs[1] || codecs[2])) goto __end; for (idx = 0; idx < 3; idx++) if (ac97->spec.ad18xx.unchained[idx]) patch_ad1881_chained(ac97, idx, cfg_idxs[idx][0], cfg_idxs[idx][1]); if (ac97->spec.ad18xx.id[1]) { ac97->flags |= AC97_AD_MULTI; ac97->scaps |= AC97_SCAP_SURROUND_DAC; } if (ac97->spec.ad18xx.id[2]) { ac97->flags |= AC97_AD_MULTI; ac97->scaps |= AC97_SCAP_CENTER_LFE_DAC; } __end: /* select all codecs */ snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, 0x7000); /* check if only one codec is present */ for (idx = num = 0; idx < 3; idx++) if (ac97->spec.ad18xx.id[idx]) num++; if (num == 1) { /* ok, deselect all ID bits */ snd_ac97_write_cache(ac97, AC97_AD_CODEC_CFG, 0x0000); ac97->spec.ad18xx.codec_cfg[0] = ac97->spec.ad18xx.codec_cfg[1] = ac97->spec.ad18xx.codec_cfg[2] = 0x0000; } /* required for AD1886/AD1885 combination */ ac97->ext_id = snd_ac97_read(ac97, AC97_EXTENDED_ID); if (ac97->spec.ad18xx.id[0]) { ac97->id &= 0xffff0000; ac97->id |= ac97->spec.ad18xx.id[0]; } ac97->build_ops = &patch_ad1881_build_ops; return 0; } static const struct snd_kcontrol_new snd_ac97_controls_ad1885[] = { AC97_SINGLE("Digital Mono Direct", AC97_AD_MISC, 11, 1, 0), /* AC97_SINGLE("Digital Audio Mode", AC97_AD_MISC, 12, 1, 0), */ /* seems problematic */ AC97_SINGLE("Low Power Mixer", AC97_AD_MISC, 14, 1, 0), AC97_SINGLE("Zero Fill DAC", AC97_AD_MISC, 15, 1, 0), AC97_SINGLE("Headphone Jack Sense", AC97_AD_JACK_SPDIF, 9, 1, 1), /* inverted */ AC97_SINGLE("Line Jack Sense", AC97_AD_JACK_SPDIF, 8, 1, 1), /* inverted */ }; static const DECLARE_TLV_DB_SCALE(db_scale_6bit_6db_max, -8850, 150, 0); static int patch_ad1885_specific(struct snd_ac97 * ac97) { int err; if ((err = patch_build_controls(ac97, snd_ac97_controls_ad1885, ARRAY_SIZE(snd_ac97_controls_ad1885))) < 0) return err; reset_tlv(ac97, "Headphone Playback Volume", db_scale_6bit_6db_max); return 0; } static const struct snd_ac97_build_ops patch_ad1885_build_ops = { .build_specific = &patch_ad1885_specific, #ifdef CONFIG_PM .resume = ad18xx_resume #endif }; static int patch_ad1885(struct snd_ac97 * ac97) { patch_ad1881(ac97); /* This is required to deal with the Intel D815EEAL2 */ /* i.e. Line out is actually headphone out from codec */ /* set default */ snd_ac97_write_cache(ac97, AC97_AD_MISC, 0x0404); ac97->build_ops = &patch_ad1885_build_ops; return 0; } static int patch_ad1886_specific(struct snd_ac97 * ac97) { reset_tlv(ac97, "Headphone Playback Volume", db_scale_6bit_6db_max); return 0; } static const struct snd_ac97_build_ops patch_ad1886_build_ops = { .build_specific = &patch_ad1886_specific, #ifdef CONFIG_PM .resume = ad18xx_resume #endif }; static int patch_ad1886(struct snd_ac97 * ac97) { patch_ad1881(ac97); /* Presario700 workaround */ /* for Jack Sense/SPDIF Register misetting causing */ snd_ac97_write_cache(ac97, AC97_AD_JACK_SPDIF, 0x0010); ac97->build_ops = &patch_ad1886_build_ops; return 0; } /* MISC bits (AD1888/AD1980/AD1985 register 0x76) */ #define AC97_AD198X_MBC 0x0003 /* mic boost */ #define AC97_AD198X_MBC_20 0x0000 /* +20dB */ #define AC97_AD198X_MBC_10 0x0001 /* +10dB */ #define AC97_AD198X_MBC_30 0x0002 /* +30dB */ #define AC97_AD198X_VREFD 0x0004 /* VREF high-Z */ #define AC97_AD198X_VREFH 0x0008 /* 0=2.25V, 1=3.7V */ #define AC97_AD198X_VREF_0 0x000c /* 0V (AD1985 only) */ #define AC97_AD198X_VREF_MASK (AC97_AD198X_VREFH | AC97_AD198X_VREFD) #define AC97_AD198X_VREF_SHIFT 2 #define AC97_AD198X_SRU 0x0010 /* sample rate unlock */ #define AC97_AD198X_LOSEL 0x0020 /* LINE_OUT amplifiers input select */ #define AC97_AD198X_2MIC 0x0040 /* 2-channel mic select */ #define AC97_AD198X_SPRD 0x0080 /* SPREAD enable */ #define AC97_AD198X_DMIX0 0x0100 /* downmix mode: */ /* 0 = 6-to-4, 1 = 6-to-2 downmix */ #define AC97_AD198X_DMIX1 0x0200 /* downmix mode: 1 = enabled */ #define AC97_AD198X_HPSEL 0x0400 /* headphone amplifier input select */ #define AC97_AD198X_CLDIS 0x0800 /* center/lfe disable */ #define AC97_AD198X_LODIS 0x1000 /* LINE_OUT disable */ #define AC97_AD198X_MSPLT 0x2000 /* mute split */ #define AC97_AD198X_AC97NC 0x4000 /* AC97 no compatible mode */ #define AC97_AD198X_DACZ 0x8000 /* DAC zero-fill mode */ /* MISC 1 bits (AD1986 register 0x76) */ #define AC97_AD1986_MBC 0x0003 /* mic boost */ #define AC97_AD1986_MBC_20 0x0000 /* +20dB */ #define AC97_AD1986_MBC_10 0x0001 /* +10dB */ #define AC97_AD1986_MBC_30 0x0002 /* +30dB */ #define AC97_AD1986_LISEL0 0x0004 /* LINE_IN select bit 0 */ #define AC97_AD1986_LISEL1 0x0008 /* LINE_IN select bit 1 */ #define AC97_AD1986_LISEL_MASK (AC97_AD1986_LISEL1 | AC97_AD1986_LISEL0) #define AC97_AD1986_LISEL_LI 0x0000 /* LINE_IN pins as LINE_IN source */ #define AC97_AD1986_LISEL_SURR 0x0004 /* SURROUND pins as LINE_IN source */ #define AC97_AD1986_LISEL_MIC 0x0008 /* MIC_1/2 pins as LINE_IN source */ #define AC97_AD1986_SRU 0x0010 /* sample rate unlock */ #define AC97_AD1986_SOSEL 0x0020 /* SURROUND_OUT amplifiers input sel */ #define AC97_AD1986_2MIC 0x0040 /* 2-channel mic select */ #define AC97_AD1986_SPRD 0x0080 /* SPREAD enable */ #define AC97_AD1986_DMIX0 0x0100 /* downmix mode: */ /* 0 = 6-to-4, 1 = 6-to-2 downmix */ #define AC97_AD1986_DMIX1 0x0200 /* downmix mode: 1 = enabled */ #define AC97_AD1986_CLDIS 0x0800 /* center/lfe disable */ #define AC97_AD1986_SODIS 0x1000 /* SURROUND_OUT disable */ #define AC97_AD1986_MSPLT 0x2000 /* mute split (read only 1) */ #define AC97_AD1986_AC97NC 0x4000 /* AC97 no compatible mode (r/o 1) */ #define AC97_AD1986_DACZ 0x8000 /* DAC zero-fill mode */ /* MISC 2 bits (AD1986 register 0x70) */ #define AC97_AD_MISC2 0x70 /* Misc Control Bits 2 (AD1986) */ #define AC97_AD1986_CVREF0 0x0004 /* C/LFE VREF_OUT 2.25V */ #define AC97_AD1986_CVREF1 0x0008 /* C/LFE VREF_OUT 0V */ #define AC97_AD1986_CVREF2 0x0010 /* C/LFE VREF_OUT 3.7V */ #define AC97_AD1986_CVREF_MASK \ (AC97_AD1986_CVREF2 | AC97_AD1986_CVREF1 | AC97_AD1986_CVREF0) #define AC97_AD1986_JSMAP 0x0020 /* Jack Sense Mapping 1 = alternate */ #define AC97_AD1986_MMDIS 0x0080 /* Mono Mute Disable */ #define AC97_AD1986_MVREF0 0x0400 /* MIC VREF_OUT 2.25V */ #define AC97_AD1986_MVREF1 0x0800 /* MIC VREF_OUT 0V */ #define AC97_AD1986_MVREF2 0x1000 /* MIC VREF_OUT 3.7V */ #define AC97_AD1986_MVREF_MASK \ (AC97_AD1986_MVREF2 | AC97_AD1986_MVREF1 | AC97_AD1986_MVREF0) /* MISC 3 bits (AD1986 register 0x7a) */ #define AC97_AD_MISC3 0x7a /* Misc Control Bits 3 (AD1986) */ #define AC97_AD1986_MMIX 0x0004 /* Mic Mix, left/right */ #define AC97_AD1986_GPO 0x0008 /* General Purpose Out */ #define AC97_AD1986_LOHPEN 0x0010 /* LINE_OUT headphone drive */ #define AC97_AD1986_LVREF0 0x0100 /* LINE_OUT VREF_OUT 2.25V */ #define AC97_AD1986_LVREF1 0x0200 /* LINE_OUT VREF_OUT 0V */ #define AC97_AD1986_LVREF2 0x0400 /* LINE_OUT VREF_OUT 3.7V */ #define AC97_AD1986_LVREF_MASK \ (AC97_AD1986_LVREF2 | AC97_AD1986_LVREF1 | AC97_AD1986_LVREF0) #define AC97_AD1986_JSINVA 0x0800 /* Jack Sense Invert SENSE_A */ #define AC97_AD1986_LOSEL 0x1000 /* LINE_OUT amplifiers input select */ #define AC97_AD1986_HPSEL0 0x2000 /* Headphone amplifiers */ /* input select Surround DACs */ #define AC97_AD1986_HPSEL1 0x4000 /* Headphone amplifiers input */ /* select C/LFE DACs */ #define AC97_AD1986_JSINVB 0x8000 /* Jack Sense Invert SENSE_B */ /* Serial Config bits (AD1986 register 0x74) (incomplete) */ #define AC97_AD1986_OMS0 0x0100 /* Optional Mic Selector bit 0 */ #define AC97_AD1986_OMS1 0x0200 /* Optional Mic Selector bit 1 */ #define AC97_AD1986_OMS2 0x0400 /* Optional Mic Selector bit 2 */ #define AC97_AD1986_OMS_MASK \ (AC97_AD1986_OMS2 | AC97_AD1986_OMS1 | AC97_AD1986_OMS0) #define AC97_AD1986_OMS_M 0x0000 /* MIC_1/2 pins are MIC sources */ #define AC97_AD1986_OMS_L 0x0100 /* LINE_IN pins are MIC sources */ #define AC97_AD1986_OMS_C 0x0200 /* Center/LFE pins are MCI sources */ #define AC97_AD1986_OMS_MC 0x0400 /* Mix of MIC and C/LFE pins */ /* are MIC sources */ #define AC97_AD1986_OMS_ML 0x0500 /* MIX of MIC and LINE_IN pins */ /* are MIC sources */ #define AC97_AD1986_OMS_LC 0x0600 /* MIX of LINE_IN and C/LFE pins */ /* are MIC sources */ #define AC97_AD1986_OMS_MLC 0x0700 /* MIX of MIC, LINE_IN, C/LFE pins */ /* are MIC sources */ static int snd_ac97_ad198x_spdif_source_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[2] = { "AC-Link", "A/D Converter" }; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 2; if (uinfo->value.enumerated.item > 1) uinfo->value.enumerated.item = 1; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_ac97_ad198x_spdif_source_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; val = ac97->regs[AC97_AD_SERIAL_CFG]; ucontrol->value.enumerated.item[0] = (val >> 2) & 1; return 0; } static int snd_ac97_ad198x_spdif_source_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; if (ucontrol->value.enumerated.item[0] > 1) return -EINVAL; val = ucontrol->value.enumerated.item[0] << 2; return snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x0004, val); } static const struct snd_kcontrol_new snd_ac97_ad198x_spdif_source = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source", .info = snd_ac97_ad198x_spdif_source_info, .get = snd_ac97_ad198x_spdif_source_get, .put = snd_ac97_ad198x_spdif_source_put, }; static int patch_ad198x_post_spdif(struct snd_ac97 * ac97) { return patch_build_controls(ac97, &snd_ac97_ad198x_spdif_source, 1); } static const struct snd_kcontrol_new snd_ac97_ad1981x_jack_sense[] = { AC97_SINGLE("Headphone Jack Sense", AC97_AD_JACK_SPDIF, 11, 1, 0), AC97_SINGLE("Line Jack Sense", AC97_AD_JACK_SPDIF, 12, 1, 0), }; /* black list to avoid HP/Line jack-sense controls * (SS vendor << 16 | device) */ static unsigned int ad1981_jacks_blacklist[] = { 0x10140523, /* Thinkpad R40 */ 0x10140534, /* Thinkpad X31 */ 0x10140537, /* Thinkpad T41p */ 0x1014053e, /* Thinkpad R40e */ 0x10140554, /* Thinkpad T42p/R50p */ 0x10140567, /* Thinkpad T43p 2668-G7U */ 0x10140581, /* Thinkpad X41-2527 */ 0x10280160, /* Dell Dimension 2400 */ 0x104380b0, /* Asus A7V8X-MX */ 0x11790241, /* Toshiba Satellite A-15 S127 */ 0x1179ff10, /* Toshiba P500 */ 0x144dc01a, /* Samsung NP-X20C004/SEG */ 0 /* end */ }; static int check_list(struct snd_ac97 *ac97, const unsigned int *list) { u32 subid = ((u32)ac97->subsystem_vendor << 16) | ac97->subsystem_device; for (; *list; list++) if (*list == subid) return 1; return 0; } static int patch_ad1981a_specific(struct snd_ac97 * ac97) { if (check_list(ac97, ad1981_jacks_blacklist)) return 0; return patch_build_controls(ac97, snd_ac97_ad1981x_jack_sense, ARRAY_SIZE(snd_ac97_ad1981x_jack_sense)); } static const struct snd_ac97_build_ops patch_ad1981a_build_ops = { .build_post_spdif = patch_ad198x_post_spdif, .build_specific = patch_ad1981a_specific, #ifdef CONFIG_PM .resume = ad18xx_resume #endif }; /* white list to enable HP jack-sense bits * (SS vendor << 16 | device) */ static unsigned int ad1981_jacks_whitelist[] = { 0x0e11005a, /* HP nc4000/4010 */ 0x103c0890, /* HP nc6000 */ 0x103c0938, /* HP nc4220 */ 0x103c099c, /* HP nx6110 */ 0x103c0944, /* HP nc6220 */ 0x103c0934, /* HP nc8220 */ 0x103c006d, /* HP nx9105 */ 0x103c300d, /* HP Compaq dc5100 SFF(PT003AW) */ 0x17340088, /* FSC Scenic-W */ 0 /* end */ }; static void check_ad1981_hp_jack_sense(struct snd_ac97 *ac97) { if (check_list(ac97, ad1981_jacks_whitelist)) /* enable headphone jack sense */ snd_ac97_update_bits(ac97, AC97_AD_JACK_SPDIF, 1<<11, 1<<11); } static int patch_ad1981a(struct snd_ac97 *ac97) { patch_ad1881(ac97); ac97->build_ops = &patch_ad1981a_build_ops; snd_ac97_update_bits(ac97, AC97_AD_MISC, AC97_AD198X_MSPLT, AC97_AD198X_MSPLT); ac97->flags |= AC97_STEREO_MUTES; check_ad1981_hp_jack_sense(ac97); return 0; } static const struct snd_kcontrol_new snd_ac97_ad198x_2cmic = AC97_SINGLE("Stereo Mic", AC97_AD_MISC, 6, 1, 0); static int patch_ad1981b_specific(struct snd_ac97 *ac97) { int err; if ((err = patch_build_controls(ac97, &snd_ac97_ad198x_2cmic, 1)) < 0) return err; if (check_list(ac97, ad1981_jacks_blacklist)) return 0; return patch_build_controls(ac97, snd_ac97_ad1981x_jack_sense, ARRAY_SIZE(snd_ac97_ad1981x_jack_sense)); } static const struct snd_ac97_build_ops patch_ad1981b_build_ops = { .build_post_spdif = patch_ad198x_post_spdif, .build_specific = patch_ad1981b_specific, #ifdef CONFIG_PM .resume = ad18xx_resume #endif }; static int patch_ad1981b(struct snd_ac97 *ac97) { patch_ad1881(ac97); ac97->build_ops = &patch_ad1981b_build_ops; snd_ac97_update_bits(ac97, AC97_AD_MISC, AC97_AD198X_MSPLT, AC97_AD198X_MSPLT); ac97->flags |= AC97_STEREO_MUTES; check_ad1981_hp_jack_sense(ac97); return 0; } #define snd_ac97_ad1888_lohpsel_info snd_ctl_boolean_mono_info static int snd_ac97_ad1888_lohpsel_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; val = ac97->regs[AC97_AD_MISC]; ucontrol->value.integer.value[0] = !(val & AC97_AD198X_LOSEL); if (ac97->spec.ad18xx.lo_as_master) ucontrol->value.integer.value[0] = !ucontrol->value.integer.value[0]; return 0; } static int snd_ac97_ad1888_lohpsel_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; val = !ucontrol->value.integer.value[0]; if (ac97->spec.ad18xx.lo_as_master) val = !val; val = val ? (AC97_AD198X_LOSEL | AC97_AD198X_HPSEL) : 0; return snd_ac97_update_bits(ac97, AC97_AD_MISC, AC97_AD198X_LOSEL | AC97_AD198X_HPSEL, val); } static int snd_ac97_ad1888_downmix_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[3] = {"Off", "6 -> 4", "6 -> 2"}; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 3; if (uinfo->value.enumerated.item > 2) uinfo->value.enumerated.item = 2; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_ac97_ad1888_downmix_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; val = ac97->regs[AC97_AD_MISC]; if (!(val & AC97_AD198X_DMIX1)) ucontrol->value.enumerated.item[0] = 0; else ucontrol->value.enumerated.item[0] = 1 + ((val >> 8) & 1); return 0; } static int snd_ac97_ad1888_downmix_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; if (ucontrol->value.enumerated.item[0] > 2) return -EINVAL; if (ucontrol->value.enumerated.item[0] == 0) val = 0; else val = AC97_AD198X_DMIX1 | ((ucontrol->value.enumerated.item[0] - 1) << 8); return snd_ac97_update_bits(ac97, AC97_AD_MISC, AC97_AD198X_DMIX0 | AC97_AD198X_DMIX1, val); } static void ad1888_update_jacks(struct snd_ac97 *ac97) { unsigned short val = 0; /* clear LODIS if shared jack is to be used for Surround out */ if (!ac97->spec.ad18xx.lo_as_master && is_shared_linein(ac97)) val |= (1 << 12); /* clear CLDIS if shared jack is to be used for C/LFE out */ if (is_shared_micin(ac97)) val |= (1 << 11); /* shared Line-In */ snd_ac97_update_bits(ac97, AC97_AD_MISC, (1 << 11) | (1 << 12), val); } static const struct snd_kcontrol_new snd_ac97_ad1888_controls[] = { { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Exchange Front/Surround", .info = snd_ac97_ad1888_lohpsel_info, .get = snd_ac97_ad1888_lohpsel_get, .put = snd_ac97_ad1888_lohpsel_put }, AC97_SINGLE("V_REFOUT Enable", AC97_AD_MISC, AC97_AD_VREFD_SHIFT, 1, 1), AC97_SINGLE("High Pass Filter Enable", AC97_AD_TEST2, AC97_AD_HPFD_SHIFT, 1, 1), AC97_SINGLE("Spread Front to Surround and Center/LFE", AC97_AD_MISC, 7, 1, 0), { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Downmix", .info = snd_ac97_ad1888_downmix_info, .get = snd_ac97_ad1888_downmix_get, .put = snd_ac97_ad1888_downmix_put }, AC97_SURROUND_JACK_MODE_CTL, AC97_CHANNEL_MODE_CTL, AC97_SINGLE("Headphone Jack Sense", AC97_AD_JACK_SPDIF, 10, 1, 0), AC97_SINGLE("Line Jack Sense", AC97_AD_JACK_SPDIF, 12, 1, 0), }; static int patch_ad1888_specific(struct snd_ac97 *ac97) { if (!ac97->spec.ad18xx.lo_as_master) { /* rename 0x04 as "Master" and 0x02 as "Master Surround" */ snd_ac97_rename_vol_ctl(ac97, "Master Playback", "Master Surround Playback"); snd_ac97_rename_vol_ctl(ac97, "Headphone Playback", "Master Playback"); } return patch_build_controls(ac97, snd_ac97_ad1888_controls, ARRAY_SIZE(snd_ac97_ad1888_controls)); } static const struct snd_ac97_build_ops patch_ad1888_build_ops = { .build_post_spdif = patch_ad198x_post_spdif, .build_specific = patch_ad1888_specific, #ifdef CONFIG_PM .resume = ad1888_resume, #endif .update_jacks = ad1888_update_jacks, }; static int patch_ad1888(struct snd_ac97 * ac97) { unsigned short misc; patch_ad1881(ac97); ac97->build_ops = &patch_ad1888_build_ops; /* * LO can be used as a real line-out on some devices, * and we need to revert the front/surround mixer switches */ if (ac97->subsystem_vendor == 0x1043 && ac97->subsystem_device == 0x1193) /* ASUS A9T laptop */ ac97->spec.ad18xx.lo_as_master = 1; misc = snd_ac97_read(ac97, AC97_AD_MISC); /* AD-compatible mode */ /* Stereo mutes enabled */ misc |= AC97_AD198X_MSPLT | AC97_AD198X_AC97NC; if (!ac97->spec.ad18xx.lo_as_master) /* Switch FRONT/SURROUND LINE-OUT/HP-OUT default connection */ /* it seems that most vendors connect line-out connector to * headphone out of AC'97 */ misc |= AC97_AD198X_LOSEL | AC97_AD198X_HPSEL; snd_ac97_write_cache(ac97, AC97_AD_MISC, misc); ac97->flags |= AC97_STEREO_MUTES; return 0; } static int patch_ad1980_specific(struct snd_ac97 *ac97) { int err; if ((err = patch_ad1888_specific(ac97)) < 0) return err; return patch_build_controls(ac97, &snd_ac97_ad198x_2cmic, 1); } static const struct snd_ac97_build_ops patch_ad1980_build_ops = { .build_post_spdif = patch_ad198x_post_spdif, .build_specific = patch_ad1980_specific, #ifdef CONFIG_PM .resume = ad18xx_resume, #endif .update_jacks = ad1888_update_jacks, }; static int patch_ad1980(struct snd_ac97 * ac97) { patch_ad1888(ac97); ac97->build_ops = &patch_ad1980_build_ops; return 0; } static int snd_ac97_ad1985_vrefout_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[4] = {"High-Z", "3.7 V", "2.25 V", "0 V"}; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 4; if (uinfo->value.enumerated.item > 3) uinfo->value.enumerated.item = 3; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_ac97_ad1985_vrefout_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { static const int reg2ctrl[4] = {2, 0, 1, 3}; struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; val = (ac97->regs[AC97_AD_MISC] & AC97_AD198X_VREF_MASK) >> AC97_AD198X_VREF_SHIFT; ucontrol->value.enumerated.item[0] = reg2ctrl[val]; return 0; } static int snd_ac97_ad1985_vrefout_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { static const int ctrl2reg[4] = {1, 2, 0, 3}; struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; if (ucontrol->value.enumerated.item[0] > 3) return -EINVAL; val = ctrl2reg[ucontrol->value.enumerated.item[0]] << AC97_AD198X_VREF_SHIFT; return snd_ac97_update_bits(ac97, AC97_AD_MISC, AC97_AD198X_VREF_MASK, val); } static const struct snd_kcontrol_new snd_ac97_ad1985_controls[] = { AC97_SINGLE("Exchange Center/LFE", AC97_AD_SERIAL_CFG, 3, 1, 0), { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Exchange Front/Surround", .info = snd_ac97_ad1888_lohpsel_info, .get = snd_ac97_ad1888_lohpsel_get, .put = snd_ac97_ad1888_lohpsel_put }, AC97_SINGLE("High Pass Filter Enable", AC97_AD_TEST2, 12, 1, 1), AC97_SINGLE("Spread Front to Surround and Center/LFE", AC97_AD_MISC, 7, 1, 0), { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Downmix", .info = snd_ac97_ad1888_downmix_info, .get = snd_ac97_ad1888_downmix_get, .put = snd_ac97_ad1888_downmix_put }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "V_REFOUT", .info = snd_ac97_ad1985_vrefout_info, .get = snd_ac97_ad1985_vrefout_get, .put = snd_ac97_ad1985_vrefout_put }, AC97_SURROUND_JACK_MODE_CTL, AC97_CHANNEL_MODE_CTL, AC97_SINGLE("Headphone Jack Sense", AC97_AD_JACK_SPDIF, 10, 1, 0), AC97_SINGLE("Line Jack Sense", AC97_AD_JACK_SPDIF, 12, 1, 0), }; static void ad1985_update_jacks(struct snd_ac97 *ac97) { ad1888_update_jacks(ac97); /* clear OMS if shared jack is to be used for C/LFE out */ snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 1 << 9, is_shared_micin(ac97) ? 1 << 9 : 0); } static int patch_ad1985_specific(struct snd_ac97 *ac97) { int err; /* rename 0x04 as "Master" and 0x02 as "Master Surround" */ snd_ac97_rename_vol_ctl(ac97, "Master Playback", "Master Surround Playback"); snd_ac97_rename_vol_ctl(ac97, "Headphone Playback", "Master Playback"); if ((err = patch_build_controls(ac97, &snd_ac97_ad198x_2cmic, 1)) < 0) return err; return patch_build_controls(ac97, snd_ac97_ad1985_controls, ARRAY_SIZE(snd_ac97_ad1985_controls)); } static const struct snd_ac97_build_ops patch_ad1985_build_ops = { .build_post_spdif = patch_ad198x_post_spdif, .build_specific = patch_ad1985_specific, #ifdef CONFIG_PM .resume = ad18xx_resume, #endif .update_jacks = ad1985_update_jacks, }; static int patch_ad1985(struct snd_ac97 * ac97) { unsigned short misc; patch_ad1881(ac97); ac97->build_ops = &patch_ad1985_build_ops; misc = snd_ac97_read(ac97, AC97_AD_MISC); /* switch front/surround line-out/hp-out */ /* AD-compatible mode */ /* Stereo mutes enabled */ snd_ac97_write_cache(ac97, AC97_AD_MISC, misc | AC97_AD198X_LOSEL | AC97_AD198X_HPSEL | AC97_AD198X_MSPLT | AC97_AD198X_AC97NC); ac97->flags |= AC97_STEREO_MUTES; /* update current jack configuration */ ad1985_update_jacks(ac97); /* on AD1985 rev. 3, AC'97 revision bits are zero */ ac97->ext_id = (ac97->ext_id & ~AC97_EI_REV_MASK) | AC97_EI_REV_23; return 0; } #define snd_ac97_ad1986_bool_info snd_ctl_boolean_mono_info static int snd_ac97_ad1986_lososel_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; val = ac97->regs[AC97_AD_MISC3]; ucontrol->value.integer.value[0] = (val & AC97_AD1986_LOSEL) != 0; return 0; } static int snd_ac97_ad1986_lososel_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); int ret0; int ret1; int sprd = (ac97->regs[AC97_AD_MISC] & AC97_AD1986_SPRD) != 0; ret0 = snd_ac97_update_bits(ac97, AC97_AD_MISC3, AC97_AD1986_LOSEL, ucontrol->value.integer.value[0] != 0 ? AC97_AD1986_LOSEL : 0); if (ret0 < 0) return ret0; /* SOSEL is set to values of "Spread" or "Exchange F/S" controls */ ret1 = snd_ac97_update_bits(ac97, AC97_AD_MISC, AC97_AD1986_SOSEL, (ucontrol->value.integer.value[0] != 0 || sprd) ? AC97_AD1986_SOSEL : 0); if (ret1 < 0) return ret1; return (ret0 > 0 || ret1 > 0) ? 1 : 0; } static int snd_ac97_ad1986_spread_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; val = ac97->regs[AC97_AD_MISC]; ucontrol->value.integer.value[0] = (val & AC97_AD1986_SPRD) != 0; return 0; } static int snd_ac97_ad1986_spread_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); int ret0; int ret1; int sprd = (ac97->regs[AC97_AD_MISC3] & AC97_AD1986_LOSEL) != 0; ret0 = snd_ac97_update_bits(ac97, AC97_AD_MISC, AC97_AD1986_SPRD, ucontrol->value.integer.value[0] != 0 ? AC97_AD1986_SPRD : 0); if (ret0 < 0) return ret0; /* SOSEL is set to values of "Spread" or "Exchange F/S" controls */ ret1 = snd_ac97_update_bits(ac97, AC97_AD_MISC, AC97_AD1986_SOSEL, (ucontrol->value.integer.value[0] != 0 || sprd) ? AC97_AD1986_SOSEL : 0); if (ret1 < 0) return ret1; return (ret0 > 0 || ret1 > 0) ? 1 : 0; } static int snd_ac97_ad1986_miclisel_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); ucontrol->value.integer.value[0] = ac97->spec.ad18xx.swap_mic_linein; return 0; } static int snd_ac97_ad1986_miclisel_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned char swap = ucontrol->value.integer.value[0] != 0; if (swap != ac97->spec.ad18xx.swap_mic_linein) { ac97->spec.ad18xx.swap_mic_linein = swap; if (ac97->build_ops->update_jacks) ac97->build_ops->update_jacks(ac97); return 1; } return 0; } static int snd_ac97_ad1986_vrefout_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { /* Use MIC_1/2 V_REFOUT as the "get" value */ struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; unsigned short reg = ac97->regs[AC97_AD_MISC2]; if ((reg & AC97_AD1986_MVREF0) != 0) val = 2; else if ((reg & AC97_AD1986_MVREF1) != 0) val = 3; else if ((reg & AC97_AD1986_MVREF2) != 0) val = 1; else val = 0; ucontrol->value.enumerated.item[0] = val; return 0; } static int snd_ac97_ad1986_vrefout_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short cval; unsigned short lval; unsigned short mval; int cret; int lret; int mret; switch (ucontrol->value.enumerated.item[0]) { case 0: /* High-Z */ cval = 0; lval = 0; mval = 0; break; case 1: /* 3.7 V */ cval = AC97_AD1986_CVREF2; lval = AC97_AD1986_LVREF2; mval = AC97_AD1986_MVREF2; break; case 2: /* 2.25 V */ cval = AC97_AD1986_CVREF0; lval = AC97_AD1986_LVREF0; mval = AC97_AD1986_MVREF0; break; case 3: /* 0 V */ cval = AC97_AD1986_CVREF1; lval = AC97_AD1986_LVREF1; mval = AC97_AD1986_MVREF1; break; default: return -EINVAL; } cret = snd_ac97_update_bits(ac97, AC97_AD_MISC2, AC97_AD1986_CVREF_MASK, cval); if (cret < 0) return cret; lret = snd_ac97_update_bits(ac97, AC97_AD_MISC3, AC97_AD1986_LVREF_MASK, lval); if (lret < 0) return lret; mret = snd_ac97_update_bits(ac97, AC97_AD_MISC2, AC97_AD1986_MVREF_MASK, mval); if (mret < 0) return mret; return (cret > 0 || lret > 0 || mret > 0) ? 1 : 0; } static const struct snd_kcontrol_new snd_ac97_ad1986_controls[] = { AC97_SINGLE("Exchange Center/LFE", AC97_AD_SERIAL_CFG, 3, 1, 0), { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Exchange Front/Surround", .info = snd_ac97_ad1986_bool_info, .get = snd_ac97_ad1986_lososel_get, .put = snd_ac97_ad1986_lososel_put }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Exchange Mic/Line In", .info = snd_ac97_ad1986_bool_info, .get = snd_ac97_ad1986_miclisel_get, .put = snd_ac97_ad1986_miclisel_put }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Spread Front to Surround and Center/LFE", .info = snd_ac97_ad1986_bool_info, .get = snd_ac97_ad1986_spread_get, .put = snd_ac97_ad1986_spread_put }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Downmix", .info = snd_ac97_ad1888_downmix_info, .get = snd_ac97_ad1888_downmix_get, .put = snd_ac97_ad1888_downmix_put }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "V_REFOUT", .info = snd_ac97_ad1985_vrefout_info, .get = snd_ac97_ad1986_vrefout_get, .put = snd_ac97_ad1986_vrefout_put }, AC97_SURROUND_JACK_MODE_CTL, AC97_CHANNEL_MODE_CTL, AC97_SINGLE("Headphone Jack Sense", AC97_AD_JACK_SPDIF, 10, 1, 0), AC97_SINGLE("Line Jack Sense", AC97_AD_JACK_SPDIF, 12, 1, 0) }; static void ad1986_update_jacks(struct snd_ac97 *ac97) { unsigned short misc_val = 0; unsigned short ser_val; /* disable SURROUND and CENTER/LFE if not surround mode */ if (!is_surround_on(ac97)) misc_val |= AC97_AD1986_SODIS; if (!is_clfe_on(ac97)) misc_val |= AC97_AD1986_CLDIS; /* select line input (default=LINE_IN, SURROUND or MIC_1/2) */ if (is_shared_linein(ac97)) misc_val |= AC97_AD1986_LISEL_SURR; else if (ac97->spec.ad18xx.swap_mic_linein != 0) misc_val |= AC97_AD1986_LISEL_MIC; snd_ac97_update_bits(ac97, AC97_AD_MISC, AC97_AD1986_SODIS | AC97_AD1986_CLDIS | AC97_AD1986_LISEL_MASK, misc_val); /* select microphone input (MIC_1/2, Center/LFE or LINE_IN) */ if (is_shared_micin(ac97)) ser_val = AC97_AD1986_OMS_C; else if (ac97->spec.ad18xx.swap_mic_linein != 0) ser_val = AC97_AD1986_OMS_L; else ser_val = AC97_AD1986_OMS_M; snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, AC97_AD1986_OMS_MASK, ser_val); } static int patch_ad1986_specific(struct snd_ac97 *ac97) { int err; if ((err = patch_build_controls(ac97, &snd_ac97_ad198x_2cmic, 1)) < 0) return err; return patch_build_controls(ac97, snd_ac97_ad1986_controls, ARRAY_SIZE(snd_ac97_ad1985_controls)); } static const struct snd_ac97_build_ops patch_ad1986_build_ops = { .build_post_spdif = patch_ad198x_post_spdif, .build_specific = patch_ad1986_specific, #ifdef CONFIG_PM .resume = ad18xx_resume, #endif .update_jacks = ad1986_update_jacks, }; static int patch_ad1986(struct snd_ac97 * ac97) { patch_ad1881(ac97); ac97->build_ops = &patch_ad1986_build_ops; ac97->flags |= AC97_STEREO_MUTES; /* update current jack configuration */ ad1986_update_jacks(ac97); return 0; } /* * realtek ALC203: use mono-out for pin 37 */ static int patch_alc203(struct snd_ac97 *ac97) { snd_ac97_update_bits(ac97, 0x7a, 0x400, 0x400); return 0; } /* * realtek ALC65x/850 codecs */ static void alc650_update_jacks(struct snd_ac97 *ac97) { int shared; /* shared Line-In / Surround Out */ shared = is_shared_surrout(ac97); snd_ac97_update_bits(ac97, AC97_ALC650_MULTICH, 1 << 9, shared ? (1 << 9) : 0); /* update shared Mic In / Center/LFE Out */ shared = is_shared_clfeout(ac97); /* disable/enable vref */ snd_ac97_update_bits(ac97, AC97_ALC650_CLOCK, 1 << 12, shared ? (1 << 12) : 0); /* turn on/off center-on-mic */ snd_ac97_update_bits(ac97, AC97_ALC650_MULTICH, 1 << 10, shared ? (1 << 10) : 0); /* GPIO0 high for mic */ snd_ac97_update_bits(ac97, AC97_ALC650_GPIO_STATUS, 0x100, shared ? 0 : 0x100); } static int alc650_swap_surround_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); struct snd_pcm_chmap *map = ac97->chmaps[SNDRV_PCM_STREAM_PLAYBACK]; if (map) { if (ucontrol->value.integer.value[0]) map->chmap = snd_pcm_std_chmaps; else map->chmap = snd_pcm_alt_chmaps; } return snd_ac97_put_volsw(kcontrol, ucontrol); } static const struct snd_kcontrol_new snd_ac97_controls_alc650[] = { AC97_SINGLE("Duplicate Front", AC97_ALC650_MULTICH, 0, 1, 0), AC97_SINGLE("Surround Down Mix", AC97_ALC650_MULTICH, 1, 1, 0), AC97_SINGLE("Center/LFE Down Mix", AC97_ALC650_MULTICH, 2, 1, 0), AC97_SINGLE("Exchange Center/LFE", AC97_ALC650_MULTICH, 3, 1, 0), /* 4: Analog Input To Surround */ /* 5: Analog Input To Center/LFE */ /* 6: Independent Master Volume Right */ /* 7: Independent Master Volume Left */ /* 8: reserved */ /* 9: Line-In/Surround share */ /* 10: Mic/CLFE share */ /* 11-13: in IEC958 controls */ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Swap Surround Slot", .info = snd_ac97_info_volsw, .get = snd_ac97_get_volsw, .put = alc650_swap_surround_put, .private_value = AC97_SINGLE_VALUE(AC97_ALC650_MULTICH, 14, 1, 0), }, #if 0 /* always set in patch_alc650 */ AC97_SINGLE("IEC958 Input Clock Enable", AC97_ALC650_CLOCK, 0, 1, 0), AC97_SINGLE("IEC958 Input Pin Enable", AC97_ALC650_CLOCK, 1, 1, 0), AC97_SINGLE("Surround DAC Switch", AC97_ALC650_SURR_DAC_VOL, 15, 1, 1), AC97_DOUBLE("Surround DAC Volume", AC97_ALC650_SURR_DAC_VOL, 8, 0, 31, 1), AC97_SINGLE("Center/LFE DAC Switch", AC97_ALC650_LFE_DAC_VOL, 15, 1, 1), AC97_DOUBLE("Center/LFE DAC Volume", AC97_ALC650_LFE_DAC_VOL, 8, 0, 31, 1), #endif AC97_SURROUND_JACK_MODE_CTL, AC97_CHANNEL_MODE_CTL, }; static const struct snd_kcontrol_new snd_ac97_spdif_controls_alc650[] = { AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH), AC97_ALC650_MULTICH, 11, 1, 0), AC97_SINGLE("Analog to IEC958 Output", AC97_ALC650_MULTICH, 12, 1, 0), /* disable this controls since it doesn't work as expected */ /* AC97_SINGLE("IEC958 Input Monitor", AC97_ALC650_MULTICH, 13, 1, 0), */ }; static const DECLARE_TLV_DB_SCALE(db_scale_5bit_3db_max, -4350, 150, 0); static int patch_alc650_specific(struct snd_ac97 * ac97) { int err; if ((err = patch_build_controls(ac97, snd_ac97_controls_alc650, ARRAY_SIZE(snd_ac97_controls_alc650))) < 0) return err; if (ac97->ext_id & AC97_EI_SPDIF) { if ((err = patch_build_controls(ac97, snd_ac97_spdif_controls_alc650, ARRAY_SIZE(snd_ac97_spdif_controls_alc650))) < 0) return err; } if (ac97->id != AC97_ID_ALC650F) reset_tlv(ac97, "Master Playback Volume", db_scale_5bit_3db_max); return 0; } static const struct snd_ac97_build_ops patch_alc650_ops = { .build_specific = patch_alc650_specific, .update_jacks = alc650_update_jacks }; static int patch_alc650(struct snd_ac97 * ac97) { unsigned short val; ac97->build_ops = &patch_alc650_ops; /* determine the revision */ val = snd_ac97_read(ac97, AC97_ALC650_REVISION) & 0x3f; if (val < 3) ac97->id = 0x414c4720; /* Old version */ else if (val < 0x10) ac97->id = 0x414c4721; /* D version */ else if (val < 0x20) ac97->id = 0x414c4722; /* E version */ else if (val < 0x30) ac97->id = 0x414c4723; /* F version */ /* revision E or F */ /* FIXME: what about revision D ? */ ac97->spec.dev_flags = (ac97->id == 0x414c4722 || ac97->id == 0x414c4723); /* enable AC97_ALC650_GPIO_SETUP, AC97_ALC650_CLOCK for R/W */ snd_ac97_write_cache(ac97, AC97_ALC650_GPIO_STATUS, snd_ac97_read(ac97, AC97_ALC650_GPIO_STATUS) | 0x8000); /* Enable SPDIF-IN only on Rev.E and above */ val = snd_ac97_read(ac97, AC97_ALC650_CLOCK); /* SPDIF IN with pin 47 */ if (ac97->spec.dev_flags && /* ASUS A6KM requires EAPD */ ! (ac97->subsystem_vendor == 0x1043 && ac97->subsystem_device == 0x1103)) val |= 0x03; /* enable */ else val &= ~0x03; /* disable */ snd_ac97_write_cache(ac97, AC97_ALC650_CLOCK, val); /* set default: slot 3,4,7,8,6,9 spdif-in monitor off, analog-spdif off, spdif-in off center on mic off, surround on line-in off downmix off, duplicate front off */ snd_ac97_write_cache(ac97, AC97_ALC650_MULTICH, 0); /* set GPIO0 for mic bias */ /* GPIO0 pin output, no interrupt, high */ snd_ac97_write_cache(ac97, AC97_ALC650_GPIO_SETUP, snd_ac97_read(ac97, AC97_ALC650_GPIO_SETUP) | 0x01); snd_ac97_write_cache(ac97, AC97_ALC650_GPIO_STATUS, (snd_ac97_read(ac97, AC97_ALC650_GPIO_STATUS) | 0x100) & ~0x10); /* full DAC volume */ snd_ac97_write_cache(ac97, AC97_ALC650_SURR_DAC_VOL, 0x0808); snd_ac97_write_cache(ac97, AC97_ALC650_LFE_DAC_VOL, 0x0808); return 0; } static void alc655_update_jacks(struct snd_ac97 *ac97) { int shared; /* shared Line-In / Surround Out */ shared = is_shared_surrout(ac97); ac97_update_bits_page(ac97, AC97_ALC650_MULTICH, 1 << 9, shared ? (1 << 9) : 0, 0); /* update shared Mic In / Center/LFE Out */ shared = is_shared_clfeout(ac97); /* misc control; vrefout disable */ snd_ac97_update_bits(ac97, AC97_ALC650_CLOCK, 1 << 12, shared ? (1 << 12) : 0); ac97_update_bits_page(ac97, AC97_ALC650_MULTICH, 1 << 10, shared ? (1 << 10) : 0, 0); } static const struct snd_kcontrol_new snd_ac97_controls_alc655[] = { AC97_PAGE_SINGLE("Duplicate Front", AC97_ALC650_MULTICH, 0, 1, 0, 0), AC97_SURROUND_JACK_MODE_CTL, AC97_CHANNEL_MODE_CTL, }; static int alc655_iec958_route_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts_655[3] = { "PCM", "Analog In", "IEC958 In" }; static char *texts_658[4] = { "PCM", "Analog1 In", "Analog2 In", "IEC958 In" }; struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = ac97->spec.dev_flags ? 4 : 3; if (uinfo->value.enumerated.item >= uinfo->value.enumerated.items) uinfo->value.enumerated.item = uinfo->value.enumerated.items - 1; strcpy(uinfo->value.enumerated.name, ac97->spec.dev_flags ? texts_658[uinfo->value.enumerated.item] : texts_655[uinfo->value.enumerated.item]); return 0; } static int alc655_iec958_route_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; val = ac97->regs[AC97_ALC650_MULTICH]; val = (val >> 12) & 3; if (ac97->spec.dev_flags && val == 3) val = 0; ucontrol->value.enumerated.item[0] = val; return 0; } static int alc655_iec958_route_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); return ac97_update_bits_page(ac97, AC97_ALC650_MULTICH, 3 << 12, (unsigned short)ucontrol->value.enumerated.item[0] << 12, 0); } static const struct snd_kcontrol_new snd_ac97_spdif_controls_alc655[] = { AC97_PAGE_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH), AC97_ALC650_MULTICH, 11, 1, 0, 0), /* disable this controls since it doesn't work as expected */ /* AC97_PAGE_SINGLE("IEC958 Input Monitor", AC97_ALC650_MULTICH, 14, 1, 0, 0), */ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source", .info = alc655_iec958_route_info, .get = alc655_iec958_route_get, .put = alc655_iec958_route_put, }, }; static int patch_alc655_specific(struct snd_ac97 * ac97) { int err; if ((err = patch_build_controls(ac97, snd_ac97_controls_alc655, ARRAY_SIZE(snd_ac97_controls_alc655))) < 0) return err; if (ac97->ext_id & AC97_EI_SPDIF) { if ((err = patch_build_controls(ac97, snd_ac97_spdif_controls_alc655, ARRAY_SIZE(snd_ac97_spdif_controls_alc655))) < 0) return err; } return 0; } static const struct snd_ac97_build_ops patch_alc655_ops = { .build_specific = patch_alc655_specific, .update_jacks = alc655_update_jacks }; static int patch_alc655(struct snd_ac97 * ac97) { unsigned int val; if (ac97->id == AC97_ID_ALC658) { ac97->spec.dev_flags = 1; /* ALC658 */ if ((snd_ac97_read(ac97, AC97_ALC650_REVISION) & 0x3f) == 2) { ac97->id = AC97_ID_ALC658D; ac97->spec.dev_flags = 2; } } ac97->build_ops = &patch_alc655_ops; /* assume only page 0 for writing cache */ snd_ac97_update_bits(ac97, AC97_INT_PAGING, AC97_PAGE_MASK, AC97_PAGE_VENDOR); /* adjust default values */ val = snd_ac97_read(ac97, 0x7a); /* misc control */ if (ac97->spec.dev_flags) /* ALC658 */ val &= ~(1 << 1); /* Pin 47 is spdif input pin */ else { /* ALC655 */ if (ac97->subsystem_vendor == 0x1462 && (ac97->subsystem_device == 0x0131 || /* MSI S270 laptop */ ac97->subsystem_device == 0x0161 || /* LG K1 Express */ ac97->subsystem_device == 0x0351 || /* MSI L725 laptop */ ac97->subsystem_device == 0x0471 || /* MSI L720 laptop */ ac97->subsystem_device == 0x0061)) /* MSI S250 laptop */ val &= ~(1 << 1); /* Pin 47 is EAPD (for internal speaker) */ else val |= (1 << 1); /* Pin 47 is spdif input pin */ /* this seems missing on some hardwares */ ac97->ext_id |= AC97_EI_SPDIF; } val &= ~(1 << 12); /* vref enable */ snd_ac97_write_cache(ac97, 0x7a, val); /* set default: spdif-in enabled, spdif-in monitor off, spdif-in PCM off center on mic off, surround on line-in off duplicate front off */ snd_ac97_write_cache(ac97, AC97_ALC650_MULTICH, 1<<15); /* full DAC volume */ snd_ac97_write_cache(ac97, AC97_ALC650_SURR_DAC_VOL, 0x0808); snd_ac97_write_cache(ac97, AC97_ALC650_LFE_DAC_VOL, 0x0808); /* update undocumented bit... */ if (ac97->id == AC97_ID_ALC658D) snd_ac97_update_bits(ac97, 0x74, 0x0800, 0x0800); return 0; } #define AC97_ALC850_JACK_SELECT 0x76 #define AC97_ALC850_MISC1 0x7a #define AC97_ALC850_MULTICH 0x6a static void alc850_update_jacks(struct snd_ac97 *ac97) { int shared; int aux_is_back_surround; /* shared Line-In / Surround Out */ shared = is_shared_surrout(ac97); /* SURR 1kOhm (bit4), Amp (bit5) */ snd_ac97_update_bits(ac97, AC97_ALC850_MISC1, (1<<4)|(1<<5), shared ? (1<<5) : (1<<4)); /* LINE-IN = 0, SURROUND = 2 */ snd_ac97_update_bits(ac97, AC97_ALC850_JACK_SELECT, 7 << 12, shared ? (2<<12) : (0<<12)); /* update shared Mic In / Center/LFE Out */ shared = is_shared_clfeout(ac97); /* Vref disable (bit12), 1kOhm (bit13) */ snd_ac97_update_bits(ac97, AC97_ALC850_MISC1, (1<<12)|(1<<13), shared ? (1<<12) : (1<<13)); /* MIC-IN = 1, CENTER-LFE = 5 */ snd_ac97_update_bits(ac97, AC97_ALC850_JACK_SELECT, 7 << 4, shared ? (5<<4) : (1<<4)); aux_is_back_surround = alc850_is_aux_back_surround(ac97); /* Aux is Back Surround */ snd_ac97_update_bits(ac97, AC97_ALC850_MULTICH, 1 << 10, aux_is_back_surround ? (1<<10) : (0<<10)); } static const struct snd_kcontrol_new snd_ac97_controls_alc850[] = { AC97_PAGE_SINGLE("Duplicate Front", AC97_ALC650_MULTICH, 0, 1, 0, 0), AC97_SINGLE("Mic Front Input Switch", AC97_ALC850_JACK_SELECT, 15, 1, 1), AC97_SURROUND_JACK_MODE_CTL, AC97_CHANNEL_MODE_8CH_CTL, }; static int patch_alc850_specific(struct snd_ac97 *ac97) { int err; if ((err = patch_build_controls(ac97, snd_ac97_controls_alc850, ARRAY_SIZE(snd_ac97_controls_alc850))) < 0) return err; if (ac97->ext_id & AC97_EI_SPDIF) { if ((err = patch_build_controls(ac97, snd_ac97_spdif_controls_alc655, ARRAY_SIZE(snd_ac97_spdif_controls_alc655))) < 0) return err; } return 0; } static const struct snd_ac97_build_ops patch_alc850_ops = { .build_specific = patch_alc850_specific, .update_jacks = alc850_update_jacks }; static int patch_alc850(struct snd_ac97 *ac97) { ac97->build_ops = &patch_alc850_ops; ac97->spec.dev_flags = 0; /* for IEC958 playback route - ALC655 compatible */ ac97->flags |= AC97_HAS_8CH; /* assume only page 0 for writing cache */ snd_ac97_update_bits(ac97, AC97_INT_PAGING, AC97_PAGE_MASK, AC97_PAGE_VENDOR); /* adjust default values */ /* set default: spdif-in enabled, spdif-in monitor off, spdif-in PCM off center on mic off, surround on line-in off duplicate front off NB default bit 10=0 = Aux is Capture, not Back Surround */ snd_ac97_write_cache(ac97, AC97_ALC650_MULTICH, 1<<15); /* SURR_OUT: on, Surr 1kOhm: on, Surr Amp: off, Front 1kOhm: off * Front Amp: on, Vref: enable, Center 1kOhm: on, Mix: on */ snd_ac97_write_cache(ac97, 0x7a, (1<<1)|(1<<4)|(0<<5)|(1<<6)| (1<<7)|(0<<12)|(1<<13)|(0<<14)); /* detection UIO2,3: all path floating, UIO3: MIC, Vref2: disable, * UIO1: FRONT, Vref3: disable, UIO3: LINE, Front-Mic: mute */ snd_ac97_write_cache(ac97, 0x76, (0<<0)|(0<<2)|(1<<4)|(1<<7)|(2<<8)| (1<<11)|(0<<12)|(1<<15)); /* full DAC volume */ snd_ac97_write_cache(ac97, AC97_ALC650_SURR_DAC_VOL, 0x0808); snd_ac97_write_cache(ac97, AC97_ALC650_LFE_DAC_VOL, 0x0808); return 0; } static int patch_aztech_azf3328_specific(struct snd_ac97 *ac97) { struct snd_kcontrol *kctl_3d_center = snd_ac97_find_mixer_ctl(ac97, "3D Control - Center"); struct snd_kcontrol *kctl_3d_depth = snd_ac97_find_mixer_ctl(ac97, "3D Control - Depth"); /* * 3D register is different from AC97 standard layout * (also do some renaming, to resemble Windows driver naming) */ if (kctl_3d_center) { kctl_3d_center->private_value = AC97_SINGLE_VALUE(AC97_3D_CONTROL, 1, 0x07, 0); snd_ac97_rename_vol_ctl(ac97, "3D Control - Center", "3D Control - Width" ); } if (kctl_3d_depth) kctl_3d_depth->private_value = AC97_SINGLE_VALUE(AC97_3D_CONTROL, 8, 0x03, 0); /* Aztech Windows driver calls the equivalent control "Modem Playback", thus rename it: */ snd_ac97_rename_vol_ctl(ac97, "Master Mono Playback", "Modem Playback" ); snd_ac97_rename_vol_ctl(ac97, "Headphone Playback", "FM Synth Playback" ); return 0; } static const struct snd_ac97_build_ops patch_aztech_azf3328_ops = { .build_specific = patch_aztech_azf3328_specific }; static int patch_aztech_azf3328(struct snd_ac97 *ac97) { ac97->build_ops = &patch_aztech_azf3328_ops; return 0; } /* * C-Media CM97xx codecs */ static void cm9738_update_jacks(struct snd_ac97 *ac97) { /* shared Line-In / Surround Out */ snd_ac97_update_bits(ac97, AC97_CM9738_VENDOR_CTRL, 1 << 10, is_shared_surrout(ac97) ? (1 << 10) : 0); } static const struct snd_kcontrol_new snd_ac97_cm9738_controls[] = { AC97_SINGLE("Duplicate Front", AC97_CM9738_VENDOR_CTRL, 13, 1, 0), AC97_SURROUND_JACK_MODE_CTL, AC97_CHANNEL_MODE_4CH_CTL, }; static int patch_cm9738_specific(struct snd_ac97 * ac97) { return patch_build_controls(ac97, snd_ac97_cm9738_controls, ARRAY_SIZE(snd_ac97_cm9738_controls)); } static const struct snd_ac97_build_ops patch_cm9738_ops = { .build_specific = patch_cm9738_specific, .update_jacks = cm9738_update_jacks }; static int patch_cm9738(struct snd_ac97 * ac97) { ac97->build_ops = &patch_cm9738_ops; /* FIXME: can anyone confirm below? */ /* CM9738 has no PCM volume although the register reacts */ ac97->flags |= AC97_HAS_NO_PCM_VOL; snd_ac97_write_cache(ac97, AC97_PCM, 0x8000); return 0; } static int snd_ac97_cmedia_spdif_playback_source_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[] = { "Analog", "Digital" }; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 2; if (uinfo->value.enumerated.item > 1) uinfo->value.enumerated.item = 1; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_ac97_cmedia_spdif_playback_source_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); unsigned short val; val = ac97->regs[AC97_CM9739_SPDIF_CTRL]; ucontrol->value.enumerated.item[0] = (val >> 1) & 0x01; return 0; } static int snd_ac97_cmedia_spdif_playback_source_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); return snd_ac97_update_bits(ac97, AC97_CM9739_SPDIF_CTRL, 0x01 << 1, (ucontrol->value.enumerated.item[0] & 0x01) << 1); } static const struct snd_kcontrol_new snd_ac97_cm9739_controls_spdif[] = { /* BIT 0: SPDI_EN - always true */ { /* BIT 1: SPDIFS */ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source", .info = snd_ac97_cmedia_spdif_playback_source_info, .get = snd_ac97_cmedia_spdif_playback_source_get, .put = snd_ac97_cmedia_spdif_playback_source_put, }, /* BIT 2: IG_SPIV */ AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,NONE) "Valid Switch", AC97_CM9739_SPDIF_CTRL, 2, 1, 0), /* BIT 3: SPI2F */ AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,NONE) "Monitor", AC97_CM9739_SPDIF_CTRL, 3, 1, 0), /* BIT 4: SPI2SDI */ AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH), AC97_CM9739_SPDIF_CTRL, 4, 1, 0), /* BIT 8: SPD32 - 32bit SPDIF - not supported yet */ }; static void cm9739_update_jacks(struct snd_ac97 *ac97) { /* shared Line-In / Surround Out */ snd_ac97_update_bits(ac97, AC97_CM9739_MULTI_CHAN, 1 << 10, is_shared_surrout(ac97) ? (1 << 10) : 0); /* shared Mic In / Center/LFE Out **/ snd_ac97_update_bits(ac97, AC97_CM9739_MULTI_CHAN, 0x3000, is_shared_clfeout(ac97) ? 0x1000 : 0x2000); } static const struct snd_kcontrol_new snd_ac97_cm9739_controls[] = { AC97_SURROUND_JACK_MODE_CTL, AC97_CHANNEL_MODE_CTL, }; static int patch_cm9739_specific(struct snd_ac97 * ac97) { return patch_build_controls(ac97, snd_ac97_cm9739_controls, ARRAY_SIZE(snd_ac97_cm9739_controls)); } static int patch_cm9739_post_spdif(struct snd_ac97 * ac97) { return patch_build_controls(ac97, snd_ac97_cm9739_controls_spdif, ARRAY_SIZE(snd_ac97_cm9739_controls_spdif)); } static const struct snd_ac97_build_ops patch_cm9739_ops = { .build_specific = patch_cm9739_specific, .build_post_spdif = patch_cm9739_post_spdif, .update_jacks = cm9739_update_jacks }; static int patch_cm9739(struct snd_ac97 * ac97) { unsigned short val; ac97->build_ops = &patch_cm9739_ops; /* CM9739/A has no Master and PCM volume although the register reacts */ ac97->flags |= AC97_HAS_NO_MASTER_VOL | AC97_HAS_NO_PCM_VOL; snd_ac97_write_cache(ac97, AC97_MASTER, 0x8000); snd_ac97_write_cache(ac97, AC97_PCM, 0x8000); /* check spdif */ val = snd_ac97_read(ac97, AC97_EXTENDED_STATUS); if (val & AC97_EA_SPCV) { /* enable spdif in */ snd_ac97_write_cache(ac97, AC97_CM9739_SPDIF_CTRL, snd_ac97_read(ac97, AC97_CM9739_SPDIF_CTRL) | 0x01); ac97->rates[AC97_RATES_SPDIF] = SNDRV_PCM_RATE_48000; /* 48k only */ } else { ac97->ext_id &= ~AC97_EI_SPDIF; /* disable extended-id */ ac97->rates[AC97_RATES_SPDIF] = 0; } /* set-up multi channel */ /* bit 14: 0 = SPDIF, 1 = EAPD */ /* bit 13: enable internal vref output for mic */ /* bit 12: disable center/lfe (swithable) */ /* bit 10: disable surround/line (switchable) */ /* bit 9: mix 2 surround off */ /* bit 4: undocumented; 0 mutes the CM9739A, which defaults to 1 */ /* bit 3: undocumented; surround? */ /* bit 0: dB */ val = snd_ac97_read(ac97, AC97_CM9739_MULTI_CHAN) & (1 << 4); val |= (1 << 3); val |= (1 << 13); if (! (ac97->ext_id & AC97_EI_SPDIF)) val |= (1 << 14); snd_ac97_write_cache(ac97, AC97_CM9739_MULTI_CHAN, val); /* FIXME: set up GPIO */ snd_ac97_write_cache(ac97, 0x70, 0x0100); snd_ac97_write_cache(ac97, 0x72, 0x0020); /* Special exception for ASUS W1000/CMI9739. It does not have an SPDIF in. */ if (ac97->pci && ac97->subsystem_vendor == 0x1043 && ac97->subsystem_device == 0x1843) { snd_ac97_write_cache(ac97, AC97_CM9739_SPDIF_CTRL, snd_ac97_read(ac97, AC97_CM9739_SPDIF_CTRL) & ~0x01); snd_ac97_write_cache(ac97, AC97_CM9739_MULTI_CHAN, snd_ac97_read(ac97, AC97_CM9739_MULTI_CHAN) | (1 << 14)); } return 0; } #define AC97_CM9761_MULTI_CHAN 0x64 #define AC97_CM9761_FUNC 0x66 #define AC97_CM9761_SPDIF_CTRL 0x6c static void cm9761_update_jacks(struct snd_ac97 *ac97) { /* FIXME: check the bits for each model * model 83 is confirmed to work */ static unsigned short surr_on[3][2] = { { 0x0008, 0x0000 }, /* 9761-78 & 82 */ { 0x0000, 0x0008 }, /* 9761-82 rev.B */ { 0x0000, 0x0008 }, /* 9761-83 */ }; static unsigned short clfe_on[3][2] = { { 0x0000, 0x1000 }, /* 9761-78 & 82 */ { 0x1000, 0x0000 }, /* 9761-82 rev.B */ { 0x0000, 0x1000 }, /* 9761-83 */ }; static unsigned short surr_shared[3][2] = { { 0x0000, 0x0400 }, /* 9761-78 & 82 */ { 0x0000, 0x0400 }, /* 9761-82 rev.B */ { 0x0000, 0x0400 }, /* 9761-83 */ }; static unsigned short clfe_shared[3][2] = { { 0x2000, 0x0880 }, /* 9761-78 & 82 */ { 0x0000, 0x2880 }, /* 9761-82 rev.B */ { 0x2000, 0x0800 }, /* 9761-83 */ }; unsigned short val = 0; val |= surr_on[ac97->spec.dev_flags][is_surround_on(ac97)]; val |= clfe_on[ac97->spec.dev_flags][is_clfe_on(ac97)]; val |= surr_shared[ac97->spec.dev_flags][is_shared_surrout(ac97)]; val |= clfe_shared[ac97->spec.dev_flags][is_shared_clfeout(ac97)]; snd_ac97_update_bits(ac97, AC97_CM9761_MULTI_CHAN, 0x3c88, val); } static const struct snd_kcontrol_new snd_ac97_cm9761_controls[] = { AC97_SURROUND_JACK_MODE_CTL, AC97_CHANNEL_MODE_CTL, }; static int cm9761_spdif_out_source_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[] = { "AC-Link", "ADC", "SPDIF-In" }; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 3; if (uinfo->value.enumerated.item > 2) uinfo->value.enumerated.item = 2; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int cm9761_spdif_out_source_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); if (ac97->regs[AC97_CM9761_FUNC] & 0x1) ucontrol->value.enumerated.item[0] = 2; /* SPDIF-loopback */ else if (ac97->regs[AC97_CM9761_SPDIF_CTRL] & 0x2) ucontrol->value.enumerated.item[0] = 1; /* ADC loopback */ else ucontrol->value.enumerated.item[0] = 0; /* AC-link */ return 0; } static int cm9761_spdif_out_source_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_ac97 *ac97 = snd_kcontrol_chip(kcontrol); if (ucontrol->value.enumerated.item[0] == 2) return snd_ac97_update_bits(ac97, AC97_CM9761_FUNC, 0x1, 0x1); snd_ac97_update_bits(ac97, AC97_CM9761_FUNC, 0x1, 0); return snd_ac97_update_bits(ac97, AC97_CM9761_SPDIF_CTRL, 0x2, ucontrol->value.enumerated.item[0] == 1 ? 0x2 : 0); } static const char *cm9761_dac_clock[] = { "AC-Link", "SPDIF-In", "Both" }; static const struct ac97_enum cm9761_dac_clock_enum = AC97_ENUM_SINGLE(AC97_CM9761_SPDIF_CTRL, 9, 3, cm9761_dac_clock); static const struct snd_kcontrol_new snd_ac97_cm9761_controls_spdif[] = { { /* BIT 1: SPDIFS */ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,NONE) "Source", .info = cm9761_spdif_out_source_info, .get = cm9761_spdif_out_source_get, .put = cm9761_spdif_out_source_put, }, /* BIT 2: IG_SPIV */ AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,NONE) "Valid Switch", AC97_CM9761_SPDIF_CTRL, 2, 1, 0), /* BIT 3: SPI2F */ AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,NONE) "Monitor", AC97_CM9761_SPDIF_CTRL, 3, 1, 0), /* BIT 4: SPI2SDI */ AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH), AC97_CM9761_SPDIF_CTRL, 4, 1, 0), /* BIT 9-10: DAC_CTL */ AC97_ENUM("DAC Clock Source", cm9761_dac_clock_enum), }; static int patch_cm9761_post_spdif(struct snd_ac97 * ac97) { return patch_build_controls(ac97, snd_ac97_cm9761_controls_spdif, ARRAY_SIZE(snd_ac97_cm9761_controls_spdif)); } static int patch_cm9761_specific(struct snd_ac97 * ac97) { return patch_build_controls(ac97, snd_ac97_cm9761_controls, ARRAY_SIZE(snd_ac97_cm9761_controls)); } static const struct snd_ac97_build_ops patch_cm9761_ops = { .build_specific = patch_cm9761_specific, .build_post_spdif = patch_cm9761_post_spdif, .update_jacks = cm9761_update_jacks }; static int patch_cm9761(struct snd_ac97 *ac97) { unsigned short val; /* CM9761 has no PCM volume although the register reacts */ /* Master volume seems to have _some_ influence on the analog * input sounds */ ac97->flags |= /*AC97_HAS_NO_MASTER_VOL |*/ AC97_HAS_NO_PCM_VOL; snd_ac97_write_cache(ac97, AC97_MASTER, 0x8808); snd_ac97_write_cache(ac97, AC97_PCM, 0x8808); ac97->spec.dev_flags = 0; /* 1 = model 82 revision B, 2 = model 83 */ if (ac97->id == AC97_ID_CM9761_82) { unsigned short tmp; /* check page 1, reg 0x60 */ val = snd_ac97_read(ac97, AC97_INT_PAGING); snd_ac97_write_cache(ac97, AC97_INT_PAGING, (val & ~0x0f) | 0x01); tmp = snd_ac97_read(ac97, 0x60); ac97->spec.dev_flags = tmp & 1; /* revision B? */ snd_ac97_write_cache(ac97, AC97_INT_PAGING, val); } else if (ac97->id == AC97_ID_CM9761_83) ac97->spec.dev_flags = 2; ac97->build_ops = &patch_cm9761_ops; /* enable spdif */ /* force the SPDIF bit in ext_id - codec doesn't set this bit! */ ac97->ext_id |= AC97_EI_SPDIF; /* to be sure: we overwrite the ext status bits */ snd_ac97_write_cache(ac97, AC97_EXTENDED_STATUS, 0x05c0); /* Don't set 0x0200 here. This results in the silent analog output */ snd_ac97_write_cache(ac97, AC97_CM9761_SPDIF_CTRL, 0x0001); /* enable spdif-in */ ac97->rates[AC97_RATES_SPDIF] = SNDRV_PCM_RATE_48000; /* 48k only */ /* set-up multi channel */ /* bit 15: pc master beep off * bit 14: pin47 = EAPD/SPDIF * bit 13: vref ctl [= cm9739] * bit 12: CLFE control (reverted on rev B) * bit 11: Mic/center share (reverted on rev B) * bit 10: suddound/line share * bit 9: Analog-in mix -> surround * bit 8: Analog-in mix -> CLFE * bit 7: Mic/LFE share (mic/center/lfe) * bit 5: vref select (9761A) * bit 4: front control * bit 3: surround control (revereted with rev B) * bit 2: front mic * bit 1: stereo mic * bit 0: mic boost level (0=20dB, 1=30dB) */ #if 0 if (ac97->spec.dev_flags) val = 0x0214; else val = 0x321c; #endif val = snd_ac97_read(ac97, AC97_CM9761_MULTI_CHAN); val |= (1 << 4); /* front on */ snd_ac97_write_cache(ac97, AC97_CM9761_MULTI_CHAN, val); /* FIXME: set up GPIO */ snd_ac97_write_cache(ac97, 0x70, 0x0100); snd_ac97_write_cache(ac97, 0x72, 0x0020); return 0; } #define AC97_CM9780_SIDE 0x60 #define AC97_CM9780_JACK 0x62 #define AC97_CM9780_MIXER 0x64 #define AC97_CM9780_MULTI_CHAN 0x66 #define AC97_CM9780_SPDIF 0x6c static const char *cm9780_ch_select[] = { "Front", "Side", "Center/LFE", "Rear" }; static const struct ac97_enum cm9780_ch_select_enum = AC97_ENUM_SINGLE(AC97_CM9780_MULTI_CHAN, 6, 4, cm9780_ch_select); static const struct snd_kcontrol_new cm9780_controls[] = { AC97_DOUBLE("Side Playback Switch", AC97_CM9780_SIDE, 15, 7, 1, 1), AC97_DOUBLE("Side Playback Volume", AC97_CM9780_SIDE, 8, 0, 31, 0), AC97_ENUM("Side Playback Route", cm9780_ch_select_enum), }; static int patch_cm9780_specific(struct snd_ac97 *ac97) { return patch_build_controls(ac97, cm9780_controls, ARRAY_SIZE(cm9780_controls)); } static const struct snd_ac97_build_ops patch_cm9780_ops = { .build_specific = patch_cm9780_specific, .build_post_spdif = patch_cm9761_post_spdif /* identical with CM9761 */ }; static int patch_cm9780(struct snd_ac97 *ac97) { unsigned short val; ac97->build_ops = &patch_cm9780_ops; /* enable spdif */ if (ac97->ext_id & AC97_EI_SPDIF) { ac97->rates[AC97_RATES_SPDIF] = SNDRV_PCM_RATE_48000; /* 48k only */ val = snd_ac97_read(ac97, AC97_CM9780_SPDIF); val |= 0x1; /* SPDI_EN */ snd_ac97_write_cache(ac97, AC97_CM9780_SPDIF, val); } return 0; } /* * VIA VT1616 codec */ static const struct snd_kcontrol_new snd_ac97_controls_vt1616[] = { AC97_SINGLE("DC Offset removal", 0x5a, 10, 1, 0), AC97_SINGLE("Alternate Level to Surround Out", 0x5a, 15, 1, 0), AC97_SINGLE("Downmix LFE and Center to Front", 0x5a, 12, 1, 0), AC97_SINGLE("Downmix Surround to Front", 0x5a, 11, 1, 0), }; static const char *slave_vols_vt1616[] = { "Front Playback Volume", "Surround Playback Volume", "Center Playback Volume", "LFE Playback Volume", NULL }; static const char *slave_sws_vt1616[] = { "Front Playback Switch", "Surround Playback Switch", "Center Playback Switch", "LFE Playback Switch", NULL }; /* find a mixer control element with the given name */ static struct snd_kcontrol *snd_ac97_find_mixer_ctl(struct snd_ac97 *ac97, const char *name) { struct snd_ctl_elem_id id; memset(&id, 0, sizeof(id)); id.iface = SNDRV_CTL_ELEM_IFACE_MIXER; strcpy(id.name, name); return snd_ctl_find_id(ac97->bus->card, &id); } /* create a virtual master control and add slaves */ static int snd_ac97_add_vmaster(struct snd_ac97 *ac97, char *name, const unsigned int *tlv, const char **slaves) { struct snd_kcontrol *kctl; const char **s; int err; kctl = snd_ctl_make_virtual_master(name, tlv); if (!kctl) return -ENOMEM; err = snd_ctl_add(ac97->bus->card, kctl); if (err < 0) return err; for (s = slaves; *s; s++) { struct snd_kcontrol *sctl; sctl = snd_ac97_find_mixer_ctl(ac97, *s); if (!sctl) { snd_printdd("Cannot find slave %s, skipped\n", *s); continue; } err = snd_ctl_add_slave(kctl, sctl); if (err < 0) return err; } return 0; } static int patch_vt1616_specific(struct snd_ac97 * ac97) { struct snd_kcontrol *kctl; int err; if (snd_ac97_try_bit(ac97, 0x5a, 9)) if ((err = patch_build_controls(ac97, &snd_ac97_controls_vt1616[0], 1)) < 0) return err; if ((err = patch_build_controls(ac97, &snd_ac97_controls_vt1616[1], ARRAY_SIZE(snd_ac97_controls_vt1616) - 1)) < 0) return err; /* There is already a misnamed master switch. Rename it. */ kctl = snd_ac97_find_mixer_ctl(ac97, "Master Playback Volume"); if (!kctl) return -EINVAL; snd_ac97_rename_vol_ctl(ac97, "Master Playback", "Front Playback"); err = snd_ac97_add_vmaster(ac97, "Master Playback Volume", kctl->tlv.p, slave_vols_vt1616); if (err < 0) return err; err = snd_ac97_add_vmaster(ac97, "Master Playback Switch", NULL, slave_sws_vt1616); if (err < 0) return err; return 0; } static const struct snd_ac97_build_ops patch_vt1616_ops = { .build_specific = patch_vt1616_specific }; static int patch_vt1616(struct snd_ac97 * ac97) { ac97->build_ops = &patch_vt1616_ops; return 0; } /* * VT1617A codec */ /* * unfortunately, the vt1617a stashes the twiddlers required for * noodling the i/o jacks on 2 different regs. that means that we can't * use the easy way provided by AC97_ENUM_DOUBLE() we have to write * are own funcs. * * NB: this is absolutely and utterly different from the vt1618. dunno * about the 1616. */ /* copied from ac97_surround_jack_mode_info() */ static int snd_ac97_vt1617a_smart51_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { /* ordering in this list reflects vt1617a docs for Reg 20 and * 7a and Table 6 that lays out the matrix NB WRT Table6: SM51 * is SM51EN *AND* it's Bit14, not Bit15 so the table is very * counter-intuitive */ static const char* texts[] = { "LineIn Mic1", "LineIn Mic1 Mic3", "Surr LFE/C Mic3", "LineIn LFE/C Mic3", "LineIn Mic2", "LineIn Mic2 Mic1", "Surr LFE Mic1", "Surr LFE Mic1 Mic2"}; return ac97_enum_text_info(kcontrol, uinfo, texts, 8); } static int snd_ac97_vt1617a_smart51_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { ushort usSM51, usMS; struct snd_ac97 *pac97; pac97 = snd_kcontrol_chip(kcontrol); /* grab codec handle */ /* grab our desired bits, then mash them together in a manner * consistent with Table 6 on page 17 in the 1617a docs */ usSM51 = snd_ac97_read(pac97, 0x7a) >> 14; usMS = snd_ac97_read(pac97, 0x20) >> 8; ucontrol->value.enumerated.item[0] = (usSM51 << 1) + usMS; return 0; } static int snd_ac97_vt1617a_smart51_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { ushort usSM51, usMS, usReg; struct snd_ac97 *pac97; pac97 = snd_kcontrol_chip(kcontrol); /* grab codec handle */ usSM51 = ucontrol->value.enumerated.item[0] >> 1; usMS = ucontrol->value.enumerated.item[0] & 1; /* push our values into the register - consider that things will be left * in a funky state if the write fails */ usReg = snd_ac97_read(pac97, 0x7a); snd_ac97_write_cache(pac97, 0x7a, (usReg & 0x3FFF) + (usSM51 << 14)); usReg = snd_ac97_read(pac97, 0x20); snd_ac97_write_cache(pac97, 0x20, (usReg & 0xFEFF) + (usMS << 8)); return 0; } static const struct snd_kcontrol_new snd_ac97_controls_vt1617a[] = { AC97_SINGLE("Center/LFE Exchange", 0x5a, 8, 1, 0), /* * These are used to enable/disable surround sound on motherboards * that have 3 bidirectional analog jacks */ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Smart 5.1 Select", .info = snd_ac97_vt1617a_smart51_info, .get = snd_ac97_vt1617a_smart51_get, .put = snd_ac97_vt1617a_smart51_put, }, }; static int patch_vt1617a(struct snd_ac97 * ac97) { int err = 0; int val; /* we choose to not fail out at this point, but we tell the caller when we return */ err = patch_build_controls(ac97, &snd_ac97_controls_vt1617a[0], ARRAY_SIZE(snd_ac97_controls_vt1617a)); /* bring analog power consumption to normal by turning off the * headphone amplifier, like WinXP driver for EPIA SP */ /* We need to check the bit before writing it. * On some (many?) hardwares, setting bit actually clears it! */ val = snd_ac97_read(ac97, 0x5c); if (!(val & 0x20)) snd_ac97_write_cache(ac97, 0x5c, 0x20); ac97->ext_id |= AC97_EI_SPDIF; /* force the detection of spdif */ ac97->rates[AC97_RATES_SPDIF] = SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000; ac97->build_ops = &patch_vt1616_ops; return err; } /* VIA VT1618 8 CHANNEL AC97 CODEC * * VIA implements 'Smart 5.1' completely differently on the 1618 than * it does on the 1617a. awesome! They seem to have sourced this * particular revision of the technology from somebody else, it's * called Universal Audio Jack and it shows up on some other folk's chips * as well. * * ordering in this list reflects vt1618 docs for Reg 60h and * the block diagram, DACs are as follows: * * OUT_O -> Front, * OUT_1 -> Surround, * OUT_2 -> C/LFE * * Unlike the 1617a, each OUT has a consistent set of mappings * for all bitpatterns other than 00: * * 01 Unmixed Output * 10 Line In * 11 Mic In * * Special Case of 00: * * OUT_0 Mixed Output * OUT_1 Reserved * OUT_2 Reserved * * I have no idea what the hell Reserved does, but on an MSI * CN700T, i have to set it to get 5.1 output - YMMV, bad * shit may happen. * * If other chips use Universal Audio Jack, then this code might be applicable * to them. */ struct vt1618_uaj_item { unsigned short mask; unsigned short shift; const char *items[4]; }; /* This list reflects the vt1618 docs for Vendor Defined Register 0x60. */ static struct vt1618_uaj_item vt1618_uaj[3] = { { /* speaker jack */ .mask = 0x03, .shift = 0, .items = { "Speaker Out", "DAC Unmixed Out", "Line In", "Mic In" } }, { /* line jack */ .mask = 0x0c, .shift = 2, .items = { "Surround Out", "DAC Unmixed Out", "Line In", "Mic In" } }, { /* mic jack */ .mask = 0x30, .shift = 4, .items = { "Center LFE Out", "DAC Unmixed Out", "Line In", "Mic In" }, }, }; static int snd_ac97_vt1618_UAJ_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { return ac97_enum_text_info(kcontrol, uinfo, vt1618_uaj[kcontrol->private_value].items, 4); } /* All of the vt1618 Universal Audio Jack twiddlers are on * Vendor Defined Register 0x60, page 0. The bits, and thus * the mask, are the only thing that changes */ static int snd_ac97_vt1618_UAJ_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { unsigned short datpag, uaj; struct snd_ac97 *pac97 = snd_kcontrol_chip(kcontrol); mutex_lock(&pac97->page_mutex); datpag = snd_ac97_read(pac97, AC97_INT_PAGING) & AC97_PAGE_MASK; snd_ac97_update_bits(pac97, AC97_INT_PAGING, AC97_PAGE_MASK, 0); uaj = snd_ac97_read(pac97, 0x60) & vt1618_uaj[kcontrol->private_value].mask; snd_ac97_update_bits(pac97, AC97_INT_PAGING, AC97_PAGE_MASK, datpag); mutex_unlock(&pac97->page_mutex); ucontrol->value.enumerated.item[0] = uaj >> vt1618_uaj[kcontrol->private_value].shift; return 0; } static int snd_ac97_vt1618_UAJ_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { return ac97_update_bits_page(snd_kcontrol_chip(kcontrol), 0x60, vt1618_uaj[kcontrol->private_value].mask, ucontrol->value.enumerated.item[0]<< vt1618_uaj[kcontrol->private_value].shift, 0); } /* config aux in jack - not found on 3 jack motherboards or soundcards */ static int snd_ac97_vt1618_aux_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static const char *txt_aux[] = {"Aux In", "Back Surr Out"}; return ac97_enum_text_info(kcontrol, uinfo, txt_aux, 2); } static int snd_ac97_vt1618_aux_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { ucontrol->value.enumerated.item[0] = (snd_ac97_read(snd_kcontrol_chip(kcontrol), 0x5c) & 0x0008)>>3; return 0; } static int snd_ac97_vt1618_aux_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { /* toggle surround rear dac power */ snd_ac97_update_bits(snd_kcontrol_chip(kcontrol), 0x5c, 0x0008, ucontrol->value.enumerated.item[0] << 3); /* toggle aux in surround rear out jack */ return snd_ac97_update_bits(snd_kcontrol_chip(kcontrol), 0x76, 0x0008, ucontrol->value.enumerated.item[0] << 3); } static const struct snd_kcontrol_new snd_ac97_controls_vt1618[] = { AC97_SINGLE("Exchange Center/LFE", 0x5a, 8, 1, 0), AC97_SINGLE("DC Offset", 0x5a, 10, 1, 0), AC97_SINGLE("Soft Mute", 0x5c, 0, 1, 1), AC97_SINGLE("Headphone Amp", 0x5c, 5, 1, 1), AC97_DOUBLE("Back Surr Volume", 0x5e, 8, 0, 31, 1), AC97_SINGLE("Back Surr Switch", 0x5e, 15, 1, 1), { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Speaker Jack Mode", .info = snd_ac97_vt1618_UAJ_info, .get = snd_ac97_vt1618_UAJ_get, .put = snd_ac97_vt1618_UAJ_put, .private_value = 0 }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Line Jack Mode", .info = snd_ac97_vt1618_UAJ_info, .get = snd_ac97_vt1618_UAJ_get, .put = snd_ac97_vt1618_UAJ_put, .private_value = 1 }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Mic Jack Mode", .info = snd_ac97_vt1618_UAJ_info, .get = snd_ac97_vt1618_UAJ_get, .put = snd_ac97_vt1618_UAJ_put, .private_value = 2 }, { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Aux Jack Mode", .info = snd_ac97_vt1618_aux_info, .get = snd_ac97_vt1618_aux_get, .put = snd_ac97_vt1618_aux_put, } }; static int patch_vt1618(struct snd_ac97 *ac97) { return patch_build_controls(ac97, snd_ac97_controls_vt1618, ARRAY_SIZE(snd_ac97_controls_vt1618)); } /* */ static void it2646_update_jacks(struct snd_ac97 *ac97) { /* shared Line-In / Surround Out */ snd_ac97_update_bits(ac97, 0x76, 1 << 9, is_shared_surrout(ac97) ? (1<<9) : 0); /* shared Mic / Center/LFE Out */ snd_ac97_update_bits(ac97, 0x76, 1 << 10, is_shared_clfeout(ac97) ? (1<<10) : 0); } static const struct snd_kcontrol_new snd_ac97_controls_it2646[] = { AC97_SURROUND_JACK_MODE_CTL, AC97_CHANNEL_MODE_CTL, }; static const struct snd_kcontrol_new snd_ac97_spdif_controls_it2646[] = { AC97_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH), 0x76, 11, 1, 0), AC97_SINGLE("Analog to IEC958 Output", 0x76, 12, 1, 0), AC97_SINGLE("IEC958 Input Monitor", 0x76, 13, 1, 0), }; static int patch_it2646_specific(struct snd_ac97 * ac97) { int err; if ((err = patch_build_controls(ac97, snd_ac97_controls_it2646, ARRAY_SIZE(snd_ac97_controls_it2646))) < 0) return err; if ((err = patch_build_controls(ac97, snd_ac97_spdif_controls_it2646, ARRAY_SIZE(snd_ac97_spdif_controls_it2646))) < 0) return err; return 0; } static const struct snd_ac97_build_ops patch_it2646_ops = { .build_specific = patch_it2646_specific, .update_jacks = it2646_update_jacks }; static int patch_it2646(struct snd_ac97 * ac97) { ac97->build_ops = &patch_it2646_ops; /* full DAC volume */ snd_ac97_write_cache(ac97, 0x5E, 0x0808); snd_ac97_write_cache(ac97, 0x7A, 0x0808); return 0; } /* * Si3036 codec */ #define AC97_SI3036_CHIP_ID 0x5a #define AC97_SI3036_LINE_CFG 0x5c static const struct snd_kcontrol_new snd_ac97_controls_si3036[] = { AC97_DOUBLE("Modem Speaker Volume", 0x5c, 14, 12, 3, 1) }; static int patch_si3036_specific(struct snd_ac97 * ac97) { int idx, err; for (idx = 0; idx < ARRAY_SIZE(snd_ac97_controls_si3036); idx++) if ((err = snd_ctl_add(ac97->bus->card, snd_ctl_new1(&snd_ac97_controls_si3036[idx], ac97))) < 0) return err; return 0; } static const struct snd_ac97_build_ops patch_si3036_ops = { .build_specific = patch_si3036_specific, }; static int mpatch_si3036(struct snd_ac97 * ac97) { ac97->build_ops = &patch_si3036_ops; snd_ac97_write_cache(ac97, 0x5c, 0xf210 ); snd_ac97_write_cache(ac97, 0x68, 0); return 0; } /* * LM 4550 Codec * * We use a static resolution table since LM4550 codec cannot be * properly autoprobed to determine the resolution via * check_volume_resolution(). */ static struct snd_ac97_res_table lm4550_restbl[] = { { AC97_MASTER, 0x1f1f }, { AC97_HEADPHONE, 0x1f1f }, { AC97_MASTER_MONO, 0x001f }, { AC97_PC_BEEP, 0x001f }, /* LSB is ignored */ { AC97_PHONE, 0x001f }, { AC97_MIC, 0x001f }, { AC97_LINE, 0x1f1f }, { AC97_CD, 0x1f1f }, { AC97_VIDEO, 0x1f1f }, { AC97_AUX, 0x1f1f }, { AC97_PCM, 0x1f1f }, { AC97_REC_GAIN, 0x0f0f }, { } /* terminator */ }; static int patch_lm4550(struct snd_ac97 *ac97) { ac97->res_table = lm4550_restbl; return 0; } /* * UCB1400 codec (http://www.semiconductors.philips.com/acrobat_download/datasheets/UCB1400-02.pdf) */ static const struct snd_kcontrol_new snd_ac97_controls_ucb1400[] = { /* enable/disable headphone driver which allows direct connection to stereo headphone without the use of external DC blocking capacitors */ AC97_SINGLE("Headphone Driver", 0x6a, 6, 1, 0), /* Filter used to compensate the DC offset is added in the ADC to remove idle tones from the audio band. */ AC97_SINGLE("DC Filter", 0x6a, 4, 1, 0), /* Control smart-low-power mode feature. Allows automatic power down of unused blocks in the ADC analog front end and the PLL. */ AC97_SINGLE("Smart Low Power Mode", 0x6c, 4, 3, 0), }; static int patch_ucb1400_specific(struct snd_ac97 * ac97) { int idx, err; for (idx = 0; idx < ARRAY_SIZE(snd_ac97_controls_ucb1400); idx++) if ((err = snd_ctl_add(ac97->bus->card, snd_ctl_new1(&snd_ac97_controls_ucb1400[idx], ac97))) < 0) return err; return 0; } static const struct snd_ac97_build_ops patch_ucb1400_ops = { .build_specific = patch_ucb1400_specific, }; static int patch_ucb1400(struct snd_ac97 * ac97) { ac97->build_ops = &patch_ucb1400_ops; /* enable headphone driver and smart low power mode by default */ snd_ac97_write_cache(ac97, 0x6a, 0x0050); snd_ac97_write_cache(ac97, 0x6c, 0x0030); return 0; }
290b23580f03ef02fbbabbc5e047c449dc53950f
526b17ad25eec622b8f266034df3506ca1580ce6
/cups/ppd-emit.c
8bffb2bc3609256358e3d624dcce09555ccc8693
[ "LLVM-exception", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "EPL-1.0", "GPL-2.0-only", "LGPL-2.0-only" ]
permissive
apple/cups
906903c936f9ec702e50dcd9971ec71af90a56fb
ec055da6794984133d48cc376f04e10af62b64dc
refs/heads/master
2023-08-24T17:53:09.249969
2022-06-27T16:22:46
2022-06-27T16:22:46
44,137,852
1,875
570
Apache-2.0
2023-01-19T21:23:20
2015-10-12T22:33:18
C
UTF-8
C
false
false
29,526
c
ppd-emit.c
/* * PPD code emission routines for CUPS. * * Copyright 2007-2019 by Apple Inc. * Copyright 1997-2007 by Easy Software Products, all rights reserved. * * Licensed under Apache License v2.0. See the file "LICENSE" for more * information. * * PostScript is a trademark of Adobe Systems, Inc. */ /* * Include necessary headers... */ #include "cups-private.h" #include "debug-internal.h" #include "ppd.h" #if defined(_WIN32) || defined(__EMX__) # include <io.h> #else # include <unistd.h> #endif /* _WIN32 || __EMX__ */ /* * Local functions... */ static int ppd_compare_cparams(ppd_cparam_t *a, ppd_cparam_t *b); static void ppd_handle_media(ppd_file_t *ppd); /* * Local globals... */ static const char ppd_custom_code[] = "pop pop pop\n" "<</PageSize[5 -2 roll]/ImagingBBox null>>setpagedevice\n"; /* * 'ppdCollect()' - Collect all marked options that reside in the specified * section. * * The choices array should be freed using @code free@ when you are * finished with it. */ int /* O - Number of options marked */ ppdCollect(ppd_file_t *ppd, /* I - PPD file data */ ppd_section_t section, /* I - Section to collect */ ppd_choice_t ***choices) /* O - Pointers to choices */ { return (ppdCollect2(ppd, section, 0.0, choices)); } /* * 'ppdCollect2()' - Collect all marked options that reside in the * specified section and minimum order. * * The choices array should be freed using @code free@ when you are * finished with it. * * @since CUPS 1.2/macOS 10.5@ */ int /* O - Number of options marked */ ppdCollect2(ppd_file_t *ppd, /* I - PPD file data */ ppd_section_t section, /* I - Section to collect */ float min_order, /* I - Minimum OrderDependency value */ ppd_choice_t ***choices) /* O - Pointers to choices */ { ppd_choice_t *c; /* Current choice */ ppd_section_t csection; /* Current section */ float corder; /* Current OrderDependency value */ int count; /* Number of choices collected */ ppd_choice_t **collect; /* Collected choices */ float *orders; /* Collected order values */ DEBUG_printf(("ppdCollect2(ppd=%p, section=%d, min_order=%f, choices=%p)", ppd, section, min_order, choices)); if (!ppd || !choices) { if (choices) *choices = NULL; return (0); } /* * Allocate memory for up to N selected choices... */ count = 0; if ((collect = calloc(sizeof(ppd_choice_t *), (size_t)cupsArrayCount(ppd->marked))) == NULL) { *choices = NULL; return (0); } if ((orders = calloc(sizeof(float), (size_t)cupsArrayCount(ppd->marked))) == NULL) { *choices = NULL; free(collect); return (0); } /* * Loop through all options and add choices as needed... */ for (c = (ppd_choice_t *)cupsArrayFirst(ppd->marked); c; c = (ppd_choice_t *)cupsArrayNext(ppd->marked)) { csection = c->option->section; corder = c->option->order; if (!strcmp(c->choice, "Custom")) { ppd_attr_t *attr; /* NonUIOrderDependency value */ float aorder; /* Order value */ char asection[17], /* Section name */ amain[PPD_MAX_NAME + 1], aoption[PPD_MAX_NAME]; /* *CustomFoo and True */ for (attr = ppdFindAttr(ppd, "NonUIOrderDependency", NULL); attr; attr = ppdFindNextAttr(ppd, "NonUIOrderDependency", NULL)) if (attr->value && sscanf(attr->value, "%f%16s%41s%40s", &aorder, asection, amain, aoption) == 4 && !strncmp(amain, "*Custom", 7) && !strcmp(amain + 7, c->option->keyword) && !strcmp(aoption, "True")) { /* * Use this NonUIOrderDependency... */ corder = aorder; if (!strcmp(asection, "DocumentSetup")) csection = PPD_ORDER_DOCUMENT; else if (!strcmp(asection, "ExitServer")) csection = PPD_ORDER_EXIT; else if (!strcmp(asection, "JCLSetup")) csection = PPD_ORDER_JCL; else if (!strcmp(asection, "PageSetup")) csection = PPD_ORDER_PAGE; else if (!strcmp(asection, "Prolog")) csection = PPD_ORDER_PROLOG; else csection = PPD_ORDER_ANY; break; } } if (csection == section && corder >= min_order) { collect[count] = c; orders[count] = corder; count ++; } } /* * If we have more than 1 marked choice, sort them... */ if (count > 1) { int i, j; /* Looping vars */ for (i = 0; i < (count - 1); i ++) for (j = i + 1; j < count; j ++) if (orders[i] > orders[j]) { c = collect[i]; corder = orders[i]; collect[i] = collect[j]; orders[i] = orders[j]; collect[j] = c; orders[j] = corder; } } free(orders); DEBUG_printf(("2ppdCollect2: %d marked choices...", count)); /* * Return the array and number of choices; if 0, free the array since * it isn't needed. */ if (count > 0) { *choices = collect; return (count); } else { *choices = NULL; free(collect); return (0); } } /* * 'ppdEmit()' - Emit code for marked options to a file. */ int /* O - 0 on success, -1 on failure */ ppdEmit(ppd_file_t *ppd, /* I - PPD file record */ FILE *fp, /* I - File to write to */ ppd_section_t section) /* I - Section to write */ { return (ppdEmitAfterOrder(ppd, fp, section, 0, 0.0)); } /* * 'ppdEmitAfterOrder()' - Emit a subset of the code for marked options to a file. * * When "limit" is non-zero, this function only emits options whose * OrderDependency value is greater than or equal to "min_order". * * When "limit" is zero, this function is identical to ppdEmit(). * * @since CUPS 1.2/macOS 10.5@ */ int /* O - 0 on success, -1 on failure */ ppdEmitAfterOrder( ppd_file_t *ppd, /* I - PPD file record */ FILE *fp, /* I - File to write to */ ppd_section_t section, /* I - Section to write */ int limit, /* I - Non-zero to use min_order */ float min_order) /* I - Lowest OrderDependency */ { char *buffer; /* Option code */ int status; /* Return status */ /* * Range check input... */ if (!ppd || !fp) return (-1); /* * Get the string... */ buffer = ppdEmitString(ppd, section, limit ? min_order : 0.0f); /* * Write it as needed and return... */ if (buffer) { status = fputs(buffer, fp) < 0 ? -1 : 0; free(buffer); } else status = 0; return (status); } /* * 'ppdEmitFd()' - Emit code for marked options to a file. */ int /* O - 0 on success, -1 on failure */ ppdEmitFd(ppd_file_t *ppd, /* I - PPD file record */ int fd, /* I - File to write to */ ppd_section_t section) /* I - Section to write */ { char *buffer, /* Option code */ *bufptr; /* Pointer into code */ size_t buflength; /* Length of option code */ ssize_t bytes; /* Bytes written */ int status; /* Return status */ /* * Range check input... */ if (!ppd || fd < 0) return (-1); /* * Get the string... */ buffer = ppdEmitString(ppd, section, 0.0); /* * Write it as needed and return... */ if (buffer) { buflength = strlen(buffer); bufptr = buffer; bytes = 0; while (buflength > 0) { #ifdef _WIN32 if ((bytes = (ssize_t)write(fd, bufptr, (unsigned)buflength)) < 0) #else if ((bytes = write(fd, bufptr, buflength)) < 0) #endif /* _WIN32 */ { if (errno == EAGAIN || errno == EINTR) continue; break; } buflength -= (size_t)bytes; bufptr += bytes; } status = bytes < 0 ? -1 : 0; free(buffer); } else status = 0; return (status); } /* * 'ppdEmitJCL()' - Emit code for JCL options to a file. */ int /* O - 0 on success, -1 on failure */ ppdEmitJCL(ppd_file_t *ppd, /* I - PPD file record */ FILE *fp, /* I - File to write to */ int job_id, /* I - Job ID */ const char *user, /* I - Username */ const char *title) /* I - Title */ { char *ptr; /* Pointer into JCL string */ char temp[65], /* Local title string */ displaymsg[33]; /* Local display string */ /* * Range check the input... */ if (!ppd || !ppd->jcl_begin || !ppd->jcl_ps) return (0); /* * See if the printer supports HP PJL... */ if (!strncmp(ppd->jcl_begin, "\033%-12345X@", 10)) { /* * This printer uses HP PJL commands for output; filter the output * so that we only have a single "@PJL JOB" command in the header... * * To avoid bugs in the PJL implementation of certain vendors' products * (Xerox in particular), we add a dummy "@PJL" command at the beginning * of the PJL commands to initialize PJL processing. */ ppd_attr_t *charset; /* PJL charset */ ppd_attr_t *display; /* PJL display command */ if ((charset = ppdFindAttr(ppd, "cupsPJLCharset", NULL)) != NULL) { if (!charset->value || _cups_strcasecmp(charset->value, "UTF-8")) charset = NULL; } if ((display = ppdFindAttr(ppd, "cupsPJLDisplay", NULL)) != NULL) { if (!display->value) display = NULL; } fputs("\033%-12345X@PJL\n", fp); for (ptr = ppd->jcl_begin + 9; *ptr;) if (!strncmp(ptr, "@PJL JOB", 8)) { /* * Skip job command... */ for (;*ptr; ptr ++) if (*ptr == '\n') break; if (*ptr) ptr ++; } else { /* * Copy line... */ for (;*ptr; ptr ++) { putc(*ptr, fp); if (*ptr == '\n') break; } if (*ptr) ptr ++; } /* * Clean up the job title... */ if (!title) title = "Unknown"; if ((ptr = strrchr(title, '/')) != NULL) { /* * Only show basename of file path... */ title = ptr + 1; } if (!strncmp(title, "smbprn.", 7)) { /* * Skip leading smbprn.######## from Samba jobs... */ for (title += 7; *title && isdigit(*title & 255); title ++); while (_cups_isspace(*title)) title ++; if ((ptr = strstr(title, " - ")) != NULL) { /* * Skip application name in "Some Application - Title of job"... */ title = ptr + 3; } } /* * Replace double quotes with single quotes and UTF-8 characters with * question marks so that the title does not cause a PJL syntax error. */ strlcpy(temp, title, sizeof(temp)); for (ptr = temp; *ptr; ptr ++) if (*ptr == '\"') *ptr = '\''; else if (!charset && (*ptr & 128)) *ptr = '?'; /* * CUPS STR #3125: Long PJL JOB NAME causes problems with some printers * * Generate the display message, truncating at 32 characters + nul to avoid * issues with some printer's PJL implementations... */ if (!user) user = "anonymous"; snprintf(displaymsg, sizeof(displaymsg), "%d %s %s", job_id, user, temp); /* * Send PJL JOB and PJL RDYMSG commands before we enter PostScript mode... */ if (display && strcmp(display->value, "job")) fprintf(fp, "@PJL JOB NAME = \"%s\"\n", temp); else if (display && !strcmp(display->value, "rdymsg")) fprintf(fp, "@PJL RDYMSG DISPLAY = \"%s\"\n", displaymsg); else fprintf(fp, "@PJL JOB NAME = \"%s\" DISPLAY = \"%s\"\n", temp, displaymsg); /* * Replace double quotes with single quotes and UTF-8 characters with * question marks so that the user does not cause a PJL syntax error. */ strlcpy(temp, user, sizeof(temp)); for (ptr = temp; *ptr; ptr ++) if (*ptr == '\"') *ptr = '\''; else if (!charset && (*ptr & 128)) *ptr = '?'; fprintf(fp, "@PJL SET USERNAME = \"%s\"\n", temp); } else fputs(ppd->jcl_begin, fp); ppdEmit(ppd, fp, PPD_ORDER_JCL); fputs(ppd->jcl_ps, fp); return (0); } /* * 'ppdEmitJCLEnd()' - Emit JCLEnd code to a file. * * @since CUPS 1.2/macOS 10.5@ */ int /* O - 0 on success, -1 on failure */ ppdEmitJCLEnd(ppd_file_t *ppd, /* I - PPD file record */ FILE *fp) /* I - File to write to */ { /* * Range check the input... */ if (!ppd) return (0); if (!ppd->jcl_end) { if (ppd->num_filters == 0) putc(0x04, fp); return (0); } /* * See if the printer supports HP PJL... */ if (!strncmp(ppd->jcl_end, "\033%-12345X@", 10)) { /* * This printer uses HP PJL commands for output; filter the output * so that we only have a single "@PJL JOB" command in the header... * * To avoid bugs in the PJL implementation of certain vendors' products * (Xerox in particular), we add a dummy "@PJL" command at the beginning * of the PJL commands to initialize PJL processing. */ fputs("\033%-12345X@PJL\n", fp); fputs("@PJL RDYMSG DISPLAY = \"\"\n", fp); fputs(ppd->jcl_end + 9, fp); } else fputs(ppd->jcl_end, fp); return (0); } /* * 'ppdEmitString()' - Get a string containing the code for marked options. * * When "min_order" is greater than zero, this function only includes options * whose OrderDependency value is greater than or equal to "min_order". * Otherwise, all options in the specified section are included in the * returned string. * * The return string is allocated on the heap and should be freed using * @code free@ when you are done with it. * * @since CUPS 1.2/macOS 10.5@ */ char * /* O - String containing option code or @code NULL@ if there is no option code */ ppdEmitString(ppd_file_t *ppd, /* I - PPD file record */ ppd_section_t section, /* I - Section to write */ float min_order) /* I - Lowest OrderDependency */ { int i, j, /* Looping vars */ count; /* Number of choices */ ppd_choice_t **choices; /* Choices */ ppd_size_t *size; /* Custom page size */ ppd_coption_t *coption; /* Custom option */ ppd_cparam_t *cparam; /* Custom parameter */ size_t bufsize; /* Size of string buffer needed */ char *buffer, /* String buffer */ *bufptr, /* Pointer into buffer */ *bufend; /* End of buffer */ struct lconv *loc; /* Locale data */ DEBUG_printf(("ppdEmitString(ppd=%p, section=%d, min_order=%f)", ppd, section, min_order)); /* * Range check input... */ if (!ppd) return (NULL); /* * Use PageSize or PageRegion as required... */ ppd_handle_media(ppd); /* * Collect the options we need to emit... */ if ((count = ppdCollect2(ppd, section, min_order, &choices)) == 0) return (NULL); /* * Count the number of bytes that are required to hold all of the * option code... */ for (i = 0, bufsize = 1; i < count; i ++) { if (section == PPD_ORDER_JCL) { if (!_cups_strcasecmp(choices[i]->choice, "Custom") && (coption = ppdFindCustomOption(ppd, choices[i]->option->keyword)) != NULL) { /* * Add space to account for custom parameter substitution... */ for (cparam = (ppd_cparam_t *)cupsArrayFirst(coption->params); cparam; cparam = (ppd_cparam_t *)cupsArrayNext(coption->params)) { switch (cparam->type) { case PPD_CUSTOM_UNKNOWN : break; case PPD_CUSTOM_CURVE : case PPD_CUSTOM_INVCURVE : case PPD_CUSTOM_POINTS : case PPD_CUSTOM_REAL : case PPD_CUSTOM_INT : bufsize += 10; break; case PPD_CUSTOM_PASSCODE : case PPD_CUSTOM_PASSWORD : case PPD_CUSTOM_STRING : if (cparam->current.custom_string) bufsize += strlen(cparam->current.custom_string); break; } } } } else if (section != PPD_ORDER_EXIT) { bufsize += 3; /* [{\n */ if ((!_cups_strcasecmp(choices[i]->option->keyword, "PageSize") || !_cups_strcasecmp(choices[i]->option->keyword, "PageRegion")) && !_cups_strcasecmp(choices[i]->choice, "Custom")) { DEBUG_puts("2ppdEmitString: Custom size set!"); bufsize += 37; /* %%BeginFeature: *CustomPageSize True\n */ bufsize += 50; /* Five 9-digit numbers + newline */ } else if (!_cups_strcasecmp(choices[i]->choice, "Custom") && (coption = ppdFindCustomOption(ppd, choices[i]->option->keyword)) != NULL) { bufsize += 23 + strlen(choices[i]->option->keyword) + 6; /* %%BeginFeature: *Customkeyword True\n */ for (cparam = (ppd_cparam_t *)cupsArrayFirst(coption->params); cparam; cparam = (ppd_cparam_t *)cupsArrayNext(coption->params)) { switch (cparam->type) { case PPD_CUSTOM_UNKNOWN : break; case PPD_CUSTOM_CURVE : case PPD_CUSTOM_INVCURVE : case PPD_CUSTOM_POINTS : case PPD_CUSTOM_REAL : case PPD_CUSTOM_INT : bufsize += 10; break; case PPD_CUSTOM_PASSCODE : case PPD_CUSTOM_PASSWORD : case PPD_CUSTOM_STRING : bufsize += 3; if (cparam->current.custom_string) bufsize += 4 * strlen(cparam->current.custom_string); break; } } } else bufsize += 17 + strlen(choices[i]->option->keyword) + 1 + strlen(choices[i]->choice) + 1; /* %%BeginFeature: *keyword choice\n */ bufsize += 13; /* %%EndFeature\n */ bufsize += 22; /* } stopped cleartomark\n */ } if (choices[i]->code) bufsize += strlen(choices[i]->code) + 1; else bufsize += strlen(ppd_custom_code); } /* * Allocate memory... */ DEBUG_printf(("2ppdEmitString: Allocating %d bytes for string...", (int)bufsize)); if ((buffer = calloc(1, bufsize)) == NULL) { free(choices); return (NULL); } bufend = buffer + bufsize - 1; loc = localeconv(); /* * Copy the option code to the buffer... */ for (i = 0, bufptr = buffer; i < count; i ++, bufptr += strlen(bufptr)) if (section == PPD_ORDER_JCL) { if (!_cups_strcasecmp(choices[i]->choice, "Custom") && choices[i]->code && (coption = ppdFindCustomOption(ppd, choices[i]->option->keyword)) != NULL) { /* * Handle substitutions in custom JCL options... */ char *cptr; /* Pointer into code */ int pnum; /* Parameter number */ for (cptr = choices[i]->code; *cptr && bufptr < bufend;) { if (*cptr == '\\') { cptr ++; if (isdigit(*cptr & 255)) { /* * Substitute parameter... */ pnum = *cptr++ - '0'; while (isdigit(*cptr & 255)) pnum = pnum * 10 + *cptr++ - '0'; for (cparam = (ppd_cparam_t *)cupsArrayFirst(coption->params); cparam; cparam = (ppd_cparam_t *)cupsArrayNext(coption->params)) if (cparam->order == pnum) break; if (cparam) { switch (cparam->type) { case PPD_CUSTOM_UNKNOWN : break; case PPD_CUSTOM_CURVE : case PPD_CUSTOM_INVCURVE : case PPD_CUSTOM_POINTS : case PPD_CUSTOM_REAL : bufptr = _cupsStrFormatd(bufptr, bufend, cparam->current.custom_real, loc); break; case PPD_CUSTOM_INT : snprintf(bufptr, (size_t)(bufend - bufptr), "%d", cparam->current.custom_int); bufptr += strlen(bufptr); break; case PPD_CUSTOM_PASSCODE : case PPD_CUSTOM_PASSWORD : case PPD_CUSTOM_STRING : if (cparam->current.custom_string) { strlcpy(bufptr, cparam->current.custom_string, (size_t)(bufend - bufptr)); bufptr += strlen(bufptr); } break; } } } else if (*cptr) *bufptr++ = *cptr++; } else *bufptr++ = *cptr++; } } else if (choices[i]->code) { /* * Otherwise just copy the option code directly... */ strlcpy(bufptr, choices[i]->code, (size_t)(bufend - bufptr + 1)); bufptr += strlen(bufptr); } } else if (section != PPD_ORDER_EXIT) { /* * Add wrapper commands to prevent printer errors for unsupported * options... */ strlcpy(bufptr, "[{\n", (size_t)(bufend - bufptr + 1)); bufptr += 3; /* * Send DSC comments with option... */ DEBUG_printf(("2ppdEmitString: Adding code for %s=%s...", choices[i]->option->keyword, choices[i]->choice)); if ((!_cups_strcasecmp(choices[i]->option->keyword, "PageSize") || !_cups_strcasecmp(choices[i]->option->keyword, "PageRegion")) && !_cups_strcasecmp(choices[i]->choice, "Custom")) { /* * Variable size; write out standard size options, using the * parameter positions defined in the PPD file... */ ppd_attr_t *attr; /* PPD attribute */ int pos, /* Position of custom value */ orientation; /* Orientation to use */ float values[5]; /* Values for custom command */ strlcpy(bufptr, "%%BeginFeature: *CustomPageSize True\n", (size_t)(bufend - bufptr + 1)); bufptr += 37; size = ppdPageSize(ppd, "Custom"); memset(values, 0, sizeof(values)); if ((attr = ppdFindAttr(ppd, "ParamCustomPageSize", "Width")) != NULL) { pos = atoi(attr->value) - 1; if (pos < 0 || pos > 4) pos = 0; } else pos = 0; values[pos] = size->width; if ((attr = ppdFindAttr(ppd, "ParamCustomPageSize", "Height")) != NULL) { pos = atoi(attr->value) - 1; if (pos < 0 || pos > 4) pos = 1; } else pos = 1; values[pos] = size->length; /* * According to the Adobe PPD specification, an orientation of 1 * will produce a print that comes out upside-down with the X * axis perpendicular to the direction of feed, which is exactly * what we want to be consistent with non-PS printers. * * We could also use an orientation of 3 to produce output that * comes out rightside-up (this is the default for many large format * printer PPDs), however for consistency we will stick with the * value 1. * * If we wanted to get fancy, we could use orientations of 0 or * 2 and swap the width and length, however we don't want to get * fancy, we just want it to work consistently. * * The orientation value is range limited by the Orientation * parameter definition, so certain non-PS printer drivers that * only support an Orientation of 0 will get the value 0 as * expected. */ orientation = 1; if ((attr = ppdFindAttr(ppd, "ParamCustomPageSize", "Orientation")) != NULL) { int min_orient, max_orient; /* Minimum and maximum orientations */ if (sscanf(attr->value, "%d%*s%d%d", &pos, &min_orient, &max_orient) != 3) pos = 4; else { pos --; if (pos < 0 || pos > 4) pos = 4; if (orientation > max_orient) orientation = max_orient; else if (orientation < min_orient) orientation = min_orient; } } else pos = 4; values[pos] = (float)orientation; for (pos = 0; pos < 5; pos ++) { bufptr = _cupsStrFormatd(bufptr, bufend, values[pos], loc); *bufptr++ = '\n'; } if (!choices[i]->code) { /* * This can happen with certain buggy PPD files that don't include * a CustomPageSize command sequence... We just use a generic * Level 2 command sequence... */ strlcpy(bufptr, ppd_custom_code, (size_t)(bufend - bufptr + 1)); bufptr += strlen(bufptr); } } else if (!_cups_strcasecmp(choices[i]->choice, "Custom") && (coption = ppdFindCustomOption(ppd, choices[i]->option->keyword)) != NULL) { /* * Custom option... */ const char *s; /* Pointer into string value */ cups_array_t *params; /* Parameters in the correct output order */ params = cupsArrayNew((cups_array_func_t)ppd_compare_cparams, NULL); for (cparam = (ppd_cparam_t *)cupsArrayFirst(coption->params); cparam; cparam = (ppd_cparam_t *)cupsArrayNext(coption->params)) cupsArrayAdd(params, cparam); snprintf(bufptr, (size_t)(bufend - bufptr + 1), "%%%%BeginFeature: *Custom%s True\n", coption->keyword); bufptr += strlen(bufptr); for (cparam = (ppd_cparam_t *)cupsArrayFirst(params); cparam; cparam = (ppd_cparam_t *)cupsArrayNext(params)) { switch (cparam->type) { case PPD_CUSTOM_UNKNOWN : break; case PPD_CUSTOM_CURVE : case PPD_CUSTOM_INVCURVE : case PPD_CUSTOM_POINTS : case PPD_CUSTOM_REAL : bufptr = _cupsStrFormatd(bufptr, bufend, cparam->current.custom_real, loc); *bufptr++ = '\n'; break; case PPD_CUSTOM_INT : snprintf(bufptr, (size_t)(bufend - bufptr + 1), "%d\n", cparam->current.custom_int); bufptr += strlen(bufptr); break; case PPD_CUSTOM_PASSCODE : case PPD_CUSTOM_PASSWORD : case PPD_CUSTOM_STRING : *bufptr++ = '('; if (cparam->current.custom_string) { for (s = cparam->current.custom_string; *s; s ++) { if (*s < ' ' || *s == '(' || *s == ')' || *s >= 127) { snprintf(bufptr, (size_t)(bufend - bufptr + 1), "\\%03o", *s & 255); bufptr += strlen(bufptr); } else *bufptr++ = *s; } } *bufptr++ = ')'; *bufptr++ = '\n'; break; } } cupsArrayDelete(params); } else { snprintf(bufptr, (size_t)(bufend - bufptr + 1), "%%%%BeginFeature: *%s %s\n", choices[i]->option->keyword, choices[i]->choice); bufptr += strlen(bufptr); } if (choices[i]->code && choices[i]->code[0]) { j = (int)strlen(choices[i]->code); memcpy(bufptr, choices[i]->code, (size_t)j); bufptr += j; if (choices[i]->code[j - 1] != '\n') *bufptr++ = '\n'; } strlcpy(bufptr, "%%EndFeature\n" "} stopped cleartomark\n", (size_t)(bufend - bufptr + 1)); bufptr += strlen(bufptr); DEBUG_printf(("2ppdEmitString: Offset in string is %d...", (int)(bufptr - buffer))); } else if (choices[i]->code) { strlcpy(bufptr, choices[i]->code, (size_t)(bufend - bufptr + 1)); bufptr += strlen(bufptr); } /* * Nul-terminate, free, and return... */ *bufptr = '\0'; free(choices); return (buffer); } /* * 'ppd_compare_cparams()' - Compare the order of two custom parameters. */ static int /* O - Result of comparison */ ppd_compare_cparams(ppd_cparam_t *a, /* I - First parameter */ ppd_cparam_t *b) /* I - Second parameter */ { return (a->order - b->order); } /* * 'ppd_handle_media()' - Handle media selection... */ static void ppd_handle_media(ppd_file_t *ppd) /* I - PPD file */ { ppd_choice_t *manual_feed, /* ManualFeed choice, if any */ *input_slot; /* InputSlot choice, if any */ ppd_size_t *size; /* Current media size */ ppd_attr_t *rpr; /* RequiresPageRegion value */ /* * This function determines what page size code to use, if any, for the * current media size, InputSlot, and ManualFeed selections. * * We use the PageSize code if: * * 1. A custom media size is selected. * 2. ManualFeed and InputSlot are not selected (or do not exist). * 3. ManualFeed is selected but is False and InputSlot is not selected or * the selection has no code - the latter check done to support "auto" or * "printer default" InputSlot options. * * We use the PageRegion code if: * * 4. RequiresPageRegion does not exist and the PPD contains cupsFilter * keywords, indicating this is a CUPS-based driver. * 5. RequiresPageRegion exists for the selected InputSlot (or "All" for any * InputSlot or ManualFeed selection) and is True. * * If none of the 5 conditions are true, no page size code is used and we * unmark any existing PageSize or PageRegion choices. */ if ((size = ppdPageSize(ppd, NULL)) == NULL) return; manual_feed = ppdFindMarkedChoice(ppd, "ManualFeed"); input_slot = ppdFindMarkedChoice(ppd, "InputSlot"); if (input_slot != NULL) rpr = ppdFindAttr(ppd, "RequiresPageRegion", input_slot->choice); else rpr = NULL; if (!rpr) rpr = ppdFindAttr(ppd, "RequiresPageRegion", "All"); if (!_cups_strcasecmp(size->name, "Custom") || (!manual_feed && !input_slot) || (manual_feed && !_cups_strcasecmp(manual_feed->choice, "False") && (!input_slot || (input_slot->code && !input_slot->code[0]))) || (!rpr && ppd->num_filters > 0)) { /* * Use PageSize code... */ ppdMarkOption(ppd, "PageSize", size->name); } else if (rpr && rpr->value && !_cups_strcasecmp(rpr->value, "True")) { /* * Use PageRegion code... */ ppdMarkOption(ppd, "PageRegion", size->name); } else { /* * Do not use PageSize or PageRegion code... */ ppd_choice_t *page; /* PageSize/Region choice, if any */ if ((page = ppdFindMarkedChoice(ppd, "PageSize")) != NULL) { /* * Unmark PageSize... */ page->marked = 0; cupsArrayRemove(ppd->marked, page); } if ((page = ppdFindMarkedChoice(ppd, "PageRegion")) != NULL) { /* * Unmark PageRegion... */ page->marked = 0; cupsArrayRemove(ppd->marked, page); } } }
81110dc3513c34e980ad44790f5118b1fd661e30
607bb971c8fd33ad3df748c492ba77ec92159c42
/tools/kfold/k_fold_parameters.c
5b16ff648a3eee649d250535f5c66b692a81203e
[ "BSD-2-Clause" ]
permissive
GHamrouni/Recommender
8478c785ad8de16a6e846a334570bd19d6eeac3d
b6cadc8fe611b7dea053568dd131f54c290690f4
refs/heads/master
2022-08-19T14:19:01.840554
2022-07-19T15:21:16
2022-07-19T15:21:16
3,101,244
266
70
BSD-2-Clause
2018-08-28T13:44:06
2012-01-04T10:40:16
C
UTF-8
C
false
false
1,607
c
k_fold_parameters.c
#include"k_fold_parameters.h" #include "matrix_factorization_bias.h" #pragma warning(disable: 4996) k_fold_parameters_t initialize_k_fold_parameters(k_fold_parameters_t _k_fold_params) { k_fold_parameters_t k_fold_params; //k_fold_params->params->users_number=_k_fold_params->users_number; //k_fold_params->params->items_number=_k_fold_params->items_number; k_fold_params->K=_k_fold_params->K; k_fold_params->ratings_number=_k_fold_params->ratings_number; k_fold_params->file_path=(char*)malloc(strlen(_k_fold_params->file_path)+1); strcpy(k_fold_params->file_path,_k_fold_params->file_path); k_fold_params->params->items_number = _k_fold_params->params->items_number; k_fold_params->params->users_number = _k_fold_params->params->users_number; k_fold_params->params->training_set_size = (size_t) (_k_fold_params->ratings_number*((_k_fold_params->K-1)/_k_fold_params->K)); k_fold_params->params->dimensionality = 30; k_fold_params->params->iteration_number = 30; k_fold_params->params->lambda = 0.055f; k_fold_params->params->step = 0.0095f; k_fold_params->params->lambda_bias = 0.02f; k_fold_params->params->step_bias = 0.001f; //Use the bias matrix factorization model k_fold_params->model->learning_algorithm = learn_mf_bias; k_fold_params->model->rating_estimator = estimate_rating_mf_bias; //Use the basic matrix factorization model /*printf("basic \n"); _model->learning_algorithm =learn_basic_mf; _model->rating_estimator = estimate_rating_basic_mf;*/ k_fold_params->model->parameters= k_fold_params->params; return k_fold_params; }
07a0d57222929822be10e6249d368cfcfde63c1e
eb4d06c58aa902fe06055327b90b99a6dacb2ebc
/OHMySQL/lib/MySQL.xcframework/ios-arm64_x86_64-maccatalyst/MySQL.framework/Versions/A/Headers/mysql_command_consumer.h
7315262d8515959f2bfc6883520cc458b436f498
[ "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-mysql-linking-exception-2018", "Universal-FOSS-exception-1.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
oleghnidets/OHMySQL
5c3741afdd866910b473cc267749e017af1900ed
c6afc83187d9527933de016438024f8472aff768
refs/heads/master
2023-07-24T12:03:42.077178
2023-07-07T20:46:40
2023-07-07T20:46:40
41,176,216
250
53
MIT
2023-02-21T20:34:01
2015-08-21T20:31:41
C
UTF-8
C
false
false
13,492
h
mysql_command_consumer.h
/* Copyright (c) 2022, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MYSQL_COMMAND_CONSUMER_H #define MYSQL_COMMAND_CONSUMER_H #include <mysql/components/service.h> #include <mysql/components/services/mysql_command_services.h> #include <cstddef> DEFINE_SERVICE_HANDLE(SRV_CTX_H); DEFINE_SERVICE_HANDLE(DECIMAL_T_H); DEFINE_SERVICE_HANDLE(MYSQL_TIME_H); /** The Field_metadata has the information about the field, which is used by field_metadata() service api. */ struct Field_metadata { const char *db_name; const char *table_name; const char *org_table_name; const char *col_name; const char *org_col_name; unsigned long length; unsigned int charsetnr; unsigned int flags; unsigned int decimals; int type; }; /** An implementation of these services will be called as the data resulting from calling mysql_query() service are produced by the server. Most often the default implementation of this service that will cache the data into a memory structure into the MYSQL handle will be used. But this will only work if the resultset expected is relatively small. @note The default implementation will allow accessing the data after the query execution. This will not be possible with a custom method. If one wants to avoid the memory caching and process the data SAX style as they are returned by the SQL execution define, they should provide their own implementation of this service that will process the data differently at the time of their production. */ /** @ingroup group_components_services_inventory A service that provides the apis for start and end. */ BEGIN_SERVICE_DEFINITION(mysql_text_consumer_factory_v1) /** Prepares the data handle(srv_ctx_h), i.e allocates and prepares the Dom_ctx object and assigned to the srv_ctx_h. @param[out] srv_ctx_h Dom_ctx data handle. @param mysql_h mysql handle used to prepare srv_ctx_h @return status of operation @retval false success. srv_ctx_h was prepared. @retval true failure. OOM or invalid mysql_h. */ DECLARE_BOOL_METHOD(start, (SRV_CTX_H * srv_ctx_h, MYSQL_H *mysql_h)); /** Deallocates the memory allocated for data handle in start api. @param srv_ctx_h dom data handle(Dom_ctx type), which needs to be deallocated. @return status of operation @retval void */ DECLARE_METHOD(void, end, (SRV_CTX_H srv_ctx_h)); END_SERVICE_DEFINITION(mysql_text_consumer_factory_v1) /** @ingroup group_components_services_inventory A service that provides the apis for start_result_metadata, field_metadata, and end_result_metadata. */ BEGIN_SERVICE_DEFINITION(mysql_text_consumer_metadata_v1) /** Indicates beginning of metadata for the result set @param srv_ctx_h Dom_ctx data handle @param num_cols Number of fields being sent @param flags Flags to alter the metadata sending @param collation_name Charset of the result set @return status of operation @retval false success. srv_ctx_h rows were prepared. @retval true failure. OOM or invalid srv_ctx_h. */ DECLARE_BOOL_METHOD(start_result_metadata, (SRV_CTX_H srv_ctx_h, unsigned int num_cols, unsigned int flags, const char *const collation_name)); /** Field metadata is provided to srv_ctx_h via this service api @param srv_ctx_h Dom_ctx data handle @param field Field's metadata (see field.h) @param collation_name Field's charset @return status of operation @retval false success. srv_ctx_h field information prepared. @retval true failure. invalid srv_ctx_h. */ DECLARE_BOOL_METHOD(field_metadata, (SRV_CTX_H srv_ctx_h, struct Field_metadata *field, const char *const collation_name)); /** Indicates end of metadata for the result set @param srv_ctx_h Dom_ctx data handle. @param server_status server status. @param warn_count warning count of current stmt. @return status of operation @retval false success. @retval true failure. */ DECLARE_BOOL_METHOD(end_result_metadata, (SRV_CTX_H srv_ctx_h, unsigned int server_status, unsigned warn_count)); END_SERVICE_DEFINITION(mysql_text_consumer_metadata_v1) /** @ingroup group_components_services_inventory A service that provides the apis for start_row, abort_row and end_row. */ BEGIN_SERVICE_DEFINITION(mysql_text_consumer_row_factory_v1) /** Indicates the beginning of a new row in the result set/metadata @param srv_ctx_h Dom_ctx data handle. @return status of operation @retval false success. @retval true failure. */ DECLARE_BOOL_METHOD(start_row, (SRV_CTX_H srv_ctx_h)); /** An error occurred during execution @details This api indicates that an error occurred during command execution and the partial row should be dropped. Server will raise error and return. @param srv_ctx_h Dom_ctx data handle. @return status of operation @retval false success. @retval true failure. */ DECLARE_BOOL_METHOD(abort_row, (SRV_CTX_H srv_ctx_h)); /** Indicates the end of the current row in the result set/metadata @param srv_ctx_h Dom_ctx data handle. @return status of operation @retval false success. @retval true failure. */ DECLARE_BOOL_METHOD(end_row, (SRV_CTX_H srv_ctx_h)); END_SERVICE_DEFINITION(mysql_text_consumer_row_factory_v1) /** @ingroup group_components_services_inventory A service that provides the apis for handle_ok, handle_error and error. */ BEGIN_SERVICE_DEFINITION(mysql_text_consumer_error_v1) /** Command ended with success @param srv_ctx_h Dom_ctx data handle. @param server_status Status of server (see mysql_com.h, SERVER_STATUS_*) @param statement_warn_count Number of warnings thrown during execution @param affected_rows Number of rows affected by the command @param last_insert_id Last insert id being assigned during execution @param message A message from server */ DECLARE_METHOD(void, handle_ok, (SRV_CTX_H srv_ctx_h, unsigned int server_status, unsigned int statement_warn_count, unsigned long long affected_rows, unsigned long long last_insert_id, const char *const message)); /** Command ended with ERROR, updating the error info into srv_ctx_h. @param srv_ctx_h Dom_ctx data handle. @param sql_errno Error code @param err_msg Error message @param sqlstate SQL state corresponding to the error code */ DECLARE_METHOD(void, handle_error, (SRV_CTX_H srv_ctx_h, unsigned int sql_errno, const char *const err_msg, const char *const sqlstate)); /** Getting the error info from srv_ctx_h. @param srv_ctx_h Dom_ctx data handle. @param err_num Error code @param error_msg Error message @return status of operation @retval false success. @retval true failure. */ DECLARE_BOOL_METHOD(error, (SRV_CTX_H srv_ctx_h, unsigned int *err_num, const char **error_msg)); END_SERVICE_DEFINITION(mysql_text_consumer_error_v1) /** @ingroup group_components_services_inventory A service that provides the apis for get_null. */ BEGIN_SERVICE_DEFINITION(mysql_text_consumer_get_null_v1) /** Receive nullptr value from server and store into srv_ctx_h data. @param srv_ctx_h Dom_ctx data handle. @return status of operation @retval false success. @retval true failure. */ DECLARE_BOOL_METHOD(get, (SRV_CTX_H srv_ctx_h)); END_SERVICE_DEFINITION(mysql_text_consumer_get_null_v1) /** @ingroup group_components_services_inventory A service that provides the apis for get_integer. */ BEGIN_SERVICE_DEFINITION(mysql_text_consumer_get_integer_v1) /** Get TINY/SHORT/LONG value from server and store into srv_ctx_h data. @param srv_ctx_h Dom_ctx data handle. @param value Value received @return status of operation @retval false success. @retval true failure. */ DECLARE_BOOL_METHOD(get, (SRV_CTX_H srv_ctx_h, long long value)); END_SERVICE_DEFINITION(mysql_text_consumer_get_integer_v1) /** @ingroup group_components_services_inventory A service that provides the apis for get_longlong. */ BEGIN_SERVICE_DEFINITION(mysql_text_consumer_get_longlong_v1) /** Get LONGLONG value from server and store into srv_ctx_h data. @param srv_ctx_h Dom_ctx data handle. @param value Value received @param unsigned_flag true <=> value is unsigned @return status of operation @retval false success. @retval true failure. */ DECLARE_BOOL_METHOD(get, (SRV_CTX_H srv_ctx_h, long long value, unsigned int unsigned_flag)); END_SERVICE_DEFINITION(mysql_text_consumer_get_longlong_v1) /** @ingroup group_components_services_inventory A service that provides the apis for get_decimal. */ BEGIN_SERVICE_DEFINITION(mysql_text_consumer_get_decimal_v1) /** Get DECIMAL value from server and store into srv_ctx_h data. @param srv_ctx_h Dom_ctx data handle. @param value Value received @return status of operation @retval false success. @retval true failure. */ DECLARE_BOOL_METHOD(get, (SRV_CTX_H srv_ctx_h, const DECIMAL_T_H value)); END_SERVICE_DEFINITION(mysql_text_consumer_get_decimal_v1) /** @ingroup group_components_services_inventory A service that provides the apis for get_double. and error. */ BEGIN_SERVICE_DEFINITION(mysql_text_consumer_get_double_v1) /** Get FLOAT/DOUBLE value from server and store into srv_ctx_h data. @param srv_ctx_h Dom_ctx data handle. @param value Value received @param decimals Number of decimals @return status of operation @retval false success. @retval true failure. */ DECLARE_BOOL_METHOD(get, (SRV_CTX_H srv_ctx_h, double value, unsigned int decimals)); END_SERVICE_DEFINITION(mysql_text_consumer_get_double_v1) /** @ingroup group_components_services_inventory A service that provides the apis for get_date, get_time and get_datatime. */ BEGIN_SERVICE_DEFINITION(mysql_text_consumer_get_date_time_v1) /** Get DATE value from server and store into srv_ctx_h data. @param srv_ctx_h Dom_ctx data handle. @param value Value received @return status of operation @retval false success. @retval true failure. */ DECLARE_BOOL_METHOD(get_date, (SRV_CTX_H srv_ctx_h, const MYSQL_TIME_H value)); /** Get TIME value from server and store into srv_ctx_h data. @param srv_ctx_h Dom_ctx data handle. @param value Value received @param precision Number of decimals @return status of operation @retval false success. @retval true failure. */ DECLARE_BOOL_METHOD(get_time, (SRV_CTX_H srv_ctx_h, const MYSQL_TIME_H value, unsigned int precision)); /** Get DATETIME value from server and store into srv_ctx_h data. @param srv_ctx_h Dom_ctx data handle. @param value Value received @param precision Number of decimals @return status of operation @retval false success. @retval true failure. */ DECLARE_BOOL_METHOD(get_datatime, (SRV_CTX_H srv_ctx_h, const MYSQL_TIME_H value, unsigned int precision)); END_SERVICE_DEFINITION(mysql_text_consumer_get_date_time_v1) /** @ingroup group_components_services_inventory A service that provides the apis for get_string. */ BEGIN_SERVICE_DEFINITION(mysql_text_consumer_get_string_v1) /** Get STRING value from server and store into srv_ctx_h data. @param srv_ctx_h Dom_ctx data handle. @param value Value received @param length Value's length @param collation_name Value's charset @return status of operation @retval false success. @retval true failure. */ DECLARE_BOOL_METHOD(get_string, (SRV_CTX_H srv_ctx_h, const char *const value, size_t length, const char *const collation_name)); END_SERVICE_DEFINITION(mysql_text_consumer_get_string_v1) /** @ingroup group_components_services_inventory A service that provides the apis for client_capabilities. */ BEGIN_SERVICE_DEFINITION(mysql_text_consumer_client_capabilities_v1) /* Stores server's capabilities into the OUT param. @param srv_ctx_h Dom_ctx data handle. @param[OUT] capabilities contains the server capabilities value. */ DECLARE_METHOD(void, client_capabilities, (SRV_CTX_H srv_ctx_h, unsigned long *capabilities)); END_SERVICE_DEFINITION(mysql_text_consumer_client_capabilities_v1) #endif // MYSQL_COMMAND_CONSUMER_H
c8bd4f73407873d8fec5ea0df37d295f82cf2433
2dfc2beac0ad497f8fc59201921097a412f0df7f
/trunk/3rdparty/ffmpeg-4-fit/libavutil/imgutils.c
afc73e2def16729a40ef0d815736441867415d72
[ "OpenSSL", "JSON", "LGPL-3.0-only", "LGPL-2.0-or-later", "LGPL-3.0-or-later", "IJG", "LicenseRef-scancode-proprietary-license", "MIT", "GPL-2.0-or-later", "LGPL-2.1-or-later", "GPL-3.0-only", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-other-permissive", "GPL-1.0-or-later", "LicenseRef-scancode-mulanpsl-2.0-en", "MulanPSL-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ossrs/srs
cf9442478fedcd32ef2817f8d53f405a6fa2c7d1
7138edd318d30b545e73e80500adda771817f8d1
refs/heads/develop
2023-09-01T03:38:35.057515
2023-08-31T01:45:25
2023-08-31T01:49:36
34,777,562
23,557
5,046
MIT
2023-09-09T00:57:42
2015-04-29T06:59:32
C++
UTF-8
C
false
false
21,144
c
imgutils.c
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * misc image utilities */ #include "avassert.h" #include "common.h" #include "imgutils.h" #include "imgutils_internal.h" #include "internal.h" #include "intreadwrite.h" #include "log.h" #include "mathematics.h" #include "pixdesc.h" #include "rational.h" void av_image_fill_max_pixsteps(int max_pixsteps[4], int max_pixstep_comps[4], const AVPixFmtDescriptor *pixdesc) { int i; memset(max_pixsteps, 0, 4*sizeof(max_pixsteps[0])); if (max_pixstep_comps) memset(max_pixstep_comps, 0, 4*sizeof(max_pixstep_comps[0])); for (i = 0; i < 4; i++) { const AVComponentDescriptor *comp = &(pixdesc->comp[i]); if (comp->step > max_pixsteps[comp->plane]) { max_pixsteps[comp->plane] = comp->step; if (max_pixstep_comps) max_pixstep_comps[comp->plane] = i; } } } static inline int image_get_linesize(int width, int plane, int max_step, int max_step_comp, const AVPixFmtDescriptor *desc) { int s, shifted_w, linesize; if (!desc) return AVERROR(EINVAL); if (width < 0) return AVERROR(EINVAL); s = (max_step_comp == 1 || max_step_comp == 2) ? desc->log2_chroma_w : 0; shifted_w = ((width + (1 << s) - 1)) >> s; if (shifted_w && max_step > INT_MAX / shifted_w) return AVERROR(EINVAL); linesize = max_step * shifted_w; if (desc->flags & AV_PIX_FMT_FLAG_BITSTREAM) linesize = (linesize + 7) >> 3; return linesize; } int av_image_get_linesize(enum AVPixelFormat pix_fmt, int width, int plane) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); int max_step [4]; /* max pixel step for each plane */ int max_step_comp[4]; /* the component for each plane which has the max pixel step */ if (!desc || desc->flags & AV_PIX_FMT_FLAG_HWACCEL) return AVERROR(EINVAL); av_image_fill_max_pixsteps(max_step, max_step_comp, desc); return image_get_linesize(width, plane, max_step[plane], max_step_comp[plane], desc); } int av_image_fill_linesizes(int linesizes[4], enum AVPixelFormat pix_fmt, int width) { int i, ret; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); int max_step [4]; /* max pixel step for each plane */ int max_step_comp[4]; /* the component for each plane which has the max pixel step */ memset(linesizes, 0, 4*sizeof(linesizes[0])); if (!desc || desc->flags & AV_PIX_FMT_FLAG_HWACCEL) return AVERROR(EINVAL); av_image_fill_max_pixsteps(max_step, max_step_comp, desc); for (i = 0; i < 4; i++) { if ((ret = image_get_linesize(width, i, max_step[i], max_step_comp[i], desc)) < 0) return ret; linesizes[i] = ret; } return 0; } int av_image_fill_pointers(uint8_t *data[4], enum AVPixelFormat pix_fmt, int height, uint8_t *ptr, const int linesizes[4]) { int i, total_size, size[4] = { 0 }, has_plane[4] = { 0 }; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); memset(data , 0, sizeof(data[0])*4); if (!desc || desc->flags & AV_PIX_FMT_FLAG_HWACCEL) return AVERROR(EINVAL); data[0] = ptr; if (linesizes[0] > (INT_MAX - 1024) / height) return AVERROR(EINVAL); size[0] = linesizes[0] * height; if (desc->flags & AV_PIX_FMT_FLAG_PAL || desc->flags & FF_PSEUDOPAL) { data[1] = ptr + size[0]; /* palette is stored here as 256 32 bits words */ return size[0] + 256 * 4; } for (i = 0; i < 4; i++) has_plane[desc->comp[i].plane] = 1; total_size = size[0]; for (i = 1; i < 4 && has_plane[i]; i++) { int h, s = (i == 1 || i == 2) ? desc->log2_chroma_h : 0; data[i] = data[i-1] + size[i-1]; h = (height + (1 << s) - 1) >> s; if (linesizes[i] > INT_MAX / h) return AVERROR(EINVAL); size[i] = h * linesizes[i]; if (total_size > INT_MAX - size[i]) return AVERROR(EINVAL); total_size += size[i]; } return total_size; } int avpriv_set_systematic_pal2(uint32_t pal[256], enum AVPixelFormat pix_fmt) { int i; for (i = 0; i < 256; i++) { int r, g, b; switch (pix_fmt) { case AV_PIX_FMT_RGB8: r = (i>>5 )*36; g = ((i>>2)&7)*36; b = (i&3 )*85; break; case AV_PIX_FMT_BGR8: b = (i>>6 )*85; g = ((i>>3)&7)*36; r = (i&7 )*36; break; case AV_PIX_FMT_RGB4_BYTE: r = (i>>3 )*255; g = ((i>>1)&3)*85; b = (i&1 )*255; break; case AV_PIX_FMT_BGR4_BYTE: b = (i>>3 )*255; g = ((i>>1)&3)*85; r = (i&1 )*255; break; case AV_PIX_FMT_GRAY8: r = b = g = i; break; default: return AVERROR(EINVAL); } pal[i] = b + (g << 8) + (r << 16) + (0xFFU << 24); } return 0; } int av_image_alloc(uint8_t *pointers[4], int linesizes[4], int w, int h, enum AVPixelFormat pix_fmt, int align) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); int i, ret; uint8_t *buf; if (!desc) return AVERROR(EINVAL); if ((ret = av_image_check_size(w, h, 0, NULL)) < 0) return ret; if ((ret = av_image_fill_linesizes(linesizes, pix_fmt, align>7 ? FFALIGN(w, 8) : w)) < 0) return ret; for (i = 0; i < 4; i++) linesizes[i] = FFALIGN(linesizes[i], align); if ((ret = av_image_fill_pointers(pointers, pix_fmt, h, NULL, linesizes)) < 0) return ret; buf = av_malloc(ret + align); if (!buf) return AVERROR(ENOMEM); if ((ret = av_image_fill_pointers(pointers, pix_fmt, h, buf, linesizes)) < 0) { av_free(buf); return ret; } if (desc->flags & AV_PIX_FMT_FLAG_PAL || (desc->flags & FF_PSEUDOPAL && pointers[1])) { avpriv_set_systematic_pal2((uint32_t*)pointers[1], pix_fmt); if (align < 4) { av_log(NULL, AV_LOG_ERROR, "Formats with a palette require a minimum alignment of 4\n"); return AVERROR(EINVAL); } } if ((desc->flags & AV_PIX_FMT_FLAG_PAL || desc->flags & FF_PSEUDOPAL) && pointers[1] && pointers[1] - pointers[0] > linesizes[0] * h) { /* zero-initialize the padding before the palette */ memset(pointers[0] + linesizes[0] * h, 0, pointers[1] - pointers[0] - linesizes[0] * h); } return ret; } typedef struct ImgUtils { const AVClass *class; int log_offset; void *log_ctx; } ImgUtils; static const AVClass imgutils_class = { .class_name = "IMGUTILS", .item_name = av_default_item_name, .option = NULL, .version = LIBAVUTIL_VERSION_INT, .log_level_offset_offset = offsetof(ImgUtils, log_offset), .parent_log_context_offset = offsetof(ImgUtils, log_ctx), }; int av_image_check_size2(unsigned int w, unsigned int h, int64_t max_pixels, enum AVPixelFormat pix_fmt, int log_offset, void *log_ctx) { ImgUtils imgutils = { .class = &imgutils_class, .log_offset = log_offset, .log_ctx = log_ctx, }; int64_t stride = av_image_get_linesize(pix_fmt, w, 0); if (stride <= 0) stride = 8LL*w; stride += 128*8; if ((int)w<=0 || (int)h<=0 || stride >= INT_MAX || stride*(uint64_t)(h+128) >= INT_MAX) { av_log(&imgutils, AV_LOG_ERROR, "Picture size %ux%u is invalid\n", w, h); return AVERROR(EINVAL); } if (max_pixels < INT64_MAX) { if (w*(int64_t)h > max_pixels) { av_log(&imgutils, AV_LOG_ERROR, "Picture size %ux%u exceeds specified max pixel count %"PRId64", see the documentation if you wish to increase it\n", w, h, max_pixels); return AVERROR(EINVAL); } } return 0; } int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx) { return av_image_check_size2(w, h, INT64_MAX, AV_PIX_FMT_NONE, log_offset, log_ctx); } int av_image_check_sar(unsigned int w, unsigned int h, AVRational sar) { int64_t scaled_dim; if (sar.den <= 0 || sar.num < 0) return AVERROR(EINVAL); if (!sar.num || sar.num == sar.den) return 0; if (sar.num < sar.den) scaled_dim = av_rescale_rnd(w, sar.num, sar.den, AV_ROUND_ZERO); else scaled_dim = av_rescale_rnd(h, sar.den, sar.num, AV_ROUND_ZERO); if (scaled_dim > 0) return 0; return AVERROR(EINVAL); } static void image_copy_plane(uint8_t *dst, ptrdiff_t dst_linesize, const uint8_t *src, ptrdiff_t src_linesize, ptrdiff_t bytewidth, int height) { if (!dst || !src) return; av_assert0(abs(src_linesize) >= bytewidth); av_assert0(abs(dst_linesize) >= bytewidth); for (;height > 0; height--) { memcpy(dst, src, bytewidth); dst += dst_linesize; src += src_linesize; } } static void image_copy_plane_uc_from(uint8_t *dst, ptrdiff_t dst_linesize, const uint8_t *src, ptrdiff_t src_linesize, ptrdiff_t bytewidth, int height) { int ret = -1; #if ARCH_X86 ret = ff_image_copy_plane_uc_from_x86(dst, dst_linesize, src, src_linesize, bytewidth, height); #endif if (ret < 0) image_copy_plane(dst, dst_linesize, src, src_linesize, bytewidth, height); } void av_image_copy_plane(uint8_t *dst, int dst_linesize, const uint8_t *src, int src_linesize, int bytewidth, int height) { image_copy_plane(dst, dst_linesize, src, src_linesize, bytewidth, height); } static void image_copy(uint8_t *dst_data[4], const ptrdiff_t dst_linesizes[4], const uint8_t *src_data[4], const ptrdiff_t src_linesizes[4], enum AVPixelFormat pix_fmt, int width, int height, void (*copy_plane)(uint8_t *, ptrdiff_t, const uint8_t *, ptrdiff_t, ptrdiff_t, int)) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); if (!desc || desc->flags & AV_PIX_FMT_FLAG_HWACCEL) return; if (desc->flags & AV_PIX_FMT_FLAG_PAL || desc->flags & FF_PSEUDOPAL) { copy_plane(dst_data[0], dst_linesizes[0], src_data[0], src_linesizes[0], width, height); /* copy the palette */ if ((desc->flags & AV_PIX_FMT_FLAG_PAL) || (dst_data[1] && src_data[1])) memcpy(dst_data[1], src_data[1], 4*256); } else { int i, planes_nb = 0; for (i = 0; i < desc->nb_components; i++) planes_nb = FFMAX(planes_nb, desc->comp[i].plane + 1); for (i = 0; i < planes_nb; i++) { int h = height; ptrdiff_t bwidth = av_image_get_linesize(pix_fmt, width, i); if (bwidth < 0) { av_log(NULL, AV_LOG_ERROR, "av_image_get_linesize failed\n"); return; } if (i == 1 || i == 2) { h = AV_CEIL_RSHIFT(height, desc->log2_chroma_h); } copy_plane(dst_data[i], dst_linesizes[i], src_data[i], src_linesizes[i], bwidth, h); } } } void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4], const uint8_t *src_data[4], const int src_linesizes[4], enum AVPixelFormat pix_fmt, int width, int height) { ptrdiff_t dst_linesizes1[4], src_linesizes1[4]; int i; for (i = 0; i < 4; i++) { dst_linesizes1[i] = dst_linesizes[i]; src_linesizes1[i] = src_linesizes[i]; } image_copy(dst_data, dst_linesizes1, src_data, src_linesizes1, pix_fmt, width, height, image_copy_plane); } void av_image_copy_uc_from(uint8_t *dst_data[4], const ptrdiff_t dst_linesizes[4], const uint8_t *src_data[4], const ptrdiff_t src_linesizes[4], enum AVPixelFormat pix_fmt, int width, int height) { image_copy(dst_data, dst_linesizes, src_data, src_linesizes, pix_fmt, width, height, image_copy_plane_uc_from); } int av_image_fill_arrays(uint8_t *dst_data[4], int dst_linesize[4], const uint8_t *src, enum AVPixelFormat pix_fmt, int width, int height, int align) { int ret, i; ret = av_image_check_size(width, height, 0, NULL); if (ret < 0) return ret; ret = av_image_fill_linesizes(dst_linesize, pix_fmt, width); if (ret < 0) return ret; for (i = 0; i < 4; i++) dst_linesize[i] = FFALIGN(dst_linesize[i], align); return av_image_fill_pointers(dst_data, pix_fmt, height, (uint8_t *)src, dst_linesize); } int av_image_get_buffer_size(enum AVPixelFormat pix_fmt, int width, int height, int align) { uint8_t *data[4]; int linesize[4]; int ret; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); if (!desc) return AVERROR(EINVAL); ret = av_image_check_size(width, height, 0, NULL); if (ret < 0) return ret; // do not include palette for these pseudo-paletted formats if (desc->flags & FF_PSEUDOPAL) return FFALIGN(width, align) * height; return av_image_fill_arrays(data, linesize, NULL, pix_fmt, width, height, align); } int av_image_copy_to_buffer(uint8_t *dst, int dst_size, const uint8_t * const src_data[4], const int src_linesize[4], enum AVPixelFormat pix_fmt, int width, int height, int align) { int i, j, nb_planes = 0, linesize[4]; int size = av_image_get_buffer_size(pix_fmt, width, height, align); const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); int ret; if (size > dst_size || size < 0 || !desc) return AVERROR(EINVAL); for (i = 0; i < desc->nb_components; i++) nb_planes = FFMAX(desc->comp[i].plane, nb_planes); nb_planes++; ret = av_image_fill_linesizes(linesize, pix_fmt, width); av_assert0(ret >= 0); // was checked previously for (i = 0; i < nb_planes; i++) { int h, shift = (i == 1 || i == 2) ? desc->log2_chroma_h : 0; const uint8_t *src = src_data[i]; h = (height + (1 << shift) - 1) >> shift; for (j = 0; j < h; j++) { memcpy(dst, src, linesize[i]); dst += FFALIGN(linesize[i], align); src += src_linesize[i]; } } if (desc->flags & AV_PIX_FMT_FLAG_PAL) { uint32_t *d32 = (uint32_t *)dst; for (i = 0; i<256; i++) AV_WL32(d32 + i, AV_RN32(src_data[1] + 4*i)); } return size; } // Fill dst[0..dst_size] with the bytes in clear[0..clear_size]. The clear // bytes are repeated until dst_size is reached. If dst_size is unaligned (i.e. // dst_size%clear_size!=0), the remaining data will be filled with the beginning // of the clear data only. static void memset_bytes(uint8_t *dst, size_t dst_size, uint8_t *clear, size_t clear_size) { int same = 1; int i; if (!clear_size) return; // Reduce to memset() if possible. for (i = 0; i < clear_size; i++) { if (clear[i] != clear[0]) { same = 0; break; } } if (same) clear_size = 1; if (clear_size == 1) { memset(dst, clear[0], dst_size); dst_size = 0; } else { if (clear_size > dst_size) clear_size = dst_size; memcpy(dst, clear, clear_size); av_memcpy_backptr(dst + clear_size, clear_size, dst_size - clear_size); } } // Maximum size in bytes of a plane element (usually a pixel, or multiple pixels // if it's a subsampled packed format). #define MAX_BLOCK_SIZE 32 int av_image_fill_black(uint8_t *dst_data[4], const ptrdiff_t dst_linesize[4], enum AVPixelFormat pix_fmt, enum AVColorRange range, int width, int height) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); int nb_planes = av_pix_fmt_count_planes(pix_fmt); // A pixel or a group of pixels on each plane, with a value that represents black. // Consider e.g. AV_PIX_FMT_UYVY422 for non-trivial cases. uint8_t clear_block[4][MAX_BLOCK_SIZE] = {{0}}; // clear padding with 0 int clear_block_size[4] = {0}; ptrdiff_t plane_line_bytes[4] = {0}; int rgb, limited; int plane, c; if (!desc || nb_planes < 1 || nb_planes > 4 || desc->flags & AV_PIX_FMT_FLAG_HWACCEL) return AVERROR(EINVAL); rgb = !!(desc->flags & AV_PIX_FMT_FLAG_RGB); limited = !rgb && range != AVCOL_RANGE_JPEG; if (desc->flags & AV_PIX_FMT_FLAG_BITSTREAM) { ptrdiff_t bytewidth = av_image_get_linesize(pix_fmt, width, 0); uint8_t *data; int mono = pix_fmt == AV_PIX_FMT_MONOWHITE || pix_fmt == AV_PIX_FMT_MONOBLACK; int fill = pix_fmt == AV_PIX_FMT_MONOWHITE ? 0xFF : 0; if (nb_planes != 1 || !(rgb || mono) || bytewidth < 1) return AVERROR(EINVAL); if (!dst_data) return 0; data = dst_data[0]; // (Bitstream + alpha will be handled incorrectly - it'll remain transparent.) for (;height > 0; height--) { memset(data, fill, bytewidth); data += dst_linesize[0]; } return 0; } for (c = 0; c < desc->nb_components; c++) { const AVComponentDescriptor comp = desc->comp[c]; // We try to operate on entire non-subsampled pixel groups (for // AV_PIX_FMT_UYVY422 this would mean two consecutive pixels). clear_block_size[comp.plane] = FFMAX(clear_block_size[comp.plane], comp.step); if (clear_block_size[comp.plane] > MAX_BLOCK_SIZE) return AVERROR(EINVAL); } // Create a byte array for clearing 1 pixel (sometimes several pixels). for (c = 0; c < desc->nb_components; c++) { const AVComponentDescriptor comp = desc->comp[c]; // (Multiple pixels happen e.g. with AV_PIX_FMT_UYVY422.) int w = clear_block_size[comp.plane] / comp.step; uint8_t *c_data[4]; const int c_linesize[4] = {0}; uint16_t src_array[MAX_BLOCK_SIZE]; uint16_t src = 0; int x; if (comp.depth > 16) return AVERROR(EINVAL); if (!rgb && comp.depth < 8) return AVERROR(EINVAL); if (w < 1) return AVERROR(EINVAL); if (c == 0 && limited) { src = 16 << (comp.depth - 8); } else if ((c == 1 || c == 2) && !rgb) { src = 128 << (comp.depth - 8); } else if (c == 3) { // (Assume even limited YUV uses full range alpha.) src = (1 << comp.depth) - 1; } for (x = 0; x < w; x++) src_array[x] = src; for (x = 0; x < 4; x++) c_data[x] = &clear_block[x][0]; av_write_image_line(src_array, c_data, c_linesize, desc, 0, 0, c, w); } for (plane = 0; plane < nb_planes; plane++) { plane_line_bytes[plane] = av_image_get_linesize(pix_fmt, width, plane); if (plane_line_bytes[plane] < 0) return AVERROR(EINVAL); } if (!dst_data) return 0; for (plane = 0; plane < nb_planes; plane++) { size_t bytewidth = plane_line_bytes[plane]; uint8_t *data = dst_data[plane]; int chroma_div = plane == 1 || plane == 2 ? desc->log2_chroma_h : 0; int plane_h = ((height + ( 1 << chroma_div) - 1)) >> chroma_div; for (; plane_h > 0; plane_h--) { memset_bytes(data, bytewidth, &clear_block[plane][0], clear_block_size[plane]); data += dst_linesize[plane]; } } return 0; }
dc775a8e286549acd5908dc10f1b29341d55199c
2f396d9c1cff7136f652f05dd3dea2e780ecc56e
/contrib/ipp/src/picopycpp8y8cn.c
67fe7efd14be15e8251a4595ae2d1dc165f90641
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Intel" ]
permissive
Intel-Media-SDK/MediaSDK
d90c84f37fd93afc9f0a0b98ac20109d322c3337
7a72de33a15d6e7cdb842b12b901a003f7154f0a
refs/heads/master
2023-08-24T09:19:16.315839
2023-05-17T16:55:38
2023-05-17T16:55:38
87,199,173
957
595
MIT
2023-05-17T16:55:40
2017-04-04T14:52:06
C++
UTF-8
C
false
false
29,433
c
picopycpp8y8cn.c
// Copyright (c) 2018 Intel Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. /* // // Contents: // mfxowniCopy_16s_C4P4R_cn // mfxowniCopy_16s_C3P3R_cn // mfxowniCopy_8u_C4P4R_cn // mfxowniCopy_8u_C3P3R_cn // */ #include <emmintrin.h> // __m128i etc #include <tmmintrin.h> // _mm_shuffle_epi8 #include "precomp.h" #include "owni.h" #include "ippcore.h" #if ( _IPP >= _IPP_P8 ) || ( _IPP32E >= _IPP32E_Y8 ) #define BOUND_NT_8u_C3P3R 1048576 #define BOUND_NT_8u_C4P4R 786432 #define BOUND_NT_16s_C3P3R 524288 #define BOUND_NT_16s_C4P4R 393216 /************************************* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 */ static __ALIGN16 Ipp8u msk_00[16] = { 0, 3, 6, 9, 12, 15,128,128,128,128,128,128,128,128,128,128 }; static __ALIGN16 Ipp8u msk_01[16] = { 128,128,128,128,128,128, 2, 5, 8, 11, 14,128,128,128,128,128 }; static __ALIGN16 Ipp8u msk_02[16] = { 128,128,128,128,128,128,128,128,128,128,128, 1, 4, 7, 10, 13 }; static __ALIGN16 Ipp8u msk_10[16] = { 1, 4, 7, 10, 13,128,128,128,128,128,128,128,128,128,128,128 }; static __ALIGN16 Ipp8u msk_11[16] = { 128,128,128,128,128, 0, 3, 6, 9, 12, 15,128,128,128,128,128 }; static __ALIGN16 Ipp8u msk_12[16] = { 128,128,128,128,128,128,128,128,128,128,128, 2, 5, 8, 11, 14 }; static __ALIGN16 Ipp8u msk_20[16] = { 2, 5, 8, 11, 14,128,128,128,128,128,128,128,128,128,128,128 }; static __ALIGN16 Ipp8u msk_21[16] = { 128,128,128,128,128, 1, 4, 7, 10, 13,128,128,128,128,128,128 }; static __ALIGN16 Ipp8u msk_22[16] = { 128,128,128,128,128,128,128,128,128,128, 0, 3, 6, 9, 12, 15 }; /************************************* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 */ static __ALIGN16 Ipp8u m16_00[16] = { 0, 1, 6, 7, 12, 13,128,128,128,128,128,128,128,128,128,128 }; static __ALIGN16 Ipp8u m16_01[16] = { 128,128,128,128,128,128, 2, 3, 8, 9, 14, 15,128,128,128,128 }; static __ALIGN16 Ipp8u m16_02[16] = { 128,128,128,128,128,128,128,128,128,128,128,128, 4, 5, 10, 11 }; static __ALIGN16 Ipp8u m16_10[16] = { 2, 3, 8, 9, 14, 15,128,128,128,128,128,128,128,128,128,128 }; static __ALIGN16 Ipp8u m16_11[16] = { 128,128,128,128,128,128, 4, 5, 10, 11,128,128,128,128,128,128 }; static __ALIGN16 Ipp8u m16_12[16] = { 128,128,128,128,128,128,128,128,128,128, 0, 1, 6, 7, 12, 13 }; static __ALIGN16 Ipp8u m16_20[16] = { 4, 5, 10, 11,128,128,128,128,128,128,128,128,128,128,128,128 }; static __ALIGN16 Ipp8u m16_21[16] = { 128,128,128,128, 0, 1, 6, 7, 12, 13,128,128,128,128,128,128 }; static __ALIGN16 Ipp8u m16_22[16] = { 128,128,128,128,128,128,128,128,128,128, 2, 3, 8, 9, 14, 15 }; /***********************************************************************/ void mfxowniCopy_16s_C4P4R_cn( const Ipp16s* pSrc, int srcStep, Ipp16s* const pDst[4], int dstStep, IppiSize roiSize ) { __ALIGN16 __m128i v0, v1, v2, v3, v4, v5; Ipp16s *dst0 = pDst[0], *dst1 = pDst[1], *dst2 = pDst[2], *dst3 = pDst[3]; int h, s, d, cache, nonTemporal = 0; Ipp64s width, width_; IppStatus ownStatus = ippStsNoErr; if( roiSize.width < 8 ) { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < roiSize.width; s += 4, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; dst3[d] = pSrc[s+3]; } pSrc = (Ipp16s*)((Ipp8u*)pSrc + srcStep); dst0 = (Ipp16s*)((Ipp8u*)dst0 + dstStep); dst1 = (Ipp16s*)((Ipp8u*)dst1 + dstStep); dst2 = (Ipp16s*)((Ipp8u*)dst2 + dstStep); dst3 = (Ipp16s*)((Ipp8u*)dst3 + dstStep); } return; } if( (dstStep*4 == srcStep) && (dstStep == roiSize.width*2) ) { width = roiSize.width*roiSize.height; roiSize.height = 1; if( width > BOUND_NT_16s_C4P4R ) { ownStatus = mfxGetMaxCacheSizeB( &cache ); if( ownStatus == ippStsNoErr ) { if( width*16 > cache ) nonTemporal = 1; } } } else { width = roiSize.width; } width_ = width - (width & 0x7); if( (IPP_UINT_PTR(pSrc)&0xf) || (srcStep&0xf) || (dstStep&0xf) || (IPP_UINT_PTR(dst0)&0xf) || (IPP_UINT_PTR(dst1)&0xf) || (IPP_UINT_PTR(dst2)&0xf) || (IPP_UINT_PTR(dst3)&0xf) ) { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < width_; s += 32, d += 8 ) { v0 = _mm_loadu_si128( (__m128i*)(pSrc + s) ); v1 = _mm_loadu_si128( (__m128i*)(pSrc + s + 8) ); v2 = _mm_loadu_si128( (__m128i*)(pSrc + s + 16) ); v3 = _mm_loadu_si128( (__m128i*)(pSrc + s + 24) ); v4 = _mm_unpacklo_epi16( v0, v1 ); v0 = _mm_unpackhi_epi16( v0, v1 ); v5 = _mm_unpacklo_epi16( v2, v3 ); v2 = _mm_unpackhi_epi16( v2, v3 ); v1 = _mm_unpacklo_epi16( v4, v0 ); v4 = _mm_unpackhi_epi16( v4, v0 ); v3 = _mm_unpacklo_epi16( v5, v2 ); v5 = _mm_unpackhi_epi16( v5, v2 ); v0 = _mm_unpacklo_epi64( v1, v3 ); v1 = _mm_unpackhi_epi64( v1, v3 ); v2 = _mm_unpacklo_epi64( v4, v5 ); v3 = _mm_unpackhi_epi64( v4, v5 ); _mm_storeu_si128( (__m128i*)(dst0 + d), v0 ); _mm_storeu_si128( (__m128i*)(dst1 + d), v1 ); _mm_storeu_si128( (__m128i*)(dst2 + d), v2 ); _mm_storeu_si128( (__m128i*)(dst3 + d), v3 ); } for( ; d < width; s += 4, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; dst3[d] = pSrc[s+3]; } pSrc = (Ipp16s*)((Ipp8u*)pSrc + srcStep); dst0 = (Ipp16s*)((Ipp8u*)dst0 + dstStep); dst1 = (Ipp16s*)((Ipp8u*)dst1 + dstStep); dst2 = (Ipp16s*)((Ipp8u*)dst2 + dstStep); dst3 = (Ipp16s*)((Ipp8u*)dst3 + dstStep); } } else { if( nonTemporal ) { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < width_; s += 32, d += 8 ) { v0 = _mm_load_si128( (__m128i*)(pSrc + s) ); v1 = _mm_load_si128( (__m128i*)(pSrc + s + 8) ); v2 = _mm_load_si128( (__m128i*)(pSrc + s + 16) ); v3 = _mm_load_si128( (__m128i*)(pSrc + s + 24) ); v4 = _mm_unpacklo_epi16( v0, v1 ); v0 = _mm_unpackhi_epi16( v0, v1 ); v5 = _mm_unpacklo_epi16( v2, v3 ); v2 = _mm_unpackhi_epi16( v2, v3 ); v1 = _mm_unpacklo_epi16( v4, v0 ); v4 = _mm_unpackhi_epi16( v4, v0 ); v3 = _mm_unpacklo_epi16( v5, v2 ); v5 = _mm_unpackhi_epi16( v5, v2 ); v0 = _mm_unpacklo_epi64( v1, v3 ); v1 = _mm_unpackhi_epi64( v1, v3 ); v2 = _mm_unpacklo_epi64( v4, v5 ); v3 = _mm_unpackhi_epi64( v4, v5 ); _mm_stream_si128( (__m128i*)(dst0 + d), v0 ); _mm_stream_si128( (__m128i*)(dst1 + d), v1 ); _mm_stream_si128( (__m128i*)(dst2 + d), v2 ); _mm_stream_si128( (__m128i*)(dst3 + d), v3 ); } for( ; d < width; s += 4, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; dst3[d] = pSrc[s+3]; } pSrc = (Ipp16s*)((Ipp8u*)pSrc + srcStep); dst0 = (Ipp16s*)((Ipp8u*)dst0 + dstStep); dst1 = (Ipp16s*)((Ipp8u*)dst1 + dstStep); dst2 = (Ipp16s*)((Ipp8u*)dst2 + dstStep); dst3 = (Ipp16s*)((Ipp8u*)dst3 + dstStep); } _mm_sfence(); } else { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < width_; s += 32, d += 8 ) { v0 = _mm_load_si128( (__m128i*)(pSrc + s) ); v1 = _mm_load_si128( (__m128i*)(pSrc + s + 8) ); v2 = _mm_load_si128( (__m128i*)(pSrc + s + 16) ); v3 = _mm_load_si128( (__m128i*)(pSrc + s + 24) ); v4 = _mm_unpacklo_epi16( v0, v1 ); v0 = _mm_unpackhi_epi16( v0, v1 ); v5 = _mm_unpacklo_epi16( v2, v3 ); v2 = _mm_unpackhi_epi16( v2, v3 ); v1 = _mm_unpacklo_epi16( v4, v0 ); v4 = _mm_unpackhi_epi16( v4, v0 ); v3 = _mm_unpacklo_epi16( v5, v2 ); v5 = _mm_unpackhi_epi16( v5, v2 ); v0 = _mm_unpacklo_epi64( v1, v3 ); v1 = _mm_unpackhi_epi64( v1, v3 ); v2 = _mm_unpacklo_epi64( v4, v5 ); v3 = _mm_unpackhi_epi64( v4, v5 ); _mm_store_si128( (__m128i*)(dst0 + d), v0 ); _mm_store_si128( (__m128i*)(dst1 + d), v1 ); _mm_store_si128( (__m128i*)(dst2 + d), v2 ); _mm_store_si128( (__m128i*)(dst3 + d), v3 ); } for( ; d < width; s += 4, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; dst3[d] = pSrc[s+3]; } pSrc = (Ipp16s*)((Ipp8u*)pSrc + srcStep); dst0 = (Ipp16s*)((Ipp8u*)dst0 + dstStep); dst1 = (Ipp16s*)((Ipp8u*)dst1 + dstStep); dst2 = (Ipp16s*)((Ipp8u*)dst2 + dstStep); dst3 = (Ipp16s*)((Ipp8u*)dst3 + dstStep); } } } return; } /***********************************************************************/ void mfxowniCopy_16s_C3P3R_cn( const Ipp16s* pSrc, int srcStep, Ipp16s* const pDst[3], int dstStep, IppiSize roiSize ) { __ALIGN16 __m128i s0, s1, s2; __ALIGN16 __m128i d0, d1, d2, t0, t1, t2; Ipp16s *dst0 = pDst[0], *dst1 = pDst[1], *dst2 = pDst[2]; int h, s, d, cache, nonTemporal = 0; Ipp64s width, width_; IppStatus ownStatus = ippStsNoErr; if( roiSize.width < 8 ) { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < roiSize.width; s += 3, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; } pSrc = (Ipp16s*)((Ipp8u*)pSrc + srcStep); dst0 = (Ipp16s*)((Ipp8u*)dst0 + dstStep); dst1 = (Ipp16s*)((Ipp8u*)dst1 + dstStep); dst2 = (Ipp16s*)((Ipp8u*)dst2 + dstStep); } return; } if( (dstStep*3 == srcStep) && (dstStep == roiSize.width*2) ) { width = roiSize.width*roiSize.height; roiSize.height = 1; if( width > BOUND_NT_16s_C3P3R ) { ownStatus = mfxGetMaxCacheSizeB( &cache ); if( ownStatus == ippStsNoErr ) { if( width*12 > cache ) nonTemporal = 1; } } } else { width = roiSize.width; } width_ = width - (width & 0x7); if( (IPP_UINT_PTR(pSrc)&0xf) || (srcStep&0xf) || (IPP_UINT_PTR(dst0)&0xf) || (IPP_UINT_PTR(dst1)&0xf) || (IPP_UINT_PTR(dst2)&0xf) || (dstStep&0xf) ) { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < width_; s += 24, d += 8 ) { s0 = _mm_loadu_si128( (__m128i*)(pSrc + s) ); s1 = _mm_loadu_si128( (__m128i*)(pSrc + s + 8) ); s2 = _mm_loadu_si128( (__m128i*)(pSrc + s + 16) ); d0 = _mm_shuffle_epi8( s0, *(__m128i*)m16_00 ); d1 = _mm_shuffle_epi8( s0, *(__m128i*)m16_10 ); d2 = _mm_shuffle_epi8( s0, *(__m128i*)m16_20 ); t0 = _mm_shuffle_epi8( s1, *(__m128i*)m16_01 ); t1 = _mm_shuffle_epi8( s1, *(__m128i*)m16_11 ); t2 = _mm_shuffle_epi8( s1, *(__m128i*)m16_21 ); d0 = _mm_or_si128( d0, t0); d1 = _mm_or_si128( d1, t1); d2 = _mm_or_si128( d2, t2); t0 = _mm_shuffle_epi8( s2, *(__m128i*)m16_02 ); t1 = _mm_shuffle_epi8( s2, *(__m128i*)m16_12 ); t2 = _mm_shuffle_epi8( s2, *(__m128i*)m16_22 ); d0 = _mm_or_si128( d0, t0); d1 = _mm_or_si128( d1, t1); d2 = _mm_or_si128( d2, t2); _mm_storeu_si128( (__m128i*)(dst0 + d), d0 ); _mm_storeu_si128( (__m128i*)(dst1 + d), d1 ); _mm_storeu_si128( (__m128i*)(dst2 + d), d2 ); } for( ; d < width; s += 3, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; } pSrc = (Ipp16s*)((Ipp8u*)pSrc + srcStep); dst0 = (Ipp16s*)((Ipp8u*)dst0 + dstStep); dst1 = (Ipp16s*)((Ipp8u*)dst1 + dstStep); dst2 = (Ipp16s*)((Ipp8u*)dst2 + dstStep); } } else { if( nonTemporal ) { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < width_; s += 24, d += 8 ) { s0 = _mm_load_si128( (__m128i*)(pSrc + s) ); s1 = _mm_load_si128( (__m128i*)(pSrc + s + 8) ); s2 = _mm_load_si128( (__m128i*)(pSrc + s + 16) ); d0 = _mm_shuffle_epi8( s0, *(__m128i*)m16_00 ); d1 = _mm_shuffle_epi8( s0, *(__m128i*)m16_10 ); d2 = _mm_shuffle_epi8( s0, *(__m128i*)m16_20 ); t0 = _mm_shuffle_epi8( s1, *(__m128i*)m16_01 ); t1 = _mm_shuffle_epi8( s1, *(__m128i*)m16_11 ); t2 = _mm_shuffle_epi8( s1, *(__m128i*)m16_21 ); d0 = _mm_or_si128( d0, t0); d1 = _mm_or_si128( d1, t1); d2 = _mm_or_si128( d2, t2); t0 = _mm_shuffle_epi8( s2, *(__m128i*)m16_02 ); t1 = _mm_shuffle_epi8( s2, *(__m128i*)m16_12 ); t2 = _mm_shuffle_epi8( s2, *(__m128i*)m16_22 ); d0 = _mm_or_si128( d0, t0); d1 = _mm_or_si128( d1, t1); d2 = _mm_or_si128( d2, t2); _mm_stream_si128( (__m128i*)(dst0 + d), d0 ); _mm_stream_si128( (__m128i*)(dst1 + d), d1 ); _mm_stream_si128( (__m128i*)(dst2 + d), d2 ); } for( ; d < width; s += 3, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; } pSrc = (Ipp16s*)((Ipp8u*)pSrc + srcStep); dst0 = (Ipp16s*)((Ipp8u*)dst0 + dstStep); dst1 = (Ipp16s*)((Ipp8u*)dst1 + dstStep); dst2 = (Ipp16s*)((Ipp8u*)dst2 + dstStep); } _mm_sfence(); } else { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < width_; s += 24, d += 8 ) { s0 = _mm_load_si128( (__m128i*)(pSrc + s) ); s1 = _mm_load_si128( (__m128i*)(pSrc + s + 8) ); s2 = _mm_load_si128( (__m128i*)(pSrc + s + 16) ); d0 = _mm_shuffle_epi8( s0, *(__m128i*)m16_00 ); d1 = _mm_shuffle_epi8( s0, *(__m128i*)m16_10 ); d2 = _mm_shuffle_epi8( s0, *(__m128i*)m16_20 ); t0 = _mm_shuffle_epi8( s1, *(__m128i*)m16_01 ); t1 = _mm_shuffle_epi8( s1, *(__m128i*)m16_11 ); t2 = _mm_shuffle_epi8( s1, *(__m128i*)m16_21 ); d0 = _mm_or_si128( d0, t0); d1 = _mm_or_si128( d1, t1); d2 = _mm_or_si128( d2, t2); t0 = _mm_shuffle_epi8( s2, *(__m128i*)m16_02 ); t1 = _mm_shuffle_epi8( s2, *(__m128i*)m16_12 ); t2 = _mm_shuffle_epi8( s2, *(__m128i*)m16_22 ); d0 = _mm_or_si128( d0, t0); d1 = _mm_or_si128( d1, t1); d2 = _mm_or_si128( d2, t2); _mm_store_si128( (__m128i*)(dst0 + d), d0 ); _mm_store_si128( (__m128i*)(dst1 + d), d1 ); _mm_store_si128( (__m128i*)(dst2 + d), d2 ); } for( ; d < width; s += 3, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; } pSrc = (Ipp16s*)((Ipp8u*)pSrc + srcStep); dst0 = (Ipp16s*)((Ipp8u*)dst0 + dstStep); dst1 = (Ipp16s*)((Ipp8u*)dst1 + dstStep); dst2 = (Ipp16s*)((Ipp8u*)dst2 + dstStep); } } } return; } /***********************************************************************/ void mfxowniCopy_8u_C4P4R_cn( const Ipp8u* pSrc, int srcStep, Ipp8u* const pDst[4], int dstStep, IppiSize roiSize ) { __ALIGN16 __m128i v0, v1, v2, v3, v4, v5; Ipp8u *dst0 = pDst[0], *dst1 = pDst[1], *dst2 = pDst[2], *dst3 = pDst[3]; int h, s, d, cache, nonTemporal = 0; Ipp64s width, width_; IppStatus ownStatus = ippStsNoErr; if( roiSize.width < 16 ) { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < roiSize.width; s += 4, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; dst3[d] = pSrc[s+3]; } pSrc += srcStep; dst0 += dstStep; dst1 += dstStep; dst2 += dstStep; dst3 += dstStep; } return; } if( (dstStep*4 == srcStep) && (dstStep == roiSize.width) ) { width = roiSize.width*roiSize.height; roiSize.height = 1; if( width > BOUND_NT_8u_C4P4R ) { ownStatus = mfxGetMaxCacheSizeB( &cache ); if( ownStatus == ippStsNoErr ) { if( width*8 > cache ) nonTemporal = 1; } } } else { width = roiSize.width; } width_ = width - (width & 0xf); if( (IPP_UINT_PTR(pSrc)&0xf) || (srcStep&0xf) || (dstStep&0xf) || (IPP_UINT_PTR(dst0)&0xf) || (IPP_UINT_PTR(dst1)&0xf) || (IPP_UINT_PTR(dst2)&0xf) || (IPP_UINT_PTR(dst3)&0xf) ) { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < width_; s += 64, d += 16 ) { v0 = _mm_loadu_si128( (__m128i*)(pSrc + s) ); v1 = _mm_loadu_si128( (__m128i*)(pSrc + s + 16) ); v2 = _mm_loadu_si128( (__m128i*)(pSrc + s + 32) ); v3 = _mm_loadu_si128( (__m128i*)(pSrc + s + 48) ); v4 = _mm_unpacklo_epi8( v0, v1 ); v0 = _mm_unpackhi_epi8( v0, v1 ); v5 = _mm_unpacklo_epi8( v2, v3 ); v2 = _mm_unpackhi_epi8( v2, v3 ); v1 = _mm_unpacklo_epi8( v4, v0 ); v4 = _mm_unpackhi_epi8( v4, v0 ); v3 = _mm_unpacklo_epi8( v5, v2 ); v5 = _mm_unpackhi_epi8( v5, v2 ); v0 = _mm_unpacklo_epi8( v1, v4 ); v1 = _mm_unpackhi_epi8( v1, v4 ); v2 = _mm_unpacklo_epi8( v3, v5 ); v3 = _mm_unpackhi_epi8( v3, v5 ); v4 = _mm_unpacklo_epi64( v0, v2 ); v0 = _mm_unpackhi_epi64( v0, v2 ); v5 = _mm_unpacklo_epi64( v1, v3 ); v1 = _mm_unpackhi_epi64( v1, v3 ); _mm_storeu_si128( (__m128i*)(dst0 + d), v4 ); _mm_storeu_si128( (__m128i*)(dst1 + d), v0 ); _mm_storeu_si128( (__m128i*)(dst2 + d), v5 ); _mm_storeu_si128( (__m128i*)(dst3 + d), v1 ); } for( ; d < width; s += 4, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; dst3[d] = pSrc[s+3]; } pSrc += srcStep; dst0 += dstStep; dst1 += dstStep; dst2 += dstStep; dst3 += dstStep; } } else { if( nonTemporal ) { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < width_; s += 64, d += 16 ) { v0 = _mm_load_si128( (__m128i*)(pSrc + s) ); v1 = _mm_load_si128( (__m128i*)(pSrc + s + 16) ); v2 = _mm_load_si128( (__m128i*)(pSrc + s + 32) ); v3 = _mm_load_si128( (__m128i*)(pSrc + s + 48) ); v4 = _mm_unpacklo_epi8( v0, v1 ); v0 = _mm_unpackhi_epi8( v0, v1 ); v5 = _mm_unpacklo_epi8( v2, v3 ); v2 = _mm_unpackhi_epi8( v2, v3 ); v1 = _mm_unpacklo_epi8( v4, v0 ); v4 = _mm_unpackhi_epi8( v4, v0 ); v3 = _mm_unpacklo_epi8( v5, v2 ); v5 = _mm_unpackhi_epi8( v5, v2 ); v0 = _mm_unpacklo_epi8( v1, v4 ); v1 = _mm_unpackhi_epi8( v1, v4 ); v2 = _mm_unpacklo_epi8( v3, v5 ); v3 = _mm_unpackhi_epi8( v3, v5 ); v4 = _mm_unpacklo_epi64( v0, v2 ); v0 = _mm_unpackhi_epi64( v0, v2 ); v5 = _mm_unpacklo_epi64( v1, v3 ); v1 = _mm_unpackhi_epi64( v1, v3 ); _mm_stream_si128( (__m128i*)(dst0 + d), v4 ); _mm_stream_si128( (__m128i*)(dst1 + d), v0 ); _mm_stream_si128( (__m128i*)(dst2 + d), v5 ); _mm_stream_si128( (__m128i*)(dst3 + d), v1 ); } for( ; d < width; s += 4, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; dst3[d] = pSrc[s+3]; } pSrc += srcStep; dst0 += dstStep; dst1 += dstStep; dst2 += dstStep; dst3 += dstStep; } _mm_sfence(); } else { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < width_; s += 64, d += 16 ) { v0 = _mm_load_si128( (__m128i*)(pSrc + s) ); v1 = _mm_load_si128( (__m128i*)(pSrc + s + 16) ); v2 = _mm_load_si128( (__m128i*)(pSrc + s + 32) ); v3 = _mm_load_si128( (__m128i*)(pSrc + s + 48) ); v4 = _mm_unpacklo_epi8( v0, v1 ); v0 = _mm_unpackhi_epi8( v0, v1 ); v5 = _mm_unpacklo_epi8( v2, v3 ); v2 = _mm_unpackhi_epi8( v2, v3 ); v1 = _mm_unpacklo_epi8( v4, v0 ); v4 = _mm_unpackhi_epi8( v4, v0 ); v3 = _mm_unpacklo_epi8( v5, v2 ); v5 = _mm_unpackhi_epi8( v5, v2 ); v0 = _mm_unpacklo_epi8( v1, v4 ); v1 = _mm_unpackhi_epi8( v1, v4 ); v2 = _mm_unpacklo_epi8( v3, v5 ); v3 = _mm_unpackhi_epi8( v3, v5 ); v4 = _mm_unpacklo_epi64( v0, v2 ); v0 = _mm_unpackhi_epi64( v0, v2 ); v5 = _mm_unpacklo_epi64( v1, v3 ); v1 = _mm_unpackhi_epi64( v1, v3 ); _mm_store_si128( (__m128i*)(dst0 + d), v4 ); _mm_store_si128( (__m128i*)(dst1 + d), v0 ); _mm_store_si128( (__m128i*)(dst2 + d), v5 ); _mm_store_si128( (__m128i*)(dst3 + d), v1 ); } for( ; d < width; s += 4, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; dst3[d] = pSrc[s+3]; } pSrc += srcStep; dst0 += dstStep; dst1 += dstStep; dst2 += dstStep; dst3 += dstStep; } } } return; } /***********************************************************************/ void mfxowniCopy_8u_C3P3R_cn( const Ipp8u* pSrc, int srcStep, Ipp8u* const pDst[3], int dstStep, IppiSize roiSize ) { __ALIGN16 __m128i s0, s1, s2; __ALIGN16 __m128i d0, d1, d2, t0, t1, t2; Ipp8u *dst0 = pDst[0], *dst1 = pDst[1], *dst2 = pDst[2]; int h, s, d, cache, nonTemporal = 0; Ipp64s width, width_; IppStatus ownStatus = ippStsNoErr; if( roiSize.width < 16 ) { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < roiSize.width; s += 3, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; } pSrc += srcStep; dst0 += dstStep; dst1 += dstStep; dst2 += dstStep; } return; } if( (dstStep*3 == srcStep) && (dstStep == roiSize.width) ) { width = roiSize.width*roiSize.height; roiSize.height = 1; if( width > BOUND_NT_8u_C3P3R ) { ownStatus = mfxGetMaxCacheSizeB( &cache ); if( ownStatus == ippStsNoErr ) { if( width*6 > cache ) nonTemporal = 1; } } } else { width = roiSize.width; } width_ = width - (width & 0xf); if( (IPP_UINT_PTR(pSrc)&0xf) || (srcStep&0xf) || (IPP_UINT_PTR(dst0)&0xf) || (IPP_UINT_PTR(dst1)&0xf) || (IPP_UINT_PTR(dst2)&0xf) || (dstStep&0xf) ) { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < width_; s += 48, d += 16 ) { s0 = _mm_loadu_si128( (__m128i*)(pSrc + s) ); s1 = _mm_loadu_si128( (__m128i*)(pSrc + s + 16) ); s2 = _mm_loadu_si128( (__m128i*)(pSrc + s + 32) ); d0 = _mm_shuffle_epi8( s0, *(__m128i*)msk_00 ); d1 = _mm_shuffle_epi8( s0, *(__m128i*)msk_10 ); d2 = _mm_shuffle_epi8( s0, *(__m128i*)msk_20 ); t0 = _mm_shuffle_epi8( s1, *(__m128i*)msk_01 ); t1 = _mm_shuffle_epi8( s1, *(__m128i*)msk_11 ); t2 = _mm_shuffle_epi8( s1, *(__m128i*)msk_21 ); d0 = _mm_or_si128( d0, t0); d1 = _mm_or_si128( d1, t1); d2 = _mm_or_si128( d2, t2); t0 = _mm_shuffle_epi8( s2, *(__m128i*)msk_02 ); t1 = _mm_shuffle_epi8( s2, *(__m128i*)msk_12 ); t2 = _mm_shuffle_epi8( s2, *(__m128i*)msk_22 ); d0 = _mm_or_si128( d0, t0); d1 = _mm_or_si128( d1, t1); d2 = _mm_or_si128( d2, t2); _mm_storeu_si128( (__m128i*)(dst0 + d), d0 ); _mm_storeu_si128( (__m128i*)(dst1 + d), d1 ); _mm_storeu_si128( (__m128i*)(dst2 + d), d2 ); } for( ; d < width; s += 3, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; } pSrc += srcStep; dst0 += dstStep; dst1 += dstStep; dst2 += dstStep; } } else { if( nonTemporal ) { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < width_; s += 48, d += 16 ) { s0 = _mm_load_si128( (__m128i*)(pSrc + s) ); s1 = _mm_load_si128( (__m128i*)(pSrc + s + 16) ); s2 = _mm_load_si128( (__m128i*)(pSrc + s + 32) ); d0 = _mm_shuffle_epi8( s0, *(__m128i*)msk_00 ); d1 = _mm_shuffle_epi8( s0, *(__m128i*)msk_10 ); d2 = _mm_shuffle_epi8( s0, *(__m128i*)msk_20 ); t0 = _mm_shuffle_epi8( s1, *(__m128i*)msk_01 ); t1 = _mm_shuffle_epi8( s1, *(__m128i*)msk_11 ); t2 = _mm_shuffle_epi8( s1, *(__m128i*)msk_21 ); d0 = _mm_or_si128( d0, t0); d1 = _mm_or_si128( d1, t1); d2 = _mm_or_si128( d2, t2); t0 = _mm_shuffle_epi8( s2, *(__m128i*)msk_02 ); t1 = _mm_shuffle_epi8( s2, *(__m128i*)msk_12 ); t2 = _mm_shuffle_epi8( s2, *(__m128i*)msk_22 ); d0 = _mm_or_si128( d0, t0); d1 = _mm_or_si128( d1, t1); d2 = _mm_or_si128( d2, t2); _mm_stream_si128( (__m128i*)(dst0 + d), d0 ); _mm_stream_si128( (__m128i*)(dst1 + d), d1 ); _mm_stream_si128( (__m128i*)(dst2 + d), d2 ); } for( ; d < width; s += 3, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; } pSrc += srcStep; dst0 += dstStep; dst1 += dstStep; dst2 += dstStep; } _mm_sfence(); } else { for( h = 0; h < roiSize.height; h++ ) { for( s = 0, d = 0; d < width_; s += 48, d += 16 ) { s0 = _mm_load_si128( (__m128i*)(pSrc + s) ); s1 = _mm_load_si128( (__m128i*)(pSrc + s + 16) ); s2 = _mm_load_si128( (__m128i*)(pSrc + s + 32) ); d0 = _mm_shuffle_epi8( s0, *(__m128i*)msk_00 ); d1 = _mm_shuffle_epi8( s0, *(__m128i*)msk_10 ); d2 = _mm_shuffle_epi8( s0, *(__m128i*)msk_20 ); t0 = _mm_shuffle_epi8( s1, *(__m128i*)msk_01 ); t1 = _mm_shuffle_epi8( s1, *(__m128i*)msk_11 ); t2 = _mm_shuffle_epi8( s1, *(__m128i*)msk_21 ); d0 = _mm_or_si128( d0, t0); d1 = _mm_or_si128( d1, t1); d2 = _mm_or_si128( d2, t2); t0 = _mm_shuffle_epi8( s2, *(__m128i*)msk_02 ); t1 = _mm_shuffle_epi8( s2, *(__m128i*)msk_12 ); t2 = _mm_shuffle_epi8( s2, *(__m128i*)msk_22 ); d0 = _mm_or_si128( d0, t0); d1 = _mm_or_si128( d1, t1); d2 = _mm_or_si128( d2, t2); _mm_store_si128( (__m128i*)(dst0 + d), d0 ); _mm_store_si128( (__m128i*)(dst1 + d), d1 ); _mm_store_si128( (__m128i*)(dst2 + d), d2 ); } for( ; d < width; s += 3, d++ ) { dst0[d] = pSrc[s]; dst1[d] = pSrc[s+1]; dst2[d] = pSrc[s+2]; } pSrc += srcStep; dst0 += dstStep; dst1 += dstStep; dst2 += dstStep; } } } return; } #endif
8e6ab6350424705a8c315efe478d3efb4ae82cba
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/fs/ext4/page-io.c
b12a4427aedc41f71bbbf697cbc61e17e30963cf
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
12,252
c
page-io.c
/* * linux/fs/ext4/page-io.c * * This contains the new page_io functions for ext4 * * Written by Theodore Ts'o, 2010. */ #include <linux/fs.h> #include <linux/time.h> #include <linux/jbd2.h> #include <linux/highuid.h> #include <linux/pagemap.h> #include <linux/quotaops.h> #include <linux/string.h> #include <linux/buffer_head.h> #include <linux/writeback.h> #include <linux/pagevec.h> #include <linux/mpage.h> #include <linux/namei.h> #include <linux/aio.h> #include <linux/uio.h> #include <linux/bio.h> #include <linux/workqueue.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/mm.h> #include "ext4_jbd2.h" #include "xattr.h" #include "acl.h" static struct kmem_cache *io_end_cachep; int __init ext4_init_pageio(void) { io_end_cachep = KMEM_CACHE(ext4_io_end, SLAB_RECLAIM_ACCOUNT); if (io_end_cachep == NULL) return -ENOMEM; return 0; } void ext4_exit_pageio(void) { kmem_cache_destroy(io_end_cachep); } /* * This function is called by ext4_evict_inode() to make sure there is * no more pending I/O completion work left to do. */ void ext4_ioend_shutdown(struct inode *inode) { wait_queue_head_t *wq = ext4_ioend_wq(inode); wait_event(*wq, (atomic_read(&EXT4_I(inode)->i_ioend_count) == 0)); /* * We need to make sure the work structure is finished being * used before we let the inode get destroyed. */ if (work_pending(&EXT4_I(inode)->i_unwritten_work)) cancel_work_sync(&EXT4_I(inode)->i_unwritten_work); } void ext4_free_io_end(ext4_io_end_t *io) { BUG_ON(!io); BUG_ON(!list_empty(&io->list)); BUG_ON(io->flag & EXT4_IO_END_UNWRITTEN); if (atomic_dec_and_test(&EXT4_I(io->inode)->i_ioend_count)) wake_up_all(ext4_ioend_wq(io->inode)); kmem_cache_free(io_end_cachep, io); } /* check a range of space and convert unwritten extents to written. */ static int ext4_end_io(ext4_io_end_t *io) { struct inode *inode = io->inode; loff_t offset = io->offset; ssize_t size = io->size; int ret = 0; ext4_debug("ext4_end_io_nolock: io 0x%p from inode %lu,list->next 0x%p," "list->prev 0x%p\n", io, inode->i_ino, io->list.next, io->list.prev); ret = ext4_convert_unwritten_extents(inode, offset, size); if (ret < 0) { ext4_msg(inode->i_sb, KERN_EMERG, "failed to convert unwritten extents to written " "extents -- potential data loss! " "(inode %lu, offset %llu, size %zd, error %d)", inode->i_ino, offset, size, ret); } /* Wake up anyone waiting on unwritten extent conversion */ if (atomic_dec_and_test(&EXT4_I(inode)->i_unwritten)) wake_up_all(ext4_ioend_wq(inode)); if (io->flag & EXT4_IO_END_DIRECT) inode_dio_done(inode); if (io->iocb) aio_complete(io->iocb, io->result, 0); return ret; } static void dump_completed_IO(struct inode *inode) { #ifdef EXT4FS_DEBUG struct list_head *cur, *before, *after; ext4_io_end_t *io, *io0, *io1; if (list_empty(&EXT4_I(inode)->i_completed_io_list)) { ext4_debug("inode %lu completed_io list is empty\n", inode->i_ino); return; } ext4_debug("Dump inode %lu completed_io list\n", inode->i_ino); list_for_each_entry(io, &EXT4_I(inode)->i_completed_io_list, list) { cur = &io->list; before = cur->prev; io0 = container_of(before, ext4_io_end_t, list); after = cur->next; io1 = container_of(after, ext4_io_end_t, list); ext4_debug("io 0x%p from inode %lu,prev 0x%p,next 0x%p\n", io, inode->i_ino, io0, io1); } #endif } /* Add the io_end to per-inode completed end_io list. */ void ext4_add_complete_io(ext4_io_end_t *io_end) { struct ext4_inode_info *ei = EXT4_I(io_end->inode); struct workqueue_struct *wq; unsigned long flags; BUG_ON(!(io_end->flag & EXT4_IO_END_UNWRITTEN)); wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq; spin_lock_irqsave(&ei->i_completed_io_lock, flags); if (list_empty(&ei->i_completed_io_list)) queue_work(wq, &ei->i_unwritten_work); list_add_tail(&io_end->list, &ei->i_completed_io_list); spin_unlock_irqrestore(&ei->i_completed_io_lock, flags); } static int ext4_do_flush_completed_IO(struct inode *inode) { ext4_io_end_t *io; struct list_head unwritten; unsigned long flags; struct ext4_inode_info *ei = EXT4_I(inode); int err, ret = 0; spin_lock_irqsave(&ei->i_completed_io_lock, flags); dump_completed_IO(inode); list_replace_init(&ei->i_completed_io_list, &unwritten); spin_unlock_irqrestore(&ei->i_completed_io_lock, flags); while (!list_empty(&unwritten)) { io = list_entry(unwritten.next, ext4_io_end_t, list); BUG_ON(!(io->flag & EXT4_IO_END_UNWRITTEN)); list_del_init(&io->list); err = ext4_end_io(io); if (unlikely(!ret && err)) ret = err; io->flag &= ~EXT4_IO_END_UNWRITTEN; ext4_free_io_end(io); } return ret; } /* * work on completed aio dio IO, to convert unwritten extents to extents */ void ext4_end_io_work(struct work_struct *work) { struct ext4_inode_info *ei = container_of(work, struct ext4_inode_info, i_unwritten_work); ext4_do_flush_completed_IO(&ei->vfs_inode); } int ext4_flush_unwritten_io(struct inode *inode) { int ret; WARN_ON_ONCE(!mutex_is_locked(&inode->i_mutex) && !(inode->i_state & I_FREEING)); ret = ext4_do_flush_completed_IO(inode); ext4_unwritten_wait(inode); return ret; } ext4_io_end_t *ext4_init_io_end(struct inode *inode, gfp_t flags) { ext4_io_end_t *io = kmem_cache_zalloc(io_end_cachep, flags); if (io) { atomic_inc(&EXT4_I(inode)->i_ioend_count); io->inode = inode; INIT_LIST_HEAD(&io->list); } return io; } /* * Print an buffer I/O error compatible with the fs/buffer.c. This * provides compatibility with dmesg scrapers that look for a specific * buffer I/O error message. We really need a unified error reporting * structure to userspace ala Digital Unix's uerf system, but it's * probably not going to happen in my lifetime, due to LKML politics... */ static void buffer_io_error(struct buffer_head *bh) { char b[BDEVNAME_SIZE]; printk(KERN_ERR "Buffer I/O error on device %s, logical block %llu\n", bdevname(bh->b_bdev, b), (unsigned long long)bh->b_blocknr); } static void ext4_end_bio(struct bio *bio, int error) { ext4_io_end_t *io_end = bio->bi_private; struct inode *inode; int i; int blocksize; sector_t bi_sector = bio->bi_sector; BUG_ON(!io_end); inode = io_end->inode; blocksize = 1 << inode->i_blkbits; bio->bi_private = NULL; bio->bi_end_io = NULL; if (test_bit(BIO_UPTODATE, &bio->bi_flags)) error = 0; for (i = 0; i < bio->bi_vcnt; i++) { struct bio_vec *bvec = &bio->bi_io_vec[i]; struct page *page = bvec->bv_page; struct buffer_head *bh, *head; unsigned bio_start = bvec->bv_offset; unsigned bio_end = bio_start + bvec->bv_len; unsigned under_io = 0; unsigned long flags; if (!page) continue; if (error) { SetPageError(page); set_bit(AS_EIO, &page->mapping->flags); } bh = head = page_buffers(page); /* * We check all buffers in the page under BH_Uptodate_Lock * to avoid races with other end io clearing async_write flags */ local_irq_save(flags); bit_spin_lock(BH_Uptodate_Lock, &head->b_state); do { if (bh_offset(bh) < bio_start || bh_offset(bh) + blocksize > bio_end) { if (buffer_async_write(bh)) under_io++; continue; } clear_buffer_async_write(bh); if (error) buffer_io_error(bh); } while ((bh = bh->b_this_page) != head); bit_spin_unlock(BH_Uptodate_Lock, &head->b_state); local_irq_restore(flags); if (!under_io) end_page_writeback(page); } bio_put(bio); if (error) { io_end->flag |= EXT4_IO_END_ERROR; ext4_warning(inode->i_sb, "I/O error writing to inode %lu " "(offset %llu size %ld starting block %llu)", inode->i_ino, (unsigned long long) io_end->offset, (long) io_end->size, (unsigned long long) bi_sector >> (inode->i_blkbits - 9)); } if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) { ext4_free_io_end(io_end); return; } ext4_add_complete_io(io_end); } void ext4_io_submit(struct ext4_io_submit *io) { struct bio *bio = io->io_bio; if (bio) { bio_get(io->io_bio); submit_bio(io->io_op, io->io_bio); BUG_ON(bio_flagged(io->io_bio, BIO_EOPNOTSUPP)); bio_put(io->io_bio); } io->io_bio = NULL; io->io_op = 0; io->io_end = NULL; } static int io_submit_init(struct ext4_io_submit *io, struct inode *inode, struct writeback_control *wbc, struct buffer_head *bh) { ext4_io_end_t *io_end; struct page *page = bh->b_page; int nvecs = bio_get_nr_vecs(bh->b_bdev); struct bio *bio; io_end = ext4_init_io_end(inode, GFP_NOFS); if (!io_end) return -ENOMEM; bio = bio_alloc(GFP_NOIO, min(nvecs, BIO_MAX_PAGES)); bio->bi_sector = bh->b_blocknr * (bh->b_size >> 9); bio->bi_bdev = bh->b_bdev; bio->bi_private = io->io_end = io_end; bio->bi_end_io = ext4_end_bio; io_end->offset = (page->index << PAGE_CACHE_SHIFT) + bh_offset(bh); io->io_bio = bio; io->io_op = (wbc->sync_mode == WB_SYNC_ALL ? WRITE_SYNC : WRITE); io->io_next_block = bh->b_blocknr; return 0; } static int io_submit_add_bh(struct ext4_io_submit *io, struct inode *inode, struct writeback_control *wbc, struct buffer_head *bh) { ext4_io_end_t *io_end; int ret; if (io->io_bio && bh->b_blocknr != io->io_next_block) { submit_and_retry: ext4_io_submit(io); } if (io->io_bio == NULL) { ret = io_submit_init(io, inode, wbc, bh); if (ret) return ret; } io_end = io->io_end; if (test_clear_buffer_uninit(bh)) ext4_set_io_unwritten_flag(inode, io_end); io->io_end->size += bh->b_size; io->io_next_block++; ret = bio_add_page(io->io_bio, bh->b_page, bh->b_size, bh_offset(bh)); if (ret != bh->b_size) goto submit_and_retry; return 0; } int ext4_bio_write_page(struct ext4_io_submit *io, struct page *page, int len, struct writeback_control *wbc) { struct inode *inode = page->mapping->host; unsigned block_start, blocksize; struct buffer_head *bh, *head; int ret = 0; int nr_submitted = 0; blocksize = 1 << inode->i_blkbits; BUG_ON(!PageLocked(page)); BUG_ON(PageWriteback(page)); set_page_writeback(page); ClearPageError(page); /* * Comments copied from block_write_full_page_endio: * * The page straddles i_size. It must be zeroed out on each and every * writepage invocation because it may be mmapped. "A file is mapped * in multiples of the page size. For a file that is not a multiple of * the page size, the remaining memory is zeroed when mapped, and * writes to that region are not written out to the file." */ if (len < PAGE_CACHE_SIZE) zero_user_segment(page, len, PAGE_CACHE_SIZE); /* * In the first loop we prepare and mark buffers to submit. We have to * mark all buffers in the page before submitting so that * end_page_writeback() cannot be called from ext4_bio_end_io() when IO * on the first buffer finishes and we are still working on submitting * the second buffer. */ bh = head = page_buffers(page); do { block_start = bh_offset(bh); if (block_start >= len) { clear_buffer_dirty(bh); set_buffer_uptodate(bh); continue; } if (!buffer_dirty(bh) || buffer_delay(bh) || !buffer_mapped(bh) || buffer_unwritten(bh)) { /* A hole? We can safely clear the dirty bit */ if (!buffer_mapped(bh)) clear_buffer_dirty(bh); if (io->io_bio) ext4_io_submit(io); continue; } if (buffer_new(bh)) { clear_buffer_new(bh); unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr); } set_buffer_async_write(bh); } while ((bh = bh->b_this_page) != head); /* Now submit buffers to write */ bh = head = page_buffers(page); do { if (!buffer_async_write(bh)) continue; ret = io_submit_add_bh(io, inode, wbc, bh); if (ret) { /* * We only get here on ENOMEM. Not much else * we can do but mark the page as dirty, and * better luck next time. */ redirty_page_for_writepage(wbc, page); break; } nr_submitted++; clear_buffer_dirty(bh); } while ((bh = bh->b_this_page) != head); /* Error stopped previous loop? Clean up buffers... */ if (ret) { do { clear_buffer_async_write(bh); bh = bh->b_this_page; } while (bh != head); } unlock_page(page); /* Nothing submitted - we have to end page writeback */ if (!nr_submitted) end_page_writeback(page); return ret; }
c1d1d99db5d5262ae33c62b54991e94922a6f704
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/epoc32/include/rwlock.h
507cba186d67b3a026c12501ef07fad1da0d15f2
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
90
h
rwlock.h
/* $NetBSD: rwlock.h,v 1.1 2013/04/28 12:11:26 kiyohara Exp $ */ #include <arm/rwlock.h>
015c9cccc97a2c8802e19fb0d4f0cde8f7b5ae7e
695180c14d136c1af33e50497c7957dc74835680
/tools/driver/drivers/char/tpu_common/tpuv4/tpuv4_interrupt_desc.h
8b221d55b8e3111da0a8eab85204eddded14e00c
[ "Apache-2.0" ]
permissive
tensorflow/tpu
4517c43b42c3dd98b8abafbbd9457384dd9639b1
0f7adb97a93ec3e3485c261d030c507eb16b33e4
refs/heads/master
2023-09-02T23:33:31.299394
2023-09-01T00:43:03
2023-09-01T00:43:03
96,946,693
5,627
2,107
Apache-2.0
2023-09-13T17:50:43
2017-07-11T23:54:39
Jupyter Notebook
UTF-8
C
false
false
1,196
h
tpuv4_interrupt_desc.h
/* SPDX-License-Identifier: GPL-2.0 */ /* * Copyright (C) 2021 Google LLC. */ #ifndef _DRIVERS_CHAR_TPU_COMMON_TPUV4_TPUV4_INTERRUPT_DESC_H_ #define _DRIVERS_CHAR_TPU_COMMON_TPUV4_TPUV4_INTERRUPT_DESC_H_ #include "drivers/gasket/gasket_core.h" #include <linux/kernel.h> #include <linux/types.h> const struct gasket_interrupt_desc tpuv4_interrupts[] = { { 2, 0x15b0008 }, { 2, 0x15b0000 }, { 2, 0x16b0008 }, { 2, 0x16b0000 }, { 2, 0x17b0008 }, { 2, 0x17b0000 }, { 2, 0x18b0008 }, { 2, 0x18b0000 }, { 2, 0x19b0020 }, { 2, 0x19b0000 }, { 2, 0x19b0008 }, { 2, 0x19b0010 }, { 2, 0x19b0018 }, { 2, 0x1ab0020 }, { 2, 0x1ab0000 }, { 2, 0x1ab0008 }, { 2, 0x1ab0010 }, { 2, 0x1ab0018 }, { 2, 0x4720000 }, { 2, 0x1bb0000 }, { 2, 0x1bb0008 }, { 2, 0x1bb0010 }, { 2, 0x1bb0018 }, { 2, 0x90000 }, { 2, 0xb0000 }, { 2, 0xd0000 }, { 2, 0xf0000 }, { 2, 0x110000 }, { 2, 0x130000 }, { 2, 0x150000 }, { 2, 0x170000 }, { 2, 0x190000 }, { 2, 0x1b0000 }, { 2, 0x1d0000 }, { 2, 0x1f0000 }, { 2, 0x210000 }, { 2, 0x230000 }, { 2, 0x250000 }, { 2, 0x270000 }, { 2, 0x290000 }, { 2, 0x2b0000 }, { 2, 0x2d0000 }, { 2, 0x2f0000 }, { 2, 0x310000 }, { 2, 0x4720018 }, }; #endif
9e5167421abc9264820978b2d9bd88032c95a837
3056334d5b034cf8d75bc006640ba9a9b74b61b9
/src/hev-jni.h
89090a2c2d50675f88aafe361358b0eedf578df9
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
heiher/hev-socks5-tunnel
986007615978650a4bf1cf30f1a37a59f1170a6a
dcbc1ea175a36c35fec3d9aa67fce1e59663c56a
refs/heads/master
2023-06-26T00:58:04.239633
2023-06-19T14:10:22
2023-06-19T14:10:22
211,069,848
359
63
MIT
2023-03-05T12:14:28
2019-09-26T11:09:51
C
UTF-8
C
false
false
373
h
hev-jni.h
/* ============================================================================ Name : hev-jni.h Author : hev <r@hev.cc> Copyright : Copyright (c) 2019 - 2023 hev Description : Java Native Interface ============================================================================ */ #ifndef __HEV_JNI_H__ #define __HEV_JNI_H__ #endif /* __HEV_JNI_H__ */
be1d4967de75255c107d262525e05214544457ba
46d7d222dc54c63228fd62bcac449b48cdaf9797
/butano/hw/3rd_party/libtonc/include/tonc_irq.h
dbccf78c7e42f81c95f00d74c89d017ee0d75ead
[ "MIT", "Zlib", "LicenseRef-scancode-unknown", "LicenseRef-scancode-unknown-license-reference" ]
permissive
GValiente/butano
020fff504c2c4cfde3395855c2b53525549bc3ff
2e39a999c3547f9f1a1839e1f89d3999f96b31f3
refs/heads/master
2023-08-30T15:05:46.091915
2023-08-30T03:42:21
2023-08-30T03:42:21
231,556,327
886
57
Zlib
2023-05-13T20:23:19
2020-01-03T09:35:05
C++
UTF-8
C
false
false
3,016
h
tonc_irq.h
// // Interrupt header // //! \file tonc_irq.h //! \author J Vijn //! \date 20060508 - 20080326 // // === NOTES === #ifndef TONC_IRQ #define TONC_IRQ #include "tonc_memmap.h" #include "tonc_memdef.h" // -------------------------------------------------------------------- // CONSTANTS // -------------------------------------------------------------------- /*! \addtogroup grpIrq \brief Hardware interrupt management. For details, see <a href="http://www.coranac.com/tonc/text/interrupts.htm">tonc:irq</a> */ /*! \{ */ //! IRQ indices, to be used in most functions. typedef enum eIrqIndex { II_VBLANK=0,II_HBLANK, II_VCOUNT, II_TIMER0, II_TIMER1, II_TIMER2, II_TIMER3, II_SERIAL, II_DMA0, II_DMA1, II_DMA2, II_DMA3, II_KEYPAD, II_GAMEPAK, II_MAX } eIrqIndex; //! \name Options for irq_set //\{ #define ISR_LAST 0x0040 //!< Last isr in line (Lowest priority) #define ISR_REPLACE 0x0080 //!< Replace old isr if existing (prio ignored) #define ISR_PRIO_MASK 0x003F //!< #define ISR_PRIO_SHIFT 0 #define ISR_PRIO(n) ((n)<<ISR_PRIO_SHIFT) #define ISR_DEF (ISR_LAST|ISR_REPLACE) //\} // -------------------------------------------------------------------- // MACROS // -------------------------------------------------------------------- //! Default irq_init() call: use irq_master_nest() for switchboard. #define IRQ_INIT() irq_init(NULL) //! Default irq_set() call: no isr, add to back of priority stack #define IRQ_SET(irq_id) irq_set(II_##irq_id, NULL, ISR_DEF) // Default irq_add() call: no isr #define IRQ_ADD(irq_id) irq_add(II_##irq_id, NULL) // -------------------------------------------------------------------- // CLASSES // -------------------------------------------------------------------- //! Struct for prioritized irq table typedef struct IRQ_REC { u32 flag; //!< Flag for interrupt in REG_IF, etc fnptr isr; //!< Pointer to interrupt routine } IRQ_REC; // -------------------------------------------------------------------- // GLOBALS // -------------------------------------------------------------------- extern IRQ_REC __isr_table[II_MAX+1]; // -------------------------------------------------------------------- // PROTOTYPES // -------------------------------------------------------------------- IWRAM_CODE void isr_master(void); IWRAM_CODE void isr_master_nest(void); void irq_init(fnptr isr); fnptr irq_set_master(fnptr isr); fnptr irq_add(enum eIrqIndex irq_id, fnptr isr); fnptr irq_add_disabled(enum eIrqIndex irq_id, fnptr isr); fnptr irq_delete(enum eIrqIndex irq_id); fnptr irq_set(enum eIrqIndex irq_id, fnptr isr, u32 opts); void irq_enable(enum eIrqIndex irq_id); void irq_disable(enum eIrqIndex irq_id); // -------------------------------------------------------------------- // INLINES // -------------------------------------------------------------------- /*! \} */ #endif // TONC_IRQ
583cfe7f51e397294cd617ab2829eaf95837fa64
0f5244a66dd11060f9c35d49f22ca026d171e29c
/src/class/net/ecm_rndis_device.c
762425732efe115fcd7ec4eee72d3e061ab75d93
[ "MIT" ]
permissive
hathach/tinyusb
b5557037f1cb1763b280f308829ceea94d31f3ae
1fdf29075d4e613eacfa881166015263797db0f6
refs/heads/master
2023-08-22T10:14:47.526256
2023-08-16T09:01:16
2023-08-16T09:01:16
6,860,771
4,096
918
MIT
2023-09-14T07:22:16
2012-11-26T06:24:00
C
UTF-8
C
false
false
14,117
c
ecm_rndis_device.c
/* * The MIT License (MIT) * * Copyright (c) 2020 Peter Lawrence * Copyright (c) 2019 Ha Thach (tinyusb.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * This file is part of the TinyUSB stack. */ #include "tusb_option.h" #if ( CFG_TUD_ENABLED && CFG_TUD_ECM_RNDIS ) #include "device/usbd.h" #include "device/usbd_pvt.h" #include "net_device.h" #include "rndis_protocol.h" void rndis_class_set_handler(uint8_t *data, int size); /* found in ./misc/networking/rndis_reports.c */ //--------------------------------------------------------------------+ // MACRO CONSTANT TYPEDEF //--------------------------------------------------------------------+ typedef struct { uint8_t itf_num; // Index number of Management Interface, +1 for Data Interface uint8_t itf_data_alt; // Alternate setting of Data Interface. 0 : inactive, 1 : active uint8_t ep_notif; uint8_t ep_in; uint8_t ep_out; bool ecm_mode; // Endpoint descriptor use to open/close when receiving SetInterface // TODO since configuration descriptor may not be long-lived memory, we should // keep a copy of endpoint attribute instead uint8_t const * ecm_desc_epdata; } netd_interface_t; #define CFG_TUD_NET_PACKET_PREFIX_LEN sizeof(rndis_data_packet_t) #define CFG_TUD_NET_PACKET_SUFFIX_LEN 0 CFG_TUD_MEM_SECTION CFG_TUSB_MEM_ALIGN tu_static uint8_t received[CFG_TUD_NET_PACKET_PREFIX_LEN + CFG_TUD_NET_MTU + CFG_TUD_NET_PACKET_PREFIX_LEN]; CFG_TUD_MEM_SECTION CFG_TUSB_MEM_ALIGN tu_static uint8_t transmitted[CFG_TUD_NET_PACKET_PREFIX_LEN + CFG_TUD_NET_MTU + CFG_TUD_NET_PACKET_PREFIX_LEN]; struct ecm_notify_struct { tusb_control_request_t header; uint32_t downlink, uplink; }; tu_static const struct ecm_notify_struct ecm_notify_nc = { .header = { .bmRequestType = 0xA1, .bRequest = 0 /* NETWORK_CONNECTION aka NetworkConnection */, .wValue = 1 /* Connected */, .wLength = 0, }, }; tu_static const struct ecm_notify_struct ecm_notify_csc = { .header = { .bmRequestType = 0xA1, .bRequest = 0x2A /* CONNECTION_SPEED_CHANGE aka ConnectionSpeedChange */, .wLength = 8, }, .downlink = 9728000, .uplink = 9728000, }; // TODO remove CFG_TUD_MEM_SECTION, control internal buffer is already in this special section CFG_TUD_MEM_SECTION CFG_TUSB_MEM_ALIGN tu_static union { uint8_t rndis_buf[120]; struct ecm_notify_struct ecm_buf; } notify; //--------------------------------------------------------------------+ // INTERNAL OBJECT & FUNCTION DECLARATION //--------------------------------------------------------------------+ // TODO remove CFG_TUD_MEM_SECTION CFG_TUD_MEM_SECTION tu_static netd_interface_t _netd_itf; tu_static bool can_xmit; void tud_network_recv_renew(void) { usbd_edpt_xfer(0, _netd_itf.ep_out, received, sizeof(received)); } static void do_in_xfer(uint8_t *buf, uint16_t len) { can_xmit = false; usbd_edpt_xfer(0, _netd_itf.ep_in, buf, len); } void netd_report(uint8_t *buf, uint16_t len) { uint8_t const rhport = 0; // skip if previous report not yet acknowledged by host if ( usbd_edpt_busy(rhport, _netd_itf.ep_notif) ) return; usbd_edpt_xfer(rhport, _netd_itf.ep_notif, buf, len); } //--------------------------------------------------------------------+ // USBD Driver API //--------------------------------------------------------------------+ void netd_init(void) { tu_memclr(&_netd_itf, sizeof(_netd_itf)); } void netd_reset(uint8_t rhport) { (void) rhport; netd_init(); } uint16_t netd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len) { bool const is_rndis = (TUD_RNDIS_ITF_CLASS == itf_desc->bInterfaceClass && TUD_RNDIS_ITF_SUBCLASS == itf_desc->bInterfaceSubClass && TUD_RNDIS_ITF_PROTOCOL == itf_desc->bInterfaceProtocol); bool const is_ecm = (TUSB_CLASS_CDC == itf_desc->bInterfaceClass && CDC_COMM_SUBCLASS_ETHERNET_CONTROL_MODEL == itf_desc->bInterfaceSubClass && 0x00 == itf_desc->bInterfaceProtocol); TU_VERIFY(is_rndis || is_ecm, 0); // confirm interface hasn't already been allocated TU_ASSERT(0 == _netd_itf.ep_notif, 0); // sanity check the descriptor _netd_itf.ecm_mode = is_ecm; //------------- Management Interface -------------// _netd_itf.itf_num = itf_desc->bInterfaceNumber; uint16_t drv_len = sizeof(tusb_desc_interface_t); uint8_t const * p_desc = tu_desc_next( itf_desc ); // Communication Functional Descriptors while ( TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc) && drv_len <= max_len ) { drv_len += tu_desc_len(p_desc); p_desc = tu_desc_next(p_desc); } // notification endpoint (if any) if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) ) { TU_ASSERT( usbd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc), 0 ); _netd_itf.ep_notif = ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress; drv_len += tu_desc_len(p_desc); p_desc = tu_desc_next(p_desc); } //------------- Data Interface -------------// // - RNDIS Data followed immediately by a pair of endpoints // - CDC-ECM data interface has 2 alternate settings // - 0 : zero endpoints for inactive (default) // - 1 : IN & OUT endpoints for active networking TU_ASSERT(TUSB_DESC_INTERFACE == tu_desc_type(p_desc), 0); do { tusb_desc_interface_t const * data_itf_desc = (tusb_desc_interface_t const *) p_desc; TU_ASSERT(TUSB_CLASS_CDC_DATA == data_itf_desc->bInterfaceClass, 0); drv_len += tu_desc_len(p_desc); p_desc = tu_desc_next(p_desc); }while( _netd_itf.ecm_mode && (TUSB_DESC_INTERFACE == tu_desc_type(p_desc)) && (drv_len <= max_len) ); // Pair of endpoints TU_ASSERT(TUSB_DESC_ENDPOINT == tu_desc_type(p_desc), 0); if ( _netd_itf.ecm_mode ) { // ECM by default is in-active, save the endpoint attribute // to open later when received setInterface _netd_itf.ecm_desc_epdata = p_desc; }else { // Open endpoint pair for RNDIS TU_ASSERT( usbd_open_edpt_pair(rhport, p_desc, 2, TUSB_XFER_BULK, &_netd_itf.ep_out, &_netd_itf.ep_in), 0 ); tud_network_init_cb(); // we are ready to transmit a packet can_xmit = true; // prepare for incoming packets tud_network_recv_renew(); } drv_len += 2*sizeof(tusb_desc_endpoint_t); return drv_len; } static void ecm_report(bool nc) { notify.ecm_buf = (nc) ? ecm_notify_nc : ecm_notify_csc; notify.ecm_buf.header.wIndex = _netd_itf.itf_num; netd_report((uint8_t *)&notify.ecm_buf, (nc) ? sizeof(notify.ecm_buf.header) : sizeof(notify.ecm_buf)); } // Invoked when a control transfer occurred on an interface of this class // Driver response accordingly to the request and the transfer stage (setup/data/ack) // return false to stall control endpoint (e.g unsupported request) bool netd_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t const * request) { if ( stage == CONTROL_STAGE_SETUP ) { switch ( request->bmRequestType_bit.type ) { case TUSB_REQ_TYPE_STANDARD: switch ( request->bRequest ) { case TUSB_REQ_GET_INTERFACE: { uint8_t const req_itfnum = (uint8_t) request->wIndex; TU_VERIFY(_netd_itf.itf_num+1 == req_itfnum); tud_control_xfer(rhport, request, &_netd_itf.itf_data_alt, 1); } break; case TUSB_REQ_SET_INTERFACE: { uint8_t const req_itfnum = (uint8_t) request->wIndex; uint8_t const req_alt = (uint8_t) request->wValue; // Only valid for Data Interface with Alternate is either 0 or 1 TU_VERIFY(_netd_itf.itf_num+1 == req_itfnum && req_alt < 2); // ACM-ECM only: qequest to enable/disable network activities TU_VERIFY(_netd_itf.ecm_mode); _netd_itf.itf_data_alt = req_alt; if ( _netd_itf.itf_data_alt ) { // TODO since we don't actually close endpoint // hack here to not re-open it if ( _netd_itf.ep_in == 0 && _netd_itf.ep_out == 0 ) { TU_ASSERT(_netd_itf.ecm_desc_epdata); TU_ASSERT( usbd_open_edpt_pair(rhport, _netd_itf.ecm_desc_epdata, 2, TUSB_XFER_BULK, &_netd_itf.ep_out, &_netd_itf.ep_in) ); // TODO should be merge with RNDIS's after endpoint opened // Also should have opposite callback for application to disable network !! tud_network_init_cb(); can_xmit = true; // we are ready to transmit a packet tud_network_recv_renew(); // prepare for incoming packets } }else { // TODO close the endpoint pair // For now pretend that we did, this should have no harm since host won't try to // communicate with the endpoints again // _netd_itf.ep_in = _netd_itf.ep_out = 0 } tud_control_status(rhport, request); } break; // unsupported request default: return false; } break; case TUSB_REQ_TYPE_CLASS: TU_VERIFY (_netd_itf.itf_num == request->wIndex); if (_netd_itf.ecm_mode) { /* the only required CDC-ECM Management Element Request is SetEthernetPacketFilter */ if (0x43 /* SET_ETHERNET_PACKET_FILTER */ == request->bRequest) { tud_control_xfer(rhport, request, NULL, 0); ecm_report(true); } } else { if (request->bmRequestType_bit.direction == TUSB_DIR_IN) { rndis_generic_msg_t *rndis_msg = (rndis_generic_msg_t *) ((void*) notify.rndis_buf); uint32_t msglen = tu_le32toh(rndis_msg->MessageLength); TU_ASSERT(msglen <= sizeof(notify.rndis_buf)); tud_control_xfer(rhport, request, notify.rndis_buf, (uint16_t) msglen); } else { tud_control_xfer(rhport, request, notify.rndis_buf, (uint16_t) sizeof(notify.rndis_buf)); } } break; // unsupported request default: return false; } } else if ( stage == CONTROL_STAGE_DATA ) { // Handle RNDIS class control OUT only if (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS && request->bmRequestType_bit.direction == TUSB_DIR_OUT && _netd_itf.itf_num == request->wIndex) { if ( !_netd_itf.ecm_mode ) { rndis_class_set_handler(notify.rndis_buf, request->wLength); } } } return true; } static void handle_incoming_packet(uint32_t len) { uint8_t *pnt = received; uint32_t size = 0; if (_netd_itf.ecm_mode) { size = len; } else { rndis_data_packet_t *r = (rndis_data_packet_t *) ((void*) pnt); if (len >= sizeof(rndis_data_packet_t)) if ( (r->MessageType == REMOTE_NDIS_PACKET_MSG) && (r->MessageLength <= len)) if ( (r->DataOffset + offsetof(rndis_data_packet_t, DataOffset) + r->DataLength) <= len) { pnt = &received[r->DataOffset + offsetof(rndis_data_packet_t, DataOffset)]; size = r->DataLength; } } if (!tud_network_recv_cb(pnt, (uint16_t) size)) { /* if a buffer was never handled by user code, we must renew on the user's behalf */ tud_network_recv_renew(); } } bool netd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) { (void) rhport; (void) result; /* new packet received */ if ( ep_addr == _netd_itf.ep_out ) { handle_incoming_packet(xferred_bytes); } /* data transmission finished */ if ( ep_addr == _netd_itf.ep_in ) { /* TinyUSB requires the class driver to implement ZLP (since ZLP usage is class-specific) */ if ( xferred_bytes && (0 == (xferred_bytes % CFG_TUD_NET_ENDPOINT_SIZE)) ) { do_in_xfer(NULL, 0); /* a ZLP is needed */ } else { /* we're finally finished */ can_xmit = true; } } if ( _netd_itf.ecm_mode && (ep_addr == _netd_itf.ep_notif) ) { if (sizeof(notify.ecm_buf.header) == xferred_bytes) ecm_report(false); } return true; } bool tud_network_can_xmit(uint16_t size) { (void)size; return can_xmit; } void tud_network_xmit(void *ref, uint16_t arg) { uint8_t *data; uint16_t len; if (!can_xmit) return; len = (_netd_itf.ecm_mode) ? 0 : CFG_TUD_NET_PACKET_PREFIX_LEN; data = transmitted + len; len += tud_network_xmit_cb(data, ref, arg); if (!_netd_itf.ecm_mode) { rndis_data_packet_t *hdr = (rndis_data_packet_t *) ((void*) transmitted); memset(hdr, 0, sizeof(rndis_data_packet_t)); hdr->MessageType = REMOTE_NDIS_PACKET_MSG; hdr->MessageLength = len; hdr->DataOffset = sizeof(rndis_data_packet_t) - offsetof(rndis_data_packet_t, DataOffset); hdr->DataLength = len - sizeof(rndis_data_packet_t); } do_in_xfer(transmitted, len); } #endif
360be2ead0cb0ada77b737f465865e4eb2e28442
c0bfd93cd7f26a271268e504959256f1e02c6806
/components/libsodium/libsodium/src/libsodium/randombytes/nativeclient/randombytes_nativeclient.c
468cd653d91d75eb8be6139fc761472b7c0fe357
[ "ISC", "Apache-2.0" ]
permissive
espressif/ESP8266_RTOS_SDK
606f396e92d2675d9854f0fabd88587fbbbaf267
af0cdc36fa2600033d0a09301c754008cf1503c1
refs/heads/master
2023-08-24T22:40:15.373553
2023-05-06T02:04:24
2023-05-06T02:04:24
27,584,181
3,163
1,749
Apache-2.0
2023-08-09T10:48:13
2014-12-05T09:27:12
C
UTF-8
C
false
false
1,462
c
randombytes_nativeclient.c
#include <assert.h> #include <stdint.h> #include <stdlib.h> #ifdef __native_client__ # include <irt.h> # include "utils.h" # include "randombytes.h" # include "randombytes_nativeclient.h" static void randombytes_nativeclient_buf(void * const buf, const size_t size) { unsigned char *buf_ = (unsigned char *) buf; struct nacl_irt_random rand_intf; size_t readnb = (size_t) 0U; size_t toread = size; if (nacl_interface_query(NACL_IRT_RANDOM_v0_1, &rand_intf, sizeof rand_intf) != sizeof rand_intf) { abort(); } while (toread > (size_t) 0U) { if (rand_intf.get_random_bytes(buf_, size, &readnb) != 0 || readnb > size) { abort(); } toread -= readnb; buf_ += readnb; } } static uint32_t randombytes_nativeclient_random(void) { uint32_t r; randombytes_nativeclient_buf(&r, sizeof r); return r; } static const char * randombytes_nativeclient_implementation_name(void) { return "nativeclient"; } struct randombytes_implementation randombytes_nativeclient_implementation = { SODIUM_C99(.implementation_name =) randombytes_nativeclient_implementation_name, SODIUM_C99(.random =) randombytes_nativeclient_random, SODIUM_C99(.stir =) NULL, SODIUM_C99(.uniform =) NULL, SODIUM_C99(.buf =) randombytes_nativeclient_buf, SODIUM_C99(.close =) NULL }; #endif
992149c521d74ae295cafc6e6acd2ddaa3c1420b
c0bfd93cd7f26a271268e504959256f1e02c6806
/components/wear_levelling/private_include/WL_Config.h
0a53106912a41e4c89a706cabbfb6dee8831f62e
[ "Apache-2.0" ]
permissive
espressif/ESP8266_RTOS_SDK
606f396e92d2675d9854f0fabd88587fbbbaf267
af0cdc36fa2600033d0a09301c754008cf1503c1
refs/heads/master
2023-08-24T22:40:15.373553
2023-05-06T02:04:24
2023-05-06T02:04:24
27,584,181
3,163
1,749
Apache-2.0
2023-08-09T10:48:13
2014-12-05T09:27:12
C
UTF-8
C
false
false
2,250
h
WL_Config.h
// Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD // // 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. #ifndef _WL_Config_H_ #define _WL_Config_H_ #include "Flash_Access.h" /** * @brief This class is used as a structure to configure wear levelling module * */ #if defined(_MSC_VER) #define ALIGNED_(x) __declspec(align(x)) #else #if defined(__GNUC__) #define ALIGNED_(x) __attribute__ ((aligned(x))) #endif #endif typedef struct ALIGNED_(16) WL_Config_s { /*!< Size of wl_config_t structure should be divided by 16 for encryption*/ size_t start_addr; /*!< start address in the flash*/ uint32_t full_mem_size; /*!< Amount of memory used to store data in bytes*/ uint32_t page_size; /*!< One page size in bytes. Page could be more then memory block. This parameter must be page_size >= N*block_size.*/ uint32_t sector_size; /*!< size of flash memory sector that will be erased and stored at once (erase)*/ uint32_t updaterate; /*!< Amount of accesses before block will be moved*/ uint32_t wr_size; /*!< Minimum amount of bytes per one block at write operation: 1...*/ uint32_t version; /*!< A version of current implementatioon. To erase and reallocate complete memory this ID must be different from id before.*/ size_t temp_buff_size; /*!< Size of temporary allocated buffer to copy from one flash area to another. The best way, if this value will be equal to sector size.*/ uint32_t crc; /*!< CRC for this config*/ } wl_config_t; #ifndef _MSC_VER // MSVS has different format for this define static_assert(sizeof(wl_config_t) % 16 == 0, "Size of wl_config_t structure should be compatible with flash encryption"); #endif // _MSC_VER #endif // _WL_Config_H_
90539dc082b128ebbee4fd23df3ff2e9bc5d0436
1ba0d12bf8b853f48dbd8cb7b702a48e4fdbfd97
/bootrom/common.h
9afe3103c07d0b4726e8150b2ea27f924064b793
[]
no_license
eugene-tarassov/vivado-risc-v
47cf44eeaa4232571a5d7de6e667531865479045
c76a8613a177b3a04face2cb8e15dd07a8d2fc40
refs/heads/master
2023-09-04T09:44:41.122100
2023-07-17T06:38:36
2023-07-17T06:38:36
240,625,745
556
154
null
2023-02-06T04:17:55
2020-02-15T01:12:54
C
UTF-8
C
false
false
491
h
common.h
#ifndef _SDBOOT_COMMON_H #define _SDBOOT_COMMON_H #define BOOTROM_DTB_ADDR 0x00010080 // Addresses must be aligned by 0x100 #define BOOTROM_MEM_ADDR 0x80000000 #define BOOTROM_MEM_END 0x80002000 #ifndef BOOTROM_MEM_ALT // If the application is linked to be loaded at BOOTROM_MEM_ADDR: // BOOTROM_MEM_ALT is used as temporary storage // system RAM size must be >= 128MB // the application size must be <= (128MB - 8KB) #define BOOTROM_MEM_ALT 0x87ffe000 #endif #endif
e0b498fc271dc55233d03155964804a3c4f1b5b4
1efd2de8bf77ec00eb2fcaf5749278495946d920
/src/include/gurt/telemetry_consumer.h
f0b1d706be718df7cbd62e82574e0d09a2a21e18
[ "BSD-2-Clause", "BSD-2-Clause-Patent" ]
permissive
daos-stack/daos
6f55bf3061fd830d5b8d28506e1295e2d3a27c38
ed5eed5df43a68571afe123132a743824c02637a
refs/heads/master
2023-08-31T21:43:37.606145
2023-08-31T16:38:00
2023-08-31T16:38:00
69,390,670
631
300
NOASSERTION
2023-09-14T18:55:15
2016-09-27T19:21:29
C
UTF-8
C
false
false
3,467
h
telemetry_consumer.h
/** * (C) Copyright 2020-2021 Intel Corporation. * * SPDX-License-Identifier: BSD-2-Clause-Patent */ #ifndef __TELEMETRY_CONSUMER_H__ #define __TELEMETRY_CONSUMER_H__ #include <gurt/telemetry_common.h> /* Developer facing client API to read data */ char *d_tm_get_name(struct d_tm_context *ctx, struct d_tm_node_t *node); int d_tm_get_counter(struct d_tm_context *ctx, uint64_t *val, struct d_tm_node_t *node); int d_tm_get_timestamp(struct d_tm_context *ctx, time_t *val, struct d_tm_node_t *node); int d_tm_get_timer_snapshot(struct d_tm_context *ctx, struct timespec *tms, struct d_tm_node_t *node); int d_tm_get_gauge(struct d_tm_context *ctx, uint64_t *val, struct d_tm_stats_t *stats, struct d_tm_node_t *node); int d_tm_get_duration(struct d_tm_context *ctx, struct timespec *tms, struct d_tm_stats_t *stats, struct d_tm_node_t *node); int d_tm_get_metadata(struct d_tm_context *ctx, char **desc, char **units, struct d_tm_node_t *node); int d_tm_get_num_buckets(struct d_tm_context *ctx, struct d_tm_histogram_t *histogram, struct d_tm_node_t *node); int d_tm_get_bucket_range(struct d_tm_context *ctx, struct d_tm_bucket_t *bucket, int bucket_id, struct d_tm_node_t *node); /* Developer facing client API to discover topology and manage results */ struct d_tm_context *d_tm_open(int id); void d_tm_close(struct d_tm_context **ctx); void d_tm_gc_ctx(struct d_tm_context *ctx); void *d_tm_conv_ptr(struct d_tm_context *ctx, struct d_tm_node_t *node, void *ptr); struct d_tm_node_t *d_tm_get_root(struct d_tm_context *ctx); struct d_tm_node_t *d_tm_get_child(struct d_tm_context *ctx, struct d_tm_node_t *node); struct d_tm_node_t *d_tm_get_sibling(struct d_tm_context *ctx, struct d_tm_node_t *node); struct d_tm_node_t *d_tm_find_metric(struct d_tm_context *ctx, char *path); uint64_t d_tm_count_metrics(struct d_tm_context *ctx, struct d_tm_node_t *node, int d_tm_type); int d_tm_list(struct d_tm_context *ctx, struct d_tm_nodeList_t **head, struct d_tm_node_t *node, int d_tm_type); int d_tm_list_subdirs(struct d_tm_context *ctx, struct d_tm_nodeList_t **head, struct d_tm_node_t *node, uint64_t *node_count, int max_depth); void d_tm_iterate(struct d_tm_context *ctx, struct d_tm_node_t *node, int level, int filter, char *path, int format, int opt_fields, uint32_t ops, FILE *stream); void d_tm_print_node(struct d_tm_context *ctx, struct d_tm_node_t *node, int level, char *name, int format, int opt_fields, FILE *stream); void d_tm_print_field_descriptors(int opt_fields, FILE *stream); void d_tm_print_counter(uint64_t val, char *name, int format, char *units, int opt_fields, FILE *stream); void d_tm_print_timestamp(time_t *clk, char *name, int format, int opt_fields, FILE *stream); void d_tm_print_timer_snapshot(struct timespec *tms, char *name, int tm_type, int format, int opt_fields, FILE *stream); void d_tm_print_duration(struct timespec *tms, struct d_tm_stats_t *stats, char *name, int tm_type, int format, int opt_fields, FILE *stream); void d_tm_print_gauge(uint64_t val, struct d_tm_stats_t *stats, char *name, int format, char *units, int opt_fields, FILE *stream); void d_tm_print_metadata(char *desc, char *units, int format, FILE *stream); int d_tm_clock_id(int clk_id); char *d_tm_clock_string(int clk_id); #endif /* __TELEMETRY_CONSUMER_H__ */
419d4f4481e1e7b2d0c16b662161dfcbdbc9a4e3
b6acd6eed2b8946c1c1e19fa30081cbab0a2954f
/starry_fmu/RTOS/components/gui/src/topwin.c
0cb522c95fb05f0c07110a5dde5f330b15618487
[ "BSD-3-Clause" ]
permissive
JcZou/StarryPilot
7ce1ed454f133ccd30d71916811e2bf23196d2eb
97af0338a54e1eeece877c72222aeaf4b7e80ad7
refs/heads/master
2023-03-12T19:10:17.225314
2021-11-27T19:44:26
2021-11-27T19:44:26
137,048,745
304
172
BSD-3-Clause
2020-08-26T07:34:49
2018-06-12T09:27:59
C
UTF-8
C
false
false
33,366
c
topwin.c
/* * File : topwin.c * This file is part of RT-Thread RTOS * COPYRIGHT (C) 2006 - 2009, RT-Thread Development Team * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rt-thread.org/license/LICENSE * * Change Logs: * Date Author Notes * 2009-10-16 Bernard first version * 2012-02-25 Grissiom rewrite topwin implementation */ #include "topwin.h" #include "mouse.h" #include <rtservice.h> #include <rtgui/event.h> #include <rtgui/image.h> //#include <rtgui/rtgui_theme.h> #include <rtgui/rtgui_system.h> #include <rtgui/rtgui_app.h> #include <rtgui/widgets/window.h> #include <rtgui/widgets/container.h> /* * windows tree in the server side. * * This list is divided into two parts. The first part is the shown list, in * which all the windows have the WINTITLE_SHOWN flag set. Second part is the * hidden items, in which all the windows don't have WINTITLE_SHOWN flag. * * The active window is the one that would receive kbd events. It should always * be in the first tree. The order of this list is the order of the windows. * Top window can always clip the window beneath it when the two * overlapping. Child window can always clip it's parent. Slibing windows can * clip each other with the same rule as this list. Each child list is the same * as _rtgui_topwin_list. This forms the hierarchy tree structure of all * windows. * * Thus, the left most leaf of the tree is the top most window and the right * most root node is the bottom window. The hidden part have no specific * order. */ #define get_topwin_from_list(list_entry) (rt_list_entry((list_entry), struct rtgui_topwin, list)) /* the direction can only be next or prev. If you want to iterate the list in * normal order, use next. If you want to iterate the list with reverse order, * use prev.*/ #define rt_list_foreach(node, list, direction) \ for ((node) = (list)->direction; (node) != list; (node) = (node)->direction) #define IS_ROOT_WIN(topwin) ((topwin)->parent == RT_NULL) static rt_list_t _rtgui_topwin_list = RT_LIST_OBJECT_INIT(_rtgui_topwin_list); static struct rt_semaphore _rtgui_topwin_lock; static void rtgui_topwin_update_clip(void); static void rtgui_topwin_redraw(struct rtgui_rect *rect); static void _rtgui_topwin_activate_next(enum rtgui_topwin_flag); void rtgui_topwin_init(void) { /* initialize semaphore */ rt_sem_init(&_rtgui_topwin_lock, "wintree", 1, RT_IPC_FLAG_FIFO); } static struct rtgui_topwin *rtgui_topwin_search_in_list(struct rtgui_win *window, struct rt_list_node *list) { /* TODO: use a cache to speed up the search. */ struct rt_list_node *node; struct rtgui_topwin *topwin; /* the action is tend to operate on the top most window. So we search in a * depth first order. */ rt_list_foreach(node, list, next) { topwin = rt_list_entry(node, struct rtgui_topwin, list); /* is this node? */ if (topwin->wid == window) { return topwin; } topwin = rtgui_topwin_search_in_list(window, &topwin->child_list); if (topwin != RT_NULL) return topwin; } return RT_NULL; } /* add a window to window list[hide] */ rt_err_t rtgui_topwin_add(struct rtgui_event_win_create *event) { struct rtgui_topwin *topwin; topwin = rtgui_malloc(sizeof(struct rtgui_topwin)); if (topwin == RT_NULL) return -RT_ERROR; topwin->wid = event->wid; if (event->wid->_title_wgt) topwin->extent = RTGUI_WIDGET(event->wid->_title_wgt)->extent; else topwin->extent = RTGUI_WIDGET(event->wid)->extent; topwin->app = event->parent.sender; if (event->parent_window == RT_NULL) { topwin->parent = RT_NULL; rt_list_insert_before(&_rtgui_topwin_list, &topwin->list); } else { topwin->parent = rtgui_topwin_search_in_list(event->parent_window, &_rtgui_topwin_list); if (topwin->parent == RT_NULL) { /* parent does not exist. Orphan window? */ rtgui_free(topwin); return -RT_ERROR; } rt_list_insert_before(&topwin->parent->child_list, &topwin->list); } rt_list_init(&topwin->child_list); topwin->flag = WINTITLE_INIT; if (event->parent.user & RTGUI_WIN_STYLE_NO_FOCUS) topwin->flag |= WINTITLE_NOFOCUS; if (event->parent.user & RTGUI_WIN_STYLE_ONTOP) topwin->flag |= WINTITLE_ONTOP; if (event->parent.user & RTGUI_WIN_STYLE_ONBTM) topwin->flag |= WINTITLE_ONBTM; topwin->title = RT_NULL; rtgui_list_init(&topwin->monitor_list); return RT_EOK; } static struct rtgui_topwin *_rtgui_topwin_get_root_win(struct rtgui_topwin *topwin) { struct rtgui_topwin *topparent; RT_ASSERT(topwin != RT_NULL); topparent = topwin; while (topparent && !IS_ROOT_WIN(topparent)) topparent = topparent->parent; return topparent; } static struct rtgui_topwin *_rtgui_topwin_get_topmost_child_shown(struct rtgui_topwin *topwin) { RT_ASSERT(topwin != RT_NULL); while (!(rt_list_isempty(&topwin->child_list)) && get_topwin_from_list(topwin->child_list.next)->flag & WINTITLE_SHOWN) { topwin = get_topwin_from_list(topwin->child_list.next); } return topwin; } static rt_bool_t _rtgui_topwin_in_layer(struct rtgui_topwin *topwin, enum rtgui_topwin_flag flag) { return (topwin->flag & (WINTITLE_ONTOP | WINTITLE_ONBTM)) == (flag & (WINTITLE_ONTOP | WINTITLE_ONBTM)); } /* find the topmost window shown in the layer set by flag. The flag has many * other infomations but we only use the ONTOP/ONBTM */ struct rtgui_topwin *rtgui_topwin_get_topmost_window_shown(enum rtgui_topwin_flag flag) { struct rt_list_node *node; rt_list_foreach(node, &_rtgui_topwin_list, next) { struct rtgui_topwin *topwin = get_topwin_from_list(node); /* reach the hidden region no window shown in current layer */ if (!(topwin->flag & WINTITLE_SHOWN)) return RT_NULL; if (_rtgui_topwin_in_layer(topwin, flag)) return _rtgui_topwin_get_topmost_child_shown(topwin); } /* no window in current layer is shown */ return RT_NULL; } struct rtgui_topwin *rtgui_topwin_get_topmost_window_shown_all(void) { struct rtgui_topwin *top; top = rtgui_topwin_get_topmost_window_shown(WINTITLE_ONTOP); /* 0 is normal layer */ if (top == RT_NULL) top = rtgui_topwin_get_topmost_window_shown(WINTITLE_INIT); if (top == RT_NULL) top = rtgui_topwin_get_topmost_window_shown(WINTITLE_ONBTM); return top; } struct rtgui_win* rtgui_win_get_topmost_shown(void) { struct rtgui_topwin *top; top = rtgui_topwin_get_topmost_window_shown_all(); if (!top) return RT_NULL; return top->wid; } static struct rtgui_topwin* _rtgui_topwin_get_next_shown(struct rtgui_topwin *top) { /* move to next sibling tree */ if (top->parent == RT_NULL) { if (top->list.next != &_rtgui_topwin_list && get_topwin_from_list(top->list.next)->flag & WINTITLE_SHOWN) top = _rtgui_topwin_get_topmost_child_shown(get_topwin_from_list(top->list.next)); else return RT_NULL; } /* move to next slibing topwin */ else if (top->list.next != &top->parent->child_list && get_topwin_from_list(top->list.next)->flag & WINTITLE_SHOWN) { top = _rtgui_topwin_get_topmost_child_shown(get_topwin_from_list(top->list.next)); } /* level up */ else { top = top->parent; } return top; } struct rtgui_win* rtgui_win_get_next_shown(void) { struct rtgui_topwin *top; top = rtgui_topwin_get_topmost_window_shown_all(); if (!top) return RT_NULL; top = _rtgui_topwin_get_next_shown(top); if (!top) return RT_NULL; return top->wid; } /* a hidden parent will hide it's children. Top level window can be shown at * any time. */ static rt_bool_t _rtgui_topwin_could_show(struct rtgui_topwin *topwin) { struct rtgui_topwin *parent; RT_ASSERT(topwin != RT_NULL); for (parent = topwin->parent; parent != RT_NULL; parent = parent->parent) { if (!(parent->flag & WINTITLE_SHOWN)) return RT_FALSE; } return RT_TRUE; } static void _rtgui_topwin_union_region_tree(struct rtgui_topwin *topwin, struct rtgui_region *region) { struct rt_list_node *node; RT_ASSERT(topwin != RT_NULL); rt_list_foreach(node, &topwin->child_list, next) _rtgui_topwin_union_region_tree(get_topwin_from_list(node), region); rtgui_region_union_rect(region, region, &topwin->extent); } /* The return value of this function is the next node in tree. * * As we freed the node in this function, it would be a null reference error of * the caller iterate the tree normally. */ static struct rt_list_node *_rtgui_topwin_free_tree(struct rtgui_topwin *topwin) { struct rt_list_node *node, *next_node; RT_ASSERT(topwin != RT_NULL); node = topwin->child_list.next; while (node != &topwin->child_list) node = _rtgui_topwin_free_tree(get_topwin_from_list(node)); next_node = topwin->list.next; rt_list_remove(&topwin->list); /* free the monitor rect list, topwin node and title */ while (topwin->monitor_list.next != RT_NULL) { struct rtgui_mouse_monitor *monitor = rtgui_list_entry(topwin->monitor_list.next, struct rtgui_mouse_monitor, list); topwin->monitor_list.next = topwin->monitor_list.next->next; rtgui_free(monitor); } rtgui_free(topwin); return next_node; } rt_err_t rtgui_topwin_remove(struct rtgui_win *wid) { struct rtgui_topwin *topwin, *old_focus; struct rtgui_region region; /* find the topwin node */ topwin = rtgui_topwin_search_in_list(wid, &_rtgui_topwin_list); if (topwin == RT_NULL) return -RT_ERROR; rtgui_region_init(&region); old_focus = rtgui_topwin_get_focus(); /* remove the root from _rtgui_topwin_list will remove the whole tree from * _rtgui_topwin_list. */ rt_list_remove(&topwin->list); if (old_focus == topwin) { _rtgui_topwin_activate_next(topwin->flag); } if (topwin->flag & WINTITLE_SHOWN) { rtgui_topwin_update_clip(); /* redraw the old rect */ _rtgui_topwin_union_region_tree(topwin, &region); rtgui_topwin_redraw(rtgui_region_extents(&region)); } rtgui_region_fini(&region); _rtgui_topwin_free_tree(topwin); return RT_EOK; } /* neither deactivate the old focus nor change _rtgui_topwin_list. * Suitable to be called when the first item is the window to be activated * already. */ static void _rtgui_topwin_only_activate(struct rtgui_topwin *topwin) { struct rtgui_event_win event; RT_ASSERT(topwin != RT_NULL); if (topwin->flag & WINTITLE_NOFOCUS) return; /* activate the raised window */ RTGUI_EVENT_WIN_ACTIVATE_INIT(&event); topwin->flag |= WINTITLE_ACTIVATE; event.wid = topwin->wid; rtgui_send(topwin->app, &(event.parent), sizeof(struct rtgui_event_win)); } /* activate next window in the same layer as flag. The flag has many other * infomations but we only use the ONTOP/ONBTM */ static void _rtgui_topwin_activate_next(enum rtgui_topwin_flag flag) { struct rtgui_topwin *topwin; topwin = rtgui_topwin_get_topmost_window_shown(flag); if (topwin == RT_NULL) return; _rtgui_topwin_only_activate(topwin); } /* this function does not update the clip(to avoid doubel clipping). So if the * tree has changed, make sure it has already updated outside. */ static void _rtgui_topwin_deactivate(struct rtgui_topwin *topwin) { struct rtgui_event_win event; RT_ASSERT(topwin != RT_NULL); RT_ASSERT(topwin->app != RT_NULL); RTGUI_EVENT_WIN_DEACTIVATE_INIT(&event); event.wid = topwin->wid; rtgui_send(topwin->app, &event.parent, sizeof(struct rtgui_event_win)); topwin->flag &= ~WINTITLE_ACTIVATE; } /* Return 1 on the tree is truely moved. If the tree is already in position, * return 0. */ static int _rtgui_topwin_move_whole_tree2top(struct rtgui_topwin *topwin) { struct rtgui_topwin *topparent; RT_ASSERT(topwin != RT_NULL); /* move the whole tree */ topparent = _rtgui_topwin_get_root_win(topwin); RT_ASSERT(topparent != RT_NULL); /* add node to show list */ if (topwin->flag & WINTITLE_ONTOP) { if (get_topwin_from_list(_rtgui_topwin_list.next) == topwin) return 0; rt_list_remove(&topparent->list); rt_list_insert_after(&_rtgui_topwin_list, &(topparent->list)); } else if (topwin->flag & WINTITLE_ONBTM) { /* botton layer window, before the fisrt bottom window or hidden window. */ struct rt_list_node *node; struct rtgui_topwin *ntopwin = RT_NULL; rt_list_foreach(node, &_rtgui_topwin_list, next) { ntopwin = get_topwin_from_list(node); if ((ntopwin->flag & WINTITLE_ONBTM) || !(ntopwin->flag & WINTITLE_SHOWN)) break; } if (get_topwin_from_list(node) == topparent) return 0; rt_list_remove(&topparent->list); rt_list_insert_before(node, &(topparent->list)); } else { /* normal layer window, before the fisrt shown normal layer window. */ struct rtgui_topwin *ntopwin = RT_NULL; struct rt_list_node *node; rt_list_foreach(node, &_rtgui_topwin_list, next) { ntopwin = get_topwin_from_list(node); if (!((ntopwin->flag & WINTITLE_ONTOP) && (ntopwin->flag & WINTITLE_SHOWN))) break; } if (get_topwin_from_list(node) == topparent) return 0; rt_list_remove(&topparent->list); rt_list_insert_before(node, &(topparent->list)); } return 1; } static void _rtgui_topwin_raise_in_sibling(struct rtgui_topwin *topwin) { struct rt_list_node *win_level; RT_ASSERT(topwin != RT_NULL); if (topwin->parent == RT_NULL) win_level = &_rtgui_topwin_list; else win_level = &topwin->parent->child_list; rt_list_remove(&topwin->list); rt_list_insert_after(win_level, &topwin->list); } /* it will do 2 things. One is moving the whole tree(the root of the tree) to * the front and the other is moving topwin to the front of it's siblings. */ static int _rtgui_topwin_raise_tree_from_root(struct rtgui_topwin *topwin) { int moved; RT_ASSERT(topwin != RT_NULL); moved = _rtgui_topwin_move_whole_tree2top(topwin); /* root win is aleady moved by _rtgui_topwin_move_whole_tree2top */ if (!IS_ROOT_WIN(topwin)) _rtgui_topwin_raise_in_sibling(topwin); return moved; } /* activate a win means: * - deactivate the old focus win if any * - raise the window to the front of it's siblings * - activate a win */ rt_err_t rtgui_topwin_activate(struct rtgui_event_win_activate *event) { struct rtgui_topwin *topwin; RT_ASSERT(event); topwin = rtgui_topwin_search_in_list(event->wid, &_rtgui_topwin_list); if (topwin == RT_NULL) return -RT_ERROR; return rtgui_topwin_activate_topwin(topwin); } static void _rtgui_topwin_draw_tree(struct rtgui_topwin *topwin, struct rtgui_event_paint *epaint) { struct rt_list_node *node; rt_list_foreach(node, &topwin->child_list, next) { if (!(get_topwin_from_list(node)->flag & WINTITLE_SHOWN)) break; _rtgui_topwin_draw_tree(get_topwin_from_list(node), epaint); } epaint->wid = topwin->wid; rtgui_send(topwin->app, &(epaint->parent), sizeof(*epaint)); } rt_err_t rtgui_topwin_activate_topwin(struct rtgui_topwin *topwin) { int tpmoved; struct rtgui_topwin *old_focus_topwin; struct rtgui_event_paint epaint; RT_ASSERT(topwin != RT_NULL); RTGUI_EVENT_PAINT_INIT(&epaint); if (!(topwin->flag & WINTITLE_SHOWN)) return -RT_ERROR; if (topwin->flag & WINTITLE_NOFOCUS) { /* just raise and show, no other effects. Active window is the one * which will receive kbd events. So a no-focus window can only be * "raised" but not "activated". */ tpmoved = _rtgui_topwin_raise_tree_from_root(topwin); rtgui_topwin_update_clip(); if (tpmoved) _rtgui_topwin_draw_tree(_rtgui_topwin_get_root_win(topwin), &epaint); else _rtgui_topwin_draw_tree(topwin, &epaint); return RT_EOK; } if (topwin->flag & WINTITLE_ACTIVATE) return RT_EOK; old_focus_topwin = rtgui_topwin_get_focus(); /* if topwin has the focus, it should have WINTITLE_ACTIVATE set and * returned above. */ RT_ASSERT(old_focus_topwin != topwin); tpmoved = _rtgui_topwin_raise_tree_from_root(topwin); /* clip before active the window, so we could get right boarder region. */ rtgui_topwin_update_clip(); if (old_focus_topwin != RT_NULL) { /* deactivate the old focus window firstly, otherwise it will make the new * window invisible. */ _rtgui_topwin_deactivate(old_focus_topwin); } _rtgui_topwin_only_activate(topwin); if (tpmoved) _rtgui_topwin_draw_tree(_rtgui_topwin_get_root_win(topwin), &epaint); else _rtgui_topwin_draw_tree(topwin, &epaint); return RT_EOK; } /* map func to the topwin tree in preorder. * * Remember that we are in a embedded system so write the @param func memory * efficiently. */ rt_inline void _rtgui_topwin_preorder_map(struct rtgui_topwin *topwin, void (*func)(struct rtgui_topwin *)) { struct rt_list_node *child; RT_ASSERT(topwin != RT_NULL); RT_ASSERT(func != RT_NULL); func(topwin); rt_list_foreach(child, &topwin->child_list, next) _rtgui_topwin_preorder_map(get_topwin_from_list(child), func); } rt_inline void _rtgui_topwin_mark_hidden(struct rtgui_topwin *topwin) { topwin->flag &= ~WINTITLE_SHOWN; RTGUI_WIDGET_HIDE(topwin->wid); } rt_inline void _rtgui_topwin_mark_shown(struct rtgui_topwin *topwin) { if (topwin->flag & WINTITLE_SHOWN) return; topwin->flag |= WINTITLE_SHOWN; if (RTGUI_WIDGET_IS_HIDE(topwin->wid)) { rtgui_widget_show(RTGUI_WIDGET(topwin->wid)); } } rt_err_t rtgui_topwin_show(struct rtgui_event_win *event) { struct rtgui_topwin *topwin; struct rtgui_win *wid = event->wid; topwin = rtgui_topwin_search_in_list(wid, &_rtgui_topwin_list); /* no such a window recorded */ if (topwin == RT_NULL) return -RT_ERROR; /* child windows could only be shown iif the parent is shown */ if (!_rtgui_topwin_could_show(topwin)) { return -RT_ERROR; } _rtgui_topwin_preorder_map(topwin, _rtgui_topwin_mark_shown); rtgui_topwin_activate_topwin(topwin); return RT_EOK; } static void _rtgui_topwin_clear_modal_tree(struct rtgui_topwin *topwin) { struct rt_list_node *node; RT_ASSERT(topwin != RT_NULL); RT_ASSERT(topwin->parent != RT_NULL); while (!IS_ROOT_WIN(topwin)) { rt_list_foreach(node, &topwin->parent->child_list, next) { get_topwin_from_list(node)->flag &= ~WINTITLE_MODALED; get_topwin_from_list(node)->wid->flag &= ~RTGUI_WIN_FLAG_UNDER_MODAL; if (get_topwin_from_list(node)->flag & WINTITLE_MODALING) { goto _out; } } topwin = topwin->parent; } _out: /* clear the modal flag of the root window */ topwin->flag &= ~WINTITLE_MODALED; topwin->wid->flag &= ~RTGUI_WIN_FLAG_UNDER_MODAL; } /* hide a window */ rt_err_t rtgui_topwin_hide(struct rtgui_event_win *event) { struct rtgui_topwin *topwin; struct rtgui_topwin *old_focus_topwin; struct rtgui_win *wid; struct rt_list_node *containing_list; if (!event) return -RT_ERROR; wid = event->wid; /* find in show list */ topwin = rtgui_topwin_search_in_list(wid, &_rtgui_topwin_list); if (topwin == RT_NULL) { return -RT_ERROR; } if (!(topwin->flag & WINTITLE_SHOWN)) { return RT_EOK; } old_focus_topwin = rtgui_topwin_get_focus(); _rtgui_topwin_preorder_map(topwin, _rtgui_topwin_mark_hidden); if (topwin->parent == RT_NULL) containing_list = &_rtgui_topwin_list; else containing_list = &topwin->parent->child_list; rt_list_remove(&topwin->list); rt_list_insert_before(containing_list, &topwin->list); /* update clip info */ rtgui_topwin_update_clip(); if (topwin->flag & WINTITLE_MODALING) { topwin->flag &= ~WINTITLE_MODALING; _rtgui_topwin_clear_modal_tree(topwin); } if (old_focus_topwin == topwin) { _rtgui_topwin_activate_next(topwin->flag); } topwin->flag &= ~WINTITLE_ACTIVATE; /* redraw the old rect */ rtgui_topwin_redraw(&(topwin->extent)); return RT_EOK; } /* move top window */ rt_err_t rtgui_topwin_move(struct rtgui_event_win_move *event) { struct rtgui_topwin *topwin; int dx, dy; rtgui_rect_t old_rect; /* the old topwin coverage area */ struct rtgui_list_node *node; /* find in show list */ topwin = rtgui_topwin_search_in_list(event->wid, &_rtgui_topwin_list); if (topwin == RT_NULL || !(topwin->flag & WINTITLE_SHOWN)) { return -RT_ERROR; } /* get the delta move x, y */ dx = event->x - topwin->extent.x1; dy = event->y - topwin->extent.y1; old_rect = topwin->extent; /* move window rect */ rtgui_rect_moveto(&(topwin->extent), dx, dy); /* move the monitor rect list */ rtgui_list_foreach(node, &(topwin->monitor_list)) { struct rtgui_mouse_monitor *monitor = rtgui_list_entry(node, struct rtgui_mouse_monitor, list); rtgui_rect_moveto(&(monitor->rect), dx, dy); } /* update windows clip info */ rtgui_topwin_update_clip(); /* update old window coverage area */ rtgui_topwin_redraw(&old_rect); if (rtgui_rect_is_intersect(&old_rect, &(topwin->extent)) != RT_EOK) { /* * the old rect is not intersect with moved rect, * re-paint window */ struct rtgui_event_paint epaint; RTGUI_EVENT_PAINT_INIT(&epaint); epaint.wid = topwin->wid; rtgui_send(topwin->app, &(epaint.parent), sizeof(epaint)); } return RT_EOK; } /* * resize a top win * Note: currently, only support resize hidden window */ void rtgui_topwin_resize(struct rtgui_win *wid, rtgui_rect_t *rect) { struct rtgui_topwin *topwin; struct rtgui_region region; /* find in show list */ topwin = rtgui_topwin_search_in_list(wid, &_rtgui_topwin_list); if (topwin == RT_NULL || !(topwin->flag & WINTITLE_SHOWN)) return; /* record the old rect */ rtgui_region_init_with_extents(&region, &topwin->extent); /* union the new rect so this is the region we should redraw */ rtgui_region_union_rect(&region, &region, rect); topwin->extent = *rect; /* update windows clip info */ rtgui_topwin_update_clip(); /* update old window coverage area */ rtgui_topwin_redraw(rtgui_region_extents(&region)); rtgui_region_fini(&region); } static struct rtgui_topwin *_rtgui_topwin_get_focus_from_list(struct rt_list_node *list) { struct rt_list_node *node; RT_ASSERT(list != RT_NULL); rt_list_foreach(node, list, next) { struct rtgui_topwin *child = get_topwin_from_list(node); if (child->flag & WINTITLE_ACTIVATE) return child; child = _rtgui_topwin_get_focus_from_list(&child->child_list); if (child != RT_NULL) return child; } return RT_NULL; } struct rtgui_topwin *rtgui_topwin_get_focus(void) { return _rtgui_topwin_get_focus_from_list(&_rtgui_topwin_list); } static struct rtgui_topwin *_rtgui_topwin_get_wnd_from_tree(struct rt_list_node *list, int x, int y, rt_bool_t exclude_modaled) { struct rt_list_node *node; struct rtgui_topwin *topwin, *target; RT_ASSERT(list != RT_NULL); rt_list_foreach(node, list, next) { topwin = get_topwin_from_list(node); if (!(topwin->flag & WINTITLE_SHOWN)) break; /* if higher window have this point, return it */ target = _rtgui_topwin_get_wnd_from_tree(&topwin->child_list, x, y, exclude_modaled); if (target != RT_NULL) return target; if (exclude_modaled && (topwin->flag & WINTITLE_MODALED)) break; if (rtgui_rect_contains_point(&(topwin->extent), x, y) == RT_EOK) { return topwin; } } return RT_NULL; } struct rtgui_topwin *rtgui_topwin_get_wnd(int x, int y) { return _rtgui_topwin_get_wnd_from_tree(&_rtgui_topwin_list, x, y, RT_FALSE); } struct rtgui_topwin *rtgui_topwin_get_wnd_no_modaled(int x, int y) { return _rtgui_topwin_get_wnd_from_tree(&_rtgui_topwin_list, x, y, RT_TRUE); } /* clip region from topwin, and the windows beneath it. */ rt_inline void _rtgui_topwin_clip_to_region(struct rtgui_topwin *topwin, struct rtgui_region *region) { RT_ASSERT(region != RT_NULL); RT_ASSERT(topwin != RT_NULL); rtgui_region_reset(&topwin->wid->outer_clip, &topwin->wid->outer_extent); rtgui_region_intersect(&topwin->wid->outer_clip, &topwin->wid->outer_clip, region); } static void rtgui_topwin_update_clip(void) { struct rtgui_topwin *top; struct rtgui_event_clip_info eclip; /* Note that the region is a "female die", that means it's the region you * can paint to, not the region covered by others. */ struct rtgui_region region_available; if (rt_list_isempty(&_rtgui_topwin_list) || !(get_topwin_from_list(_rtgui_topwin_list.next)->flag & WINTITLE_SHOWN)) return; RTGUI_EVENT_CLIP_INFO_INIT(&eclip); rtgui_region_init_rect(&region_available, 0, 0, rtgui_graphic_driver_get_default()->width, rtgui_graphic_driver_get_default()->height); /* from top to bottom. */ top = rtgui_topwin_get_topmost_window_shown(WINTITLE_ONTOP); /* 0 is normal layer */ if (top == RT_NULL) top = rtgui_topwin_get_topmost_window_shown(WINTITLE_INIT); if (top == RT_NULL) top = rtgui_topwin_get_topmost_window_shown(WINTITLE_ONBTM); while (top != RT_NULL) { /* clip the topwin */ _rtgui_topwin_clip_to_region(top, &region_available); /* update available region */ rtgui_region_subtract_rect(&region_available, &region_available, &top->extent); /* send clip event to destination window */ eclip.wid = top->wid; rtgui_send(top->app, &(eclip.parent), sizeof(struct rtgui_event_clip_info)); top = _rtgui_topwin_get_next_shown(top); } rtgui_region_fini(&region_available); } static void _rtgui_topwin_redraw_tree(struct rt_list_node *list, struct rtgui_rect *rect, struct rtgui_event_paint *epaint) { struct rt_list_node *node; RT_ASSERT(list != RT_NULL); RT_ASSERT(rect != RT_NULL); RT_ASSERT(epaint != RT_NULL); /* skip the hidden windows */ rt_list_foreach(node, list, prev) { if (get_topwin_from_list(node)->flag & WINTITLE_SHOWN) break; } for (; node != list; node = node->prev) { struct rtgui_topwin *topwin; topwin = get_topwin_from_list(node); //FIXME: intersect with clip? if (rtgui_rect_is_intersect(rect, &(topwin->extent)) == RT_EOK) { epaint->wid = topwin->wid; rtgui_send(topwin->app, &(epaint->parent), sizeof(*epaint)); } _rtgui_topwin_redraw_tree(&topwin->child_list, rect, epaint); } } static void rtgui_topwin_redraw(struct rtgui_rect *rect) { struct rtgui_event_paint epaint; RTGUI_EVENT_PAINT_INIT(&epaint); epaint.wid = RT_NULL; _rtgui_topwin_redraw_tree(&_rtgui_topwin_list, rect, &epaint); } /* a window enter modal mode will modal all the sibling window and parent * window all along to the root window. If a root window modals, there is * nothing to do here.*/ rt_err_t rtgui_topwin_modal_enter(struct rtgui_event_win_modal_enter *event) { struct rtgui_topwin *topwin, *parent_top; struct rt_list_node *node; topwin = rtgui_topwin_search_in_list(event->wid, &_rtgui_topwin_list); if (topwin == RT_NULL) return -RT_ERROR; if (IS_ROOT_WIN(topwin)) return RT_EOK; parent_top = topwin->parent; /* modal window should be on top already */ RT_ASSERT(get_topwin_from_list(parent_top->child_list.next) == topwin); do { rt_list_foreach(node, &parent_top->child_list, next) { get_topwin_from_list(node)->flag |= WINTITLE_MODALED; get_topwin_from_list(node)->wid->flag |= RTGUI_WIN_FLAG_UNDER_MODAL; } parent_top->flag |= WINTITLE_MODALED; parent_top->wid->flag |= RTGUI_WIN_FLAG_UNDER_MODAL; parent_top = parent_top->parent; } while (parent_top); topwin->flag &= ~WINTITLE_MODALED; topwin->wid->flag &= ~RTGUI_WIN_FLAG_UNDER_MODAL; topwin->flag |= WINTITLE_MODALING; return RT_EOK; } void rtgui_topwin_append_monitor_rect(struct rtgui_win *wid, rtgui_rect_t *rect) { struct rtgui_topwin *win; /* parameters check */ if (wid == RT_NULL || rect == RT_NULL) return; /* find topwin */ win = rtgui_topwin_search_in_list(wid, &_rtgui_topwin_list); if (win == RT_NULL) return; /* append rect to top window monitor rect list */ rtgui_mouse_monitor_append(&(win->monitor_list), rect); } void rtgui_topwin_remove_monitor_rect(struct rtgui_win *wid, rtgui_rect_t *rect) { struct rtgui_topwin *win; /* parameters check */ if (wid == RT_NULL || rect == RT_NULL) return; /* find topwin */ win = rtgui_topwin_search_in_list(wid, &_rtgui_topwin_list); if (win == RT_NULL) return; /* remove rect from top window monitor rect list */ rtgui_mouse_monitor_remove(&(win->monitor_list), rect); } static struct rtgui_object* _get_obj_in_topwin(struct rtgui_topwin *topwin, struct rtgui_app *app, rt_uint32_t id) { struct rtgui_object *object; struct rt_list_node *node; object = RTGUI_OBJECT(topwin->wid); if (object->id == id) return object; object = rtgui_container_get_object(RTGUI_CONTAINER(object), id); if (object) return object; rt_list_foreach(node, &topwin->child_list, next) { struct rtgui_topwin *topwin; topwin = get_topwin_from_list(node); if (topwin->app != app) continue; object = _get_obj_in_topwin(topwin, app, id); if (object) return object; } return RT_NULL; } struct rtgui_object* rtgui_get_object(struct rtgui_app *app, rt_uint32_t id) { struct rtgui_object *object; struct rt_list_node *node; object = RTGUI_OBJECT(app); if (object->id == id) return object; rt_list_foreach(node, &_rtgui_topwin_list, next) { struct rtgui_topwin *topwin; topwin = get_topwin_from_list(node); if (topwin->app != app) continue; object = _get_obj_in_topwin(topwin, app, id); if (object) return object; } return RT_NULL; } RTM_EXPORT(rtgui_get_object); struct rtgui_object* rtgui_get_self_object(rt_uint32_t id) { return rtgui_get_object(rtgui_app_self(), id); } RTM_EXPORT(rtgui_get_self_object); static void _rtgui_topwin_dump(struct rtgui_topwin *topwin) { rt_kprintf("0x%p:%s,0x%x,%c%c", topwin, topwin->wid->title, topwin->flag, topwin->flag & WINTITLE_SHOWN ? 'S' : 'H', topwin->flag & WINTITLE_MODALED ? 'm' : topwin->flag & WINTITLE_MODALING ? 'M' : ' '); } static void _rtgui_topwin_dump_tree(struct rtgui_topwin *topwin) { struct rt_list_node *node; _rtgui_topwin_dump(topwin); rt_kprintf("("); rt_list_foreach(node, &topwin->child_list, next) { _rtgui_topwin_dump_tree(get_topwin_from_list(node)); } rt_kprintf(")"); } void rtgui_topwin_dump_tree(void) { struct rt_list_node *node; rt_list_foreach(node, &_rtgui_topwin_list, next) { _rtgui_topwin_dump_tree(get_topwin_from_list(node)); rt_kprintf("\n"); } } #ifdef RT_USING_FINSH #include <finsh.h> void dump_tree() { rtgui_topwin_dump_tree(); } FINSH_FUNCTION_EXPORT(dump_tree, dump rtgui topwin tree) #endif
fea28639b2e889a9473a503feb54bb8b57524ffc
5816ae8b5fdfe9ab93b3653742b5d4c2a1567111
/hitcon-2018/abyss/src/kernel/syscalls/sys_open.c
1ee5f52fc5550bf4b642c85bf43df894f3467e46
[]
no_license
david942j/ctf-writeups
6c2ff633d80809e422f0263b8ac9a69607d31e84
a4d086684a939000286d0876dd29463ccdceea2e
refs/heads/master
2022-09-07T00:27:23.594820
2021-12-14T10:50:47
2021-12-14T10:50:47
77,058,219
316
49
null
null
null
null
UTF-8
C
false
false
1,245
c
sys_open.c
#include <hypercalls/hp_access.h> #include <hypercalls/hp_open.h> #include <mm/kmalloc.h> #include <mm/translate.h> #include <mm/uaccess.h> #include <syscalls/sys_open.h> #include <utils/errno.h> #include <utils/string.h> int sys_open(const char *path) { if(!access_string_ok(path)) return -EFAULT; void *dst = copy_str_from_user(path); if(dst == 0) return -ENOMEM; /* do whitelist here */ if(!( #define OK(str) strcmp(dst, #str) == 0 OK(ld.so.2) || /* OK(/lib64/ld-linux-x86-64.so.2) || */ /* OK(libc.so.6) || */ /* OK(./bc.so.6) || */ OK(/lib/x86_64-linux-gnu/libc.so.6) || OK(/proc/sys/kernel/osrelease) || OK(/etc/ld.so.cache) || OK(./user.elf) || /* OK(/bin/cat) || */ OK(flag) #undef OK )) return -ENOENT; int fd = hp_open(physical(dst)); kfree(dst); return fd; } int sys_openat(int fildes, const char *path) { /* only supports fd == AT_FDCWD */ if(fildes != AT_FDCWD) return -EINVAL; return sys_open(path); } int sys_access(const char *path, int mode) { if(!access_string_ok(path)) return -EFAULT; void *dst = copy_str_from_user(path); if(dst == 0) return -ENOMEM; int ret = hp_access(physical(dst), mode); kfree(dst); return ret; }
d36822a5589659fafeb6ca1b8f8d6f9e76df0cff
55540f3e86f1d5d86ef6b5d295a63518e274efe3
/components/utils/include/utils_ringblk.h
91526bccf17a7f556920cda5a2c2f7fb4a7c173e
[ "Apache-2.0" ]
permissive
bouffalolab/bl_iot_sdk
bc5eaf036b70f8c65dd389439062b169f8d09daa
b90664de0bd4c1897a9f1f5d9e360a9631d38b34
refs/heads/master
2023-08-31T03:38:03.369853
2023-08-16T08:50:33
2023-08-18T09:13:27
307,347,250
244
101
Apache-2.0
2023-08-28T06:29:02
2020-10-26T11:16:30
C
UTF-8
C
false
false
4,636
h
utils_ringblk.h
/* * Copyright (c) 2016-2022 Bouffalolab. * * This file is part of * *** Bouffalolab Software Dev Kit *** * (see www.bouffalolab.com). * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of Bouffalo Lab 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 _UTILS_RINGBLK_H_ #define _UTILS_RINGBLK_H_ #include "stddef.h" #include <stdint.h> #include "utils_list.h" #define UTILS_RINGBLK_TEST /* * Introduction: * The rbb is the ring buffer which is composed with many blocks. It is different from the ring buffer. * The ring buffer is only composed with chars. The rbb put and get supported zero copies. So the rbb * is very suitable for put block and get block by a certain order. Such as DMA block transmit, * communicate frame send/recv, and so on. */ #ifdef __cplusplus extern "C" { #endif enum utils_rbb_status { /* unused status when first initialize or after blk_free() */ RBB_BLK_UNUSED, /* initialized status after blk_alloc() */ RBB_BLK_INITED, /* put status after blk_put() */ RBB_BLK_PUT, /* get status after blk_get() */ RBB_BLK_GET, }; typedef enum utils_rbb_status utils_rbb_status_t; /** * the block of rbb */ struct utils_rbb_blk { utils_rbb_status_t status :8; /* less then 2^24 */ uint32_t size :24; uint8_t *buf; utils_slist_t list; }; typedef struct utils_rbb_blk *utils_rbb_blk_t; /** * Rbb block queue: the blocks (from block1->buf to blockn->buf) memory which on this queue is continuous. */ struct utils_rbb_blk_queue { utils_rbb_blk_t blocks; uint32_t blk_num; }; typedef struct utils_rbb_blk_queue *utils_rbb_blk_queue_t; /** * ring block buffer */ struct utils_rbb { uint8_t *buf; uint32_t buf_size; /* all of blocks */ utils_rbb_blk_t blk_set; uint32_t blk_max_num; /* saved the initialized and put status blocks */ utils_slist_t blk_list; }; typedef struct utils_rbb *utils_rbb_t; /* rbb (ring block buffer) API */ void utils_rbb_init(utils_rbb_t rbb, uint8_t *buf, uint32_t buf_size, utils_rbb_blk_t block_set, uint32_t blk_max_num); uint32_t utils_rbb_get_buf_size(utils_rbb_t rbb); utils_rbb_t utils_rbb_create(uint32_t buf_size, uint32_t blk_max_num); void utils_rbb_destroy(utils_rbb_t rbb); /* rbb block API */ utils_rbb_blk_t utils_rbb_blk_alloc(utils_rbb_t rbb, uint32_t blk_size); void utils_rbb_blk_put(utils_rbb_blk_t block); utils_rbb_blk_t utils_rbb_blk_get(utils_rbb_t rbb); uint32_t utils_rbb_blk_size(utils_rbb_blk_t block); uint8_t *utils_rbb_blk_buf(utils_rbb_blk_t block); void utils_rbb_blk_free(utils_rbb_t rbb, utils_rbb_blk_t block); utils_rbb_blk_t utils_rbb_find_empty_blk(utils_rbb_t rbb); utils_rbb_blk_t utils_rbb_find_used_blk(utils_rbb_t rbb); /* rbb block queue API */ uint32_t utils_rbb_blk_queue_get(utils_rbb_t rbb, uint32_t queue_data_len, utils_rbb_blk_queue_t blk_queue); uint32_t utils_rbb_blk_queue_len(utils_rbb_blk_queue_t blk_queue); uint8_t *utils_rbb_blk_queue_buf(utils_rbb_blk_queue_t blk_queue); void utils_rbb_blk_queue_free(utils_rbb_t rbb, utils_rbb_blk_queue_t blk_queue); uint32_t utils_rbb_next_blk_queue_len(utils_rbb_t rbb); int utils_rbb_cli_init(void); #ifdef __cplusplus } #endif #endif /* _UTILS_RINGBLK_H_ */
2eaad42512cb45c9acd8dfe31badf6a10a4308f4
f7a2aa9d933466c25177a1abe06cc25a0650d9dd
/client/libraries/audio/bass_fx.h
9c8c26c1ab68a311845080d6ba33fe0ab9899b38
[ "MIT" ]
permissive
CyberMor/sampvoice
b6f055dc32c975faef95a1eca31e60e6ea0120b2
11988682bf46a6ebdff8eab2810385610f221a21
refs/heads/master
2023-07-26T15:16:11.941105
2023-07-18T11:17:21
2023-07-18T11:17:21
165,523,561
139
105
MIT
2023-07-16T06:59:55
2019-01-13T15:47:46
C++
UTF-8
C
false
false
19,448
h
bass_fx.h
/*=========================================================================== BASS_FX 2.4 - Copyright (c) 2002-2018 (: JOBnik! :) [Arthur Aminov, ISRAEL] [http://www.jobnik.org] bugs/suggestions/questions: forum : http://www.un4seen.com/forum/?board=1 http://www.jobnik.org/forums e-mail : bass_fx@jobnik.org -------------------------------------------------- NOTE: This header will work only with BASS_FX version 2.4.12 Check www.un4seen.com or www.jobnik.org for any later versions. * Requires BASS 2.4 (available at http://www.un4seen.com) ===========================================================================*/ #ifndef BASS_FX_H #define BASS_FX_H #ifdef __cplusplus extern "C" { #endif #ifndef BASS_FXDEF #define BASS_FXDEF(f) WINAPI f #endif // BASS_CHANNELINFO types #define BASS_CTYPE_STREAM_TEMPO 0x1f200 #define BASS_CTYPE_STREAM_REVERSE 0x1f201 // Tempo / Reverse / BPM / Beat flag #define BASS_FX_FREESOURCE 0x10000 // Free the source handle as well? // BASS_FX Version DWORD BASS_FXDEF(BASS_FX_GetVersion)(); /*=========================================================================== DSP (Digital Signal Processing) ===========================================================================*/ /* Multi-channel order of each channel is as follows: 3 channels left-front, right-front, center. 4 channels left-front, right-front, left-rear/side, right-rear/side. 5 channels left-front, right-front, center, left-rear/side, right-rear/side. 6 channels (5.1) left-front, right-front, center, LFE, left-rear/side, right-rear/side. 8 channels (7.1) left-front, right-front, center, LFE, left-rear/side, right-rear/side, left-rear center, right-rear center. */ // DSP channels flags #define BASS_BFX_CHANALL -1 // all channels at once (as by default) #define BASS_BFX_CHANNONE 0 // disable an effect for all channels #define BASS_BFX_CHAN1 1 // left-front channel #define BASS_BFX_CHAN2 2 // right-front channel #define BASS_BFX_CHAN3 4 // see above info #define BASS_BFX_CHAN4 8 // see above info #define BASS_BFX_CHAN5 16 // see above info #define BASS_BFX_CHAN6 32 // see above info #define BASS_BFX_CHAN7 64 // see above info #define BASS_BFX_CHAN8 128 // see above info // if you have more than 8 channels (7.1), use this macro #define BASS_BFX_CHANNEL_N(n) (1<<((n)-1)) // DSP effects enum { BASS_FX_BFX_ROTATE = 0x10000, // A channels volume ping-pong / multi channel BASS_FX_BFX_ECHO, // Echo / 2 channels max (deprecated) BASS_FX_BFX_FLANGER, // Flanger / multi channel (deprecated) BASS_FX_BFX_VOLUME, // Volume / multi channel BASS_FX_BFX_PEAKEQ, // Peaking Equalizer / multi channel BASS_FX_BFX_REVERB, // Reverb / 2 channels max (deprecated) BASS_FX_BFX_LPF, // Low Pass Filter 24dB / multi channel (deprecated) BASS_FX_BFX_MIX, // Swap, remap and mix channels / multi channel BASS_FX_BFX_DAMP, // Dynamic Amplification / multi channel BASS_FX_BFX_AUTOWAH, // Auto Wah / multi channel BASS_FX_BFX_ECHO2, // Echo 2 / multi channel (deprecated) BASS_FX_BFX_PHASER, // Phaser / multi channel BASS_FX_BFX_ECHO3, // Echo 3 / multi channel (deprecated) BASS_FX_BFX_CHORUS, // Chorus/Flanger / multi channel BASS_FX_BFX_APF, // All Pass Filter / multi channel (deprecated) BASS_FX_BFX_COMPRESSOR, // Compressor / multi channel (deprecated) BASS_FX_BFX_DISTORTION, // Distortion / multi channel BASS_FX_BFX_COMPRESSOR2, // Compressor 2 / multi channel BASS_FX_BFX_VOLUME_ENV, // Volume envelope / multi channel BASS_FX_BFX_BQF, // BiQuad filters / multi channel BASS_FX_BFX_ECHO4, // Echo 4 / multi channel BASS_FX_BFX_PITCHSHIFT, // Pitch shift using FFT / multi channel (not available on mobile) BASS_FX_BFX_FREEVERB // Reverb using "Freeverb" algo / multi channel }; /* Deprecated effects in 2.4.10 version: ------------------------------------ BASS_FX_BFX_ECHO -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_ECHO2 -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_ECHO3 -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_REVERB -> use BASS_FX_BFX_FREEVERB BASS_FX_BFX_FLANGER -> use BASS_FX_BFX_CHORUS BASS_FX_BFX_COMPRESSOR -> use BASS_FX_BFX_COMPRESSOR2 BASS_FX_BFX_APF -> use BASS_FX_BFX_BQF with BASS_BFX_BQF_ALLPASS filter BASS_FX_BFX_LPF -> use 2x BASS_FX_BFX_BQF with BASS_BFX_BQF_LOWPASS filter and appropriate fQ values */ // Rotate typedef struct { float fRate; // rotation rate/speed in Hz (A negative rate can be used for reverse direction) int lChannel; // BASS_BFX_CHANxxx flag/s (supported only even number of channels) } BASS_BFX_ROTATE; // Echo (deprecated) typedef struct { float fLevel; // [0....1....n] linear int lDelay; // [1200..30000] } BASS_BFX_ECHO; // Flanger (deprecated) typedef struct { float fWetDry; // [0....1....n] linear float fSpeed; // [0......0.09] int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_FLANGER; // Volume typedef struct { int lChannel; // BASS_BFX_CHANxxx flag/s or 0 for global volume control float fVolume; // [0....1....n] linear } BASS_BFX_VOLUME; // Peaking Equalizer typedef struct { int lBand; // [0...............n] more bands means more memory & cpu usage float fBandwidth; // [0.1...........<10] in octaves - fQ is not in use (Bandwidth has a priority over fQ) float fQ; // [0...............1] the EE kinda definition (linear) (if Bandwidth is not in use) float fCenter; // [1Hz..<info.freq/2] in Hz float fGain; // [-15dB...0...+15dB] in dB (can be above/below these limits) int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_PEAKEQ; // Reverb (deprecated) typedef struct { float fLevel; // [0....1....n] linear int lDelay; // [1200..10000] } BASS_BFX_REVERB; // Low Pass Filter (deprecated) typedef struct { float fResonance; // [0.01...........10] float fCutOffFreq; // [1Hz...info.freq/2] cutoff frequency int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_LPF; // Swap, remap and mix typedef struct { const int *lChannel; // an array of channels to mix using BASS_BFX_CHANxxx flag/s (lChannel[0] is left channel...) } BASS_BFX_MIX; // Dynamic Amplification typedef struct { float fTarget; // target volume level [0<......1] linear float fQuiet; // quiet volume level [0.......1] linear float fRate; // amp adjustment rate [0.......1] linear float fGain; // amplification level [0...1...n] linear float fDelay; // delay in seconds before increasing level [0.......n] linear int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_DAMP; // Auto Wah typedef struct { float fDryMix; // dry (unaffected) signal mix [-2......2] float fWetMix; // wet (affected) signal mix [-2......2] float fFeedback; // output signal to feed back into input [-1......1] float fRate; // rate of sweep in cycles per second [0<....<10] float fRange; // sweep range in octaves [0<....<10] float fFreq; // base frequency of sweep Hz [0<...1000] int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_AUTOWAH; // Echo 2 (deprecated) typedef struct { float fDryMix; // dry (unaffected) signal mix [-2......2] float fWetMix; // wet (affected) signal mix [-2......2] float fFeedback; // output signal to feed back into input [-1......1] float fDelay; // delay sec [0<......n] int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_ECHO2; // Phaser typedef struct { float fDryMix; // dry (unaffected) signal mix [-2......2] float fWetMix; // wet (affected) signal mix [-2......2] float fFeedback; // output signal to feed back into input [-1......1] float fRate; // rate of sweep in cycles per second [0<....<10] float fRange; // sweep range in octaves [0<....<10] float fFreq; // base frequency of sweep [0<...1000] int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_PHASER; // Echo 3 (deprecated) typedef struct { float fDryMix; // dry (unaffected) signal mix [-2......2] float fWetMix; // wet (affected) signal mix [-2......2] float fDelay; // delay sec [0<......n] int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_ECHO3; // Chorus/Flanger typedef struct { float fDryMix; // dry (unaffected) signal mix [-2......2] float fWetMix; // wet (affected) signal mix [-2......2] float fFeedback; // output signal to feed back into input [-1......1] float fMinSweep; // minimal delay ms [0<...6000] float fMaxSweep; // maximum delay ms [0<...6000] float fRate; // rate ms/s [0<...1000] int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_CHORUS; // All Pass Filter (deprecated) typedef struct { float fGain; // reverberation time [-1=<..<=1] float fDelay; // delay sec [0<....<=n] int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_APF; // Compressor (deprecated) typedef struct { float fThreshold; // compressor threshold [0<=...<=1] float fAttacktime; // attack time ms [0<.<=1000] float fReleasetime; // release time ms [0<.<=5000] int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_COMPRESSOR; // Distortion typedef struct { float fDrive; // distortion drive [0<=...<=5] float fDryMix; // dry (unaffected) signal mix [-5<=..<=5] float fWetMix; // wet (affected) signal mix [-5<=..<=5] float fFeedback; // output signal to feed back into input [-1<=..<=1] float fVolume; // distortion volume [0=<...<=2] int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_DISTORTION; // Compressor 2 typedef struct { float fGain; // output gain of signal after compression [-60....60] in dB float fThreshold; // point at which compression begins [-60.....0] in dB float fRatio; // compression ratio [1.......n] float fAttack; // attack time in ms [0.01.1000] float fRelease; // release time in ms [0.01.5000] int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_COMPRESSOR2; // Volume envelope typedef struct { int lChannel; // BASS_BFX_CHANxxx flag/s int lNodeCount; // number of nodes const struct BASS_BFX_ENV_NODE *pNodes; // the nodes BOOL bFollow; // follow source position } BASS_BFX_VOLUME_ENV; #pragma pack(push,4) typedef struct BASS_BFX_ENV_NODE { double pos; // node position in seconds (1st envelope node must be at position 0) float val; // node value } BASS_BFX_ENV_NODE; #pragma pack(pop) // BiQuad Filters enum { BASS_BFX_BQF_LOWPASS, BASS_BFX_BQF_HIGHPASS, BASS_BFX_BQF_BANDPASS, // constant 0 dB peak gain BASS_BFX_BQF_BANDPASS_Q, // constant skirt gain, peak gain = Q BASS_BFX_BQF_NOTCH, BASS_BFX_BQF_ALLPASS, BASS_BFX_BQF_PEAKINGEQ, BASS_BFX_BQF_LOWSHELF, BASS_BFX_BQF_HIGHSHELF }; typedef struct { int lFilter; // BASS_BFX_BQF_xxx filter types float fCenter; // [1Hz..<info.freq/2] Cutoff (central) frequency in Hz float fGain; // [-15dB...0...+15dB] Used only for PEAKINGEQ and Shelving filters in dB (can be above/below these limits) float fBandwidth; // [0.1...........<10] Bandwidth in octaves (fQ is not in use (fBandwidth has a priority over fQ)) // (between -3 dB frequencies for BANDPASS and NOTCH or between midpoint // (fGgain/2) gain frequencies for PEAKINGEQ) float fQ; // [0.1.............1] The EE kinda definition (linear) (if fBandwidth is not in use) float fS; // [0.1.............1] A "shelf slope" parameter (linear) (used only with Shelving filters) // when fS = 1, the shelf slope is as steep as you can get it and remain monotonically // increasing or decreasing gain with frequency. int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_BQF; // Echo 4 typedef struct { float fDryMix; // dry (unaffected) signal mix [-2.......2] float fWetMix; // wet (affected) signal mix [-2.......2] float fFeedback; // output signal to feed back into input [-1.......1] float fDelay; // delay sec [0<.......n] BOOL bStereo; // echo adjoining channels to each other [TRUE/FALSE] int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_ECHO4; // Pitch shift (not available on mobile) typedef struct { float fPitchShift; // A factor value which is between 0.5 (one octave down) and 2 (one octave up) (1 won't change the pitch) [1 default] // (fSemitones is not in use, fPitchShift has a priority over fSemitones) float fSemitones; // Semitones (0 won't change the pitch) [0 default] long lFFTsize; // Defines the FFT frame size used for the processing. Typical values are 1024, 2048 and 4096 [2048 default] // It may be any value <= 8192 but it MUST be a power of 2 long lOsamp; // Is the STFT oversampling factor which also determines the overlap between adjacent STFT frames [8 default] // It should at least be 4 for moderate scaling ratios. A value of 32 is recommended for best quality (better quality = higher CPU usage) int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_PITCHSHIFT; // Freeverb #define BASS_BFX_FREEVERB_MODE_FREEZE 1 typedef struct { float fDryMix; // dry (unaffected) signal mix [0........1], def. 0 float fWetMix; // wet (affected) signal mix [0........3], def. 1.0f float fRoomSize; // room size [0........1], def. 0.5f float fDamp; // damping [0........1], def. 0.5f float fWidth; // stereo width [0........1], def. 1 DWORD lMode; // 0 or BASS_BFX_FREEVERB_MODE_FREEZE, def. 0 (no freeze) int lChannel; // BASS_BFX_CHANxxx flag/s } BASS_BFX_FREEVERB; /*=========================================================================== set dsp fx - BASS_ChannelSetFX remove dsp fx - BASS_ChannelRemoveFX set parameters - BASS_FXSetParameters retrieve parameters - BASS_FXGetParameters reset the state - BASS_FXReset ===========================================================================*/ /*=========================================================================== Tempo, Pitch scaling and Sample rate changers ===========================================================================*/ // NOTE: Enable Tempo supported flags in BASS_FX_TempoCreate and the others to source handle. // tempo attributes (BASS_ChannelSet/GetAttribute) enum { BASS_ATTRIB_TEMPO = 0x10000, BASS_ATTRIB_TEMPO_PITCH, BASS_ATTRIB_TEMPO_FREQ }; // tempo attributes options enum { BASS_ATTRIB_TEMPO_OPTION_USE_AA_FILTER = 0x10010, // TRUE (default) / FALSE (default for multi-channel on mobile devices for lower CPU usage) BASS_ATTRIB_TEMPO_OPTION_AA_FILTER_LENGTH, // 32 default (8 .. 128 taps) BASS_ATTRIB_TEMPO_OPTION_USE_QUICKALGO, // TRUE (default on mobile devices for lower CPU usage) / FALSE (default) BASS_ATTRIB_TEMPO_OPTION_SEQUENCE_MS, // 82 default, 0 = automatic BASS_ATTRIB_TEMPO_OPTION_SEEKWINDOW_MS, // 28 default, 0 = automatic BASS_ATTRIB_TEMPO_OPTION_OVERLAP_MS, // 8 default BASS_ATTRIB_TEMPO_OPTION_PREVENT_CLICK // TRUE / FALSE (default) }; // tempo algorithm flags #define BASS_FX_TEMPO_ALGO_LINEAR 0x200 #define BASS_FX_TEMPO_ALGO_CUBIC 0x400 // default #define BASS_FX_TEMPO_ALGO_SHANNON 0x800 HSTREAM BASS_FXDEF(BASS_FX_TempoCreate)(DWORD chan, DWORD flags); DWORD BASS_FXDEF(BASS_FX_TempoGetSource)(HSTREAM chan); float BASS_FXDEF(BASS_FX_TempoGetRateRatio)(HSTREAM chan); /*=========================================================================== Reverse playback ===========================================================================*/ // NOTES: 1. MODs won't load without BASS_MUSIC_PRESCAN flag. // 2. Enable Reverse supported flags in BASS_FX_ReverseCreate and the others to source handle. // reverse attribute (BASS_ChannelSet/GetAttribute) #define BASS_ATTRIB_REVERSE_DIR 0x11000 // playback directions #define BASS_FX_RVS_REVERSE -1 #define BASS_FX_RVS_FORWARD 1 HSTREAM BASS_FXDEF(BASS_FX_ReverseCreate)(DWORD chan, float dec_block, DWORD flags); DWORD BASS_FXDEF(BASS_FX_ReverseGetSource)(HSTREAM chan); /*=========================================================================== BPM (Beats Per Minute) ===========================================================================*/ // bpm flags #define BASS_FX_BPM_BKGRND 1 // if in use, then you can do other processing while detection's in progress. Available only in Windows platforms (BPM/Beat) #define BASS_FX_BPM_MULT2 2 // if in use, then will auto multiply bpm by 2 (if BPM < minBPM*2) // translation options (deprecated) enum { BASS_FX_BPM_TRAN_X2, // multiply the original BPM value by 2 (may be called only once & will change the original BPM as well!) BASS_FX_BPM_TRAN_2FREQ, // BPM value to Frequency BASS_FX_BPM_TRAN_FREQ2, // Frequency to BPM value BASS_FX_BPM_TRAN_2PERCENT, // BPM value to Percents BASS_FX_BPM_TRAN_PERCENT2 // Percents to BPM value }; typedef void (CALLBACK BPMPROC)(DWORD chan, float bpm, void *user); typedef void (CALLBACK BPMPROGRESSPROC)(DWORD chan, float percent, void *user); typedef BPMPROGRESSPROC BPMPROCESSPROC; // back-compatibility float BASS_FXDEF(BASS_FX_BPM_DecodeGet)(DWORD chan, double startSec, double endSec, DWORD minMaxBPM, DWORD flags, BPMPROGRESSPROC *proc, void *user); BOOL BASS_FXDEF(BASS_FX_BPM_CallbackSet)(DWORD handle, BPMPROC *proc, double period, DWORD minMaxBPM, DWORD flags, void *user); BOOL BASS_FXDEF(BASS_FX_BPM_CallbackReset)(DWORD handle); float BASS_FXDEF(BASS_FX_BPM_Translate)(DWORD handle, float val2tran, DWORD trans); // deprecated BOOL BASS_FXDEF(BASS_FX_BPM_Free)(DWORD handle); /*=========================================================================== Beat position trigger ===========================================================================*/ typedef void (CALLBACK BPMBEATPROC)(DWORD chan, double beatpos, void *user); BOOL BASS_FXDEF(BASS_FX_BPM_BeatCallbackSet)(DWORD handle, BPMBEATPROC *proc, void *user); BOOL BASS_FXDEF(BASS_FX_BPM_BeatCallbackReset)(DWORD handle); BOOL BASS_FXDEF(BASS_FX_BPM_BeatDecodeGet)(DWORD chan, double startSec, double endSec, DWORD flags, BPMBEATPROC *proc, void *user); BOOL BASS_FXDEF(BASS_FX_BPM_BeatSetParameters)(DWORD handle, float bandwidth, float centerfreq, float beat_rtime); BOOL BASS_FXDEF(BASS_FX_BPM_BeatGetParameters)(DWORD handle, float *bandwidth, float *centerfreq, float *beat_rtime); BOOL BASS_FXDEF(BASS_FX_BPM_BeatFree)(DWORD handle); /*=========================================================================== Macros ===========================================================================*/ // translate linear level to logarithmic dB #define BASS_BFX_Linear2dB(level) (20*log10(level)) // translate logarithmic dB level to linear #define BASS_BFX_dB2Linear(dB) pow(10,(dB)/20) #ifdef __cplusplus } #endif #endif
bbbef4cb133c6cb88484b17a1f7dd29ebdc1d1c7
3bd385b466cb035fecd2b0c11ae054d42bf44fc2
/src/extended/genome_node.h
42975fdf922a3dea7a75404118463040e83b4931
[ "LicenseRef-scancode-unknown-license-reference", "ISC", "BSD-2-Clause", "LicenseRef-scancode-mit-old-style", "Zlib", "MIT", "BSD-3-Clause", "bzip2-1.0.6" ]
permissive
genometools/genometools
c366dff04f6baa887f6b3be3ec55bce824b2bae1
df1df94b8c05a9c9bf848ffc6755c87b58573da5
refs/heads/master
2023-04-13T13:57:18.748796
2023-04-09T21:29:53
2023-04-09T21:29:53
11,177,980
237
63
NOASSERTION
2023-04-09T21:29:54
2013-07-04T13:39:38
C
UTF-8
C
false
false
2,506
h
genome_node.h
/* Copyright (c) 2006-2011 Gordon Gremme <gordon@gremme.org> Copyright (c) 2006-2008 Center for Bioinformatics, University of Hamburg Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef GENOME_NODE_H #define GENOME_NODE_H #include "core/bittab.h" #include "core/phase_api.h" #include "core/range_api.h" #include "core/str_api.h" #include "extended/genome_node_api.h" void gt_genome_node_set_origin(GtGenomeNode*, GtStr *filename, unsigned int line_number); void* gt_genome_node_cast(const GtGenomeNodeClass*, GtGenomeNode*); void* gt_genome_node_try_cast(const GtGenomeNodeClass*, GtGenomeNode*); /* Used to sort nodes. */ GtStr* gt_genome_node_get_idstr(GtGenomeNode*); void gt_genome_node_change_seqid(GtGenomeNode*, GtStr*); int gt_genome_node_compare(GtGenomeNode**, GtGenomeNode**); int gt_genome_node_compare_with_data(GtGenomeNode**, GtGenomeNode**, void *unused); /* <delta> has to point to a variable of type GtUword. */ int gt_genome_node_compare_delta(GtGenomeNode**, GtGenomeNode**, void *delta); int gt_genome_node_compare_numeric_seqids(GtGenomeNode **gn_a, GtGenomeNode **gn_b); bool gt_genome_nodes_are_equal_region_nodes(GtGenomeNode*, GtGenomeNode*); bool gt_genome_nodes_are_sorted(const GtArray*); void gt_genome_nodes_sort_with_func(GtArray *nodes, GtCompare cmp); void gt_genome_nodes_sort_stable_with_func(GtArray *nodes, GtCompare cmp); int gt_genome_node_unit_test(GtError*); #endif
ebf0033573ff8aebc75f1e9499aba0b80c8d5779
7c857119fe1505b1d80d6e62969661c06dc1a2f4
/NetworkPkg/HttpDxe/HttpProto.c
bacfbc99584711c85f1a35422db1795c835c142d
[ "BSD-2-Clause" ]
permissive
CloverHackyColor/CloverBootloader
7042ca7dd6b513d22be591a295e49071ae1482ee
2711170df4f60b2ae5aa20add3e00f35cf57b7e5
refs/heads/master
2023-08-30T22:14:34.590134
2023-08-27T19:14:02
2023-08-27T19:14:02
205,810,121
4,734
770
BSD-2-Clause
2023-09-03T12:41:33
2019-09-02T08:22:14
C
UTF-8
C
false
false
65,076
c
HttpProto.c
/** @file Miscellaneous routines for HttpDxe driver. Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR> (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "HttpDriver.h" /** The common notify function used in HTTP driver. @param[in] Event The event signaled. @param[in] Context The context. **/ VOID EFIAPI HttpCommonNotify ( IN EFI_EVENT Event, IN VOID *Context ) { if ((Event == NULL) || (Context == NULL)) { return ; } *((BOOLEAN *) Context) = TRUE; } /** The notify function associated with Tx4Token for Tcp4->Transmit() or Tx6Token for Tcp6->Transmit(). @param[in] Context The context. **/ VOID EFIAPI HttpTcpTransmitNotifyDpc ( IN VOID *Context ) { HTTP_TOKEN_WRAP *Wrap; HTTP_PROTOCOL *HttpInstance; if (Context == NULL) { return ; } Wrap = (HTTP_TOKEN_WRAP *) Context; HttpInstance = Wrap->HttpInstance; if (!HttpInstance->LocalAddressIsIPv6) { Wrap->HttpToken->Status = Wrap->TcpWrap.Tx4Token.CompletionToken.Status; gBS->SignalEvent (Wrap->HttpToken->Event); // // Free resources. // if (Wrap->TcpWrap.Tx4Token.Packet.TxData->FragmentTable[0].FragmentBuffer != NULL) { FreePool (Wrap->TcpWrap.Tx4Token.Packet.TxData->FragmentTable[0].FragmentBuffer); } if (Wrap->TcpWrap.Tx4Token.CompletionToken.Event != NULL) { gBS->CloseEvent (Wrap->TcpWrap.Tx4Token.CompletionToken.Event); } } else { Wrap->HttpToken->Status = Wrap->TcpWrap.Tx6Token.CompletionToken.Status; gBS->SignalEvent (Wrap->HttpToken->Event); // // Free resources. // if (Wrap->TcpWrap.Tx6Token.Packet.TxData->FragmentTable[0].FragmentBuffer != NULL) { FreePool (Wrap->TcpWrap.Tx6Token.Packet.TxData->FragmentTable[0].FragmentBuffer); } if (Wrap->TcpWrap.Tx6Token.CompletionToken.Event != NULL) { gBS->CloseEvent (Wrap->TcpWrap.Tx6Token.CompletionToken.Event); } } Wrap->TcpWrap.IsTxDone = TRUE; // // Check pending TxTokens and sent out. // NetMapIterate (&Wrap->HttpInstance->TxTokens, HttpTcpTransmit, NULL); } /** Request HttpTcpTransmitNotifyDpc as a DPC at TPL_CALLBACK. @param Event The receive event delivered to TCP for transmit. @param Context Context for the callback. **/ VOID EFIAPI HttpTcpTransmitNotify ( IN EFI_EVENT Event, IN VOID *Context ) { // // Request HttpTcpTransmitNotifyDpc as a DPC at TPL_CALLBACK // QueueDpc (TPL_CALLBACK, HttpTcpTransmitNotifyDpc, Context); } /** The notify function associated with Rx4Token for Tcp4->Receive () or Rx6Token for Tcp6->Receive(). @param[in] Context The context. **/ VOID EFIAPI HttpTcpReceiveNotifyDpc ( IN VOID *Context ) { HTTP_TOKEN_WRAP *Wrap; NET_MAP_ITEM *Item; UINTN Length; EFI_STATUS Status; HTTP_PROTOCOL *HttpInstance; BOOLEAN UsingIpv6; if (Context == NULL) { return ; } Wrap = (HTTP_TOKEN_WRAP *) Context; HttpInstance = Wrap->HttpInstance; UsingIpv6 = HttpInstance->LocalAddressIsIPv6; if (UsingIpv6) { gBS->CloseEvent (Wrap->TcpWrap.Rx6Token.CompletionToken.Event); Wrap->TcpWrap.Rx6Token.CompletionToken.Event = NULL; if (EFI_ERROR (Wrap->TcpWrap.Rx6Token.CompletionToken.Status)) { DEBUG ((EFI_D_ERROR, "HttpTcpReceiveNotifyDpc: %r!\n", Wrap->TcpWrap.Rx6Token.CompletionToken.Status)); Wrap->HttpToken->Status = Wrap->TcpWrap.Rx6Token.CompletionToken.Status; gBS->SignalEvent (Wrap->HttpToken->Event); Item = NetMapFindKey (&HttpInstance->RxTokens, Wrap->HttpToken); if (Item != NULL) { NetMapRemoveItem (&HttpInstance->RxTokens, Item, NULL); } FreePool (Wrap); Wrap = NULL; return ; } } else { gBS->CloseEvent (Wrap->TcpWrap.Rx4Token.CompletionToken.Event); Wrap->TcpWrap.Rx4Token.CompletionToken.Event = NULL; if (EFI_ERROR (Wrap->TcpWrap.Rx4Token.CompletionToken.Status)) { DEBUG ((EFI_D_ERROR, "HttpTcpReceiveNotifyDpc: %r!\n", Wrap->TcpWrap.Rx4Token.CompletionToken.Status)); Wrap->HttpToken->Status = Wrap->TcpWrap.Rx4Token.CompletionToken.Status; gBS->SignalEvent (Wrap->HttpToken->Event); Item = NetMapFindKey (&HttpInstance->RxTokens, Wrap->HttpToken); if (Item != NULL) { NetMapRemoveItem (&HttpInstance->RxTokens, Item, NULL); } FreePool (Wrap); Wrap = NULL; return ; } } // // Check whether we receive a complete HTTP message. // ASSERT (HttpInstance->MsgParser != NULL); if (UsingIpv6) { Length = (UINTN) Wrap->TcpWrap.Rx6Data.FragmentTable[0].FragmentLength; } else { Length = (UINTN) Wrap->TcpWrap.Rx4Data.FragmentTable[0].FragmentLength; } // // Record the CallbackData data. // HttpInstance->CallbackData.Wrap = (VOID *) Wrap; HttpInstance->CallbackData.ParseData = Wrap->HttpToken->Message->Body; HttpInstance->CallbackData.ParseDataLength = Length; // // Parse Body with CallbackData data. // Status = HttpParseMessageBody ( HttpInstance->MsgParser, Length, Wrap->HttpToken->Message->Body ); if (EFI_ERROR (Status)) { return ; } if (HttpIsMessageComplete (HttpInstance->MsgParser)) { // // Free the MsgParse since we already have a full HTTP message. // HttpFreeMsgParser (HttpInstance->MsgParser); HttpInstance->MsgParser = NULL; } Wrap->HttpToken->Message->BodyLength = Length; ASSERT (HttpInstance->CacheBody == NULL); // // We receive part of header of next HTTP msg. // if (HttpInstance->NextMsg != NULL) { Wrap->HttpToken->Message->BodyLength = HttpInstance->NextMsg - (CHAR8 *) Wrap->HttpToken->Message->Body; HttpInstance->CacheLen = Length - Wrap->HttpToken->Message->BodyLength; if (HttpInstance->CacheLen != 0) { HttpInstance->CacheBody = AllocateZeroPool (HttpInstance->CacheLen); if (HttpInstance->CacheBody == NULL) { return ; } CopyMem (HttpInstance->CacheBody, HttpInstance->NextMsg, HttpInstance->CacheLen); HttpInstance->NextMsg = HttpInstance->CacheBody; HttpInstance->CacheOffset = 0; } } Item = NetMapFindKey (&Wrap->HttpInstance->RxTokens, Wrap->HttpToken); if (Item != NULL) { NetMapRemoveItem (&Wrap->HttpInstance->RxTokens, Item, NULL); } Wrap->TcpWrap.IsRxDone = TRUE; if (UsingIpv6) { Wrap->HttpToken->Status = Wrap->TcpWrap.Rx6Token.CompletionToken.Status; } else { Wrap->HttpToken->Status = Wrap->TcpWrap.Rx4Token.CompletionToken.Status; } gBS->SignalEvent (Wrap->HttpToken->Event); // // Check pending RxTokens and receive the HTTP message. // NetMapIterate (&Wrap->HttpInstance->RxTokens, HttpTcpReceive, NULL); FreePool (Wrap); Wrap = NULL; } /** Request HttpTcpReceiveNotifyDpc as a DPC at TPL_CALLBACK. @param Event The receive event delivered to TCP for receive. @param Context Context for the callback. **/ VOID EFIAPI HttpTcpReceiveNotify ( IN EFI_EVENT Event, IN VOID *Context ) { // // Request HttpTcpTransmitNotifyDpc as a DPC at TPL_CALLBACK // QueueDpc (TPL_CALLBACK, HttpTcpReceiveNotifyDpc, Context); } /** Create events for the TCP connection token and TCP close token. @param[in] HttpInstance Pointer to HTTP_PROTOCOL structure. @retval EFI_SUCCESS The events are created successfully. @retval others Other error as indicated. **/ EFI_STATUS HttpCreateTcpConnCloseEvent ( IN HTTP_PROTOCOL *HttpInstance ) { EFI_STATUS Status; if (!HttpInstance->LocalAddressIsIPv6) { // // Create events for variuos asynchronous operations. // Status = gBS->CreateEvent ( EVT_NOTIFY_SIGNAL, TPL_NOTIFY, HttpCommonNotify, &HttpInstance->IsTcp4ConnDone, &HttpInstance->Tcp4ConnToken.CompletionToken.Event ); if (EFI_ERROR (Status)) { goto ERROR; } // // Initialize Tcp4CloseToken // Status = gBS->CreateEvent ( EVT_NOTIFY_SIGNAL, TPL_NOTIFY, HttpCommonNotify, &HttpInstance->IsTcp4CloseDone, &HttpInstance->Tcp4CloseToken.CompletionToken.Event ); if (EFI_ERROR (Status)) { goto ERROR; } } else { // // Create events for variuos asynchronous operations. // Status = gBS->CreateEvent ( EVT_NOTIFY_SIGNAL, TPL_NOTIFY, HttpCommonNotify, &HttpInstance->IsTcp6ConnDone, &HttpInstance->Tcp6ConnToken.CompletionToken.Event ); if (EFI_ERROR (Status)) { goto ERROR; } // // Initialize Tcp6CloseToken // Status = gBS->CreateEvent ( EVT_NOTIFY_SIGNAL, TPL_NOTIFY, HttpCommonNotify, &HttpInstance->IsTcp6CloseDone, &HttpInstance->Tcp6CloseToken.CompletionToken.Event ); if (EFI_ERROR (Status)) { goto ERROR; } } return EFI_SUCCESS; ERROR: // // Error handling // HttpCloseTcpConnCloseEvent (HttpInstance); return Status; } /** Close events in the TCP connection token and TCP close token. @param[in] HttpInstance Pointer to HTTP_PROTOCOL structure. **/ VOID HttpCloseTcpConnCloseEvent ( IN HTTP_PROTOCOL *HttpInstance ) { ASSERT (HttpInstance != NULL); if (HttpInstance->LocalAddressIsIPv6) { if (NULL != HttpInstance->Tcp6ConnToken.CompletionToken.Event) { gBS->CloseEvent (HttpInstance->Tcp6ConnToken.CompletionToken.Event); HttpInstance->Tcp6ConnToken.CompletionToken.Event = NULL; } if (NULL != HttpInstance->Tcp6CloseToken.CompletionToken.Event) { gBS->CloseEvent(HttpInstance->Tcp6CloseToken.CompletionToken.Event); HttpInstance->Tcp6CloseToken.CompletionToken.Event = NULL; } } else { if (NULL != HttpInstance->Tcp4ConnToken.CompletionToken.Event) { gBS->CloseEvent (HttpInstance->Tcp4ConnToken.CompletionToken.Event); HttpInstance->Tcp4ConnToken.CompletionToken.Event = NULL; } if (NULL != HttpInstance->Tcp4CloseToken.CompletionToken.Event) { gBS->CloseEvent(HttpInstance->Tcp4CloseToken.CompletionToken.Event); HttpInstance->Tcp4CloseToken.CompletionToken.Event = NULL; } } } /** Create event for the TCP transmit token. @param[in] Wrap Point to HTTP token's wrap data. @retval EFI_SUCCESS The events is created successfully. @retval others Other error as indicated. **/ EFI_STATUS HttpCreateTcpTxEvent ( IN HTTP_TOKEN_WRAP *Wrap ) { EFI_STATUS Status; HTTP_PROTOCOL *HttpInstance; HTTP_TCP_TOKEN_WRAP *TcpWrap; HttpInstance = Wrap->HttpInstance; TcpWrap = &Wrap->TcpWrap; if (!HttpInstance->LocalAddressIsIPv6) { Status = gBS->CreateEvent ( EVT_NOTIFY_SIGNAL, TPL_NOTIFY, HttpTcpTransmitNotify, Wrap, &TcpWrap->Tx4Token.CompletionToken.Event ); if (EFI_ERROR (Status)) { return Status; } TcpWrap->Tx4Data.Push = TRUE; TcpWrap->Tx4Data.Urgent = FALSE; TcpWrap->Tx4Data.FragmentCount = 1; TcpWrap->Tx4Token.Packet.TxData = &Wrap->TcpWrap.Tx4Data; TcpWrap->Tx4Token.CompletionToken.Status = EFI_NOT_READY; } else { Status = gBS->CreateEvent ( EVT_NOTIFY_SIGNAL, TPL_NOTIFY, HttpTcpTransmitNotify, Wrap, &TcpWrap->Tx6Token.CompletionToken.Event ); if (EFI_ERROR (Status)) { return Status; } TcpWrap->Tx6Data.Push = TRUE; TcpWrap->Tx6Data.Urgent = FALSE; TcpWrap->Tx6Data.FragmentCount = 1; TcpWrap->Tx6Token.Packet.TxData = &Wrap->TcpWrap.Tx6Data; TcpWrap->Tx6Token.CompletionToken.Status =EFI_NOT_READY; } return EFI_SUCCESS; } /** Create event for the TCP receive token which is used to receive HTTP header. @param[in] HttpInstance Pointer to HTTP_PROTOCOL structure. @retval EFI_SUCCESS The events is created successfully. @retval others Other error as indicated. **/ EFI_STATUS HttpCreateTcpRxEventForHeader ( IN HTTP_PROTOCOL *HttpInstance ) { EFI_STATUS Status; if (!HttpInstance->LocalAddressIsIPv6) { Status = gBS->CreateEvent ( EVT_NOTIFY_SIGNAL, TPL_NOTIFY, HttpCommonNotify, &HttpInstance->IsRxDone, &HttpInstance->Rx4Token.CompletionToken.Event ); if (EFI_ERROR (Status)) { return Status; } HttpInstance->Rx4Data.FragmentCount = 1; HttpInstance->Rx4Token.Packet.RxData = &HttpInstance->Rx4Data; HttpInstance->Rx4Token.CompletionToken.Status = EFI_NOT_READY; } else { Status = gBS->CreateEvent ( EVT_NOTIFY_SIGNAL, TPL_NOTIFY, HttpCommonNotify, &HttpInstance->IsRxDone, &HttpInstance->Rx6Token.CompletionToken.Event ); if (EFI_ERROR (Status)) { return Status; } HttpInstance->Rx6Data.FragmentCount =1; HttpInstance->Rx6Token.Packet.RxData = &HttpInstance->Rx6Data; HttpInstance->Rx6Token.CompletionToken.Status = EFI_NOT_READY; } return EFI_SUCCESS; } /** Create event for the TCP receive token which is used to receive HTTP body. @param[in] Wrap Point to HTTP token's wrap data. @retval EFI_SUCCESS The events is created successfully. @retval others Other error as indicated. **/ EFI_STATUS HttpCreateTcpRxEvent ( IN HTTP_TOKEN_WRAP *Wrap ) { EFI_STATUS Status; HTTP_PROTOCOL *HttpInstance; HTTP_TCP_TOKEN_WRAP *TcpWrap; HttpInstance = Wrap->HttpInstance; TcpWrap = &Wrap->TcpWrap; if (!HttpInstance->LocalAddressIsIPv6) { Status = gBS->CreateEvent ( EVT_NOTIFY_SIGNAL, TPL_NOTIFY, HttpTcpReceiveNotify, Wrap, &TcpWrap->Rx4Token.CompletionToken.Event ); if (EFI_ERROR (Status)) { return Status; } TcpWrap->Rx4Data.FragmentCount = 1; TcpWrap->Rx4Token.Packet.RxData = &Wrap->TcpWrap.Rx4Data; TcpWrap->Rx4Token.CompletionToken.Status = EFI_NOT_READY; } else { Status = gBS->CreateEvent ( EVT_NOTIFY_SIGNAL, TPL_NOTIFY, HttpTcpReceiveNotify, Wrap, &TcpWrap->Rx6Token.CompletionToken.Event ); if (EFI_ERROR (Status)) { return Status; } TcpWrap->Rx6Data.FragmentCount = 1; TcpWrap->Rx6Token.Packet.RxData = &Wrap->TcpWrap.Rx6Data; TcpWrap->Rx6Token.CompletionToken.Status = EFI_NOT_READY; } return EFI_SUCCESS; } /** Close Events for Tcp Receive Tokens for HTTP body and HTTP header. @param[in] Wrap Pointer to HTTP token's wrap data. **/ VOID HttpCloseTcpRxEvent ( IN HTTP_TOKEN_WRAP *Wrap ) { HTTP_PROTOCOL *HttpInstance; ASSERT (Wrap != NULL); HttpInstance = Wrap->HttpInstance; if (HttpInstance->LocalAddressIsIPv6) { if (Wrap->TcpWrap.Rx6Token.CompletionToken.Event != NULL) { gBS->CloseEvent (Wrap->TcpWrap.Rx6Token.CompletionToken.Event); } if (HttpInstance->Rx6Token.CompletionToken.Event != NULL) { gBS->CloseEvent (HttpInstance->Rx6Token.CompletionToken.Event); HttpInstance->Rx6Token.CompletionToken.Event = NULL; } } else { if (Wrap->TcpWrap.Rx4Token.CompletionToken.Event != NULL) { gBS->CloseEvent (Wrap->TcpWrap.Rx4Token.CompletionToken.Event); } if (HttpInstance->Rx4Token.CompletionToken.Event != NULL) { gBS->CloseEvent (HttpInstance->Rx4Token.CompletionToken.Event); HttpInstance->Rx4Token.CompletionToken.Event = NULL; } } } /** Intiialize the HTTP_PROTOCOL structure to the unconfigured state. @param[in, out] HttpInstance Pointer to HTTP_PROTOCOL structure. @param[in] IpVersion Indicate us TCP4 protocol or TCP6 protocol. @retval EFI_SUCCESS HTTP_PROTOCOL structure is initialized successfully. @retval Others Other error as indicated. **/ EFI_STATUS HttpInitProtocol ( IN OUT HTTP_PROTOCOL *HttpInstance, IN BOOLEAN IpVersion ) { EFI_STATUS Status; VOID *Interface; BOOLEAN UsingIpv6; ASSERT (HttpInstance != NULL); UsingIpv6 = IpVersion; if (!UsingIpv6) { // // Create TCP4 child. // Status = NetLibCreateServiceChild ( HttpInstance->Service->ControllerHandle, HttpInstance->Service->Ip4DriverBindingHandle, &gEfiTcp4ServiceBindingProtocolGuid, &HttpInstance->Tcp4ChildHandle ); if (EFI_ERROR (Status)) { goto ON_ERROR; } Status = gBS->OpenProtocol ( HttpInstance->Tcp4ChildHandle, &gEfiTcp4ProtocolGuid, (VOID **) &Interface, HttpInstance->Service->Ip4DriverBindingHandle, HttpInstance->Service->ControllerHandle, EFI_OPEN_PROTOCOL_BY_DRIVER ); if (EFI_ERROR (Status)) { goto ON_ERROR; } Status = gBS->OpenProtocol ( HttpInstance->Tcp4ChildHandle, &gEfiTcp4ProtocolGuid, (VOID **) &HttpInstance->Tcp4, HttpInstance->Service->Ip4DriverBindingHandle, HttpInstance->Handle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER ); if (EFI_ERROR(Status)) { goto ON_ERROR; } Status = gBS->OpenProtocol ( HttpInstance->Service->Tcp4ChildHandle, &gEfiTcp4ProtocolGuid, (VOID **) &Interface, HttpInstance->Service->Ip4DriverBindingHandle, HttpInstance->Handle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER ); if (EFI_ERROR(Status)) { goto ON_ERROR; } } else { // // Create TCP6 Child. // Status = NetLibCreateServiceChild ( HttpInstance->Service->ControllerHandle, HttpInstance->Service->Ip6DriverBindingHandle, &gEfiTcp6ServiceBindingProtocolGuid, &HttpInstance->Tcp6ChildHandle ); if (EFI_ERROR (Status)) { goto ON_ERROR; } Status = gBS->OpenProtocol ( HttpInstance->Tcp6ChildHandle, &gEfiTcp6ProtocolGuid, (VOID **) &Interface, HttpInstance->Service->Ip6DriverBindingHandle, HttpInstance->Service->ControllerHandle, EFI_OPEN_PROTOCOL_BY_DRIVER ); if (EFI_ERROR (Status)) { goto ON_ERROR; } Status = gBS->OpenProtocol ( HttpInstance->Tcp6ChildHandle, &gEfiTcp6ProtocolGuid, (VOID **) &HttpInstance->Tcp6, HttpInstance->Service->Ip6DriverBindingHandle, HttpInstance->Handle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER ); if (EFI_ERROR(Status)) { goto ON_ERROR; } Status = gBS->OpenProtocol ( HttpInstance->Service->Tcp6ChildHandle, &gEfiTcp6ProtocolGuid, (VOID **) &Interface, HttpInstance->Service->Ip6DriverBindingHandle, HttpInstance->Handle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER ); if (EFI_ERROR(Status)) { goto ON_ERROR; } } HttpInstance->Url = AllocateZeroPool (HTTP_URL_BUFFER_LEN); if (HttpInstance->Url == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ON_ERROR; } return EFI_SUCCESS; ON_ERROR: if (HttpInstance->Tcp4ChildHandle != NULL) { gBS->CloseProtocol ( HttpInstance->Tcp4ChildHandle, &gEfiTcp4ProtocolGuid, HttpInstance->Service->Ip4DriverBindingHandle, HttpInstance->Service->ControllerHandle ); gBS->CloseProtocol ( HttpInstance->Tcp4ChildHandle, &gEfiTcp4ProtocolGuid, HttpInstance->Service->Ip4DriverBindingHandle, HttpInstance->Handle ); NetLibDestroyServiceChild ( HttpInstance->Service->ControllerHandle, HttpInstance->Service->Ip4DriverBindingHandle, &gEfiTcp4ServiceBindingProtocolGuid, HttpInstance->Tcp4ChildHandle ); } if (HttpInstance->Service->Tcp4ChildHandle != NULL) { gBS->CloseProtocol ( HttpInstance->Service->Tcp4ChildHandle, &gEfiTcp4ProtocolGuid, HttpInstance->Service->Ip4DriverBindingHandle, HttpInstance->Handle ); } if (HttpInstance->Tcp6ChildHandle != NULL) { gBS->CloseProtocol ( HttpInstance->Tcp6ChildHandle, &gEfiTcp6ProtocolGuid, HttpInstance->Service->Ip6DriverBindingHandle, HttpInstance->Service->ControllerHandle ); gBS->CloseProtocol ( HttpInstance->Tcp6ChildHandle, &gEfiTcp6ProtocolGuid, HttpInstance->Service->Ip6DriverBindingHandle, HttpInstance->Handle ); NetLibDestroyServiceChild ( HttpInstance->Service->ControllerHandle, HttpInstance->Service->Ip6DriverBindingHandle, &gEfiTcp6ServiceBindingProtocolGuid, HttpInstance->Tcp6ChildHandle ); } if (HttpInstance->Service->Tcp6ChildHandle != NULL) { gBS->CloseProtocol ( HttpInstance->Service->Tcp6ChildHandle, &gEfiTcp6ProtocolGuid, HttpInstance->Service->Ip6DriverBindingHandle, HttpInstance->Handle ); } return EFI_UNSUPPORTED; } /** Clean up the HTTP child, release all the resources used by it. @param[in] HttpInstance The HTTP child to clean up. **/ VOID HttpCleanProtocol ( IN HTTP_PROTOCOL *HttpInstance ) { HttpCloseConnection (HttpInstance); HttpCloseTcpConnCloseEvent (HttpInstance); if (HttpInstance->TimeoutEvent != NULL) { gBS->CloseEvent (HttpInstance->TimeoutEvent); HttpInstance->TimeoutEvent = NULL; } if (HttpInstance->CacheBody != NULL) { FreePool (HttpInstance->CacheBody); HttpInstance->CacheBody = NULL; HttpInstance->NextMsg = NULL; } if (HttpInstance->RemoteHost != NULL) { FreePool (HttpInstance->RemoteHost); HttpInstance->RemoteHost = NULL; } if (HttpInstance->MsgParser != NULL) { HttpFreeMsgParser (HttpInstance->MsgParser); HttpInstance->MsgParser = NULL; } if (HttpInstance->Url != NULL) { FreePool (HttpInstance->Url); HttpInstance->Url = NULL; } NetMapClean (&HttpInstance->TxTokens); NetMapClean (&HttpInstance->RxTokens); if (HttpInstance->TlsSb != NULL && HttpInstance->TlsChildHandle != NULL) { // // Destroy the TLS instance. // HttpInstance->TlsSb->DestroyChild (HttpInstance->TlsSb, HttpInstance->TlsChildHandle); } if (HttpInstance->Tcp4ChildHandle != NULL) { gBS->CloseProtocol ( HttpInstance->Tcp4ChildHandle, &gEfiTcp4ProtocolGuid, HttpInstance->Service->Ip4DriverBindingHandle, HttpInstance->Service->ControllerHandle ); gBS->CloseProtocol ( HttpInstance->Tcp4ChildHandle, &gEfiTcp4ProtocolGuid, HttpInstance->Service->Ip4DriverBindingHandle, HttpInstance->Handle ); NetLibDestroyServiceChild ( HttpInstance->Service->ControllerHandle, HttpInstance->Service->Ip4DriverBindingHandle, &gEfiTcp4ServiceBindingProtocolGuid, HttpInstance->Tcp4ChildHandle ); } if (HttpInstance->Service->Tcp4ChildHandle != NULL) { gBS->CloseProtocol ( HttpInstance->Service->Tcp4ChildHandle, &gEfiTcp4ProtocolGuid, HttpInstance->Service->Ip4DriverBindingHandle, HttpInstance->Handle ); } if (HttpInstance->Tcp6ChildHandle != NULL) { gBS->CloseProtocol ( HttpInstance->Tcp6ChildHandle, &gEfiTcp6ProtocolGuid, HttpInstance->Service->Ip6DriverBindingHandle, HttpInstance->Service->ControllerHandle ); gBS->CloseProtocol ( HttpInstance->Tcp6ChildHandle, &gEfiTcp6ProtocolGuid, HttpInstance->Service->Ip6DriverBindingHandle, HttpInstance->Handle ); NetLibDestroyServiceChild ( HttpInstance->Service->ControllerHandle, HttpInstance->Service->Ip6DriverBindingHandle, &gEfiTcp6ServiceBindingProtocolGuid, HttpInstance->Tcp6ChildHandle ); } if (HttpInstance->Service->Tcp6ChildHandle != NULL) { gBS->CloseProtocol ( HttpInstance->Service->Tcp6ChildHandle, &gEfiTcp6ProtocolGuid, HttpInstance->Service->Ip6DriverBindingHandle, HttpInstance->Handle ); } TlsCloseTxRxEvent (HttpInstance); } /** Establish TCP connection with HTTP server. @param[in] HttpInstance The HTTP instance private data. @retval EFI_SUCCESS The TCP connection is established. @retval Others Other error as indicated. **/ EFI_STATUS HttpCreateConnection ( IN HTTP_PROTOCOL *HttpInstance ) { EFI_STATUS Status; // // Connect to Http server // if (!HttpInstance->LocalAddressIsIPv6) { HttpInstance->IsTcp4ConnDone = FALSE; HttpInstance->Tcp4ConnToken.CompletionToken.Status = EFI_NOT_READY; Status = HttpInstance->Tcp4->Connect (HttpInstance->Tcp4, &HttpInstance->Tcp4ConnToken); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "HttpCreateConnection: Tcp4->Connect() = %r\n", Status)); return Status; } while (!HttpInstance->IsTcp4ConnDone) { HttpInstance->Tcp4->Poll (HttpInstance->Tcp4); } Status = HttpInstance->Tcp4ConnToken.CompletionToken.Status; } else { HttpInstance->IsTcp6ConnDone = FALSE; HttpInstance->Tcp6ConnToken.CompletionToken.Status = EFI_NOT_READY; Status = HttpInstance->Tcp6->Connect (HttpInstance->Tcp6, &HttpInstance->Tcp6ConnToken); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "HttpCreateConnection: Tcp6->Connect() = %r\n", Status)); return Status; } while(!HttpInstance->IsTcp6ConnDone) { HttpInstance->Tcp6->Poll (HttpInstance->Tcp6); } Status = HttpInstance->Tcp6ConnToken.CompletionToken.Status; } if (!EFI_ERROR (Status)) { HttpInstance->State = HTTP_STATE_TCP_CONNECTED; } return Status; } /** Close existing TCP connection. @param[in] HttpInstance The HTTP instance private data. @retval EFI_SUCCESS The TCP connection is closed. @retval Others Other error as indicated. **/ EFI_STATUS HttpCloseConnection ( IN HTTP_PROTOCOL *HttpInstance ) { EFI_STATUS Status; if (HttpInstance->State == HTTP_STATE_TCP_CONNECTED) { if (HttpInstance->LocalAddressIsIPv6) { HttpInstance->Tcp6CloseToken.AbortOnClose = TRUE; HttpInstance->IsTcp6CloseDone = FALSE; Status = HttpInstance->Tcp6->Close (HttpInstance->Tcp6, &HttpInstance->Tcp6CloseToken); if (EFI_ERROR (Status)) { return Status; } while (!HttpInstance->IsTcp6CloseDone) { HttpInstance->Tcp6->Poll (HttpInstance->Tcp6); } } else { HttpInstance->Tcp4CloseToken.AbortOnClose = TRUE; HttpInstance->IsTcp4CloseDone = FALSE; Status = HttpInstance->Tcp4->Close (HttpInstance->Tcp4, &HttpInstance->Tcp4CloseToken); if (EFI_ERROR (Status)) { return Status; } while (!HttpInstance->IsTcp4CloseDone) { HttpInstance->Tcp4->Poll (HttpInstance->Tcp4); } } } HttpInstance->State = HTTP_STATE_TCP_CLOSED; return EFI_SUCCESS; } /** Configure TCP4 protocol child. @param[in] HttpInstance The HTTP instance private data. @param[in] Wrap The HTTP token's wrap data. @retval EFI_SUCCESS The TCP4 protocol child is configured. @retval Others Other error as indicated. **/ EFI_STATUS HttpConfigureTcp4 ( IN HTTP_PROTOCOL *HttpInstance, IN HTTP_TOKEN_WRAP *Wrap ) { EFI_STATUS Status; EFI_TCP4_CONFIG_DATA *Tcp4CfgData; EFI_TCP4_ACCESS_POINT *Tcp4AP; EFI_TCP4_OPTION *Tcp4Option; ASSERT (HttpInstance != NULL); Tcp4CfgData = &HttpInstance->Tcp4CfgData; ZeroMem (Tcp4CfgData, sizeof (EFI_TCP4_CONFIG_DATA)); Tcp4CfgData->TypeOfService = HTTP_TOS_DEAULT; Tcp4CfgData->TimeToLive = HTTP_TTL_DEAULT; Tcp4CfgData->ControlOption = &HttpInstance->Tcp4Option; Tcp4AP = &Tcp4CfgData->AccessPoint; Tcp4AP->UseDefaultAddress = HttpInstance->IPv4Node.UseDefaultAddress; if (!Tcp4AP->UseDefaultAddress) { IP4_COPY_ADDRESS (&Tcp4AP->StationAddress, &HttpInstance->IPv4Node.LocalAddress); IP4_COPY_ADDRESS (&Tcp4AP->SubnetMask, &HttpInstance->IPv4Node.LocalSubnet); } Tcp4AP->StationPort = HttpInstance->IPv4Node.LocalPort; Tcp4AP->RemotePort = HttpInstance->RemotePort; Tcp4AP->ActiveFlag = TRUE; IP4_COPY_ADDRESS (&Tcp4AP->RemoteAddress, &HttpInstance->RemoteAddr); Tcp4Option = Tcp4CfgData->ControlOption; Tcp4Option->ReceiveBufferSize = HTTP_BUFFER_SIZE_DEAULT; Tcp4Option->SendBufferSize = HTTP_BUFFER_SIZE_DEAULT; Tcp4Option->MaxSynBackLog = HTTP_MAX_SYN_BACK_LOG; Tcp4Option->ConnectionTimeout = HTTP_CONNECTION_TIMEOUT; Tcp4Option->DataRetries = HTTP_DATA_RETRIES; Tcp4Option->FinTimeout = HTTP_FIN_TIMEOUT; Tcp4Option->KeepAliveProbes = HTTP_KEEP_ALIVE_PROBES; Tcp4Option->KeepAliveTime = HTTP_KEEP_ALIVE_TIME; Tcp4Option->KeepAliveInterval = HTTP_KEEP_ALIVE_INTERVAL; Tcp4Option->EnableNagle = TRUE; Tcp4CfgData->ControlOption = Tcp4Option; Status = HttpInstance->Tcp4->Configure (HttpInstance->Tcp4, Tcp4CfgData); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "HttpConfigureTcp4 - %r\n", Status)); return Status; } Status = HttpCreateTcpConnCloseEvent (HttpInstance); if (EFI_ERROR (Status)) { return Status; } Status = HttpCreateTcpTxEvent (Wrap); if (EFI_ERROR (Status)) { return Status; } HttpInstance->State = HTTP_STATE_TCP_CONFIGED; return EFI_SUCCESS; } /** Configure TCP6 protocol child. @param[in] HttpInstance The HTTP instance private data. @param[in] Wrap The HTTP token's wrap data. @retval EFI_SUCCESS The TCP6 protocol child is configured. @retval Others Other error as indicated. **/ EFI_STATUS HttpConfigureTcp6 ( IN HTTP_PROTOCOL *HttpInstance, IN HTTP_TOKEN_WRAP *Wrap ) { EFI_STATUS Status; EFI_TCP6_CONFIG_DATA *Tcp6CfgData; EFI_TCP6_ACCESS_POINT *Tcp6Ap; EFI_TCP6_OPTION *Tcp6Option; ASSERT (HttpInstance != NULL); Tcp6CfgData = &HttpInstance->Tcp6CfgData; ZeroMem (Tcp6CfgData, sizeof (EFI_TCP6_CONFIG_DATA)); Tcp6CfgData->TrafficClass = 0; Tcp6CfgData->HopLimit = 255; Tcp6CfgData->ControlOption = &HttpInstance->Tcp6Option; Tcp6Ap = &Tcp6CfgData->AccessPoint; Tcp6Ap->ActiveFlag = TRUE; Tcp6Ap->StationPort = HttpInstance->Ipv6Node.LocalPort; Tcp6Ap->RemotePort = HttpInstance->RemotePort; IP6_COPY_ADDRESS (&Tcp6Ap->StationAddress, &HttpInstance->Ipv6Node.LocalAddress); IP6_COPY_ADDRESS (&Tcp6Ap->RemoteAddress , &HttpInstance->RemoteIpv6Addr); Tcp6Option = Tcp6CfgData->ControlOption; Tcp6Option->ReceiveBufferSize = HTTP_BUFFER_SIZE_DEAULT; Tcp6Option->SendBufferSize = HTTP_BUFFER_SIZE_DEAULT; Tcp6Option->MaxSynBackLog = HTTP_MAX_SYN_BACK_LOG; Tcp6Option->ConnectionTimeout = HTTP_CONNECTION_TIMEOUT; Tcp6Option->DataRetries = HTTP_DATA_RETRIES; Tcp6Option->FinTimeout = HTTP_FIN_TIMEOUT; Tcp6Option->KeepAliveProbes = HTTP_KEEP_ALIVE_PROBES; Tcp6Option->KeepAliveTime = HTTP_KEEP_ALIVE_TIME; Tcp6Option->KeepAliveInterval = HTTP_KEEP_ALIVE_INTERVAL; Tcp6Option->EnableNagle = TRUE; Status = HttpInstance->Tcp6->Configure (HttpInstance->Tcp6, Tcp6CfgData); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "HttpConfigureTcp6 - %r\n", Status)); return Status; } Status = HttpCreateTcpConnCloseEvent (HttpInstance); if (EFI_ERROR (Status)) { return Status; } Status = HttpCreateTcpTxEvent (Wrap); if (EFI_ERROR (Status)) { return Status; } HttpInstance->State = HTTP_STATE_TCP_CONFIGED; return EFI_SUCCESS; } /** Check existing TCP connection, if in error state, recover TCP4 connection. Then, connect one TLS session if required. @param[in] HttpInstance The HTTP instance private data. @retval EFI_SUCCESS The TCP connection is established. @retval EFI_NOT_READY TCP4 protocol child is not created or configured. @retval Others Other error as indicated. **/ EFI_STATUS HttpConnectTcp4 ( IN HTTP_PROTOCOL *HttpInstance ) { EFI_STATUS Status; EFI_TCP4_CONNECTION_STATE Tcp4State; if (HttpInstance->State < HTTP_STATE_TCP_CONFIGED || HttpInstance->Tcp4 == NULL) { return EFI_NOT_READY; } Status = HttpInstance->Tcp4->GetModeData( HttpInstance->Tcp4, &Tcp4State, NULL, NULL, NULL, NULL ); if (EFI_ERROR(Status)){ DEBUG ((EFI_D_ERROR, "Tcp4 GetModeData fail - %x\n", Status)); return Status; } if (Tcp4State == Tcp4StateEstablished) { return EFI_SUCCESS; } else if (Tcp4State > Tcp4StateEstablished ) { HttpCloseConnection(HttpInstance); } Status = HttpCreateConnection (HttpInstance); if (EFI_ERROR(Status)){ DEBUG ((EFI_D_ERROR, "Tcp4 Connection fail - %x\n", Status)); return Status; } // // Tls session connection. // if (HttpInstance->UseHttps) { if (HttpInstance->TimeoutEvent == NULL) { // // Create TimeoutEvent for TLS connection. // Status = gBS->CreateEvent ( EVT_TIMER, TPL_CALLBACK, NULL, NULL, &HttpInstance->TimeoutEvent ); if (EFI_ERROR (Status)) { TlsCloseTxRxEvent (HttpInstance); return Status; } } // // Start the timer, and wait Timeout seconds for connection. // Status = gBS->SetTimer (HttpInstance->TimeoutEvent, TimerRelative, HTTP_CONNECTION_TIMEOUT * TICKS_PER_SECOND); if (EFI_ERROR (Status)) { TlsCloseTxRxEvent (HttpInstance); return Status; } Status = TlsConnectSession (HttpInstance, HttpInstance->TimeoutEvent); gBS->SetTimer (HttpInstance->TimeoutEvent, TimerCancel, 0); if (EFI_ERROR (Status)) { TlsCloseTxRxEvent (HttpInstance); return Status; } } return Status; } /** Check existing TCP connection, if in error state, recover TCP6 connection. Then, connect one TLS session if required. @param[in] HttpInstance The HTTP instance private data. @retval EFI_SUCCESS The TCP connection is established. @retval EFI_NOT_READY TCP6 protocol child is not created or configured. @retval Others Other error as indicated. **/ EFI_STATUS HttpConnectTcp6 ( IN HTTP_PROTOCOL *HttpInstance ) { EFI_STATUS Status; EFI_TCP6_CONNECTION_STATE Tcp6State; if (HttpInstance->State < HTTP_STATE_TCP_CONFIGED || HttpInstance->Tcp6 == NULL) { return EFI_NOT_READY; } Status = HttpInstance->Tcp6->GetModeData ( HttpInstance->Tcp6, &Tcp6State, NULL, NULL, NULL, NULL ); if (EFI_ERROR(Status)){ DEBUG ((EFI_D_ERROR, "Tcp6 GetModeData fail - %x\n", Status)); return Status; } if (Tcp6State == Tcp6StateEstablished) { return EFI_SUCCESS; } else if (Tcp6State > Tcp6StateEstablished ) { HttpCloseConnection(HttpInstance); } Status = HttpCreateConnection (HttpInstance); if (EFI_ERROR(Status)){ DEBUG ((EFI_D_ERROR, "Tcp6 Connection fail - %x\n", Status)); return Status; } // // Tls session connection. // if (HttpInstance->UseHttps) { if (HttpInstance->TimeoutEvent == NULL) { // // Create TimeoutEvent for TLS connection. // Status = gBS->CreateEvent ( EVT_TIMER, TPL_CALLBACK, NULL, NULL, &HttpInstance->TimeoutEvent ); if (EFI_ERROR (Status)) { TlsCloseTxRxEvent (HttpInstance); return Status; } } // // Start the timer, and wait Timeout seconds for connection. // Status = gBS->SetTimer (HttpInstance->TimeoutEvent, TimerRelative, HTTP_CONNECTION_TIMEOUT * TICKS_PER_SECOND); if (EFI_ERROR (Status)) { TlsCloseTxRxEvent (HttpInstance); return Status; } Status = TlsConnectSession (HttpInstance, HttpInstance->TimeoutEvent); gBS->SetTimer (HttpInstance->TimeoutEvent, TimerCancel, 0); if (EFI_ERROR (Status)) { TlsCloseTxRxEvent (HttpInstance); return Status; } } return Status; } /** Initialize Http session. @param[in] HttpInstance The HTTP instance private data. @param[in] Wrap The HTTP token's wrap data. @param[in] Configure The Flag indicates whether need to initialize session. @param[in] TlsConfigure The Flag indicates whether it's the new Tls session. @retval EFI_SUCCESS The initialization of session is done. @retval Others Other error as indicated. **/ EFI_STATUS HttpInitSession ( IN HTTP_PROTOCOL *HttpInstance, IN HTTP_TOKEN_WRAP *Wrap, IN BOOLEAN Configure, IN BOOLEAN TlsConfigure ) { EFI_STATUS Status; ASSERT (HttpInstance != NULL); // // Configure Tls session. // if (TlsConfigure) { Status = TlsConfigureSession (HttpInstance); if (EFI_ERROR (Status)) { return Status; } } if (!HttpInstance->LocalAddressIsIPv6) { // // Configure TCP instance. // if (Configure) { Status = HttpConfigureTcp4 (HttpInstance, Wrap); if (EFI_ERROR (Status)) { return Status; } } // // Connect TCP. // Status = HttpConnectTcp4 (HttpInstance); if (EFI_ERROR (Status)) { return Status; } } else { // // Configure TCP instance. // if (Configure) { Status = HttpConfigureTcp6 (HttpInstance, Wrap); if (EFI_ERROR (Status)) { return Status; } } // // Connect TCP. // Status = HttpConnectTcp6 (HttpInstance); if (EFI_ERROR (Status)) { return Status; } } return EFI_SUCCESS; } /** Send the HTTP or HTTPS message through TCP4 or TCP6. @param[in] HttpInstance The HTTP instance private data. @param[in] Wrap The HTTP token's wrap data. @param[in] TxString Buffer containing the HTTP message string. @param[in] TxStringLen Length of the HTTP message string in bytes. @retval EFI_SUCCESS The HTTP message is queued into TCP transmit queue. @retval Others Other error as indicated. **/ EFI_STATUS HttpTransmitTcp ( IN HTTP_PROTOCOL *HttpInstance, IN HTTP_TOKEN_WRAP *Wrap, IN UINT8 *TxString, IN UINTN TxStringLen ) { EFI_STATUS Status; EFI_TCP4_IO_TOKEN *Tx4Token; EFI_TCP4_PROTOCOL *Tcp4; EFI_TCP6_IO_TOKEN *Tx6Token; EFI_TCP6_PROTOCOL *Tcp6; UINT8 *TlsRecord; UINT16 PayloadSize; NET_FRAGMENT TempFragment; NET_FRAGMENT Fragment; UINTN RecordCount; UINTN RemainingLen; Status = EFI_SUCCESS; TlsRecord = NULL; PayloadSize = 0; TempFragment.Len = 0; TempFragment.Bulk = NULL; Fragment.Len = 0; Fragment.Bulk = NULL; RecordCount = 0; RemainingLen = 0; // // Need to encrypt data. // if (HttpInstance->UseHttps) { // // Allocate enough buffer for each TLS plaintext records. // TlsRecord = AllocateZeroPool (TLS_RECORD_HEADER_LENGTH + TLS_PLAINTEXT_RECORD_MAX_PAYLOAD_LENGTH); if (TlsRecord == NULL) { Status = EFI_OUT_OF_RESOURCES; return Status; } // // Allocate enough buffer for all TLS ciphertext records. // RecordCount = TxStringLen / TLS_PLAINTEXT_RECORD_MAX_PAYLOAD_LENGTH + 1; Fragment.Bulk = AllocateZeroPool (RecordCount * (TLS_RECORD_HEADER_LENGTH + TLS_CIPHERTEXT_RECORD_MAX_PAYLOAD_LENGTH)); if (Fragment.Bulk == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ON_ERROR; } // // Encrypt each TLS plaintext records. // RemainingLen = TxStringLen; while (RemainingLen != 0) { PayloadSize = (UINT16) MIN (TLS_PLAINTEXT_RECORD_MAX_PAYLOAD_LENGTH, RemainingLen); ((TLS_RECORD_HEADER *) TlsRecord)->ContentType = TlsContentTypeApplicationData; ((TLS_RECORD_HEADER *) TlsRecord)->Version.Major = HttpInstance->TlsConfigData.Version.Major; ((TLS_RECORD_HEADER *) TlsRecord)->Version.Minor = HttpInstance->TlsConfigData.Version.Minor; ((TLS_RECORD_HEADER *) TlsRecord)->Length = PayloadSize; CopyMem (TlsRecord + TLS_RECORD_HEADER_LENGTH, TxString + (TxStringLen - RemainingLen), PayloadSize); Status = TlsProcessMessage ( HttpInstance, TlsRecord, TLS_RECORD_HEADER_LENGTH + PayloadSize, EfiTlsEncrypt, &TempFragment ); if (EFI_ERROR (Status)) { goto ON_ERROR; } // // Record the processed/encrypted Packet. // CopyMem (Fragment.Bulk + Fragment.Len, TempFragment.Bulk, TempFragment.Len); Fragment.Len += TempFragment.Len; FreePool (TempFragment.Bulk); TempFragment.Len = 0; TempFragment.Bulk = NULL; RemainingLen -= (UINTN) PayloadSize; ZeroMem (TlsRecord, TLS_RECORD_HEADER_LENGTH + TLS_PLAINTEXT_RECORD_MAX_PAYLOAD_LENGTH); } FreePool (TlsRecord); TlsRecord = NULL; } if (!HttpInstance->LocalAddressIsIPv6) { Tcp4 = HttpInstance->Tcp4; Tx4Token = &Wrap->TcpWrap.Tx4Token; if (HttpInstance->UseHttps) { Tx4Token->Packet.TxData->DataLength = Fragment.Len; Tx4Token->Packet.TxData->FragmentTable[0].FragmentLength = Fragment.Len; Tx4Token->Packet.TxData->FragmentTable[0].FragmentBuffer = (VOID *) Fragment.Bulk; } else { Tx4Token->Packet.TxData->DataLength = (UINT32) TxStringLen; Tx4Token->Packet.TxData->FragmentTable[0].FragmentLength = (UINT32) TxStringLen; Tx4Token->Packet.TxData->FragmentTable[0].FragmentBuffer = (VOID *) TxString; } Tx4Token->CompletionToken.Status = EFI_NOT_READY; Wrap->TcpWrap.IsTxDone = FALSE; Status = Tcp4->Transmit (Tcp4, Tx4Token); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "Transmit failed: %r\n", Status)); goto ON_ERROR; } } else { Tcp6 = HttpInstance->Tcp6; Tx6Token = &Wrap->TcpWrap.Tx6Token; if (HttpInstance->UseHttps) { Tx6Token->Packet.TxData->DataLength = Fragment.Len; Tx6Token->Packet.TxData->FragmentTable[0].FragmentLength = Fragment.Len; Tx6Token->Packet.TxData->FragmentTable[0].FragmentBuffer = (VOID *) Fragment.Bulk; } else { Tx6Token->Packet.TxData->DataLength = (UINT32) TxStringLen; Tx6Token->Packet.TxData->FragmentTable[0].FragmentLength = (UINT32) TxStringLen; Tx6Token->Packet.TxData->FragmentTable[0].FragmentBuffer = (VOID *) TxString; } Tx6Token->CompletionToken.Status = EFI_NOT_READY; Wrap->TcpWrap.IsTxDone = FALSE; Status = Tcp6->Transmit (Tcp6, Tx6Token); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "Transmit failed: %r\n", Status)); goto ON_ERROR; } } return Status; ON_ERROR: if (HttpInstance->UseHttps) { if (TlsRecord != NULL) { FreePool (TlsRecord); TlsRecord = NULL; } if (Fragment.Bulk != NULL) { FreePool (Fragment.Bulk); Fragment.Bulk = NULL; } } return Status; } /** Check whether the user's token or event has already been enqueue on HTTP Tx or Rx Token list. @param[in] Map The container of either user's transmit or receive token. @param[in] Item Current item to check against. @param[in] Context The Token to check againist. @retval EFI_ACCESS_DENIED The token or event has already been enqueued in IP @retval EFI_SUCCESS The current item isn't the same token/event as the context. **/ EFI_STATUS EFIAPI HttpTokenExist ( IN NET_MAP *Map, IN NET_MAP_ITEM *Item, IN VOID *Context ) { EFI_HTTP_TOKEN *Token; EFI_HTTP_TOKEN *TokenInItem; Token = (EFI_HTTP_TOKEN *) Context; TokenInItem = (EFI_HTTP_TOKEN *) Item->Key; if (Token == TokenInItem || Token->Event == TokenInItem->Event) { return EFI_ACCESS_DENIED; } return EFI_SUCCESS; } /** Check whether the HTTP message associated with Tx4Token or Tx6Token is already sent out. @param[in] Map The container of Tx4Token or Tx6Token. @param[in] Item Current item to check against. @param[in] Context The Token to check againist. @retval EFI_NOT_READY The HTTP message is still queued in the list. @retval EFI_SUCCESS The HTTP message has been sent out. **/ EFI_STATUS EFIAPI HttpTcpNotReady ( IN NET_MAP *Map, IN NET_MAP_ITEM *Item, IN VOID *Context ) { HTTP_TOKEN_WRAP *ValueInItem; ValueInItem = (HTTP_TOKEN_WRAP *) Item->Value; if (!ValueInItem->TcpWrap.IsTxDone) { return EFI_NOT_READY; } return EFI_SUCCESS; } /** Transmit the HTTP or HTTPS mssage by processing the associated HTTP token. @param[in] Map The container of Tx4Token or Tx6Token. @param[in] Item Current item to check against. @param[in] Context The Token to check againist. @retval EFI_OUT_OF_RESOURCES Failed to allocate resources. @retval EFI_SUCCESS The HTTP message is queued into TCP transmit queue. **/ EFI_STATUS EFIAPI HttpTcpTransmit ( IN NET_MAP *Map, IN NET_MAP_ITEM *Item, IN VOID *Context ) { HTTP_TOKEN_WRAP *ValueInItem; EFI_STATUS Status; CHAR8 *RequestMsg; CHAR8 *Url; UINTN UrlSize; UINTN RequestMsgSize; RequestMsg = NULL; ValueInItem = (HTTP_TOKEN_WRAP *) Item->Value; if (ValueInItem->TcpWrap.IsTxDone) { return EFI_SUCCESS; } // // Parse the URI of the remote host. // UrlSize = StrLen (ValueInItem->HttpToken->Message->Data.Request->Url) + 1; Url = AllocatePool (UrlSize); if (Url == NULL) { return EFI_OUT_OF_RESOURCES; } UnicodeStrToAsciiStrS (ValueInItem->HttpToken->Message->Data.Request->Url, Url, UrlSize); // // Create request message. // Status = HttpGenRequestMessage ( ValueInItem->HttpToken->Message, Url, &RequestMsg, &RequestMsgSize ); FreePool (Url); if (EFI_ERROR (Status) || NULL == RequestMsg){ return Status; } ASSERT (RequestMsg != NULL); // // Transmit the request message. // Status = HttpTransmitTcp ( ValueInItem->HttpInstance, ValueInItem, (UINT8*) RequestMsg, RequestMsgSize ); FreePool (RequestMsg); return Status; } /** Receive the HTTP response by processing the associated HTTP token. @param[in] Map The container of Rx4Token or Rx6Token. @param[in] Item Current item to check against. @param[in] Context The Token to check againist. @retval EFI_SUCCESS The HTTP response is queued into TCP receive queue. @retval Others Other error as indicated. **/ EFI_STATUS EFIAPI HttpTcpReceive ( IN NET_MAP *Map, IN NET_MAP_ITEM *Item, IN VOID *Context ) { // // Process the queued HTTP response. // return HttpResponseWorker ((HTTP_TOKEN_WRAP *) Item->Value); } /** Receive the HTTP header by processing the associated HTTP token. @param[in] HttpInstance The HTTP instance private data. @param[in, out] SizeofHeaders The HTTP header length. @param[in, out] BufferSize The size of buffer to cacahe the header message. @param[in] Timeout The time to wait for receiving the header packet. @retval EFI_SUCCESS The HTTP header is received. @retval Others Other errors as indicated. **/ EFI_STATUS HttpTcpReceiveHeader ( IN HTTP_PROTOCOL *HttpInstance, IN OUT UINTN *SizeofHeaders, IN OUT UINTN *BufferSize, IN EFI_EVENT Timeout ) { EFI_STATUS Status; EFI_TCP4_IO_TOKEN *Rx4Token; EFI_TCP4_PROTOCOL *Tcp4; EFI_TCP6_IO_TOKEN *Rx6Token; EFI_TCP6_PROTOCOL *Tcp6; CHAR8 **EndofHeader; CHAR8 **HttpHeaders; CHAR8 *Buffer; NET_FRAGMENT Fragment; ASSERT (HttpInstance != NULL); EndofHeader = HttpInstance->EndofHeader; HttpHeaders = HttpInstance->HttpHeaders; Tcp4 = HttpInstance->Tcp4; Tcp6 = HttpInstance->Tcp6; Buffer = NULL; Rx4Token = NULL; Rx6Token = NULL; Fragment.Len = 0; Fragment.Bulk = NULL; if (HttpInstance->LocalAddressIsIPv6) { ASSERT (Tcp6 != NULL); } else { ASSERT (Tcp4 != NULL); } if (!HttpInstance->UseHttps) { Status = HttpCreateTcpRxEventForHeader (HttpInstance); if (EFI_ERROR (Status)) { return Status; } } if (!HttpInstance->LocalAddressIsIPv6) { if (!HttpInstance->UseHttps) { Rx4Token = &HttpInstance->Rx4Token; Rx4Token->Packet.RxData->FragmentTable[0].FragmentBuffer = AllocateZeroPool (DEF_BUF_LEN); if (Rx4Token->Packet.RxData->FragmentTable[0].FragmentBuffer == NULL) { Status = EFI_OUT_OF_RESOURCES; return Status; } } // // Receive the HTTP headers only when EFI_HTTP_RESPONSE_DATA is not NULL. // while (*EndofHeader == NULL) { if (!HttpInstance->UseHttps) { HttpInstance->IsRxDone = FALSE; Rx4Token->Packet.RxData->DataLength = DEF_BUF_LEN; Rx4Token->Packet.RxData->FragmentTable[0].FragmentLength = DEF_BUF_LEN; Status = Tcp4->Receive (Tcp4, Rx4Token); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "Tcp4 receive failed: %r\n", Status)); return Status; } while (!HttpInstance->IsRxDone && ((Timeout == NULL) || EFI_ERROR (gBS->CheckEvent (Timeout)))) { Tcp4->Poll (Tcp4); } if (!HttpInstance->IsRxDone) { // // Cancle the Token before close its Event. // Tcp4->Cancel (HttpInstance->Tcp4, &Rx4Token->CompletionToken); gBS->CloseEvent (Rx4Token->CompletionToken.Event); Rx4Token->CompletionToken.Status = EFI_TIMEOUT; } Status = Rx4Token->CompletionToken.Status; if (EFI_ERROR (Status)) { return Status; } Fragment.Len = Rx4Token->Packet.RxData->FragmentTable[0].FragmentLength; Fragment.Bulk = (UINT8 *) Rx4Token->Packet.RxData->FragmentTable[0].FragmentBuffer; } else { if (Fragment.Bulk != NULL) { FreePool (Fragment.Bulk); Fragment.Bulk = NULL; } Status = HttpsReceive (HttpInstance, &Fragment, Timeout); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "Tcp4 receive failed: %r\n", Status)); return Status; } } // // Append the response string along with a Null-terminator. // *BufferSize = *SizeofHeaders + Fragment.Len; Buffer = AllocatePool (*BufferSize + 1); if (Buffer == NULL) { Status = EFI_OUT_OF_RESOURCES; return Status; } if (*HttpHeaders != NULL) { CopyMem (Buffer, *HttpHeaders, *SizeofHeaders); FreePool (*HttpHeaders); } CopyMem ( Buffer + *SizeofHeaders, Fragment.Bulk, Fragment.Len ); *(Buffer + *BufferSize) = '\0'; *HttpHeaders = Buffer; *SizeofHeaders = *BufferSize; // // Check whether we received end of HTTP headers. // *EndofHeader = AsciiStrStr (*HttpHeaders, HTTP_END_OF_HDR_STR); }; // // Free the buffer. // if (Rx4Token != NULL && Rx4Token->Packet.RxData != NULL && Rx4Token->Packet.RxData->FragmentTable[0].FragmentBuffer != NULL) { FreePool (Rx4Token->Packet.RxData->FragmentTable[0].FragmentBuffer); Rx4Token->Packet.RxData->FragmentTable[0].FragmentBuffer = NULL; Fragment.Bulk = NULL; } if (Fragment.Bulk != NULL) { FreePool (Fragment.Bulk); Fragment.Bulk = NULL; } } else { if (!HttpInstance->UseHttps) { Rx6Token = &HttpInstance->Rx6Token; Rx6Token->Packet.RxData->FragmentTable[0].FragmentBuffer = AllocateZeroPool (DEF_BUF_LEN); if (Rx6Token->Packet.RxData->FragmentTable[0].FragmentBuffer == NULL) { Status = EFI_OUT_OF_RESOURCES; return Status; } } // // Receive the HTTP headers only when EFI_HTTP_RESPONSE_DATA is not NULL. // while (*EndofHeader == NULL) { if (!HttpInstance->UseHttps) { HttpInstance->IsRxDone = FALSE; Rx6Token->Packet.RxData->DataLength = DEF_BUF_LEN; Rx6Token->Packet.RxData->FragmentTable[0].FragmentLength = DEF_BUF_LEN; Status = Tcp6->Receive (Tcp6, Rx6Token); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "Tcp6 receive failed: %r\n", Status)); return Status; } while (!HttpInstance->IsRxDone && ((Timeout == NULL) || EFI_ERROR (gBS->CheckEvent (Timeout)))) { Tcp6->Poll (Tcp6); } if (!HttpInstance->IsRxDone) { // // Cancle the Token before close its Event. // Tcp6->Cancel (HttpInstance->Tcp6, &Rx6Token->CompletionToken); gBS->CloseEvent (Rx6Token->CompletionToken.Event); Rx6Token->CompletionToken.Status = EFI_TIMEOUT; } Status = Rx6Token->CompletionToken.Status; if (EFI_ERROR (Status)) { return Status; } Fragment.Len = Rx6Token->Packet.RxData->FragmentTable[0].FragmentLength; Fragment.Bulk = (UINT8 *) Rx6Token->Packet.RxData->FragmentTable[0].FragmentBuffer; } else { if (Fragment.Bulk != NULL) { FreePool (Fragment.Bulk); Fragment.Bulk = NULL; } Status = HttpsReceive (HttpInstance, &Fragment, Timeout); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "Tcp6 receive failed: %r\n", Status)); return Status; } } // // Append the response string along with a Null-terminator. // *BufferSize = *SizeofHeaders + Fragment.Len; Buffer = AllocatePool (*BufferSize + 1); if (Buffer == NULL) { Status = EFI_OUT_OF_RESOURCES; return Status; } if (*HttpHeaders != NULL) { CopyMem (Buffer, *HttpHeaders, *SizeofHeaders); FreePool (*HttpHeaders); } CopyMem ( Buffer + *SizeofHeaders, Fragment.Bulk, Fragment.Len ); *(Buffer + *BufferSize) = '\0'; *HttpHeaders = Buffer; *SizeofHeaders = *BufferSize; // // Check whether we received end of HTTP headers. // *EndofHeader = AsciiStrStr (*HttpHeaders, HTTP_END_OF_HDR_STR); }; // // Free the buffer. // if (Rx6Token != NULL && Rx6Token->Packet.RxData != NULL && Rx6Token->Packet.RxData->FragmentTable[0].FragmentBuffer != NULL) { FreePool (Rx6Token->Packet.RxData->FragmentTable[0].FragmentBuffer); Rx6Token->Packet.RxData->FragmentTable[0].FragmentBuffer = NULL; Fragment.Bulk = NULL; } if (Fragment.Bulk != NULL) { FreePool (Fragment.Bulk); Fragment.Bulk = NULL; } } // // Skip the CRLF after the HTTP headers. // *EndofHeader = *EndofHeader + AsciiStrLen (HTTP_END_OF_HDR_STR); *SizeofHeaders = *EndofHeader - *HttpHeaders; return EFI_SUCCESS; } /** Receive the HTTP body by processing the associated HTTP token. @param[in] Wrap The HTTP token's wrap data. @param[in] HttpMsg The HTTP message data. @retval EFI_SUCCESS The HTTP body is received. @retval Others Other error as indicated. **/ EFI_STATUS HttpTcpReceiveBody ( IN HTTP_TOKEN_WRAP *Wrap, IN EFI_HTTP_MESSAGE *HttpMsg ) { EFI_STATUS Status; HTTP_PROTOCOL *HttpInstance; EFI_TCP6_PROTOCOL *Tcp6; EFI_TCP6_IO_TOKEN *Rx6Token; EFI_TCP4_PROTOCOL *Tcp4; EFI_TCP4_IO_TOKEN *Rx4Token; HttpInstance = Wrap->HttpInstance; Tcp4 = HttpInstance->Tcp4; Tcp6 = HttpInstance->Tcp6; Rx4Token = NULL; Rx6Token = NULL; if (HttpInstance->LocalAddressIsIPv6) { ASSERT (Tcp6 != NULL); } else { ASSERT (Tcp4 != NULL); } if (HttpInstance->LocalAddressIsIPv6) { Rx6Token = &Wrap->TcpWrap.Rx6Token; Rx6Token ->Packet.RxData->DataLength = (UINT32) MIN (MAX_UINT32, HttpMsg->BodyLength); Rx6Token ->Packet.RxData->FragmentTable[0].FragmentLength = (UINT32) MIN (MAX_UINT32, HttpMsg->BodyLength); Rx6Token ->Packet.RxData->FragmentTable[0].FragmentBuffer = (VOID *) HttpMsg->Body; Rx6Token->CompletionToken.Status = EFI_NOT_READY; Status = Tcp6->Receive (Tcp6, Rx6Token); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "Tcp6 receive failed: %r\n", Status)); return Status; } } else { Rx4Token = &Wrap->TcpWrap.Rx4Token; Rx4Token->Packet.RxData->DataLength = (UINT32) MIN (MAX_UINT32, HttpMsg->BodyLength); Rx4Token->Packet.RxData->FragmentTable[0].FragmentLength = (UINT32) MIN (MAX_UINT32, HttpMsg->BodyLength); Rx4Token->Packet.RxData->FragmentTable[0].FragmentBuffer = (VOID *) HttpMsg->Body; Rx4Token->CompletionToken.Status = EFI_NOT_READY; Status = Tcp4->Receive (Tcp4, Rx4Token); if (EFI_ERROR (Status)) { DEBUG ((EFI_D_ERROR, "Tcp4 receive failed: %r\n", Status)); return Status; } } return EFI_SUCCESS; } /** Clean up Tcp Tokens while the Tcp transmission error occurs. @param[in] Wrap Pointer to HTTP token's wrap data. **/ VOID HttpTcpTokenCleanup ( IN HTTP_TOKEN_WRAP *Wrap ) { HTTP_PROTOCOL *HttpInstance; EFI_TCP4_IO_TOKEN *Rx4Token; EFI_TCP6_IO_TOKEN *Rx6Token; ASSERT (Wrap != NULL); HttpInstance = Wrap->HttpInstance; Rx4Token = NULL; Rx6Token = NULL; if (HttpInstance->LocalAddressIsIPv6) { Rx6Token = &Wrap->TcpWrap.Rx6Token; if (Rx6Token->CompletionToken.Event != NULL) { gBS->CloseEvent (Rx6Token->CompletionToken.Event); Rx6Token->CompletionToken.Event = NULL; } FreePool (Wrap); Rx6Token = &HttpInstance->Rx6Token; if (Rx6Token->CompletionToken.Event != NULL) { gBS->CloseEvent (Rx6Token->CompletionToken.Event); Rx6Token->CompletionToken.Event = NULL; } if (Rx6Token->Packet.RxData->FragmentTable[0].FragmentBuffer != NULL) { FreePool (Rx6Token->Packet.RxData->FragmentTable[0].FragmentBuffer); Rx6Token->Packet.RxData->FragmentTable[0].FragmentBuffer = NULL; } } else { Rx4Token = &Wrap->TcpWrap.Rx4Token; if (Rx4Token->CompletionToken.Event != NULL) { gBS->CloseEvent (Rx4Token->CompletionToken.Event); Rx4Token->CompletionToken.Event = NULL; } FreePool (Wrap); Rx4Token = &HttpInstance->Rx4Token; if (Rx4Token->CompletionToken.Event != NULL) { gBS->CloseEvent (Rx4Token->CompletionToken.Event); Rx4Token->CompletionToken.Event = NULL; } if (Rx4Token->Packet.RxData->FragmentTable[0].FragmentBuffer != NULL) { FreePool (Rx4Token->Packet.RxData->FragmentTable[0].FragmentBuffer); Rx4Token->Packet.RxData->FragmentTable[0].FragmentBuffer = NULL; } } }
801df44dc727e33a0626e9d4ef7a44c39ea660d3
7547d54f6f5f231fdd23a235b3c06bf80a6365df
/ext/polyphony/backend_common.h
7c09d5c577646dd9a487c4283b3623cff67462fb
[ "MIT" ]
permissive
digital-fabric/polyphony
fed42f534dc4e72ec3b4de60c998fa4ec904795c
77b4e264344ef82ab5a31ebaa832a25489b26cda
refs/heads/master
2023-08-09T06:58:33.581327
2023-08-06T07:19:49
2023-08-06T07:19:49
145,374,867
624
18
MIT
2023-08-06T08:07:26
2018-08-20T06:22:07
C
UTF-8
C
false
false
5,262
h
backend_common.h
#ifndef BACKEND_COMMON_H #define BACKEND_COMMON_H #include <sys/types.h> #ifdef POLYPHONY_WINDOWS #include <winsock2.h> #else #include <arpa/inet.h> #include <netinet/in.h> #include <netdb.h> #include <sys/socket.h> #endif #include "ruby.h" #include "ruby/io.h" #include "runqueue.h" extern VALUE cBackend; #ifndef HAVE_RB_IO_DESCRIPTOR static int rb_io_descriptor_fallback(VALUE io) { rb_io_t *fptr; GetOpenFile(io, fptr); return fptr->fd; } #define rb_io_descriptor rb_io_descriptor_fallback #endif struct backend_stats { unsigned int runqueue_size; unsigned int runqueue_length; unsigned int runqueue_max_length; unsigned int op_count; unsigned int switch_count; unsigned int poll_count; unsigned int pending_ops; }; struct Backend_base { runqueue_t runqueue; runqueue_t parked_runqueue; unsigned int currently_polling; unsigned int op_count; unsigned int switch_count; unsigned int poll_count; unsigned int pending_count; double idle_gc_period; double idle_gc_last_time; VALUE idle_proc; VALUE trace_proc; unsigned int in_trace_proc; }; void backend_base_initialize(struct Backend_base *base); void backend_base_finalize(struct Backend_base *base); void backend_base_mark(struct Backend_base *base); void backend_base_reset(struct Backend_base *base); VALUE backend_base_switch_fiber(VALUE backend, struct Backend_base *base); void backend_base_schedule_fiber(VALUE thread, VALUE backend, struct Backend_base *base, VALUE fiber, VALUE value, int prioritize); void backend_base_park_fiber(struct Backend_base *base, VALUE fiber); void backend_base_unpark_fiber(struct Backend_base *base, VALUE fiber); void backend_trace(struct Backend_base *base, int argc, VALUE *argv); struct backend_stats backend_base_stats(struct Backend_base *base); // tracing #define SHOULD_TRACE(base) ((base)->trace_proc != Qnil && !(base)->in_trace_proc) #define TRACE(base, ...) { \ (base)->in_trace_proc = 1; \ rb_funcall((base)->trace_proc, ID_call, __VA_ARGS__); \ (base)->in_trace_proc = 0; \ } #define COND_TRACE(base, ...) if (SHOULD_TRACE(base)) { TRACE(base, __VA_ARGS__); } // buffers struct buffer_spec { unsigned char *ptr; int len; }; struct backend_buffer_spec { unsigned char *ptr; int len; int raw; int pos; int expandable:1; int shrinkable:1; int reserved:30; }; #define FIX2PTR(v) ((void *)(FIX2LONG(v))) #define PTR2FIX(p) LONG2FIX((long)p) struct backend_buffer_spec backend_get_buffer_spec(VALUE in, int rw); void backend_prepare_read_buffer(VALUE buffer, VALUE length, struct backend_buffer_spec *buffer_spec, int pos); void backend_grow_string_buffer(VALUE buffer, struct backend_buffer_spec *buffer_spec, int total); void backend_finalize_string_buffer(VALUE buffer, struct backend_buffer_spec *buffer_spec, int total, rb_io_t *fptr); VALUE coerce_io_string_or_buffer(VALUE buf); #ifdef POLYPHONY_USE_PIDFD_OPEN int pidfd_open(pid_t pid, unsigned int flags); #endif ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // the following is copied verbatim from the Ruby source code (io.c) struct io_internal_read_struct { int fd; int nonblock; void *buf; size_t capa; }; #define StringValue(v) rb_string_value(&(v)) int io_setstrbuf(VALUE *str, long len); void io_shrink_read_string(VALUE str, long n); void io_set_read_length(VALUE str, long n, int shrinkable); rb_encoding* io_read_encoding(rb_io_t *fptr); VALUE io_enc_str(VALUE str, rb_io_t *fptr); void fptr_finalize(rb_io_t *fptr); ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// struct backend_stats backend_get_stats(VALUE self); VALUE backend_await(struct Backend_base *backend); VALUE backend_snooze(struct Backend_base *backend); // macros for doing read loops #define READ_LOOP_PREPARE_STR() { \ buffer = Qnil; \ shrinkable = io_setstrbuf(&buffer, len); \ ptr = RSTRING_PTR(buffer); \ total = 0; \ } #define READ_LOOP_YIELD_STR() { \ io_set_read_length(buffer, total, shrinkable); \ if (fptr) io_enc_str(buffer, fptr); \ rb_yield(buffer); \ READ_LOOP_PREPARE_STR(); \ } #define READ_LOOP_PASS_STR_TO_RECEIVER(receiver, method_id) { \ io_set_read_length(buffer, total, shrinkable); \ if (fptr) io_enc_str(buffer, fptr); \ rb_funcall_passing_block(receiver, method_id, 1, &buffer); \ READ_LOOP_PREPARE_STR(); \ } void rectify_io_file_pos(rb_io_t *fptr); double current_time(); uint64_t current_time_ns(); VALUE backend_timeout_exception(VALUE exception); VALUE Backend_timeout_ensure_safe(VALUE arg); VALUE Backend_timeout_ensure_safe(VALUE arg); VALUE Backend_sendv(VALUE self, VALUE io, VALUE ary, VALUE flags); VALUE Backend_stats(VALUE self); VALUE Backend_verify_blocking_mode(VALUE self, VALUE io, VALUE blocking); void backend_run_idle_tasks(struct Backend_base *base); void set_fd_blocking_mode(int fd, int blocking); void io_verify_blocking_mode(VALUE io, int fd, VALUE blocking); void backend_setup_stats_symbols(); int backend_getaddrinfo(VALUE host, VALUE port, struct sockaddr **ai_addr); VALUE name_to_addrinfo(void *name, socklen_t len); #endif /* BACKEND_COMMON_H */
c80890af7996566e4e30eea8d89cfaf687485710
a0838b4cd2ce8a2862a6a82dc2e75a701447c28b
/components/encoder/encoder.h
1268e983b51ff83999a862bcc8eb68d3efc3beef
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
UncleRus/esp-idf-lib
bfa97226f6df9313dd01f56de1b8bef1824ad642
9dd86b23aff2445b905da63d3c6481474e430a10
refs/heads/master
2023-08-31T06:04:48.102658
2023-08-30T15:57:59
2023-08-30T15:57:59
126,475,029
1,117
394
null
2023-09-01T06:25:56
2018-03-23T11:17:22
C
UTF-8
C
false
false
3,805
h
encoder.h
/* * Copyright (c) 2019 Ruslan V. Uss <unclerus@gmail.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the copyright holder nor the names of itscontributors * 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. */ /** * @file encoder.h * @defgroup encoder encoder * @{ * * ESP-IDF HW timer-based driver for rotary encoders * * Copyright (c) 2019 Ruslan V. Uss <unclerus@gmail.com> * * BSD Licensed as described in the file LICENSE */ #ifndef __ENCODER_H__ #define __ENCODER_H__ #include <esp_err.h> #include <driver/gpio.h> #include <freertos/FreeRTOS.h> #include <freertos/queue.h> #ifdef __cplusplus extern "C" { #endif /** * Button state */ typedef enum { RE_BTN_RELEASED = 0, //!< Button currently released RE_BTN_PRESSED = 1, //!< Button currently pressed RE_BTN_LONG_PRESSED = 2 //!< Button currently long pressed } rotary_encoder_btn_state_t; /** * Rotary encoder descriptor */ typedef struct { gpio_num_t pin_a, pin_b, pin_btn; //!< Encoder pins. pin_btn can be >= GPIO_NUM_MAX if no button used uint8_t code; uint16_t store; size_t index; uint64_t btn_pressed_time_us; rotary_encoder_btn_state_t btn_state; } rotary_encoder_t; /** * Event type */ typedef enum { RE_ET_CHANGED = 0, //!< Encoder turned RE_ET_BTN_RELEASED, //!< Button released RE_ET_BTN_PRESSED, //!< Button pressed RE_ET_BTN_LONG_PRESSED, //!< Button long pressed (press time (us) > RE_BTN_LONG_PRESS_TIME_US) RE_ET_BTN_CLICKED //!< Button was clicked } rotary_encoder_event_type_t; /** * Event */ typedef struct { rotary_encoder_event_type_t type; //!< Event type rotary_encoder_t *sender; //!< Pointer to descriptor int32_t diff; //!< Difference between new and old positions (only if type == RE_ET_CHANGED) } rotary_encoder_event_t; /** * @brief Initialize library * * @param queue Event queue to send encoder events * @return `ESP_OK` on success */ esp_err_t rotary_encoder_init(QueueHandle_t queue); /** * @brief Add new rotary encoder * * @param re Encoder descriptor * @return `ESP_OK` on success */ esp_err_t rotary_encoder_add(rotary_encoder_t *re); /** * @brief Remove previously added rotary encoder * * @param re Encoder descriptor * @return `ESP_OK` on success */ esp_err_t rotary_encoder_remove(rotary_encoder_t *re); #ifdef __cplusplus } #endif /**@}*/ #endif /* __ENCODER_H__ */
24cf4ce9f678338dd05d838b8f8578f6ccc387c2
fa1a4c9c404b20cac10f537c419489ed8bb84ede
/examples/hello-getchar.c
5e5053a2c3127230d67604e130bf7981ebf45fae
[ "LLVM-exception", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
llvm-mos/llvm-mos-sdk
cff8ec1780b5c79b63649ba567acb7cd271f0c32
18e0edd90648f67717b26f99559dae408eaa8b32
refs/heads/main
2023-08-31T15:47:28.907521
2023-08-29T16:40:59
2023-08-29T17:31:04
348,140,902
170
37
NOASSERTION
2023-09-14T19:46:55
2021-03-15T22:30:33
C
UTF-8
C
false
false
1,016
c
hello-getchar.c
#include <stdint.h> #include <stdio.h> #include <string.h> int main(void) { static char last_input_line[81]; uint8_t in_end = 0; static const char *EXIT_TOKEN = "SOME INPUT"; const unsigned char EXIT_TOKEN_LEN = strlen(EXIT_TOKEN); char eof = 0; while (!eof) { puts("ENTER SOME INPUT:"); putchar('>'); putchar(' '); in_end = 0; for (;;) { const int input = getchar(); if (input == EOF) { eof = 1; break; } putchar(input); if (input == '\n') { break; } last_input_line[in_end++] = input; // null terminate at the end of the buffer last_input_line[in_end] = 0; // exit loop before the last byte is used in the buffer. Reserve the last // byte for null termination. if (in_end == sizeof(last_input_line) - 1) { break; } } if (in_end >= EXIT_TOKEN_LEN && strncmp(EXIT_TOKEN, last_input_line, EXIT_TOKEN_LEN) == 0) { break; } } return 0; }
5e09b9f29486052abc7b7e459810f8ac0583924c
1efd2de8bf77ec00eb2fcaf5749278495946d920
/src/common/tests/prop_tests.c
2bdbff433a78079fa78e7446b1412a8896afb657
[ "BSD-2-Clause", "BSD-2-Clause-Patent" ]
permissive
daos-stack/daos
6f55bf3061fd830d5b8d28506e1295e2d3a27c38
ed5eed5df43a68571afe123132a743824c02637a
refs/heads/master
2023-08-31T21:43:37.606145
2023-08-31T16:38:00
2023-08-31T16:38:00
69,390,670
631
300
NOASSERTION
2023-09-14T18:55:15
2016-09-27T19:21:29
C
UTF-8
C
false
false
11,833
c
prop_tests.c
/* * (C) Copyright 2020-2022 Intel Corporation. * * SPDX-License-Identifier: BSD-2-Clause-Patent */ /** * Unit tests for the DAOS property API */ #include <stdarg.h> #include <stdlib.h> #include <setjmp.h> #include <cmocka.h> #include <daos/tests_lib.h> #include <daos_prop.h> #include <daos/common.h> static void test_daos_prop_merge_null(void **state) { daos_prop_t *prop; prop = daos_prop_alloc(0); assert_null(daos_prop_merge(prop, NULL)); assert_null(daos_prop_merge(NULL, prop)); daos_prop_free(prop); } static void expect_merge_result(daos_prop_t *old, daos_prop_t *new, daos_prop_t *exp_result) { daos_prop_t *result; struct daos_prop_entry *entry; struct daos_prop_entry *exp_entry; uint32_t i; result = daos_prop_merge(old, new); assert_non_null(result); assert_int_equal(result->dpp_nr, exp_result->dpp_nr); for (i = 0; i < exp_result->dpp_nr; i++) { /* * This check is agnostic to the order of the properties. */ exp_entry = &exp_result->dpp_entries[i]; printf("- Checking for property type %u\n", exp_entry->dpe_type); entry = daos_prop_entry_get(result, exp_entry->dpe_type); assert_non_null(entry); switch (entry->dpe_type) { case DAOS_PROP_PO_LABEL: case DAOS_PROP_CO_LABEL: case DAOS_PROP_PO_OWNER: case DAOS_PROP_CO_OWNER: case DAOS_PROP_PO_OWNER_GROUP: case DAOS_PROP_CO_OWNER_GROUP: case DAOS_PROP_PO_POLICY: assert_string_equal(entry->dpe_str, exp_entry->dpe_str); break; case DAOS_PROP_PO_ACL: case DAOS_PROP_CO_ACL: assert_rc_equal(daos_prop_entry_cmp_acl(entry, exp_entry), 0); break; default: assert_int_equal(entry->dpe_val, exp_entry->dpe_val); break; }; } daos_prop_free(result); } static void test_daos_prop_merge_empty(void **state) { daos_prop_t *prop_empty; daos_prop_t *prop; prop_empty = daos_prop_alloc(0); prop = daos_prop_alloc(2); prop->dpp_entries[0].dpe_type = DAOS_PROP_PO_LABEL; D_STRNDUP_S(prop->dpp_entries[0].dpe_str, "Test"); prop->dpp_entries[1].dpe_type = DAOS_PROP_PO_RECLAIM; prop->dpp_entries[1].dpe_val = DAOS_RECLAIM_LAZY; printf("Case: Two empty props\n"); expect_merge_result(prop_empty, prop_empty, prop_empty); printf("Case: Add empty to non-empty\n"); expect_merge_result(prop, prop_empty, prop); printf("Case: Add non-empty to empty\n"); expect_merge_result(prop_empty, prop, prop); daos_prop_free(prop_empty); daos_prop_free(prop); } static void test_daos_prop_merge_add_only(void **state) { daos_prop_t *prop1; daos_prop_t *prop2; uint32_t exp_nr, i, result_i; daos_prop_t *exp_result; prop1 = daos_prop_alloc(2); prop1->dpp_entries[0].dpe_type = DAOS_PROP_CO_LABEL; D_STRNDUP_S(prop1->dpp_entries[0].dpe_str, "Test"); prop1->dpp_entries[1].dpe_type = DAOS_PROP_CO_COMPRESS; prop1->dpp_entries[1].dpe_val = 1; prop2 = daos_prop_alloc(3); prop2->dpp_entries[0].dpe_type = DAOS_PROP_CO_OWNER; D_STRNDUP_S(prop2->dpp_entries[0].dpe_str, "test@"); prop2->dpp_entries[1].dpe_type = DAOS_PROP_CO_CSUM; prop2->dpp_entries[1].dpe_val = DAOS_PROP_CO_CSUM_CRC32; prop2->dpp_entries[2].dpe_type = DAOS_PROP_CO_ENCRYPT; prop2->dpp_entries[2].dpe_val = 1; /* Should be set of all the prop entries, no conflicts */ exp_nr = prop1->dpp_nr + prop2->dpp_nr; exp_result = daos_prop_alloc(exp_nr); result_i = 0; for (i = 0; i < prop1->dpp_nr; i++, result_i++) daos_prop_entry_copy(&prop1->dpp_entries[i], &exp_result->dpp_entries[result_i]); for (i = 0; i < prop2->dpp_nr; i++, result_i++) daos_prop_entry_copy(&prop2->dpp_entries[i], &exp_result->dpp_entries[result_i]); expect_merge_result(prop1, prop2, exp_result); daos_prop_free(prop1); daos_prop_free(prop2); daos_prop_free(exp_result); } static void test_daos_prop_merge_total_update(void **state) { daos_prop_t *prop1; daos_prop_t *prop2; prop1 = daos_prop_alloc(2); prop1->dpp_entries[0].dpe_type = DAOS_PROP_CO_LABEL; D_STRNDUP_S(prop1->dpp_entries[0].dpe_str, "Test"); prop1->dpp_entries[1].dpe_type = DAOS_PROP_CO_COMPRESS; prop1->dpp_entries[1].dpe_val = 1; prop2 = daos_prop_alloc(2); prop2->dpp_entries[0].dpe_type = DAOS_PROP_CO_LABEL; D_STRNDUP_S(prop2->dpp_entries[0].dpe_str, "Updated"); prop2->dpp_entries[1].dpe_type = DAOS_PROP_CO_COMPRESS; prop2->dpp_entries[1].dpe_val = 0; /* Expecting all props to be overwritten */ expect_merge_result(prop1, prop2, prop2); daos_prop_free(prop1); daos_prop_free(prop2); } static void test_daos_prop_merge_subset_update(void **state) { daos_prop_t *prop1; daos_prop_t *prop2; daos_prop_t *exp_result; struct daos_prop_entry *entry; prop1 = daos_prop_alloc(2); prop1->dpp_entries[0].dpe_type = DAOS_PROP_CO_LABEL; D_STRNDUP_S(prop1->dpp_entries[0].dpe_str, "Test"); prop1->dpp_entries[1].dpe_type = DAOS_PROP_CO_COMPRESS; prop1->dpp_entries[1].dpe_val = 1; prop2 = daos_prop_alloc(1); prop2->dpp_entries[0].dpe_type = DAOS_PROP_CO_LABEL; D_STRNDUP_S(prop2->dpp_entries[0].dpe_str, "Updated"); /* Expecting only one prop to be overwritten */ exp_result = daos_prop_dup(prop1, false /* pool */, true /* input */); entry = daos_prop_entry_get(exp_result, prop2->dpp_entries[0].dpe_type); assert_int_equal(daos_prop_entry_copy(&prop2->dpp_entries[0], entry), 0); expect_merge_result(prop1, prop2, exp_result); daos_prop_free(prop1); daos_prop_free(prop2); daos_prop_free(exp_result); } static void test_daos_prop_merge_add_and_update(void **state) { daos_prop_t *prop1; daos_prop_t *prop2; uint32_t exp_nr; uint32_t i, result_i; uint32_t new_idx, dup_idx; daos_prop_t *exp_result; struct daos_prop_entry *entry; prop1 = daos_prop_alloc(2); prop1->dpp_entries[0].dpe_type = DAOS_PROP_CO_LABEL; D_STRNDUP_S(prop1->dpp_entries[0].dpe_str, "Test"); prop1->dpp_entries[1].dpe_type = DAOS_PROP_CO_COMPRESS; prop1->dpp_entries[1].dpe_val = 1; prop2 = daos_prop_alloc(2); dup_idx = 0; /* duplicate type to what's in prop1 */ prop2->dpp_entries[dup_idx].dpe_type = DAOS_PROP_CO_LABEL; D_STRNDUP_S(prop2->dpp_entries[dup_idx].dpe_str, "Updated"); new_idx = 1; /* type that isn't in prop1 */ prop2->dpp_entries[1].dpe_type = DAOS_PROP_CO_CSUM; prop2->dpp_entries[1].dpe_val = DAOS_PROP_CO_CSUM_CRC32; /* Expecting duplicate prop to be overwritten, and new to be added */ exp_nr = prop1->dpp_nr + prop2->dpp_nr - 1; exp_result = daos_prop_alloc(exp_nr); result_i = 0; for (i = 0; i < prop1->dpp_nr; i++, result_i++) { entry = &exp_result->dpp_entries[result_i]; assert_rc_equal(daos_prop_entry_copy(&prop1->dpp_entries[i], entry), 0); } entry = &exp_result->dpp_entries[result_i]; assert_rc_equal(daos_prop_entry_copy(&prop2->dpp_entries[new_idx], entry), 0); result_i++; assert_int_equal(result_i, exp_nr); /* Overwrite the entry prop2 is duplicating */ entry = daos_prop_entry_get(exp_result, prop2->dpp_entries[dup_idx].dpe_type); assert_rc_equal(daos_prop_entry_copy(&prop2->dpp_entries[dup_idx], entry), 0); expect_merge_result(prop1, prop2, exp_result); daos_prop_free(prop1); daos_prop_free(prop2); daos_prop_free(exp_result); } static void test_daos_prop_from_str(void **state) { /** Valid prop entries & values */ char *LABEL = "label:hello"; char *CSUM = "cksum:crc64"; char *CSUM_SIZE = "cksum_size:1048576"; char *DEDUP = "dedup:hash"; char *DEDUP_TH = "dedup_threshold:8192"; char *COMP = "compression:lz4"; char *ENC = "encryption:aes-xts128"; char *RF = "rd_fac:2"; char *RF_OLD = "rf:2"; char *EC_CELL = "ec_cell_sz:2021"; char *EC_PDA = "ec_pda:1"; char *RP_PDA = "rp_pda:4"; /** Valid prop entries, wrong values */ char *CSUM_INV = "cksum:crc2000"; char *RF_INV = "rd_fac:64"; char *RF_OLD_INV = "rf:64"; /** Read only props, that should not be parsed */ char *OID = "alloc_oid:25"; char *LAYOUT = "layout_type:posix"; /** Invalid prop entries */ char *PROP_INV1 = "hello:world"; char *PROP_INV2 = "helloworld"; char *PROP_INV3 = ":helloworld"; char *PROP_INV4 = "helloworld:"; char buf[1024] = {0}; daos_prop_t *prop; struct daos_prop_entry *entry; int rc; rc = daos_prop_from_str(NULL, sizeof(buf), &prop); assert_int_equal(rc, -DER_INVAL); rc = daos_prop_from_str(buf, sizeof(buf), NULL); assert_int_equal(rc, -DER_INVAL); rc = daos_prop_from_str(buf, 0, &prop); assert_int_equal(rc, -DER_INVAL); /** Buffer containing read only entries should fail */ sprintf(buf, "%s;%s", CSUM, OID); rc = daos_prop_from_str(buf, sizeof(buf), &prop); assert_int_equal(rc, -DER_INVAL); sprintf(buf, "%s;%s", CSUM, LAYOUT); rc = daos_prop_from_str(buf, sizeof(buf), &prop); assert_int_equal(rc, -DER_INVAL); /** Buffer containing invalid entries should fail */ sprintf(buf, "%s;%s;%s", CSUM, LABEL, PROP_INV1); rc = daos_prop_from_str(buf, sizeof(buf), &prop); assert_int_equal(rc, -DER_INVAL); sprintf(buf, "%s;%s;%s", CSUM, LABEL, PROP_INV2); rc = daos_prop_from_str(buf, sizeof(buf), &prop); assert_int_equal(rc, -DER_INVAL); sprintf(buf, "%s;%s;%s", CSUM, LABEL, PROP_INV3); rc = daos_prop_from_str(buf, sizeof(buf), &prop); assert_int_equal(rc, -DER_INVAL); sprintf(buf, "%s;%s;%s", CSUM, LABEL, PROP_INV4); rc = daos_prop_from_str(buf, sizeof(buf), &prop); assert_int_equal(rc, -DER_INVAL); /** Buffer containing invalid values should fail */ sprintf(buf, "%s;%s", CSUM_INV, RF); rc = daos_prop_from_str(buf, sizeof(buf), &prop); assert_int_equal(rc, -DER_INVAL); sprintf(buf, "%s;%s", CSUM_INV, RF_OLD); rc = daos_prop_from_str(buf, sizeof(buf), &prop); assert_int_equal(rc, -DER_INVAL); sprintf(buf, "%s;%s", CSUM, RF_INV); rc = daos_prop_from_str(buf, sizeof(buf), &prop); assert_int_equal(rc, -DER_INVAL); sprintf(buf, "%s;%s", CSUM, RF_OLD_INV); rc = daos_prop_from_str(buf, sizeof(buf), &prop); assert_int_equal(rc, -DER_INVAL); sprintf(buf, "%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s", LABEL, CSUM, CSUM_SIZE, DEDUP, DEDUP_TH, COMP, ENC, RF, EC_CELL, EC_PDA, RP_PDA); rc = daos_prop_from_str(buf, sizeof(buf), &prop); assert_int_equal(rc, 0); /** verify entry values */ entry = daos_prop_entry_get(prop, DAOS_PROP_CO_LABEL); assert_string_equal(entry->dpe_str, "hello"); entry = daos_prop_entry_get(prop, DAOS_PROP_CO_CSUM); assert_int_equal(entry->dpe_val, DAOS_PROP_CO_CSUM_CRC64); entry = daos_prop_entry_get(prop, DAOS_PROP_CO_CSUM_CHUNK_SIZE); assert_int_equal(entry->dpe_val, 1048576); entry = daos_prop_entry_get(prop, DAOS_PROP_CO_DEDUP); assert_int_equal(entry->dpe_val, DAOS_PROP_CO_DEDUP_HASH); entry = daos_prop_entry_get(prop, DAOS_PROP_CO_DEDUP_THRESHOLD); assert_int_equal(entry->dpe_val, 8192); entry = daos_prop_entry_get(prop, DAOS_PROP_CO_COMPRESS); assert_int_equal(entry->dpe_val, DAOS_PROP_CO_COMPRESS_LZ4); entry = daos_prop_entry_get(prop, DAOS_PROP_CO_ENCRYPT); assert_int_equal(entry->dpe_val, DAOS_PROP_CO_ENCRYPT_AES_XTS128); entry = daos_prop_entry_get(prop, DAOS_PROP_CO_REDUN_FAC); assert_int_equal(entry->dpe_val, DAOS_PROP_CO_REDUN_RF2); entry = daos_prop_entry_get(prop, DAOS_PROP_CO_EC_CELL_SZ); assert_int_equal(entry->dpe_val, 2021); entry = daos_prop_entry_get(prop, DAOS_PROP_CO_EC_PDA); assert_int_equal(entry->dpe_val, 1); entry = daos_prop_entry_get(prop, DAOS_PROP_CO_RP_PDA); assert_int_equal(entry->dpe_val, 4); daos_prop_free(prop); } int main(void) { const struct CMUnitTest tests[] = { cmocka_unit_test(test_daos_prop_merge_null), cmocka_unit_test(test_daos_prop_merge_empty), cmocka_unit_test(test_daos_prop_merge_add_only), cmocka_unit_test(test_daos_prop_merge_total_update), cmocka_unit_test(test_daos_prop_merge_subset_update), cmocka_unit_test(test_daos_prop_merge_add_and_update), cmocka_unit_test(test_daos_prop_from_str), }; return cmocka_run_group_tests_name("common_prop", tests, NULL, NULL); }
08ba7624ff1aa82039273846bdd32fd832df9e43
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/media/usb/b2c2/flexcop-usb.c
8b6275f859088d703fcc2893412dfe5c4ccd58b8
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
15,969
c
flexcop-usb.c
/* * Linux driver for digital TV devices equipped with B2C2 FlexcopII(b)/III * flexcop-usb.c - covers the USB part * see flexcop.c for copyright information */ #define FC_LOG_PREFIX "flexcop_usb" #include "flexcop-usb.h" #include "flexcop-common.h" /* Version information */ #define DRIVER_VERSION "0.1" #define DRIVER_NAME "Technisat/B2C2 FlexCop II/IIb/III Digital TV USB Driver" #define DRIVER_AUTHOR "Patrick Boettcher <patrick.boettcher@desy.de>" /* debug */ #ifdef CONFIG_DVB_B2C2_FLEXCOP_DEBUG #define dprintk(level,args...) \ do { if ((debug & level)) printk(args); } while (0) #define debug_dump(b, l, method) do {\ int i; \ for (i = 0; i < l; i++) \ method("%02x ", b[i]); \ method("\n"); \ } while (0) #define DEBSTATUS "" #else #define dprintk(level, args...) #define debug_dump(b, l, method) #define DEBSTATUS " (debugging is not enabled)" #endif static int debug; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "set debugging level (1=info,ts=2," "ctrl=4,i2c=8,v8mem=16 (or-able))." DEBSTATUS); #undef DEBSTATUS #define deb_info(args...) dprintk(0x01, args) #define deb_ts(args...) dprintk(0x02, args) #define deb_ctrl(args...) dprintk(0x04, args) #define deb_i2c(args...) dprintk(0x08, args) #define deb_v8(args...) dprintk(0x10, args) /* JLP 111700: we will include the 1 bit gap between the upper and lower 3 bits * in the IBI address, to make the V8 code simpler. * PCI ADDRESS FORMAT: 0x71C -> 0000 0111 0001 1100 (the six bits used) * in general: 0000 0HHH 000L LL00 * IBI ADDRESS FORMAT: RHHH BLLL * * where R is the read(1)/write(0) bit, B is the busy bit * and HHH and LLL are the two sets of three bits from the PCI address. */ #define B2C2_FLEX_PCIOFFSET_TO_INTERNALADDR(usPCI) (u8) \ (((usPCI >> 2) & 0x07) + ((usPCI >> 4) & 0x70)) #define B2C2_FLEX_INTERNALADDR_TO_PCIOFFSET(ucAddr) (u16) \ (((ucAddr & 0x07) << 2) + ((ucAddr & 0x70) << 4)) /* * DKT 020228 * - forget about this VENDOR_BUFFER_SIZE, read and write register * deal with DWORD or 4 bytes, that should be should from now on * - from now on, we don't support anything older than firm 1.00 * I eliminated the write register as a 2 trip of writing hi word and lo word * and force this to write only 4 bytes at a time. * NOTE: this should work with all the firmware from 1.00 and newer */ static int flexcop_usb_readwrite_dw(struct flexcop_device *fc, u16 wRegOffsPCI, u32 *val, u8 read) { struct flexcop_usb *fc_usb = fc->bus_specific; u8 request = read ? B2C2_USB_READ_REG : B2C2_USB_WRITE_REG; u8 request_type = (read ? USB_DIR_IN : USB_DIR_OUT) | USB_TYPE_VENDOR; u8 wAddress = B2C2_FLEX_PCIOFFSET_TO_INTERNALADDR(wRegOffsPCI) | (read ? 0x80 : 0); int len = usb_control_msg(fc_usb->udev, read ? B2C2_USB_CTRL_PIPE_IN : B2C2_USB_CTRL_PIPE_OUT, request, request_type, /* 0xc0 read or 0x40 write */ wAddress, 0, val, sizeof(u32), B2C2_WAIT_FOR_OPERATION_RDW * HZ); if (len != sizeof(u32)) { err("error while %s dword from %d (%d).", read ? "reading" : "writing", wAddress, wRegOffsPCI); return -EIO; } return 0; } /* * DKT 010817 - add support for V8 memory read/write and flash update */ static int flexcop_usb_v8_memory_req(struct flexcop_usb *fc_usb, flexcop_usb_request_t req, u8 page, u16 wAddress, u8 *pbBuffer, u32 buflen) { u8 request_type = USB_TYPE_VENDOR; u16 wIndex; int nWaitTime, pipe, len; wIndex = page << 8; switch (req) { case B2C2_USB_READ_V8_MEM: nWaitTime = B2C2_WAIT_FOR_OPERATION_V8READ; request_type |= USB_DIR_IN; pipe = B2C2_USB_CTRL_PIPE_IN; break; case B2C2_USB_WRITE_V8_MEM: wIndex |= pbBuffer[0]; request_type |= USB_DIR_OUT; nWaitTime = B2C2_WAIT_FOR_OPERATION_V8WRITE; pipe = B2C2_USB_CTRL_PIPE_OUT; break; case B2C2_USB_FLASH_BLOCK: request_type |= USB_DIR_OUT; nWaitTime = B2C2_WAIT_FOR_OPERATION_V8FLASH; pipe = B2C2_USB_CTRL_PIPE_OUT; break; default: deb_info("unsupported request for v8_mem_req %x.\n", req); return -EINVAL; } deb_v8("v8mem: %02x %02x %04x %04x, len: %d\n", request_type, req, wAddress, wIndex, buflen); len = usb_control_msg(fc_usb->udev, pipe, req, request_type, wAddress, wIndex, pbBuffer, buflen, nWaitTime * HZ); debug_dump(pbBuffer, len, deb_v8); return len == buflen ? 0 : -EIO; } #define bytes_left_to_read_on_page(paddr,buflen) \ ((V8_MEMORY_PAGE_SIZE - (paddr & V8_MEMORY_PAGE_MASK)) > buflen \ ? buflen : (V8_MEMORY_PAGE_SIZE - (paddr & V8_MEMORY_PAGE_MASK))) static int flexcop_usb_memory_req(struct flexcop_usb *fc_usb, flexcop_usb_request_t req, flexcop_usb_mem_page_t page_start, u32 addr, int extended, u8 *buf, u32 len) { int i,ret = 0; u16 wMax; u32 pagechunk = 0; switch(req) { case B2C2_USB_READ_V8_MEM: wMax = USB_MEM_READ_MAX; break; case B2C2_USB_WRITE_V8_MEM: wMax = USB_MEM_WRITE_MAX; break; case B2C2_USB_FLASH_BLOCK: wMax = USB_FLASH_MAX; break; default: return -EINVAL; break; } for (i = 0; i < len;) { pagechunk = wMax < bytes_left_to_read_on_page(addr, len) ? wMax : bytes_left_to_read_on_page(addr, len); deb_info("%x\n", (addr & V8_MEMORY_PAGE_MASK) | (V8_MEMORY_EXTENDED*extended)); ret = flexcop_usb_v8_memory_req(fc_usb, req, page_start + (addr / V8_MEMORY_PAGE_SIZE), (addr & V8_MEMORY_PAGE_MASK) | (V8_MEMORY_EXTENDED*extended), &buf[i], pagechunk); if (ret < 0) return ret; addr += pagechunk; len -= pagechunk; } return 0; } static int flexcop_usb_get_mac_addr(struct flexcop_device *fc, int extended) { return flexcop_usb_memory_req(fc->bus_specific, B2C2_USB_READ_V8_MEM, V8_MEMORY_PAGE_FLASH, 0x1f010, 1, fc->dvb_adapter.proposed_mac, 6); } #if 0 static int flexcop_usb_utility_req(struct flexcop_usb *fc_usb, int set, flexcop_usb_utility_function_t func, u8 extra, u16 wIndex, u16 buflen, u8 *pvBuffer) { u16 wValue; u8 request_type = (set ? USB_DIR_OUT : USB_DIR_IN) | USB_TYPE_VENDOR; int nWaitTime = 2, pipe = set ? B2C2_USB_CTRL_PIPE_OUT : B2C2_USB_CTRL_PIPE_IN, len; wValue = (func << 8) | extra; len = usb_control_msg(fc_usb->udev,pipe, B2C2_USB_UTILITY, request_type, wValue, wIndex, pvBuffer, buflen, nWaitTime * HZ); return len == buflen ? 0 : -EIO; } #endif /* usb i2c stuff */ static int flexcop_usb_i2c_req(struct flexcop_i2c_adapter *i2c, flexcop_usb_request_t req, flexcop_usb_i2c_function_t func, u8 chipaddr, u8 addr, u8 *buf, u8 buflen) { struct flexcop_usb *fc_usb = i2c->fc->bus_specific; u16 wValue, wIndex; int nWaitTime,pipe,len; u8 request_type = USB_TYPE_VENDOR; switch (func) { case USB_FUNC_I2C_WRITE: case USB_FUNC_I2C_MULTIWRITE: case USB_FUNC_I2C_REPEATWRITE: /* DKT 020208 - add this to support special case of DiSEqC */ case USB_FUNC_I2C_CHECKWRITE: pipe = B2C2_USB_CTRL_PIPE_OUT; nWaitTime = 2; request_type |= USB_DIR_OUT; break; case USB_FUNC_I2C_READ: case USB_FUNC_I2C_REPEATREAD: pipe = B2C2_USB_CTRL_PIPE_IN; nWaitTime = 2; request_type |= USB_DIR_IN; break; default: deb_info("unsupported function for i2c_req %x\n", func); return -EINVAL; } wValue = (func << 8) | (i2c->port << 4); wIndex = (chipaddr << 8 ) | addr; deb_i2c("i2c %2d: %02x %02x %02x %02x %02x %02x\n", func, request_type, req, wValue & 0xff, wValue >> 8, wIndex & 0xff, wIndex >> 8); len = usb_control_msg(fc_usb->udev,pipe, req, request_type, wValue, wIndex, buf, buflen, nWaitTime * HZ); return len == buflen ? 0 : -EREMOTEIO; } /* actual bus specific access functions, make sure prototype are/will be equal to pci */ static flexcop_ibi_value flexcop_usb_read_ibi_reg(struct flexcop_device *fc, flexcop_ibi_register reg) { flexcop_ibi_value val; val.raw = 0; flexcop_usb_readwrite_dw(fc, reg, &val.raw, 1); return val; } static int flexcop_usb_write_ibi_reg(struct flexcop_device *fc, flexcop_ibi_register reg, flexcop_ibi_value val) { return flexcop_usb_readwrite_dw(fc, reg, &val.raw, 0); } static int flexcop_usb_i2c_request(struct flexcop_i2c_adapter *i2c, flexcop_access_op_t op, u8 chipaddr, u8 addr, u8 *buf, u16 len) { if (op == FC_READ) return flexcop_usb_i2c_req(i2c, B2C2_USB_I2C_REQUEST, USB_FUNC_I2C_READ, chipaddr, addr, buf, len); else return flexcop_usb_i2c_req(i2c, B2C2_USB_I2C_REQUEST, USB_FUNC_I2C_WRITE, chipaddr, addr, buf, len); } static void flexcop_usb_process_frame(struct flexcop_usb *fc_usb, u8 *buffer, int buffer_length) { u8 *b; int l; deb_ts("tmp_buffer_length=%d, buffer_length=%d\n", fc_usb->tmp_buffer_length, buffer_length); if (fc_usb->tmp_buffer_length > 0) { memcpy(fc_usb->tmp_buffer+fc_usb->tmp_buffer_length, buffer, buffer_length); fc_usb->tmp_buffer_length += buffer_length; b = fc_usb->tmp_buffer; l = fc_usb->tmp_buffer_length; } else { b=buffer; l=buffer_length; } while (l >= 190) { if (*b == 0xff) { switch (*(b+1) & 0x03) { case 0x01: /* media packet */ if (*(b+2) == 0x47) flexcop_pass_dmx_packets( fc_usb->fc_dev, b+2, 1); else deb_ts("not ts packet %*ph\n", 4, b+2); b += 190; l -= 190; break; default: deb_ts("wrong packet type\n"); l = 0; break; } } else { deb_ts("wrong header\n"); l = 0; } } if (l>0) memcpy(fc_usb->tmp_buffer, b, l); fc_usb->tmp_buffer_length = l; } static void flexcop_usb_urb_complete(struct urb *urb) { struct flexcop_usb *fc_usb = urb->context; int i; if (urb->actual_length > 0) deb_ts("urb completed, bufsize: %d actlen; %d\n", urb->transfer_buffer_length, urb->actual_length); for (i = 0; i < urb->number_of_packets; i++) { if (urb->iso_frame_desc[i].status < 0) { err("iso frame descriptor %d has an error: %d\n", i, urb->iso_frame_desc[i].status); } else if (urb->iso_frame_desc[i].actual_length > 0) { deb_ts("passed %d bytes to the demux\n", urb->iso_frame_desc[i].actual_length); flexcop_usb_process_frame(fc_usb, urb->transfer_buffer + urb->iso_frame_desc[i].offset, urb->iso_frame_desc[i].actual_length); } urb->iso_frame_desc[i].status = 0; urb->iso_frame_desc[i].actual_length = 0; } usb_submit_urb(urb,GFP_ATOMIC); } static int flexcop_usb_stream_control(struct flexcop_device *fc, int onoff) { /* submit/kill iso packets */ return 0; } static void flexcop_usb_transfer_exit(struct flexcop_usb *fc_usb) { int i; for (i = 0; i < B2C2_USB_NUM_ISO_URB; i++) if (fc_usb->iso_urb[i] != NULL) { deb_ts("unlinking/killing urb no. %d\n",i); usb_kill_urb(fc_usb->iso_urb[i]); usb_free_urb(fc_usb->iso_urb[i]); } if (fc_usb->iso_buffer != NULL) pci_free_consistent(NULL, fc_usb->buffer_size, fc_usb->iso_buffer, fc_usb->dma_addr); } static int flexcop_usb_transfer_init(struct flexcop_usb *fc_usb) { u16 frame_size = le16_to_cpu( fc_usb->uintf->cur_altsetting->endpoint[0].desc.wMaxPacketSize); int bufsize = B2C2_USB_NUM_ISO_URB * B2C2_USB_FRAMES_PER_ISO * frame_size, i, j, ret; int buffer_offset = 0; deb_ts("creating %d iso-urbs with %d frames " "each of %d bytes size = %d.\n", B2C2_USB_NUM_ISO_URB, B2C2_USB_FRAMES_PER_ISO, frame_size, bufsize); fc_usb->iso_buffer = pci_alloc_consistent(NULL, bufsize, &fc_usb->dma_addr); if (fc_usb->iso_buffer == NULL) return -ENOMEM; memset(fc_usb->iso_buffer, 0, bufsize); fc_usb->buffer_size = bufsize; /* creating iso urbs */ for (i = 0; i < B2C2_USB_NUM_ISO_URB; i++) { fc_usb->iso_urb[i] = usb_alloc_urb(B2C2_USB_FRAMES_PER_ISO, GFP_ATOMIC); if (fc_usb->iso_urb[i] == NULL) { ret = -ENOMEM; goto urb_error; } } /* initialising and submitting iso urbs */ for (i = 0; i < B2C2_USB_NUM_ISO_URB; i++) { int frame_offset = 0; struct urb *urb = fc_usb->iso_urb[i]; deb_ts("initializing and submitting urb no. %d " "(buf_offset: %d).\n", i, buffer_offset); urb->dev = fc_usb->udev; urb->context = fc_usb; urb->complete = flexcop_usb_urb_complete; urb->pipe = B2C2_USB_DATA_PIPE; urb->transfer_flags = URB_ISO_ASAP; urb->interval = 1; urb->number_of_packets = B2C2_USB_FRAMES_PER_ISO; urb->transfer_buffer_length = frame_size * B2C2_USB_FRAMES_PER_ISO; urb->transfer_buffer = fc_usb->iso_buffer + buffer_offset; buffer_offset += frame_size * B2C2_USB_FRAMES_PER_ISO; for (j = 0; j < B2C2_USB_FRAMES_PER_ISO; j++) { deb_ts("urb no: %d, frame: %d, frame_offset: %d\n", i, j, frame_offset); urb->iso_frame_desc[j].offset = frame_offset; urb->iso_frame_desc[j].length = frame_size; frame_offset += frame_size; } if ((ret = usb_submit_urb(fc_usb->iso_urb[i],GFP_ATOMIC))) { err("submitting urb %d failed with %d.", i, ret); goto urb_error; } deb_ts("submitted urb no. %d.\n",i); } /* SRAM */ flexcop_sram_set_dest(fc_usb->fc_dev, FC_SRAM_DEST_MEDIA | FC_SRAM_DEST_NET | FC_SRAM_DEST_CAO | FC_SRAM_DEST_CAI, FC_SRAM_DEST_TARGET_WAN_USB); flexcop_wan_set_speed(fc_usb->fc_dev, FC_WAN_SPEED_8MBITS); flexcop_sram_ctrl(fc_usb->fc_dev, 1, 1, 1); return 0; urb_error: flexcop_usb_transfer_exit(fc_usb); return ret; } static int flexcop_usb_init(struct flexcop_usb *fc_usb) { /* use the alternate setting with the larges buffer */ usb_set_interface(fc_usb->udev,0,1); switch (fc_usb->udev->speed) { case USB_SPEED_LOW: err("cannot handle USB speed because it is too slow."); return -ENODEV; break; case USB_SPEED_FULL: info("running at FULL speed."); break; case USB_SPEED_HIGH: info("running at HIGH speed."); break; case USB_SPEED_UNKNOWN: /* fall through */ default: err("cannot handle USB speed because it is unknown."); return -ENODEV; } usb_set_intfdata(fc_usb->uintf, fc_usb); return 0; } static void flexcop_usb_exit(struct flexcop_usb *fc_usb) { usb_set_intfdata(fc_usb->uintf, NULL); } static int flexcop_usb_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev(intf); struct flexcop_usb *fc_usb = NULL; struct flexcop_device *fc = NULL; int ret; if ((fc = flexcop_device_kmalloc(sizeof(struct flexcop_usb))) == NULL) { err("out of memory\n"); return -ENOMEM; } /* general flexcop init */ fc_usb = fc->bus_specific; fc_usb->fc_dev = fc; fc->read_ibi_reg = flexcop_usb_read_ibi_reg; fc->write_ibi_reg = flexcop_usb_write_ibi_reg; fc->i2c_request = flexcop_usb_i2c_request; fc->get_mac_addr = flexcop_usb_get_mac_addr; fc->stream_control = flexcop_usb_stream_control; fc->pid_filtering = 1; fc->bus_type = FC_USB; fc->dev = &udev->dev; fc->owner = THIS_MODULE; /* bus specific part */ fc_usb->udev = udev; fc_usb->uintf = intf; if ((ret = flexcop_usb_init(fc_usb)) != 0) goto err_kfree; /* init flexcop */ if ((ret = flexcop_device_initialize(fc)) != 0) goto err_usb_exit; /* xfer init */ if ((ret = flexcop_usb_transfer_init(fc_usb)) != 0) goto err_fc_exit; info("%s successfully initialized and connected.", DRIVER_NAME); return 0; err_fc_exit: flexcop_device_exit(fc); err_usb_exit: flexcop_usb_exit(fc_usb); err_kfree: flexcop_device_kfree(fc); return ret; } static void flexcop_usb_disconnect(struct usb_interface *intf) { struct flexcop_usb *fc_usb = usb_get_intfdata(intf); flexcop_usb_transfer_exit(fc_usb); flexcop_device_exit(fc_usb->fc_dev); flexcop_usb_exit(fc_usb); flexcop_device_kfree(fc_usb->fc_dev); info("%s successfully deinitialized and disconnected.", DRIVER_NAME); } static struct usb_device_id flexcop_usb_table [] = { { USB_DEVICE(0x0af7, 0x0101) }, { } }; MODULE_DEVICE_TABLE (usb, flexcop_usb_table); /* usb specific object needed to register this driver with the usb subsystem */ static struct usb_driver flexcop_usb_driver = { .name = "b2c2_flexcop_usb", .probe = flexcop_usb_probe, .disconnect = flexcop_usb_disconnect, .id_table = flexcop_usb_table, }; module_usb_driver(flexcop_usb_driver); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_NAME); MODULE_LICENSE("GPL");
3cd6b31edd2614be18e82a2f93475372ccfbe4fb
61da6274995cf914291af51bd02e60f408fdfedd
/src/simu/shepplogan.h
cef3f34f8cd4ee48be45ded2b30ac2e576f0d962
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
mrirecon/bart
360d518b4c79836d506803aa4a77e8e252ab820b
a3c9dc313f79c4c52f1ba3e617d5831ef088ddf7
refs/heads/master
2023-08-31T11:01:08.932824
2023-08-30T12:15:35
2023-08-30T13:51:18
23,212,230
264
185
BSD-3-Clause
2023-08-03T18:43:36
2014-08-22T03:57:09
C
UTF-8
C
false
false
2,407
h
shepplogan.h
/* Copyright 2014-2015. The Regents of the University of California. * Copyright 2016. Martin Uecker. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. */ #ifndef __SHEPPLOGAN_H #define __SHEPPLOGAN_H #include <complex.h> #include "misc/cppwrap.h" struct ellipsis_s { complex double intensity; double axis[2]; double center[2]; double angle; }; struct ellipsis3d_s { complex double intensity; double axis[3]; double center[3]; double angle; }; struct ellipsis_bs { struct ellipsis_s geo; bool background; }; extern const struct ellipsis_s shepplogan[10]; extern const struct ellipsis_s shepplogan_mod[10]; extern const struct ellipsis_s phantom_disc[1]; extern const struct ellipsis_s phantom_ring[4]; extern const struct ellipsis3d_s phantom_disc3d[1]; extern const struct ellipsis3d_s shepplogan3d[10]; extern const struct ellipsis_s phantom_geo1[3]; extern const struct ellipsis_s phantom_geo2[2]; extern const struct ellipsis_s phantom_geo3[7]; extern const struct ellipsis_s phantom_geo4[1]; extern const struct ellipsis_s phantom_geo5[1]; extern const struct ellipsis_bs phantom_tubes[21]; extern const struct ellipsis_bs nist_phantom_t2[29]; extern const struct ellipsis_bs phantom_sonar[15]; extern complex double xellipsis(const double center[2], const double axis[2], double angle, const double p[2]); extern complex double kellipsis(const double center[2], const double axis[2], double angle, const double p[2]); extern complex double xellipsis3d(const double center[3], const double axis[3], double angle, const double p[3]); extern complex double kellipsis3d(const double center[3], const double axis[3], double angle, const double p[3]); extern complex double xrectangle(const double center[2], const double axis[2], double angle, const double p[2]); extern complex double krectangle(const double center[2], const double axis[2], double angle, const double p[2]); extern complex double phantom(unsigned int N, const struct ellipsis_s arr[__VLA(N)], const double pos[2], _Bool ksp); extern complex double phantomX(unsigned int N, const struct ellipsis_s arr[__VLA(N)], const double pos[2], _Bool ksp); extern complex double phantom3d(unsigned int N, const struct ellipsis3d_s arr[__VLA(N)], const double pos[3], _Bool ksp); #include "misc/cppwrap.h" #endif // __SHEPPLOGAN_H
4e6f7f8fc0b42333ffab466475be96af4800f390
d38ed5f31d74a79a054ed55dd9123a8d615283b9
/third_party/libgit2/include/git2/sys/openssl.h
b41c55c6d7f692c78ea814a5da58978c1a904705
[ "Apache-2.0", "GPL-2.0-only", "LicenseRef-scancode-public-domain", "GCC-exception-2.0", "LGPL-2.0-or-later", "Zlib", "LGPL-2.1-or-later", "LGPL-2.1-only", "ISC", "MIT" ]
permissive
chigraph/chigraph
8ff76a14337da29fa2b2a84d5c35f2eac4156c6e
6981bdd6763db54edfe284c1f7d223193584c69a
refs/heads/master
2022-12-21T13:46:57.273039
2022-12-17T18:41:19
2022-12-17T18:41:19
60,776,831
364
65
Apache-2.0
2019-12-13T14:46:43
2016-06-09T13:27:37
C++
UTF-8
C
false
false
1,105
h
openssl.h
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_git_openssl_h__ #define INCLUDE_git_openssl_h__ #include "git2/common.h" GIT_BEGIN_DECL /** * Initialize the OpenSSL locks * * OpenSSL requires the application to determine how it performs * locking. * * This is a last-resort convenience function which libgit2 provides for * allocating and initializing the locks as well as setting the * locking function to use the system's native locking functions. * * The locking function will be cleared and the memory will be freed * when you call git_threads_sutdown(). * * If your programming language has an OpenSSL package/bindings, it * likely sets up locking. You should very strongly prefer that over * this function. * * @return 0 on success, -1 if there are errors or if libgit2 was not * built with OpenSSL and threading support. */ GIT_EXTERN(int) git_openssl_set_locking(void); GIT_END_DECL #endif
84186fb0a64d31071c0c370e0070e27e255f4691
5816ae8b5fdfe9ab93b3653742b5d4c2a1567111
/hitcon-2021/uml/src/note.c
24d3ee17206ef5c6ec8536c6930053a1499420a9
[]
no_license
david942j/ctf-writeups
6c2ff633d80809e422f0263b8ac9a69607d31e84
a4d086684a939000286d0876dd29463ccdceea2e
refs/heads/master
2022-09-07T00:27:23.594820
2021-12-14T10:50:47
2021-12-14T10:50:47
77,058,219
316
49
null
null
null
null
UTF-8
C
false
false
1,372
c
note.c
#include <stdio.h> #include <stdlib.h> #include <sys/sendfile.h> #include <unistd.h> #define CHECK(cond) do { if (!(cond)) exit(1); } while (0) static void *readn(int fd, size_t sz) { void *ptr = malloc(sz); size_t off = 0; CHECK(ptr); while (sz) { ssize_t n = read(fd, ptr + off, sz); CHECK(n > 0); sz -= n; off += n; } return ptr; } static void work() { puts("Name of note?"); char s[32] = {}, fname[40]; CHECK(scanf("%30s", s) == 1); CHECK(s[0] != '.'); sprintf(fname, "/tmp/%s", s); const char *mode; if (access(fname, F_OK)) mode = "w+"; else if (access(fname, W_OK)) mode = "r"; else mode = "r+"; FILE *f = fopen(fname, mode); CHECK(f); while (1) { puts("1. Write the note\n" "2. Read the note\n" "3. I'm good\n" "Choose one:"); int choose; CHECK(scanf("%d", &choose) == 1); if (choose == 3) break; int sz; puts("Size?"); CHECK(scanf("%d", &sz) == 1); CHECK(sz > 0 && sz <= 0x10000); if (choose == 1) { void *ptr = readn(0, sz); CHECK(fwrite(ptr, 1, sz, f) == sz); rewind(f); free(ptr); } else if (choose == 2) { void *ptr = readn(fileno(f), sz); CHECK(write(1, ptr, sz) == sz); free(ptr); } } fclose(f); } int main() { setbuf(stdin, NULL); setbuf(stdout, NULL); work(); return 0; }
69ce25cc5f7858b3a72335d28cb37fa2a802f74a
9ceacf33fd96913cac7ef15492c126d96cae6911
/sys/isofs/udf/udf.h
f6dc2adc294d87489255e47bbb0fc5c102032dc6
[]
no_license
openbsd/src
ab97ef834fd2d5a7f6729814665e9782b586c130
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
refs/heads/master
2023-09-02T18:54:56.624627
2023-09-02T15:16:12
2023-09-02T15:16:12
66,966,208
3,394
1,235
null
2023-08-08T02:42:25
2016-08-30T18:18:25
C
UTF-8
C
false
false
4,269
h
udf.h
/* $OpenBSD: udf.h,v 1.21 2016/06/19 11:54:33 natano Exp $ */ /* * Copyright (c) 2001, 2002 Scott Long <scottl@freebsd.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * $FreeBSD: src/sys/fs/udf/udf.h,v 1.9 2004/10/29 10:40:58 phk Exp $ */ /* * Ported to OpenBSD by Pedro Martelletto in February 2005. */ #define UDF_HASHTBLSIZE 100 typedef uint32_t udfino_t; struct unode { LIST_ENTRY(unode) u_le; struct vnode *u_vnode; struct vnode *u_devvp; struct umount *u_ump; struct rrwlock u_lock; dev_t u_dev; udfino_t u_ino; union { long u_diroff; long u_vatlen; } un_u; struct extfile_entry *u_fentry; }; #define u_diroff un_u.u_diroff #define u_vatlen un_u.u_vatlen struct umount { int um_flags; struct mount *um_mountp; struct vnode *um_devvp; dev_t um_dev; int um_bsize; int um_bshift; int um_bmask; uint32_t um_start; uint32_t um_realstart; uint32_t um_len; uint32_t um_reallen; uint32_t um_meta_start; uint32_t um_meta_len; struct unode *um_vat; struct long_ad um_root_icb; LIST_HEAD(udf_hash_lh, unode) *um_hashtbl; SIPHASH_KEY um_hashkey; u_long um_hashsz; struct mutex um_hashmtx; int um_psecs; int um_stbl_len; struct udf_sparing_table *um_stbl; }; #define UDF_MNT_FIND_VAT 0x01 /* Indicates a VAT must be found */ #define UDF_MNT_USES_VAT 0x02 /* Indicates a VAT must be used */ #define UDF_MNT_USES_META 0x04 /* Indicates we are using a Metadata partition*/ #define VTOU(vp) ((struct unode *)((vp)->v_data)) #ifdef _KERNEL struct udf_dirstream { struct unode *node; struct umount *ump; struct buf *bp; uint8_t *data; uint8_t *buf; int fsize; int off; int this_off; int offset; int size; int error; int fid_fragment; }; #define VFSTOUDFFS(mp) ((struct umount *)((mp)->mnt_data)) /* * The block layer refers to things in terms of 512 byte blocks by default. * btodb() is expensive, so speed things up. * Can the block layer be forced to use a different block size? */ #define RDSECTOR(devvp, sector, size, bp) \ bread(devvp, \ ((daddr_t)(sector) << ump->um_bshift) / DEV_BSIZE, size, bp) static __inline int udf_readlblks(struct umount *ump, int sector, int size, struct buf **bp) { return (RDSECTOR(ump->um_devvp, sector, (size + ump->um_bmask) & ~ump->um_bmask, bp)); } /* * Produce a suitable file number from an ICB. The passed in ICB is expected * to be in little endian (meaning that it hasn't been swapped for big * endian machines yet). * If the fileno resolves to 0, we might be in big trouble. * Assumes the ICB is a long_ad. This struct is compatible with short_ad, * but not ext_ad. */ static __inline udfino_t udf_getid(struct long_ad *icb) { return (letoh32(icb->loc.lb_num)); } int udf_allocv(struct mount *, struct vnode **, struct proc *); int udf_hashlookup(struct umount *, udfino_t, int, struct vnode **); int udf_hashins(struct unode *); int udf_hashrem(struct unode *); int udf_checktag(struct desc_tag *, uint16_t); typedef uint16_t unicode_t; #endif /* _KERNEL */
da0f8b5c4e0bfa38f55b528e4bc8da422120ce07
b970e053302588f44ee1c6b7187c4769934c857f
/ajax/libs/openlayers/5.0.3/format/TextFeature.js
33d6eac33dd00f9546f37634f477028a457fc644
[ "MIT" ]
permissive
cdnjs/cdnjs
2fe0f21477c08618fe609da844f5d133224c3eda
6843ffa5339e4595b3a6893ae3e9ede1117cc5f9
refs/heads/master
2023-07-23T14:52:44.587645
2023-07-23T07:12:24
2023-07-23T07:12:24
1,409,811
8,894
5,633
MIT
2023-06-27T12:32:50
2011-02-25T05:53:47
null
UTF-8
C
false
false
3,865
js
TextFeature.js
/** * @module ol/format/TextFeature */ import {inherits} from '../util.js'; import FeatureFormat from '../format/Feature.js'; import FormatType from '../format/FormatType.js'; /** * @classdesc * Abstract base class; normally only used for creating subclasses and not * instantiated in apps. * Base class for text feature formats. * * @constructor * @abstract * @extends {module:ol/format/Feature} */ const TextFeature = function() { FeatureFormat.call(this); }; inherits(TextFeature, FeatureFormat); /** * @param {Document|Node|Object|string} source Source. * @return {string} Text. */ function getText(source) { if (typeof source === 'string') { return source; } else { return ''; } } /** * @inheritDoc */ TextFeature.prototype.getType = function() { return FormatType.TEXT; }; /** * @inheritDoc */ TextFeature.prototype.readFeature = function(source, opt_options) { return this.readFeatureFromText(getText(source), this.adaptOptions(opt_options)); }; /** * @abstract * @param {string} text Text. * @param {module:ol/format/Feature~ReadOptions=} opt_options Read options. * @protected * @return {module:ol/Feature} Feature. */ TextFeature.prototype.readFeatureFromText = function(text, opt_options) {}; /** * @inheritDoc */ TextFeature.prototype.readFeatures = function(source, opt_options) { return this.readFeaturesFromText(getText(source), this.adaptOptions(opt_options)); }; /** * @abstract * @param {string} text Text. * @param {module:ol/format/Feature~ReadOptions=} opt_options Read options. * @protected * @return {Array.<module:ol/Feature>} Features. */ TextFeature.prototype.readFeaturesFromText = function(text, opt_options) {}; /** * @inheritDoc */ TextFeature.prototype.readGeometry = function(source, opt_options) { return this.readGeometryFromText(getText(source), this.adaptOptions(opt_options)); }; /** * @abstract * @param {string} text Text. * @param {module:ol/format/Feature~ReadOptions=} opt_options Read options. * @protected * @return {module:ol/geom/Geometry} Geometry. */ TextFeature.prototype.readGeometryFromText = function(text, opt_options) {}; /** * @inheritDoc */ TextFeature.prototype.readProjection = function(source) { return this.readProjectionFromText(getText(source)); }; /** * @param {string} text Text. * @protected * @return {module:ol/proj/Projection} Projection. */ TextFeature.prototype.readProjectionFromText = function(text) { return this.dataProjection; }; /** * @inheritDoc */ TextFeature.prototype.writeFeature = function(feature, opt_options) { return this.writeFeatureText(feature, this.adaptOptions(opt_options)); }; /** * @abstract * @param {module:ol/Feature} feature Features. * @param {module:ol/format/Feature~WriteOptions=} opt_options Write options. * @protected * @return {string} Text. */ TextFeature.prototype.writeFeatureText = function(feature, opt_options) {}; /** * @inheritDoc */ TextFeature.prototype.writeFeatures = function(features, opt_options) { return this.writeFeaturesText(features, this.adaptOptions(opt_options)); }; /** * @abstract * @param {Array.<module:ol/Feature>} features Features. * @param {module:ol/format/Feature~WriteOptions=} opt_options Write options. * @protected * @return {string} Text. */ TextFeature.prototype.writeFeaturesText = function(features, opt_options) {}; /** * @inheritDoc */ TextFeature.prototype.writeGeometry = function(geometry, opt_options) { return this.writeGeometryText(geometry, this.adaptOptions(opt_options)); }; /** * @abstract * @param {module:ol/geom/Geometry} geometry Geometry. * @param {module:ol/format/Feature~WriteOptions=} opt_options Write options. * @protected * @return {string} Text. */ TextFeature.prototype.writeGeometryText = function(geometry, opt_options) {}; export default TextFeature;
4b73175cf828010a016572f9958b1e2165c0e1df
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/apollo2/libraries/drivers/regs/am_reg_pdm.h
042dfd2ce3fa0f2af3d3edff6b53137f39148229
[ "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
RT-Thread/rt-thread
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
3602f891211904a27dcbd51e5ba72fefce7326b2
refs/heads/master
2023-09-01T04:10:20.295801
2023-08-31T16:20:55
2023-08-31T16:20:55
7,408,108
9,599
5,805
Apache-2.0
2023-09-14T13:37:26
2013-01-02T14:49:21
C
UTF-8
C
false
false
18,636
h
am_reg_pdm.h
//***************************************************************************** // // am_reg_pdm.h //! @file //! //! @brief Register macros for the PDM module // //***************************************************************************** //***************************************************************************** // // Copyright (c) 2017, Ambiq Micro // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. 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. // // 3. Neither the name of the copyright holder 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. // // This is part of revision 1.2.11 of the AmbiqSuite Development Package. // //***************************************************************************** #ifndef AM_REG_PDM_H #define AM_REG_PDM_H //***************************************************************************** // // Instance finder. (1 instance(s) available) // //***************************************************************************** #define AM_REG_PDM_NUM_MODULES 1 #define AM_REG_PDMn(n) \ (REG_PDM_BASEADDR + 0x00000000 * n) //***************************************************************************** // // Register offsets. // //***************************************************************************** #define AM_REG_PDM_PCFG_O 0x00000000 #define AM_REG_PDM_VCFG_O 0x00000004 #define AM_REG_PDM_FR_O 0x00000008 #define AM_REG_PDM_FRD_O 0x0000000C #define AM_REG_PDM_FLUSH_O 0x00000010 #define AM_REG_PDM_FTHR_O 0x00000014 #define AM_REG_PDM_INTEN_O 0x00000200 #define AM_REG_PDM_INTSTAT_O 0x00000204 #define AM_REG_PDM_INTCLR_O 0x00000208 #define AM_REG_PDM_INTSET_O 0x0000020C //***************************************************************************** // // PDM_INTEN - IO Master Interrupts: Enable // //***************************************************************************** // This is the FIFO underflow interrupt. #define AM_REG_PDM_INTEN_UNDFL_S 2 #define AM_REG_PDM_INTEN_UNDFL_M 0x00000004 #define AM_REG_PDM_INTEN_UNDFL(n) (((uint32_t)(n) << 2) & 0x00000004) // This is the FIFO overflow interrupt. #define AM_REG_PDM_INTEN_OVF_S 1 #define AM_REG_PDM_INTEN_OVF_M 0x00000002 #define AM_REG_PDM_INTEN_OVF(n) (((uint32_t)(n) << 1) & 0x00000002) // This is the FIFO threshold interrupt. #define AM_REG_PDM_INTEN_THR_S 0 #define AM_REG_PDM_INTEN_THR_M 0x00000001 #define AM_REG_PDM_INTEN_THR(n) (((uint32_t)(n) << 0) & 0x00000001) //***************************************************************************** // // PDM_INTSTAT - IO Master Interrupts: Status // //***************************************************************************** // This is the FIFO underflow interrupt. #define AM_REG_PDM_INTSTAT_UNDFL_S 2 #define AM_REG_PDM_INTSTAT_UNDFL_M 0x00000004 #define AM_REG_PDM_INTSTAT_UNDFL(n) (((uint32_t)(n) << 2) & 0x00000004) // This is the FIFO overflow interrupt. #define AM_REG_PDM_INTSTAT_OVF_S 1 #define AM_REG_PDM_INTSTAT_OVF_M 0x00000002 #define AM_REG_PDM_INTSTAT_OVF(n) (((uint32_t)(n) << 1) & 0x00000002) // This is the FIFO threshold interrupt. #define AM_REG_PDM_INTSTAT_THR_S 0 #define AM_REG_PDM_INTSTAT_THR_M 0x00000001 #define AM_REG_PDM_INTSTAT_THR(n) (((uint32_t)(n) << 0) & 0x00000001) //***************************************************************************** // // PDM_INTCLR - IO Master Interrupts: Clear // //***************************************************************************** // This is the FIFO underflow interrupt. #define AM_REG_PDM_INTCLR_UNDFL_S 2 #define AM_REG_PDM_INTCLR_UNDFL_M 0x00000004 #define AM_REG_PDM_INTCLR_UNDFL(n) (((uint32_t)(n) << 2) & 0x00000004) // This is the FIFO overflow interrupt. #define AM_REG_PDM_INTCLR_OVF_S 1 #define AM_REG_PDM_INTCLR_OVF_M 0x00000002 #define AM_REG_PDM_INTCLR_OVF(n) (((uint32_t)(n) << 1) & 0x00000002) // This is the FIFO threshold interrupt. #define AM_REG_PDM_INTCLR_THR_S 0 #define AM_REG_PDM_INTCLR_THR_M 0x00000001 #define AM_REG_PDM_INTCLR_THR(n) (((uint32_t)(n) << 0) & 0x00000001) //***************************************************************************** // // PDM_INTSET - IO Master Interrupts: Set // //***************************************************************************** // This is the FIFO underflow interrupt. #define AM_REG_PDM_INTSET_UNDFL_S 2 #define AM_REG_PDM_INTSET_UNDFL_M 0x00000004 #define AM_REG_PDM_INTSET_UNDFL(n) (((uint32_t)(n) << 2) & 0x00000004) // This is the FIFO overflow interrupt. #define AM_REG_PDM_INTSET_OVF_S 1 #define AM_REG_PDM_INTSET_OVF_M 0x00000002 #define AM_REG_PDM_INTSET_OVF(n) (((uint32_t)(n) << 1) & 0x00000002) // This is the FIFO threshold interrupt. #define AM_REG_PDM_INTSET_THR_S 0 #define AM_REG_PDM_INTSET_THR_M 0x00000001 #define AM_REG_PDM_INTSET_THR(n) (((uint32_t)(n) << 0) & 0x00000001) //***************************************************************************** // // PDM_PCFG - PDM Configuration Register // //***************************************************************************** // Left/right channel swap. #define AM_REG_PDM_PCFG_LRSWAP_S 31 #define AM_REG_PDM_PCFG_LRSWAP_M 0x80000000 #define AM_REG_PDM_PCFG_LRSWAP(n) (((uint32_t)(n) << 31) & 0x80000000) #define AM_REG_PDM_PCFG_LRSWAP_EN 0x80000000 #define AM_REG_PDM_PCFG_LRSWAP_NOSWAP 0x00000000 // Right channel PGA gain. #define AM_REG_PDM_PCFG_PGARIGHT_S 27 #define AM_REG_PDM_PCFG_PGARIGHT_M 0x78000000 #define AM_REG_PDM_PCFG_PGARIGHT(n) (((uint32_t)(n) << 27) & 0x78000000) #define AM_REG_PDM_PCFG_PGARIGHT_M15DB 0x78000000 #define AM_REG_PDM_PCFG_PGARIGHT_M300DB 0x70000000 #define AM_REG_PDM_PCFG_PGARIGHT_M45DB 0x68000000 #define AM_REG_PDM_PCFG_PGARIGHT_M60DB 0x60000000 #define AM_REG_PDM_PCFG_PGARIGHT_M75DB 0x58000000 #define AM_REG_PDM_PCFG_PGARIGHT_M90DB 0x50000000 #define AM_REG_PDM_PCFG_PGARIGHT_M105DB 0x48000000 #define AM_REG_PDM_PCFG_PGARIGHT_M120DB 0x40000000 #define AM_REG_PDM_PCFG_PGARIGHT_P105DB 0x38000000 #define AM_REG_PDM_PCFG_PGARIGHT_P90DB 0x30000000 #define AM_REG_PDM_PCFG_PGARIGHT_P75DB 0x28000000 #define AM_REG_PDM_PCFG_PGARIGHT_P60DB 0x20000000 #define AM_REG_PDM_PCFG_PGARIGHT_P45DB 0x18000000 #define AM_REG_PDM_PCFG_PGARIGHT_P30DB 0x10000000 #define AM_REG_PDM_PCFG_PGARIGHT_P15DB 0x08000000 #define AM_REG_PDM_PCFG_PGARIGHT_0DB 0x00000000 // Left channel PGA gain. #define AM_REG_PDM_PCFG_PGALEFT_S 23 #define AM_REG_PDM_PCFG_PGALEFT_M 0x07800000 #define AM_REG_PDM_PCFG_PGALEFT(n) (((uint32_t)(n) << 23) & 0x07800000) #define AM_REG_PDM_PCFG_PGALEFT_M15DB 0x07800000 #define AM_REG_PDM_PCFG_PGALEFT_M300DB 0x07000000 #define AM_REG_PDM_PCFG_PGALEFT_M45DB 0x06800000 #define AM_REG_PDM_PCFG_PGALEFT_M60DB 0x06000000 #define AM_REG_PDM_PCFG_PGALEFT_M75DB 0x05800000 #define AM_REG_PDM_PCFG_PGALEFT_M90DB 0x05000000 #define AM_REG_PDM_PCFG_PGALEFT_M105DB 0x04800000 #define AM_REG_PDM_PCFG_PGALEFT_M120DB 0x04000000 #define AM_REG_PDM_PCFG_PGALEFT_P105DB 0x03800000 #define AM_REG_PDM_PCFG_PGALEFT_P90DB 0x03000000 #define AM_REG_PDM_PCFG_PGALEFT_P75DB 0x02800000 #define AM_REG_PDM_PCFG_PGALEFT_P60DB 0x02000000 #define AM_REG_PDM_PCFG_PGALEFT_P45DB 0x01800000 #define AM_REG_PDM_PCFG_PGALEFT_P30DB 0x01000000 #define AM_REG_PDM_PCFG_PGALEFT_P15DB 0x00800000 #define AM_REG_PDM_PCFG_PGALEFT_0DB 0x00000000 // PDM_CLK frequency divisor. #define AM_REG_PDM_PCFG_MCLKDIV_S 17 #define AM_REG_PDM_PCFG_MCLKDIV_M 0x00060000 #define AM_REG_PDM_PCFG_MCLKDIV(n) (((uint32_t)(n) << 17) & 0x00060000) #define AM_REG_PDM_PCFG_MCLKDIV_MCKDIV4 0x00060000 #define AM_REG_PDM_PCFG_MCLKDIV_MCKDIV3 0x00040000 #define AM_REG_PDM_PCFG_MCLKDIV_MCKDIV2 0x00020000 #define AM_REG_PDM_PCFG_MCLKDIV_MCKDIV1 0x00000000 // SINC decimation rate. #define AM_REG_PDM_PCFG_SINCRATE_S 10 #define AM_REG_PDM_PCFG_SINCRATE_M 0x0001FC00 #define AM_REG_PDM_PCFG_SINCRATE(n) (((uint32_t)(n) << 10) & 0x0001FC00) // High pass filter control. #define AM_REG_PDM_PCFG_ADCHPD_S 9 #define AM_REG_PDM_PCFG_ADCHPD_M 0x00000200 #define AM_REG_PDM_PCFG_ADCHPD(n) (((uint32_t)(n) << 9) & 0x00000200) #define AM_REG_PDM_PCFG_ADCHPD_EN 0x00000200 #define AM_REG_PDM_PCFG_ADCHPD_DIS 0x00000000 // High pass filter coefficients. #define AM_REG_PDM_PCFG_HPCUTOFF_S 5 #define AM_REG_PDM_PCFG_HPCUTOFF_M 0x000001E0 #define AM_REG_PDM_PCFG_HPCUTOFF(n) (((uint32_t)(n) << 5) & 0x000001E0) // Number of clocks during gain-setting changes. #define AM_REG_PDM_PCFG_CYCLES_S 2 #define AM_REG_PDM_PCFG_CYCLES_M 0x0000001C #define AM_REG_PDM_PCFG_CYCLES(n) (((uint32_t)(n) << 2) & 0x0000001C) // Soft mute control. #define AM_REG_PDM_PCFG_SOFTMUTE_S 1 #define AM_REG_PDM_PCFG_SOFTMUTE_M 0x00000002 #define AM_REG_PDM_PCFG_SOFTMUTE(n) (((uint32_t)(n) << 1) & 0x00000002) #define AM_REG_PDM_PCFG_SOFTMUTE_EN 0x00000002 #define AM_REG_PDM_PCFG_SOFTMUTE_DIS 0x00000000 // Data Streaming Control. #define AM_REG_PDM_PCFG_PDMCORE_S 0 #define AM_REG_PDM_PCFG_PDMCORE_M 0x00000001 #define AM_REG_PDM_PCFG_PDMCORE(n) (((uint32_t)(n) << 0) & 0x00000001) #define AM_REG_PDM_PCFG_PDMCORE_EN 0x00000001 #define AM_REG_PDM_PCFG_PDMCORE_DIS 0x00000000 //***************************************************************************** // // PDM_VCFG - Voice Configuration Register // //***************************************************************************** // Enable the IO clock. #define AM_REG_PDM_VCFG_IOCLKEN_S 31 #define AM_REG_PDM_VCFG_IOCLKEN_M 0x80000000 #define AM_REG_PDM_VCFG_IOCLKEN(n) (((uint32_t)(n) << 31) & 0x80000000) #define AM_REG_PDM_VCFG_IOCLKEN_DIS 0x00000000 #define AM_REG_PDM_VCFG_IOCLKEN_EN 0x80000000 // Reset the IP core. #define AM_REG_PDM_VCFG_RSTB_S 30 #define AM_REG_PDM_VCFG_RSTB_M 0x40000000 #define AM_REG_PDM_VCFG_RSTB(n) (((uint32_t)(n) << 30) & 0x40000000) #define AM_REG_PDM_VCFG_RSTB_RESET 0x00000000 #define AM_REG_PDM_VCFG_RSTB_NORM 0x40000000 // Select the PDM input clock. #define AM_REG_PDM_VCFG_PDMCLKSEL_S 27 #define AM_REG_PDM_VCFG_PDMCLKSEL_M 0x38000000 #define AM_REG_PDM_VCFG_PDMCLKSEL(n) (((uint32_t)(n) << 27) & 0x38000000) #define AM_REG_PDM_VCFG_PDMCLKSEL_DISABLE 0x00000000 #define AM_REG_PDM_VCFG_PDMCLKSEL_12MHz 0x08000000 #define AM_REG_PDM_VCFG_PDMCLKSEL_6MHz 0x10000000 #define AM_REG_PDM_VCFG_PDMCLKSEL_3MHz 0x18000000 #define AM_REG_PDM_VCFG_PDMCLKSEL_1_5MHz 0x20000000 #define AM_REG_PDM_VCFG_PDMCLKSEL_750KHz 0x28000000 #define AM_REG_PDM_VCFG_PDMCLKSEL_375KHz 0x30000000 #define AM_REG_PDM_VCFG_PDMCLKSEL_187KHz 0x38000000 // Enable the serial clock. #define AM_REG_PDM_VCFG_PDMCLK_S 26 #define AM_REG_PDM_VCFG_PDMCLK_M 0x04000000 #define AM_REG_PDM_VCFG_PDMCLK(n) (((uint32_t)(n) << 26) & 0x04000000) #define AM_REG_PDM_VCFG_PDMCLK_DIS 0x00000000 #define AM_REG_PDM_VCFG_PDMCLK_EN 0x04000000 // I2S interface enable. #define AM_REG_PDM_VCFG_I2SMODE_S 20 #define AM_REG_PDM_VCFG_I2SMODE_M 0x00100000 #define AM_REG_PDM_VCFG_I2SMODE(n) (((uint32_t)(n) << 20) & 0x00100000) #define AM_REG_PDM_VCFG_I2SMODE_DIS 0x00000000 #define AM_REG_PDM_VCFG_I2SMODE_EN 0x00100000 // I2S BCLK input inversion. #define AM_REG_PDM_VCFG_BCLKINV_S 19 #define AM_REG_PDM_VCFG_BCLKINV_M 0x00080000 #define AM_REG_PDM_VCFG_BCLKINV(n) (((uint32_t)(n) << 19) & 0x00080000) #define AM_REG_PDM_VCFG_BCLKINV_INV 0x00000000 #define AM_REG_PDM_VCFG_BCLKINV_NORM 0x00080000 // PDM clock sampling delay. #define AM_REG_PDM_VCFG_DMICKDEL_S 17 #define AM_REG_PDM_VCFG_DMICKDEL_M 0x00020000 #define AM_REG_PDM_VCFG_DMICKDEL(n) (((uint32_t)(n) << 17) & 0x00020000) #define AM_REG_PDM_VCFG_DMICKDEL_0CYC 0x00000000 #define AM_REG_PDM_VCFG_DMICKDEL_1CYC 0x00020000 // Select PDM input clock source. #define AM_REG_PDM_VCFG_SELAP_S 16 #define AM_REG_PDM_VCFG_SELAP_M 0x00010000 #define AM_REG_PDM_VCFG_SELAP(n) (((uint32_t)(n) << 16) & 0x00010000) #define AM_REG_PDM_VCFG_SELAP_I2S 0x00010000 #define AM_REG_PDM_VCFG_SELAP_INTERNAL 0x00000000 // PCM data packing enable. #define AM_REG_PDM_VCFG_PCMPACK_S 8 #define AM_REG_PDM_VCFG_PCMPACK_M 0x00000100 #define AM_REG_PDM_VCFG_PCMPACK(n) (((uint32_t)(n) << 8) & 0x00000100) #define AM_REG_PDM_VCFG_PCMPACK_DIS 0x00000000 #define AM_REG_PDM_VCFG_PCMPACK_EN 0x00000100 // Set PCM channels. #define AM_REG_PDM_VCFG_CHSET_S 3 #define AM_REG_PDM_VCFG_CHSET_M 0x00000018 #define AM_REG_PDM_VCFG_CHSET(n) (((uint32_t)(n) << 3) & 0x00000018) #define AM_REG_PDM_VCFG_CHSET_DIS 0x00000000 #define AM_REG_PDM_VCFG_CHSET_LEFT 0x00000008 #define AM_REG_PDM_VCFG_CHSET_RIGHT 0x00000010 #define AM_REG_PDM_VCFG_CHSET_STEREO 0x00000018 //***************************************************************************** // // PDM_FR - Voice Status Register // //***************************************************************************** // Valid 32-bit entries currently in the FIFO. #define AM_REG_PDM_FR_FIFOCNT_S 0 #define AM_REG_PDM_FR_FIFOCNT_M 0x000001FF #define AM_REG_PDM_FR_FIFOCNT(n) (((uint32_t)(n) << 0) & 0x000001FF) //***************************************************************************** // // PDM_FRD - FIFO Read // //***************************************************************************** // FIFO read data. #define AM_REG_PDM_FRD_FIFOREAD_S 0 #define AM_REG_PDM_FRD_FIFOREAD_M 0xFFFFFFFF #define AM_REG_PDM_FRD_FIFOREAD(n) (((uint32_t)(n) << 0) & 0xFFFFFFFF) //***************************************************************************** // // PDM_FLUSH - FIFO Flush // //***************************************************************************** // FIFO FLUSH. #define AM_REG_PDM_FLUSH_FIFOFLUSH_S 0 #define AM_REG_PDM_FLUSH_FIFOFLUSH_M 0x00000001 #define AM_REG_PDM_FLUSH_FIFOFLUSH(n) (((uint32_t)(n) << 0) & 0x00000001) //***************************************************************************** // // PDM_FTHR - FIFO Threshold // //***************************************************************************** // FIFO interrupt threshold. #define AM_REG_PDM_FTHR_FIFOTHR_S 0 #define AM_REG_PDM_FTHR_FIFOTHR_M 0x000000FF #define AM_REG_PDM_FTHR_FIFOTHR(n) (((uint32_t)(n) << 0) & 0x000000FF) #endif // AM_REG_PDM_H
11ca95c51789e5881f5ec3867194f66438b08d19
e3acfc4f06840e23ef1185dcf367f40d3e3f59b4
/tests/regression/56-witness/01-base-lor-enums.c
7cfc24cddab5e04f0c2eaa2c552295dd310481fe
[ "MIT" ]
permissive
goblint/analyzer
d62d3c610b86ed288849371b41c330c30678abc7
69ee7163eef0bfbfd6a4f3b9fda7cea5ce9ab79f
refs/heads/master
2023-08-16T21:58:53.013737
2023-08-16T08:49:18
2023-08-16T08:49:18
2,066,905
141
62
MIT
2023-09-14T18:48:34
2011-07-18T15:10:56
OCaml
UTF-8
C
false
false
505
c
01-base-lor-enums.c
// PARAM: --enable ana.int.enums --set witness.yaml.validate 01-base-lor-enums.yml int main() { int r; // rand int x; switch (r) { case 0: x = 1; break; case 1: x = 3; break; default: x = 6; break; } ; // SUCCESS (witness) ; // UNKNOWN! (witness) int y; switch (r) { case 0: y = 11; break; default: y = x; break; } ; // UNKNOWN (witness) ; // SUCCESS (witness) ; // UNKNOWN! (witness) return 0; }
8d393994f286af56e8d4d302c76b58f61a114c2e
d169de4c5c6b281984df35536430dcc931a957a9
/source/shell/sys/linux/app/ntp/vsf_linux_ntp.h
5a0056e056c1eb7454387c824ac08199d50b27ed
[ "LGPL-2.1-only", "Apache-2.0" ]
permissive
vsfteam/vsf
2ba968ba2ef53b036668019c6c6746149a63c38a
522a52ff2ee4ed149b52789a5bd366f80c08c458
refs/heads/master
2023-08-27T07:32:08.339123
2023-08-26T17:46:07
2023-08-26T17:46:07
181,911,464
273
83
Apache-2.0
2023-08-29T03:08:36
2019-04-17T14:43:42
C
UTF-8
C
false
false
2,893
h
vsf_linux_ntp.h
/***************************************************************************** * Copyright(C)2009-2022 by VSF Team * * * * 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. * * * ****************************************************************************/ #ifndef __VSF_LINUX_NTP_H__ #define __VSF_LINUX_NTP_H__ /*============================ INCLUDES ======================================*/ #include "shell/sys/linux/vsf_linux_cfg.h" #if VSF_LINUX_CFG_RELATIVE_PATH == ENABLED # include "../../include/sys/socket.h" # include "../../include/netinet/in.h" #else # include <sys/socket.h> # include <netinet/in.h> #endif // for rtc #include "hal/vsf_hal.h" #if defined(__VSF_LINUX_NTP_CLASS_IMPLEMENT) # undef __VSF_LINUX_NTP_CLASS_IMPLEMENT # define __VSF_CLASS_IMPLEMENT__ #endif #include "utilities/ooc_class.h" #ifdef __cplusplus extern "C" { #endif /*============================ MACROS ========================================*/ /*============================ MACROFIED FUNCTIONS ===========================*/ /*============================ TYPES =========================================*/ vsf_class(vsf_linux_ntp_rtc_t) { public_member( #if VSF_RTC_CFG_MULTI_CLASS == ENABLED vsf_rtc_t vsf_rtc; #endif struct sockaddr_in host_addr; uint16_t timeout_ms; ) private_member( int sock; ) }; /*============================ GLOBAL VARIABLES ==============================*/ /*============================ PROTOTYPES ====================================*/ extern vsf_err_t vsf_linux_ntp_rtc_init(vsf_rtc_t *rtc_ptr, vsf_rtc_cfg_t *cfg_ptr); extern fsm_rt_t vsf_linux_ntp_rtc_enable(vsf_rtc_t *rtc_ptr); extern vsf_err_t vsf_linux_ntp_rtc_get(vsf_rtc_t *rtc_ptr, vsf_rtc_tm_t *rtc_tm); #ifdef __cplusplus } #endif #endif /* EOF */
6bffc755b7a543f7bac47f5ec3f8bd1f4f1c5a12
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
/x11/qt5-qtwebengine/patches/patch-src_3rdparty_chromium_chrome_common_chrome__paths.h
f935ad90e468ae2df4a4a5b9e1f7ca4ed6272447
[]
no_license
NetBSD/pkgsrc
a0732c023519650ef821ab89c23ab6ab59e25bdb
d042034ec4896cc5b47ed6f2e5b8802d9bc5c556
refs/heads/trunk
2023-09-01T07:40:12.138283
2023-09-01T05:25:19
2023-09-01T05:25:19
88,439,572
321
138
null
2023-07-12T22:34:14
2017-04-16T20:04:15
null
UTF-8
C
false
false
2,881
h
patch-src_3rdparty_chromium_chrome_common_chrome__paths.h
$NetBSD: patch-src_3rdparty_chromium_chrome_common_chrome__paths.h,v 1.2 2022/04/18 11:18:18 adam Exp $ --- src/3rdparty/chromium/chrome/common/chrome_paths.h.orig 2021-02-19 16:41:59.000000000 +0000 +++ src/3rdparty/chromium/chrome/common/chrome_paths.h @@ -51,7 +51,7 @@ enum { // contains subdirectories. #endif #if defined(OS_CHROMEOS) || \ - (defined(OS_LINUX) && BUILDFLAG(CHROMIUM_BRANDING)) || defined(OS_MAC) + ((defined(OS_LINUX) || defined(OS_BSD)) && BUILDFLAG(CHROMIUM_BRANDING)) || defined(OS_MAC) DIR_USER_EXTERNAL_EXTENSIONS, // Directory for per-user external extensions // on Chrome Mac and Chromium Linux. // On Chrome OS, this path is used for OEM @@ -59,7 +59,7 @@ enum { // create it. #endif -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_BSD) DIR_STANDALONE_EXTERNAL_EXTENSIONS, // Directory for 'per-extension' // definition manifest files that // describe extensions which are to be @@ -91,7 +91,7 @@ enum { DIR_PNACL_BASE, // Full path to the base dir for PNaCl. DIR_PNACL_COMPONENT, // Full path to the latest PNaCl version // (subdir of DIR_PNACL_BASE). -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_BSD) DIR_BUNDLED_WIDEVINE_CDM, // Full path to the directory containing the // bundled Widevine CDM. #if !defined(OS_CHROMEOS) @@ -120,7 +120,7 @@ enum { DIR_SUPERVISED_USER_INSTALLED_WHITELISTS, // Directory where sanitized // supervised user whitelists are // installed. -#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_MAC) +#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_MAC) || defined(OS_BSD) DIR_NATIVE_MESSAGING, // System directory where native messaging host // manifest files are stored. DIR_USER_NATIVE_MESSAGING, // Directory with Native Messaging Hosts @@ -135,7 +135,7 @@ enum { DIR_GEN_TEST_DATA, // Directory where generated test data resides. DIR_TEST_DATA, // Directory where unit test data resides. DIR_TEST_TOOLS, // Directory where unit test tools reside. -#if defined(OS_LINUX) || defined(OS_CHROMEOS) +#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_BSD) FILE_COMPONENT_FLASH_HINT, // A file in a known location that points to // the component updated flash plugin. #endif // defined(OS_LINUX) || defined(OS_CHROMEOS)
bc8ef4a8d067dc6b74c220b5754c2e3f1d9f88ac
fbe68d84e97262d6d26dd65c704a7b50af2b3943
/third_party/virtualbox/src/VBox/Runtime/r0drv/freebsd/timer-r0drv-freebsd.c
0dbca47a218fb99175fc385fed7a13e6b400b9c3
[ "GPL-2.0-only", "LicenseRef-scancode-unknown-license-reference", "CDDL-1.0", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "LGPL-2.1-or-later", "GPL-2.0-or-later", "MPL-1.0", "LicenseRef-scancode-generic-exception", "Apache-2.0", "OpenSSL", "MIT" ]
permissive
thalium/icebox
c4e6573f2b4f0973b6c7bb0bf068fe9e795fdcfb
6f78952d58da52ea4f0e55b2ab297f28e80c1160
refs/heads/master
2022-08-14T00:19:36.984579
2022-02-22T13:10:31
2022-02-22T13:10:31
190,019,914
585
109
MIT
2022-01-13T20:58:15
2019-06-03T14:18:12
C++
UTF-8
C
false
false
8,885
c
timer-r0drv-freebsd.c
/* $Id: timer-r0drv-freebsd.c $ */ /** @file * IPRT - Memory Allocation, Ring-0 Driver, FreeBSD. */ /* * Copyright (c) 2007 knut st. osmundsen <bird-src-spam@anduin.net> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /********************************************************************************************************************************* * Header Files * *********************************************************************************************************************************/ #include "the-freebsd-kernel.h" #include <iprt/timer.h> #include <iprt/time.h> #include <iprt/spinlock.h> #include <iprt/err.h> #include <iprt/asm.h> #include <iprt/assert.h> #include <iprt/alloc.h> #include "internal/magics.h" /********************************************************************************************************************************* * Structures and Typedefs * *********************************************************************************************************************************/ /** * The internal representation of an FreeBSD timer handle. */ typedef struct RTTIMER { /** Magic. * This is RTTIMER_MAGIC, but changes to something else before the timer * is destroyed to indicate clearly that thread should exit. */ uint32_t volatile u32Magic; /** Flag indicating that the timer is suspended. */ uint8_t volatile fSuspended; /** Whether the timer must run on a specific CPU or not. */ uint8_t fSpecificCpu; /** The CPU it must run on if fSpecificCpu is set. */ uint32_t iCpu; /** The FreeBSD callout structure. */ struct callout Callout; /** Callback. */ PFNRTTIMER pfnTimer; /** User argument. */ void *pvUser; /** The timer interval. 0 if one-shot. */ uint64_t u64NanoInterval; /** The start of the current run. * This is used to calculate when the timer ought to fire the next time. */ uint64_t volatile u64StartTS; /** The start of the current run. * This is used to calculate when the timer ought to fire the next time. */ uint64_t volatile u64NextTS; /** The current tick number (since u64StartTS). */ uint64_t volatile iTick; } RTTIMER; /********************************************************************************************************************************* * Internal Functions * *********************************************************************************************************************************/ static void rtTimerFreeBSDCallback(void *pvTimer); RTDECL(int) RTTimerCreateEx(PRTTIMER *ppTimer, uint64_t u64NanoInterval, uint32_t fFlags, PFNRTTIMER pfnTimer, void *pvUser) { *ppTimer = NULL; /* * Validate flags. */ if (!RTTIMER_FLAGS_ARE_VALID(fFlags)) return VERR_INVALID_PARAMETER; if ( (fFlags & RTTIMER_FLAGS_CPU_SPECIFIC) && (fFlags & RTTIMER_FLAGS_CPU_ALL) != RTTIMER_FLAGS_CPU_ALL && (fFlags & RTTIMER_FLAGS_CPU_MASK) > mp_maxid) return VERR_CPU_NOT_FOUND; /* * Allocate and initialize the timer handle. */ PRTTIMER pTimer = (PRTTIMER)RTMemAlloc(sizeof(*pTimer)); if (!pTimer) return VERR_NO_MEMORY; pTimer->u32Magic = RTTIMER_MAGIC; pTimer->fSuspended = true; pTimer->fSpecificCpu = !!(fFlags & RTTIMER_FLAGS_CPU_SPECIFIC); pTimer->iCpu = fFlags & RTTIMER_FLAGS_CPU_MASK; pTimer->pfnTimer = pfnTimer; pTimer->pvUser = pvUser; pTimer->u64NanoInterval = u64NanoInterval; pTimer->u64StartTS = 0; callout_init(&pTimer->Callout, CALLOUT_MPSAFE); *ppTimer = pTimer; return VINF_SUCCESS; } /** * Validates the timer handle. * * @returns true if valid, false if invalid. * @param pTimer The handle. */ DECLINLINE(bool) rtTimerIsValid(PRTTIMER pTimer) { AssertReturn(VALID_PTR(pTimer), false); AssertReturn(pTimer->u32Magic == RTTIMER_MAGIC, false); return true; } RTDECL(int) RTTimerDestroy(PRTTIMER pTimer) { /* It's ok to pass NULL pointer. */ if (pTimer == /*NIL_RTTIMER*/ NULL) return VINF_SUCCESS; if (!rtTimerIsValid(pTimer)) return VERR_INVALID_HANDLE; /* * Free the associated resources. */ pTimer->u32Magic++; callout_stop(&pTimer->Callout); RTMemFree(pTimer); return VINF_SUCCESS; } RTDECL(int) RTTimerStart(PRTTIMER pTimer, uint64_t u64First) { struct timeval tv; if (!rtTimerIsValid(pTimer)) return VERR_INVALID_HANDLE; if (!pTimer->fSuspended) return VERR_TIMER_ACTIVE; if ( pTimer->fSpecificCpu && !RTMpIsCpuOnline(RTMpCpuIdFromSetIndex(pTimer->iCpu))) return VERR_CPU_OFFLINE; /* * Calc when it should start firing. */ u64First += RTTimeNanoTS(); pTimer->fSuspended = false; pTimer->iTick = 0; pTimer->u64StartTS = u64First; pTimer->u64NextTS = u64First; tv.tv_sec = u64First / 1000000000; tv.tv_usec = (u64First % 1000000000) / 1000; callout_reset(&pTimer->Callout, tvtohz(&tv), rtTimerFreeBSDCallback, pTimer); return VINF_SUCCESS; } RTDECL(int) RTTimerStop(PRTTIMER pTimer) { if (!rtTimerIsValid(pTimer)) return VERR_INVALID_HANDLE; if (pTimer->fSuspended) return VERR_TIMER_SUSPENDED; /* * Suspend the timer. */ pTimer->fSuspended = true; callout_stop(&pTimer->Callout); return VINF_SUCCESS; } RTDECL(int) RTTimerChangeInterval(PRTTIMER pTimer, uint64_t u64NanoInterval) { if (!rtTimerIsValid(pTimer)) return VERR_INVALID_HANDLE; return VERR_NOT_SUPPORTED; } /** * smp_rendezvous action callback. * * This will perform the timer callback if we're on the right CPU. * * @param pvTimer The timer. */ static void rtTimerFreeBSDIpiAction(void *pvTimer) { PRTTIMER pTimer = (PRTTIMER)pvTimer; if ( pTimer->iCpu == RTTIMER_FLAGS_CPU_MASK || (u_int)pTimer->iCpu == curcpu) pTimer->pfnTimer(pTimer, pTimer->pvUser, pTimer->iTick); } static void rtTimerFreeBSDCallback(void *pvTimer) { PRTTIMER pTimer = (PRTTIMER)pvTimer; /* calculate and set the next timeout */ pTimer->iTick++; if (!pTimer->u64NanoInterval) { pTimer->fSuspended = true; callout_stop(&pTimer->Callout); } else { struct timeval tv; const uint64_t u64NanoTS = RTTimeNanoTS(); pTimer->u64NextTS = pTimer->u64StartTS + pTimer->iTick * pTimer->u64NanoInterval; if (pTimer->u64NextTS < u64NanoTS) pTimer->u64NextTS = u64NanoTS + RTTimerGetSystemGranularity() / 2; tv.tv_sec = pTimer->u64NextTS / 1000000000; tv.tv_usec = (pTimer->u64NextTS % 1000000000) / 1000; callout_reset(&pTimer->Callout, tvtohz(&tv), rtTimerFreeBSDCallback, pTimer); } /* callback */ if ( !pTimer->fSpecificCpu || pTimer->iCpu == curcpu) pTimer->pfnTimer(pTimer, pTimer->pvUser, pTimer->iTick); else smp_rendezvous(NULL, rtTimerFreeBSDIpiAction, NULL, pvTimer); } RTDECL(uint32_t) RTTimerGetSystemGranularity(void) { return 1000000000 / hz; /* ns */ } RTDECL(int) RTTimerRequestSystemGranularity(uint32_t u32Request, uint32_t *pu32Granted) { return VERR_NOT_SUPPORTED; } RTDECL(int) RTTimerReleaseSystemGranularity(uint32_t u32Granted) { return VERR_NOT_SUPPORTED; } RTDECL(bool) RTTimerCanDoHighResolution(void) { return false; }
216e12c0930c28dd2062e61ae96187cd62241674
08d028267d3494963a87e5e5cdc3bd0cf65df843
/lib/src/length.h
42d61ef3876d48e948116f07686292cf46306499
[ "MIT" ]
permissive
tree-sitter/tree-sitter
921e199555dcb0cfc1f50255abe2de3f711e7e41
293f0d1ca30a63839810ad4b943c0f19f1cb4933
refs/heads/master
2023-09-01T11:36:31.992607
2023-09-01T01:01:47
2023-09-01T01:01:47
14,164,618
13,334
968
MIT
2023-09-12T00:15:14
2013-11-06T06:16:00
Rust
UTF-8
C
false
false
1,242
h
length.h
#ifndef TREE_SITTER_LENGTH_H_ #define TREE_SITTER_LENGTH_H_ #include <stdlib.h> #include <stdbool.h> #include "./point.h" #include "tree_sitter/api.h" typedef struct { uint32_t bytes; TSPoint extent; } Length; static const Length LENGTH_UNDEFINED = {0, {0, 1}}; static const Length LENGTH_MAX = {UINT32_MAX, {UINT32_MAX, UINT32_MAX}}; static inline bool length_is_undefined(Length length) { return length.bytes == 0 && length.extent.column != 0; } static inline Length length_min(Length len1, Length len2) { return (len1.bytes < len2.bytes) ? len1 : len2; } static inline Length length_add(Length len1, Length len2) { Length result; result.bytes = len1.bytes + len2.bytes; result.extent = point_add(len1.extent, len2.extent); return result; } static inline Length length_sub(Length len1, Length len2) { Length result; result.bytes = len1.bytes - len2.bytes; result.extent = point_sub(len1.extent, len2.extent); return result; } static inline Length length_zero(void) { Length result = {0, {0, 0}}; return result; } static inline Length length_saturating_sub(Length len1, Length len2) { if (len1.bytes > len2.bytes) { return length_sub(len1, len2); } else { return length_zero(); } } #endif
4cadc6d89bbf38242827bcd3e4e534fc0e91527d
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/comms/bforce-kst/files/patch-prot_emsi.c
53ce650c97e878c6461a86cb5313017b5e67894d
[ "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C
false
false
707
c
patch-prot_emsi.c
diff -ruN bforce-0.22.8.kst7/source/bforce/prot_emsi.c bforce-0.22.8.kst8/source/bforce/prot_emsi.c --- bforce/prot_emsi.c Thu Nov 21 23:22:56 2002 +++ bforce/prot_emsi.c Sat Nov 30 01:41:15 2002 @@ -829,10 +829,14 @@ /* ----------------------------------------------------------------- */ if( state.caller == 0 && hrc != HRC_BAD_PASSWD ) { - emsi->have_traf = emsi->have_moh = 1; + emsi->have_traf = 1; emsi->netmail_size = state.traff_send.netmail_size; emsi->arcmail_size = state.traff_send.arcmail_size; - emsi->files_size = state.traff_send.files_size; + if ( state.traff_send.files_size ) + { + emsi->have_moh = 1; + emsi->files_size = state.traff_send.files_size; + } } }
84df8f6beeb3d37ee491477c929374dabf155082
baa9fffc817a2a993d4ecc774d3f277783308c20
/src/ucp/wireup/ep_match.h
2e9bf64c30733cf26abc8514390e41720a6d4187
[ "BSD-3-Clause" ]
permissive
openucx/ucx
9a0f2205295afbdf3cff14b5d24af781b123f5ea
73a48700badb7cbace64d94b82f408e2a26fca32
refs/heads/master
2023-09-01T16:51:26.913950
2023-09-01T13:02:25
2023-09-01T13:02:25
25,379,390
966
420
NOASSERTION
2023-09-14T12:29:35
2014-10-17T22:17:24
C
UTF-8
C
false
false
1,414
h
ep_match.h
/** * Copyright (c) NVIDIA CORPORATION & AFFILIATES, 2018-2020. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #ifndef UCP_EP_MATCH_H_ #define UCP_EP_MATCH_H_ #include <ucp/core/ucp_types.h> #include <ucs/datastruct/conn_match.h> /** * Maximal value for EP connection sequence number */ #define UCP_EP_MATCH_CONN_SN_MAX ((ucp_ep_match_conn_sn_t)-1) /** * UCP EP connection matching sequence number */ typedef uint16_t ucp_ep_match_conn_sn_t; /** * Object that represents matching with remote endpoints */ typedef struct { uint64_t dest_uuid; /* Destination worker UUID */ ucs_conn_match_elem_t conn_match; /* Connection matching object */ } ucp_ep_match_elem_t; extern const ucs_conn_match_ops_t ucp_ep_match_ops; ucp_ep_match_conn_sn_t ucp_ep_match_get_sn(ucp_worker_h worker, uint64_t dest_uuid); int ucp_ep_match_insert(ucp_worker_h worker, ucp_ep_h ep, uint64_t dest_uuid, ucp_ep_match_conn_sn_t conn_sn, ucs_conn_match_queue_type_t conn_queue_type); ucp_ep_h ucp_ep_match_retrieve(ucp_worker_h worker, uint64_t dest_uuid, ucp_ep_match_conn_sn_t conn_sn, ucs_conn_match_queue_type_t conn_queue_type); void ucp_ep_match_remove_ep(ucp_worker_h worker, ucp_ep_h ep); #endif
f1a9e449e62c02ceccbb16d78d5eca8d43a0a73c
2d5743a0cc3b0ca82856d12e5576949868630031
/perf/dispatch.h
6847852dabe77b492f1a677ee0d1e577b7831ec0
[ "BSD-2-Clause" ]
permissive
Tarsnap/kivaloo
20dfd70438375c7b8f8ea00a928b87c9299ae8be
1b4fffe65e8bdc789cb47a6191b4df33613a98e0
refs/heads/master
2023-09-03T01:26:01.625376
2023-08-26T18:52:14
2023-08-26T18:52:14
36,057,493
207
22
NOASSERTION
2023-08-29T18:49:29
2015-05-22T07:05:37
C
UTF-8
C
false
false
769
h
dispatch.h
#ifndef DISPATCH_H_ #define DISPATCH_H_ #include <stddef.h> /* Opaque types. */ struct dispatch_state; struct perfstats; struct wire_requestqueue; /** * dispatch_accept(s, Q, P): * Initialize a dispatcher to accept a connection from the listening socket * ${s} and shuttle request/responses to/from the request queue ${Q}, recording * performance for each request via ${P}. */ struct dispatch_state * dispatch_accept(int, struct wire_requestqueue *, struct perfstats *); /** * dispatch_alive(D): * Return non-zero if the dispatcher with state ${D} is still alive. */ int dispatch_alive(struct dispatch_state *); /** * dispatch_done(D): * Clean up the dispatcher state ${D}. */ void dispatch_done(struct dispatch_state *); #endif /* !DISPATCH_H_ */
ab3b9e376a3704bd18fa0a4f2457845742ae22a1
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/bouffalo_lab/libraries/bl_mcu_sdk/drivers/lhal/src/bflb_kys.c
95fa963764a6156de9c35ec0f5a4b4cdeac8db82
[ "Apache-2.0", "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC", "LicenseRef-scancode-unknown-license-reference" ]
permissive
RT-Thread/rt-thread
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
3602f891211904a27dcbd51e5ba72fefce7326b2
refs/heads/master
2023-09-01T04:10:20.295801
2023-08-31T16:20:55
2023-08-31T16:20:55
7,408,108
9,599
5,805
Apache-2.0
2023-09-14T13:37:26
2013-01-02T14:49:21
C
UTF-8
C
false
false
6,585
c
bflb_kys.c
/** ****************************************************************************** * @file bflb_kys.c * @version V1.0 * @date 2022-11-17 * @brief This file is the low hardware abstraction layer file ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2022 Bouffalo Lab</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of Bouffalo Lab 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. * ****************************************************************************** */ #include "bflb_core.h" #include "bflb_kys.h" #include "bflb_clock.h" #include "bflb_l1c.h" #include "hardware/kys_reg.h" /** * @brief keyscan init * * @param dev * @param config */ void bflb_kys_init(struct bflb_device_s *dev, const struct bflb_kys_config_s *config) { uint32_t reg_base; uint32_t reg_val; reg_base = dev->reg_base; /* disable kys */ reg_val = getreg32(reg_base + KYS_KS_CTRL_OFFSET); reg_val &= ~(KYS_KS_EN_MASK); putreg32(reg_val, reg_base + KYS_KS_CTRL_OFFSET); /* mask all interrupt before init */ reg_val = getreg32(reg_base + KYS_KS_INT_EN_OFFSET); #if defined(BL702) reg_val &= ~(KYS_KS_INT_EN_MASK); #else reg_val &= ~(KYS_KS_DONE_INT_EN_MASK | KYS_KEYFIFO_FULL_INT_EN_MASK | KYS_KEYFIFO_HALF_INT_EN_MASK | KYS_KEYFIFO_QUARTER_INT_EN_MASK | KYS_KEYFIFO_NONEMPTY_INT_EN_MASK | KYS_GHOST_INT_EN_MASK); #endif /* kys init */ reg_val = getreg32(reg_base + KYS_KS_CTRL_OFFSET); reg_val &= ~(KYS_COL_NUM_MASK | KYS_ROW_NUM_MASK | #if defined(BL702L) KYS_FIFO_MODE_MASK | #endif KYS_RC_EXT_MASK | KYS_GHOST_EN_MASK | KYS_DEG_EN_MASK | KYS_DEG_CNT_MASK); reg_val |= ((config->col - 1) << KYS_COL_NUM_SHIFT); reg_val |= ((config->row - 1) << KYS_ROW_NUM_SHIFT); reg_val |= ((config->idle_duration) << KYS_RC_EXT_SHIFT); reg_val |= (config->ghost_en << KYS_GHOST_EN_SHIFT); reg_val |= (config->deglitch_en << KYS_DEG_EN_SHIFT); reg_val |= (config->deglitch_cnt << KYS_DEG_CNT_SHIFT); #if defined(BL702L) reg_val |= (0x1 << KYS_FIFO_MODE_SHIFT); #endif putreg32(reg_val, reg_base + KYS_KS_CTRL_OFFSET); } /** * @brief keyscan enable * */ void bflb_kys_enable(struct bflb_device_s *dev) { uint32_t reg_base; uint32_t reg_val; reg_base = dev->reg_base; reg_val = getreg32(reg_base + KYS_KS_CTRL_OFFSET); reg_val |= (0x1 << KYS_KS_EN_SHIFT); putreg32(reg_val, reg_base + KYS_KS_CTRL_OFFSET); } /** * @brief keyscan disable * */ void bflb_kys_disable(struct bflb_device_s *dev) { uint32_t reg_base; uint32_t reg_val; reg_base = dev->reg_base; reg_val = getreg32(reg_base + KYS_KS_CTRL_OFFSET); reg_val &= ~(KYS_KS_EN_MASK); putreg32(reg_val, reg_base + KYS_KS_CTRL_OFFSET); } /** * @brief keyscan interrupt enable * * @param dev * @param flag interrupt flag @KEYSCAN_INT_EN define * @param enable enable or disable interrupt */ void bflb_kys_int_enable(struct bflb_device_s *dev, uint32_t flag, bool enable) { uint32_t reg_base; uint32_t reg_val_en; reg_base = dev->reg_base; reg_val_en = getreg32(reg_base + KYS_KS_INT_EN_OFFSET); if (enable) { reg_val_en |= (flag); } else { reg_val_en &= ~(flag); } putreg32(reg_val_en, reg_base + KYS_KS_INT_EN_OFFSET); } /** * @brief keyscan interrupt clear flag * * @param dev * @param flag */ void bflb_kys_int_clear(struct bflb_device_s *dev, uint32_t flag) { putreg32(flag, dev->reg_base + KYS_KEYCODE_CLR_OFFSET); } /** * @brief keyscan get interrupt status * * @param dev * @return uint32_t */ uint32_t bflb_kys_get_int_status(struct bflb_device_s *dev) { uint32_t reg_base; uint32_t reg_sts_val, reg_mask_val; reg_base = dev->reg_base; reg_sts_val = getreg32(reg_base + KYS_KS_INT_STS_OFFSET); reg_mask_val = getreg32(reg_base + KYS_KS_INT_EN_OFFSET); return (reg_sts_val & (reg_mask_val)); } #if defined(BL702L) /** * @brief get keyscan keycode index in fifo * * @param dev * @param fifo_head * @param fifo_tail * @param fifo_valid_cnt * */ void bflb_kys_get_fifo_info(struct bflb_device_s *dev, uint8_t *fifo_head, uint8_t *fifo_tail, uint8_t *fifo_valid_cnt) { uint32_t reg_base; uint32_t reg_val; reg_base = dev->reg_base; reg_val = getreg32(reg_base + KYS_KEYFIFO_IDX_OFFSET); *fifo_head = (uint8_t)(reg_val & 0x7); *fifo_tail = (uint8_t)((reg_val & 0x700) >> 8); *fifo_valid_cnt = (uint8_t)((reg_val & 0xf0000) >> 16); } #endif /** * @brief get keyscan keycode value * * @param dev * @param index * @return uint8_t */ uint8_t bflb_kys_read_keyvalue(struct bflb_device_s *dev, uint8_t index) { #if defined(BL702L) return (uint8_t)(getreg32(dev->reg_base + KYS_KEYFIFO_VALUE_OFFSET) & 0xff); #endif #if defined(BL702) return (uint8_t)((getreg32(dev->reg_base + KYS_KEYFIFO_VALUE_OFFSET) >> (index * 8)) & 0xff); #endif }
7a10c4917c9990ab37aca11bfb900c7d5f807116
30b736259b38c916e96f8e1517f92231070f5464
/babblesim/hw/mcu/nordic/nrf52_bsim/src/hal_flash.c
b39b5158ce34114a0dbef73c65330edbe37924d5
[ "Apache-2.0", "LicenseRef-scancode-gary-s-brown", "BSD-3-Clause" ]
permissive
apache/mynewt-nimble
5bcc87df4482705c5a6542467bab028c8fd4e5fe
b5e107e9c55f32d18b16e5afc0a7e1720b901b68
refs/heads/master
2023-09-01T19:28:57.874159
2023-08-31T09:07:59
2023-08-31T14:46:07
113,086,218
606
354
Apache-2.0
2023-09-14T12:14:19
2017-12-04T19:34:47
C
UTF-8
C
false
false
7,172
c
hal_flash.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 <sys/mman.h> #include <fcntl.h> #include <assert.h> #include <string.h> #include <inttypes.h> #include <stdlib.h> #include <unistd.h> #include "os/mynewt.h" #include "hal/hal_flash_int.h" #include "mcu/mcu_sim.h" char *native_flash_file; static int file = -1; static void *file_loc; static int native_flash_init(const struct hal_flash *dev); static int native_flash_read(const struct hal_flash *dev, uint32_t address, void *dst, uint32_t length); static int native_flash_write(const struct hal_flash *dev, uint32_t address, const void *src, uint32_t length); static int native_flash_erase_sector(const struct hal_flash *dev, uint32_t sector_address); static int native_flash_sector_info(const struct hal_flash *dev, int idx, uint32_t *address, uint32_t *size); static const struct hal_flash_funcs native_flash_funcs = { .hff_read = native_flash_read, .hff_write = native_flash_write, .hff_erase_sector = native_flash_erase_sector, .hff_sector_info = native_flash_sector_info, .hff_init = native_flash_init }; #if MYNEWT_VAL(MCU_FLASH_STYLE_ST) static const uint32_t native_flash_sectors[] = { 0x00000000, /* 16 * 1024 */ 0x00004000, /* 16 * 1024 */ 0x00008000, /* 16 * 1024 */ 0x0000c000, /* 16 * 1024 */ 0x00010000, /* 64 * 1024 */ 0x00020000, /* 128 * 1024 */ 0x00040000, /* 128 * 1024 */ 0x00060000, /* 128 * 1024 */ 0x00080000, /* 128 * 1024 */ 0x000a0000, /* 128 * 1024 */ 0x000c0000, /* 128 * 1024 */ 0x000e0000, /* 128 * 1024 */ }; #elif MYNEWT_VAL(MCU_FLASH_STYLE_NORDIC) static uint32_t native_flash_sectors[1024 * 1024 / 2048]; #else #error "Need to specify either MCU_FLASH_STYLE_NORDIC or MCU_FLASH_STYLE_ST" #endif #define FLASH_NUM_AREAS (int)(sizeof native_flash_sectors / \ sizeof native_flash_sectors[0]) const struct hal_flash native_flash_dev = { .hf_itf = &native_flash_funcs, .hf_base_addr = 0, .hf_size = 1024 * 1024, .hf_sector_cnt = FLASH_NUM_AREAS, .hf_align = MYNEWT_VAL(MCU_FLASH_MIN_WRITE_SIZE), .hf_erased_val = 0xff, }; static void flash_native_erase(uint32_t addr, uint32_t len) { memset(file_loc + addr, 0xff, len); } static void flash_native_file_open(char *name) { int created = 0; char tmpl[] = "/tmp/native_flash.XXXXXX"; extern int ftruncate(int fd, off_t length); if (file != -1) { close(file); file = -1; } if (name) { file = open(name, O_RDWR); if (file < 0) { file = open(name, O_RDWR | O_CREAT, 0660); assert(file > 0); created = 1; } } else { file = mkstemp(tmpl); assert(file > 0); created = 1; } if (created) { if (ftruncate(file, native_flash_dev.hf_size) < 0) { assert(0); } } if (file_loc != NULL) { munmap(file_loc, native_flash_dev.hf_size); } file_loc = mmap(0, native_flash_dev.hf_size, PROT_READ | PROT_WRITE, MAP_SHARED, file, 0); assert(file_loc != MAP_FAILED); if (created) { flash_native_erase(0, native_flash_dev.hf_size); } /* If using a temporary file, unlink it immediately. */ if (name == NULL) { remove(tmpl); } } static void flash_native_ensure_file_open(void) { if (file == 0) { flash_native_file_open(NULL); } } static int flash_native_write_internal(uint32_t address, const void *src, uint32_t length, int allow_overwrite) { static uint8_t buf[256]; uint32_t cur; uint32_t end; int chunk_sz; int rc; int i; if (length == 0) { return 0; } end = address + length; flash_native_ensure_file_open(); cur = address; while (cur < end) { if (end - cur < sizeof buf) { chunk_sz = end - cur; } else { chunk_sz = sizeof buf; } /* Ensure data is not being overwritten. */ if (!allow_overwrite) { rc = native_flash_read(NULL, cur, buf, chunk_sz); assert(rc == 0); for (i = 0; i < chunk_sz; i++) { assert(buf[i] == 0xff); } } cur += chunk_sz; } memcpy((char *)file_loc + address, src, length); return 0; } static int native_flash_write(const struct hal_flash *dev, uint32_t address, const void *src, uint32_t length) { assert(address % native_flash_dev.hf_align == 0); return flash_native_write_internal(address, src, length, 0); } int flash_native_memset(uint32_t offset, uint8_t c, uint32_t len) { memset(file_loc + offset, c, len); return 0; } static int native_flash_read(const struct hal_flash *dev, uint32_t address, void *dst, uint32_t length) { flash_native_ensure_file_open(); memcpy(dst, (char *)file_loc + address, length); return 0; } static int find_area(uint32_t address) { int i; for (i = 0; i < FLASH_NUM_AREAS; i++) { if (native_flash_sectors[i] == address) { return i; } } return -1; } static int flash_sector_len(int sector) { uint32_t end; if (sector == FLASH_NUM_AREAS - 1) { end = native_flash_dev.hf_size + native_flash_sectors[0]; } else { end = native_flash_sectors[sector + 1]; } return end - native_flash_sectors[sector]; } static int native_flash_erase_sector(const struct hal_flash *dev, uint32_t sector_address) { int area_id; uint32_t len; flash_native_ensure_file_open(); area_id = find_area(sector_address); if (area_id == -1) { return -1; } len = flash_sector_len(area_id); flash_native_erase(sector_address, len); return 0; } static int native_flash_sector_info(const struct hal_flash *dev, int idx, uint32_t *address, uint32_t *size) { assert(idx < FLASH_NUM_AREAS); *address = native_flash_sectors[idx]; *size = flash_sector_len(idx); return 0; } static int native_flash_init(const struct hal_flash *dev) { //if (native_flash_file) { flash_native_file_open(native_flash_file); //} #if MYNEWT_VAL(MCU_FLASH_STYLE_NORDIC) int i; for (i = 0; i < FLASH_NUM_AREAS; i++) { native_flash_sectors[i] = i * 2048; } #endif return 0; }
854945e15d0f9bc245f089e2c8d63f9303878717
ae3e9369882d46a2a009c41a58449c3da9cb3ae1
/src/include/lkl/virtio_net.h
45072738cf856cb4d9e21e8e7d78c0fb98d49d66
[ "MIT" ]
permissive
lsds/sgx-lkl
efc1f9bc0b9621ff1d301abf0b5bbbcc7c80ef96
b6e838e0034de86b48470b6a6bf87d2e262e65c9
refs/heads/oe_port
2023-06-04T04:44:34.776274
2021-04-12T17:33:53
2021-04-12T17:33:53
113,332,442
267
109
MIT
2022-12-29T04:35:40
2017-12-06T15:22:02
C
UTF-8
C
false
false
479
h
virtio_net.h
#ifndef _MUSLKL_VIRTIO_NET_H #define _MUSLKL_VIRTIO_NET_H struct ifreq; /** * lkl_register_netdev_linux_fdnet - register a file descriptor-based network * device as a NIC * * @fd - a POSIX file descriptor number for input/output * @sync_io - 1 if I/O should be synchronous, i.e. threads should busy wait for * I/O to complete. * @returns a struct lkl_netdev_linux_fdnet entry for virtio-net */ struct lkl_netdev* sgxlkl_register_netdev_fd(int fd, int sync_io); #endif
5b5f074017cc3f8aee599f37b157f2422dfdf46b
c26d7b0ed875357278e61627da2da0650da77986
/sys/pic32/gpanel-spi.c
30b3fa5faf5140fa88f66b0ca49bea9af2dcf48e
[ "BSD-3-Clause" ]
permissive
RetroBSD/retrobsd
5343d9e3c424637fc3ad5b03fe720b2744490025
486f81f6abff01c7dcc207235cd2979b226a95ff
refs/heads/master
2023-09-02T23:12:05.110883
2023-07-07T18:41:40
2023-07-07T18:41:40
18,598,087
282
59
BSD-3-Clause
2023-07-18T07:35:36
2014-04-09T13:25:46
C
UTF-8
C
false
false
12,917
c
gpanel-spi.c
/* * Generic TFT LCD driver with SPI interface. * Supported chips: ILI9341. * * Copyright (C) 2015 Serge Vakulenko <serge@vak.ru> * * Permission to use, copy, modify, and distribute this software * and its documentation for any purpose and without fee is hereby * granted, provided that the above copyright notice appear in all * copies and that both that the copyright notice and this * permission notice and warranty disclaimer appear in supporting * documentation, and that the name of the author not be used in * advertising or publicity pertaining to distribution of the * software without specific, written prior permission. * * The author disclaim all warranties with regard to this * software, including all implied warranties of merchantability * and fitness. In no event shall the author be liable for any * special, indirect or consequential damages or any damages * whatsoever resulting from loss of use, data or profits, whether * in an action of contract, negligence or other tortious action, * arising out of or in connection with the use or performance of * this software. */ #include <sys/param.h> #include <sys/conf.h> #include <sys/user.h> #include <sys/ioctl.h> #include <sys/systm.h> #include <sys/uio.h> #include <sys/tty.h> #include <sys/kconfig.h> #include <sys/spi.h> #include <sys/gpanel.h> #define SGPANEL_KHZ 10000 /* clock 10 MHz */ /* * Descriptor for access to the hardware-level driver. */ static struct gpanel_hw hw; /* * Cursor position for text output. */ static int _col, _row; /* * ID of the LCD controller chip. */ static int _chip_id; /* * Data/command signal pin. */ static int _dc; static int _last_dc = -1; /* last DC value */ static struct spiio _spiio; /* * Display size. */ int gpanel_width, gpanel_height; /* * Control /CS signal. */ void gpanel_cs_active() { spi_select(&_spiio); } void gpanel_cs_idle() { spi_deselect(&_spiio); } /* * Send a command to the SPI bus. */ int gpanel_send_command(int value) { if (_last_dc != 0) { gpio_clr(_dc); _last_dc = 0; } return spi_transfer(&_spiio, value); } /* * Send data to the SPI bus. */ int gpanel_send_data(int value) { if (_last_dc != 1) { gpio_set(_dc); _last_dc = 1; } return spi_transfer(&_spiio, value); } /* * Draw a line. */ static void gpanel_draw_line(int x0, int y0, int x1, int y1, int color) { int dx, dy, stepx, stepy, fraction; if (x0 == x1 || y0 == y1) { hw.fill_rectangle(x0, y0, x1, y1, color); return; } /* Use Bresenham's line algorithm. */ dy = y1 - y0; if (dy < 0) { dy = -dy; stepy = -1; } else { stepy = 1; } dx = x1 - x0; if (dx < 0) { dx = -dx; stepx = -1; } else { stepx = 1; } dy <<= 1; /* dy is now 2*dy */ dx <<= 1; /* dx is now 2*dx */ hw.set_pixel(x0, y0, color); if (dx > dy) { fraction = dy - (dx >> 1); /* same as 2*dy - dx */ while (x0 != x1) { if (fraction >= 0) { y0 += stepy; fraction -= dx; /* same as fraction -= 2*dx */ } x0 += stepx; fraction += dy; /* same as fraction -= 2*dy */ hw.set_pixel(x0, y0, color); } } else { fraction = dx - (dy >> 1); while (y0 != y1) { if (fraction >= 0) { x0 += stepx; fraction -= dy; } y0 += stepy; fraction += dx; hw.set_pixel(x0, y0, color); } } } /* * Draw a rectangular frame. */ static void gpanel_draw_frame(int x0, int y0, int x1, int y1, int color) { hw.fill_rectangle(x0, y0, x1, y0, color); hw.fill_rectangle(x0, y1, x1, y1, color); hw.fill_rectangle(x0, y0, x0, y1, color); hw.fill_rectangle(x1, y0, x1, y1, color); } /* * Draw a circle. */ static void gpanel_draw_circle(int x0, int y0, int radius, int color) { int f = 1 - radius; int ddF_x = 0; int ddF_y = -2 * radius; int x = 0; int y = radius; hw.set_pixel(x0, y0 + radius, color); hw.set_pixel(x0, y0 - radius, color); hw.set_pixel(x0 + radius, y0, color); hw.set_pixel(x0 - radius, y0, color); while (x < y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x + 1; hw.set_pixel(x0 + x, y0 + y, color); hw.set_pixel(x0 - x, y0 + y, color); hw.set_pixel(x0 + x, y0 - y, color); hw.set_pixel(x0 - x, y0 - y, color); hw.set_pixel(x0 + y, y0 + x, color); hw.set_pixel(x0 - y, y0 + x, color); hw.set_pixel(x0 + y, y0 - x, color); hw.set_pixel(x0 - y, y0 - x, color); } } /* * Draw a character from a specified font. */ static void gpanel_draw_char(const struct gpanel_font_t *font, int color, int background, int sym) { unsigned cindex, width; const unsigned short *bits; switch (sym) { case '\n': /* goto next line */ _row += font->height; _col = 0; if (_row > gpanel_height - font->height) _row = 0; return; case '\r': /* carriage return - go to begin of line */ _col = 0; return; case '\t': /* tab replaced by space */ sym = ' '; break; } if (sym < font->firstchar || sym >= font->firstchar + font->size) sym = font->defaultchar; cindex = sym - font->firstchar; /* Get font bitmap depending on fixed pitch or not. */ if (font->width) { /* Proportional font. */ width = font->width[cindex]; } else { /* Fixed width font. */ width = font->maxwidth; } if (font->offset) { bits = font->bits + font->offset[cindex]; } else { bits = font->bits + cindex * font->height; } /* Draw a character. */ hw.draw_glyph(font, color, background, _col, _row, width, bits); _col += width; } /* * Draw a string of characters. * TODO: Decode UTF-8. */ static void gpanel_draw_text(const struct gpanel_font_t *font, int color, int background, int x, int y, const char *text) { int sym; _col = x; _row = y; for (;;) { sym = *text++; if (! sym) break; gpanel_draw_char(font, color, background, sym); } } int gpanel_open(dev_t dev, int flag, int mode) { if (minor(dev) != 0) return ENODEV; return 0; } int gpanel_close(dev_t dev, int flag, int mode) { return 0; } int gpanel_read(dev_t dev, struct uio *uio, int flag) { return ENODEV; } int gpanel_write(dev_t dev, struct uio *uio, int flag) { return ENODEV; } /* * TODO: check whether user pointers are valid. */ int gpanel_ioctl(dev_t dev, register u_int cmd, caddr_t addr, int flag) { switch (cmd) { /* * Clear the whole screen with a given color. */ case GPANEL_CLEAR: { struct gpanel_clear_t *param = (struct gpanel_clear_t*) addr; if (hw.resize != 0) hw.resize(&hw, param->xsize, param->ysize); hw.fill_rectangle(0, 0, gpanel_width - 1, gpanel_height - 1, param->color); param->xsize = gpanel_width; param->ysize = gpanel_height; break; } /* * Draw a single pixel. */ case GPANEL_PIXEL: { struct gpanel_pixel_t *param = (struct gpanel_pixel_t*) addr; hw.set_pixel(param->x, param->y, param->color); break; } /* * Draw a line. */ case GPANEL_LINE: { struct gpanel_line_t *param = (struct gpanel_line_t*) addr; gpanel_draw_line(param->x0, param->y0, param->x1, param->y1, param->color); break; } /* * Draw a rectangle frame. */ case GPANEL_RECT: { struct gpanel_rect_t *param = (struct gpanel_rect_t*) addr; gpanel_draw_frame(param->x0, param->y0, param->x1, param->y1, param->color); break; } /* * Fill a rectangle with color. */ case GPANEL_FILL: { struct gpanel_rect_t *param = (struct gpanel_rect_t*) addr; hw.fill_rectangle(param->x0, param->y0, param->x1, param->y1, param->color); break; } /* * Draw a circle. */ case GPANEL_CIRCLE: { struct gpanel_circle_t *param = (struct gpanel_circle_t*) addr; gpanel_draw_circle(param->x, param->y, param->radius, param->color); break; } /* * Fill a rectangular area with the user-supplied data. */ case GPANEL_IMAGE: { struct gpanel_image_t *param = (struct gpanel_image_t*) addr; hw.draw_image(param->x, param->y, param->width, param->height, param->image); break; } /* * Draw a character. */ case GPANEL_CHAR: { struct gpanel_char_t *param = (struct gpanel_char_t*) addr; _col = param->x; _row = param->y; gpanel_draw_char(param->font, param->color, param->background, param->sym); break; } /* * Draw a string of characters. */ case GPANEL_TEXT: { struct gpanel_text_t *param = (struct gpanel_text_t*) addr; gpanel_draw_text(param->font, param->color, param->background, param->x, param->y, param->text); break; } } return 0; } /* * Draw a BSD logo on the screen. */ static void draw_logo() { #define K 7 #define COLOR_B 0xf81f #define COLOR_S 0x07ff #define COLOR_D 0xffe0 int x = gpanel_width/2 - 17*K; int y = gpanel_height/2 + 11*K; hw.fill_rectangle(0, 0, gpanel_width - 1, gpanel_height - 1, 0); /* B */ gpanel_draw_line( 0*K+x, y- 0*K, 0*K+x, y-11*K, COLOR_B); gpanel_draw_line( 0*K+x, y-11*K, 0*K+x, y-22*K, COLOR_B); gpanel_draw_line( 0*K+x, y-22*K, 10*K+x, y-19*K, COLOR_B); gpanel_draw_line(10*K+x, y-19*K, 0*K+x, y-11*K, COLOR_B); gpanel_draw_line( 0*K+x, y-11*K, 10*K+x, y- 8*K, COLOR_B); gpanel_draw_line(10*K+x, y- 8*K, 0*K+x, y- 0*K, COLOR_B); /* S */ gpanel_draw_line(22*K+x, y-22*K, 12*K+x, y-19*K, COLOR_S); gpanel_draw_line(12*K+x, y-19*K, 22*K+x, y- 8*K, COLOR_S); gpanel_draw_line(22*K+x, y- 8*K, 12*K+x, y- 0*K, COLOR_S); /* D */ gpanel_draw_line(24*K+x, y-22*K, 24*K+x, y- 0*K, COLOR_D); gpanel_draw_line(24*K+x, y-22*K, 34*K+x, y-19*K, COLOR_D); gpanel_draw_line(34*K+x, y-19*K, 34*K+x, y- 8*K, COLOR_D); gpanel_draw_line(34*K+x, y- 8*K, 24*K+x, y- 0*K, COLOR_D); } /* * Read the chip ID register. */ static int read_id() { int id; /* Read ID4 from register #D3. * Use undocumented command #D9 to get access to ID4. */ gpanel_cs_active(); gpanel_send_command(0xD9); gpanel_send_data(0x11); gpanel_send_command(0xD3); id = gpanel_send_data(0xff) << 16; gpanel_send_command(0xD9); gpanel_send_data(0x12); gpanel_send_command(0xD3); id |= gpanel_send_data(0xff) << 8; gpanel_send_command(0xD9); gpanel_send_data(0x13); gpanel_send_command(0xD3); id |= gpanel_send_data(0xff); gpanel_cs_idle(); return id; } /* * Detect the type of the LCD controller, and initialize it. * Return true if found and initialized ok. */ static int probe(config) struct conf_device *config; { int cs; struct spiio *io = &_spiio; /* Only one device is allowed. */ if (config->dev_unit > 0) return 0; cs = config->dev_pins[0]; _dc = config->dev_pins[1]; printf("sgpanel: port SPI%d, pins cs=R%c%d/dc=R%c%d\n", config->dev_ctlr, gpio_portname(cs), gpio_pinno(cs), gpio_portname(_dc), gpio_pinno(_dc)); if (spi_setup(io, config->dev_ctlr, cs) != 0) { printf("sgpanel: cannot open SPI%u port\n", config->dev_ctlr); return 0; } spi_brg(io, SGPANEL_KHZ); spi_set(io, PIC32_SPICON_CKE); gpio_set_output(_dc); /* Identify the LCD controller chip. */ _chip_id = read_id(); switch (_chip_id) { default: /* Disable outputs. */ gpio_set_input(_dc); gpio_set_input(cs); printf("gpanel0: Unknown chip ID = 0x%04x\n", _chip_id); return 0; case 0x009341: /* Ilitek ILI9341. */ ili9341_init_display(&hw); break; } printf("gpanel0: <%s> display %ux%u\n", hw.name, gpanel_width, gpanel_height); draw_logo(); return 1; } struct driver sgpaneldriver = { "sgpanel", probe, };
b56676404bf6efae6d7f46642aa100c2a18b23fc
a09d2734b97a58d06e79182666a4ebc27360d3d5
/vkFFT/vkFFT/vkFFT_PlanManagement/vkFFT_HostFunctions/vkFFT_AxisBlockSplitter.h
d48c9756d140597e8009cc1f62c38e422b9c2e78
[ "MIT" ]
permissive
DTolm/VkFFT
9c4aadb51ab776918822c7483fc1f6db62eba415
116bf7ff92a9dde115957bb7beb33c2d89c87fda
refs/heads/master
2023-08-10T03:53:00.613036
2023-08-01T17:42:19
2023-08-01T17:42:19
284,421,891
1,320
77
MIT
2023-09-12T23:27:43
2020-08-02T08:28:36
C++
UTF-8
C
false
false
37,998
h
vkFFT_AxisBlockSplitter.h
// This file is part of VkFFT // // Copyright (C) 2021 - present Dmitrii Tolmachev <dtolm96@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef VKFFT_AXISBLOCKSPLITTER_H #define VKFFT_AXISBLOCKSPLITTER_H #include "vkFFT/vkFFT_Structs/vkFFT_Structs.h" static inline VkFFTResult VkFFTSplitAxisBlock(VkFFTApplication* app, VkFFTPlan* FFTPlan, VkFFTAxis* axis, uint64_t axis_id, uint64_t axis_upload_id, uint64_t allowedSharedMemory, uint64_t allowedSharedMemoryPow2) { uint64_t maxBatchCoalesced = app->configuration.coalescedMemory / axis->specializationConstants.complexSize; axis->groupedBatch = maxBatchCoalesced; uint64_t maxSequenceLengthSharedMemory = allowedSharedMemory / axis->specializationConstants.complexSize; uint64_t maxSequenceLengthSharedMemoryPow2 = allowedSharedMemoryPow2 / axis->specializationConstants.complexSize; uint64_t maxSingleSizeStrided = (app->configuration.coalescedMemory > axis->specializationConstants.complexSize) ? allowedSharedMemory / (app->configuration.coalescedMemory) : allowedSharedMemory / axis->specializationConstants.complexSize; uint64_t maxSingleSizeStridedPow2 = (app->configuration.coalescedMemory > axis->specializationConstants.complexSize) ? allowedSharedMemoryPow2 / (app->configuration.coalescedMemory) : allowedSharedMemoryPow2 / axis->specializationConstants.complexSize; if (((FFTPlan->numAxisUploads[axis_id] == 1) && (axis_id == 0)) || ((axis_id == 0) && (!axis->specializationConstants.reorderFourStep) && (axis_upload_id == 0))) { axis->groupedBatch = (maxSequenceLengthSharedMemory / axis->specializationConstants.fftDim.data.i > axis->groupedBatch) ? maxSequenceLengthSharedMemory / axis->specializationConstants.fftDim.data.i : axis->groupedBatch; } else { axis->groupedBatch = (maxSingleSizeStrided / axis->specializationConstants.fftDim.data.i > 1) ? maxSingleSizeStrided / axis->specializationConstants.fftDim.data.i * axis->groupedBatch : axis->groupedBatch; } if (app->configuration.groupedBatch[axis_id]) { uint64_t maxThreadNum = app->configuration.maxThreadsNum; axis->specializationConstants.axisSwapped = 0; uint64_t r2cmult = (axis->specializationConstants.mergeSequencesR2C) ? 2 : 1; if (axis_id == 0) { if (axis_upload_id == 0) { axis->axisBlock[0] = (((uint64_t)ceil(axis->specializationConstants.fftDim.data.i / (double)axis->specializationConstants.min_registers_per_thread)) / axis->specializationConstants.registerBoost > 1) ? ((uint64_t)ceil(axis->specializationConstants.fftDim.data.i / (double)axis->specializationConstants.min_registers_per_thread)) / axis->specializationConstants.registerBoost : 1; if (axis->specializationConstants.useRaderMult) { uint64_t locMaxBatchCoalesced = ((axis_id == 0) && (((axis_upload_id == 0) && ((!app->configuration.reorderFourStep) || (app->useBluesteinFFT[axis_id]))) || (axis->specializationConstants.numAxisUploads == 1))) ? 1 : maxBatchCoalesced; uint64_t final_rader_thread_count = 0; for (uint64_t i = 0; i < axis->specializationConstants.numRaderPrimes; i++) { if (axis->specializationConstants.raderContainer[i].type == 1) { uint64_t temp_rader = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / (double)((axis->specializationConstants.rader_min_registers / 2) * 2)) / (double)((axis->specializationConstants.raderContainer[i].prime + 1) / 2)); uint64_t active_rader = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)temp_rader); if (active_rader > 1) { if ((((double)active_rader - (axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)temp_rader) >= 0.5) && ((((uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)(active_rader - 1)) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2)) * locMaxBatchCoalesced) <= app->configuration.maxThreadsNum)) active_rader--; } uint64_t local_estimate_rader_threadnum = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)active_rader) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2); uint64_t temp_rader_thread_count = ((uint64_t)ceil(axis->axisBlock[0] / (double)((axis->specializationConstants.raderContainer[i].prime + 1) / 2))) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2); if (temp_rader_thread_count < local_estimate_rader_threadnum) temp_rader_thread_count = local_estimate_rader_threadnum; if (temp_rader_thread_count > final_rader_thread_count) final_rader_thread_count = temp_rader_thread_count; } } axis->axisBlock[0] = final_rader_thread_count; if (axis->axisBlock[0] * axis->groupedBatch > maxThreadNum) axis->groupedBatch = locMaxBatchCoalesced; } if (axis->specializationConstants.useRaderFFT) { if (axis->axisBlock[0] < axis->specializationConstants.minRaderFFTThreadNum) axis->axisBlock[0] = axis->specializationConstants.minRaderFFTThreadNum; } if (axis->axisBlock[0] > maxThreadNum) axis->axisBlock[0] = maxThreadNum; if (axis->axisBlock[0] > app->configuration.maxComputeWorkGroupSize[0]) axis->axisBlock[0] = app->configuration.maxComputeWorkGroupSize[0]; axis->axisBlock[1] = (axis->groupedBatch > app->configuration.groupedBatch[0]) ? app->configuration.groupedBatch[0] : axis->groupedBatch; if (axis->axisBlock[0] * axis->axisBlock[1] > maxThreadNum) { axis->axisBlock[1] = maxThreadNum / axis->axisBlock[0]; } while ((axis->axisBlock[1] * (axis->specializationConstants.fftDim.data.i / axis->specializationConstants.registerBoost)) > maxSequenceLengthSharedMemory) axis->axisBlock[1] /= 2; axis->groupedBatch = axis->axisBlock[1]; if (((axis->specializationConstants.fftDim.data.i % 2 == 0) || (axis->axisBlock[0] < app->configuration.numSharedBanks / 4)) && (!(((!axis->specializationConstants.reorderFourStep) || (axis->specializationConstants.useBluesteinFFT)) && (FFTPlan->numAxisUploads[0] > 1))) && (axis->axisBlock[1] > 1) && (axis->axisBlock[1] * axis->specializationConstants.fftDim.data.i < maxSequenceLengthSharedMemory) && (!((app->configuration.performZeropadding[0] || app->configuration.performZeropadding[1] || app->configuration.performZeropadding[2])))) { /*#if (VKFFT_BACKEND==0) if (((axis->specializationConstants.fftDim & (axis->specializationConstants.fftDim - 1)) != 0)) { uint64_t temp = axis->axisBlock[1]; axis->axisBlock[1] = axis->axisBlock[0]; axis->axisBlock[0] = temp; axis->specializationConstants.axisSwapped = 1; } #else*/ uint64_t temp = axis->axisBlock[1]; axis->axisBlock[1] = axis->axisBlock[0]; axis->axisBlock[0] = temp; axis->specializationConstants.axisSwapped = 1; //#endif } axis->axisBlock[2] = 1; axis->axisBlock[3] = axis->specializationConstants.fftDim.data.i; } else { axis->axisBlock[1] = ((uint64_t)ceil(axis->specializationConstants.fftDim.data.i / (double)axis->specializationConstants.min_registers_per_thread) / axis->specializationConstants.registerBoost > 1) ? (uint64_t)ceil(axis->specializationConstants.fftDim.data.i / (double)axis->specializationConstants.min_registers_per_thread) / axis->specializationConstants.registerBoost : 1; if (axis->specializationConstants.useRaderMult) { uint64_t final_rader_thread_count = 0; for (uint64_t i = 0; i < axis->specializationConstants.numRaderPrimes; i++) { if (axis->specializationConstants.raderContainer[i].type == 1) { uint64_t temp_rader = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / (double)((axis->specializationConstants.rader_min_registers / 2) * 2)) / (double)((axis->specializationConstants.raderContainer[i].prime + 1) / 2)); uint64_t active_rader = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)temp_rader); if (active_rader > 1) { if ((((double)active_rader - (axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)temp_rader) >= 0.5) && ((((uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)(active_rader - 1)) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2)) * maxBatchCoalesced) <= app->configuration.maxThreadsNum)) active_rader--; } uint64_t local_estimate_rader_threadnum = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)active_rader) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2); uint64_t temp_rader_thread_count = ((uint64_t)ceil(axis->axisBlock[1] / (double)((axis->specializationConstants.raderContainer[i].prime + 1) / 2))) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2); if (temp_rader_thread_count < local_estimate_rader_threadnum) temp_rader_thread_count = local_estimate_rader_threadnum; if (temp_rader_thread_count > final_rader_thread_count) final_rader_thread_count = temp_rader_thread_count; } } axis->axisBlock[1] = final_rader_thread_count; if (axis->groupedBatch * axis->axisBlock[1] > maxThreadNum) axis->groupedBatch = maxBatchCoalesced; } if (axis->specializationConstants.useRaderFFT) { if (axis->axisBlock[1] < axis->specializationConstants.minRaderFFTThreadNum) axis->axisBlock[1] = axis->specializationConstants.minRaderFFTThreadNum; } uint64_t scale = app->configuration.aimThreads / axis->axisBlock[1] / axis->groupedBatch; if ((scale > 1) && ((axis->specializationConstants.fftDim.data.i * axis->groupedBatch * scale <= maxSequenceLengthSharedMemory))) axis->groupedBatch *= scale; axis->axisBlock[0] = ((uint64_t)axis->specializationConstants.stageStartSize.data.i > axis->groupedBatch) ? axis->groupedBatch : (uint64_t)axis->specializationConstants.stageStartSize.data.i; if (app->configuration.vendorID == 0x10DE) { while ((axis->axisBlock[1] * axis->axisBlock[0] >= 2 * app->configuration.aimThreads) && (axis->axisBlock[0] > maxBatchCoalesced)) { axis->axisBlock[0] /= 2; if (axis->axisBlock[0] < maxBatchCoalesced) axis->axisBlock[0] = maxBatchCoalesced; } } if (axis->axisBlock[0] > app->configuration.maxComputeWorkGroupSize[0]) axis->axisBlock[0] = app->configuration.maxComputeWorkGroupSize[0]; if (axis->axisBlock[0] * axis->axisBlock[1] > maxThreadNum) { for (uint64_t i = 1; i <= axis->axisBlock[0]; i++) { if ((axis->axisBlock[0] / i) * axis->axisBlock[1] <= maxThreadNum) { axis->axisBlock[0] /= i; i = axis->axisBlock[0] + 1; } } } axis->axisBlock[2] = 1; axis->axisBlock[3] = axis->specializationConstants.fftDim.data.i; axis->groupedBatch = axis->axisBlock[0]; } } if (axis_id >= 1) { axis->axisBlock[1] = ((uint64_t)ceil(axis->specializationConstants.fftDim.data.i / (double)axis->specializationConstants.min_registers_per_thread) / axis->specializationConstants.registerBoost > 1) ? ((uint64_t)ceil(axis->specializationConstants.fftDim.data.i / (double)axis->specializationConstants.min_registers_per_thread)) / axis->specializationConstants.registerBoost : 1; if (axis->specializationConstants.useRaderMult) { uint64_t final_rader_thread_count = 0; for (uint64_t i = 0; i < axis->specializationConstants.numRaderPrimes; i++) { if (axis->specializationConstants.raderContainer[i].type == 1) { uint64_t temp_rader = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / (double)((axis->specializationConstants.rader_min_registers / 2) * 2)) / (double)((axis->specializationConstants.raderContainer[i].prime + 1) / 2)); uint64_t active_rader = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)temp_rader); if (active_rader > 1) { if ((((double)active_rader - (axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)temp_rader) >= 0.5) && ((((uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)(active_rader - 1)) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2)) * maxBatchCoalesced) <= app->configuration.maxThreadsNum)) active_rader--; } uint64_t local_estimate_rader_threadnum = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)active_rader) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2); uint64_t temp_rader_thread_count = ((uint64_t)ceil(axis->axisBlock[1] / (double)((axis->specializationConstants.raderContainer[i].prime + 1) / 2))) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2); if (temp_rader_thread_count < local_estimate_rader_threadnum) temp_rader_thread_count = local_estimate_rader_threadnum; if (temp_rader_thread_count > final_rader_thread_count) final_rader_thread_count = temp_rader_thread_count; } } axis->axisBlock[1] = final_rader_thread_count; if (axis->groupedBatch * axis->axisBlock[1] > maxThreadNum) axis->groupedBatch = maxBatchCoalesced; } if (axis->specializationConstants.useRaderFFT) { if (axis->axisBlock[1] < axis->specializationConstants.minRaderFFTThreadNum) axis->axisBlock[1] = axis->specializationConstants.minRaderFFTThreadNum; } axis->axisBlock[0] = (FFTPlan->actualFFTSizePerAxis[axis_id][0] > axis->groupedBatch) ? axis->groupedBatch : FFTPlan->actualFFTSizePerAxis[axis_id][0]; axis->axisBlock[0] = (axis->axisBlock[0] > app->configuration.groupedBatch[1]) ? app->configuration.groupedBatch[axis_id] : axis->axisBlock[0]; if (axis->axisBlock[0] > app->configuration.maxComputeWorkGroupSize[0]) axis->axisBlock[0] = app->configuration.maxComputeWorkGroupSize[0]; if (axis->axisBlock[0] * axis->axisBlock[1] > maxThreadNum) { axis->axisBlock[0] = maxThreadNum / axis->axisBlock[0]; } axis->axisBlock[2] = 1; axis->axisBlock[3] = axis->specializationConstants.fftDim.data.i; axis->groupedBatch = axis->axisBlock[0]; } return VKFFT_SUCCESS; } /*if ((FFTPlan->actualFFTSizePerAxis[axis_id][0] < 4096) && (FFTPlan->actualFFTSizePerAxis[axis_id][1] < 512) && (FFTPlan->actualFFTSizePerAxis[axis_id][2] == 1)) { if (app->configuration.sharedMemorySize / axis->specializationConstants.fftDim >= app->configuration.coalescedMemory) { if (1024 / axis->specializationConstants.fftDim < maxSequenceLengthSharedMemory / axis->specializationConstants.fftDim) { if (1024 / axis->specializationConstants.fftDim > axis->groupedBatch) axis->groupedBatch = 1024 / axis->specializationConstants.fftDim; else axis->groupedBatch = maxSequenceLengthSharedMemory / axis->specializationConstants.fftDim; } } } else { axis->groupedBatch = (app->configuration.sharedMemorySize / axis->specializationConstants.fftDim >= app->configuration.coalescedMemory) ? maxSequenceLengthSharedMemory / axis->specializationConstants.fftDim : axis->groupedBatch; }*/ //if (axis->groupedBatch * (uint64_t)ceil(axis->specializationConstants.fftDim / 8.0) < app->configuration.warpSize) axis->groupedBatch = app->configuration.warpSize / (uint64_t)ceil(axis->specializationConstants.fftDim / 8.0); //axis->groupedBatch = (app->configuration.sharedMemorySize / axis->specializationConstants.fftDim >= app->configuration.coalescedMemory) ? maxSequenceLengthSharedMemory / axis->specializationConstants.fftDim : axis->groupedBatch; //axis->groupedBatch = 8; //shared memory bank conflict resolve //#if(VKFFT_BACKEND!=2)//for some reason, hip doesn't get performance increase from having variable shared memory strides. if (app->configuration.vendorID == 0x10DE) { if (FFTPlan->numAxisUploads[axis_id] == 2) { if ((axis_upload_id > 0) || (axis->specializationConstants.fftDim.data.i <= 512)) { if ((uint64_t)(axis->specializationConstants.fftDim.data.i * (64 / axis->specializationConstants.complexSize)) <= maxSequenceLengthSharedMemory) { axis->groupedBatch = 64 / axis->specializationConstants.complexSize; maxBatchCoalesced = 64 / axis->specializationConstants.complexSize; } if ((uint64_t)(axis->specializationConstants.fftDim.data.i * (128 / axis->specializationConstants.complexSize)) <= maxSequenceLengthSharedMemory) { axis->groupedBatch = 128 / axis->specializationConstants.complexSize; maxBatchCoalesced = 128 / axis->specializationConstants.complexSize; } } } //#endif if (FFTPlan->numAxisUploads[axis_id] == 3) { if ((uint64_t)(axis->specializationConstants.fftDim.data.i * (64 / axis->specializationConstants.complexSize)) <= maxSequenceLengthSharedMemory) { axis->groupedBatch = 64 / axis->specializationConstants.complexSize; maxBatchCoalesced = 64 / axis->specializationConstants.complexSize; } if ((uint64_t)(axis->specializationConstants.fftDim.data.i * (128 / axis->specializationConstants.complexSize)) <= maxSequenceLengthSharedMemory) { axis->groupedBatch = 128 / axis->specializationConstants.complexSize; maxBatchCoalesced = 128 / axis->specializationConstants.complexSize; } } } else { if ((FFTPlan->numAxisUploads[axis_id] == 2) && (axis_upload_id == 0) && (axis->specializationConstants.fftDim.data.i * maxBatchCoalesced <= maxSequenceLengthSharedMemory)) { axis->groupedBatch = (uint64_t)ceil(axis->groupedBatch / 2.0); } //#endif if ((FFTPlan->numAxisUploads[axis_id] == 3) && (axis_upload_id == 0) && ((uint64_t)axis->specializationConstants.fftDim.data.i < maxSequenceLengthSharedMemory / (2 * axis->specializationConstants.complexSize))) { axis->groupedBatch = (uint64_t)ceil(axis->groupedBatch / 2.0); } } if (axis->groupedBatch < maxBatchCoalesced) axis->groupedBatch = maxBatchCoalesced; axis->groupedBatch = (axis->groupedBatch / maxBatchCoalesced) * maxBatchCoalesced; //half bandiwdth technique if (!((axis_id == 0) && (FFTPlan->numAxisUploads[axis_id] == 1)) && !((axis_id == 0) && (axis_upload_id == 0) && (!axis->specializationConstants.reorderFourStep)) && ((uint64_t)axis->specializationConstants.fftDim.data.i > maxSingleSizeStrided)) { axis->groupedBatch = maxSequenceLengthSharedMemory / axis->specializationConstants.fftDim.data.i; if (axis->groupedBatch == 0) axis->groupedBatch = 1; } if ((app->configuration.halfThreads) && (axis->groupedBatch * axis->specializationConstants.fftDim.data.i * axis->specializationConstants.complexSize >= app->configuration.sharedMemorySize)) axis->groupedBatch = (uint64_t)ceil(axis->groupedBatch / 2.0); if (axis->groupedBatch > app->configuration.warpSize) axis->groupedBatch = (axis->groupedBatch / app->configuration.warpSize) * app->configuration.warpSize; if (axis->groupedBatch > 2 * maxBatchCoalesced) axis->groupedBatch = (axis->groupedBatch / (2 * maxBatchCoalesced)) * (2 * maxBatchCoalesced); if (axis->groupedBatch > 4 * maxBatchCoalesced) axis->groupedBatch = (axis->groupedBatch / (4 * maxBatchCoalesced)) * (4 * maxBatchCoalesced); //uint64_t maxThreadNum = (axis_id) ? (maxSingleSizeStrided * app->configuration.coalescedMemory / axis->specializationConstants.complexSize) / (axis->specializationConstants.min_registers_per_thread * axis->specializationConstants.registerBoost) : maxSequenceLengthSharedMemory / (axis->specializationConstants.min_registers_per_thread * axis->specializationConstants.registerBoost); //if (maxThreadNum > app->configuration.maxThreadsNum) maxThreadNum = app->configuration.maxThreadsNum; uint64_t maxThreadNum = app->configuration.maxThreadsNum; axis->specializationConstants.axisSwapped = 0; uint64_t r2cmult = (axis->specializationConstants.mergeSequencesR2C) ? 2 : 1; if (axis_id == 0) { if (axis_upload_id == 0) { axis->axisBlock[0] = (((uint64_t)ceil(axis->specializationConstants.fftDim.data.i / (double)axis->specializationConstants.min_registers_per_thread)) / axis->specializationConstants.registerBoost > 1) ? ((uint64_t)ceil(axis->specializationConstants.fftDim.data.i / (double)axis->specializationConstants.min_registers_per_thread)) / axis->specializationConstants.registerBoost : 1; if (axis->specializationConstants.useRaderMult) { uint64_t locMaxBatchCoalesced = ((axis_id == 0) && (((axis_upload_id == 0) && ((!app->configuration.reorderFourStep) || (app->useBluesteinFFT[axis_id]))) || (axis->specializationConstants.numAxisUploads == 1))) ? 1 : maxBatchCoalesced; uint64_t final_rader_thread_count = 0; for (uint64_t i = 0; i < axis->specializationConstants.numRaderPrimes; i++) { if (axis->specializationConstants.raderContainer[i].type == 1) { uint64_t temp_rader = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / (double)((axis->specializationConstants.rader_min_registers / 2) * 2)) / (double)((axis->specializationConstants.raderContainer[i].prime + 1) / 2)); uint64_t active_rader = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)temp_rader); if (active_rader > 1) { if ((((double)active_rader - (axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)temp_rader) >= 0.5) && ((((uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)(active_rader - 1)) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2)) * locMaxBatchCoalesced) <= app->configuration.maxThreadsNum)) active_rader--; } uint64_t local_estimate_rader_threadnum = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)active_rader) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2); uint64_t temp_rader_thread_count = ((uint64_t)ceil(axis->axisBlock[0] / (double)((axis->specializationConstants.raderContainer[i].prime + 1) / 2))) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2); if (temp_rader_thread_count < local_estimate_rader_threadnum) temp_rader_thread_count = local_estimate_rader_threadnum; if (temp_rader_thread_count > final_rader_thread_count) final_rader_thread_count = temp_rader_thread_count; } } axis->axisBlock[0] = final_rader_thread_count; if (axis->axisBlock[0] * axis->groupedBatch > maxThreadNum) axis->groupedBatch = locMaxBatchCoalesced; } if (axis->specializationConstants.useRaderFFT) { if (axis->axisBlock[0] < axis->specializationConstants.minRaderFFTThreadNum) axis->axisBlock[0] = axis->specializationConstants.minRaderFFTThreadNum; } if (axis->axisBlock[0] > maxThreadNum) axis->axisBlock[0] = maxThreadNum; if (axis->axisBlock[0] > app->configuration.maxComputeWorkGroupSize[0]) axis->axisBlock[0] = app->configuration.maxComputeWorkGroupSize[0]; if (axis->specializationConstants.reorderFourStep && (FFTPlan->numAxisUploads[axis_id] > 1)) axis->axisBlock[1] = axis->groupedBatch; else { //axis->axisBlock[1] = (axis->axisBlock[0] < app->configuration.warpSize) ? app->configuration.warpSize / axis->axisBlock[0] : 1; uint64_t estimate_batch = (((axis->axisBlock[0] / app->configuration.warpSize) == 1) && ((axis->axisBlock[0] / (double)app->configuration.warpSize) < 1.5)) ? app->configuration.aimThreads / app->configuration.warpSize : app->configuration.aimThreads / axis->axisBlock[0]; if (estimate_batch == 0) estimate_batch = 1; axis->axisBlock[1] = ((axis->axisBlock[0] < app->configuration.aimThreads) && ((axis->axisBlock[0] < app->configuration.warpSize) || (axis->specializationConstants.useRader))) ? estimate_batch : 1; } uint64_t currentAxisBlock1 = axis->axisBlock[1]; for (uint64_t i = currentAxisBlock1; i < 2 * currentAxisBlock1; i++) { if (((FFTPlan->numAxisUploads[0] > 1) && (!(((FFTPlan->actualFFTSizePerAxis[axis_id][0] / axis->specializationConstants.fftDim.data.i) % axis->axisBlock[1]) == 0))) || ((FFTPlan->numAxisUploads[0] == 1) && (!(((FFTPlan->actualFFTSizePerAxis[axis_id][1] / r2cmult) % axis->axisBlock[1]) == 0)))) { if (i * axis->specializationConstants.fftDim.data.i * axis->specializationConstants.complexSize <= allowedSharedMemory) axis->axisBlock[1] = i; i = 2 * currentAxisBlock1; } } if (((axis->specializationConstants.fftDim.data.i % 2 == 0) || (axis->axisBlock[0] < app->configuration.numSharedBanks / 4)) && (!(((!axis->specializationConstants.reorderFourStep) || (axis->specializationConstants.useBluesteinFFT)) && (FFTPlan->numAxisUploads[0] > 1))) && (axis->axisBlock[1] > 1) && (axis->axisBlock[1] * axis->specializationConstants.fftDim.data.i < maxSequenceLengthSharedMemoryPow2) && (!((app->configuration.performZeropadding[0] || app->configuration.performZeropadding[1] || app->configuration.performZeropadding[2])))) { //we plan to swap - this reduces bank conflicts axis->axisBlock[1] = (uint64_t)pow(2, (uint64_t)ceil(log2((double)axis->axisBlock[1]))); } if ((FFTPlan->numAxisUploads[0] > 1) && ((uint64_t)ceil(FFTPlan->actualFFTSizePerAxis[axis_id][0] / axis->specializationConstants.fftDim.data.i) < axis->axisBlock[1])) axis->axisBlock[1] = (uint64_t)ceil(FFTPlan->actualFFTSizePerAxis[axis_id][0] / axis->specializationConstants.fftDim.data.i); if ((axis->specializationConstants.mergeSequencesR2C != 0) && (axis->specializationConstants.fftDim.data.i * axis->axisBlock[1] >= maxSequenceLengthSharedMemory)) { axis->specializationConstants.mergeSequencesR2C = 0; /*if ((!inverse) && (axis_id == 0) && (axis_upload_id == 0) && (!(app->configuration.isInputFormatted))) { axis->specializationConstants.inputStride[1] /= 2; axis->specializationConstants.inputStride[2] /= 2; axis->specializationConstants.inputStride[3] /= 2; axis->specializationConstants.inputStride[4] /= 2; } if ((inverse) && (axis_id == 0) && (axis_upload_id == 0) && (!((app->configuration.isInputFormatted) && (app->configuration.inverseReturnToInputBuffer))) && (!app->configuration.isOutputFormatted)) { axis->specializationConstants.outputStride[1] /= 2; axis->specializationConstants.outputStride[2] /= 2; axis->specializationConstants.outputStride[3] /= 2; axis->specializationConstants.outputStride[4] /= 2; }*/ r2cmult = 1; } if ((FFTPlan->numAxisUploads[0] == 1) && ((uint64_t)ceil(FFTPlan->actualFFTSizePerAxis[axis_id][1] / (double)r2cmult) < axis->axisBlock[1])) axis->axisBlock[1] = (uint64_t)ceil(FFTPlan->actualFFTSizePerAxis[axis_id][1] / (double)r2cmult); if (app->configuration.vendorID == 0x10DE) { while ((axis->axisBlock[1] * axis->axisBlock[0] >= 2 * app->configuration.aimThreads) && (axis->axisBlock[1] > maxBatchCoalesced)) { axis->axisBlock[1] /= 2; if (axis->axisBlock[1] < maxBatchCoalesced) axis->axisBlock[1] = maxBatchCoalesced; } } if (axis->axisBlock[1] > app->configuration.maxComputeWorkGroupSize[1]) axis->axisBlock[1] = app->configuration.maxComputeWorkGroupSize[1]; //if (axis->axisBlock[0] * axis->axisBlock[1] > app->configuration.maxThreadsNum) axis->axisBlock[1] /= 2; if (axis->axisBlock[0] * axis->axisBlock[1] > maxThreadNum) { for (uint64_t i = 1; i <= axis->axisBlock[1]; i++) { if ((axis->axisBlock[1] / i) * axis->axisBlock[0] <= maxThreadNum) { axis->axisBlock[1] /= i; i = axis->axisBlock[1] + 1; } } } while ((axis->axisBlock[1] * (axis->specializationConstants.fftDim.data.i / axis->specializationConstants.registerBoost)) > maxSequenceLengthSharedMemory) axis->axisBlock[1] /= 2; axis->groupedBatch = axis->axisBlock[1]; if (((axis->specializationConstants.fftDim.data.i % 2 == 0) || (axis->axisBlock[0] < app->configuration.numSharedBanks / 4)) && (!(((!axis->specializationConstants.reorderFourStep) || (axis->specializationConstants.useBluesteinFFT)) && (FFTPlan->numAxisUploads[0] > 1))) && (axis->axisBlock[1] > 1) && (axis->axisBlock[1] * axis->specializationConstants.fftDim.data.i < maxSequenceLengthSharedMemory) && (!((app->configuration.performZeropadding[0] || app->configuration.performZeropadding[1] || app->configuration.performZeropadding[2])))) { /*#if (VKFFT_BACKEND==0) if (((axis->specializationConstants.fftDim & (axis->specializationConstants.fftDim - 1)) != 0)) { uint64_t temp = axis->axisBlock[1]; axis->axisBlock[1] = axis->axisBlock[0]; axis->axisBlock[0] = temp; axis->specializationConstants.axisSwapped = 1; } #else*/ uint64_t temp = axis->axisBlock[1]; axis->axisBlock[1] = axis->axisBlock[0]; axis->axisBlock[0] = temp; axis->specializationConstants.axisSwapped = 1; //#endif } axis->axisBlock[2] = 1; axis->axisBlock[3] = axis->specializationConstants.fftDim.data.i; } else { axis->axisBlock[1] = ((uint64_t)ceil(axis->specializationConstants.fftDim.data.i / (double)axis->specializationConstants.min_registers_per_thread) / axis->specializationConstants.registerBoost > 1) ? (uint64_t)ceil(axis->specializationConstants.fftDim.data.i / (double)axis->specializationConstants.min_registers_per_thread) / axis->specializationConstants.registerBoost : 1; if (axis->specializationConstants.useRaderMult) { uint64_t final_rader_thread_count = 0; for (uint64_t i = 0; i < axis->specializationConstants.numRaderPrimes; i++) { if (axis->specializationConstants.raderContainer[i].type == 1) { uint64_t temp_rader = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / (double)((axis->specializationConstants.rader_min_registers / 2) * 2)) / (double)((axis->specializationConstants.raderContainer[i].prime + 1) / 2)); uint64_t active_rader = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)temp_rader); if (active_rader > 1) { if ((((double)active_rader - (axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)temp_rader) >= 0.5) && ((((uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)(active_rader - 1)) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2)) * maxBatchCoalesced) <= app->configuration.maxThreadsNum)) active_rader--; } uint64_t local_estimate_rader_threadnum = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)active_rader) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2); uint64_t temp_rader_thread_count = ((uint64_t)ceil(axis->axisBlock[1] / (double)((axis->specializationConstants.raderContainer[i].prime + 1) / 2))) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2); if (temp_rader_thread_count < local_estimate_rader_threadnum) temp_rader_thread_count = local_estimate_rader_threadnum; if (temp_rader_thread_count > final_rader_thread_count) final_rader_thread_count = temp_rader_thread_count; } } axis->axisBlock[1] = final_rader_thread_count; if (axis->groupedBatch * axis->axisBlock[1] > maxThreadNum) axis->groupedBatch = maxBatchCoalesced; } if (axis->specializationConstants.useRaderFFT) { if (axis->axisBlock[1] < axis->specializationConstants.minRaderFFTThreadNum) axis->axisBlock[1] = axis->specializationConstants.minRaderFFTThreadNum; } uint64_t scale = app->configuration.aimThreads / axis->axisBlock[1] / axis->groupedBatch; if ((scale > 1) && ((axis->specializationConstants.fftDim.data.i * axis->groupedBatch * scale <= maxSequenceLengthSharedMemory))) axis->groupedBatch *= scale; axis->axisBlock[0] = ((uint64_t)axis->specializationConstants.stageStartSize.data.i > axis->groupedBatch) ? axis->groupedBatch : axis->specializationConstants.stageStartSize.data.i; if (app->configuration.vendorID == 0x10DE) { while ((axis->axisBlock[1] * axis->axisBlock[0] >= 2 * app->configuration.aimThreads) && (axis->axisBlock[0] > maxBatchCoalesced)) { axis->axisBlock[0] /= 2; if (axis->axisBlock[0] < maxBatchCoalesced) axis->axisBlock[0] = maxBatchCoalesced; } } if (axis->axisBlock[0] > app->configuration.maxComputeWorkGroupSize[0]) axis->axisBlock[0] = app->configuration.maxComputeWorkGroupSize[0]; if (axis->axisBlock[0] * axis->axisBlock[1] > maxThreadNum) { for (uint64_t i = 1; i <= axis->axisBlock[0]; i++) { if ((axis->axisBlock[0] / i) * axis->axisBlock[1] <= maxThreadNum) { axis->axisBlock[0] /= i; i = axis->axisBlock[0] + 1; } } } axis->axisBlock[2] = 1; axis->axisBlock[3] = axis->specializationConstants.fftDim.data.i; axis->groupedBatch = axis->axisBlock[0]; } } if (axis_id >= 1) { axis->axisBlock[1] = ((uint64_t)ceil(axis->specializationConstants.fftDim.data.i / (double)axis->specializationConstants.min_registers_per_thread) / axis->specializationConstants.registerBoost > 1) ? ((uint64_t)ceil(axis->specializationConstants.fftDim.data.i / (double)axis->specializationConstants.min_registers_per_thread)) / axis->specializationConstants.registerBoost : 1; if (axis->specializationConstants.useRaderMult) { uint64_t final_rader_thread_count = 0; for (uint64_t i = 0; i < axis->specializationConstants.numRaderPrimes; i++) { if (axis->specializationConstants.raderContainer[i].type == 1) { uint64_t temp_rader = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / (double)((axis->specializationConstants.rader_min_registers / 2) * 2)) / (double)((axis->specializationConstants.raderContainer[i].prime + 1) / 2)); uint64_t active_rader = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)temp_rader); if (active_rader > 1) { if ((((double)active_rader - (axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)temp_rader) >= 0.5) && ((((uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)(active_rader - 1)) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2)) * maxBatchCoalesced) <= app->configuration.maxThreadsNum)) active_rader--; } uint64_t local_estimate_rader_threadnum = (uint64_t)ceil((axis->specializationConstants.fftDim.data.i / axis->specializationConstants.raderContainer[i].prime) / (double)active_rader) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2); uint64_t temp_rader_thread_count = ((uint64_t)ceil(axis->axisBlock[1] / (double)((axis->specializationConstants.raderContainer[i].prime + 1) / 2))) * ((axis->specializationConstants.raderContainer[i].prime + 1) / 2); if (temp_rader_thread_count < local_estimate_rader_threadnum) temp_rader_thread_count = local_estimate_rader_threadnum; if (temp_rader_thread_count > final_rader_thread_count) final_rader_thread_count = temp_rader_thread_count; } } axis->axisBlock[1] = final_rader_thread_count; if (axis->groupedBatch * axis->axisBlock[1] > maxThreadNum) axis->groupedBatch = maxBatchCoalesced; } if (axis->specializationConstants.useRaderFFT) { if (axis->axisBlock[1] < axis->specializationConstants.minRaderFFTThreadNum) axis->axisBlock[1] = axis->specializationConstants.minRaderFFTThreadNum; } axis->axisBlock[0] = (FFTPlan->actualFFTSizePerAxis[axis_id][0] > axis->groupedBatch) ? axis->groupedBatch : FFTPlan->actualFFTSizePerAxis[axis_id][0]; if (app->configuration.vendorID == 0x10DE) { while ((axis->axisBlock[1] * axis->axisBlock[0] >= 2 * app->configuration.aimThreads) && (axis->axisBlock[0] > maxBatchCoalesced)) { axis->axisBlock[0] /= 2; if (axis->axisBlock[0] < maxBatchCoalesced) axis->axisBlock[0] = maxBatchCoalesced; } } if (axis->axisBlock[0] > app->configuration.maxComputeWorkGroupSize[0]) axis->axisBlock[0] = app->configuration.maxComputeWorkGroupSize[0]; if (axis->axisBlock[0] * axis->axisBlock[1] > maxThreadNum) { for (uint64_t i = 1; i <= axis->axisBlock[0]; i++) { if ((axis->axisBlock[0] / i) * axis->axisBlock[1] <= maxThreadNum) { axis->axisBlock[0] /= i; i = axis->axisBlock[0] + 1; } } } axis->axisBlock[2] = 1; axis->axisBlock[3] = axis->specializationConstants.fftDim.data.i; axis->groupedBatch = axis->axisBlock[0]; } return VKFFT_SUCCESS; } #endif
b7cd75e2af2cf783c7d37a0fa460669d24f8f2f4
7c857119fe1505b1d80d6e62969661c06dc1a2f4
/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h
9a34dc6e4f1514210d8068344e461ef3cea9dd9e
[ "BSD-2-Clause" ]
permissive
CloverHackyColor/CloverBootloader
7042ca7dd6b513d22be591a295e49071ae1482ee
2711170df4f60b2ae5aa20add3e00f35cf57b7e5
refs/heads/master
2023-08-30T22:14:34.590134
2023-08-27T19:14:02
2023-08-27T19:14:02
205,810,121
4,734
770
BSD-2-Clause
2023-09-03T12:41:33
2019-09-02T08:22:14
C
UTF-8
C
false
false
28,617
h
AhciPei.h
/** @file The AhciPei driver is used to manage ATA hard disk device working under AHCI mode at PEI phase. Copyright (c) 2019, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef _AHCI_PEI_H_ #define _AHCI_PEI_H_ #include <PiPei.h> #include <IndustryStandard/Atapi.h> #include <Ppi/AtaAhciController.h> #include <Ppi/IoMmu.h> #include <Ppi/EndOfPeiPhase.h> #include <Ppi/AtaPassThru.h> #include <Ppi/BlockIo.h> #include <Ppi/BlockIo2.h> #include <Ppi/StorageSecurityCommand.h> #include <Library/DebugLib.h> #include <Library/PeiServicesLib.h> #include <Library/MemoryAllocationLib.h> #include <Library/BaseMemoryLib.h> #include <Library/IoLib.h> #include <Library/TimerLib.h> // // Structure forward declarations // typedef struct _PEI_AHCI_CONTROLLER_PRIVATE_DATA PEI_AHCI_CONTROLLER_PRIVATE_DATA; #include "AhciPeiPassThru.h" #include "AhciPeiBlockIo.h" #include "AhciPeiStorageSecurity.h" // // ATA AHCI driver implementation related definitions // // // Refer SATA1.0a spec section 5.2, the Phy detection time should be less than 10ms. // The value is in millisecond units. Add a bit of margin for robustness. // #define AHCI_BUS_PHY_DETECT_TIMEOUT 15 // // Refer SATA1.0a spec, the bus reset time should be less than 1s. // The value is in 100ns units. // #define AHCI_PEI_RESET_TIMEOUT 10000000 // // Time out Value for ATA pass through protocol, in 100ns units. // #define ATA_TIMEOUT 30000000 // // Maximal number of Physical Region Descriptor Table entries supported. // #define AHCI_MAX_PRDT_NUMBER 8 #define AHCI_CAPABILITY_OFFSET 0x0000 #define AHCI_CAP_SAM BIT18 #define AHCI_CAP_SSS BIT27 #define AHCI_GHC_OFFSET 0x0004 #define AHCI_GHC_RESET BIT0 #define AHCI_GHC_ENABLE BIT31 #define AHCI_IS_OFFSET 0x0008 #define AHCI_PI_OFFSET 0x000C #define AHCI_MAX_PORTS 32 typedef struct { UINT32 Lower32; UINT32 Upper32; } DATA_32; typedef union { DATA_32 Uint32; UINT64 Uint64; } DATA_64; #define AHCI_ATAPI_SIG_MASK 0xFFFF0000 #define AHCI_ATA_DEVICE_SIG 0x00000000 // // Each PRDT entry can point to a memory block up to 4M byte // #define AHCI_MAX_DATA_PER_PRDT 0x400000 #define AHCI_FIS_REGISTER_H2D 0x27 //Register FIS - Host to Device #define AHCI_FIS_REGISTER_H2D_LENGTH 20 #define AHCI_FIS_REGISTER_D2H 0x34 //Register FIS - Device to Host #define AHCI_FIS_PIO_SETUP 0x5F //PIO Setup FIS - Device to Host #define AHCI_D2H_FIS_OFFSET 0x40 #define AHCI_PIO_FIS_OFFSET 0x20 #define AHCI_FIS_TYPE_MASK 0xFF // // Port register // #define AHCI_PORT_START 0x0100 #define AHCI_PORT_REG_WIDTH 0x0080 #define AHCI_PORT_CLB 0x0000 #define AHCI_PORT_CLBU 0x0004 #define AHCI_PORT_FB 0x0008 #define AHCI_PORT_FBU 0x000C #define AHCI_PORT_IS 0x0010 #define AHCI_PORT_IE 0x0014 #define AHCI_PORT_CMD 0x0018 #define AHCI_PORT_CMD_ST BIT0 #define AHCI_PORT_CMD_SUD BIT1 #define AHCI_PORT_CMD_POD BIT2 #define AHCI_PORT_CMD_CLO BIT3 #define AHCI_PORT_CMD_FRE BIT4 #define AHCI_PORT_CMD_FR BIT14 #define AHCI_PORT_CMD_CR BIT15 #define AHCI_PORT_CMD_CPD BIT20 #define AHCI_PORT_CMD_ATAPI BIT24 #define AHCI_PORT_CMD_DLAE BIT25 #define AHCI_PORT_CMD_ALPE BIT26 #define AHCI_PORT_CMD_ACTIVE (1 << 28) #define AHCI_PORT_CMD_ICC_MASK (BIT28 | BIT29 | BIT30 | BIT31) #define AHCI_PORT_TFD 0x0020 #define AHCI_PORT_TFD_ERR BIT0 #define AHCI_PORT_TFD_DRQ BIT3 #define AHCI_PORT_TFD_BSY BIT7 #define AHCI_PORT_TFD_MASK (BIT7 | BIT3 | BIT0) #define AHCI_PORT_SIG 0x0024 #define AHCI_PORT_SSTS 0x0028 #define AHCI_PORT_SSTS_DET_MASK 0x000F #define AHCI_PORT_SSTS_DET 0x0001 #define AHCI_PORT_SSTS_DET_PCE 0x0003 #define AHCI_PORT_SCTL 0x002C #define AHCI_PORT_SCTL_IPM_INIT 0x0300 #define AHCI_PORT_SERR 0x0030 #define AHCI_PORT_CI 0x0038 #define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) #define TIMER_PERIOD_SECONDS(Seconds) MultU64x32((UINT64)(Seconds), 10000000) #pragma pack(1) // // Received FIS structure // typedef struct { UINT8 AhciDmaSetupFis[0x1C]; // Dma Setup Fis: offset 0x00 UINT8 AhciDmaSetupFisRsvd[0x04]; UINT8 AhciPioSetupFis[0x14]; // Pio Setup Fis: offset 0x20 UINT8 AhciPioSetupFisRsvd[0x0C]; UINT8 AhciD2HRegisterFis[0x14]; // D2H Register Fis: offset 0x40 UINT8 AhciD2HRegisterFisRsvd[0x04]; UINT64 AhciSetDeviceBitsFis; // Set Device Bits Fix: offset 0x58 UINT8 AhciUnknownFis[0x40]; // Unkonwn Fis: offset 0x60 UINT8 AhciUnknownFisRsvd[0x60]; } EFI_AHCI_RECEIVED_FIS; // // Command List structure includes total 32 entries. // The entry Data structure is listed at the following. // typedef struct { UINT32 AhciCmdCfl:5; //Command FIS Length UINT32 AhciCmdA:1; //ATAPI UINT32 AhciCmdW:1; //Write UINT32 AhciCmdP:1; //Prefetchable UINT32 AhciCmdR:1; //Reset UINT32 AhciCmdB:1; //BIST UINT32 AhciCmdC:1; //Clear Busy upon R_OK UINT32 AhciCmdRsvd:1; UINT32 AhciCmdPmp:4; //Port Multiplier Port UINT32 AhciCmdPrdtl:16; //Physical Region Descriptor Table Length UINT32 AhciCmdPrdbc; //Physical Region Descriptor Byte Count UINT32 AhciCmdCtba; //Command Table Descriptor Base Address UINT32 AhciCmdCtbau; //Command Table Descriptor Base Address Upper 32-BITs UINT32 AhciCmdRsvd1[4]; } EFI_AHCI_COMMAND_LIST; // // This is a software constructed FIS. // For Data transfer operations, this is the H2D Register FIS format as // specified in the Serial ATA Revision 2.6 specification. // typedef struct { UINT8 AhciCFisType; UINT8 AhciCFisPmNum:4; UINT8 AhciCFisRsvd:1; UINT8 AhciCFisRsvd1:1; UINT8 AhciCFisRsvd2:1; UINT8 AhciCFisCmdInd:1; UINT8 AhciCFisCmd; UINT8 AhciCFisFeature; UINT8 AhciCFisSecNum; UINT8 AhciCFisClyLow; UINT8 AhciCFisClyHigh; UINT8 AhciCFisDevHead; UINT8 AhciCFisSecNumExp; UINT8 AhciCFisClyLowExp; UINT8 AhciCFisClyHighExp; UINT8 AhciCFisFeatureExp; UINT8 AhciCFisSecCount; UINT8 AhciCFisSecCountExp; UINT8 AhciCFisRsvd3; UINT8 AhciCFisControl; UINT8 AhciCFisRsvd4[4]; UINT8 AhciCFisRsvd5[44]; } EFI_AHCI_COMMAND_FIS; // // ACMD: ATAPI command (12 or 16 bytes) // typedef struct { UINT8 AtapiCmd[0x10]; } EFI_AHCI_ATAPI_COMMAND; // // Physical Region Descriptor Table includes up to 65535 entries // The entry data structure is listed at the following. // the actual entry number comes from the PRDTL field in the command // list entry for this command slot. // typedef struct { UINT32 AhciPrdtDba; //Data Base Address UINT32 AhciPrdtDbau; //Data Base Address Upper 32-BITs UINT32 AhciPrdtRsvd; UINT32 AhciPrdtDbc:22; //Data Byte Count UINT32 AhciPrdtRsvd1:9; UINT32 AhciPrdtIoc:1; //Interrupt on Completion } EFI_AHCI_COMMAND_PRDT; // // Command table Data strucute which is pointed to by the entry in the command list // typedef struct { EFI_AHCI_COMMAND_FIS CommandFis; // A software constructed FIS. EFI_AHCI_ATAPI_COMMAND AtapiCmd; // 12 or 16 bytes ATAPI cmd. UINT8 Reserved[0x30]; // // The scatter/gather list for Data transfer. // EFI_AHCI_COMMAND_PRDT PrdtTable[AHCI_MAX_PRDT_NUMBER]; } EFI_AHCI_COMMAND_TABLE; #pragma pack() typedef struct { EFI_AHCI_RECEIVED_FIS *AhciRFis; EFI_AHCI_COMMAND_LIST *AhciCmdList; EFI_AHCI_COMMAND_TABLE *AhciCmdTable; UINTN MaxRFisSize; UINTN MaxCmdListSize; UINTN MaxCmdTableSize; VOID *AhciRFisMap; VOID *AhciCmdListMap; VOID *AhciCmdTableMap; } EFI_AHCI_REGISTERS; // // Unique signature for AHCI ATA device information structure. // #define AHCI_PEI_ATA_DEVICE_DATA_SIGNATURE SIGNATURE_32 ('A', 'P', 'A', 'D') // // AHCI mode device information structure. // typedef struct { UINT32 Signature; LIST_ENTRY Link; UINT16 Port; UINT16 PortMultiplier; UINT8 FisIndex; UINTN DeviceIndex; ATA_IDENTIFY_DATA *IdentifyData; BOOLEAN Lba48Bit; BOOLEAN TrustComputing; UINTN TrustComputingDeviceIndex; EFI_PEI_BLOCK_IO2_MEDIA Media; PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; } PEI_AHCI_ATA_DEVICE_DATA; #define AHCI_PEI_ATA_DEVICE_INFO_FROM_THIS(a) \ CR (a, \ PEI_AHCI_ATA_DEVICE_DATA, \ Link, \ AHCI_PEI_ATA_DEVICE_DATA_SIGNATURE \ ); // // Unique signature for private data structure. // #define AHCI_PEI_CONTROLLER_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('A','P','C','P') // // ATA AHCI controller private data structure. // struct _PEI_AHCI_CONTROLLER_PRIVATE_DATA { UINT32 Signature; UINTN MmioBase; UINTN DevicePathLength; EFI_DEVICE_PATH_PROTOCOL *DevicePath; EFI_ATA_PASS_THRU_MODE AtaPassThruMode; EDKII_PEI_ATA_PASS_THRU_PPI AtaPassThruPpi; EFI_PEI_RECOVERY_BLOCK_IO_PPI BlkIoPpi; EFI_PEI_RECOVERY_BLOCK_IO2_PPI BlkIo2Ppi; EDKII_PEI_STORAGE_SECURITY_CMD_PPI StorageSecurityPpi; EFI_PEI_PPI_DESCRIPTOR AtaPassThruPpiList; EFI_PEI_PPI_DESCRIPTOR BlkIoPpiList; EFI_PEI_PPI_DESCRIPTOR BlkIo2PpiList; EFI_PEI_PPI_DESCRIPTOR StorageSecurityPpiList; EFI_PEI_NOTIFY_DESCRIPTOR EndOfPeiNotifyList; EFI_AHCI_REGISTERS AhciRegisters; UINT32 PortBitMap; UINT32 ActiveDevices; UINT32 TrustComputingDevices; LIST_ENTRY DeviceList; UINT16 PreviousPort; UINT16 PreviousPortMultiplier; }; #define GET_AHCI_PEIM_HC_PRIVATE_DATA_FROM_THIS_PASS_THRU(a) \ CR (a, PEI_AHCI_CONTROLLER_PRIVATE_DATA, AtaPassThruPpi, AHCI_PEI_CONTROLLER_PRIVATE_DATA_SIGNATURE) #define GET_AHCI_PEIM_HC_PRIVATE_DATA_FROM_THIS_BLKIO(a) \ CR (a, PEI_AHCI_CONTROLLER_PRIVATE_DATA, BlkIoPpi, AHCI_PEI_CONTROLLER_PRIVATE_DATA_SIGNATURE) #define GET_AHCI_PEIM_HC_PRIVATE_DATA_FROM_THIS_BLKIO2(a) \ CR (a, PEI_AHCI_CONTROLLER_PRIVATE_DATA, BlkIo2Ppi, AHCI_PEI_CONTROLLER_PRIVATE_DATA_SIGNATURE) #define GET_AHCI_PEIM_HC_PRIVATE_DATA_FROM_THIS_STROAGE_SECURITY(a) \ CR (a, PEI_AHCI_CONTROLLER_PRIVATE_DATA, StorageSecurityPpi, AHCI_PEI_CONTROLLER_PRIVATE_DATA_SIGNATURE) #define GET_AHCI_PEIM_HC_PRIVATE_DATA_FROM_THIS_NOTIFY(a) \ CR (a, PEI_AHCI_CONTROLLER_PRIVATE_DATA, EndOfPeiNotifyList, AHCI_PEI_CONTROLLER_PRIVATE_DATA_SIGNATURE) // // Global variables // extern UINT32 mMaxTransferBlockNumber[2]; // // Internal functions // /** Allocates pages that are suitable for an OperationBusMasterCommonBuffer or OperationBusMasterCommonBuffer64 mapping. @param Pages The number of pages to allocate. @param HostAddress A pointer to store the base system memory address of the allocated range. @param DeviceAddress The resulting map address for the bus master PCI controller to use to access the hosts HostAddress. @param Mapping A resulting value to pass to Unmap(). @retval EFI_SUCCESS The requested memory pages were allocated. @retval EFI_UNSUPPORTED Attributes is unsupported. The only legal attribute bits are MEMORY_WRITE_COMBINE and MEMORY_CACHED. @retval EFI_INVALID_PARAMETER One or more parameters are invalid. @retval EFI_OUT_OF_RESOURCES The memory pages could not be allocated. **/ EFI_STATUS IoMmuAllocateBuffer ( IN UINTN Pages, OUT VOID **HostAddress, OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, OUT VOID **Mapping ); /** Frees memory that was allocated with AllocateBuffer(). @param Pages The number of pages to free. @param HostAddress The base system memory address of the allocated range. @param Mapping The mapping value returned from Map(). @retval EFI_SUCCESS The requested memory pages were freed. @retval EFI_INVALID_PARAMETER The memory range specified by HostAddress and Pages was not allocated with AllocateBuffer(). **/ EFI_STATUS IoMmuFreeBuffer ( IN UINTN Pages, IN VOID *HostAddress, IN VOID *Mapping ); /** Provides the controller-specific addresses required to access system memory from a DMA bus master. @param Operation Indicates if the bus master is going to read or write to system memory. @param HostAddress The system memory address to map to the PCI controller. @param NumberOfBytes On input the number of bytes to map. On output the number of bytes that were mapped. @param DeviceAddress The resulting map address for the bus master PCI controller to use to access the hosts HostAddress. @param Mapping A resulting value to pass to Unmap(). @retval EFI_SUCCESS The range was mapped for the returned NumberOfBytes. @retval EFI_UNSUPPORTED The HostAddress cannot be mapped as a common buffer. @retval EFI_INVALID_PARAMETER One or more parameters are invalid. @retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack of resources. @retval EFI_DEVICE_ERROR The system hardware could not map the requested address. **/ EFI_STATUS IoMmuMap ( IN EDKII_IOMMU_OPERATION Operation, IN VOID *HostAddress, IN OUT UINTN *NumberOfBytes, OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, OUT VOID **Mapping ); /** Completes the Map() operation and releases any corresponding resources. @param Mapping The mapping value returned from Map(). @retval EFI_SUCCESS The range was unmapped. @retval EFI_INVALID_PARAMETER Mapping is not a value that was returned by Map(). @retval EFI_DEVICE_ERROR The data was not committed to the target system memory. **/ EFI_STATUS IoMmuUnmap ( IN VOID *Mapping ); /** One notified function to cleanup the allocated DMA buffers at EndOfPei. @param[in] PeiServices Pointer to PEI Services Table. @param[in] NotifyDescriptor Pointer to the descriptor for the Notification event that caused this function to execute. @param[in] Ppi Pointer to the PPI data associated with this function. @retval EFI_SUCCESS The function completes successfully **/ EFI_STATUS EFIAPI AhciPeimEndOfPei ( IN EFI_PEI_SERVICES **PeiServices, IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, IN VOID *Ppi ); /** Collect the number of bits set within a port bitmap. @param[in] PortBitMap A 32-bit wide bit map of ATA AHCI ports. @retval The number of bits set in the bitmap. **/ UINT8 AhciGetNumberOfPortsFromMap ( IN UINT32 PortBitMap ); /** Start a PIO Data transfer on specific port. @param[in] Private The pointer to the PEI_AHCI_CONTROLLER_PRIVATE_DATA. @param[in] Port The number of port. @param[in] PortMultiplier The number of port multiplier. @param[in] FisIndex The offset index of the FIS base address. @param[in] Read The transfer direction. @param[in] AtaCommandBlock The EFI_ATA_COMMAND_BLOCK data. @param[in,out] AtaStatusBlock The EFI_ATA_STATUS_BLOCK data. @param[in,out] MemoryAddr The pointer to the data buffer. @param[in] DataCount The data count to be transferred. @param[in] Timeout The timeout value of PIO data transfer, uses 100ns as a unit. @retval EFI_DEVICE_ERROR The PIO data transfer abort with error occurs. @retval EFI_TIMEOUT The operation is time out. @retval EFI_UNSUPPORTED The device is not ready for transfer. @retval EFI_OUT_OF_RESOURCES The operation fails due to lack of resources. @retval EFI_SUCCESS The PIO data transfer executes successfully. **/ EFI_STATUS AhciPioTransfer ( IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, IN UINT8 Port, IN UINT8 PortMultiplier, IN UINT8 FisIndex, IN BOOLEAN Read, IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, IN OUT VOID *MemoryAddr, IN UINT32 DataCount, IN UINT64 Timeout ); /** Start a non data transfer on specific port. @param[in] Private The pointer to the PEI_AHCI_CONTROLLER_PRIVATE_DATA. @param[in] Port The number of port. @param[in] PortMultiplier The number of port multiplier. @param[in] FisIndex The offset index of the FIS base address. @param[in] AtaCommandBlock The EFI_ATA_COMMAND_BLOCK data. @param[in,out] AtaStatusBlock The EFI_ATA_STATUS_BLOCK data. @param[in] Timeout The timeout value of non data transfer, uses 100ns as a unit. @retval EFI_DEVICE_ERROR The non data transfer abort with error occurs. @retval EFI_TIMEOUT The operation is time out. @retval EFI_UNSUPPORTED The device is not ready for transfer. @retval EFI_SUCCESS The non data transfer executes successfully. **/ EFI_STATUS AhciNonDataTransfer ( IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, IN UINT8 Port, IN UINT8 PortMultiplier, IN UINT8 FisIndex, IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, IN UINT64 Timeout ); /** Initialize ATA host controller at AHCI mode. The function is designed to initialize ATA host controller. @param[in,out] Private A pointer to the PEI_AHCI_CONTROLLER_PRIVATE_DATA instance. @retval EFI_SUCCESS The ATA AHCI controller is initialized successfully. @retval EFI_OUT_OF_RESOURCES Not enough resource to complete while initializing the controller. @retval Others A device error occurred while initializing the controller. **/ EFI_STATUS AhciModeInitialization ( IN OUT PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private ); /** Transfer data from ATA device. This function performs one ATA pass through transaction to transfer data from/to ATA device. It chooses the appropriate ATA command and protocol to invoke PassThru interface of ATA pass through. @param[in] DeviceData A pointer to PEI_AHCI_ATA_DEVICE_DATA structure. @param[in,out] Buffer The pointer to the current transaction buffer. @param[in] StartLba The starting logical block address to be accessed. @param[in] TransferLength The block number or sector count of the transfer. @param[in] IsWrite Indicates whether it is a write operation. @retval EFI_SUCCESS The data transfer is complete successfully. @return others Some error occurs when transferring data. **/ EFI_STATUS TransferAtaDevice ( IN PEI_AHCI_ATA_DEVICE_DATA *DeviceData, IN OUT VOID *Buffer, IN EFI_LBA StartLba, IN UINT32 TransferLength, IN BOOLEAN IsWrite ); /** Trust transfer data from/to ATA device. This function performs one ATA pass through transaction to do a trust transfer from/to ATA device. It chooses the appropriate ATA command and protocol to invoke PassThru interface of ATA pass through. @param[in] DeviceData Pointer to PEI_AHCI_ATA_DEVICE_DATA structure. @param[in,out] Buffer The pointer to the current transaction buffer. @param[in] SecurityProtocolId The value of the "Security Protocol" parameter of the security protocol command to be sent. @param[in] SecurityProtocolSpecificData The value of the "Security Protocol Specific" parameter of the security protocol command to be sent. @param[in] TransferLength The block number or sector count of the transfer. @param[in] IsTrustSend Indicates whether it is a trust send operation or not. @param[in] Timeout The timeout, in 100ns units, to use for the execution of the security protocol command. A Timeout value of 0 means that this function will wait indefinitely for the security protocol command to execute. If Timeout is greater than zero, then this function will return EFI_TIMEOUT if the time required to execute the receive data command is greater than Timeout. @param[out] TransferLengthOut A pointer to a buffer to store the size in bytes of the data written to the buffer. Ignore it when IsTrustSend is TRUE. @retval EFI_SUCCESS The data transfer is complete successfully. @return others Some error occurs when transferring data. **/ EFI_STATUS TrustTransferAtaDevice ( IN PEI_AHCI_ATA_DEVICE_DATA *DeviceData, IN OUT VOID *Buffer, IN UINT8 SecurityProtocolId, IN UINT16 SecurityProtocolSpecificData, IN UINTN TransferLength, IN BOOLEAN IsTrustSend, IN UINT64 Timeout, OUT UINTN *TransferLengthOut ); /** Returns a pointer to the next node in a device path. If Node is NULL, then ASSERT(). @param Node A pointer to a device path node data structure. @return a pointer to the device path node that follows the device path node specified by Node. **/ EFI_DEVICE_PATH_PROTOCOL * NextDevicePathNode ( IN CONST VOID *Node ); /** Get the size of the current device path instance. @param[in] DevicePath A pointer to the EFI_DEVICE_PATH_PROTOCOL structure. @param[out] InstanceSize The size of the current device path instance. @param[out] EntireDevicePathEnd Indicate whether the instance is the last one in the device path strucure. @retval EFI_SUCCESS The size of the current device path instance is fetched. @retval Others Fails to get the size of the current device path instance. **/ EFI_STATUS GetDevicePathInstanceSize ( IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, OUT UINTN *InstanceSize, OUT BOOLEAN *EntireDevicePathEnd ); /** Check the validity of the device path of a ATA AHCI host controller. @param[in] DevicePath A pointer to the EFI_DEVICE_PATH_PROTOCOL structure. @param[in] DevicePathLength The length of the device path. @retval EFI_SUCCESS The device path is valid. @retval EFI_INVALID_PARAMETER The device path is invalid. **/ EFI_STATUS AhciIsHcDevicePathValid ( IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, IN UINTN DevicePathLength ); /** Build the device path for an ATA device with given port and port multiplier number. @param[in] Private A pointer to the PEI_AHCI_CONTROLLER_PRIVATE_DATA data structure. @param[in] Port The given port number. @param[in] PortMultiplierPort The given port multiplier number. @param[out] DevicePathLength The length of the device path in bytes specified by DevicePath. @param[out] DevicePath The device path of ATA device. @retval EFI_SUCCESS The operation succeeds. @retval EFI_INVALID_PARAMETER The parameters are invalid. @retval EFI_OUT_OF_RESOURCES The operation fails due to lack of resources. **/ EFI_STATUS AhciBuildDevicePath ( IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, IN UINT16 Port, IN UINT16 PortMultiplierPort, OUT UINTN *DevicePathLength, OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ); /** Collect the ports that need to be enumerated on a controller for S3 phase. @param[in] HcDevicePath Device path of the controller. @param[in] HcDevicePathLength Length of the device path specified by HcDevicePath. @param[out] PortBitMap Bitmap that indicates the ports that need to be enumerated on the controller. @retval The number of ports that need to be enumerated. **/ UINT8 AhciS3GetEumeratePorts ( IN EFI_DEVICE_PATH_PROTOCOL *HcDevicePath, IN UINTN HcDevicePathLength, OUT UINT32 *PortBitMap ); #endif
9191118bcbfa61502d22db2ec7fa41d5e4ccddda
b732361d6b3405c3e79ac0a7d8361cf5b329b015
/ext/phalcon/db/rawvalue.zep.h
2efaedf9499a5f1eb127ae1f6055804557e04ecf
[ "BSD-3-Clause" ]
permissive
phalcon/cphalcon
4a5b26f47b5c2a4107541d7fd73c595c0d90ed73
fc183e11e8b96c43daf7d893244846206dc2aa73
refs/heads/master
2023-03-07T22:09:48.814291
2023-02-28T16:45:15
2023-02-28T16:45:15
2,854,337
8,135
2,343
BSD-3-Clause
2023-09-12T12:41:13
2011-11-26T05:52:50
PHP
UTF-8
C
false
true
961
h
rawvalue.zep.h
extern zend_class_entry *phalcon_db_rawvalue_ce; ZEPHIR_INIT_CLASS(Phalcon_Db_RawValue); PHP_METHOD(Phalcon_Db_RawValue, __construct); PHP_METHOD(Phalcon_Db_RawValue, __toString); PHP_METHOD(Phalcon_Db_RawValue, getValue); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_db_rawvalue___construct, 0, 0, 1) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_phalcon_db_rawvalue___tostring, 0, 0, IS_STRING, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_phalcon_db_rawvalue_getvalue, 0, 0, IS_STRING, 0) ZEND_END_ARG_INFO() ZEPHIR_INIT_FUNCS(phalcon_db_rawvalue_method_entry) { PHP_ME(Phalcon_Db_RawValue, __construct, arginfo_phalcon_db_rawvalue___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(Phalcon_Db_RawValue, __toString, arginfo_phalcon_db_rawvalue___tostring, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Db_RawValue, getValue, arginfo_phalcon_db_rawvalue_getvalue, ZEND_ACC_PUBLIC) PHP_FE_END };
e149b367b342414c910a896b565a40c3a7d1ea38
0744dcc5394cebf57ebcba343747af6871b67017
/apps/examples/fota_sample/fota_sample.c
c1ef5968fca9ce4d5c87c64745725bd4c3902c90
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
Samsung/TizenRT
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
refs/heads/master
2023-08-31T08:59:33.327998
2023-08-08T06:09:20
2023-08-31T04:38:20
82,517,252
590
719
Apache-2.0
2023-09-14T06:54:49
2017-02-20T04:38:30
C
UTF-8
C
false
false
5,249
c
fota_sample.c
/**************************************************************************** * * Copyright 2016 Samsung Electronics All Rights Reserved. * * 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <stdio.h> #include <tinyara/config.h> #ifdef CONFIG_TASH #include <apps/shell/tash.h> #endif #include <apps/system/fota_hal.h> /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: fota_sample * * Description: * fota sample application ****************************************************************************/ #ifdef CONFIG_BUILD_KERNEL int main(int argc, FAR char *argv[]) #else int fota_sample(int argc, char *argv[]) #endif { int ret = ERROR; int bin_id; int max_bins; uint32_t part_id; uint32_t next_part_id; char user_input; char buffer[] = "dummy"; fotahal_handle_t fotahal_handle; fotahal_bin_header_t fotahal_header; printf("***********************************************************\n"); printf(" fota update is in progress !!!\n"); /* Example call sequence to use fota hal */ /* open fota hal, get the handle to work with it */ if ((fotahal_handle = fotahal_open()) == NULL) { printf("%s : fotahal_open error\n", __func__); goto open_error; } /* Get the current running partition */ part_id = fotahal_get_partition(fotahal_handle); if (part_id == -1) { printf("%s : fotahal_get_partition error\n", __func__); goto part_error; } printf(" current running partition is [ OTA%d ]\n", part_id); /* Decide the next partiton we can use, may be first free partition */ for (next_part_id = FOTA_PARTITION_OTA0; (next_part_id < FOTA_PARTITION_MAX) && next_part_id == part_id; next_part_id++) ; if (next_part_id >= FOTA_PARTITION_MAX) { printf("%s : No free partition left\n", __func__); goto part_error; } printf(" next fota update partition is [ OTA%d ]\n", next_part_id); /* FIXME: * This is for fota sample test, Real application might need to handle * it differently. * We are not downloading binary from server. * Let's post a banner here to inform user to manually download the binary */ printf("******* oh!! Fota Server is Down !!! ******\n"); printf(" please download fota binary manually using below step !!! \n"); printf(" [ make download TINYARA_OTA%d ] \n", next_part_id); printf("Is OTA%d binary manually downloaded? If yes press Y to continue [Y/N]\n", next_part_id); user_input = getchar(); if (user_input != 'Y' && user_input != 'y') { printf(" fota update cancelled !!!\n"); printf("***********************************************************\n"); goto fota_exit; } if (fotahal_set_partition(fotahal_handle, next_part_id) != FOTAHAL_RETURN_SUCCESS) { printf("%s : fotahal_set_partition error\n", __func__); goto part_error; } /* max_bins = 1; for testing */ max_bins = 1; for (bin_id = 0; bin_id < max_bins; bin_id++) { /* Extract fota header from binary */ /* But unfortunately, we have not received binary, * hence for testing, construct binary header locally */ fotahal_header.fotahal_bin_id = bin_id; if (fotahal_set_binary(fotahal_handle, fotahal_header.fotahal_bin_id) != FOTAHAL_RETURN_SUCCESS) { printf("%s : fotahal_set_binary error\n", __func__); goto part_error; } if (fotahal_write(fotahal_handle, buffer, 0) != FOTAHAL_RETURN_SUCCESS) { printf("%s : fotahal_write error\n", __func__); goto write_error; } /* Lets update boot param, to trigger fota update in next cycle */ if (fotahal_update_bootparam(fotahal_handle) != FOTAHAL_RETURN_SUCCESS) { printf("%s : fotahal_update_bootparam error\n", __func__); goto param_error; } } if (fotahal_close(fotahal_handle) != FOTAHAL_RETURN_SUCCESS) { printf("%s : fotahal_close error\n", __func__); goto close_error; } printf(" fota update successfully downloaded !!!\n"); printf(" Please reset your board to continue fota update !!!\n"); printf("***********************************************************\n"); ret = OK; close_error: param_error: write_error: fota_exit: part_error: fotahal_close(fotahal_handle); open_error: return ret; }
c389651af92a6a2d574acbe0b1ec2d5b0cfb00f4
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/nuvoton/numaker-m032ki/board/NuPinConfig/nutool_pincfg.c
dab10a7699460318d88f5a4401d744cda41efd61
[ "Apache-2.0", "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC", "LicenseRef-scancode-unknown-license-reference" ]
permissive
RT-Thread/rt-thread
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
3602f891211904a27dcbd51e5ba72fefce7326b2
refs/heads/master
2023-09-01T04:10:20.295801
2023-08-31T16:20:55
2023-08-31T16:20:55
7,408,108
9,599
5,805
Apache-2.0
2023-09-14T13:37:26
2013-01-02T14:49:21
C
UTF-8
C
false
false
7,313
c
nutool_pincfg.c
/**************************************************************************** * @file nutool_pincfg.c * @version V1.21 * @Date 2021/03/03-17:36:00 * @brief NuMicro generated code file * * SPDX-License-Identifier: Apache-2.0 * * Copyright (C) 2013-2020 Nuvoton Technology Corp. All rights reserved. *****************************************************************************/ /******************** MCU:M032KIAAE(LQFP128) Pin Configuration: Pin1:ADC0_CH5 Pin2:ADC0_CH4 Pin3:UART1_TXD Pin4:UART1_RXD Pin9:ADC0_CH1 Pin10:ADC0_CH0 Pin31:X32_IN Pin32:X32_OUT Pin37:XT1_IN Pin38:XT1_OUT Pin50:PWM1_CH4 Pin51:PWM1_CH5 Pin55:QSPI0_MISO1 Pin56:QSPI0_MOSI1 Pin57:QSPI0_SS Pin58:QSPI0_CLK Pin59:QSPI0_MISO0 Pin60:QSPI0_MOSI0 Pin65:ICE_DAT Pin66:ICE_CLK Pin69:PWM1_CH0 Pin70:PWM1_CH1 Pin71:PWM1_CH2 Pin72:PWM1_CH3 Pin73:I2C0_SCL Pin74:I2C0_SDA Pin118:UART0_TXD Pin119:UART0_RXD Pin127:ADC0_CH7 Pin128:ADC0_CH6 ********************/ #include "M031Series.h" #include "rtconfig.h" void nutool_pincfg_init_ice(void) { SYS->GPF_MFPL &= ~(SYS_GPF_MFPL_PF1MFP_Msk | SYS_GPF_MFPL_PF0MFP_Msk); SYS->GPF_MFPL |= (SYS_GPF_MFPL_PF1MFP_ICE_CLK | SYS_GPF_MFPL_PF0MFP_ICE_DAT); return; } void nutool_pincfg_deinit_ice(void) { SYS->GPF_MFPL &= ~(SYS_GPF_MFPL_PF1MFP_Msk | SYS_GPF_MFPL_PF0MFP_Msk); return; } void nutool_pincfg_init_uart0(void) { SYS->GPB_MFPH &= ~(SYS_GPB_MFPH_PB13MFP_Msk | SYS_GPB_MFPH_PB12MFP_Msk); SYS->GPB_MFPH |= (SYS_GPB_MFPH_PB13MFP_UART0_TXD | SYS_GPB_MFPH_PB12MFP_UART0_RXD); return; } void nutool_pincfg_deinit_uart0(void) { SYS->GPB_MFPH &= ~(SYS_GPB_MFPH_PB13MFP_Msk | SYS_GPB_MFPH_PB12MFP_Msk); return; } void nutool_pincfg_init_x32(void) { SYS->GPF_MFPL &= ~(SYS_GPF_MFPL_PF5MFP_Msk | SYS_GPF_MFPL_PF4MFP_Msk); SYS->GPF_MFPL |= (SYS_GPF_MFPL_PF5MFP_X32_IN | SYS_GPF_MFPL_PF4MFP_X32_OUT); return; } void nutool_pincfg_deinit_x32(void) { SYS->GPF_MFPL &= ~(SYS_GPF_MFPL_PF5MFP_Msk | SYS_GPF_MFPL_PF4MFP_Msk); return; } void nutool_pincfg_init_xt1(void) { SYS->GPF_MFPL &= ~(SYS_GPF_MFPL_PF3MFP_Msk | SYS_GPF_MFPL_PF2MFP_Msk); SYS->GPF_MFPL |= (SYS_GPF_MFPL_PF3MFP_XT1_IN | SYS_GPF_MFPL_PF2MFP_XT1_OUT); return; } void nutool_pincfg_deinit_xt1(void) { SYS->GPF_MFPL &= ~(SYS_GPF_MFPL_PF3MFP_Msk | SYS_GPF_MFPL_PF2MFP_Msk); return; } void nutool_pincfg_init_qspi0(void) { SYS->GPA_MFPL &= ~(SYS_GPA_MFPL_PA0MFP_Msk | SYS_GPA_MFPL_PA1MFP_Msk | SYS_GPA_MFPL_PA2MFP_Msk | SYS_GPA_MFPL_PA3MFP_Msk | SYS_GPA_MFPL_PA4MFP_Msk | SYS_GPA_MFPL_PA5MFP_Msk); SYS->GPA_MFPL |= (SYS_GPA_MFPL_PA0MFP_QSPI0_MOSI0 | SYS_GPA_MFPL_PA1MFP_QSPI0_MISO0 | SYS_GPA_MFPL_PA2MFP_QSPI0_CLK | SYS_GPA_MFPL_PA3MFP_QSPI0_SS | SYS_GPA_MFPL_PA4MFP_QSPI0_MOSI1 | SYS_GPA_MFPL_PA5MFP_QSPI0_MISO1); /* pull high qspi quad mode pins. */ GPIO_SetMode(PA, BIT4 | BIT5, GPIO_MODE_QUASI); } void nutool_pincfg_init_usci0(void) { SYS->GPA_MFPH &= ~(SYS_GPA_MFPH_PA8MFP_Msk | SYS_GPA_MFPH_PA9MFP_Msk | SYS_GPA_MFPH_PA10MFP_Msk | SYS_GPA_MFPH_PA11MFP_Msk); SYS->GPA_MFPH |= (/*SYS_GPA_MFPH_PA8MFP_USCI0_CTL1 |*/ SYS_GPA_MFPH_PA9MFP_USCI0_DAT1 | SYS_GPA_MFPH_PA10MFP_USCI0_DAT0 | SYS_GPA_MFPH_PA11MFP_USCI0_CLK); } void nutool_pincfg_deinit_qspi0(void) { SYS->GPA_MFPL &= ~(SYS_GPA_MFPL_PA0MFP_Msk | SYS_GPA_MFPL_PA1MFP_Msk | SYS_GPA_MFPL_PA2MFP_Msk | SYS_GPA_MFPL_PA3MFP_Msk | SYS_GPA_MFPL_PA4MFP_Msk | SYS_GPA_MFPL_PA5MFP_Msk); } void nutool_pincfg_init_i2c0(void) { SYS->GPC_MFPL &= ~(SYS_GPC_MFPL_PC0MFP_Msk | SYS_GPC_MFPL_PC1MFP_Msk); SYS->GPC_MFPL |= (SYS_GPC_MFPL_PC0MFP_I2C0_SDA | SYS_GPC_MFPL_PC1MFP_I2C0_SCL); } void nutool_pincfg_deinit_i2c0(void) { SYS->GPC_MFPL &= ~(SYS_GPC_MFPL_PC0MFP_Msk | SYS_GPC_MFPL_PC1MFP_Msk); } void nutool_pincfg_init_adc0(void) { SYS->GPB_MFPL &= ~(SYS_GPB_MFPL_PB0MFP_Msk | SYS_GPB_MFPL_PB1MFP_Msk | SYS_GPB_MFPL_PB4MFP_Msk | SYS_GPB_MFPL_PB5MFP_Msk | SYS_GPB_MFPL_PB6MFP_Msk | SYS_GPB_MFPL_PB7MFP_Msk); SYS->GPB_MFPL |= (SYS_GPB_MFPL_PB0MFP_ADC_CH0 | SYS_GPB_MFPL_PB1MFP_ADC_CH1 | SYS_GPB_MFPL_PB4MFP_ADC_CH4 | SYS_GPB_MFPL_PB5MFP_ADC_CH5 | SYS_GPB_MFPL_PB6MFP_ADC_CH6 | SYS_GPB_MFPL_PB7MFP_ADC_CH7); /* Disable digital path on these ADC pins */ GPIO_DISABLE_DIGITAL_PATH(PB, BIT0 | BIT1 | BIT4 | BIT5 | BIT6 | BIT7); } void nutool_pincfg_deinit_adc0(void) { SYS->GPB_MFPL &= ~(SYS_GPB_MFPL_PB0MFP_Msk | SYS_GPB_MFPL_PB1MFP_Msk | SYS_GPB_MFPL_PB4MFP_Msk | SYS_GPB_MFPL_PB5MFP_Msk | SYS_GPB_MFPL_PB6MFP_Msk | SYS_GPB_MFPL_PB7MFP_Msk); /* Enable digital path on these ADC pins */ GPIO_ENABLE_DIGITAL_PATH(PB, BIT0 | BIT1 | BIT4 | BIT5 | BIT6 | BIT7); } void nutool_pincfg_init_pwm0(void) { SYS->GPA_MFPL &= ~(SYS_GPA_MFPL_PA6MFP_Msk | SYS_GPA_MFPL_PA7MFP_Msk); SYS->GPC_MFPL &= ~(SYS_GPC_MFPL_PC2MFP_Msk | SYS_GPC_MFPL_PC3MFP_Msk | SYS_GPC_MFPL_PC4MFP_Msk | SYS_GPC_MFPL_PC5MFP_Msk); SYS->GPA_MFPL |= (SYS_GPA_MFPL_PA6MFP_PWM1_CH5 | SYS_GPA_MFPL_PA7MFP_PWM1_CH4); SYS->GPC_MFPL |= (SYS_GPC_MFPL_PC2MFP_PWM1_CH3 | SYS_GPC_MFPL_PC3MFP_PWM1_CH2 | SYS_GPC_MFPL_PC4MFP_PWM1_CH1 | SYS_GPC_MFPL_PC5MFP_PWM1_CH0); } void nutool_pincfg_deinit_pwm0(void) { SYS->GPA_MFPL &= ~(SYS_GPA_MFPL_PA6MFP_Msk | SYS_GPA_MFPL_PA7MFP_Msk); SYS->GPC_MFPL &= ~(SYS_GPC_MFPL_PC2MFP_Msk | SYS_GPC_MFPL_PC3MFP_Msk | SYS_GPC_MFPL_PC4MFP_Msk | SYS_GPC_MFPL_PC5MFP_Msk); } void nutool_pincfg_init_uart1(void) { SYS->GPB_MFPL &= ~(SYS_GPB_MFPL_PB2MFP_Msk | SYS_GPB_MFPL_PB3MFP_Msk); SYS->GPB_MFPL |= (SYS_GPB_MFPL_PB2MFP_UART1_RXD | SYS_GPB_MFPL_PB3MFP_UART1_TXD); } void nutool_pincfg_deinit_uart1(void) { SYS->GPB_MFPL &= ~(SYS_GPB_MFPL_PB2MFP_Msk | SYS_GPB_MFPL_PB3MFP_Msk); } void nutool_pincfg_init(void) { //SYS->GPA_MFPH = 0x00000000UL; //SYS->GPA_MFPL = 0xBB333333UL; //SYS->GPB_MFPH = 0x00660000UL; //SYS->GPB_MFPL = 0x11116611UL; //SYS->GPC_MFPH = 0x00000000UL; //SYS->GPC_MFPL = 0x00CCCC99UL; //SYS->GPD_MFPH = 0x00000000UL; //SYS->GPD_MFPL = 0x00000000UL; //SYS->GPE_MFPH = 0x00000000UL; //SYS->GPE_MFPL = 0x00000000UL; //SYS->GPF_MFPH = 0x00000000UL; //SYS->GPF_MFPL = 0x00AAAAEEUL; //SYS->GPG_MFPH = 0x00000000UL; //SYS->GPG_MFPL = 0x00000000UL; //SYS->GPH_MFPH = 0x00000000UL; //SYS->GPH_MFPL = 0x00000000UL; nutool_pincfg_init_ice(); nutool_pincfg_init_uart0(); nutool_pincfg_init_x32(); nutool_pincfg_init_xt1(); nutool_pincfg_init_qspi0(); #if defined(BOARD_USING_LCD_ILI9341) nutool_pincfg_init_usci0(); #endif nutool_pincfg_init_i2c0(); nutool_pincfg_init_adc0(); #if !defined(BOARD_USING_LCD_ILI9341) nutool_pincfg_deinit_pwm0(); nutool_pincfg_deinit_uart1(); #endif return; } void nutool_pincfg_deinit(void) { nutool_pincfg_deinit_ice(); nutool_pincfg_deinit_uart0(); nutool_pincfg_deinit_x32(); nutool_pincfg_deinit_xt1(); nutool_pincfg_deinit_qspi0(); nutool_pincfg_init_usci0(); nutool_pincfg_deinit_i2c0(); nutool_pincfg_deinit_adc0(); nutool_pincfg_deinit_pwm0(); nutool_pincfg_deinit_uart1(); return; } /*** (C) COPYRIGHT 2013-2020 Nuvoton Technology Corp. ***/
c27c75abd62c9e09d38e8b6f3b668516e2078267
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
/lib/libc/include/any-windows-any/usbcamdi.h
0b36d71a38a9d5e16bc42b22e57f6bc1cd49e568
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
ziglang/zig
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
refs/heads/master
2023-08-31T13:16:45.980913
2023-08-31T05:50:29
2023-08-31T05:50:29
40,276,274
25,560
2,399
MIT
2023-09-14T21:09:50
2015-08-06T00:51:28
Zig
UTF-8
C
false
false
9,633
h
usbcamdi.h
/* * usbcamdi.h * * USB Camera driver interface. * * This file is part of the ReactOS PSDK package. * * Contributors: * Created by Casper S. Hornstrup <chorns@users.sourceforge.net> * * THIS SOFTWARE IS NOT COPYRIGHTED * * This source code is offered for use in the public domain. You may * use, modify or distribute it freely. * * This code is distributed in the hope that it will be useful but * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY * DISCLAIMED. This includes but is not limited to warranties of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * */ #if !defined(__USB_H) && !defined(__USBDI_H) #ifdef __cplusplus extern "C" { #endif #if defined(_BATTERYCLASS_) # define USBCAMAPI #else # define USBCAMAPI DECLSPEC_IMPORT #endif typedef struct _pipe_config_descriptor { CHAR StreamAssociation; UCHAR PipeConfigFlags; } USBCAMD_Pipe_Config_Descriptor, *PUSBCAMD_Pipe_Config_Descriptor; #define USBCAMD_DATA_PIPE 0x0001 #define USBCAMD_MULTIPLEX_PIPE 0x0002 #define USBCAMD_SYNC_PIPE 0x0004 #define USBCAMD_DONT_CARE_PIPE 0x0008 #define USBCAMD_VIDEO_STREAM 0x1 #define USBCAMD_STILL_STREAM 0x2 #define USBCAMD_VIDEO_STILL_STREAM (USBCAMD_VIDEO_STREAM | USBCAMD_STILL_STREAM) #define USBCAMD_PROCESSPACKETEX_DropFrame 0x0002 #define USBCAMD_PROCESSPACKETEX_NextFrameIsStill 0x0004 #define USBCAMD_PROCESSPACKETEX_CurrentFrameIsStill 0x0008 #define USBCAMD_STOP_STREAM 0x00000001 #define USBCAMD_START_STREAM 0x00000000 typedef enum { USBCAMD_CamControlFlag_NoVideoRawProcessing = 1, USBCAMD_CamControlFlag_NoStillRawProcessing = 2, USBCAMD_CamControlFlag_AssociatedFormat = 4, USBCAMD_CamControlFlag_EnableDeviceEvents = 8 } USBCAMD_CamControlFlags; typedef NTSTATUS (NTAPI *PCOMMAND_COMPLETE_FUNCTION)( PVOID DeviceContext, PVOID CommandContext, NTSTATUS NtStatus); typedef VOID (NTAPI *PSTREAM_RECEIVE_PACKET)( PVOID Srb, PVOID DeviceContext, PBOOLEAN Completed); typedef NTSTATUS (NTAPI *PCAM_INITIALIZE_ROUTINE)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext); typedef NTSTATUS (NTAPI *PCAM_CONFIGURE_ROUTINE)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext, PUSBD_INTERFACE_INFORMATION Interface, PUSB_CONFIGURATION_DESCRIPTOR ConfigurationDescriptor, PLONG DataPipeIndex, PLONG SyncPipeIndex); typedef NTSTATUS (NTAPI *PCAM_CONFIGURE_ROUTINE_EX)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext, PUSBD_INTERFACE_INFORMATION Interface, PUSB_CONFIGURATION_DESCRIPTOR ConfigurationDescriptor, ULONG PipeConfigListSize, PUSBCAMD_Pipe_Config_Descriptor PipeConfig, PUSB_DEVICE_DESCRIPTOR DeviceDescriptor); typedef NTSTATUS (NTAPI *PCAM_START_CAPTURE_ROUTINE)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext); typedef NTSTATUS (NTAPI *PCAM_START_CAPTURE_ROUTINE_EX)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext, ULONG StreamNumber); typedef NTSTATUS (NTAPI *PCAM_ALLOCATE_BW_ROUTINE)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext, PULONG RawFrameLength, PVOID Format); typedef NTSTATUS (NTAPI *PCAM_ALLOCATE_BW_ROUTINE_EX)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext, PULONG RawFrameLength, PVOID Format, ULONG StreamNumber); typedef NTSTATUS (NTAPI *PCAM_FREE_BW_ROUTINE)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext); typedef NTSTATUS (NTAPI *PCAM_FREE_BW_ROUTINE_EX)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext, ULONG StreamNumber); typedef VOID (NTAPI *PADAPTER_RECEIVE_PACKET_ROUTINE)( PHW_STREAM_REQUEST_BLOCK Srb); typedef NTSTATUS (NTAPI *PCAM_STOP_CAPTURE_ROUTINE)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext); typedef NTSTATUS (NTAPI *PCAM_STOP_CAPTURE_ROUTINE_EX)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext, ULONG StreamNumber); typedef ULONG (NTAPI *PCAM_PROCESS_PACKET_ROUTINE)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext, PVOID CurrentFrameContext, PUSBD_ISO_PACKET_DESCRIPTOR SyncPacket, PVOID SyncBuffer, PUSBD_ISO_PACKET_DESCRIPTOR DataPacket, PVOID DataBuffer, PBOOLEAN FrameComplete, PBOOLEAN NextFrameIsStill); typedef ULONG (NTAPI *PCAM_PROCESS_PACKET_ROUTINE_EX)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext, PVOID CurrentFrameContext, PUSBD_ISO_PACKET_DESCRIPTOR SyncPacket, PVOID SyncBuffer, PUSBD_ISO_PACKET_DESCRIPTOR DataPacket, PVOID DataBuffer, PBOOLEAN FrameComplete, PULONG PacketFlag, PULONG ValidDataOffset); typedef VOID (NTAPI *PCAM_NEW_FRAME_ROUTINE)( PVOID DeviceContext, PVOID FrameContext); typedef VOID (NTAPI *PCAM_NEW_FRAME_ROUTINE_EX)( PVOID DeviceContext, PVOID FrameContext, ULONG StreamNumber, PULONG FrameLength); typedef NTSTATUS (NTAPI *PCAM_PROCESS_RAW_FRAME_ROUTINE)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext, PVOID FrameContext, PVOID FrameBuffer, ULONG FrameLength, PVOID RawFrameBuffer, ULONG RawFrameLength, ULONG NumberOfPackets, PULONG BytesReturned); typedef NTSTATUS (NTAPI *PCAM_PROCESS_RAW_FRAME_ROUTINE_EX)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext, PVOID FrameContext, PVOID FrameBuffer, ULONG FrameLength, PVOID RawFrameBuffer, ULONG RawFrameLength, ULONG NumberOfPackets, PULONG BytesReturned, ULONG ActualRawFrameLength, ULONG StreamNumber); typedef NTSTATUS (NTAPI *PCAM_STATE_ROUTINE)( PDEVICE_OBJECT BusDeviceObject, PVOID DeviceContext); #if defined(DEBUG_LOG) USBCAMAPI VOID NTAPI USBCAMD_Debug_LogEntry( CHAR *Name, ULONG Info1, ULONG Info2, ULONG Info3); #define ILOGENTRY(sig, info1, info2, info3) \ USBCAMD_Debug_LogEntry(sig, (ULONG)info1, (ULONG)info2, (ULONG)info3) #else #define ILOGENTRY(sig, info1, info2, info3) #endif /* DEBUG_LOG */ typedef struct _USBCAMD_DEVICE_DATA { ULONG Sig; PCAM_INITIALIZE_ROUTINE CamInitialize; PCAM_INITIALIZE_ROUTINE CamUnInitialize; PCAM_PROCESS_PACKET_ROUTINE CamProcessUSBPacket; PCAM_NEW_FRAME_ROUTINE CamNewVideoFrame; PCAM_PROCESS_RAW_FRAME_ROUTINE CamProcessRawVideoFrame; PCAM_START_CAPTURE_ROUTINE CamStartCapture; PCAM_STOP_CAPTURE_ROUTINE CamStopCapture; PCAM_CONFIGURE_ROUTINE CamConfigure; PCAM_STATE_ROUTINE CamSaveState; PCAM_STATE_ROUTINE CamRestoreState; PCAM_ALLOCATE_BW_ROUTINE CamAllocateBandwidth; PCAM_FREE_BW_ROUTINE CamFreeBandwidth; } USBCAMD_DEVICE_DATA, *PUSBCAMD_DEVICE_DATA; typedef struct _USBCAMD_DEVICE_DATA2 { ULONG Sig; PCAM_INITIALIZE_ROUTINE CamInitialize; PCAM_INITIALIZE_ROUTINE CamUnInitialize; PCAM_PROCESS_PACKET_ROUTINE_EX CamProcessUSBPacketEx; PCAM_NEW_FRAME_ROUTINE_EX CamNewVideoFrameEx; PCAM_PROCESS_RAW_FRAME_ROUTINE_EX CamProcessRawVideoFrameEx; PCAM_START_CAPTURE_ROUTINE_EX CamStartCaptureEx; PCAM_STOP_CAPTURE_ROUTINE_EX CamStopCaptureEx; PCAM_CONFIGURE_ROUTINE_EX CamConfigureEx; PCAM_STATE_ROUTINE CamSaveState; PCAM_STATE_ROUTINE CamRestoreState; PCAM_ALLOCATE_BW_ROUTINE_EX CamAllocateBandwidthEx; PCAM_FREE_BW_ROUTINE_EX CamFreeBandwidthEx; } USBCAMD_DEVICE_DATA2, *PUSBCAMD_DEVICE_DATA2; DEFINE_GUID(GUID_USBCAMD_INTERFACE, 0x2bcb75c0, 0xb27f, 0x11d1, 0xba, 0x41, 0x0, 0xa0, 0xc9, 0xd, 0x2b, 0x5); typedef NTSTATUS (NTAPI *PFNUSBCAMD_SetVideoFormat)( PVOID DeviceContext, PHW_STREAM_REQUEST_BLOCK pSrb); typedef NTSTATUS (NTAPI *PFNUSBCAMD_WaitOnDeviceEvent)( PVOID DeviceContext, ULONG PipeIndex, PVOID Buffer, ULONG BufferLength, PCOMMAND_COMPLETE_FUNCTION EventComplete, PVOID EventContext, BOOLEAN LoopBack); typedef NTSTATUS (NTAPI *PFNUSBCAMD_CancelBulkReadWrite)( PVOID DeviceContext, ULONG PipeIndex); typedef NTSTATUS (NTAPI *PFNUSBCAMD_SetIsoPipeState)( PVOID DeviceContext, ULONG PipeStateFlags); typedef NTSTATUS (NTAPI *PFNUSBCAMD_BulkReadWrite)( PVOID DeviceContext, USHORT PipeIndex, PVOID Buffer, ULONG BufferLength, PCOMMAND_COMPLETE_FUNCTION CommandComplete, PVOID CommandContext); #define USBCAMD_VERSION_200 0x200 typedef struct _USBCAMD_INTERFACE { INTERFACE Interface; PFNUSBCAMD_WaitOnDeviceEvent USBCAMD_WaitOnDeviceEvent; PFNUSBCAMD_BulkReadWrite USBCAMD_BulkReadWrite; PFNUSBCAMD_SetVideoFormat USBCAMD_SetVideoFormat; PFNUSBCAMD_SetIsoPipeState USBCAMD_SetIsoPipeState; PFNUSBCAMD_CancelBulkReadWrite USBCAMD_CancelBulkReadWrite; } USBCAMD_INTERFACE, *PUSBCAMD_INTERFACE; /* FIXME : Do we need USBCAMAPI here ? */ USBCAMAPI ULONG NTAPI USBCAMD_DriverEntry( PVOID Context1, PVOID Context2, ULONG DeviceContextSize, ULONG FrameContextSize, PADAPTER_RECEIVE_PACKET_ROUTINE ReceivePacket); USBCAMAPI PVOID NTAPI USBCAMD_AdapterReceivePacket( PHW_STREAM_REQUEST_BLOCK Srb, PUSBCAMD_DEVICE_DATA DeviceData, PDEVICE_OBJECT *DeviceObject, BOOLEAN NeedsCompletion); USBCAMAPI NTSTATUS NTAPI USBCAMD_ControlVendorCommand( PVOID DeviceContext, UCHAR Request, USHORT Value, USHORT Index, PVOID Buffer, PULONG BufferLength, BOOLEAN GetData, PCOMMAND_COMPLETE_FUNCTION CommandComplete, PVOID CommandContext); USBCAMAPI NTSTATUS NTAPI USBCAMD_SelectAlternateInterface( PVOID DeviceContext, PUSBD_INTERFACE_INFORMATION RequestInterface); USBCAMAPI NTSTATUS NTAPI USBCAMD_GetRegistryKeyValue( HANDLE Handle, PWCHAR KeyNameString, ULONG KeyNameStringLength, PVOID Data, ULONG DataLength); USBCAMAPI ULONG NTAPI USBCAMD_InitializeNewInterface( PVOID DeviceContext, PVOID DeviceData, ULONG Version, ULONG CamControlFlag); #ifdef __cplusplus } #endif #endif /* !defined(__USB_H) && !defined(__USBDI_H) */
8fd2671422caa7e28b55a831c25e1bc310f9b162
7df190df28da7e4ff166e55dc8ce780f11236a9f
/src/router/xfsprogs/db/sig.c
d4851cbc3c74f1b0a178e6b49451d6e5eea0dfa9
[]
no_license
mirror/dd-wrt
25416946e6132aa54b35809de61834a1825a9a36
8f2934a5a2adfbb59b471375aa3a38de5d036531
refs/heads/master
2023-08-31T14:54:47.496685
2023-08-30T17:40:54
2023-08-30T17:40:54
7,470,282
520
281
null
2023-05-29T20:56:24
2013-01-06T17:21:29
null
UTF-8
C
false
false
710
c
sig.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (c) 2000-2001,2005 Silicon Graphics, Inc. * All Rights Reserved. */ #include "libxfs.h" #include <signal.h> #include "sig.h" static int gotintr; static sigset_t intrset; static void interrupt(int sig, siginfo_t *info, void *uc) { gotintr = 1; } void blockint(void) { sigprocmask(SIG_BLOCK, &intrset, NULL); } void clearint(void) { gotintr = 0; } void init_sig(void) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = interrupt; sigaction(SIGINT, &sa, NULL); sigemptyset(&intrset); sigaddset(&intrset, SIGINT); } int seenint(void) { return gotintr; } void unblockint(void) { sigprocmask(SIG_UNBLOCK, &intrset, NULL); }
f7562fd255cb137a3a85bb83389ac10c6b7fbda6
e2b9f2354c36bd1edfa141d29f60c13ea176c0fe
/2017/sctf2017finals/defense/SSS/runner.c
bdc6de9cef9259cd358b44f802266ff4aab28b10
[]
no_license
Jinmo/ctfs
236d2c9c5a49d500e80ece4631a22c7fb32c3c3f
d225baef7942250a5ff15a3f2a9b7ad8501c7566
refs/heads/master
2021-07-24T15:17:05.489163
2021-07-05T16:05:15
2021-07-05T16:05:15
68,125,231
162
26
null
null
null
null
UTF-8
C
false
false
2,773
c
runner.c
#include <stdio.h> #include <stdlib.h> #include "script.h" void init_script() { setvbuf(stdin,0,2,0); setvbuf(stdout,0,2,0); alarm(120); } void print_message() { printf(" minimal script service\n"); printf(" this is not well-made script, so its function is limited\n"); printf(" declaration : \n"); printf("\n"); printf(" INTCONST : 64bit signed integer\n"); printf(" STRINGCONST: any printable characters\n"); printf(" SYMCONST : alphanumeric characters(max 32 characters)\n"); printf(" INT : (add INT INT)\n"); printf(" (sub INT INT)\n"); printf(" (mul INT INT)\n"); printf(" (and INT INT)\n"); printf(" (or INT INT)\n"); printf(" (int INTCONST)\n"); printf(" STR : (concat STR STR)\n"); printf(" (subst STR INT INT)\n"); printf(" (string \"STRINGCONST\")\n"); printf(" SYM : (sym SYMCONST)\n"); printf(" LIST: (con ANY ANY)\n"); printf(" FUNC: (fun SYM ANY)\n"); printf(" BOOL: (lt INT INT)\n"); printf(" (gt INT INT)\n"); printf(" (eq INT INT)\n"); printf(" (eq STR STR)\n"); printf(" (eq BOOL BOOL)\n"); printf(" (or BOOL BOOL)\n"); printf(" (and BOOL BOOL)\n"); printf(" (not BOOL)\n"); printf(" ANY: (car LIST)\n"); printf(" (cdr LIST)\n"); printf(" (ite BOOL ANY ANY)\n"); printf(" (let SYM ANY ANY)\n"); printf(" (FUNC ANY)\n"); printf(" example : \n"); printf(" (add (int 1) (int 2))\n"); printf(" - it computes 1 + 2.\n"); printf(" (concat (string \"hello \") (string \"world!\"))\n"); printf(" - it concatenate two strings.\n"); printf(" (let (sym odd) (fun (sym x) (sub (mul (sym x) (int 2)) (int 1))) ((sym odd) (int 6)))\n"); printf(" - it computes 6th odd number.\n"); printf(" (let (sym fib) (fun (sym x) (cdr (let (sym fibr) (fun (sym c) (ite (eq (cdr (sym c)) (int 0)) (con (car (sym c)) (int 0)) (ite (eq (cdr (sym c)) (int 1)) (con (car (sym c)) (int 1)) (con (car (sym c)) (add (cdr ((car (sym c)) (con (car (sym c)) (sub (cdr (sym c)) (int 1))))) (cdr ((car (sym c)) (con (car (sym c)) (sub (cdr (sym c)) (int 2)))))))))) ((sym fibr) (con (sym fibr) (sym x)))))) ((sym fib) (int 13)))\n"); printf(" - it computes 13th fibonacci number.\n"); } int main() { init_script(); print_message(); char linebuf[0x10000]; int errorno; while(1) { printf(">> "); fgets_eof(linebuf, 0x1000); if(errorno = execute(linebuf)) { printf("error occured, eno=%d\n", errorno); } } }
c9d9512a0f0c36532828122c048c8b01b498c7ae
7f6c235b0598353549959c18f69eefd20b766907
/libsrc/_DEVELOPMENT/EXAMPLES/zx/demo_sp1/BlackStar/src/sprites.c
dabf5f58d3faca615ff86cc4715710699c668f7b
[ "ClArtistic", "MIT" ]
permissive
z88dk/z88dk
46dfd4905f36d99333173cadd0a660839befc9f0
8b07f37cc43c5d9ffe69b563c80763491d8faff7
refs/heads/master
2023-09-04T19:29:49.254958
2023-09-03T20:51:24
2023-09-03T20:51:24
54,035,569
820
263
NOASSERTION
2023-09-05T11:09:04
2016-03-16T13:48:16
Assembly
UTF-8
C
false
false
4,038
c
sprites.c
#include <arch/zx/sp1.h> #include <stdlib.h> #include "gfx.h" #include "sprites.h" struct ssprites sprites[MAX_SPRITES]; // lists struct ssprites *sp_free; struct ssprites *sp_used; // shared iterators struct ssprites *sp_iter; struct ssprites *sp_iter2; // if there are items to garbage collect int sp_collect = 0; void init_sprites(void) { unsigned char i; // to be run ONCE sprites[PLAYER].s = sp1_CreateSpr(SP1_DRAW_MASK2LB, SP1_TYPE_2BYTE, 3, 16, 0); sp1_AddColSpr(sprites[PLAYER].s, SP1_DRAW_MASK2, 0, 64, 0); sp1_AddColSpr(sprites[PLAYER].s, SP1_DRAW_MASK2RB, 0, 0, 0); sprites[PLAYER].sprite = NULL; sprites[PLAYER].alive = 1; sprites[PLAYER].n = NULL; sprites[PLAYER].type = ST_PLAYER; // init our lists sp_used = sprites; sp_free = sprites + 1; for (i = 1; i < MAX_SPRITES - 1; ++i) { sprites[i].n = sprites + i + 1; sprites[i].alive = 0; } sprites[MAX_SPRITES - 1].n = NULL; sprites[MAX_SPRITES - 1].alive = 0; } unsigned char add_sprite(void) { struct ssprites *t; if (!sp_free) return 0; // always one is in use: the player! t = sp_used; sp_used = sp_free; sp_free = sp_free->n; sp_used->n = t; sp_used->alive = 1; return 1; } void collect_sprites(void) { struct ssprites *t, *tp; if (!sp_collect) return; // current, previous for (t = tp = sp_used; t && sp_collect;) { if (!t->alive) { if (t == sp_used) { tp = sp_free; sp_free = sp_used; sp_used = sp_used->n; sp_free->n = tp; t = tp = sp_used; --sp_collect; continue; } else { tp->n = t->n; t->n = sp_free; sp_free = t; t = tp->n; --sp_collect; continue; } } tp = t; t = t->n; } } void destroy_type_sprite(unsigned char type) { struct ssprites *t; if (!sp_used) return; for (t = sp_used; t; t = t->n) { if (t->alive && t->type & type) { sp1_MoveSprAbs(t->s, &cr, NULL, 0, 34, 0, 0); sp1_DeleteSpr(t->s); t->alive = 0; sp_collect++; } } } int add_explo(int x, int y) { if (!add_sprite()) return 0; sp_used->s = sp1_CreateSpr(SP1_DRAW_MASK2LB, SP1_TYPE_2BYTE, 3, 16, 2); sp1_AddColSpr(sp_used->s, SP1_DRAW_MASK2, 0, 64, 2); sp1_AddColSpr(sp_used->s, SP1_DRAW_MASK2RB, 0, 0, 2); sp_used->type = ST_EXPLO; sp_used->frame = 0; sp_used->delay = 0; sp_used->x = x; sp_used->y = y; sp_used->sprite = NULL; //explosion; sp1_MoveSprPix(sp_used->s, &cr, sp_used->sprite, 8 + sp_used->x, 8 + sp_used->y); return 1; } void add_enemy(int x, int y, unsigned char *sprite) { // not really a explosion, but saves some bytes as they're the same size if(!add_explo(x, y)) return; sp_used->type = ST_ENEMY; sp_used->sprite = sprite; sp_used->alive = 1; sp_used->delay = rand() % 15; sp_used->x = x; sp_used->y = y; sp1_MoveSprPix(sp_used->s, &cr, sp_used->sprite + sp_used->frame * 8 * 12, 8 + sp_used->x, 8 + sp_used->y); } void remove_sprite(struct ssprites *s) { sp1_MoveSprAbs(s->s, &cr, NULL, 0, 34, 0, 0); sp1_DeleteSpr(s->s); s->alive = 0; ++sp_collect; } void add_bullet(unsigned char type, unsigned char x, unsigned char y) { if(!add_sprite()) return; sp_used->s = sp1_CreateSpr(SP1_DRAW_MASK2LB, SP1_TYPE_2BYTE, 2, 8, 1); sp1_AddColSpr(sp_used->s, SP1_DRAW_MASK2RB, 0, 0, 1); sp_used->type = type; sp_used->frame = 0; sp_used->delay = 0; sp_used->x = x; sp_used->y = y; // player bullet if (type == ST_BULLET) { sp_used->sprite = impact; sp_used->iy = -6; } else { // ENEMY BULLET sp_used->sprite = impact + 4 * 8; sp_used->iy = 6; } sp1_MoveSprPix(sp_used->s, &cr, sp_used->sprite, sp_used->x, sp_used->y); }
c94236a7e3abecab706a765a1c9e8d870469d2ff
50dd46b8ece33f3cdd174284b15d1d51f89669d4
/third_party/edk2/EdkCompatibilityPkg/Foundation/Library/Smm/SmmScriptLib/SmmScriptLib.h
0a50afe9fc1547a650edc2534a1c6714370fde46
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause", "OpenSSL" ]
permissive
google/google-ctf
f99da1ee07729bbccb869fff1cbaed6a80e43bcc
df02323eaf945d15e124801c74abaadca2749dc7
refs/heads/master
2023-08-31T14:30:27.548081
2023-08-29T13:04:20
2023-08-29T13:04:20
131,317,137
4,136
607
Apache-2.0
2023-08-30T22:17:02
2018-04-27T15:56:03
Go
UTF-8
C
false
false
4,211
h
SmmScriptLib.h
/** @file This is an thunk implementation of the BootScript at run time. SmmScriptLib in Framework implementation is to save S3 Boot Script in SMM runtime. Here is the header file to define the API in this thunk library. Copyright (c) 2010, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #ifndef _SMM_SCRIPT_SAVE_H_ #define _SMM_SCRIPT_SAVE_H_ #include "Tiano.h" #include "EfiBootScript.h" #include "PiSmmDefinition.h" #include "PiSmmS3SaveState.h" typedef EFI_PHYSICAL_ADDRESS EFI_SMM_SCRIPT_TABLE; /** Intialize Boot Script table. This function should be called in SMM mode. The Thunk implementation is try to locate SmmSaveState protocol. @param SystemTable Pointer to the EFI sytem table @param SmmScriptTablePages The expected ScriptTable page number @param SmmScriptTableBase The returned ScriptTable base address @retval EFI_OUT_OF_RESOURCES No resource to do the initialization. @retval EFI_SUCCESS Function has completed successfully. **/ EFI_STATUS EFIAPI InitializeSmmScriptLib ( IN EFI_SYSTEM_TABLE *SystemTable, IN UINTN SmmScriptTablePages, OUT EFI_PHYSICAL_ADDRESS *SmmScriptTableBase ); /** Create Boot Script table. It will be ignore and just return EFI_SUCCESS since the boot script table is maintained by DxeBootScriptLib. Create Table is not needed. @param ScriptTable Pointer to the boot script table to create. @param Type The type of table to creat. @retval EFI_SUCCESS Function has completed successfully. **/ EFI_STATUS EFIAPI SmmBootScriptCreateTable ( IN OUT EFI_SMM_SCRIPT_TABLE *ScriptTable, IN UINTN Type ); /** Adds a record into a specified Framework boot script table. This function is used to store a boot script record into a given boot script table in SMM runtime. The parameter is the same with definitionin BootScriptSave Protocol. @param ScriptTable Pointer to the script table to write to. In the thunk implementation, this parameter is ignored since the boot script table is maintained by BootScriptLib. @param Type Not used. @param OpCode The operation code (opcode) number. @param ... Argument list that is specific to each opcode. @retval EFI_SUCCESS The operation succeeded. A record was added into the specified script table. @retval EFI_INVALID_PARAMETER The parameter is illegal or the given boot script is not supported. If the opcode is unknow or not supported because of the PCD Feature Flags. @retval EFI_OUT_OF_RESOURCES There is insufficient memory to store the boot script. **/ EFI_STATUS EFIAPI SmmBootScriptWrite ( IN OUT EFI_SMM_SCRIPT_TABLE *ScriptTable, IN UINTN Type, IN UINT16 OpCode, ... ); /** Close Boot Script table. It will be ignore and just return EFI_SUCCESS since the boot script table is maintained by DxeBootScriptLib. @param ScriptTableBase Pointer to the boot script table to create. @param ScriptTablePtr Pointer to the script table to write to. @param Type The type of table to creat. @retval EFI_SUCCESS - Function has completed successfully. **/ EFI_STATUS EFIAPI SmmBootScriptCloseTable ( IN EFI_SMM_SCRIPT_TABLE ScriptTableBase, IN EFI_SMM_SCRIPT_TABLE ScriptTablePtr, IN UINTN Type ); #endif
62f8490d8f4cbcd1e4306536b29c4cd1e73dda45
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/rump/dev/lib/libumass/umass_component.c
ab7457ec80227caff640479853225ddb5f436ddc
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
478
c
umass_component.c
/* $NetBSD: umass_component.c,v 1.5 2019/01/27 09:19:37 rin Exp $ */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: umass_component.c,v 1.5 2019/01/27 09:19:37 rin Exp $"); #include <sys/param.h> #include <sys/conf.h> #include <sys/device.h> #include <sys/kmem.h> #include <sys/stat.h> #include "ioconf.c" #include <rump-sys/kern.h> RUMP_COMPONENT(RUMP_COMPONENT_DEV) { config_init_component(cfdriver_ioconf_umass, cfattach_ioconf_umass, cfdata_ioconf_umass); }
53e51f6ce794c2e4842b2e1fee5d06307bfc3a53
1efb2283837c9b70bc6449cec877799e4efa3268
/test/mpi/rma/strided_get_indexed.c
12916a3931ce4a3b70467a4fc2b22c140e07133b
[ "mpich2" ]
permissive
pmodels/mpich
d2392e8e30536cad3e500c16aa1e71211101d83f
2d265f9f5f93ebdd07ad547423bc6212868262a4
refs/heads/main
2023-09-04T05:50:15.041823
2023-09-01T23:07:33
2023-09-01T23:07:33
70,918,679
506
313
NOASSERTION
2023-09-14T14:38:36
2016-10-14T14:39:42
C
UTF-8
C
false
false
3,889
c
strided_get_indexed.c
/* * Copyright (C) by Argonne National Laboratory * See COPYRIGHT in top-level directory */ /* One-Sided MPI 2-D Strided Get Test * * Author: James Dinan <dinan@mcs.anl.gov> * Date : December, 2010 * * This code performs N strided get operations from a 2d patch of a shared * array. The array has dimensions [X, Y] and the subarray has dimensions * [SUB_X, SUB_Y] and begins at index [0, 0]. The input and output buffers are * specified using an MPI indexed type. */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <mpi.h> #include "mpitest.h" #include "squelch.h" #define XDIM 8 #define YDIM 1024 #define SUB_XDIM 8 #define SUB_YDIM 256 int main(int argc, char **argv) { int i, j, rank, nranks, peer, bufsize, errors; double *win_buf, *loc_buf; MPI_Win buf_win; int idx_rem[SUB_YDIM]; int blk_len[SUB_YDIM]; MPI_Datatype loc_type, rem_type; MTest_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &nranks); bufsize = XDIM * YDIM * sizeof(double); MPI_Alloc_mem(bufsize, MPI_INFO_NULL, &win_buf); MPI_Alloc_mem(bufsize, MPI_INFO_NULL, &loc_buf); for (i = 0; i < XDIM * YDIM; i++) { *(win_buf + i) = 1.0 + rank; *(loc_buf + i) = -1.0; } MPI_Win_create(win_buf, bufsize, 1, MPI_INFO_NULL, MPI_COMM_WORLD, &buf_win); peer = (rank + 1) % nranks; /* Build the datatype */ for (i = 0; i < SUB_YDIM; i++) { idx_rem[i] = i * XDIM; blk_len[i] = SUB_XDIM; } MPI_Type_indexed(SUB_YDIM, blk_len, idx_rem, MPI_DOUBLE, &loc_type); MPI_Type_indexed(SUB_YDIM, blk_len, idx_rem, MPI_DOUBLE, &rem_type); MPI_Type_commit(&loc_type); MPI_Type_commit(&rem_type); /* Perform get operation */ MPI_Win_lock(MPI_LOCK_EXCLUSIVE, peer, 0, buf_win); MPI_Get(loc_buf, 1, loc_type, peer, 0, 1, rem_type, buf_win); /* Use the datatype only on the remote side (must have SUB_XDIM == XDIM) */ /* MPI_Get(loc_buf, SUB_XDIM*SUB_YDIM, MPI_DOUBLE, peer, 0, 1, rem_type, buf_win); */ MPI_Win_unlock(peer, buf_win); MPI_Type_free(&loc_type); MPI_Type_free(&rem_type); MPI_Barrier(MPI_COMM_WORLD); /* Verify that the results are correct */ errors = 0; for (i = 0; i < SUB_XDIM; i++) { for (j = 0; j < SUB_YDIM; j++) { const double actual = *(loc_buf + i + j * XDIM); const double expected = (1.0 + peer); if (fabs(actual - expected) > 1.0e-10) { SQUELCH(printf("%d: Data validation failed at [%d, %d] expected=%f actual=%f\n", rank, j, i, expected, actual);); errors++; fflush(stdout); } } } for (i = SUB_XDIM; i < XDIM; i++) { for (j = 0; j < SUB_YDIM; j++) { const double actual = *(loc_buf + i + j * XDIM); const double expected = -1.0; if (fabs(actual - expected) > 1.0e-10) { SQUELCH(printf("%d: Data validation failed at [%d, %d] expected=%f actual=%f\n", rank, j, i, expected, actual);); errors++; fflush(stdout); } } } for (i = 0; i < XDIM; i++) { for (j = SUB_YDIM; j < YDIM; j++) { const double actual = *(loc_buf + i + j * XDIM); const double expected = -1.0; if (fabs(actual - expected) > 1.0e-10) { SQUELCH(printf("%d: Data validation failed at [%d, %d] expected=%f actual=%f\n", rank, j, i, expected, actual);); errors++; fflush(stdout); } } } MPI_Win_free(&buf_win); MPI_Free_mem(win_buf); MPI_Free_mem(loc_buf); MTest_Finalize(errors); return MTestReturnValue(errors); }
27576f612398dbf07e5959880ad9143c20a6cc3d
e90671c6b1cb69eaf57bd0ab4bbd1bd92ba9aea9
/android/vendored/sdk48/@shopify/react-native-skia/cpp/skia/include/core/SkRSXform.h
5fcfff29221afdf6c5b98d9667da2f52666b4697
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
expo/expo
72fc802e3b6806789225bdd856031a8d150dd6f5
40f087fc0c0ab22270cfef2673bced44af170c34
refs/heads/main
2023-08-17T01:38:28.442098
2023-08-16T21:43:11
2023-08-16T21:43:11
65,750,241
23,742
5,421
MIT
2023-09-14T21:37:37
2016-08-15T17:14:25
TypeScript
UTF-8
C
false
false
1,919
h
SkRSXform.h
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkRSXform_DEFINED #define SkRSXform_DEFINED #include "include/core/SkPoint.h" #include "include/core/SkSize.h" /** * A compressed form of a rotation+scale matrix. * * [ fSCos -fSSin fTx ] * [ fSSin fSCos fTy ] * [ 0 0 1 ] */ struct SK_API SkRSXform { static SkRSXform Make(SkScalar scos, SkScalar ssin, SkScalar tx, SkScalar ty) { SkRSXform xform = { scos, ssin, tx, ty }; return xform; } /* * Initialize a new xform based on the scale, rotation (in radians), final tx,ty location * and anchor-point ax,ay within the src quad. * * Note: the anchor point is not normalized (e.g. 0...1) but is in pixels of the src image. */ static SkRSXform MakeFromRadians(SkScalar scale, SkScalar radians, SkScalar tx, SkScalar ty, SkScalar ax, SkScalar ay) { const SkScalar s = SkScalarSin(radians) * scale; const SkScalar c = SkScalarCos(radians) * scale; return Make(c, s, tx + -c * ax + s * ay, ty + -s * ax - c * ay); } SkScalar fSCos; SkScalar fSSin; SkScalar fTx; SkScalar fTy; bool rectStaysRect() const { return 0 == fSCos || 0 == fSSin; } void setIdentity() { fSCos = 1; fSSin = fTx = fTy = 0; } void set(SkScalar scos, SkScalar ssin, SkScalar tx, SkScalar ty) { fSCos = scos; fSSin = ssin; fTx = tx; fTy = ty; } void toQuad(SkScalar width, SkScalar height, SkPoint quad[4]) const; void toQuad(const SkSize& size, SkPoint quad[4]) const { this->toQuad(size.width(), size.height(), quad); } void toTriStrip(SkScalar width, SkScalar height, SkPoint strip[4]) const; }; #endif
6234eb6868075e4470a572656cb6d46392e4d6c4
e726b667d365a72cdf0fcd739aa830470f06d20a
/src/readstat/readstat_parser.c
e5c4625e8ee49a794a0822bdf0941ca7343be3da
[ "MIT" ]
permissive
tidyverse/haven
49e3a1bc82a766612eec1ff0c4e5d56a26e42a66
9b3b21b5e9b64867eb53818faa7e9a22480f347d
refs/heads/main
2023-08-30T19:02:26.976602
2023-06-30T20:44:03
2023-06-30T20:44:03
30,308,523
283
115
NOASSERTION
2023-09-04T06:31:40
2015-02-04T16:28:17
C
UTF-8
C
false
false
3,941
c
readstat_parser.c
#include <stdlib.h> #include "readstat.h" #include "readstat_io_unistd.h" readstat_parser_t *readstat_parser_init(void) { readstat_parser_t *parser = calloc(1, sizeof(readstat_parser_t)); parser->io = calloc(1, sizeof(readstat_io_t)); if (unistd_io_init(parser) != READSTAT_OK) { readstat_parser_free(parser); return NULL; } parser->output_encoding = "UTF-8"; return parser; } void readstat_parser_free(readstat_parser_t *parser) { if (parser) { if (parser->io) { readstat_set_io_ctx(parser, NULL); free(parser->io); } free(parser); } } readstat_error_t readstat_set_metadata_handler(readstat_parser_t *parser, readstat_metadata_handler metadata_handler) { parser->handlers.metadata = metadata_handler; return READSTAT_OK; } readstat_error_t readstat_set_note_handler(readstat_parser_t *parser, readstat_note_handler note_handler) { parser->handlers.note = note_handler; return READSTAT_OK; } readstat_error_t readstat_set_variable_handler(readstat_parser_t *parser, readstat_variable_handler variable_handler) { parser->handlers.variable = variable_handler; return READSTAT_OK; } readstat_error_t readstat_set_value_handler(readstat_parser_t *parser, readstat_value_handler value_handler) { parser->handlers.value = value_handler; return READSTAT_OK; } readstat_error_t readstat_set_value_label_handler(readstat_parser_t *parser, readstat_value_label_handler label_handler) { parser->handlers.value_label = label_handler; return READSTAT_OK; } readstat_error_t readstat_set_error_handler(readstat_parser_t *parser, readstat_error_handler error_handler) { parser->handlers.error = error_handler; return READSTAT_OK; } readstat_error_t readstat_set_progress_handler(readstat_parser_t *parser, readstat_progress_handler progress_handler) { parser->handlers.progress = progress_handler; return READSTAT_OK; } readstat_error_t readstat_set_fweight_handler(readstat_parser_t *parser, readstat_fweight_handler fweight_handler) { parser->handlers.fweight = fweight_handler; return READSTAT_OK; } readstat_error_t readstat_set_open_handler(readstat_parser_t *parser, readstat_open_handler open_handler) { parser->io->open = open_handler; return READSTAT_OK; } readstat_error_t readstat_set_close_handler(readstat_parser_t *parser, readstat_close_handler close_handler) { parser->io->close = close_handler; return READSTAT_OK; } readstat_error_t readstat_set_seek_handler(readstat_parser_t *parser, readstat_seek_handler seek_handler) { parser->io->seek = seek_handler; return READSTAT_OK; } readstat_error_t readstat_set_read_handler(readstat_parser_t *parser, readstat_read_handler read_handler) { parser->io->read = read_handler; return READSTAT_OK; } readstat_error_t readstat_set_update_handler(readstat_parser_t *parser, readstat_update_handler update_handler) { parser->io->update = update_handler; return READSTAT_OK; } readstat_error_t readstat_set_io_ctx(readstat_parser_t *parser, void *io_ctx) { if (parser->io->io_ctx_needs_free) { free(parser->io->io_ctx); } parser->io->io_ctx = io_ctx; parser->io->io_ctx_needs_free = 0; return READSTAT_OK; } readstat_error_t readstat_set_file_character_encoding(readstat_parser_t *parser, const char *encoding) { parser->input_encoding = encoding; return READSTAT_OK; } readstat_error_t readstat_set_handler_character_encoding(readstat_parser_t *parser, const char *encoding) { parser->output_encoding = encoding; return READSTAT_OK; } readstat_error_t readstat_set_row_limit(readstat_parser_t *parser, long row_limit) { parser->row_limit = row_limit; return READSTAT_OK; } readstat_error_t readstat_set_row_offset(readstat_parser_t *parser, long row_offset) { parser->row_offset = row_offset; return READSTAT_OK; }
4d429e193e77a661e8cbe1a31924258cab2cf4ca
7df190df28da7e4ff166e55dc8ce780f11236a9f
/src/router/xfsprogs/scrub/scrub.h
537a2ebe8d3b046269256af7b4d75c8a487e18e8
[]
no_license
mirror/dd-wrt
25416946e6132aa54b35809de61834a1825a9a36
8f2934a5a2adfbb59b471375aa3a38de5d036531
refs/heads/master
2023-08-31T14:54:47.496685
2023-08-30T17:40:54
2023-08-30T17:40:54
7,470,282
520
281
null
2023-05-29T20:56:24
2013-01-06T17:21:29
null
UTF-8
C
false
false
2,790
h
scrub.h
// SPDX-License-Identifier: GPL-2.0+ /* * Copyright (C) 2018 Oracle. All Rights Reserved. * Author: Darrick J. Wong <darrick.wong@oracle.com> */ #ifndef XFS_SCRUB_SCRUB_H_ #define XFS_SCRUB_SCRUB_H_ /* Online scrub and repair. */ enum check_outcome { CHECK_DONE, /* no further processing needed */ CHECK_REPAIR, /* schedule this for repairs */ CHECK_ABORT, /* end program */ CHECK_RETRY, /* repair failed, try again later */ }; struct action_item; void scrub_report_preen_triggers(struct scrub_ctx *ctx); int scrub_primary_super(struct scrub_ctx *ctx, struct action_list *alist); int scrub_ag_headers(struct scrub_ctx *ctx, xfs_agnumber_t agno, struct action_list *alist); int scrub_ag_metadata(struct scrub_ctx *ctx, xfs_agnumber_t agno, struct action_list *alist); int scrub_fs_metadata(struct scrub_ctx *ctx, struct action_list *alist); int scrub_fs_summary(struct scrub_ctx *ctx, struct action_list *alist); bool can_scrub_fs_metadata(struct scrub_ctx *ctx); bool can_scrub_inode(struct scrub_ctx *ctx); bool can_scrub_bmap(struct scrub_ctx *ctx); bool can_scrub_dir(struct scrub_ctx *ctx); bool can_scrub_attr(struct scrub_ctx *ctx); bool can_scrub_symlink(struct scrub_ctx *ctx); bool can_scrub_parent(struct scrub_ctx *ctx); bool xfs_can_repair(struct scrub_ctx *ctx); int scrub_inode_fields(struct scrub_ctx *ctx, uint64_t ino, uint32_t gen, struct action_list *alist); int scrub_data_fork(struct scrub_ctx *ctx, uint64_t ino, uint32_t gen, struct action_list *alist); int scrub_attr_fork(struct scrub_ctx *ctx, uint64_t ino, uint32_t gen, struct action_list *alist); int scrub_cow_fork(struct scrub_ctx *ctx, uint64_t ino, uint32_t gen, struct action_list *alist); int scrub_dir(struct scrub_ctx *ctx, uint64_t ino, uint32_t gen, struct action_list *alist); int scrub_attr(struct scrub_ctx *ctx, uint64_t ino, uint32_t gen, struct action_list *alist); int scrub_symlink(struct scrub_ctx *ctx, uint64_t ino, uint32_t gen, struct action_list *alist); int scrub_parent(struct scrub_ctx *ctx, uint64_t ino, uint32_t gen, struct action_list *alist); /* Repair parameters are the scrub inputs and retry count. */ struct action_item { struct list_head list; __u64 ino; __u32 type; __u32 flags; __u32 gen; __u32 agno; }; /* * Only ask the kernel to repair this object if the kernel directly told us it * was corrupt. Objects that are only flagged as having cross-referencing * errors or flagged as eligible for optimization are left for later. */ #define XRM_REPAIR_ONLY (1U << 0) /* Complain if still broken even after fix. */ #define XRM_COMPLAIN_IF_UNFIXED (1U << 1) enum check_outcome xfs_repair_metadata(struct scrub_ctx *ctx, int fd, struct action_item *aitem, unsigned int repair_flags); #endif /* XFS_SCRUB_SCRUB_H_ */
3caef823e1a82a9d7e5a1006f0f4d79a6d36897a
18333497cc6db4a990a5f5e7b0dca14e9a517a73
/include/cmt/common.h
ce4b397f2ac80b5a6dbe541b625c4e3d7b95177b
[ "MIT" ]
permissive
recp/cmt
6ecbca0a356ec044257285ab58e062ee6af55c7c
e2730ade077345b389213d6695d0d7a6c4e93264
refs/heads/master
2023-05-25T16:32:50.511305
2023-05-14T11:40:55
2023-05-14T11:40:55
137,069,724
138
12
MIT
2023-05-14T11:40:56
2018-06-12T12:39:37
C
UTF-8
C
false
false
1,038
h
common.h
/* * Copyright (c), Recep Aslantas. * MIT License (MIT), http://opensource.org/licenses/MIT */ #ifndef cmt_common_h #define cmt_common_h #define MT_EXPORT __attribute__((visibility("default"))) #define MT_HIDE __attribute__((visibility("hidden"))) #define MT_INLINE inline __attribute((always_inline)) #define MT_ALIGN(X) __attribute((aligned(X))) #include <stdlib.h> #include <stdint.h> #include <stdbool.h> /* MT_API_AVAILABLE usage: MT_API_AVAILABLE(minimum_macos_version, minimum_ios_version) */ #ifdef __APPLE__ # include <os/availability.h> # define mt_macCatalyst macCatalyst # define mt_ios ios # define mt_macos macos //# define MT_API_AVAILABLE(M, I) API_AVAILABLE(macos(M), ios(I)) # define MT_API_AVAILABLE(...) API_AVAILABLE(__VA_ARGS__) # define MT_API_UNAVAILABLE(X) API_UNAVAILABLE(X) #else # define mt_macCatalyst # define mt_ios # define mt_macos # define MT_API_AVAILABLE(...) # define MT_API_UNAVAILABLE(x) # define API_UNAVAILABLE(...) #endif #endif /* cmt_common_h */
23ab3ba1a29e745642e79fe14a2855bf2d279006
0cc343d927d5db6693006018986715c43acab961
/tests/check_expr_varargs.c
7195aee736921ea7476916759ca4f7b8cadfb541
[ "MIT" ]
permissive
verifast/verifast
ec0101fc4a69bd33c5f66be4444169c4e060ead8
d152da790c7ebf72ce616533a6c83082629adbdb
refs/heads/master
2023-08-25T00:13:51.464802
2023-08-13T10:00:00
2023-08-13T10:00:00
14,519,163
325
64
NOASSERTION
2023-08-10T21:16:08
2013-11-19T08:57:02
OCaml
UTF-8
C
false
false
163
c
check_expr_varargs.c
#include <stdio.h> int foo() //@ requires true; //@ ensures true; { return 42; } void test() //@ requires true; //@ ensures true; { printf("%d\n", foo()); }
05f35f6d52f54e043eb43f982d72b698b56e8dad
c85df9a1ad627707fc603f40f7df056af16900c9
/source/libs/libruntimeiospatch/runtimeiospatch.h
d7cb9ba851315218bd6069948085fc9319533dcd
[]
no_license
wiidev/usbloadergx
28b582c2c8231ca7f313a321a134d6784358a770
e25c4e96430524c080767679b0c4a0d7595412a8
refs/heads/enhanced
2023-08-11T18:47:12.728031
2023-01-07T23:30:02
2023-01-07T23:30:02
204,522,898
313
124
null
2023-07-21T17:06:18
2019-08-26T17:05:59
C
UTF-8
C
false
false
6,084
h
runtimeiospatch.h
// 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, version 2.0. // 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 2.0 for more details. // Copyright (C) 2010 Joseph Jordan <joe.ftpii@psychlaw.com.au> // Copyright (C) 2012-2013 damysteryman // Copyright (C) 2012-2015 Christopher Bratusek <nano@jpberlin.de> // Copyright (C) 2013 DarkMatterCore // Copyright (C) 2014 megazig // Copyright (C) 2015 FIX94 #ifndef __RUNTIMEIOSPATCH_H__ #define __RUNTIMEIOSPATCH_H__ /** * Version information for Libruntimeiospatch. */ #define LIB_RUNTIMEIOSPATCH_VERSION "1.5.2" //============================================================================== // HW_RVL header //============================================================================== #if defined(HW_RVL) /* defined(HW_RVL) */ /** *Returns true when HW_AHBPROT access can be applied */ #define AHBPROT_DISABLED (*(vu32*)0xcd800064 == 0xFFFFFFFF) //============================================================================== // Error code definitions: //============================================================================== #define ERROR_AHBPROT -5 #define ERROR_PATCH -7 //============================================================================== // C++ header //============================================================================== #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ //============================================================================== // Extra standard declarations //============================================================================== //typedef signed int s32; //============================================================================== //============================================================================== // Patchsets: //============================================================================== /* Wii: * DI Readlimit * ISFS Permissions * ES SetUID * ES SetIdentify * Hash Check (aka Trucha) * New Hash Check (aka New Trucha) * SSL patches Sciifii: * MEM2 Prot * ES OpenTitleContent 1 & 2 * ES ReadContent Prot * ES CloseContent * ES TitleVersionCheck * ES TitleDeleteCheck vWii: * Kill Anti-SystemTitle-Install 1, 2, 3, 4 & 5 */ //============================================================================== // Functions: //============================================================================== /** * This function can be used to keep HW_AHBPROT access when going to reload IOS * @param verbose Flag determing whether or not to print messages on-screen * @example * if(AHBPROT_DISABLED) { * s32 ret; * ret = IosPatch_AHBPROT(false); * if (ret) { * IOS_ReloadIOS(36); * } else { * printf("IosPatch_AHBPROT failed."); * } * } * @return Signed 32bit integer representing code * > 0 : Success - return equals to number of applied patches * ERROR_AHBPROT : Error - No HW_AHBPROT access */ s32 IosPatch_AHBPROT(bool verbose); /** * This function applies patches on current IOS * @see Patchsets * @param wii Flag determining whether or not to apply Wii patches. * @param sciifii Flag determining whether or not to apply extra Sciifii patches. * @param vwii Flag determining whether or not to apply extra vWii patches. * @param wiivc Flag determining whether or not to apply WiiVC patches. * @param verbose Flag determining whether or not to print messages on-screen. * @example if(AHBPROT_DISABLED) IosPatch_FULL(true, false, false, false); * @return Signed 32bit integer representing code * > 0 : Success - return equals to number of applied patches * ERROR_AHBPROT : Error - No HW_AHBPROT access * ERROR_PATCH : Error - Patching HW_AHBPROT access failed */ s32 IosPatch_RUNTIME(bool wii, bool sciifii, bool vwii, bool wiivc, bool verbose); /** * This function combines IosPatch_AHBPROT + IOS_ReloadIOS + IosPatch_RUNTIME * @see Patchsets * @param wii Flag determining whether or not to apply Wii patches. * @param sciifii Flag determining whether or not to apply extra Sciifii patches. * @param vwii Flag determining whether or not to apply extra vWii patches. * @param wiivc Flag determining whether or not to apply WiiVC patches. * @param verbose Flag determining whether or not to print messages on-screen. * @param IOS Which IOS to reload into. * @example if(AHBPROT_DISABLED) IosPatch_FULL(true, false, false, false, 58); * @return Signed 32bit integer representing code * > 0 : Success - return equals to number of applied patches * ERROR_AHBPROT : Error - No HW_AHBPROT access * ERROR_PATCH : Error - Patching HW_AHBPROT access failed */ s32 IosPatch_FULL(bool wii, bool sciifii, bool vwii, bool wiivc, bool verbose, int IOS); /** * This function patches only SSL certificate check * @param verbose Flag determing whether or not to print messages on-screen. * @example if(AHBPROT_DISABLED) IosPatch_SSL(true); * @return Signed 32bit integer representing code * > 0 : Success - return equals to number of applied patches * ERROR_AHBPROT : Error - No HW_AHBPROT access */ s32 IosPatch_SSL(bool verbose); //============================================================================== // C++ footer //============================================================================== #ifdef __cplusplus } #endif /* __cplusplus */ //============================================================================== // HW_RVL footer //============================================================================== #endif /* defined(HW_RVL) */ #endif
453c07d138268c0ad622e42516494d625890e031
aa3befea459382dc5c01c925653d54f435b3fb0f
/arch/arm/src/samd2l2/hardware/saml_adc.h
e2d8e3fc43f14088677491f446abefaf51ddc807
[ "MIT-open-group", "BSD-3-Clause", "HPND-sell-variant", "BSD-4-Clause-UC", "LicenseRef-scancode-warranty-disclaimer", "MIT-0", "LicenseRef-scancode-bsd-atmel", "LicenseRef-scancode-gary-s-brown", "LicenseRef-scancode-proprietary-license", "SunPro", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "LicenseRef-scancode-other-permissive", "HPND", "ISC", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "GPL-1.0-or-later", "CC-BY-2.0", "CC-BY-4.0" ]
permissive
apache/nuttx
14519a7bff4a87935d94fb8fb2b19edb501c7cec
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
refs/heads/master
2023-08-25T06:55:45.822534
2023-08-23T16:03:31
2023-08-24T21:25:47
228,103,273
407
241
Apache-2.0
2023-09-14T18:26:05
2019-12-14T23:27:55
C
UTF-8
C
false
false
5,175
h
saml_adc.h
/**************************************************************************** * arch/arm/src/samd2l2/hardware/saml_adc.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you 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. * ****************************************************************************/ /* References: * "Microchip SAM L21 Family Datasheet", Rev A - 02/2017 */ #ifndef __ARCH_ARM_SRC_SAMD2L2_HARDWARE_SAML_ADC_H #define __ARCH_ARM_SRC_SAMD2L2_HARDWARE_SAML_ADC_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include "chip.h" #ifdef CONFIG_ARCH_FAMILY_SAML21 /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* ADC register offsets *****************************************************/ #define SAM_ADC_CTRLA_OFFSET 0x0000 /* Control A Register */ #define SAM_ADC_CTRLB_OFFSET 0x0001 /* Control B Register */ #define SAM_ADC_REFCTL_OFFSET 0x0002 /* Reference Control Register */ #define SAM_ADC_EVCTRL_OFFSET 0x0003 /* Event Control Register */ #define SAM_ADC_INTENCLR_OFFSET 0x0004 /* Interrupt Enable Clear Register */ #define SAM_ADC_INTENSET_OFFSET 0x0005 /* Interrupt Enable Set Register */ #define SAM_ADC_INTFLAG_OFFSET 0x0006 /* Interrupt Flag Status and Clear Register */ #define SAM_ADC_SEQSTATUS_OFFSET 0x0007 /* Sequence Status Register */ #define SAM_ADC_INPUTCTRL_OFFSET 0x0008 /* Input Control Register */ #define SAM_ADC_CTRLC_OFFSET 0x000A /* Control C Register */ #define SAM_ADC_AVGCTRL_OFFSET 0x000C /* Average Control Register */ #define SAM_ADC_SAMPCTRL_OFFSET 0x000D /* Sampling Time Control Register */ #define SAM_ADC_WINLT_OFFSET 0x000E /* Window Monitor Lower Threshold Register */ #define SAM_ADC_WINUT_OFFSET 0x0010 /* Window Monitor Upper Threshold Register */ #define SAM_ADC_GAINCORR_OFFSET 0x0012 /* Gain Correction Register */ #define SAM_ADC_OFFSETCORR_OFFSET 0x0014 /* Offset Correction Register */ #define SAM_ADC_SWTRIG_OFFSET 0x0018 /* Software Trigger Register */ #define SAM_ADC_DBGCTRL_OFFSET 0x001C /* Debug Control Register */ #define SAM_ADC_SYNCBUSY_OFFSET 0x0020 /* Synchronization Busy Register */ #define SAM_ADC_RESULT_OFFSET 0x0024 /* Result Register */ #define SAM_ADC_SEQCTRL_OFFSET 0x0028 /* Sequence Control Register */ #define SAM_ADC_CALIB_OFFSET 0x002C /* Calibration Register */ /* ADC register addresses ***************************************************/ #define SAM_ADC_CTRLA (SAM_ADC_BASE + SAM_ADC_CTRLA_OFFSET) #define SAM_ADC_CTRLB (SAM_ADC_BASE + SAM_ADC_CTRLB_OFFSET) #define SAM_ADC_REFCTL (SAM_ADC_BASE + SAM_ADC_REFCTL_OFFSET) #define SAM_ADC_EVCTRL (SAM_ADC_BASE + SAM_ADC_EVCTRL_OFFSET) #define SAM_ADC_INTENCLR (SAM_ADC_BASE + SAM_ADC_INTENCLR_OFFSET) #define SAM_ADC_INTENSET (SAM_ADC_BASE + SAM_ADC_INTENSET_OFFSET) #define SAM_ADC_INTFLAG (SAM_ADC_BASE + SAM_ADC_INTFLAG_OFFSET) #define SAM_ADC_SEQSTATUS (SAM_ADC_BASE + SAM_ADC_SEQSTATUS_OFFSET) #define SAM_ADC_INPUTCTRL (SAM_ADC_BASE + SAM_ADC_INPUTCTRL_OFFSET) #define SAM_ADC_CTRLC (SAM_ADC_BASE + SAM_ADC_CTRLC_OFFSET) #define SAM_ADC_AVGCTRL (SAM_ADC_BASE + SAM_ADC_AVGCTRL_OFFSET) #define SAM_ADC_SAMPCTRL (SAM_ADC_BASE + SAM_ADC_SAMPCTRL_OFFSET) #define SAM_ADC_WINLT (SAM_ADC_BASE + SAM_ADC_WINLT_OFFSET) #define SAM_ADC_WINUT (SAM_ADC_BASE + SAM_ADC_WINUT_OFFSET) #define SAM_ADC_GAINCORR (SAM_ADC_BASE + SAM_ADC_GAINCORR_OFFSET) #define SAM_ADC_OFFSETCORR (SAM_ADC_BASE + SAM_ADC_OFFSETCORR_OFFSET) #define SAM_ADC_SWTRIG (SAM_ADC_BASE + SAM_ADC_SWTRIG_OFFSET) #define SAM_ADC_DBGCTRL (SAM_ADC_BASE + SAM_ADC_DBGCTRL_OFFSET) #define SAM_ADC_SYNCBUSY (SAM_ADC_BASE + SAM_ADC_SYNCBUSY_OFFSET) #define SAM_ADC_RESULT (SAM_ADC_BASE + SAM_ADC_RESULT_OFFSET) #define SAM_ADC_SEQCTRL (SAM_ADC_BASE + SAM_ADC_SEQCTRL_OFFSET) #define SAM_ADC_CALIB (SAM_ADC_BASE + SAM_ADC_CALIB_OFFSET) #endif /* CONFIG_ARCH_FAMILY_SAML21 */ #endif /* __ARCH_ARM_SRC_SAMD2L2_HARDWARE_SAML_ADC_H */
5c5e562b344ec311d8a6559cb1a8b5d7f735c7e5
010279e2ba272d09e9d2c4e903722e5faba2cf7a
/contrib/libs/libxml/xmlregexp.c
8d01c2ba32c85fbfc08576a02a0606c0723a92a0
[ "MIT", "Apache-2.0" ]
permissive
catboost/catboost
854c1a1f439a96f1ae6b48e16644be20aa04dba2
f5042e35b945aded77b23470ead62d7eacefde92
refs/heads/master
2023-09-01T12:14:14.174108
2023-09-01T10:01:01
2023-09-01T10:22:12
97,556,265
8,012
1,425
Apache-2.0
2023-09-11T03:32:32
2017-07-18T05:29:04
Python
UTF-8
C
false
false
222,917
c
xmlregexp.c
/* * regexp.c: generic and extensible Regular Expression engine * * Basically designed with the purpose of compiling regexps for * the variety of validation/schemas mechanisms now available in * XML related specifications these include: * - XML-1.0 DTD validation * - XML Schemas structure part 1 * - XML Schemas Datatypes part 2 especially Appendix F * - RELAX-NG/TREX i.e. the counter proposal * * See Copyright for the status of this software. * * Daniel Veillard <veillard@redhat.com> */ #define IN_LIBXML #include "libxml.h" #ifdef LIBXML_REGEXP_ENABLED /* #define DEBUG_ERR */ #include <stdio.h> #include <string.h> #ifdef HAVE_LIMITS_H #include <limits.h> #endif #ifdef HAVE_STDINT_H #include <stdint.h> #endif #include <libxml/tree.h> #include <libxml/parserInternals.h> #include <libxml/xmlregexp.h> #include <libxml/xmlautomata.h> #include <libxml/xmlunicode.h> #ifndef INT_MAX #define INT_MAX 123456789 /* easy to flag and big enough for our needs */ #endif #ifndef SIZE_MAX #define SIZE_MAX ((size_t) -1) #endif /* #define DEBUG_REGEXP_GRAPH */ /* #define DEBUG_REGEXP_EXEC */ /* #define DEBUG_PUSH */ /* #define DEBUG_COMPACTION */ #define MAX_PUSH 10000000 #ifdef ERROR #undef ERROR #endif #define ERROR(str) \ ctxt->error = XML_REGEXP_COMPILE_ERROR; \ xmlRegexpErrCompile(ctxt, str); #define NEXT ctxt->cur++ #define CUR (*(ctxt->cur)) #define NXT(index) (ctxt->cur[index]) #define CUR_SCHAR(s, l) xmlStringCurrentChar(NULL, s, &l) #define NEXTL(l) ctxt->cur += l; #define XML_REG_STRING_SEPARATOR '|' /* * Need PREV to check on a '-' within a Character Group. May only be used * when it's guaranteed that cur is not at the beginning of ctxt->string! */ #define PREV (ctxt->cur[-1]) /** * TODO: * * macro to flag unimplemented blocks */ #define TODO \ xmlGenericError(xmlGenericErrorContext, \ "Unimplemented block at %s:%d\n", \ __FILE__, __LINE__); /************************************************************************ * * * Datatypes and structures * * * ************************************************************************/ /* * Note: the order of the enums below is significant, do not shuffle */ typedef enum { XML_REGEXP_EPSILON = 1, XML_REGEXP_CHARVAL, XML_REGEXP_RANGES, XML_REGEXP_SUBREG, /* used for () sub regexps */ XML_REGEXP_STRING, XML_REGEXP_ANYCHAR, /* . */ XML_REGEXP_ANYSPACE, /* \s */ XML_REGEXP_NOTSPACE, /* \S */ XML_REGEXP_INITNAME, /* \l */ XML_REGEXP_NOTINITNAME, /* \L */ XML_REGEXP_NAMECHAR, /* \c */ XML_REGEXP_NOTNAMECHAR, /* \C */ XML_REGEXP_DECIMAL, /* \d */ XML_REGEXP_NOTDECIMAL, /* \D */ XML_REGEXP_REALCHAR, /* \w */ XML_REGEXP_NOTREALCHAR, /* \W */ XML_REGEXP_LETTER = 100, XML_REGEXP_LETTER_UPPERCASE, XML_REGEXP_LETTER_LOWERCASE, XML_REGEXP_LETTER_TITLECASE, XML_REGEXP_LETTER_MODIFIER, XML_REGEXP_LETTER_OTHERS, XML_REGEXP_MARK, XML_REGEXP_MARK_NONSPACING, XML_REGEXP_MARK_SPACECOMBINING, XML_REGEXP_MARK_ENCLOSING, XML_REGEXP_NUMBER, XML_REGEXP_NUMBER_DECIMAL, XML_REGEXP_NUMBER_LETTER, XML_REGEXP_NUMBER_OTHERS, XML_REGEXP_PUNCT, XML_REGEXP_PUNCT_CONNECTOR, XML_REGEXP_PUNCT_DASH, XML_REGEXP_PUNCT_OPEN, XML_REGEXP_PUNCT_CLOSE, XML_REGEXP_PUNCT_INITQUOTE, XML_REGEXP_PUNCT_FINQUOTE, XML_REGEXP_PUNCT_OTHERS, XML_REGEXP_SEPAR, XML_REGEXP_SEPAR_SPACE, XML_REGEXP_SEPAR_LINE, XML_REGEXP_SEPAR_PARA, XML_REGEXP_SYMBOL, XML_REGEXP_SYMBOL_MATH, XML_REGEXP_SYMBOL_CURRENCY, XML_REGEXP_SYMBOL_MODIFIER, XML_REGEXP_SYMBOL_OTHERS, XML_REGEXP_OTHER, XML_REGEXP_OTHER_CONTROL, XML_REGEXP_OTHER_FORMAT, XML_REGEXP_OTHER_PRIVATE, XML_REGEXP_OTHER_NA, XML_REGEXP_BLOCK_NAME } xmlRegAtomType; typedef enum { XML_REGEXP_QUANT_EPSILON = 1, XML_REGEXP_QUANT_ONCE, XML_REGEXP_QUANT_OPT, XML_REGEXP_QUANT_MULT, XML_REGEXP_QUANT_PLUS, XML_REGEXP_QUANT_ONCEONLY, XML_REGEXP_QUANT_ALL, XML_REGEXP_QUANT_RANGE } xmlRegQuantType; typedef enum { XML_REGEXP_START_STATE = 1, XML_REGEXP_FINAL_STATE, XML_REGEXP_TRANS_STATE, XML_REGEXP_SINK_STATE, XML_REGEXP_UNREACH_STATE } xmlRegStateType; typedef enum { XML_REGEXP_MARK_NORMAL = 0, XML_REGEXP_MARK_START, XML_REGEXP_MARK_VISITED } xmlRegMarkedType; typedef struct _xmlRegRange xmlRegRange; typedef xmlRegRange *xmlRegRangePtr; struct _xmlRegRange { int neg; /* 0 normal, 1 not, 2 exclude */ xmlRegAtomType type; int start; int end; xmlChar *blockName; }; typedef struct _xmlRegAtom xmlRegAtom; typedef xmlRegAtom *xmlRegAtomPtr; typedef struct _xmlAutomataState xmlRegState; typedef xmlRegState *xmlRegStatePtr; struct _xmlRegAtom { int no; xmlRegAtomType type; xmlRegQuantType quant; int min; int max; void *valuep; void *valuep2; int neg; int codepoint; xmlRegStatePtr start; xmlRegStatePtr start0; xmlRegStatePtr stop; int maxRanges; int nbRanges; xmlRegRangePtr *ranges; void *data; }; typedef struct _xmlRegCounter xmlRegCounter; typedef xmlRegCounter *xmlRegCounterPtr; struct _xmlRegCounter { int min; int max; }; typedef struct _xmlRegTrans xmlRegTrans; typedef xmlRegTrans *xmlRegTransPtr; struct _xmlRegTrans { xmlRegAtomPtr atom; int to; int counter; int count; int nd; }; struct _xmlAutomataState { xmlRegStateType type; xmlRegMarkedType mark; xmlRegMarkedType markd; xmlRegMarkedType reached; int no; int maxTrans; int nbTrans; xmlRegTrans *trans; /* knowing states pointing to us can speed things up */ int maxTransTo; int nbTransTo; int *transTo; }; typedef struct _xmlAutomata xmlRegParserCtxt; typedef xmlRegParserCtxt *xmlRegParserCtxtPtr; #define AM_AUTOMATA_RNG 1 struct _xmlAutomata { xmlChar *string; xmlChar *cur; int error; int neg; xmlRegStatePtr start; xmlRegStatePtr end; xmlRegStatePtr state; xmlRegAtomPtr atom; int maxAtoms; int nbAtoms; xmlRegAtomPtr *atoms; int maxStates; int nbStates; xmlRegStatePtr *states; int maxCounters; int nbCounters; xmlRegCounter *counters; int determinist; int negs; int flags; int depth; }; struct _xmlRegexp { xmlChar *string; int nbStates; xmlRegStatePtr *states; int nbAtoms; xmlRegAtomPtr *atoms; int nbCounters; xmlRegCounter *counters; int determinist; int flags; /* * That's the compact form for determinists automatas */ int nbstates; int *compact; void **transdata; int nbstrings; xmlChar **stringMap; }; typedef struct _xmlRegExecRollback xmlRegExecRollback; typedef xmlRegExecRollback *xmlRegExecRollbackPtr; struct _xmlRegExecRollback { xmlRegStatePtr state;/* the current state */ int index; /* the index in the input stack */ int nextbranch; /* the next transition to explore in that state */ int *counts; /* save the automata state if it has some */ }; typedef struct _xmlRegInputToken xmlRegInputToken; typedef xmlRegInputToken *xmlRegInputTokenPtr; struct _xmlRegInputToken { xmlChar *value; void *data; }; struct _xmlRegExecCtxt { int status; /* execution status != 0 indicate an error */ int determinist; /* did we find an indeterministic behaviour */ xmlRegexpPtr comp; /* the compiled regexp */ xmlRegExecCallbacks callback; void *data; xmlRegStatePtr state;/* the current state */ int transno; /* the current transition on that state */ int transcount; /* the number of chars in char counted transitions */ /* * A stack of rollback states */ int maxRollbacks; int nbRollbacks; xmlRegExecRollback *rollbacks; /* * The state of the automata if any */ int *counts; /* * The input stack */ int inputStackMax; int inputStackNr; int index; int *charStack; const xmlChar *inputString; /* when operating on characters */ xmlRegInputTokenPtr inputStack;/* when operating on strings */ /* * error handling */ int errStateNo; /* the error state number */ xmlRegStatePtr errState; /* the error state */ xmlChar *errString; /* the string raising the error */ int *errCounts; /* counters at the error state */ int nbPush; }; #define REGEXP_ALL_COUNTER 0x123456 #define REGEXP_ALL_LAX_COUNTER 0x123457 static void xmlFAParseRegExp(xmlRegParserCtxtPtr ctxt, int top); static void xmlRegFreeState(xmlRegStatePtr state); static void xmlRegFreeAtom(xmlRegAtomPtr atom); static int xmlRegStrEqualWildcard(const xmlChar *expStr, const xmlChar *valStr); static int xmlRegCheckCharacter(xmlRegAtomPtr atom, int codepoint); static int xmlRegCheckCharacterRange(xmlRegAtomType type, int codepoint, int neg, int start, int end, const xmlChar *blockName); void xmlAutomataSetFlags(xmlAutomataPtr am, int flags); /************************************************************************ * * * Regexp memory error handler * * * ************************************************************************/ /** * xmlRegexpErrMemory: * @extra: extra information * * Handle an out of memory condition */ static void xmlRegexpErrMemory(xmlRegParserCtxtPtr ctxt, const char *extra) { const char *regexp = NULL; if (ctxt != NULL) { regexp = (const char *) ctxt->string; ctxt->error = XML_ERR_NO_MEMORY; } __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_REGEXP, XML_ERR_NO_MEMORY, XML_ERR_FATAL, NULL, 0, extra, regexp, NULL, 0, 0, "Memory allocation failed : %s\n", extra); } /** * xmlRegexpErrCompile: * @extra: extra information * * Handle a compilation failure */ static void xmlRegexpErrCompile(xmlRegParserCtxtPtr ctxt, const char *extra) { const char *regexp = NULL; int idx = 0; if (ctxt != NULL) { regexp = (const char *) ctxt->string; idx = ctxt->cur - ctxt->string; ctxt->error = XML_REGEXP_COMPILE_ERROR; } __xmlRaiseError(NULL, NULL, NULL, NULL, NULL, XML_FROM_REGEXP, XML_REGEXP_COMPILE_ERROR, XML_ERR_FATAL, NULL, 0, extra, regexp, NULL, idx, 0, "failed to compile: %s\n", extra); } /************************************************************************ * * * Allocation/Deallocation * * * ************************************************************************/ static int xmlFAComputesDeterminism(xmlRegParserCtxtPtr ctxt); /** * xmlRegCalloc2: * @dim1: size of first dimension * @dim2: size of second dimension * @elemSize: size of element * * Allocate a two-dimensional array and set all elements to zero. * * Returns the new array or NULL in case of error. */ static void* xmlRegCalloc2(size_t dim1, size_t dim2, size_t elemSize) { size_t totalSize; void *ret; /* Check for overflow */ if (dim1 > SIZE_MAX / dim2 / elemSize) return (NULL); totalSize = dim1 * dim2 * elemSize; ret = xmlMalloc(totalSize); if (ret != NULL) memset(ret, 0, totalSize); return (ret); } /** * xmlRegEpxFromParse: * @ctxt: the parser context used to build it * * Allocate a new regexp and fill it with the result from the parser * * Returns the new regexp or NULL in case of error */ static xmlRegexpPtr xmlRegEpxFromParse(xmlRegParserCtxtPtr ctxt) { xmlRegexpPtr ret; ret = (xmlRegexpPtr) xmlMalloc(sizeof(xmlRegexp)); if (ret == NULL) { xmlRegexpErrMemory(ctxt, "compiling regexp"); return(NULL); } memset(ret, 0, sizeof(xmlRegexp)); ret->string = ctxt->string; ret->nbStates = ctxt->nbStates; ret->states = ctxt->states; ret->nbAtoms = ctxt->nbAtoms; ret->atoms = ctxt->atoms; ret->nbCounters = ctxt->nbCounters; ret->counters = ctxt->counters; ret->determinist = ctxt->determinist; ret->flags = ctxt->flags; if (ret->determinist == -1) { xmlRegexpIsDeterminist(ret); } if ((ret->determinist != 0) && (ret->nbCounters == 0) && (ctxt->negs == 0) && (ret->atoms != NULL) && (ret->atoms[0] != NULL) && (ret->atoms[0]->type == XML_REGEXP_STRING)) { int i, j, nbstates = 0, nbatoms = 0; int *stateRemap; int *stringRemap; int *transitions; void **transdata; xmlChar **stringMap; xmlChar *value; /* * Switch to a compact representation * 1/ counting the effective number of states left * 2/ counting the unique number of atoms, and check that * they are all of the string type * 3/ build a table state x atom for the transitions */ stateRemap = xmlMalloc(ret->nbStates * sizeof(int)); if (stateRemap == NULL) { xmlRegexpErrMemory(ctxt, "compiling regexp"); xmlFree(ret); return(NULL); } for (i = 0;i < ret->nbStates;i++) { if (ret->states[i] != NULL) { stateRemap[i] = nbstates; nbstates++; } else { stateRemap[i] = -1; } } #ifdef DEBUG_COMPACTION printf("Final: %d states\n", nbstates); #endif stringMap = xmlMalloc(ret->nbAtoms * sizeof(char *)); if (stringMap == NULL) { xmlRegexpErrMemory(ctxt, "compiling regexp"); xmlFree(stateRemap); xmlFree(ret); return(NULL); } stringRemap = xmlMalloc(ret->nbAtoms * sizeof(int)); if (stringRemap == NULL) { xmlRegexpErrMemory(ctxt, "compiling regexp"); xmlFree(stringMap); xmlFree(stateRemap); xmlFree(ret); return(NULL); } for (i = 0;i < ret->nbAtoms;i++) { if ((ret->atoms[i]->type == XML_REGEXP_STRING) && (ret->atoms[i]->quant == XML_REGEXP_QUANT_ONCE)) { value = ret->atoms[i]->valuep; for (j = 0;j < nbatoms;j++) { if (xmlStrEqual(stringMap[j], value)) { stringRemap[i] = j; break; } } if (j >= nbatoms) { stringRemap[i] = nbatoms; stringMap[nbatoms] = xmlStrdup(value); if (stringMap[nbatoms] == NULL) { for (i = 0;i < nbatoms;i++) xmlFree(stringMap[i]); xmlFree(stringRemap); xmlFree(stringMap); xmlFree(stateRemap); xmlFree(ret); return(NULL); } nbatoms++; } } else { xmlFree(stateRemap); xmlFree(stringRemap); for (i = 0;i < nbatoms;i++) xmlFree(stringMap[i]); xmlFree(stringMap); xmlFree(ret); return(NULL); } } #ifdef DEBUG_COMPACTION printf("Final: %d atoms\n", nbatoms); #endif transitions = (int *) xmlRegCalloc2(nbstates + 1, nbatoms + 1, sizeof(int)); if (transitions == NULL) { xmlFree(stateRemap); xmlFree(stringRemap); for (i = 0;i < nbatoms;i++) xmlFree(stringMap[i]); xmlFree(stringMap); xmlFree(ret); return(NULL); } /* * Allocate the transition table. The first entry for each * state corresponds to the state type. */ transdata = NULL; for (i = 0;i < ret->nbStates;i++) { int stateno, atomno, targetno, prev; xmlRegStatePtr state; xmlRegTransPtr trans; stateno = stateRemap[i]; if (stateno == -1) continue; state = ret->states[i]; transitions[stateno * (nbatoms + 1)] = state->type; for (j = 0;j < state->nbTrans;j++) { trans = &(state->trans[j]); if ((trans->to == -1) || (trans->atom == NULL)) continue; atomno = stringRemap[trans->atom->no]; if ((trans->atom->data != NULL) && (transdata == NULL)) { transdata = (void **) xmlRegCalloc2(nbstates, nbatoms, sizeof(void *)); if (transdata == NULL) { xmlRegexpErrMemory(ctxt, "compiling regexp"); break; } } targetno = stateRemap[trans->to]; /* * if the same atom can generate transitions to 2 different * states then it means the automata is not deterministic and * the compact form can't be used ! */ prev = transitions[stateno * (nbatoms + 1) + atomno + 1]; if (prev != 0) { if (prev != targetno + 1) { ret->determinist = 0; #ifdef DEBUG_COMPACTION printf("Indet: state %d trans %d, atom %d to %d : %d to %d\n", i, j, trans->atom->no, trans->to, atomno, targetno); printf(" previous to is %d\n", prev); #endif if (transdata != NULL) xmlFree(transdata); xmlFree(transitions); xmlFree(stateRemap); xmlFree(stringRemap); for (i = 0;i < nbatoms;i++) xmlFree(stringMap[i]); xmlFree(stringMap); goto not_determ; } } else { #if 0 printf("State %d trans %d: atom %d to %d : %d to %d\n", i, j, trans->atom->no, trans->to, atomno, targetno); #endif transitions[stateno * (nbatoms + 1) + atomno + 1] = targetno + 1; /* to avoid 0 */ if (transdata != NULL) transdata[stateno * nbatoms + atomno] = trans->atom->data; } } } ret->determinist = 1; #ifdef DEBUG_COMPACTION /* * Debug */ for (i = 0;i < nbstates;i++) { for (j = 0;j < nbatoms + 1;j++) { printf("%02d ", transitions[i * (nbatoms + 1) + j]); } printf("\n"); } printf("\n"); #endif /* * Cleanup of the old data */ if (ret->states != NULL) { for (i = 0;i < ret->nbStates;i++) xmlRegFreeState(ret->states[i]); xmlFree(ret->states); } ret->states = NULL; ret->nbStates = 0; if (ret->atoms != NULL) { for (i = 0;i < ret->nbAtoms;i++) xmlRegFreeAtom(ret->atoms[i]); xmlFree(ret->atoms); } ret->atoms = NULL; ret->nbAtoms = 0; ret->compact = transitions; ret->transdata = transdata; ret->stringMap = stringMap; ret->nbstrings = nbatoms; ret->nbstates = nbstates; xmlFree(stateRemap); xmlFree(stringRemap); } not_determ: ctxt->string = NULL; ctxt->nbStates = 0; ctxt->states = NULL; ctxt->nbAtoms = 0; ctxt->atoms = NULL; ctxt->nbCounters = 0; ctxt->counters = NULL; return(ret); } /** * xmlRegNewParserCtxt: * @string: the string to parse * * Allocate a new regexp parser context * * Returns the new context or NULL in case of error */ static xmlRegParserCtxtPtr xmlRegNewParserCtxt(const xmlChar *string) { xmlRegParserCtxtPtr ret; ret = (xmlRegParserCtxtPtr) xmlMalloc(sizeof(xmlRegParserCtxt)); if (ret == NULL) return(NULL); memset(ret, 0, sizeof(xmlRegParserCtxt)); if (string != NULL) ret->string = xmlStrdup(string); ret->cur = ret->string; ret->neg = 0; ret->negs = 0; ret->error = 0; ret->determinist = -1; return(ret); } /** * xmlRegNewRange: * @ctxt: the regexp parser context * @neg: is that negative * @type: the type of range * @start: the start codepoint * @end: the end codepoint * * Allocate a new regexp range * * Returns the new range or NULL in case of error */ static xmlRegRangePtr xmlRegNewRange(xmlRegParserCtxtPtr ctxt, int neg, xmlRegAtomType type, int start, int end) { xmlRegRangePtr ret; ret = (xmlRegRangePtr) xmlMalloc(sizeof(xmlRegRange)); if (ret == NULL) { xmlRegexpErrMemory(ctxt, "allocating range"); return(NULL); } ret->neg = neg; ret->type = type; ret->start = start; ret->end = end; return(ret); } /** * xmlRegFreeRange: * @range: the regexp range * * Free a regexp range */ static void xmlRegFreeRange(xmlRegRangePtr range) { if (range == NULL) return; if (range->blockName != NULL) xmlFree(range->blockName); xmlFree(range); } /** * xmlRegCopyRange: * @range: the regexp range * * Copy a regexp range * * Returns the new copy or NULL in case of error. */ static xmlRegRangePtr xmlRegCopyRange(xmlRegParserCtxtPtr ctxt, xmlRegRangePtr range) { xmlRegRangePtr ret; if (range == NULL) return(NULL); ret = xmlRegNewRange(ctxt, range->neg, range->type, range->start, range->end); if (ret == NULL) return(NULL); if (range->blockName != NULL) { ret->blockName = xmlStrdup(range->blockName); if (ret->blockName == NULL) { xmlRegexpErrMemory(ctxt, "allocating range"); xmlRegFreeRange(ret); return(NULL); } } return(ret); } /** * xmlRegNewAtom: * @ctxt: the regexp parser context * @type: the type of atom * * Allocate a new atom * * Returns the new atom or NULL in case of error */ static xmlRegAtomPtr xmlRegNewAtom(xmlRegParserCtxtPtr ctxt, xmlRegAtomType type) { xmlRegAtomPtr ret; ret = (xmlRegAtomPtr) xmlMalloc(sizeof(xmlRegAtom)); if (ret == NULL) { xmlRegexpErrMemory(ctxt, "allocating atom"); return(NULL); } memset(ret, 0, sizeof(xmlRegAtom)); ret->type = type; ret->quant = XML_REGEXP_QUANT_ONCE; ret->min = 0; ret->max = 0; return(ret); } /** * xmlRegFreeAtom: * @atom: the regexp atom * * Free a regexp atom */ static void xmlRegFreeAtom(xmlRegAtomPtr atom) { int i; if (atom == NULL) return; for (i = 0;i < atom->nbRanges;i++) xmlRegFreeRange(atom->ranges[i]); if (atom->ranges != NULL) xmlFree(atom->ranges); if ((atom->type == XML_REGEXP_STRING) && (atom->valuep != NULL)) xmlFree(atom->valuep); if ((atom->type == XML_REGEXP_STRING) && (atom->valuep2 != NULL)) xmlFree(atom->valuep2); if ((atom->type == XML_REGEXP_BLOCK_NAME) && (atom->valuep != NULL)) xmlFree(atom->valuep); xmlFree(atom); } /** * xmlRegCopyAtom: * @ctxt: the regexp parser context * @atom: the original atom * * Allocate a new regexp range * * Returns the new atom or NULL in case of error */ static xmlRegAtomPtr xmlRegCopyAtom(xmlRegParserCtxtPtr ctxt, xmlRegAtomPtr atom) { xmlRegAtomPtr ret; ret = (xmlRegAtomPtr) xmlMalloc(sizeof(xmlRegAtom)); if (ret == NULL) { xmlRegexpErrMemory(ctxt, "copying atom"); return(NULL); } memset(ret, 0, sizeof(xmlRegAtom)); ret->type = atom->type; ret->quant = atom->quant; ret->min = atom->min; ret->max = atom->max; if (atom->nbRanges > 0) { int i; ret->ranges = (xmlRegRangePtr *) xmlMalloc(sizeof(xmlRegRangePtr) * atom->nbRanges); if (ret->ranges == NULL) { xmlRegexpErrMemory(ctxt, "copying atom"); goto error; } for (i = 0;i < atom->nbRanges;i++) { ret->ranges[i] = xmlRegCopyRange(ctxt, atom->ranges[i]); if (ret->ranges[i] == NULL) goto error; ret->nbRanges = i + 1; } } return(ret); error: xmlRegFreeAtom(ret); return(NULL); } static xmlRegStatePtr xmlRegNewState(xmlRegParserCtxtPtr ctxt) { xmlRegStatePtr ret; ret = (xmlRegStatePtr) xmlMalloc(sizeof(xmlRegState)); if (ret == NULL) { xmlRegexpErrMemory(ctxt, "allocating state"); return(NULL); } memset(ret, 0, sizeof(xmlRegState)); ret->type = XML_REGEXP_TRANS_STATE; ret->mark = XML_REGEXP_MARK_NORMAL; return(ret); } /** * xmlRegFreeState: * @state: the regexp state * * Free a regexp state */ static void xmlRegFreeState(xmlRegStatePtr state) { if (state == NULL) return; if (state->trans != NULL) xmlFree(state->trans); if (state->transTo != NULL) xmlFree(state->transTo); xmlFree(state); } /** * xmlRegFreeParserCtxt: * @ctxt: the regexp parser context * * Free a regexp parser context */ static void xmlRegFreeParserCtxt(xmlRegParserCtxtPtr ctxt) { int i; if (ctxt == NULL) return; if (ctxt->string != NULL) xmlFree(ctxt->string); if (ctxt->states != NULL) { for (i = 0;i < ctxt->nbStates;i++) xmlRegFreeState(ctxt->states[i]); xmlFree(ctxt->states); } if (ctxt->atoms != NULL) { for (i = 0;i < ctxt->nbAtoms;i++) xmlRegFreeAtom(ctxt->atoms[i]); xmlFree(ctxt->atoms); } if (ctxt->counters != NULL) xmlFree(ctxt->counters); xmlFree(ctxt); } /************************************************************************ * * * Display of Data structures * * * ************************************************************************/ static void xmlRegPrintAtomType(FILE *output, xmlRegAtomType type) { switch (type) { case XML_REGEXP_EPSILON: fprintf(output, "epsilon "); break; case XML_REGEXP_CHARVAL: fprintf(output, "charval "); break; case XML_REGEXP_RANGES: fprintf(output, "ranges "); break; case XML_REGEXP_SUBREG: fprintf(output, "subexpr "); break; case XML_REGEXP_STRING: fprintf(output, "string "); break; case XML_REGEXP_ANYCHAR: fprintf(output, "anychar "); break; case XML_REGEXP_ANYSPACE: fprintf(output, "anyspace "); break; case XML_REGEXP_NOTSPACE: fprintf(output, "notspace "); break; case XML_REGEXP_INITNAME: fprintf(output, "initname "); break; case XML_REGEXP_NOTINITNAME: fprintf(output, "notinitname "); break; case XML_REGEXP_NAMECHAR: fprintf(output, "namechar "); break; case XML_REGEXP_NOTNAMECHAR: fprintf(output, "notnamechar "); break; case XML_REGEXP_DECIMAL: fprintf(output, "decimal "); break; case XML_REGEXP_NOTDECIMAL: fprintf(output, "notdecimal "); break; case XML_REGEXP_REALCHAR: fprintf(output, "realchar "); break; case XML_REGEXP_NOTREALCHAR: fprintf(output, "notrealchar "); break; case XML_REGEXP_LETTER: fprintf(output, "LETTER "); break; case XML_REGEXP_LETTER_UPPERCASE: fprintf(output, "LETTER_UPPERCASE "); break; case XML_REGEXP_LETTER_LOWERCASE: fprintf(output, "LETTER_LOWERCASE "); break; case XML_REGEXP_LETTER_TITLECASE: fprintf(output, "LETTER_TITLECASE "); break; case XML_REGEXP_LETTER_MODIFIER: fprintf(output, "LETTER_MODIFIER "); break; case XML_REGEXP_LETTER_OTHERS: fprintf(output, "LETTER_OTHERS "); break; case XML_REGEXP_MARK: fprintf(output, "MARK "); break; case XML_REGEXP_MARK_NONSPACING: fprintf(output, "MARK_NONSPACING "); break; case XML_REGEXP_MARK_SPACECOMBINING: fprintf(output, "MARK_SPACECOMBINING "); break; case XML_REGEXP_MARK_ENCLOSING: fprintf(output, "MARK_ENCLOSING "); break; case XML_REGEXP_NUMBER: fprintf(output, "NUMBER "); break; case XML_REGEXP_NUMBER_DECIMAL: fprintf(output, "NUMBER_DECIMAL "); break; case XML_REGEXP_NUMBER_LETTER: fprintf(output, "NUMBER_LETTER "); break; case XML_REGEXP_NUMBER_OTHERS: fprintf(output, "NUMBER_OTHERS "); break; case XML_REGEXP_PUNCT: fprintf(output, "PUNCT "); break; case XML_REGEXP_PUNCT_CONNECTOR: fprintf(output, "PUNCT_CONNECTOR "); break; case XML_REGEXP_PUNCT_DASH: fprintf(output, "PUNCT_DASH "); break; case XML_REGEXP_PUNCT_OPEN: fprintf(output, "PUNCT_OPEN "); break; case XML_REGEXP_PUNCT_CLOSE: fprintf(output, "PUNCT_CLOSE "); break; case XML_REGEXP_PUNCT_INITQUOTE: fprintf(output, "PUNCT_INITQUOTE "); break; case XML_REGEXP_PUNCT_FINQUOTE: fprintf(output, "PUNCT_FINQUOTE "); break; case XML_REGEXP_PUNCT_OTHERS: fprintf(output, "PUNCT_OTHERS "); break; case XML_REGEXP_SEPAR: fprintf(output, "SEPAR "); break; case XML_REGEXP_SEPAR_SPACE: fprintf(output, "SEPAR_SPACE "); break; case XML_REGEXP_SEPAR_LINE: fprintf(output, "SEPAR_LINE "); break; case XML_REGEXP_SEPAR_PARA: fprintf(output, "SEPAR_PARA "); break; case XML_REGEXP_SYMBOL: fprintf(output, "SYMBOL "); break; case XML_REGEXP_SYMBOL_MATH: fprintf(output, "SYMBOL_MATH "); break; case XML_REGEXP_SYMBOL_CURRENCY: fprintf(output, "SYMBOL_CURRENCY "); break; case XML_REGEXP_SYMBOL_MODIFIER: fprintf(output, "SYMBOL_MODIFIER "); break; case XML_REGEXP_SYMBOL_OTHERS: fprintf(output, "SYMBOL_OTHERS "); break; case XML_REGEXP_OTHER: fprintf(output, "OTHER "); break; case XML_REGEXP_OTHER_CONTROL: fprintf(output, "OTHER_CONTROL "); break; case XML_REGEXP_OTHER_FORMAT: fprintf(output, "OTHER_FORMAT "); break; case XML_REGEXP_OTHER_PRIVATE: fprintf(output, "OTHER_PRIVATE "); break; case XML_REGEXP_OTHER_NA: fprintf(output, "OTHER_NA "); break; case XML_REGEXP_BLOCK_NAME: fprintf(output, "BLOCK "); break; } } static void xmlRegPrintQuantType(FILE *output, xmlRegQuantType type) { switch (type) { case XML_REGEXP_QUANT_EPSILON: fprintf(output, "epsilon "); break; case XML_REGEXP_QUANT_ONCE: fprintf(output, "once "); break; case XML_REGEXP_QUANT_OPT: fprintf(output, "? "); break; case XML_REGEXP_QUANT_MULT: fprintf(output, "* "); break; case XML_REGEXP_QUANT_PLUS: fprintf(output, "+ "); break; case XML_REGEXP_QUANT_RANGE: fprintf(output, "range "); break; case XML_REGEXP_QUANT_ONCEONLY: fprintf(output, "onceonly "); break; case XML_REGEXP_QUANT_ALL: fprintf(output, "all "); break; } } static void xmlRegPrintRange(FILE *output, xmlRegRangePtr range) { fprintf(output, " range: "); if (range->neg) fprintf(output, "negative "); xmlRegPrintAtomType(output, range->type); fprintf(output, "%c - %c\n", range->start, range->end); } static void xmlRegPrintAtom(FILE *output, xmlRegAtomPtr atom) { fprintf(output, " atom: "); if (atom == NULL) { fprintf(output, "NULL\n"); return; } if (atom->neg) fprintf(output, "not "); xmlRegPrintAtomType(output, atom->type); xmlRegPrintQuantType(output, atom->quant); if (atom->quant == XML_REGEXP_QUANT_RANGE) fprintf(output, "%d-%d ", atom->min, atom->max); if (atom->type == XML_REGEXP_STRING) fprintf(output, "'%s' ", (char *) atom->valuep); if (atom->type == XML_REGEXP_CHARVAL) fprintf(output, "char %c\n", atom->codepoint); else if (atom->type == XML_REGEXP_RANGES) { int i; fprintf(output, "%d entries\n", atom->nbRanges); for (i = 0; i < atom->nbRanges;i++) xmlRegPrintRange(output, atom->ranges[i]); } else if (atom->type == XML_REGEXP_SUBREG) { fprintf(output, "start %d end %d\n", atom->start->no, atom->stop->no); } else { fprintf(output, "\n"); } } static void xmlRegPrintTrans(FILE *output, xmlRegTransPtr trans) { fprintf(output, " trans: "); if (trans == NULL) { fprintf(output, "NULL\n"); return; } if (trans->to < 0) { fprintf(output, "removed\n"); return; } if (trans->nd != 0) { if (trans->nd == 2) fprintf(output, "last not determinist, "); else fprintf(output, "not determinist, "); } if (trans->counter >= 0) { fprintf(output, "counted %d, ", trans->counter); } if (trans->count == REGEXP_ALL_COUNTER) { fprintf(output, "all transition, "); } else if (trans->count >= 0) { fprintf(output, "count based %d, ", trans->count); } if (trans->atom == NULL) { fprintf(output, "epsilon to %d\n", trans->to); return; } if (trans->atom->type == XML_REGEXP_CHARVAL) fprintf(output, "char %c ", trans->atom->codepoint); fprintf(output, "atom %d, to %d\n", trans->atom->no, trans->to); } static void xmlRegPrintState(FILE *output, xmlRegStatePtr state) { int i; fprintf(output, " state: "); if (state == NULL) { fprintf(output, "NULL\n"); return; } if (state->type == XML_REGEXP_START_STATE) fprintf(output, "START "); if (state->type == XML_REGEXP_FINAL_STATE) fprintf(output, "FINAL "); fprintf(output, "%d, %d transitions:\n", state->no, state->nbTrans); for (i = 0;i < state->nbTrans; i++) { xmlRegPrintTrans(output, &(state->trans[i])); } } #ifdef DEBUG_REGEXP_GRAPH static void xmlRegPrintCtxt(FILE *output, xmlRegParserCtxtPtr ctxt) { int i; fprintf(output, " ctxt: "); if (ctxt == NULL) { fprintf(output, "NULL\n"); return; } fprintf(output, "'%s' ", ctxt->string); if (ctxt->error) fprintf(output, "error "); if (ctxt->neg) fprintf(output, "neg "); fprintf(output, "\n"); fprintf(output, "%d atoms:\n", ctxt->nbAtoms); for (i = 0;i < ctxt->nbAtoms; i++) { fprintf(output, " %02d ", i); xmlRegPrintAtom(output, ctxt->atoms[i]); } if (ctxt->atom != NULL) { fprintf(output, "current atom:\n"); xmlRegPrintAtom(output, ctxt->atom); } fprintf(output, "%d states:", ctxt->nbStates); if (ctxt->start != NULL) fprintf(output, " start: %d", ctxt->start->no); if (ctxt->end != NULL) fprintf(output, " end: %d", ctxt->end->no); fprintf(output, "\n"); for (i = 0;i < ctxt->nbStates; i++) { xmlRegPrintState(output, ctxt->states[i]); } fprintf(output, "%d counters:\n", ctxt->nbCounters); for (i = 0;i < ctxt->nbCounters; i++) { fprintf(output, " %d: min %d max %d\n", i, ctxt->counters[i].min, ctxt->counters[i].max); } } #endif /************************************************************************ * * * Finite Automata structures manipulations * * * ************************************************************************/ static void xmlRegAtomAddRange(xmlRegParserCtxtPtr ctxt, xmlRegAtomPtr atom, int neg, xmlRegAtomType type, int start, int end, xmlChar *blockName) { xmlRegRangePtr range; if (atom == NULL) { ERROR("add range: atom is NULL"); return; } if (atom->type != XML_REGEXP_RANGES) { ERROR("add range: atom is not ranges"); return; } if (atom->maxRanges == 0) { atom->maxRanges = 4; atom->ranges = (xmlRegRangePtr *) xmlMalloc(atom->maxRanges * sizeof(xmlRegRangePtr)); if (atom->ranges == NULL) { xmlRegexpErrMemory(ctxt, "adding ranges"); atom->maxRanges = 0; return; } } else if (atom->nbRanges >= atom->maxRanges) { xmlRegRangePtr *tmp; atom->maxRanges *= 2; tmp = (xmlRegRangePtr *) xmlRealloc(atom->ranges, atom->maxRanges * sizeof(xmlRegRangePtr)); if (tmp == NULL) { xmlRegexpErrMemory(ctxt, "adding ranges"); atom->maxRanges /= 2; return; } atom->ranges = tmp; } range = xmlRegNewRange(ctxt, neg, type, start, end); if (range == NULL) return; range->blockName = blockName; atom->ranges[atom->nbRanges++] = range; } static int xmlRegGetCounter(xmlRegParserCtxtPtr ctxt) { if (ctxt->maxCounters == 0) { ctxt->maxCounters = 4; ctxt->counters = (xmlRegCounter *) xmlMalloc(ctxt->maxCounters * sizeof(xmlRegCounter)); if (ctxt->counters == NULL) { xmlRegexpErrMemory(ctxt, "allocating counter"); ctxt->maxCounters = 0; return(-1); } } else if (ctxt->nbCounters >= ctxt->maxCounters) { xmlRegCounter *tmp; ctxt->maxCounters *= 2; tmp = (xmlRegCounter *) xmlRealloc(ctxt->counters, ctxt->maxCounters * sizeof(xmlRegCounter)); if (tmp == NULL) { xmlRegexpErrMemory(ctxt, "allocating counter"); ctxt->maxCounters /= 2; return(-1); } ctxt->counters = tmp; } ctxt->counters[ctxt->nbCounters].min = -1; ctxt->counters[ctxt->nbCounters].max = -1; return(ctxt->nbCounters++); } static int xmlRegAtomPush(xmlRegParserCtxtPtr ctxt, xmlRegAtomPtr atom) { if (atom == NULL) { ERROR("atom push: atom is NULL"); return(-1); } if (ctxt->maxAtoms == 0) { ctxt->maxAtoms = 4; ctxt->atoms = (xmlRegAtomPtr *) xmlMalloc(ctxt->maxAtoms * sizeof(xmlRegAtomPtr)); if (ctxt->atoms == NULL) { xmlRegexpErrMemory(ctxt, "pushing atom"); ctxt->maxAtoms = 0; return(-1); } } else if (ctxt->nbAtoms >= ctxt->maxAtoms) { xmlRegAtomPtr *tmp; ctxt->maxAtoms *= 2; tmp = (xmlRegAtomPtr *) xmlRealloc(ctxt->atoms, ctxt->maxAtoms * sizeof(xmlRegAtomPtr)); if (tmp == NULL) { xmlRegexpErrMemory(ctxt, "allocating counter"); ctxt->maxAtoms /= 2; return(-1); } ctxt->atoms = tmp; } atom->no = ctxt->nbAtoms; ctxt->atoms[ctxt->nbAtoms++] = atom; return(0); } static void xmlRegStateAddTransTo(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr target, int from) { if (target->maxTransTo == 0) { target->maxTransTo = 8; target->transTo = (int *) xmlMalloc(target->maxTransTo * sizeof(int)); if (target->transTo == NULL) { xmlRegexpErrMemory(ctxt, "adding transition"); target->maxTransTo = 0; return; } } else if (target->nbTransTo >= target->maxTransTo) { int *tmp; target->maxTransTo *= 2; tmp = (int *) xmlRealloc(target->transTo, target->maxTransTo * sizeof(int)); if (tmp == NULL) { xmlRegexpErrMemory(ctxt, "adding transition"); target->maxTransTo /= 2; return; } target->transTo = tmp; } target->transTo[target->nbTransTo] = from; target->nbTransTo++; } static void xmlRegStateAddTrans(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr state, xmlRegAtomPtr atom, xmlRegStatePtr target, int counter, int count) { int nrtrans; if (state == NULL) { ERROR("add state: state is NULL"); return; } if (target == NULL) { ERROR("add state: target is NULL"); return; } /* * Other routines follow the philosophy 'When in doubt, add a transition' * so we check here whether such a transition is already present and, if * so, silently ignore this request. */ for (nrtrans = state->nbTrans - 1; nrtrans >= 0; nrtrans--) { xmlRegTransPtr trans = &(state->trans[nrtrans]); if ((trans->atom == atom) && (trans->to == target->no) && (trans->counter == counter) && (trans->count == count)) { #ifdef DEBUG_REGEXP_GRAPH printf("Ignoring duplicate transition from %d to %d\n", state->no, target->no); #endif return; } } if (state->maxTrans == 0) { state->maxTrans = 8; state->trans = (xmlRegTrans *) xmlMalloc(state->maxTrans * sizeof(xmlRegTrans)); if (state->trans == NULL) { xmlRegexpErrMemory(ctxt, "adding transition"); state->maxTrans = 0; return; } } else if (state->nbTrans >= state->maxTrans) { xmlRegTrans *tmp; state->maxTrans *= 2; tmp = (xmlRegTrans *) xmlRealloc(state->trans, state->maxTrans * sizeof(xmlRegTrans)); if (tmp == NULL) { xmlRegexpErrMemory(ctxt, "adding transition"); state->maxTrans /= 2; return; } state->trans = tmp; } #ifdef DEBUG_REGEXP_GRAPH printf("Add trans from %d to %d ", state->no, target->no); if (count == REGEXP_ALL_COUNTER) printf("all transition\n"); else if (count >= 0) printf("count based %d\n", count); else if (counter >= 0) printf("counted %d\n", counter); else if (atom == NULL) printf("epsilon transition\n"); else if (atom != NULL) xmlRegPrintAtom(stdout, atom); #endif state->trans[state->nbTrans].atom = atom; state->trans[state->nbTrans].to = target->no; state->trans[state->nbTrans].counter = counter; state->trans[state->nbTrans].count = count; state->trans[state->nbTrans].nd = 0; state->nbTrans++; xmlRegStateAddTransTo(ctxt, target, state->no); } static int xmlRegStatePush(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr state) { if (state == NULL) return(-1); if (ctxt->maxStates == 0) { ctxt->maxStates = 4; ctxt->states = (xmlRegStatePtr *) xmlMalloc(ctxt->maxStates * sizeof(xmlRegStatePtr)); if (ctxt->states == NULL) { xmlRegexpErrMemory(ctxt, "adding state"); ctxt->maxStates = 0; return(-1); } } else if (ctxt->nbStates >= ctxt->maxStates) { xmlRegStatePtr *tmp; ctxt->maxStates *= 2; tmp = (xmlRegStatePtr *) xmlRealloc(ctxt->states, ctxt->maxStates * sizeof(xmlRegStatePtr)); if (tmp == NULL) { xmlRegexpErrMemory(ctxt, "adding state"); ctxt->maxStates /= 2; return(-1); } ctxt->states = tmp; } state->no = ctxt->nbStates; ctxt->states[ctxt->nbStates++] = state; return(0); } /** * xmlFAGenerateAllTransition: * @ctxt: a regexp parser context * @from: the from state * @to: the target state or NULL for building a new one * @lax: * */ static void xmlFAGenerateAllTransition(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr from, xmlRegStatePtr to, int lax) { if (to == NULL) { to = xmlRegNewState(ctxt); xmlRegStatePush(ctxt, to); ctxt->state = to; } if (lax) xmlRegStateAddTrans(ctxt, from, NULL, to, -1, REGEXP_ALL_LAX_COUNTER); else xmlRegStateAddTrans(ctxt, from, NULL, to, -1, REGEXP_ALL_COUNTER); } /** * xmlFAGenerateEpsilonTransition: * @ctxt: a regexp parser context * @from: the from state * @to: the target state or NULL for building a new one * */ static void xmlFAGenerateEpsilonTransition(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr from, xmlRegStatePtr to) { if (to == NULL) { to = xmlRegNewState(ctxt); xmlRegStatePush(ctxt, to); ctxt->state = to; } xmlRegStateAddTrans(ctxt, from, NULL, to, -1, -1); } /** * xmlFAGenerateCountedEpsilonTransition: * @ctxt: a regexp parser context * @from: the from state * @to: the target state or NULL for building a new one * counter: the counter for that transition * */ static void xmlFAGenerateCountedEpsilonTransition(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr from, xmlRegStatePtr to, int counter) { if (to == NULL) { to = xmlRegNewState(ctxt); xmlRegStatePush(ctxt, to); ctxt->state = to; } xmlRegStateAddTrans(ctxt, from, NULL, to, counter, -1); } /** * xmlFAGenerateCountedTransition: * @ctxt: a regexp parser context * @from: the from state * @to: the target state or NULL for building a new one * counter: the counter for that transition * */ static void xmlFAGenerateCountedTransition(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr from, xmlRegStatePtr to, int counter) { if (to == NULL) { to = xmlRegNewState(ctxt); xmlRegStatePush(ctxt, to); ctxt->state = to; } xmlRegStateAddTrans(ctxt, from, NULL, to, -1, counter); } /** * xmlFAGenerateTransitions: * @ctxt: a regexp parser context * @from: the from state * @to: the target state or NULL for building a new one * @atom: the atom generating the transition * * Returns 0 if success and -1 in case of error. */ static int xmlFAGenerateTransitions(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr from, xmlRegStatePtr to, xmlRegAtomPtr atom) { xmlRegStatePtr end; int nullable = 0; if (atom == NULL) { ERROR("generate transition: atom == NULL"); return(-1); } if (atom->type == XML_REGEXP_SUBREG) { /* * this is a subexpression handling one should not need to * create a new node except for XML_REGEXP_QUANT_RANGE. */ if (xmlRegAtomPush(ctxt, atom) < 0) { return(-1); } if ((to != NULL) && (atom->stop != to) && (atom->quant != XML_REGEXP_QUANT_RANGE)) { /* * Generate an epsilon transition to link to the target */ xmlFAGenerateEpsilonTransition(ctxt, atom->stop, to); #ifdef DV } else if ((to == NULL) && (atom->quant != XML_REGEXP_QUANT_RANGE) && (atom->quant != XML_REGEXP_QUANT_ONCE)) { to = xmlRegNewState(ctxt); xmlRegStatePush(ctxt, to); ctxt->state = to; xmlFAGenerateEpsilonTransition(ctxt, atom->stop, to); #endif } switch (atom->quant) { case XML_REGEXP_QUANT_OPT: atom->quant = XML_REGEXP_QUANT_ONCE; /* * transition done to the state after end of atom. * 1. set transition from atom start to new state * 2. set transition from atom end to this state. */ if (to == NULL) { xmlFAGenerateEpsilonTransition(ctxt, atom->start, 0); xmlFAGenerateEpsilonTransition(ctxt, atom->stop, ctxt->state); } else { xmlFAGenerateEpsilonTransition(ctxt, atom->start, to); } break; case XML_REGEXP_QUANT_MULT: atom->quant = XML_REGEXP_QUANT_ONCE; xmlFAGenerateEpsilonTransition(ctxt, atom->start, atom->stop); xmlFAGenerateEpsilonTransition(ctxt, atom->stop, atom->start); break; case XML_REGEXP_QUANT_PLUS: atom->quant = XML_REGEXP_QUANT_ONCE; xmlFAGenerateEpsilonTransition(ctxt, atom->stop, atom->start); break; case XML_REGEXP_QUANT_RANGE: { int counter; xmlRegStatePtr inter, newstate; /* * create the final state now if needed */ if (to != NULL) { newstate = to; } else { newstate = xmlRegNewState(ctxt); xmlRegStatePush(ctxt, newstate); } /* * The principle here is to use counted transition * to avoid explosion in the number of states in the * graph. This is clearly more complex but should not * be exploitable at runtime. */ if ((atom->min == 0) && (atom->start0 == NULL)) { xmlRegAtomPtr copy; /* * duplicate a transition based on atom to count next * occurrences after 1. We cannot loop to atom->start * directly because we need an epsilon transition to * newstate. */ /* ???? For some reason it seems we never reach that case, I suppose this got optimized out before when building the automata */ copy = xmlRegCopyAtom(ctxt, atom); if (copy == NULL) return(-1); copy->quant = XML_REGEXP_QUANT_ONCE; copy->min = 0; copy->max = 0; if (xmlFAGenerateTransitions(ctxt, atom->start, NULL, copy) < 0) return(-1); inter = ctxt->state; counter = xmlRegGetCounter(ctxt); ctxt->counters[counter].min = atom->min - 1; ctxt->counters[counter].max = atom->max - 1; /* count the number of times we see it again */ xmlFAGenerateCountedEpsilonTransition(ctxt, inter, atom->stop, counter); /* allow a way out based on the count */ xmlFAGenerateCountedTransition(ctxt, inter, newstate, counter); /* and also allow a direct exit for 0 */ xmlFAGenerateEpsilonTransition(ctxt, atom->start, newstate); } else { /* * either we need the atom at least once or there * is an atom->start0 allowing to easily plug the * epsilon transition. */ counter = xmlRegGetCounter(ctxt); ctxt->counters[counter].min = atom->min - 1; ctxt->counters[counter].max = atom->max - 1; /* count the number of times we see it again */ xmlFAGenerateCountedEpsilonTransition(ctxt, atom->stop, atom->start, counter); /* allow a way out based on the count */ xmlFAGenerateCountedTransition(ctxt, atom->stop, newstate, counter); /* and if needed allow a direct exit for 0 */ if (atom->min == 0) xmlFAGenerateEpsilonTransition(ctxt, atom->start0, newstate); } atom->min = 0; atom->max = 0; atom->quant = XML_REGEXP_QUANT_ONCE; ctxt->state = newstate; } default: break; } return(0); } if ((atom->min == 0) && (atom->max == 0) && (atom->quant == XML_REGEXP_QUANT_RANGE)) { /* * we can discard the atom and generate an epsilon transition instead */ if (to == NULL) { to = xmlRegNewState(ctxt); if (to != NULL) xmlRegStatePush(ctxt, to); else { return(-1); } } xmlFAGenerateEpsilonTransition(ctxt, from, to); ctxt->state = to; xmlRegFreeAtom(atom); return(0); } if (to == NULL) { to = xmlRegNewState(ctxt); if (to != NULL) xmlRegStatePush(ctxt, to); else { return(-1); } } end = to; if ((atom->quant == XML_REGEXP_QUANT_MULT) || (atom->quant == XML_REGEXP_QUANT_PLUS)) { /* * Do not pollute the target state by adding transitions from * it as it is likely to be the shared target of multiple branches. * So isolate with an epsilon transition. */ xmlRegStatePtr tmp; tmp = xmlRegNewState(ctxt); if (tmp != NULL) xmlRegStatePush(ctxt, tmp); else { return(-1); } xmlFAGenerateEpsilonTransition(ctxt, tmp, to); to = tmp; } if (xmlRegAtomPush(ctxt, atom) < 0) { return(-1); } if ((atom->quant == XML_REGEXP_QUANT_RANGE) && (atom->min == 0) && (atom->max > 0)) { nullable = 1; atom->min = 1; if (atom->max == 1) atom->quant = XML_REGEXP_QUANT_OPT; } xmlRegStateAddTrans(ctxt, from, atom, to, -1, -1); ctxt->state = end; switch (atom->quant) { case XML_REGEXP_QUANT_OPT: atom->quant = XML_REGEXP_QUANT_ONCE; xmlFAGenerateEpsilonTransition(ctxt, from, to); break; case XML_REGEXP_QUANT_MULT: atom->quant = XML_REGEXP_QUANT_ONCE; xmlFAGenerateEpsilonTransition(ctxt, from, to); xmlRegStateAddTrans(ctxt, to, atom, to, -1, -1); break; case XML_REGEXP_QUANT_PLUS: atom->quant = XML_REGEXP_QUANT_ONCE; xmlRegStateAddTrans(ctxt, to, atom, to, -1, -1); break; case XML_REGEXP_QUANT_RANGE: if (nullable) xmlFAGenerateEpsilonTransition(ctxt, from, to); break; default: break; } return(0); } /** * xmlFAReduceEpsilonTransitions: * @ctxt: a regexp parser context * @fromnr: the from state * @tonr: the to state * @counter: should that transition be associated to a counted * */ static void xmlFAReduceEpsilonTransitions(xmlRegParserCtxtPtr ctxt, int fromnr, int tonr, int counter) { int transnr; xmlRegStatePtr from; xmlRegStatePtr to; #ifdef DEBUG_REGEXP_GRAPH printf("xmlFAReduceEpsilonTransitions(%d, %d)\n", fromnr, tonr); #endif from = ctxt->states[fromnr]; if (from == NULL) return; to = ctxt->states[tonr]; if (to == NULL) return; if ((to->mark == XML_REGEXP_MARK_START) || (to->mark == XML_REGEXP_MARK_VISITED)) return; to->mark = XML_REGEXP_MARK_VISITED; if (to->type == XML_REGEXP_FINAL_STATE) { #ifdef DEBUG_REGEXP_GRAPH printf("State %d is final, so %d becomes final\n", tonr, fromnr); #endif from->type = XML_REGEXP_FINAL_STATE; } for (transnr = 0;transnr < to->nbTrans;transnr++) { if (to->trans[transnr].to < 0) continue; if (to->trans[transnr].atom == NULL) { /* * Don't remove counted transitions * Don't loop either */ if (to->trans[transnr].to != fromnr) { if (to->trans[transnr].count >= 0) { int newto = to->trans[transnr].to; xmlRegStateAddTrans(ctxt, from, NULL, ctxt->states[newto], -1, to->trans[transnr].count); } else { #ifdef DEBUG_REGEXP_GRAPH printf("Found epsilon trans %d from %d to %d\n", transnr, tonr, to->trans[transnr].to); #endif if (to->trans[transnr].counter >= 0) { xmlFAReduceEpsilonTransitions(ctxt, fromnr, to->trans[transnr].to, to->trans[transnr].counter); } else { xmlFAReduceEpsilonTransitions(ctxt, fromnr, to->trans[transnr].to, counter); } } } } else { int newto = to->trans[transnr].to; if (to->trans[transnr].counter >= 0) { xmlRegStateAddTrans(ctxt, from, to->trans[transnr].atom, ctxt->states[newto], to->trans[transnr].counter, -1); } else { xmlRegStateAddTrans(ctxt, from, to->trans[transnr].atom, ctxt->states[newto], counter, -1); } } } to->mark = XML_REGEXP_MARK_NORMAL; } /** * xmlFAEliminateSimpleEpsilonTransitions: * @ctxt: a regexp parser context * * Eliminating general epsilon transitions can get costly in the general * algorithm due to the large amount of generated new transitions and * associated comparisons. However for simple epsilon transition used just * to separate building blocks when generating the automata this can be * reduced to state elimination: * - if there exists an epsilon from X to Y * - if there is no other transition from X * then X and Y are semantically equivalent and X can be eliminated * If X is the start state then make Y the start state, else replace the * target of all transitions to X by transitions to Y. * * If X is a final state, skip it. * Otherwise it would be necessary to manipulate counters for this case when * eliminating state 2: * State 1 has a transition with an atom to state 2. * State 2 is final and has an epsilon transition to state 1. */ static void xmlFAEliminateSimpleEpsilonTransitions(xmlRegParserCtxtPtr ctxt) { int statenr, i, j, newto; xmlRegStatePtr state, tmp; for (statenr = 0;statenr < ctxt->nbStates;statenr++) { state = ctxt->states[statenr]; if (state == NULL) continue; if (state->nbTrans != 1) continue; if (state->type == XML_REGEXP_UNREACH_STATE || state->type == XML_REGEXP_FINAL_STATE) continue; /* is the only transition out a basic transition */ if ((state->trans[0].atom == NULL) && (state->trans[0].to >= 0) && (state->trans[0].to != statenr) && (state->trans[0].counter < 0) && (state->trans[0].count < 0)) { newto = state->trans[0].to; if (state->type == XML_REGEXP_START_STATE) { #ifdef DEBUG_REGEXP_GRAPH printf("Found simple epsilon trans from start %d to %d\n", statenr, newto); #endif } else { #ifdef DEBUG_REGEXP_GRAPH printf("Found simple epsilon trans from %d to %d\n", statenr, newto); #endif for (i = 0;i < state->nbTransTo;i++) { tmp = ctxt->states[state->transTo[i]]; for (j = 0;j < tmp->nbTrans;j++) { if (tmp->trans[j].to == statenr) { #ifdef DEBUG_REGEXP_GRAPH printf("Changed transition %d on %d to go to %d\n", j, tmp->no, newto); #endif tmp->trans[j].to = -1; xmlRegStateAddTrans(ctxt, tmp, tmp->trans[j].atom, ctxt->states[newto], tmp->trans[j].counter, tmp->trans[j].count); } } } if (state->type == XML_REGEXP_FINAL_STATE) ctxt->states[newto]->type = XML_REGEXP_FINAL_STATE; /* eliminate the transition completely */ state->nbTrans = 0; state->type = XML_REGEXP_UNREACH_STATE; } } } } /** * xmlFAEliminateEpsilonTransitions: * @ctxt: a regexp parser context * */ static void xmlFAEliminateEpsilonTransitions(xmlRegParserCtxtPtr ctxt) { int statenr, transnr; xmlRegStatePtr state; int has_epsilon; if (ctxt->states == NULL) return; /* * Eliminate simple epsilon transition and the associated unreachable * states. */ xmlFAEliminateSimpleEpsilonTransitions(ctxt); for (statenr = 0;statenr < ctxt->nbStates;statenr++) { state = ctxt->states[statenr]; if ((state != NULL) && (state->type == XML_REGEXP_UNREACH_STATE)) { #ifdef DEBUG_REGEXP_GRAPH printf("Removed unreachable state %d\n", statenr); #endif xmlRegFreeState(state); ctxt->states[statenr] = NULL; } } has_epsilon = 0; /* * Build the completed transitions bypassing the epsilons * Use a marking algorithm to avoid loops * Mark sink states too. * Process from the latest states backward to the start when * there is long cascading epsilon chains this minimize the * recursions and transition compares when adding the new ones */ for (statenr = ctxt->nbStates - 1;statenr >= 0;statenr--) { state = ctxt->states[statenr]; if (state == NULL) continue; if ((state->nbTrans == 0) && (state->type != XML_REGEXP_FINAL_STATE)) { state->type = XML_REGEXP_SINK_STATE; } for (transnr = 0;transnr < state->nbTrans;transnr++) { if ((state->trans[transnr].atom == NULL) && (state->trans[transnr].to >= 0)) { if (state->trans[transnr].to == statenr) { state->trans[transnr].to = -1; #ifdef DEBUG_REGEXP_GRAPH printf("Removed loopback epsilon trans %d on %d\n", transnr, statenr); #endif } else if (state->trans[transnr].count < 0) { int newto = state->trans[transnr].to; #ifdef DEBUG_REGEXP_GRAPH printf("Found epsilon trans %d from %d to %d\n", transnr, statenr, newto); #endif has_epsilon = 1; state->trans[transnr].to = -2; state->mark = XML_REGEXP_MARK_START; xmlFAReduceEpsilonTransitions(ctxt, statenr, newto, state->trans[transnr].counter); state->mark = XML_REGEXP_MARK_NORMAL; #ifdef DEBUG_REGEXP_GRAPH } else { printf("Found counted transition %d on %d\n", transnr, statenr); #endif } } } } /* * Eliminate the epsilon transitions */ if (has_epsilon) { for (statenr = 0;statenr < ctxt->nbStates;statenr++) { state = ctxt->states[statenr]; if (state == NULL) continue; for (transnr = 0;transnr < state->nbTrans;transnr++) { xmlRegTransPtr trans = &(state->trans[transnr]); if ((trans->atom == NULL) && (trans->count < 0) && (trans->to >= 0)) { trans->to = -1; } } } } /* * Use this pass to detect unreachable states too */ for (statenr = 0;statenr < ctxt->nbStates;statenr++) { state = ctxt->states[statenr]; if (state != NULL) state->reached = XML_REGEXP_MARK_NORMAL; } state = ctxt->states[0]; if (state != NULL) state->reached = XML_REGEXP_MARK_START; while (state != NULL) { xmlRegStatePtr target = NULL; state->reached = XML_REGEXP_MARK_VISITED; /* * Mark all states reachable from the current reachable state */ for (transnr = 0;transnr < state->nbTrans;transnr++) { if ((state->trans[transnr].to >= 0) && ((state->trans[transnr].atom != NULL) || (state->trans[transnr].count >= 0))) { int newto = state->trans[transnr].to; if (ctxt->states[newto] == NULL) continue; if (ctxt->states[newto]->reached == XML_REGEXP_MARK_NORMAL) { ctxt->states[newto]->reached = XML_REGEXP_MARK_START; target = ctxt->states[newto]; } } } /* * find the next accessible state not explored */ if (target == NULL) { for (statenr = 1;statenr < ctxt->nbStates;statenr++) { state = ctxt->states[statenr]; if ((state != NULL) && (state->reached == XML_REGEXP_MARK_START)) { target = state; break; } } } state = target; } for (statenr = 0;statenr < ctxt->nbStates;statenr++) { state = ctxt->states[statenr]; if ((state != NULL) && (state->reached == XML_REGEXP_MARK_NORMAL)) { #ifdef DEBUG_REGEXP_GRAPH printf("Removed unreachable state %d\n", statenr); #endif xmlRegFreeState(state); ctxt->states[statenr] = NULL; } } } static int xmlFACompareRanges(xmlRegRangePtr range1, xmlRegRangePtr range2) { int ret = 0; if ((range1->type == XML_REGEXP_RANGES) || (range2->type == XML_REGEXP_RANGES) || (range2->type == XML_REGEXP_SUBREG) || (range1->type == XML_REGEXP_SUBREG) || (range1->type == XML_REGEXP_STRING) || (range2->type == XML_REGEXP_STRING)) return(-1); /* put them in order */ if (range1->type > range2->type) { xmlRegRangePtr tmp; tmp = range1; range1 = range2; range2 = tmp; } if ((range1->type == XML_REGEXP_ANYCHAR) || (range2->type == XML_REGEXP_ANYCHAR)) { ret = 1; } else if ((range1->type == XML_REGEXP_EPSILON) || (range2->type == XML_REGEXP_EPSILON)) { return(0); } else if (range1->type == range2->type) { if (range1->type != XML_REGEXP_CHARVAL) ret = 1; else if ((range1->end < range2->start) || (range2->end < range1->start)) ret = 0; else ret = 1; } else if (range1->type == XML_REGEXP_CHARVAL) { int codepoint; int neg = 0; /* * just check all codepoints in the range for acceptance, * this is usually way cheaper since done only once at * compilation than testing over and over at runtime or * pushing too many states when evaluating. */ if (((range1->neg == 0) && (range2->neg != 0)) || ((range1->neg != 0) && (range2->neg == 0))) neg = 1; for (codepoint = range1->start;codepoint <= range1->end ;codepoint++) { ret = xmlRegCheckCharacterRange(range2->type, codepoint, 0, range2->start, range2->end, range2->blockName); if (ret < 0) return(-1); if (((neg == 1) && (ret == 0)) || ((neg == 0) && (ret == 1))) return(1); } return(0); } else if ((range1->type == XML_REGEXP_BLOCK_NAME) || (range2->type == XML_REGEXP_BLOCK_NAME)) { if (range1->type == range2->type) { ret = xmlStrEqual(range1->blockName, range2->blockName); } else { /* * comparing a block range with anything else is way * too costly, and maintaining the table is like too much * memory too, so let's force the automata to save state * here. */ return(1); } } else if ((range1->type < XML_REGEXP_LETTER) || (range2->type < XML_REGEXP_LETTER)) { if ((range1->type == XML_REGEXP_ANYSPACE) && (range2->type == XML_REGEXP_NOTSPACE)) ret = 0; else if ((range1->type == XML_REGEXP_INITNAME) && (range2->type == XML_REGEXP_NOTINITNAME)) ret = 0; else if ((range1->type == XML_REGEXP_NAMECHAR) && (range2->type == XML_REGEXP_NOTNAMECHAR)) ret = 0; else if ((range1->type == XML_REGEXP_DECIMAL) && (range2->type == XML_REGEXP_NOTDECIMAL)) ret = 0; else if ((range1->type == XML_REGEXP_REALCHAR) && (range2->type == XML_REGEXP_NOTREALCHAR)) ret = 0; else { /* same thing to limit complexity */ return(1); } } else { ret = 0; /* range1->type < range2->type here */ switch (range1->type) { case XML_REGEXP_LETTER: /* all disjoint except in the subgroups */ if ((range2->type == XML_REGEXP_LETTER_UPPERCASE) || (range2->type == XML_REGEXP_LETTER_LOWERCASE) || (range2->type == XML_REGEXP_LETTER_TITLECASE) || (range2->type == XML_REGEXP_LETTER_MODIFIER) || (range2->type == XML_REGEXP_LETTER_OTHERS)) ret = 1; break; case XML_REGEXP_MARK: if ((range2->type == XML_REGEXP_MARK_NONSPACING) || (range2->type == XML_REGEXP_MARK_SPACECOMBINING) || (range2->type == XML_REGEXP_MARK_ENCLOSING)) ret = 1; break; case XML_REGEXP_NUMBER: if ((range2->type == XML_REGEXP_NUMBER_DECIMAL) || (range2->type == XML_REGEXP_NUMBER_LETTER) || (range2->type == XML_REGEXP_NUMBER_OTHERS)) ret = 1; break; case XML_REGEXP_PUNCT: if ((range2->type == XML_REGEXP_PUNCT_CONNECTOR) || (range2->type == XML_REGEXP_PUNCT_DASH) || (range2->type == XML_REGEXP_PUNCT_OPEN) || (range2->type == XML_REGEXP_PUNCT_CLOSE) || (range2->type == XML_REGEXP_PUNCT_INITQUOTE) || (range2->type == XML_REGEXP_PUNCT_FINQUOTE) || (range2->type == XML_REGEXP_PUNCT_OTHERS)) ret = 1; break; case XML_REGEXP_SEPAR: if ((range2->type == XML_REGEXP_SEPAR_SPACE) || (range2->type == XML_REGEXP_SEPAR_LINE) || (range2->type == XML_REGEXP_SEPAR_PARA)) ret = 1; break; case XML_REGEXP_SYMBOL: if ((range2->type == XML_REGEXP_SYMBOL_MATH) || (range2->type == XML_REGEXP_SYMBOL_CURRENCY) || (range2->type == XML_REGEXP_SYMBOL_MODIFIER) || (range2->type == XML_REGEXP_SYMBOL_OTHERS)) ret = 1; break; case XML_REGEXP_OTHER: if ((range2->type == XML_REGEXP_OTHER_CONTROL) || (range2->type == XML_REGEXP_OTHER_FORMAT) || (range2->type == XML_REGEXP_OTHER_PRIVATE)) ret = 1; break; default: if ((range2->type >= XML_REGEXP_LETTER) && (range2->type < XML_REGEXP_BLOCK_NAME)) ret = 0; else { /* safety net ! */ return(1); } } } if (((range1->neg == 0) && (range2->neg != 0)) || ((range1->neg != 0) && (range2->neg == 0))) ret = !ret; return(ret); } /** * xmlFACompareAtomTypes: * @type1: an atom type * @type2: an atom type * * Compares two atoms type to check whether they intersect in some ways, * this is used by xmlFACompareAtoms only * * Returns 1 if they may intersect and 0 otherwise */ static int xmlFACompareAtomTypes(xmlRegAtomType type1, xmlRegAtomType type2) { if ((type1 == XML_REGEXP_EPSILON) || (type1 == XML_REGEXP_CHARVAL) || (type1 == XML_REGEXP_RANGES) || (type1 == XML_REGEXP_SUBREG) || (type1 == XML_REGEXP_STRING) || (type1 == XML_REGEXP_ANYCHAR)) return(1); if ((type2 == XML_REGEXP_EPSILON) || (type2 == XML_REGEXP_CHARVAL) || (type2 == XML_REGEXP_RANGES) || (type2 == XML_REGEXP_SUBREG) || (type2 == XML_REGEXP_STRING) || (type2 == XML_REGEXP_ANYCHAR)) return(1); if (type1 == type2) return(1); /* simplify subsequent compares by making sure type1 < type2 */ if (type1 > type2) { xmlRegAtomType tmp = type1; type1 = type2; type2 = tmp; } switch (type1) { case XML_REGEXP_ANYSPACE: /* \s */ /* can't be a letter, number, mark, punctuation, symbol */ if ((type2 == XML_REGEXP_NOTSPACE) || ((type2 >= XML_REGEXP_LETTER) && (type2 <= XML_REGEXP_LETTER_OTHERS)) || ((type2 >= XML_REGEXP_NUMBER) && (type2 <= XML_REGEXP_NUMBER_OTHERS)) || ((type2 >= XML_REGEXP_MARK) && (type2 <= XML_REGEXP_MARK_ENCLOSING)) || ((type2 >= XML_REGEXP_PUNCT) && (type2 <= XML_REGEXP_PUNCT_OTHERS)) || ((type2 >= XML_REGEXP_SYMBOL) && (type2 <= XML_REGEXP_SYMBOL_OTHERS)) ) return(0); break; case XML_REGEXP_NOTSPACE: /* \S */ break; case XML_REGEXP_INITNAME: /* \l */ /* can't be a number, mark, separator, punctuation, symbol or other */ if ((type2 == XML_REGEXP_NOTINITNAME) || ((type2 >= XML_REGEXP_NUMBER) && (type2 <= XML_REGEXP_NUMBER_OTHERS)) || ((type2 >= XML_REGEXP_MARK) && (type2 <= XML_REGEXP_MARK_ENCLOSING)) || ((type2 >= XML_REGEXP_SEPAR) && (type2 <= XML_REGEXP_SEPAR_PARA)) || ((type2 >= XML_REGEXP_PUNCT) && (type2 <= XML_REGEXP_PUNCT_OTHERS)) || ((type2 >= XML_REGEXP_SYMBOL) && (type2 <= XML_REGEXP_SYMBOL_OTHERS)) || ((type2 >= XML_REGEXP_OTHER) && (type2 <= XML_REGEXP_OTHER_NA)) ) return(0); break; case XML_REGEXP_NOTINITNAME: /* \L */ break; case XML_REGEXP_NAMECHAR: /* \c */ /* can't be a mark, separator, punctuation, symbol or other */ if ((type2 == XML_REGEXP_NOTNAMECHAR) || ((type2 >= XML_REGEXP_MARK) && (type2 <= XML_REGEXP_MARK_ENCLOSING)) || ((type2 >= XML_REGEXP_PUNCT) && (type2 <= XML_REGEXP_PUNCT_OTHERS)) || ((type2 >= XML_REGEXP_SEPAR) && (type2 <= XML_REGEXP_SEPAR_PARA)) || ((type2 >= XML_REGEXP_SYMBOL) && (type2 <= XML_REGEXP_SYMBOL_OTHERS)) || ((type2 >= XML_REGEXP_OTHER) && (type2 <= XML_REGEXP_OTHER_NA)) ) return(0); break; case XML_REGEXP_NOTNAMECHAR: /* \C */ break; case XML_REGEXP_DECIMAL: /* \d */ /* can't be a letter, mark, separator, punctuation, symbol or other */ if ((type2 == XML_REGEXP_NOTDECIMAL) || (type2 == XML_REGEXP_REALCHAR) || ((type2 >= XML_REGEXP_LETTER) && (type2 <= XML_REGEXP_LETTER_OTHERS)) || ((type2 >= XML_REGEXP_MARK) && (type2 <= XML_REGEXP_MARK_ENCLOSING)) || ((type2 >= XML_REGEXP_PUNCT) && (type2 <= XML_REGEXP_PUNCT_OTHERS)) || ((type2 >= XML_REGEXP_SEPAR) && (type2 <= XML_REGEXP_SEPAR_PARA)) || ((type2 >= XML_REGEXP_SYMBOL) && (type2 <= XML_REGEXP_SYMBOL_OTHERS)) || ((type2 >= XML_REGEXP_OTHER) && (type2 <= XML_REGEXP_OTHER_NA)) )return(0); break; case XML_REGEXP_NOTDECIMAL: /* \D */ break; case XML_REGEXP_REALCHAR: /* \w */ /* can't be a mark, separator, punctuation, symbol or other */ if ((type2 == XML_REGEXP_NOTDECIMAL) || ((type2 >= XML_REGEXP_MARK) && (type2 <= XML_REGEXP_MARK_ENCLOSING)) || ((type2 >= XML_REGEXP_PUNCT) && (type2 <= XML_REGEXP_PUNCT_OTHERS)) || ((type2 >= XML_REGEXP_SEPAR) && (type2 <= XML_REGEXP_SEPAR_PARA)) || ((type2 >= XML_REGEXP_SYMBOL) && (type2 <= XML_REGEXP_SYMBOL_OTHERS)) || ((type2 >= XML_REGEXP_OTHER) && (type2 <= XML_REGEXP_OTHER_NA)) )return(0); break; case XML_REGEXP_NOTREALCHAR: /* \W */ break; /* * at that point we know both type 1 and type2 are from * character categories are ordered and are different, * it becomes simple because this is a partition */ case XML_REGEXP_LETTER: if (type2 <= XML_REGEXP_LETTER_OTHERS) return(1); return(0); case XML_REGEXP_LETTER_UPPERCASE: case XML_REGEXP_LETTER_LOWERCASE: case XML_REGEXP_LETTER_TITLECASE: case XML_REGEXP_LETTER_MODIFIER: case XML_REGEXP_LETTER_OTHERS: return(0); case XML_REGEXP_MARK: if (type2 <= XML_REGEXP_MARK_ENCLOSING) return(1); return(0); case XML_REGEXP_MARK_NONSPACING: case XML_REGEXP_MARK_SPACECOMBINING: case XML_REGEXP_MARK_ENCLOSING: return(0); case XML_REGEXP_NUMBER: if (type2 <= XML_REGEXP_NUMBER_OTHERS) return(1); return(0); case XML_REGEXP_NUMBER_DECIMAL: case XML_REGEXP_NUMBER_LETTER: case XML_REGEXP_NUMBER_OTHERS: return(0); case XML_REGEXP_PUNCT: if (type2 <= XML_REGEXP_PUNCT_OTHERS) return(1); return(0); case XML_REGEXP_PUNCT_CONNECTOR: case XML_REGEXP_PUNCT_DASH: case XML_REGEXP_PUNCT_OPEN: case XML_REGEXP_PUNCT_CLOSE: case XML_REGEXP_PUNCT_INITQUOTE: case XML_REGEXP_PUNCT_FINQUOTE: case XML_REGEXP_PUNCT_OTHERS: return(0); case XML_REGEXP_SEPAR: if (type2 <= XML_REGEXP_SEPAR_PARA) return(1); return(0); case XML_REGEXP_SEPAR_SPACE: case XML_REGEXP_SEPAR_LINE: case XML_REGEXP_SEPAR_PARA: return(0); case XML_REGEXP_SYMBOL: if (type2 <= XML_REGEXP_SYMBOL_OTHERS) return(1); return(0); case XML_REGEXP_SYMBOL_MATH: case XML_REGEXP_SYMBOL_CURRENCY: case XML_REGEXP_SYMBOL_MODIFIER: case XML_REGEXP_SYMBOL_OTHERS: return(0); case XML_REGEXP_OTHER: if (type2 <= XML_REGEXP_OTHER_NA) return(1); return(0); case XML_REGEXP_OTHER_CONTROL: case XML_REGEXP_OTHER_FORMAT: case XML_REGEXP_OTHER_PRIVATE: case XML_REGEXP_OTHER_NA: return(0); default: break; } return(1); } /** * xmlFAEqualAtoms: * @atom1: an atom * @atom2: an atom * @deep: if not set only compare string pointers * * Compares two atoms to check whether they are the same exactly * this is used to remove equivalent transitions * * Returns 1 if same and 0 otherwise */ static int xmlFAEqualAtoms(xmlRegAtomPtr atom1, xmlRegAtomPtr atom2, int deep) { int ret = 0; if (atom1 == atom2) return(1); if ((atom1 == NULL) || (atom2 == NULL)) return(0); if (atom1->type != atom2->type) return(0); switch (atom1->type) { case XML_REGEXP_EPSILON: ret = 0; break; case XML_REGEXP_STRING: if (!deep) ret = (atom1->valuep == atom2->valuep); else ret = xmlStrEqual((xmlChar *)atom1->valuep, (xmlChar *)atom2->valuep); break; case XML_REGEXP_CHARVAL: ret = (atom1->codepoint == atom2->codepoint); break; case XML_REGEXP_RANGES: /* too hard to do in the general case */ ret = 0; default: break; } return(ret); } /** * xmlFACompareAtoms: * @atom1: an atom * @atom2: an atom * @deep: if not set only compare string pointers * * Compares two atoms to check whether they intersect in some ways, * this is used by xmlFAComputesDeterminism and xmlFARecurseDeterminism only * * Returns 1 if yes and 0 otherwise */ static int xmlFACompareAtoms(xmlRegAtomPtr atom1, xmlRegAtomPtr atom2, int deep) { int ret = 1; if (atom1 == atom2) return(1); if ((atom1 == NULL) || (atom2 == NULL)) return(0); if ((atom1->type == XML_REGEXP_ANYCHAR) || (atom2->type == XML_REGEXP_ANYCHAR)) return(1); if (atom1->type > atom2->type) { xmlRegAtomPtr tmp; tmp = atom1; atom1 = atom2; atom2 = tmp; } if (atom1->type != atom2->type) { ret = xmlFACompareAtomTypes(atom1->type, atom2->type); /* if they can't intersect at the type level break now */ if (ret == 0) return(0); } switch (atom1->type) { case XML_REGEXP_STRING: if (!deep) ret = (atom1->valuep != atom2->valuep); else { xmlChar *val1 = (xmlChar *)atom1->valuep; xmlChar *val2 = (xmlChar *)atom2->valuep; int compound1 = (xmlStrchr(val1, '|') != NULL); int compound2 = (xmlStrchr(val2, '|') != NULL); /* Ignore negative match flag for ##other namespaces */ if (compound1 != compound2) return(0); ret = xmlRegStrEqualWildcard(val1, val2); } break; case XML_REGEXP_EPSILON: goto not_determinist; case XML_REGEXP_CHARVAL: if (atom2->type == XML_REGEXP_CHARVAL) { ret = (atom1->codepoint == atom2->codepoint); } else { ret = xmlRegCheckCharacter(atom2, atom1->codepoint); if (ret < 0) ret = 1; } break; case XML_REGEXP_RANGES: if (atom2->type == XML_REGEXP_RANGES) { int i, j, res; xmlRegRangePtr r1, r2; /* * need to check that none of the ranges eventually matches */ for (i = 0;i < atom1->nbRanges;i++) { for (j = 0;j < atom2->nbRanges;j++) { r1 = atom1->ranges[i]; r2 = atom2->ranges[j]; res = xmlFACompareRanges(r1, r2); if (res == 1) { ret = 1; goto done; } } } ret = 0; } break; default: goto not_determinist; } done: if (atom1->neg != atom2->neg) { ret = !ret; } if (ret == 0) return(0); not_determinist: return(1); } /** * xmlFARecurseDeterminism: * @ctxt: a regexp parser context * * Check whether the associated regexp is determinist, * should be called after xmlFAEliminateEpsilonTransitions() * */ static int xmlFARecurseDeterminism(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr state, int to, xmlRegAtomPtr atom) { int ret = 1; int res; int transnr, nbTrans; xmlRegTransPtr t1; int deep = 1; if (state == NULL) return(ret); if (state->markd == XML_REGEXP_MARK_VISITED) return(ret); if (ctxt->flags & AM_AUTOMATA_RNG) deep = 0; /* * don't recurse on transitions potentially added in the course of * the elimination. */ nbTrans = state->nbTrans; for (transnr = 0;transnr < nbTrans;transnr++) { t1 = &(state->trans[transnr]); /* * check transitions conflicting with the one looked at */ if (t1->atom == NULL) { if (t1->to < 0) continue; state->markd = XML_REGEXP_MARK_VISITED; res = xmlFARecurseDeterminism(ctxt, ctxt->states[t1->to], to, atom); if (res == 0) { ret = 0; /* t1->nd = 1; */ } continue; } if (t1->to != to) continue; if (xmlFACompareAtoms(t1->atom, atom, deep)) { ret = 0; /* mark the transition as non-deterministic */ t1->nd = 1; } } return(ret); } /** * xmlFAFinishRecurseDeterminism: * @ctxt: a regexp parser context * * Reset flags after checking determinism. */ static void xmlFAFinishRecurseDeterminism(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr state) { int transnr, nbTrans; if (state == NULL) return; if (state->markd != XML_REGEXP_MARK_VISITED) return; state->markd = 0; nbTrans = state->nbTrans; for (transnr = 0; transnr < nbTrans; transnr++) { xmlRegTransPtr t1 = &state->trans[transnr]; if ((t1->atom == NULL) && (t1->to >= 0)) xmlFAFinishRecurseDeterminism(ctxt, ctxt->states[t1->to]); } } /** * xmlFAComputesDeterminism: * @ctxt: a regexp parser context * * Check whether the associated regexp is determinist, * should be called after xmlFAEliminateEpsilonTransitions() * */ static int xmlFAComputesDeterminism(xmlRegParserCtxtPtr ctxt) { int statenr, transnr; xmlRegStatePtr state; xmlRegTransPtr t1, t2, last; int i; int ret = 1; int deep = 1; #ifdef DEBUG_REGEXP_GRAPH printf("xmlFAComputesDeterminism\n"); xmlRegPrintCtxt(stdout, ctxt); #endif if (ctxt->determinist != -1) return(ctxt->determinist); if (ctxt->flags & AM_AUTOMATA_RNG) deep = 0; /* * First cleanup the automata removing cancelled transitions */ for (statenr = 0;statenr < ctxt->nbStates;statenr++) { state = ctxt->states[statenr]; if (state == NULL) continue; if (state->nbTrans < 2) continue; for (transnr = 0;transnr < state->nbTrans;transnr++) { t1 = &(state->trans[transnr]); /* * Determinism checks in case of counted or all transitions * will have to be handled separately */ if (t1->atom == NULL) { /* t1->nd = 1; */ continue; } if (t1->to == -1) /* eliminated */ continue; for (i = 0;i < transnr;i++) { t2 = &(state->trans[i]); if (t2->to == -1) /* eliminated */ continue; if (t2->atom != NULL) { if (t1->to == t2->to) { /* * Here we use deep because we want to keep the * transitions which indicate a conflict */ if (xmlFAEqualAtoms(t1->atom, t2->atom, deep) && (t1->counter == t2->counter) && (t1->count == t2->count)) t2->to = -1; /* eliminated */ } } } } } /* * Check for all states that there aren't 2 transitions * with the same atom and a different target. */ for (statenr = 0;statenr < ctxt->nbStates;statenr++) { state = ctxt->states[statenr]; if (state == NULL) continue; if (state->nbTrans < 2) continue; last = NULL; for (transnr = 0;transnr < state->nbTrans;transnr++) { t1 = &(state->trans[transnr]); /* * Determinism checks in case of counted or all transitions * will have to be handled separately */ if (t1->atom == NULL) { continue; } if (t1->to == -1) /* eliminated */ continue; for (i = 0;i < transnr;i++) { t2 = &(state->trans[i]); if (t2->to == -1) /* eliminated */ continue; if (t2->atom != NULL) { /* * But here we don't use deep because we want to * find transitions which indicate a conflict */ if (xmlFACompareAtoms(t1->atom, t2->atom, 1)) { ret = 0; /* mark the transitions as non-deterministic ones */ t1->nd = 1; t2->nd = 1; last = t1; } } else if (t1->to != -1) { /* * do the closure in case of remaining specific * epsilon transitions like choices or all */ ret = xmlFARecurseDeterminism(ctxt, ctxt->states[t1->to], t2->to, t2->atom); xmlFAFinishRecurseDeterminism(ctxt, ctxt->states[t1->to]); /* don't shortcut the computation so all non deterministic transition get marked down if (ret == 0) return(0); */ if (ret == 0) { t1->nd = 1; /* t2->nd = 1; */ last = t1; } } } /* don't shortcut the computation so all non deterministic transition get marked down if (ret == 0) break; */ } /* * mark specifically the last non-deterministic transition * from a state since there is no need to set-up rollback * from it */ if (last != NULL) { last->nd = 2; } /* don't shortcut the computation so all non deterministic transition get marked down if (ret == 0) break; */ } ctxt->determinist = ret; return(ret); } /************************************************************************ * * * Routines to check input against transition atoms * * * ************************************************************************/ static int xmlRegCheckCharacterRange(xmlRegAtomType type, int codepoint, int neg, int start, int end, const xmlChar *blockName) { int ret = 0; switch (type) { case XML_REGEXP_STRING: case XML_REGEXP_SUBREG: case XML_REGEXP_RANGES: case XML_REGEXP_EPSILON: return(-1); case XML_REGEXP_ANYCHAR: ret = ((codepoint != '\n') && (codepoint != '\r')); break; case XML_REGEXP_CHARVAL: ret = ((codepoint >= start) && (codepoint <= end)); break; case XML_REGEXP_NOTSPACE: neg = !neg; /* Falls through. */ case XML_REGEXP_ANYSPACE: ret = ((codepoint == '\n') || (codepoint == '\r') || (codepoint == '\t') || (codepoint == ' ')); break; case XML_REGEXP_NOTINITNAME: neg = !neg; /* Falls through. */ case XML_REGEXP_INITNAME: ret = (IS_LETTER(codepoint) || (codepoint == '_') || (codepoint == ':')); break; case XML_REGEXP_NOTNAMECHAR: neg = !neg; /* Falls through. */ case XML_REGEXP_NAMECHAR: ret = (IS_LETTER(codepoint) || IS_DIGIT(codepoint) || (codepoint == '.') || (codepoint == '-') || (codepoint == '_') || (codepoint == ':') || IS_COMBINING(codepoint) || IS_EXTENDER(codepoint)); break; case XML_REGEXP_NOTDECIMAL: neg = !neg; /* Falls through. */ case XML_REGEXP_DECIMAL: ret = xmlUCSIsCatNd(codepoint); break; case XML_REGEXP_REALCHAR: neg = !neg; /* Falls through. */ case XML_REGEXP_NOTREALCHAR: ret = xmlUCSIsCatP(codepoint); if (ret == 0) ret = xmlUCSIsCatZ(codepoint); if (ret == 0) ret = xmlUCSIsCatC(codepoint); break; case XML_REGEXP_LETTER: ret = xmlUCSIsCatL(codepoint); break; case XML_REGEXP_LETTER_UPPERCASE: ret = xmlUCSIsCatLu(codepoint); break; case XML_REGEXP_LETTER_LOWERCASE: ret = xmlUCSIsCatLl(codepoint); break; case XML_REGEXP_LETTER_TITLECASE: ret = xmlUCSIsCatLt(codepoint); break; case XML_REGEXP_LETTER_MODIFIER: ret = xmlUCSIsCatLm(codepoint); break; case XML_REGEXP_LETTER_OTHERS: ret = xmlUCSIsCatLo(codepoint); break; case XML_REGEXP_MARK: ret = xmlUCSIsCatM(codepoint); break; case XML_REGEXP_MARK_NONSPACING: ret = xmlUCSIsCatMn(codepoint); break; case XML_REGEXP_MARK_SPACECOMBINING: ret = xmlUCSIsCatMc(codepoint); break; case XML_REGEXP_MARK_ENCLOSING: ret = xmlUCSIsCatMe(codepoint); break; case XML_REGEXP_NUMBER: ret = xmlUCSIsCatN(codepoint); break; case XML_REGEXP_NUMBER_DECIMAL: ret = xmlUCSIsCatNd(codepoint); break; case XML_REGEXP_NUMBER_LETTER: ret = xmlUCSIsCatNl(codepoint); break; case XML_REGEXP_NUMBER_OTHERS: ret = xmlUCSIsCatNo(codepoint); break; case XML_REGEXP_PUNCT: ret = xmlUCSIsCatP(codepoint); break; case XML_REGEXP_PUNCT_CONNECTOR: ret = xmlUCSIsCatPc(codepoint); break; case XML_REGEXP_PUNCT_DASH: ret = xmlUCSIsCatPd(codepoint); break; case XML_REGEXP_PUNCT_OPEN: ret = xmlUCSIsCatPs(codepoint); break; case XML_REGEXP_PUNCT_CLOSE: ret = xmlUCSIsCatPe(codepoint); break; case XML_REGEXP_PUNCT_INITQUOTE: ret = xmlUCSIsCatPi(codepoint); break; case XML_REGEXP_PUNCT_FINQUOTE: ret = xmlUCSIsCatPf(codepoint); break; case XML_REGEXP_PUNCT_OTHERS: ret = xmlUCSIsCatPo(codepoint); break; case XML_REGEXP_SEPAR: ret = xmlUCSIsCatZ(codepoint); break; case XML_REGEXP_SEPAR_SPACE: ret = xmlUCSIsCatZs(codepoint); break; case XML_REGEXP_SEPAR_LINE: ret = xmlUCSIsCatZl(codepoint); break; case XML_REGEXP_SEPAR_PARA: ret = xmlUCSIsCatZp(codepoint); break; case XML_REGEXP_SYMBOL: ret = xmlUCSIsCatS(codepoint); break; case XML_REGEXP_SYMBOL_MATH: ret = xmlUCSIsCatSm(codepoint); break; case XML_REGEXP_SYMBOL_CURRENCY: ret = xmlUCSIsCatSc(codepoint); break; case XML_REGEXP_SYMBOL_MODIFIER: ret = xmlUCSIsCatSk(codepoint); break; case XML_REGEXP_SYMBOL_OTHERS: ret = xmlUCSIsCatSo(codepoint); break; case XML_REGEXP_OTHER: ret = xmlUCSIsCatC(codepoint); break; case XML_REGEXP_OTHER_CONTROL: ret = xmlUCSIsCatCc(codepoint); break; case XML_REGEXP_OTHER_FORMAT: ret = xmlUCSIsCatCf(codepoint); break; case XML_REGEXP_OTHER_PRIVATE: ret = xmlUCSIsCatCo(codepoint); break; case XML_REGEXP_OTHER_NA: /* ret = xmlUCSIsCatCn(codepoint); */ /* Seems it doesn't exist anymore in recent Unicode releases */ ret = 0; break; case XML_REGEXP_BLOCK_NAME: ret = xmlUCSIsBlock(codepoint, (const char *) blockName); break; } if (neg) return(!ret); return(ret); } static int xmlRegCheckCharacter(xmlRegAtomPtr atom, int codepoint) { int i, ret = 0; xmlRegRangePtr range; if ((atom == NULL) || (!IS_CHAR(codepoint))) return(-1); switch (atom->type) { case XML_REGEXP_SUBREG: case XML_REGEXP_EPSILON: return(-1); case XML_REGEXP_CHARVAL: return(codepoint == atom->codepoint); case XML_REGEXP_RANGES: { int accept = 0; for (i = 0;i < atom->nbRanges;i++) { range = atom->ranges[i]; if (range->neg == 2) { ret = xmlRegCheckCharacterRange(range->type, codepoint, 0, range->start, range->end, range->blockName); if (ret != 0) return(0); /* excluded char */ } else if (range->neg) { ret = xmlRegCheckCharacterRange(range->type, codepoint, 0, range->start, range->end, range->blockName); if (ret == 0) accept = 1; else return(0); } else { ret = xmlRegCheckCharacterRange(range->type, codepoint, 0, range->start, range->end, range->blockName); if (ret != 0) accept = 1; /* might still be excluded */ } } return(accept); } case XML_REGEXP_STRING: printf("TODO: XML_REGEXP_STRING\n"); return(-1); case XML_REGEXP_ANYCHAR: case XML_REGEXP_ANYSPACE: case XML_REGEXP_NOTSPACE: case XML_REGEXP_INITNAME: case XML_REGEXP_NOTINITNAME: case XML_REGEXP_NAMECHAR: case XML_REGEXP_NOTNAMECHAR: case XML_REGEXP_DECIMAL: case XML_REGEXP_NOTDECIMAL: case XML_REGEXP_REALCHAR: case XML_REGEXP_NOTREALCHAR: case XML_REGEXP_LETTER: case XML_REGEXP_LETTER_UPPERCASE: case XML_REGEXP_LETTER_LOWERCASE: case XML_REGEXP_LETTER_TITLECASE: case XML_REGEXP_LETTER_MODIFIER: case XML_REGEXP_LETTER_OTHERS: case XML_REGEXP_MARK: case XML_REGEXP_MARK_NONSPACING: case XML_REGEXP_MARK_SPACECOMBINING: case XML_REGEXP_MARK_ENCLOSING: case XML_REGEXP_NUMBER: case XML_REGEXP_NUMBER_DECIMAL: case XML_REGEXP_NUMBER_LETTER: case XML_REGEXP_NUMBER_OTHERS: case XML_REGEXP_PUNCT: case XML_REGEXP_PUNCT_CONNECTOR: case XML_REGEXP_PUNCT_DASH: case XML_REGEXP_PUNCT_OPEN: case XML_REGEXP_PUNCT_CLOSE: case XML_REGEXP_PUNCT_INITQUOTE: case XML_REGEXP_PUNCT_FINQUOTE: case XML_REGEXP_PUNCT_OTHERS: case XML_REGEXP_SEPAR: case XML_REGEXP_SEPAR_SPACE: case XML_REGEXP_SEPAR_LINE: case XML_REGEXP_SEPAR_PARA: case XML_REGEXP_SYMBOL: case XML_REGEXP_SYMBOL_MATH: case XML_REGEXP_SYMBOL_CURRENCY: case XML_REGEXP_SYMBOL_MODIFIER: case XML_REGEXP_SYMBOL_OTHERS: case XML_REGEXP_OTHER: case XML_REGEXP_OTHER_CONTROL: case XML_REGEXP_OTHER_FORMAT: case XML_REGEXP_OTHER_PRIVATE: case XML_REGEXP_OTHER_NA: case XML_REGEXP_BLOCK_NAME: ret = xmlRegCheckCharacterRange(atom->type, codepoint, 0, 0, 0, (const xmlChar *)atom->valuep); if (atom->neg) ret = !ret; break; } return(ret); } /************************************************************************ * * * Saving and restoring state of an execution context * * * ************************************************************************/ #ifdef DEBUG_REGEXP_EXEC static void xmlFARegDebugExec(xmlRegExecCtxtPtr exec) { printf("state: %d:%d:idx %d", exec->state->no, exec->transno, exec->index); if (exec->inputStack != NULL) { int i; printf(": "); for (i = 0;(i < 3) && (i < exec->inputStackNr);i++) printf("%s ", (const char *) exec->inputStack[exec->inputStackNr - (i + 1)].value); } else { printf(": %s", &(exec->inputString[exec->index])); } printf("\n"); } #endif static void xmlFARegExecSave(xmlRegExecCtxtPtr exec) { #ifdef DEBUG_REGEXP_EXEC printf("saving "); exec->transno++; xmlFARegDebugExec(exec); exec->transno--; #endif #ifdef MAX_PUSH if (exec->nbPush > MAX_PUSH) { return; } exec->nbPush++; #endif if (exec->maxRollbacks == 0) { exec->maxRollbacks = 4; exec->rollbacks = (xmlRegExecRollback *) xmlMalloc(exec->maxRollbacks * sizeof(xmlRegExecRollback)); if (exec->rollbacks == NULL) { xmlRegexpErrMemory(NULL, "saving regexp"); exec->maxRollbacks = 0; return; } memset(exec->rollbacks, 0, exec->maxRollbacks * sizeof(xmlRegExecRollback)); } else if (exec->nbRollbacks >= exec->maxRollbacks) { xmlRegExecRollback *tmp; int len = exec->maxRollbacks; exec->maxRollbacks *= 2; tmp = (xmlRegExecRollback *) xmlRealloc(exec->rollbacks, exec->maxRollbacks * sizeof(xmlRegExecRollback)); if (tmp == NULL) { xmlRegexpErrMemory(NULL, "saving regexp"); exec->maxRollbacks /= 2; return; } exec->rollbacks = tmp; tmp = &exec->rollbacks[len]; memset(tmp, 0, (exec->maxRollbacks - len) * sizeof(xmlRegExecRollback)); } exec->rollbacks[exec->nbRollbacks].state = exec->state; exec->rollbacks[exec->nbRollbacks].index = exec->index; exec->rollbacks[exec->nbRollbacks].nextbranch = exec->transno + 1; if (exec->comp->nbCounters > 0) { if (exec->rollbacks[exec->nbRollbacks].counts == NULL) { exec->rollbacks[exec->nbRollbacks].counts = (int *) xmlMalloc(exec->comp->nbCounters * sizeof(int)); if (exec->rollbacks[exec->nbRollbacks].counts == NULL) { xmlRegexpErrMemory(NULL, "saving regexp"); exec->status = -5; return; } } memcpy(exec->rollbacks[exec->nbRollbacks].counts, exec->counts, exec->comp->nbCounters * sizeof(int)); } exec->nbRollbacks++; } static void xmlFARegExecRollBack(xmlRegExecCtxtPtr exec) { if (exec->nbRollbacks <= 0) { exec->status = -1; #ifdef DEBUG_REGEXP_EXEC printf("rollback failed on empty stack\n"); #endif return; } exec->nbRollbacks--; exec->state = exec->rollbacks[exec->nbRollbacks].state; exec->index = exec->rollbacks[exec->nbRollbacks].index; exec->transno = exec->rollbacks[exec->nbRollbacks].nextbranch; if (exec->comp->nbCounters > 0) { if (exec->rollbacks[exec->nbRollbacks].counts == NULL) { fprintf(stderr, "exec save: allocation failed"); exec->status = -6; return; } if (exec->counts) { memcpy(exec->counts, exec->rollbacks[exec->nbRollbacks].counts, exec->comp->nbCounters * sizeof(int)); } } #ifdef DEBUG_REGEXP_EXEC printf("restored "); xmlFARegDebugExec(exec); #endif } /************************************************************************ * * * Verifier, running an input against a compiled regexp * * * ************************************************************************/ static int xmlFARegExec(xmlRegexpPtr comp, const xmlChar *content) { xmlRegExecCtxt execval; xmlRegExecCtxtPtr exec = &execval; int ret, codepoint = 0, len, deter; exec->inputString = content; exec->index = 0; exec->nbPush = 0; exec->determinist = 1; exec->maxRollbacks = 0; exec->nbRollbacks = 0; exec->rollbacks = NULL; exec->status = 0; exec->comp = comp; exec->state = comp->states[0]; exec->transno = 0; exec->transcount = 0; exec->inputStack = NULL; exec->inputStackMax = 0; if (comp->nbCounters > 0) { exec->counts = (int *) xmlMalloc(comp->nbCounters * sizeof(int)); if (exec->counts == NULL) { xmlRegexpErrMemory(NULL, "running regexp"); return(-1); } memset(exec->counts, 0, comp->nbCounters * sizeof(int)); } else exec->counts = NULL; while ((exec->status == 0) && (exec->state != NULL) && ((exec->inputString[exec->index] != 0) || ((exec->state != NULL) && (exec->state->type != XML_REGEXP_FINAL_STATE)))) { xmlRegTransPtr trans; xmlRegAtomPtr atom; /* * If end of input on non-terminal state, rollback, however we may * still have epsilon like transition for counted transitions * on counters, in that case don't break too early. Additionally, * if we are working on a range like "AB{0,2}", where B is not present, * we don't want to break. */ len = 1; if ((exec->inputString[exec->index] == 0) && (exec->counts == NULL)) { /* * if there is a transition, we must check if * atom allows minOccurs of 0 */ if (exec->transno < exec->state->nbTrans) { trans = &exec->state->trans[exec->transno]; if (trans->to >=0) { atom = trans->atom; if (!((atom->min == 0) && (atom->max > 0))) goto rollback; } } else goto rollback; } exec->transcount = 0; for (;exec->transno < exec->state->nbTrans;exec->transno++) { trans = &exec->state->trans[exec->transno]; if (trans->to < 0) continue; atom = trans->atom; ret = 0; deter = 1; if (trans->count >= 0) { int count; xmlRegCounterPtr counter; if (exec->counts == NULL) { exec->status = -1; goto error; } /* * A counted transition. */ count = exec->counts[trans->count]; counter = &exec->comp->counters[trans->count]; #ifdef DEBUG_REGEXP_EXEC printf("testing count %d: val %d, min %d, max %d\n", trans->count, count, counter->min, counter->max); #endif ret = ((count >= counter->min) && (count <= counter->max)); if ((ret) && (counter->min != counter->max)) deter = 0; } else if (atom == NULL) { fprintf(stderr, "epsilon transition left at runtime\n"); exec->status = -2; break; } else if (exec->inputString[exec->index] != 0) { codepoint = CUR_SCHAR(&(exec->inputString[exec->index]), len); ret = xmlRegCheckCharacter(atom, codepoint); if ((ret == 1) && (atom->min >= 0) && (atom->max > 0)) { xmlRegStatePtr to = comp->states[trans->to]; /* * this is a multiple input sequence * If there is a counter associated increment it now. * before potentially saving and rollback * do not increment if the counter is already over the * maximum limit in which case get to next transition */ if (trans->counter >= 0) { xmlRegCounterPtr counter; if ((exec->counts == NULL) || (exec->comp == NULL) || (exec->comp->counters == NULL)) { exec->status = -1; goto error; } counter = &exec->comp->counters[trans->counter]; if (exec->counts[trans->counter] >= counter->max) continue; /* for loop on transitions */ #ifdef DEBUG_REGEXP_EXEC printf("Increasing count %d\n", trans->counter); #endif exec->counts[trans->counter]++; } if (exec->state->nbTrans > exec->transno + 1) { xmlFARegExecSave(exec); } exec->transcount = 1; do { /* * Try to progress as much as possible on the input */ if (exec->transcount == atom->max) { break; } exec->index += len; /* * End of input: stop here */ if (exec->inputString[exec->index] == 0) { exec->index -= len; break; } if (exec->transcount >= atom->min) { int transno = exec->transno; xmlRegStatePtr state = exec->state; /* * The transition is acceptable save it */ exec->transno = -1; /* trick */ exec->state = to; xmlFARegExecSave(exec); exec->transno = transno; exec->state = state; } codepoint = CUR_SCHAR(&(exec->inputString[exec->index]), len); ret = xmlRegCheckCharacter(atom, codepoint); exec->transcount++; } while (ret == 1); if (exec->transcount < atom->min) ret = 0; /* * If the last check failed but one transition was found * possible, rollback */ if (ret < 0) ret = 0; if (ret == 0) { goto rollback; } if (trans->counter >= 0) { if (exec->counts == NULL) { exec->status = -1; goto error; } #ifdef DEBUG_REGEXP_EXEC printf("Decreasing count %d\n", trans->counter); #endif exec->counts[trans->counter]--; } } else if ((ret == 0) && (atom->min == 0) && (atom->max > 0)) { /* * we don't match on the codepoint, but minOccurs of 0 * says that's ok. Setting len to 0 inhibits stepping * over the codepoint. */ exec->transcount = 1; len = 0; ret = 1; } } else if ((atom->min == 0) && (atom->max > 0)) { /* another spot to match when minOccurs is 0 */ exec->transcount = 1; len = 0; ret = 1; } if (ret == 1) { if ((trans->nd == 1) || ((trans->count >= 0) && (deter == 0) && (exec->state->nbTrans > exec->transno + 1))) { #ifdef DEBUG_REGEXP_EXEC if (trans->nd == 1) printf("Saving on nd transition atom %d for %c at %d\n", trans->atom->no, codepoint, exec->index); else printf("Saving on counted transition count %d for %c at %d\n", trans->count, codepoint, exec->index); #endif xmlFARegExecSave(exec); } if (trans->counter >= 0) { xmlRegCounterPtr counter; /* make sure we don't go over the counter maximum value */ if ((exec->counts == NULL) || (exec->comp == NULL) || (exec->comp->counters == NULL)) { exec->status = -1; goto error; } counter = &exec->comp->counters[trans->counter]; if (exec->counts[trans->counter] >= counter->max) continue; /* for loop on transitions */ #ifdef DEBUG_REGEXP_EXEC printf("Increasing count %d\n", trans->counter); #endif exec->counts[trans->counter]++; } if ((trans->count >= 0) && (trans->count < REGEXP_ALL_COUNTER)) { if (exec->counts == NULL) { exec->status = -1; goto error; } #ifdef DEBUG_REGEXP_EXEC printf("resetting count %d on transition\n", trans->count); #endif exec->counts[trans->count] = 0; } #ifdef DEBUG_REGEXP_EXEC printf("entering state %d\n", trans->to); #endif exec->state = comp->states[trans->to]; exec->transno = 0; if (trans->atom != NULL) { exec->index += len; } goto progress; } else if (ret < 0) { exec->status = -4; break; } } if ((exec->transno != 0) || (exec->state->nbTrans == 0)) { rollback: /* * Failed to find a way out */ exec->determinist = 0; #ifdef DEBUG_REGEXP_EXEC printf("rollback from state %d on %d:%c\n", exec->state->no, codepoint,codepoint); #endif xmlFARegExecRollBack(exec); } progress: continue; } error: if (exec->rollbacks != NULL) { if (exec->counts != NULL) { int i; for (i = 0;i < exec->maxRollbacks;i++) if (exec->rollbacks[i].counts != NULL) xmlFree(exec->rollbacks[i].counts); } xmlFree(exec->rollbacks); } if (exec->state == NULL) return(-1); if (exec->counts != NULL) xmlFree(exec->counts); if (exec->status == 0) return(1); if (exec->status == -1) { if (exec->nbPush > MAX_PUSH) return(-1); return(0); } return(exec->status); } /************************************************************************ * * * Progressive interface to the verifier one atom at a time * * * ************************************************************************/ #ifdef DEBUG_ERR static void testerr(xmlRegExecCtxtPtr exec); #endif /** * xmlRegNewExecCtxt: * @comp: a precompiled regular expression * @callback: a callback function used for handling progresses in the * automata matching phase * @data: the context data associated to the callback in this context * * Build a context used for progressive evaluation of a regexp. * * Returns the new context */ xmlRegExecCtxtPtr xmlRegNewExecCtxt(xmlRegexpPtr comp, xmlRegExecCallbacks callback, void *data) { xmlRegExecCtxtPtr exec; if (comp == NULL) return(NULL); if ((comp->compact == NULL) && (comp->states == NULL)) return(NULL); exec = (xmlRegExecCtxtPtr) xmlMalloc(sizeof(xmlRegExecCtxt)); if (exec == NULL) { xmlRegexpErrMemory(NULL, "creating execution context"); return(NULL); } memset(exec, 0, sizeof(xmlRegExecCtxt)); exec->inputString = NULL; exec->index = 0; exec->determinist = 1; exec->maxRollbacks = 0; exec->nbRollbacks = 0; exec->rollbacks = NULL; exec->status = 0; exec->comp = comp; if (comp->compact == NULL) exec->state = comp->states[0]; exec->transno = 0; exec->transcount = 0; exec->callback = callback; exec->data = data; if (comp->nbCounters > 0) { /* * For error handling, exec->counts is allocated twice the size * the second half is used to store the data in case of rollback */ exec->counts = (int *) xmlMalloc(comp->nbCounters * sizeof(int) * 2); if (exec->counts == NULL) { xmlRegexpErrMemory(NULL, "creating execution context"); xmlFree(exec); return(NULL); } memset(exec->counts, 0, comp->nbCounters * sizeof(int) * 2); exec->errCounts = &exec->counts[comp->nbCounters]; } else { exec->counts = NULL; exec->errCounts = NULL; } exec->inputStackMax = 0; exec->inputStackNr = 0; exec->inputStack = NULL; exec->errStateNo = -1; exec->errString = NULL; exec->nbPush = 0; return(exec); } /** * xmlRegFreeExecCtxt: * @exec: a regular expression evaluation context * * Free the structures associated to a regular expression evaluation context. */ void xmlRegFreeExecCtxt(xmlRegExecCtxtPtr exec) { if (exec == NULL) return; if (exec->rollbacks != NULL) { if (exec->counts != NULL) { int i; for (i = 0;i < exec->maxRollbacks;i++) if (exec->rollbacks[i].counts != NULL) xmlFree(exec->rollbacks[i].counts); } xmlFree(exec->rollbacks); } if (exec->counts != NULL) xmlFree(exec->counts); if (exec->inputStack != NULL) { int i; for (i = 0;i < exec->inputStackNr;i++) { if (exec->inputStack[i].value != NULL) xmlFree(exec->inputStack[i].value); } xmlFree(exec->inputStack); } if (exec->errString != NULL) xmlFree(exec->errString); xmlFree(exec); } static void xmlFARegExecSaveInputString(xmlRegExecCtxtPtr exec, const xmlChar *value, void *data) { #ifdef DEBUG_PUSH printf("saving value: %d:%s\n", exec->inputStackNr, value); #endif if (exec->inputStackMax == 0) { exec->inputStackMax = 4; exec->inputStack = (xmlRegInputTokenPtr) xmlMalloc(exec->inputStackMax * sizeof(xmlRegInputToken)); if (exec->inputStack == NULL) { xmlRegexpErrMemory(NULL, "pushing input string"); exec->inputStackMax = 0; return; } } else if (exec->inputStackNr + 1 >= exec->inputStackMax) { xmlRegInputTokenPtr tmp; exec->inputStackMax *= 2; tmp = (xmlRegInputTokenPtr) xmlRealloc(exec->inputStack, exec->inputStackMax * sizeof(xmlRegInputToken)); if (tmp == NULL) { xmlRegexpErrMemory(NULL, "pushing input string"); exec->inputStackMax /= 2; return; } exec->inputStack = tmp; } exec->inputStack[exec->inputStackNr].value = xmlStrdup(value); exec->inputStack[exec->inputStackNr].data = data; exec->inputStackNr++; exec->inputStack[exec->inputStackNr].value = NULL; exec->inputStack[exec->inputStackNr].data = NULL; } /** * xmlRegStrEqualWildcard: * @expStr: the string to be evaluated * @valStr: the validation string * * Checks if both strings are equal or have the same content. "*" * can be used as a wildcard in @valStr; "|" is used as a separator of * substrings in both @expStr and @valStr. * * Returns 1 if the comparison is satisfied and the number of substrings * is equal, 0 otherwise. */ static int xmlRegStrEqualWildcard(const xmlChar *expStr, const xmlChar *valStr) { if (expStr == valStr) return(1); if (expStr == NULL) return(0); if (valStr == NULL) return(0); do { /* * Eval if we have a wildcard for the current item. */ if (*expStr != *valStr) { /* if one of them starts with a wildcard make valStr be it */ if (*valStr == '*') { const xmlChar *tmp; tmp = valStr; valStr = expStr; expStr = tmp; } if ((*valStr != 0) && (*expStr != 0) && (*expStr++ == '*')) { do { if (*valStr == XML_REG_STRING_SEPARATOR) break; valStr++; } while (*valStr != 0); continue; } else return(0); } expStr++; valStr++; } while (*valStr != 0); if (*expStr != 0) return (0); else return (1); } /** * xmlRegCompactPushString: * @exec: a regexp execution context * @comp: the precompiled exec with a compact table * @value: a string token input * @data: data associated to the token to reuse in callbacks * * Push one input token in the execution context * * Returns: 1 if the regexp reached a final state, 0 if non-final, and * a negative value in case of error. */ static int xmlRegCompactPushString(xmlRegExecCtxtPtr exec, xmlRegexpPtr comp, const xmlChar *value, void *data) { int state = exec->index; int i, target; if ((comp == NULL) || (comp->compact == NULL) || (comp->stringMap == NULL)) return(-1); if (value == NULL) { /* * are we at a final state ? */ if (comp->compact[state * (comp->nbstrings + 1)] == XML_REGEXP_FINAL_STATE) return(1); return(0); } #ifdef DEBUG_PUSH printf("value pushed: %s\n", value); #endif /* * Examine all outside transitions from current state */ for (i = 0;i < comp->nbstrings;i++) { target = comp->compact[state * (comp->nbstrings + 1) + i + 1]; if ((target > 0) && (target <= comp->nbstates)) { target--; /* to avoid 0 */ if (xmlRegStrEqualWildcard(comp->stringMap[i], value)) { exec->index = target; if ((exec->callback != NULL) && (comp->transdata != NULL)) { exec->callback(exec->data, value, comp->transdata[state * comp->nbstrings + i], data); } #ifdef DEBUG_PUSH printf("entering state %d\n", target); #endif if (comp->compact[target * (comp->nbstrings + 1)] == XML_REGEXP_SINK_STATE) goto error; if (comp->compact[target * (comp->nbstrings + 1)] == XML_REGEXP_FINAL_STATE) return(1); return(0); } } } /* * Failed to find an exit transition out from current state for the * current token */ #ifdef DEBUG_PUSH printf("failed to find a transition for %s on state %d\n", value, state); #endif error: if (exec->errString != NULL) xmlFree(exec->errString); exec->errString = xmlStrdup(value); exec->errStateNo = state; exec->status = -1; #ifdef DEBUG_ERR testerr(exec); #endif return(-1); } /** * xmlRegExecPushStringInternal: * @exec: a regexp execution context or NULL to indicate the end * @value: a string token input * @data: data associated to the token to reuse in callbacks * @compound: value was assembled from 2 strings * * Push one input token in the execution context * * Returns: 1 if the regexp reached a final state, 0 if non-final, and * a negative value in case of error. */ static int xmlRegExecPushStringInternal(xmlRegExecCtxtPtr exec, const xmlChar *value, void *data, int compound) { xmlRegTransPtr trans; xmlRegAtomPtr atom; int ret; int final = 0; int progress = 1; if (exec == NULL) return(-1); if (exec->comp == NULL) return(-1); if (exec->status != 0) return(exec->status); if (exec->comp->compact != NULL) return(xmlRegCompactPushString(exec, exec->comp, value, data)); if (value == NULL) { if (exec->state->type == XML_REGEXP_FINAL_STATE) return(1); final = 1; } #ifdef DEBUG_PUSH printf("value pushed: %s\n", value); #endif /* * If we have an active rollback stack push the new value there * and get back to where we were left */ if ((value != NULL) && (exec->inputStackNr > 0)) { xmlFARegExecSaveInputString(exec, value, data); value = exec->inputStack[exec->index].value; data = exec->inputStack[exec->index].data; #ifdef DEBUG_PUSH printf("value loaded: %s\n", value); #endif } while ((exec->status == 0) && ((value != NULL) || ((final == 1) && (exec->state->type != XML_REGEXP_FINAL_STATE)))) { /* * End of input on non-terminal state, rollback, however we may * still have epsilon like transition for counted transitions * on counters, in that case don't break too early. */ if ((value == NULL) && (exec->counts == NULL)) goto rollback; exec->transcount = 0; for (;exec->transno < exec->state->nbTrans;exec->transno++) { trans = &exec->state->trans[exec->transno]; if (trans->to < 0) continue; atom = trans->atom; ret = 0; if (trans->count == REGEXP_ALL_LAX_COUNTER) { int i; int count; xmlRegTransPtr t; xmlRegCounterPtr counter; ret = 0; #ifdef DEBUG_PUSH printf("testing all lax %d\n", trans->count); #endif /* * Check all counted transitions from the current state */ if ((value == NULL) && (final)) { ret = 1; } else if (value != NULL) { for (i = 0;i < exec->state->nbTrans;i++) { t = &exec->state->trans[i]; if ((t->counter < 0) || (t == trans)) continue; counter = &exec->comp->counters[t->counter]; count = exec->counts[t->counter]; if ((count < counter->max) && (t->atom != NULL) && (xmlStrEqual(value, t->atom->valuep))) { ret = 0; break; } if ((count >= counter->min) && (count < counter->max) && (t->atom != NULL) && (xmlStrEqual(value, t->atom->valuep))) { ret = 1; break; } } } } else if (trans->count == REGEXP_ALL_COUNTER) { int i; int count; xmlRegTransPtr t; xmlRegCounterPtr counter; ret = 1; #ifdef DEBUG_PUSH printf("testing all %d\n", trans->count); #endif /* * Check all counted transitions from the current state */ for (i = 0;i < exec->state->nbTrans;i++) { t = &exec->state->trans[i]; if ((t->counter < 0) || (t == trans)) continue; counter = &exec->comp->counters[t->counter]; count = exec->counts[t->counter]; if ((count < counter->min) || (count > counter->max)) { ret = 0; break; } } } else if (trans->count >= 0) { int count; xmlRegCounterPtr counter; /* * A counted transition. */ count = exec->counts[trans->count]; counter = &exec->comp->counters[trans->count]; #ifdef DEBUG_PUSH printf("testing count %d: val %d, min %d, max %d\n", trans->count, count, counter->min, counter->max); #endif ret = ((count >= counter->min) && (count <= counter->max)); } else if (atom == NULL) { fprintf(stderr, "epsilon transition left at runtime\n"); exec->status = -2; break; } else if (value != NULL) { ret = xmlRegStrEqualWildcard(atom->valuep, value); if (atom->neg) { ret = !ret; if (!compound) ret = 0; } if ((ret == 1) && (trans->counter >= 0)) { xmlRegCounterPtr counter; int count; count = exec->counts[trans->counter]; counter = &exec->comp->counters[trans->counter]; if (count >= counter->max) ret = 0; } if ((ret == 1) && (atom->min > 0) && (atom->max > 0)) { xmlRegStatePtr to = exec->comp->states[trans->to]; /* * this is a multiple input sequence */ if (exec->state->nbTrans > exec->transno + 1) { if (exec->inputStackNr <= 0) { xmlFARegExecSaveInputString(exec, value, data); } xmlFARegExecSave(exec); } exec->transcount = 1; do { /* * Try to progress as much as possible on the input */ if (exec->transcount == atom->max) { break; } exec->index++; value = exec->inputStack[exec->index].value; data = exec->inputStack[exec->index].data; #ifdef DEBUG_PUSH printf("value loaded: %s\n", value); #endif /* * End of input: stop here */ if (value == NULL) { exec->index --; break; } if (exec->transcount >= atom->min) { int transno = exec->transno; xmlRegStatePtr state = exec->state; /* * The transition is acceptable save it */ exec->transno = -1; /* trick */ exec->state = to; if (exec->inputStackNr <= 0) { xmlFARegExecSaveInputString(exec, value, data); } xmlFARegExecSave(exec); exec->transno = transno; exec->state = state; } ret = xmlStrEqual(value, atom->valuep); exec->transcount++; } while (ret == 1); if (exec->transcount < atom->min) ret = 0; /* * If the last check failed but one transition was found * possible, rollback */ if (ret < 0) ret = 0; if (ret == 0) { goto rollback; } } } if (ret == 1) { if ((exec->callback != NULL) && (atom != NULL) && (data != NULL)) { exec->callback(exec->data, atom->valuep, atom->data, data); } if (exec->state->nbTrans > exec->transno + 1) { if (exec->inputStackNr <= 0) { xmlFARegExecSaveInputString(exec, value, data); } xmlFARegExecSave(exec); } if (trans->counter >= 0) { #ifdef DEBUG_PUSH printf("Increasing count %d\n", trans->counter); #endif exec->counts[trans->counter]++; } if ((trans->count >= 0) && (trans->count < REGEXP_ALL_COUNTER)) { #ifdef DEBUG_REGEXP_EXEC printf("resetting count %d on transition\n", trans->count); #endif exec->counts[trans->count] = 0; } #ifdef DEBUG_PUSH printf("entering state %d\n", trans->to); #endif if ((exec->comp->states[trans->to] != NULL) && (exec->comp->states[trans->to]->type == XML_REGEXP_SINK_STATE)) { /* * entering a sink state, save the current state as error * state. */ if (exec->errString != NULL) xmlFree(exec->errString); exec->errString = xmlStrdup(value); exec->errState = exec->state; memcpy(exec->errCounts, exec->counts, exec->comp->nbCounters * sizeof(int)); } exec->state = exec->comp->states[trans->to]; exec->transno = 0; if (trans->atom != NULL) { if (exec->inputStack != NULL) { exec->index++; if (exec->index < exec->inputStackNr) { value = exec->inputStack[exec->index].value; data = exec->inputStack[exec->index].data; #ifdef DEBUG_PUSH printf("value loaded: %s\n", value); #endif } else { value = NULL; data = NULL; #ifdef DEBUG_PUSH printf("end of input\n"); #endif } } else { value = NULL; data = NULL; #ifdef DEBUG_PUSH printf("end of input\n"); #endif } } goto progress; } else if (ret < 0) { exec->status = -4; break; } } if ((exec->transno != 0) || (exec->state->nbTrans == 0)) { rollback: /* * if we didn't yet rollback on the current input * store the current state as the error state. */ if ((progress) && (exec->state != NULL) && (exec->state->type != XML_REGEXP_SINK_STATE)) { progress = 0; if (exec->errString != NULL) xmlFree(exec->errString); exec->errString = xmlStrdup(value); exec->errState = exec->state; if (exec->comp->nbCounters) memcpy(exec->errCounts, exec->counts, exec->comp->nbCounters * sizeof(int)); } /* * Failed to find a way out */ exec->determinist = 0; xmlFARegExecRollBack(exec); if ((exec->inputStack != NULL ) && (exec->status == 0)) { value = exec->inputStack[exec->index].value; data = exec->inputStack[exec->index].data; #ifdef DEBUG_PUSH printf("value loaded: %s\n", value); #endif } } continue; progress: progress = 1; continue; } if (exec->status == 0) { return(exec->state->type == XML_REGEXP_FINAL_STATE); } #ifdef DEBUG_ERR if (exec->status < 0) { testerr(exec); } #endif return(exec->status); } /** * xmlRegExecPushString: * @exec: a regexp execution context or NULL to indicate the end * @value: a string token input * @data: data associated to the token to reuse in callbacks * * Push one input token in the execution context * * Returns: 1 if the regexp reached a final state, 0 if non-final, and * a negative value in case of error. */ int xmlRegExecPushString(xmlRegExecCtxtPtr exec, const xmlChar *value, void *data) { return(xmlRegExecPushStringInternal(exec, value, data, 0)); } /** * xmlRegExecPushString2: * @exec: a regexp execution context or NULL to indicate the end * @value: the first string token input * @value2: the second string token input * @data: data associated to the token to reuse in callbacks * * Push one input token in the execution context * * Returns: 1 if the regexp reached a final state, 0 if non-final, and * a negative value in case of error. */ int xmlRegExecPushString2(xmlRegExecCtxtPtr exec, const xmlChar *value, const xmlChar *value2, void *data) { xmlChar buf[150]; int lenn, lenp, ret; xmlChar *str; if (exec == NULL) return(-1); if (exec->comp == NULL) return(-1); if (exec->status != 0) return(exec->status); if (value2 == NULL) return(xmlRegExecPushString(exec, value, data)); lenn = strlen((char *) value2); lenp = strlen((char *) value); if (150 < lenn + lenp + 2) { str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2); if (str == NULL) { exec->status = -1; return(-1); } } else { str = buf; } memcpy(&str[0], value, lenp); str[lenp] = XML_REG_STRING_SEPARATOR; memcpy(&str[lenp + 1], value2, lenn); str[lenn + lenp + 1] = 0; if (exec->comp->compact != NULL) ret = xmlRegCompactPushString(exec, exec->comp, str, data); else ret = xmlRegExecPushStringInternal(exec, str, data, 1); if (str != buf) xmlFree(str); return(ret); } /** * xmlRegExecGetValues: * @exec: a regexp execution context * @err: error extraction or normal one * @nbval: pointer to the number of accepted values IN/OUT * @nbneg: return number of negative transitions * @values: pointer to the array of acceptable values * @terminal: return value if this was a terminal state * * Extract information from the regexp execution, internal routine to * implement xmlRegExecNextValues() and xmlRegExecErrInfo() * * Returns: 0 in case of success or -1 in case of error. */ static int xmlRegExecGetValues(xmlRegExecCtxtPtr exec, int err, int *nbval, int *nbneg, xmlChar **values, int *terminal) { int maxval; int nb = 0; if ((exec == NULL) || (nbval == NULL) || (nbneg == NULL) || (values == NULL) || (*nbval <= 0)) return(-1); maxval = *nbval; *nbval = 0; *nbneg = 0; if ((exec->comp != NULL) && (exec->comp->compact != NULL)) { xmlRegexpPtr comp; int target, i, state; comp = exec->comp; if (err) { if (exec->errStateNo == -1) return(-1); state = exec->errStateNo; } else { state = exec->index; } if (terminal != NULL) { if (comp->compact[state * (comp->nbstrings + 1)] == XML_REGEXP_FINAL_STATE) *terminal = 1; else *terminal = 0; } for (i = 0;(i < comp->nbstrings) && (nb < maxval);i++) { target = comp->compact[state * (comp->nbstrings + 1) + i + 1]; if ((target > 0) && (target <= comp->nbstates) && (comp->compact[(target - 1) * (comp->nbstrings + 1)] != XML_REGEXP_SINK_STATE)) { values[nb++] = comp->stringMap[i]; (*nbval)++; } } for (i = 0;(i < comp->nbstrings) && (nb < maxval);i++) { target = comp->compact[state * (comp->nbstrings + 1) + i + 1]; if ((target > 0) && (target <= comp->nbstates) && (comp->compact[(target - 1) * (comp->nbstrings + 1)] == XML_REGEXP_SINK_STATE)) { values[nb++] = comp->stringMap[i]; (*nbneg)++; } } } else { int transno; xmlRegTransPtr trans; xmlRegAtomPtr atom; xmlRegStatePtr state; if (terminal != NULL) { if (exec->state->type == XML_REGEXP_FINAL_STATE) *terminal = 1; else *terminal = 0; } if (err) { if (exec->errState == NULL) return(-1); state = exec->errState; } else { if (exec->state == NULL) return(-1); state = exec->state; } for (transno = 0; (transno < state->nbTrans) && (nb < maxval); transno++) { trans = &state->trans[transno]; if (trans->to < 0) continue; atom = trans->atom; if ((atom == NULL) || (atom->valuep == NULL)) continue; if (trans->count == REGEXP_ALL_LAX_COUNTER) { /* this should not be reached but ... */ TODO; } else if (trans->count == REGEXP_ALL_COUNTER) { /* this should not be reached but ... */ TODO; } else if (trans->counter >= 0) { xmlRegCounterPtr counter = NULL; int count; if (err) count = exec->errCounts[trans->counter]; else count = exec->counts[trans->counter]; if (exec->comp != NULL) counter = &exec->comp->counters[trans->counter]; if ((counter == NULL) || (count < counter->max)) { if (atom->neg) values[nb++] = (xmlChar *) atom->valuep2; else values[nb++] = (xmlChar *) atom->valuep; (*nbval)++; } } else { if ((exec->comp != NULL) && (exec->comp->states[trans->to] != NULL) && (exec->comp->states[trans->to]->type != XML_REGEXP_SINK_STATE)) { if (atom->neg) values[nb++] = (xmlChar *) atom->valuep2; else values[nb++] = (xmlChar *) atom->valuep; (*nbval)++; } } } for (transno = 0; (transno < state->nbTrans) && (nb < maxval); transno++) { trans = &state->trans[transno]; if (trans->to < 0) continue; atom = trans->atom; if ((atom == NULL) || (atom->valuep == NULL)) continue; if (trans->count == REGEXP_ALL_LAX_COUNTER) { continue; } else if (trans->count == REGEXP_ALL_COUNTER) { continue; } else if (trans->counter >= 0) { continue; } else { if ((exec->comp->states[trans->to] != NULL) && (exec->comp->states[trans->to]->type == XML_REGEXP_SINK_STATE)) { if (atom->neg) values[nb++] = (xmlChar *) atom->valuep2; else values[nb++] = (xmlChar *) atom->valuep; (*nbneg)++; } } } } return(0); } /** * xmlRegExecNextValues: * @exec: a regexp execution context * @nbval: pointer to the number of accepted values IN/OUT * @nbneg: return number of negative transitions * @values: pointer to the array of acceptable values * @terminal: return value if this was a terminal state * * Extract information from the regexp execution, * the parameter @values must point to an array of @nbval string pointers * on return nbval will contain the number of possible strings in that * state and the @values array will be updated with them. The string values * returned will be freed with the @exec context and don't need to be * deallocated. * * Returns: 0 in case of success or -1 in case of error. */ int xmlRegExecNextValues(xmlRegExecCtxtPtr exec, int *nbval, int *nbneg, xmlChar **values, int *terminal) { return(xmlRegExecGetValues(exec, 0, nbval, nbneg, values, terminal)); } /** * xmlRegExecErrInfo: * @exec: a regexp execution context generating an error * @string: return value for the error string * @nbval: pointer to the number of accepted values IN/OUT * @nbneg: return number of negative transitions * @values: pointer to the array of acceptable values * @terminal: return value if this was a terminal state * * Extract error information from the regexp execution, the parameter * @string will be updated with the value pushed and not accepted, * the parameter @values must point to an array of @nbval string pointers * on return nbval will contain the number of possible strings in that * state and the @values array will be updated with them. The string values * returned will be freed with the @exec context and don't need to be * deallocated. * * Returns: 0 in case of success or -1 in case of error. */ int xmlRegExecErrInfo(xmlRegExecCtxtPtr exec, const xmlChar **string, int *nbval, int *nbneg, xmlChar **values, int *terminal) { if (exec == NULL) return(-1); if (string != NULL) { if (exec->status != 0) *string = exec->errString; else *string = NULL; } return(xmlRegExecGetValues(exec, 1, nbval, nbneg, values, terminal)); } #ifdef DEBUG_ERR static void testerr(xmlRegExecCtxtPtr exec) { const xmlChar *string; xmlChar *values[5]; int nb = 5; int nbneg; int terminal; xmlRegExecErrInfo(exec, &string, &nb, &nbneg, &values[0], &terminal); } #endif #if 0 static int xmlRegExecPushChar(xmlRegExecCtxtPtr exec, int UCS) { xmlRegTransPtr trans; xmlRegAtomPtr atom; int ret; int codepoint, len; if (exec == NULL) return(-1); if (exec->status != 0) return(exec->status); while ((exec->status == 0) && ((exec->inputString[exec->index] != 0) || (exec->state->type != XML_REGEXP_FINAL_STATE))) { /* * End of input on non-terminal state, rollback, however we may * still have epsilon like transition for counted transitions * on counters, in that case don't break too early. */ if ((exec->inputString[exec->index] == 0) && (exec->counts == NULL)) goto rollback; exec->transcount = 0; for (;exec->transno < exec->state->nbTrans;exec->transno++) { trans = &exec->state->trans[exec->transno]; if (trans->to < 0) continue; atom = trans->atom; ret = 0; if (trans->count >= 0) { int count; xmlRegCounterPtr counter; /* * A counted transition. */ count = exec->counts[trans->count]; counter = &exec->comp->counters[trans->count]; #ifdef DEBUG_REGEXP_EXEC printf("testing count %d: val %d, min %d, max %d\n", trans->count, count, counter->min, counter->max); #endif ret = ((count >= counter->min) && (count <= counter->max)); } else if (atom == NULL) { fprintf(stderr, "epsilon transition left at runtime\n"); exec->status = -2; break; } else if (exec->inputString[exec->index] != 0) { codepoint = CUR_SCHAR(&(exec->inputString[exec->index]), len); ret = xmlRegCheckCharacter(atom, codepoint); if ((ret == 1) && (atom->min > 0) && (atom->max > 0)) { xmlRegStatePtr to = exec->comp->states[trans->to]; /* * this is a multiple input sequence */ if (exec->state->nbTrans > exec->transno + 1) { xmlFARegExecSave(exec); } exec->transcount = 1; do { /* * Try to progress as much as possible on the input */ if (exec->transcount == atom->max) { break; } exec->index += len; /* * End of input: stop here */ if (exec->inputString[exec->index] == 0) { exec->index -= len; break; } if (exec->transcount >= atom->min) { int transno = exec->transno; xmlRegStatePtr state = exec->state; /* * The transition is acceptable save it */ exec->transno = -1; /* trick */ exec->state = to; xmlFARegExecSave(exec); exec->transno = transno; exec->state = state; } codepoint = CUR_SCHAR(&(exec->inputString[exec->index]), len); ret = xmlRegCheckCharacter(atom, codepoint); exec->transcount++; } while (ret == 1); if (exec->transcount < atom->min) ret = 0; /* * If the last check failed but one transition was found * possible, rollback */ if (ret < 0) ret = 0; if (ret == 0) { goto rollback; } } } if (ret == 1) { if (exec->state->nbTrans > exec->transno + 1) { xmlFARegExecSave(exec); } /* * restart count for expressions like this ((abc){2})* */ if (trans->count >= 0) { #ifdef DEBUG_REGEXP_EXEC printf("Reset count %d\n", trans->count); #endif exec->counts[trans->count] = 0; } if (trans->counter >= 0) { #ifdef DEBUG_REGEXP_EXEC printf("Increasing count %d\n", trans->counter); #endif exec->counts[trans->counter]++; } #ifdef DEBUG_REGEXP_EXEC printf("entering state %d\n", trans->to); #endif exec->state = exec->comp->states[trans->to]; exec->transno = 0; if (trans->atom != NULL) { exec->index += len; } goto progress; } else if (ret < 0) { exec->status = -4; break; } } if ((exec->transno != 0) || (exec->state->nbTrans == 0)) { rollback: /* * Failed to find a way out */ exec->determinist = 0; xmlFARegExecRollBack(exec); } progress: continue; } } #endif /************************************************************************ * * * Parser for the Schemas Datatype Regular Expressions * * http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/#regexs * * * ************************************************************************/ /** * xmlFAIsChar: * @ctxt: a regexp parser context * * [10] Char ::= [^.\?*+()|#x5B#x5D] */ static int xmlFAIsChar(xmlRegParserCtxtPtr ctxt) { int cur; int len; cur = CUR_SCHAR(ctxt->cur, len); if ((cur == '.') || (cur == '\\') || (cur == '?') || (cur == '*') || (cur == '+') || (cur == '(') || (cur == ')') || (cur == '|') || (cur == 0x5B) || (cur == 0x5D) || (cur == 0)) return(-1); return(cur); } /** * xmlFAParseCharProp: * @ctxt: a regexp parser context * * [27] charProp ::= IsCategory | IsBlock * [28] IsCategory ::= Letters | Marks | Numbers | Punctuation | * Separators | Symbols | Others * [29] Letters ::= 'L' [ultmo]? * [30] Marks ::= 'M' [nce]? * [31] Numbers ::= 'N' [dlo]? * [32] Punctuation ::= 'P' [cdseifo]? * [33] Separators ::= 'Z' [slp]? * [34] Symbols ::= 'S' [mcko]? * [35] Others ::= 'C' [cfon]? * [36] IsBlock ::= 'Is' [a-zA-Z0-9#x2D]+ */ static void xmlFAParseCharProp(xmlRegParserCtxtPtr ctxt) { int cur; xmlRegAtomType type = (xmlRegAtomType) 0; xmlChar *blockName = NULL; cur = CUR; if (cur == 'L') { NEXT; cur = CUR; if (cur == 'u') { NEXT; type = XML_REGEXP_LETTER_UPPERCASE; } else if (cur == 'l') { NEXT; type = XML_REGEXP_LETTER_LOWERCASE; } else if (cur == 't') { NEXT; type = XML_REGEXP_LETTER_TITLECASE; } else if (cur == 'm') { NEXT; type = XML_REGEXP_LETTER_MODIFIER; } else if (cur == 'o') { NEXT; type = XML_REGEXP_LETTER_OTHERS; } else { type = XML_REGEXP_LETTER; } } else if (cur == 'M') { NEXT; cur = CUR; if (cur == 'n') { NEXT; /* nonspacing */ type = XML_REGEXP_MARK_NONSPACING; } else if (cur == 'c') { NEXT; /* spacing combining */ type = XML_REGEXP_MARK_SPACECOMBINING; } else if (cur == 'e') { NEXT; /* enclosing */ type = XML_REGEXP_MARK_ENCLOSING; } else { /* all marks */ type = XML_REGEXP_MARK; } } else if (cur == 'N') { NEXT; cur = CUR; if (cur == 'd') { NEXT; /* digital */ type = XML_REGEXP_NUMBER_DECIMAL; } else if (cur == 'l') { NEXT; /* letter */ type = XML_REGEXP_NUMBER_LETTER; } else if (cur == 'o') { NEXT; /* other */ type = XML_REGEXP_NUMBER_OTHERS; } else { /* all numbers */ type = XML_REGEXP_NUMBER; } } else if (cur == 'P') { NEXT; cur = CUR; if (cur == 'c') { NEXT; /* connector */ type = XML_REGEXP_PUNCT_CONNECTOR; } else if (cur == 'd') { NEXT; /* dash */ type = XML_REGEXP_PUNCT_DASH; } else if (cur == 's') { NEXT; /* open */ type = XML_REGEXP_PUNCT_OPEN; } else if (cur == 'e') { NEXT; /* close */ type = XML_REGEXP_PUNCT_CLOSE; } else if (cur == 'i') { NEXT; /* initial quote */ type = XML_REGEXP_PUNCT_INITQUOTE; } else if (cur == 'f') { NEXT; /* final quote */ type = XML_REGEXP_PUNCT_FINQUOTE; } else if (cur == 'o') { NEXT; /* other */ type = XML_REGEXP_PUNCT_OTHERS; } else { /* all punctuation */ type = XML_REGEXP_PUNCT; } } else if (cur == 'Z') { NEXT; cur = CUR; if (cur == 's') { NEXT; /* space */ type = XML_REGEXP_SEPAR_SPACE; } else if (cur == 'l') { NEXT; /* line */ type = XML_REGEXP_SEPAR_LINE; } else if (cur == 'p') { NEXT; /* paragraph */ type = XML_REGEXP_SEPAR_PARA; } else { /* all separators */ type = XML_REGEXP_SEPAR; } } else if (cur == 'S') { NEXT; cur = CUR; if (cur == 'm') { NEXT; type = XML_REGEXP_SYMBOL_MATH; /* math */ } else if (cur == 'c') { NEXT; type = XML_REGEXP_SYMBOL_CURRENCY; /* currency */ } else if (cur == 'k') { NEXT; type = XML_REGEXP_SYMBOL_MODIFIER; /* modifiers */ } else if (cur == 'o') { NEXT; type = XML_REGEXP_SYMBOL_OTHERS; /* other */ } else { /* all symbols */ type = XML_REGEXP_SYMBOL; } } else if (cur == 'C') { NEXT; cur = CUR; if (cur == 'c') { NEXT; /* control */ type = XML_REGEXP_OTHER_CONTROL; } else if (cur == 'f') { NEXT; /* format */ type = XML_REGEXP_OTHER_FORMAT; } else if (cur == 'o') { NEXT; /* private use */ type = XML_REGEXP_OTHER_PRIVATE; } else if (cur == 'n') { NEXT; /* not assigned */ type = XML_REGEXP_OTHER_NA; } else { /* all others */ type = XML_REGEXP_OTHER; } } else if (cur == 'I') { const xmlChar *start; NEXT; cur = CUR; if (cur != 's') { ERROR("IsXXXX expected"); return; } NEXT; start = ctxt->cur; cur = CUR; if (((cur >= 'a') && (cur <= 'z')) || ((cur >= 'A') && (cur <= 'Z')) || ((cur >= '0') && (cur <= '9')) || (cur == 0x2D)) { NEXT; cur = CUR; while (((cur >= 'a') && (cur <= 'z')) || ((cur >= 'A') && (cur <= 'Z')) || ((cur >= '0') && (cur <= '9')) || (cur == 0x2D)) { NEXT; cur = CUR; } } type = XML_REGEXP_BLOCK_NAME; blockName = xmlStrndup(start, ctxt->cur - start); } else { ERROR("Unknown char property"); return; } if (ctxt->atom == NULL) { ctxt->atom = xmlRegNewAtom(ctxt, type); if (ctxt->atom != NULL) ctxt->atom->valuep = blockName; } else if (ctxt->atom->type == XML_REGEXP_RANGES) { xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg, type, 0, 0, blockName); } } /** * xmlFAParseCharClassEsc: * @ctxt: a regexp parser context * * [23] charClassEsc ::= ( SingleCharEsc | MultiCharEsc | catEsc | complEsc ) * [24] SingleCharEsc ::= '\' [nrt\|.?*+(){}#x2D#x5B#x5D#x5E] * [25] catEsc ::= '\p{' charProp '}' * [26] complEsc ::= '\P{' charProp '}' * [37] MultiCharEsc ::= '.' | ('\' [sSiIcCdDwW]) */ static void xmlFAParseCharClassEsc(xmlRegParserCtxtPtr ctxt) { int cur; if (CUR == '.') { if (ctxt->atom == NULL) { ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_ANYCHAR); } else if (ctxt->atom->type == XML_REGEXP_RANGES) { xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg, XML_REGEXP_ANYCHAR, 0, 0, NULL); } NEXT; return; } if (CUR != '\\') { ERROR("Escaped sequence: expecting \\"); return; } NEXT; cur = CUR; if (cur == 'p') { NEXT; if (CUR != '{') { ERROR("Expecting '{'"); return; } NEXT; xmlFAParseCharProp(ctxt); if (CUR != '}') { ERROR("Expecting '}'"); return; } NEXT; } else if (cur == 'P') { NEXT; if (CUR != '{') { ERROR("Expecting '{'"); return; } NEXT; xmlFAParseCharProp(ctxt); if (ctxt->atom != NULL) ctxt->atom->neg = 1; if (CUR != '}') { ERROR("Expecting '}'"); return; } NEXT; } else if ((cur == 'n') || (cur == 'r') || (cur == 't') || (cur == '\\') || (cur == '|') || (cur == '.') || (cur == '?') || (cur == '*') || (cur == '+') || (cur == '(') || (cur == ')') || (cur == '{') || (cur == '}') || (cur == 0x2D) || (cur == 0x5B) || (cur == 0x5D) || (cur == 0x5E)) { if (ctxt->atom == NULL) { ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_CHARVAL); if (ctxt->atom != NULL) { switch (cur) { case 'n': ctxt->atom->codepoint = '\n'; break; case 'r': ctxt->atom->codepoint = '\r'; break; case 't': ctxt->atom->codepoint = '\t'; break; default: ctxt->atom->codepoint = cur; } } } else if (ctxt->atom->type == XML_REGEXP_RANGES) { switch (cur) { case 'n': cur = '\n'; break; case 'r': cur = '\r'; break; case 't': cur = '\t'; break; } xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg, XML_REGEXP_CHARVAL, cur, cur, NULL); } NEXT; } else if ((cur == 's') || (cur == 'S') || (cur == 'i') || (cur == 'I') || (cur == 'c') || (cur == 'C') || (cur == 'd') || (cur == 'D') || (cur == 'w') || (cur == 'W')) { xmlRegAtomType type = XML_REGEXP_ANYSPACE; switch (cur) { case 's': type = XML_REGEXP_ANYSPACE; break; case 'S': type = XML_REGEXP_NOTSPACE; break; case 'i': type = XML_REGEXP_INITNAME; break; case 'I': type = XML_REGEXP_NOTINITNAME; break; case 'c': type = XML_REGEXP_NAMECHAR; break; case 'C': type = XML_REGEXP_NOTNAMECHAR; break; case 'd': type = XML_REGEXP_DECIMAL; break; case 'D': type = XML_REGEXP_NOTDECIMAL; break; case 'w': type = XML_REGEXP_REALCHAR; break; case 'W': type = XML_REGEXP_NOTREALCHAR; break; } NEXT; if (ctxt->atom == NULL) { ctxt->atom = xmlRegNewAtom(ctxt, type); } else if (ctxt->atom->type == XML_REGEXP_RANGES) { xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg, type, 0, 0, NULL); } } else { ERROR("Wrong escape sequence, misuse of character '\\'"); } } /** * xmlFAParseCharRange: * @ctxt: a regexp parser context * * [17] charRange ::= seRange | XmlCharRef | XmlCharIncDash * [18] seRange ::= charOrEsc '-' charOrEsc * [20] charOrEsc ::= XmlChar | SingleCharEsc * [21] XmlChar ::= [^\#x2D#x5B#x5D] * [22] XmlCharIncDash ::= [^\#x5B#x5D] */ static void xmlFAParseCharRange(xmlRegParserCtxtPtr ctxt) { int cur, len; int start = -1; int end = -1; if (CUR == '\0') { ERROR("Expecting ']'"); return; } cur = CUR; if (cur == '\\') { NEXT; cur = CUR; switch (cur) { case 'n': start = 0xA; break; case 'r': start = 0xD; break; case 't': start = 0x9; break; case '\\': case '|': case '.': case '-': case '^': case '?': case '*': case '+': case '{': case '}': case '(': case ')': case '[': case ']': start = cur; break; default: ERROR("Invalid escape value"); return; } end = start; len = 1; } else if ((cur != 0x5B) && (cur != 0x5D)) { end = start = CUR_SCHAR(ctxt->cur, len); } else { ERROR("Expecting a char range"); return; } /* * Since we are "inside" a range, we can assume ctxt->cur is past * the start of ctxt->string, and PREV should be safe */ if ((start == '-') && (NXT(1) != ']') && (PREV != '[') && (PREV != '^')) { NEXTL(len); return; } NEXTL(len); cur = CUR; if ((cur != '-') || (NXT(1) == ']')) { xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg, XML_REGEXP_CHARVAL, start, end, NULL); return; } NEXT; cur = CUR; if (cur == '\\') { NEXT; cur = CUR; switch (cur) { case 'n': end = 0xA; break; case 'r': end = 0xD; break; case 't': end = 0x9; break; case '\\': case '|': case '.': case '-': case '^': case '?': case '*': case '+': case '{': case '}': case '(': case ')': case '[': case ']': end = cur; break; default: ERROR("Invalid escape value"); return; } len = 1; } else if ((cur != '\0') && (cur != 0x5B) && (cur != 0x5D)) { end = CUR_SCHAR(ctxt->cur, len); } else { ERROR("Expecting the end of a char range"); return; } /* TODO check that the values are acceptable character ranges for XML */ if (end < start) { ERROR("End of range is before start of range"); } else { NEXTL(len); xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg, XML_REGEXP_CHARVAL, start, end, NULL); } return; } /** * xmlFAParsePosCharGroup: * @ctxt: a regexp parser context * * [14] posCharGroup ::= ( charRange | charClassEsc )+ */ static void xmlFAParsePosCharGroup(xmlRegParserCtxtPtr ctxt) { do { if (CUR == '\\') { xmlFAParseCharClassEsc(ctxt); } else { xmlFAParseCharRange(ctxt); } } while ((CUR != ']') && (CUR != '-') && (CUR != 0) && (ctxt->error == 0)); } /** * xmlFAParseCharGroup: * @ctxt: a regexp parser context * * [13] charGroup ::= posCharGroup | negCharGroup | charClassSub * [15] negCharGroup ::= '^' posCharGroup * [16] charClassSub ::= ( posCharGroup | negCharGroup ) '-' charClassExpr * [12] charClassExpr ::= '[' charGroup ']' */ static void xmlFAParseCharGroup(xmlRegParserCtxtPtr ctxt) { int neg = ctxt->neg; if (CUR == '^') { NEXT; ctxt->neg = !ctxt->neg; xmlFAParsePosCharGroup(ctxt); ctxt->neg = neg; } while ((CUR != ']') && (ctxt->error == 0)) { if ((CUR == '-') && (NXT(1) == '[')) { NEXT; /* eat the '-' */ NEXT; /* eat the '[' */ ctxt->neg = 2; xmlFAParseCharGroup(ctxt); ctxt->neg = neg; if (CUR == ']') { NEXT; } else { ERROR("charClassExpr: ']' expected"); } break; } else { xmlFAParsePosCharGroup(ctxt); } } } /** * xmlFAParseCharClass: * @ctxt: a regexp parser context * * [11] charClass ::= charClassEsc | charClassExpr * [12] charClassExpr ::= '[' charGroup ']' */ static void xmlFAParseCharClass(xmlRegParserCtxtPtr ctxt) { if (CUR == '[') { NEXT; ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_RANGES); if (ctxt->atom == NULL) return; xmlFAParseCharGroup(ctxt); if (CUR == ']') { NEXT; } else { ERROR("xmlFAParseCharClass: ']' expected"); } } else { xmlFAParseCharClassEsc(ctxt); } } /** * xmlFAParseQuantExact: * @ctxt: a regexp parser context * * [8] QuantExact ::= [0-9]+ * * Returns 0 if success or -1 in case of error */ static int xmlFAParseQuantExact(xmlRegParserCtxtPtr ctxt) { int ret = 0; int ok = 0; int overflow = 0; while ((CUR >= '0') && (CUR <= '9')) { if (ret > INT_MAX / 10) { overflow = 1; } else { int digit = CUR - '0'; ret *= 10; if (ret > INT_MAX - digit) overflow = 1; else ret += digit; } ok = 1; NEXT; } if ((ok != 1) || (overflow == 1)) { return(-1); } return(ret); } /** * xmlFAParseQuantifier: * @ctxt: a regexp parser context * * [4] quantifier ::= [?*+] | ( '{' quantity '}' ) * [5] quantity ::= quantRange | quantMin | QuantExact * [6] quantRange ::= QuantExact ',' QuantExact * [7] quantMin ::= QuantExact ',' * [8] QuantExact ::= [0-9]+ */ static int xmlFAParseQuantifier(xmlRegParserCtxtPtr ctxt) { int cur; cur = CUR; if ((cur == '?') || (cur == '*') || (cur == '+')) { if (ctxt->atom != NULL) { if (cur == '?') ctxt->atom->quant = XML_REGEXP_QUANT_OPT; else if (cur == '*') ctxt->atom->quant = XML_REGEXP_QUANT_MULT; else if (cur == '+') ctxt->atom->quant = XML_REGEXP_QUANT_PLUS; } NEXT; return(1); } if (cur == '{') { int min = 0, max = 0; NEXT; cur = xmlFAParseQuantExact(ctxt); if (cur >= 0) min = cur; else { ERROR("Improper quantifier"); } if (CUR == ',') { NEXT; if (CUR == '}') max = INT_MAX; else { cur = xmlFAParseQuantExact(ctxt); if (cur >= 0) max = cur; else { ERROR("Improper quantifier"); } } } if (CUR == '}') { NEXT; } else { ERROR("Unterminated quantifier"); } if (max == 0) max = min; if (ctxt->atom != NULL) { ctxt->atom->quant = XML_REGEXP_QUANT_RANGE; ctxt->atom->min = min; ctxt->atom->max = max; } return(1); } return(0); } /** * xmlFAParseAtom: * @ctxt: a regexp parser context * * [9] atom ::= Char | charClass | ( '(' regExp ')' ) */ static int xmlFAParseAtom(xmlRegParserCtxtPtr ctxt) { int codepoint, len; codepoint = xmlFAIsChar(ctxt); if (codepoint > 0) { ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_CHARVAL); if (ctxt->atom == NULL) return(-1); codepoint = CUR_SCHAR(ctxt->cur, len); ctxt->atom->codepoint = codepoint; NEXTL(len); return(1); } else if (CUR == '|') { return(0); } else if (CUR == 0) { return(0); } else if (CUR == ')') { return(0); } else if (CUR == '(') { xmlRegStatePtr start, oldend, start0; NEXT; if (ctxt->depth >= 50) { ERROR("xmlFAParseAtom: maximum nesting depth exceeded"); return(-1); } /* * this extra Epsilon transition is needed if we count with 0 allowed * unfortunately this can't be known at that point */ xmlFAGenerateEpsilonTransition(ctxt, ctxt->state, NULL); start0 = ctxt->state; xmlFAGenerateEpsilonTransition(ctxt, ctxt->state, NULL); start = ctxt->state; oldend = ctxt->end; ctxt->end = NULL; ctxt->atom = NULL; ctxt->depth++; xmlFAParseRegExp(ctxt, 0); ctxt->depth--; if (CUR == ')') { NEXT; } else { ERROR("xmlFAParseAtom: expecting ')'"); } ctxt->atom = xmlRegNewAtom(ctxt, XML_REGEXP_SUBREG); if (ctxt->atom == NULL) return(-1); ctxt->atom->start = start; ctxt->atom->start0 = start0; ctxt->atom->stop = ctxt->state; ctxt->end = oldend; return(1); } else if ((CUR == '[') || (CUR == '\\') || (CUR == '.')) { xmlFAParseCharClass(ctxt); return(1); } return(0); } /** * xmlFAParsePiece: * @ctxt: a regexp parser context * * [3] piece ::= atom quantifier? */ static int xmlFAParsePiece(xmlRegParserCtxtPtr ctxt) { int ret; ctxt->atom = NULL; ret = xmlFAParseAtom(ctxt); if (ret == 0) return(0); if (ctxt->atom == NULL) { ERROR("internal: no atom generated"); } xmlFAParseQuantifier(ctxt); return(1); } /** * xmlFAParseBranch: * @ctxt: a regexp parser context * @to: optional target to the end of the branch * * @to is used to optimize by removing duplicate path in automata * in expressions like (a|b)(c|d) * * [2] branch ::= piece* */ static int xmlFAParseBranch(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr to) { xmlRegStatePtr previous; int ret; previous = ctxt->state; ret = xmlFAParsePiece(ctxt); if (ret == 0) { /* Empty branch */ xmlFAGenerateEpsilonTransition(ctxt, previous, to); } else { if (xmlFAGenerateTransitions(ctxt, previous, (CUR=='|' || CUR==')' || CUR==0) ? to : NULL, ctxt->atom) < 0) return(-1); previous = ctxt->state; ctxt->atom = NULL; } while ((ret != 0) && (ctxt->error == 0)) { ret = xmlFAParsePiece(ctxt); if (ret != 0) { if (xmlFAGenerateTransitions(ctxt, previous, (CUR=='|' || CUR==')' || CUR==0) ? to : NULL, ctxt->atom) < 0) return(-1); previous = ctxt->state; ctxt->atom = NULL; } } return(0); } /** * xmlFAParseRegExp: * @ctxt: a regexp parser context * @top: is this the top-level expression ? * * [1] regExp ::= branch ( '|' branch )* */ static void xmlFAParseRegExp(xmlRegParserCtxtPtr ctxt, int top) { xmlRegStatePtr start, end; /* if not top start should have been generated by an epsilon trans */ start = ctxt->state; ctxt->end = NULL; xmlFAParseBranch(ctxt, NULL); if (top) { #ifdef DEBUG_REGEXP_GRAPH printf("State %d is final\n", ctxt->state->no); #endif ctxt->state->type = XML_REGEXP_FINAL_STATE; } if (CUR != '|') { ctxt->end = ctxt->state; return; } end = ctxt->state; while ((CUR == '|') && (ctxt->error == 0)) { NEXT; ctxt->state = start; ctxt->end = NULL; xmlFAParseBranch(ctxt, end); } if (!top) { ctxt->state = end; ctxt->end = end; } } /************************************************************************ * * * The basic API * * * ************************************************************************/ /** * xmlRegexpPrint: * @output: the file for the output debug * @regexp: the compiled regexp * * Print the content of the compiled regular expression */ void xmlRegexpPrint(FILE *output, xmlRegexpPtr regexp) { int i; if (output == NULL) return; fprintf(output, " regexp: "); if (regexp == NULL) { fprintf(output, "NULL\n"); return; } fprintf(output, "'%s' ", regexp->string); fprintf(output, "\n"); fprintf(output, "%d atoms:\n", regexp->nbAtoms); for (i = 0;i < regexp->nbAtoms; i++) { fprintf(output, " %02d ", i); xmlRegPrintAtom(output, regexp->atoms[i]); } fprintf(output, "%d states:", regexp->nbStates); fprintf(output, "\n"); for (i = 0;i < regexp->nbStates; i++) { xmlRegPrintState(output, regexp->states[i]); } fprintf(output, "%d counters:\n", regexp->nbCounters); for (i = 0;i < regexp->nbCounters; i++) { fprintf(output, " %d: min %d max %d\n", i, regexp->counters[i].min, regexp->counters[i].max); } } /** * xmlRegexpCompile: * @regexp: a regular expression string * * Parses a regular expression conforming to XML Schemas Part 2 Datatype * Appendix F and builds an automata suitable for testing strings against * that regular expression * * Returns the compiled expression or NULL in case of error */ xmlRegexpPtr xmlRegexpCompile(const xmlChar *regexp) { xmlRegexpPtr ret; xmlRegParserCtxtPtr ctxt; ctxt = xmlRegNewParserCtxt(regexp); if (ctxt == NULL) return(NULL); /* initialize the parser */ ctxt->end = NULL; ctxt->start = ctxt->state = xmlRegNewState(ctxt); xmlRegStatePush(ctxt, ctxt->start); /* parse the expression building an automata */ xmlFAParseRegExp(ctxt, 1); if (CUR != 0) { ERROR("xmlFAParseRegExp: extra characters"); } if (ctxt->error != 0) { xmlRegFreeParserCtxt(ctxt); return(NULL); } ctxt->end = ctxt->state; ctxt->start->type = XML_REGEXP_START_STATE; ctxt->end->type = XML_REGEXP_FINAL_STATE; /* remove the Epsilon except for counted transitions */ xmlFAEliminateEpsilonTransitions(ctxt); if (ctxt->error != 0) { xmlRegFreeParserCtxt(ctxt); return(NULL); } ret = xmlRegEpxFromParse(ctxt); xmlRegFreeParserCtxt(ctxt); return(ret); } /** * xmlRegexpExec: * @comp: the compiled regular expression * @content: the value to check against the regular expression * * Check if the regular expression generates the value * * Returns 1 if it matches, 0 if not and a negative value in case of error */ int xmlRegexpExec(xmlRegexpPtr comp, const xmlChar *content) { if ((comp == NULL) || (content == NULL)) return(-1); return(xmlFARegExec(comp, content)); } /** * xmlRegexpIsDeterminist: * @comp: the compiled regular expression * * Check if the regular expression is determinist * * Returns 1 if it yes, 0 if not and a negative value in case of error */ int xmlRegexpIsDeterminist(xmlRegexpPtr comp) { xmlAutomataPtr am; int ret; if (comp == NULL) return(-1); if (comp->determinist != -1) return(comp->determinist); am = xmlNewAutomata(); if (am == NULL) return(-1); if (am->states != NULL) { int i; for (i = 0;i < am->nbStates;i++) xmlRegFreeState(am->states[i]); xmlFree(am->states); } am->nbAtoms = comp->nbAtoms; am->atoms = comp->atoms; am->nbStates = comp->nbStates; am->states = comp->states; am->determinist = -1; am->flags = comp->flags; ret = xmlFAComputesDeterminism(am); am->atoms = NULL; am->states = NULL; xmlFreeAutomata(am); comp->determinist = ret; return(ret); } /** * xmlRegFreeRegexp: * @regexp: the regexp * * Free a regexp */ void xmlRegFreeRegexp(xmlRegexpPtr regexp) { int i; if (regexp == NULL) return; if (regexp->string != NULL) xmlFree(regexp->string); if (regexp->states != NULL) { for (i = 0;i < regexp->nbStates;i++) xmlRegFreeState(regexp->states[i]); xmlFree(regexp->states); } if (regexp->atoms != NULL) { for (i = 0;i < regexp->nbAtoms;i++) xmlRegFreeAtom(regexp->atoms[i]); xmlFree(regexp->atoms); } if (regexp->counters != NULL) xmlFree(regexp->counters); if (regexp->compact != NULL) xmlFree(regexp->compact); if (regexp->transdata != NULL) xmlFree(regexp->transdata); if (regexp->stringMap != NULL) { for (i = 0; i < regexp->nbstrings;i++) xmlFree(regexp->stringMap[i]); xmlFree(regexp->stringMap); } xmlFree(regexp); } #ifdef LIBXML_AUTOMATA_ENABLED /************************************************************************ * * * The Automata interface * * * ************************************************************************/ /** * xmlNewAutomata: * * Create a new automata * * Returns the new object or NULL in case of failure */ xmlAutomataPtr xmlNewAutomata(void) { xmlAutomataPtr ctxt; ctxt = xmlRegNewParserCtxt(NULL); if (ctxt == NULL) return(NULL); /* initialize the parser */ ctxt->end = NULL; ctxt->start = ctxt->state = xmlRegNewState(ctxt); if (ctxt->start == NULL) { xmlFreeAutomata(ctxt); return(NULL); } ctxt->start->type = XML_REGEXP_START_STATE; if (xmlRegStatePush(ctxt, ctxt->start) < 0) { xmlRegFreeState(ctxt->start); xmlFreeAutomata(ctxt); return(NULL); } ctxt->flags = 0; return(ctxt); } /** * xmlFreeAutomata: * @am: an automata * * Free an automata */ void xmlFreeAutomata(xmlAutomataPtr am) { if (am == NULL) return; xmlRegFreeParserCtxt(am); } /** * xmlAutomataSetFlags: * @am: an automata * @flags: a set of internal flags * * Set some flags on the automata */ void xmlAutomataSetFlags(xmlAutomataPtr am, int flags) { if (am == NULL) return; am->flags |= flags; } /** * xmlAutomataGetInitState: * @am: an automata * * Initial state lookup * * Returns the initial state of the automata */ xmlAutomataStatePtr xmlAutomataGetInitState(xmlAutomataPtr am) { if (am == NULL) return(NULL); return(am->start); } /** * xmlAutomataSetFinalState: * @am: an automata * @state: a state in this automata * * Makes that state a final state * * Returns 0 or -1 in case of error */ int xmlAutomataSetFinalState(xmlAutomataPtr am, xmlAutomataStatePtr state) { if ((am == NULL) || (state == NULL)) return(-1); state->type = XML_REGEXP_FINAL_STATE; return(0); } /** * xmlAutomataNewTransition: * @am: an automata * @from: the starting point of the transition * @to: the target point of the transition or NULL * @token: the input string associated to that transition * @data: data passed to the callback function if the transition is activated * * If @to is NULL, this creates first a new target state in the automata * and then adds a transition from the @from state to the target state * activated by the value of @token * * Returns the target state or NULL in case of error */ xmlAutomataStatePtr xmlAutomataNewTransition(xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, void *data) { xmlRegAtomPtr atom; if ((am == NULL) || (from == NULL) || (token == NULL)) return(NULL); atom = xmlRegNewAtom(am, XML_REGEXP_STRING); if (atom == NULL) return(NULL); atom->data = data; atom->valuep = xmlStrdup(token); if (xmlFAGenerateTransitions(am, from, to, atom) < 0) { xmlRegFreeAtom(atom); return(NULL); } if (to == NULL) return(am->state); return(to); } /** * xmlAutomataNewTransition2: * @am: an automata * @from: the starting point of the transition * @to: the target point of the transition or NULL * @token: the first input string associated to that transition * @token2: the second input string associated to that transition * @data: data passed to the callback function if the transition is activated * * If @to is NULL, this creates first a new target state in the automata * and then adds a transition from the @from state to the target state * activated by the value of @token * * Returns the target state or NULL in case of error */ xmlAutomataStatePtr xmlAutomataNewTransition2(xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, const xmlChar *token2, void *data) { xmlRegAtomPtr atom; if ((am == NULL) || (from == NULL) || (token == NULL)) return(NULL); atom = xmlRegNewAtom(am, XML_REGEXP_STRING); if (atom == NULL) return(NULL); atom->data = data; if ((token2 == NULL) || (*token2 == 0)) { atom->valuep = xmlStrdup(token); } else { int lenn, lenp; xmlChar *str; lenn = strlen((char *) token2); lenp = strlen((char *) token); str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2); if (str == NULL) { xmlRegFreeAtom(atom); return(NULL); } memcpy(&str[0], token, lenp); str[lenp] = '|'; memcpy(&str[lenp + 1], token2, lenn); str[lenn + lenp + 1] = 0; atom->valuep = str; } if (xmlFAGenerateTransitions(am, from, to, atom) < 0) { xmlRegFreeAtom(atom); return(NULL); } if (to == NULL) return(am->state); return(to); } /** * xmlAutomataNewNegTrans: * @am: an automata * @from: the starting point of the transition * @to: the target point of the transition or NULL * @token: the first input string associated to that transition * @token2: the second input string associated to that transition * @data: data passed to the callback function if the transition is activated * * If @to is NULL, this creates first a new target state in the automata * and then adds a transition from the @from state to the target state * activated by any value except (@token,@token2) * Note that if @token2 is not NULL, then (X, NULL) won't match to follow # the semantic of XSD ##other * * Returns the target state or NULL in case of error */ xmlAutomataStatePtr xmlAutomataNewNegTrans(xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, const xmlChar *token2, void *data) { xmlRegAtomPtr atom; xmlChar err_msg[200]; if ((am == NULL) || (from == NULL) || (token == NULL)) return(NULL); atom = xmlRegNewAtom(am, XML_REGEXP_STRING); if (atom == NULL) return(NULL); atom->data = data; atom->neg = 1; if ((token2 == NULL) || (*token2 == 0)) { atom->valuep = xmlStrdup(token); } else { int lenn, lenp; xmlChar *str; lenn = strlen((char *) token2); lenp = strlen((char *) token); str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2); if (str == NULL) { xmlRegFreeAtom(atom); return(NULL); } memcpy(&str[0], token, lenp); str[lenp] = '|'; memcpy(&str[lenp + 1], token2, lenn); str[lenn + lenp + 1] = 0; atom->valuep = str; } snprintf((char *) err_msg, 199, "not %s", (const char *) atom->valuep); err_msg[199] = 0; atom->valuep2 = xmlStrdup(err_msg); if (xmlFAGenerateTransitions(am, from, to, atom) < 0) { xmlRegFreeAtom(atom); return(NULL); } am->negs++; if (to == NULL) return(am->state); return(to); } /** * xmlAutomataNewCountTrans2: * @am: an automata * @from: the starting point of the transition * @to: the target point of the transition or NULL * @token: the input string associated to that transition * @token2: the second input string associated to that transition * @min: the minimum successive occurrences of token * @max: the maximum successive occurrences of token * @data: data associated to the transition * * If @to is NULL, this creates first a new target state in the automata * and then adds a transition from the @from state to the target state * activated by a succession of input of value @token and @token2 and * whose number is between @min and @max * * Returns the target state or NULL in case of error */ xmlAutomataStatePtr xmlAutomataNewCountTrans2(xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, const xmlChar *token2, int min, int max, void *data) { xmlRegAtomPtr atom; int counter; if ((am == NULL) || (from == NULL) || (token == NULL)) return(NULL); if (min < 0) return(NULL); if ((max < min) || (max < 1)) return(NULL); atom = xmlRegNewAtom(am, XML_REGEXP_STRING); if (atom == NULL) return(NULL); if ((token2 == NULL) || (*token2 == 0)) { atom->valuep = xmlStrdup(token); } else { int lenn, lenp; xmlChar *str; lenn = strlen((char *) token2); lenp = strlen((char *) token); str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2); if (str == NULL) { xmlRegFreeAtom(atom); return(NULL); } memcpy(&str[0], token, lenp); str[lenp] = '|'; memcpy(&str[lenp + 1], token2, lenn); str[lenn + lenp + 1] = 0; atom->valuep = str; } atom->data = data; if (min == 0) atom->min = 1; else atom->min = min; atom->max = max; /* * associate a counter to the transition. */ counter = xmlRegGetCounter(am); am->counters[counter].min = min; am->counters[counter].max = max; /* xmlFAGenerateTransitions(am, from, to, atom); */ if (to == NULL) { to = xmlRegNewState(am); xmlRegStatePush(am, to); } xmlRegStateAddTrans(am, from, atom, to, counter, -1); xmlRegAtomPush(am, atom); am->state = to; if (to == NULL) to = am->state; if (to == NULL) return(NULL); if (min == 0) xmlFAGenerateEpsilonTransition(am, from, to); return(to); } /** * xmlAutomataNewCountTrans: * @am: an automata * @from: the starting point of the transition * @to: the target point of the transition or NULL * @token: the input string associated to that transition * @min: the minimum successive occurrences of token * @max: the maximum successive occurrences of token * @data: data associated to the transition * * If @to is NULL, this creates first a new target state in the automata * and then adds a transition from the @from state to the target state * activated by a succession of input of value @token and whose number * is between @min and @max * * Returns the target state or NULL in case of error */ xmlAutomataStatePtr xmlAutomataNewCountTrans(xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, int min, int max, void *data) { xmlRegAtomPtr atom; int counter; if ((am == NULL) || (from == NULL) || (token == NULL)) return(NULL); if (min < 0) return(NULL); if ((max < min) || (max < 1)) return(NULL); atom = xmlRegNewAtom(am, XML_REGEXP_STRING); if (atom == NULL) return(NULL); atom->valuep = xmlStrdup(token); atom->data = data; if (min == 0) atom->min = 1; else atom->min = min; atom->max = max; /* * associate a counter to the transition. */ counter = xmlRegGetCounter(am); am->counters[counter].min = min; am->counters[counter].max = max; /* xmlFAGenerateTransitions(am, from, to, atom); */ if (to == NULL) { to = xmlRegNewState(am); xmlRegStatePush(am, to); } xmlRegStateAddTrans(am, from, atom, to, counter, -1); xmlRegAtomPush(am, atom); am->state = to; if (to == NULL) to = am->state; if (to == NULL) return(NULL); if (min == 0) xmlFAGenerateEpsilonTransition(am, from, to); return(to); } /** * xmlAutomataNewOnceTrans2: * @am: an automata * @from: the starting point of the transition * @to: the target point of the transition or NULL * @token: the input string associated to that transition * @token2: the second input string associated to that transition * @min: the minimum successive occurrences of token * @max: the maximum successive occurrences of token * @data: data associated to the transition * * If @to is NULL, this creates first a new target state in the automata * and then adds a transition from the @from state to the target state * activated by a succession of input of value @token and @token2 and whose * number is between @min and @max, moreover that transition can only be * crossed once. * * Returns the target state or NULL in case of error */ xmlAutomataStatePtr xmlAutomataNewOnceTrans2(xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, const xmlChar *token2, int min, int max, void *data) { xmlRegAtomPtr atom; int counter; if ((am == NULL) || (from == NULL) || (token == NULL)) return(NULL); if (min < 1) return(NULL); if (max < min) return(NULL); atom = xmlRegNewAtom(am, XML_REGEXP_STRING); if (atom == NULL) return(NULL); if ((token2 == NULL) || (*token2 == 0)) { atom->valuep = xmlStrdup(token); } else { int lenn, lenp; xmlChar *str; lenn = strlen((char *) token2); lenp = strlen((char *) token); str = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2); if (str == NULL) { xmlRegFreeAtom(atom); return(NULL); } memcpy(&str[0], token, lenp); str[lenp] = '|'; memcpy(&str[lenp + 1], token2, lenn); str[lenn + lenp + 1] = 0; atom->valuep = str; } atom->data = data; atom->quant = XML_REGEXP_QUANT_ONCEONLY; atom->min = min; atom->max = max; /* * associate a counter to the transition. */ counter = xmlRegGetCounter(am); am->counters[counter].min = 1; am->counters[counter].max = 1; /* xmlFAGenerateTransitions(am, from, to, atom); */ if (to == NULL) { to = xmlRegNewState(am); xmlRegStatePush(am, to); } xmlRegStateAddTrans(am, from, atom, to, counter, -1); xmlRegAtomPush(am, atom); am->state = to; return(to); } /** * xmlAutomataNewOnceTrans: * @am: an automata * @from: the starting point of the transition * @to: the target point of the transition or NULL * @token: the input string associated to that transition * @min: the minimum successive occurrences of token * @max: the maximum successive occurrences of token * @data: data associated to the transition * * If @to is NULL, this creates first a new target state in the automata * and then adds a transition from the @from state to the target state * activated by a succession of input of value @token and whose number * is between @min and @max, moreover that transition can only be crossed * once. * * Returns the target state or NULL in case of error */ xmlAutomataStatePtr xmlAutomataNewOnceTrans(xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, int min, int max, void *data) { xmlRegAtomPtr atom; int counter; if ((am == NULL) || (from == NULL) || (token == NULL)) return(NULL); if (min < 1) return(NULL); if (max < min) return(NULL); atom = xmlRegNewAtom(am, XML_REGEXP_STRING); if (atom == NULL) return(NULL); atom->valuep = xmlStrdup(token); atom->data = data; atom->quant = XML_REGEXP_QUANT_ONCEONLY; atom->min = min; atom->max = max; /* * associate a counter to the transition. */ counter = xmlRegGetCounter(am); am->counters[counter].min = 1; am->counters[counter].max = 1; /* xmlFAGenerateTransitions(am, from, to, atom); */ if (to == NULL) { to = xmlRegNewState(am); xmlRegStatePush(am, to); } xmlRegStateAddTrans(am, from, atom, to, counter, -1); xmlRegAtomPush(am, atom); am->state = to; return(to); } /** * xmlAutomataNewState: * @am: an automata * * Create a new disconnected state in the automata * * Returns the new state or NULL in case of error */ xmlAutomataStatePtr xmlAutomataNewState(xmlAutomataPtr am) { xmlAutomataStatePtr to; if (am == NULL) return(NULL); to = xmlRegNewState(am); xmlRegStatePush(am, to); return(to); } /** * xmlAutomataNewEpsilon: * @am: an automata * @from: the starting point of the transition * @to: the target point of the transition or NULL * * If @to is NULL, this creates first a new target state in the automata * and then adds an epsilon transition from the @from state to the * target state * * Returns the target state or NULL in case of error */ xmlAutomataStatePtr xmlAutomataNewEpsilon(xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to) { if ((am == NULL) || (from == NULL)) return(NULL); xmlFAGenerateEpsilonTransition(am, from, to); if (to == NULL) return(am->state); return(to); } /** * xmlAutomataNewAllTrans: * @am: an automata * @from: the starting point of the transition * @to: the target point of the transition or NULL * @lax: allow to transition if not all all transitions have been activated * * If @to is NULL, this creates first a new target state in the automata * and then adds a an ALL transition from the @from state to the * target state. That transition is an epsilon transition allowed only when * all transitions from the @from node have been activated. * * Returns the target state or NULL in case of error */ xmlAutomataStatePtr xmlAutomataNewAllTrans(xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, int lax) { if ((am == NULL) || (from == NULL)) return(NULL); xmlFAGenerateAllTransition(am, from, to, lax); if (to == NULL) return(am->state); return(to); } /** * xmlAutomataNewCounter: * @am: an automata * @min: the minimal value on the counter * @max: the maximal value on the counter * * Create a new counter * * Returns the counter number or -1 in case of error */ int xmlAutomataNewCounter(xmlAutomataPtr am, int min, int max) { int ret; if (am == NULL) return(-1); ret = xmlRegGetCounter(am); if (ret < 0) return(-1); am->counters[ret].min = min; am->counters[ret].max = max; return(ret); } /** * xmlAutomataNewCountedTrans: * @am: an automata * @from: the starting point of the transition * @to: the target point of the transition or NULL * @counter: the counter associated to that transition * * If @to is NULL, this creates first a new target state in the automata * and then adds an epsilon transition from the @from state to the target state * which will increment the counter provided * * Returns the target state or NULL in case of error */ xmlAutomataStatePtr xmlAutomataNewCountedTrans(xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, int counter) { if ((am == NULL) || (from == NULL) || (counter < 0)) return(NULL); xmlFAGenerateCountedEpsilonTransition(am, from, to, counter); if (to == NULL) return(am->state); return(to); } /** * xmlAutomataNewCounterTrans: * @am: an automata * @from: the starting point of the transition * @to: the target point of the transition or NULL * @counter: the counter associated to that transition * * If @to is NULL, this creates first a new target state in the automata * and then adds an epsilon transition from the @from state to the target state * which will be allowed only if the counter is within the right range. * * Returns the target state or NULL in case of error */ xmlAutomataStatePtr xmlAutomataNewCounterTrans(xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, int counter) { if ((am == NULL) || (from == NULL) || (counter < 0)) return(NULL); xmlFAGenerateCountedTransition(am, from, to, counter); if (to == NULL) return(am->state); return(to); } /** * xmlAutomataCompile: * @am: an automata * * Compile the automata into a Reg Exp ready for being executed. * The automata should be free after this point. * * Returns the compiled regexp or NULL in case of error */ xmlRegexpPtr xmlAutomataCompile(xmlAutomataPtr am) { xmlRegexpPtr ret; if ((am == NULL) || (am->error != 0)) return(NULL); xmlFAEliminateEpsilonTransitions(am); /* xmlFAComputesDeterminism(am); */ ret = xmlRegEpxFromParse(am); return(ret); } /** * xmlAutomataIsDeterminist: * @am: an automata * * Checks if an automata is determinist. * * Returns 1 if true, 0 if not, and -1 in case of error */ int xmlAutomataIsDeterminist(xmlAutomataPtr am) { int ret; if (am == NULL) return(-1); ret = xmlFAComputesDeterminism(am); return(ret); } #endif /* LIBXML_AUTOMATA_ENABLED */ #ifdef LIBXML_EXPR_ENABLED /************************************************************************ * * * Formal Expression handling code * * * ************************************************************************/ /************************************************************************ * * * Expression handling context * * * ************************************************************************/ struct _xmlExpCtxt { xmlDictPtr dict; xmlExpNodePtr *table; int size; int nbElems; int nb_nodes; int maxNodes; const char *expr; const char *cur; int nb_cons; int tabSize; }; /** * xmlExpNewCtxt: * @maxNodes: the maximum number of nodes * @dict: optional dictionary to use internally * * Creates a new context for manipulating expressions * * Returns the context or NULL in case of error */ xmlExpCtxtPtr xmlExpNewCtxt(int maxNodes, xmlDictPtr dict) { xmlExpCtxtPtr ret; int size = 256; if (maxNodes <= 4096) maxNodes = 4096; ret = (xmlExpCtxtPtr) xmlMalloc(sizeof(xmlExpCtxt)); if (ret == NULL) return(NULL); memset(ret, 0, sizeof(xmlExpCtxt)); ret->size = size; ret->nbElems = 0; ret->maxNodes = maxNodes; ret->table = xmlMalloc(size * sizeof(xmlExpNodePtr)); if (ret->table == NULL) { xmlFree(ret); return(NULL); } memset(ret->table, 0, size * sizeof(xmlExpNodePtr)); if (dict == NULL) { ret->dict = xmlDictCreate(); if (ret->dict == NULL) { xmlFree(ret->table); xmlFree(ret); return(NULL); } } else { ret->dict = dict; xmlDictReference(ret->dict); } return(ret); } /** * xmlExpFreeCtxt: * @ctxt: an expression context * * Free an expression context */ void xmlExpFreeCtxt(xmlExpCtxtPtr ctxt) { if (ctxt == NULL) return; xmlDictFree(ctxt->dict); if (ctxt->table != NULL) xmlFree(ctxt->table); xmlFree(ctxt); } /************************************************************************ * * * Structure associated to an expression node * * * ************************************************************************/ #define MAX_NODES 10000 /* #define DEBUG_DERIV */ /* * TODO: * - Wildcards * - public API for creation * * Started * - regression testing * * Done * - split into module and test tool * - memleaks */ typedef enum { XML_EXP_NILABLE = (1 << 0) } xmlExpNodeInfo; #define IS_NILLABLE(node) ((node)->info & XML_EXP_NILABLE) struct _xmlExpNode { unsigned char type;/* xmlExpNodeType */ unsigned char info;/* OR of xmlExpNodeInfo */ unsigned short key; /* the hash key */ unsigned int ref; /* The number of references */ int c_max; /* the maximum length it can consume */ xmlExpNodePtr exp_left; xmlExpNodePtr next;/* the next node in the hash table or free list */ union { struct { int f_min; int f_max; } count; struct { xmlExpNodePtr f_right; } children; const xmlChar *f_str; } field; }; #define exp_min field.count.f_min #define exp_max field.count.f_max /* #define exp_left field.children.f_left */ #define exp_right field.children.f_right #define exp_str field.f_str static xmlExpNodePtr xmlExpNewNode(xmlExpCtxtPtr ctxt, xmlExpNodeType type); static xmlExpNode forbiddenExpNode = { XML_EXP_FORBID, 0, 0, 0, 0, NULL, NULL, {{ 0, 0}} }; xmlExpNodePtr forbiddenExp = &forbiddenExpNode; static xmlExpNode emptyExpNode = { XML_EXP_EMPTY, 1, 0, 0, 0, NULL, NULL, {{ 0, 0}} }; xmlExpNodePtr emptyExp = &emptyExpNode; /************************************************************************ * * * The custom hash table for unicity and canonicalization * * of sub-expressions pointers * * * ************************************************************************/ /* * xmlExpHashNameComputeKey: * Calculate the hash key for a token */ static unsigned short xmlExpHashNameComputeKey(const xmlChar *name) { unsigned short value = 0L; char ch; if (name != NULL) { value += 30 * (*name); while ((ch = *name++) != 0) { value = value ^ ((value << 5) + (value >> 3) + (unsigned long)ch); } } return (value); } /* * xmlExpHashComputeKey: * Calculate the hash key for a compound expression */ static unsigned short xmlExpHashComputeKey(xmlExpNodeType type, xmlExpNodePtr left, xmlExpNodePtr right) { unsigned long value; unsigned short ret; switch (type) { case XML_EXP_SEQ: value = left->key; value += right->key; value *= 3; ret = (unsigned short) value; break; case XML_EXP_OR: value = left->key; value += right->key; value *= 7; ret = (unsigned short) value; break; case XML_EXP_COUNT: value = left->key; value += right->key; ret = (unsigned short) value; break; default: ret = 0; } return(ret); } static xmlExpNodePtr xmlExpNewNode(xmlExpCtxtPtr ctxt, xmlExpNodeType type) { xmlExpNodePtr ret; if (ctxt->nb_nodes >= MAX_NODES) return(NULL); ret = (xmlExpNodePtr) xmlMalloc(sizeof(xmlExpNode)); if (ret == NULL) return(NULL); memset(ret, 0, sizeof(xmlExpNode)); ret->type = type; ret->next = NULL; ctxt->nb_nodes++; ctxt->nb_cons++; return(ret); } /** * xmlExpHashGetEntry: * @table: the hash table * * Get the unique entry from the hash table. The entry is created if * needed. @left and @right are consumed, i.e. their ref count will * be decremented by the operation. * * Returns the pointer or NULL in case of error */ static xmlExpNodePtr xmlExpHashGetEntry(xmlExpCtxtPtr ctxt, xmlExpNodeType type, xmlExpNodePtr left, xmlExpNodePtr right, const xmlChar *name, int min, int max) { unsigned short kbase, key; xmlExpNodePtr entry; xmlExpNodePtr insert; if (ctxt == NULL) return(NULL); /* * Check for duplicate and insertion location. */ if (type == XML_EXP_ATOM) { kbase = xmlExpHashNameComputeKey(name); } else if (type == XML_EXP_COUNT) { /* COUNT reduction rule 1 */ /* a{1} -> a */ if (min == max) { if (min == 1) { return(left); } if (min == 0) { xmlExpFree(ctxt, left); return(emptyExp); } } if (min < 0) { xmlExpFree(ctxt, left); return(forbiddenExp); } if (max == -1) kbase = min + 79; else kbase = max - min; kbase += left->key; } else if (type == XML_EXP_OR) { /* Forbid reduction rules */ if (left->type == XML_EXP_FORBID) { xmlExpFree(ctxt, left); return(right); } if (right->type == XML_EXP_FORBID) { xmlExpFree(ctxt, right); return(left); } /* OR reduction rule 1 */ /* a | a reduced to a */ if (left == right) { xmlExpFree(ctxt, right); return(left); } /* OR canonicalization rule 1 */ /* linearize (a | b) | c into a | (b | c) */ if ((left->type == XML_EXP_OR) && (right->type != XML_EXP_OR)) { xmlExpNodePtr tmp = left; left = right; right = tmp; } /* OR reduction rule 2 */ /* a | (a | b) and b | (a | b) are reduced to a | b */ if (right->type == XML_EXP_OR) { if ((left == right->exp_left) || (left == right->exp_right)) { xmlExpFree(ctxt, left); return(right); } } /* OR canonicalization rule 2 */ /* linearize (a | b) | c into a | (b | c) */ if (left->type == XML_EXP_OR) { xmlExpNodePtr tmp; /* OR canonicalization rule 2 */ if ((left->exp_right->type != XML_EXP_OR) && (left->exp_right->key < left->exp_left->key)) { tmp = left->exp_right; left->exp_right = left->exp_left; left->exp_left = tmp; } left->exp_right->ref++; tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, left->exp_right, right, NULL, 0, 0); left->exp_left->ref++; tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, left->exp_left, tmp, NULL, 0, 0); xmlExpFree(ctxt, left); return(tmp); } if (right->type == XML_EXP_OR) { /* Ordering in the tree */ /* C | (A | B) -> A | (B | C) */ if (left->key > right->exp_right->key) { xmlExpNodePtr tmp; right->exp_right->ref++; tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, right->exp_right, left, NULL, 0, 0); right->exp_left->ref++; tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, right->exp_left, tmp, NULL, 0, 0); xmlExpFree(ctxt, right); return(tmp); } /* Ordering in the tree */ /* B | (A | C) -> A | (B | C) */ if (left->key > right->exp_left->key) { xmlExpNodePtr tmp; right->exp_right->ref++; tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, left, right->exp_right, NULL, 0, 0); right->exp_left->ref++; tmp = xmlExpHashGetEntry(ctxt, XML_EXP_OR, right->exp_left, tmp, NULL, 0, 0); xmlExpFree(ctxt, right); return(tmp); } } /* we know both types are != XML_EXP_OR here */ else if (left->key > right->key) { xmlExpNodePtr tmp = left; left = right; right = tmp; } kbase = xmlExpHashComputeKey(type, left, right); } else if (type == XML_EXP_SEQ) { /* Forbid reduction rules */ if (left->type == XML_EXP_FORBID) { xmlExpFree(ctxt, right); return(left); } if (right->type == XML_EXP_FORBID) { xmlExpFree(ctxt, left); return(right); } /* Empty reduction rules */ if (right->type == XML_EXP_EMPTY) { return(left); } if (left->type == XML_EXP_EMPTY) { return(right); } kbase = xmlExpHashComputeKey(type, left, right); } else return(NULL); key = kbase % ctxt->size; if (ctxt->table[key] != NULL) { for (insert = ctxt->table[key]; insert != NULL; insert = insert->next) { if ((insert->key == kbase) && (insert->type == type)) { if (type == XML_EXP_ATOM) { if (name == insert->exp_str) { insert->ref++; return(insert); } } else if (type == XML_EXP_COUNT) { if ((insert->exp_min == min) && (insert->exp_max == max) && (insert->exp_left == left)) { insert->ref++; left->ref--; return(insert); } } else if ((insert->exp_left == left) && (insert->exp_right == right)) { insert->ref++; left->ref--; right->ref--; return(insert); } } } } entry = xmlExpNewNode(ctxt, type); if (entry == NULL) return(NULL); entry->key = kbase; if (type == XML_EXP_ATOM) { entry->exp_str = name; entry->c_max = 1; } else if (type == XML_EXP_COUNT) { entry->exp_min = min; entry->exp_max = max; entry->exp_left = left; if ((min == 0) || (IS_NILLABLE(left))) entry->info |= XML_EXP_NILABLE; if (max < 0) entry->c_max = -1; else entry->c_max = max * entry->exp_left->c_max; } else { entry->exp_left = left; entry->exp_right = right; if (type == XML_EXP_OR) { if ((IS_NILLABLE(left)) || (IS_NILLABLE(right))) entry->info |= XML_EXP_NILABLE; if ((entry->exp_left->c_max == -1) || (entry->exp_right->c_max == -1)) entry->c_max = -1; else if (entry->exp_left->c_max > entry->exp_right->c_max) entry->c_max = entry->exp_left->c_max; else entry->c_max = entry->exp_right->c_max; } else { if ((IS_NILLABLE(left)) && (IS_NILLABLE(right))) entry->info |= XML_EXP_NILABLE; if ((entry->exp_left->c_max == -1) || (entry->exp_right->c_max == -1)) entry->c_max = -1; else entry->c_max = entry->exp_left->c_max + entry->exp_right->c_max; } } entry->ref = 1; if (ctxt->table[key] != NULL) entry->next = ctxt->table[key]; ctxt->table[key] = entry; ctxt->nbElems++; return(entry); } /** * xmlExpFree: * @ctxt: the expression context * @exp: the expression * * Dereference the expression */ void xmlExpFree(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp) { if ((exp == NULL) || (exp == forbiddenExp) || (exp == emptyExp)) return; exp->ref--; if (exp->ref == 0) { unsigned short key; /* Unlink it first from the hash table */ key = exp->key % ctxt->size; if (ctxt->table[key] == exp) { ctxt->table[key] = exp->next; } else { xmlExpNodePtr tmp; tmp = ctxt->table[key]; while (tmp != NULL) { if (tmp->next == exp) { tmp->next = exp->next; break; } tmp = tmp->next; } } if ((exp->type == XML_EXP_SEQ) || (exp->type == XML_EXP_OR)) { xmlExpFree(ctxt, exp->exp_left); xmlExpFree(ctxt, exp->exp_right); } else if (exp->type == XML_EXP_COUNT) { xmlExpFree(ctxt, exp->exp_left); } xmlFree(exp); ctxt->nb_nodes--; } } /** * xmlExpRef: * @exp: the expression * * Increase the reference count of the expression */ void xmlExpRef(xmlExpNodePtr exp) { if (exp != NULL) exp->ref++; } /** * xmlExpNewAtom: * @ctxt: the expression context * @name: the atom name * @len: the atom name length in byte (or -1); * * Get the atom associated to this name from that context * * Returns the node or NULL in case of error */ xmlExpNodePtr xmlExpNewAtom(xmlExpCtxtPtr ctxt, const xmlChar *name, int len) { if ((ctxt == NULL) || (name == NULL)) return(NULL); name = xmlDictLookup(ctxt->dict, name, len); if (name == NULL) return(NULL); return(xmlExpHashGetEntry(ctxt, XML_EXP_ATOM, NULL, NULL, name, 0, 0)); } /** * xmlExpNewOr: * @ctxt: the expression context * @left: left expression * @right: right expression * * Get the atom associated to the choice @left | @right * Note that @left and @right are consumed in the operation, to keep * an handle on them use xmlExpRef() and use xmlExpFree() to release them, * this is true even in case of failure (unless ctxt == NULL). * * Returns the node or NULL in case of error */ xmlExpNodePtr xmlExpNewOr(xmlExpCtxtPtr ctxt, xmlExpNodePtr left, xmlExpNodePtr right) { if (ctxt == NULL) return(NULL); if ((left == NULL) || (right == NULL)) { xmlExpFree(ctxt, left); xmlExpFree(ctxt, right); return(NULL); } return(xmlExpHashGetEntry(ctxt, XML_EXP_OR, left, right, NULL, 0, 0)); } /** * xmlExpNewSeq: * @ctxt: the expression context * @left: left expression * @right: right expression * * Get the atom associated to the sequence @left , @right * Note that @left and @right are consumed in the operation, to keep * an handle on them use xmlExpRef() and use xmlExpFree() to release them, * this is true even in case of failure (unless ctxt == NULL). * * Returns the node or NULL in case of error */ xmlExpNodePtr xmlExpNewSeq(xmlExpCtxtPtr ctxt, xmlExpNodePtr left, xmlExpNodePtr right) { if (ctxt == NULL) return(NULL); if ((left == NULL) || (right == NULL)) { xmlExpFree(ctxt, left); xmlExpFree(ctxt, right); return(NULL); } return(xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, left, right, NULL, 0, 0)); } /** * xmlExpNewRange: * @ctxt: the expression context * @subset: the expression to be repeated * @min: the lower bound for the repetition * @max: the upper bound for the repetition, -1 means infinite * * Get the atom associated to the range (@subset){@min, @max} * Note that @subset is consumed in the operation, to keep * an handle on it use xmlExpRef() and use xmlExpFree() to release it, * this is true even in case of failure (unless ctxt == NULL). * * Returns the node or NULL in case of error */ xmlExpNodePtr xmlExpNewRange(xmlExpCtxtPtr ctxt, xmlExpNodePtr subset, int min, int max) { if (ctxt == NULL) return(NULL); if ((subset == NULL) || (min < 0) || (max < -1) || ((max >= 0) && (min > max))) { xmlExpFree(ctxt, subset); return(NULL); } return(xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, subset, NULL, NULL, min, max)); } /************************************************************************ * * * Public API for operations on expressions * * * ************************************************************************/ static int xmlExpGetLanguageInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, const xmlChar**list, int len, int nb) { int tmp, tmp2; tail: switch (exp->type) { case XML_EXP_EMPTY: return(0); case XML_EXP_ATOM: for (tmp = 0;tmp < nb;tmp++) if (list[tmp] == exp->exp_str) return(0); if (nb >= len) return(-2); list[nb] = exp->exp_str; return(1); case XML_EXP_COUNT: exp = exp->exp_left; goto tail; case XML_EXP_SEQ: case XML_EXP_OR: tmp = xmlExpGetLanguageInt(ctxt, exp->exp_left, list, len, nb); if (tmp < 0) return(tmp); tmp2 = xmlExpGetLanguageInt(ctxt, exp->exp_right, list, len, nb + tmp); if (tmp2 < 0) return(tmp2); return(tmp + tmp2); } return(-1); } /** * xmlExpGetLanguage: * @ctxt: the expression context * @exp: the expression * @langList: where to store the tokens * @len: the allocated length of @list * * Find all the strings used in @exp and store them in @list * * Returns the number of unique strings found, -1 in case of errors and * -2 if there is more than @len strings */ int xmlExpGetLanguage(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, const xmlChar**langList, int len) { if ((ctxt == NULL) || (exp == NULL) || (langList == NULL) || (len <= 0)) return(-1); return(xmlExpGetLanguageInt(ctxt, exp, langList, len, 0)); } static int xmlExpGetStartInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, const xmlChar**list, int len, int nb) { int tmp, tmp2; tail: switch (exp->type) { case XML_EXP_FORBID: return(0); case XML_EXP_EMPTY: return(0); case XML_EXP_ATOM: for (tmp = 0;tmp < nb;tmp++) if (list[tmp] == exp->exp_str) return(0); if (nb >= len) return(-2); list[nb] = exp->exp_str; return(1); case XML_EXP_COUNT: exp = exp->exp_left; goto tail; case XML_EXP_SEQ: tmp = xmlExpGetStartInt(ctxt, exp->exp_left, list, len, nb); if (tmp < 0) return(tmp); if (IS_NILLABLE(exp->exp_left)) { tmp2 = xmlExpGetStartInt(ctxt, exp->exp_right, list, len, nb + tmp); if (tmp2 < 0) return(tmp2); tmp += tmp2; } return(tmp); case XML_EXP_OR: tmp = xmlExpGetStartInt(ctxt, exp->exp_left, list, len, nb); if (tmp < 0) return(tmp); tmp2 = xmlExpGetStartInt(ctxt, exp->exp_right, list, len, nb + tmp); if (tmp2 < 0) return(tmp2); return(tmp + tmp2); } return(-1); } /** * xmlExpGetStart: * @ctxt: the expression context * @exp: the expression * @tokList: where to store the tokens * @len: the allocated length of @list * * Find all the strings that appears at the start of the languages * accepted by @exp and store them in @list. E.g. for (a, b) | c * it will return the list [a, c] * * Returns the number of unique strings found, -1 in case of errors and * -2 if there is more than @len strings */ int xmlExpGetStart(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, const xmlChar**tokList, int len) { if ((ctxt == NULL) || (exp == NULL) || (tokList == NULL) || (len <= 0)) return(-1); return(xmlExpGetStartInt(ctxt, exp, tokList, len, 0)); } /** * xmlExpIsNillable: * @exp: the expression * * Finds if the expression is nillable, i.e. if it accepts the empty sequence * * Returns 1 if nillable, 0 if not and -1 in case of error */ int xmlExpIsNillable(xmlExpNodePtr exp) { if (exp == NULL) return(-1); return(IS_NILLABLE(exp) != 0); } static xmlExpNodePtr xmlExpStringDeriveInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, const xmlChar *str) { xmlExpNodePtr ret; switch (exp->type) { case XML_EXP_EMPTY: return(forbiddenExp); case XML_EXP_FORBID: return(forbiddenExp); case XML_EXP_ATOM: if (exp->exp_str == str) { #ifdef DEBUG_DERIV printf("deriv atom: equal => Empty\n"); #endif ret = emptyExp; } else { #ifdef DEBUG_DERIV printf("deriv atom: mismatch => forbid\n"); #endif /* TODO wildcards here */ ret = forbiddenExp; } return(ret); case XML_EXP_OR: { xmlExpNodePtr tmp; #ifdef DEBUG_DERIV printf("deriv or: => or(derivs)\n"); #endif tmp = xmlExpStringDeriveInt(ctxt, exp->exp_left, str); if (tmp == NULL) { return(NULL); } ret = xmlExpStringDeriveInt(ctxt, exp->exp_right, str); if (ret == NULL) { xmlExpFree(ctxt, tmp); return(NULL); } ret = xmlExpHashGetEntry(ctxt, XML_EXP_OR, tmp, ret, NULL, 0, 0); return(ret); } case XML_EXP_SEQ: #ifdef DEBUG_DERIV printf("deriv seq: starting with left\n"); #endif ret = xmlExpStringDeriveInt(ctxt, exp->exp_left, str); if (ret == NULL) { return(NULL); } else if (ret == forbiddenExp) { if (IS_NILLABLE(exp->exp_left)) { #ifdef DEBUG_DERIV printf("deriv seq: left failed but nillable\n"); #endif ret = xmlExpStringDeriveInt(ctxt, exp->exp_right, str); } } else { #ifdef DEBUG_DERIV printf("deriv seq: left match => sequence\n"); #endif exp->exp_right->ref++; ret = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret, exp->exp_right, NULL, 0, 0); } return(ret); case XML_EXP_COUNT: { int min, max; xmlExpNodePtr tmp; if (exp->exp_max == 0) return(forbiddenExp); ret = xmlExpStringDeriveInt(ctxt, exp->exp_left, str); if (ret == NULL) return(NULL); if (ret == forbiddenExp) { #ifdef DEBUG_DERIV printf("deriv count: pattern mismatch => forbid\n"); #endif return(ret); } if (exp->exp_max == 1) return(ret); if (exp->exp_max < 0) /* unbounded */ max = -1; else max = exp->exp_max - 1; if (exp->exp_min > 0) min = exp->exp_min - 1; else min = 0; exp->exp_left->ref++; tmp = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, exp->exp_left, NULL, NULL, min, max); if (ret == emptyExp) { #ifdef DEBUG_DERIV printf("deriv count: match to empty => new count\n"); #endif return(tmp); } #ifdef DEBUG_DERIV printf("deriv count: match => sequence with new count\n"); #endif return(xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret, tmp, NULL, 0, 0)); } } return(NULL); } /** * xmlExpStringDerive: * @ctxt: the expression context * @exp: the expression * @str: the string * @len: the string len in bytes if available * * Do one step of Brzozowski derivation of the expression @exp with * respect to the input string * * Returns the resulting expression or NULL in case of internal error */ xmlExpNodePtr xmlExpStringDerive(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, const xmlChar *str, int len) { const xmlChar *input; if ((exp == NULL) || (ctxt == NULL) || (str == NULL)) { return(NULL); } /* * check the string is in the dictionary, if yes use an interned * copy, otherwise we know it's not an acceptable input */ input = xmlDictExists(ctxt->dict, str, len); if (input == NULL) { return(forbiddenExp); } return(xmlExpStringDeriveInt(ctxt, exp, input)); } static int xmlExpCheckCard(xmlExpNodePtr exp, xmlExpNodePtr sub) { int ret = 1; if (sub->c_max == -1) { if (exp->c_max != -1) ret = 0; } else if ((exp->c_max >= 0) && (exp->c_max < sub->c_max)) { ret = 0; } #if 0 if ((IS_NILLABLE(sub)) && (!IS_NILLABLE(exp))) ret = 0; #endif return(ret); } static xmlExpNodePtr xmlExpExpDeriveInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub); /** * xmlExpDivide: * @ctxt: the expressions context * @exp: the englobing expression * @sub: the subexpression * @mult: the multiple expression * @remain: the remain from the derivation of the multiple * * Check if exp is a multiple of sub, i.e. if there is a finite number n * so that sub{n} subsume exp * * Returns the multiple value if successful, 0 if it is not a multiple * and -1 in case of internal error. */ static int xmlExpDivide(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub, xmlExpNodePtr *mult, xmlExpNodePtr *remain) { int i; xmlExpNodePtr tmp, tmp2; if (mult != NULL) *mult = NULL; if (remain != NULL) *remain = NULL; if (exp->c_max == -1) return(0); if (IS_NILLABLE(exp) && (!IS_NILLABLE(sub))) return(0); for (i = 1;i <= exp->c_max;i++) { sub->ref++; tmp = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, sub, NULL, NULL, i, i); if (tmp == NULL) { return(-1); } if (!xmlExpCheckCard(tmp, exp)) { xmlExpFree(ctxt, tmp); continue; } tmp2 = xmlExpExpDeriveInt(ctxt, tmp, exp); if (tmp2 == NULL) { xmlExpFree(ctxt, tmp); return(-1); } if ((tmp2 != forbiddenExp) && (IS_NILLABLE(tmp2))) { if (remain != NULL) *remain = tmp2; else xmlExpFree(ctxt, tmp2); if (mult != NULL) *mult = tmp; else xmlExpFree(ctxt, tmp); #ifdef DEBUG_DERIV printf("Divide succeeded %d\n", i); #endif return(i); } xmlExpFree(ctxt, tmp); xmlExpFree(ctxt, tmp2); } #ifdef DEBUG_DERIV printf("Divide failed\n"); #endif return(0); } /** * xmlExpExpDeriveInt: * @ctxt: the expressions context * @exp: the englobing expression * @sub: the subexpression * * Try to do a step of Brzozowski derivation but at a higher level * the input being a subexpression. * * Returns the resulting expression or NULL in case of internal error */ static xmlExpNodePtr xmlExpExpDeriveInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub) { xmlExpNodePtr ret, tmp, tmp2, tmp3; const xmlChar **tab; int len, i; /* * In case of equality and if the expression can only consume a finite * amount, then the derivation is empty */ if ((exp == sub) && (exp->c_max >= 0)) { #ifdef DEBUG_DERIV printf("Equal(exp, sub) and finite -> Empty\n"); #endif return(emptyExp); } /* * decompose sub sequence first */ if (sub->type == XML_EXP_EMPTY) { #ifdef DEBUG_DERIV printf("Empty(sub) -> Empty\n"); #endif exp->ref++; return(exp); } if (sub->type == XML_EXP_SEQ) { #ifdef DEBUG_DERIV printf("Seq(sub) -> decompose\n"); #endif tmp = xmlExpExpDeriveInt(ctxt, exp, sub->exp_left); if (tmp == NULL) return(NULL); if (tmp == forbiddenExp) return(tmp); ret = xmlExpExpDeriveInt(ctxt, tmp, sub->exp_right); xmlExpFree(ctxt, tmp); return(ret); } if (sub->type == XML_EXP_OR) { #ifdef DEBUG_DERIV printf("Or(sub) -> decompose\n"); #endif tmp = xmlExpExpDeriveInt(ctxt, exp, sub->exp_left); if (tmp == forbiddenExp) return(tmp); if (tmp == NULL) return(NULL); ret = xmlExpExpDeriveInt(ctxt, exp, sub->exp_right); if ((ret == NULL) || (ret == forbiddenExp)) { xmlExpFree(ctxt, tmp); return(ret); } return(xmlExpHashGetEntry(ctxt, XML_EXP_OR, tmp, ret, NULL, 0, 0)); } if (!xmlExpCheckCard(exp, sub)) { #ifdef DEBUG_DERIV printf("CheckCard(exp, sub) failed -> Forbid\n"); #endif return(forbiddenExp); } switch (exp->type) { case XML_EXP_EMPTY: if (sub == emptyExp) return(emptyExp); #ifdef DEBUG_DERIV printf("Empty(exp) -> Forbid\n"); #endif return(forbiddenExp); case XML_EXP_FORBID: #ifdef DEBUG_DERIV printf("Forbid(exp) -> Forbid\n"); #endif return(forbiddenExp); case XML_EXP_ATOM: if (sub->type == XML_EXP_ATOM) { /* TODO: handle wildcards */ if (exp->exp_str == sub->exp_str) { #ifdef DEBUG_DERIV printf("Atom match -> Empty\n"); #endif return(emptyExp); } #ifdef DEBUG_DERIV printf("Atom mismatch -> Forbid\n"); #endif return(forbiddenExp); } if ((sub->type == XML_EXP_COUNT) && (sub->exp_max == 1) && (sub->exp_left->type == XML_EXP_ATOM)) { /* TODO: handle wildcards */ if (exp->exp_str == sub->exp_left->exp_str) { #ifdef DEBUG_DERIV printf("Atom match -> Empty\n"); #endif return(emptyExp); } #ifdef DEBUG_DERIV printf("Atom mismatch -> Forbid\n"); #endif return(forbiddenExp); } #ifdef DEBUG_DERIV printf("Complex exp vs Atom -> Forbid\n"); #endif return(forbiddenExp); case XML_EXP_SEQ: /* try to get the sequence consumed only if possible */ if (xmlExpCheckCard(exp->exp_left, sub)) { /* See if the sequence can be consumed directly */ #ifdef DEBUG_DERIV printf("Seq trying left only\n"); #endif ret = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub); if ((ret != forbiddenExp) && (ret != NULL)) { #ifdef DEBUG_DERIV printf("Seq trying left only worked\n"); #endif /* * TODO: assumption here that we are determinist * i.e. we won't get to a nillable exp left * subset which could be matched by the right * part too. * e.g.: (a | b)+,(a | c) and 'a+,a' */ exp->exp_right->ref++; return(xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret, exp->exp_right, NULL, 0, 0)); } #ifdef DEBUG_DERIV } else { printf("Seq: left too short\n"); #endif } /* Try instead to decompose */ if (sub->type == XML_EXP_COUNT) { int min, max; #ifdef DEBUG_DERIV printf("Seq: sub is a count\n"); #endif ret = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub->exp_left); if (ret == NULL) return(NULL); if (ret != forbiddenExp) { #ifdef DEBUG_DERIV printf("Seq , Count match on left\n"); #endif if (sub->exp_max < 0) max = -1; else max = sub->exp_max -1; if (sub->exp_min > 0) min = sub->exp_min -1; else min = 0; exp->exp_right->ref++; tmp = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret, exp->exp_right, NULL, 0, 0); if (tmp == NULL) return(NULL); sub->exp_left->ref++; tmp2 = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, sub->exp_left, NULL, NULL, min, max); if (tmp2 == NULL) { xmlExpFree(ctxt, tmp); return(NULL); } ret = xmlExpExpDeriveInt(ctxt, tmp, tmp2); xmlExpFree(ctxt, tmp); xmlExpFree(ctxt, tmp2); return(ret); } } /* we made no progress on structured operations */ break; case XML_EXP_OR: #ifdef DEBUG_DERIV printf("Or , trying both side\n"); #endif ret = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub); if (ret == NULL) return(NULL); tmp = xmlExpExpDeriveInt(ctxt, exp->exp_right, sub); if (tmp == NULL) { xmlExpFree(ctxt, ret); return(NULL); } return(xmlExpHashGetEntry(ctxt, XML_EXP_OR, ret, tmp, NULL, 0, 0)); case XML_EXP_COUNT: { int min, max; if (sub->type == XML_EXP_COUNT) { /* * Try to see if the loop is completely subsumed */ tmp = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub->exp_left); if (tmp == NULL) return(NULL); if (tmp == forbiddenExp) { int mult; #ifdef DEBUG_DERIV printf("Count, Count inner don't subsume\n"); #endif mult = xmlExpDivide(ctxt, sub->exp_left, exp->exp_left, NULL, &tmp); if (mult <= 0) { #ifdef DEBUG_DERIV printf("Count, Count not multiple => forbidden\n"); #endif return(forbiddenExp); } if (sub->exp_max == -1) { max = -1; if (exp->exp_max == -1) { if (exp->exp_min <= sub->exp_min * mult) min = 0; else min = exp->exp_min - sub->exp_min * mult; } else { #ifdef DEBUG_DERIV printf("Count, Count finite can't subsume infinite\n"); #endif xmlExpFree(ctxt, tmp); return(forbiddenExp); } } else { if (exp->exp_max == -1) { #ifdef DEBUG_DERIV printf("Infinite loop consume mult finite loop\n"); #endif if (exp->exp_min > sub->exp_min * mult) { max = -1; min = exp->exp_min - sub->exp_min * mult; } else { max = -1; min = 0; } } else { if (exp->exp_max < sub->exp_max * mult) { #ifdef DEBUG_DERIV printf("loops max mult mismatch => forbidden\n"); #endif xmlExpFree(ctxt, tmp); return(forbiddenExp); } if (sub->exp_max * mult > exp->exp_min) min = 0; else min = exp->exp_min - sub->exp_max * mult; max = exp->exp_max - sub->exp_max * mult; } } } else if (!IS_NILLABLE(tmp)) { /* * TODO: loop here to try to grow if working on finite * blocks. */ #ifdef DEBUG_DERIV printf("Count, Count remain not nillable => forbidden\n"); #endif xmlExpFree(ctxt, tmp); return(forbiddenExp); } else if (sub->exp_max == -1) { if (exp->exp_max == -1) { if (exp->exp_min <= sub->exp_min) { #ifdef DEBUG_DERIV printf("Infinite loops Okay => COUNT(0,Inf)\n"); #endif max = -1; min = 0; } else { #ifdef DEBUG_DERIV printf("Infinite loops min => Count(X,Inf)\n"); #endif max = -1; min = exp->exp_min - sub->exp_min; } } else if (exp->exp_min > sub->exp_min) { #ifdef DEBUG_DERIV printf("loops min mismatch 1 => forbidden ???\n"); #endif xmlExpFree(ctxt, tmp); return(forbiddenExp); } else { max = -1; min = 0; } } else { if (exp->exp_max == -1) { #ifdef DEBUG_DERIV printf("Infinite loop consume finite loop\n"); #endif if (exp->exp_min > sub->exp_min) { max = -1; min = exp->exp_min - sub->exp_min; } else { max = -1; min = 0; } } else { if (exp->exp_max < sub->exp_max) { #ifdef DEBUG_DERIV printf("loops max mismatch => forbidden\n"); #endif xmlExpFree(ctxt, tmp); return(forbiddenExp); } if (sub->exp_max > exp->exp_min) min = 0; else min = exp->exp_min - sub->exp_max; max = exp->exp_max - sub->exp_max; } } #ifdef DEBUG_DERIV printf("loops match => SEQ(COUNT())\n"); #endif exp->exp_left->ref++; tmp2 = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, exp->exp_left, NULL, NULL, min, max); if (tmp2 == NULL) { return(NULL); } ret = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, tmp, tmp2, NULL, 0, 0); return(ret); } tmp = xmlExpExpDeriveInt(ctxt, exp->exp_left, sub); if (tmp == NULL) return(NULL); if (tmp == forbiddenExp) { #ifdef DEBUG_DERIV printf("loop mismatch => forbidden\n"); #endif return(forbiddenExp); } if (exp->exp_min > 0) min = exp->exp_min - 1; else min = 0; if (exp->exp_max < 0) max = -1; else max = exp->exp_max - 1; #ifdef DEBUG_DERIV printf("loop match => SEQ(COUNT())\n"); #endif exp->exp_left->ref++; tmp2 = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, exp->exp_left, NULL, NULL, min, max); if (tmp2 == NULL) return(NULL); ret = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, tmp, tmp2, NULL, 0, 0); return(ret); } } #ifdef DEBUG_DERIV printf("Fallback to derivative\n"); #endif if (IS_NILLABLE(sub)) { if (!(IS_NILLABLE(exp))) return(forbiddenExp); else ret = emptyExp; } else ret = NULL; /* * here the structured derivation made no progress so * we use the default token based derivation to force one more step */ if (ctxt->tabSize == 0) ctxt->tabSize = 40; tab = (const xmlChar **) xmlMalloc(ctxt->tabSize * sizeof(const xmlChar *)); if (tab == NULL) { return(NULL); } /* * collect all the strings accepted by the subexpression on input */ len = xmlExpGetStartInt(ctxt, sub, tab, ctxt->tabSize, 0); while (len < 0) { const xmlChar **temp; temp = (const xmlChar **) xmlRealloc((xmlChar **) tab, ctxt->tabSize * 2 * sizeof(const xmlChar *)); if (temp == NULL) { xmlFree((xmlChar **) tab); return(NULL); } tab = temp; ctxt->tabSize *= 2; len = xmlExpGetStartInt(ctxt, sub, tab, ctxt->tabSize, 0); } for (i = 0;i < len;i++) { tmp = xmlExpStringDeriveInt(ctxt, exp, tab[i]); if ((tmp == NULL) || (tmp == forbiddenExp)) { xmlExpFree(ctxt, ret); xmlFree((xmlChar **) tab); return(tmp); } tmp2 = xmlExpStringDeriveInt(ctxt, sub, tab[i]); if ((tmp2 == NULL) || (tmp2 == forbiddenExp)) { xmlExpFree(ctxt, tmp); xmlExpFree(ctxt, ret); xmlFree((xmlChar **) tab); return(tmp); } tmp3 = xmlExpExpDeriveInt(ctxt, tmp, tmp2); xmlExpFree(ctxt, tmp); xmlExpFree(ctxt, tmp2); if ((tmp3 == NULL) || (tmp3 == forbiddenExp)) { xmlExpFree(ctxt, ret); xmlFree((xmlChar **) tab); return(tmp3); } if (ret == NULL) ret = tmp3; else { ret = xmlExpHashGetEntry(ctxt, XML_EXP_OR, ret, tmp3, NULL, 0, 0); if (ret == NULL) { xmlFree((xmlChar **) tab); return(NULL); } } } xmlFree((xmlChar **) tab); return(ret); } /** * xmlExpExpDerive: * @ctxt: the expressions context * @exp: the englobing expression * @sub: the subexpression * * Evaluates the expression resulting from @exp consuming a sub expression @sub * Based on algebraic derivation and sometimes direct Brzozowski derivation * it usually takes less than linear time and can handle expressions generating * infinite languages. * * Returns the resulting expression or NULL in case of internal error, the * result must be freed */ xmlExpNodePtr xmlExpExpDerive(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub) { if ((exp == NULL) || (ctxt == NULL) || (sub == NULL)) return(NULL); /* * O(1) speedups */ if (IS_NILLABLE(sub) && (!IS_NILLABLE(exp))) { #ifdef DEBUG_DERIV printf("Sub nillable and not exp : can't subsume\n"); #endif return(forbiddenExp); } if (xmlExpCheckCard(exp, sub) == 0) { #ifdef DEBUG_DERIV printf("sub generate longer sequences than exp : can't subsume\n"); #endif return(forbiddenExp); } return(xmlExpExpDeriveInt(ctxt, exp, sub)); } /** * xmlExpSubsume: * @ctxt: the expressions context * @exp: the englobing expression * @sub: the subexpression * * Check whether @exp accepts all the languages accepted by @sub * the input being a subexpression. * * Returns 1 if true 0 if false and -1 in case of failure. */ int xmlExpSubsume(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub) { xmlExpNodePtr tmp; if ((exp == NULL) || (ctxt == NULL) || (sub == NULL)) return(-1); /* * TODO: speedup by checking the language of sub is a subset of the * language of exp */ /* * O(1) speedups */ if (IS_NILLABLE(sub) && (!IS_NILLABLE(exp))) { #ifdef DEBUG_DERIV printf("Sub nillable and not exp : can't subsume\n"); #endif return(0); } if (xmlExpCheckCard(exp, sub) == 0) { #ifdef DEBUG_DERIV printf("sub generate longer sequences than exp : can't subsume\n"); #endif return(0); } tmp = xmlExpExpDeriveInt(ctxt, exp, sub); #ifdef DEBUG_DERIV printf("Result derivation :\n"); PRINT_EXP(tmp); #endif if (tmp == NULL) return(-1); if (tmp == forbiddenExp) return(0); if (tmp == emptyExp) return(1); if ((tmp != NULL) && (IS_NILLABLE(tmp))) { xmlExpFree(ctxt, tmp); return(1); } xmlExpFree(ctxt, tmp); return(0); } /************************************************************************ * * * Parsing expression * * * ************************************************************************/ static xmlExpNodePtr xmlExpParseExpr(xmlExpCtxtPtr ctxt); #undef CUR #define CUR (*ctxt->cur) #undef NEXT #define NEXT ctxt->cur++; #undef IS_BLANK #define IS_BLANK(c) ((c == ' ') || (c == '\n') || (c == '\r') || (c == '\t')) #define SKIP_BLANKS while (IS_BLANK(*ctxt->cur)) ctxt->cur++; static int xmlExpParseNumber(xmlExpCtxtPtr ctxt) { int ret = 0; SKIP_BLANKS if (CUR == '*') { NEXT return(-1); } if ((CUR < '0') || (CUR > '9')) return(-1); while ((CUR >= '0') && (CUR <= '9')) { ret = ret * 10 + (CUR - '0'); NEXT } return(ret); } static xmlExpNodePtr xmlExpParseOr(xmlExpCtxtPtr ctxt) { const char *base; xmlExpNodePtr ret; const xmlChar *val; SKIP_BLANKS base = ctxt->cur; if (*ctxt->cur == '(') { NEXT ret = xmlExpParseExpr(ctxt); SKIP_BLANKS if (*ctxt->cur != ')') { fprintf(stderr, "unbalanced '(' : %s\n", base); xmlExpFree(ctxt, ret); return(NULL); } NEXT; SKIP_BLANKS goto parse_quantifier; } while ((CUR != 0) && (!(IS_BLANK(CUR))) && (CUR != '(') && (CUR != ')') && (CUR != '|') && (CUR != ',') && (CUR != '{') && (CUR != '*') && (CUR != '+') && (CUR != '?') && (CUR != '}')) NEXT; val = xmlDictLookup(ctxt->dict, BAD_CAST base, ctxt->cur - base); if (val == NULL) return(NULL); ret = xmlExpHashGetEntry(ctxt, XML_EXP_ATOM, NULL, NULL, val, 0, 0); if (ret == NULL) return(NULL); SKIP_BLANKS parse_quantifier: if (CUR == '{') { int min, max; NEXT min = xmlExpParseNumber(ctxt); if (min < 0) { xmlExpFree(ctxt, ret); return(NULL); } SKIP_BLANKS if (CUR == ',') { NEXT max = xmlExpParseNumber(ctxt); SKIP_BLANKS } else max = min; if (CUR != '}') { xmlExpFree(ctxt, ret); return(NULL); } NEXT ret = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, ret, NULL, NULL, min, max); SKIP_BLANKS } else if (CUR == '?') { NEXT ret = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, ret, NULL, NULL, 0, 1); SKIP_BLANKS } else if (CUR == '+') { NEXT ret = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, ret, NULL, NULL, 1, -1); SKIP_BLANKS } else if (CUR == '*') { NEXT ret = xmlExpHashGetEntry(ctxt, XML_EXP_COUNT, ret, NULL, NULL, 0, -1); SKIP_BLANKS } return(ret); } static xmlExpNodePtr xmlExpParseSeq(xmlExpCtxtPtr ctxt) { xmlExpNodePtr ret, right; ret = xmlExpParseOr(ctxt); SKIP_BLANKS while (CUR == '|') { NEXT right = xmlExpParseOr(ctxt); if (right == NULL) { xmlExpFree(ctxt, ret); return(NULL); } ret = xmlExpHashGetEntry(ctxt, XML_EXP_OR, ret, right, NULL, 0, 0); if (ret == NULL) return(NULL); } return(ret); } static xmlExpNodePtr xmlExpParseExpr(xmlExpCtxtPtr ctxt) { xmlExpNodePtr ret, right; ret = xmlExpParseSeq(ctxt); SKIP_BLANKS while (CUR == ',') { NEXT right = xmlExpParseSeq(ctxt); if (right == NULL) { xmlExpFree(ctxt, ret); return(NULL); } ret = xmlExpHashGetEntry(ctxt, XML_EXP_SEQ, ret, right, NULL, 0, 0); if (ret == NULL) return(NULL); } return(ret); } /** * xmlExpParse: * @ctxt: the expressions context * @expr: the 0 terminated string * * Minimal parser for regexps, it understand the following constructs * - string terminals * - choice operator | * - sequence operator , * - subexpressions (...) * - usual cardinality operators + * and ? * - finite sequences { min, max } * - infinite sequences { min, * } * There is minimal checkings made especially no checking on strings values * * Returns a new expression or NULL in case of failure */ xmlExpNodePtr xmlExpParse(xmlExpCtxtPtr ctxt, const char *expr) { xmlExpNodePtr ret; ctxt->expr = expr; ctxt->cur = expr; ret = xmlExpParseExpr(ctxt); SKIP_BLANKS if (*ctxt->cur != 0) { xmlExpFree(ctxt, ret); return(NULL); } return(ret); } static void xmlExpDumpInt(xmlBufferPtr buf, xmlExpNodePtr expr, int glob) { xmlExpNodePtr c; if (expr == NULL) return; if (glob) xmlBufferWriteChar(buf, "("); switch (expr->type) { case XML_EXP_EMPTY: xmlBufferWriteChar(buf, "empty"); break; case XML_EXP_FORBID: xmlBufferWriteChar(buf, "forbidden"); break; case XML_EXP_ATOM: xmlBufferWriteCHAR(buf, expr->exp_str); break; case XML_EXP_SEQ: c = expr->exp_left; if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR)) xmlExpDumpInt(buf, c, 1); else xmlExpDumpInt(buf, c, 0); xmlBufferWriteChar(buf, " , "); c = expr->exp_right; if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR)) xmlExpDumpInt(buf, c, 1); else xmlExpDumpInt(buf, c, 0); break; case XML_EXP_OR: c = expr->exp_left; if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR)) xmlExpDumpInt(buf, c, 1); else xmlExpDumpInt(buf, c, 0); xmlBufferWriteChar(buf, " | "); c = expr->exp_right; if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR)) xmlExpDumpInt(buf, c, 1); else xmlExpDumpInt(buf, c, 0); break; case XML_EXP_COUNT: { char rep[40]; c = expr->exp_left; if ((c->type == XML_EXP_SEQ) || (c->type == XML_EXP_OR)) xmlExpDumpInt(buf, c, 1); else xmlExpDumpInt(buf, c, 0); if ((expr->exp_min == 0) && (expr->exp_max == 1)) { rep[0] = '?'; rep[1] = 0; } else if ((expr->exp_min == 0) && (expr->exp_max == -1)) { rep[0] = '*'; rep[1] = 0; } else if ((expr->exp_min == 1) && (expr->exp_max == -1)) { rep[0] = '+'; rep[1] = 0; } else if (expr->exp_max == expr->exp_min) { snprintf(rep, 39, "{%d}", expr->exp_min); } else if (expr->exp_max < 0) { snprintf(rep, 39, "{%d,inf}", expr->exp_min); } else { snprintf(rep, 39, "{%d,%d}", expr->exp_min, expr->exp_max); } rep[39] = 0; xmlBufferWriteChar(buf, rep); break; } default: fprintf(stderr, "Error in tree\n"); } if (glob) xmlBufferWriteChar(buf, ")"); } /** * xmlExpDump: * @buf: a buffer to receive the output * @expr: the compiled expression * * Serialize the expression as compiled to the buffer */ void xmlExpDump(xmlBufferPtr buf, xmlExpNodePtr expr) { if ((buf == NULL) || (expr == NULL)) return; xmlExpDumpInt(buf, expr, 0); } /** * xmlExpMaxToken: * @expr: a compiled expression * * Indicate the maximum number of input a expression can accept * * Returns the maximum length or -1 in case of error */ int xmlExpMaxToken(xmlExpNodePtr expr) { if (expr == NULL) return(-1); return(expr->c_max); } /** * xmlExpCtxtNbNodes: * @ctxt: an expression context * * Debugging facility provides the number of allocated nodes at a that point * * Returns the number of nodes in use or -1 in case of error */ int xmlExpCtxtNbNodes(xmlExpCtxtPtr ctxt) { if (ctxt == NULL) return(-1); return(ctxt->nb_nodes); } /** * xmlExpCtxtNbCons: * @ctxt: an expression context * * Debugging facility provides the number of allocated nodes over lifetime * * Returns the number of nodes ever allocated or -1 in case of error */ int xmlExpCtxtNbCons(xmlExpCtxtPtr ctxt) { if (ctxt == NULL) return(-1); return(ctxt->nb_cons); } #endif /* LIBXML_EXPR_ENABLED */ #define bottom_xmlregexp #include "elfgcchack.h" #endif /* LIBXML_REGEXP_ENABLED */
c8f59a0d53b85ad95afd99110232aa2027c93fe6
a6cd311ab7fa599cea774ff85de066570f068951
/vendor/github.com/petermattis/goid/goid_go1.3.c
2e3f7ab79d264cfddd998a00f76615525b2f3da3
[ "MIT", "Apache-2.0" ]
permissive
jesseduffield/lazygit
8d90251e9f4a1667475aadac8e6577853bb3ae96
fc6008fdff405044bd089dc59cda15f92f39e079
refs/heads/master
2023-08-22T18:22:51.272891
2023-08-21T09:27:26
2023-08-21T09:27:26
134,017,286
39,216
1,898
MIT
2023-09-13T13:43:52
2018-05-19T00:53:06
Go
UTF-8
C
false
false
739
c
goid_go1.3.c
// Copyright 2015 Peter Mattis. // // 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. See the AUTHORS file // for names of contributors. // +build !go1.4 #include <runtime.h> void ·Get(int64 ret) { ret = g->goid; USED(&ret); }
72b6a92109397865bcf470c06f98fe02191f55a3
601d283e1cf70ade91c849f13dac482cb8283a61
/stm8s/lib/uart.c
1271d45eac88b487871bfc95a3cf17c4a559835d
[ "MIT" ]
permissive
lujji/stm8-bare-min
671ef8cb830950f8f74791f324077fb5a6a4313b
27c36ae3255ae08b294c0a0f61e3fd261e172580
refs/heads/master
2022-11-12T05:41:59.288372
2022-11-01T05:29:04
2022-11-01T05:29:04
77,332,596
115
39
MIT
2022-11-01T05:19:02
2016-12-25T15:47:27
C
UTF-8
C
false
false
547
c
uart.c
#include "uart.h" #include "stm8s.h" void uart_init() { /* round to nearest integer */ uint16_t div = (F_CPU + BAUDRATE / 2) / BAUDRATE; /* madness.. */ UART1_BRR2 = ((div >> 8) & 0xF0) + (div & 0x0F); UART1_BRR1 = div >> 4; /* enable transmitter and receiver */ UART1_CR2 = (1 << UART1_CR2_TEN) | (1 << UART1_CR2_REN); } void uart_write(uint8_t data) { UART1_DR = data; while (!(UART1_SR & (1 << UART1_SR_TC))); } uint8_t uart_read() { while (!(UART1_SR & (1 << UART1_SR_RXNE))); return UART1_DR; }
cd8bfc9d1a0bb3dbf408a41e89a9636edf51570b
76f9898ff7a555f4a729d725056a317af818375d
/assets/objects/object_gi_niwatori/object_gi_niwatori.c
ae3202a9ebd8de4e23091d60aef4804295fc5f11
[]
no_license
z64proto/sw97
0b65837ab2f2a4073faca5670761d7fe0e74d29d
f571505ade2cefd4a5b5d19da06d33e7c6b02c60
refs/heads/master
2023-08-01T02:47:42.895871
2022-05-15T20:29:08
2022-05-15T20:29:08
430,216,978
208
29
null
2021-11-22T12:23:50
2021-11-20T21:52:59
C
UTF-8
C
false
false
15,276
c
object_gi_niwatori.c
#include "ultra64.h" #include "z64.h" #include "macros.h" #include "object_gi_niwatori.h" static Vtx object_gi_niwatoriVtx_000C00[63]; static Vtx object_gi_niwatoriVtx_000FF0[41]; static Vtx object_gi_niwatoriVtx_001280[3]; static Vtx object_gi_niwatoriVtx_0012B0[21]; static Vtx object_gi_niwatoriVtx_001400[25]; static Vtx object_gi_niwatoriVtx_001590[6]; u64 object_gi_niwatoriTex_000000[] = { #include "assets/objects/object_gi_niwatori//object_gi_niwatoriTex_000000.i8.inc.c" }; u64 object_gi_niwatoriTex_000800[] = { #include "assets/objects/object_gi_niwatori//object_gi_niwatoriTex_000800.ia16.inc.c" }; static Vtx object_gi_niwatoriVtx_000C00[63] = { VTX(0, 4, -8, 1536, 1123, 151, 55, 12, 255), VTX(-3, 1, -18, 1608, 1517, 141, 26, 240, 255), VTX(0, 4, 0, 1536, 853, 0, 118, 236, 255), VTX(-10, -11, -14, 2027, 1686, 152, 240, 200, 255), VTX(0, -5, 25, 3072, 230, 0, 244, 119, 255), VTX(-16, -19, 6, 2613, 1241, 152, 217, 45, 255), VTX(0, -18, 25, 3072, 562, 0, 208, 110, 255), VTX(0, 4, 26, 3072, -8, 0, 253, 119, 255), VTX(-5, 9, 25, 2345, -119, 166, 14, 78, 255), VTX(-8, 14, 15, 1866, 75, 153, 57, 24, 255), VTX(0, 15, 26, 1536, -302, 0, 81, 88, 255), VTX(0, 23, 20, 1536, -284, 0, 108, 52, 255), VTX(0, -25, -17, 3072, 2143, 0, 157, 190, 255), VTX(0, -11, -25, 1536, 2048, 215, 242, 145, 255), VTX(0, -26, 18, 3072, 1024, 0, 146, 46, 255), VTX(-7, -28, 0, 2859, 1629, 194, 155, 239, 255), VTX(0, -28, 0, 3072, 1652, 0, 137, 252, 255), VTX(-13, -3, 9, 2354, 717, 147, 50, 253, 255), VTX(-2, 21, 11, 1582, 47, 162, 61, 214, 255), VTX(0, 14, 4, 1536, 447, 0, 59, 152, 255), VTX(-13, -1, -2, 2254, 1033, 170, 82, 244, 255), VTX(0, 4, 0, 1536, 970, 0, 118, 236, 255), VTX(-5, 2, -18, 1914, 1558, 176, 86, 233, 255), VTX(-9, -12, -24, 2677, 1768, 150, 31, 211, 255), VTX(-14, -24, -11, 2791, 1321, 143, 229, 230, 255), VTX(-19, -11, 0, 2511, 976, 138, 14, 250, 255), VTX(-13, -3, 9, 2334, 642, 147, 50, 253, 255), VTX(-16, -19, 6, 2695, 771, 152, 217, 45, 255), VTX(-10, -11, -14, 2652, 1414, 113, 218, 4, 255), VTX(-16, -19, 6, 2695, 771, 113, 227, 26, 255), VTX(-14, -24, -11, 2791, 1321, 114, 224, 17, 255), VTX(0, 4, 0, 1536, 970, 16, 116, 232, 255), VTX(-10, -11, -14, 2652, 1414, 113, 218, 4, 255), VTX(-5, 2, -18, 1914, 1558, 111, 213, 248, 255), VTX(-14, -24, -11, 2791, 1321, 114, 224, 17, 255), VTX(-9, -12, -24, 2677, 1768, 114, 220, 7, 255), VTX(-3, 1, -18, 1608, 1517, 141, 26, 240, 255), VTX(0, 4, -8, 1536, 1123, 151, 55, 12, 255), VTX(0, 22, -12, 1536, 802, 137, 14, 2, 255), VTX(0, 16, -17, 1536, 1093, 138, 20, 249, 255), VTX(0, 21, -23, 1536, 1190, 138, 10, 237, 255), VTX(0, 13, -23, 1536, 1386, 140, 14, 233, 255), VTX(0, 15, -31, 1536, 1611, 138, 8, 241, 255), VTX(0, 7, -29, 1536, 1723, 139, 13, 235, 255), VTX(0, 6, -36, 1536, 2014, 138, 11, 242, 255), VTX(0, -11, -25, 1536, 2048, 215, 242, 145, 255), VTX(0, 4, 0, 1536, 853, 0, 118, 236, 255), VTX(3, 1, -18, 1608, 1517, 115, 26, 240, 255), VTX(0, 4, -8, 1536, 1123, 105, 55, 12, 255), VTX(10, -11, -14, 2027, 1686, 104, 240, 200, 255), VTX(0, -18, 25, 3072, 562, 0, 208, 110, 255), VTX(16, -19, 6, 2613, 1241, 104, 217, 45, 255), VTX(0, -5, 25, 3072, 230, 0, 244, 119, 255), VTX(5, 9, 25, 2345, -119, 89, 13, 78, 255), VTX(0, 4, 26, 3072, -8, 0, 253, 119, 255), VTX(0, 23, 20, 1536, -284, 0, 108, 52, 255), VTX(0, 15, 26, 1536, -302, 0, 81, 88, 255), VTX(8, 14, 15, 1866, 75, 103, 56, 24, 255), VTX(0, -25, -17, 3072, 2143, 0, 157, 190, 255), VTX(0, -28, 0, 3072, 1652, 0, 137, 252, 255), VTX(7, -28, 0, 2859, 1629, 62, 155, 239, 255), VTX(0, -26, 18, 3072, 1024, 0, 146, 46, 255), VTX(13, -3, 9, 2354, 717, 109, 50, 253, 255), }; static Vtx object_gi_niwatoriVtx_000FF0[41] = { VTX(0, 14, 4, 1536, 447, 0, 59, 152, 255), VTX(2, 21, 11, 1582, 47, 94, 61, 214, 255), VTX(13, -3, 9, 2354, 717, 109, 50, 253, 255), VTX(5, 9, 25, 2345, -119, 89, 13, 78, 255), VTX(16, -19, 6, 2613, 1241, 104, 217, 45, 255), VTX(0, -26, 18, 3072, 1024, 0, 146, 46, 255), VTX(7, -28, 0, 2859, 1629, 62, 155, 239, 255), VTX(10, -11, -14, 2027, 1686, 104, 240, 200, 255), VTX(8, 14, 15, 1866, 75, 103, 56, 24, 255), VTX(0, 4, 0, 1536, 853, 0, 118, 236, 255), VTX(0, 15, 26, 1536, -302, 0, 81, 88, 255), VTX(0, -18, 25, 3072, 562, 0, 208, 110, 255), VTX(0, 23, 20, 1536, -284, 0, 108, 52, 255), VTX(3, 1, -18, 1608, 1517, 115, 26, 240, 255), VTX(0, -11, -25, 1536, 2048, 215, 242, 145, 255), VTX(0, -25, -17, 3072, 2143, 0, 157, 190, 255), VTX(0, -28, 0, 3072, 1652, 0, 137, 252, 255), VTX(5, 2, -18, 1914, 1558, 80, 86, 233, 255), VTX(0, 4, 0, 1536, 970, 0, 118, 236, 255), VTX(13, -1, -2, 2254, 1033, 86, 82, 244, 255), VTX(19, -11, 0, 2511, 976, 118, 14, 250, 255), VTX(14, -24, -11, 2791, 1321, 113, 229, 230, 255), VTX(9, -12, -24, 2677, 1768, 106, 31, 211, 255), VTX(13, -3, 9, 2334, 642, 109, 50, 253, 255), VTX(16, -19, 6, 2695, 771, 104, 217, 45, 255), VTX(14, -24, -11, 2791, 1321, 142, 224, 17, 255), VTX(16, -19, 6, 2695, 771, 216, 154, 48, 255), VTX(10, -11, -14, 2652, 1414, 143, 218, 4, 255), VTX(5, 2, -18, 1914, 1558, 145, 213, 248, 255), VTX(0, 4, 0, 1536, 970, 149, 209, 232, 255), VTX(9, -12, -24, 2677, 1768, 142, 220, 7, 255), VTX(0, 22, -12, 1536, 802, 119, 14, 2, 255), VTX(0, 4, -8, 1536, 1123, 105, 55, 12, 255), VTX(3, 1, -18, 1608, 1517, 115, 26, 240, 255), VTX(0, 16, -17, 1536, 1093, 118, 20, 249, 255), VTX(0, 21, -23, 1536, 1190, 118, 10, 237, 255), VTX(0, 13, -23, 1536, 1386, 116, 14, 233, 255), VTX(0, 15, -31, 1536, 1611, 118, 8, 241, 255), VTX(0, 7, -29, 1536, 1723, 117, 13, 235, 255), VTX(0, 6, -36, 1536, 2014, 118, 11, 242, 255), VTX(0, -11, -25, 1536, 2048, 117, 242, 235, 255), }; static Vtx object_gi_niwatoriVtx_001280[3] = { VTX(-1, -31, 13, 817, 1989, 246, 117, 23, 255), VTX(0, -28, 0, 768, 1821, 0, 116, 30, 255), VTX(-13, -31, 8, 923, 1856, 251, 116, 30, 255), }; static Vtx object_gi_niwatoriVtx_0012B0[21] = { VTX(-3, -31, -1, 797, 1824, 252, 178, 166, 255), VTX(-13, -31, 8, 923, 1856, 200, 164, 203, 255), VTX(-6, -28, 0, 819, 1813, 211, 80, 180, 255), VTX(-13, -31, 8, 923, 1856, 251, 116, 30, 255), VTX(0, -28, 0, 768, 1821, 0, 116, 30, 255), VTX(0, -28, 0, 768, 1821, 0, 226, 140, 255), VTX(-1, -31, 13, 817, 1989, 41, 144, 250, 255), VTX(6, -28, 0, 717, 1813, 45, 80, 180, 255), VTX(13, -31, 8, 613, 1856, 5, 116, 30, 255), VTX(13, -31, 8, 613, 1856, 56, 164, 203, 255), VTX(3, -31, -1, 739, 1824, 4, 178, 166, 255), VTX(1, -31, 13, 719, 1989, 10, 117, 23, 255), VTX(1, -31, 13, 719, 1989, 215, 144, 250, 255), VTX(0, 15, 26, 256, 1139, 2, 96, 71, 255), VTX(-5, 9, 25, 163, 1177, 166, 64, 47, 255), VTX(0, 8, 36, 256, 1309, 2, 96, 71, 255), VTX(0, 8, 36, 256, 1309, 2, 144, 41, 255), VTX(-5, 9, 25, 163, 1177, 166, 182, 27, 255), VTX(0, 4, 26, 256, 1222, 2, 144, 41, 255), VTX(5, 9, 25, 344, 1174, 93, 185, 26, 255), VTX(5, 9, 25, 344, 1174, 92, 61, 45, 255), }; static Vtx object_gi_niwatoriVtx_001400[25] = { VTX(0, 27, 17, 256, 1041, 117, 16, 16, 255), VTX(0, 23, 20, 256, 1127, 117, 12, 20, 255), VTX(2, 21, 11, 719, 1193, 118, 12, 244, 255), VTX(0, 31, 11, 768, 1116, 117, 18, 242, 255), VTX(0, 27, 9, 768, 1171, 115, 25, 236, 255), VTX(0, 27, 3, 768, 1255, 118, 11, 240, 255), VTX(0, 22, 5, 768, 1296, 116, 8, 227, 255), VTX(0, 18, 1, 768, 1406, 118, 7, 236, 255), VTX(0, 14, 4, 768, 1467, 118, 243, 241, 255), VTX(-2, 21, 11, -207, 1193, 138, 12, 244, 255), VTX(0, 23, 20, 256, 1127, 139, 12, 20, 255), VTX(0, 27, 17, 256, 1041, 139, 16, 16, 255), VTX(0, 31, 11, 768, 1116, 139, 18, 242, 255), VTX(0, 27, 9, 768, 1171, 141, 25, 236, 255), VTX(-2, 21, 11, 817, 1193, 138, 12, 244, 255), VTX(0, 27, 3, 768, 1255, 138, 11, 240, 255), VTX(0, 22, 5, 768, 1296, 140, 8, 227, 255), VTX(0, 18, 1, 768, 1406, 138, 7, 236, 255), VTX(0, 14, 4, 768, 1467, 138, 243, 241, 255), VTX(0, 4, 26, 256, 1758, 0, 113, 40, 255), VTX(-1, -2, 32, 241, 1771, 158, 13, 67, 255), VTX(1, -2, 32, 271, 1771, 98, 13, 67, 255), VTX(0, -8, 30, 256, 1845, 0, 175, 88, 255), VTX(0, -5, 25, 256, 1884, 139, 244, 235, 255), VTX(0, -5, 25, 256, 1884, 117, 244, 235, 255), }; static Vtx object_gi_niwatoriVtx_001590[6] = { VTX(0, 23, 20, 361, -467, 28, 88, 76, 255), VTX(-8, 14, 15, 1196, 669, 157, 57, 35, 255), VTX(0, 15, 26, -335, 441, 0, 81, 88, 255), VTX(-5, 9, 25, -9, 1258, 166, 22, 75, 255), VTX(8, 14, 15, 1196, 669, 100, 56, 35, 255), VTX(5, 9, 25, -9, 1258, 90, 22, 75, 255), }; Gfx gGiChickenColorDL[] = { gsDPPipeSync(), gsDPSetPrimColor(0, 0, 255, 255, 220, 255), gsDPSetEnvColor(50, 50, 20, 255), gsSPEndDisplayList(), }; Gfx gGiCojiroColorDL[] = { gsDPPipeSync(), gsDPSetPrimColor(0, 0, 80, 140, 255, 255), gsDPSetEnvColor(20, 30, 60, 255), gsSPEndDisplayList(), }; Gfx gGiChickenDL[] = { gsDPPipeSync(), gsDPSetRenderMode(G_RM_PASS, G_RM_AA_ZB_TEX_EDGE2), gsDPSetCombineLERP(PRIMITIVE, ENVIRONMENT, TEXEL0, ENVIRONMENT, 0, 0, 0, 1, COMBINED, K5, SHADE, COMBINED_ALPHA, 0, 0, 0, 1), gsDPSetTextureLUT(G_TT_NONE), gsSPTexture(65535, 65535, 0, 0, G_ON), gsDPSetTextureImage(G_IM_FMT_I, G_IM_SIZ_16b, 1, object_gi_niwatoriTex_000000), gsDPSetTile(G_IM_FMT_I, G_IM_SIZ_16b, 0, 0, 7, 0, 2, 6, 0, 0, 5, 0), gsDPLoadSync(), gsDPLoadBlock(7, 0, 0, 1023, 512), gsDPPipeSync(), gsDPSetTile(G_IM_FMT_I, G_IM_SIZ_8b, 4, 0, 0, 0, 2, 6, 0, 0, 5, 0), gsDPSetTileSize(0, 0, 0, 124, 252), gsSPClearGeometryMode(G_TEXTURE_ENABLE | G_FOG | G_TEXTURE_GEN | G_TEXTURE_GEN_LINEAR), gsSPSetGeometryMode(G_TEXTURE_ENABLE | G_CULL_BACK | G_LIGHTING), gsSPVertex(&object_gi_niwatoriVtx_000C00[0], 32, 0), gsSP2Triangles(0, 1, 2, 0, 2, 1, 3, 0), gsSP2Triangles(4, 5, 6, 0, 4, 7, 8, 0), gsSP2Triangles(5, 4, 8, 0, 9, 10, 11, 0), gsSP2Triangles(12, 3, 13, 0, 14, 15, 16, 0), gsSP2Triangles(8, 9, 17, 0, 15, 3, 12, 0), gsSP2Triangles(17, 18, 19, 0, 17, 5, 8, 0), gsSP2Triangles(5, 15, 14, 0, 3, 15, 5, 0), gsSP2Triangles(9, 18, 17, 0, 19, 2, 17, 0), gsSP2Triangles(10, 9, 8, 0, 5, 14, 6, 0), gsSP2Triangles(9, 11, 18, 0, 13, 3, 1, 0), gsSP2Triangles(16, 15, 12, 0, 20, 21, 22, 0), gsSP2Triangles(23, 24, 25, 0, 26, 21, 20, 0), gsSP2Triangles(25, 27, 26, 0, 24, 27, 25, 0), gsSP2Triangles(25, 20, 23, 0, 26, 20, 25, 0), gsSP2Triangles(20, 22, 23, 0, 28, 29, 30, 0), gsSPVertex(&object_gi_niwatoriVtx_000C00[31], 32, 0), gsSP2Triangles(0, 1, 2, 0, 3, 4, 1, 0), gsSP2Triangles(4, 2, 1, 0, 5, 6, 7, 0), gsSP2Triangles(7, 8, 5, 0, 5, 8, 9, 0), gsSP2Triangles(9, 10, 5, 0, 10, 11, 5, 0), gsSP2Triangles(5, 11, 12, 0, 5, 12, 13, 0), gsSP2Triangles(14, 5, 13, 0, 15, 16, 17, 0), gsSP2Triangles(18, 16, 15, 0, 19, 20, 21, 0), gsSP2Triangles(22, 23, 21, 0, 22, 21, 20, 0), gsSP2Triangles(24, 25, 26, 0, 14, 18, 27, 0), gsSP2Triangles(28, 29, 30, 0, 31, 26, 22, 0), gsSP1Triangle(27, 18, 29, 0), gsSPVertex(&object_gi_niwatoriVtx_000FF0[0], 32, 0), gsSP2Triangles(0, 1, 2, 0, 3, 4, 2, 0), gsSP2Triangles(5, 6, 4, 0, 4, 6, 7, 0), gsSP2Triangles(2, 1, 8, 0, 2, 9, 0, 0), gsSP2Triangles(3, 8, 10, 0, 11, 5, 4, 0), gsSP2Triangles(1, 12, 8, 0, 13, 7, 14, 0), gsSP2Triangles(15, 6, 16, 0, 17, 18, 19, 0), gsSP2Triangles(20, 21, 22, 0, 19, 18, 23, 0), gsSP2Triangles(23, 24, 20, 0, 20, 24, 21, 0), gsSP2Triangles(22, 19, 20, 0, 20, 19, 23, 0), gsSP2Triangles(22, 17, 19, 0, 25, 26, 27, 0), gsSP2Triangles(28, 27, 29, 0, 27, 30, 25, 0), gsSP1Triangle(27, 28, 30, 0), gsSPVertex(&object_gi_niwatoriVtx_000FF0[31], 10, 0), gsSP2Triangles(0, 1, 2, 0, 2, 3, 0, 0), gsSP2Triangles(4, 3, 2, 0, 2, 5, 4, 0), gsSP2Triangles(2, 6, 5, 0, 7, 6, 2, 0), gsSP2Triangles(8, 7, 2, 0, 8, 2, 9, 0), gsDPPipeSync(), gsDPSetPrimColor(0, 0, 255, 170, 40, 255), gsDPSetEnvColor(70, 50, 20, 255), gsSPTexture(4000, 3000, 0, 0, G_ON), gsDPSetTextureImage(G_IM_FMT_I, G_IM_SIZ_16b, 1, 0x04032890), gsDPSetTile(G_IM_FMT_I, G_IM_SIZ_16b, 0, 0, 7, 0, 0, 5, 0, 0, 5, 0), gsDPLoadSync(), gsDPLoadBlock(7, 0, 0, 511, 512), gsDPPipeSync(), gsDPSetTile(G_IM_FMT_I, G_IM_SIZ_8b, 4, 0, 0, 0, 0, 5, 0, 0, 5, 0), gsDPSetTileSize(0, 0, 0, 124, 124), gsSPSetGeometryMode(G_TEXTURE_ENABLE | G_TEXTURE_GEN | G_TEXTURE_GEN_LINEAR), gsSPVertex(&object_gi_niwatoriVtx_001280[0], 3, 0), gsSP1Triangle(0, 1, 2, 0), gsSPVertex(&object_gi_niwatoriVtx_0012B0[0], 21, 0), gsSP2Triangles(0, 1, 2, 0, 2, 3, 4, 0), gsSP2Triangles(0, 2, 5, 0, 0, 5, 6, 0), gsSP2Triangles(0, 6, 1, 0, 7, 4, 8, 0), gsSP2Triangles(7, 9, 10, 0, 11, 8, 4, 0), gsSP2Triangles(5, 7, 10, 0, 12, 5, 10, 0), gsSP2Triangles(9, 12, 10, 0, 13, 14, 15, 0), gsSP2Triangles(16, 17, 18, 0, 19, 16, 18, 0), gsSP1Triangle(13, 15, 20, 0), gsDPPipeSync(), gsDPSetPrimColor(0, 0, 200, 50, 40, 255), gsDPSetEnvColor(100, 20, 10, 255), gsSPTexture(2000, 2000, 0, 0, G_ON), gsSPVertex(&object_gi_niwatoriVtx_001400[0], 25, 0), gsSP2Triangles(0, 1, 2, 0, 2, 3, 0, 0), gsSP2Triangles(4, 3, 2, 0, 2, 5, 4, 0), gsSP2Triangles(6, 5, 2, 0, 7, 6, 2, 0), gsSP2Triangles(2, 8, 7, 0, 9, 10, 11, 0), gsSP2Triangles(9, 11, 12, 0, 12, 13, 14, 0), gsSP2Triangles(14, 13, 15, 0, 15, 16, 14, 0), gsSP2Triangles(14, 16, 17, 0, 17, 18, 14, 0), gsSP2Triangles(19, 20, 21, 0, 22, 21, 20, 0), gsSP2Triangles(23, 20, 19, 0, 23, 22, 20, 0), gsSP2Triangles(24, 19, 21, 0, 21, 22, 24, 0), gsSPEndDisplayList(), }; Gfx gGiChickenEyesDL[] = { gsDPPipeSync(), gsDPSetRenderMode(G_RM_OPA_SURF, G_RM_AA_ZB_XLU_DECAL2), gsDPSetCombineLERP(PRIMITIVE, ENVIRONMENT, TEXEL0, ENVIRONMENT, 0, 0, 0, TEXEL0, COMBINED, K5, SHADE, COMBINED_ALPHA, 0, 0, 0, COMBINED), gsDPSetPrimColor(0, 0, 255, 255, 255, 255), gsDPSetEnvColor(10, 20, 40, 255), gsDPSetTextureLUT(G_TT_NONE), gsSPTexture(65535, 65535, 0, 0, G_ON), gsDPSetTextureImage(G_IM_FMT_IA, G_IM_SIZ_16b, 1, object_gi_niwatoriTex_000800), gsDPSetTile(G_IM_FMT_IA, G_IM_SIZ_16b, 0, 0, 7, 0, 2, 5, 0, 2, 5, 0), gsDPLoadSync(), gsDPLoadBlock(7, 0, 0, 511, 512), gsDPPipeSync(), gsDPSetTile(G_IM_FMT_IA, G_IM_SIZ_8b, 4, 0, 0, 0, 2, 5, 0, 2, 5, 0), gsDPSetTileSize(0, 0, 0, 124, 124), gsSPClearGeometryMode(G_TEXTURE_ENABLE | G_FOG | G_TEXTURE_GEN | G_TEXTURE_GEN_LINEAR), gsSPSetGeometryMode(G_TEXTURE_ENABLE | G_CULL_BACK | G_LIGHTING), gsSPVertex(&object_gi_niwatoriVtx_001590[0], 6, 0), gsSP2Triangles(0, 1, 2, 0, 3, 2, 1, 0), gsSP2Triangles(4, 2, 5, 0, 2, 4, 0, 0), gsSPEndDisplayList(), }; static u8 unaccounted_0019E8[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, };
463f3220f3bac5bafbccf853919318c6d2ed78a9
f7dc806f341ef5dbb0e11252a4693003a66853d5
/thirdparty/mbedtls/include/mbedtls/platform_time.h
eee61d695a3c03bbe82c592d0c15bec9a3621cb6
[ "Apache-2.0", "MIT", "OFL-1.1", "JSON", "LicenseRef-scancode-nvidia-2002", "BSD-3-Clause", "Zlib", "MPL-2.0", "CC0-1.0", "BSL-1.0", "Libpng", "LicenseRef-scancode-public-domain", "Unlicense", "LicenseRef-scancode-free-unknown", "CC-BY-4.0", "Bison-exception-2.2", "LicenseRef-scancode-other-permissive", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-unicode", "BSD-2-Clause", "FTL", "GPL-3.0-or-later", "Bitstream-Vera", "MIT-Modern-Variant" ]
permissive
godotengine/godot
8a2419750f4851d1426a8f3bcb52cac5c86f23c2
970be7afdc111ccc7459d7ef3560de70e6d08c80
refs/heads/master
2023-08-21T14:37:00.262883
2023-08-21T06:26:15
2023-08-21T06:26:15
15,634,981
68,852
18,388
MIT
2023-09-14T21:42:16
2014-01-04T16:05:36
C++
UTF-8
C
false
false
1,833
h
platform_time.h
/** * \file platform_time.h * * \brief mbed TLS Platform time abstraction */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * 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. */ #ifndef MBEDTLS_PLATFORM_TIME_H #define MBEDTLS_PLATFORM_TIME_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #ifdef __cplusplus extern "C" { #endif /* * The time_t datatype */ #if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO) typedef MBEDTLS_PLATFORM_TIME_TYPE_MACRO mbedtls_time_t; #else /* For time_t */ #include <time.h> typedef time_t mbedtls_time_t; #endif /* MBEDTLS_PLATFORM_TIME_TYPE_MACRO */ /* * The function pointers for time */ #if defined(MBEDTLS_PLATFORM_TIME_ALT) extern mbedtls_time_t (*mbedtls_time)(mbedtls_time_t *time); /** * \brief Set your own time function pointer * * \param time_func the time function implementation * * \return 0 */ int mbedtls_platform_set_time(mbedtls_time_t (*time_func)(mbedtls_time_t *time)); #else #if defined(MBEDTLS_PLATFORM_TIME_MACRO) #define mbedtls_time MBEDTLS_PLATFORM_TIME_MACRO #else #define mbedtls_time time #endif /* MBEDTLS_PLATFORM_TIME_MACRO */ #endif /* MBEDTLS_PLATFORM_TIME_ALT */ #ifdef __cplusplus } #endif #endif /* platform_time.h */
a7f8c32a5fbb5ea3eaf67d6987fcf0ebb10a02ed
7268fc3bfc290281741d302d67e48cbfa794a2f8
/server/serverCalls.h
91bf01074e2627041f48df58d5aaa31dc59f2330
[ "LicenseRef-scancode-public-domain" ]
permissive
jasonrohrer/OneLife
5b5c83eea12363fef88f96869aa9039024e8a5d1
09579bed8675bba6a3b6235c0821e02c6f85a78f
refs/heads/master
2023-08-31T15:57:46.028105
2023-08-25T21:38:25
2023-08-25T21:38:25
106,724,750
970
341
NOASSERTION
2023-05-17T14:37:02
2017-10-12T17:32:19
C++
UTF-8
C
false
false
247
h
serverCalls.h
#include "../gameSource/GridPos.h" #include "minorGems/network/web/WebRequest.h" GridPos killPlayer( const char *inEmail ); void forcePlayerAge( const char *inEmail, double inAge ); WebRequest *defaultTimeoutWebRequest( const char *inURL );
ac6461216db75fc58d82b092054f375a6ac9a8d8
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/lpc54114-lite/drivers/drv_romfs.c
d488b163fcc728e377070a49d03117a46a4eb783
[ "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
RT-Thread/rt-thread
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
3602f891211904a27dcbd51e5ba72fefce7326b2
refs/heads/master
2023-09-01T04:10:20.295801
2023-08-31T16:20:55
2023-08-31T16:20:55
7,408,108
9,599
5,805
Apache-2.0
2023-09-14T13:37:26
2013-01-02T14:49:21
C
UTF-8
C
false
false
71,524
c
drv_romfs.c
/* Generated by mkromfs. Edit with caution. */ #include <rtthread.h> #include <dfs_romfs.h> static const rt_uint8_t _romfs_root_license[] = { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x41, 0x70, 0x61, 0x63, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x32, 0x2e, 0x30, 0x2c, 0x20, 0x4a, 0x61, 0x6e, 0x75, 0x61, 0x72, 0x79, 0x20, 0x32, 0x30, 0x30, 0x34, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x61, 0x70, 0x61, 0x63, 0x68, 0x65, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x73, 0x2f, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x54, 0x45, 0x52, 0x4d, 0x53, 0x20, 0x41, 0x4e, 0x44, 0x20, 0x43, 0x4f, 0x4e, 0x44, 0x49, 0x54, 0x49, 0x4f, 0x4e, 0x53, 0x20, 0x46, 0x4f, 0x52, 0x20, 0x55, 0x53, 0x45, 0x2c, 0x20, 0x52, 0x45, 0x50, 0x52, 0x4f, 0x44, 0x55, 0x43, 0x54, 0x49, 0x4f, 0x4e, 0x2c, 0x20, 0x41, 0x4e, 0x44, 0x20, 0x44, 0x49, 0x53, 0x54, 0x52, 0x49, 0x42, 0x55, 0x54, 0x49, 0x4f, 0x4e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x31, 0x2e, 0x20, 0x44, 0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x22, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x6d, 0x65, 0x61, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x65, 0x72, 0x6d, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x75, 0x73, 0x65, 0x2c, 0x20, 0x72, 0x65, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x73, 0x20, 0x64, 0x65, 0x66, 0x69, 0x6e, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x53, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x31, 0x20, 0x74, 0x68, 0x72, 0x6f, 0x75, 0x67, 0x68, 0x20, 0x39, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x22, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x6d, 0x65, 0x61, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x20, 0x6f, 0x72, 0x20, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x20, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x20, 0x62, 0x79, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x69, 0x73, 0x20, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x4c, 0x65, 0x67, 0x61, 0x6c, 0x20, 0x45, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x22, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x6d, 0x65, 0x61, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x75, 0x6e, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x61, 0x63, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x61, 0x6c, 0x6c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x20, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x69, 0x65, 0x73, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x2c, 0x20, 0x61, 0x72, 0x65, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x64, 0x20, 0x62, 0x79, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x61, 0x72, 0x65, 0x20, 0x75, 0x6e, 0x64, 0x65, 0x72, 0x20, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x2e, 0x20, 0x46, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x72, 0x70, 0x6f, 0x73, 0x65, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x64, 0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x22, 0x20, 0x6d, 0x65, 0x61, 0x6e, 0x73, 0x20, 0x28, 0x69, 0x29, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x6f, 0x77, 0x65, 0x72, 0x2c, 0x20, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x20, 0x6f, 0x72, 0x20, 0x69, 0x6e, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x2c, 0x20, 0x74, 0x6f, 0x20, 0x63, 0x61, 0x75, 0x73, 0x65, 0x20, 0x74, 0x68, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x72, 0x20, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x2c, 0x20, 0x77, 0x68, 0x65, 0x74, 0x68, 0x65, 0x72, 0x20, 0x62, 0x79, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x20, 0x6f, 0x72, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x77, 0x69, 0x73, 0x65, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x28, 0x69, 0x69, 0x29, 0x20, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x73, 0x68, 0x69, 0x70, 0x20, 0x6f, 0x66, 0x20, 0x66, 0x69, 0x66, 0x74, 0x79, 0x20, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x20, 0x28, 0x35, 0x30, 0x25, 0x29, 0x20, 0x6f, 0x72, 0x20, 0x6d, 0x6f, 0x72, 0x65, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x75, 0x74, 0x73, 0x74, 0x61, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x73, 0x68, 0x61, 0x72, 0x65, 0x73, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x28, 0x69, 0x69, 0x69, 0x29, 0x20, 0x62, 0x65, 0x6e, 0x65, 0x66, 0x69, 0x63, 0x69, 0x61, 0x6c, 0x20, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x73, 0x68, 0x69, 0x70, 0x20, 0x6f, 0x66, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x59, 0x6f, 0x75, 0x22, 0x20, 0x28, 0x6f, 0x72, 0x20, 0x22, 0x59, 0x6f, 0x75, 0x72, 0x22, 0x29, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x6d, 0x65, 0x61, 0x6e, 0x20, 0x61, 0x6e, 0x20, 0x69, 0x6e, 0x64, 0x69, 0x76, 0x69, 0x64, 0x75, 0x61, 0x6c, 0x20, 0x6f, 0x72, 0x20, 0x4c, 0x65, 0x67, 0x61, 0x6c, 0x20, 0x45, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78, 0x65, 0x72, 0x63, 0x69, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x22, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x6d, 0x65, 0x61, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x72, 0x65, 0x66, 0x65, 0x72, 0x72, 0x65, 0x64, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x6d, 0x61, 0x6b, 0x69, 0x6e, 0x67, 0x20, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x62, 0x75, 0x74, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x73, 0x6f, 0x66, 0x74, 0x77, 0x61, 0x72, 0x65, 0x20, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x2c, 0x20, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2c, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x22, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x6d, 0x65, 0x61, 0x6e, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x66, 0x72, 0x6f, 0x6d, 0x20, 0x6d, 0x65, 0x63, 0x68, 0x61, 0x6e, 0x69, 0x63, 0x61, 0x6c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x72, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x61, 0x20, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x2c, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x62, 0x75, 0x74, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x63, 0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x65, 0x64, 0x20, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x2c, 0x20, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x64, 0x20, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x63, 0x6f, 0x6e, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x74, 0x6f, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x20, 0x6d, 0x65, 0x64, 0x69, 0x61, 0x20, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x57, 0x6f, 0x72, 0x6b, 0x22, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x6d, 0x65, 0x61, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x77, 0x6f, 0x72, 0x6b, 0x20, 0x6f, 0x66, 0x20, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x73, 0x68, 0x69, 0x70, 0x2c, 0x20, 0x77, 0x68, 0x65, 0x74, 0x68, 0x65, 0x72, 0x20, 0x69, 0x6e, 0x20, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x20, 0x6f, 0x72, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x2c, 0x20, 0x6d, 0x61, 0x64, 0x65, 0x20, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x20, 0x75, 0x6e, 0x64, 0x65, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2c, 0x20, 0x61, 0x73, 0x20, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x61, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x6e, 0x6f, 0x74, 0x69, 0x63, 0x65, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x69, 0x73, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x20, 0x6f, 0x72, 0x20, 0x61, 0x74, 0x74, 0x61, 0x63, 0x68, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x77, 0x6f, 0x72, 0x6b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x28, 0x61, 0x6e, 0x20, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x41, 0x70, 0x70, 0x65, 0x6e, 0x64, 0x69, 0x78, 0x20, 0x62, 0x65, 0x6c, 0x6f, 0x77, 0x29, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x22, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x6d, 0x65, 0x61, 0x6e, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x77, 0x6f, 0x72, 0x6b, 0x2c, 0x20, 0x77, 0x68, 0x65, 0x74, 0x68, 0x65, 0x72, 0x20, 0x69, 0x6e, 0x20, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x20, 0x6f, 0x72, 0x20, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x2c, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x69, 0x73, 0x20, 0x62, 0x61, 0x73, 0x65, 0x64, 0x20, 0x6f, 0x6e, 0x20, 0x28, 0x6f, 0x72, 0x20, 0x64, 0x65, 0x72, 0x69, 0x76, 0x65, 0x64, 0x20, 0x66, 0x72, 0x6f, 0x6d, 0x29, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x77, 0x68, 0x69, 0x63, 0x68, 0x20, 0x74, 0x68, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65, 0x64, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x61, 0x6c, 0x20, 0x72, 0x65, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x2c, 0x20, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2c, 0x20, 0x65, 0x6c, 0x61, 0x62, 0x6f, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x20, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x70, 0x72, 0x65, 0x73, 0x65, 0x6e, 0x74, 0x2c, 0x20, 0x61, 0x73, 0x20, 0x61, 0x20, 0x77, 0x68, 0x6f, 0x6c, 0x65, 0x2c, 0x20, 0x61, 0x6e, 0x20, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x20, 0x77, 0x6f, 0x72, 0x6b, 0x20, 0x6f, 0x66, 0x20, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x73, 0x68, 0x69, 0x70, 0x2e, 0x20, 0x46, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x72, 0x70, 0x6f, 0x73, 0x65, 0x73, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2c, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x20, 0x77, 0x6f, 0x72, 0x6b, 0x73, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x72, 0x65, 0x6d, 0x61, 0x69, 0x6e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x70, 0x61, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x20, 0x66, 0x72, 0x6f, 0x6d, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x6d, 0x65, 0x72, 0x65, 0x6c, 0x79, 0x20, 0x6c, 0x69, 0x6e, 0x6b, 0x20, 0x28, 0x6f, 0x72, 0x20, 0x62, 0x69, 0x6e, 0x64, 0x20, 0x62, 0x79, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x29, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x66, 0x61, 0x63, 0x65, 0x73, 0x20, 0x6f, 0x66, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x20, 0x74, 0x68, 0x65, 0x72, 0x65, 0x6f, 0x66, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x6d, 0x65, 0x61, 0x6e, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x77, 0x6f, 0x72, 0x6b, 0x20, 0x6f, 0x66, 0x20, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x73, 0x68, 0x69, 0x70, 0x2c, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x69, 0x6e, 0x67, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x6f, 0x72, 0x20, 0x61, 0x64, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x6f, 0x72, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x20, 0x74, 0x68, 0x65, 0x72, 0x65, 0x6f, 0x66, 0x2c, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x69, 0x73, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x6c, 0x79, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x72, 0x20, 0x62, 0x79, 0x20, 0x61, 0x6e, 0x20, 0x69, 0x6e, 0x64, 0x69, 0x76, 0x69, 0x64, 0x75, 0x61, 0x6c, 0x20, 0x6f, 0x72, 0x20, 0x4c, 0x65, 0x67, 0x61, 0x6c, 0x20, 0x45, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x20, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x73, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x20, 0x6f, 0x6e, 0x20, 0x62, 0x65, 0x68, 0x61, 0x6c, 0x66, 0x20, 0x6f, 0x66, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x2e, 0x20, 0x46, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x72, 0x70, 0x6f, 0x73, 0x65, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x64, 0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x22, 0x73, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x64, 0x22, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x65, 0x61, 0x6e, 0x73, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x6f, 0x66, 0x20, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x72, 0x6f, 0x6e, 0x69, 0x63, 0x2c, 0x20, 0x76, 0x65, 0x72, 0x62, 0x61, 0x6c, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x77, 0x72, 0x69, 0x74, 0x74, 0x65, 0x6e, 0x20, 0x63, 0x6f, 0x6d, 0x6d, 0x75, 0x6e, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x73, 0x65, 0x6e, 0x74, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x6f, 0x72, 0x20, 0x69, 0x74, 0x73, 0x20, 0x72, 0x65, 0x70, 0x72, 0x65, 0x73, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x2c, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x62, 0x75, 0x74, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6d, 0x6d, 0x75, 0x6e, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x6e, 0x20, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x72, 0x6f, 0x6e, 0x69, 0x63, 0x20, 0x6d, 0x61, 0x69, 0x6c, 0x69, 0x6e, 0x67, 0x20, 0x6c, 0x69, 0x73, 0x74, 0x73, 0x2c, 0x20, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x20, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x69, 0x73, 0x73, 0x75, 0x65, 0x20, 0x74, 0x72, 0x61, 0x63, 0x6b, 0x69, 0x6e, 0x67, 0x20, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x61, 0x72, 0x65, 0x20, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x20, 0x62, 0x79, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x6f, 0x6e, 0x20, 0x62, 0x65, 0x68, 0x61, 0x6c, 0x66, 0x20, 0x6f, 0x66, 0x2c, 0x20, 0x74, 0x68, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x72, 0x70, 0x6f, 0x73, 0x65, 0x20, 0x6f, 0x66, 0x20, 0x64, 0x69, 0x73, 0x63, 0x75, 0x73, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x69, 0x6d, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x2c, 0x20, 0x62, 0x75, 0x74, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78, 0x63, 0x6c, 0x75, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x63, 0x6f, 0x6d, 0x6d, 0x75, 0x6e, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x69, 0x73, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x70, 0x69, 0x63, 0x75, 0x6f, 0x75, 0x73, 0x6c, 0x79, 0x20, 0x6d, 0x61, 0x72, 0x6b, 0x65, 0x64, 0x20, 0x6f, 0x72, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x77, 0x69, 0x73, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x20, 0x77, 0x72, 0x69, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x20, 0x61, 0x73, 0x20, 0x22, 0x4e, 0x6f, 0x74, 0x20, 0x61, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x22, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x22, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x6d, 0x65, 0x61, 0x6e, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x69, 0x6e, 0x64, 0x69, 0x76, 0x69, 0x64, 0x75, 0x61, 0x6c, 0x20, 0x6f, 0x72, 0x20, 0x4c, 0x65, 0x67, 0x61, 0x6c, 0x20, 0x45, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x6e, 0x20, 0x62, 0x65, 0x68, 0x61, 0x6c, 0x66, 0x20, 0x6f, 0x66, 0x20, 0x77, 0x68, 0x6f, 0x6d, 0x20, 0x61, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x68, 0x61, 0x73, 0x20, 0x62, 0x65, 0x65, 0x6e, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x61, 0x6e, 0x64, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x75, 0x62, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x6c, 0x79, 0x20, 0x69, 0x6e, 0x63, 0x6f, 0x72, 0x70, 0x6f, 0x72, 0x61, 0x74, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x32, 0x2e, 0x20, 0x47, 0x72, 0x61, 0x6e, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2e, 0x20, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x65, 0x72, 0x6d, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x6f, 0x66, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2c, 0x20, 0x65, 0x61, 0x63, 0x68, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x20, 0x68, 0x65, 0x72, 0x65, 0x62, 0x79, 0x20, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x73, 0x20, 0x74, 0x6f, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x61, 0x20, 0x70, 0x65, 0x72, 0x70, 0x65, 0x74, 0x75, 0x61, 0x6c, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x77, 0x69, 0x64, 0x65, 0x2c, 0x20, 0x6e, 0x6f, 0x6e, 0x2d, 0x65, 0x78, 0x63, 0x6c, 0x75, 0x73, 0x69, 0x76, 0x65, 0x2c, 0x20, 0x6e, 0x6f, 0x2d, 0x63, 0x68, 0x61, 0x72, 0x67, 0x65, 0x2c, 0x20, 0x72, 0x6f, 0x79, 0x61, 0x6c, 0x74, 0x79, 0x2d, 0x66, 0x72, 0x65, 0x65, 0x2c, 0x20, 0x69, 0x72, 0x72, 0x65, 0x76, 0x6f, 0x63, 0x61, 0x62, 0x6c, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x20, 0x74, 0x6f, 0x20, 0x72, 0x65, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x65, 0x2c, 0x20, 0x70, 0x72, 0x65, 0x70, 0x61, 0x72, 0x65, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x20, 0x6f, 0x66, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x6c, 0x79, 0x20, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x2c, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x6c, 0x79, 0x20, 0x70, 0x65, 0x72, 0x66, 0x6f, 0x72, 0x6d, 0x2c, 0x20, 0x73, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2c, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x20, 0x74, 0x68, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x20, 0x69, 0x6e, 0x20, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x20, 0x6f, 0x72, 0x20, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x33, 0x2e, 0x20, 0x47, 0x72, 0x61, 0x6e, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x50, 0x61, 0x74, 0x65, 0x6e, 0x74, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2e, 0x20, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x65, 0x72, 0x6d, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x6f, 0x66, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2c, 0x20, 0x65, 0x61, 0x63, 0x68, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x20, 0x68, 0x65, 0x72, 0x65, 0x62, 0x79, 0x20, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x73, 0x20, 0x74, 0x6f, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x61, 0x20, 0x70, 0x65, 0x72, 0x70, 0x65, 0x74, 0x75, 0x61, 0x6c, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x77, 0x69, 0x64, 0x65, 0x2c, 0x20, 0x6e, 0x6f, 0x6e, 0x2d, 0x65, 0x78, 0x63, 0x6c, 0x75, 0x73, 0x69, 0x76, 0x65, 0x2c, 0x20, 0x6e, 0x6f, 0x2d, 0x63, 0x68, 0x61, 0x72, 0x67, 0x65, 0x2c, 0x20, 0x72, 0x6f, 0x79, 0x61, 0x6c, 0x74, 0x79, 0x2d, 0x66, 0x72, 0x65, 0x65, 0x2c, 0x20, 0x69, 0x72, 0x72, 0x65, 0x76, 0x6f, 0x63, 0x61, 0x62, 0x6c, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x28, 0x65, 0x78, 0x63, 0x65, 0x70, 0x74, 0x20, 0x61, 0x73, 0x20, 0x73, 0x74, 0x61, 0x74, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x73, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x29, 0x20, 0x70, 0x61, 0x74, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x20, 0x74, 0x6f, 0x20, 0x6d, 0x61, 0x6b, 0x65, 0x2c, 0x20, 0x68, 0x61, 0x76, 0x65, 0x20, 0x6d, 0x61, 0x64, 0x65, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x75, 0x73, 0x65, 0x2c, 0x20, 0x6f, 0x66, 0x66, 0x65, 0x72, 0x20, 0x74, 0x6f, 0x20, 0x73, 0x65, 0x6c, 0x6c, 0x2c, 0x20, 0x73, 0x65, 0x6c, 0x6c, 0x2c, 0x20, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x2c, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x77, 0x69, 0x73, 0x65, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x77, 0x68, 0x65, 0x72, 0x65, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x20, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x65, 0x73, 0x20, 0x6f, 0x6e, 0x6c, 0x79, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x6f, 0x73, 0x65, 0x20, 0x70, 0x61, 0x74, 0x65, 0x6e, 0x74, 0x20, 0x63, 0x6c, 0x61, 0x69, 0x6d, 0x73, 0x20, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62, 0x79, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x61, 0x72, 0x65, 0x20, 0x6e, 0x65, 0x63, 0x65, 0x73, 0x73, 0x61, 0x72, 0x69, 0x6c, 0x79, 0x20, 0x69, 0x6e, 0x66, 0x72, 0x69, 0x6e, 0x67, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x69, 0x72, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x28, 0x73, 0x29, 0x20, 0x61, 0x6c, 0x6f, 0x6e, 0x65, 0x20, 0x6f, 0x72, 0x20, 0x62, 0x79, 0x20, 0x63, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x69, 0x72, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x28, 0x73, 0x29, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x68, 0x69, 0x63, 0x68, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x28, 0x73, 0x29, 0x20, 0x77, 0x61, 0x73, 0x20, 0x73, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x64, 0x2e, 0x20, 0x49, 0x66, 0x20, 0x59, 0x6f, 0x75, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6e, 0x73, 0x74, 0x69, 0x74, 0x75, 0x74, 0x65, 0x20, 0x70, 0x61, 0x74, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x69, 0x74, 0x69, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x67, 0x61, 0x69, 0x6e, 0x73, 0x74, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x20, 0x28, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x61, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x72, 0x6f, 0x73, 0x73, 0x2d, 0x63, 0x6c, 0x61, 0x69, 0x6d, 0x20, 0x6f, 0x72, 0x20, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x63, 0x6c, 0x61, 0x69, 0x6d, 0x20, 0x69, 0x6e, 0x20, 0x61, 0x20, 0x6c, 0x61, 0x77, 0x73, 0x75, 0x69, 0x74, 0x29, 0x20, 0x61, 0x6c, 0x6c, 0x65, 0x67, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x72, 0x20, 0x61, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x69, 0x6e, 0x63, 0x6f, 0x72, 0x70, 0x6f, 0x72, 0x61, 0x74, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x69, 0x74, 0x75, 0x74, 0x65, 0x73, 0x20, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x72, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x79, 0x20, 0x70, 0x61, 0x74, 0x65, 0x6e, 0x74, 0x20, 0x69, 0x6e, 0x66, 0x72, 0x69, 0x6e, 0x67, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x2c, 0x20, 0x74, 0x68, 0x65, 0x6e, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x70, 0x61, 0x74, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x73, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x75, 0x6e, 0x64, 0x65, 0x72, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x74, 0x65, 0x72, 0x6d, 0x69, 0x6e, 0x61, 0x74, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x61, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x64, 0x61, 0x74, 0x65, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x6c, 0x69, 0x74, 0x69, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x69, 0x73, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x64, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x34, 0x2e, 0x20, 0x52, 0x65, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x6d, 0x61, 0x79, 0x20, 0x72, 0x65, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x65, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x20, 0x63, 0x6f, 0x70, 0x69, 0x65, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x6f, 0x72, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x20, 0x74, 0x68, 0x65, 0x72, 0x65, 0x6f, 0x66, 0x20, 0x69, 0x6e, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x6d, 0x65, 0x64, 0x69, 0x75, 0x6d, 0x2c, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x6f, 0x72, 0x20, 0x77, 0x69, 0x74, 0x68, 0x6f, 0x75, 0x74, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2c, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x69, 0x6e, 0x20, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x20, 0x6f, 0x72, 0x20, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x2c, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x64, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x59, 0x6f, 0x75, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x65, 0x65, 0x74, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x6f, 0x6c, 0x6c, 0x6f, 0x77, 0x69, 0x6e, 0x67, 0x20, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3a, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x28, 0x61, 0x29, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x6d, 0x75, 0x73, 0x74, 0x20, 0x67, 0x69, 0x76, 0x65, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x20, 0x72, 0x65, 0x63, 0x69, 0x70, 0x69, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x6f, 0x72, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x20, 0x61, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x3b, 0x20, 0x61, 0x6e, 0x64, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x28, 0x62, 0x29, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x6d, 0x75, 0x73, 0x74, 0x20, 0x63, 0x61, 0x75, 0x73, 0x65, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x20, 0x74, 0x6f, 0x20, 0x63, 0x61, 0x72, 0x72, 0x79, 0x20, 0x70, 0x72, 0x6f, 0x6d, 0x69, 0x6e, 0x65, 0x6e, 0x74, 0x20, 0x6e, 0x6f, 0x74, 0x69, 0x63, 0x65, 0x73, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x74, 0x61, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x64, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x3b, 0x20, 0x61, 0x6e, 0x64, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x28, 0x63, 0x29, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x6d, 0x75, 0x73, 0x74, 0x20, 0x72, 0x65, 0x74, 0x61, 0x69, 0x6e, 0x2c, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x6f, 0x66, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x2c, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x2c, 0x20, 0x70, 0x61, 0x74, 0x65, 0x6e, 0x74, 0x2c, 0x20, 0x74, 0x72, 0x61, 0x64, 0x65, 0x6d, 0x61, 0x72, 0x6b, 0x2c, 0x20, 0x61, 0x6e, 0x64, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6e, 0x6f, 0x74, 0x69, 0x63, 0x65, 0x73, 0x20, 0x66, 0x72, 0x6f, 0x6d, 0x20, 0x74, 0x68, 0x65, 0x20, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78, 0x63, 0x6c, 0x75, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x68, 0x6f, 0x73, 0x65, 0x20, 0x6e, 0x6f, 0x74, 0x69, 0x63, 0x65, 0x73, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x64, 0x6f, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x70, 0x65, 0x72, 0x74, 0x61, 0x69, 0x6e, 0x20, 0x74, 0x6f, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x70, 0x61, 0x72, 0x74, 0x20, 0x6f, 0x66, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x3b, 0x20, 0x61, 0x6e, 0x64, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x28, 0x64, 0x29, 0x20, 0x49, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x73, 0x20, 0x61, 0x20, 0x22, 0x4e, 0x4f, 0x54, 0x49, 0x43, 0x45, 0x22, 0x20, 0x74, 0x65, 0x78, 0x74, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x61, 0x73, 0x20, 0x70, 0x61, 0x72, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x69, 0x74, 0x73, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x74, 0x68, 0x65, 0x6e, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x20, 0x6d, 0x75, 0x73, 0x74, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x20, 0x61, 0x20, 0x72, 0x65, 0x61, 0x64, 0x61, 0x62, 0x6c, 0x65, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6e, 0x6f, 0x74, 0x69, 0x63, 0x65, 0x73, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x64, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x77, 0x69, 0x74, 0x68, 0x69, 0x6e, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x4e, 0x4f, 0x54, 0x49, 0x43, 0x45, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x2c, 0x20, 0x65, 0x78, 0x63, 0x6c, 0x75, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x68, 0x6f, 0x73, 0x65, 0x20, 0x6e, 0x6f, 0x74, 0x69, 0x63, 0x65, 0x73, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x64, 0x6f, 0x20, 0x6e, 0x6f, 0x74, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70, 0x65, 0x72, 0x74, 0x61, 0x69, 0x6e, 0x20, 0x74, 0x6f, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x70, 0x61, 0x72, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x2c, 0x20, 0x69, 0x6e, 0x20, 0x61, 0x74, 0x20, 0x6c, 0x65, 0x61, 0x73, 0x74, 0x20, 0x6f, 0x6e, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x6f, 0x6c, 0x6c, 0x6f, 0x77, 0x69, 0x6e, 0x67, 0x20, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x73, 0x3a, 0x20, 0x77, 0x69, 0x74, 0x68, 0x69, 0x6e, 0x20, 0x61, 0x20, 0x4e, 0x4f, 0x54, 0x49, 0x43, 0x45, 0x20, 0x74, 0x65, 0x78, 0x74, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x64, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x61, 0x73, 0x20, 0x70, 0x61, 0x72, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x3b, 0x20, 0x77, 0x69, 0x74, 0x68, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x6f, 0x72, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x69, 0x66, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x64, 0x20, 0x61, 0x6c, 0x6f, 0x6e, 0x67, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x74, 0x68, 0x65, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x3b, 0x20, 0x6f, 0x72, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x77, 0x69, 0x74, 0x68, 0x69, 0x6e, 0x20, 0x61, 0x20, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x20, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x2c, 0x20, 0x69, 0x66, 0x20, 0x61, 0x6e, 0x64, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x77, 0x68, 0x65, 0x72, 0x65, 0x76, 0x65, 0x72, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x74, 0x68, 0x69, 0x72, 0x64, 0x2d, 0x70, 0x61, 0x72, 0x74, 0x79, 0x20, 0x6e, 0x6f, 0x74, 0x69, 0x63, 0x65, 0x73, 0x20, 0x6e, 0x6f, 0x72, 0x6d, 0x61, 0x6c, 0x6c, 0x79, 0x20, 0x61, 0x70, 0x70, 0x65, 0x61, 0x72, 0x2e, 0x20, 0x54, 0x68, 0x65, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4e, 0x4f, 0x54, 0x49, 0x43, 0x45, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x61, 0x72, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x69, 0x6e, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x70, 0x75, 0x72, 0x70, 0x6f, 0x73, 0x65, 0x73, 0x20, 0x6f, 0x6e, 0x6c, 0x79, 0x20, 0x61, 0x6e, 0x64, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x6f, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2e, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x6d, 0x61, 0x79, 0x20, 0x61, 0x64, 0x64, 0x20, 0x59, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e, 0x20, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6e, 0x6f, 0x74, 0x69, 0x63, 0x65, 0x73, 0x20, 0x77, 0x69, 0x74, 0x68, 0x69, 0x6e, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x2c, 0x20, 0x61, 0x6c, 0x6f, 0x6e, 0x67, 0x73, 0x69, 0x64, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x72, 0x20, 0x61, 0x73, 0x20, 0x61, 0x6e, 0x20, 0x61, 0x64, 0x64, 0x65, 0x6e, 0x64, 0x75, 0x6d, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4e, 0x4f, 0x54, 0x49, 0x43, 0x45, 0x20, 0x74, 0x65, 0x78, 0x74, 0x20, 0x66, 0x72, 0x6f, 0x6d, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x2c, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x64, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x61, 0x64, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6e, 0x6f, 0x74, 0x69, 0x63, 0x65, 0x73, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62, 0x65, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x65, 0x64, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x61, 0x73, 0x20, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x6d, 0x61, 0x79, 0x20, 0x61, 0x64, 0x64, 0x20, 0x59, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x73, 0x74, 0x61, 0x74, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x59, 0x6f, 0x75, 0x72, 0x20, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x61, 0x79, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x20, 0x61, 0x64, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x6f, 0x72, 0x20, 0x64, 0x69, 0x66, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x20, 0x74, 0x65, 0x72, 0x6d, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x75, 0x73, 0x65, 0x2c, 0x20, 0x72, 0x65, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x59, 0x6f, 0x75, 0x72, 0x20, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2c, 0x20, 0x6f, 0x72, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x20, 0x61, 0x73, 0x20, 0x61, 0x20, 0x77, 0x68, 0x6f, 0x6c, 0x65, 0x2c, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x64, 0x20, 0x59, 0x6f, 0x75, 0x72, 0x20, 0x75, 0x73, 0x65, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x77, 0x69, 0x73, 0x65, 0x20, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x69, 0x65, 0x73, 0x20, 0x77, 0x69, 0x74, 0x68, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x73, 0x74, 0x61, 0x74, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x35, 0x2e, 0x20, 0x53, 0x75, 0x62, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x20, 0x55, 0x6e, 0x6c, 0x65, 0x73, 0x73, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x65, 0x78, 0x70, 0x6c, 0x69, 0x63, 0x69, 0x74, 0x6c, 0x79, 0x20, 0x73, 0x74, 0x61, 0x74, 0x65, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x77, 0x69, 0x73, 0x65, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x6c, 0x79, 0x20, 0x73, 0x75, 0x62, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x64, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62, 0x79, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x62, 0x65, 0x20, 0x75, 0x6e, 0x64, 0x65, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x65, 0x72, 0x6d, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x6f, 0x66, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2c, 0x20, 0x77, 0x69, 0x74, 0x68, 0x6f, 0x75, 0x74, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x61, 0x64, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x74, 0x65, 0x72, 0x6d, 0x73, 0x20, 0x6f, 0x72, 0x20, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4e, 0x6f, 0x74, 0x77, 0x69, 0x74, 0x68, 0x73, 0x74, 0x61, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x68, 0x65, 0x20, 0x61, 0x62, 0x6f, 0x76, 0x65, 0x2c, 0x20, 0x6e, 0x6f, 0x74, 0x68, 0x69, 0x6e, 0x67, 0x20, 0x68, 0x65, 0x72, 0x65, 0x69, 0x6e, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x73, 0x75, 0x70, 0x65, 0x72, 0x73, 0x65, 0x64, 0x65, 0x20, 0x6f, 0x72, 0x20, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x65, 0x72, 0x6d, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x73, 0x65, 0x70, 0x61, 0x72, 0x61, 0x74, 0x65, 0x20, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x20, 0x61, 0x67, 0x72, 0x65, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6d, 0x61, 0x79, 0x20, 0x68, 0x61, 0x76, 0x65, 0x20, 0x65, 0x78, 0x65, 0x63, 0x75, 0x74, 0x65, 0x64, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x72, 0x65, 0x67, 0x61, 0x72, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x36, 0x2e, 0x20, 0x54, 0x72, 0x61, 0x64, 0x65, 0x6d, 0x61, 0x72, 0x6b, 0x73, 0x2e, 0x20, 0x54, 0x68, 0x69, 0x73, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x20, 0x64, 0x6f, 0x65, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x20, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x74, 0x6f, 0x20, 0x75, 0x73, 0x65, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x72, 0x61, 0x64, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x2c, 0x20, 0x74, 0x72, 0x61, 0x64, 0x65, 0x6d, 0x61, 0x72, 0x6b, 0x73, 0x2c, 0x20, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x20, 0x6d, 0x61, 0x72, 0x6b, 0x73, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78, 0x63, 0x65, 0x70, 0x74, 0x20, 0x61, 0x73, 0x20, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x61, 0x72, 0x79, 0x20, 0x75, 0x73, 0x65, 0x20, 0x69, 0x6e, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x62, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x68, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x72, 0x65, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4e, 0x4f, 0x54, 0x49, 0x43, 0x45, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x37, 0x2e, 0x20, 0x44, 0x69, 0x73, 0x63, 0x6c, 0x61, 0x69, 0x6d, 0x65, 0x72, 0x20, 0x6f, 0x66, 0x20, 0x57, 0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2e, 0x20, 0x55, 0x6e, 0x6c, 0x65, 0x73, 0x73, 0x20, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x62, 0x6c, 0x65, 0x20, 0x6c, 0x61, 0x77, 0x20, 0x6f, 0x72, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x61, 0x67, 0x72, 0x65, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x69, 0x6e, 0x20, 0x77, 0x72, 0x69, 0x74, 0x69, 0x6e, 0x67, 0x2c, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x28, 0x61, 0x6e, 0x64, 0x20, 0x65, 0x61, 0x63, 0x68, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x73, 0x20, 0x69, 0x74, 0x73, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x29, 0x20, 0x6f, 0x6e, 0x20, 0x61, 0x6e, 0x20, 0x22, 0x41, 0x53, 0x20, 0x49, 0x53, 0x22, 0x20, 0x42, 0x41, 0x53, 0x49, 0x53, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x57, 0x49, 0x54, 0x48, 0x4f, 0x55, 0x54, 0x20, 0x57, 0x41, 0x52, 0x52, 0x41, 0x4e, 0x54, 0x49, 0x45, 0x53, 0x20, 0x4f, 0x52, 0x20, 0x43, 0x4f, 0x4e, 0x44, 0x49, 0x54, 0x49, 0x4f, 0x4e, 0x53, 0x20, 0x4f, 0x46, 0x20, 0x41, 0x4e, 0x59, 0x20, 0x4b, 0x49, 0x4e, 0x44, 0x2c, 0x20, 0x65, 0x69, 0x74, 0x68, 0x65, 0x72, 0x20, 0x65, 0x78, 0x70, 0x72, 0x65, 0x73, 0x73, 0x20, 0x6f, 0x72, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6d, 0x70, 0x6c, 0x69, 0x65, 0x64, 0x2c, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x69, 0x6e, 0x67, 0x2c, 0x20, 0x77, 0x69, 0x74, 0x68, 0x6f, 0x75, 0x74, 0x20, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x77, 0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x69, 0x65, 0x73, 0x20, 0x6f, 0x72, 0x20, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x66, 0x20, 0x54, 0x49, 0x54, 0x4c, 0x45, 0x2c, 0x20, 0x4e, 0x4f, 0x4e, 0x2d, 0x49, 0x4e, 0x46, 0x52, 0x49, 0x4e, 0x47, 0x45, 0x4d, 0x45, 0x4e, 0x54, 0x2c, 0x20, 0x4d, 0x45, 0x52, 0x43, 0x48, 0x41, 0x4e, 0x54, 0x41, 0x42, 0x49, 0x4c, 0x49, 0x54, 0x59, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x46, 0x49, 0x54, 0x4e, 0x45, 0x53, 0x53, 0x20, 0x46, 0x4f, 0x52, 0x20, 0x41, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x50, 0x41, 0x52, 0x54, 0x49, 0x43, 0x55, 0x4c, 0x41, 0x52, 0x20, 0x50, 0x55, 0x52, 0x50, 0x4f, 0x53, 0x45, 0x2e, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x61, 0x72, 0x65, 0x20, 0x73, 0x6f, 0x6c, 0x65, 0x6c, 0x79, 0x20, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x69, 0x62, 0x6c, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x64, 0x65, 0x74, 0x65, 0x72, 0x6d, 0x69, 0x6e, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x68, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x61, 0x70, 0x70, 0x72, 0x6f, 0x70, 0x72, 0x69, 0x61, 0x74, 0x65, 0x6e, 0x65, 0x73, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x75, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x6f, 0x72, 0x20, 0x72, 0x65, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x61, 0x73, 0x73, 0x75, 0x6d, 0x65, 0x20, 0x61, 0x6e, 0x79, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x69, 0x73, 0x6b, 0x73, 0x20, 0x61, 0x73, 0x73, 0x6f, 0x63, 0x69, 0x61, 0x74, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x59, 0x6f, 0x75, 0x72, 0x20, 0x65, 0x78, 0x65, 0x72, 0x63, 0x69, 0x73, 0x65, 0x20, 0x6f, 0x66, 0x20, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x75, 0x6e, 0x64, 0x65, 0x72, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x38, 0x2e, 0x20, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x4c, 0x69, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x2e, 0x20, 0x49, 0x6e, 0x20, 0x6e, 0x6f, 0x20, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x75, 0x6e, 0x64, 0x65, 0x72, 0x20, 0x6e, 0x6f, 0x20, 0x6c, 0x65, 0x67, 0x61, 0x6c, 0x20, 0x74, 0x68, 0x65, 0x6f, 0x72, 0x79, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x77, 0x68, 0x65, 0x74, 0x68, 0x65, 0x72, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x6f, 0x72, 0x74, 0x20, 0x28, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x6e, 0x65, 0x67, 0x6c, 0x69, 0x67, 0x65, 0x6e, 0x63, 0x65, 0x29, 0x2c, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x77, 0x69, 0x73, 0x65, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x75, 0x6e, 0x6c, 0x65, 0x73, 0x73, 0x20, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x62, 0x6c, 0x65, 0x20, 0x6c, 0x61, 0x77, 0x20, 0x28, 0x73, 0x75, 0x63, 0x68, 0x20, 0x61, 0x73, 0x20, 0x64, 0x65, 0x6c, 0x69, 0x62, 0x65, 0x72, 0x61, 0x74, 0x65, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x67, 0x72, 0x6f, 0x73, 0x73, 0x6c, 0x79, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6e, 0x65, 0x67, 0x6c, 0x69, 0x67, 0x65, 0x6e, 0x74, 0x20, 0x61, 0x63, 0x74, 0x73, 0x29, 0x20, 0x6f, 0x72, 0x20, 0x61, 0x67, 0x72, 0x65, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x69, 0x6e, 0x20, 0x77, 0x72, 0x69, 0x74, 0x69, 0x6e, 0x67, 0x2c, 0x20, 0x73, 0x68, 0x61, 0x6c, 0x6c, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x20, 0x62, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x20, 0x74, 0x6f, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x64, 0x61, 0x6d, 0x61, 0x67, 0x65, 0x73, 0x2c, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x2c, 0x20, 0x69, 0x6e, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x2c, 0x20, 0x73, 0x70, 0x65, 0x63, 0x69, 0x61, 0x6c, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6e, 0x63, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x61, 0x6c, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x20, 0x64, 0x61, 0x6d, 0x61, 0x67, 0x65, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x63, 0x68, 0x61, 0x72, 0x61, 0x63, 0x74, 0x65, 0x72, 0x20, 0x61, 0x72, 0x69, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x61, 0x73, 0x20, 0x61, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x20, 0x6f, 0x72, 0x20, 0x6f, 0x75, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x75, 0x73, 0x65, 0x20, 0x6f, 0x72, 0x20, 0x69, 0x6e, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x20, 0x74, 0x6f, 0x20, 0x75, 0x73, 0x65, 0x20, 0x74, 0x68, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x28, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x62, 0x75, 0x74, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x64, 0x61, 0x6d, 0x61, 0x67, 0x65, 0x73, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x6c, 0x6f, 0x73, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x67, 0x6f, 0x6f, 0x64, 0x77, 0x69, 0x6c, 0x6c, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x77, 0x6f, 0x72, 0x6b, 0x20, 0x73, 0x74, 0x6f, 0x70, 0x70, 0x61, 0x67, 0x65, 0x2c, 0x20, 0x63, 0x6f, 0x6d, 0x70, 0x75, 0x74, 0x65, 0x72, 0x20, 0x66, 0x61, 0x69, 0x6c, 0x75, 0x72, 0x65, 0x20, 0x6f, 0x72, 0x20, 0x6d, 0x61, 0x6c, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x61, 0x6c, 0x6c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x20, 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x72, 0x63, 0x69, 0x61, 0x6c, 0x20, 0x64, 0x61, 0x6d, 0x61, 0x67, 0x65, 0x73, 0x20, 0x6f, 0x72, 0x20, 0x6c, 0x6f, 0x73, 0x73, 0x65, 0x73, 0x29, 0x2c, 0x20, 0x65, 0x76, 0x65, 0x6e, 0x20, 0x69, 0x66, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x68, 0x61, 0x73, 0x20, 0x62, 0x65, 0x65, 0x6e, 0x20, 0x61, 0x64, 0x76, 0x69, 0x73, 0x65, 0x64, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x6f, 0x73, 0x73, 0x69, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x20, 0x6f, 0x66, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x64, 0x61, 0x6d, 0x61, 0x67, 0x65, 0x73, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x39, 0x2e, 0x20, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x57, 0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x20, 0x6f, 0x72, 0x20, 0x41, 0x64, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x4c, 0x69, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x2e, 0x20, 0x57, 0x68, 0x69, 0x6c, 0x65, 0x20, 0x72, 0x65, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x69, 0x6e, 0x67, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x20, 0x6f, 0x72, 0x20, 0x44, 0x65, 0x72, 0x69, 0x76, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x73, 0x20, 0x74, 0x68, 0x65, 0x72, 0x65, 0x6f, 0x66, 0x2c, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x6d, 0x61, 0x79, 0x20, 0x63, 0x68, 0x6f, 0x6f, 0x73, 0x65, 0x20, 0x74, 0x6f, 0x20, 0x6f, 0x66, 0x66, 0x65, 0x72, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x63, 0x68, 0x61, 0x72, 0x67, 0x65, 0x20, 0x61, 0x20, 0x66, 0x65, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x2c, 0x20, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x20, 0x6f, 0x66, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x2c, 0x20, 0x77, 0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2c, 0x20, 0x69, 0x6e, 0x64, 0x65, 0x6d, 0x6e, 0x69, 0x74, 0x79, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x72, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x20, 0x6c, 0x69, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x20, 0x6f, 0x62, 0x6c, 0x69, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x2f, 0x6f, 0x72, 0x20, 0x72, 0x69, 0x67, 0x68, 0x74, 0x73, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x74, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x74, 0x68, 0x69, 0x73, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2e, 0x20, 0x48, 0x6f, 0x77, 0x65, 0x76, 0x65, 0x72, 0x2c, 0x20, 0x69, 0x6e, 0x20, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x6f, 0x62, 0x6c, 0x69, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2c, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x6d, 0x61, 0x79, 0x20, 0x61, 0x63, 0x74, 0x20, 0x6f, 0x6e, 0x6c, 0x79, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x6e, 0x20, 0x59, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e, 0x20, 0x62, 0x65, 0x68, 0x61, 0x6c, 0x66, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x6f, 0x6e, 0x20, 0x59, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x6f, 0x6c, 0x65, 0x20, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x69, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x2c, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x6f, 0x6e, 0x20, 0x62, 0x65, 0x68, 0x61, 0x6c, 0x66, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x66, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x2c, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x6f, 0x6e, 0x6c, 0x79, 0x20, 0x69, 0x66, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x61, 0x67, 0x72, 0x65, 0x65, 0x20, 0x74, 0x6f, 0x20, 0x69, 0x6e, 0x64, 0x65, 0x6d, 0x6e, 0x69, 0x66, 0x79, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x66, 0x65, 0x6e, 0x64, 0x2c, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x68, 0x6f, 0x6c, 0x64, 0x20, 0x65, 0x61, 0x63, 0x68, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x20, 0x68, 0x61, 0x72, 0x6d, 0x6c, 0x65, 0x73, 0x73, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x6c, 0x69, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x64, 0x20, 0x62, 0x79, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x63, 0x6c, 0x61, 0x69, 0x6d, 0x73, 0x20, 0x61, 0x73, 0x73, 0x65, 0x72, 0x74, 0x65, 0x64, 0x20, 0x61, 0x67, 0x61, 0x69, 0x6e, 0x73, 0x74, 0x2c, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x20, 0x62, 0x79, 0x20, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x66, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x77, 0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x20, 0x6f, 0x72, 0x20, 0x61, 0x64, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x20, 0x6c, 0x69, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x45, 0x4e, 0x44, 0x20, 0x4f, 0x46, 0x20, 0x54, 0x45, 0x52, 0x4d, 0x53, 0x20, 0x41, 0x4e, 0x44, 0x20, 0x43, 0x4f, 0x4e, 0x44, 0x49, 0x54, 0x49, 0x4f, 0x4e, 0x53, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x41, 0x50, 0x50, 0x45, 0x4e, 0x44, 0x49, 0x58, 0x3a, 0x20, 0x48, 0x6f, 0x77, 0x20, 0x74, 0x6f, 0x20, 0x61, 0x70, 0x70, 0x6c, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x41, 0x70, 0x61, 0x63, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x20, 0x74, 0x6f, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x77, 0x6f, 0x72, 0x6b, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x54, 0x6f, 0x20, 0x61, 0x70, 0x70, 0x6c, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x41, 0x70, 0x61, 0x63, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x20, 0x74, 0x6f, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x77, 0x6f, 0x72, 0x6b, 0x2c, 0x20, 0x61, 0x74, 0x74, 0x61, 0x63, 0x68, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x6f, 0x6c, 0x6c, 0x6f, 0x77, 0x69, 0x6e, 0x67, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62, 0x6f, 0x69, 0x6c, 0x65, 0x72, 0x70, 0x6c, 0x61, 0x74, 0x65, 0x20, 0x6e, 0x6f, 0x74, 0x69, 0x63, 0x65, 0x2c, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x73, 0x20, 0x65, 0x6e, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x62, 0x72, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x73, 0x20, 0x22, 0x5b, 0x5d, 0x22, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x79, 0x69, 0x6e, 0x67, 0x20, 0x69, 0x6e, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x20, 0x28, 0x44, 0x6f, 0x6e, 0x27, 0x74, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65, 0x20, 0x62, 0x72, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x73, 0x21, 0x29, 0x20, 0x20, 0x54, 0x68, 0x65, 0x20, 0x74, 0x65, 0x78, 0x74, 0x20, 0x73, 0x68, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x65, 0x6e, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x61, 0x70, 0x70, 0x72, 0x6f, 0x70, 0x72, 0x69, 0x61, 0x74, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x2e, 0x20, 0x57, 0x65, 0x20, 0x61, 0x6c, 0x73, 0x6f, 0x20, 0x72, 0x65, 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x64, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x61, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x6f, 0x72, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x70, 0x75, 0x72, 0x70, 0x6f, 0x73, 0x65, 0x20, 0x62, 0x65, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x64, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x61, 0x6d, 0x65, 0x20, 0x22, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x65, 0x64, 0x20, 0x70, 0x61, 0x67, 0x65, 0x22, 0x20, 0x61, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x6e, 0x6f, 0x74, 0x69, 0x63, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x65, 0x61, 0x73, 0x69, 0x65, 0x72, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x77, 0x69, 0x74, 0x68, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x69, 0x72, 0x64, 0x2d, 0x70, 0x61, 0x72, 0x74, 0x79, 0x20, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x73, 0x2e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x5b, 0x79, 0x79, 0x79, 0x79, 0x5d, 0x20, 0x5b, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x6f, 0x66, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x5d, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x64, 0x20, 0x75, 0x6e, 0x64, 0x65, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x41, 0x70, 0x61, 0x63, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2c, 0x20, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x32, 0x2e, 0x30, 0x20, 0x28, 0x74, 0x68, 0x65, 0x20, 0x22, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x22, 0x29, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6d, 0x61, 0x79, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x75, 0x73, 0x65, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x65, 0x78, 0x63, 0x65, 0x70, 0x74, 0x20, 0x69, 0x6e, 0x20, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x69, 0x61, 0x6e, 0x63, 0x65, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x59, 0x6f, 0x75, 0x20, 0x6d, 0x61, 0x79, 0x20, 0x6f, 0x62, 0x74, 0x61, 0x69, 0x6e, 0x20, 0x61, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x20, 0x61, 0x74, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x61, 0x70, 0x61, 0x63, 0x68, 0x65, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x73, 0x2f, 0x4c, 0x49, 0x43, 0x45, 0x4e, 0x53, 0x45, 0x2d, 0x32, 0x2e, 0x30, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x55, 0x6e, 0x6c, 0x65, 0x73, 0x73, 0x20, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x62, 0x6c, 0x65, 0x20, 0x6c, 0x61, 0x77, 0x20, 0x6f, 0x72, 0x20, 0x61, 0x67, 0x72, 0x65, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x69, 0x6e, 0x20, 0x77, 0x72, 0x69, 0x74, 0x69, 0x6e, 0x67, 0x2c, 0x20, 0x73, 0x6f, 0x66, 0x74, 0x77, 0x61, 0x72, 0x65, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x64, 0x20, 0x75, 0x6e, 0x64, 0x65, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x20, 0x69, 0x73, 0x20, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x64, 0x20, 0x6f, 0x6e, 0x20, 0x61, 0x6e, 0x20, 0x22, 0x41, 0x53, 0x20, 0x49, 0x53, 0x22, 0x20, 0x42, 0x41, 0x53, 0x49, 0x53, 0x2c, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x57, 0x49, 0x54, 0x48, 0x4f, 0x55, 0x54, 0x20, 0x57, 0x41, 0x52, 0x52, 0x41, 0x4e, 0x54, 0x49, 0x45, 0x53, 0x20, 0x4f, 0x52, 0x20, 0x43, 0x4f, 0x4e, 0x44, 0x49, 0x54, 0x49, 0x4f, 0x4e, 0x53, 0x20, 0x4f, 0x46, 0x20, 0x41, 0x4e, 0x59, 0x20, 0x4b, 0x49, 0x4e, 0x44, 0x2c, 0x20, 0x65, 0x69, 0x74, 0x68, 0x65, 0x72, 0x20, 0x65, 0x78, 0x70, 0x72, 0x65, 0x73, 0x73, 0x20, 0x6f, 0x72, 0x20, 0x69, 0x6d, 0x70, 0x6c, 0x69, 0x65, 0x64, 0x2e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x53, 0x65, 0x65, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x63, 0x20, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x20, 0x67, 0x6f, 0x76, 0x65, 0x72, 0x6e, 0x69, 0x6e, 0x67, 0x20, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x75, 0x6e, 0x64, 0x65, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65, 0x2e, 0x0d, 0x0a }; static const rt_uint8_t _romfs_root_mnt_flash__keep[] = { 0x2e, 0x6b, 0x65, 0x65, 0x70, 0x20, 0x0d, 0x0a }; static const struct romfs_dirent _romfs_root_mnt_flash[] = { {ROMFS_DIRENT_FILE, ".keep", (rt_uint8_t *)_romfs_root_mnt_flash__keep, sizeof(_romfs_root_mnt_flash__keep) / sizeof(_romfs_root_mnt_flash__keep[0])} }; static const rt_uint8_t _romfs_root_mnt_sd__keep[] = { 0x2e, 0x6b, 0x65, 0x65, 0x70, 0x20, 0x0d, 0x0a }; static const struct romfs_dirent _romfs_root_mnt_sd[] = { {ROMFS_DIRENT_FILE, ".keep", (rt_uint8_t *)_romfs_root_mnt_sd__keep, sizeof(_romfs_root_mnt_sd__keep) / sizeof(_romfs_root_mnt_sd__keep[0])} }; static const rt_uint8_t _romfs_root_mnt_tmp__keep[] = { 0x2e, 0x6b, 0x65, 0x65, 0x70, 0x20, 0x0d, 0x0a }; static const struct romfs_dirent _romfs_root_mnt_tmp[] = { {ROMFS_DIRENT_FILE, ".keep", (rt_uint8_t *)_romfs_root_mnt_tmp__keep, sizeof(_romfs_root_mnt_tmp__keep) / sizeof(_romfs_root_mnt_tmp__keep[0])} }; static const struct romfs_dirent _romfs_root_mnt[] = { {ROMFS_DIRENT_DIR, "flash", (rt_uint8_t *)_romfs_root_mnt_flash, sizeof(_romfs_root_mnt_flash) / sizeof(_romfs_root_mnt_flash[0])}, {ROMFS_DIRENT_DIR, "sd", (rt_uint8_t *)_romfs_root_mnt_sd, sizeof(_romfs_root_mnt_sd) / sizeof(_romfs_root_mnt_sd[0])}, {ROMFS_DIRENT_DIR, "tmp", (rt_uint8_t *)_romfs_root_mnt_tmp, sizeof(_romfs_root_mnt_tmp) / sizeof(_romfs_root_mnt_tmp[0])} }; static const struct romfs_dirent _romfs_root[] = { {ROMFS_DIRENT_FILE, "license", (rt_uint8_t *)_romfs_root_license, sizeof(_romfs_root_license) / sizeof(_romfs_root_license[0])}, {ROMFS_DIRENT_DIR, "mnt", (rt_uint8_t *)_romfs_root_mnt, sizeof(_romfs_root_mnt) / sizeof(_romfs_root_mnt[0])} }; const struct romfs_dirent romfs_root = { ROMFS_DIRENT_DIR, "/", (rt_uint8_t *)_romfs_root, sizeof(_romfs_root) / sizeof(_romfs_root[0]) }; #include <dfs_fs.h> int rt_hw_romfs_init(void) { dfs_mount(RT_NULL, "/", "rom", 0, &romfs_root); return 0; } INIT_EXPORT(rt_hw_romfs_init, "4.end");
e3a815ff93527f117af45ac80856c5cb7a9e3549
cf56b5fcf51fddb219c47f5f006d8595a4483c57
/src/components/tl/cuda/tl_cuda_team_topo.c
b1161ede6ad226a123635a4313da4da9013e4d94
[ "BSD-3-Clause" ]
permissive
openucx/ucc
3b39fbd849a7850c559b60eaec7882292f8a5eca
f89cd7557e6ebb19b4c6ebd529647d8b42c30657
refs/heads/master
2023-08-18T03:18:54.072899
2023-08-17T18:05:44
2023-08-17T18:05:44
282,490,868
150
57
BSD-3-Clause
2023-09-12T09:49:18
2020-07-25T17:18:51
C
UTF-8
C
false
false
17,303
c
tl_cuda_team_topo.c
/** * Copyright (c) 2022-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. * * See file LICENSE for terms. */ #include "tl_cuda_team_topo.h" #include "tl_cuda.h" #define UCC_TL_CUDA_TEAM_TOPO_SAME_DEVICE ((ucc_rank_t)(UCC_RANK_MAX)) static ucc_status_t ucc_tl_cuda_team_topo_add_ring(const ucc_tl_cuda_team_t *team, ucc_tl_cuda_team_topo_t *topo, ucc_tl_cuda_ring_t *ring, int invert, int num_dups) { ucc_rank_t size = UCC_TL_TEAM_SIZE(team); ucc_tl_cuda_ring_t *new_ring; ucc_status_t status; int i, j; ucc_assert(size > 1); for (i = 0; i < num_dups; i++) { topo->rings[topo->num_rings + i].ring = NULL; topo->rings[topo->num_rings + i].iring = NULL; } for (i = 0; i < num_dups; i++) { new_ring = &topo->rings[topo->num_rings + i]; new_ring->ring = (ucc_rank_t*)ucc_malloc(2 * size * sizeof(ucc_rank_t), "cuda_topo_ring"); new_ring->iring = PTR_OFFSET(new_ring->ring, size * sizeof(ucc_rank_t)); if (!new_ring->ring) { tl_error(UCC_TL_TEAM_LIB(team), "failed to allocate topo ring"); status = UCC_ERR_NO_MEMORY; goto free_rings; } for (j = 0; j < size; j++) { if (invert) { new_ring->ring[j] = ring->ring[size - j - 1]; } else { new_ring->ring[j] = ring->ring[j]; } } for (j = 0; j < size; j++) { new_ring->iring[new_ring->ring[j]] = j; } } topo->num_rings += num_dups; return UCC_OK; free_rings: for (i = 0; i < num_dups; i++) { ucc_free(topo->rings[topo->num_rings + i].ring); } return status; } static ucc_status_t ucc_tl_cuda_team_topo_build_ring(const ucc_tl_cuda_team_t *team, const ucc_rank_t *graph, ucc_tl_cuda_ring_t *ring, ucc_rank_t pos, int width) { ucc_rank_t size = UCC_TL_TEAM_SIZE(team); ucc_rank_t i, j; int in_ring; int links; ucc_status_t status; if (pos == size) { links = graph[ring->ring[pos - 1] * size + ring->ring[0]]; if ((links == UCC_TL_CUDA_TEAM_TOPO_SAME_DEVICE) || (links >= width)) { return UCC_OK; } else { return UCC_ERR_NOT_SUPPORTED; } } for (i = 0; i < size; i++) { links = graph[ring->ring[pos - 1] * size + i]; if ((links < width) && (links != UCC_TL_CUDA_TEAM_TOPO_SAME_DEVICE)) { continue; } in_ring = 0; for (j = 0; j < pos; j++) { if (ring->ring[j] == i) { in_ring = 1; break; } } if (in_ring) { continue; } ring->ring[pos] = i; status = ucc_tl_cuda_team_topo_build_ring(team, graph, ring, pos + 1, width); if (status == UCC_OK) { return UCC_OK; } } return UCC_ERR_NOT_SUPPORTED; } /* TODO: simple algorithm to find NVLink rings. * 1. Find number of rings and minimal ring width * 2. Try to find ring of width W in given team topo. * 3. If found * 3.1. Duplicate ring W/min_width times to get rings of width min_width * 3.2. Duplicate inverted ring W times because NVLink is full duplex * 3.3. Remove ring from topology * 3. W = W/2 goto 2 */ static ucc_status_t ucc_tl_cuda_team_topo_init_rings(const ucc_tl_cuda_team_t *team, ucc_tl_cuda_team_topo_t *topo) { ucc_rank_t size = UCC_TL_TEAM_SIZE(team); ucc_tl_cuda_ring_t ring; int i, width, nr, num_rings, min_width; ucc_status_t status; ucc_rank_t *graph; ucc_assert(size > 1); topo->num_rings = 0; ring.ring = (ucc_rank_t*) ucc_malloc(size * sizeof(ucc_rank_t), "cuda_topo_ring"); if (!ring.ring) { tl_error(UCC_TL_TEAM_LIB(team), "failed to allocate topo ring"); return UCC_ERR_NO_MEMORY; } graph = (ucc_rank_t*) ucc_malloc(size * size * sizeof(ucc_rank_t), "cuda_topo_graph"); if (!graph) { status = UCC_ERR_NO_MEMORY; tl_error(UCC_TL_TEAM_LIB(team), "failed to allocate topo graph"); goto free_ring; } memcpy(graph, topo->matrix, size * size * sizeof(ucc_rank_t)); num_rings = 0; min_width = 4; for (width = min_width; width > 0; width >>= 1) { ring.ring[0] = 0; status = ucc_tl_cuda_team_topo_build_ring(team, graph, &ring, 1, width); if (status == UCC_OK) { num_rings += 2*width; if (width < min_width) { min_width = width; } for (i = 0; i < size; i++) { if (graph[ring.ring[i] * size + ring.ring[(i+1)%size]] != UCC_TL_CUDA_TEAM_TOPO_SAME_DEVICE) { graph[ring.ring[i] * size + ring.ring[(i+1)%size]] -= width; graph[ring.ring[(i+1)%size] * size + ring.ring[i]] -= width; } } } } if (num_rings == 0) { status = UCC_ERR_NOT_SUPPORTED; tl_debug(UCC_TL_TEAM_LIB(team), "no rings found"); goto free_graph; } topo->rings = (ucc_tl_cuda_ring_t*)ucc_malloc(num_rings * sizeof(*topo->rings), "cuda_topo_rings"); if (!topo->rings) { status = UCC_ERR_NO_MEMORY; tl_error(UCC_TL_TEAM_LIB(team), "failed to allocate topo rings array"); goto free_graph; } for (i = 0; i < size * size; i++) { graph[i] = topo->matrix[i]; } for (width = 4; width > 0; width >>= 1) { ring.ring[0] = 0; status = ucc_tl_cuda_team_topo_build_ring(team, graph, &ring, 1, width); if (status == UCC_OK) { nr = width / min_width; status = ucc_tl_cuda_team_topo_add_ring(team, topo, &ring, 0, nr); if (status != UCC_OK) { goto free_rings; } if (size > 2) { status = ucc_tl_cuda_team_topo_add_ring(team, topo, &ring, 1, nr); if (status != UCC_OK) { goto free_rings; } } for (i = 0; i < size; i++) { if (graph[ring.ring[i] * size + ring.ring[(i+1)%size]] != UCC_TL_CUDA_TEAM_TOPO_SAME_DEVICE) { graph[ring.ring[i] * size + ring.ring[(i+1)%size]] -= width; graph[ring.ring[(i+1)%size] * size + ring.ring[i]] -= width; } } } } ucc_free(graph); ucc_free(ring.ring); return UCC_OK; free_rings: for (i = 0; i < topo->num_rings; i++) { ucc_free(topo->rings[i].ring); } ucc_free(topo->rings); free_graph: ucc_free(graph); free_ring: ucc_free(ring.ring); return status; } static ucc_status_t ucc_tl_cuda_team_topo_init_proxies(const ucc_tl_cuda_team_t *team, ucc_tl_cuda_team_topo_t *topo) { ucc_rank_t size = UCC_TL_TEAM_SIZE(team); ucc_rank_t rank = UCC_TL_TEAM_RANK(team); ucc_rank_t num_proxies = 0; ucc_rank_t i, j, k, proxy; float *data; float score, min_score; ucc_status_t status; char pci_str[2][MAX_PCI_BUS_ID_STR]; topo->proxy_needed = 0; for (i = 0; i < size * size; i++) { if (topo->matrix[i] == 0) { num_proxies++; } } topo->num_proxies = num_proxies; topo->is_fully_connected = (num_proxies == 0) ? 1 : 0; if (num_proxies == 0) { return UCC_OK; } topo->proxies = (ucc_tl_cuda_proxy_t*)ucc_malloc( num_proxies * sizeof(ucc_tl_cuda_proxy_t), "cuda_topo_proxies"); if (!topo->proxies) { tl_error(UCC_TL_TEAM_LIB(team), "failed to alloc cuda topo proxies"); return UCC_ERR_NO_MEMORY; } data = (float*)ucc_malloc(size * size * sizeof(float), "cuda topo proxies data"); if (!data) { tl_error(UCC_TL_TEAM_LIB(team), "failed to alloc cuda topo work array"); status = UCC_ERR_NO_MEMORY; goto free_proxy; } for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { if (ucc_tl_cuda_team_topo_is_direct(&team->super, topo, i, j)) { data[i * size + j] = 1.0; } else { data[i * size + j] = 0.0; } } } num_proxies = 0; for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { if (ucc_tl_cuda_team_topo_is_direct(&team->super, topo, i, j)) { continue; } if ((i == rank) || (j == rank)) { topo->proxy_needed = 1; } proxy = UCC_RANK_INVALID; min_score = (float)(UCC_RANK_MAX); for (k = 0; k < size; k++) { if (ucc_tl_cuda_team_topo_is_direct(&team->super, topo, i, k) && ucc_tl_cuda_team_topo_is_direct(&team->super, topo, k, j)) { ucc_assert((topo->matrix[i * size + k] > 0) && (topo->matrix[k * size + j] > 0)); score = ucc_max((data[i * size + k] + 1.0) / topo->matrix[i * size + k], (data[k * size + j] + 1.0) / topo->matrix[k * size + j]); if (score >= min_score) { continue; } proxy = k; min_score = score; } } if (proxy == UCC_RANK_INVALID) { ucc_tl_cuda_topo_pci_id_to_str(&team->ids[i].pci_id, pci_str[0], MAX_PCI_BUS_ID_STR); ucc_tl_cuda_topo_pci_id_to_str(&team->ids[j].pci_id, pci_str[1], MAX_PCI_BUS_ID_STR); tl_debug(UCC_TL_TEAM_LIB(team), "no proxy found between " "dev %s (%d) and dev %s (%d), " "cuda topology is not supported", pci_str[0], i, pci_str[j], j); status = UCC_ERR_NOT_SUPPORTED; goto free_data; } if (proxy == rank) { topo->proxies[num_proxies].src = i; topo->proxies[num_proxies].dst = j; topo->proxies[num_proxies].proxy = proxy; num_proxies++; } data[i * size + proxy] += 1.0; data[proxy * size + j] += 1.0; } } topo->num_proxies = num_proxies; ucc_free(data); return UCC_OK; free_data: ucc_free(data); free_proxy: ucc_free(topo->proxies); return status; } static ucc_status_t ucc_tl_cuda_team_topo_init_matrix(const ucc_tl_cuda_team_t *team, ucc_rank_t *matrix) { ucc_tl_cuda_topo_t *topo = UCC_TL_CUDA_TEAM_CTX(team)->topo; int size = UCC_TL_TEAM_SIZE(team); ucc_status_t status; int i, j; for (i = 0; i < size; i++) { matrix[i + i*size] = UCC_TL_CUDA_TEAM_TOPO_SAME_DEVICE; for (j = i + 1; j < size; j++) { if (ucc_tl_cuda_topo_device_id_equal(&team->ids[i].pci_id, &team->ids[j].pci_id)) { matrix[i + j*size] = UCC_TL_CUDA_TEAM_TOPO_SAME_DEVICE; } else { status = ucc_tl_cuda_topo_num_links(topo, &team->ids[i].pci_id, &team->ids[j].pci_id, &matrix[i + j*size]); if (status != UCC_OK) { return status; } } matrix[j + i*size] = matrix[i +j*size]; } } return UCC_OK; } ucc_status_t ucc_tl_cuda_team_topo_create(const ucc_tl_team_t *cuda_team, ucc_tl_cuda_team_topo_t **team_topo) { ucc_tl_cuda_team_t *team = ucc_derived_of(cuda_team, ucc_tl_cuda_team_t); ucc_rank_t size = UCC_TL_TEAM_SIZE(team); ucc_tl_cuda_team_topo_t *topo; ucc_status_t status; topo = (ucc_tl_cuda_team_topo_t*)ucc_malloc(sizeof(*topo), "cuda_team_topo"); if (!topo) { tl_error(UCC_TL_TEAM_LIB(team), "failed to alloc cuda team topo"); return UCC_ERR_NO_MEMORY; } topo->matrix = (ucc_rank_t*)ucc_malloc(size * size * sizeof(ucc_rank_t), "cuda_topo_matrix"); if (!topo->matrix) { tl_error(UCC_TL_TEAM_LIB(team), "failed to alloc cuda team topo matrix"); status = UCC_ERR_NO_MEMORY; goto free_topo; } status = ucc_tl_cuda_team_topo_init_matrix(team, topo->matrix); if (status != UCC_OK) { goto free_matrix; } status = ucc_tl_cuda_team_topo_init_proxies(team, topo); if (status != UCC_OK) { if (status != UCC_ERR_NOT_SUPPORTED) { tl_error(UCC_TL_TEAM_LIB(team), "failed to init cuda topo proxy"); } goto free_matrix; } status = ucc_tl_cuda_team_topo_init_rings(team, topo); if (status != UCC_OK) { if (status != UCC_ERR_NOT_SUPPORTED) { tl_error(UCC_TL_TEAM_LIB(team), "failed to init cuda topo rings"); } goto free_proxy; } *team_topo = topo; return UCC_OK; free_proxy: if (topo->num_proxies > 0) { ucc_free(topo->proxies); } free_matrix: ucc_free(topo->matrix); free_topo: ucc_free(topo); return status; } void ucc_tl_cuda_team_topo_print_proxies(const ucc_tl_team_t *tl_team, const ucc_tl_cuda_team_topo_t *topo) { ucc_tl_cuda_team_t *team = ucc_derived_of(tl_team, ucc_tl_cuda_team_t); ucc_rank_t size = UCC_TL_TEAM_SIZE(team); ucc_rank_t rank = UCC_TL_TEAM_RANK(team); ucc_rank_t i; char pci_str[3][MAX_PCI_BUS_ID_STR]; for (i = 0; i < size; i++) { if (ucc_tl_cuda_team_topo_is_direct(tl_team, topo, rank, i)) { ucc_tl_cuda_topo_pci_id_to_str(&team->ids[rank].pci_id, pci_str[0], MAX_PCI_BUS_ID_STR); ucc_tl_cuda_topo_pci_id_to_str(&team->ids[i].pci_id, pci_str[1], MAX_PCI_BUS_ID_STR); if (topo->matrix[rank * size +i] == UCC_TL_CUDA_TEAM_TOPO_SAME_DEVICE) { tl_debug(UCC_TL_TEAM_LIB(team), "dev %s (%d) to dev %s (%d): same device", pci_str[0], rank, pci_str[1], i); } else { tl_debug(UCC_TL_TEAM_LIB(team), "dev %s (%d) to dev %s (%d): %d direct links", pci_str[0], rank, pci_str[1], i, topo->matrix[rank * size + i]); } } } for (i = 0; i < topo->num_proxies; i++) { ucc_tl_cuda_topo_pci_id_to_str(&team->ids[topo->proxies[i].src].pci_id, pci_str[0], MAX_PCI_BUS_ID_STR); ucc_tl_cuda_topo_pci_id_to_str(&team->ids[topo->proxies[i].dst].pci_id, pci_str[1], MAX_PCI_BUS_ID_STR); ucc_tl_cuda_topo_pci_id_to_str(&team->ids[topo->proxies[i].proxy].pci_id, pci_str[2], MAX_PCI_BUS_ID_STR); tl_debug(UCC_TL_TEAM_LIB(team), "dev %s (%d) to dev %s (%d): proxy dev %s (%d)", pci_str[0], topo->proxies[i].src, pci_str[1], topo->proxies[i].dst, pci_str[2], topo->proxies[i].proxy); } } void ucc_tl_cuda_team_topo_print_rings(const ucc_tl_team_t *tl_team, const ucc_tl_cuda_team_topo_t *topo) { ucc_tl_cuda_team_t *team = ucc_derived_of(tl_team, ucc_tl_cuda_team_t); ucc_rank_t rank = UCC_TL_TEAM_RANK(team); ucc_rank_t size = UCC_TL_TEAM_SIZE(team); int i, j; for (i = 0; i < topo->num_rings; i++) { for (j = 0; j < size; j++) { if (topo->rings[i].ring[j] == rank) { tl_debug(UCC_TL_TEAM_LIB(team), "ring %d: %d send to %d", i, rank, topo->rings[i].ring[(j + 1) % size]); } } } } ucc_status_t ucc_tl_cuda_team_topo_destroy(ucc_tl_cuda_team_topo_t *team_topo) { int i; for (i = 0; i < team_topo->num_rings; i++) { ucc_free(team_topo->rings[i].ring); } ucc_free(team_topo->rings); if (team_topo->num_proxies > 0) { ucc_free(team_topo->proxies); } ucc_free(team_topo->matrix); ucc_free(team_topo); return UCC_OK; }
5004253705e7fc9f22643df668f19e23bf05a101
2d11442aa09b51e10c245ee2b64231aeb051744f
/platforms/minheadless/windows/sqWin32Threads.c
5ee2844c1b793cefb4122bdd5bcd020f968329a9
[ "MIT" ]
permissive
OpenSmalltalk/opensmalltalk-vm
622b01c10017a93fdff4f1ef2188c45342384c78
330d6779ad2ecbce1f07131f53d75cd168165f0b
refs/heads/Cog
2023-09-04T05:36:54.320281
2023-08-17T11:32:52
2023-08-31T12:26:44
59,481,716
556
153
NOASSERTION
2023-06-19T19:58:13
2016-05-23T12:40:27
C
UTF-8
C
false
false
7,154
c
sqWin32Threads.c
/**************************************************************************** * PROJECT: Squeak port for Win32 (NT / Win95) * FILE: sqWin32Threads.c * CONTENT: Win32 thread support code for Cog & Stack VMs * * AUTHOR: Eliot Miranda * * NOTES: See the comment of CogThreadManager in the VMMaker package for * overall design documentation. * *****************************************************************************/ #include <stdlib.h> #include <stdarg.h> #include <limits.h> #include <windows.h> #define ForCOGMTVMImplementation 1 #include "sq.h" #include "sqAssert.h" #include "sqWin32.h" /* for printLastError */ /* * A note on thread handles and Ids. The only globally shared and globally * unique handle/id Win32 provides for threads is the value answered by the * last argument of CreateThread and GetCurrentThreadId, but this is not a * handle. GetCurrentThread answers a constant that means "this thread". * The handle returned by CreateThread is not directly accessible to the * thread that has been created, and does not seem to work reliably when * used as the argument of GetExitCodeThread. * * Therefore we need to create a process-wide handle. We do so via * DuplicateHandle because OpenThread seems to answer a handle that again * isn't reliable with GetExitCodeThread. But DuplicateHandle must be used * with the pseudo-handle returned by GetCurrentThread, and hence we need a * wrapper around the thread creation function that duplicates the handle * before calling the thread start function. (Sigh...) */ DWORD tlthIndex = (DWORD)-1; /* process-wide thread handle thread-local key */ DWORD tltiIndex = (DWORD)-1; /* thread index thread-local key */ static void initThreadLocalThreadIndices(void) { if (tlthIndex == (DWORD)-1) { tlthIndex = TlsAlloc(); tltiIndex = TlsAlloc(); if (tlthIndex == TLS_OUT_OF_INDEXES || tltiIndex == TLS_OUT_OF_INDEXES) { /* illiterate swine! */ printLastError(TEXT("ThreadLocalThreadIndices TlsAlloc failed")); exit(1); } } } /* * ioGetThreadLocalThreadIndex & ioSetThreadLocalThreadIndex are defined in * sqPlatformSpecific.h. */ static DWORD duplicateAndSetThreadHandleForCurrentThread(void) { HANDLE threadHandle; DWORD lastError; if (DuplicateHandle(GetCurrentProcess(), // source process handle GetCurrentThread(), // source handle (N.B. pseudo) GetCurrentProcess(), // target process handle &threadHandle, // out param 0,// desired access, ignored if DUPLICATE_SAME_ACCESS TRUE, // handle is inheritable DUPLICATE_SAME_ACCESS)) { // options assert(threadHandle); TlsSetValue(tlthIndex,threadHandle); return 0; } lastError = GetLastError(); printLastError(TEXT("DuplicateHandle")); return lastError; } /* * Re TlsGetValue. From msdn: * "The data stored in a TLS slot can have a value of 0 because it still has its * initial value or because the thread called the TlsSetValue function with 0. * Therefore, if the return value is 0, you must check whether GetLastError * returns ERROR_SUCCESS before determining that the function has failed. * If GetLastError returns ERROR_SUCCESS, then the function has succeeded and * the data stored in the TLS slot is 0. Otherwise, the function has failed." * * But since we never store a null thread handle we can omit this check. */ HANDLE ioCurrentOSThread() { HANDLE threadHandle = TlsGetValue(tlthIndex); if (!threadHandle) (void)duplicateAndSetThreadHandleForCurrentThread(); assert(TlsGetValue(tlthIndex)); return TlsGetValue(tlthIndex); } #if COGMTVM typedef struct { void (*func)(void *); void *arg; } InitTuple; static void * angel(void *arg) { InitTuple it = *(InitTuple *)arg; DWORD err = duplicateAndSetThreadHandleForCurrentThread(); free(arg); if (err) ExitThread(err); it.func(it.arg); return 0; } int ioNewOSThread(void (*func)(void *), void *arg) { HANDLE newThread; InitTuple *it = malloc(sizeof(InitTuple)); if (!it) return ERROR_OUTOFMEMORY; it->func = func; it->arg = arg; newThread = CreateThread(0, /* no security */ 0, /* default stack size */ (LPTHREAD_START_ROUTINE)angel, (void *)it, STACK_SIZE_PARAM_IS_A_RESERVATION, /* creation flags 0 => run immediately */ 0 /* thread id; we don't use it */); if (!newThread) { int err = GetLastError(); return err == 0 ? -1 : err; } /* we need to close this handle so that closing the duplicated handle will * actually release resources. Keeping this handle open will prevent that. */ (void)CloseHandle(newThread); return 0; } int ioOSThreadIsAlive(HANDLE thread) { DWORD result; return GetExitCodeThread(thread, &result) ? FALSE : GetLastError() == STILL_ACTIVE; } void ioExitOSThread(HANDLE thread) { if (thread == ioCurrentOSThread()) { ioReleaseOSThreadState(thread); ExitThread(0); /*NOTREACHED*/ } TerminateThread(thread, 0); ioReleaseOSThreadState(thread); } void ioReleaseOSThreadState(HANDLE thread) { (void)CloseHandle(thread); } int ioNumProcessors(void) { char *nprocs = getenv("NUMBER_OF_PROCESSORS"); return nprocs ? atoi(nprocs) : 1; } int ioNewOSSemaphore(sqOSSemaphore *sem) { *sem = CreateSemaphore( 0, /* don't need no stinkin' security */ 0, /* initial signal count */ LONG_MAX, /* sky's the limit */ 0 /* don't need no stinkin' name */); if (!*sem) printLastError("ioNewOSSemaphore CreateSemaphore"); return *sem ? 0 : GetLastError(); } void ioDestroyOSSemaphore(sqOSSemaphore *sem) { CloseHandle(*sem); } void ioSignalOSSemaphore(sqOSSemaphore *sem) { if (!ReleaseSemaphore(*sem, 1, 0)) abortMessage(TEXT("Fatal: ReleaseMutex(*sem) %ld"), GetLastError()); } void ioWaitOnOSSemaphore(sqOSSemaphore *sem) { if (WaitForSingleObject(*sem, INFINITE) == WAIT_FAILED) abortMessage(TEXT("Fatal: WaitForSingleObject(*sem) %ld"), GetLastError()); } #else /* COGMTVM */ /* This is for sqVirtualMachine.h's default ownVM implementation. */ sqInt amInVMThread() { return ioOSThreadsEqual(ioCurrentOSThread(),getVMOSThread()); } #endif /* COGMTVM */ void ioInitThreads() { extern void ioInitExternalSemaphores(void); initThreadLocalThreadIndices(); #if !COGMTVM ioVMThread = ioCurrentOSThread(); #endif ioInitExternalSemaphores(); } /* this for testing crash dumps */ static sqInt indirect(sqIntptr_t p) { if ((p & 2)) error("crashInThisOrAnotherThread"); return p > 99 ? indirect(p - 100), indirect(p - 50) /* evade tail recursion opt */ : *(sqInt *)p; } /* bit 0 = thread to crash in; 1 => this thread * bit 1 = crash method; 0 => indirect through null pointer; 1 => call exit */ sqInt crashInThisOrAnotherThread(sqInt flags) { if ((flags & 1)) { if (!(flags & 2)) return indirect(flags & ~1); error("crashInThisOrAnotherThread"); return 0; } else { CreateThread(0, /* no security */ 0, /* default stack size */ (LPTHREAD_START_ROUTINE)indirect, (void *)300, STACK_SIZE_PARAM_IS_A_RESERVATION, /* creation flags 0 => run immediately */ 0 /* thread id; we don't use it */); Sleep(1000); } return 0; }
aa9a3b132a854b61d59a633044ee3d97cdf2aab5
8f3bf2d3f72e9c7022b3e2efde3d787c9ca354fc
/test/integration/sys-encrypt-decrypt-2.int.c
bcfc64229ced8e9b2bccd88c0a0da6895e6239ca
[ "BSD-2-Clause" ]
permissive
tpm2-software/tpm2-tss
27dc9cddb545a04958c29839a9cdafb0df54ff3c
b7bad346b4b55def7fd1cd78c8724df00dddd76c
refs/heads/master
2023-09-03T19:58:41.440023
2023-08-15T18:30:40
2023-08-16T07:09:48
38,320,020
563
311
BSD-2-Clause
2023-09-14T08:28:43
2015-06-30T16:21:57
C
UTF-8
C
false
false
3,195
c
sys-encrypt-decrypt-2.int.c
/* SPDX-License-Identifier: BSD-2-Clause */ /*********************************************************************** * Copyright (c) 2017-2018, Intel Corporation * * All rights reserved. ***********************************************************************/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <inttypes.h> #include <stdlib.h> #include <string.h> #define LOGMODULE test #include "util/log.h" #include "sys-util.h" #include "test-esys.h" #include "test.h" #define ENC_STR "test-data-test-data-test-data" /* * This test is intended to exercise the EncryptDecrypt2 command. */ int test_invoke (TSS2_SYS_CONTEXT *sys_context) { TSS2_RC rc; TPM2_HANDLE handle_parent, handle; TPM2B_MAX_BUFFER data_in = { 0 }; TPM2B_MAX_BUFFER data_encrypted = TPM2B_MAX_BUFFER_INIT; TPM2B_MAX_BUFFER data_decrypted = TPM2B_MAX_BUFFER_INIT; data_in.size = strlen (ENC_STR); strcpy ((char*)data_in.buffer, ENC_STR); rc = create_primary_rsa_2048_aes_128_cfb (sys_context, &handle_parent); if (rc != TSS2_RC_SUCCESS) { LOG_ERROR("Failed to create primary RSA 2048 key: 0x%" PRIx32 "", rc); exit(1); } rc = create_aes_128_cfb (sys_context, handle_parent, &handle); if (rc != TSS2_RC_SUCCESS) { LOG_ERROR("Failed to create child AES 128 key: 0x%" PRIx32 "", rc); exit(1); } LOG_INFO("Encrypting data: \"%s\" with key handle: 0x%08" PRIx32, data_in.buffer, handle); rc = tpm_encrypt_2_cfb (sys_context, handle, &data_in, &data_encrypted); if (rc == TPM2_RC_COMMAND_CODE) { LOG_WARNING("Encrypt/Decrypt 2 not supported by TPM"); rc = Tss2_Sys_FlushContext(sys_context, handle_parent); if (rc != TSS2_RC_SUCCESS) { LOG_ERROR("Tss2_Sys_FlushContext failed with 0x%"PRIx32, rc); return 99; /* fatal error */ } rc = Tss2_Sys_FlushContext(sys_context, handle); if (rc != TSS2_RC_SUCCESS) { LOG_ERROR("Tss2_Sys_FlushContext failed with 0x%"PRIx32, rc); return 99; /* fatal error */ } return EXIT_SKIP; } if (rc != TSS2_RC_SUCCESS) { LOG_ERROR("Failed to encrypt buffer: 0x%" PRIx32 "", rc); exit(1); } rc = tpm_decrypt_2_cfb (sys_context, handle, &data_encrypted, &data_decrypted); if (rc != TSS2_RC_SUCCESS) { LOG_ERROR("Failed to encrypt buffer: 0x%" PRIx32 "", rc); exit(1); } LOG_INFO("Decrypted data: \"%s\" with key handle: 0x%08" PRIx32, data_decrypted.buffer, handle); if (strcmp ((char*)data_in.buffer, (char*)data_decrypted.buffer)) { LOG_ERROR("Decrypt succeeded but decrypted data != to input data"); exit(1); } rc = Tss2_Sys_FlushContext(sys_context, handle_parent); if (rc != TSS2_RC_SUCCESS) { LOG_ERROR("Tss2_Sys_FlushContext failed with 0x%"PRIx32, rc); return 99; /* fatal error */ } rc = Tss2_Sys_FlushContext(sys_context, handle); if (rc != TSS2_RC_SUCCESS) { LOG_ERROR("Tss2_Sys_FlushContext failed with 0x%"PRIx32, rc); return 99; /* fatal error */ } return 0; }
296be1dea4f015611ffea451b4f2e29e0943a0f7
fb47ab6337a71029dee71933e449cf7f6805fc0f
/external/platform/cc13xx/cc13xxware/driverlib/aux_wuc.c
bbd7bde8c101c286107c3dd6b27d633e81cdfc09
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
littlekernel/lk
7e7ba50b87b1f2e0b6e2f052c59249825c91975b
30dc320054f70910e1c1ee40a6948ee99672acec
refs/heads/master
2023-09-02T00:47:52.203963
2023-06-21T22:42:35
2023-06-21T22:42:35
3,058,456
3,077
618
MIT
2023-08-30T09:41:31
2011-12-27T19:19:36
C
UTF-8
C
false
false
11,150
c
aux_wuc.c
/****************************************************************************** * Filename: aux_wuc.c * Revised: 2015-06-01 15:19:54 +0200 (Mon, 01 Jun 2015) * Revision: 43689 * * Description: Driver for the AUX Wakeup Controller. * * Copyright (c) 2015, Texas Instruments Incorporated * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1) Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2) 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. * * 3) Neither the name of the ORGANIZATION 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. * ******************************************************************************/ #include <driverlib/aux_wuc.h> //***************************************************************************** // // Handle support for DriverLib in ROM: // This section will undo prototype renaming made in the header file // //***************************************************************************** #if !defined(DOXYGEN) #undef AUXWUCClockEnable #define AUXWUCClockEnable NOROM_AUXWUCClockEnable #undef AUXWUCClockDisable #define AUXWUCClockDisable NOROM_AUXWUCClockDisable #undef AUXWUCClockStatus #define AUXWUCClockStatus NOROM_AUXWUCClockStatus #undef AUXWUCPowerCtrl #define AUXWUCPowerCtrl NOROM_AUXWUCPowerCtrl #endif //**************************************************************************** // //! Enable clocks for peripherals in the AUX domain // //**************************************************************************** void AUXWUCClockEnable(uint32_t ui32Clocks) { // // Check the arguments. // ASSERT((ui32Clocks & AUX_WUC_ADI_CLOCK) || (ui32Clocks & AUX_WUC_OSCCTRL_CLOCK) || (ui32Clocks & AUX_WUC_TDCIF_CLOCK) || (ui32Clocks & AUX_WUC_ANAIF_CLOCK) || (ui32Clocks & AUX_WUC_TIMER_CLOCK) || (ui32Clocks & AUX_WUC_AIODIO0_CLOCK) || (ui32Clocks & AUX_WUC_AIODIO1_CLOCK) || (ui32Clocks & AUX_WUC_SMPH_CLOCK) || (ui32Clocks & AUX_WUC_TDC_CLOCK) || (ui32Clocks & AUX_WUC_ADC_CLOCK) || (ui32Clocks & AUX_WUC_REF_CLOCK)); // // Enable some of the clocks in the clock register. // HWREG(AUX_WUC_BASE + AUX_WUC_O_MODCLKEN0) |= (ui32Clocks & AUX_WUC_MODCLK_MASK); // // Check the rest. // if(ui32Clocks & AUX_WUC_ADC_CLOCK) { HWREG(AUX_WUC_BASE + AUX_WUC_O_ADCCLKCTL) = AUX_WUC_ADCCLKCTL_REQ; } if(ui32Clocks & AUX_WUC_TDC_CLOCK) { HWREG(AUX_WUC_BASE + AUX_WUC_O_TDCCLKCTL) = AUX_WUC_TDCCLKCTL_REQ; } if(ui32Clocks & AUX_WUC_REF_CLOCK) { HWREG(AUX_WUC_BASE + AUX_WUC_O_REFCLKCTL) = AUX_WUC_REFCLKCTL_REQ; } } //**************************************************************************** // //! Disable clocks for peripherals in the AUX domain // //**************************************************************************** void AUXWUCClockDisable(uint32_t ui32Clocks) { // // Check the arguments. // ASSERT((ui32Clocks & AUX_WUC_ADI_CLOCK) || (ui32Clocks & AUX_WUC_OSCCTRL_CLOCK) || (ui32Clocks & AUX_WUC_TDCIF_CLOCK) || (ui32Clocks & AUX_WUC_ANAIF_CLOCK) || (ui32Clocks & AUX_WUC_TIMER_CLOCK) || (ui32Clocks & AUX_WUC_AIODIO0_CLOCK) || (ui32Clocks & AUX_WUC_AIODIO1_CLOCK) || (ui32Clocks & AUX_WUC_SMPH_CLOCK) || (ui32Clocks & AUX_WUC_TDC_CLOCK) || (ui32Clocks & AUX_WUC_ADC_CLOCK) || (ui32Clocks & AUX_WUC_REF_CLOCK)); // // Disable some of the clocks in the clock register. // HWREG(AUX_WUC_BASE + AUX_WUC_O_MODCLKEN0) &= ~(ui32Clocks & AUX_WUC_MODCLK_MASK); // // Check the rest. // if(ui32Clocks & AUX_WUC_ADC_CLOCK) { HWREG(AUX_WUC_BASE + AUX_WUC_O_ADCCLKCTL) &= ~AUX_WUC_ADCCLKCTL_REQ; } if(ui32Clocks & AUX_WUC_TDC_CLOCK) { HWREG(AUX_WUC_BASE + AUX_WUC_O_TDCCLKCTL) &= ~AUX_WUC_TDCCLKCTL_REQ; } if(ui32Clocks & AUX_WUC_REF_CLOCK) { HWREG(AUX_WUC_BASE + AUX_WUC_O_REFCLKCTL) &= ~AUX_WUC_REFCLKCTL_REQ; } } //**************************************************************************** // //! Get the status of a clock // //**************************************************************************** uint32_t AUXWUCClockStatus(uint32_t ui32Clocks) { bool bClockStatus; uint32_t ui32ClockRegister; // // Check the arguments. // ASSERT((ui32Clocks & AUX_WUC_ADI_CLOCK) || (ui32Clocks & AUX_WUC_OSCCTRL_CLOCK) || (ui32Clocks & AUX_WUC_TDCIF_CLOCK) || (ui32Clocks & AUX_WUC_ANAIF_CLOCK) || (ui32Clocks & AUX_WUC_TIMER_CLOCK) || (ui32Clocks & AUX_WUC_AIODIO0_CLOCK) || (ui32Clocks & AUX_WUC_AIODIO1_CLOCK) || (ui32Clocks & AUX_WUC_SMPH_CLOCK) || (ui32Clocks & AUX_WUC_TDC_CLOCK) || (ui32Clocks & AUX_WUC_ADC_CLOCK) || (ui32Clocks & AUX_WUC_REF_CLOCK)); bClockStatus = true; // // Read the status registers. // ui32ClockRegister = HWREG(AUX_WUC_BASE + AUX_WUC_O_MODCLKEN0); // // Check all requested clocks // if(ui32Clocks & AUX_WUC_ADI_CLOCK) { bClockStatus = bClockStatus && (ui32ClockRegister & AUX_WUC_MODCLKEN0_AUX_ADI4 ? true : false); } if(ui32Clocks & AUX_WUC_OSCCTRL_CLOCK) { bClockStatus = bClockStatus && (ui32ClockRegister & AUX_WUC_MODCLKEN0_AUX_DDI0_OSC ? true : false); } if(ui32Clocks & AUX_WUC_TDCIF_CLOCK) { bClockStatus = bClockStatus && (ui32ClockRegister & AUX_WUC_MODCLKEN0_TDC ? true : false); } if(ui32Clocks & AUX_WUC_ANAIF_CLOCK) { bClockStatus = bClockStatus && (ui32ClockRegister & AUX_WUC_MODCLKEN0_ANAIF ? true : false); } if(ui32Clocks & AUX_WUC_TIMER_CLOCK) { bClockStatus = bClockStatus && (ui32ClockRegister & AUX_WUC_MODCLKEN0_TIMER ? true : false); } if(ui32Clocks & AUX_WUC_AIODIO0_CLOCK) { bClockStatus = bClockStatus && (ui32ClockRegister & AUX_WUC_MODCLKEN0_AIODIO0 ? true : false); } if(ui32Clocks & AUX_WUC_AIODIO1_CLOCK) { bClockStatus = bClockStatus && (ui32ClockRegister & AUX_WUC_MODCLKEN0_AIODIO1 ? true : false); } if(ui32Clocks & AUX_WUC_SMPH_CLOCK) { bClockStatus = bClockStatus && (ui32ClockRegister & AUX_WUC_MODCLKEN0_SMPH ? true : false); } if(ui32Clocks & AUX_WUC_ADC_CLOCK) { ui32ClockRegister = HWREG(AUX_WUC_BASE + AUX_WUC_O_ADCCLKCTL); bClockStatus = bClockStatus && (ui32ClockRegister & AUX_WUC_ADCCLKCTL_ACK ? true : false); } if(ui32Clocks & AUX_WUC_TDC_CLOCK) { ui32ClockRegister = HWREG(AUX_WUC_BASE + AUX_WUC_O_TDCCLKCTL); bClockStatus = bClockStatus && (ui32ClockRegister & AUX_WUC_TDCCLKCTL_ACK ? true : false); } if(ui32Clocks & AUX_WUC_REF_CLOCK) { ui32ClockRegister = HWREG(AUX_WUC_BASE + AUX_WUC_O_REFCLKCTL); bClockStatus = bClockStatus && (ui32ClockRegister & AUX_WUC_REFCLKCTL_ACK ? true : false); } // // Return the clock status. // return bClockStatus ? AUX_WUC_CLOCK_READY : AUX_WUC_CLOCK_OFF; } //**************************************************************************** // //! Control the power to the AUX domain // //**************************************************************************** void AUXWUCPowerCtrl(uint32_t ui32PowerMode) { // // Check the arguments. // ASSERT((ui32PowerMode == AUX_WUC_POWER_OFF) || (ui32PowerMode == AUX_WUC_POWER_DOWN) || (ui32PowerMode == AUX_WUC_POWER_ACTIVE)); // // Power on/off. // if(ui32PowerMode == AUX_WUC_POWER_OFF) { HWREG(AUX_WUC_BASE + AUX_WUC_O_PWROFFREQ) = AUX_WUC_PWROFFREQ_REQ; HWREG(AUX_WUC_BASE + AUX_WUC_O_MCUBUSCTL) = AUX_WUC_MCUBUSCTL_DISCONNECT_REQ; return; } else { HWREG(AUX_WUC_BASE + AUX_WUC_O_PWROFFREQ) = 0x0; } // // Power down/active. // if(ui32PowerMode == AUX_WUC_POWER_DOWN) { HWREG(AUX_WUC_BASE + AUX_WUC_O_PWRDWNREQ) = AUX_WUC_PWRDWNREQ_REQ; HWREG(AUX_WUC_BASE + AUX_WUC_O_MCUBUSCTL) = AUX_WUC_MCUBUSCTL_DISCONNECT_REQ; } else { HWREG(AUX_WUC_BASE + AUX_WUC_O_PWRDWNREQ) = 0x0; } }