tor/src/common/mempool.c

629 lines
20 KiB
C
Raw Normal View History

2013-01-16 07:54:56 +01:00
/* Copyright (c) 2007-2013, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#if 1
/* Tor dependencies */
#include "orconfig.h"
#endif
#include <stdlib.h>
#include <string.h>
#include "torint.h"
#include "crypto.h"
#define MEMPOOL_PRIVATE
#include "mempool.h"
/* OVERVIEW:
*
* This is an implementation of memory pools for Tor cells. It may be
* useful for you too.
*
* Generally, a memory pool is an allocation strategy optimized for large
* numbers of identically-sized objects. Rather than the elaborate arena
2007-05-25 21:41:31 +02:00
* and coalescing strategies you need to get good performance for a
* general-purpose malloc(), pools use a series of large memory "chunks",
* each of which is carved into a bunch of smaller "items" or
* "allocations".
*
* To get decent performance, you need to:
* - Minimize the number of times you hit the underlying allocator.
* - Try to keep accesses as local in memory as possible.
* - Try to keep the common case fast.
*
* Our implementation uses three lists of chunks per pool. Each chunk can
* be either "full" (no more room for items); "empty" (no items); or
* "used" (not full, not empty). There are independent doubly-linked
* lists for each state.
*
* CREDIT:
*
* I wrote this after looking at 3 or 4 other pooling allocators, but
* without copying. The strategy this most resembles (which is funny,
2007-05-25 21:41:31 +02:00
* since that's the one I looked at longest ago) is the pool allocator
* underlying Python's obmalloc code. Major differences from obmalloc's
* pools are:
* - We don't even try to be threadsafe.
* - We only handle objects of one size.
* - Our list of empty chunks is doubly-linked, not singly-linked.
* (This could change pretty easily; it's only doubly-linked for
* consistency.)
* - We keep a list of full chunks (so we can have a "nuke everything"
* function). Obmalloc's pools leave full chunks to float unanchored.
*
* LIMITATIONS:
* - Not even slightly threadsafe.
* - Likes to have lots of items per chunks.
* - One pointer overhead per allocated thing. (The alternative is
* something like glib's use of an RB-tree to keep track of what
* chunk any given piece of memory is in.)
2009-05-27 22:35:03 +02:00
* - Only aligns allocated things to void* level: redefine ALIGNMENT_TYPE
* if you need doubles.
* - Could probably be optimized a bit; the representation contains
* a bit more info than it really needs to have.
*/
#if 1
/* Tor dependencies */
#include "util.h"
#include "compat.h"
#include "torlog.h"
#define ALLOC(x) tor_malloc(x)
#define FREE(x) tor_free(x)
#define ASSERT(x) tor_assert(x)
#undef ALLOC_CAN_RETURN_NULL
#define TOR
/* End Tor dependencies */
#else
/* If you're not building this as part of Tor, you'll want to define the
* following macros. For now, these should do as defaults.
*/
#include <assert.h>
#define PREDICT_UNLIKELY(x) (x)
#define PREDICT_LIKELY(x) (x)
#define ALLOC(x) malloc(x)
#define FREE(x) free(x)
#define STRUCT_OFFSET(tp, member) \
((off_t) (((char*)&((tp*)0)->member)-(char*)0))
#define ASSERT(x) assert(x)
#define ALLOC_CAN_RETURN_NULL
#endif
/* Tuning parameters */
/** Largest type that we need to ensure returned memory items are aligned to.
* Change this to "double" if we need to be safe for structs with doubles. */
#define ALIGNMENT_TYPE void *
2007-05-25 21:41:31 +02:00
/** Increment that we need to align allocated. */
#define ALIGNMENT sizeof(ALIGNMENT_TYPE)
/** Largest memory chunk that we should allocate. */
#define MAX_CHUNK (8*(1L<<20))
/** Smallest memory chunk size that we should allocate. */
#define MIN_CHUNK 4096
typedef struct mp_allocated_t mp_allocated_t;
typedef struct mp_chunk_t mp_chunk_t;
/** Holds a single allocated item, allocated as part of a chunk. */
struct mp_allocated_t {
/** The chunk that this item is allocated in. This adds overhead to each
* allocated item, thus making this implementation inappropriate for
* very small items. */
mp_chunk_t *in_chunk;
union {
/** If this item is free, the next item on the free list. */
mp_allocated_t *next_free;
/** If this item is not free, the actual memory contents of this item.
* (Not actual size.) */
char mem[1];
/** An extra element to the union to insure correct alignment. */
Rename all reserved C identifiers we defined For everything we declare that starts with _, make it end with _ instead. This is a machine-generated patch. To make it, start by getting the list of reserved identifiers using: git ls-tree -r --name-only HEAD | grep '\.[ch]$' | \ xargs ctags --c-kinds=defglmpstuvx -o - | grep '^_' | \ cut -f 1 | sort| uniq You might need gnu ctags. Then pipe the output through this script: ============================== use strict; BEGIN { print "#!/usr/bin/perl -w -i -p\n\n"; } chomp; next if ( /^__attribute__/ or /^__func__/ or /^_FILE_OFFSET_BITS/ or /^_FORTIFY_SOURCE/ or /^_GNU_SOURCE/ or /^_WIN32/ or /^_DARWIN_UNLIMITED/ or /^_FILE_OFFSET_BITS/ or /^_LARGEFILE64_SOURCE/ or /^_LFS64_LARGEFILE/ or /^__cdecl/ or /^__attribute__/ or /^__func__/ or /^_WIN32_WINNT/); my $ident = $_; my $better = $ident; $better =~ s/^_//; $better = "${better}_"; print "s/(?<![A-Za-z0-9_])$ident(?![A-Za-z0-9_])/$better/g;\n"; ============================== Then run the resulting script on all the files you want to change. (That is, all the C except that in src/ext.) The resulting script was: ============================== s/(?<![A-Za-z0-9_])_address(?![A-Za-z0-9_])/address_/g; s/(?<![A-Za-z0-9_])_aes_fill_buf(?![A-Za-z0-9_])/aes_fill_buf_/g; s/(?<![A-Za-z0-9_])_AllowInvalid(?![A-Za-z0-9_])/AllowInvalid_/g; s/(?<![A-Za-z0-9_])_AP_CONN_STATE_MAX(?![A-Za-z0-9_])/AP_CONN_STATE_MAX_/g; s/(?<![A-Za-z0-9_])_AP_CONN_STATE_MIN(?![A-Za-z0-9_])/AP_CONN_STATE_MIN_/g; s/(?<![A-Za-z0-9_])_assert_cache_ok(?![A-Za-z0-9_])/assert_cache_ok_/g; s/(?<![A-Za-z0-9_])_A_UNKNOWN(?![A-Za-z0-9_])/A_UNKNOWN_/g; s/(?<![A-Za-z0-9_])_base(?![A-Za-z0-9_])/base_/g; s/(?<![A-Za-z0-9_])_BridgePassword_AuthDigest(?![A-Za-z0-9_])/BridgePassword_AuthDigest_/g; s/(?<![A-Za-z0-9_])_buffer_stats_compare_entries(?![A-Za-z0-9_])/buffer_stats_compare_entries_/g; s/(?<![A-Za-z0-9_])_chan_circid_entries_eq(?![A-Za-z0-9_])/chan_circid_entries_eq_/g; s/(?<![A-Za-z0-9_])_chan_circid_entry_hash(?![A-Za-z0-9_])/chan_circid_entry_hash_/g; s/(?<![A-Za-z0-9_])_check_no_tls_errors(?![A-Za-z0-9_])/check_no_tls_errors_/g; s/(?<![A-Za-z0-9_])_c_hist_compare(?![A-Za-z0-9_])/c_hist_compare_/g; s/(?<![A-Za-z0-9_])_circ(?![A-Za-z0-9_])/circ_/g; s/(?<![A-Za-z0-9_])_circuit_get_global_list(?![A-Za-z0-9_])/circuit_get_global_list_/g; s/(?<![A-Za-z0-9_])_circuit_mark_for_close(?![A-Za-z0-9_])/circuit_mark_for_close_/g; s/(?<![A-Za-z0-9_])_CIRCUIT_PURPOSE_C_MAX(?![A-Za-z0-9_])/CIRCUIT_PURPOSE_C_MAX_/g; s/(?<![A-Za-z0-9_])_CIRCUIT_PURPOSE_MAX(?![A-Za-z0-9_])/CIRCUIT_PURPOSE_MAX_/g; s/(?<![A-Za-z0-9_])_CIRCUIT_PURPOSE_MIN(?![A-Za-z0-9_])/CIRCUIT_PURPOSE_MIN_/g; s/(?<![A-Za-z0-9_])_CIRCUIT_PURPOSE_OR_MAX(?![A-Za-z0-9_])/CIRCUIT_PURPOSE_OR_MAX_/g; s/(?<![A-Za-z0-9_])_CIRCUIT_PURPOSE_OR_MIN(?![A-Za-z0-9_])/CIRCUIT_PURPOSE_OR_MIN_/g; s/(?<![A-Za-z0-9_])_cmp_int_strings(?![A-Za-z0-9_])/cmp_int_strings_/g; s/(?<![A-Za-z0-9_])_compare_cached_resolves_by_expiry(?![A-Za-z0-9_])/compare_cached_resolves_by_expiry_/g; s/(?<![A-Za-z0-9_])_compare_digests(?![A-Za-z0-9_])/compare_digests_/g; s/(?<![A-Za-z0-9_])_compare_digests256(?![A-Za-z0-9_])/compare_digests256_/g; s/(?<![A-Za-z0-9_])_compare_dir_src_ents_by_authority_id(?![A-Za-z0-9_])/compare_dir_src_ents_by_authority_id_/g; s/(?<![A-Za-z0-9_])_compare_duration_idx(?![A-Za-z0-9_])/compare_duration_idx_/g; s/(?<![A-Za-z0-9_])_compare_int(?![A-Za-z0-9_])/compare_int_/g; s/(?<![A-Za-z0-9_])_compare_networkstatus_v2_published_on(?![A-Za-z0-9_])/compare_networkstatus_v2_published_on_/g; s/(?<![A-Za-z0-9_])_compare_old_routers_by_identity(?![A-Za-z0-9_])/compare_old_routers_by_identity_/g; s/(?<![A-Za-z0-9_])_compare_orports(?![A-Za-z0-9_])/compare_orports_/g; s/(?<![A-Za-z0-9_])_compare_pairs(?![A-Za-z0-9_])/compare_pairs_/g; s/(?<![A-Za-z0-9_])_compare_routerinfo_by_id_digest(?![A-Za-z0-9_])/compare_routerinfo_by_id_digest_/g; s/(?<![A-Za-z0-9_])_compare_routerinfo_by_ip_and_bw(?![A-Za-z0-9_])/compare_routerinfo_by_ip_and_bw_/g; s/(?<![A-Za-z0-9_])_compare_signed_descriptors_by_age(?![A-Za-z0-9_])/compare_signed_descriptors_by_age_/g; s/(?<![A-Za-z0-9_])_compare_string_ptrs(?![A-Za-z0-9_])/compare_string_ptrs_/g; s/(?<![A-Za-z0-9_])_compare_strings_for_pqueue(?![A-Za-z0-9_])/compare_strings_for_pqueue_/g; s/(?<![A-Za-z0-9_])_compare_strs(?![A-Za-z0-9_])/compare_strs_/g; s/(?<![A-Za-z0-9_])_compare_tor_version_str_ptr(?![A-Za-z0-9_])/compare_tor_version_str_ptr_/g; s/(?<![A-Za-z0-9_])_compare_vote_rs(?![A-Za-z0-9_])/compare_vote_rs_/g; s/(?<![A-Za-z0-9_])_compare_votes_by_authority_id(?![A-Za-z0-9_])/compare_votes_by_authority_id_/g; s/(?<![A-Za-z0-9_])_compare_without_first_ch(?![A-Za-z0-9_])/compare_without_first_ch_/g; s/(?<![A-Za-z0-9_])_connection_free(?![A-Za-z0-9_])/connection_free_/g; s/(?<![A-Za-z0-9_])_connection_mark_and_flush(?![A-Za-z0-9_])/connection_mark_and_flush_/g; s/(?<![A-Za-z0-9_])_connection_mark_for_close(?![A-Za-z0-9_])/connection_mark_for_close_/g; s/(?<![A-Za-z0-9_])_connection_mark_unattached_ap(?![A-Za-z0-9_])/connection_mark_unattached_ap_/g; s/(?<![A-Za-z0-9_])_connection_write_to_buf_impl(?![A-Za-z0-9_])/connection_write_to_buf_impl_/g; s/(?<![A-Za-z0-9_])_ConnLimit(?![A-Za-z0-9_])/ConnLimit_/g; s/(?<![A-Za-z0-9_])_CONN_TYPE_MAX(?![A-Za-z0-9_])/CONN_TYPE_MAX_/g; s/(?<![A-Za-z0-9_])_CONN_TYPE_MIN(?![A-Za-z0-9_])/CONN_TYPE_MIN_/g; s/(?<![A-Za-z0-9_])_CONTROL_CONN_STATE_MAX(?![A-Za-z0-9_])/CONTROL_CONN_STATE_MAX_/g; s/(?<![A-Za-z0-9_])_CONTROL_CONN_STATE_MIN(?![A-Za-z0-9_])/CONTROL_CONN_STATE_MIN_/g; s/(?<![A-Za-z0-9_])_CPUWORKER_STATE_MAX(?![A-Za-z0-9_])/CPUWORKER_STATE_MAX_/g; s/(?<![A-Za-z0-9_])_CPUWORKER_STATE_MIN(?![A-Za-z0-9_])/CPUWORKER_STATE_MIN_/g; s/(?<![A-Za-z0-9_])_crypto_dh_get_dh(?![A-Za-z0-9_])/crypto_dh_get_dh_/g; s/(?<![A-Za-z0-9_])_crypto_global_initialized(?![A-Za-z0-9_])/crypto_global_initialized_/g; s/(?<![A-Za-z0-9_])_crypto_new_pk_from_rsa(?![A-Za-z0-9_])/crypto_new_pk_from_rsa_/g; s/(?<![A-Za-z0-9_])_crypto_pk_get_evp_pkey(?![A-Za-z0-9_])/crypto_pk_get_evp_pkey_/g; s/(?<![A-Za-z0-9_])_crypto_pk_get_rsa(?![A-Za-z0-9_])/crypto_pk_get_rsa_/g; s/(?<![A-Za-z0-9_])_DIR_CONN_STATE_MAX(?![A-Za-z0-9_])/DIR_CONN_STATE_MAX_/g; s/(?<![A-Za-z0-9_])_DIR_CONN_STATE_MIN(?![A-Za-z0-9_])/DIR_CONN_STATE_MIN_/g; s/(?<![A-Za-z0-9_])_DIR_PURPOSE_MAX(?![A-Za-z0-9_])/DIR_PURPOSE_MAX_/g; s/(?<![A-Za-z0-9_])_DIR_PURPOSE_MIN(?![A-Za-z0-9_])/DIR_PURPOSE_MIN_/g; s/(?<![A-Za-z0-9_])_dirreq_map_get(?![A-Za-z0-9_])/dirreq_map_get_/g; s/(?<![A-Za-z0-9_])_dirreq_map_put(?![A-Za-z0-9_])/dirreq_map_put_/g; s/(?<![A-Za-z0-9_])_dns_randfn(?![A-Za-z0-9_])/dns_randfn_/g; s/(?<![A-Za-z0-9_])_dummy(?![A-Za-z0-9_])/dummy_/g; s/(?<![A-Za-z0-9_])_edge(?![A-Za-z0-9_])/edge_/g; s/(?<![A-Za-z0-9_])_END_CIRC_REASON_MAX(?![A-Za-z0-9_])/END_CIRC_REASON_MAX_/g; s/(?<![A-Za-z0-9_])_END_CIRC_REASON_MIN(?![A-Za-z0-9_])/END_CIRC_REASON_MIN_/g; s/(?<![A-Za-z0-9_])_EOF(?![A-Za-z0-9_])/EOF_/g; s/(?<![A-Za-z0-9_])_ERR(?![A-Za-z0-9_])/ERR_/g; s/(?<![A-Za-z0-9_])_escaped_val(?![A-Za-z0-9_])/escaped_val_/g; s/(?<![A-Za-z0-9_])_evdns_log(?![A-Za-z0-9_])/evdns_log_/g; s/(?<![A-Za-z0-9_])_evdns_nameserver_add_impl(?![A-Za-z0-9_])/evdns_nameserver_add_impl_/g; s/(?<![A-Za-z0-9_])_EVENT_MAX(?![A-Za-z0-9_])/EVENT_MAX_/g; s/(?<![A-Za-z0-9_])_EVENT_MIN(?![A-Za-z0-9_])/EVENT_MIN_/g; s/(?<![A-Za-z0-9_])_ExcludeExitNodesUnion(?![A-Za-z0-9_])/ExcludeExitNodesUnion_/g; s/(?<![A-Za-z0-9_])_EXIT_CONN_STATE_MAX(?![A-Za-z0-9_])/EXIT_CONN_STATE_MAX_/g; s/(?<![A-Za-z0-9_])_EXIT_CONN_STATE_MIN(?![A-Za-z0-9_])/EXIT_CONN_STATE_MIN_/g; s/(?<![A-Za-z0-9_])_EXIT_PURPOSE_MAX(?![A-Za-z0-9_])/EXIT_PURPOSE_MAX_/g; s/(?<![A-Za-z0-9_])_EXIT_PURPOSE_MIN(?![A-Za-z0-9_])/EXIT_PURPOSE_MIN_/g; s/(?<![A-Za-z0-9_])_extrainfo_free(?![A-Za-z0-9_])/extrainfo_free_/g; s/(?<![A-Za-z0-9_])_find_by_keyword(?![A-Za-z0-9_])/find_by_keyword_/g; s/(?<![A-Za-z0-9_])_free_cached_dir(?![A-Za-z0-9_])/free_cached_dir_/g; s/(?<![A-Za-z0-9_])_free_cached_resolve(?![A-Za-z0-9_])/free_cached_resolve_/g; s/(?<![A-Za-z0-9_])_free_duplicate_routerstatus_entry(?![A-Za-z0-9_])/free_duplicate_routerstatus_entry_/g; s/(?<![A-Za-z0-9_])_free_link_history(?![A-Za-z0-9_])/free_link_history_/g; s/(?<![A-Za-z0-9_])_geoip_compare_entries(?![A-Za-z0-9_])/geoip_compare_entries_/g; s/(?<![A-Za-z0-9_])_geoip_compare_key_to_entry(?![A-Za-z0-9_])/geoip_compare_key_to_entry_/g; s/(?<![A-Za-z0-9_])_hex_decode_digit(?![A-Za-z0-9_])/hex_decode_digit_/g; s/(?<![A-Za-z0-9_])_idxplus1(?![A-Za-z0-9_])/idxplus1_/g; s/(?<![A-Za-z0-9_])__libc_enable_secure(?![A-Za-z0-9_])/_libc_enable_secure_/g; s/(?<![A-Za-z0-9_])_log_debug(?![A-Za-z0-9_])/log_debug_/g; s/(?<![A-Za-z0-9_])_log_err(?![A-Za-z0-9_])/log_err_/g; s/(?<![A-Za-z0-9_])_log_fn(?![A-Za-z0-9_])/log_fn_/g; s/(?<![A-Za-z0-9_])_log_fn_function_name(?![A-Za-z0-9_])/log_fn_function_name_/g; s/(?<![A-Za-z0-9_])_log_global_min_severity(?![A-Za-z0-9_])/log_global_min_severity_/g; s/(?<![A-Za-z0-9_])_log_info(?![A-Za-z0-9_])/log_info_/g; s/(?<![A-Za-z0-9_])_log_notice(?![A-Za-z0-9_])/log_notice_/g; s/(?<![A-Za-z0-9_])_log_prefix(?![A-Za-z0-9_])/log_prefix_/g; s/(?<![A-Za-z0-9_])_log_warn(?![A-Za-z0-9_])/log_warn_/g; s/(?<![A-Za-z0-9_])_magic(?![A-Za-z0-9_])/magic_/g; s/(?<![A-Za-z0-9_])_MALLOC_LOCK(?![A-Za-z0-9_])/MALLOC_LOCK_/g; s/(?<![A-Za-z0-9_])_MALLOC_LOCK_INIT(?![A-Za-z0-9_])/MALLOC_LOCK_INIT_/g; s/(?<![A-Za-z0-9_])_MALLOC_UNLOCK(?![A-Za-z0-9_])/MALLOC_UNLOCK_/g; s/(?<![A-Za-z0-9_])_microdesc_eq(?![A-Za-z0-9_])/microdesc_eq_/g; s/(?<![A-Za-z0-9_])_microdesc_hash(?![A-Za-z0-9_])/microdesc_hash_/g; s/(?<![A-Za-z0-9_])_MIN_TOR_TLS_ERROR_VAL(?![A-Za-z0-9_])/MIN_TOR_TLS_ERROR_VAL_/g; s/(?<![A-Za-z0-9_])_mm_free(?![A-Za-z0-9_])/mm_free_/g; s/(?<![A-Za-z0-9_])_NIL(?![A-Za-z0-9_])/NIL_/g; s/(?<![A-Za-z0-9_])_n_openssl_mutexes(?![A-Za-z0-9_])/n_openssl_mutexes_/g; s/(?<![A-Za-z0-9_])_openssl_dynlock_create_cb(?![A-Za-z0-9_])/openssl_dynlock_create_cb_/g; s/(?<![A-Za-z0-9_])_openssl_dynlock_destroy_cb(?![A-Za-z0-9_])/openssl_dynlock_destroy_cb_/g; s/(?<![A-Za-z0-9_])_openssl_dynlock_lock_cb(?![A-Za-z0-9_])/openssl_dynlock_lock_cb_/g; s/(?<![A-Za-z0-9_])_openssl_locking_cb(?![A-Za-z0-9_])/openssl_locking_cb_/g; s/(?<![A-Za-z0-9_])_openssl_mutexes(?![A-Za-z0-9_])/openssl_mutexes_/g; s/(?<![A-Za-z0-9_])_option_abbrevs(?![A-Za-z0-9_])/option_abbrevs_/g; s/(?<![A-Za-z0-9_])_option_vars(?![A-Za-z0-9_])/option_vars_/g; s/(?<![A-Za-z0-9_])_OR_CONN_STATE_MAX(?![A-Za-z0-9_])/OR_CONN_STATE_MAX_/g; s/(?<![A-Za-z0-9_])_OR_CONN_STATE_MIN(?![A-Za-z0-9_])/OR_CONN_STATE_MIN_/g; s/(?<![A-Za-z0-9_])_OutboundBindAddressIPv4(?![A-Za-z0-9_])/OutboundBindAddressIPv4_/g; s/(?<![A-Za-z0-9_])_OutboundBindAddressIPv6(?![A-Za-z0-9_])/OutboundBindAddressIPv6_/g; s/(?<![A-Za-z0-9_])_PDS_PREFER_TUNNELED_DIR_CONNS(?![A-Za-z0-9_])/PDS_PREFER_TUNNELED_DIR_CONNS_/g; s/(?<![A-Za-z0-9_])_port(?![A-Za-z0-9_])/port_/g; s/(?<![A-Za-z0-9_])__progname(?![A-Za-z0-9_])/_progname_/g; s/(?<![A-Za-z0-9_])_PublishServerDescriptor(?![A-Za-z0-9_])/PublishServerDescriptor_/g; s/(?<![A-Za-z0-9_])_remove_old_client_helper(?![A-Za-z0-9_])/remove_old_client_helper_/g; s/(?<![A-Za-z0-9_])_rend_cache_entry_free(?![A-Za-z0-9_])/rend_cache_entry_free_/g; s/(?<![A-Za-z0-9_])_routerlist_find_elt(?![A-Za-z0-9_])/routerlist_find_elt_/g; s/(?<![A-Za-z0-9_])_SafeLogging(?![A-Za-z0-9_])/SafeLogging_/g; s/(?<![A-Za-z0-9_])_SHORT_FILE_(?![A-Za-z0-9_])/SHORT_FILE__/g; s/(?<![A-Za-z0-9_])_state_abbrevs(?![A-Za-z0-9_])/state_abbrevs_/g; s/(?<![A-Za-z0-9_])_state_vars(?![A-Za-z0-9_])/state_vars_/g; s/(?<![A-Za-z0-9_])_t(?![A-Za-z0-9_])/t_/g; s/(?<![A-Za-z0-9_])_t32(?![A-Za-z0-9_])/t32_/g; s/(?<![A-Za-z0-9_])_test_op_ip6(?![A-Za-z0-9_])/test_op_ip6_/g; s/(?<![A-Za-z0-9_])_thread1_name(?![A-Za-z0-9_])/thread1_name_/g; s/(?<![A-Za-z0-9_])_thread2_name(?![A-Za-z0-9_])/thread2_name_/g; s/(?<![A-Za-z0-9_])_thread_test_func(?![A-Za-z0-9_])/thread_test_func_/g; s/(?<![A-Za-z0-9_])_thread_test_mutex(?![A-Za-z0-9_])/thread_test_mutex_/g; s/(?<![A-Za-z0-9_])_thread_test_start1(?![A-Za-z0-9_])/thread_test_start1_/g; s/(?<![A-Za-z0-9_])_thread_test_start2(?![A-Za-z0-9_])/thread_test_start2_/g; s/(?<![A-Za-z0-9_])_thread_test_strmap(?![A-Za-z0-9_])/thread_test_strmap_/g; s/(?<![A-Za-z0-9_])_tor_calloc(?![A-Za-z0-9_])/tor_calloc_/g; s/(?<![A-Za-z0-9_])_TOR_CHANNEL_INTERNAL(?![A-Za-z0-9_])/TOR_CHANNEL_INTERNAL_/g; s/(?<![A-Za-z0-9_])_TOR_CIRCUITMUX_EWMA_C(?![A-Za-z0-9_])/TOR_CIRCUITMUX_EWMA_C_/g; s/(?<![A-Za-z0-9_])_tor_free(?![A-Za-z0-9_])/tor_free_/g; s/(?<![A-Za-z0-9_])_tor_malloc(?![A-Za-z0-9_])/tor_malloc_/g; s/(?<![A-Za-z0-9_])_tor_malloc_zero(?![A-Za-z0-9_])/tor_malloc_zero_/g; s/(?<![A-Za-z0-9_])_tor_memdup(?![A-Za-z0-9_])/tor_memdup_/g; s/(?<![A-Za-z0-9_])_tor_realloc(?![A-Za-z0-9_])/tor_realloc_/g; s/(?<![A-Za-z0-9_])_tor_strdup(?![A-Za-z0-9_])/tor_strdup_/g; s/(?<![A-Za-z0-9_])_tor_strndup(?![A-Za-z0-9_])/tor_strndup_/g; s/(?<![A-Za-z0-9_])_TOR_TLS_SYSCALL(?![A-Za-z0-9_])/TOR_TLS_SYSCALL_/g; s/(?<![A-Za-z0-9_])_TOR_TLS_ZERORETURN(?![A-Za-z0-9_])/TOR_TLS_ZERORETURN_/g; s/(?<![A-Za-z0-9_])__USE_ISOC99(?![A-Za-z0-9_])/_USE_ISOC99_/g; s/(?<![A-Za-z0-9_])_UsingTestNetworkDefaults(?![A-Za-z0-9_])/UsingTestNetworkDefaults_/g; s/(?<![A-Za-z0-9_])_val(?![A-Za-z0-9_])/val_/g; s/(?<![A-Za-z0-9_])_void_for_alignment(?![A-Za-z0-9_])/void_for_alignment_/g; ==============================
2012-10-12 18:22:13 +02:00
ALIGNMENT_TYPE dummy_;
} u;
};
/** 'Magic' value used to detect memory corruption. */
#define MP_CHUNK_MAGIC 0x09870123
/** A chunk of memory. Chunks come from malloc; we use them */
struct mp_chunk_t {
unsigned long magic; /**< Must be MP_CHUNK_MAGIC if this chunk is valid. */
mp_chunk_t *next; /**< The next free, used, or full chunk in sequence. */
mp_chunk_t *prev; /**< The previous free, used, or full chunk in sequence. */
2007-05-25 21:41:31 +02:00
mp_pool_t *pool; /**< The pool that this chunk is part of. */
/** First free item in the freelist for this chunk. Note that this may be
* NULL even if this chunk is not at capacity: if so, the free memory at
* next_mem has not yet been carved into items.
*/
mp_allocated_t *first_free;
2007-05-25 21:41:31 +02:00
int n_allocated; /**< Number of currently allocated items in this chunk. */
int capacity; /**< Number of items that can be fit into this chunk. */
size_t mem_size; /**< Number of usable bytes in mem. */
char *next_mem; /**< Pointer into part of <b>mem</b> not yet carved up. */
2011-01-13 00:38:52 +01:00
char mem[FLEXIBLE_ARRAY_MEMBER]; /**< Storage for this chunk. */
};
/** Number of extra bytes needed beyond mem_size to allocate a chunk. */
#define CHUNK_OVERHEAD STRUCT_OFFSET(mp_chunk_t, mem[0])
/** Given a pointer to a mp_allocated_t, return a pointer to the memory
* item it holds. */
#define A2M(a) (&(a)->u.mem)
/** Given a pointer to a memory_item_t, return a pointer to its enclosing
* mp_allocated_t. */
#define M2A(p) ( ((char*)p) - STRUCT_OFFSET(mp_allocated_t, u.mem) )
#ifdef ALLOC_CAN_RETURN_NULL
/** If our ALLOC() macro can return NULL, check whether <b>x</b> is NULL,
* and if so, return NULL. */
#define CHECK_ALLOC(x) \
if (PREDICT_UNLIKELY(!x)) { return NULL; }
#else
/** If our ALLOC() macro can't return NULL, do nothing. */
#define CHECK_ALLOC(x)
#endif
/** Helper: Allocate and return a new memory chunk for <b>pool</b>. Does not
* link the chunk into any list. */
static mp_chunk_t *
mp_chunk_new(mp_pool_t *pool)
{
size_t sz = pool->new_chunk_capacity * pool->item_alloc_size;
mp_chunk_t *chunk = ALLOC(CHUNK_OVERHEAD + sz);
#ifdef MEMPOOL_STATS
++pool->total_chunks_allocated;
#endif
CHECK_ALLOC(chunk);
memset(chunk, 0, sizeof(mp_chunk_t)); /* Doesn't clear the whole thing. */
chunk->magic = MP_CHUNK_MAGIC;
chunk->capacity = pool->new_chunk_capacity;
chunk->mem_size = sz;
chunk->next_mem = chunk->mem;
chunk->pool = pool;
return chunk;
}
/** Take a <b>chunk</b> that has just been allocated or removed from
* <b>pool</b>'s empty chunk list, and add it to the head of the used chunk
* list. */
static INLINE void
add_newly_used_chunk_to_used_list(mp_pool_t *pool, mp_chunk_t *chunk)
{
chunk->next = pool->used_chunks;
if (chunk->next)
chunk->next->prev = chunk;
pool->used_chunks = chunk;
ASSERT(!chunk->prev);
}
2008-02-09 04:11:10 +01:00
/** Return a newly allocated item from <b>pool</b>. */
void *
mp_pool_get(mp_pool_t *pool)
{
mp_chunk_t *chunk;
mp_allocated_t *allocated;
if (PREDICT_LIKELY(pool->used_chunks != NULL)) {
/* Common case: there is some chunk that is neither full nor empty. Use
* that one. (We can't use the full ones, obviously, and we should fill
* up the used ones before we start on any empty ones. */
chunk = pool->used_chunks;
} else if (pool->empty_chunks) {
/* We have no used chunks, but we have an empty chunk that we haven't
* freed yet: use that. (We pull from the front of the list, which should
* get us the most recently emptied chunk.) */
chunk = pool->empty_chunks;
/* Remove the chunk from the empty list. */
pool->empty_chunks = chunk->next;
if (chunk->next)
chunk->next->prev = NULL;
/* Put the chunk on the 'used' list*/
add_newly_used_chunk_to_used_list(pool, chunk);
ASSERT(!chunk->prev);
--pool->n_empty_chunks;
if (pool->n_empty_chunks < pool->min_empty_chunks)
pool->min_empty_chunks = pool->n_empty_chunks;
} else {
/* We have no used or empty chunks: allocate a new chunk. */
chunk = mp_chunk_new(pool);
CHECK_ALLOC(chunk);
/* Add the new chunk to the used list. */
add_newly_used_chunk_to_used_list(pool, chunk);
}
ASSERT(chunk->n_allocated < chunk->capacity);
if (chunk->first_free) {
/* If there's anything on the chunk's freelist, unlink it and use it. */
allocated = chunk->first_free;
chunk->first_free = allocated->u.next_free;
allocated->u.next_free = NULL; /* For debugging; not really needed. */
ASSERT(allocated->in_chunk == chunk);
} else {
/* Otherwise, the chunk had better have some free space left on it. */
ASSERT(chunk->next_mem + pool->item_alloc_size <=
chunk->mem + chunk->mem_size);
/* Good, it did. Let's carve off a bit of that free space, and use
* that. */
allocated = (void*)chunk->next_mem;
chunk->next_mem += pool->item_alloc_size;
allocated->in_chunk = chunk;
allocated->u.next_free = NULL; /* For debugging; not really needed. */
}
++chunk->n_allocated;
#ifdef MEMPOOL_STATS
++pool->total_items_allocated;
#endif
if (PREDICT_UNLIKELY(chunk->n_allocated == chunk->capacity)) {
/* This chunk just became full. */
ASSERT(chunk == pool->used_chunks);
ASSERT(chunk->prev == NULL);
/* Take it off the used list. */
pool->used_chunks = chunk->next;
if (chunk->next)
chunk->next->prev = NULL;
/* Put it on the full list. */
chunk->next = pool->full_chunks;
if (chunk->next)
chunk->next->prev = chunk;
pool->full_chunks = chunk;
}
/* And return the memory portion of the mp_allocated_t. */
return A2M(allocated);
}
/** Return an allocated memory item to its memory pool. */
void
mp_pool_release(void *item)
{
mp_allocated_t *allocated = (void*) M2A(item);
mp_chunk_t *chunk = allocated->in_chunk;
ASSERT(chunk);
ASSERT(chunk->magic == MP_CHUNK_MAGIC);
ASSERT(chunk->n_allocated > 0);
allocated->u.next_free = chunk->first_free;
chunk->first_free = allocated;
if (PREDICT_UNLIKELY(chunk->n_allocated == chunk->capacity)) {
/* This chunk was full and is about to be used. */
mp_pool_t *pool = chunk->pool;
/* unlink from the full list */
if (chunk->prev)
chunk->prev->next = chunk->next;
if (chunk->next)
chunk->next->prev = chunk->prev;
if (chunk == pool->full_chunks)
pool->full_chunks = chunk->next;
/* link to the used list. */
chunk->next = pool->used_chunks;
chunk->prev = NULL;
if (chunk->next)
chunk->next->prev = chunk;
pool->used_chunks = chunk;
} else if (PREDICT_UNLIKELY(chunk->n_allocated == 1)) {
/* This was used and is about to be empty. */
mp_pool_t *pool = chunk->pool;
/* Unlink from the used list */
if (chunk->prev)
chunk->prev->next = chunk->next;
if (chunk->next)
chunk->next->prev = chunk->prev;
if (chunk == pool->used_chunks)
pool->used_chunks = chunk->next;
/* Link to the empty list */
chunk->next = pool->empty_chunks;
chunk->prev = NULL;
if (chunk->next)
chunk->next->prev = chunk;
pool->empty_chunks = chunk;
/* Reset the guts of this chunk to defragment it, in case it gets
* used again. */
chunk->first_free = NULL;
chunk->next_mem = chunk->mem;
++pool->n_empty_chunks;
}
--chunk->n_allocated;
}
/** Allocate a new memory pool to hold items of size <b>item_size</b>. We'll
* try to fit about <b>chunk_capacity</b> bytes in each chunk. */
mp_pool_t *
mp_pool_new(size_t item_size, size_t chunk_capacity)
{
mp_pool_t *pool;
size_t alloc_size, new_chunk_cap;
tor_assert(item_size < SIZE_T_CEILING);
tor_assert(chunk_capacity < SIZE_T_CEILING);
tor_assert(SIZE_T_CEILING / item_size > chunk_capacity);
pool = ALLOC(sizeof(mp_pool_t));
CHECK_ALLOC(pool);
memset(pool, 0, sizeof(mp_pool_t));
/* First, we figure out how much space to allow per item. We'll want to
* use make sure we have enough for the overhead plus the item size. */
alloc_size = (size_t)(STRUCT_OFFSET(mp_allocated_t, u.mem) + item_size);
/* If the item_size is less than sizeof(next_free), we need to make
* the allocation bigger. */
if (alloc_size < sizeof(mp_allocated_t))
alloc_size = sizeof(mp_allocated_t);
/* If we're not an even multiple of ALIGNMENT, round up. */
if (alloc_size % ALIGNMENT) {
alloc_size = alloc_size + ALIGNMENT - (alloc_size % ALIGNMENT);
}
if (alloc_size < ALIGNMENT)
alloc_size = ALIGNMENT;
ASSERT((alloc_size % ALIGNMENT) == 0);
/* Now we figure out how many items fit in each chunk. We need to fit at
* least 2 items per chunk. No chunk can be more than MAX_CHUNK bytes long,
* or less than MIN_CHUNK. */
if (chunk_capacity > MAX_CHUNK)
chunk_capacity = MAX_CHUNK;
/* Try to be around a power of 2 in size, since that's what allocators like
* handing out. 512K-1 byte is a lot better than 512K+1 byte. */
chunk_capacity = (size_t) round_to_power_of_2(chunk_capacity);
while (chunk_capacity < alloc_size * 2 + CHUNK_OVERHEAD)
chunk_capacity *= 2;
if (chunk_capacity < MIN_CHUNK)
chunk_capacity = MIN_CHUNK;
new_chunk_cap = (chunk_capacity-CHUNK_OVERHEAD) / alloc_size;
tor_assert(new_chunk_cap < INT_MAX);
pool->new_chunk_capacity = (int)new_chunk_cap;
pool->item_alloc_size = alloc_size;
log_debug(LD_MM, "Capacity is %lu, item size is %lu, alloc size is %lu",
(unsigned long)pool->new_chunk_capacity,
(unsigned long)pool->item_alloc_size,
(unsigned long)(pool->new_chunk_capacity*pool->item_alloc_size));
return pool;
}
/** Helper function for qsort: used to sort pointers to mp_chunk_t into
* descending order of fullness. */
static int
mp_pool_sort_used_chunks_helper(const void *_a, const void *_b)
{
mp_chunk_t *a = *(mp_chunk_t**)_a;
mp_chunk_t *b = *(mp_chunk_t**)_b;
return b->n_allocated - a->n_allocated;
}
/** Sort the used chunks in <b>pool</b> into descending order of fullness,
* so that we preferentially fill up mostly full chunks before we make
* nearly empty chunks less nearly empty. */
static void
mp_pool_sort_used_chunks(mp_pool_t *pool)
{
int i, n=0, inverted=0;
mp_chunk_t **chunks, *chunk;
for (chunk = pool->used_chunks; chunk; chunk = chunk->next) {
++n;
if (chunk->next && chunk->next->n_allocated > chunk->n_allocated)
++inverted;
}
if (!inverted)
return;
//printf("Sort %d/%d\n",inverted,n);
chunks = ALLOC(sizeof(mp_chunk_t *)*n);
#ifdef ALLOC_CAN_RETURN_NULL
if (PREDICT_UNLIKELY(!chunks)) return;
#endif
for (i=0,chunk = pool->used_chunks; chunk; chunk = chunk->next)
chunks[i++] = chunk;
qsort(chunks, n, sizeof(mp_chunk_t *), mp_pool_sort_used_chunks_helper);
pool->used_chunks = chunks[0];
chunks[0]->prev = NULL;
for (i=1;i<n;++i) {
chunks[i-1]->next = chunks[i];
chunks[i]->prev = chunks[i-1];
}
chunks[n-1]->next = NULL;
FREE(chunks);
mp_pool_assert_ok(pool);
}
/** If there are more than <b>n</b> empty chunks in <b>pool</b>, free the
* excess ones that have been empty for the longest. If
* <b>keep_recently_used</b> is true, do not free chunks unless they have been
* empty since the last call to this function.
**/
void
mp_pool_clean(mp_pool_t *pool, int n_to_keep, int keep_recently_used)
{
mp_chunk_t *chunk, **first_to_free;
mp_pool_sort_used_chunks(pool);
ASSERT(n_to_keep >= 0);
if (keep_recently_used) {
int n_recently_used = pool->n_empty_chunks - pool->min_empty_chunks;
if (n_to_keep < n_recently_used)
n_to_keep = n_recently_used;
}
ASSERT(n_to_keep >= 0);
first_to_free = &pool->empty_chunks;
while (*first_to_free && n_to_keep > 0) {
first_to_free = &(*first_to_free)->next;
--n_to_keep;
}
if (!*first_to_free) {
pool->min_empty_chunks = pool->n_empty_chunks;
return;
}
chunk = *first_to_free;
while (chunk) {
mp_chunk_t *next = chunk->next;
chunk->magic = 0xdeadbeef;
FREE(chunk);
#ifdef MEMPOOL_STATS
++pool->total_chunks_freed;
#endif
--pool->n_empty_chunks;
chunk = next;
}
pool->min_empty_chunks = pool->n_empty_chunks;
*first_to_free = NULL;
}
/** Helper: Given a list of chunks, free all the chunks in the list. */
static void
destroy_chunks(mp_chunk_t *chunk)
{
mp_chunk_t *next;
while (chunk) {
chunk->magic = 0xd3adb33f;
next = chunk->next;
FREE(chunk);
chunk = next;
}
}
/** Free all space held in <b>pool</b> This makes all pointers returned from
* mp_pool_get(<b>pool</b>) invalid. */
void
mp_pool_destroy(mp_pool_t *pool)
{
destroy_chunks(pool->empty_chunks);
destroy_chunks(pool->used_chunks);
destroy_chunks(pool->full_chunks);
memwipe(pool, 0xe0, sizeof(mp_pool_t));
FREE(pool);
}
/** Helper: make sure that a given chunk list is not corrupt. */
static int
assert_chunks_ok(mp_pool_t *pool, mp_chunk_t *chunk, int empty, int full)
{
mp_allocated_t *allocated;
int n = 0;
if (chunk)
ASSERT(chunk->prev == NULL);
while (chunk) {
n++;
ASSERT(chunk->magic == MP_CHUNK_MAGIC);
ASSERT(chunk->pool == pool);
for (allocated = chunk->first_free; allocated;
allocated = allocated->u.next_free) {
ASSERT(allocated->in_chunk == chunk);
}
if (empty)
ASSERT(chunk->n_allocated == 0);
else if (full)
ASSERT(chunk->n_allocated == chunk->capacity);
else
ASSERT(chunk->n_allocated > 0 && chunk->n_allocated < chunk->capacity);
ASSERT(chunk->capacity == pool->new_chunk_capacity);
ASSERT(chunk->mem_size ==
pool->new_chunk_capacity * pool->item_alloc_size);
ASSERT(chunk->next_mem >= chunk->mem &&
chunk->next_mem <= chunk->mem + chunk->mem_size);
if (chunk->next)
ASSERT(chunk->next->prev == chunk);
chunk = chunk->next;
}
return n;
}
/** Fail with an assertion if <b>pool</b> is not internally consistent. */
void
mp_pool_assert_ok(mp_pool_t *pool)
{
int n_empty;
n_empty = assert_chunks_ok(pool, pool->empty_chunks, 1, 0);
assert_chunks_ok(pool, pool->full_chunks, 0, 1);
assert_chunks_ok(pool, pool->used_chunks, 0, 0);
ASSERT(pool->n_empty_chunks == n_empty);
}
#ifdef TOR
/** Dump information about <b>pool</b>'s memory usage to the Tor log at level
* <b>severity</b>. */
/*FFFF uses Tor logging functions. */
void
mp_pool_log_status(mp_pool_t *pool, int severity)
{
uint64_t bytes_used = 0;
uint64_t bytes_allocated = 0;
uint64_t bu = 0, ba = 0;
mp_chunk_t *chunk;
int n_full = 0, n_used = 0;
ASSERT(pool);
for (chunk = pool->empty_chunks; chunk; chunk = chunk->next) {
bytes_allocated += chunk->mem_size;
}
log_fn(severity, LD_MM, U64_FORMAT" bytes in %d empty chunks",
U64_PRINTF_ARG(bytes_allocated), pool->n_empty_chunks);
for (chunk = pool->used_chunks; chunk; chunk = chunk->next) {
++n_used;
bu += chunk->n_allocated * pool->item_alloc_size;
ba += chunk->mem_size;
log_fn(severity, LD_MM, " used chunk: %d items allocated",
chunk->n_allocated);
}
log_fn(severity, LD_MM, U64_FORMAT"/"U64_FORMAT
" bytes in %d partially full chunks",
U64_PRINTF_ARG(bu), U64_PRINTF_ARG(ba), n_used);
bytes_used += bu;
bytes_allocated += ba;
bu = ba = 0;
for (chunk = pool->full_chunks; chunk; chunk = chunk->next) {
++n_full;
bu += chunk->n_allocated * pool->item_alloc_size;
ba += chunk->mem_size;
}
log_fn(severity, LD_MM, U64_FORMAT"/"U64_FORMAT
" bytes in %d full chunks",
U64_PRINTF_ARG(bu), U64_PRINTF_ARG(ba), n_full);
bytes_used += bu;
bytes_allocated += ba;
log_fn(severity, LD_MM, "Total: "U64_FORMAT"/"U64_FORMAT" bytes allocated "
"for cell pools are full.",
U64_PRINTF_ARG(bytes_used), U64_PRINTF_ARG(bytes_allocated));
#ifdef MEMPOOL_STATS
log_fn(severity, LD_MM, U64_FORMAT" cell allocations ever; "
U64_FORMAT" chunk allocations ever; "
U64_FORMAT" chunk frees ever.",
U64_PRINTF_ARG(pool->total_items_allocated),
U64_PRINTF_ARG(pool->total_chunks_allocated),
U64_PRINTF_ARG(pool->total_chunks_freed));
#endif
}
#endif