code
stringlengths
1.03k
250k
repo_name
stringlengths
7
70
path
stringlengths
4
177
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
1.03k
250k
#include "yinyang.h" #include "kmeans_utils.h" #include "../../utils/matrix/csr_matrix/csr_to_vector_list.h" #include "../../utils/matrix/vector_list/vector_list_math.h" #include "../../utils/matrix/csr_matrix/csr_math.h" #include "../../utils/vector/common/common_vector_math.h" #include "../../utils/vector/sparse/sparse_vector_math.h" #include "../../utils/fcl_logging.h" #include <math.h> #include <unistd.h> #include <float.h> struct kmeans_result* yinyang_kmeans(struct csr_matrix* samples, struct kmeans_params *prms) { uint32_t i; uint64_t j; uint64_t block_vectors_dim; uint64_t no_groups; uint32_t disable_optimizations; uint64_t keys_per_block; VALUE_TYPE desired_bv_annz; /* desired size of the block vectors */ uint64_t *cluster_to_group; struct csr_matrix block_vectors_samples; struct sparse_vector* block_vectors_clusters; /* block vector matrix of clusters */ struct general_kmeans_context ctx; struct kmeans_result* res; VALUE_TYPE *distance_clustersold_to_clustersnew; struct group* groups; VALUE_TYPE *group_max_drift; VALUE_TYPE **lower_bounds; disable_optimizations = prms->kmeans_algorithm_id == ALGORITHM_YINYANG; initialize_general_context(prms, &ctx, samples); desired_bv_annz = d_get_subfloat_default(&(prms->tr) , "additional_params", "bv_annz", 0.3); block_vectors_dim = 0; keys_per_block = 0; if (!disable_optimizations) { initialize_csr_matrix_zero(&block_vectors_samples); if (prms->kmeans_algorithm_id == ALGORITHM_BV_YINYANG) { /* search for a suitable size of the block vectors for the input samples and create them */ search_samples_block_vectors(prms, ctx.samples, desired_bv_annz , &block_vectors_samples , &block_vectors_dim); } if (prms->kmeans_algorithm_id == ALGORITHM_BV_YINYANG_ONDEMAND) { block_vectors_dim = search_block_vector_size(ctx.samples, desired_bv_annz, prms->verbose); keys_per_block = ctx.samples->dim / block_vectors_dim; if (ctx.samples->dim % block_vectors_dim > 0) keys_per_block++; } /* create block vectors for the clusters */ create_block_vectors_list_from_vector_list(ctx.cluster_vectors , block_vectors_dim , ctx.no_clusters , ctx.samples->dim , &block_vectors_clusters); } distance_clustersold_to_clustersnew = (VALUE_TYPE*) calloc(ctx.no_clusters, sizeof(VALUE_TYPE)); /* no_groups is set to no_clusters / 10 as suggested in the yinyang paper */ no_groups = ctx.no_clusters / 10; if (no_groups == 0) no_groups = 1; /* create yinyang cluster groups by doing 5 k-means iterations on the clusters */ create_kmeans_cluster_groups(ctx.cluster_vectors , ctx.no_clusters , ctx.samples->sample_count , &groups, &no_groups); group_max_drift = (VALUE_TYPE*) calloc(no_groups, sizeof(VALUE_TYPE)); lower_bounds = (VALUE_TYPE**) calloc(ctx.samples->sample_count, sizeof(VALUE_TYPE*)); for (i = 0; i < ctx.samples->sample_count; i++) { lower_bounds[i] = (VALUE_TYPE*) calloc(no_groups, sizeof(VALUE_TYPE)); } cluster_to_group = (uint64_t*) calloc(ctx.no_clusters, sizeof(uint64_t)); for (i = 0; i < no_groups; i++) { for (j = 0; j < groups[i].no_clusters; j++) { cluster_to_group[groups[i].clusters[j]] = i; } } for (i = 0; i < prms->iteration_limit && !ctx.converged && !prms->stop; i++) { uint64_t saved_calculations_prev_cluster, saved_calculations_bv; uint64_t saved_calculations_global, saved_calculations_local; uint64_t done_blockvector_calcs; uint64_t groups_not_skipped; done_blockvector_calcs = 0; saved_calculations_bv = 0; saved_calculations_global = 0; saved_calculations_local = 0; saved_calculations_prev_cluster = 0; groups_not_skipped = 0; /* initialize data needed for the iteration */ pre_process_iteration(&ctx); if (i == 0) { /* first iteration is done with regular kmeans to find the upper and lower bounds */ uint64_t sample_id, l; /* do one regular kmeans step to initialize bounds */ #pragma omp parallel for schedule(dynamic, 1000) private(l) for (sample_id = 0; sample_id < ctx.samples->sample_count; sample_id++) { uint64_t cluster_id; VALUE_TYPE dist; uint32_t is_first_assignment; struct sparse_vector bv; bv.nnz = 0; bv.keys = NULL; bv.values = NULL; is_first_assignment = 0; if (omp_get_thread_num() == 0) check_signals(&(prms->stop)); if (!prms->stop) { for (l = 0; l < no_groups; l++) { lower_bounds[sample_id][l] = DBL_MAX; } for (cluster_id = 0; cluster_id < ctx.no_clusters; cluster_id++) { if (!disable_optimizations) { /* block vector optimizations */ /* check if sqrt( ||s||² + ||c||² - 2*< s_B, c_B > ) >= ctx.cluster_distances[sample_id] */ if (prms->kmeans_algorithm_id == ALGORITHM_BV_YINYANG) { /* evaluate block vector approximation. */ dist = euclid_vector_list(&block_vectors_samples, sample_id , block_vectors_clusters, cluster_id , ctx.vector_lengths_samples , ctx.vector_lengths_clusters); } else { /* kmeans_algorithm_id == ALGORITHM_BV_YINYANG_ONDEMAND */ if (bv.keys == NULL) { create_block_vector_from_csr_matrix_vector(ctx.samples , sample_id , keys_per_block , &bv); } dist = euclid_vector(bv.keys, bv.values, bv.nnz , block_vectors_clusters[cluster_id].keys , block_vectors_clusters[cluster_id].values , block_vectors_clusters[cluster_id].nnz , ctx.vector_lengths_samples[sample_id] , ctx.vector_lengths_clusters[cluster_id]); } done_blockvector_calcs += 1; /* we do this fabs to not run into numeric errors */ if (dist >= ctx.cluster_distances[sample_id] && fabs(dist - ctx.cluster_distances[sample_id]) >= 1e-6) { saved_calculations_bv += 1; goto end_cluster_init; } } dist = euclid_vector_list(samples, sample_id, ctx.cluster_vectors, cluster_id , ctx.vector_lengths_samples, ctx.vector_lengths_clusters); /*#pragma omp critical*/ ctx.done_calculations += 1; if (dist < ctx.cluster_distances[sample_id]) { if (is_first_assignment) { is_first_assignment = 0; } else { lower_bounds[sample_id][cluster_to_group[ctx.cluster_assignments[sample_id]]] = ctx.cluster_distances[sample_id]; } ctx.cluster_distances[sample_id] = dist; ctx.cluster_assignments[sample_id] = cluster_id; } else { end_cluster_init:; if (dist < lower_bounds[sample_id][cluster_to_group[cluster_id]]) { lower_bounds[sample_id][cluster_to_group[cluster_id]] = dist; } } } } if (!disable_optimizations) { free_null(bv.keys); free_null(bv.values); } } } else { #pragma omp parallel for schedule(dynamic, 1000) for (j = 0; j < ctx.samples->sample_count; j++) { VALUE_TYPE dist; uint64_t cluster_id, sample_id, l; VALUE_TYPE *temp_lower_bounds; VALUE_TYPE global_lower_bound; VALUE_TYPE *should_group_be_updated; struct sparse_vector bv; bv.nnz = 0; bv.keys = NULL; bv.values = NULL; sample_id = j; if (omp_get_thread_num() == 0) check_signals(&(prms->stop)); if (!prms->stop) { /* update upper bound of this sample with drift of assigned cluster */ ctx.cluster_distances[sample_id] = ctx.cluster_distances[sample_id] + distance_clustersold_to_clustersnew[ctx.cluster_assignments[sample_id]]; temp_lower_bounds = (VALUE_TYPE*) calloc(no_groups, sizeof(VALUE_TYPE)); should_group_be_updated = (VALUE_TYPE*) calloc(no_groups, sizeof(VALUE_TYPE)); global_lower_bound = DBL_MAX; for (l = 0; l < no_groups; l++) { temp_lower_bounds[l] = lower_bounds[sample_id][l]; lower_bounds[sample_id][l] = lower_bounds[sample_id][l] - group_max_drift[l]; if (global_lower_bound > lower_bounds[sample_id][l]) global_lower_bound = lower_bounds[sample_id][l]; } /* check if the global lower bound is already bigger than the current upper bound */ if (global_lower_bound >= ctx.cluster_distances[sample_id]) { saved_calculations_global += ctx.no_clusters; goto end; } /* tighten the upper bound by calculating the actual distance to the current closest cluster */ ctx.cluster_distances[sample_id] = euclid_vector_list(samples, sample_id, ctx.cluster_vectors, ctx.cluster_assignments[sample_id] , ctx.vector_lengths_samples, ctx.vector_lengths_clusters); /*#pragma omp critical*/ ctx.done_calculations += 1; /* recheck if the global lower bound is now bigger than the current upper bound */ if (global_lower_bound >= ctx.cluster_distances[sample_id]) { saved_calculations_global += ctx.no_clusters - 1; goto end; } for (l = 0; l < no_groups; l++) { if (lower_bounds[sample_id][l] < ctx.cluster_distances[sample_id]) { should_group_be_updated[l] = 1; groups_not_skipped += 1; lower_bounds[sample_id][l] = DBL_MAX; } } for (cluster_id = 0; cluster_id < ctx.no_clusters; cluster_id++) { if (!should_group_be_updated[cluster_to_group[cluster_id]]) { saved_calculations_prev_cluster++; continue; } if (ctx.cluster_counts[cluster_id] == 0 || cluster_id == ctx.previous_cluster_assignments[sample_id]) continue; if (lower_bounds[sample_id][cluster_to_group[cluster_id]] < temp_lower_bounds[cluster_to_group[cluster_id]] - distance_clustersold_to_clustersnew[cluster_id]) { dist = lower_bounds[sample_id][cluster_to_group[cluster_id]]; saved_calculations_local += 1; goto end_cluster; } if (!disable_optimizations) { if (i < 15) { /* block vector optimizations */ /* check if sqrt( ||s||² + ||c||² - 2*< s_B, c_B > ) >= ctx.cluster_distances[sample_id] */ if (prms->kmeans_algorithm_id == ALGORITHM_BV_YINYANG) { /* evaluate block vector approximation. */ dist = euclid_vector_list(&block_vectors_samples, sample_id , block_vectors_clusters, cluster_id , ctx.vector_lengths_samples , ctx.vector_lengths_clusters); } else { /* kmeans_algorithm_id == ALGORITHM_BV_YINYANG_ONDEMAND */ if (bv.keys == NULL) { create_block_vector_from_csr_matrix_vector(ctx.samples , sample_id , keys_per_block , &bv); } dist = euclid_vector(bv.keys, bv.values, bv.nnz , block_vectors_clusters[cluster_id].keys , block_vectors_clusters[cluster_id].values , block_vectors_clusters[cluster_id].nnz , ctx.vector_lengths_samples[sample_id] , ctx.vector_lengths_clusters[cluster_id]); } done_blockvector_calcs += 1; if (dist >= ctx.cluster_distances[sample_id] && fabs(dist - ctx.cluster_distances[sample_id]) >= 1e-6) { saved_calculations_bv += 1; goto end_cluster; } } } dist = euclid_vector_list(samples, sample_id, ctx.cluster_vectors, cluster_id , ctx.vector_lengths_samples, ctx.vector_lengths_clusters); /*#pragma omp critical*/ ctx.done_calculations += 1; if (dist < ctx.cluster_distances[sample_id]) { lower_bounds[sample_id][cluster_to_group[ctx.cluster_assignments[sample_id]]] = ctx.cluster_distances[sample_id]; ctx.cluster_distances[sample_id] = dist; ctx.cluster_assignments[sample_id] = cluster_id; } else { end_cluster:; if (dist < lower_bounds[sample_id][cluster_to_group[cluster_id]]) { lower_bounds[sample_id][cluster_to_group[cluster_id]] = dist; } } } end:; free(should_group_be_updated); free(temp_lower_bounds); } if (!disable_optimizations) { free_null(bv.keys); free_null(bv.values); } } /* block iterate over samples */ } /* block is first iteration */ post_process_iteration(&ctx, prms); /* shift clusters to new position */ calculate_shifted_clusters(&ctx); /* calculate distance between a cluster before and after the shift */ calculate_distance_clustersold_to_clustersnew(distance_clustersold_to_clustersnew , ctx.shifted_cluster_vectors , ctx.cluster_vectors , ctx.no_clusters , ctx.vector_lengths_shifted_clusters , ctx.vector_lengths_clusters , ctx.clusters_not_changed); switch_to_shifted_clusters(&ctx); /* ------------ calculate maximum drift for every group ------------- */ { uint64_t *clusters; uint64_t n_clusters, l, k; VALUE_TYPE drift; for (l = 0; l < no_groups; l++) { clusters = groups[l].clusters; n_clusters = groups[l].no_clusters; group_max_drift[l] = 0; for (k = 0; k < n_clusters; k++) { drift = distance_clustersold_to_clustersnew[clusters[k]]; if (group_max_drift[l] < drift) group_max_drift[l] = drift; } } } if (!disable_optimizations) { /* update only block vectors for cluster that shifted */ update_changed_blockvectors(ctx.cluster_vectors , block_vectors_dim , ctx.no_clusters , ctx.samples->dim , ctx.clusters_not_changed , block_vectors_clusters); d_add_ilist(&(prms->tr), "iteration_bv_calcs", done_blockvector_calcs); d_add_ilist(&(prms->tr), "iteration_bv_calcs_success", saved_calculations_bv); } print_iteration_summary(&ctx, prms, i); /* print block vector and yinyang statistics */ if (prms->verbose) LOG_INFO("statistics [BV] b:%" PRINTF_INT64_MODIFIER "u/db:%" PRINTF_INT64_MODIFIER "u [YY] grp_not_skip=%" PRINTF_INT64_MODIFIER "u/pc:%" PRINTF_INT64_MODIFIER "u/g=%" PRINTF_INT64_MODIFIER "u/l=%" PRINTF_INT64_MODIFIER "u" , saved_calculations_bv , done_blockvector_calcs , groups_not_skipped , saved_calculations_prev_cluster , saved_calculations_global , saved_calculations_local); } if (prms->verbose) LOG_INFO("total total_no_calcs = %" PRINTF_INT64_MODIFIER "u", ctx.total_no_calcs); res = create_kmeans_result(prms, &ctx); /* cleanup all */ if (!disable_optimizations) { free_csr_matrix(&block_vectors_samples); free_vector_list(block_vectors_clusters, ctx.no_clusters); free(block_vectors_clusters); } free_general_context(&ctx, prms); free_null(distance_clustersold_to_clustersnew); free_null(group_max_drift); for (i = 0; i < ctx.samples->sample_count; i++) { free_null(lower_bounds[i]); } for (i = 0; i < no_groups; i++) { free_null(groups[i].clusters); } free_null(groups); free_null(lower_bounds); free_null(cluster_to_group); return res; }
thomas-bottesch/fcl
algorithms/kmeans/yinyang.c
C
mit
20,368
#include <stddef.h> #define _GNU_SOURCE #include <sys/uio.h> #include <sys/socket.h> #include "brubeck.h" #ifdef __GLIBC__ # if ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12))) # define HAVE_RECVMMSG 1 # endif #endif #define MAX_PACKET_SIZE 512 #ifdef HAVE_RECVMMSG static void statsd_run_recvmmsg(struct brubeck_statsd *statsd, int sock) { const unsigned int SIM_PACKETS = statsd->mmsg_count; struct brubeck_server *server = statsd->sampler.server; struct brubeck_statsd_msg msg; struct brubeck_metric *metric; unsigned int i; struct iovec iovecs[SIM_PACKETS]; struct mmsghdr msgs[SIM_PACKETS]; memset(msgs, 0x0, sizeof(msgs)); for (i = 0; i < SIM_PACKETS; ++i) { iovecs[i].iov_base = xmalloc(MAX_PACKET_SIZE); iovecs[i].iov_len = MAX_PACKET_SIZE; msgs[i].msg_hdr.msg_iov = &iovecs[i]; msgs[i].msg_hdr.msg_iovlen = 1; } log_splunk("sampler=statsd event=worker_online syscall=recvmmsg socket=%d", sock); for (;;) { int res = recvmmsg(sock, msgs, SIM_PACKETS, 0, NULL); if (res == EAGAIN || res == EINTR || res == 0) continue; /* store stats */ brubeck_atomic_add(&server->stats.metrics, SIM_PACKETS); brubeck_atomic_add(&statsd->sampler.inflow, SIM_PACKETS); if (res < 0) { brubeck_server_mark_dropped(server); continue; } for (i = 0; i < SIM_PACKETS; ++i) { char *buf = msgs[i].msg_hdr.msg_iov->iov_base; int len = msgs[i].msg_len; if (brubeck_statsd_msg_parse(&msg, buf, len) < 0) { brubeck_server_mark_dropped(server); log_splunk("sampler=statsd event=packet_drop"); continue; } metric = brubeck_metric_find(server, msg.key, msg.key_len, msg.type); if (metric != NULL) brubeck_metric_record(metric, msg.value); } } } #endif static void statsd_run_recvmsg(struct brubeck_statsd *statsd, int sock) { struct brubeck_server *server = statsd->sampler.server; struct brubeck_statsd_msg msg; struct brubeck_metric *metric; char buffer[MAX_PACKET_SIZE]; struct sockaddr_in reporter; socklen_t reporter_len = sizeof(reporter); memset(&reporter, 0, reporter_len); log_splunk("sampler=statsd event=worker_online syscall=recvmsg socket=%d", sock); for (;;) { int res = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&reporter, &reporter_len); if (res == EAGAIN || res == EINTR || res == 0) continue; /* store stats */ brubeck_atomic_inc(&server->stats.metrics); brubeck_atomic_inc(&statsd->sampler.inflow); if (res < 0) { brubeck_server_mark_dropped(server); log_splunk_errno("sampler=statsd event=failed_read from=%s", inet_ntoa(reporter.sin_addr)); continue; } if (brubeck_statsd_msg_parse(&msg, buffer, (size_t)res) < 0) { if (msg.key_len > 0) buffer[msg.key_len] = ':'; log_splunk("sampler=statsd event=bad_key key='%.*s' from=%s", res, buffer, inet_ntoa(reporter.sin_addr)); brubeck_server_mark_dropped(server); continue; } metric = brubeck_metric_find(server, msg.key, msg.key_len, msg.type); if (metric != NULL) { brubeck_metric_record(metric, msg.value); } } } int brubeck_statsd_msg_parse(struct brubeck_statsd_msg *msg, char *buffer, size_t length) { char *end = buffer + length; *end = '\0'; /** * Message key: all the string until the first ':' * * gaugor:333|g * ^^^^^^ */ { msg->key = buffer; msg->key_len = 0; while (*buffer != ':' && *buffer != '\0') { /* Invalid metric, can't have a space */ if (*buffer == ' ') return -1; ++buffer; } if (*buffer == '\0') return -1; msg->key_len = buffer - msg->key; *buffer++ = '\0'; /* Corrupted metric. Graphite won't swallow this */ if (msg->key[msg->key_len - 1] == '.') return -1; } /** * Message value: the numeric value between ':' and '|'. * This is already converted to an integer. * * gaugor:333|g * ^^^ */ { int negative = 0; char *start = buffer; msg->value = 0.0; if (*buffer == '-') { ++buffer; negative = 1; } while (*buffer >= '0' && *buffer <= '9') { msg->value = (msg->value * 10.0) + (*buffer - '0'); ++buffer; } if (*buffer == '.') { double f = 0.0, n = 0.0; ++buffer; while (*buffer >= '0' && *buffer <= '9') { f = (f * 10.0) + (*buffer - '0'); ++buffer; n += 1.0; } msg->value += f / pow(10.0, n); } if (negative) msg->value = -msg->value; if (unlikely(*buffer == 'e')) { msg->value = strtod(start, &buffer); } if (*buffer != '|') return -1; buffer++; } /** * Message type: one or two char identifier with the * message type. Valid values: g, c, C, h, ms * * gaugor:333|g * ^ */ { switch (*buffer) { case 'g': msg->type = BRUBECK_MT_GAUGE; break; case 'c': msg->type = BRUBECK_MT_METER; break; case 'C': msg->type = BRUBECK_MT_COUNTER; break; case 'h': msg->type = BRUBECK_MT_HISTO; break; case 'm': ++buffer; if (*buffer == 's') { msg->type = BRUBECK_MT_TIMER; break; } default: return -1; } } /** * Trailing bytes: data appended at the end of the message. * This is stored verbatim and will be parsed when processing * the specific message type. This is optional. * * gorets:1|c|@0.1 * ^^^^---- */ { buffer++; if (buffer[0] == '\0' || (buffer[0] == '\n' && buffer[1] == '\0')) { msg->trail = NULL; return 0; } if (*buffer == '@' || *buffer == '|') { msg->trail = buffer; return 0; } return -1; } } static void *statsd__thread(void *_in) { struct brubeck_statsd *statsd = _in; int sock = statsd->sampler.in_sock; #ifdef SO_REUSEPORT if (sock < 0) { sock = brubeck_sampler_socket(&statsd->sampler, 1); } #endif assert(sock >= 0); #ifdef HAVE_RECVMMSG if (statsd->mmsg_count > 1) { statsd_run_recvmmsg(statsd, sock); return NULL; } #endif statsd_run_recvmsg(statsd, sock); return NULL; } static void run_worker_threads(struct brubeck_statsd *statsd) { unsigned int i; statsd->workers = xmalloc(statsd->worker_count * sizeof(pthread_t)); for (i = 0; i < statsd->worker_count; ++i) { pthread_create(&statsd->workers[i], NULL, &statsd__thread, statsd); } } static void shutdown_sampler(struct brubeck_sampler *sampler) { struct brubeck_statsd *statsd = (struct brubeck_statsd *)sampler; size_t i; for (i = 0; i < statsd->worker_count; ++i) { pthread_cancel(statsd->workers[i]); } } struct brubeck_sampler * brubeck_statsd_new(struct brubeck_server *server, json_t *settings) { struct brubeck_statsd *std = xmalloc(sizeof(struct brubeck_statsd)); char *address; int port; int multisock = 0; std->sampler.type = BRUBECK_SAMPLER_STATSD; std->sampler.shutdown = &shutdown_sampler; std->sampler.in_sock = -1; std->worker_count = 4; std->mmsg_count = 1; json_unpack_or_die(settings, "{s:s, s:i, s?:i, s?:i, s?:b}", "address", &address, "port", &port, "workers", &std->worker_count, "multimsg", &std->mmsg_count, "multisock", &multisock); brubeck_sampler_init_inet(&std->sampler, server, address, port); #ifndef SO_REUSEPORT multisock = 0; #endif if (!multisock) std->sampler.in_sock = brubeck_sampler_socket(&std->sampler, 0); run_worker_threads(std); return &std->sampler; }
IonicaBizauKitchen/brubeck
src/samplers/statsd.c
C
mit
7,290
/* FreeRTOS V7.4.0 - Copyright (C) 2013 Real Time Engineers Ltd. FEATURES AND PORTS ARE ADDED TO FREERTOS ALL THE TIME. PLEASE VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. *************************************************************************** * * * FreeRTOS tutorial books are available in pdf and paperback. * * Complete, revised, and edited pdf reference manuals are also * * available. * * * * Purchasing FreeRTOS documentation will not only help you, by * * ensuring you get running as quickly as possible and with an * * in-depth knowledge of how to use FreeRTOS, it will also help * * the FreeRTOS project to continue with its mission of providing * * professional grade, cross platform, de facto standard solutions * * for microcontrollers - completely free of charge! * * * * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * * * * Thank you for using FreeRTOS, and thank you for your support! * * * *************************************************************************** This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation AND MODIFIED BY the FreeRTOS exception. >>>>>>NOTE<<<<<< The modification to the GPL is included to allow you to distribute a combined work that includes FreeRTOS without being obliged to provide the source code for proprietary components outside of the FreeRTOS kernel. FreeRTOS 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 and the FreeRTOS license exception along with FreeRTOS; if not itcan be viewed here: http://www.freertos.org/a00114.html and also obtained by writing to Real Time Engineers Ltd., contact details for whom are available on the FreeRTOS WEB site. 1 tab == 4 spaces! *************************************************************************** * * * Having a problem? Start by reading the FAQ "My application does * * not run, what could be wrong?" * * * * http://www.FreeRTOS.org/FAQHelp.html * * * *************************************************************************** http://www.FreeRTOS.org - Documentation, books, training, latest versions, license and Real Time Engineers Ltd. contact details. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, and our new fully thread aware and reentrant UDP/IP stack. http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High Integrity Systems, who sell the code with commercial support, indemnification and middleware, under the OpenRTOS brand. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. */ /*----------------------------------------------------------- * Characters on the LCD are used to simulate LED's. In this case the 'ParTest' * is really operating on the LCD display. *-----------------------------------------------------------*/ /* * This demo is configured to execute on the ES449 prototyping board from * SoftBaugh. The ES449 has a built in LCD display and a single built in user * LED. Therefore, in place of flashing an LED, the 'flash' and 'check' tasks * toggle '*' characters on the LCD. The left most '*' represents LED 0, the * next LED 1, etc. * * There is a single genuine on board LED referenced as LED 10. */ /* Standard includes. */ #include <signal.h> /* Scheduler includes. */ #include "FreeRTOS.h" #include "task.h" /* Demo application includes. */ #include "partest.h" /* Constants required to setup the LCD. */ #define LCD_DIV_64 5 /* Constants required to access the "LED's". The LED segments are turned on and off to generate '*' characters. */ #define partstNUM_LEDS ( ( unsigned char ) 6 ) #define partstSEGMENTS_ON ( ( unsigned char ) 0x0f ) #define partstSEGMENTS_OFF ( ( unsigned char ) 0x00 ) /* The LED number of the real on board LED, rather than a simulated LED. */ #define partstON_BOARD_LED ( ( unsigned portBASE_TYPE ) 10 ) #define mainON_BOARD_LED_BIT ( ( unsigned char ) 0x01 ) /* The LCD segments used to generate the '*' characters for LED's 0 to 5. */ unsigned char * const ucRHSSegments[ partstNUM_LEDS ] = { ( unsigned char * )0xa4, ( unsigned char * )0xa2, ( unsigned char * )0xa0, ( unsigned char * )0x9e, ( unsigned char * )0x9c, ( unsigned char * )0x9a }; unsigned char * const ucLHSSegments[ partstNUM_LEDS ] = { ( unsigned char * )0xa3, ( unsigned char * )0xa1, ( unsigned char * )0x9f, ( unsigned char * )0x9d, ( unsigned char * )0x9b, ( unsigned char * )0x99 }; /* * Toggle the single genuine built in LED. */ static void prvToggleOnBoardLED( void ); /*-----------------------------------------------------------*/ void vParTestInitialise( void ) { /* Initialise the LCD hardware. */ /* Used for the onboard LED. */ P1DIR = 0x01; // Setup Basic Timer for LCD operation BTCTL = (LCD_DIV_64+0x23); // Setup port functions P1SEL = 0x32; P2SEL = 0x00; P3SEL = 0x00; P4SEL = 0xFC; P5SEL = 0xFF; /* Initialise all segments to off. */ LCDM1 = partstSEGMENTS_OFF; LCDM2 = partstSEGMENTS_OFF; LCDM3 = partstSEGMENTS_OFF; LCDM4 = partstSEGMENTS_OFF; LCDM5 = partstSEGMENTS_OFF; LCDM6 = partstSEGMENTS_OFF; LCDM7 = partstSEGMENTS_OFF; LCDM8 = partstSEGMENTS_OFF; LCDM9 = partstSEGMENTS_OFF; LCDM10 = partstSEGMENTS_OFF; LCDM11 = partstSEGMENTS_OFF; LCDM12 = partstSEGMENTS_OFF; LCDM13 = partstSEGMENTS_OFF; LCDM14 = partstSEGMENTS_OFF; LCDM15 = partstSEGMENTS_OFF; LCDM16 = partstSEGMENTS_OFF; LCDM17 = partstSEGMENTS_OFF; LCDM18 = partstSEGMENTS_OFF; LCDM19 = partstSEGMENTS_OFF; LCDM20 = partstSEGMENTS_OFF; /* Setup LCD control. */ LCDCTL = (LCDSG0_7|LCD4MUX|LCDON); } /*-----------------------------------------------------------*/ void vParTestSetLED( unsigned portBASE_TYPE uxLED, signed portBASE_TYPE xValue ) { /* Set or clear the output [in this case show or hide the '*' character. */ if( uxLED < ( portBASE_TYPE ) partstNUM_LEDS ) { vTaskSuspendAll(); { if( xValue ) { /* Turn on the segments required to show the '*'. */ *( ucRHSSegments[ uxLED ] ) = partstSEGMENTS_ON; *( ucLHSSegments[ uxLED ] ) = partstSEGMENTS_ON; } else { /* Turn off all the segments. */ *( ucRHSSegments[ uxLED ] ) = partstSEGMENTS_OFF; *( ucLHSSegments[ uxLED ] ) = partstSEGMENTS_OFF; } } xTaskResumeAll(); } } /*-----------------------------------------------------------*/ void vParTestToggleLED( unsigned portBASE_TYPE uxLED ) { if( uxLED < ( portBASE_TYPE ) partstNUM_LEDS ) { vTaskSuspendAll(); { /* If the '*' is already showing - hide it. If it is not already showing then show it. */ if( *( ucRHSSegments[ uxLED ] ) ) { *( ucRHSSegments[ uxLED ] ) = partstSEGMENTS_OFF; *( ucLHSSegments[ uxLED ] ) = partstSEGMENTS_OFF; } else { *( ucRHSSegments[ uxLED ] ) = partstSEGMENTS_ON; *( ucLHSSegments[ uxLED ] ) = partstSEGMENTS_ON; } } xTaskResumeAll(); } else { if( uxLED == partstON_BOARD_LED ) { /* The request related to the genuine on board LED. */ prvToggleOnBoardLED(); } } } /*-----------------------------------------------------------*/ static void prvToggleOnBoardLED( void ) { static unsigned short sState = pdFALSE; /* Toggle the state of the single genuine on board LED. */ if( sState ) { P1OUT |= mainON_BOARD_LED_BIT; } else { P1OUT &= ~mainON_BOARD_LED_BIT; } sState = !sState; } /*-----------------------------------------------------------*/
andyOsaft/02_SourceCode
freeRTOS/FreeRTOSV7.4.0/FreeRTOSV7.4.0/FreeRTOS/Demo/msp430_GCC/ParTest/ParTest.c
C
mit
9,205
/* * Name: * Section: * Assignment: * Date: * */ #include<stdio.h> #include<stdlib.h> #include<ctype.h> #include<time.h> #include<string.h> #define MAX_STR_LEN 25 typedef struct Data_ { char *name; struct Data_ *nextData; }Data; // KEEP THIS STRUCTURE typedef struct Timer_ { double start; double end; }Timer; // USED FOR BUBBLE SORT Data* bubble_sort(Data *list); //USED FOR MERGE SORT int length(Data* list); void move_node(Data** destRef, Data** sourceRef); void split_in_half(Data *source, Data **frontRef, Data** backRef); Data* merge(Data *a, Data* b); void merge_sort(Data **list); // USED FOR creating out list void push(Data **head, char *name); //USED FOR freeing our list void destroy(Data *list); //Allows us to open a file and create our linked list Data* read_from_file(const char* file, const int size); // shows to the user the linked list void display(Data *list); // USED FOR TIMING OUR CODE void start_timer(Timer* t); double get_time_diff(Timer* t); void end_timer(Timer *t); int main (int argc, char **argv) { /* * Error checking the number of passed in parameters * */ if (argc < 3) { printf("Not enough parameters bub!\n"); exit(0); } /* * Opening file for writng the timing output * */ FILE* fp = fopen("timing.out", "w"); Data *head = NULL; // Pulling the number of names needed to read into my program const int size = atoi(argv[2]); /* * Setting up timer structure * */ Timer *t = malloc(sizeof(Timer)); t->start = 0; t->end = 0; /* * Timing read from file * */ start_timer(t); head = read_from_file(argv[1], size); end_timer(t); fprintf(fp,"\nReading from the %s %d took %lf msecs\n\n", argv[1], size,get_time_diff(t)); /* * Timing the time taken to sort with bubble sort * */ fprintf(fp,"Bubble Sort\n"); start_timer(t); head = bubble_sort(head); end_timer(t); fprintf(fp,"Sorting the linked list with bubble sort\ntook %lf msecs for %d nodes\n\n", get_time_diff(t), size); display(head); /* * Destroying current head and reassigning back to NULL * */ destroy(head); head = NULL; head = read_from_file(argv[1], size); /* * Timing the time taken to sort with merge sort * */ fprintf(fp,"\nMerge Sort\n"); start_timer(t); merge_sort(&head); end_timer(t); fprintf(fp,"Sorting the linked list with merge sort\ntook %lf msecs for %d nodes\n\n", get_time_diff(t), size); display(head); /* * Clean up of allocations and open files * */ destroy(head); free(t); fclose(fp); // destroy list return 0; } /* * Timing functions (DO NOT DELETE THEM!) **/ void start_timer(Timer *t) { struct timeval tp; int rtn; rtn=gettimeofday(&tp, NULL); t->start = (double)tp.tv_sec+(1.e-6)*tp.tv_usec; } double get_time_diff(Timer *t) { return t->end - t->start; } void end_timer(Timer *t) { struct timeval tp; int rtn; rtn=gettimeofday(&tp, NULL); t->end = (double)tp.tv_sec+(1.e-6)*tp.tv_usec; } void destroy(Data* list) { } Data* read_from_file(const char *file, const int size){ } void push(Data **head, char *name) { } Data* bubble_sort(Data *list) { } Data* swap(Data *left, Data *right) { } void display(Data *list) { } /* * Used to find the length of an linked list useful inside split_in_half function * */ int length(Data* list) { int count = 0; Data* current = list; while(current) { current = current->nextData; ++count; } return count; } void split_in_half(Data *source, Data **frontRef, Data** backRef) { } /* * Take the node from the front of the source, and move it to the front * of the dest. It is an error to call this with the sourceRef list is empty. * * before calling move_node(): * source == {1,2,3} * dest == {1,2,3} * * After calling move_node(): * source == {2,3} * dest == {1,1,2,3} * */ void move_node(Data** destRef, Data** sourceRef) { Data* newData = *sourceRef; *sourceRef = newData->nextData; newData->nextData = *destRef; *destRef = newData; } Data* merge(Data *a, Data* b) { } void merge_sort(Data **list) { }
mremtf/assignments
c/cs2050Solutions/hw2/hw2_template.c
C
mit
4,027
/* * rt_rand.c * * Real-Time Workshop code generation for Simulink model "modell.mdl". * * Model Version : 1.149 * Real-Time Workshop version : 7.3 (R2009a) 15-Jan-2009 * C source code generated on : Tue Mar 12 15:06:30 2013 * * Target selection: nidll.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: 32-bit Generic * Code generation objectives: Unspecified * Validation result: Not run * */ #include "rt_rand.h" /* Function: rt_Urand ======================================================= * Abstract: * Uniform random number generator (random number between 0 and 1) * * #define IA 16807 magic multiplier = 7^5 * #define IM 2147483647 modulus = 2^31-1 * #define IQ 127773 IM div IA * #define IR 2836 IM modulo IA * #define S 4.656612875245797e-10 reciprocal of 2^31-1 * * test = IA * (seed % IQ) - IR * (seed/IQ) * seed = test < 0 ? (test + IM) : test * return (seed*S) * */ real_T rt_Urand(uint32_T *seed) /* pointer to a running seed */ { uint32_T hi = *seed / 127773U; uint32_T lo = *seed % 127773U; int32_T test = (16807 * lo) - (2836 * hi);/* never overflows */ *seed = ((test < 0) ? (uint32_T)(test + 2147483647) : (uint32_T)test); return ((real_T) (*seed * 4.656612875245797e-10)); } /* end rt_Urand */ /* Function: rt_NormalRand ==================================================== * Abstract: * Normal (Gaussian) random number generator also known as mlUrandn in * MATLAB V4. */ real_T rt_NormalRand(uint32_T *seed) { real_T sr, si, t; do { sr = (2.0 * rt_Urand(seed)) - 1.0; si = (2.0 * rt_Urand(seed)) - 1.0; t = (sr * sr) + (si * si); } while (t > 1.0); return(sr * sqrt((-2.0 * log(t)) / t)); } /* end rt_NormalRand */
NTNU-MCS/CS_EnterpriseI
10 prev work/2013 Sundland/modell_nidll_rtw/rt_rand.c
C
mit
2,007
/* * The MIT License (MIT) * * Copyright (c) 2015 by Sergey Fetisov <fsenok@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. */ /* * version: 1.0 demo (7.02.2015) * brief: tiny dns ipv4 server using lwip (pcb) */ #include "dnserver.h" #define DNS_MAX_HOST_NAME_LEN 128 static struct udp_pcb *pcb = NULL; dns_query_proc_t query_proc = NULL; #pragma pack(push, 1) typedef struct { #if BYTE_ORDER == LITTLE_ENDIAN uint8_t rd: 1, /* Recursion Desired */ tc: 1, /* Truncation Flag */ aa: 1, /* Authoritative Answer Flag */ opcode: 4, /* Operation code */ qr: 1; /* Query/Response Flag */ uint8_t rcode: 4, /* Response Code */ z: 3, /* Zero */ ra: 1; /* Recursion Available */ #else uint8_t qr: 1, /* Query/Response Flag */ opcode: 4, /* Operation code */ aa: 1, /* Authoritative Answer Flag */ tc: 1, /* Truncation Flag */ rd: 1; /* Recursion Desired */ uint8_t ra: 1, /* Recursion Available */ z: 3, /* Zero */ rcode: 4; /* Response Code */ #endif } dns_header_flags_t; typedef struct { uint16_t id; dns_header_flags_t flags; uint16_t n_record[4]; } dns_header_t; typedef struct dns_answer { uint16_t name; uint16_t type; uint16_t Class; uint32_t ttl; uint16_t len; uint32_t addr; } dns_answer_t; #pragma pack(pop) typedef struct dns_query { char name[DNS_MAX_HOST_NAME_LEN]; uint16_t type; uint16_t Class; } dns_query_t; static int parse_next_query(void *data, int size, dns_query_t *query) { int len; int lables; uint8_t *ptr; len = 0; lables = 0; ptr = (uint8_t *)data; while (true) { uint8_t lable_len; if (size <= 0) return -1; lable_len = *ptr++; size--; if (lable_len == 0) break; if (lables > 0) { if (len == DNS_MAX_HOST_NAME_LEN) return -2; query->name[len++] = '.'; } if (lable_len > size) return -1; if (len + lable_len >= DNS_MAX_HOST_NAME_LEN) return -2; memcpy(&query->name[len], ptr, lable_len); len += lable_len; ptr += lable_len; size -= lable_len; lables++; } if (size < 4) return -1; query->name[len] = 0; query->type = *(uint16_t *)ptr; ptr += 2; query->Class = *(uint16_t *)ptr; ptr += 2; return ptr - (uint8_t *)data; } static void udp_recv_proc(void *arg, struct udp_pcb *upcb, struct pbuf *p, struct ip_addr *addr, u16_t port) { int len; dns_header_t *header; static dns_query_t query; struct pbuf *out; ip_addr_t host_addr; dns_answer_t *answer; if (p->len <= sizeof(dns_header_t)) goto error; header = (dns_header_t *)p->payload; if (header->flags.qr != 0) goto error; if (ntohs(header->n_record[0]) != 1) goto error; len = parse_next_query(header + 1, p->len - sizeof(dns_header_t), &query); if (len < 0) goto error; if (!query_proc(query.name, &host_addr)) goto error; len += sizeof(dns_header_t); out = pbuf_alloc(PBUF_TRANSPORT, len + 16, PBUF_POOL); if (out == NULL) goto error; memcpy(out->payload, p->payload, len); header = (dns_header_t *)out->payload; header->flags.qr = 1; header->n_record[1] = htons(1); answer = (struct dns_answer *)((uint8_t *)out->payload + len); answer->name = htons(0xC00C); answer->type = htons(1); answer->Class = htons(1); answer->ttl = htonl(32); answer->len = htons(4); answer->addr = host_addr.addr; udp_sendto(upcb, out, addr, port); pbuf_free(out); error: pbuf_free(p); } err_t dnserv_init(ip_addr_t *bind, uint16_t port, dns_query_proc_t qp) { err_t err; udp_init(); dnserv_free(); pcb = udp_new(); if (pcb == NULL) return ERR_MEM; err = udp_bind(pcb, bind, port); if (err != ERR_OK) { dnserv_free(); return err; } udp_recv(pcb, udp_recv_proc, NULL); query_proc = qp; return ERR_OK; } void dnserv_free() { if (pcb == NULL) return; udp_remove(pcb); pcb = NULL; }
fetisov/lrndis
lrndis/dns-server/dnserver.c
C
mit
4,878