You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@trafficserver.apache.org by bc...@apache.org on 2017/05/31 02:41:20 UTC
[trafficserver] branch master updated: Ran clang-tidy with
readability-braces-around-statements
This is an automated email from the ASF dual-hosted git repository.
bcall pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/trafficserver.git
The following commit(s) were added to refs/heads/master by this push:
new 002d8ff Ran clang-tidy with readability-braces-around-statements
002d8ff is described below
commit 002d8ffe2ffe1917592c7022fd3da7421bf09780
Author: Bryan Call <bc...@apache.org>
AuthorDate: Sun May 28 22:15:19 2017 -0700
Ran clang-tidy with readability-braces-around-statements
---
cmd/traffic_cop/traffic_cop.cc | 7 +-
example/cppapi/boom/boom.cc | 49 +--
example/cppapi/websocket/WSBuffer.cc | 18 +-
example/cppapi/websocket/WebSocket.cc | 3 +-
example/redirect_1/redirect_1.c | 32 +-
iocore/aio/AIO.cc | 38 ++-
iocore/aio/test_AIO.cc | 65 ++--
iocore/cache/Cache.cc | 334 ++++++++++++-------
iocore/cache/CacheDir.cc | 213 +++++++-----
iocore/cache/CacheDisk.cc | 12 +-
iocore/cache/CacheHosting.cc | 47 ++-
iocore/cache/CacheHttp.cc | 9 +-
iocore/cache/CacheLink.cc | 33 +-
iocore/cache/CachePages.cc | 30 +-
iocore/cache/CachePagesInternal.cc | 30 +-
iocore/cache/CacheRead.cc | 237 +++++++++-----
iocore/cache/CacheTest.cc | 105 +++---
iocore/cache/CacheVol.cc | 62 ++--
iocore/cache/CacheWrite.cc | 360 +++++++++++++--------
iocore/cache/RamCacheCLFUS.cc | 121 ++++---
iocore/cache/RamCacheLRU.cc | 20 +-
iocore/cache/Store.cc | 204 ++++++++----
iocore/dns/DNS.cc | 223 ++++++++-----
iocore/dns/DNSConnection.cc | 40 ++-
iocore/dns/SplitDNS.cc | 24 +-
iocore/eventsystem/IOBuffer.cc | 30 +-
iocore/eventsystem/PQ-List.cc | 3 +-
iocore/eventsystem/ProtectedQueue.cc | 28 +-
iocore/eventsystem/SocketManager.cc | 8 +-
iocore/eventsystem/Thread.cc | 5 +-
iocore/eventsystem/UnixEThread.cc | 67 ++--
iocore/eventsystem/UnixEvent.cc | 24 +-
iocore/eventsystem/test_Event.cc | 6 +-
iocore/hostdb/HostDB.cc | 229 ++++++++-----
iocore/net/Connection.cc | 3 +-
iocore/net/OCSPStapling.cc | 57 ++--
iocore/net/SSLCertLookup.cc | 3 +-
iocore/net/SSLConfig.cc | 24 +-
iocore/net/SSLNetProcessor.cc | 3 +-
iocore/net/SSLNetVConnection.cc | 52 +--
iocore/net/SSLSessionCache.cc | 6 +-
iocore/net/SSLUtils.cc | 18 +-
iocore/net/Socks.cc | 54 ++--
iocore/net/UnixConnection.cc | 75 +++--
iocore/net/UnixNet.cc | 23 +-
iocore/net/UnixNetAccept.cc | 52 +--
iocore/net/UnixNetPages.cc | 24 +-
iocore/net/UnixNetProcessor.cc | 38 ++-
iocore/net/UnixNetVConnection.cc | 118 ++++---
iocore/net/UnixUDPConnection.cc | 16 +-
iocore/net/UnixUDPNet.cc | 59 ++--
iocore/utils/Machine.cc | 3 +-
iocore/utils/OneWayMultiTunnel.cc | 51 +--
iocore/utils/OneWayTunnel.cc | 42 ++-
lib/cppapi/Headers.cc | 15 +-
lib/cppapi/Plugin.cc | 3 +-
lib/cppapi/Request.cc | 3 +-
lib/cppapi/Transaction.cc | 8 +-
lib/records/RecCore.cc | 3 +-
lib/ts/BaseLogFile.cc | 21 +-
lib/ts/CompileParseRules.cc | 102 ++++--
lib/ts/Diags.cc | 67 ++--
lib/ts/EventNotify.cc | 21 +-
lib/ts/HostLookup.cc | 3 +-
lib/ts/IpMap.cc | 107 +++---
lib/ts/IpMapConf.cc | 23 +-
lib/ts/MMH.cc | 12 +-
lib/ts/MatcherUtils.cc | 6 +-
lib/ts/MemView.cc | 21 +-
lib/ts/ParseRules.cc | 52 +--
lib/ts/RbTree.cc | 25 +-
lib/ts/Regex.cc | 23 +-
lib/ts/Regression.cc | 32 +-
lib/ts/SourceLocation.cc | 3 +-
lib/ts/Tokenizer.cc | 21 +-
lib/ts/Vec.cc | 32 +-
lib/ts/Version.cc | 33 +-
lib/ts/X509HostnameValidator.cc | 60 ++--
lib/ts/ink_args.cc | 22 +-
lib/ts/ink_base64.cc | 25 +-
lib/ts/ink_defs.cc | 9 +-
lib/ts/ink_file.cc | 74 +++--
lib/ts/ink_hash_table.cc | 19 +-
lib/ts/ink_hrtime.cc | 11 +-
lib/ts/ink_inet.cc | 109 ++++---
lib/ts/ink_memory.cc | 18 +-
lib/ts/ink_queue.cc | 20 +-
lib/ts/ink_rand.cc | 3 +-
lib/ts/ink_res_init.cc | 124 ++++---
lib/ts/ink_res_mkquery.cc | 70 ++--
lib/ts/ink_rwlock.cc | 21 +-
lib/ts/ink_sock.cc | 40 ++-
lib/ts/ink_sprintf.cc | 28 +-
lib/ts/ink_stack_trace.cc | 6 +-
lib/ts/ink_string++.cc | 14 +-
lib/ts/ink_string.cc | 45 ++-
lib/ts/ink_thread.cc | 6 +-
lib/ts/ink_time.cc | 6 +-
lib/ts/llqueue.cc | 14 +-
lib/ts/lockfile.cc | 12 +-
lib/ts/test_Map.cc | 10 +-
lib/ts/test_Scalar.cc | 6 +-
lib/ts/test_Vec.cc | 45 ++-
lib/ts/test_atomic.cc | 15 +-
lib/tsconfig/Errata.cc | 9 +-
lib/tsconfig/TsBuilder.cc | 23 +-
lib/tsconfig/TsValue.cc | 97 +++---
lib/tsconfig/test-tsconfig.cc | 5 +-
mgmt/ProcessManager.cc | 3 +-
mgmt/utils/MgmtSocket.cc | 6 +-
plugins/esi/combo_handler.cc | 3 +-
.../experimental/cache_key_genid/cache_key_genid.c | 6 +-
plugins/experimental/cachekey/pattern.cc | 9 +-
plugins/experimental/header_freq/header_freq.cc | 6 +-
.../memcached_remap/memcached_remap.cc | 9 +-
plugins/experimental/mysql_remap/lib/dictionary.c | 36 ++-
plugins/experimental/mysql_remap/lib/iniparser.c | 54 ++--
plugins/experimental/mysql_remap/mysql_remap.cc | 9 +-
plugins/gzip/configuration.cc | 7 +-
plugins/gzip/gzip.cc | 12 +-
proxy/IPAllow.cc | 6 +-
proxy/InkAPI.cc | 9 +-
proxy/Main.cc | 3 +-
proxy/http/Http1ClientSession.cc | 6 +-
proxy/http/HttpBodyFactory.cc | 3 +-
proxy/http/HttpTransact.cc | 6 +-
proxy/http/HttpTransactHeaders.cc | 3 +-
proxy/http/HttpTunnel.cc | 9 +-
proxy/http/remap/RemapConfig.cc | 3 +-
proxy/http/remap/RemapProcessor.cc | 3 +-
proxy/http2/Http2Stream.cc | 15 +-
131 files changed, 3382 insertions(+), 1883 deletions(-)
diff --git a/cmd/traffic_cop/traffic_cop.cc b/cmd/traffic_cop/traffic_cop.cc
index 193b6c9..c4ea158 100644
--- a/cmd/traffic_cop/traffic_cop.cc
+++ b/cmd/traffic_cop/traffic_cop.cc
@@ -1383,12 +1383,13 @@ check_memory()
memfree = swapfree = swapsize = 0;
if ((fp = fopen("/proc/meminfo", "r"))) {
while (fgets(buf, sizeof buf, fp)) {
- if (strncmp(buf, "MemFree:", sizeof "MemFree:" - 1) == 0)
+ if (strncmp(buf, "MemFree:", sizeof "MemFree:" - 1) == 0) {
memfree = strtoll(buf + sizeof "MemFree:" - 1, nullptr, 10);
- else if (strncmp(buf, "SwapFree:", sizeof "SwapFree:" - 1) == 0)
+ } else if (strncmp(buf, "SwapFree:", sizeof "SwapFree:" - 1) == 0) {
swapfree = strtoll(buf + sizeof "SwapFree:" - 1, nullptr, 10);
- else if (strncmp(buf, "SwapTotal:", sizeof "SwapTotal:" - 1) == 0)
+ } else if (strncmp(buf, "SwapTotal:", sizeof "SwapTotal:" - 1) == 0) {
swapsize = strtoll(buf + sizeof "SwapTotal:" - 1, nullptr, 10);
+ }
}
fclose(fp);
// simple heuristic for linux
diff --git a/example/cppapi/boom/boom.cc b/example/cppapi/boom/boom.cc
index a919bd3..8a9f2e0 100644
--- a/example/cppapi/boom/boom.cc
+++ b/example/cppapi/boom/boom.cc
@@ -119,18 +119,24 @@ public:
operator()(const std::string &code) const
{
TS_DEBUG(TAG, "Checking if %s matches code %s", current_code_string_.c_str(), code.c_str());
- if (code == current_code_string_)
+ if (code == current_code_string_) {
return true;
- if (code == "2xx" && current_code_ >= 200 && current_code_ <= 299)
+ }
+ if (code == "2xx" && current_code_ >= 200 && current_code_ <= 299) {
return true;
- if (code == "3xx" && current_code_ >= 300 && current_code_ <= 399)
+ }
+ if (code == "3xx" && current_code_ >= 300 && current_code_ <= 399) {
return true;
- if (code == "4xx" && current_code_ >= 400 && current_code_ <= 499)
+ }
+ if (code == "4xx" && current_code_ >= 400 && current_code_ <= 499) {
return true;
- if (code == "5xx" && current_code_ >= 500 && current_code_ <= 599)
+ }
+ if (code == "5xx" && current_code_ >= 500 && current_code_ <= 599) {
return true;
- if (code == "6xx" && current_code_ >= 600 && current_code_ <= 699)
+ }
+ if (code == "6xx" && current_code_ >= 600 && current_code_ <= 699) {
return true;
+ }
return false;
}
@@ -204,8 +210,9 @@ BoomResponseRegistry::populate_error_responses(const std::string &base_directory
base_error_directory_ = base_directory;
// Make sure we have a trailing / after the base directory
- if (!base_error_directory_.empty() && base_error_directory_[base_error_directory_.length() - 1] != '/')
+ if (!base_error_directory_.empty() && base_error_directory_[base_error_directory_.length() - 1] != '/') {
base_error_directory_.append("/"); // make sure we have a trailing /
+ }
// Iterate over files in the base directory.
// Filename (sans the .html suffix) becomes the entry to the
@@ -217,8 +224,9 @@ BoomResponseRegistry::populate_error_responses(const std::string &base_directory
if (pDIR != nullptr) {
while (true) {
entry = readdir(pDIR);
- if (entry == nullptr)
+ if (entry == nullptr) {
break;
+ }
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
std::string file_name(entry->d_name, strlen(entry->d_name));
@@ -248,16 +256,19 @@ BoomResponseRegistry::get_response_for_error_code(int http_status_code)
{
std::string code_str = code_from_status(http_status_code);
- if (error_responses_.count(code_str))
+ if (error_responses_.count(code_str)) {
return error_responses_[code_str];
+ }
std::string gen_code_str = generic_code_from_status(http_status_code);
- if (error_responses_.count(gen_code_str))
+ if (error_responses_.count(gen_code_str)) {
return error_responses_[gen_code_str];
+ }
- if (error_responses_.count(DEFAULT_ERROR_FILE))
+ if (error_responses_.count(DEFAULT_ERROR_FILE)) {
return error_responses_[DEFAULT_ERROR_FILE];
+ }
return DEFAULT_ERROR_RESPONSE;
}
@@ -267,25 +278,27 @@ BoomResponseRegistry::has_code_registered(int http_status_code)
{
// Only rewritable codes are allowed.
std::set<std::string>::iterator ii = std::find_if(error_codes_.begin(), error_codes_.end(), IsRewritableCode(http_status_code));
- if (ii == error_codes_.end())
+ if (ii == error_codes_.end()) {
return false;
- else
+ } else {
return true;
+ }
}
std::string
BoomResponseRegistry::generic_code_from_status(int code)
{
- if (code >= 200 && code <= 299)
+ if (code >= 200 && code <= 299) {
return "2xx";
- else if (code >= 300 && code <= 399)
+ } else if (code >= 300 && code <= 399) {
return "3xx";
- else if (code >= 400 && code <= 499)
+ } else if (code >= 400 && code <= 499) {
return "4xx";
- else if (code >= 500 && code <= 599)
+ } else if (code >= 500 && code <= 599) {
return "5xx";
- else
+ } else {
return "default";
+ }
}
std::string
diff --git a/example/cppapi/websocket/WSBuffer.cc b/example/cppapi/websocket/WSBuffer.cc
index cfa7b4a..69a8240 100644
--- a/example/cppapi/websocket/WSBuffer.cc
+++ b/example/cppapi/websocket/WSBuffer.cc
@@ -87,8 +87,9 @@ WSBuffer::read_buffered_message(std::string &message, int &code)
size_t avail = ws_buf_.size();
// Check if there is a mask (there should be).
- if (avail < 2)
+ if (avail < 2) {
return false;
+ }
size_t mask_len = (ws_buf_[1] & WS_MASKED) ? 4 : 0;
int frame = ws_buf_[0] & WS_OPCODE;
@@ -99,12 +100,14 @@ WSBuffer::read_buffered_message(std::string &message, int &code)
if (first) {
frame_ = frame;
msg_buf_.clear();
- } else
+ } else {
frame = frame_;
+ }
// Read the msg_length if we have enough data.
- if (avail < 2 + mask_len)
+ if (avail < 2 + mask_len) {
return false;
+ }
size_t msg_len = ws_buf_[1] & WS_LENGTH;
size_t pos;
@@ -125,8 +128,9 @@ WSBuffer::read_buffered_message(std::string &message, int &code)
}
// Check if we have enough data to read the message.
- if (ws_buf_.size() < pos + msg_len)
+ if (ws_buf_.size() < pos + msg_len) {
return false; // not enough data.
+ }
// Copy any mask.
for (size_t i = 0; i < mask_len; ++i, ++pos) {
@@ -245,11 +249,13 @@ WSBuffer::get_closing_code(std::string const &message, std::string *desc)
code = (unsigned char)message[0];
code <<= 8;
code += (unsigned char)message[1];
- if (desc)
+ if (desc) {
*desc = message.substr(2);
+ }
} else {
- if (desc)
+ if (desc) {
*desc = "";
+ }
}
return code;
}
diff --git a/example/cppapi/websocket/WebSocket.cc b/example/cppapi/websocket/WebSocket.cc
index ee2ea54..d0da601 100644
--- a/example/cppapi/websocket/WebSocket.cc
+++ b/example/cppapi/websocket/WebSocket.cc
@@ -90,8 +90,9 @@ WebSocket::consume(const std::string &data, InterceptPlugin::RequestDataType typ
ws_buf_.buffer(data);
while (ws_buf_.read_buffered_message(message, code)) {
ws_receive(message, code);
- if (code == WS_FRAME_CLOSE)
+ if (code == WS_FRAME_CLOSE) {
break;
+ }
}
} else {
body_ += data;
diff --git a/example/redirect_1/redirect_1.c b/example/redirect_1/redirect_1.c
index 494e397..677ef71 100644
--- a/example/redirect_1/redirect_1.c
+++ b/example/redirect_1/redirect_1.c
@@ -84,15 +84,17 @@ handle_client_lookup(TSHttpTxn txnp, TSCont contp)
if (addr) {
socklen_t addr_size = 0;
- if (addr->sa_family == AF_INET)
+ if (addr->sa_family == AF_INET) {
addr_size = sizeof(struct sockaddr_in);
- else if (addr->sa_family == AF_INET6)
+ } else if (addr->sa_family == AF_INET6) {
addr_size = sizeof(struct sockaddr_in6);
+ }
if (addr_size > 0) {
char clientstring[INET6_ADDRSTRLEN];
- if (NULL != inet_ntop(addr->sa_family, addr, clientstring, addr_size))
+ if (NULL != inet_ntop(addr->sa_family, addr, clientstring, addr_size)) {
TSDebug(PLUGIN_NAME, "clientip is %s and block_ip is %s", clientstring, block_ip);
+ }
}
}
}
@@ -249,17 +251,17 @@ update_redirected_method_stats(TSMBuffer bufp, TSMLoc hdr_loc)
txn_method = TSHttpHdrMethodGet(bufp, hdr_loc, &length);
if (NULL != txn_method) {
- if (0 == strncmp(txn_method, TS_HTTP_METHOD_CONNECT, length))
+ if (0 == strncmp(txn_method, TS_HTTP_METHOD_CONNECT, length)) {
TSStatIntIncrement(redirect_count_connect, 1);
- else if (0 == strncmp(txn_method, TS_HTTP_METHOD_DELETE, length))
+ } else if (0 == strncmp(txn_method, TS_HTTP_METHOD_DELETE, length)) {
TSStatIntIncrement(redirect_count_delete, 1);
- else if (0 == strncmp(txn_method, TS_HTTP_METHOD_GET, length))
+ } else if (0 == strncmp(txn_method, TS_HTTP_METHOD_GET, length)) {
TSStatIntIncrement(redirect_count_get, 1);
- else if (0 == strncmp(txn_method, TS_HTTP_METHOD_HEAD, length))
+ } else if (0 == strncmp(txn_method, TS_HTTP_METHOD_HEAD, length)) {
TSStatIntIncrement(redirect_count_head, 1);
- else if (0 == strncmp(txn_method, TS_HTTP_METHOD_OPTIONS, length)) {
+ } else if (0 == strncmp(txn_method, TS_HTTP_METHOD_OPTIONS, length)) {
// This is a bad idea in a real plugin because it causes a race condition
// with other transactions, but is here for illustrative purposes.
tempint = TSStatIntGet(redirect_count_options);
@@ -271,14 +273,15 @@ update_redirected_method_stats(TSMBuffer bufp, TSMLoc hdr_loc)
TSStatIntIncrement(redirect_count_post, 2);
}
- else if (0 == strncmp(txn_method, TS_HTTP_METHOD_PURGE, length))
+ else if (0 == strncmp(txn_method, TS_HTTP_METHOD_PURGE, length)) {
TSStatIntIncrement(redirect_count_purge, 1);
- else if (0 == strncmp(txn_method, TS_HTTP_METHOD_PUT, length))
+ } else if (0 == strncmp(txn_method, TS_HTTP_METHOD_PUT, length)) {
TSStatIntIncrement(redirect_count_put, 1);
- else if (0 == strncmp(txn_method, TS_HTTP_METHOD_TRACE, length))
+ } else if (0 == strncmp(txn_method, TS_HTTP_METHOD_TRACE, length)) {
TSStatIntIncrement(redirect_count_trace, 1);
- else
+ } else {
TSStatIntIncrement(redirect_count_unknown, 1);
+ }
}
}
@@ -329,8 +332,9 @@ TSPluginInit(int argc, const char *argv[])
* be done in debug mode.
*/
- if (TSIsDebugTagSet(PLUGIN_NAME ".demo"))
+ if (TSIsDebugTagSet(PLUGIN_NAME ".demo")) {
TSDebug(PLUGIN_NAME ".init", "The redirect_demo tag is set");
- else
+ } else {
TSDebug(PLUGIN_NAME ".init", "The redirect_demo tag is not set");
+ }
}
diff --git a/iocore/aio/AIO.cc b/iocore/aio/AIO.cc
index 7651bfe..cc084b5 100644
--- a/iocore/aio/AIO.cc
+++ b/iocore/aio/AIO.cc
@@ -252,10 +252,11 @@ aio_init_fildes(int fildes, int fromAPI = 0)
REC_ReadConfigInteger(stacksize, "proxy.config.thread.default.stacksize");
for (i = 0; i < thread_num; i++) {
- if (i == (thread_num - 1))
+ if (i == (thread_num - 1)) {
thr_info = new AIOThreadInfo(request, 1);
- else
+ } else {
thr_info = new AIOThreadInfo(request, 0);
+ }
snprintf(thr_name, MAX_THREAD_NAME_LENGTH, "[ET_AIO %d:%d]", i, fildes);
ink_assert(eventProcessor.spawn_thread(thr_info, thr_name, stacksize));
}
@@ -280,10 +281,11 @@ aio_insert(AIOCallback *op, AIO_Reqs *req)
if (op->aiocb.aio_reqprio == AIO_LOWEST_PRIORITY) // http request
{
AIOCallback *cb = (AIOCallback *)req->http_aio_todo.tail;
- if (!cb)
+ if (!cb) {
req->http_aio_todo.push(op);
- else
+ } else {
req->http_aio_todo.insert(op, cb);
+ }
} else {
AIOCallback *cb = (AIOCallback *)req->aio_todo.tail;
@@ -305,8 +307,9 @@ aio_move(AIO_Reqs *req)
{
AIOCallback *next = nullptr, *prev = nullptr, *cb = (AIOCallback *)ink_atomiclist_popall(&req->aio_temp_list);
/* flip the list */
- if (!cb)
+ if (!cb) {
return;
+ }
while (cb->link.next) {
next = (AIOCallback *)cb->link.next;
cb->link.next = prev;
@@ -359,8 +362,9 @@ aio_queue_req(AIOCallbackInternal *op, int fromAPI = 0)
break;
}
}
- if (!req)
+ if (!req) {
req = aio_init_fildes(op->aiocb.aio_fildes);
+ }
}
ink_mutex_release(&insert_mutex);
}
@@ -387,8 +391,9 @@ aio_queue_req(AIOCallbackInternal *op, int fromAPI = 0)
#ifdef AIO_STATS
ink_atomic_increment(&data->num_queue, 1);
#endif
- if (!INK_ATOMICLIST_EMPTY(req->aio_temp_list))
+ if (!INK_ATOMICLIST_EMPTY(req->aio_temp_list)) {
aio_move(req);
+ }
/* now put the new request */
aio_insert(op, req);
ink_cond_signal(&req->aio_cond);
@@ -406,10 +411,11 @@ cache_op(AIOCallbackInternal *op)
while (a->aio_nbytes - res > 0) {
do {
- if (read)
+ if (read) {
err = pread(a->aio_fildes, ((char *)a->aio_buf) + res, a->aio_nbytes - res, a->aio_offset + res);
- else
+ } else {
err = pwrite(a->aio_fildes, ((char *)a->aio_buf) + res, a->aio_nbytes - res, a->aio_offset + res);
+ }
} while ((err < 0) && (errno == EINTR || errno == ENOBUFS || errno == ENOMEM));
if (err <= 0) {
Warning("cache disk operation failed %s %zd %d\n", (a->aio_lio_opcode == LIO_READ) ? "READ" : "WRITE", err, errno);
@@ -469,10 +475,12 @@ aio_thread_main(void *arg)
}
current_req = my_aio_req;
/* check if any pending requests on the atomic list */
- if (!INK_ATOMICLIST_EMPTY(my_aio_req->aio_temp_list))
+ if (!INK_ATOMICLIST_EMPTY(my_aio_req->aio_temp_list)) {
aio_move(my_aio_req);
- if (!(op = my_aio_req->aio_todo.pop()) && !(op = my_aio_req->http_aio_todo.pop()))
+ }
+ if (!(op = my_aio_req->aio_todo.pop()) && !(op = my_aio_req->http_aio_todo.pop())) {
break;
+ }
#ifdef AIO_STATS
num_requests--;
current_req->queued--;
@@ -506,12 +514,14 @@ aio_thread_main(void *arg)
op->mutex = op->action.mutex;
if (op->thread == AIO_CALLBACK_THREAD_AIO) {
SCOPED_MUTEX_LOCK(lock, op->mutex, thr_info->mutex->thread_holding);
- if (!op->action.cancelled)
+ if (!op->action.cancelled) {
op->action.continuation->handleEvent(AIO_EVENT_DONE, op);
- } else if (op->thread == AIO_CALLBACK_THREAD_ANY)
+ }
+ } else if (op->thread == AIO_CALLBACK_THREAD_ANY) {
eventProcessor.schedule_imm_signal(op);
- else
+ } else {
op->thread->schedule_imm_signal(op);
+ }
ink_mutex_acquire(&my_aio_req->aio_mutex);
} while (true);
timespec timedwait_msec = ink_hrtime_to_timespec(Thread::get_hrtime_updated() + HRTIME_MSECONDS(net_config_poll_timeout));
diff --git a/iocore/aio/test_AIO.cc b/iocore/aio/test_AIO.cc
index b6ec70d..5c2545f 100644
--- a/iocore/aio/test_AIO.cc
+++ b/iocore/aio/test_AIO.cc
@@ -106,18 +106,20 @@ struct AIO_Device : public Continuation {
int
select_mode(double p)
{
- if (p < real_seq_read_percent)
+ if (p < real_seq_read_percent) {
return READ_MODE;
- else if (p < real_seq_read_percent + real_seq_write_percent)
+ } else if (p < real_seq_read_percent + real_seq_write_percent) {
return WRITE_MODE;
- else
+ } else {
return RANDOM_READ_MODE;
+ }
};
void
do_touch_data(off_t orig_len, off_t orig_offset)
{
- if (!touch_data)
+ if (!touch_data) {
return;
+ }
unsigned int len = (unsigned int)orig_len;
unsigned int offset = (unsigned int)orig_offset;
offset = offset % 1024;
@@ -131,15 +133,17 @@ struct AIO_Device : public Continuation {
int
do_check_data(off_t orig_len, off_t orig_offset)
{
- if (!touch_data)
+ if (!touch_data) {
return 0;
+ }
unsigned int len = (unsigned int)orig_len;
unsigned int offset = (unsigned int)orig_offset;
offset = offset % 1024;
unsigned *x = (unsigned *)buf;
for (unsigned j = 0; j < (len / sizeof(int)); j++) {
- if (x[j] != offset)
+ if (x[j] != offset) {
return 1;
+ }
offset = (offset + 1) % 1024;
}
return 0;
@@ -207,9 +211,11 @@ dump_summary()
printf("%0.2f total mbytes/sec\n", sr + sw + rr);
printf("----------------------------------------------------------\n");
- if (delete_disks)
- for (int i = 0; i < n_disk_path; i++)
+ if (delete_disks) {
+ for (int i = 0; i < n_disk_path; i++) {
unlink(disk_path[i]);
+ }
+ }
exit(0);
}
@@ -222,8 +228,9 @@ AIO_Device::do_hotset(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
io->aiocb.aio_offset = MIN_OFFSET + hotset_idx * max_size;
do_touch_data(seq_read_size, io->aiocb.aio_offset);
ink_assert(!do_check_data(seq_read_size, io->aiocb.aio_offset));
- if (!hotset_idx)
+ if (!hotset_idx) {
fprintf(stderr, "Starting hotset document writing \n");
+ }
if (io->aiocb.aio_offset > max_offset) {
fprintf(stderr, "Finished hotset documents [%d] offset [%6.0f] size [%6.0f]\n", hotset_idx, (float)MIN_OFFSET,
(float)max_size);
@@ -250,8 +257,9 @@ AIO_Device::do_fd(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
if ((Thread::get_hrtime() - time_start) > (run_time * HRTIME_SECOND)) {
time_end = Thread::get_hrtime();
ink_atomic_increment(&n_accessors, -1);
- if (n_accessors <= 0)
+ if (n_accessors <= 0) {
dump_summary();
+ }
return 0;
}
@@ -260,8 +268,9 @@ AIO_Device::do_fd(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
off_t seq_read_point = ((off_t)MIN_OFFSET);
off_t seq_write_point = ((off_t)MIN_OFFSET) + max_offset / 2 + write_after * 1024 * 1024;
seq_write_point += (id % n_disk_path) * (max_offset / (threads_per_disk * 4));
- if (seq_write_point > max_offset)
+ if (seq_write_point > max_offset) {
seq_write_point = MIN_OFFSET;
+ }
if (io->aiocb.aio_lio_opcode == LIO_READ) {
ink_assert(!do_check_data(io->aiocb.aio_nbytes, io->aiocb.aio_offset));
@@ -279,8 +288,9 @@ AIO_Device::do_fd(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
io->aiocb.aio_lio_opcode = LIO_READ;
ink_assert(ink_aio_read(io) >= 0);
seq_read_point += seq_read_size;
- if (seq_read_point > max_offset)
+ if (seq_read_point > max_offset) {
seq_read_point = MIN_OFFSET;
+ }
seq_reads++;
break;
case WRITE_MODE:
@@ -291,8 +301,9 @@ AIO_Device::do_fd(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
ink_assert(ink_aio_write(io) >= 0);
seq_write_point += seq_write_size;
seq_write_point += write_skip;
- if (seq_write_point > max_offset)
+ if (seq_write_point > max_offset) {
seq_write_point = MIN_OFFSET;
+ }
seq_writes++;
break;
@@ -302,12 +313,14 @@ AIO_Device::do_fd(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
p = drand48();
f = drand48();
off_t o = 0;
- if (f < hotset_frequency)
+ if (f < hotset_frequency) {
o = (off_t)p * max_hotset_offset;
- else
+ } else {
o = (off_t)p * (max_offset - rand_read_size);
- if (o < MIN_OFFSET)
- o = MIN_OFFSET;
+ }
+ if (o < MIN_OFFSET) {
+ o = MIN_OFFSET;
+ }
o = (o + (seq_read_size - 1)) & (~(seq_read_size - 1));
io->aiocb.aio_offset = o;
io->aiocb.aio_nbytes = rand_read_size;
@@ -377,12 +390,15 @@ read_config(const char *config_filename)
real_seq_read_percent = seq_read_percent;
real_seq_write_percent = seq_write_percent;
real_rand_read_percent = rand_read_percent;
- if (seq_read_size)
+ if (seq_read_size) {
real_seq_read_percent *= t / seq_read_size;
- if (seq_write_size)
+ }
+ if (seq_write_size) {
real_seq_write_percent *= t / seq_write_size;
- if (rand_read_size)
+ }
+ if (rand_read_size) {
real_rand_read_percent *= t / rand_read_size;
+ }
float tt = real_seq_read_percent + real_seq_write_percent + real_rand_read_percent;
real_seq_read_percent = real_seq_read_percent / tt;
real_seq_write_percent = real_seq_write_percent / tt;
@@ -418,14 +434,17 @@ main(int /* argc ATS_UNUSED */, char *argv[])
ink_aio_init(AIO_MODULE_VERSION);
srand48(time(nullptr));
printf("input file %s\n", argv[1]);
- if (!read_config(argv[1]))
+ if (!read_config(argv[1])) {
exit(1);
+ }
max_size = seq_read_size;
- if (seq_write_size > max_size)
+ if (seq_write_size > max_size) {
max_size = seq_write_size;
- if (rand_read_size > max_size)
+ }
+ if (rand_read_size > max_size) {
max_size = rand_read_size;
+ }
cache_config_threads_per_disk = threads_per_disk;
orig_n_accessors = n_disk_path * threads_per_disk;
diff --git a/iocore/cache/Cache.cc b/iocore/cache/Cache.cc
index 1281b7a..5049de3 100644
--- a/iocore/cache/Cache.cc
+++ b/iocore/cache/Cache.cc
@@ -211,10 +211,11 @@ cache_bytes_used(int volume)
for (int i = 0; i < gnvol; i++) {
if (!DISK_BAD(gvol[i]->disk) && (volume == -1 || gvol[i]->cache_vol->vol_number == volume)) {
- if (!gvol[i]->header->cycle)
+ if (!gvol[i]->header->cycle) {
used += gvol[i]->header->write_pos - gvol[i]->start;
- else
+ } else {
used += gvol[i]->len - vol_dirlen(gvol[i]) - EVACUATION_SIZE;
+ }
}
}
@@ -307,8 +308,9 @@ CacheVC::do_io_read(Continuation *c, int64_t nbytes, MIOBuffer *abuf)
#ifdef DEBUG
ink_assert(c->mutex->thread_holding);
#endif
- if (!trigger && !recursive)
+ if (!trigger && !recursive) {
trigger = c->mutex->thread_holding->schedule_imm_local(this);
+ }
return &vio;
}
@@ -325,8 +327,9 @@ CacheVC::do_io_pread(Continuation *c, int64_t nbytes, MIOBuffer *abuf, int64_t o
#ifdef DEBUG
ink_assert(c->mutex->thread_holding);
#endif
- if (!trigger && !recursive)
+ if (!trigger && !recursive) {
trigger = c->mutex->thread_holding->schedule_imm_local(this);
+ }
return &vio;
}
@@ -343,8 +346,9 @@ CacheVC::do_io_write(Continuation *c, int64_t nbytes, IOBufferReader *abuf, bool
#ifdef DEBUG
ink_assert(c->mutex->thread_holding);
#endif
- if (!trigger && !recursive)
+ if (!trigger && !recursive) {
trigger = c->mutex->thread_holding->schedule_imm_local(this);
+ }
return &vio;
}
@@ -355,8 +359,9 @@ CacheVC::do_io_close(int alerrno)
int previous_closed = closed;
closed = (alerrno == -1) ? 1 : -1; // Stupid default arguments
DDebug("cache_close", "do_io_close %p %d %d", this, alerrno, closed);
- if (!previous_closed && !recursive)
+ if (!previous_closed && !recursive) {
die();
+ }
}
void
@@ -390,8 +395,9 @@ CacheVC::reenable_re(VIO *avio)
if (!trigger) {
if (!is_io_in_progress() && !recursive) {
handleEvent(EVENT_NONE, (void *)nullptr);
- } else
+ } else {
trigger = avio->mutex->thread_holding->schedule_imm_local(this);
+ }
}
}
@@ -447,12 +453,14 @@ CacheVC::set_http_info(CacheHTTPInfo *ainfo)
}
if (enable_cache_empty_http_doc) {
MIMEField *field = ainfo->m_alt->m_response_hdr.field_find(MIME_FIELD_CONTENT_LENGTH, MIME_LEN_CONTENT_LENGTH);
- if (field && !field->value_get_int64())
+ if (field && !field->value_get_int64()) {
f.allow_empty_doc = 1;
- else
+ } else {
f.allow_empty_doc = 0;
- } else
+ }
+ } else {
f.allow_empty_doc = 0;
+ }
alternate.copy_shallow(ainfo);
ainfo->clear();
}
@@ -502,15 +510,18 @@ Vol::begin_read(CacheVC *cont)
stat_cache_vcs.enqueue(cont, cont->stat_link);
#endif
// no need for evacuation as the entire document is already in memory
- if (cont->f.single_fragment)
+ if (cont->f.single_fragment) {
return 0;
+ }
int i = dir_evac_bucket(&cont->earliest_dir);
EvacuationBlock *b;
for (b = evacuate[i].head; b; b = b->link.next) {
- if (dir_offset(&b->dir) != dir_offset(&cont->earliest_dir))
+ if (dir_offset(&b->dir) != dir_offset(&cont->earliest_dir)) {
continue;
- if (b->readers)
+ }
+ if (b->readers) {
b->readers = b->readers + 1;
+ }
return 0;
}
// we don't actually need to preserve this block as it is already in
@@ -530,8 +541,9 @@ Vol::close_read(CacheVC *cont)
EThread *t = cont->mutex->thread_holding;
ink_assert(t == this_ethread());
ink_assert(t == mutex->thread_holding);
- if (dir_is_empty(&cont->earliest_dir))
+ if (dir_is_empty(&cont->earliest_dir)) {
return 1;
+ }
int i = dir_evac_bucket(&cont->earliest_dir);
EvacuationBlock *b;
for (b = evacuate[i].head; b;) {
@@ -635,8 +647,9 @@ CacheProcessor::start_internal(int flags)
int fd = open(path, opts, 0644);
int64_t blocks = sd->blocks;
- if (fd < 0 && (opts & O_CREAT)) // Try without O_DIRECT if this is a file on filesystem, e.g. tmpfs.
+ if (fd < 0 && (opts & O_CREAT)) { // Try without O_DIRECT if this is a file on filesystem, e.g. tmpfs.
fd = open(path, DEFAULT_CACHE_OPTIONS | O_CREAT, 0644);
+ }
if (fd >= 0) {
if (!sd->file_pathname) {
@@ -662,11 +675,13 @@ CacheProcessor::start_internal(int flags)
int sector_size = sd->hw_sector_size;
gdisks[gndisks] = new CacheDisk();
- if (check)
- gdisks[gndisks]->read_only_p = true;
+ if (check) {
+ gdisks[gndisks]->read_only_p = true;
+ }
gdisks[gndisks]->forced_volume_num = sd->forced_volume_num;
- if (sd->hash_base_string)
+ if (sd->hash_base_string) {
gdisks[gndisks]->hash_base_string = ats_strdup(sd->hash_base_string);
+ }
Debug("cache_hosting", "Disk: %d, blocks: %" PRId64 "", gndisks, blocks);
@@ -693,10 +708,11 @@ CacheProcessor::start_internal(int flags)
gndisks++;
}
} else {
- if (errno == EINVAL)
+ if (errno == EINVAL) {
Warning("cache unable to open '%s': It must be placed on a file system that supports direct I/O.", path);
- else
+ } else {
Warning("cache unable to open '%s': %s", path, strerror(errno));
+ }
}
if (fd >= 0) {
close(fd);
@@ -708,8 +724,9 @@ CacheProcessor::start_internal(int flags)
if (gndisks == 0) {
CacheProcessor::initialized = CACHE_INIT_FAILED;
// Have to do this here because no IO events were scheduled and so @c diskInitialized() won't be called.
- if (cb_after_init)
+ if (cb_after_init) {
cb_after_init();
+ }
if (this->waitForCache() > 1) {
Fatal("Cache initialization failed - no disks available but cache required");
@@ -719,8 +736,9 @@ CacheProcessor::start_internal(int flags)
}
} else if (this->waitForCache() == 3 && static_cast<unsigned int>(gndisks) < theCacheStore.n_disks_in_config) {
CacheProcessor::initialized = CACHE_INIT_FAILED;
- if (cb_after_init)
+ if (cb_after_init) {
cb_after_init();
+ }
Fatal("Cache initialization failed - only %d out of %d disks were valid and all were required.", gndisks,
theCacheStore.n_disks_in_config);
}
@@ -737,8 +755,9 @@ CacheProcessor::diskInitialized()
if (n_init == gndisks - 1) {
int i;
for (i = 0; i < gndisks; i++) {
- if (DISK_BAD(gdisks[i]))
+ if (DISK_BAD(gdisks[i])) {
bad_disks++;
+ }
}
if (bad_disks != 0) {
@@ -747,17 +766,19 @@ CacheProcessor::diskInitialized()
// This could be passed off to @c cacheInitialized (as with volume config problems) but I think
// the more specific error message here is worth the extra code.
CacheProcessor::initialized = CACHE_INIT_FAILED;
- if (cb_after_init)
+ if (cb_after_init) {
cb_after_init();
+ }
Fatal("Cache initialization failed - only %d of %d disks were available.", gndisks, theCacheStore.n_disks_in_config);
}
// still good, create a new array to hold the valid disks.
CacheDisk **p_good_disks;
- if ((gndisks - bad_disks) > 0)
+ if ((gndisks - bad_disks) > 0) {
p_good_disks = (CacheDisk **)ats_malloc((gndisks - bad_disks) * sizeof(CacheDisk *));
- else
+ } else {
p_good_disks = nullptr;
+ }
int insert_at = 0;
for (i = 0; i < gndisks; i++) {
@@ -823,8 +844,9 @@ CacheProcessor::diskInitialized()
d->header->vol_info[j].len, d->header->vol_info[j].free);
}
}
- if (!check)
+ if (!check) {
d->sync();
+ }
}
if (config_volumes.num_volumes == 0) {
theCache = new Cache();
@@ -851,8 +873,9 @@ CacheProcessor::cacheInitialized()
{
int i;
- if ((theCache && (theCache->ready == CACHE_INITIALIZING)) || (theStreamCache && (theStreamCache->ready == CACHE_INITIALIZING)))
+ if ((theCache && (theCache->ready == CACHE_INITIALIZING)) || (theStreamCache && (theStreamCache->ready == CACHE_INITIALIZING))) {
return;
+ }
int caches_ready = 0;
int cache_init_ok = 0;
/* allocate ram size in proportion to the disk space the
@@ -901,15 +924,18 @@ CacheProcessor::cacheInitialized()
}
// Update stripe version data.
- if (gnvol) // start with whatever the first stripe is.
+ if (gnvol) { // start with whatever the first stripe is.
cacheProcessor.min_stripe_version = cacheProcessor.max_stripe_version = gvol[0]->header->version;
+ }
// scan the rest of the stripes.
for (i = 1; i < gnvol; i++) {
Vol *v = gvol[i];
- if (v->header->version < cacheProcessor.min_stripe_version)
+ if (v->header->version < cacheProcessor.min_stripe_version) {
cacheProcessor.min_stripe_version = v->header->version;
- if (cacheProcessor.max_stripe_version < v->header->version)
+ }
+ if (cacheProcessor.max_stripe_version < v->header->version) {
cacheProcessor.max_stripe_version = v->header->version;
+ }
}
if (caches_ready) {
@@ -1029,11 +1055,13 @@ CacheProcessor::cacheInitialized()
GLOBAL_CACHE_SET_DYN_STAT(cache_bytes_total_stat, total_cache_bytes);
GLOBAL_CACHE_SET_DYN_STAT(cache_direntries_total_stat, total_direntries);
GLOBAL_CACHE_SET_DYN_STAT(cache_direntries_used_stat, used_direntries);
- if (!check)
+ if (!check) {
dir_sync_init();
+ }
cache_init_ok = 1;
- } else
+ } else {
Warning("cache unable to open any vols, disabled");
+ }
}
if (cache_init_ok) {
// Initialize virtual cache
@@ -1046,8 +1074,9 @@ CacheProcessor::cacheInitialized()
}
// Fire callback to signal initialization finished.
- if (cb_after_init)
+ if (cb_after_init) {
cb_after_init();
+ }
// TS-3848
if (CACHE_INIT_FAILED == CacheProcessor::initialized && cacheProcessor.waitForCache() > 1) {
@@ -1063,16 +1092,18 @@ CacheProcessor::stop()
int
CacheProcessor::dir_check(bool afix)
{
- for (int i = 0; i < gnvol; i++)
+ for (int i = 0; i < gnvol; i++) {
gvol[i]->dir_check(afix);
+ }
return 0;
}
int
CacheProcessor::db_check(bool afix)
{
- for (int i = 0; i < gnvol; i++)
+ for (int i = 0; i < gnvol; i++) {
gvol[i]->db_check(afix);
+ }
return 0;
}
@@ -1123,8 +1154,9 @@ CacheProcessor::IsCacheEnabled()
bool
CacheProcessor::IsCacheReady(CacheFragType type)
{
- if (IsCacheEnabled() != CACHE_INITIALIZED)
+ if (IsCacheEnabled() != CACHE_INITIALIZED) {
return false;
+ }
return (bool)(cache_ready & (1 << type));
}
@@ -1267,10 +1299,12 @@ Vol::init(char *s, off_t blocks, off_t dir_skip, bool clear)
(double)vol_dirlen(this) / (double)this->len * 100.0);
raw_dir = nullptr;
- if (ats_hugepage_enabled())
+ if (ats_hugepage_enabled()) {
raw_dir = (char *)ats_alloc_hugepage(vol_dirlen(this));
- if (raw_dir == nullptr)
+ }
+ if (raw_dir == nullptr) {
raw_dir = (char *)ats_memalign(ats_pagesize(), vol_dirlen(this));
+ }
dir = (Dir *)(raw_dir + vol_headerlen(this));
header = (VolHeaderFooter *)raw_dir;
@@ -1286,8 +1320,9 @@ Vol::init(char *s, off_t blocks, off_t dir_skip, bool clear)
off_t footer_offset = vol_dirlen(this) - footerlen;
// try A
off_t as = skip;
- if (is_debug_tag_set("cache_init"))
+ if (is_debug_tag_set("cache_init")) {
Note("reading directory '%s'", hash_text.get());
+ }
SET_HANDLER(&Vol::handle_header_read);
init_info->vol_aio[0].aiocb.aio_offset = as;
init_info->vol_aio[1].aiocb.aio_offset = as + footer_offset;
@@ -1437,8 +1472,9 @@ Vol::handle_recover_from_data(int event, void * /* data ATS_UNUSED */)
}
io.aiocb.aio_buf = (char *)ats_memalign(ats_pagesize(), RECOVERY_SIZE);
io.aiocb.aio_nbytes = RECOVERY_SIZE;
- if ((off_t)(recover_pos + io.aiocb.aio_nbytes) > (off_t)(skip + len))
+ if ((off_t)(recover_pos + io.aiocb.aio_nbytes) > (off_t)(skip + len)) {
io.aiocb.aio_nbytes = (skip + len) - recover_pos;
+ }
} else if (event == AIO_EVENT_DONE) {
if ((size_t)io.aiocb.aio_nbytes != (size_t)io.aio_result) {
Warning("disk read error on recover '%s', clearing", hash_text.get());
@@ -1462,8 +1498,9 @@ Vol::handle_recover_from_data(int event, void * /* data ATS_UNUSED */)
goto Lclear;
}
done += round_to_approx_size(doc->len);
- if (doc->sync_serial > last_write_serial)
+ if (doc->sync_serial > last_write_serial) {
last_sync_serial = doc->sync_serial;
+ }
}
ink_assert(done == to_check);
@@ -1495,8 +1532,9 @@ Vol::handle_recover_from_data(int event, void * /* data ATS_UNUSED */)
if (doc->magic != DOC_MAGIC || doc->sync_serial != last_sync_serial) {
if (doc->magic == DOC_MAGIC) {
- if (doc->sync_serial > header->sync_serial)
+ if (doc->sync_serial > header->sync_serial) {
max_sync_serial = doc->sync_serial;
+ }
/*
doc->magic == DOC_MAGIC, but doc->sync_serial != last_sync_serial
@@ -1570,20 +1608,23 @@ Vol::handle_recover_from_data(int event, void * /* data ATS_UNUSED */)
if (s >= e) {
/* In the last iteration, we increment s by doc->len...need to undo
that change */
- if (s > e)
+ if (s > e) {
s -= round_to_approx_size(doc->len);
+ }
recover_pos -= e - s;
if (recover_pos >= skip + len) {
recover_wrapped = true;
recover_pos = start;
}
io.aiocb.aio_nbytes = RECOVERY_SIZE;
- if ((off_t)(recover_pos + io.aiocb.aio_nbytes) > (off_t)(skip + len))
+ if ((off_t)(recover_pos + io.aiocb.aio_nbytes) > (off_t)(skip + len)) {
io.aiocb.aio_nbytes = (skip + len) - recover_pos;
+ }
}
}
- if (recover_pos == prev_recover_pos) // this should never happen, but if it does break the loop
+ if (recover_pos == prev_recover_pos) { // this should never happen, but if it does break the loop
goto Lclear;
+ }
prev_recover_pos = recover_pos;
io.aiocb.aio_offset = recover_pos;
ink_assert(ink_aio_read(&io));
@@ -1593,8 +1634,9 @@ Ldone : {
/* if we come back to the starting position, then we don't have to recover anything */
if (recover_pos == header->write_pos && recover_wrapped) {
SET_HANDLER(&Vol::handle_recover_write_dir);
- if (is_debug_tag_set("cache_init"))
+ if (is_debug_tag_set("cache_init")) {
Note("recovery wrapped around. nothing to clear\n");
+ }
return handle_recover_write_dir(EVENT_IMMEDIATE, nullptr);
}
@@ -1605,25 +1647,28 @@ Ldone : {
goto Lclear;
}
- if (recover_pos > skip + len)
+ if (recover_pos > skip + len) {
recover_pos -= skip + len;
+ }
// bump sync number so it is different from that in the Doc structs
uint32_t next_sync_serial = max_sync_serial + 1;
// make that the next sync does not overwrite our good copy!
- if (!(header->sync_serial & 1) == !(next_sync_serial & 1))
+ if (!(header->sync_serial & 1) == !(next_sync_serial & 1)) {
next_sync_serial++;
+ }
// clear effected portion of the cache
off_t clear_start = offset_to_vol_offset(this, header->write_pos);
off_t clear_end = offset_to_vol_offset(this, recover_pos);
- if (clear_start <= clear_end)
+ if (clear_start <= clear_end) {
dir_clear_range(clear_start, clear_end, this);
- else {
+ } else {
dir_clear_range(clear_end, DIR_OFFSET_MAX, this);
dir_clear_range(1, clear_start, this);
}
- if (is_debug_tag_set("cache_init"))
+ if (is_debug_tag_set("cache_init")) {
Note("recovery clearing offsets [%" PRIu64 ", %" PRIu64 "] sync_serial %d next %d\n", header->write_pos, recover_pos,
header->sync_serial, next_sync_serial);
+ }
footer->sync_serial = header->sync_serial = next_sync_serial;
for (int i = 0; i < 3; i++) {
@@ -1668,8 +1713,9 @@ Lclear:
int
Vol::handle_recover_write_dir(int /* event ATS_UNUSED */, void * /* data ATS_UNUSED */)
{
- if (io.aiocb.aio_buf)
+ if (io.aiocb.aio_buf) {
free((char *)io.aiocb.aio_buf);
+ }
delete init_info;
init_info = nullptr;
set_io_not_in_progress();
@@ -1707,16 +1753,18 @@ Vol::handle_header_read(int event, void *data)
if (hf[0]->sync_serial == hf[1]->sync_serial &&
(hf[0]->sync_serial >= hf[2]->sync_serial || hf[2]->sync_serial != hf[3]->sync_serial)) {
SET_HANDLER(&Vol::handle_dir_read);
- if (is_debug_tag_set("cache_init"))
+ if (is_debug_tag_set("cache_init")) {
Note("using directory A for '%s'", hash_text.get());
+ }
io.aiocb.aio_offset = skip;
ink_assert(ink_aio_read(&io));
}
// try B
else if (hf[2]->sync_serial == hf[3]->sync_serial) {
SET_HANDLER(&Vol::handle_dir_read);
- if (is_debug_tag_set("cache_init"))
+ if (is_debug_tag_set("cache_init")) {
Note("using directory B for '%s'", hash_text.get());
+ }
io.aiocb.aio_offset = skip + vol_dirlen(this);
ink_assert(ink_aio_read(&io));
} else {
@@ -1743,10 +1791,11 @@ Vol::dir_init_done(int /* event ATS_UNUSED */, void * /* data ATS_UNUSED */)
ink_assert(!gvol[vol_no]);
gvol[vol_no] = this;
SET_HANDLER(&Vol::aggWrite);
- if (fd == -1)
+ if (fd == -1) {
cache->vol_initialized(false);
- else
+ } else {
cache->vol_initialized(true);
+ }
return EVENT_DONE;
}
}
@@ -1764,10 +1813,12 @@ cmprtable(const void *aa, const void *bb)
{
rtable_pair *a = (rtable_pair *)aa;
rtable_pair *b = (rtable_pair *)bb;
- if (a->rval < b->rval)
+ if (a->rval < b->rval) {
return -1;
- if (a->rval > b->rval)
+ }
+ if (a->rval > b->rval) {
return 1;
+ }
return 0;
}
@@ -1826,25 +1877,28 @@ build_vol_hash_table(CacheHostRecord *cp)
}
// spread around the excess
int extra = VOL_HASH_TABLE_SIZE - used;
- for (int i = 0; i < extra; i++)
+ for (int i = 0; i < extra; i++) {
forvol[i % num_vols]++;
+ }
// seed random number generator
for (int i = 0; i < num_vols; i++) {
uint64_t x = p[i]->hash_id.fold();
rnd[i] = (unsigned int)x;
}
// initialize table to "empty"
- for (int i = 0; i < VOL_HASH_TABLE_SIZE; i++)
+ for (int i = 0; i < VOL_HASH_TABLE_SIZE; i++) {
ttable[i] = VOL_HASH_EMPTY;
+ }
// generate random numbers proportaion to allocation
rtable_pair *rtable = (rtable_pair *)ats_malloc(sizeof(rtable_pair) * rtable_size);
int rindex = 0;
- for (int i = 0; i < num_vols; i++)
+ for (int i = 0; i < num_vols; i++) {
for (int j = 0; j < (int)rtable_entries[i]; j++) {
rtable[rindex].rval = next_rand(&rnd[i]);
rtable[rindex].idx = i;
rindex++;
}
+ }
ink_assert(rindex == (int)rtable_size);
// sort (rand #, vol $ pairs)
qsort(rtable, rtable_size, sizeof(rtable_pair), cmprtable);
@@ -1854,8 +1908,9 @@ build_vol_hash_table(CacheHostRecord *cp)
int i = 0; // index moving through the random numbers
for (int j = 0; j < VOL_HASH_TABLE_SIZE; j++) {
pos = width / 2 + j * width; // position to select closest to
- while (pos > rtable[i].rval && i < (int)rtable_size - 1)
+ while (pos > rtable[i].rval && i < (int)rtable_size - 1) {
i++;
+ }
ttable[j] = mapping[rtable[i].idx];
gotvol[rtable[i].idx]++;
}
@@ -1863,8 +1918,9 @@ build_vol_hash_table(CacheHostRecord *cp)
Debug("cache_init", "build_vol_hash_table index %d mapped to %d requested %d got %d", i, mapping[i], forvol[i], gotvol[i]);
}
// install new table
- if (nullptr != (old_table = ink_atomic_swap(&(cp->vol_hash_table), ttable)))
+ if (nullptr != (old_table = ink_atomic_swap(&(cp->vol_hash_table), ttable))) {
new_Freer(old_table, CACHE_MEM_FREE_TIMEOUT);
+ }
ats_free(mapping);
ats_free(p);
ats_free(forvol);
@@ -1877,10 +1933,12 @@ build_vol_hash_table(CacheHostRecord *cp)
void
Cache::vol_initialized(bool result)
{
- if (result)
+ if (result) {
ink_atomic_increment(&total_good_nvol, 1);
- if (total_nvol == ink_atomic_increment(&total_initialized_vol, 1) + 1)
+ }
+ if (total_nvol == ink_atomic_increment(&total_initialized_vol, 1) + 1) {
open_done();
+ }
}
/** Set the state of a disk programmatically.
@@ -1902,8 +1960,9 @@ CacheProcessor::mark_storage_offline(CacheDisk *d, ///< Target disk
d->online = false;
- if (!DISK_BAD(d))
+ if (!DISK_BAD(d)) {
SET_DISK_BAD(d);
+ }
for (p = 0; p < gnvol; p++) {
if (d->fd == gvol[p]->fd) {
@@ -1959,8 +2018,9 @@ CacheProcessor::has_online_storage() const
{
CacheDisk **dptr = gdisks;
for (int disk_no = 0; disk_no < gndisks; ++disk_no, ++dptr) {
- if (!DISK_BAD(*dptr) && (*dptr)->online)
+ if (!DISK_BAD(*dptr) && (*dptr)->online) {
return true;
+ }
}
return false;
}
@@ -1969,8 +2029,9 @@ int
AIO_Callback_handler::handle_disk_failure(int /* event ATS_UNUSED */, void *data)
{
/* search for the matching file descriptor */
- if (!CacheProcessor::cache_ready)
+ if (!CacheProcessor::cache_ready) {
return EVENT_DONE;
+ }
int disk_no = 0;
AIOCallback *cb = (AIOCallback *)data;
@@ -2017,10 +2078,11 @@ Cache::open_done()
hosttable = new CacheHostTable(this, scheme);
hosttable->register_config_callback(&hosttable);
- if (hosttable->gen_host_rec.num_cachevols == 0)
+ if (hosttable->gen_host_rec.num_cachevols == 0) {
ready = CACHE_INIT_FAILED;
- else
+ } else {
ready = CACHE_INITIALIZED;
+ }
// TS-3848
if (ready == CACHE_INIT_FAILED && cacheProcessor.waitForCache() >= 2) {
@@ -2076,8 +2138,9 @@ Cache::open(bool clear, bool /* fix ATS_UNUSED */)
total_nvol += vol_no;
}
}
- if (total_nvol == 0)
+ if (total_nvol == 0) {
return open_done();
+ }
cache_read_done = 1;
return 0;
}
@@ -2172,8 +2235,9 @@ upgrade_doc_version(Ptr<IOBufferData> &buf)
n -= sizeofDoc;
// We copy the fragment table iff there is a fragment table and there is only one alternate.
- if (frag_count > 0 && cache_bc::HTTPInfo_v21::marshalled_length(src) > doc->hlen)
+ if (frag_count > 0 && cache_bc::HTTPInfo_v21::marshalled_length(src) > doc->hlen) {
frag_count = 0; // inhibit fragment table insertion.
+ }
while (zret && src < hdr_limit) {
zret = cache_bc::HTTPInfo_v21::copy_and_upgrade_unmarshalled_to_v23(dst, src, n, frag_count, frags);
@@ -2213,14 +2277,16 @@ CacheVC::handleReadDone(int event, Event *e)
ink_assert(this_ethread() == mutex->thread_holding);
Doc *doc = nullptr;
- if (event == AIO_EVENT_DONE)
+ if (event == AIO_EVENT_DONE) {
set_io_not_in_progress();
- else if (is_io_in_progress())
+ } else if (is_io_in_progress()) {
return EVENT_CONT;
+ }
{
MUTEX_TRY_LOCK(lock, vol->mutex, mutex->thread_holding);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
VC_SCHED_LOCK_RETRY();
+ }
if ((!dir_valid(vol, &dir)) || (!io.ok())) {
if (!io.ok()) {
Debug("cache_disk_error", "Read error on disk %s\n \
@@ -2289,13 +2355,15 @@ CacheVC::handleReadDone(int event, Event *e)
// put into ram cache?
if (io.ok() && ((doc->first_key == *read_key) || (doc->key == *read_key) || STORE_COLLISION) && doc->magic == DOC_MAGIC) {
int okay = 1;
- if (!f.doc_from_ram_cache)
+ if (!f.doc_from_ram_cache) {
f.not_from_ram_cache = 1;
+ }
if (cache_config_enable_checksum && doc->checksum != DOC_NO_CHECKSUM) {
// verify that the checksum matches
uint32_t checksum = 0;
- for (char *b = doc->hdr(); b < (char *)doc + doc->len; b++)
+ for (char *b = doc->hdr(); b < (char *)doc + doc->len; b++) {
checksum += *b;
+ }
ink_assert(checksum == doc->checksum);
if (checksum != doc->checksum) {
Note("cache: checksum error for [%" PRIu64 " %" PRIu64 "] len %d, hlen %d, disk %s, offset %" PRIu64 " size %zu",
@@ -2311,8 +2379,9 @@ CacheVC::handleReadDone(int event, Event *e)
cache_config_ram_cache_compress && !f.doc_from_ram_cache && doc->doc_type == CACHE_FRAG_TYPE_HTTP && doc->hlen;
// If http doc we need to unmarshal the headers before putting in the ram cache
// unless it could be compressed
- if (!http_copy_hdr && doc->doc_type == CACHE_FRAG_TYPE_HTTP && doc->hlen && okay)
+ if (!http_copy_hdr && doc->doc_type == CACHE_FRAG_TYPE_HTTP && doc->hlen && okay) {
unmarshal_helper(doc, buf, okay);
+ }
// Put the request in the ram cache only if its a open_read or lookup
if (vio.op == VIO::READ && okay) {
bool cutoff_check;
@@ -2338,8 +2407,9 @@ CacheVC::handleReadDone(int event, Event *e)
}
} // end VIO::READ check
// If it could be compressed, unmarshal after
- if (http_copy_hdr && doc->doc_type == CACHE_FRAG_TYPE_HTTP && doc->hlen && okay)
+ if (http_copy_hdr && doc->doc_type == CACHE_FRAG_TYPE_HTTP && doc->hlen && okay) {
unmarshal_helper(doc, buf, okay);
+ }
} // end io.ok() check
}
Ldone:
@@ -2383,12 +2453,13 @@ CacheVC::handleRead(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
io.aiocb.aio_fildes = vol->fd;
io.aiocb.aio_offset = vol_offset(vol, &dir);
- if ((off_t)(io.aiocb.aio_offset + io.aiocb.aio_nbytes) > (off_t)(vol->skip + vol->len))
+ if ((off_t)(io.aiocb.aio_offset + io.aiocb.aio_nbytes) > (off_t)(vol->skip + vol->len)) {
io.aiocb.aio_nbytes = vol->skip + vol->len - io.aiocb.aio_offset;
- buf = new_IOBufferData(iobuffer_size_to_index(io.aiocb.aio_nbytes, MAX_BUFFER_SIZE_INDEX), MEMALIGNED);
- io.aiocb.aio_buf = buf->data();
- io.action = this;
- io.thread = mutex->thread_holding->tt == DEDICATED ? AIO_CALLBACK_THREAD_ANY : mutex->thread_holding;
+ }
+ buf = new_IOBufferData(iobuffer_size_to_index(io.aiocb.aio_nbytes, MAX_BUFFER_SIZE_INDEX), MEMALIGNED);
+ io.aiocb.aio_buf = buf->data();
+ io.action = this;
+ io.thread = mutex->thread_holding->tt == DEDICATED ? AIO_CALLBACK_THREAD_ANY : mutex->thread_holding;
SET_HANDLER(&CacheVC::handleReadDone);
ink_assert(ink_aio_read(&io) >= 0);
CACHE_DEBUG_INCREMENT_DYN_STAT(cache_pread_count_stat);
@@ -2431,10 +2502,11 @@ Cache::lookup(Continuation *cont, const CacheKey *key, CacheFragType type, const
c->vol = vol;
c->last_collision = nullptr;
- if (c->handleEvent(EVENT_INTERVAL, nullptr) == EVENT_CONT)
+ if (c->handleEvent(EVENT_INTERVAL, nullptr) == EVENT_CONT) {
return &c->_action;
- else
+ } else {
return ACTION_RESULT_DONE;
+ }
}
int
@@ -2444,8 +2516,9 @@ CacheVC::removeEvent(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
set_io_not_in_progress();
{
MUTEX_TRY_LOCK(lock, vol->mutex, mutex->thread_holding);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
VC_SCHED_LOCK_RETRY();
+ }
if (_action.cancelled) {
if (od) {
vol->close_write(this);
@@ -2467,15 +2540,17 @@ CacheVC::removeEvent(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
}
Lread:
SET_HANDLER(&CacheVC::removeEvent);
- if (!buf)
+ if (!buf) {
goto Lcollision;
+ }
if (!dir_valid(vol, &dir)) {
last_collision = nullptr;
goto Lcollision;
}
// check read completed correct FIXME: remove bad vols
- if ((size_t)io.aio_result != (size_t)io.aiocb.aio_nbytes)
+ if ((size_t)io.aio_result != (size_t)io.aiocb.aio_nbytes) {
goto Ldone;
+ }
{
// verify that this is our document
Doc *doc = (Doc *)buf->data();
@@ -2483,8 +2558,9 @@ CacheVC::removeEvent(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
if (doc->first_key == key) {
ink_assert(doc->magic == DOC_MAGIC);
if (dir_delete(&key, vol, &dir) > 0) {
- if (od)
+ if (od) {
vol->close_write(this);
+ }
od = nullptr;
goto Lremoved;
}
@@ -2495,14 +2571,16 @@ CacheVC::removeEvent(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
// check for collision
if (dir_probe(&key, vol, &dir, &last_collision) > 0) {
int ret = do_read_call(&key);
- if (ret == EVENT_RETURN)
+ if (ret == EVENT_RETURN) {
goto Lread;
+ }
return ret;
}
Ldone:
CACHE_INCREMENT_DYN_STAT(cache_remove_failure_stat);
- if (od)
+ if (od) {
vol->close_write(this);
+ }
}
ink_assert(!vol || this_ethread() != vol->mutex->thread_holding);
_action.continuation->handleEvent(CACHE_EVENT_REMOVE_FAILED, (void *)-ECACHE_NO_DOC);
@@ -2517,14 +2595,16 @@ Action *
Cache::remove(Continuation *cont, const CacheKey *key, CacheFragType type, const char *hostname, int host_len)
{
if (!CacheProcessor::IsCacheReady(type)) {
- if (cont)
+ if (cont) {
cont->handleEvent(CACHE_EVENT_REMOVE_FAILED, nullptr);
+ }
return ACTION_RESULT_DONE;
}
Ptr<ProxyMutex> mutex;
- if (!cont)
+ if (!cont) {
cont = new_CacheRemoveCont();
+ }
CACHE_TRY_LOCK(lock, cont->mutex, this_ethread());
ink_assert(lock.is_locked());
@@ -2546,10 +2626,11 @@ Cache::remove(Continuation *cont, const CacheKey *key, CacheFragType type, const
SET_CONTINUATION_HANDLER(c, &CacheVC::removeEvent);
int ret = c->removeEvent(EVENT_IMMEDIATE, nullptr);
- if (ret == EVENT_DONE)
+ if (ret == EVENT_DONE) {
return ACTION_RESULT_DONE;
- else
+ } else {
return &c->_action;
+ }
}
// CacheVConnection
@@ -2637,8 +2718,9 @@ cplist_update()
// Delete hte volume from the cache vol list
int d_no;
for (d_no = 0; d_no < gndisks; d_no++) {
- if (cp->disk_vols[d_no])
+ if (cp->disk_vols[d_no]) {
cp->disk_vols[d_no]->disk->delete_volume(cp->vol_number);
+ }
}
CacheVol *temp_cp = cp;
cp = cp->link.next;
@@ -2646,8 +2728,9 @@ cplist_update()
cp_list_len--;
delete temp_cp;
continue;
- } else
+ } else {
cp = cp->link.next;
+ }
}
}
@@ -2754,8 +2837,9 @@ cplist_reconfigure()
off_t blocks_per_vol = VOL_BLOCK_SIZE / STORE_BLOCK_SIZE;
/* sum up the total space available on all the disks.
round down the space to 128 megabytes */
- for (int i = 0; i < gndisks; i++)
+ for (int i = 0; i < gndisks; i++) {
tot_space_in_blks += (gdisks[i]->num_usable_blocks / blocks_per_vol) * blocks_per_vol;
+ }
double percent_remaining = 100.00;
for (config_vol = config_volumes.cp_queue.head; config_vol; config_vol = config_vol->link.next) {
@@ -2794,8 +2878,9 @@ cplist_reconfigure()
for (config_vol = config_volumes.cp_queue.head; config_vol; config_vol = config_vol->link.next) {
size = config_vol->size;
- if (size < 128)
+ if (size < 128) {
continue;
+ }
volume_number = config_vol->number;
@@ -2833,8 +2918,9 @@ cplist_reconfigure()
/* search the cp_list */
int *sorted_vols = new int[gndisks];
- for (int i = 0; i < gndisks; i++)
+ for (int i = 0; i < gndisks; i++) {
sorted_vols[i] = i;
+ }
for (int i = 0; i < gndisks - 1; i++) {
int smallest = sorted_vols[i];
int smallest_ndx = i;
@@ -2873,8 +2959,9 @@ cplist_reconfigure()
size_diff = (size_diff < size_to_alloc) ? size_diff : size_to_alloc;
/* if size_diff == 0, then then the disks have volumes of the
same sizes, so we don't need to balance the disks */
- if (size_diff == 0)
+ if (size_diff == 0) {
break;
+ }
DiskVolBlock *dpb;
do {
@@ -2886,12 +2973,14 @@ cplist_reconfigure()
size_diff -= dpb->len;
cp->size += dpb->len;
cp->num_vols++;
- } else
+ } else {
break;
+ }
} while ((size_diff > 0));
- if (!dpb)
+ if (!dpb) {
disk_full++;
+ }
size_to_alloc = size_in_blocks - cp->size;
}
@@ -2899,8 +2988,9 @@ cplist_reconfigure()
delete[] sorted_vols;
if (size_to_alloc) {
- if (create_volume(volume_number, size_to_alloc, cp->scheme, cp))
+ if (create_volume(volume_number, size_to_alloc, cp->scheme, cp)) {
return -1;
+ }
}
gnvol += cp->num_vols;
}
@@ -2938,12 +3028,13 @@ create_volume(int volume_number, off_t size_in_blocks, int scheme, CacheVol *cp)
if (full_disks == gndisks) {
char config_file[PATH_NAME_MAX];
REC_ReadConfigString(config_file, "proxy.config.cache.volume_filename", PATH_NAME_MAX);
- if (cp->size)
+ if (cp->size) {
Warning("not enough space to increase volume: [%d] to size: [%" PRId64 "]", volume_number,
(int64_t)((to_create + cp->size) >> (20 - STORE_BLOCK_SHIFT)));
- else
+ } else {
Warning("not enough space to create volume: [%d], size: [%" PRId64 "]", volume_number,
(int64_t)(to_create >> (20 - STORE_BLOCK_SHIFT)));
+ }
Note("edit the %s file and restart traffic_server", config_file);
delete[] sp;
@@ -2964,8 +3055,9 @@ create_volume(int volume_number, off_t size_in_blocks, int scheme, CacheVol *cp)
cp->num_vols++;
cp->size += p->len;
}
- if (!cp->disk_vols[i])
+ if (!cp->disk_vols[i]) {
cp->disk_vols[i] = gdisks[i]->get_diskvol(volume_number);
+ }
}
}
delete[] sp;
@@ -3017,8 +3109,9 @@ Cache::key_to_vol(const CacheKey *key, const char *hostname, int host_len)
Debug("cache_hosting", format_str, host_rec, hostname);
}
return host_rec->vols[hash_table[h]];
- } else
+ } else {
return host_rec->vols[0];
+ }
}
static void
@@ -3146,8 +3239,9 @@ ink_cache_init(ModuleVersion v)
REC_EstablishStaticConfigInt32(cache_config_force_sector_size, "proxy.config.cache.force_sector_size");
REC_EstablishStaticConfigInt32(cache_config_target_fragment_size, "proxy.config.cache.target_fragment_size");
- if (cache_config_target_fragment_size == 0)
+ if (cache_config_target_fragment_size == 0) {
cache_config_target_fragment_size = DEFAULT_TARGET_FRAGMENT_SIZE;
+ }
REC_EstablishStaticConfigInt32(enable_cache_empty_http_doc, "proxy.config.http.cache.allow_empty_doc");
@@ -3210,12 +3304,14 @@ CacheProcessor::find_by_path(const char *path, int len)
{
if (CACHE_INITIALIZED == initialized) {
// If no length is passed in, assume it's null terminated.
- if (0 >= len && 0 != *path)
+ if (0 >= len && 0 != *path) {
len = strlen(path);
+ }
for (int i = 0; i < gndisks; ++i) {
- if (0 == strncmp(path, gdisks[i]->path, len))
+ if (0 == strncmp(path, gdisks[i]->path, len)) {
return gdisks[i];
+ }
}
}
@@ -3258,8 +3354,9 @@ HTTPInfo_v21::copy_and_upgrade_unmarshalled_to_v23(char *&dst, char *&src, size_
HdrHeap_v23 *d_hdr;
size_t hdr_size;
- if (length < HTTP_ALT_MARSHAL_SIZE)
+ if (length < HTTP_ALT_MARSHAL_SIZE) {
return false; // Absolutely no hope in this case.
+ }
memcpy(dst, src, OLD_OFFSET); // initially same data
// Now data that's now after extra
@@ -3272,8 +3369,9 @@ HTTPInfo_v21::copy_and_upgrade_unmarshalled_to_v23(char *&dst, char *&src, size_
static size_t const IFT_SIZE = HTTPCacheAlt_v23::N_INTEGRAL_FRAG_OFFSETS * sizeof(FragOffset);
size_t ift_actual = min(n_frags, HTTPCacheAlt_v23::N_INTEGRAL_FRAG_OFFSETS) * sizeof(FragOffset);
- if (length < (HTTP_ALT_MARSHAL_SIZE + n_frags * sizeof(FragOffset) - IFT_SIZE))
+ if (length < (HTTP_ALT_MARSHAL_SIZE + n_frags * sizeof(FragOffset) - IFT_SIZE)) {
return false; // can't place fragment table.
+ }
d_alt->m_frag_offset_count = n_frags;
d_alt->m_frag_offsets = reinterpret_cast<FragOffset *>(dst - reinterpret_cast<char *>(d_alt));
@@ -3299,8 +3397,9 @@ HTTPInfo_v21::copy_and_upgrade_unmarshalled_to_v23(char *&dst, char *&src, size_
reinterpret_cast<HdrHeap_v23 *>(reinterpret_cast<char *>(s_alt) + reinterpret_cast<uintptr_t>(s_alt->m_request_hdr.m_heap));
d_hdr = reinterpret_cast<HdrHeap_v23 *>(dst);
hdr_size = ROUND(s_hdr->unmarshal_size(), HDR_PTR_SIZE);
- if (hdr_size > length)
+ if (hdr_size > length) {
return false;
+ }
memcpy(d_hdr, s_hdr, hdr_size);
d_alt->m_request_hdr.m_heap = reinterpret_cast<HdrHeap_v23 *>(reinterpret_cast<char *>(d_hdr) - reinterpret_cast<char *>(d_alt));
dst += hdr_size;
@@ -3310,8 +3409,9 @@ HTTPInfo_v21::copy_and_upgrade_unmarshalled_to_v23(char *&dst, char *&src, size_
reinterpret_cast<HdrHeap_v23 *>(reinterpret_cast<char *>(s_alt) + reinterpret_cast<uintptr_t>(s_alt->m_response_hdr.m_heap));
d_hdr = reinterpret_cast<HdrHeap_v23 *>(dst);
hdr_size = ROUND(s_hdr->unmarshal_size(), HDR_PTR_SIZE);
- if (hdr_size > length)
+ if (hdr_size > length) {
return false;
+ }
memcpy(d_hdr, s_hdr, hdr_size);
d_alt->m_response_hdr.m_heap = reinterpret_cast<HdrHeap_v23 *>(reinterpret_cast<char *>(d_hdr) - reinterpret_cast<char *>(d_alt));
dst += hdr_size;
diff --git a/iocore/cache/CacheDir.cc b/iocore/cache/CacheDir.cc
index bad2f9d..2616d81 100644
--- a/iocore/cache/CacheDir.cc
+++ b/iocore/cache/CacheDir.cc
@@ -76,8 +76,9 @@ OpenDir::open_write(CacheVC *cont, int allow_if_writers, int max_writers)
unsigned int h = cont->first_key.slice32(0);
int b = h % OPEN_DIR_BUCKETS;
for (OpenDirEntry *d = bucket[b].head; d; d = d->link.next) {
- if (!(d->writers.head->first_key == cont->first_key))
+ if (!(d->writers.head->first_key == cont->first_key)) {
continue;
+ }
if (allow_if_writers && d->num_writers < d->max_writers) {
d->writers.push(cont);
d->num_writers++;
@@ -122,8 +123,9 @@ OpenDir::signal_readers(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
if (newly_delayed_readers.head) {
delayed_readers = newly_delayed_readers;
EThread *t1 = newly_delayed_readers.head->mutex->thread_holding;
- if (!t1)
+ if (!t1) {
t1 = mutex->thread_holding;
+ }
t1->schedule_in(this, HRTIME_MSECONDS(cache_config_mutex_retry_delay));
}
return 0;
@@ -153,9 +155,11 @@ OpenDir::open_read(const CryptoHash *key)
{
unsigned int h = key->slice32(0);
int b = h % OPEN_DIR_BUCKETS;
- for (OpenDirEntry *d = bucket[b].head; d; d = d->link.next)
- if (d->writers.head->first_key == *key)
+ for (OpenDirEntry *d = bucket[b].head; d; d = d->link.next) {
+ if (d->writers.head->first_key == *key) {
return d;
+ }
+ }
return nullptr;
}
@@ -179,8 +183,9 @@ OpenDirEntry::wait(CacheVC *cont, int msec)
int
dir_bucket_loop_check(Dir *start_dir, Dir *seg)
{
- if (start_dir == nullptr)
+ if (start_dir == nullptr) {
return 1;
+ }
Dir *p1 = start_dir;
Dir *p2 = start_dir;
@@ -191,13 +196,15 @@ dir_bucket_loop_check(Dir *start_dir, Dir *seg)
p1 = next_dir(p1, seg);
// p2 moves by two entries per iteration
p2 = next_dir(p2, seg);
- if (p2)
+ if (p2) {
p2 = next_dir(p2, seg);
- else
+ } else {
return 1;
+ }
- if (p2 == p1)
+ if (p2 == p1) {
return 0; // we have a loop
+ }
}
return 1;
}
@@ -238,8 +245,9 @@ dir_freelist_length(Vol *d, int s)
int free = 0;
Dir *seg = dir_segment(s, d);
Dir *e = dir_from_offset(d->header->freelist[s], seg);
- if (dir_bucket_loop_fix(e, s, d))
+ if (dir_bucket_loop_fix(e, s, d)) {
return (DIR_DEPTH - 1) * d->buckets;
+ }
while (e) {
free++;
e = next_dir(e, seg);
@@ -259,8 +267,9 @@ dir_bucket_length(Dir *b, int s, Vol *d)
#endif
while (e) {
i++;
- if (i > 100)
+ if (i > 100) {
return -1;
+ }
e = next_dir(e, seg);
}
return i;
@@ -275,12 +284,15 @@ check_dir(Vol *d)
Dir *seg = dir_segment(s, d);
for (i = 0; i < d->buckets; i++) {
Dir *b = dir_bucket(i, seg);
- if (!(dir_bucket_length(b, s, d) >= 0))
+ if (!(dir_bucket_length(b, s, d) >= 0)) {
return 0;
- if (!(!dir_next(b) || dir_offset(b)))
+ }
+ if (!(!dir_next(b) || dir_offset(b))) {
return 0;
- if (!(dir_bucket_loop_check(b, seg)))
+ }
+ if (!(dir_bucket_loop_check(b, seg))) {
return 0;
+ }
}
}
return 1;
@@ -291,13 +303,15 @@ unlink_from_freelist(Dir *e, int s, Vol *d)
{
Dir *seg = dir_segment(s, d);
Dir *p = dir_from_offset(dir_prev(e), seg);
- if (p)
+ if (p) {
dir_set_next(p, dir_next(e));
- else
+ } else {
d->header->freelist[s] = dir_next(e);
- Dir *n = dir_from_offset(dir_next(e), seg);
- if (n)
+ }
+ Dir *n = dir_from_offset(dir_next(e), seg);
+ if (n) {
dir_set_prev(n, dir_prev(e));
+ }
}
inline Dir *
@@ -312,8 +326,9 @@ dir_delete_entry(Dir *e, Dir *p, int s, Vol *d)
dir_clear(e);
dir_set_next(p, no);
dir_set_next(e, fo);
- if (fo)
+ if (fo) {
dir_set_prev(dir_from_offset(fo, seg), eo);
+ }
d->header->freelist[s] = eo;
} else {
Dir *n = next_dir(e, seg);
@@ -346,11 +361,13 @@ dir_clean_bucket(Dir *b, int s, Vol *vol)
}
#endif
if (!dir_valid(vol, e) || !dir_offset(e)) {
- if (is_debug_tag_set("dir_clean"))
+ if (is_debug_tag_set("dir_clean")) {
Debug("dir_clean", "cleaning %p tag %X boffset %" PRId64 " b %p p %p l %d", e, dir_tag(e), dir_offset(e), b, p,
dir_bucket_length(b, s, vol));
- if (dir_offset(e))
+ }
+ if (dir_offset(e)) {
CACHE_DEC_DIR_USED(vol->mutex);
+ }
e = dir_delete_entry(e, p, s, vol);
continue;
}
@@ -372,8 +389,9 @@ dir_clean_segment(int s, Vol *d)
void
dir_clean_vol(Vol *d)
{
- for (int64_t i = 0; i < d->segments; i++)
+ for (int64_t i = 0; i < d->segments; i++) {
dir_clean_segment(i, d);
+ }
CHECK_DIR(d);
}
@@ -395,8 +413,9 @@ check_bucket_not_contains(Dir *b, Dir *e, Dir *seg)
{
Dir *x = b;
do {
- if (x == e)
+ if (x == e) {
break;
+ }
x = next_dir(x, seg);
} while (x);
ink_assert(!x);
@@ -406,8 +425,9 @@ void
freelist_clean(int s, Vol *vol)
{
dir_clean_segment(s, vol);
- if (vol->header->freelist[s])
+ if (vol->header->freelist[s]) {
return;
+ }
Warning("cache directory overflow on '%s' segment %d, purging...", vol->path, s);
int n = 0;
Dir *seg = dir_segment(s, vol);
@@ -440,8 +460,9 @@ freelist_pop(int s, Vol *d)
return nullptr;
}
Dir *h = dir_from_offset(d->header->freelist[s], seg);
- if (h)
+ if (h) {
dir_set_prev(h, 0);
+ }
return e;
}
@@ -462,29 +483,38 @@ dir_segment_accounted(int s, Vol *d, int offby, int *f, int *u, int *et, int *v,
empty++;
} else {
used++;
- if (dir_valid(d, e))
+ if (dir_valid(d, e)) {
valid++;
- if (dir_agg_valid(d, e))
+ }
+ if (dir_agg_valid(d, e)) {
agg_valid++;
+ }
agg_size += dir_approx_size(e);
}
e = next_dir(e, seg);
- if (!e)
+ if (!e) {
break;
+ }
}
}
- if (f)
+ if (f) {
*f = free;
- if (u)
+ }
+ if (u) {
*u = used;
- if (et)
+ }
+ if (et) {
*et = empty;
- if (v)
+ }
+ if (v) {
*v = valid;
- if (av)
+ }
+ if (av) {
*av = agg_valid;
- if (as)
+ }
+ if (as) {
*as = used ? (int)(agg_size / used) : 0;
+ }
ink_assert(d->buckets * DIR_DEPTH - (free + used + empty) <= offby);
return d->buckets * DIR_DEPTH - (free + used + empty) <= offby;
}
@@ -496,8 +526,9 @@ dir_free_entry(Dir *e, int s, Vol *d)
unsigned int fo = d->header->freelist[s];
unsigned int eo = dir_to_offset(e, seg);
dir_set_next(e, fo);
- if (fo)
+ if (fo) {
dir_set_prev(dir_from_offset(fo, seg), eo);
+ }
d->header->freelist[s] = eo;
}
@@ -517,7 +548,7 @@ dir_probe(const CacheKey *key, Vol *d, Dir *result, Dir **last_collision)
#endif
Lagain:
e = dir_bucket(b, seg);
- if (dir_offset(e))
+ if (dir_offset(e)) {
do {
if (dir_compare_tag(e, key)) {
ink_assert(dir_offset(e));
@@ -556,6 +587,7 @@ Lagain:
p = e;
e = next_dir(e, seg);
} while (e);
+ }
if (collision) { // last collision no longer in the list, retry
DDebug("cache_stats", "Incrementing dir collisions");
CACHE_INC_DIR_COLLISIONS(d->mutex);
@@ -591,8 +623,9 @@ dir_insert(const CacheKey *key, Vol *d, Dir *to_part)
Lagain:
// get from this row first
e = b;
- if (dir_is_empty(e))
+ if (dir_is_empty(e)) {
goto Lfill;
+ }
for (l = 1; l < DIR_DEPTH; l++) {
e = dir_bucket_row(b, l);
if (dir_is_empty(e)) {
@@ -602,8 +635,9 @@ Lagain:
}
// get one from the freelist
e = freelist_pop(s, d);
- if (!e)
+ if (!e) {
goto Lagain;
+ }
Llink:
dir_set_next(e, dir_next(b));
dir_set_next(b, dir_to_offset(e, seg));
@@ -641,7 +675,7 @@ dir_overwrite(const CacheKey *key, Vol *d, Dir *dir, Dir *overwrite, bool must_o
Lagain:
// find entry to overwrite
e = b;
- if (dir_offset(e))
+ if (dir_offset(e)) {
do {
#ifdef LOOP_CHECK_MODE
loop_count++;
@@ -652,12 +686,15 @@ Lagain:
}
}
#endif
- if (dir_tag(e) == t && dir_offset(e) == dir_offset(overwrite))
+ if (dir_tag(e) == t && dir_offset(e) == dir_offset(overwrite)) {
goto Lfill;
+ }
e = next_dir(e, seg);
} while (e);
- if (must_overwrite)
+ }
+ if (must_overwrite) {
return 0;
+ }
res = 0;
// get from this row first
e = b;
@@ -674,8 +711,9 @@ Lagain:
}
// get one from the freelist
e = freelist_pop(s, d);
- if (!e)
+ if (!e) {
goto Lagain;
+ }
Llink:
CACHE_INC_DIR_USED(d->mutex);
dir_set_next(e, dir_next(b));
@@ -706,7 +744,7 @@ dir_delete(const CacheKey *key, Vol *d, Dir *del)
CHECK_DIR(d);
e = dir_bucket(b, seg);
- if (dir_offset(e))
+ if (dir_offset(e)) {
do {
#ifdef LOOP_CHECK_MODE
loop_count++;
@@ -724,6 +762,7 @@ dir_delete(const CacheKey *key, Vol *d, Dir *del)
p = e;
e = next_dir(e, seg);
} while (e);
+ }
CHECK_DIR(d);
return 0;
}
@@ -741,8 +780,9 @@ dir_lookaside_probe(const CacheKey *key, Vol *d, Dir *result, EvacuationBlock **
if (dir_valid(d, &b->new_dir)) {
*result = b->new_dir;
DDebug("dir_lookaside", "probe %X success", key->slice32(0));
- if (eblock)
+ if (eblock) {
*eblock = b;
+ }
return 1;
}
}
@@ -874,11 +914,13 @@ dir_entries_used(Vol *d)
break;
}
while (e) {
- if (dir_offset(e))
+ if (dir_offset(e)) {
sfull++;
+ }
e = next_dir(e, seg);
- if (!e)
+ if (!e) {
break;
+ }
}
}
}
@@ -943,10 +985,11 @@ sync_cache_dir_on_shutdown()
if (buflen < dirlen) {
if (buf) {
- if (buf_huge)
+ if (buf_huge) {
ats_free_hugepage(buf, buflen);
- else
+ } else {
ats_memalign_free(buf);
+ }
buf = nullptr;
}
buflen = dirlen;
@@ -977,10 +1020,11 @@ sync_cache_dir_on_shutdown()
}
Debug("cache_dir_sync", "sync done");
if (buf) {
- if (buf_huge)
+ if (buf_huge) {
ats_free_hugepage(buf, buflen);
- else
+ } else {
ats_memalign_free(buf);
+ }
buf = nullptr;
}
}
@@ -997,19 +1041,21 @@ Lrestart:
if (vol_idx >= gnvol) {
vol_idx = 0;
if (buf) {
- if (buf_huge)
+ if (buf_huge) {
ats_free_hugepage(buf, buflen);
- else
+ } else {
ats_memalign_free(buf);
+ }
buflen = 0;
buf = nullptr;
buf_huge = false;
}
Debug("cache_dir_sync", "sync done");
- if (event == EVENT_INTERVAL)
+ if (event == EVENT_INTERVAL) {
trigger = e->ethread->schedule_in(this, HRTIME_SECONDS(cache_config_dir_sync_frequency));
- else
+ } else {
trigger = eventProcessor.schedule_in(this, HRTIME_SECONDS(cache_config_dir_sync_frequency));
+ }
return EVENT_CONT;
}
@@ -1034,14 +1080,16 @@ Lrestart:
return EVENT_CONT;
}
- if (!vol->dir_sync_in_progress)
+ if (!vol->dir_sync_in_progress) {
start_time = Thread::get_hrtime();
+ }
// recompute hit_evacuate_window
vol->hit_evacuate_window = (vol->data_blocks * cache_config_hit_evacuate_percent) / 100;
- if (DISK_BAD(vol->disk))
+ if (DISK_BAD(vol->disk)) {
goto Ldone;
+ }
int headerlen = ROUND_TO_STORE_BLOCK(sizeof(VolHeaderFooter));
size_t dirlen = vol_dirlen(vol);
@@ -1061,18 +1109,20 @@ Lrestart:
if (vol->is_io_in_progress() || vol->agg_buf_pos) {
Debug("cache_dir_sync", "Dir %s: waiting for agg buffer", vol->hash_text.get());
vol->dir_sync_waiting = true;
- if (!vol->is_io_in_progress())
+ if (!vol->is_io_in_progress()) {
vol->aggWrite(EVENT_IMMEDIATE, nullptr);
+ }
return EVENT_CONT;
}
Debug("cache_dir_sync", "pos: %" PRIu64 " Dir %s dirty...syncing to disk", vol->header->write_pos, vol->hash_text.get());
vol->header->dirty = 0;
if (buflen < dirlen) {
if (buf) {
- if (buf_huge)
+ if (buf_huge) {
ats_free_hugepage(buf, buflen);
- else
+ } else {
ats_memalign_free(buf);
+ }
buf = nullptr;
}
buflen = dirlen;
@@ -1101,8 +1151,9 @@ Lrestart:
} else if (writepos < (off_t)dirlen - headerlen) {
// write part of body
int l = SYNC_MAX_WRITE;
- if (writepos + l > (off_t)dirlen - headerlen)
+ if (writepos + l > (off_t)dirlen - headerlen) {
l = dirlen - headerlen - writepos;
+ }
aio_write(vol->fd, buf + writepos, l, start + writepos);
writepos += l;
} else if (writepos < (off_t)dirlen) {
@@ -1208,16 +1259,18 @@ int Vol::dir_check(bool /* fix ATS_UNUSED */) // TODO: we should eliminate this
++seg_stale;
} else {
uint64_t size = dir_approx_size(e);
- if (dir_head(e))
+ if (dir_head(e)) {
++head;
+ }
++seg_in_use;
seg_bytes_in_use += size;
++frag_demographics[dir_size(e)][dir_big(e)];
}
}
e = next_dir(e, seg);
- if (!e)
+ if (!e) {
break;
+ }
}
// Check for duplicates (identical tags in the same bucket).
@@ -1226,8 +1279,9 @@ int Vol::dir_check(bool /* fix ATS_UNUSED */) // TODO: we should eliminate this
qsort(chain_tag, h, sizeof(chain_tag[0]), &compare_ushort);
last = chain_tag[0];
for (int k = 1; k < h; ++k) {
- if (last == chain_tag[k])
+ if (last == chain_tag[k]) {
++seg_dups;
+ }
last = chain_tag[k];
}
}
@@ -1253,8 +1307,9 @@ int Vol::dir_check(bool /* fix ATS_UNUSED */) // TODO: we should eliminate this
max_chain_length, buckets_in_use ? static_cast<float>(in_use + stale) / buckets_in_use : 0);
printf(" Chain lengths: ");
- for (j = 0; j < SEGMENT_HISTOGRAM_WIDTH; ++j)
+ for (j = 0; j < SEGMENT_HISTOGRAM_WIDTH; ++j) {
printf(" %d=%d ", j, hist[j]);
+ }
printf(" %d>=%d\n", SEGMENT_HISTOGRAM_WIDTH, hist[SEGMENT_HISTOGRAM_WIDTH]);
char tt[256];
@@ -1340,8 +1395,9 @@ static void
regress_rand_CacheKey(const CacheKey *key)
{
unsigned int *x = (unsigned int *)key;
- for (int i = 0; i < 4; i++)
- x[i] = next_rand(®ress_rand_seed);
+ for (int i = 0; i < 4; i++) {
+ x[i] = next_rand(®ress_rand_seed);
+ }
}
void
@@ -1398,24 +1454,29 @@ EXCLUSIVE_REGRESSION_TEST(Cache_dir)(RegressionTest *t, int /* atype ATS_UNUSED
int n = free;
rprintf(t, "free: %d\n", free);
while (n--) {
- if (!dir_insert(&key, d, &dir))
+ if (!dir_insert(&key, d, &dir)) {
break;
+ }
inserted++;
}
rprintf(t, "inserted: %d\n", inserted);
- if ((unsigned int)(inserted - free) > 1)
+ if ((unsigned int)(inserted - free) > 1) {
ret = REGRESSION_TEST_FAILED;
+ }
// test delete
rprintf(t, "delete test\n");
- for (i = 0; i < d->buckets; i++)
- for (j = 0; j < DIR_DEPTH; j++)
+ for (i = 0; i < d->buckets; i++) {
+ for (j = 0; j < DIR_DEPTH; j++) {
dir_set_offset(dir_bucket_row(dir_bucket(i, seg), j), 0); // delete
+ }
+ }
dir_clean_segment(s, d);
int newfree = dir_freelist_length(d, s);
rprintf(t, "newfree: %d\n", newfree);
- if ((unsigned int)(newfree - free) > 1)
+ if ((unsigned int)(newfree - free) > 1) {
ret = REGRESSION_TEST_FAILED;
+ }
// test insert-delete
rprintf(t, "insert-delete test\n");
@@ -1428,21 +1489,24 @@ EXCLUSIVE_REGRESSION_TEST(Cache_dir)(RegressionTest *t, int /* atype ATS_UNUSED
uint64_t us = (Thread::get_hrtime_updated() - ttime) / HRTIME_USECOND;
// On windows us is sometimes 0. I don't know why.
// printout the insert rate only if its not 0
- if (us)
+ if (us) {
rprintf(t, "insert rate = %d / second\n", (int)((newfree * (uint64_t)1000000) / us));
+ }
regress_rand_init(13);
ttime = Thread::get_hrtime_updated();
for (i = 0; i < newfree; i++) {
Dir *last_collision = nullptr;
regress_rand_CacheKey(&key);
- if (!dir_probe(&key, d, &dir, &last_collision))
+ if (!dir_probe(&key, d, &dir, &last_collision)) {
ret = REGRESSION_TEST_FAILED;
+ }
}
us = (Thread::get_hrtime_updated() - ttime) / HRTIME_USECOND;
// On windows us is sometimes 0. I don't know why.
// printout the probe rate only if its not 0
- if (us)
+ if (us) {
rprintf(t, "probe rate = %d / second\n", (int)((newfree * (uint64_t)1000000) / us));
+ }
for (int c = 0; c < vol_direntries(d) * 0.75; c++) {
regress_rand_CacheKey(&key);
@@ -1523,8 +1587,9 @@ EXCLUSIVE_REGRESSION_TEST(Cache_dir)(RegressionTest *t, int /* atype ATS_UNUSED
dir_insert(&key, d, &dir1);
dir_insert(&key, d, &dir1);
dir_corrupt_bucket(dir_bucket(b1, dir_segment(s1, d)), s1, d);
- if (check_dir(d))
+ if (check_dir(d)) {
ret = REGRESSION_TEST_FAILED;
+ }
#endif
}
vol_dir_clear(d);
diff --git a/iocore/cache/CacheDisk.cc b/iocore/cache/CacheDisk.cc
index 551301d..45432f0 100644
--- a/iocore/cache/CacheDisk.cc
+++ b/iocore/cache/CacheDisk.cc
@@ -245,14 +245,16 @@ CacheDisk::syncDone(int event, void * /* data ATS_UNUSED */)
DiskVolBlock *
CacheDisk::create_volume(int number, off_t size_in_blocks, int scheme)
{
- if (size_in_blocks == 0)
+ if (size_in_blocks == 0) {
return nullptr;
+ }
DiskVolBlockQueue *q = free_blocks->dpb_queue.head;
DiskVolBlockQueue *closest_match = q;
- if (!q)
+ if (!q) {
return nullptr;
+ }
off_t max_blocks = MAX_VOL_SIZE >> STORE_BLOCK_SHIFT;
size_in_blocks = (size_in_blocks <= max_blocks) ? size_in_blocks : max_blocks;
@@ -266,8 +268,9 @@ CacheDisk::create_volume(int number, off_t size_in_blocks, int scheme)
q->new_block = 1;
break;
} else {
- if (closest_match->b->len < q->b->len)
+ if (closest_match->b->len < q->b->len) {
closest_match = q;
+ }
}
}
@@ -301,8 +304,9 @@ CacheDisk::create_volume(int number, off_t size_in_blocks, int scheme)
free_blocks->size += dpb->len;
free_space += dpb->len;
header->num_diskvol_blks++;
- } else
+ } else {
header->num_free--;
+ }
p->len = size_in_blocks;
p->free = 0;
diff --git a/iocore/cache/CacheHosting.cc b/iocore/cache/CacheHosting.cc
index 24f102e..0ccc4bf 100644
--- a/iocore/cache/CacheHosting.cc
+++ b/iocore/cache/CacheHosting.cc
@@ -106,8 +106,9 @@ CacheHostMatcher::Match(const char *rdata, int rlen, CacheHostResult *result)
return;
}
- if (rlen == 0)
+ if (rlen == 0) {
return;
+ }
char *data = (char *)ats_malloc(rlen + 1);
memcpy(data, rdata, rlen);
*(data + rlen) = '\0';
@@ -153,8 +154,9 @@ CacheHostMatcher::NewEntry(matcher_line *line_info)
ink_assert(match_data != nullptr);
// Remove our consumed label from the parsed line
- if (line_info->dest_entry < MATCHER_MAX_TOKENS)
+ if (line_info->dest_entry < MATCHER_MAX_TOKENS) {
line_info->line[0][line_info->dest_entry] = nullptr;
+ }
line_info->num_el--;
// Fill in the parameter info
@@ -261,8 +263,9 @@ CacheHostTable::BuildTableFromString(const char *config_file_path, char *file_bu
// We have an empty file
/* no hosting customers -- put all the volumes in the
generic table */
- if (gen_host_rec.Init(type))
+ if (gen_host_rec.Init(type)) {
Warning("Problems encountered while initializing the Generic Volume");
+ }
return 0;
}
// First get the number of entries
@@ -342,16 +345,18 @@ CacheHostTable::BuildTableFromString(const char *config_file_path, char *file_bu
ink_assert(current->dest_entry < MATCHER_MAX_TOKENS);
// Remove our consumed label from the parsed line
- if (current->dest_entry < MATCHER_MAX_TOKENS)
+ if (current->dest_entry < MATCHER_MAX_TOKENS) {
current->line[0][current->dest_entry] = nullptr;
- else
+ } else {
Warning("Problems encountered while initializing the Generic Volume");
+ }
current->num_el--;
- if (!gen_host_rec.Init(current, type))
+ if (!gen_host_rec.Init(current, type)) {
generic_rec_initd = 1;
- else
+ } else {
Warning("Problems encountered while initializing the Generic Volume");
+ }
} else {
hostMatch->NewEntry(current);
@@ -452,8 +457,9 @@ CacheHostRecord::Init(matcher_line *line_info, CacheType typ)
type = typ;
for (i = 0; i < MATCHER_MAX_TOKENS; i++) {
char *label = line_info->line[0][i];
- if (!label)
+ if (!label) {
continue;
+ }
char *val;
if (!strcasecmp(label, "volume")) {
@@ -522,8 +528,9 @@ CacheHostRecord::Init(matcher_line *line_info, CacheType typ)
}
return -1;
}
- if (c == '\0')
+ if (c == '\0') {
break;
+ }
vol_no = s + 1;
}
s++;
@@ -643,12 +650,13 @@ ConfigVolumes::BuildListFromString(char *config_file_path, char *file_buf)
}
end = (char *)tmp;
- while (*end && !isspace(*end))
+ while (*end && !isspace(*end)) {
end++;
+ }
- if (!(*end))
+ if (!(*end)) {
line_end = end;
- else {
+ } else {
line_end = end + 1;
*end = '\0';
}
@@ -697,8 +705,9 @@ ConfigVolumes::BuildListFromString(char *config_file_path, char *file_buf)
tmp += 5;
size = atoi(tmp);
- while (ParseRules::is_digit(*tmp))
+ while (ParseRules::is_digit(*tmp)) {
tmp++;
+ }
if (*tmp == '%') {
// added by YTS Team, yamsat for bug id 59632
@@ -716,8 +725,9 @@ ConfigVolumes::BuildListFromString(char *config_file_path, char *file_buf)
}
// ends here
- if (end < line_end)
+ if (end < line_end) {
tmp++;
+ }
}
if (err) {
@@ -812,8 +822,9 @@ create_config(RegressionTest *t, int num)
}
/* create 128 MB volumes */
for (; blocks >= STORE_BLOCKS_PER_VOL; blocks -= STORE_BLOCKS_PER_VOL) {
- if (vol_num > 255)
+ if (vol_num > 255) {
break;
+ }
ConfigVol *cp = new ConfigVol();
cp->number = vol_num++;
cp->scheme = CACHE_HTTP_TYPE;
@@ -894,8 +905,9 @@ create_config(RegressionTest *t, int num)
}
}
while (total_space > 0) {
- if (vol_num > 255)
+ if (vol_num > 255) {
break;
+ }
off_t modu = MAX_VOL_SIZE;
if (total_space < (MAX_VOL_SIZE >> STORE_BLOCK_SHIFT)) {
modu = total_space * STORE_BLOCK_SIZE;
@@ -942,8 +954,9 @@ execute_and_verify(RegressionTest *t)
cplist_reconfigure();
/* compare the volumes */
- if (cp_list_len != config_volumes.num_volumes)
+ if (cp_list_len != config_volumes.num_volumes) {
return REGRESSION_TEST_FAILED;
+ }
/* check that the volumes and sizes
match the configuration */
diff --git a/iocore/cache/CacheHttp.cc b/iocore/cache/CacheHttp.cc
index e572d11..315a7b9 100644
--- a/iocore/cache/CacheHttp.cc
+++ b/iocore/cache/CacheHttp.cc
@@ -56,8 +56,9 @@ CacheHTTPInfoVector::~CacheHTTPInfoVector()
int
CacheHTTPInfoVector::insert(CacheHTTPInfo *info, int index)
{
- if (index == CACHE_ALT_INDEX_DEFAULT)
+ if (index == CACHE_ALT_INDEX_DEFAULT) {
index = xcount++;
+ }
data(index).alternate.copy_shallow(info);
return index;
@@ -90,11 +91,13 @@ CacheHTTPInfoVector::detach(int idx, CacheHTTPInfo *r)
void
CacheHTTPInfoVector::remove(int idx, bool destroy)
{
- if (destroy)
+ if (destroy) {
data[idx].alternate.destroy();
+ }
- for (; idx < (xcount - 1); idx++)
+ for (; idx < (xcount - 1); idx++) {
data[idx] = data[idx + 1];
+ }
xcount--;
}
diff --git a/iocore/cache/CacheLink.cc b/iocore/cache/CacheLink.cc
index 6b1f6dc..4b3f9f3 100644
--- a/iocore/cache/CacheLink.cc
+++ b/iocore/cache/CacheLink.cc
@@ -48,10 +48,11 @@ Cache::link(Continuation *cont, const CacheKey *from, const CacheKey *to, CacheF
SET_CONTINUATION_HANDLER(c, &CacheVC::linkWrite);
- if (c->do_write_lock() == EVENT_DONE)
+ if (c->do_write_lock() == EVENT_DONE) {
return ACTION_RESULT_DONE;
- else
+ } else {
return &c->_action;
+ }
}
int
@@ -60,12 +61,14 @@ CacheVC::linkWrite(int event, Event * /* e ATS_UNUSED */)
ink_assert(event == AIO_EVENT_DONE);
set_io_not_in_progress();
dir_insert(&first_key, vol, &dir);
- if (_action.cancelled)
+ if (_action.cancelled) {
goto Ldone;
- if (io.ok())
+ }
+ if (io.ok()) {
_action.continuation->handleEvent(CACHE_EVENT_LINK, nullptr);
- else
+ } else {
_action.continuation->handleEvent(CACHE_EVENT_LINK_FAILED, nullptr);
+ }
Ldone:
return free_CacheVC(this);
}
@@ -114,10 +117,11 @@ Cache::deref(Continuation *cont, const CacheKey *key, CacheFragType type, const
}
}
Lcallreturn:
- if (c->handleEvent(AIO_EVENT_DONE, nullptr) == EVENT_DONE)
+ if (c->handleEvent(AIO_EVENT_DONE, nullptr) == EVENT_DONE) {
return ACTION_RESULT_DONE;
- else
+ } else {
return &c->_action;
+ }
}
int
@@ -127,19 +131,23 @@ CacheVC::derefRead(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
cancel_trigger();
set_io_not_in_progress();
- if (_action.cancelled)
+ if (_action.cancelled) {
return free_CacheVC(this);
- if (!buf)
+ }
+ if (!buf) {
goto Lcollision;
- if ((int)io.aio_result != (int)io.aiocb.aio_nbytes)
+ }
+ if ((int)io.aio_result != (int)io.aiocb.aio_nbytes) {
goto Ldone;
+ }
if (!dir_agg_valid(vol, &dir)) {
last_collision = nullptr;
goto Lcollision;
}
doc = (Doc *)buf->data();
- if (!(doc->first_key == key))
+ if (!(doc->first_key == key)) {
goto Lcollision;
+ }
#ifdef DEBUG
ink_assert(!memcmp(doc->data(), &doc->key, sizeof(doc->key)));
#endif
@@ -154,8 +162,9 @@ Lcollision : {
}
if (dir_probe(&key, vol, &dir, &last_collision)) {
int ret = do_read_call(&first_key);
- if (ret == EVENT_RETURN)
+ if (ret == EVENT_RETURN) {
goto Lcallreturn;
+ }
return ret;
}
}
diff --git a/iocore/cache/CachePages.cc b/iocore/cache/CachePages.cc
index 4644256..6d7bc86 100644
--- a/iocore/cache/CachePages.cc
+++ b/iocore/cache/CachePages.cc
@@ -110,10 +110,11 @@ struct ShowCache : public ShowCont {
if (p) {
while ((p = strstr(p, "\n"))) {
nstrings++;
- if ((size_t)(p - query) >= strlen(query) - 1)
+ if ((size_t)(p - query) >= strlen(query) - 1) {
break;
- else
+ } else {
p++;
+ }
}
}
// initialize url array
@@ -125,13 +126,15 @@ struct ShowCache : public ShowCont {
if (p) {
p += 4; // 4 ==> strlen("url=")
t = strchr(p, '&');
- if (!t)
+ if (!t) {
t = (char *)unescapedQuery + strlen(unescapedQuery);
+ }
for (int s = 0; p < t; s++) {
show_cache_urlstrs[s][0] = '\0';
q = strstr(p, "%0D%0A" /* \r\n */); // we used this in the JS to separate urls
- if (!q)
+ if (!q) {
q = t;
+ }
ink_strlcpy(show_cache_urlstrs[s], p, q - p + 1);
p = q + 6; // +6 ==> strlen(%0D%0A)
}
@@ -154,8 +157,9 @@ struct ShowCache : public ShowCont {
~ShowCache() override
{
- if (show_cache_urlstrs)
+ if (show_cache_urlstrs) {
delete[] show_cache_urlstrs;
+ }
url.destroy();
}
};
@@ -418,8 +422,9 @@ ShowCache::handleCacheEvent(int event, Event *e)
buffer_reader = buffer->alloc_reader();
content_length = cache_vc->get_object_size();
cvio = cache_vc->do_io_read(this, content_length, buffer);
- } else
+ } else {
buffer_reader->consume(buffer_reader->read_avail());
+ }
return EVENT_DONE;
case CACHE_EVENT_OPEN_READ_FAILED:
// something strange happen, or cache miss in cluster mode.
@@ -450,15 +455,17 @@ ShowCache::lookup_url(int event, Event *e)
SET_HANDLER(&ShowCache::handleCacheEvent);
Action *lookup_result = cacheProcessor.open_read(this, &key.hash, CACHE_FRAG_TYPE_HTTP, key.hostname, key.hostlen);
- if (!lookup_result)
+ if (!lookup_result) {
lookup_result = ACTION_IO_ERROR;
- if (lookup_result == ACTION_RESULT_DONE)
+ }
+ if (lookup_result == ACTION_RESULT_DONE) {
return EVENT_DONE; // callback complete
- else if (lookup_result == ACTION_IO_ERROR) {
+ } else if (lookup_result == ACTION_IO_ERROR) {
handleEvent(CACHE_EVENT_OPEN_READ_FAILED, nullptr);
return EVENT_DONE; // callback complete
- } else
+ } else {
return EVENT_CONT; // callback pending, will be a cluster read.
+ }
}
int
@@ -653,12 +660,13 @@ ShowCache::handleCacheScanCallback(int event, Event *e)
}
case CACHE_EVENT_SCAN_DONE:
CHECK_SHOW(show("</TABLE></B>\n"));
- if (scan_flag == 0)
+ if (scan_flag == 0) {
if (linecount) {
CHECK_SHOW(show("<P><INPUT TYPE=button value=\"Delete\" "
"onClick=\"setUrls(window.document.f)\"></P>"
"</FORM>\n"));
}
+ }
CHECK_SHOW(show("<H3>Done</H3>\n"));
Debug("cache_inspector", "scan done");
complete(event, e);
diff --git a/iocore/cache/CachePagesInternal.cc b/iocore/cache/CachePagesInternal.cc
index 069baa0..a14a8fa 100644
--- a/iocore/cache/CachePagesInternal.cc
+++ b/iocore/cache/CachePagesInternal.cc
@@ -82,10 +82,11 @@ register_ShowCacheInternal(Continuation *c, HTTPHdr *h)
SET_CONTINUATION_HANDLER(theshowcacheInternal, &ShowCacheInternal::showVolumes);
}
- if (theshowcacheInternal->mutex->thread_holding)
+ if (theshowcacheInternal->mutex->thread_holding) {
CONT_SCHED_LOCK_RETRY(theshowcacheInternal);
- else
+ } else {
eventProcessor.schedule_imm(theshowcacheInternal, ET_TASK);
+ }
return &theshowcacheInternal->action;
}
@@ -196,8 +197,9 @@ ShowCacheInternal::showVolEvacuations(int event, Event *e)
{
Vol *p = gvol[vol_index];
CACHE_TRY_LOCK(lock, p->mutex, mutex->thread_holding);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
CONT_SCHED_LOCK_RETRY_RET(this);
+ }
EvacuationBlock *b;
int last = (p->len - (p->start - p->skip)) / EVACUATION_BUCKET_SIZE;
@@ -215,9 +217,9 @@ ShowCacheInternal::showVolEvacuations(int event, Event *e)
}
}
vol_index++;
- if (vol_index < gnvol)
+ if (vol_index < gnvol) {
CONT_SCHED_LOCK_RETRY(this);
- else {
+ } else {
CHECK_SHOW(show("</table>\n"));
return complete(event, e);
}
@@ -252,8 +254,9 @@ ShowCacheInternal::showVolVolumes(int event, Event *e)
{
Vol *p = gvol[vol_index];
CACHE_TRY_LOCK(lock, p->mutex, mutex->thread_holding);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
CONT_SCHED_LOCK_RETRY_RET(this);
+ }
char ctime[256];
ink_ctime_r(&p->header->create_time, ctime);
@@ -261,8 +264,9 @@ ShowCacheInternal::showVolVolumes(int event, Event *e)
int agg_todo = 0;
int agg_done = p->agg_buf_pos;
CacheVC *c = nullptr;
- for (c = p->agg.head; c; c = (CacheVC *)c->link.next)
+ for (c = p->agg.head; c; c = (CacheVC *)c->link.next) {
agg_todo++;
+ }
CHECK_SHOW(show("<tr>"
"<td>%s</td>" // ID
"<td>%" PRId64 "</td>" // blocks
@@ -308,8 +312,9 @@ ShowCacheInternal::showSegSegment(int event, Event *e)
{
Vol *p = gvol[vol_index];
CACHE_TRY_LOCK(lock, p->mutex, mutex->thread_holding);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
CONT_SCHED_LOCK_RETRY_RET(this);
+ }
int free = 0, used = 0, empty = 0, valid = 0, agg_valid = 0, avg_size = 0;
dir_segment_accounted(seg_index, p, 0, &free, &used, &empty, &valid, &agg_valid, &avg_size);
CHECK_SHOW(show("<tr>"
@@ -322,16 +327,17 @@ ShowCacheInternal::showSegSegment(int event, Event *e)
"</tr>\n",
free, used, empty, valid, agg_valid, avg_size));
seg_index++;
- if (seg_index < p->segments)
+ if (seg_index < p->segments) {
CONT_SCHED_LOCK_RETRY(this);
- else {
+ } else {
CHECK_SHOW(show("</table>\n"));
seg_index = 0;
vol_index++;
- if (vol_index < gnvol)
+ if (vol_index < gnvol) {
CONT_SCHED_LOCK_RETRY(this);
- else
+ } else {
return complete(event, e);
+ }
}
return EVENT_CONT;
}
diff --git a/iocore/cache/CacheRead.cc b/iocore/cache/CacheRead.cc
index b1e4875..b9a6ccd 100644
--- a/iocore/cache/CacheRead.cc
+++ b/iocore/cache/CacheRead.cc
@@ -54,14 +54,16 @@ Cache::open_read(Continuation *cont, const CacheKey *key, CacheFragType type, co
c->frag_type = type;
c->od = od;
}
- if (!c)
+ if (!c) {
goto Lmiss;
+ }
if (!lock.is_locked()) {
CONT_SCHED_LOCK_RETRY(c);
return &c->_action;
}
- if (c->od)
+ if (c->od) {
goto Lwriter;
+ }
c->dir = result;
c->last_collision = last_collision;
switch (c->do_read_call(&c->key)) {
@@ -79,12 +81,14 @@ Lmiss:
return ACTION_RESULT_DONE;
Lwriter:
SET_CONTINUATION_HANDLER(c, &CacheVC::openReadFromWriter);
- if (c->handleEvent(EVENT_IMMEDIATE, nullptr) == EVENT_DONE)
+ if (c->handleEvent(EVENT_IMMEDIATE, nullptr) == EVENT_DONE) {
return ACTION_RESULT_DONE;
+ }
return &c->_action;
Lcallreturn:
- if (c->handleEvent(AIO_EVENT_DONE, nullptr) == EVENT_DONE)
+ if (c->handleEvent(AIO_EVENT_DONE, nullptr) == EVENT_DONE) {
return ACTION_RESULT_DONE;
+ }
return &c->_action;
}
@@ -123,10 +127,12 @@ Cache::open_read(Continuation *cont, const CacheKey *key, CacheHTTPHdr *request,
CONT_SCHED_LOCK_RETRY(c);
return &c->_action;
}
- if (!c)
+ if (!c) {
goto Lmiss;
- if (c->od)
+ }
+ if (c->od) {
goto Lwriter;
+ }
// hit
c->dir = c->first_dir = result;
c->last_collision = last_collision;
@@ -148,12 +154,14 @@ Lwriter:
// this is a horrible violation of the interface and should be fixed (FIXME)
((HttpCacheSM *)cont)->set_readwhilewrite_inprogress(true);
SET_CONTINUATION_HANDLER(c, &CacheVC::openReadFromWriter);
- if (c->handleEvent(EVENT_IMMEDIATE, nullptr) == EVENT_DONE)
+ if (c->handleEvent(EVENT_IMMEDIATE, nullptr) == EVENT_DONE) {
return ACTION_RESULT_DONE;
+ }
return &c->_action;
Lcallreturn:
- if (c->handleEvent(AIO_EVENT_DONE, nullptr) == EVENT_DONE)
+ if (c->handleEvent(AIO_EVENT_DONE, nullptr) == EVENT_DONE) {
return ACTION_RESULT_DONE;
+ }
return &c->_action;
}
@@ -193,8 +201,9 @@ CacheVC::openReadChooseWriter(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSE
ink_assert(vol->mutex->thread_holding == mutex->thread_holding && write_vc == nullptr);
- if (!od)
+ if (!od) {
return EVENT_RETURN;
+ }
if (frag_type != CACHE_FRAG_TYPE_HTTP) {
ink_assert(od->num_writers == 1);
@@ -203,24 +212,28 @@ CacheVC::openReadChooseWriter(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSE
od = nullptr;
return EVENT_RETURN;
}
- if (!w->closed)
+ if (!w->closed) {
return -err;
+ }
write_vc = w;
} else {
write_vector = &od->vector;
int write_vec_cnt = write_vector->count();
- for (int c = 0; c < write_vec_cnt; c++)
+ for (int c = 0; c < write_vec_cnt; c++) {
vector.insert(write_vector->get(c));
+ }
// check if all the writers who came before this reader have
// set the http_info.
for (w = (CacheVC *)od->writers.head; w; w = (CacheVC *)w->opendir_link.next) {
- if (w->start_time > start_time || w->closed < 0)
+ if (w->start_time > start_time || w->closed < 0) {
continue;
+ }
if (!w->closed && !cache_config_read_while_writer) {
return -err;
}
- if (w->alternate_index != CACHE_ALT_INDEX_DEFAULT)
+ if (w->alternate_index != CACHE_ALT_INDEX_DEFAULT) {
continue;
+ }
if (!w->closed && !w->alternate.valid()) {
od = nullptr;
@@ -235,14 +248,16 @@ CacheVC::openReadChooseWriter(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSE
alt_ndx = get_alternate_index(&vector, w->update_key);
// if its an alternate delete
if (!w->alternate.valid()) {
- if (alt_ndx >= 0)
+ if (alt_ndx >= 0) {
vector.remove(alt_ndx, false);
+ }
continue;
}
}
ink_assert(w->alternate.valid());
- if (w->alternate.valid())
+ if (w->alternate.valid()) {
vector.insert(&w->alternate, alt_ndx);
+ }
}
if (!vector.count()) {
@@ -257,10 +272,12 @@ CacheVC::openReadChooseWriter(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSE
}
if (cache_config_select_alternate) {
alternate_index = HttpTransactCache::SelectFromAlternates(&vector, &request, params);
- if (alternate_index < 0)
+ if (alternate_index < 0) {
return -ECACHE_ALT_MISS;
- } else
- alternate_index = 0;
+ }
+ } else {
+ alternate_index = 0;
+ }
CacheHTTPInfo *obj = vector.get(alternate_index);
for (w = (CacheVC *)od->writers.head; w; w = (CacheVC *)w->opendir_link.next) {
if (obj->m_alt == w->alternate.m_alt) {
@@ -304,16 +321,18 @@ CacheVC::openReadFromWriter(int event, Event *e)
return free_CacheVC(this);
}
CACHE_TRY_LOCK(lock, vol->mutex, mutex->thread_holding);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
VC_SCHED_LOCK_RETRY();
+ }
od = vol->open_read(&first_key); // recheck in case the lock failed
if (!od) {
MUTEX_RELEASE(lock);
write_vc = nullptr;
SET_HANDLER(&CacheVC::openReadStartHead);
return openReadStartHead(event, e);
- } else
+ } else {
ink_assert(od == vol->open_read(&first_key));
+ }
if (!write_vc) {
int ret = openReadChooseWriter(event, e);
if (ret < 0) {
@@ -331,8 +350,9 @@ CacheVC::openReadFromWriter(int event, Event *e)
} else {
return openReadFromWriterFailure(CACHE_EVENT_OPEN_READ_FAILED, (Event *)-err);
}
- } else
+ } else {
ink_assert(write_vc);
+ }
} else {
if (writer_done()) {
MUTEX_RELEASE(lock);
@@ -373,23 +393,26 @@ CacheVC::openReadFromWriter(int event, Event *e)
}
MUTEX_RELEASE(lock);
- if (!write_vc->io.ok())
+ if (!write_vc->io.ok()) {
return openReadFromWriterFailure(CACHE_EVENT_OPEN_READ_FAILED, (Event *)-err);
+ }
if (frag_type == CACHE_FRAG_TYPE_HTTP) {
DDebug("cache_read_agg", "%p: key: %X http passed stage 1, closed: %d, frag: %d", this, first_key.slice32(1), write_vc->closed,
write_vc->fragment);
- if (!write_vc->alternate.valid())
+ if (!write_vc->alternate.valid()) {
return openReadFromWriterFailure(CACHE_EVENT_OPEN_READ_FAILED, (Event *)-err);
+ }
alternate.copy(&write_vc->alternate);
vector.insert(&alternate);
alternate.object_key_get(&key);
write_vc->f.readers = 1;
if (!(write_vc->f.update && write_vc->total_len == 0)) {
key = write_vc->earliest_key;
- if (!write_vc->closed)
+ if (!write_vc->closed) {
alternate.object_size_set(write_vc->vio.nbytes);
- else
+ } else {
alternate.object_size_set(write_vc->total_len);
+ }
} else {
key = write_vc->update_key;
ink_assert(write_vc->closed);
@@ -464,8 +487,9 @@ CacheVC::openReadFromWriterMain(int /* event ATS_UNUSED */, Event * /* e ATS_UNU
}
IOBufferBlock *b = nullptr;
int64_t ntodo = vio.ntodo();
- if (ntodo <= 0)
+ if (ntodo <= 0) {
return EVENT_CONT;
+ }
if (length < ((int64_t)doc_len) - vio.ndone) {
DDebug("cache_read_agg", "truncation %X", first_key.slice32(1));
if (is_action_tag_set("cache")) {
@@ -481,8 +505,9 @@ CacheVC::openReadFromWriterMain(int /* event ATS_UNUSED */, Event * /* e ATS_UNU
iobufferblock_skip(writer_buf.get(), &writer_offset, &length, skip_bytes);
}
int64_t bytes = length;
- if (bytes > vio.ntodo())
+ if (bytes > vio.ntodo()) {
bytes = vio.ntodo();
+ }
if (vio.ndone >= (int64_t)doc_len) {
ink_assert(bytes <= 0);
// reached the end of the document and the user still wants more
@@ -492,10 +517,11 @@ CacheVC::openReadFromWriterMain(int /* event ATS_UNUSED */, Event * /* e ATS_UNU
writer_buf = iobufferblock_skip(writer_buf.get(), &writer_offset, &length, bytes);
vio.buffer.writer()->append_block(b);
vio.ndone += bytes;
- if (vio.ntodo() <= 0)
+ if (vio.ntodo() <= 0) {
return calluser(VC_EVENT_READ_COMPLETE);
- else
+ } else {
return calluser(VC_EVENT_READ_READY);
+ }
}
int
@@ -503,17 +529,19 @@ CacheVC::openReadClose(int event, Event * /* e ATS_UNUSED */)
{
cancel_trigger();
if (is_io_in_progress()) {
- if (event != AIO_EVENT_DONE)
+ if (event != AIO_EVENT_DONE) {
return EVENT_CONT;
+ }
set_io_not_in_progress();
}
CACHE_TRY_LOCK(lock, vol->mutex, mutex->thread_holding);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
VC_SCHED_LOCK_RETRY();
+ }
if (f.hit_evacuate && dir_valid(vol, &first_dir) && closed > 0) {
- if (f.single_fragment)
+ if (f.single_fragment) {
vol->force_evacuate_head(&first_dir, dir_pinned(&first_dir));
- else if (dir_valid(vol, &earliest_dir)) {
+ } else if (dir_valid(vol, &earliest_dir)) {
vol->force_evacuate_head(&first_dir, dir_pinned(&first_dir));
vol->force_evacuate_head(&earliest_dir, dir_pinned(&earliest_dir));
}
@@ -528,13 +556,15 @@ CacheVC::openReadReadDone(int event, Event *e)
Doc *doc = nullptr;
cancel_trigger();
- if (event == EVENT_IMMEDIATE)
+ if (event == EVENT_IMMEDIATE) {
return EVENT_CONT;
+ }
set_io_not_in_progress();
{
CACHE_TRY_LOCK(lock, vol->mutex, mutex->thread_holding);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
VC_SCHED_LOCK_RETRY();
+ }
if (event == AIO_EVENT_DONE && !io.ok()) {
dir_delete(&earliest_key, vol, &earliest_dir);
goto Lerror;
@@ -545,21 +575,25 @@ CacheVC::openReadReadDone(int event, Event *e)
doc = (Doc *)buf->data();
if (doc->magic != DOC_MAGIC) {
char tmpstring[100];
- if (doc->magic == DOC_CORRUPT)
+ if (doc->magic == DOC_CORRUPT) {
Warning("Middle: Doc checksum does not match for %s", key.toHexStr(tmpstring));
- else
+ } else {
Warning("Middle: Doc magic does not match for %s", key.toHexStr(tmpstring));
+ }
goto Lerror;
}
- if (doc->key == key)
+ if (doc->key == key) {
goto LreadMain;
+ }
}
- if (last_collision && dir_offset(&dir) != dir_offset(last_collision))
+ if (last_collision && dir_offset(&dir) != dir_offset(last_collision)) {
last_collision = nullptr; // object has been/is being overwritten
+ }
if (dir_probe(&key, vol, &dir, &last_collision)) {
int ret = do_read_call(&key);
- if (ret == EVENT_RETURN)
+ if (ret == EVENT_RETURN) {
goto Lcallreturn;
+ }
return EVENT_CONT;
} else if (write_vc) {
if (writer_done()) {
@@ -648,8 +682,9 @@ CacheVC::openReadMain(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
while (seek_to >= next_off && target < lfi) {
next_off = frags[++target];
}
- if (target == lfi && seek_to >= next_off)
+ if (target == lfi && seek_to >= next_off) {
++target;
+ }
} else { // shortcut if we are in the fragment already
target = fragment;
}
@@ -676,8 +711,9 @@ CacheVC::openReadMain(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
}
}
doc_pos = doc->prefix_len() + seek_to;
- if (fragment && frags)
+ if (fragment && frags) {
doc_pos -= static_cast<int64_t>(frags[fragment - 1]);
+ }
vio.ndone = 0;
seek_to = 0;
ntodo = vio.ntodo();
@@ -688,34 +724,41 @@ CacheVC::openReadMain(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
Debug("cache_seek", "Read # %d @ %" PRId64 "/%d for %" PRId64, fragment, doc_pos, doc->len, bytes);
}
}
- if (ntodo <= 0)
+ if (ntodo <= 0) {
return EVENT_CONT;
- if (vio.buffer.writer()->max_read_avail() > vio.buffer.writer()->water_mark && vio.ndone) // initiate read of first block
+ }
+ if (vio.buffer.writer()->max_read_avail() > vio.buffer.writer()->water_mark && vio.ndone) { // initiate read of first block
return EVENT_CONT;
- if ((bytes <= 0) && vio.ntodo() >= 0)
+ }
+ if ((bytes <= 0) && vio.ntodo() >= 0) {
goto Lread;
- if (bytes > vio.ntodo())
- bytes = vio.ntodo();
+ }
+ if (bytes > vio.ntodo()) {
+ bytes = vio.ntodo();
+ }
b = new_IOBufferBlock(buf, bytes, doc_pos);
b->_buf_end = b->_end;
vio.buffer.writer()->append_block(b);
vio.ndone += bytes;
doc_pos += bytes;
- if (vio.ntodo() <= 0)
+ if (vio.ntodo() <= 0) {
return calluser(VC_EVENT_READ_COMPLETE);
- else {
- if (calluser(VC_EVENT_READ_READY) == EVENT_DONE)
+ } else {
+ if (calluser(VC_EVENT_READ_READY) == EVENT_DONE) {
return EVENT_DONE;
+ }
// we have to keep reading until we give the user all the
// bytes it wanted or we hit the watermark.
- if (vio.ntodo() > 0 && !vio.buffer.writer()->high_water())
+ if (vio.ntodo() > 0 && !vio.buffer.writer()->high_water()) {
goto Lread;
+ }
return EVENT_CONT;
}
Lread : {
- if (vio.ndone >= (int64_t)doc_len)
+ if (vio.ndone >= (int64_t)doc_len) {
// reached the end of the document and the user still wants more
return calluser(VC_EVENT_EOS);
+ }
last_collision = nullptr;
writer_lock_retry = 0;
// if the state machine calls reenable on the callback from the cache,
@@ -731,8 +774,9 @@ Lread : {
if (dir_probe(&key, vol, &dir, &last_collision)) {
SET_HANDLER(&CacheVC::openReadReadDone);
int ret = do_read_call(&key);
- if (ret == EVENT_RETURN)
+ if (ret == EVENT_RETURN) {
goto Lcallreturn;
+ }
return EVENT_CONT;
} else if (write_vc) {
if (writer_done()) {
@@ -751,8 +795,9 @@ Lread : {
SET_HANDLER(&CacheVC::openReadMain);
VC_SCHED_WRITER_RETRY();
}
- if (is_action_tag_set("cache"))
+ if (is_action_tag_set("cache")) {
ink_release_assert(false);
+ }
Warning("Document %X truncated at %d of %d, missing fragment %X", first_key.slice32(1), (int)vio.ndone, (int)doc_len,
key.slice32(1));
// remove the directory entry
@@ -777,22 +822,27 @@ CacheVC::openReadStartEarliest(int /* event ATS_UNUSED */, Event * /* e ATS_UNUS
Doc *doc = nullptr;
cancel_trigger();
set_io_not_in_progress();
- if (_action.cancelled)
+ if (_action.cancelled) {
return free_CacheVC(this);
+ }
{
CACHE_TRY_LOCK(lock, vol->mutex, mutex->thread_holding);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
VC_SCHED_LOCK_RETRY();
- if (!buf)
+ }
+ if (!buf) {
goto Lread;
- if (!io.ok())
+ }
+ if (!io.ok()) {
goto Ldone;
+ }
// an object needs to be outside the aggregation window in order to be
// be evacuated as it is read
if (!dir_agg_valid(vol, &dir)) {
// a directory entry which is nolonger valid may have been overwritten
- if (!dir_valid(vol, &dir))
+ if (!dir_valid(vol, &dir)) {
last_collision = nullptr;
+ }
goto Lread;
}
doc = (Doc *)buf->data();
@@ -801,10 +851,11 @@ CacheVC::openReadStartEarliest(int /* event ATS_UNUSED */, Event * /* e ATS_UNUS
if (is_action_tag_set("cache")) {
ink_release_assert(false);
}
- if (doc->magic == DOC_CORRUPT)
+ if (doc->magic == DOC_CORRUPT) {
Warning("Earliest: Doc checksum does not match for %s", key.toHexStr(tmpstring));
- else
+ } else {
Warning("Earliest : Doc magic does not match for %s", key.toHexStr(tmpstring));
+ }
// remove the dir entry
dir_delete(&key, vol, &dir);
// try going through the directory entries again
@@ -814,8 +865,9 @@ CacheVC::openReadStartEarliest(int /* event ATS_UNUSED */, Event * /* e ATS_UNUS
last_collision = nullptr;
goto Lread;
}
- if (!(doc->key == key)) // collisiion
+ if (!(doc->key == key)) { // collisiion
goto Lread;
+ }
// success
earliest_key = key;
doc_pos = doc->prefix_len();
@@ -831,8 +883,9 @@ CacheVC::openReadStartEarliest(int /* event ATS_UNUSED */, Event * /* e ATS_UNUS
Lread:
if (dir_probe(&key, vol, &earliest_dir, &last_collision) || dir_lookaside_probe(&key, vol, &earliest_dir, nullptr)) {
dir = earliest_dir;
- if ((ret = do_read_call(&key)) == EVENT_RETURN)
+ if ((ret = do_read_call(&key)) == EVENT_RETURN) {
goto Lcallreturn;
+ }
return ret;
}
// read has detected that alternate does not exist in the cache.
@@ -882,16 +935,18 @@ CacheVC::openReadStartEarliest(int /* event ATS_UNUSED */, Event * /* e ATS_UNUS
dir_set_tag(&od->single_doc_dir, od->single_doc_key.slice32(2));
}
SET_HANDLER(&CacheVC::openReadVecWrite);
- if ((ret = do_write_call()) == EVENT_RETURN)
+ if ((ret = do_write_call()) == EVENT_RETURN) {
goto Lcallreturn;
+ }
return ret;
}
}
}
// open write failure - another writer, so don't modify the vector
Ldone:
- if (od)
+ if (od) {
vol->close_write(this);
+ }
}
CACHE_INCREMENT_DYN_STAT(cache_read_failure_stat);
_action.continuation->handleEvent(CACHE_EVENT_OPEN_READ_FAILED, (void *)-ECACHE_NO_DOC);
@@ -914,12 +969,14 @@ CacheVC::openReadVecWrite(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */
set_io_not_in_progress();
ink_assert(od);
od->writing_vec = false;
- if (_action.cancelled)
+ if (_action.cancelled) {
return openWriteCloseDir(EVENT_IMMEDIATE, nullptr);
+ }
{
CACHE_TRY_LOCK(lock, vol->mutex, mutex->thread_holding);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
VC_SCHED_LOCK_RETRY();
+ }
if (io.ok()) {
ink_assert(f.evac_vector);
ink_assert(frag_type == CACHE_FRAG_TYPE_HTTP);
@@ -931,8 +988,9 @@ CacheVC::openReadVecWrite(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */
f.use_first_key = 0;
vio.op = VIO::READ;
dir_overwrite(&first_key, vol, &dir, &od->first_dir);
- if (od->move_resident_alt)
+ if (od->move_resident_alt) {
dir_insert(&od->single_doc_key, vol, &od->single_doc_dir);
+ }
int alt_ndx = HttpTransactCache::SelectFromAlternates(write_vector, &request, params);
vol->close_write(this);
if (alt_ndx >= 0) {
@@ -966,22 +1024,27 @@ CacheVC::openReadStartHead(int event, Event *e)
Doc *doc = nullptr;
cancel_trigger();
set_io_not_in_progress();
- if (_action.cancelled)
+ if (_action.cancelled) {
return free_CacheVC(this);
+ }
{
CACHE_TRY_LOCK(lock, vol->mutex, mutex->thread_holding);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
VC_SCHED_LOCK_RETRY();
- if (!buf)
+ }
+ if (!buf) {
goto Lread;
- if (!io.ok())
+ }
+ if (!io.ok()) {
goto Ldone;
+ }
// an object needs to be outside the aggregation window in order to be
// be evacuated as it is read
if (!dir_agg_valid(vol, &dir)) {
// a directory entry which is nolonger valid may have been overwritten
- if (!dir_valid(vol, &dir))
+ if (!dir_valid(vol, &dir)) {
last_collision = nullptr;
+ }
goto Lread;
}
doc = (Doc *)buf->data();
@@ -990,10 +1053,11 @@ CacheVC::openReadStartHead(int event, Event *e)
if (is_action_tag_set("cache")) {
ink_release_assert(false);
}
- if (doc->magic == DOC_CORRUPT)
+ if (doc->magic == DOC_CORRUPT) {
Warning("Head: Doc checksum does not match for %s", key.toHexStr(tmpstring));
- else
+ } else {
Warning("Head : Doc magic does not match for %s", key.toHexStr(tmpstring));
+ }
// remove the dir entry
dir_delete(&key, vol, &dir);
// try going through the directory entries again
@@ -1003,17 +1067,20 @@ CacheVC::openReadStartHead(int event, Event *e)
last_collision = nullptr;
goto Lread;
}
- if (!(doc->first_key == key))
+ if (!(doc->first_key == key)) {
goto Lread;
- if (f.lookup)
+ }
+ if (f.lookup) {
goto Lookup;
+ }
earliest_dir = dir;
CacheHTTPInfo *alternate_tmp;
if (frag_type == CACHE_FRAG_TYPE_HTTP) {
uint32_t uml;
ink_assert(doc->hlen);
- if (!doc->hlen)
+ if (!doc->hlen) {
goto Ldone;
+ }
if ((uml = this->load_http_info(&vector, doc)) != doc->hlen) {
if (buf) {
HTTPCacheAlt *alt = reinterpret_cast<HTTPCacheAlt *>(doc->hdr());
@@ -1022,8 +1089,9 @@ CacheVC::openReadStartHead(int event, Event *e)
// by bad disk data - count should be the number of successfully unmarshalled alts.
for (int32_t i = 0; i < vector.count(); ++i) {
CacheHTTPInfo *info = vector.get(i);
- if (info && info->m_alt)
+ if (info && info->m_alt) {
alt_length += info->m_alt->m_unmarshal_len;
+ }
}
Note("OpenReadHead failed for cachekey %X : vector inconsistency - "
"unmarshalled %d expecting %d in %d (base=%d, ver=%d:%d) "
@@ -1045,9 +1113,10 @@ CacheVC::openReadStartHead(int event, Event *e)
err = ECACHE_ALT_MISS;
goto Ldone;
}
- } else
+ } else {
alternate_index = 0;
- alternate_tmp = vector.get(alternate_index);
+ }
+ alternate_tmp = vector.get(alternate_index);
if (!alternate_tmp->valid()) {
if (buf) {
Note("OpenReadHead failed for cachekey %X : alternate inconsistency", key.slice32(0));
@@ -1083,8 +1152,9 @@ CacheVC::openReadStartHead(int event, Event *e)
}
// the first fragment might have been gc'ed. Make sure the first
// fragment is there before returning CACHE_EVENT_OPEN_READ
- if (!f.single_fragment)
+ if (!f.single_fragment) {
goto Learliest;
+ }
if (vol->within_hit_evacuate_window(&dir) &&
(!cache_config_hit_evacuate_size_limit || doc_len <= (uint64_t)cache_config_hit_evacuate_size_limit)) {
@@ -1118,8 +1188,9 @@ CacheVC::openReadStartHead(int event, Event *e)
if (dir_probe(&key, vol, &dir, &last_collision)) {
first_dir = dir;
int ret = do_read_call(&key);
- if (ret == EVENT_RETURN)
+ if (ret == EVENT_RETURN) {
goto Lcallreturn;
+ }
return ret;
}
}
diff --git a/iocore/cache/CacheTest.cc b/iocore/cache/CacheTest.cc
index 52d3b30..8483c4b 100644
--- a/iocore/cache/CacheTest.cc
+++ b/iocore/cache/CacheTest.cc
@@ -47,10 +47,12 @@ CacheTestSM::~CacheTestSM()
{
ink_assert(!cache_action);
ink_assert(!cache_vc);
- if (buffer_reader)
+ if (buffer_reader) {
buffer->dealloc_reader(buffer_reader);
- if (buffer)
+ }
+ if (buffer) {
free_MIOBuffer(buffer);
+ }
}
int
@@ -97,24 +99,27 @@ CacheTestSM::event_handler(int event, void *data)
cache_vc = (CacheVConnection *)data;
buffer = new_empty_MIOBuffer();
buffer_reader = buffer->alloc_reader();
- if (open_read_callout() < 0)
+ if (open_read_callout() < 0) {
goto Lclose_error_next;
- else
+ } else {
return EVENT_DONE;
+ }
case CACHE_EVENT_OPEN_READ_FAILED:
goto Lcancel_next;
case VC_EVENT_READ_READY:
- if (!check_buffer())
+ if (!check_buffer()) {
goto Lclose_error_next;
+ }
buffer_reader->consume(buffer_reader->read_avail());
((VIO *)data)->reenable();
return EVENT_CONT;
case VC_EVENT_READ_COMPLETE:
- if (!check_buffer())
+ if (!check_buffer()) {
goto Lclose_error_next;
+ }
goto Lclose_next;
case VC_EVENT_ERROR:
@@ -128,10 +133,11 @@ CacheTestSM::event_handler(int event, void *data)
cache_vc = (CacheVConnection *)data;
buffer = new_empty_MIOBuffer();
buffer_reader = buffer->alloc_reader();
- if (open_write_callout() < 0)
+ if (open_write_callout() < 0) {
goto Lclose_error_next;
- else
+ } else {
return EVENT_DONE;
+ }
case CACHE_EVENT_OPEN_WRITE_FAILED:
goto Lcancel_next;
@@ -142,8 +148,9 @@ CacheTestSM::event_handler(int event, void *data)
return EVENT_CONT;
case VC_EVENT_WRITE_COMPLETE:
- if (nbytes != cvio->ndone)
+ if (nbytes != cvio->ndone) {
goto Lclose_error_next;
+ }
goto Lclose_next;
case CACHE_EVENT_REMOVE:
@@ -203,8 +210,9 @@ Lnext:
repeat_count--;
timeout = eventProcessor.schedule_imm(this);
return EVENT_DONE;
- } else
+ } else {
return complete(event);
+ }
}
void
@@ -216,14 +224,16 @@ CacheTestSM::fill_buffer()
int64_t sk = (int64_t)sizeof(key);
while (avail > 0) {
int64_t l = avail;
- if (l > sk)
+ if (l > sk) {
l = sk;
+ }
int64_t pos = cvio->ndone + buffer_reader->read_avail();
int64_t o = pos % sk;
- if (l > sk - o)
- l = sk - o;
+ if (l > sk - o) {
+ l = sk - o;
+ }
k.b[0] = pos / sk;
char *x = ((char *)&k) + o;
buffer->write(x, l);
@@ -243,16 +253,19 @@ CacheTestSM::check_buffer()
int64_t pos = cvio->ndone - buffer_reader->read_avail();
while (avail > 0) {
int64_t l = avail;
- if (l > sk)
- l = sk;
+ if (l > sk) {
+ l = sk;
+ }
int64_t o = pos % sk;
- if (l > sk - o)
- l = sk - o;
+ if (l > sk - o) {
+ l = sk - o;
+ }
k.b[0] = pos / sk;
char *x = ((char *)&k) + o;
buffer_reader->read(&b[0], l);
- if (::memcmp(b, x, l))
+ if (::memcmp(b, x, l)) {
return 0;
+ }
buffer_reader->consume(l);
pos += l;
avail -= l;
@@ -269,10 +282,11 @@ CacheTestSM::check_result(int event)
int
CacheTestSM::complete(int event)
{
- if (!check_result(event))
+ if (!check_result(event)) {
done(REGRESSION_TEST_FAILED);
- else
+ } else {
done(REGRESSION_TEST_PASSED);
+ }
delete this;
return EVENT_DONE;
}
@@ -460,15 +474,18 @@ REGRESSION_TEST(cache_disk_replacement_stability)(RegressionTest *t, int level,
int to = 0, from = 0;
int then = 0, now = 0;
for (int i = 0; i < VOL_HASH_TABLE_SIZE; ++i) {
- if (hr1.vol_hash_table[i] == sample_idx)
+ if (hr1.vol_hash_table[i] == sample_idx) {
++then;
- if (hr2.vol_hash_table[i] == sample_idx)
+ }
+ if (hr2.vol_hash_table[i] == sample_idx) {
++now;
+ }
if (hr1.vol_hash_table[i] != hr2.vol_hash_table[i]) {
- if (hr1.vol_hash_table[i] == sample_idx)
+ if (hr1.vol_hash_table[i] == sample_idx) {
++from;
- else
+ } else {
++to;
+ }
}
}
rprintf(t, "Cache stability difference - "
@@ -490,16 +507,20 @@ static double *zipf_table = nullptr;
static void
build_zipf()
{
- if (zipf_table)
+ if (zipf_table) {
return;
+ }
zipf_table = (double *)ats_malloc(ZIPF_SIZE * sizeof(double));
- for (int i = 0; i < ZIPF_SIZE; i++)
+ for (int i = 0; i < ZIPF_SIZE; i++) {
zipf_table[i] = 1.0 / pow(i + 2, zipf_alpha);
- for (int i = 1; i < ZIPF_SIZE; i++)
+ }
+ for (int i = 1; i < ZIPF_SIZE; i++) {
zipf_table[i] = zipf_table[i - 1] + zipf_table[i];
- double x = zipf_table[ZIPF_SIZE - 1];
- for (int i = 0; i < ZIPF_SIZE; i++)
+ }
+ double x = zipf_table[ZIPF_SIZE - 1];
+ for (int i = 0; i < ZIPF_SIZE; i++) {
zipf_table[i] = zipf_table[i] / x;
+ }
}
static int
@@ -508,13 +529,15 @@ get_zipf(double v)
int l = 0, r = ZIPF_SIZE - 1, m;
do {
m = (r + l) / 2;
- if (v < zipf_table[m])
+ if (v < zipf_table[m]) {
r = m - 1;
- else
+ } else {
l = m + 1;
+ }
} while (l < r);
- if (zipf_bucket_size == 1)
+ if (zipf_bucket_size == 1) {
return m;
+ }
double x = zipf_table[m], y = zipf_table[m + 1];
m += static_cast<int>((v - x) / (y - x));
return m;
@@ -567,9 +590,10 @@ test_RamCache(RegressionTest *t, RamCache *cache, const char *name, int64_t cach
build_zipf();
srand48(13);
int *r = (int *)ats_malloc(sample_size * sizeof(int));
- for (int i = 0; i < sample_size; i++)
+ for (int i = 0; i < sample_size; i++) {
// coverity[dont_call]
r[i] = get_zipf(drand48());
+ }
data.clear();
int misses = 0;
for (int i = 0; i < sample_size; i++) {
@@ -582,8 +606,9 @@ test_RamCache(RegressionTest *t, RamCache *cache, const char *name, int64_t cach
d->alloc(BUFFER_SIZE_INDEX_16K);
data.push_back(make_ptr(d));
cache->put(&md5, data.back().get(), 1 << 15);
- if (i >= sample_size / 2)
+ if (i >= sample_size / 2) {
misses++; // Sample last half of the gets.
+ }
}
}
double fixed_hit_rate = 1.0 - (((double)(misses)) / (sample_size / 2));
@@ -601,8 +626,9 @@ test_RamCache(RegressionTest *t, RamCache *cache, const char *name, int64_t cach
d->alloc(BUFFER_SIZE_INDEX_8K + (r[i] % 3));
data.push_back(make_ptr(d));
cache->put(&md5, data.back().get(), d->block_size());
- if (i >= sample_size / 2)
+ if (i >= sample_size / 2) {
misses++; // Sample last half of the gets.
+ }
}
}
double variable_hit_rate = 1.0 - (((double)(misses)) / (sample_size / 2));
@@ -610,10 +636,12 @@ test_RamCache(RegressionTest *t, RamCache *cache, const char *name, int64_t cach
rprintf(t, "RamCache %s Nominal Size %lld Size %lld\n", name, cache_size, cache->size());
- if (fixed_hit_rate < 0.55 || variable_hit_rate < 0.55)
+ if (fixed_hit_rate < 0.55 || variable_hit_rate < 0.55) {
return false;
- if (abs(cache_size - cache->size()) > 0.02 * cache_size)
+ }
+ if (abs(cache_size - cache->size()) > 0.02 * cache_size) {
return false;
+ }
ats_free(r);
@@ -638,7 +666,8 @@ REGRESSION_TEST(ram_cache)(RegressionTest *t, int level, int *pstatus)
for (int s = 20; s <= 28; s += 4) {
int64_t cache_size = 1LL << s;
*pstatus = REGRESSION_TEST_PASSED;
- if (!test_RamCache(t, new_RamCacheLRU(), "LRU", cache_size) || !test_RamCache(t, new_RamCacheCLFUS(), "CLFUS", cache_size))
+ if (!test_RamCache(t, new_RamCacheLRU(), "LRU", cache_size) || !test_RamCache(t, new_RamCacheCLFUS(), "CLFUS", cache_size)) {
*pstatus = REGRESSION_TEST_FAILED;
+ }
}
}
diff --git a/iocore/cache/CacheVol.cc b/iocore/cache/CacheVol.cc
index 7dfb0ee..45c8598 100644
--- a/iocore/cache/CacheVol.cc
+++ b/iocore/cache/CacheVol.cc
@@ -54,25 +54,29 @@ int
CacheVC::scanVol(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
{
Debug("cache_scan_truss", "inside %p:scanVol", this);
- if (_action.cancelled)
+ if (_action.cancelled) {
return free_CacheVC(this);
+ }
CacheHostRecord *rec = &theCache->hosttable->gen_host_rec;
if (host_len) {
CacheHostResult res;
theCache->hosttable->Match(hostname, host_len, &res);
- if (res.record)
+ if (res.record) {
rec = res.record;
+ }
}
if (!vol) {
- if (!rec->num_vols)
+ if (!rec->num_vols) {
goto Ldone;
+ }
vol = rec->vols[0];
} else {
- for (int i = 0; i < rec->num_vols - 1; i++)
+ for (int i = 0; i < rec->num_vols - 1; i++) {
if (vol == rec->vols[i]) {
vol = rec->vols[i + 1];
goto Lcont;
}
+ }
goto Ldone;
}
Lcont:
@@ -98,10 +102,12 @@ next_in_map(Vol *d, char *vol_map, off_t offset)
off_t new_off = (offset - start_offset);
off_t vol_len = vol_relative_length(d, start_offset);
- while (new_off < vol_len && !vol_map[new_off / SCAN_BUF_SIZE])
+ while (new_off < vol_len && !vol_map[new_off / SCAN_BUF_SIZE]) {
new_off += SCAN_BUF_SIZE;
- if (new_off >= vol_len)
+ }
+ if (new_off >= vol_len) {
return vol_len + start_offset;
+ }
return new_off + start_offset;
}
@@ -137,12 +143,14 @@ make_vol_map(Vol *d)
while (e) {
if (dir_offset(e) && dir_valid(d, e) && dir_agg_valid(d, e) && dir_head(e)) {
off_t offset = vol_offset(d, e) - start_offset;
- if (offset <= vol_len)
+ if (offset <= vol_len) {
vol_map[offset / SCAN_BUF_SIZE] = 1;
+ }
}
e = next_dir(e, seg);
- if (!e)
+ if (!e) {
break;
+ }
}
}
}
@@ -164,8 +172,9 @@ CacheVC::scanObject(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
cancel_trigger();
set_io_not_in_progress();
- if (_action.cancelled)
+ if (_action.cancelled) {
return free_CacheVC(this);
+ }
CACHE_TRY_LOCK(lock, vol->mutex, mutex->thread_holding);
if (!lock.is_locked()) {
@@ -178,8 +187,9 @@ CacheVC::scanObject(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
fragment = 1;
scan_vol_map = make_vol_map(vol);
io.aiocb.aio_offset = next_in_map(vol, scan_vol_map, vol_offset_to_offset(vol, 0));
- if (io.aiocb.aio_offset >= (off_t)(vol->skip + vol->len))
+ if (io.aiocb.aio_offset >= (off_t)(vol->skip + vol->len)) {
goto Lnext_vol;
+ }
io.aiocb.aio_nbytes = SCAN_BUF_SIZE;
io.aiocb.aio_buf = buf->data();
io.action = this;
@@ -216,16 +226,19 @@ CacheVC::scanObject(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
continue;
}
- if (doc->doc_type != CACHE_FRAG_TYPE_HTTP || !doc->hlen)
+ if (doc->doc_type != CACHE_FRAG_TYPE_HTTP || !doc->hlen) {
goto Lskip;
+ }
last_collision = nullptr;
while (true) {
- if (!dir_probe(&doc->first_key, vol, &dir, &last_collision))
+ if (!dir_probe(&doc->first_key, vol, &dir, &last_collision)) {
goto Lskip;
+ }
if (!dir_agg_valid(vol, &dir) || !dir_head(&dir) ||
- (vol_offset(vol, &dir) != io.aiocb.aio_offset + ((char *)doc - buf->data())))
+ (vol_offset(vol, &dir) != io.aiocb.aio_offset + ((char *)doc - buf->data()))) {
continue;
+ }
break;
}
if (doc->data() - buf->data() > (int)io.aiocb.aio_nbytes) {
@@ -245,13 +258,15 @@ CacheVC::scanObject(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
tmp += r;
}
}
- if (this->load_http_info(&vector, doc) != doc->hlen)
+ if (this->load_http_info(&vector, doc) != doc->hlen) {
goto Lskip;
+ }
changed = false;
hostinfo_copied = false;
for (i = 0; i < vector.count(); i++) {
- if (!vector.get(i)->valid())
+ if (!vector.get(i)->valid()) {
goto Lskip;
+ }
if (!hostinfo_copied) {
memccpy(hname, vector.get(i)->request_get()->host_get(&hlen), 0, 500);
hname[hlen] = 0;
@@ -263,8 +278,9 @@ CacheVC::scanObject(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
// verify that the earliest block exists, reducing 'false hit' callbacks
if (!(key == doc->key)) {
last_collision = nullptr;
- if (!dir_probe(&key, vol, &earliest_dir, &last_collision))
+ if (!dir_probe(&key, vol, &earliest_dir, &last_collision)) {
continue;
+ }
}
earliest_key = key;
int result1 = _action.continuation->handleEvent(CACHE_EVENT_SCAN_OBJECT, vector.get(i));
@@ -284,8 +300,9 @@ CacheVC::scanObject(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
case CACHE_SCAN_RESULT_UPDATE:
ink_assert(alternate_index >= 0);
vector.insert(&alternate, alternate_index);
- if (!vector.get(alternate_index)->valid())
+ if (!vector.get(alternate_index)->valid()) {
continue;
+ }
changed = true;
continue;
case EVENT_DONE:
@@ -350,9 +367,10 @@ CacheVC::scanObject(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
Lread:
io.aiocb.aio_fildes = vol->fd;
- if ((off_t)(io.aiocb.aio_offset + io.aiocb.aio_nbytes) > (off_t)(vol->skip + vol->len))
+ if ((off_t)(io.aiocb.aio_offset + io.aiocb.aio_nbytes) > (off_t)(vol->skip + vol->len)) {
io.aiocb.aio_nbytes = vol->skip + vol->len - io.aiocb.aio_offset;
- offset = 0;
+ }
+ offset = 0;
ink_assert(ink_aio_read(&io) >= 0);
Debug("cache_scan_truss", "read %p:scanObject %" PRId64 " %zu", this, (int64_t)io.aiocb.aio_offset, (size_t)io.aiocb.aio_nbytes);
return EVENT_CONT;
@@ -451,13 +469,15 @@ CacheVC::scanOpenWrite(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
// the document was not modified
// we are safe from now on as we hold the
// writer lock on the doc
- if (f.evac_vector)
+ if (f.evac_vector) {
header_len = write_vector->marshal_length();
+ }
SET_HANDLER(&CacheVC::scanUpdateDone);
ret = do_write_call();
}
- if (ret == EVENT_RETURN)
+ if (ret == EVENT_RETURN) {
return handleEvent(AIO_EVENT_DONE, nullptr);
+ }
return ret;
}
diff --git a/iocore/cache/CacheWrite.cc b/iocore/cache/CacheWrite.cc
index 18012c6..5871980 100644
--- a/iocore/cache/CacheWrite.cc
+++ b/iocore/cache/CacheWrite.cc
@@ -35,8 +35,9 @@ get_alternate_index(CacheHTTPInfoVector *cache_vector, CacheKey key)
{
int alt_count = cache_vector->count();
CacheHTTPInfo *obj;
- if (!alt_count)
+ if (!alt_count) {
return -1;
+ }
for (int i = 0; i < alt_count; i++) {
obj = cache_vector->get(i);
if (obj->compare_object_key(&key)) {
@@ -57,13 +58,15 @@ int
CacheVC::updateVector(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
{
cancel_trigger();
- if (od->reading_vec || od->writing_vec)
+ if (od->reading_vec || od->writing_vec) {
VC_SCHED_LOCK_RETRY();
+ }
int ret = 0;
{
CACHE_TRY_LOCK(lock, vol->mutex, mutex->thread_holding);
- if (!lock.is_locked() || od->writing_vec)
+ if (!lock.is_locked() || od->writing_vec) {
VC_SCHED_LOCK_RETRY();
+ }
int vec = alternate.valid();
if (f.update) {
@@ -77,8 +80,9 @@ CacheVC::updateVector(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
if (alternate_index >= 0) {
write_vector->remove(alternate_index, true);
alternate_index = CACHE_ALT_REMOVED;
- if (!write_vector->count())
+ if (!write_vector->count()) {
dir_delete(&first_key, vol, &od->first_dir);
+ }
}
// the alternate is not there any more. somebody might have
// deleted it. Just close this writer
@@ -87,12 +91,14 @@ CacheVC::updateVector(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
return openWriteCloseDir(EVENT_IMMEDIATE, nullptr);
}
}
- if (update_key == od->single_doc_key && (total_len || !vec))
+ if (update_key == od->single_doc_key && (total_len || !vec)) {
od->move_resident_alt = false;
+ }
}
if (cache_config_http_max_alts > 1 && write_vector->count() >= cache_config_http_max_alts && alternate_index < 0) {
- if (od->move_resident_alt && get_alternate_index(write_vector, od->single_doc_key) == 0)
+ if (od->move_resident_alt && get_alternate_index(write_vector, od->single_doc_key) == 0) {
od->move_resident_alt = false;
+ }
write_vector->remove(0, true);
}
if (vec) {
@@ -100,8 +106,9 @@ CacheVC::updateVector(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
called iff the update is a header only update so the fragment
data should remain valid.
*/
- if (alternate_index >= 0)
+ if (alternate_index >= 0) {
alternate.copy_frag_offsets_from(write_vector->get(alternate_index));
+ }
alternate_index = write_vector->insert(&alternate, alternate_index);
}
@@ -134,8 +141,9 @@ CacheVC::updateVector(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
SET_HANDLER(&CacheVC::openWriteCloseHeadDone);
ret = do_write_call();
}
- if (ret == EVENT_RETURN)
+ if (ret == EVENT_RETURN) {
return handleEvent(AIO_EVENT_DONE, nullptr);
+ }
return ret;
}
/*
@@ -197,17 +205,20 @@ CacheVC::handleWrite(int event, Event * /* e ATS_UNUSED */)
CACHE_INCREMENT_DYN_STAT(base_stat + CACHE_STAT_FAILURE);
vol->agg_todo_size -= agg_len;
io.aio_result = AIO_SOFT_FAILURE;
- if (event == EVENT_CALL)
+ if (event == EVENT_CALL) {
return EVENT_RETURN;
+ }
return handleEvent(AIO_EVENT_DONE, nullptr);
}
ink_assert(agg_len <= AGG_SIZE);
- if (f.evac_vector)
+ if (f.evac_vector) {
vol->agg.push(this);
- else
+ } else {
vol->agg.enqueue(this);
- if (!vol->is_io_in_progress())
+ }
+ if (!vol->is_io_in_progress()) {
return vol->aggWrite(event, this);
+ }
return EVENT_CONT;
}
@@ -226,8 +237,9 @@ iobufferblock_memcpy(char *p, int len, IOBufferBlock *ab, int offset)
continue;
}
int bytes = len;
- if (bytes >= max_bytes)
+ if (bytes >= max_bytes) {
bytes = max_bytes;
+ }
::memcpy(p, start + offset, bytes);
p += bytes;
len -= bytes;
@@ -244,8 +256,9 @@ Vol::force_evacuate_head(Dir *evac_dir, int pinned)
EvacuationBlock *b = evacuation_block_exists(evac_dir, this);
// if we have already started evacuating this document, its too late
// to evacuate the head...bad luck
- if (b && b->f.done)
+ if (b && b->f.done) {
return b;
+ }
if (!b) {
b = new_EvacuationBlock(mutex->thread_holding);
@@ -278,11 +291,13 @@ Vol::scan_for_pinned_documents()
// select objects only within this PIN_SCAN region
int o = dir_offset(&dir[i]);
if (dir_phase(&dir[i]) == header->phase) {
- if (before_end_of_vol || o >= (pe - vol_end_offset))
+ if (before_end_of_vol || o >= (pe - vol_end_offset)) {
continue;
+ }
} else {
- if (o < ps || o >= pe)
+ if (o < ps || o >= pe) {
continue;
+ }
}
force_evacuate_head(&dir[i], 1);
// DDebug("cache_evac", "scan pinned at offset %d %d %d %d %d %d",
@@ -316,8 +331,9 @@ Vol::aggWriteDone(int event, Event *e)
DDebug("cache_agg", "Dir %s, Write: %" PRIu64 ", last Write: %" PRIu64 "", hash_text.get(), header->write_pos,
header->last_write_pos);
ink_assert(header->write_pos == header->agg_pos);
- if (header->write_pos + EVACUATION_SIZE > scan_pos)
+ if (header->write_pos + EVACUATION_SIZE > scan_pos) {
periodic_scan();
+ }
agg_buf_pos = 0;
header->write_serial++;
} else {
@@ -342,9 +358,9 @@ Vol::aggWriteDone(int event, Event *e)
// callback ready sync CacheVCs
CacheVC *c = nullptr;
while ((c = sync.dequeue())) {
- if (UINT_WRAP_LTE(c->write_serial + 2, header->write_serial))
+ if (UINT_WRAP_LTE(c->write_serial + 2, header->write_serial)) {
c->initial_thread->schedule_imm_signal(c, AIO_EVENT_DONE);
- else {
+ } else {
sync.push(c); // put it back on the front
break;
}
@@ -353,8 +369,9 @@ Vol::aggWriteDone(int event, Event *e)
dir_sync_waiting = false;
cacheDirSync->handleEvent(EVENT_IMMEDIATE, nullptr);
}
- if (agg.head || sync.head)
+ if (agg.head || sync.head) {
return aggWrite(event, e);
+ }
return EVENT_CONT;
}
@@ -381,15 +398,17 @@ CacheVC::evacuateReadHead(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */
cancel_trigger();
Doc *doc = (Doc *)buf->data();
CacheHTTPInfo *alternate_tmp = nullptr;
- if (!io.ok())
+ if (!io.ok()) {
goto Ldone;
+ }
// a directory entry which is nolonger valid may have been overwritten
if (!dir_valid(vol, &dir)) {
last_collision = nullptr;
goto Lcollision;
}
- if (doc->magic != DOC_MAGIC || !(doc->first_key == first_key))
+ if (doc->magic != DOC_MAGIC || !(doc->first_key == first_key)) {
goto Lcollision;
+ }
alternate_tmp = nullptr;
if (doc->doc_type == CACHE_FRAG_TYPE_HTTP && doc->hlen) {
// its an http document
@@ -398,8 +417,9 @@ CacheVC::evacuateReadHead(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */
goto Ldone;
}
alternate_index = get_alternate_index(&vector, earliest_key);
- if (alternate_index < 0)
+ if (alternate_index < 0) {
goto Ldone;
+ }
alternate_tmp = vector.get(alternate_index);
doc_len = alternate_tmp->object_size_get();
Debug("cache_evac", "evacuateReadHead http earliest %X first: %X len: %" PRId64, first_key.slice32(0), earliest_key.slice32(0),
@@ -408,8 +428,9 @@ CacheVC::evacuateReadHead(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */
// non-http document
CacheKey next_key;
next_CacheKey(&next_key, &doc->key);
- if (!(next_key == earliest_key))
+ if (!(next_key == earliest_key)) {
goto Ldone;
+ }
doc_len = doc->total_len;
DDebug("cache_evac", "evacuateReadHead non-http earliest %X first: %X len: %" PRId64, first_key.slice32(0),
earliest_key.slice32(0), doc_len);
@@ -424,8 +445,9 @@ CacheVC::evacuateReadHead(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */
Lcollision:
if (dir_probe(&first_key, vol, &dir, &last_collision)) {
int ret = do_read_call(&first_key);
- if (ret == EVENT_RETURN)
+ if (ret == EVENT_RETURN) {
return handleEvent(AIO_EVENT_DONE, nullptr);
+ }
return ret;
}
Ldone:
@@ -455,11 +477,13 @@ CacheVC::evacuateDocDone(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
if (!dir_head(&overwrite_dir)) {
// find the earliest key
EvacuationKey *evac = &b->evac_frags;
- for (; evac && !(evac->key == doc->key); evac = evac->link.next)
+ for (; evac && !(evac->key == doc->key); evac = evac->link.next) {
;
+ }
ink_assert(evac);
- if (!evac)
+ if (!evac) {
break;
+ }
if (evac->earliest_key.fold()) {
DDebug("cache_evac", "evacdocdone: evacuating key %X earliest %X", evac->key.slice32(0), evac->earliest_key.slice32(0));
EvacuationBlock *eblock = nullptr;
@@ -510,8 +534,9 @@ CacheVC::evacuateDocDone(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
// read the vector
SET_HANDLER(&CacheVC::evacuateReadHead);
int ret = do_read_call(&first_key);
- if (ret == EVENT_RETURN)
+ if (ret == EVENT_RETURN) {
return handleEvent(AIO_EVENT_DONE, nullptr);
+ }
return ret;
}
}
@@ -530,8 +555,9 @@ evacuate_fragments(CacheKey *key, CacheKey *earliest_key, int force, Vol *vol)
while (dir_probe(key, vol, &dir, &last_collision)) {
// next fragment cannot be a head...if it is, it must have been a
// directory collision.
- if (dir_head(&dir))
+ if (dir_head(&dir)) {
continue;
+ }
EvacuationBlock *b = evacuation_block_exists(&dir, vol);
if (!b) {
b = new_EvacuationBlock(vol->mutex->thread_holding);
@@ -549,8 +575,9 @@ evacuate_fragments(CacheKey *key, CacheKey *earliest_key, int force, Vol *vol)
evac_frag->link.next = b->evac_frags.link.next;
b->evac_frags.link.next = evac_frag;
}
- if (force)
+ if (force) {
b->readers = 0;
+ }
DDebug("cache_evac", "next fragment %X Earliest: %X offset %d phase %d force %d", (int)key->slice32(0),
(int)earliest_key->slice32(0), (int)dir_offset(&dir), (int)dir_phase(&dir), force);
}
@@ -567,8 +594,9 @@ Vol::evacuateWrite(CacheVC *evacuator, int event, Event *e)
/* insert the evacuator after all the other evacuators */
CacheVC *cur = (CacheVC *)agg.head;
CacheVC *after = nullptr;
- for (; cur && cur->f.evacuator; cur = (CacheVC *)cur->link.next)
+ for (; cur && cur->f.evacuator; cur = (CacheVC *)cur->link.next) {
after = cur;
+ }
ink_assert(evacuator->agg_len <= AGG_SIZE);
agg.insert(evacuator, after);
return aggWrite(event, e);
@@ -578,8 +606,9 @@ int
Vol::evacuateDocReadDone(int event, Event *e)
{
cancel_trigger();
- if (event != AIO_EVENT_DONE)
+ if (event != AIO_EVENT_DONE) {
return EVENT_DONE;
+ }
ink_assert(is_io_in_progress());
set_io_not_in_progress();
ink_assert(mutex->thread_holding == this_ethread());
@@ -597,14 +626,17 @@ Vol::evacuateDocReadDone(int event, Event *e)
b = evacuate[dir_evac_bucket(&doc_evacuator->overwrite_dir)].head;
while (b) {
- if (dir_offset(&b->dir) == dir_offset(&doc_evacuator->overwrite_dir))
+ if (dir_offset(&b->dir) == dir_offset(&doc_evacuator->overwrite_dir)) {
break;
+ }
b = b->link.next;
}
- if (!b)
+ if (!b) {
goto Ldone;
- if ((b->f.pinned && !b->readers) && doc->pinned < (uint32_t)(Thread::get_hrtime() / HRTIME_SECOND))
+ }
+ if ((b->f.pinned && !b->readers) && doc->pinned < (uint32_t)(Thread::get_hrtime() / HRTIME_SECOND)) {
goto Ldone;
+ }
if (dir_head(&b->dir) && b->f.evacuate_head) {
ink_assert(!b->evac_frags.key.fold());
@@ -633,8 +665,9 @@ Vol::evacuateDocReadDone(int event, Event *e)
} else {
// find which key matches the document
EvacuationKey *ek = &b->evac_frags;
- for (; ek && !(ek->key == doc->key); ek = ek->link.next)
+ for (; ek && !(ek->key == doc->key); ek = ek->link.next) {
;
+ }
if (!ek) {
b->f.unused = 77;
goto Ldone;
@@ -674,19 +707,21 @@ Vol::evac_range(off_t low, off_t high, int evac_phase)
for (; b; b = b->link.next) {
int64_t offset = dir_offset(&b->dir);
int phase = dir_phase(&b->dir);
- if (offset >= s && offset < e && !b->f.done && phase == evac_phase)
+ if (offset >= s && offset < e && !b->f.done && phase == evac_phase) {
if (offset < first_offset) {
first = b;
first_offset = offset;
}
+ }
}
if (first) {
first->f.done = 1;
io.aiocb.aio_fildes = fd;
io.aiocb.aio_nbytes = dir_approx_size(&first->dir);
io.aiocb.aio_offset = vol_offset(this, &first->dir);
- if ((off_t)(io.aiocb.aio_offset + io.aiocb.aio_nbytes) > (off_t)(skip + len))
- io.aiocb.aio_nbytes = skip + len - io.aiocb.aio_offset;
+ if ((off_t)(io.aiocb.aio_offset + io.aiocb.aio_nbytes) > (off_t)(skip + len)) {
+ io.aiocb.aio_nbytes = skip + len - io.aiocb.aio_offset;
+ }
doc_evacuator = new_DocEvacuator(io.aiocb.aio_nbytes, this);
doc_evacuator->overwrite_dir = first->dir;
@@ -743,10 +778,11 @@ agg_copy(char *p, CacheVC *vc)
}
if (vc->f.use_first_key) {
- if (doc->data_len() || vc->f.allow_empty_doc)
+ if (doc->data_len() || vc->f.allow_empty_doc) {
doc->key = vc->earliest_key;
- else // the vector is being written by itself
+ } else { // the vector is being written by itself
prev_CacheKey(&doc->key, &vc->earliest_key);
+ }
dir_set_head(&vc->dir, true);
} else {
doc->key = vc->key;
@@ -778,8 +814,9 @@ agg_copy(char *p, CacheVC *vc)
}
ink_assert(!(((uintptr_t)&doc->hdr()[0]) & HDR_PTR_ALIGNMENT_MASK));
ink_assert(vc->header_len == vc->write_vector->marshal(doc->hdr(), vc->header_len));
- } else
+ } else {
memcpy(doc->hdr(), vc->header_to_write, vc->header_len);
+ }
// the single fragment flag is not used in the write call.
// putting it in for completeness.
vc->f.single_fragment = doc->single_fragment();
@@ -791,10 +828,11 @@ agg_copy(char *p, CacheVC *vc)
ink_assert(mutex->thread_holding == this_ethread());
CACHE_DEBUG_SUM_DYN_STAT(cache_write_bytes_stat, vc->write_len);
}
- if (vc->f.rewrite_resident_alt)
+ if (vc->f.rewrite_resident_alt) {
iobufferblock_memcpy(doc->data(), vc->write_len, res_alt_blk, 0);
- else
+ } else {
iobufferblock_memcpy(doc->data(), vc->write_len, vc->blocks.get(), vc->offset);
+ }
#ifdef VERIFY_JTEST_DATA
if (f.use_first_key && header_len) {
int ib = 0, xd = 0;
@@ -809,14 +847,17 @@ agg_copy(char *p, CacheVC *vc)
}
if (cache_config_enable_checksum) {
doc->checksum = 0;
- for (char *b = doc->hdr(); b < (char *)doc + doc->len; b++)
+ for (char *b = doc->hdr(); b < (char *)doc + doc->len; b++) {
doc->checksum += *b;
+ }
}
- if (vc->frag_type == CACHE_FRAG_TYPE_HTTP && vc->f.single_fragment)
+ if (vc->frag_type == CACHE_FRAG_TYPE_HTTP && vc->f.single_fragment) {
ink_assert(doc->hlen);
+ }
- if (res_alt_blk)
+ if (res_alt_blk) {
res_alt_blk->free();
+ }
return vc->agg_len;
} else {
@@ -869,20 +910,25 @@ Vol::evacuate_cleanup()
int64_t s = sx;
int i;
- if (e > evacuate_size)
+ if (e > evacuate_size) {
e = evacuate_size;
- if (sx < 0)
+ }
+ if (sx < 0) {
s = 0;
- for (i = s; i < e; i++)
+ }
+ for (i = s; i < e; i++) {
evacuate_cleanup_blocks(i);
+ }
// if we have wrapped, handle the end bit
if (sx <= 0) {
s = evacuate_size + sx - 2;
- if (s < 0)
+ if (s < 0) {
s = 0;
- for (i = s; i < evacuate_size; i++)
+ }
+ for (i = s; i < evacuate_size; i++) {
evacuate_cleanup_blocks(i);
+ }
}
}
@@ -891,8 +937,9 @@ Vol::periodic_scan()
{
evacuate_cleanup();
scan_for_pinned_documents();
- if (header->write_pos == start)
+ if (header->write_pos == start) {
scan_pos = start;
+ }
scan_pos += len / PIN_SCAN_EVERY;
}
@@ -937,8 +984,9 @@ Lagain:
int writelen = c->agg_len;
// [amc] this is checked multiple places, on here was it strictly less.
ink_assert(writelen <= AGG_SIZE);
- if (agg_buf_pos + writelen > AGG_SIZE || header->write_pos + agg_buf_pos + writelen > (skip + len))
+ if (agg_buf_pos + writelen > AGG_SIZE || header->write_pos + agg_buf_pos + writelen > (skip + len)) {
break;
+ }
DDebug("agg_read", "copying: %d, %" PRIu64 ", key: %d", agg_buf_pos, header->write_pos + agg_buf_pos, c->first_key.slice32(0));
int wrotelen = agg_copy(agg_buffer + agg_buf_pos, c);
ink_assert(writelen == wrotelen);
@@ -948,20 +996,23 @@ Lagain:
agg.dequeue();
if (c->f.sync && c->f.use_first_key) {
CacheVC *last = sync.tail;
- while (last && UINT_WRAP_LT(c->write_serial, last->write_serial))
+ while (last && UINT_WRAP_LT(c->write_serial, last->write_serial)) {
last = (CacheVC *)last->link.prev;
+ }
sync.insert(c, last);
- } else if (c->f.evacuator)
+ } else if (c->f.evacuator) {
c->handleEvent(AIO_EVENT_DONE, nullptr);
- else
+ } else {
tocall.enqueue(c);
+ }
c = n;
}
// if we got nothing...
if (!agg_buf_pos) {
- if (!agg.head && !sync.head) // nothing to get
+ if (!agg.head && !sync.head) { // nothing to get
return EVENT_CONT;
+ }
if (header->write_pos == start) {
// write aggregation too long, bad bad, punt on everything.
Note("write aggregation exceeds vol size");
@@ -969,10 +1020,11 @@ Lagain:
ink_assert(false);
while ((c = agg.dequeue())) {
agg_todo_size -= c->agg_len;
- if (c->initial_thread != nullptr)
+ if (c->initial_thread != nullptr) {
c->initial_thread->schedule_imm_signal(c, AIO_EVENT_DONE);
- else
+ } else {
eventProcessor.schedule_imm_signal(c, ET_CALL, AIO_EVENT_DONE);
+ }
}
return EVENT_CONT;
}
@@ -985,16 +1037,20 @@ Lagain:
// evacuate space
off_t end = header->write_pos + agg_buf_pos + EVACUATION_SIZE;
- if (evac_range(header->write_pos, end, !header->phase) < 0)
+ if (evac_range(header->write_pos, end, !header->phase) < 0) {
goto Lwait;
- if (end > skip + len)
- if (evac_range(start, start + (end - (skip + len)), header->phase) < 0)
+ }
+ if (end > skip + len) {
+ if (evac_range(start, start + (end - (skip + len)), header->phase) < 0) {
goto Lwait;
+ }
+ }
// if agg.head, then we are near the end of the disk, so
// write down the aggregation in whatever size it is.
- if (agg_buf_pos < AGG_HIGH_WATER && !agg.head && !sync.head && !dir_sync_waiting)
+ if (agg_buf_pos < AGG_HIGH_WATER && !agg.head && !sync.head && !dir_sync_waiting) {
goto Lwait;
+ }
// write sync marker
if (!agg_buf_pos) {
@@ -1029,12 +1085,13 @@ Lagain:
Lwait:
int ret = EVENT_CONT;
while ((c = tocall.dequeue())) {
- if (event == EVENT_CALL && c->mutex->thread_holding == mutex->thread_holding)
+ if (event == EVENT_CALL && c->mutex->thread_holding == mutex->thread_holding) {
ret = EVENT_RETURN;
- else if (c->initial_thread != nullptr)
+ } else if (c->initial_thread != nullptr) {
c->initial_thread->schedule_imm_signal(c, AIO_EVENT_DONE);
- else
+ } else {
eventProcessor.schedule_imm_signal(c, ET_CALL, AIO_EVENT_DONE);
+ }
}
return ret;
}
@@ -1051,8 +1108,9 @@ CacheVC::openWriteCloseDir(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED *
VC_SCHED_LOCK_RETRY();
}
vol->close_write(this);
- if (closed < 0 && fragment)
+ if (closed < 0 && fragment) {
dir_delete(&earliest_key, vol, &earliest_dir);
+ }
}
if (is_debug_tag_set("cache_update")) {
if (f.update && closed > 0) {
@@ -1100,17 +1158,20 @@ CacheVC::openWriteCloseDir(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED *
int
CacheVC::openWriteCloseHeadDone(int event, Event *e)
{
- if (event == AIO_EVENT_DONE)
+ if (event == AIO_EVENT_DONE) {
set_io_not_in_progress();
- else if (is_io_in_progress())
+ } else if (is_io_in_progress()) {
return EVENT_CONT;
+ }
{
CACHE_TRY_LOCK(lock, vol->mutex, mutex->thread_holding);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
VC_LOCK_RETRY_EVENT();
+ }
od->writing_vec = false;
- if (!io.ok())
+ if (!io.ok()) {
goto Lclose;
+ }
ink_assert(f.use_first_key);
if (!od->dont_update_directory) {
if (dir_is_empty(&od->first_dir)) {
@@ -1120,8 +1181,9 @@ CacheVC::openWriteCloseHeadDone(int event, Event *e)
dir_overwrite(&first_key, vol, &dir, &od->first_dir, false);
// insert moved resident alternate
if (od->move_resident_alt) {
- if (dir_valid(vol, &od->single_doc_dir))
+ if (dir_valid(vol, &od->single_doc_dir)) {
dir_insert(&od->single_doc_key, vol, &od->single_doc_dir);
+ }
od->move_resident_alt = false;
}
}
@@ -1146,14 +1208,16 @@ CacheVC::openWriteCloseHead(int event, Event *e)
{
cancel_trigger();
f.use_first_key = 1;
- if (io.ok())
+ if (io.ok()) {
ink_assert(fragment || (length == (int64_t)total_len));
- else
+ } else {
return openWriteCloseDir(event, e);
- if (f.data_done)
+ }
+ if (f.data_done) {
write_len = 0;
- else
+ } else {
write_len = length;
+ }
if (frag_type == CACHE_FRAG_TYPE_HTTP) {
SET_HANDLER(&CacheVC::updateVector);
return updateVector(EVENT_IMMEDIATE, nullptr);
@@ -1170,24 +1234,28 @@ CacheVC::openWriteCloseDataDone(int event, Event *e)
int ret = 0;
cancel_trigger();
- if (event == AIO_EVENT_DONE)
+ if (event == AIO_EVENT_DONE) {
set_io_not_in_progress();
- else if (is_io_in_progress())
+ } else if (is_io_in_progress()) {
return EVENT_CONT;
- if (!io.ok())
+ }
+ if (!io.ok()) {
return openWriteCloseDir(event, e);
+ }
{
CACHE_TRY_LOCK(lock, vol->mutex, this_ethread());
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
VC_LOCK_RETRY_EVENT();
+ }
if (!fragment) {
ink_assert(key == earliest_key);
earliest_dir = dir;
} else {
// Store the offset only if there is a table.
// Currently there is no alt (and thence no table) for non-HTTP.
- if (alternate.valid())
+ if (alternate.valid()) {
alternate.push_frag_offset(write_pos);
+ }
}
fragment++;
write_pos += write_len;
@@ -1196,10 +1264,12 @@ CacheVC::openWriteCloseDataDone(int event, Event *e)
next_CacheKey(&key, &key);
if (length) {
write_len = length;
- if (write_len > MAX_FRAG_SIZE)
+ if (write_len > MAX_FRAG_SIZE) {
write_len = MAX_FRAG_SIZE;
- if ((ret = do_write_call()) == EVENT_RETURN)
+ }
+ if ((ret = do_write_call()) == EVENT_RETURN) {
goto Lcallreturn;
+ }
return ret;
}
f.data_done = 1;
@@ -1214,11 +1284,13 @@ CacheVC::openWriteClose(int event, Event *e)
{
cancel_trigger();
if (is_io_in_progress()) {
- if (event != AIO_EVENT_DONE)
+ if (event != AIO_EVENT_DONE) {
return EVENT_CONT;
+ }
set_io_not_in_progress();
- if (!io.ok())
+ if (!io.ok()) {
return openWriteCloseDir(event, e);
+ }
}
if (closed > 0 || f.allow_empty_doc) {
if (total_len == 0) {
@@ -1234,23 +1306,27 @@ CacheVC::openWriteClose(int event, Event *e)
if (length && (fragment || length > MAX_FRAG_SIZE)) {
SET_HANDLER(&CacheVC::openWriteCloseDataDone);
write_len = length;
- if (write_len > MAX_FRAG_SIZE)
+ if (write_len > MAX_FRAG_SIZE) {
write_len = MAX_FRAG_SIZE;
+ }
return do_write_lock_call();
- } else
+ } else {
return openWriteCloseHead(event, e);
- } else
+ }
+ } else {
return openWriteCloseDir(event, e);
+ }
}
int
CacheVC::openWriteWriteDone(int event, Event *e)
{
cancel_trigger();
- if (event == AIO_EVENT_DONE)
+ if (event == AIO_EVENT_DONE) {
set_io_not_in_progress();
- else if (is_io_in_progress())
+ } else if (is_io_in_progress()) {
return EVENT_CONT;
+ }
// In the event of VC_EVENT_ERROR, the cont must do an io_close
if (!io.ok()) {
if (closed) {
@@ -1262,8 +1338,9 @@ CacheVC::openWriteWriteDone(int event, Event *e)
}
{
CACHE_TRY_LOCK(lock, vol->mutex, mutex->thread_holding);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
VC_LOCK_RETRY_EVENT();
+ }
// store the earliest directory. Need to remove the earliest dir
// in case the writer aborts.
if (!fragment) {
@@ -1272,8 +1349,9 @@ CacheVC::openWriteWriteDone(int event, Event *e)
} else {
// Store the offset only if there is a table.
// Currently there is no alt (and thence no table) for non-HTTP.
- if (alternate.valid())
+ if (alternate.valid()) {
alternate.push_frag_offset(write_pos);
+ }
}
++fragment;
write_pos += write_len;
@@ -1282,8 +1360,9 @@ CacheVC::openWriteWriteDone(int event, Event *e)
blocks = iobufferblock_skip(blocks.get(), &offset, &length, write_len);
next_CacheKey(&key, &key);
}
- if (closed)
+ if (closed) {
return die();
+ }
SET_HANDLER(&CacheVC::openWriteMain);
return openWriteMain(event, e);
}
@@ -1302,18 +1381,22 @@ CacheVC::openWriteMain(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
ink_assert(!is_io_in_progress());
Lagain:
if (!vio.buffer.writer()) {
- if (calluser(VC_EVENT_WRITE_READY) == EVENT_DONE)
+ if (calluser(VC_EVENT_WRITE_READY) == EVENT_DONE) {
return EVENT_DONE;
- if (!vio.buffer.writer())
+ }
+ if (!vio.buffer.writer()) {
return EVENT_CONT;
+ }
}
if (vio.ntodo() <= 0) {
called_user = 1;
- if (calluser(VC_EVENT_WRITE_COMPLETE) == EVENT_DONE)
+ if (calluser(VC_EVENT_WRITE_COMPLETE) == EVENT_DONE) {
return EVENT_DONE;
+ }
ink_assert(!f.close_complete || !"close expected after write COMPLETE");
- if (vio.ntodo() <= 0)
+ if (vio.ntodo() <= 0) {
return EVENT_CONT;
+ }
}
int64_t ntodo = (int64_t)(vio.ntodo() + length);
int64_t total_avail = vio.buffer.reader()->read_avail();
@@ -1337,22 +1420,26 @@ Lagain:
total_len += avail;
}
length = (uint64_t)towrite;
- if (length > target_fragment_size() && (length < target_fragment_size() + target_fragment_size() / 4))
+ if (length > target_fragment_size() && (length < target_fragment_size() + target_fragment_size() / 4)) {
write_len = target_fragment_size();
- else
- write_len = length;
+ } else {
+ write_len = length;
+ }
bool not_writing = towrite != ntodo && towrite < target_fragment_size();
if (!called_user) {
if (not_writing) {
called_user = 1;
- if (calluser(VC_EVENT_WRITE_READY) == EVENT_DONE)
+ if (calluser(VC_EVENT_WRITE_READY) == EVENT_DONE) {
return EVENT_DONE;
+ }
goto Lagain;
- } else if (vio.ntodo() <= 0)
+ } else if (vio.ntodo() <= 0) {
goto Lagain;
+ }
}
- if (not_writing)
+ if (not_writing) {
return EVENT_CONT;
+ }
if (towrite == ntodo && f.close_complete) {
closed = 1;
SET_HANDLER(&CacheVC::openWriteClose);
@@ -1368,30 +1455,36 @@ CacheVC::openWriteOverwrite(int event, Event *e)
{
cancel_trigger();
if (event != AIO_EVENT_DONE) {
- if (event == EVENT_IMMEDIATE)
+ if (event == EVENT_IMMEDIATE) {
last_collision = nullptr;
+ }
} else {
Doc *doc = nullptr;
set_io_not_in_progress();
- if (_action.cancelled)
+ if (_action.cancelled) {
return openWriteCloseDir(event, e);
- if (!io.ok())
+ }
+ if (!io.ok()) {
goto Ldone;
+ }
doc = (Doc *)buf->data();
- if (!(doc->first_key == first_key))
+ if (!(doc->first_key == first_key)) {
goto Lcollision;
+ }
od->first_dir = dir;
first_buf = buf;
goto Ldone;
}
Lcollision : {
CACHE_TRY_LOCK(lock, vol->mutex, this_ethread());
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
VC_LOCK_RETRY_EVENT();
+ }
int res = dir_probe(&first_key, vol, &dir, &last_collision);
if (res > 0) {
- if ((res = do_read_call(&first_key)) == EVENT_RETURN)
+ if ((res = do_read_call(&first_key)) == EVENT_RETURN) {
goto Lcallreturn;
+ }
return res;
}
}
@@ -1410,17 +1503,20 @@ CacheVC::openWriteStartDone(int event, Event *e)
intptr_t err = ECACHE_NO_DOC;
cancel_trigger();
if (is_io_in_progress()) {
- if (event != AIO_EVENT_DONE)
+ if (event != AIO_EVENT_DONE) {
return EVENT_CONT;
+ }
set_io_not_in_progress();
}
{
CACHE_TRY_LOCK(lock, vol->mutex, mutex->thread_holding);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
VC_LOCK_RETRY_EVENT();
+ }
- if (_action.cancelled && (!od || !od->has_multiple_writers()))
+ if (_action.cancelled && (!od || !od->has_multiple_writers())) {
goto Lcancel;
+ }
if (event == AIO_EVENT_DONE) { // vector read done
Doc *doc = (Doc *)buf->data();
@@ -1440,8 +1536,9 @@ CacheVC::openWriteStartDone(int event, Event *e)
last_collision = nullptr;
goto Lcollision;
}
- if (!(doc->first_key == first_key))
+ if (!(doc->first_key == first_key)) {
goto Lcollision;
+ }
if (doc->magic != DOC_MAGIC || !doc->hlen || this->load_http_info(write_vector, doc, buf.object()) != doc->hlen) {
err = ECACHE_BAD_META_DATA;
@@ -1464,8 +1561,9 @@ CacheVC::openWriteStartDone(int event, Event *e)
Lcollision:
int if_writers = ((uintptr_t)info == CACHE_ALLOW_MULTIPLE_WRITES);
if (!od) {
- if ((err = vol->open_write(this, if_writers, cache_config_http_max_alts > 1 ? cache_config_http_max_alts : 0)) > 0)
+ if ((err = vol->open_write(this, if_writers, cache_config_http_max_alts > 1 ? cache_config_http_max_alts : 0)) > 0) {
goto Lfailure;
+ }
if (od->has_multiple_writers()) {
MUTEX_RELEASE(lock);
SET_HANDLER(&CacheVC::openWriteMain);
@@ -1476,8 +1574,9 @@ CacheVC::openWriteStartDone(int event, Event *e)
if (dir_probe(&first_key, vol, &dir, &last_collision)) {
od->reading_vec = true;
int ret = do_read_call(&first_key);
- if (ret == EVENT_RETURN)
+ if (ret == EVENT_RETURN) {
goto Lcallreturn;
+ }
return ret;
}
if (f.update) {
@@ -1487,8 +1586,9 @@ CacheVC::openWriteStartDone(int event, Event *e)
}
Lsuccess:
od->reading_vec = false;
- if (_action.cancelled)
+ if (_action.cancelled) {
goto Lcancel;
+ }
SET_HANDLER(&CacheVC::openWriteMain);
return callcont(CACHE_EVENT_OPEN_WRITE);
@@ -1499,8 +1599,9 @@ Lcancel:
if (od) {
od->reading_vec = false;
return openWriteCloseDir(event, e);
- } else
+ } else {
return free_CacheVC(this);
+ }
Lcallreturn:
return handleEvent(AIO_EVENT_DONE, nullptr); // hopefully a tail call
}
@@ -1511,16 +1612,18 @@ CacheVC::openWriteStartBegin(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED
{
intptr_t err;
cancel_trigger();
- if (_action.cancelled)
+ if (_action.cancelled) {
return free_CacheVC(this);
+ }
if (((err = vol->open_write_lock(this, false, 1)) > 0)) {
CACHE_INCREMENT_DYN_STAT(base_stat + CACHE_STAT_FAILURE);
free_CacheVC(this);
_action.continuation->handleEvent(CACHE_EVENT_OPEN_WRITE_FAILED, (void *)-err);
return EVENT_DONE;
}
- if (err < 0)
+ if (err < 0) {
VC_SCHED_LOCK_RETRY();
+ }
if (f.overwrite) {
SET_HANDLER(&CacheVC::openWriteOverwrite);
return openWriteOverwrite(EVENT_IMMEDIATE, nullptr);
@@ -1589,10 +1692,11 @@ Cache::open_write(Continuation *cont, const CacheKey *key, CacheFragType frag_ty
return ACTION_RESULT_DONE;
} else {
SET_CONTINUATION_HANDLER(c, &CacheVC::openWriteOverwrite);
- if (c->openWriteOverwrite(EVENT_IMMEDIATE, nullptr) == EVENT_DONE)
+ if (c->openWriteOverwrite(EVENT_IMMEDIATE, nullptr) == EVENT_DONE) {
return ACTION_RESULT_DONE;
- else
+ } else {
return &c->_action;
+ }
}
}
@@ -1664,21 +1768,24 @@ Cache::open_write(Continuation *cont, const CacheKey *key, CacheHTTPInfo *info,
info->object_key_get(&c->update_key);
ink_assert(!(c->update_key == zero_key));
c->update_len = info->object_size_get();
- } else
+ } else {
c->base_stat = cache_write_active_stat;
+ }
CACHE_INCREMENT_DYN_STAT(c->base_stat + CACHE_STAT_ACTIVE);
c->pin_in_cache = (uint32_t)apin_in_cache;
{
CACHE_TRY_LOCK(lock, c->vol->mutex, cont->mutex->thread_holding);
if (lock.is_locked()) {
- if ((err = c->vol->open_write(c, if_writers, cache_config_http_max_alts > 1 ? cache_config_http_max_alts : 0)) > 0)
+ if ((err = c->vol->open_write(c, if_writers, cache_config_http_max_alts > 1 ? cache_config_http_max_alts : 0)) > 0) {
goto Lfailure;
+ }
// If there are multiple writers, then this one cannot be an update.
// Only the first writer can do an update. If that's the case, we can
// return success to the state machine now.;
- if (c->od->has_multiple_writers())
+ if (c->od->has_multiple_writers()) {
goto Lmiss;
+ }
if (!dir_probe(key, c->vol, &c->dir, &c->last_collision)) {
if (c->f.update) {
// fail update because vector has been GC'd
@@ -1724,7 +1831,8 @@ Lfailure:
return ACTION_RESULT_DONE;
Lcallreturn:
- if (c->handleEvent(AIO_EVENT_DONE, nullptr) == EVENT_DONE)
+ if (c->handleEvent(AIO_EVENT_DONE, nullptr) == EVENT_DONE) {
return ACTION_RESULT_DONE;
+ }
return &c->_action;
}
diff --git a/iocore/cache/RamCacheCLFUS.cc b/iocore/cache/RamCacheCLFUS.cc
index c5bda05..2cee965 100644
--- a/iocore/cache/RamCacheCLFUS.cc
+++ b/iocore/cache/RamCacheCLFUS.cc
@@ -164,8 +164,9 @@ RamCacheCLFUSCompressor::mainEvent(int /* event ATS_UNUSED */, Event *e)
#endif
break;
}
- if (cache_config_ram_cache_compress_percent)
+ if (cache_config_ram_cache_compress_percent) {
rc->compress_entries(e->ethread);
+ }
return EVENT_CONT;
}
@@ -186,8 +187,9 @@ RamCacheCLFUS::resize_hashtable()
if (bucket) {
for (int64_t i = 0; i < nbuckets; i++) {
RamCacheCLFUSEntry *e = nullptr;
- while ((e = bucket[i].pop()))
+ while ((e = bucket[i].pop())) {
new_bucket[e->key.slice32(3) % anbuckets].push(e);
+ }
}
ats_free(bucket);
}
@@ -208,8 +210,9 @@ RamCacheCLFUS::init(int64_t abytes, Vol *avol)
vol = avol;
max_bytes = abytes;
DDebug("ram_cache", "initializing ram_cache %" PRId64 " bytes", abytes);
- if (!max_bytes)
+ if (!max_bytes) {
return;
+ }
resize_hashtable();
if (cache_config_ram_cache_compress) {
eventProcessor.schedule_every(new RamCacheCLFUSCompressor(this), HRTIME_SECOND, ET_TASK);
@@ -243,8 +246,9 @@ check_accounting(RamCacheCLFUS *c)
int
RamCacheCLFUS::get(INK_MD5 *key, Ptr<IOBufferData> *ret_data, uint32_t auxkey1, uint32_t auxkey2)
{
- if (!max_bytes)
+ if (!max_bytes) {
return 0;
+ }
int64_t i = key->slice32(3) % nbuckets;
RamCacheCLFUSEntry *e = bucket[i].head;
char *b = nullptr;
@@ -265,16 +269,18 @@ RamCacheCLFUS::get(INK_MD5 *key, Ptr<IOBufferData> *ret_data, uint32_t auxkey1,
goto Lfailed;
case CACHE_COMPRESSION_FASTLZ: {
int l = (int)e->len;
- if ((l != (int)fastlz_decompress(e->data->data(), e->compressed_len, b, l)))
+ if ((l != (int)fastlz_decompress(e->data->data(), e->compressed_len, b, l))) {
goto Lfailed;
+ }
ram_hit_state = RAM_HIT_COMPRESS_FASTLZ;
break;
}
#ifdef HAVE_ZLIB_H
case CACHE_COMPRESSION_LIBZ: {
uLongf l = e->len;
- if (Z_OK != uncompress((Bytef *)b, &l, (Bytef *)e->data->data(), e->compressed_len))
+ if (Z_OK != uncompress((Bytef *)b, &l, (Bytef *)e->data->data(), e->compressed_len)) {
goto Lfailed;
+ }
ram_hit_state = RAM_HIT_COMPRESS_LIBZ;
break;
}
@@ -284,8 +290,9 @@ RamCacheCLFUS::get(INK_MD5 *key, Ptr<IOBufferData> *ret_data, uint32_t auxkey1,
size_t l = (size_t)e->len, ipos = 0, opos = 0;
uint64_t memlimit = e->len * 2 + LZMA_BASE_MEMLIMIT;
if (LZMA_OK != lzma_stream_buffer_decode(&memlimit, 0, nullptr, (uint8_t *)e->data->data(), &ipos, e->compressed_len,
- (uint8_t *)b, &opos, l))
+ (uint8_t *)b, &opos, l)) {
goto Lfailed;
+ }
ram_hit_state = RAM_HIT_COMPRESS_LIBLZMA;
break;
}
@@ -338,20 +345,24 @@ void
RamCacheCLFUS::tick()
{
RamCacheCLFUSEntry *e = lru[1].dequeue();
- if (!e)
+ if (!e) {
return;
+ }
e->hits >>= 1;
if (e->hits) {
e->hits = REQUEUE_HITS(e->hits);
lru[1].enqueue(e);
- } else
+ } else {
goto Lfree;
- if (history <= objects + HISTORY_HYSTERIA)
+ }
+ if (history <= objects + HISTORY_HYSTERIA) {
return;
+ }
e = lru[1].dequeue();
Lfree:
- if (!e) // e may be nullptr after e= lru[1].dequeue()
+ if (!e) { // e may be nullptr after e= lru[1].dequeue()
return;
+ }
e->flag_bits.lru = 0;
history--;
uint32_t b = e->key.slice32(3) % nbuckets;
@@ -375,9 +386,9 @@ void
RamCacheCLFUS::move_compressed(RamCacheCLFUSEntry *e)
{
if (e == compressed) {
- if (compressed->lru_link.next)
+ if (compressed->lru_link.next) {
compressed = compressed->lru_link.next;
- else {
+ } else {
ncompressed--;
compressed = compressed->lru_link.prev;
}
@@ -395,8 +406,9 @@ RamCacheCLFUS::destroy(RamCacheCLFUSEntry *e)
bytes -= e->size + ENTRY_OVERHEAD;
CACHE_SUM_DYN_STAT_THREAD(cache_ram_cache_bytes_stat, -(int64_t)e->size);
e->data = nullptr;
- } else
+ } else {
history--;
+ }
uint32_t b = e->key.slice32(3) % nbuckets;
bucket[b].remove(e);
DDebug("ram_cache", "put %X %d %d DESTROYED", e->key.slice32(3), e->auxkey1, e->auxkey2);
@@ -407,8 +419,9 @@ RamCacheCLFUS::destroy(RamCacheCLFUSEntry *e)
void
RamCacheCLFUS::compress_entries(EThread *thread, int do_at_most)
{
- if (!cache_config_ram_cache_compress)
+ if (!cache_config_ram_cache_compress) {
return;
+ }
ink_assert(vol != nullptr);
MUTEX_TAKE_LOCK(vol->mutex, thread);
if (!compressed) {
@@ -420,11 +433,13 @@ RamCacheCLFUS::compress_entries(EThread *thread, int do_at_most)
char *b = nullptr, *bb = nullptr;
while (compressed && target > ncompressed) {
RamCacheCLFUSEntry *e = compressed;
- if (e->flag_bits.incompressible || e->flag_bits.compressed)
+ if (e->flag_bits.incompressible || e->flag_bits.compressed) {
goto Lcontinue;
+ }
n++;
- if (do_at_most < n)
+ if (do_at_most < n) {
break;
+ }
{
e->compressed_len = e->size;
uint32_t l = 0;
@@ -457,17 +472,20 @@ RamCacheCLFUS::compress_entries(EThread *thread, int do_at_most)
default:
goto Lfailed;
case CACHE_COMPRESSION_FASTLZ:
- if (e->len < 16)
+ if (e->len < 16) {
goto Lfailed;
- if ((l = fastlz_compress(edata->data(), elen, b)) <= 0)
+ }
+ if ((l = fastlz_compress(edata->data(), elen, b)) <= 0) {
failed = true;
+ }
break;
#ifdef HAVE_ZLIB_H
case CACHE_COMPRESSION_LIBZ: {
uLongf ll = l;
- if ((Z_OK != compress((Bytef *)b, &ll, (Bytef *)edata->data(), elen)))
+ if ((Z_OK != compress((Bytef *)b, &ll, (Bytef *)edata->data(), elen))) {
failed = true;
- l = (int)ll;
+ }
+ l = (int)ll;
break;
}
#endif
@@ -475,9 +493,10 @@ RamCacheCLFUS::compress_entries(EThread *thread, int do_at_most)
case CACHE_COMPRESSION_LIBLZMA: {
size_t pos = 0, ll = l;
if (LZMA_OK != lzma_easy_buffer_encode(LZMA_PRESET_DEFAULT, LZMA_CHECK_NONE, nullptr, (uint8_t *)edata->data(), elen,
- (uint8_t *)b, &pos, ll))
+ (uint8_t *)b, &pos, ll)) {
failed = true;
- l = (int)pos;
+ }
+ l = (int)pos;
break;
}
#endif
@@ -485,13 +504,15 @@ RamCacheCLFUS::compress_entries(EThread *thread, int do_at_most)
MUTEX_TAKE_LOCK(vol->mutex, thread);
// see if the entry is till around
{
- if (failed)
+ if (failed) {
goto Lfailed;
+ }
uint32_t i = key.slice32(3) % nbuckets;
RamCacheCLFUSEntry *ee = bucket[i].head;
while (ee) {
- if (ee->key == key && ee->data == edata)
+ if (ee->key == key && ee->data == edata) {
break;
+ }
ee = ee->hash_link.next;
}
if (!ee || ee != e) {
@@ -500,10 +521,12 @@ RamCacheCLFUS::compress_entries(EThread *thread, int do_at_most)
goto Lcontinue;
}
}
- if (l > REQUIRED_COMPRESSION * e->len)
+ if (l > REQUIRED_COMPRESSION * e->len) {
e->flag_bits.incompressible = true;
- if (l > REQUIRED_SHRINK * e->size)
+ }
+ if (l > REQUIRED_SHRINK * e->size) {
goto Lfailed;
+ }
if (l < e->len) {
e->flag_bits.compressed = cache_config_ram_cache_compress;
bb = (char *)ats_malloc(l);
@@ -536,8 +559,9 @@ RamCacheCLFUS::compress_entries(EThread *thread, int do_at_most)
Lcontinue:;
DDebug("ram_cache", "compress %X %d %d %d %d %d %d %d", e->key.slice32(3), e->auxkey1, e->auxkey2, e->flag_bits.incompressible,
e->flag_bits.compressed, e->len, e->compressed_len, ncompressed);
- if (!e->lru_link.next)
+ if (!e->lru_link.next) {
break;
+ }
compressed = e->lru_link.next;
ncompressed++;
}
@@ -559,17 +583,18 @@ void RamCacheCLFUS::requeue_victims(Que(RamCacheCLFUSEntry, lru_link) & victims)
int
RamCacheCLFUS::put(INK_MD5 *key, IOBufferData *data, uint32_t len, bool copy, uint32_t auxkey1, uint32_t auxkey2)
{
- if (!max_bytes)
+ if (!max_bytes) {
return 0;
+ }
uint32_t i = key->slice32(3) % nbuckets;
RamCacheCLFUSEntry *e = bucket[i].head;
uint32_t size = copy ? len : data->block_size();
double victim_value = 0;
while (e) {
if (e->key == *key) {
- if (e->auxkey1 == auxkey1 && e->auxkey2 == auxkey2)
+ if (e->auxkey1 == auxkey1 && e->auxkey2 == auxkey2) {
break;
- else {
+ } else {
e = destroy(e); // discard when aux keys conflict
continue;
}
@@ -611,9 +636,11 @@ RamCacheCLFUS::put(INK_MD5 *key, IOBufferData *data, uint32_t len, bool copy, ui
Que(RamCacheCLFUSEntry, lru_link) victims;
RamCacheCLFUSEntry *victim = nullptr;
int requeue_limit = REQUEUE_LIMIT;
- if (!lru[1].head) // initial fill
- if (bytes + size <= max_bytes)
+ if (!lru[1].head) { // initial fill
+ if (bytes + size <= max_bytes) {
goto Linsert;
+ }
+ }
if (!e && cache_config_ram_cache_use_seen_filter) {
uint32_t s = key->slice32(3) % bucket_sizes[ibuckets];
uint16_t k = key->slice32(3) >> 16;
@@ -627,10 +654,12 @@ RamCacheCLFUS::put(INK_MD5 *key, IOBufferData *data, uint32_t len, bool copy, ui
while (true) {
victim = lru[0].dequeue();
if (!victim) {
- if (bytes + size <= max_bytes)
+ if (bytes + size <= max_bytes) {
goto Linsert;
- if (e)
+ }
+ if (e) {
lru[1].enqueue(e);
+ }
requeue_victims(victims);
DDebug("ram_cache", "put %X %d %d NO VICTIM", key->slice32(3), auxkey1, auxkey2);
return 0;
@@ -643,15 +672,16 @@ RamCacheCLFUS::put(INK_MD5 *key, IOBufferData *data, uint32_t len, bool copy, ui
bytes -= victim->size + ENTRY_OVERHEAD;
CACHE_SUM_DYN_STAT_THREAD(cache_ram_cache_bytes_stat, -(int64_t)victim->size);
victims.enqueue(victim);
- if (victim == compressed)
+ if (victim == compressed) {
compressed = nullptr;
- else
+ } else {
ncompressed--;
+ }
victim_value += CACHE_VALUE(victim);
tick();
- if (!e)
+ if (!e) {
goto Lhistory;
- else { // e from history
+ } else { // e from history
DDebug("ram_cache_compare", "put %f %f", victim_value, CACHE_VALUE(e));
if (bytes + victim->size + size > max_bytes && victim_value > CACHE_VALUE(e)) {
requeue_victims(victims);
@@ -660,8 +690,9 @@ RamCacheCLFUS::put(INK_MD5 *key, IOBufferData *data, uint32_t len, bool copy, ui
return 0;
}
}
- if (bytes + size <= max_bytes)
+ if (bytes + size <= max_bytes) {
goto Linsert;
+ }
}
Linsert:
while ((victim = victims.dequeue())) {
@@ -670,8 +701,9 @@ Linsert:
CACHE_SUM_DYN_STAT_THREAD(cache_ram_cache_bytes_stat, victim->size);
victim->hits = REQUEUE_HITS(victim->hits);
lru[0].enqueue(victim);
- } else
+ } else {
victimize(victim);
+ }
}
if (e) {
history--; // move from history
@@ -689,9 +721,9 @@ Linsert:
}
check_accounting(this);
e->flags = 0;
- if (!copy)
+ if (!copy) {
e->data = data;
- else {
+ } else {
char *b = (char *)ats_malloc(len);
memcpy(b, data->data(), len);
e->data = new_xmalloc_IOBufferData(b, len);
@@ -728,8 +760,9 @@ Lhistory:
int
RamCacheCLFUS::fixup(const INK_MD5 *key, uint32_t old_auxkey1, uint32_t old_auxkey2, uint32_t new_auxkey1, uint32_t new_auxkey2)
{
- if (!max_bytes)
+ if (!max_bytes) {
return 0;
+ }
uint32_t i = key->slice32(3) % nbuckets;
RamCacheCLFUSEntry *e = bucket[i].head;
while (e) {
diff --git a/iocore/cache/RamCacheLRU.cc b/iocore/cache/RamCacheLRU.cc
index 37724c8..38fa7f0 100644
--- a/iocore/cache/RamCacheLRU.cc
+++ b/iocore/cache/RamCacheLRU.cc
@@ -89,8 +89,9 @@ RamCacheLRU::resize_hashtable()
if (bucket) {
for (int64_t i = 0; i < nbuckets; i++) {
RamCacheLRUEntry *e = nullptr;
- while ((e = bucket[i].pop()))
+ while ((e = bucket[i].pop())) {
new_bucket[e->key.slice32(3) % anbuckets].push(e);
+ }
}
ats_free(bucket);
}
@@ -110,16 +111,18 @@ RamCacheLRU::init(int64_t abytes, Vol *avol)
vol = avol;
max_bytes = abytes;
DDebug("ram_cache", "initializing ram_cache %" PRId64 " bytes", abytes);
- if (!max_bytes)
+ if (!max_bytes) {
return;
+ }
resize_hashtable();
}
int
RamCacheLRU::get(INK_MD5 *key, Ptr<IOBufferData> *ret_data, uint32_t auxkey1, uint32_t auxkey2)
{
- if (!max_bytes)
+ if (!max_bytes) {
return 0;
+ }
uint32_t i = key->slice32(3) % nbuckets;
RamCacheLRUEntry *e = bucket[i].head;
while (e) {
@@ -158,8 +161,9 @@ RamCacheLRU::remove(RamCacheLRUEntry *e)
int
RamCacheLRU::put(INK_MD5 *key, IOBufferData *data, uint32_t len, bool, uint32_t auxkey1, uint32_t auxkey2)
{
- if (!max_bytes)
+ if (!max_bytes) {
return 0;
+ }
uint32_t i = key->slice32(3) % nbuckets;
if (cache_config_ram_cache_use_seen_filter) {
uint16_t k = key->slice32(3) >> 16;
@@ -196,10 +200,11 @@ RamCacheLRU::put(INK_MD5 *key, IOBufferData *data, uint32_t len, bool, uint32_t
CACHE_SUM_DYN_STAT_THREAD(cache_ram_cache_bytes_stat, ENTRY_OVERHEAD + data->block_size());
while (bytes > max_bytes) {
RamCacheLRUEntry *ee = lru.dequeue();
- if (ee)
+ if (ee) {
remove(ee);
- else
+ } else {
break;
+ }
}
DDebug("ram_cache", "put %X %d %d INSERTED", key->slice32(3), auxkey1, auxkey2);
if (objects > nbuckets) {
@@ -212,8 +217,9 @@ RamCacheLRU::put(INK_MD5 *key, IOBufferData *data, uint32_t len, bool, uint32_t
int
RamCacheLRU::fixup(const INK_MD5 *key, uint32_t old_auxkey1, uint32_t old_auxkey2, uint32_t new_auxkey1, uint32_t new_auxkey2)
{
- if (!max_bytes)
+ if (!max_bytes) {
return 0;
+ }
uint32_t i = key->slice32(3) % nbuckets;
RamCacheLRUEntry *e = bucket[i].head;
while (e) {
diff --git a/iocore/cache/Store.cc b/iocore/cache/Store.cc
index 54ea293..cb41c26 100644
--- a/iocore/cache/Store.cc
+++ b/iocore/cache/Store.cc
@@ -101,14 +101,17 @@ Store::free(Store &s)
{
for (unsigned i = 0; i < s.n_disks; i++) {
for (Span *sd = s.disk[i]; sd; sd = sd->link.next) {
- for (unsigned j = 0; j < n_disks; j++)
- for (Span *d = disk[j]; d; d = d->link.next)
+ for (unsigned j = 0; j < n_disks; j++) {
+ for (Span *d = disk[j]; d; d = d->link.next) {
if (!strcmp(sd->pathname, d->pathname)) {
- if (sd->offset < d->offset)
+ if (sd->offset < d->offset) {
d->offset = sd->offset;
+ }
d->blocks += sd->blocks;
goto Lfound;
}
+ }
+ }
ink_release_assert(!"Store::free failed");
Lfound:;
}
@@ -178,8 +181,9 @@ Store::sort()
if (!sd->file_pathname) {
sd->blocks += next->blocks;
} else if (next->offset <= sd->end()) {
- if (next->end() >= sd->end())
+ if (next->end() >= sd->end()) {
sd->blocks += (next->end() - sd->end());
+ }
} else {
sd = next;
continue;
@@ -187,8 +191,9 @@ Store::sort()
sd->link.next = next->link.next;
delete next;
sd = sd->link.next;
- } else
+ } else {
sd = next;
+ }
}
}
}
@@ -221,8 +226,9 @@ Span::path(char *filename, int64_t *aoffset, char *buf, int buflen)
ink_assert(!aoffset);
Span *ds = this;
- if ((strlen(ds->pathname) + strlen(filename) + 2) > (size_t)buflen)
+ if ((strlen(ds->pathname) + strlen(filename) + 2) > (size_t)buflen) {
return -1;
+ }
if (!ds->file_pathname) {
ink_filepath_make(buf, buflen, ds->pathname, filename);
} else {
@@ -248,8 +254,9 @@ void
Store::delete_all()
{
for (unsigned i = 0; i < n_disks; i++) {
- if (disk[i])
+ if (disk[i]) {
delete disk[i];
+ }
}
n_disks = 0;
ats_free(disk);
@@ -263,16 +270,18 @@ Store::~Store()
Span::~Span()
{
- if (link.next)
+ if (link.next) {
delete link.next;
+ }
}
static int
get_int64(int fd, int64_t &data)
{
char buf[PATH_NAME_MAX];
- if (ink_file_fd_readline(fd, PATH_NAME_MAX, buf) <= 0)
+ if (ink_file_fd_readline(fd, PATH_NAME_MAX, buf) <= 0) {
return (-1);
+ }
// the above line will guarantee buf to be no longer than PATH_NAME_MAX
// so the next statement should be a safe use of sscanf
// coverity[secure_coding]
@@ -292,10 +301,11 @@ Lagain:
for (Span *sd = disk[i]; sd; sd = sd->link.next) {
if (!strcmp(n, sd->pathname)) {
found = true;
- if (p)
+ if (p) {
p->link.next = sd->link.next;
- else
- disk[i] = sd->link.next;
+ } else {
+ disk[i] = sd->link.next;
+ }
sd->link.next = nullptr;
delete sd;
goto Lagain;
@@ -336,16 +346,18 @@ Store::read_config()
++ln;
// Because the SimpleTokenizer is a bit too simple, we have to normalize whitespace.
- for (char *spot = line, *limit = line + len; spot < limit; ++spot)
- if (ParseRules::is_space(*spot))
+ for (char *spot = line, *limit = line + len; spot < limit; ++spot) {
+ if (ParseRules::is_space(*spot)) {
*spot = ' '; // force whitespace to literal space.
-
+ }
+ }
SimpleTokenizer tokens(line, ' ', SimpleTokenizer::OVERWRITE_INPUT_STRING);
// skip comments and blank lines
path = tokens.getNext();
- if (nullptr == path || '#' == path[0])
+ if (nullptr == path || '#' == path[0]) {
continue;
+ }
// parse
Debug("cache_init", "Store::read_config: \"%s\"", path);
@@ -362,14 +374,17 @@ Store::read_config()
}
} else if (0 == strncasecmp(HASH_BASE_STRING_KEY, e, sizeof(HASH_BASE_STRING_KEY) - 1)) {
e += sizeof(HASH_BASE_STRING_KEY) - 1;
- if ('=' == *e)
+ if ('=' == *e) {
++e;
- if (*e && !ParseRules::is_space(*e))
+ }
+ if (*e && !ParseRules::is_space(*e)) {
seed = e;
+ }
} else if (0 == strncasecmp(VOLUME_KEY, e, sizeof(VOLUME_KEY) - 1)) {
e += sizeof(VOLUME_KEY) - 1;
- if ('=' == *e)
+ if ('=' == *e) {
++e;
+ }
if (!*e || !ParseRules::is_digit(*e) || 0 >= (volume_num = ink_atoi(e))) {
delete sd;
return Result::failure("failed to parse volume number '%s'", e);
@@ -394,19 +409,22 @@ Store::read_config()
n_dsstore++;
// Set side values if present.
- if (seed)
+ if (seed) {
ns->hash_base_string_set(seed);
- if (volume_num > 0)
+ }
+ if (volume_num > 0) {
ns->volume_number_set(volume_num);
+ }
// new Span
{
Span *prev = cur;
cur = ns;
- if (!sd)
+ if (!sd) {
sd = cur;
- else
+ } else {
prev->link.next = cur;
+ }
}
}
@@ -428,13 +446,15 @@ Store::read_config()
int
Store::write_config_data(int fd) const
{
- for (unsigned i = 0; i < n_disks; i++)
+ for (unsigned i = 0; i < n_disks; i++) {
for (Span *sd = disk[i]; sd; sd = sd->link.next) {
char buf[PATH_NAME_MAX + 64];
snprintf(buf, sizeof(buf), "%s %" PRId64 "\n", sd->pathname.get(), (int64_t)sd->blocks * (int64_t)STORE_BLOCK_SIZE);
- if (ink_file_fd_writestring(fd, buf) == -1)
+ if (ink_file_fd_writestring(fd, buf) == -1) {
return (-1);
+ }
}
+ }
return 0;
}
@@ -582,8 +602,9 @@ Store::normalize()
{
unsigned ndisks = 0;
for (unsigned i = 0; i < n_disks; i++) {
- if (disk[i])
+ if (disk[i]) {
disk[ndisks++] = disk[i];
+ }
}
n_disks = ndisks;
}
@@ -596,27 +617,31 @@ try_alloc(Store &target, Span *source, unsigned int start_blocks, bool one_only
while (source && blocks) {
if (source->blocks) {
unsigned int a; // allocated
- if (blocks > source->blocks)
+ if (blocks > source->blocks) {
a = source->blocks;
- else
- a = blocks;
+ } else {
+ a = blocks;
+ }
Span *d = new Span(*source);
d->blocks = a;
d->link.next = ds;
- if (d->file_pathname)
+ if (d->file_pathname) {
source->offset += a;
+ }
source->blocks -= a;
ds = d;
blocks -= a;
- if (one_only)
+ if (one_only) {
break;
+ }
}
source = source->link.next;
}
- if (ds)
+ if (ds) {
target.add(ds);
+ }
return start_blocks - blocks;
}
@@ -647,8 +672,9 @@ Store::spread_alloc(Store &s, unsigned int blocks, bool mmapable)
for (unsigned i = 0; blocks && disks_left && i < n_disks; i++) {
if (!(mmapable && !disk[i]->is_mmapable())) {
unsigned int target = blocks / disks_left;
- if (blocks - target > total_blocks(i + 1))
+ if (blocks - target > total_blocks(i + 1)) {
target = blocks - total_blocks(i + 1);
+ }
blocks -= try_alloc(s, disk[i], target);
disks_left--;
}
@@ -661,8 +687,8 @@ Store::try_realloc(Store &s, Store &diff)
for (unsigned i = 0; i < s.n_disks; i++) {
Span *prev = nullptr;
for (Span *sd = s.disk[i]; sd;) {
- for (unsigned j = 0; j < n_disks; j++)
- for (Span *d = disk[j]; d; d = d->link.next)
+ for (unsigned j = 0; j < n_disks; j++) {
+ for (Span *d = disk[j]; d; d = d->link.next) {
if (!strcmp(sd->pathname, d->pathname)) {
if (sd->offset >= d->offset && (sd->end() <= d->end())) {
if (!sd->file_pathname || (sd->end() == d->end())) {
@@ -684,11 +710,14 @@ Store::try_realloc(Store &s, Store &diff)
}
}
}
+ }
+ }
{
- if (!prev)
+ if (!prev) {
s.disk[i] = s.disk[i]->link.next;
- else
+ } else {
prev->link.next = sd->link.next;
+ }
diff.extend(i + 1);
sd->link.next = diff.disk[i];
diff.disk[i] = sd;
@@ -715,8 +744,9 @@ Store::alloc(Store &s, unsigned int blocks, bool one_only, bool mmapable)
for (unsigned i = 0; blocks && i < n_disks; i++) {
if (!(mmapable && !disk[i]->is_mmapable())) {
blocks -= try_alloc(s, disk[i], blocks, one_only);
- if (one_only && oblocks != blocks)
+ if (one_only && oblocks != blocks) {
break;
+ }
}
}
}
@@ -726,26 +756,32 @@ Span::write(int fd) const
{
char buf[32];
- if (ink_file_fd_writestring(fd, (pathname ? pathname.get() : ")")) == -1)
+ if (ink_file_fd_writestring(fd, (pathname ? pathname.get() : ")")) == -1) {
return (-1);
- if (ink_file_fd_writestring(fd, "\n") == -1)
+ }
+ if (ink_file_fd_writestring(fd, "\n") == -1) {
return (-1);
+ }
snprintf(buf, sizeof(buf), "%" PRId64 "\n", blocks);
- if (ink_file_fd_writestring(fd, buf) == -1)
+ if (ink_file_fd_writestring(fd, buf) == -1) {
return (-1);
+ }
snprintf(buf, sizeof(buf), "%d\n", file_pathname);
- if (ink_file_fd_writestring(fd, buf) == -1)
+ if (ink_file_fd_writestring(fd, buf) == -1) {
return (-1);
+ }
snprintf(buf, sizeof(buf), "%" PRId64 "\n", offset);
- if (ink_file_fd_writestring(fd, buf) == -1)
+ if (ink_file_fd_writestring(fd, buf) == -1) {
return (-1);
+ }
snprintf(buf, sizeof(buf), "%d\n", (int)is_mmapable());
- if (ink_file_fd_writestring(fd, buf) == -1)
+ if (ink_file_fd_writestring(fd, buf) == -1) {
return (-1);
+ }
return 0;
}
@@ -755,14 +791,17 @@ Store::write(int fd, const char *name) const
{
char buf[32];
- if (ink_file_fd_writestring(fd, name) == -1)
+ if (ink_file_fd_writestring(fd, name) == -1) {
return (-1);
- if (ink_file_fd_writestring(fd, "\n") == -1)
+ }
+ if (ink_file_fd_writestring(fd, "\n") == -1) {
return (-1);
+ }
snprintf(buf, sizeof(buf), "%d\n", n_disks);
- if (ink_file_fd_writestring(fd, buf) == -1)
+ if (ink_file_fd_writestring(fd, buf) == -1) {
return (-1);
+ }
for (unsigned i = 0; i < n_disks; i++) {
int n = 0;
@@ -772,12 +811,14 @@ Store::write(int fd, const char *name) const
}
snprintf(buf, sizeof(buf), "%d\n", n);
- if (ink_file_fd_writestring(fd, buf) == -1)
+ if (ink_file_fd_writestring(fd, buf) == -1) {
return (-1);
+ }
for (sd = disk[i]; sd; sd = sd->link.next) {
- if (sd->write(fd))
+ if (sd->write(fd)) {
return -1;
+ }
}
}
return 0;
@@ -788,8 +829,9 @@ Span::read(int fd)
{
char buf[PATH_NAME_MAX], p[PATH_NAME_MAX];
- if (ink_file_fd_readline(fd, PATH_NAME_MAX, buf) <= 0)
+ if (ink_file_fd_readline(fd, PATH_NAME_MAX, buf) <= 0) {
return (-1);
+ }
// the above line will guarantee buf to be no longer than PATH_NAME_MAX
// so the next statement should be a safe use of sscanf
// coverity[secure_coding]
@@ -802,13 +844,15 @@ Span::read(int fd)
}
int b = 0;
- if (ink_file_fd_readline(fd, PATH_NAME_MAX, buf) <= 0)
+ if (ink_file_fd_readline(fd, PATH_NAME_MAX, buf) <= 0) {
return (-1);
+ }
// the above line will guarantee buf to be no longer than PATH_NAME_MAX
// so the next statement should be a safe use of sscanf
// coverity[secure_coding]
- if (sscanf(buf, "%d", &b) != 1)
+ if (sscanf(buf, "%d", &b) != 1) {
return (-1);
+ }
file_pathname = (b ? true : false);
if (get_int64(fd, offset) < 0) {
@@ -816,13 +860,15 @@ Span::read(int fd)
}
int tmp;
- if (ink_file_fd_readline(fd, PATH_NAME_MAX, buf) <= 0)
+ if (ink_file_fd_readline(fd, PATH_NAME_MAX, buf) <= 0) {
return (-1);
+ }
// the above line will guarantee buf to be no longer than PATH_NAME_MAX
// so the next statement should be a safe use of sscanf
// coverity[secure_coding]
- if (sscanf(buf, "%d", &tmp) != 1)
+ if (sscanf(buf, "%d", &tmp) != 1) {
return (-1);
+ }
set_mmapable(tmp != 0);
return (0);
@@ -834,58 +880,69 @@ Store::read(int fd, char *aname)
char *name = aname;
char tname[PATH_NAME_MAX];
char buf[PATH_NAME_MAX];
- if (!aname)
+ if (!aname) {
name = tname;
+ }
- if (ink_file_fd_readline(fd, PATH_NAME_MAX, buf) <= 0)
+ if (ink_file_fd_readline(fd, PATH_NAME_MAX, buf) <= 0) {
return (-1);
+ }
// the above line will guarantee buf to be no longer than PATH_NAME_MAX
// so the next statement should be a safe use of sscanf
// coverity[secure_coding]
- if (sscanf(buf, "%s\n", name) != 1)
+ if (sscanf(buf, "%s\n", name) != 1) {
return (-1);
+ }
- if (ink_file_fd_readline(fd, PATH_NAME_MAX, buf) <= 0)
+ if (ink_file_fd_readline(fd, PATH_NAME_MAX, buf) <= 0) {
return (-1);
+ }
// the above line will guarantee buf to be no longer than PATH_NAME_MAX
// so the next statement should be a safe use of sscanf
// coverity[secure_coding]
- if (sscanf(buf, "%d\n", &n_disks) != 1)
+ if (sscanf(buf, "%d\n", &n_disks) != 1) {
return (-1);
+ }
disk = (Span **)ats_malloc(sizeof(Span *) * n_disks);
- if (!disk)
+ if (!disk) {
return -1;
+ }
memset(disk, 0, sizeof(Span *) * n_disks);
for (unsigned i = 0; i < n_disks; i++) {
int n = 0;
- if (ink_file_fd_readline(fd, PATH_NAME_MAX, buf) <= 0)
+ if (ink_file_fd_readline(fd, PATH_NAME_MAX, buf) <= 0) {
return (-1);
+ }
// the above line will guarantee buf to be no longer than PATH_NAME_MAX
// so the next statement should be a safe use of sscanf
// coverity[secure_coding]
- if (sscanf(buf, "%d\n", &n) != 1)
+ if (sscanf(buf, "%d\n", &n) != 1) {
return (-1);
+ }
Span *sd = nullptr;
while (n--) {
Span *last = sd;
sd = new Span;
- if (!last)
+ if (!last) {
disk[i] = sd;
- else
+ } else {
last->link.next = sd;
- if (sd->read(fd))
+ }
+ if (sd->read(fd)) {
goto Lbail;
+ }
}
}
return 0;
Lbail:
for (unsigned i = 0; i < n_disks; i++) {
- if (disk[i])
+ if (disk[i]) {
delete disk[i];
+ }
}
return -1;
}
@@ -894,8 +951,9 @@ Span *
Span::dup()
{
Span *ds = new Span(*this);
- if (this->link.next)
+ if (this->link.next) {
ds->link.next = this->link.next->dup();
+ }
return ds;
}
@@ -919,19 +977,23 @@ Store::clear(char *filename, bool clear_dirs)
for (unsigned j = 0; j < disk[i]->paths(); j++) {
char path[PATH_NAME_MAX];
Span *d = ds->nth(j);
- if (!clear_dirs && !d->file_pathname)
+ if (!clear_dirs && !d->file_pathname) {
continue;
+ }
int r = d->path(filename, nullptr, path, PATH_NAME_MAX);
- if (r < 0)
+ if (r < 0) {
return -1;
+ }
int fd = ::open(path, O_RDWR | O_CREAT, 0644);
- if (fd < 0)
+ if (fd < 0) {
return -1;
- for (int b = 0; d->blocks; b++)
+ }
+ for (int b = 0; d->blocks; b++) {
if (socketManager.pwrite(fd, z, STORE_BLOCK_SIZE, d->offset + (b * STORE_BLOCK_SIZE)) < 0) {
close(fd);
return -1;
}
+ }
close(fd);
}
}
diff --git a/iocore/dns/DNS.cc b/iocore/dns/DNS.cc
index 454ee00..8ec00f4 100644
--- a/iocore/dns/DNS.cc
+++ b/iocore/dns/DNS.cc
@@ -96,8 +96,9 @@ char try_server_names[DEFAULT_NUM_TRY_SERVER][MAXDNAME];
static inline char *
strnchr(char *s, char c, int len)
{
- while (*s && *s != c && len)
+ while (*s && *s != c && len) {
++s, --len;
+ }
return *s == c ? s : (char *)nullptr;
}
@@ -122,30 +123,38 @@ make_ipv4_ptr(in_addr_t addr, char *buffer)
char *p = buffer;
uint8_t const *u = reinterpret_cast<uint8_t *>(&addr);
- if (u[3] > 99)
+ if (u[3] > 99) {
*p++ = (u[3] / 100) + '0';
- if (u[3] > 9)
+ }
+ if (u[3] > 9) {
*p++ = ((u[3] / 10) % 10) + '0';
- *p++ = u[3] % 10 + '0';
- *p++ = '.';
- if (u[2] > 99)
+ }
+ *p++ = u[3] % 10 + '0';
+ *p++ = '.';
+ if (u[2] > 99) {
*p++ = (u[2] / 100) + '0';
- if (u[2] > 9)
+ }
+ if (u[2] > 9) {
*p++ = ((u[2] / 10) % 10) + '0';
- *p++ = u[2] % 10 + '0';
- *p++ = '.';
- if (u[1] > 99)
+ }
+ *p++ = u[2] % 10 + '0';
+ *p++ = '.';
+ if (u[1] > 99) {
*p++ = (u[1] / 100) + '0';
- if (u[1] > 9)
+ }
+ if (u[1] > 9) {
*p++ = ((u[1] / 10) % 10) + '0';
- *p++ = u[1] % 10 + '0';
- *p++ = '.';
- if (u[0] > 99)
+ }
+ *p++ = u[1] % 10 + '0';
+ *p++ = '.';
+ if (u[0] > 99) {
*p++ = (u[0] / 100) + '0';
- if (u[0] > 9)
+ }
+ if (u[0] > 9) {
*p++ = ((u[0] / 10) % 10) + '0';
- *p++ = u[0] % 10 + '0';
- *p++ = '.';
+ }
+ *p++ = u[0] % 10 + '0';
+ *p++ = '.';
ink_strlcpy(p, "in-addr.arpa", MAXDNAME - (p - buffer + 1));
}
@@ -225,13 +234,15 @@ DNSProcessor::open(sockaddr const *target)
ats_ip_copy(&h->local_ipv4.sa, &local_ipv4.sa);
ats_ip_copy(&h->local_ipv6.sa, &local_ipv6.sa);
- if (target)
+ if (target) {
ats_ip_copy(&h->ip, target);
- else
+ } else {
ats_ip_invalidate(&h->ip); // marked to use default.
+ }
- if (!dns_handler_initialized)
+ if (!dns_handler_initialized) {
handler = h;
+ }
SET_CONTINUATION_HANDLER(h, &DNSHandler::startEvent);
thread->schedule_imm(h);
@@ -266,14 +277,16 @@ DNSProcessor::dns_init()
if ('[' == *ns) {
char *ndx = strchr(ns + 1, ']');
if (ndx) {
- if (':' == ndx[1])
+ if (':' == ndx[1]) {
colon = ndx + 1;
+ }
} else {
err = true;
Warning("Unmatched '[' in address for nameserver '%s', discarding.", ns);
}
- } else
+ } else {
colon = strchr(ns, ':');
+ }
if (!err && colon) {
*colon = '\0';
@@ -306,8 +319,9 @@ DNSProcessor::dns_init()
}
// The default domain (5th param) and search list (6th param) will
// come from /etc/resolv.conf.
- if (ink_res_init(&l_res, nameserver, nserv, dns_search, nullptr, nullptr, dns_resolv_conf) < 0)
+ if (ink_res_init(&l_res, nameserver, nserv, dns_search, nullptr, nullptr, dns_resolv_conf) < 0) {
Warning("Failed to build DNS res records for the servers (%s). Using resolv.conf.", dns_ns_list);
+ }
// Check for local forced bindings.
@@ -396,12 +410,13 @@ DNSEntry::init(const char *x, int len, int qtype_arg, Continuation *acont, DNSPr
}
} else { // T_PTR
IpAddr const *ip = reinterpret_cast<IpAddr const *>(x);
- if (ip->isIp6())
+ if (ip->isIp6()) {
make_ipv6_ptr(&ip->_addr._ip6, qname);
- else if (ip->isIp4())
+ } else if (ip->isIp4()) {
make_ipv4_ptr(ip->_addr._ip4, qname);
- else
+ } else {
ink_assert(!"T_PTR query to DNS must be IP address.");
+ }
}
SET_HANDLER((DNSEntryHandler)&DNSEntry::mainEvent);
@@ -441,10 +456,11 @@ DNSHandler::open_con(sockaddr const *target, bool failed, int icon)
.setLocalIpv4(&local_ipv4.sa)) < 0) {
Debug("dns", "opening connection %s FAILED for %d", ip_text, icon);
if (!failed) {
- if (dns_ns_rr)
+ if (dns_ns_rr) {
rr_failure(icon);
- else
+ } else {
failover();
+ }
}
return;
} else {
@@ -493,9 +509,10 @@ DNSHandler::startEvent(int /* event ATS_UNUSED */, Event *e)
SET_HANDLER(&DNSHandler::mainEvent);
if (dns_ns_rr) {
int max_nscount = m_res->nscount;
- if (max_nscount > MAX_NAMED)
+ if (max_nscount > MAX_NAMED) {
max_nscount = MAX_NAMED;
- n_con = 0;
+ }
+ n_con = 0;
for (int i = 0; i < max_nscount; i++) {
ip_port_text_buffer buff;
sockaddr *sa = &m_res->nsaddr_list[i].sa;
@@ -591,10 +608,11 @@ DNSHandler::try_primary_named(bool reopen)
int r = _ink_res_mkquery(m_res, try_server_names[try_servers], T_A, buffer);
// if try_server_names[] is not full, round-robin within the
// filled entries.
- if (local_num_entries < DEFAULT_NUM_TRY_SERVER)
+ if (local_num_entries < DEFAULT_NUM_TRY_SERVER) {
try_servers = (try_servers + 1) % local_num_entries;
- else
+ } else {
try_servers = (try_servers + 1) % countof(try_server_names);
+ }
ink_assert(r >= 0);
if (r >= 0) { // looking for a bounce
int res = socketManager.send(con[0].fd, buffer, r, 0);
@@ -608,8 +626,9 @@ DNSHandler::switch_named(int ndx)
{
for (DNSEntry *e = entries.head; e; e = (DNSEntry *)e->link.next) {
e->written_flag = false;
- if (e->retries < dns_retries)
+ if (e->retries < dns_retries) {
++(e->retries); // give them another chance
+ }
}
in_flight = 0;
received_one(ndx); // reset failover counters
@@ -625,8 +644,9 @@ DNSHandler::failover()
ip_text_buffer buff1, buff2;
int max_nscount = m_res->nscount;
- if (max_nscount > MAX_NAMED)
- max_nscount = MAX_NAMED;
+ if (max_nscount > MAX_NAMED) {
+ max_nscount = MAX_NAMED;
+ }
sockaddr const *old_addr = &m_res->nsaddr_list[name_server].sa;
name_server = (name_server + 1) % max_nscount;
Debug("dns", "failover: failing over to name_server=%d", name_server);
@@ -637,12 +657,14 @@ DNSHandler::failover()
Warning("failover: connection to DNS server %s lost, move to %s", ats_ip_ntop(old_addr, buff1, sizeof(buff1)),
ats_ip_ntop(&target.sa, buff2, sizeof(buff2)));
- if (!target.isValid())
+ if (!target.isValid()) {
target.setToLoopback(AF_INET);
+ }
open_con(&target.sa, true, name_server);
- if (n_con <= name_server)
+ if (n_con <= name_server) {
n_con = name_server + 1;
+ }
switch_named(name_server);
} else {
ip_text_buffer buff;
@@ -664,8 +686,9 @@ DNSHandler::rr_failure(int ndx)
}
int nscount = m_res->nscount;
- if (nscount > MAX_NAMED)
+ if (nscount > MAX_NAMED) {
nscount = MAX_NAMED;
+ }
// See if all nameservers are down
int all_down = 1;
@@ -683,8 +706,9 @@ DNSHandler::rr_failure(int ndx)
// mark any outstanding requests as not sent for later retry
for (DNSEntry *e = entries.head; e; e = (DNSEntry *)e->link.next) {
e->written_flag = false;
- if (e->retries < dns_retries)
+ if (e->retries < dns_retries) {
++(e->retries); // give them another chance
+ }
--in_flight;
DNS_DECREMENT_DYN_STAT(dns_in_flight_stat);
}
@@ -693,8 +717,9 @@ DNSHandler::rr_failure(int ndx)
for (DNSEntry *e = entries.head; e; e = (DNSEntry *)e->link.next) {
if (e->which_ns == ndx) {
e->written_flag = false;
- if (e->retries < dns_retries)
+ if (e->retries < dns_retries) {
++(e->retries); // give them another chance
+ }
--in_flight;
DNS_DECREMENT_DYN_STAT(dns_in_flight_stat);
}
@@ -732,20 +757,23 @@ DNSHandler::recv_dns(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
IpEndpoint from_ip;
socklen_t from_length = sizeof(from_ip);
- if (!hostent_cache)
+ if (!hostent_cache) {
hostent_cache = dnsBufAllocator.alloc();
- HostEnt *buf = hostent_cache;
+ }
+ HostEnt *buf = hostent_cache;
int res = socketManager.recvfrom(dnsc->fd, buf->buf, MAX_DNS_PACKET_LEN, 0, &from_ip.sa, &from_length);
- if (res == -EAGAIN)
+ if (res == -EAGAIN) {
break;
+ }
if (res <= 0) {
Debug("dns", "named error: %d", res);
- if (dns_ns_rr)
+ if (dns_ns_rr) {
rr_failure(dnsc->num);
- else if (dnsc->num == name_server)
+ } else if (dnsc->num == name_server) {
failover();
+ }
break;
}
@@ -772,17 +800,19 @@ DNSHandler::recv_dns(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
if (!dnsc->num) {
Debug("dns", "primary DNS response code = %d", get_rcode(buf));
if (good_rcode(buf->buf)) {
- if (name_server)
+ if (name_server) {
recover();
- else
+ } else {
received_one(name_server);
+ }
}
}
}
Ptr<HostEnt> protect_hostent = make_ptr(buf);
if (dns_process(this, buf, res)) {
- if (dnsc->num == name_server)
+ if (dnsc->num == name_server) {
received_one(name_server);
+ }
}
}
}
@@ -807,9 +837,9 @@ DNSHandler::mainEvent(int event, Event *e)
for (int i = 0; i < n_con; i++) {
if (!ns_down[i] && failover_soon(i)) {
Debug("dns", "mainEvent: nameserver = %d failover soon", name_server);
- if (failover_now(i))
+ if (failover_now(i)) {
rr_failure(i);
- else {
+ } else {
Debug("dns", "mainEvent: nameserver = %d no failover now - retrying", i);
retry_named(i, t, false);
++failover_soon_number[i];
@@ -826,12 +856,14 @@ DNSHandler::mainEvent(int event, Event *e)
try_primary_named(false);
++failover_soon_number[name_server];
}
- } else if (name_server) // not on the primary named
+ } else if (name_server) { // not on the primary named
try_primary_named(true);
+ }
}
- if (entries.head)
+ if (entries.head) {
write_dns(this);
+ }
return EVENT_CONT;
}
@@ -862,10 +894,12 @@ get_entry(DNSHandler *h, char *qname, int qtype)
for (DNSEntry *e = h->entries.head; e; e = (DNSEntry *)e->link.next) {
if (e->qtype == qtype) {
if (is_addr_query(qtype)) {
- if (!strcmp(qname, e->qname))
+ if (!strcmp(qname, e->qname)) {
return e;
- } else if (0 == memcmp(qname, e->qname, e->qname_len))
+ }
+ } else if (0 == memcmp(qname, e->qname, e->qname_len)) {
return e;
+ }
}
}
return nullptr;
@@ -878,8 +912,9 @@ write_dns(DNSHandler *h)
ProxyMutex *mutex = h->mutex.get();
DNS_INCREMENT_DYN_STAT(dns_total_lookups_stat);
int max_nscount = h->m_res->nscount;
- if (max_nscount > MAX_NAMED)
+ if (max_nscount > MAX_NAMED) {
max_nscount = MAX_NAMED;
+ }
if (max_nscount <= 0) {
Warning("There is no name server found in the resolv.conf");
if (h->entries.head) {
@@ -888,8 +923,9 @@ write_dns(DNSHandler *h)
return;
}
- if (h->in_write_dns)
+ if (h->in_write_dns) {
return;
+ }
h->in_write_dns = true;
// Debug("dns", "in_flight: %d, dns_max_dns_in_flight: %d", h->in_flight, dns_max_dns_in_flight);
if (h->in_flight < dns_max_dns_in_flight) {
@@ -903,11 +939,13 @@ write_dns(DNSHandler *h)
h->name_server = (h->name_server + 1) % max_nscount;
} while (h->ns_down[h->name_server] && h->name_server != ns_start);
}
- if (!write_dns_event(h, e))
+ if (!write_dns_event(h, e)) {
break;
+ }
}
- if (h->in_flight >= dns_max_dns_in_flight)
+ if (h->in_flight >= dns_max_dns_in_flight) {
break;
+ }
e = n;
}
}
@@ -983,10 +1021,11 @@ write_dns_event(DNSHandler *h, DNSEntry *e)
Debug("dns", "send() failed: qname = %s, %d != %d, nameserver= %d", e->qname, s, r, h->name_server);
// changed if condition from 'r < 0' to 's < 0' - 8/2001 pas
if (s < 0) {
- if (dns_ns_rr)
+ if (dns_ns_rr) {
h->rr_failure(h->name_server);
- else
+ } else {
h->failover();
+ }
}
return false;
}
@@ -999,8 +1038,9 @@ write_dns_event(DNSHandler *h, DNSEntry *e)
e->send_time = Thread::get_hrtime();
- if (e->timeout)
+ if (e->timeout) {
e->timeout->cancel();
+ }
if (h->txn_lookup_timeout) {
e->timeout = h->mutex->thread_holding->schedule_in(e, HRTIME_MSECONDS(h->txn_lookup_timeout)); // this is in msec
@@ -1034,8 +1074,9 @@ DNSEntry::mainEvent(int event, Event *e)
ink_assert(!"bad case");
return EVENT_DONE;
case EVENT_IMMEDIATE: {
- if (!dnsH)
+ if (!dnsH) {
dnsH = dnsProcessor.handler;
+ }
if (!dnsH) {
Debug("dns", "handler not found, retrying...");
SET_HANDLER((DNSEntryHandler)&DNSEntry::delayEvent);
@@ -1097,10 +1138,11 @@ DNSProcessor::getby(const char *x, int len, int type, Continuation *cont, Option
e->retries = dns_retries;
e->init(x, len, type, cont, opt);
MUTEX_TRY_LOCK(lock, e->mutex, this_ethread());
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
thread->schedule_imm(e);
- else
+ } else {
e->handleEvent(EVENT_IMMEDIATE, nullptr);
+ }
return &e->action;
}
@@ -1158,8 +1200,9 @@ dns_result(DNSHandler *h, DNSEntry *e, HostEnt *ent, bool retry)
DNS_INCREMENT_DYN_STAT(dns_max_retries_exceeded_stat);
}
}
- if (ent == BAD_DNS_RESULT)
+ if (ent == BAD_DNS_RESULT) {
ent = nullptr;
+ }
if (!cancelled) {
if (!ent) {
DNS_SUM_DYN_STAT(dns_fail_time_stat, Thread::get_hrtime() - e->submit_time);
@@ -1215,15 +1258,17 @@ dns_result(DNSHandler *h, DNSEntry *e, HostEnt *ent, bool retry)
goto Lretry;
}
for (int i : e->id) {
- if (i < 0)
+ if (i < 0) {
break;
+ }
h->release_query_id(i);
}
e->postEvent(0, nullptr);
} else {
for (int i : e->id) {
- if (i < 0)
+ if (i < 0) {
break;
+ }
h->release_query_id(i);
}
e->mutex = e->action.mutex;
@@ -1234,8 +1279,9 @@ dns_result(DNSHandler *h, DNSEntry *e, HostEnt *ent, bool retry)
Lretry:
e->result_ent = ent;
e->retries = 0;
- if (e->timeout)
+ if (e->timeout) {
e->timeout->cancel();
+ }
e->timeout = h->mutex->thread_holding->schedule_in(e, DNS_PERIOD);
}
@@ -1352,8 +1398,9 @@ dns_process(DNSHandler *handler, HostEnt *buf, int len)
//
// Expand name
//
- if ((n = ink_dn_expand((u_char *)h, eom, cp, bp, buflen)) < 0)
+ if ((n = ink_dn_expand((u_char *)h, eom, cp, bp, buflen)) < 0) {
goto Lerror;
+ }
// Should we validate the query name?
if (dns_validate_qname) {
@@ -1361,10 +1408,12 @@ dns_process(DNSHandler *handler, HostEnt *buf, int len)
int rlen = strlen((char *)bp);
rname_len = rlen; // Save for later use
- if ((qlen > 0) && ('.' == e->qname[qlen - 1]))
+ if ((qlen > 0) && ('.' == e->qname[qlen - 1])) {
--qlen;
- if ((rlen > 0) && ('.' == bp[rlen - 1]))
+ }
+ if ((rlen > 0) && ('.' == bp[rlen - 1])) {
--rlen;
+ }
// TODO: At some point, we might want to care about the case here, and use an algorithm
// to randomly pick upper case characters in the query, and validate the response with
// case sensitivity.
@@ -1379,10 +1428,11 @@ dns_process(DNSHandler *handler, HostEnt *buf, int len)
cp += n + QFIXEDSZ;
if (is_addr_query(e->qtype)) {
- if (-1 == rname_len)
+ if (-1 == rname_len) {
n = strlen((char *)bp) + 1;
- else
- n = rname_len + 1;
+ } else {
+ n = rname_len + 1;
+ }
buf->ent.h_name = (char *)bp;
bp += n;
buflen -= n;
@@ -1446,16 +1496,18 @@ dns_process(DNSHandler *handler, HostEnt *buf, int len)
NS_GET16(type, cp);
cp += NS_INT16SZ; // NS_GET16(cls, cp);
NS_GET32(temp_ttl, cp); // NOTE: this is not a "long" but 32-bits (from nameser_compat.h)
- if ((temp_ttl < buf->ttl) || (buf->ttl == 0))
+ if ((temp_ttl < buf->ttl) || (buf->ttl == 0)) {
buf->ttl = temp_ttl;
+ }
NS_GET16(n, cp);
//
// Decode cname
//
if (is_addr_query(e->qtype) && (type == T_CNAME || type == T_DNAME)) {
- if (ap >= &buf->host_aliases[DNS_MAX_ALIASES - 1])
+ if (ap >= &buf->host_aliases[DNS_MAX_ALIASES - 1]) {
continue;
+ }
n = ink_dn_expand((u_char *)h, eom, cp, tbuf, sizeof(tbuf));
if (n < 0) {
++error;
@@ -1514,8 +1566,9 @@ dns_process(DNSHandler *handler, HostEnt *buf, int len)
buflen -= n;
}
} else if (type == T_SRV) {
- if (num_srv >= HOST_DB_MAX_ROUND_ROBIN_INFO)
+ if (num_srv >= HOST_DB_MAX_ROUND_ROBIN_INFO) {
break;
+ }
cp = here; /* hack */
int strlen = dn_skipname(cp, eom);
cp += strlen;
@@ -1540,10 +1593,11 @@ dns_process(DNSHandler *handler, HostEnt *buf, int len)
srv->host_len = ::strlen(srv->host) + 1;
srv->key = makeHostHash(srv->host);
- if (srv->host[0] != '\0')
+ if (srv->host[0] != '\0') {
buf->srv_hosts.srv_hosts_length += srv->host_len;
- else
+ } else {
continue;
+ }
++num_srv;
} else if (is_addr_query(type)) {
if (answer) {
@@ -1578,8 +1632,9 @@ dns_process(DNSHandler *handler, HostEnt *buf, int len)
bp += n;
cp += n;
}
- } else
+ } else {
goto Lerror;
+ }
++answer;
}
if (answer) {
@@ -1614,8 +1669,9 @@ ink_dns_init(ModuleVersion v)
Debug("dns", "ink_dns_init: called with init_called = %d", init_called);
ink_release_assert(!checkModuleVersion(v, HOSTDB_MODULE_VERSION));
- if (init_called)
+ if (init_called) {
return;
+ }
init_called = 1;
// do one time stuff
@@ -1686,10 +1742,11 @@ struct DNSRegressionContinuation : public Continuation {
++i;
return EVENT_CONT;
} else {
- if (found == tofind)
+ if (found == tofind) {
*status = REGRESSION_TEST_PASSED;
- else
+ } else {
*status = REGRESSION_TEST_FAILED;
+ }
return EVENT_DONE;
}
}
diff --git a/iocore/dns/DNSConnection.cc b/iocore/dns/DNSConnection.cc
index 662b36b..eddbadd 100644
--- a/iocore/dns/DNSConnection.cc
+++ b/iocore/dns/DNSConnection.cc
@@ -93,12 +93,14 @@ DNSConnection::connect(sockaddr const *addr, Options const &opt)
if (opt._use_tcp) {
Proto = IPPROTO_TCP;
- if ((res = socketManager.socket(af, SOCK_STREAM, 0)) < 0)
+ if ((res = socketManager.socket(af, SOCK_STREAM, 0)) < 0) {
goto Lerror;
+ }
} else {
Proto = IPPROTO_UDP;
- if ((res = socketManager.socket(af, SOCK_DGRAM, 0)) < 0)
+ if ((res = socketManager.socket(af, SOCK_DGRAM, 0)) < 0) {
goto Lerror;
+ }
}
fd = res;
@@ -114,11 +116,12 @@ DNSConnection::connect(sockaddr const *addr, Options const &opt)
}
bind_size = sizeof(sockaddr_in6);
} else if (AF_INET == af) {
- if (ats_is_ip4(opt._local_ipv4))
+ if (ats_is_ip4(opt._local_ipv4)) {
ats_ip_copy(&bind_addr.sa, opt._local_ipv4);
- else
+ } else {
bind_addr.sin.sin_addr.s_addr = INADDR_ANY;
- bind_size = sizeof(sockaddr_in);
+ }
+ bind_size = sizeof(sockaddr_in);
} else {
ink_assert(!"Target DNS address must be IP.");
}
@@ -152,19 +155,24 @@ DNSConnection::connect(sockaddr const *addr, Options const &opt)
} else if (ats_is_ip(&bind_addr.sa)) {
ip_text_buffer b;
res = socketManager.ink_bind(fd, &bind_addr.sa, bind_size, Proto);
- if (res < 0)
+ if (res < 0) {
Warning("Unable to bind local address to %s.", ats_ip_ntop(&bind_addr.sa, b, sizeof b));
+ }
}
- if (opt._non_blocking_connect)
- if ((res = safe_nonblocking(fd)) < 0)
+ if (opt._non_blocking_connect) {
+ if ((res = safe_nonblocking(fd)) < 0) {
goto Lerror;
+ }
+ }
// cannot do this after connection on non-blocking connect
#ifdef SET_TCP_NO_DELAY
- if (opt._use_tcp)
- if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, SOCKOPT_ON, sizeof(int))) < 0)
+ if (opt._use_tcp) {
+ if ((res = safe_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, SOCKOPT_ON, sizeof(int))) < 0) {
goto Lerror;
+ }
+ }
#endif
#ifdef RECV_BUF_SIZE
socketManager.set_rcvbuf_size(fd, RECV_BUF_SIZE);
@@ -179,18 +187,22 @@ DNSConnection::connect(sockaddr const *addr, Options const &opt)
res = ::connect(fd, addr, ats_ip_size(addr));
if (!res || ((res < 0) && (errno == EINPROGRESS || errno == EWOULDBLOCK))) {
- if (!opt._non_blocking_connect && opt._non_blocking_io)
- if ((res = safe_nonblocking(fd)) < 0)
+ if (!opt._non_blocking_connect && opt._non_blocking_io) {
+ if ((res = safe_nonblocking(fd)) < 0) {
goto Lerror;
+ }
+ }
// Shouldn't we turn off non-blocking when it's a non-blocking connect
// and blocking IO?
- } else
+ } else {
goto Lerror;
+ }
return 0;
Lerror:
- if (fd != NO_FD)
+ if (fd != NO_FD) {
close();
+ }
return res;
}
diff --git a/iocore/dns/SplitDNS.cc b/iocore/dns/SplitDNS.cc
index 096bfb3..8baf84f 100644
--- a/iocore/dns/SplitDNS.cc
+++ b/iocore/dns/SplitDNS.cc
@@ -130,8 +130,9 @@ SplitDNSConfig::startup()
void
SplitDNSConfig::reconfigure()
{
- if (0 == gsplit_dns_enabled)
+ if (0 == gsplit_dns_enabled) {
return;
+ }
SplitDNS *params = new SplitDNS;
@@ -233,19 +234,22 @@ SplitDNS::findServer(RequestData *rdata, SplitDNSResult *result)
int len = strlen(pHost);
HostLeaf *pxHL = (HostLeaf *)m_pxLeafArray;
for (int i = 0; i < m_numEle; i++) {
- if (nullptr == pxHL)
+ if (nullptr == pxHL) {
break;
+ }
- if (false == pxHL[i].isNot && pxHL[i].len > len)
+ if (false == pxHL[i].isNot && pxHL[i].len > len) {
continue;
+ }
int idx = len - pxHL[i].len;
char *pH = &pHost[idx];
char *pMatch = (char *)pxHL[i].match;
char cNot = *pMatch;
- if ('!' == cNot)
+ if ('!' == cNot) {
pMatch++;
+ }
int res = memcmp(pH, pMatch, pxHL[i].len);
@@ -325,10 +329,12 @@ SplitDNSRecord::ProcessDNSHosts(char *val)
---------------------------------------- */
if (tmp) {
char *scan = tmp + 1;
- for (; *scan != '\0' && ParseRules::is_digit(*scan); scan++)
+ for (; *scan != '\0' && ParseRules::is_digit(*scan); scan++) {
;
- for (; *scan != '\0' && ParseRules::is_wslfcr(*scan); scan++)
+ }
+ for (; *scan != '\0' && ParseRules::is_wslfcr(*scan); scan++) {
;
+ }
if (*scan != '\0') {
return "Garbage trailing entry or invalid separator";
@@ -411,8 +417,9 @@ SplitDNSRecord::ProcessDomainSrchList(char *val)
current = pTok[i];
cnt = sz += strlen(current);
- if (MAXDNAME - 1 < sz)
+ if (MAXDNAME - 1 < sz) {
break;
+ }
memcpy(pSp, current, cnt);
pSp += (cnt + 1);
@@ -544,8 +551,9 @@ ink_split_dns_init(ModuleVersion v)
static int init_called = 0;
ink_release_assert(!checkModuleVersion(v, SPLITDNS_MODULE_VERSION));
- if (init_called)
+ if (init_called) {
return;
+ }
init_called = 1;
}
diff --git a/iocore/eventsystem/IOBuffer.cc b/iocore/eventsystem/IOBuffer.cc
index c1c11d7..2ef31ca 100644
--- a/iocore/eventsystem/IOBuffer.cc
+++ b/iocore/eventsystem/IOBuffer.cc
@@ -51,8 +51,9 @@ init_buffer_allocators(int iobuffer_advice)
int64_t s = DEFAULT_BUFFER_BASE_SIZE * (((int64_t)1) << i);
int64_t a = DEFAULT_BUFFER_ALIGNMENT;
int n = i <= default_large_iobuffer_size ? DEFAULT_BUFFER_NUMBER : DEFAULT_HUGE_BUFFER_NUMBER;
- if (s < a)
+ if (s < a) {
a = s;
+ }
name = new char[64];
snprintf(name, 64, "ioBufAllocator[%d]", i);
@@ -86,8 +87,9 @@ MIOBuffer::write(const void *abuf, int64_t alen)
const char *buf = (const char *)abuf;
int64_t len = alen;
while (len) {
- if (!_writer)
+ if (!_writer) {
add_block();
+ }
int64_t f = _writer->write_avail();
f = f < len ? f : len;
if (f > 0) {
@@ -97,10 +99,11 @@ MIOBuffer::write(const void *abuf, int64_t alen)
len -= f;
}
if (len) {
- if (!_writer->next)
+ if (!_writer->next) {
add_block();
- else
+ } else {
_writer = _writer->next;
+ }
}
}
return alen;
@@ -170,8 +173,9 @@ MIOBuffer::puts(char *s, int64_t len)
char *pc = end();
char *pb = s;
while (pc < buf_end()) {
- if (len-- <= 0)
+ if (len-- <= 0) {
return -1;
+ }
if (!*pb || *pb == '\n') {
int64_t n = (int64_t)(pb - s);
memcpy(end(), s, n + 1); // Upto and including '\n'
@@ -194,8 +198,9 @@ IOBufferReader::read(void *ab, int64_t len)
int64_t bytes = 0;
while (n && l) {
- if (n < l)
+ if (n < l) {
l = n;
+ }
::memcpy(b, start(), l);
consume(l);
b += l;
@@ -223,14 +228,16 @@ IOBufferReader::memchr(char c, int64_t len, int64_t offset)
continue;
}
int64_t bytes;
- if (len < 0 || len >= max_bytes)
+ if (len < 0 || len >= max_bytes) {
bytes = max_bytes;
- else
+ } else {
bytes = len;
+ }
char *s = b->start() + offset;
char *p = (char *)::memchr(s, c, bytes);
- if (p)
+ if (p) {
return (int64_t)(o - start_offset + p - s);
+ }
o += bytes;
len -= bytes;
b = b->next.get();
@@ -256,10 +263,11 @@ IOBufferReader::memcpy(const void *ap, int64_t len, int64_t offset)
continue;
}
int64_t bytes;
- if (len < 0 || len >= max_bytes)
+ if (len < 0 || len >= max_bytes) {
bytes = max_bytes;
- else
+ } else {
bytes = len;
+ }
::memcpy(p, b->start() + offset, bytes);
p += bytes;
len -= bytes;
diff --git a/iocore/eventsystem/PQ-List.cc b/iocore/eventsystem/PQ-List.cc
index 100a597..12c8214 100644
--- a/iocore/eventsystem/PQ-List.cc
+++ b/iocore/eventsystem/PQ-List.cc
@@ -53,8 +53,9 @@ PriorityEventQueue::check_ready(ink_hrtime now, EThread *t)
EVENT_FREE(e, eventAllocator, t);
} else {
ink_hrtime tt = e->timeout_at - now;
- for (j = i; j > 0 && tt <= PQ_BUCKET_TIME(j - 1);)
+ for (j = i; j > 0 && tt <= PQ_BUCKET_TIME(j - 1);) {
j--;
+ }
e->in_heap = j;
after[j].enqueue(e);
}
diff --git a/iocore/eventsystem/ProtectedQueue.cc b/iocore/eventsystem/ProtectedQueue.cc
index 80876d5..c0e1d8e 100644
--- a/iocore/eventsystem/ProtectedQueue.cc
+++ b/iocore/eventsystem/ProtectedQueue.cc
@@ -59,8 +59,9 @@ ProtectedQueue::enqueue(Event *e, bool fast_signal)
if (!inserting_thread || !inserting_thread->ethreads_to_be_signalled) {
signal();
if (fast_signal) {
- if (e_ethread->signal_hook)
+ if (e_ethread->signal_hook) {
e_ethread->signal_hook(e_ethread);
+ }
}
} else {
#ifdef EAGER_SIGNALLING
@@ -69,8 +70,9 @@ ProtectedQueue::enqueue(Event *e, bool fast_signal)
return;
#endif
if (fast_signal) {
- if (e_ethread->signal_hook)
+ if (e_ethread->signal_hook) {
e_ethread->signal_hook(e_ethread);
+ }
}
int &t = inserting_thread->n_ethreads_to_be_signalled;
EThread **sig_e = inserting_thread->ethreads_to_be_signalled;
@@ -83,22 +85,25 @@ ProtectedQueue::enqueue(Event *e, bool fast_signal)
EThread *cur = sig_e[i]; // put this ethread
while (cur) {
EThread *next = sig_e[cur->id]; // into this location
- if (next == cur)
+ if (next == cur) {
break;
+ }
sig_e[cur->id] = cur;
cur = next;
}
// if not overwritten
- if (sig_e[i] && sig_e[i]->id != i)
+ if (sig_e[i] && sig_e[i]->id != i) {
sig_e[i] = nullptr;
+ }
}
t++;
}
// we have a direct map, insert this EThread
sig_e[e_ethread->id] = e_ethread;
- } else
+ } else {
// insert into vector
sig_e[t++] = e_ethread;
+ }
}
}
}
@@ -109,8 +114,9 @@ flush_signals(EThread *thr)
{
ink_assert(this_ethread() == thr);
int n = thr->n_ethreads_to_be_signalled;
- if (n > eventProcessor.n_ethreads)
+ if (n > eventProcessor.n_ethreads) {
n = eventProcessor.n_ethreads; // MAX
+ }
int i;
// Since the lock is only there to prevent a race in ink_cond_timedwait
@@ -128,8 +134,9 @@ flush_signals(EThread *thr)
for (i = 0; i < n; i++) {
if (thr->ethreads_to_be_signalled[i]) {
thr->ethreads_to_be_signalled[i]->EventQueueExternal.signal();
- if (thr->ethreads_to_be_signalled[i]->signal_hook)
+ if (thr->ethreads_to_be_signalled[i]->signal_hook) {
thr->ethreads_to_be_signalled[i]->signal_hook(thr->ethreads_to_be_signalled[i]);
+ }
thr->ethreads_to_be_signalled[i] = nullptr;
}
}
@@ -154,13 +161,14 @@ ProtectedQueue::dequeue_timed(ink_hrtime cur_time, ink_hrtime timeout, bool slee
// invert the list, to preserve order
SLL<Event, Event::Link_link> l, t;
t.head = e;
- while ((e = t.pop()))
+ while ((e = t.pop())) {
l.push(e);
+ }
// insert into localQueue
while ((e = l.pop())) {
- if (!e->cancelled)
+ if (!e->cancelled) {
localQueue.enqueue(e);
- else {
+ } else {
e->mutex = nullptr;
eventAllocator.free(e);
}
diff --git a/iocore/eventsystem/SocketManager.cc b/iocore/eventsystem/SocketManager.cc
index 167c1d2..bfddc94 100644
--- a/iocore/eventsystem/SocketManager.cc
+++ b/iocore/eventsystem/SocketManager.cc
@@ -99,15 +99,17 @@ SocketManager::close(int s)
{
int res;
- if (s == 0)
+ if (s == 0) {
return -EACCES;
- else if (s < 0)
+ } else if (s < 0) {
return -EINVAL;
+ }
do {
res = ::close(s);
- if (res == -1)
+ if (res == -1) {
res = -errno;
+ }
} while (res == -EINTR);
return res;
}
diff --git a/iocore/eventsystem/Thread.cc b/iocore/eventsystem/Thread.cc
index af04099..8be6140 100644
--- a/iocore/eventsystem/Thread.cc
+++ b/iocore/eventsystem/Thread.cc
@@ -85,10 +85,11 @@ spawn_thread_internal(void *a)
p->me->set_specific();
ink_set_thread_name(p->name);
- if (p->f)
+ if (p->f) {
p->f(p->a);
- else
+ } else {
p->me->execute();
+ }
ats_free(a);
return nullptr;
}
diff --git a/iocore/eventsystem/UnixEThread.cc b/iocore/eventsystem/UnixEThread.cc
index 1c508b0..b1cc766 100644
--- a/iocore/eventsystem/UnixEThread.cc
+++ b/iocore/eventsystem/UnixEThread.cc
@@ -57,10 +57,12 @@ EThread::EThread(ThreadType att, int anid)
if (evfd < 0) {
if (errno == EINVAL) { // flags invalid for kernel <= 2.6.26
evfd = eventfd(0, 0);
- if (evfd < 0)
+ if (evfd < 0) {
Fatal("EThread::EThread: %d=eventfd(0,0),errno(%d)", evfd, errno);
- } else
+ }
+ } else {
Fatal("EThread::EThread: %d=eventfd(0,EFD_NONBLOCK | EFD_CLOEXEC),errno(%d)", evfd, errno);
+ }
}
#elif TS_USE_PORT
/* Solaris ports requires no crutches to do cross thread signaling.
@@ -93,8 +95,9 @@ EThread::EThread(ThreadType att, Event *e)
// threads won't have to deal with EThread memory deallocation.
EThread::~EThread()
{
- if (n_ethreads_to_be_signalled > 0)
+ if (n_ethreads_to_be_signalled > 0) {
flush_signals(this);
+ }
ats_free(ethreads_to_be_signalled);
// TODO: This can't be deleted ....
// delete[]l1_hash;
@@ -132,18 +135,20 @@ EThread::process_event(Event *e, int calling_code)
MUTEX_RELEASE(lock);
if (e->period) {
if (!e->in_the_prot_queue && !e->in_the_priority_queue) {
- if (e->period < 0)
+ if (e->period < 0) {
e->timeout_at = e->period;
- else {
+ } else {
this->get_hrtime_updated();
e->timeout_at = cur_time + e->period;
- if (e->timeout_at < cur_time)
+ if (e->timeout_at < cur_time) {
e->timeout_at = cur_time;
+ }
}
EventQueueExternal.enqueue_local(e);
}
- } else if (!e->in_the_prot_queue && !e->in_the_priority_queue)
+ } else if (!e->in_the_prot_queue && !e->in_the_priority_queue) {
free_event(e);
+ }
}
}
@@ -176,24 +181,25 @@ EThread::execute()
// already been dequeued
cur_time = Thread::get_hrtime_updated();
while ((e = EventQueueExternal.dequeue_local())) {
- if (e->cancelled)
+ if (e->cancelled) {
free_event(e);
- else if (!e->timeout_at) { // IMMEDIATE
+ } else if (!e->timeout_at) { // IMMEDIATE
ink_assert(e->period == 0);
process_event(e, e->callback_event);
- } else if (e->timeout_at > 0) // INTERVAL
+ } else if (e->timeout_at > 0) { // INTERVAL
EventQueue.enqueue(e, cur_time);
- else { // NEGATIVE
+ } else { // NEGATIVE
Event *p = nullptr;
Event *a = NegativeQueue.head;
while (a && a->timeout_at > e->timeout_at) {
p = a;
a = a->link.next;
}
- if (!a)
+ if (!a) {
NegativeQueue.enqueue(e);
- else
+ } else {
NegativeQueue.insert(e, p);
+ }
}
}
bool done_one;
@@ -204,9 +210,9 @@ EThread::execute()
while ((e = EventQueue.dequeue_ready(cur_time))) {
ink_assert(e);
ink_assert(e->timeout_at > 0);
- if (e->cancelled)
+ if (e->cancelled) {
free_event(e);
- else {
+ } else {
done_one = true;
process_event(e, e->callback_event);
}
@@ -214,20 +220,22 @@ EThread::execute()
} while (done_one);
// execute any negative (poll) events
if (NegativeQueue.head) {
- if (n_ethreads_to_be_signalled)
+ if (n_ethreads_to_be_signalled) {
flush_signals(this);
+ }
// dequeue all the external events and put them in a local
// queue. If there are no external events available, don't
// do a cond_timedwait.
- if (!INK_ATOMICLIST_EMPTY(EventQueueExternal.al))
+ if (!INK_ATOMICLIST_EMPTY(EventQueueExternal.al)) {
EventQueueExternal.dequeue_timed(cur_time, next_time, false);
+ }
while ((e = EventQueueExternal.dequeue_local())) {
- if (!e->timeout_at)
+ if (!e->timeout_at) {
process_event(e, e->callback_event);
- else {
- if (e->cancelled)
+ } else {
+ if (e->cancelled) {
free_event(e);
- else {
+ } else {
// If its a negative event, it must be a result of
// a negative event, which has been turned into a
// timed-event (because of a missed lock), executed
@@ -242,20 +250,24 @@ EThread::execute()
p = a;
a = a->link.next;
}
- if (!a)
+ if (!a) {
NegativeQueue.enqueue(e);
- else
+ } else {
NegativeQueue.insert(e, p);
- } else
+ }
+ } else {
EventQueue.enqueue(e, cur_time);
+ }
}
}
}
// execute poll events
- while ((e = NegativeQueue.dequeue()))
+ while ((e = NegativeQueue.dequeue())) {
process_event(e, EVENT_POLL);
- if (!INK_ATOMICLIST_EMPTY(EventQueueExternal.al))
+ }
+ if (!INK_ATOMICLIST_EMPTY(EventQueueExternal.al)) {
EventQueueExternal.dequeue_timed(cur_time, next_time, false);
+ }
} else { // Means there are no negative events
next_time = EventQueue.earliest_timeout();
ink_hrtime sleep_time = next_time - cur_time;
@@ -266,8 +278,9 @@ EThread::execute()
// dequeue all the external events and put them in a local
// queue. If there are no external events available, do a
// cond_timedwait.
- if (n_ethreads_to_be_signalled)
+ if (n_ethreads_to_be_signalled) {
flush_signals(this);
+ }
EventQueueExternal.dequeue_timed(cur_time, next_time, true);
}
}
diff --git a/iocore/eventsystem/UnixEvent.cc b/iocore/eventsystem/UnixEvent.cc
index 8596f47..b5589ae 100644
--- a/iocore/eventsystem/UnixEvent.cc
+++ b/iocore/eventsystem/UnixEvent.cc
@@ -36,14 +36,16 @@ Event::schedule_imm(int acallback_event)
{
callback_event = acallback_event;
ink_assert(ethread == this_ethread());
- if (in_the_priority_queue)
+ if (in_the_priority_queue) {
ethread->EventQueue.remove(this);
+ }
timeout_at = 0;
period = 0;
immediate = true;
mutex = continuation->mutex;
- if (!in_the_prot_queue)
+ if (!in_the_prot_queue) {
ethread->EventQueueExternal.enqueue_local(this);
+ }
}
void
@@ -52,14 +54,16 @@ Event::schedule_at(ink_hrtime atimeout_at, int acallback_event)
callback_event = acallback_event;
ink_assert(ethread == this_ethread());
ink_assert(atimeout_at > 0);
- if (in_the_priority_queue)
+ if (in_the_priority_queue) {
ethread->EventQueue.remove(this);
+ }
timeout_at = atimeout_at;
period = 0;
immediate = false;
mutex = continuation->mutex;
- if (!in_the_prot_queue)
+ if (!in_the_prot_queue) {
ethread->EventQueueExternal.enqueue_local(this);
+ }
}
void
@@ -67,14 +71,16 @@ Event::schedule_in(ink_hrtime atimeout_in, int acallback_event)
{
callback_event = acallback_event;
ink_assert(ethread == this_ethread());
- if (in_the_priority_queue)
+ if (in_the_priority_queue) {
ethread->EventQueue.remove(this);
+ }
timeout_at = Thread::get_hrtime() + atimeout_in;
period = 0;
immediate = false;
mutex = continuation->mutex;
- if (!in_the_prot_queue)
+ if (!in_the_prot_queue) {
ethread->EventQueueExternal.enqueue_local(this);
+ }
}
void
@@ -83,8 +89,9 @@ Event::schedule_every(ink_hrtime aperiod, int acallback_event)
callback_event = acallback_event;
ink_assert(ethread == this_ethread());
ink_assert(aperiod != 0);
- if (in_the_priority_queue)
+ if (in_the_priority_queue) {
ethread->EventQueue.remove(this);
+ }
if (aperiod < 0) {
timeout_at = aperiod;
} else {
@@ -93,6 +100,7 @@ Event::schedule_every(ink_hrtime aperiod, int acallback_event)
period = aperiod;
immediate = false;
mutex = continuation->mutex;
- if (!in_the_prot_queue)
+ if (!in_the_prot_queue) {
ethread->EventQueueExternal.enqueue_local(this);
+ }
}
diff --git a/iocore/eventsystem/test_Event.cc b/iocore/eventsystem/test_Event.cc
index e5c9287..2a0a343 100644
--- a/iocore/eventsystem/test_Event.cc
+++ b/iocore/eventsystem/test_Event.cc
@@ -47,10 +47,12 @@ struct process_killer : public Continuation {
kill_function(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
{
printf("Count is %d \n", count);
- if (count <= 0)
+ if (count <= 0) {
exit(1);
- if (count > TEST_TIME_SECOND * TEST_THREADS)
+ }
+ if (count > TEST_TIME_SECOND * TEST_THREADS) {
exit(1);
+ }
exit(0);
return 0;
}
diff --git a/iocore/hostdb/HostDB.cc b/iocore/hostdb/HostDB.cc
index a5c2db0..684cc37 100644
--- a/iocore/hostdb/HostDB.cc
+++ b/iocore/hostdb/HostDB.cc
@@ -79,8 +79,9 @@ void ParseHostFile(const char *path, unsigned int interval);
char *
HostDBInfo::srvname(HostDBRoundRobin *rr) const
{
- if (!is_srv || !data.srv.srv_offset)
+ if (!is_srv || !data.srv.srv_offset) {
return nullptr;
+ }
return (char *)rr + data.srv.srv_offset;
}
@@ -99,12 +100,13 @@ ip_addr_set(sockaddr *ip, ///< Target storage, sockaddr compliant.
void *ptr ///< Raw address data
)
{
- if (AF_INET6 == af)
+ if (AF_INET6 == af) {
ats_ip6_set(ip, *static_cast<in6_addr *>(ptr));
- else if (AF_INET == af)
+ } else if (AF_INET == af) {
ats_ip4_set(ip, *static_cast<in_addr_t *>(ptr));
- else
+ } else {
ats_ip_invalidate(ip);
+ }
}
static inline void
@@ -113,19 +115,21 @@ ip_addr_set(IpAddr &ip, ///< Target storage.
void *ptr ///< Raw address data
)
{
- if (AF_INET6 == af)
+ if (AF_INET6 == af) {
ip = *static_cast<in6_addr *>(ptr);
- else if (AF_INET == af)
+ } else if (AF_INET == af) {
ip = *static_cast<in_addr_t *>(ptr);
- else
+ } else {
ip.invalidate();
+ }
}
inline void
hostdb_cont_free(HostDBContinuation *cont)
{
- if (cont->pending_action)
+ if (cont->pending_action) {
cont->pending_action->cancel();
+ }
cont->mutex = nullptr;
cont->action.mutex = nullptr;
hostDBContAllocator.free(cont);
@@ -139,12 +143,13 @@ static inline bool
check_for_retry(HostDBMark &mark, HostResStyle style)
{
bool zret = true;
- if (HOSTDB_MARK_IPV4 == mark && HOST_RES_IPV4 == style)
+ if (HOSTDB_MARK_IPV4 == mark && HOST_RES_IPV4 == style) {
mark = HOSTDB_MARK_IPV6;
- else if (HOSTDB_MARK_IPV6 == mark && HOST_RES_IPV6 == style)
+ } else if (HOSTDB_MARK_IPV6 == mark && HOST_RES_IPV6 == style) {
mark = HOSTDB_MARK_IPV4;
- else
+ } else {
zret = false;
+ }
return zret;
}
@@ -169,13 +174,15 @@ HostDBMD5::set_host(const char *name, int len)
if (host_name && SplitDNSConfig::isSplitDNSEnabled()) {
const char *scan;
// I think this is checking for a hostname that is just an address.
- for (scan = host_name; *scan != '\0' && (ParseRules::is_digit(*scan) || '.' == *scan || ':' == *scan); ++scan)
+ for (scan = host_name; *scan != '\0' && (ParseRules::is_digit(*scan) || '.' == *scan || ':' == *scan); ++scan) {
;
+ }
if ('\0' != *scan) {
// config is released in the destructor, because we must make sure values we
// get out of it don't evaporate while @a this is still around.
- if (!pSD)
+ if (!pSD) {
pSD = SplitDNSConfig::acquire();
+ }
if (pSD) {
dns_server = static_cast<DNSServer *>(pSD->getDNSRecord(host_name));
}
@@ -199,8 +206,9 @@ HostDBMD5::refresh()
ctx.update(host_name, host_len);
ctx.update(reinterpret_cast<uint8_t *>(&port), sizeof(port));
ctx.update(&m, sizeof(m));
- if (server_line)
+ if (server_line) {
ctx.update(server_line, strlen(server_line));
+ }
} else {
// INK_MD5 the ip, pad on both sizes with 0's
// so that it does not intersect the string space
@@ -221,8 +229,9 @@ HostDBMD5::HostDBMD5() : host_name(nullptr), host_len(0), port(0), dns_server(nu
HostDBMD5::~HostDBMD5()
{
- if (pSD)
+ if (pSD) {
SplitDNSConfig::release(pSD);
+ }
}
HostDBCache::HostDBCache() : refcountcache(nullptr), pending_dns(nullptr), remoteHostDBQueue(nullptr)
@@ -257,10 +266,11 @@ HostDBBackgroundTask::wait_event(int, void *)
ink_hrtime next_sync = HRTIME_SECONDS(this->frequency) - (Thread::get_hrtime() - start_time);
SET_HANDLER(&HostDBBackgroundTask::sync_event);
- if (next_sync > HRTIME_MSECONDS(100))
+ if (next_sync > HRTIME_MSECONDS(100)) {
eventProcessor.schedule_in(this, next_sync, ET_TASK);
- else
+ } else {
eventProcessor.schedule_imm(this, ET_TASK);
+ }
return EVENT_DONE;
}
@@ -362,11 +372,13 @@ HostDBCache::start(int flags)
int
HostDBProcessor::start(int, size_t)
{
- if (hostDB.start(0) < 0)
+ if (hostDB.start(0) < 0) {
return -1;
+ }
- if (auto_clear_hostdb_flag)
+ if (auto_clear_hostdb_flag) {
hostDB.refcountcache->clear();
+ }
statPagesManager.register_http("hostdb", register_ShowHostDB);
@@ -405,8 +417,9 @@ HostDBContinuation::init(HostDBMD5 const &the_md5, Options const &opt)
md5 = the_md5;
if (md5.host_name) {
// copy to backing store.
- if (md5.host_len > static_cast<int>(sizeof(md5_host_name_store) - 1))
+ if (md5.host_len > static_cast<int>(sizeof(md5_host_name_store) - 1)) {
md5.host_len = sizeof(md5_host_name_store) - 1;
+ }
memcpy(md5_host_name_store, md5.host_name, md5.host_len);
} else {
md5.host_len = 0;
@@ -491,10 +504,11 @@ inline HostDBMark
db_mark_for(HostResStyle style)
{
HostDBMark zret = HOSTDB_MARK_GENERIC;
- if (HOST_RES_IPV4 == style || HOST_RES_IPV4_ONLY == style)
+ if (HOST_RES_IPV4 == style || HOST_RES_IPV4_ONLY == style) {
zret = HOSTDB_MARK_IPV4;
- else if (HOST_RES_IPV6 == style || HOST_RES_IPV6_ONLY == style)
+ } else if (HOST_RES_IPV6 == style || HOST_RES_IPV6_ONLY == style) {
zret = HOSTDB_MARK_IPV6;
+ }
return zret;
}
@@ -563,8 +577,9 @@ HostDBContinuation::insert(unsigned int attl)
HostDBInfo *r = HostDBInfo::alloc();
r->key = folded_md5;
- if (attl > HOST_DB_MAX_TTL)
- attl = HOST_DB_MAX_TTL;
+ if (attl > HOST_DB_MAX_TTL) {
+ attl = HOST_DB_MAX_TTL;
+ }
r->ip_timeout_interval = attl;
r->ip_timestamp = hostdb_current_interval;
Debug("hostdb", "inserting for: %.*s: (md5: %" PRIx64 ") now: %u timeout: %u ttl: %u", md5.host_len, md5.host_name, folded_md5,
@@ -590,8 +605,9 @@ HostDBProcessor::getby(Continuation *cont, const char *hostname, int len, sockad
if ((!hostdb_enable || (hostname && !*hostname)) || (hostdb_disable_reverse_lookup && ip)) {
MUTEX_TRY_LOCK(lock, cont->mutex, thread);
- if (!lock.is_locked())
+ if (!lock.is_locked()) {
goto Lretry;
+ }
cont->handleEvent(EVENT_HOST_DB_LOOKUP, nullptr);
return ACTION_RESULT_DONE;
}
@@ -620,8 +636,9 @@ HostDBProcessor::getby(Continuation *cont, const char *hostname, int len, sockad
// If we can get the lock and a level 1 probe succeeds, return
Ptr<HostDBInfo> r = probe(bmutex, md5, aforce_dns);
if (r) {
- if (r->is_failed() && hostname)
+ if (r->is_failed() && hostname) {
loop = check_for_retry(md5.db_mark, host_res_style);
+ }
if (!loop) {
// No retry -> final result. Return it.
Debug("hostdb", "immediate answer for %s",
@@ -671,12 +688,13 @@ HostDBProcessor::getbyname_re(Continuation *cont, const char *ahostname, int len
EThread *thread = this_ethread();
ProxyMutex *mutex = thread->mutex.get();
- if (opt.flags & HOSTDB_FORCE_DNS_ALWAYS)
+ if (opt.flags & HOSTDB_FORCE_DNS_ALWAYS) {
force_dns = true;
- else if (opt.flags & HOSTDB_FORCE_DNS_RELOAD) {
+ } else if (opt.flags & HOSTDB_FORCE_DNS_RELOAD) {
force_dns = (hostdb_re_dns_on_reload ? true : false);
- if (force_dns)
+ if (force_dns) {
HOSTDB_INCREMENT_DYN_STAT(hostdb_re_dns_on_reload_stat);
+ }
}
return getby(cont, ahostname, len, nullptr, force_dns, opt.host_res_style, opt.timeout);
}
@@ -688,12 +706,13 @@ HostDBProcessor::getbynameport_re(Continuation *cont, const char *ahostname, int
EThread *thread = this_ethread();
ProxyMutex *mutex = thread->mutex.get();
- if (opt.flags & HOSTDB_FORCE_DNS_ALWAYS)
+ if (opt.flags & HOSTDB_FORCE_DNS_ALWAYS) {
force_dns = true;
- else if (opt.flags & HOSTDB_FORCE_DNS_RELOAD) {
+ } else if (opt.flags & HOSTDB_FORCE_DNS_RELOAD) {
force_dns = (hostdb_re_dns_on_reload ? true : false);
- if (force_dns)
+ if (force_dns) {
HOSTDB_INCREMENT_DYN_STAT(hostdb_re_dns_on_reload_stat);
+ }
}
sockaddr sa;
ats_ip4_set(&sa, INADDR_ANY, htons(opt.port));
@@ -712,12 +731,13 @@ HostDBProcessor::getSRVbyname_imm(Continuation *cont, process_srv_info_pfn proce
ink_assert(nullptr != hostname);
- if (opt.flags & HOSTDB_FORCE_DNS_ALWAYS)
+ if (opt.flags & HOSTDB_FORCE_DNS_ALWAYS) {
force_dns = true;
- else if (opt.flags & HOSTDB_FORCE_DNS_RELOAD) {
+ } else if (opt.flags & HOSTDB_FORCE_DNS_RELOAD) {
force_dns = (hostdb_re_dns_on_reload ? true : false);
- if (force_dns)
+ if (force_dns) {
HOSTDB_INCREMENT_DYN_STAT(hostdb_re_dns_on_reload_stat);
+ }
}
HostDBMD5 md5;
@@ -788,12 +808,13 @@ HostDBProcessor::getbyname_imm(Continuation *cont, process_hostdb_info_pfn proce
ink_assert(nullptr != hostname);
- if (opt.flags & HOSTDB_FORCE_DNS_ALWAYS)
+ if (opt.flags & HOSTDB_FORCE_DNS_ALWAYS) {
force_dns = true;
- else if (opt.flags & HOSTDB_FORCE_DNS_RELOAD) {
+ } else if (opt.flags & HOSTDB_FORCE_DNS_RELOAD) {
force_dns = (hostdb_re_dns_on_reload ? true : false);
- if (force_dns)
+ if (force_dns) {
HOSTDB_INCREMENT_DYN_STAT(hostdb_re_dns_on_reload_stat);
+ }
}
HOSTDB_INCREMENT_DYN_STAT(hostdb_total_lookups_stat);
@@ -819,8 +840,9 @@ HostDBProcessor::getbyname_imm(Continuation *cont, process_hostdb_info_pfn proce
// do a level 1 probe for immediate result.
Ptr<HostDBInfo> r = probe(bucket_mutex, md5, false);
if (r) {
- if (r->is_failed()) // fail, see if we should retry with alternate
+ if (r->is_failed()) { // fail, see if we should retry with alternate
loop = check_for_retry(md5.db_mark, opt.host_res_style);
+ }
if (!loop) {
// No retry -> final result. Return it.
Debug("hostdb", "immediate answer for %.*s", md5.host_len, md5.host_name);
@@ -883,8 +905,9 @@ do_setby(HostDBInfo *r, HostDBApplicationInfo *app, const char *hostname, IpAddr
{
HostDBRoundRobin *rr = r->rr();
- if (is_srv && (!r->is_srv || !rr))
+ if (is_srv && (!r->is_srv || !rr)) {
return;
+ }
if (rr) {
if (is_srv) {
@@ -897,7 +920,7 @@ do_setby(HostDBInfo *r, HostDBApplicationInfo *app, const char *hostname, IpAddr
return;
}
}
- } else
+ } else {
for (int i = 0; i < rr->rrcount; i++) {
if (rr->info(i).ip() == ip) {
Debug("hostdb", "immediate setby for %s", hostname ? hostname : "<addr>");
@@ -906,6 +929,7 @@ do_setby(HostDBInfo *r, HostDBApplicationInfo *app, const char *hostname, IpAddr
return;
}
}
+ }
} else {
if (r->reverse_dns || (!r->round_robin && ip == r->ip())) {
Debug("hostdb", "immediate setby for %s", hostname ? hostname : "<addr>");
@@ -918,8 +942,9 @@ do_setby(HostDBInfo *r, HostDBApplicationInfo *app, const char *hostname, IpAddr
void
HostDBProcessor::setby(const char *hostname, int len, sockaddr const *ip, HostDBApplicationInfo *app)
{
- if (!hostdb_enable)
+ if (!hostdb_enable) {
return;
+ }
HostDBMD5 md5;
md5.set_host(hostname, hostname ? (len ? len : strlen(hostname)) : 0);
@@ -936,8 +961,9 @@ HostDBProcessor::setby(const char *hostname, int len, sockaddr const *ip, HostDB
if (lock.is_locked()) {
Ptr<HostDBInfo> r = probe(mutex, md5, false);
- if (r)
+ if (r) {
do_setby(r.get(), app, hostname, md5.ip);
+ }
return;
}
// Create a continuation to do a deaper probe in the background
@@ -953,8 +979,9 @@ HostDBProcessor::setby(const char *hostname, int len, sockaddr const *ip, HostDB
void
HostDBProcessor::setby_srv(const char *hostname, int len, const char *target, HostDBApplicationInfo *app)
{
- if (!hostdb_enable || !hostname || !target)
+ if (!hostdb_enable || !hostname || !target) {
return;
+ }
HostDBMD5 md5;
md5.set_host(hostname, len ? len : strlen(hostname));
@@ -977,8 +1004,9 @@ HostDBContinuation::setbyEvent(int /* event ATS_UNUSED */, Event * /* e ATS_UNUS
{
Ptr<HostDBInfo> r = probe(mutex.get(), md5, false);
- if (r)
+ if (r) {
do_setby(r.get(), &app, md5.host_name, md5.ip, is_srv());
+ }
hostdb_cont_free(this);
return EVENT_DONE;
@@ -988,11 +1016,13 @@ static bool
remove_round_robin(HostDBInfo *r, const char *hostname, IpAddr const &ip)
{
if (r) {
- if (!r->round_robin)
+ if (!r->round_robin) {
return false;
+ }
HostDBRoundRobin *rr = r->rr();
- if (!rr)
+ if (!rr) {
return false;
+ }
for (int i = 0; i < rr->good; i++) {
if (ip == rr->info(i).ip()) {
ip_text_buffer b;
@@ -1037,13 +1067,15 @@ HostDBContinuation::removeEvent(int /* event ATS_UNUSED */, Event *e)
}
if (!action.cancelled) {
if (!hostdb_enable) {
- if (cont)
+ if (cont) {
cont->handleEvent(EVENT_HOST_DB_IP_REMOVED, (void *)nullptr);
+ }
} else {
Ptr<HostDBInfo> r = probe(mutex.get(), md5, false);
bool res = remove_round_robin(r.get(), md5.host_name, md5.ip);
- if (cont)
+ if (cont) {
cont->handleEvent(EVENT_HOST_DB_IP_REMOVED, res ? static_cast<void *>(&md5.ip) : static_cast<void *>(nullptr));
+ }
}
}
hostdb_cont_free(this);
@@ -1104,8 +1136,9 @@ HostDBContinuation::lookup_done(IpAddr const &ip, const char *aname, bool around
// Not sure about this - it seems wrong but I can't be sure. If we got a fail
// in the DNS event, 0 is passed in which we then change to 1 here. Do we need this
// to be non-zero to avoid an infinite timeout?
- if (0 == ttl_seconds)
+ if (0 == ttl_seconds) {
ttl_seconds = 1;
+ }
if (r == nullptr) {
r = insert(hostdb_ip_fail_timeout_interval); // currently ... 0
@@ -1168,8 +1201,9 @@ HostDBContinuation::dnsPendingEvent(int event, Event *e)
timeout = eventProcessor.schedule_in(this, HOST_DB_RETRY_PERIOD);
return EVENT_CONT;
}
- if (!action.cancelled && action.continuation)
+ if (!action.cancelled && action.continuation) {
action.continuation->handleEvent(EVENT_HOST_DB_LOOKUP, nullptr);
+ }
hostDB.pending_dns_for_hash(md5.hash).remove(this);
hostdb_cont_free(this);
return EVENT_DONE;
@@ -1184,16 +1218,18 @@ static int
restore_info(HostDBInfo *r, HostDBInfo *old_r, HostDBInfo &old_info, HostDBRoundRobin *old_rr_data)
{
if (old_rr_data) {
- for (int j = 0; j < old_rr_data->rrcount; j++)
+ for (int j = 0; j < old_rr_data->rrcount; j++) {
if (ats_ip_addr_eq(old_rr_data->info(j).ip(), r->ip())) {
r->app = old_rr_data->info(j).app;
return true;
}
- } else if (old_r)
+ }
+ } else if (old_r) {
if (ats_ip_addr_eq(old_info.ip(), r->ip())) {
r->app = old_info.app;
return true;
}
+ }
return false;
}
@@ -1224,8 +1260,9 @@ HostDBContinuation::dnsEvent(int event, HostEnt *e)
// We don't try a different family here because a timeout indicates
// a server issue that won't be fixed by asking for a different
// address family.
- if (!action.cancelled && action.continuation)
+ if (!action.cancelled && action.continuation) {
action.continuation->handleEvent(EVENT_HOST_DB_LOOKUP, nullptr);
+ }
action = nullptr;
// do not exit yet, wait to see if we can insert into DB
timeout = thread->schedule_in(this, HRTIME_SECONDS(hostdb_insert_timeout));
@@ -1248,8 +1285,9 @@ HostDBContinuation::dnsEvent(int event, HostEnt *e)
Ptr<HostDBInfo> old_r = probe(mutex.get(), md5, false);
HostDBInfo old_info;
- if (old_r)
- old_info = *old_r.get();
+ if (old_r) {
+ old_info = *old_r.get();
+ }
HostDBRoundRobin *old_rr_data = old_r ? old_r->rr() : nullptr;
int valid_records = 0;
void *first_record = nullptr;
@@ -1316,16 +1354,18 @@ HostDBContinuation::dnsEvent(int event, HostEnt *e)
if (failed && old_r && old_r->serve_stale_but_revalidate()) {
r = old_r.get();
} else if (is_byname()) {
- if (first_record)
+ if (first_record) {
ip_addr_set(tip, af, first_record);
+ }
r = lookup_done(tip, md5.host_name, is_rr, ttl_seconds, failed ? nullptr : &e->srv_hosts, r);
} else if (is_srv()) {
- if (!failed)
- tip._family = AF_INET; // force the tip valid, or else the srv will fail
- r = lookup_done(tip, /* junk: FIXME: is the code in lookup_done() wrong to NEED this? */
- md5.host_name, /* hostname */
- is_rr, /* is round robin, doesnt matter for SRV since we recheck getCount() inside lookup_done() */
- ttl_seconds, /* ttl in seconds */
+ if (!failed) {
+ tip._family = AF_INET; // force the tip valid, or else the srv will fail
+ }
+ r = lookup_done(tip, /* junk: FIXME: is the code in lookup_done() wrong to NEED this? */
+ md5.host_name, /* hostname */
+ is_rr, /* is round robin, doesnt matter for SRV since we recheck getCount() inside lookup_done() */
+ ttl_seconds, /* ttl in seconds */
failed ? nullptr : &e->srv_hosts, r);
} else if (failed) {
r = lookup_done(tip, md5.host_name, false, ttl_seconds, nullptr, r);
@@ -1391,8 +1431,9 @@ HostDBContinuation::dnsEvent(int event, HostEnt *e)
if (rr_data->info(i).data.srv.key == old_rr_data->info(ii).data.srv.key) {
char *new_host = rr_data->info(i).srvname(rr_data);
char *old_host = old_rr_data->info(ii).srvname(old_rr_data);
- if (!strcmp(new_host, old_host))
+ if (!strcmp(new_host, old_host)) {
rr_data->info(i).app = old_rr_data->info(ii).app;
+ }
}
}
}
@@ -1415,8 +1456,9 @@ HostDBContinuation::dnsEvent(int event, HostEnt *e)
}
}
- if (!failed && !is_rr && !is_srv())
+ if (!failed && !is_rr && !is_srv()) {
restore_info(r, old_r.get(), old_info, old_rr_data);
+ }
ink_assert(!r || !r->round_robin || !r->reverse_dns);
ink_assert(failed || !r->round_robin || r->app.rr.offset);
@@ -1440,8 +1482,9 @@ HostDBContinuation::dnsEvent(int event, HostEnt *e)
thread->schedule_in(this, HOST_DB_RETRY_PERIOD);
return EVENT_CONT;
}
- if (!action.cancelled)
+ if (!action.cancelled) {
reply_to_cont(action.continuation, r, is_srv());
+ }
}
// wake up everyone else who is waiting
remove_trigger_pending_dns();
@@ -1529,8 +1572,9 @@ HostDBContinuation::probeEvent(int /* event ATS_UNUSED */, Event *e)
}
if (!hostdb_enable || (!*md5.host_name && !md5.ip.isValid())) {
- if (action.continuation)
+ if (action.continuation) {
action.continuation->handleEvent(EVENT_HOST_DB_LOOKUP, nullptr);
+ }
hostdb_cont_free(this);
return EVENT_DONE;
}
@@ -1540,11 +1584,13 @@ HostDBContinuation::probeEvent(int /* event ATS_UNUSED */, Event *e)
//
Ptr<HostDBInfo> r = probe(mutex.get(), md5, false);
- if (r)
+ if (r) {
HOSTDB_INCREMENT_DYN_STAT(hostdb_total_hits_stat);
+ }
- if (action.continuation && r)
+ if (action.continuation && r) {
reply_to_cont(action.continuation, r.get());
+ }
// If it suceeds or it was a remote probe, we are done
//
@@ -1591,8 +1637,9 @@ HostDBContinuation::remove_trigger_pending_dns()
}
c = n;
}
- while ((c = qq.dequeue()))
+ while ((c = qq.dequeue())) {
c->handleEvent(EVENT_IMMEDIATE, nullptr);
+ }
}
//
@@ -1640,8 +1687,9 @@ HostDBContinuation::do_dns()
opt.host_res_style = host_res_style_for(md5.db_mark);
SET_HANDLER((HostDBContHandler)&HostDBContinuation::dnsEvent);
if (is_byname()) {
- if (md5.dns_server)
- opt.handler = md5.dns_server->x_dnsH;
+ if (md5.dns_server) {
+ opt.handler = md5.dns_server->x_dnsH;
+ }
pending_action = dnsProcessor.gethostbyname(this, md5.host_name, opt);
} else if (is_srv()) {
Debug("dns_srv", "SRV lookup of %s", md5.host_name);
@@ -1712,8 +1760,9 @@ HostDBContinuation::backgroundEvent(int /* event ATS_UNUSED */, Event * /* e ATS
char *
HostDBInfo::hostname() const
{
- if (!reverse_dns)
+ if (!reverse_dns) {
return nullptr;
+ }
return (char *)this + data.hostname_offset;
}
@@ -1724,8 +1773,9 @@ HostDBInfo::hostname() const
char *
HostDBInfo::perm_hostname() const
{
- if (hostname_offset == 0)
+ if (hostname_offset == 0) {
return nullptr;
+ }
return (char *)this + hostname_offset;
}
@@ -1733,8 +1783,9 @@ HostDBInfo::perm_hostname() const
HostDBRoundRobin *
HostDBInfo::rr()
{
- if (!round_robin)
+ if (!round_robin) {
return nullptr;
+ }
return (HostDBRoundRobin *)((char *)this + this->app.rr.offset);
}
@@ -1778,8 +1829,9 @@ struct ShowHostDB : public ShowCont {
opts.port = port;
opts.flags = HostDBProcessor::HOSTDB_DO_NOT_FORCE_DNS;
hostDBProcessor.getbynameport_re(this, name, strlen(name), opts);
- } else
+ } else {
hostDBProcessor.getbyaddr_re(this, &ip.sa);
+ }
return EVENT_CONT;
}
@@ -1945,8 +1997,9 @@ struct ShowHostDB : public ShowCont {
CHECK_SHOW(show("<tr><td>%s</td><td>%d</td></tr>\n", "Current", rr_data->current));
CHECK_SHOW(show("</table>\n"));
- for (int i = 0; i < rr_data->rrcount; i++)
+ for (int i = 0; i < rr_data->rrcount; i++) {
showOne(&rr_data->info(i), true, event, e, rr_data);
+ }
}
}
} else {
@@ -1984,8 +2037,9 @@ register_ShowHostDB(Continuation *c, HTTPHdr *h)
const char *query = h->url_get()->query_get(&query_len);
s->sarg = ats_strndup(query, query_len);
char *gn = nullptr;
- if (s->sarg)
+ if (s->sarg) {
gn = (char *)memchr(s->sarg, '=', strlen(s->sarg));
+ }
if (gn) {
ats_ip_pton(gn + 1, &s->ip); // hope that's null terminated.
}
@@ -1996,8 +2050,9 @@ register_ShowHostDB(Continuation *c, HTTPHdr *h)
const char *query = h->url_get()->query_get(&query_len);
s->sarg = ats_strndup(query, query_len);
char *gn = nullptr;
- if (s->sarg)
+ if (s->sarg) {
gn = (char *)memchr(s->sarg, '=', strlen(s->sarg));
+ }
if (gn) {
s->name = gn + 1;
char *pos = strstr(s->name, "%3A");
@@ -2098,8 +2153,9 @@ ink_hostdb_init(ModuleVersion v)
static int init_called = 0;
ink_release_assert(!checkModuleVersion(v, HOSTDB_MODULE_VERSION));
- if (init_called)
+ if (init_called) {
return;
+ }
init_called = 1;
// do one time stuff
@@ -2228,15 +2284,18 @@ ParseHostFile(const char *path, unsigned int hostdb_hostfile_check_interval)
char *spot = strchr(base, '\n');
// terminate the line.
- if (nullptr == spot)
+ if (nullptr == spot) {
spot = limit; // no trailing EOL, grab remaining
- else
+ } else {
*spot = 0;
+ }
- while (base < spot && isspace(*base))
- ++base; // skip leading ws
- if (*base != '#' && base < spot) // non-empty non-comment line
+ while (base < spot && isspace(*base)) {
+ ++base; // skip leading ws
+ }
+ if (*base != '#' && base < spot) { // non-empty non-comment line
ParseHostLine(parsed_hosts_file_ptr, base);
+ }
base = spot + 1;
}
diff --git a/iocore/net/Connection.cc b/iocore/net/Connection.cc
index e52af10..dbacdf7 100644
--- a/iocore/net/Connection.cc
+++ b/iocore/net/Connection.cc
@@ -74,8 +74,9 @@ Server::accept(Connection *c)
socklen_t sz = sizeof(c->addr);
res = socketManager.accept4(fd, &c->addr.sa, &sz, SOCK_NONBLOCK | SOCK_CLOEXEC);
- if (res < 0)
+ if (res < 0) {
return res;
+ }
c->fd = res;
if (is_debug_tag_set("iocore_net_server")) {
ip_port_text_buffer ipb1, ipb2;
diff --git a/iocore/net/OCSPStapling.cc b/iocore/net/OCSPStapling.cc
index 5d061b2..a20d7af 100644
--- a/iocore/net/OCSPStapling.cc
+++ b/iocore/net/OCSPStapling.cc
@@ -50,12 +50,15 @@ certinfo_free(void * /*parent*/, void *ptr, CRYPTO_EX_DATA * /*ad*/, int /*idx*/
{
certinfo *cinf = (certinfo *)ptr;
- if (!cinf)
+ if (!cinf) {
return;
- if (cinf->uri)
+ }
+ if (cinf->uri) {
OPENSSL_free(cinf->uri);
- if (cinf->certname)
+ }
+ if (cinf->certname) {
ats_free(cinf->certname);
+ }
ink_mutex_destroy(&cinf->stapling_mutex);
OPENSSL_free(cinf);
}
@@ -65,8 +68,9 @@ static int ssl_stapling_index = -1;
void
ssl_stapling_ex_init()
{
- if (ssl_stapling_index != -1)
+ if (ssl_stapling_index != -1) {
return;
+ }
ssl_stapling_index = SSL_CTX_get_ex_new_index(0, nullptr, nullptr, nullptr, certinfo_free);
}
@@ -85,8 +89,9 @@ stapling_get_issuer(SSL_CTX *ssl_ctx, X509 *x)
extra_certs = ssl_ctx->extra_certs;
#endif
- if (sk_X509_num(extra_certs) == 0)
+ if (sk_X509_num(extra_certs) == 0) {
return nullptr;
+ }
for (i = 0; i < sk_X509_num(extra_certs); i++) {
issuer = sk_X509_value(extra_certs, i);
@@ -96,10 +101,12 @@ stapling_get_issuer(SSL_CTX *ssl_ctx, X509 *x)
}
}
- if (!X509_STORE_CTX_init(&inctx, st, nullptr, nullptr))
+ if (!X509_STORE_CTX_init(&inctx, st, nullptr, nullptr)) {
return nullptr;
- if (X509_STORE_CTX_get1_issuer(&issuer, &inctx, x) <= 0)
+ }
+ if (X509_STORE_CTX_get1_issuer(&issuer, &inctx, x) <= 0) {
issuer = nullptr;
+ }
X509_STORE_CTX_cleanup(&inctx);
return issuer;
@@ -147,18 +154,21 @@ ssl_stapling_init_cert(SSL_CTX *ctx, X509 *cert, const char *certname)
}
cinf->cid = OCSP_cert_to_id(nullptr, cert, issuer);
- if (!cinf->cid)
+ if (!cinf->cid) {
return false;
+ }
X509_digest(cert, EVP_sha1(), cinf->idx, nullptr);
aia = X509_get1_ocsp(cert);
- if (aia)
+ if (aia) {
cinf->uri = sk_OPENSSL_STRING_pop(aia);
+ }
if (!cinf->uri) {
Note("no responder URI for %s", certname);
}
- if (aia)
+ if (aia) {
X509_email_free(aia);
+ }
Note("successfully initialized certinfo for %s into SSL_CTX: %p", certname, ctx);
return true;
@@ -170,8 +180,9 @@ stapling_get_cert_info(SSL_CTX *ctx)
certinfo *cinf;
cinf = (certinfo *)SSL_CTX_get_ex_data(ctx, ssl_stapling_index);
- if (cinf && cinf->cid)
+ if (cinf && cinf->cid) {
return cinf;
+ }
return nullptr;
}
@@ -274,8 +285,9 @@ query_responder(BIO *b, char *host, char *path, OCSP_REQUEST *req, int req_timeo
OCSP_REQ_CTX_free(ctx);
- if (rv)
+ if (rv) {
return resp;
+ }
return nullptr;
}
@@ -289,8 +301,9 @@ process_responder(OCSP_REQUEST *req, char *host, char *path, char *port, int req
if (!cbio) {
goto end;
}
- if (port)
+ if (port) {
BIO_set_conn_port(cbio, port);
+ }
BIO_set_nbio(cbio, 1);
if (BIO_do_connect(cbio) <= 0 && !BIO_should_retry(cbio)) {
@@ -300,8 +313,9 @@ process_responder(OCSP_REQUEST *req, char *host, char *path, char *port, int req
resp = query_responder(cbio, host, path, req, req_timeout);
end:
- if (cbio)
+ if (cbio) {
BIO_free_all(cbio);
+ }
return resp;
}
@@ -323,13 +337,16 @@ stapling_refresh_response(certinfo *cinf, OCSP_RESPONSE **prsp)
}
req = OCSP_REQUEST_new();
- if (!req)
+ if (!req) {
goto err;
+ }
id = OCSP_CERTID_dup(cinf->cid);
- if (!id)
+ if (!id) {
goto err;
- if (!OCSP_request_add0_id(req, id))
+ }
+ if (!OCSP_request_add0_id(req, id)) {
goto err;
+ }
req_timeout = SSLConfigParams::ssl_ocsp_request_timeout;
*prsp = process_responder(req, host, path, port, req_timeout);
@@ -353,10 +370,12 @@ stapling_refresh_response(certinfo *cinf, OCSP_RESPONSE **prsp)
}
done:
- if (req)
+ if (req) {
OCSP_REQUEST_free(req);
- if (*prsp)
+ }
+ if (*prsp) {
OCSP_RESPONSE_free(*prsp);
+ }
return rv;
err:
diff --git a/iocore/net/SSLCertLookup.cc b/iocore/net/SSLCertLookup.cc
index a1dbe5a..7eb84e2 100644
--- a/iocore/net/SSLCertLookup.cc
+++ b/iocore/net/SSLCertLookup.cc
@@ -411,8 +411,9 @@ SSLContextStorage::insert(const char *name, SSLCertContext const &cc)
{
int idx = this->store(cc);
idx = this->insert(name, idx);
- if (idx < 0)
+ if (idx < 0) {
this->ctx_store.drop();
+ }
return idx;
}
diff --git a/iocore/net/SSLConfig.cc b/iocore/net/SSLConfig.cc
index dd6ef4b..73d1e3f 100644
--- a/iocore/net/SSLConfig.cc
+++ b/iocore/net/SSLConfig.cc
@@ -181,8 +181,9 @@ SSLConfigParams::initialize()
int options;
int client_ssl_options = 0;
REC_ReadConfigInteger(options, "proxy.config.ssl.TLSv1");
- if (!options)
+ if (!options) {
ssl_ctx_options |= SSL_OP_NO_TLSv1;
+ }
#if TS_USE_SSLV3_CLIENT
REC_ReadConfigInteger(client_ssl_options, "proxy.config.ssl.client.SSLv3");
@@ -190,33 +191,39 @@ SSLConfigParams::initialize()
ssl_client_ctx_protocols &= ~SSL_OP_NO_SSLv3;
#endif
REC_ReadConfigInteger(client_ssl_options, "proxy.config.ssl.client.TLSv1");
- if (!client_ssl_options)
+ if (!client_ssl_options) {
ssl_client_ctx_protocols |= SSL_OP_NO_TLSv1;
+ }
// These are not available in all versions of OpenSSL (e.g. CentOS6). Also see http://s.apache.org/TS-2355.
#ifdef SSL_OP_NO_TLSv1_1
REC_ReadConfigInteger(options, "proxy.config.ssl.TLSv1_1");
- if (!options)
+ if (!options) {
ssl_ctx_options |= SSL_OP_NO_TLSv1_1;
+ }
REC_ReadConfigInteger(client_ssl_options, "proxy.config.ssl.client.TLSv1_1");
- if (!client_ssl_options)
+ if (!client_ssl_options) {
ssl_client_ctx_protocols |= SSL_OP_NO_TLSv1_1;
+ }
#endif
#ifdef SSL_OP_NO_TLSv1_2
REC_ReadConfigInteger(options, "proxy.config.ssl.TLSv1_2");
- if (!options)
+ if (!options) {
ssl_ctx_options |= SSL_OP_NO_TLSv1_2;
+ }
REC_ReadConfigInteger(client_ssl_options, "proxy.config.ssl.client.TLSv1_2");
- if (!client_ssl_options)
+ if (!client_ssl_options) {
ssl_client_ctx_protocols |= SSL_OP_NO_TLSv1_2;
+ }
#endif
#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
REC_ReadConfigInteger(options, "proxy.config.ssl.server.honor_cipher_order");
- if (options)
+ if (options) {
ssl_ctx_options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
+ }
#endif
#ifdef SSL_OP_NO_COMPRESSION
@@ -387,8 +394,9 @@ SSLConfigParams::printCTXmap()
{
Vec<cchar *> keys;
ctx_map.get_keys(keys);
- for (size_t i = 0; i < keys.length(); i++)
+ for (size_t i = 0; i < keys.length(); i++) {
Debug("ssl", "Client certificates in the map %s", keys.get(i));
+ }
}
void
SSLConfigParams::freeCTXmap() const
diff --git a/iocore/net/SSLNetProcessor.cc b/iocore/net/SSLNetProcessor.cc
index 658d1eb..2bc04a0 100644
--- a/iocore/net/SSLNetProcessor.cc
+++ b/iocore/net/SSLNetProcessor.cc
@@ -60,8 +60,9 @@ SSLNetProcessor::start(int, size_t stacksize)
SSLInitializeLibrary();
SSLConfig::startup();
- if (!SSLCertificateConfig::startup())
+ if (!SSLCertificateConfig::startup()) {
return -1;
+ }
// Acquire a SSLConfigParams instance *after* we start SSL up.
// SSLConfig::scoped_config params;
diff --git a/iocore/net/SSLNetVConnection.cc b/iocore/net/SSLNetVConnection.cc
index ddb3424..8d64262 100644
--- a/iocore/net/SSLNetVConnection.cc
+++ b/iocore/net/SSLNetVConnection.cc
@@ -340,13 +340,15 @@ SSLNetVConnection::read_raw_data()
if (a > 0) {
tiovec[niov].iov_base = b->_end;
int64_t togo = toread - total_read - rattempted;
- if (a > togo)
- a = togo;
+ if (a > togo) {
+ a = togo;
+ }
tiovec[niov].iov_len = a;
rattempted += a;
niov++;
- if (a >= togo)
+ if (a >= togo) {
break;
+ }
}
b = b->next.get();
}
@@ -367,10 +369,11 @@ SSLNetVConnection::read_raw_data()
// if we have already moved some bytes successfully, summarize in r
if (total_read != rattempted) {
- if (r <= 0)
+ if (r <= 0) {
r = total_read - rattempted;
- else
+ } else {
r = total_read - rattempted + r;
+ }
}
// check for errors
if (r <= 0) {
@@ -524,8 +527,9 @@ SSLNetVConnection::net_read_io(NetHandler *nh, EThread *lthread)
readSignalDone(VC_EVENT_READ_COMPLETE, nh);
} else {
read.triggered = 1;
- if (read.enabled)
+ if (read.enabled) {
nh->read_ready_list.in_or_enqueue(this);
+ }
}
} else if (ret == SSL_WAIT_FOR_HOOK) {
// avoid readReschedule - done when the plugin calls us back to reenable
@@ -600,10 +604,11 @@ SSLNetVConnection::net_read_io(NetHandler *nh, EThread *lthread)
case SSL_READ_WOULD_BLOCK:
if (lock.get_mutex() != s->vio.mutex.get()) {
Debug("ssl", "ssl_read_from_net, mutex switched");
- if (ret == SSL_READ_WOULD_BLOCK)
+ if (ret == SSL_READ_WOULD_BLOCK) {
readReschedule(nh);
- else
+ } else {
writeReschedule(nh);
+ }
return;
}
// reset the trigger and remove from the ready queue
@@ -612,10 +617,11 @@ SSLNetVConnection::net_read_io(NetHandler *nh, EThread *lthread)
nh->read_ready_list.remove(this);
Debug("ssl", "read_from_net, read finished - would block");
#ifdef TS_USE_PORT
- if (ret == SSL_READ_WOULD_BLOCK)
+ if (ret == SSL_READ_WOULD_BLOCK) {
readReschedule(nh);
- else
+ } else {
writeReschedule(nh);
+ }
#endif
break;
@@ -967,10 +973,11 @@ SSLNetVConnection::sslStartHandShake(int event, int &err)
const char *certfile = (const char *)this->options.clientCertificate;
if (certfile != nullptr) {
clientCTX = params->getCTX(certfile);
- if (clientCTX != nullptr)
+ if (clientCTX != nullptr) {
Debug("ssl", "context for %s is found at %p", this->options.clientCertificate.get(), (void *)clientCTX);
- else
+ } else {
Debug("ssl", "failed to find context for %s", this->options.clientCertificate.get());
+ }
}
} else {
clientCTX = params->client_ctx;
@@ -1255,8 +1262,9 @@ SSLNetVConnection::sslClientHandShakeEvent(int &err)
}
// if the handshake is complete and write is enabled reschedule the write
- if (closed == 0 && write.enabled)
+ if (closed == 0 && write.enabled) {
writeReschedule(nh);
+ }
SSL_INCREMENT_DYN_STAT(ssl_total_success_handshake_count_out_stat);
@@ -1408,10 +1416,11 @@ SSLNetVConnection::sslContextSet(void *ctx)
{
#if TS_USE_TLS_SNI
bool zret = true;
- if (ssl)
+ if (ssl) {
SSL_set_SSL_CTX(ssl, static_cast<SSL_CTX *>(ctx));
- else
+ } else {
zret = false;
+ }
#else
bool zret = false;
#endif
@@ -1518,8 +1527,9 @@ int
SSLNetVConnection::populate(Connection &con, Continuation *c, void *arg)
{
int retval = super::populate(con, c, arg);
- if (retval != EVENT_DONE)
+ if (retval != EVENT_DONE) {
return retval;
+ }
// Add in the SSL data
this->ssl = (SSL *)arg;
// Maybe bring over the stats?
@@ -1545,12 +1555,13 @@ SSLNetVConnection::map_tls_protocol_to_tag(const char *proto_string) const
} else if (*proto == '.') {
++proto; // skip .
if (proto.size() == 1) {
- if (*proto == '1')
+ if (*proto == '1') {
retval = IP_PROTO_TAG_TLS_1_1;
- else if (*proto == '2')
+ } else if (*proto == '2') {
retval = IP_PROTO_TAG_TLS_1_2;
- else if (*proto == '3')
+ } else if (*proto == '3') {
retval = IP_PROTO_TAG_TLS_1_3;
+ }
}
}
}
@@ -1563,8 +1574,9 @@ SSLNetVConnection::populate_protocol(ts::StringView *results, int n) const
int retval = 0;
if (n > retval) {
results[retval] = map_tls_protocol_to_tag(getSSLProtocol());
- if (results[retval])
+ if (results[retval]) {
++retval;
+ }
if (n > retval) {
retval += super::populate_protocol(results + retval, n - retval);
}
diff --git a/iocore/net/SSLSessionCache.cc b/iocore/net/SSLSessionCache.cc
index a28b4b2..71a5e43 100644
--- a/iocore/net/SSLSessionCache.cc
+++ b/iocore/net/SSLSessionCache.cc
@@ -128,8 +128,9 @@ SSLSessionBucket::insertSession(const SSLSessionID &id, SSL_SESSION *sess)
MUTEX_TRY_LOCK(lock, mutex, this_ethread());
if (!lock.is_locked()) {
SSL_INCREMENT_DYN_STAT(ssl_session_cache_lock_contention);
- if (SSLConfigParams::session_cache_skip_on_lock_contention)
+ if (SSLConfigParams::session_cache_skip_on_lock_contention) {
return;
+ }
lock.acquire(this_ethread());
}
@@ -159,8 +160,9 @@ SSLSessionBucket::getSession(const SSLSessionID &id, SSL_SESSION **sess)
MUTEX_TRY_LOCK(lock, mutex, this_ethread());
if (!lock.is_locked()) {
SSL_INCREMENT_DYN_STAT(ssl_session_cache_lock_contention);
- if (SSLConfigParams::session_cache_skip_on_lock_contention)
+ if (SSLConfigParams::session_cache_skip_on_lock_contention) {
return false;
+ }
lock.acquire(this_ethread());
}
diff --git a/iocore/net/SSLUtils.cc b/iocore/net/SSLUtils.cc
index ef20872..59a062a 100644
--- a/iocore/net/SSLUtils.cc
+++ b/iocore/net/SSLUtils.cc
@@ -322,8 +322,9 @@ set_context_cert(SSL *ssl)
// already made a best effort to find the best match.
if (likely(servername)) {
cc = lookup->find((char *)servername);
- if (cc && cc->ctx)
+ if (cc && cc->ctx) {
ctx = cc->ctx;
+ }
if (cc && SSLCertContext::OPT_TUNNEL == cc->opt && netvc->get_is_transparent()) {
netvc->attributes = HttpProxyPort::TRANSPORT_BLIND_TUNNEL;
netvc->setSSLHandShakeComplete(true);
@@ -339,8 +340,9 @@ set_context_cert(SSL *ssl)
safe_getsockname(netvc->get_socket(), &ip.sa, &namelen);
cc = lookup->find(ip);
- if (cc && cc->ctx)
+ if (cc && cc->ctx) {
ctx = cc->ctx;
+ }
}
if (ctx != nullptr) {
@@ -745,8 +747,9 @@ ssl_private_key_validate_exec(const char *cmdLine)
char *cmdLineCopy = ats_strdup(cmdLine);
char *ptr = cmdLineCopy;
- while (*ptr && !isspace(*ptr))
+ while (*ptr && !isspace(*ptr)) {
++ptr;
+ }
*ptr = 0;
if (access(cmdLineCopy, X_OK) != -1) {
bReturn = true;
@@ -1375,8 +1378,9 @@ ssl_index_certificate(SSLCertLookup *lookup, SSLCertContext const &cc, X509 *cer
subj_name = asn1_strdup(cn);
Debug("ssl", "mapping '%s' to certificate %s", (const char *)subj_name, certname);
- if (lookup->insert(subj_name, cc) >= 0)
+ if (lookup->insert(subj_name, cc) >= 0) {
inserted = true;
+ }
}
}
@@ -1394,8 +1398,9 @@ ssl_index_certificate(SSLCertLookup *lookup, SSLCertContext const &cc, X509 *cer
// only try to insert if the alternate name is not the main name
if (strcmp(dns, subj_name) != 0) {
Debug("ssl", "mapping '%s' to certificates %s", (const char *)dns, certname);
- if (lookup->insert(dns, cc) >= 0)
+ if (lookup->insert(dns, cc) >= 0) {
inserted = true;
+ }
}
}
}
@@ -2084,8 +2089,9 @@ ssl_callback_session_ticket(SSL *ssl, unsigned char *keyname, unsigned char *iv,
// Increase the total number of decrypted tickets.
SSL_INCREMENT_DYN_STAT(ssl_total_tickets_verified_stat);
- if (i != 0) // The number of tickets decrypted with "older" keys.
+ if (i != 0) { // The number of tickets decrypted with "older" keys.
SSL_INCREMENT_DYN_STAT(ssl_total_tickets_verified_old_key_stat);
+ }
SSLNetVConnection *netvc = SSLNetVCAccess(ssl);
netvc->setSSLSessionCacheHit(true);
diff --git a/iocore/net/Socks.cc b/iocore/net/Socks.cc
index c03413c..ad06956 100644
--- a/iocore/net/Socks.cc
+++ b/iocore/net/Socks.cc
@@ -49,10 +49,11 @@ SocksEntry::init(Ptr<ProxyMutex> &m, SocksNetVC *vc, unsigned char socks_support
socks_cmd = socks_support;
- if (ver == SOCKS_DEFAULT_VERSION)
+ if (ver == SOCKS_DEFAULT_VERSION) {
version = netProcessor.socks_conf_stuff->default_version;
- else
+ } else {
version = ver;
+ }
SET_HANDLER(&SocksEntry::startEvent);
@@ -91,15 +92,17 @@ SocksEntry::findServer()
server_params->findParent(&req_data, &server_result);
} else {
socks_conf_struct *conf = netProcessor.socks_conf_stuff;
- if ((nattempts - 1) % conf->per_server_connection_attempts)
+ if ((nattempts - 1) % conf->per_server_connection_attempts) {
return; // attempt again
+ }
server_params->markParentDown(&server_result);
- if (nattempts > conf->connection_attempts)
+ if (nattempts > conf->connection_attempts) {
server_result.result = PARENT_FAIL;
- else
+ } else {
server_params->nextParent(&req_data, &server_result);
+ }
}
switch (server_result.result) {
@@ -140,16 +143,19 @@ SocksEntry::free()
// so acquiring a lock shouldn't fail
ink_release_assert(lock.is_locked());
- if (timeout)
+ if (timeout) {
timeout->cancel(this);
+ }
#ifdef SOCKS_WITH_TS
- if (!lerrno && netVConnection && server_result.retry)
+ if (!lerrno && netVConnection && server_result.retry) {
server_params->markParentUp(&server_result);
+ }
#endif
- if ((action_.cancelled || lerrno) && netVConnection)
+ if ((action_.cancelled || lerrno) && netVConnection) {
netVConnection->do_io_close();
+ }
if (!action_.cancelled) {
if (lerrno || !netVConnection) {
@@ -182,8 +188,9 @@ SocksEntry::startEvent(int event, void *data)
if (event == NET_EVENT_OPEN) {
netVConnection = (SocksNetVC *)data;
- if (version == SOCKS5_VERSION)
+ if (version == SOCKS5_VERSION) {
auth_handler = &socks5BasicAuthHandler;
+ }
SET_HANDLER((SocksEntryHandler)&SocksEntry::mainEvent);
mainEvent(NET_EVENT_OPEN, data);
@@ -308,11 +315,11 @@ SocksEntry::mainEvent(int event, void *data)
buf->reset(); // Use the same buffer for a read now
- if (auth_handler)
+ if (auth_handler) {
n_bytes = invokeSocksAuthHandler(auth_handler, SOCKS_AUTH_WRITE_COMPLETE, nullptr);
- else if (socks_cmd == NORMAL_SOCKS)
+ } else if (socks_cmd == NORMAL_SOCKS) {
n_bytes = (version == SOCKS5_VERSION) ? SOCKS5_REP_LEN : SOCKS4_REP_LEN;
- else {
+ } else {
Debug("Socks", "Tunnelling the connection");
// let the client handle the response
free();
@@ -359,8 +366,9 @@ SocksEntry::mainEvent(int event, void *data)
}
}
- if (ret == EVENT_CONT)
+ if (ret == EVENT_CONT) {
break;
+ }
// Fall Through
case VC_EVENT_READ_COMPLETE:
if (timeout) {
@@ -387,8 +395,9 @@ SocksEntry::mainEvent(int event, void *data)
if (version == SOCKS5_VERSION) {
success = (p[0] == SOCKS5_VERSION && p[1] == SOCKS5_REQ_GRANTED);
Debug("Socks", "received reply of length %" PRId64 " addr type %d", ((VIO *)data)->ndone, (int)p[3]);
- } else
+ } else {
success = (p[0] == 0 && p[1] == SOCKS4_REQ_GRANTED);
+ }
// ink_assert(*(p) == 0);
if (!success) { // SOCKS request failed
@@ -522,8 +531,9 @@ error:
socks_conf_stuff->socks_needed = 0;
socks_conf_stuff->accept_enabled = 0;
- if (socks_config_fd >= 0)
+ if (socks_config_fd >= 0) {
::close(socks_config_fd);
+ }
}
int
@@ -542,11 +552,13 @@ loadSocksAuthInfo(int fd, socks_conf_struct *socks_stuff)
bool end_of_file = false;
do {
int n = 0, rc;
- while (((rc = read(fd, &c, 1)) == 1) && (c != '\n') && (n < 254))
+ while (((rc = read(fd, &c, 1)) == 1) && (c != '\n') && (n < 254)) {
line[n++] = c;
- if (rc <= 0)
+ }
+ if (rc <= 0) {
end_of_file = true;
- line[n] = '\0';
+ }
+ line[n] = '\0';
// coverity[secure_coding]
rc = sscanf(line, " auth u %255s %255s ", user_name, passwd);
@@ -585,8 +597,9 @@ socks5BasicAuthHandler(int event, unsigned char *p, void (**h_ptr)(void))
p[ret++] = SOCKS5_VERSION; // version
p[ret++] = (pass_phrase) ? 2 : 1; //#Methods
p[ret++] = 0; // no authentication
- if (pass_phrase)
+ if (pass_phrase) {
p[ret++] = 2;
+ }
break;
@@ -612,8 +625,9 @@ socks5BasicAuthHandler(int event, unsigned char *p, void (**h_ptr)(void))
"when not supplied as an option");
ret = -1;
*h_ptr = nullptr;
- } else
+ } else {
*(SocksAuthHandler *)h_ptr = &socks5PasswdAuthHandler;
+ }
break;
diff --git a/iocore/net/UnixConnection.cc b/iocore/net/UnixConnection.cc
index 742f150..8f01d46 100644
--- a/iocore/net/UnixConnection.cc
+++ b/iocore/net/UnixConnection.cc
@@ -55,8 +55,9 @@ Connection::setup_mc_send(sockaddr const *mc_addr, sockaddr const *my_addr, bool
int enable_reuseaddr = 1;
in_addr_t mc_if = ats_ip4_addr_cast(my_addr);
- if ((res = socketManager.socket(my_addr->sa_family, SOCK_DGRAM, 0)) < 0)
+ if ((res = socketManager.socket(my_addr->sa_family, SOCK_DGRAM, 0)) < 0) {
goto Lerror;
+ }
fd = res;
@@ -70,33 +71,40 @@ Connection::setup_mc_send(sockaddr const *mc_addr, sockaddr const *my_addr, bool
ats_ip_copy(&addr, mc_addr);
- if ((res = safe_fcntl(fd, F_SETFD, FD_CLOEXEC)) < 0)
+ if ((res = safe_fcntl(fd, F_SETFD, FD_CLOEXEC)) < 0) {
goto Lerror;
+ }
- if (non_blocking)
- if ((res = safe_nonblocking(fd)) < 0)
+ if (non_blocking) {
+ if ((res = safe_nonblocking(fd)) < 0) {
goto Lerror;
+ }
+ }
// Set MultiCast TTL to specified value
- if ((res = safe_setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, (char *)&mc_ttl, sizeof(mc_ttl)) < 0))
+ if ((res = safe_setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, (char *)&mc_ttl, sizeof(mc_ttl)) < 0)) {
goto Lerror;
+ }
// Set MultiCast Interface to specified value
- if ((res = safe_setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, (char *)&mc_if, sizeof(mc_if)) < 0))
+ if ((res = safe_setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, (char *)&mc_if, sizeof(mc_if)) < 0)) {
goto Lerror;
+ }
// Disable MultiCast loopback if requested
if (!mc_loopback) {
char loop = 0;
- if ((res = safe_setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&loop, sizeof(loop)) < 0))
+ if ((res = safe_setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&loop, sizeof(loop)) < 0)) {
goto Lerror;
+ }
}
return 0;
Lerror:
- if (fd != NO_FD)
+ if (fd != NO_FD) {
close();
+ }
return res;
}
@@ -111,25 +119,31 @@ Connection::setup_mc_receive(sockaddr const *mc_addr, sockaddr const *my_addr, b
int enable_reuseaddr = 1;
IpAddr inaddr_any(INADDR_ANY);
- if ((res = socketManager.socket(mc_addr->sa_family, SOCK_DGRAM, 0)) < 0)
+ if ((res = socketManager.socket(mc_addr->sa_family, SOCK_DGRAM, 0)) < 0) {
goto Lerror;
+ }
fd = res;
- if ((res = safe_fcntl(fd, F_SETFD, FD_CLOEXEC)) < 0)
+ if ((res = safe_fcntl(fd, F_SETFD, FD_CLOEXEC)) < 0) {
goto Lerror;
+ }
- if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&enable_reuseaddr, sizeof(enable_reuseaddr)) < 0))
+ if ((res = safe_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&enable_reuseaddr, sizeof(enable_reuseaddr)) < 0)) {
goto Lerror;
+ }
addr.assign(inaddr_any, ats_ip_port_cast(mc_addr));
- if ((res = socketManager.ink_bind(fd, &addr.sa, ats_ip_size(&addr.sa), IPPROTO_TCP)) < 0)
+ if ((res = socketManager.ink_bind(fd, &addr.sa, ats_ip_size(&addr.sa), IPPROTO_TCP)) < 0) {
goto Lerror;
+ }
- if (non_blocking)
- if ((res = safe_nonblocking(fd)) < 0)
+ if (non_blocking) {
+ if ((res = safe_nonblocking(fd)) < 0) {
goto Lerror;
+ }
+ }
if (ats_is_ip4(&addr)) {
struct ip_mreq mc_request;
@@ -137,14 +151,16 @@ Connection::setup_mc_receive(sockaddr const *mc_addr, sockaddr const *my_addr, b
mc_request.imr_multiaddr.s_addr = ats_ip4_addr_cast(mc_addr);
mc_request.imr_interface.s_addr = ats_ip4_addr_cast(my_addr);
- if ((res = safe_setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mc_request, sizeof(mc_request)) < 0))
+ if ((res = safe_setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mc_request, sizeof(mc_request)) < 0)) {
goto Lerror;
+ }
}
return 0;
Lerror:
- if (fd != NO_FD)
+ if (fd != NO_FD) {
close();
+ }
return res;
}
@@ -184,8 +200,9 @@ template <typename T> struct cleaner {
cleaner(T *_obj, method _method) : obj(_obj), m(_method) {}
~cleaner()
{
- if (obj)
+ if (obj) {
(obj->*m)();
+ }
}
void
reset()
@@ -245,8 +262,9 @@ Connection::open(NetVCOptions const &opt)
}
res = socketManager.socket(family, sock_type, 0);
- if (-1 == res)
+ if (-1 == res) {
return -errno;
+ }
fd = res;
// mark fd for close until we succeed.
@@ -254,8 +272,9 @@ Connection::open(NetVCOptions const &opt)
// Try setting the various socket options, if requested.
- if (-1 == safe_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&enable_reuseaddr), sizeof(enable_reuseaddr)))
+ if (-1 == safe_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&enable_reuseaddr), sizeof(enable_reuseaddr))) {
return -errno;
+ }
if (NetVCOptions::FOREIGN_ADDR == opt.addr_binding) {
static char const *const DEBUG_TEXT = "::open setsockopt() IP_TRANSPARENT";
@@ -272,15 +291,17 @@ Connection::open(NetVCOptions const &opt)
#endif
}
- if (!opt.f_blocking_connect && -1 == safe_nonblocking(fd))
+ if (!opt.f_blocking_connect && -1 == safe_nonblocking(fd)) {
return -errno;
+ }
if (opt.socket_recv_bufsize > 0) {
if (socketManager.set_rcvbuf_size(fd, opt.socket_recv_bufsize)) {
// Round down until success
int rbufsz = ROUNDUP(opt.socket_recv_bufsize, 1024);
- while (rbufsz && !socketManager.set_rcvbuf_size(fd, rbufsz))
+ while (rbufsz && !socketManager.set_rcvbuf_size(fd, rbufsz)) {
rbufsz -= 1024;
+ }
Debug("socket", "::open: recv_bufsize = %d of %d", rbufsz, opt.socket_recv_bufsize);
}
}
@@ -288,8 +309,9 @@ Connection::open(NetVCOptions const &opt)
if (socketManager.set_sndbuf_size(fd, opt.socket_send_bufsize)) {
// Round down until success
int sbufsz = ROUNDUP(opt.socket_send_bufsize, 1024);
- while (sbufsz && !socketManager.set_sndbuf_size(fd, sbufsz))
+ while (sbufsz && !socketManager.set_sndbuf_size(fd, sbufsz)) {
sbufsz -= 1024;
+ }
Debug("socket", "::open: send_bufsize = %d of %d", sbufsz, opt.socket_send_bufsize);
}
}
@@ -298,8 +320,9 @@ Connection::open(NetVCOptions const &opt)
apply_options(opt);
if (local_addr.port() || !is_any_address) {
- if (-1 == socketManager.ink_bind(fd, &local_addr.sa, ats_ip_size(&local_addr.sa)))
+ if (-1 == socketManager.ink_bind(fd, &local_addr.sa, ats_ip_size(&local_addr.sa))) {
return -errno;
+ }
}
cleanup.reset();
@@ -342,11 +365,13 @@ Connection::connect(sockaddr const *target, NetVCOptions const &opt)
if (-1 == res && (opt.f_blocking_connect || !(EINPROGRESS == errno || EWOULDBLOCK == errno))) {
return -errno;
} else if (opt.f_blocking_connect && !opt.f_blocking) {
- if (-1 == safe_nonblocking(fd))
+ if (-1 == safe_nonblocking(fd)) {
return -errno;
+ }
} else if (!opt.f_blocking_connect && opt.f_blocking) {
- if (-1 == safe_blocking(fd))
+ if (-1 == safe_blocking(fd)) {
return -errno;
+ }
}
cleanup.reset();
diff --git a/iocore/net/UnixNet.cc b/iocore/net/UnixNet.cc
index b574032..b11dc06 100644
--- a/iocore/net/UnixNet.cc
+++ b/iocore/net/UnixNet.cc
@@ -362,8 +362,9 @@ NetHandler::process_enabled_list(NetHandler *nh)
vc->ep.modify(EVENTIO_READ);
vc->ep.refresh(EVENTIO_READ);
vc->read.in_enabled_list = 0;
- if ((vc->read.enabled && vc->read.triggered) || vc->closed)
+ if ((vc->read.enabled && vc->read.triggered) || vc->closed) {
nh->read_ready_list.in_or_enqueue(vc);
+ }
}
SListM(UnixNetVConnection, NetState, write, enable_link) wq(nh->write_enable_list.popall());
@@ -371,8 +372,9 @@ NetHandler::process_enabled_list(NetHandler *nh)
vc->ep.modify(EVENTIO_WRITE);
vc->ep.refresh(EVENTIO_WRITE);
vc->write.in_enabled_list = 0;
- if ((vc->write.enabled && vc->write.triggered) || vc->closed)
+ if ((vc->write.enabled && vc->write.triggered) || vc->closed) {
nh->write_ready_list.in_or_enqueue(vc);
+ }
}
}
@@ -393,10 +395,11 @@ NetHandler::mainNetEvent(int event, Event *e)
NET_INCREMENT_DYN_STAT(net_handler_run_stat);
process_enabled_list(this);
- if (likely(!read_ready_list.empty() || !write_ready_list.empty() || !read_enable_list.empty() || !write_enable_list.empty()))
+ if (likely(!read_ready_list.empty() || !write_ready_list.empty() || !read_enable_list.empty() || !write_enable_list.empty())) {
poll_timeout = 0; // poll immediately returns -- we have triggered stuff to process right now
- else
+ } else {
poll_timeout = net_config_poll_timeout;
+ }
PollDescriptor *pd = get_PollDescriptor(trigger_event->ethread);
UnixNetVConnection *vc = nullptr;
@@ -503,11 +506,11 @@ NetHandler::mainNetEvent(int event, Event *e)
while ((vc = read_ready_list.dequeue())) {
// Initialize the thread-local continuation flags
set_cont_flags(vc->control_flags);
- if (vc->closed)
+ if (vc->closed) {
close_UnixNetVConnection(vc, trigger_event->ethread);
- else if (vc->read.triggered && (vc->read.enabled || (vc->read.error && vc->read.vio._cont != nullptr)))
+ } else if (vc->read.triggered && (vc->read.enabled || (vc->read.error && vc->read.vio._cont != nullptr))) {
vc->net_read_io(this, trigger_event->ethread);
- else if (!vc->read.enabled) {
+ } else if (!vc->read.enabled) {
read_ready_list.remove(vc);
#if defined(solaris)
if (vc->read.triggered && vc->write.enabled) {
@@ -520,11 +523,11 @@ NetHandler::mainNetEvent(int event, Event *e)
}
while ((vc = write_ready_list.dequeue())) {
set_cont_flags(vc->control_flags);
- if (vc->closed)
+ if (vc->closed) {
close_UnixNetVConnection(vc, trigger_event->ethread);
- else if (vc->write.triggered && (vc->write.enabled || (vc->write.error && vc->write.vio._cont != nullptr)))
+ } else if (vc->write.triggered && (vc->write.enabled || (vc->write.error && vc->write.vio._cont != nullptr))) {
write_to_net(this, vc, trigger_event->ethread);
- else if (!vc->write.enabled) {
+ } else if (!vc->write.enabled) {
write_ready_list.remove(vc);
#if defined(solaris)
if (vc->write.triggered && vc->read.enabled) {
diff --git a/iocore/net/UnixNetAccept.cc b/iocore/net/UnixNetAccept.cc
index 2afd8dd..63accc1 100644
--- a/iocore/net/UnixNetAccept.cc
+++ b/iocore/net/UnixNetAccept.cc
@@ -62,12 +62,13 @@ net_accept(NetAccept *na, void *ep, bool blockable)
// added by YTS Team, yamsat
do {
if ((res = na->server.accept(&con)) < 0) {
- if (res == -EAGAIN || res == -ECONNABORTED || res == -EPIPE)
+ if (res == -EAGAIN || res == -ECONNABORTED || res == -EPIPE) {
goto Ldone;
+ }
if (na->server.fd != NO_FD && !na->action_->cancelled) {
- if (!blockable)
+ if (!blockable) {
na->action_->continuation->handleEvent(EVENT_ERROR, (void *)(intptr_t)res);
- else {
+ } else {
SCOPED_MUTEX_LOCK(lock, na->action_->mutex, e->ethread);
na->action_->continuation->handleEvent(EVENT_ERROR, (void *)(intptr_t)res);
}
@@ -78,8 +79,9 @@ net_accept(NetAccept *na, void *ep, bool blockable)
NET_SUM_GLOBAL_DYN_STAT(net_tcp_accept_stat, 1);
vc = static_cast<UnixNetVConnection *>(na->getNetProcessor()->allocate_vc(e->ethread));
- if (!vc)
+ if (!vc) {
goto Ldone; // note: @a con will clean up the socket when it goes out of scope.
+ }
++count;
NET_SUM_GLOBAL_DYN_STAT(net_connections_currently_open_stat, 1);
@@ -92,15 +94,17 @@ net_accept(NetAccept *na, void *ep, bool blockable)
vc->set_context(NET_VCONNECTION_IN);
SET_CONTINUATION_HANDLER(vc, (NetVConnHandler)&UnixNetVConnection::acceptEvent);
- if (e->ethread->is_event_type(na->opt.etype))
+ if (e->ethread->is_event_type(na->opt.etype)) {
vc->handleEvent(EVENT_NONE, e);
- else
+ } else {
eventProcessor.schedule_imm(vc, na->opt.etype);
+ }
} while (loop);
Ldone:
- if (!blockable)
+ if (!blockable) {
MUTEX_UNTAKE_LOCK(na->action_->mutex.get(), e->ethread);
+ }
return count;
}
@@ -134,8 +138,9 @@ NetAccept::init_accept_loop(const char *thr_name)
void
NetAccept::init_accept(EThread *t)
{
- if (!t)
+ if (!t) {
t = eventProcessor.assign_thread(opt.etype);
+ }
if (!action_->continuation->mutex) {
action_->continuation->mutex = t->mutex;
@@ -162,10 +167,11 @@ NetAccept::init_accept_per_thread()
return;
}
- if (accept_fn == net_accept)
+ if (accept_fn == net_accept) {
SET_HANDLER((NetAcceptHandler)&NetAccept::acceptFastEvent);
- else
+ } else {
SET_HANDLER((NetAcceptHandler)&NetAccept::acceptEvent);
+ }
period = -HRTIME_MSECONDS(net_accept_period);
n = eventProcessor.n_threads_for_type[opt.etype];
@@ -182,8 +188,9 @@ NetAccept::init_accept_per_thread()
EThread *t = eventProcessor.eventthread[opt.etype][i];
PollDescriptor *pd = get_PollDescriptor(t);
- if (a->ep.start(pd, a, EVENTIO_READ) < 0)
+ if (a->ep.start(pd, a, EVENTIO_READ) < 0) {
Warning("[NetAccept::init_accept_per_thread]:error starting EventIO");
+ }
a->mutex = get_NetHandler(t)->mutex;
t->schedule_every(a, period, opt.etype);
@@ -208,10 +215,11 @@ NetAccept::do_listen(bool non_blocking)
}
if (opt.f_callback_on_open && !action_->cancelled) {
- if (res)
+ if (res) {
action_->continuation->handleEvent(NET_EVENT_ACCEPT_FAILED, this);
- else
+ } else {
action_->continuation->handleEvent(NET_EVENT_ACCEPT_SUCCEED, this);
+ }
mutex = nullptr;
}
@@ -234,8 +242,9 @@ NetAccept::do_blocking_accept(EThread *t)
if ((res = server.accept(&con)) < 0) {
int seriousness = accept_error_seriousness(res);
if (seriousness >= 0) { // not so bad
- if (!seriousness) // bad enough to warn about
+ if (!seriousness) { // bad enough to warn about
check_transient_accept_error(res);
+ }
safe_delay(net_throttle_delay);
return 0;
}
@@ -363,8 +372,9 @@ NetAccept::acceptFastEvent(int event, void *ep)
if (unlikely(socketManager.set_sndbuf_size(fd, opt.send_bufsize))) {
bufsz = ROUNDUP(opt.send_bufsize, 1024);
while (bufsz > 0) {
- if (!socketManager.set_sndbuf_size(fd, bufsz))
+ if (!socketManager.set_sndbuf_size(fd, bufsz)) {
break;
+ }
bufsz -= 1024;
}
}
@@ -373,8 +383,9 @@ NetAccept::acceptFastEvent(int event, void *ep)
if (unlikely(socketManager.set_rcvbuf_size(fd, opt.recv_bufsize))) {
bufsz = ROUNDUP(opt.recv_bufsize, 1024);
while (bufsz > 0) {
- if (!socketManager.set_rcvbuf_size(fd, bufsz))
+ if (!socketManager.set_rcvbuf_size(fd, bufsz)) {
break;
+ }
bufsz -= 1024;
}
}
@@ -405,8 +416,9 @@ NetAccept::acceptFastEvent(int event, void *ep)
check_transient_accept_error(res);
goto Ldone;
}
- if (!action_->cancelled)
+ if (!action_->cancelled) {
action_->continuation->handleEvent(EVENT_ERROR, (void *)(intptr_t)res);
+ }
goto Lerror;
}
@@ -464,8 +476,9 @@ Ldone:
Lerror:
server.close();
e->cancel();
- if (vc)
+ if (vc) {
vc->free(e->ethread);
+ }
NET_DECREMENT_DYN_STAT(net_accepts_currently_open_stat);
delete this;
return EVENT_DONE;
@@ -478,8 +491,9 @@ NetAccept::acceptLoopEvent(int event, Event *e)
(void)e;
EThread *t = this_ethread();
- while (do_blocking_accept(t) >= 0)
+ while (do_blocking_accept(t) >= 0) {
;
+ }
// Don't think this ever happens ...
NET_DECREMENT_DYN_STAT(net_accepts_currently_open_stat);
diff --git a/iocore/net/UnixNetPages.cc b/iocore/net/UnixNetPages.cc
index a20e1a8..288a031 100644
--- a/iocore/net/UnixNetPages.cc
+++ b/iocore/net/UnixNetPages.cc
@@ -64,8 +64,9 @@ struct ShowNet : public ShowCont {
forl_LL(UnixNetVConnection, vc, nh->open_list)
{
// uint16_t port = ats_ip_port_host_order(&addr.sa);
- if (ats_is_ip(&addr) && !ats_ip_addr_port_eq(&addr.sa, vc->get_remote_addr()))
+ if (ats_is_ip(&addr) && !ats_ip_addr_port_eq(&addr.sa, vc->get_remote_addr())) {
continue;
+ }
// if (port && port != ats_ip_port_host_order(&vc->server_addr.sa) && port != vc->accept_port)
// continue;
char ipbuf[INET6_ADDRSTRLEN];
@@ -103,9 +104,9 @@ struct ShowNet : public ShowCont {
vc->f.shutdown, vc->closed ? "closed " : ""));
}
ithread++;
- if (ithread < eventProcessor.n_threads_for_type[ET_NET])
+ if (ithread < eventProcessor.n_threads_for_type[ET_NET]) {
eventProcessor.eventthread[ET_NET][ithread]->schedule_imm(this);
- else {
+ } else {
CHECK_SHOW(show("</table>\n"));
return complete(event, e);
}
@@ -166,10 +167,11 @@ struct ShowNet : public ShowCont {
CHECK_SHOW(show("<tr><th>#</th><th>Read Priority</th><th>Read Bucket</th><th>Write Priority</th><th>Write Bucket</th></tr>\n"));
CHECK_SHOW(show("</table>\n"));
ithread++;
- if (ithread < eventProcessor.n_threads_for_type[ET_NET])
+ if (ithread < eventProcessor.n_threads_for_type[ET_NET]) {
eventProcessor.eventthread[ET_NET][ithread]->schedule_imm(this);
- else
+ } else {
return complete(event, e);
+ }
return EVENT_CONT;
}
@@ -220,20 +222,24 @@ register_ShowNet(Continuation *c, HTTPHdr *h)
const char *query = h->url_get()->query_get(&query_len);
s->sarg = ats_strndup(query, query_len);
char *gn = nullptr;
- if (s->sarg)
+ if (s->sarg) {
gn = (char *)memchr(s->sarg, '=', strlen(s->sarg));
- if (gn)
+ }
+ if (gn) {
ats_ip_pton(gn + 1, &s->addr);
+ }
SET_CONTINUATION_HANDLER(s, &ShowNet::showConnections);
} else if (STREQ_PREFIX(path, path_len, "ports")) {
int query_len;
const char *query = h->url_get()->query_get(&query_len);
s->sarg = ats_strndup(query, query_len);
char *gn = nullptr;
- if (s->sarg)
+ if (s->sarg) {
gn = (char *)memchr(s->sarg, '=', strlen(s->sarg));
- if (gn)
+ }
+ if (gn) {
ats_ip_port_cast(&s->addr.sa) = htons(atoi(gn + 1));
+ }
SET_CONTINUATION_HANDLER(s, &ShowNet::showConnections);
}
eventProcessor.schedule_imm(s, ET_TASK);
diff --git a/iocore/net/UnixNetProcessor.cc b/iocore/net/UnixNetProcessor.cc
index 905d268..a7a89c7 100644
--- a/iocore/net/UnixNetProcessor.cc
+++ b/iocore/net/UnixNetProcessor.cc
@@ -127,8 +127,9 @@ UnixNetProcessor::accept_internal(Continuation *cont, int fd, AcceptOptions cons
int should_filter_int = 0;
na->server.http_accept_filter = false;
REC_ReadConfigInteger(should_filter_int, "proxy.config.net.defer_accept");
- if (should_filter_int > 0 && opt.etype == ET_NET)
+ if (should_filter_int > 0 && opt.etype == ET_NET) {
na->server.http_accept_filter = true;
+ }
SessionAccept *sa = dynamic_cast<SessionAccept *>(cont);
na->proxyPort = sa ? sa->proxyPort : nullptr;
@@ -201,10 +202,11 @@ UnixNetProcessor::connect_re_internal(Continuation *cont, sockaddr const *target
EThread *t = cont->mutex->thread_holding;
UnixNetVConnection *vc = (UnixNetVConnection *)this->allocate_vc(t);
- if (opt)
+ if (opt) {
vc->options = *opt;
- else
+ } else {
opt = &vc->options;
+ }
vc->set_context(NET_VCONNECTION_OUT);
bool using_socks = (socks_conf_stuff->socks_needed && opt->socks_support != NO_SOCKS
@@ -259,10 +261,11 @@ UnixNetProcessor::connect_re_internal(Continuation *cont, sockaddr const *target
if (lock2.is_locked()) {
int ret;
ret = vc->connectUp(t, NO_FD);
- if ((using_socks) && (ret == CONNECT_SUCCESS))
+ if ((using_socks) && (ret == CONNECT_SUCCESS)) {
return &socksEntry->action_;
- else
+ } else {
return ACTION_RESULT_DONE;
+ }
}
}
}
@@ -274,8 +277,9 @@ UnixNetProcessor::connect_re_internal(Continuation *cont, sockaddr const *target
}
if (using_socks) {
return &socksEntry->action_;
- } else
+ } else {
return result;
+ }
}
Action *
@@ -310,8 +314,9 @@ struct CheckConnect : public Continuation {
case NET_EVENT_OPEN_FAILED:
Debug("iocore_net_connect", "connect Net open failed");
- if (!action_.cancelled)
+ if (!action_.cancelled) {
action_.continuation->handleEvent(NET_EVENT_OPEN_FAILED, (void *)e);
+ }
break;
case VC_EVENT_WRITE_READY:
@@ -337,22 +342,26 @@ struct CheckConnect : public Continuation {
}
}
vc->do_io_close();
- if (!action_.cancelled)
+ if (!action_.cancelled) {
action_.continuation->handleEvent(NET_EVENT_OPEN_FAILED, (void *)-ENET_CONNECT_FAILED);
+ }
break;
case VC_EVENT_INACTIVITY_TIMEOUT:
Debug("iocore_net_connect", "connect timed out");
vc->do_io_close();
- if (!action_.cancelled)
+ if (!action_.cancelled) {
action_.continuation->handleEvent(NET_EVENT_OPEN_FAILED, (void *)-ENET_CONNECT_TIMEOUT);
+ }
break;
default:
ink_assert(!"unknown connect event");
- if (!action_.cancelled)
+ if (!action_.cancelled) {
action_.continuation->handleEvent(NET_EVENT_OPEN_FAILED, (void *)-ENET_CONNECT_FAILED);
+ }
}
- if (!recursion)
+ if (!recursion) {
delete this;
+ }
return EVENT_DONE;
}
@@ -364,9 +373,9 @@ struct CheckConnect : public Continuation {
recursion++;
netProcessor.connect_re(this, target, opt);
recursion--;
- if (connect_status != NET_EVENT_OPEN_FAILED)
+ if (connect_status != NET_EVENT_OPEN_FAILED) {
return &action_;
- else {
+ } else {
delete this;
return ACTION_RESULT_DONE;
}
@@ -444,8 +453,9 @@ UnixNetProcessor::start(int, size_t)
* Stat pages
*/
extern Action *register_ShowNet(Continuation * c, HTTPHdr * h);
- if (etype == ET_NET)
+ if (etype == ET_NET) {
statPagesManager.register_http("net", register_ShowNet);
+ }
return 1;
}
diff --git a/iocore/net/UnixNetVConnection.cc b/iocore/net/UnixNetVConnection.cc
index ac6f6c0..ef8dbaf 100644
--- a/iocore/net/UnixNetVConnection.cc
+++ b/iocore/net/UnixNetVConnection.cc
@@ -44,8 +44,9 @@ read_reschedule(NetHandler *nh, UnixNetVConnection *vc)
vc->ep.refresh(EVENTIO_READ);
if (vc->read.triggered && vc->read.enabled) {
nh->read_ready_list.in_or_enqueue(vc);
- } else
+ } else {
nh->read_ready_list.remove(vc);
+ }
}
static inline void
@@ -54,8 +55,9 @@ write_reschedule(NetHandler *nh, UnixNetVConnection *vc)
vc->ep.refresh(EVENTIO_WRITE);
if (vc->write.triggered && vc->write.enabled) {
nh->write_ready_list.in_or_enqueue(vc);
- } else
+ } else {
nh->write_ready_list.remove(vc);
+ }
}
void
@@ -75,10 +77,11 @@ net_activity(UnixNetVConnection *vc, EThread *thread)
vc->inactivity_timeout = 0;
}
#else
- if (vc->inactivity_timeout_in)
+ if (vc->inactivity_timeout_in) {
vc->next_inactivity_timeout_at = Thread::get_hrtime() + vc->inactivity_timeout_in;
- else
+ } else {
vc->next_inactivity_timeout_at = 0;
+ }
#endif
}
@@ -305,8 +308,9 @@ read_from_net(NetHandler *nh, UnixNetVConnection *vc, EThread *thread)
return;
}
int64_t toread = buf.writer()->write_avail();
- if (toread > ntodo)
+ if (toread > ntodo) {
toread = ntodo;
+ }
// read data
int64_t rattempted = 0, total_read = 0;
@@ -322,13 +326,15 @@ read_from_net(NetHandler *nh, UnixNetVConnection *vc, EThread *thread)
if (a > 0) {
tiovec[niov].iov_base = b->_end;
int64_t togo = toread - total_read - rattempted;
- if (a > togo)
- a = togo;
+ if (a > togo) {
+ a = togo;
+ }
tiovec[niov].iov_len = a;
rattempted += a;
niov++;
- if (a >= togo)
+ if (a >= togo) {
break;
+ }
}
b = b->next.get();
}
@@ -362,10 +368,11 @@ read_from_net(NetHandler *nh, UnixNetVConnection *vc, EThread *thread)
// if we have already moved some bytes successfully, summarize in r
if (total_read != rattempted) {
- if (r <= 0)
+ if (r <= 0) {
r = total_read - rattempted;
- else
+ } else {
r = total_read - rattempted + r;
+ }
}
// check for errors
if (r <= 0) {
@@ -396,8 +403,9 @@ read_from_net(NetHandler *nh, UnixNetVConnection *vc, EThread *thread)
#endif
s->vio.ndone += r;
net_activity(vc, thread);
- } else
+ } else {
r = 0;
+ }
// Signal read ready, check if user is not done
if (r) {
@@ -702,8 +710,9 @@ UnixNetVConnection::do_io_read(Continuation *c, int64_t nbytes, MIOBuffer *buf)
read.vio.vc_server = (VConnection *)this;
if (buf) {
read.vio.buffer.writer_for(buf);
- if (!read.enabled)
+ if (!read.enabled) {
read.vio.reenable();
+ }
} else {
read.vio.buffer.clear();
read.enabled = 0;
@@ -727,8 +736,9 @@ UnixNetVConnection::do_io_write(Continuation *c, int64_t nbytes, IOBufferReader
if (reader) {
ink_assert(!owner);
write.vio.buffer.reader_for(reader);
- if (nbytes && !write.enabled)
+ if (nbytes && !write.enabled) {
write.vio.reenable();
+ }
} else {
write.enabled = 0;
}
@@ -753,15 +763,18 @@ UnixNetVConnection::do_io_close(int alerrno /* = -1 */)
bool close_inline = !recursion && (!nh || nh->mutex->thread_holding == t);
INK_WRITE_MEMORY_BARRIER;
- if (alerrno && alerrno != -1)
+ if (alerrno && alerrno != -1) {
this->lerrno = alerrno;
- if (alerrno == -1)
+ }
+ if (alerrno == -1) {
closed = 1;
- else
+ } else {
closed = -1;
+ }
- if (close_inline)
+ if (close_inline) {
close_UnixNetVConnection(this, t);
+ }
}
void
@@ -865,11 +878,13 @@ UnixNetVConnection::send_OOB(Continuation *cont, char *buf, int len)
void
UnixNetVConnection::reenable(VIO *vio)
{
- if (STATE_FROM_VIO(vio)->enabled)
+ if (STATE_FROM_VIO(vio)->enabled) {
return;
+ }
set_enabled(vio);
- if (!thread)
+ if (!thread) {
return;
+ }
EThread *t = vio->mutex->thread_holding;
ink_assert(t == this_ethread());
ink_release_assert(!closed);
@@ -877,17 +892,19 @@ UnixNetVConnection::reenable(VIO *vio)
if (vio == &read.vio) {
ep.modify(EVENTIO_READ);
ep.refresh(EVENTIO_READ);
- if (read.triggered)
+ if (read.triggered) {
nh->read_ready_list.in_or_enqueue(this);
- else
+ } else {
nh->read_ready_list.remove(this);
+ }
} else {
ep.modify(EVENTIO_WRITE);
ep.refresh(EVENTIO_WRITE);
- if (write.triggered)
+ if (write.triggered) {
nh->write_ready_list.in_or_enqueue(this);
- else
+ } else {
nh->write_ready_list.remove(this);
+ }
}
} else {
MUTEX_TRY_LOCK(lock, nh->mutex, t);
@@ -903,23 +920,26 @@ UnixNetVConnection::reenable(VIO *vio)
nh->write_enable_list.push(this);
}
}
- if (nh->trigger_event && nh->trigger_event->ethread->signal_hook)
+ if (nh->trigger_event && nh->trigger_event->ethread->signal_hook) {
nh->trigger_event->ethread->signal_hook(nh->trigger_event->ethread);
+ }
} else {
if (vio == &read.vio) {
ep.modify(EVENTIO_READ);
ep.refresh(EVENTIO_READ);
- if (read.triggered)
+ if (read.triggered) {
nh->read_ready_list.in_or_enqueue(this);
- else
+ } else {
nh->read_ready_list.remove(this);
+ }
} else {
ep.modify(EVENTIO_WRITE);
ep.refresh(EVENTIO_WRITE);
- if (write.triggered)
+ if (write.triggered) {
nh->write_ready_list.in_or_enqueue(this);
- else
+ } else {
nh->write_ready_list.remove(this);
+ }
}
}
}
@@ -928,8 +948,9 @@ UnixNetVConnection::reenable(VIO *vio)
void
UnixNetVConnection::reenable_re(VIO *vio)
{
- if (!thread)
+ if (!thread) {
return;
+ }
EThread *t = vio->mutex->thread_holding;
ink_assert(t == this_ethread());
if (nh->mutex->thread_holding == t) {
@@ -937,20 +958,23 @@ UnixNetVConnection::reenable_re(VIO *vio)
if (vio == &read.vio) {
ep.modify(EVENTIO_READ);
ep.refresh(EVENTIO_READ);
- if (read.triggered)
+ if (read.triggered) {
net_read_io(nh, t);
- else
+ } else {
nh->read_ready_list.remove(this);
+ }
} else {
ep.modify(EVENTIO_WRITE);
ep.refresh(EVENTIO_WRITE);
- if (write.triggered)
+ if (write.triggered) {
write_to_net(nh, this, t);
- else
+ } else {
nh->write_ready_list.remove(this);
+ }
}
- } else
+ } else {
reenable(vio);
+ }
}
UnixNetVConnection::UnixNetVConnection()
@@ -995,8 +1019,9 @@ UnixNetVConnection::set_enabled(VIO *vio)
inactivity_timeout = thread->schedule_in(this, inactivity_timeout_in);
}
#else
- if (!next_inactivity_timeout_at && inactivity_timeout_in)
+ if (!next_inactivity_timeout_at && inactivity_timeout_in) {
next_inactivity_timeout_at = Thread::get_hrtime() + inactivity_timeout_in;
+ }
#endif
}
@@ -1172,10 +1197,11 @@ UnixNetVConnection::startEvent(int /* event ATS_UNUSED */, Event *e)
e->schedule_in(HRTIME_MSECONDS(net_retry_delay));
return EVENT_CONT;
}
- if (!action_.cancelled)
+ if (!action_.cancelled) {
connectUp(e->ethread, NO_FD);
- else
+ } else {
free(e->ethread);
+ }
return EVENT_DONE;
}
@@ -1282,8 +1308,9 @@ UnixNetVConnection::mainEvent(int event, Event *e)
/* BZ 49408 */
// ink_assert(inactivity_timeout_in);
// ink_assert(next_inactivity_timeout_at < Thread::get_hrtime());
- if (!inactivity_timeout_in || next_inactivity_timeout_at > Thread::get_hrtime())
+ if (!inactivity_timeout_in || next_inactivity_timeout_at > Thread::get_hrtime()) {
return EVENT_CONT;
+ }
signal_event = VC_EVENT_INACTIVITY_TIMEOUT;
signal_timeout_at = &next_inactivity_timeout_at;
} else {
@@ -1303,14 +1330,17 @@ UnixNetVConnection::mainEvent(int event, Event *e)
if (read.vio.op == VIO::READ && !(f.shutdown & NET_VC_SHUTDOWN_READ)) {
reader_cont = read.vio._cont;
- if (read_signal_and_update(signal_event, this) == EVENT_DONE)
+ if (read_signal_and_update(signal_event, this) == EVENT_DONE) {
return EVENT_DONE;
+ }
}
if (!*signal_timeout && !*signal_timeout_at && !closed && write.vio.op == VIO::WRITE && !(f.shutdown & NET_VC_SHUTDOWN_WRITE) &&
- reader_cont != write.vio._cont && writer_cont == write.vio._cont)
- if (write_signal_and_update(signal_event, this) == EVENT_DONE)
+ reader_cont != write.vio._cont && writer_cont == write.vio._cont) {
+ if (write_signal_and_update(signal_event, this) == EVENT_DONE) {
return EVENT_DONE;
+ }
+ }
return EVENT_DONE;
}
@@ -1608,11 +1638,13 @@ UnixNetVConnection::populate_protocol(ts::StringView *results, int n) const
{
int retval = 0;
if (n > retval) {
- if (!(results[retval] = options.get_proto_string()).isEmpty())
+ if (!(results[retval] = options.get_proto_string()).isEmpty()) {
++retval;
+ }
if (n > retval) {
- if (!(results[retval] = options.get_family_string()).isEmpty())
+ if (!(results[retval] = options.get_family_string()).isEmpty()) {
++retval;
+ }
}
}
return retval;
diff --git a/iocore/net/UnixUDPConnection.cc b/iocore/net/UnixUDPConnection.cc
index ec2929b..bc5ee95 100644
--- a/iocore/net/UnixUDPConnection.cc
+++ b/iocore/net/UnixUDPConnection.cc
@@ -36,8 +36,9 @@ UnixUDPConnection::~UnixUDPConnection()
{
UDPPacketInternal *p = (UDPPacketInternal *)ink_atomiclist_popall(&inQueue);
- if (!tobedestroyed)
+ if (!tobedestroyed) {
tobedestroyed = 1;
+ }
if (p) {
UDPPacketInternal *pnext = nullptr;
@@ -67,12 +68,14 @@ UnixUDPConnection::callbackHandler(int event, void *data)
(void)event;
(void)data;
callbackAction = nullptr;
- if (continuation == nullptr)
+ if (continuation == nullptr) {
return EVENT_CONT;
+ }
if (m_errno) {
- if (!shouldDestroy())
+ if (!shouldDestroy()) {
continuation->handleEvent(NET_EVENT_DATAGRAM_ERROR, this);
+ }
destroy(); // don't destroy until after calling back with error
Release();
return EVENT_CONT;
@@ -88,11 +91,12 @@ UnixUDPConnection::callbackHandler(int event, void *data)
result.push(p);
p = pnext;
}
- if (!shouldDestroy())
+ if (!shouldDestroy()) {
continuation->handleEvent(NET_EVENT_DATAGRAM_READ_READY, &result);
- else {
- while ((p = result.dequeue()))
+ } else {
+ while ((p = result.dequeue())) {
p->free();
+ }
}
}
}
diff --git a/iocore/net/UnixUDPNet.cc b/iocore/net/UnixUDPNet.cc
index 092aedf..41bd62d 100644
--- a/iocore/net/UnixUDPNet.cc
+++ b/iocore/net/UnixUDPNet.cc
@@ -88,18 +88,21 @@ initialize_thread_for_udp_net(EThread *thread)
int
UDPNetProcessorInternal::start(int n_upd_threads, size_t stacksize)
{
- if (n_upd_threads < 1)
+ if (n_upd_threads < 1) {
return -1;
+ }
ET_UDP = eventProcessor.spawn_event_threads(n_upd_threads, "ET_UDP", stacksize);
- if (ET_UDP < 0) // Probably can't happen, maybe at some point EventType should be unsigned ?
+ if (ET_UDP < 0) { // Probably can't happen, maybe at some point EventType should be unsigned ?
return -1;
+ }
pollCont_offset = eventProcessor.allocate(sizeof(PollCont));
udpNetHandler_offset = eventProcessor.allocate(sizeof(UDPNetHandler));
- for (int i = 0; i < eventProcessor.n_threads_for_type[ET_UDP]; i++)
+ for (int i = 0; i < eventProcessor.n_threads_for_type[ET_UDP]; i++) {
initialize_thread_for_udp_net(eventProcessor.eventthread[ET_UDP][i]);
+ }
return 0;
}
@@ -228,10 +231,11 @@ UDPReadContinuation::UDPReadContinuation(Event *completionToken)
elapsed_time(0),
timeout_interval(0)
{
- if (completionToken->continuation)
+ if (completionToken->continuation) {
this->mutex = completionToken->continuation->mutex;
- else
+ } else {
this->mutex = new_ProxyMutex();
+ }
}
UDPReadContinuation::UDPReadContinuation() : Continuation(nullptr)
@@ -518,11 +522,13 @@ UDPNetProcessor::CreateUDPSocket(int *resfd, sockaddr const *remote_addr, sockad
ink_assert(ats_ip_are_compatible(remote_addr, local_addr));
*resfd = -1;
- if ((res = socketManager.socket(remote_addr->sa_family, SOCK_DGRAM, 0)) < 0)
+ if ((res = socketManager.socket(remote_addr->sa_family, SOCK_DGRAM, 0)) < 0) {
goto HardError;
+ }
fd = res;
- if ((res = safe_fcntl(fd, F_SETFL, O_NONBLOCK)) < 0)
+ if ((res = safe_fcntl(fd, F_SETFL, O_NONBLOCK)) < 0) {
goto HardError;
+ }
if ((res = socketManager.ink_bind(fd, remote_addr, ats_ip_size(remote_addr), IPPROTO_UDP)) < 0) {
char buff[INET6_ADDRPORTSTRLEN];
Debug("udpnet", "ink bind failed on %s", ats_ip_nptop(remote_addr, buff, sizeof(buff)));
@@ -530,12 +536,14 @@ UDPNetProcessor::CreateUDPSocket(int *resfd, sockaddr const *remote_addr, sockad
}
if (recv_bufsize) {
- if (unlikely(socketManager.set_rcvbuf_size(fd, recv_bufsize)))
+ if (unlikely(socketManager.set_rcvbuf_size(fd, recv_bufsize))) {
Debug("udpnet", "set_dnsbuf_size(%d) failed", recv_bufsize);
+ }
}
if (send_bufsize) {
- if (unlikely(socketManager.set_sndbuf_size(fd, send_bufsize)))
+ if (unlikely(socketManager.set_sndbuf_size(fd, send_bufsize))) {
Debug("udpnet", "set_dnsbuf_size(%d) failed", send_bufsize);
+ }
}
if ((res = safe_getsockname(fd, local_addr, local_addr_len)) < 0) {
Debug("udpnet", "CreateUdpsocket: getsockname didnt' work");
@@ -548,15 +556,17 @@ UDPNetProcessor::CreateUDPSocket(int *resfd, sockaddr const *remote_addr, sockad
return true;
SoftError:
Debug("udpnet", "creating a udp socket port = %d---soft failure", ats_ip_port_host_order(local_addr));
- if (fd != -1)
+ if (fd != -1) {
socketManager.close(fd);
+ }
*resfd = -1;
*status = nullptr;
return false;
HardError:
Debug("udpnet", "creating a udp socket port = %d---hard failure", ats_ip_port_host_order(local_addr));
- if (fd != -1)
+ if (fd != -1) {
socketManager.close(fd);
+ }
*resfd = -1;
*status = ACTION_IO_ERROR;
return false;
@@ -571,11 +581,13 @@ UDPNetProcessor::UDPBind(Continuation *cont, sockaddr const *addr, int send_bufs
IpEndpoint myaddr;
int myaddr_len = sizeof(myaddr);
- if ((res = socketManager.socket(addr->sa_family, SOCK_DGRAM, 0)) < 0)
+ if ((res = socketManager.socket(addr->sa_family, SOCK_DGRAM, 0)) < 0) {
goto Lerror;
+ }
fd = res;
- if ((res = fcntl(fd, F_SETFL, O_NONBLOCK) < 0))
+ if ((res = fcntl(fd, F_SETFL, O_NONBLOCK) < 0)) {
goto Lerror;
+ }
// If this is a class D address (i.e. multicast address), use REUSEADDR.
if (ats_is_ip_multicast(addr)) {
@@ -591,12 +603,14 @@ UDPNetProcessor::UDPBind(Continuation *cont, sockaddr const *addr, int send_bufs
}
if (recv_bufsize) {
- if (unlikely(socketManager.set_rcvbuf_size(fd, recv_bufsize)))
+ if (unlikely(socketManager.set_rcvbuf_size(fd, recv_bufsize))) {
Debug("udpnet", "set_dnsbuf_size(%d) failed", recv_bufsize);
+ }
}
if (send_bufsize) {
- if (unlikely(socketManager.set_sndbuf_size(fd, send_bufsize)))
+ if (unlikely(socketManager.set_sndbuf_size(fd, send_bufsize))) {
Debug("udpnet", "set_dnsbuf_size(%d) failed", send_bufsize);
+ }
}
if ((res = safe_getsockname(fd, &myaddr.sa, &myaddr_len)) < 0) {
goto Lerror;
@@ -610,8 +624,9 @@ UDPNetProcessor::UDPBind(Continuation *cont, sockaddr const *addr, int send_bufs
cont->handleEvent(NET_EVENT_DATAGRAM_OPEN, n);
return ACTION_RESULT_DONE;
Lerror:
- if (fd != NO_FD)
+ if (fd != NO_FD) {
socketManager.close(fd);
+ }
cont->handleEvent(NET_EVENT_DATAGRAM_ERROR, nullptr);
return ACTION_IO_ERROR;
}
@@ -703,10 +718,12 @@ sendPackets:
p = pipeInfo.getFirstPacket();
pktLen = p->getPktLength();
- if (p->conn->shouldDestroy())
+ if (p->conn->shouldDestroy()) {
goto next_pkt;
- if (p->conn->GetSendGenerationNumber() != p->reqGenerationNum)
+ }
+ if (p->conn->GetSendGenerationNumber() != p->reqGenerationNum) {
goto next_pkt;
+ }
SendUDPPacket(p, pktLen);
bytesUsed += pktLen;
@@ -715,8 +732,9 @@ sendPackets:
sentOne = true;
p->free();
- if (bytesThisPipe < 0)
+ if (bytesThisPipe < 0) {
break;
+ }
}
bytesThisSlot -= bytesUsed;
@@ -769,9 +787,10 @@ UDPQueue::SendUDPPacket(UDPPacketInternal *p, int32_t /* pktLen ATS_UNUSED */)
while (true) {
// stupid Linux problem: sendmsg can return EAGAIN
n = ::sendmsg(p->conn->getFd(), &msg, 0);
- if ((n >= 0) || ((n < 0) && (errno != EAGAIN)))
+ if ((n >= 0) || ((n < 0) && (errno != EAGAIN))) {
// send succeeded or some random error happened.
break;
+ }
if (errno == EAGAIN) {
++count;
if ((g_udp_numSendRetries > 0) && (count >= g_udp_numSendRetries)) {
diff --git a/iocore/utils/Machine.cc b/iocore/utils/Machine.cc
index aeb62b8..09bf84c 100644
--- a/iocore/utils/Machine.cc
+++ b/iocore/utils/Machine.cc
@@ -188,8 +188,9 @@ Machine::Machine(char const *the_hostname, sockaddr const *addr)
if (0 != status) {
ip_text_buffer ipbuff;
Warning("Failed to find hostname for address '%s' - %s", ats_ip_ntop(addr, ipbuff, sizeof(ipbuff)), gai_strerror(status));
- } else
+ } else {
hostname = ats_strdup(localhost);
+ }
}
hostname_len = hostname ? strlen(hostname) : 0;
diff --git a/iocore/utils/OneWayMultiTunnel.cc b/iocore/utils/OneWayMultiTunnel.cc
index 23408d2..428d345 100644
--- a/iocore/utils/OneWayMultiTunnel.cc
+++ b/iocore/utils/OneWayMultiTunnel.cc
@@ -75,10 +75,11 @@ OneWayMultiTunnel::init(VConnection *vcSource, VConnection **vcTargets, int n_vc
n_connections = n_vioTargets + 1;
int64_t size_index = 0;
- if (size_estimate)
+ if (size_estimate) {
size_index = buffer_size_to_index(size_estimate, default_large_iobuffer_size);
- else
+ } else {
size_index = default_large_iobuffer_size;
+ }
tunnel_till_done = (nbytes == TUNNEL_TILL_DONE);
@@ -87,10 +88,11 @@ OneWayMultiTunnel::init(VConnection *vcSource, VConnection **vcTargets, int n_vc
single_buffer = asingle_buffer;
- if (single_buffer)
+ if (single_buffer) {
buf2 = buf1;
- else
+ } else {
buf2 = new_MIOBuffer(size_index);
+ }
topOutBuffer.writer_for(buf2);
buf1->water_mark = water_mark;
@@ -98,8 +100,9 @@ OneWayMultiTunnel::init(VConnection *vcSource, VConnection **vcTargets, int n_vc
vioSource = vcSource->do_io_read(this, nbytes, buf1);
ink_assert(n_vcTargets <= ONE_WAY_MULTI_TUNNEL_LIMIT);
- for (int i = 0; i < n_vcTargets; i++)
+ for (int i = 0; i < n_vcTargets; i++) {
vioTargets[i] = vc_do_io_write(vcTargets[i], this, INT64_MAX, buf2, 0);
+ }
return;
}
@@ -160,37 +163,43 @@ OneWayMultiTunnel::startEvent(int event, void *data)
switch (event) {
case VC_EVENT_READ_READY: { // SunCC uses old scoping rules
transform(vioSource->buffer, topOutBuffer);
- for (int i = 0; i < n_vioTargets; i++)
- if (vioTargets[i])
+ for (int i = 0; i < n_vioTargets; i++) {
+ if (vioTargets[i]) {
vioTargets[i]->reenable();
+ }
+ }
ret = VC_EVENT_CONT;
break;
}
case VC_EVENT_WRITE_READY:
- if (vioSource)
+ if (vioSource) {
vioSource->reenable();
+ }
ret = VC_EVENT_CONT;
break;
case VC_EVENT_EOS:
- if (!tunnel_till_done && vio->ntodo())
+ if (!tunnel_till_done && vio->ntodo()) {
goto Lerror;
+ }
if (vio == vioSource) {
transform(vioSource->buffer, topOutBuffer);
goto Lread_complete;
- } else
+ } else {
goto Lwrite_complete;
+ }
Lread_complete:
case VC_EVENT_READ_COMPLETE: { // SunCC uses old scoping rules
// set write nbytes to the current buffer size
//
- for (int i = 0; i < n_vioTargets; i++)
+ for (int i = 0; i < n_vioTargets; i++) {
if (vioTargets[i]) {
vioTargets[i]->nbytes = vioTargets[i]->ndone + vioTargets[i]->buffer.reader()->read_avail();
vioTargets[i]->reenable();
}
+ }
close_source_vio(0);
ret = VC_EVENT_DONE;
break;
@@ -199,10 +208,11 @@ OneWayMultiTunnel::startEvent(int event, void *data)
Lwrite_complete:
case VC_EVENT_WRITE_COMPLETE:
close_target_vio(0, (VIO *)data);
- if ((n_connections == 0) || (n_connections == 1 && source_read_previously_completed))
+ if ((n_connections == 0) || (n_connections == 1 && source_read_previously_completed)) {
goto Ldone;
- else if (vioSource)
+ } else if (vioSource) {
vioSource->reenable();
+ }
break;
Lerror:
@@ -232,10 +242,12 @@ OneWayMultiTunnel::close_target_vio(int result, VIO *vio)
for (int i = 0; i < n_vioTargets; i++) {
VIO *v = vioTargets[i];
if (v && (!vio || v == vio)) {
- if (last_connection() || !single_buffer)
+ if (last_connection() || !single_buffer) {
free_MIOBuffer(v->buffer.writer());
- if (close_target)
+ }
+ if (close_target) {
v->vc_server->do_io_close();
+ }
vioTargets[i] = nullptr;
n_connections--;
}
@@ -245,9 +257,12 @@ OneWayMultiTunnel::close_target_vio(int result, VIO *vio)
void
OneWayMultiTunnel::reenable_all()
{
- for (int i = 0; i < n_vioTargets; i++)
- if (vioTargets[i])
+ for (int i = 0; i < n_vioTargets; i++) {
+ if (vioTargets[i]) {
vioTargets[i]->reenable();
- if (vioSource)
+ }
+ }
+ if (vioSource) {
vioSource->reenable();
+ }
}
diff --git a/iocore/utils/OneWayTunnel.cc b/iocore/utils/OneWayTunnel.cc
index d45e5f1..53709f9 100644
--- a/iocore/utils/OneWayTunnel.cc
+++ b/iocore/utils/OneWayTunnel.cc
@@ -53,10 +53,12 @@ transfer_data(MIOBufferAccessor &in_buf, MIOBufferAccessor &out_buf)
int64_t n = in_buf.reader()->read_avail();
int64_t o = out_buf.writer()->write_avail();
- if (n > o)
+ if (n > o) {
n = o;
- if (!n)
+ }
+ if (!n) {
return;
+ }
memcpy(in_buf.reader()->start(), out_buf.writer()->end(), n);
in_buf.reader()->consume(n);
out_buf.writer()->fill(n);
@@ -140,20 +142,22 @@ OneWayTunnel::init(VConnection *vcSource, VConnection *vcTarget, Continuation *a
int64_t size_index = 0;
- if (size_estimate)
+ if (size_estimate) {
size_index = buffer_size_to_index(size_estimate);
- else
+ } else {
size_index = default_large_iobuffer_size;
+ }
Debug("one_way_tunnel", "buffer size index [%" PRId64 "] [%d]", size_index, size_estimate);
// enqueue read request on vcSource.
MIOBuffer *buf1 = new_MIOBuffer(size_index);
MIOBuffer *buf2 = nullptr;
- if (single_buffer)
+ if (single_buffer) {
buf2 = buf1;
- else
+ } else {
buf2 = new_MIOBuffer(size_index);
+ }
buf1->water_mark = water_mark;
@@ -220,10 +224,11 @@ OneWayTunnel::init(Continuation *aCont, VIO *SourceVio, VIO *TargetVio, bool acl
void
OneWayTunnel::transform(MIOBufferAccessor &in_buf, MIOBufferAccessor &out_buf)
{
- if (manipulate_fn)
+ if (manipulate_fn) {
manipulate_fn(in_buf, out_buf);
- else if (in_buf.writer() != out_buf.writer())
+ } else if (in_buf.writer() != out_buf.writer()) {
transfer_data(in_buf, out_buf);
+ }
}
//////////////////////////////////////////////////////////////////////////////
@@ -247,8 +252,9 @@ OneWayTunnel::startEvent(int event, void *data)
printf("OneWayTunnel --- %s received from %s VC\n", event_name, event_origin);
#endif
- if (!vioTarget)
+ if (!vioTarget) {
goto Lerror;
+ }
// handle the event
//
@@ -268,14 +274,16 @@ OneWayTunnel::startEvent(int event, void *data)
break;
case VC_EVENT_WRITE_READY:
- if (vioSource)
+ if (vioSource) {
vioSource->reenable();
+ }
ret = VC_EVENT_CONT;
break;
case VC_EVENT_EOS:
- if (!tunnel_till_done && vio->ntodo())
+ if (!tunnel_till_done && vio->ntodo()) {
goto Lerror;
+ }
if (vio == vioSource) {
transform(vioSource->buffer, vioTarget->buffer);
goto Lread_complete;
@@ -288,11 +296,13 @@ OneWayTunnel::startEvent(int event, void *data)
// set write nbytes to the current buffer size
//
vioTarget->nbytes = vioTarget->ndone + vioTarget->buffer.reader()->read_avail();
- if (vioTarget->nbytes == vioTarget->ndone)
+ if (vioTarget->nbytes == vioTarget->ndone) {
goto Ldone;
+ }
vioTarget->reenable();
- if (!tunnel_peer)
+ if (!tunnel_peer) {
close_source_vio(0);
+ }
break;
case VC_EVENT_ERROR:
@@ -378,10 +388,12 @@ OneWayTunnel::connection_closed(int result)
void
OneWayTunnel::reenable_all()
{
- if (vioSource)
+ if (vioSource) {
vioSource->reenable();
- if (vioTarget)
+ }
+ if (vioTarget) {
vioTarget->reenable();
+ }
}
bool
diff --git a/lib/cppapi/Headers.cc b/lib/cppapi/Headers.cc
index c1e5b74..5645951 100644
--- a/lib/cppapi/Headers.cc
+++ b/lib/cppapi/Headers.cc
@@ -346,8 +346,9 @@ HeaderField::operator!=(const std::string &field_name) const
bool
HeaderField::operator=(const std::string &field_value)
{
- if (!clear())
+ if (!clear()) {
return false;
+ }
return append(field_value);
}
@@ -355,8 +356,9 @@ HeaderField::operator=(const std::string &field_value)
bool
HeaderField::operator=(const char *field_value)
{
- if (!clear())
+ if (!clear()) {
return false;
+ }
return append(field_value);
}
@@ -382,8 +384,9 @@ operator<<(std::ostream &os, HeaderField &obj)
int count = obj.size();
for (HeaderField::iterator it = obj.begin(); it != obj.end(); ++it) {
os << (*it);
- if (--count > 0)
+ if (--count > 0) {
os << ",";
+ }
}
return os;
}
@@ -638,8 +641,9 @@ header_field_iterator
Headers::find(const char *key, int length)
{
TSMLoc field_loc = TSMimeHdrFieldFind(state_->hdr_buf_, state_->hdr_loc_, key, length);
- if (field_loc != TS_NULL_MLOC)
+ if (field_loc != TS_NULL_MLOC) {
return header_field_iterator(state_->hdr_buf_, state_->hdr_loc_, field_loc);
+ }
return end();
}
@@ -654,8 +658,9 @@ Headers::append(const std::string &key, const std::string &value)
TSMimeHdrFieldAppend(state_->hdr_buf_, state_->hdr_loc_, field_loc);
TSMimeHdrFieldValueStringInsert(state_->hdr_buf_, state_->hdr_loc_, field_loc, 0, value.c_str(), value.length());
return header_field_iterator(state_->hdr_buf_, state_->hdr_loc_, field_loc);
- } else
+ } else {
return end();
+ }
}
Headers::iterator
diff --git a/lib/cppapi/Plugin.cc b/lib/cppapi/Plugin.cc
index a7d2514..22925c3 100644
--- a/lib/cppapi/Plugin.cc
+++ b/lib/cppapi/Plugin.cc
@@ -35,6 +35,7 @@ atscppapi::RegisterGlobalPlugin(const char *name, const char *vendor, const char
info.plugin_name = name;
info.vendor_name = vendor;
info.support_email = email;
- if (TSPluginRegister(&info) != TS_SUCCESS)
+ if (TSPluginRegister(&info) != TS_SUCCESS) {
TSError("[Plugin.cc] Plugin registration failed");
+ }
}
diff --git a/lib/cppapi/Request.cc b/lib/cppapi/Request.cc
index 528e7fc..8131e1e 100644
--- a/lib/cppapi/Request.cc
+++ b/lib/cppapi/Request.cc
@@ -186,8 +186,9 @@ Request::setHost(std::string const &host)
Url &url = this->getUrl();
// Update the URL if it has a host currently.
- if (!url.getHost().empty())
+ if (!url.getHost().empty()) {
url.setHost(host);
+ }
// Force a HOST field.
this->getHeaders().set(HOST_FIELD_NAME, host);
diff --git a/lib/cppapi/Transaction.cc b/lib/cppapi/Transaction.cc
index 03a9d98..5e72eec 100644
--- a/lib/cppapi/Transaction.cc
+++ b/lib/cppapi/Transaction.cc
@@ -144,10 +144,11 @@ Transaction::configStringGet(TSOverridableConfigKey conf, std::string &value)
const char *svalue;
int length;
bool zret = TS_SUCCESS == TSHttpTxnConfigStringGet(state_->txn_, conf, &svalue, &length);
- if (zret)
+ if (zret) {
value.assign(svalue, length);
- else
+ } else {
value.clear();
+ }
return zret;
}
@@ -262,8 +263,9 @@ Transaction::getEffectiveUrl()
ret_val.assign(buf, length);
}
- if (buf)
+ if (buf) {
TSfree(buf);
+ }
return ret_val;
}
diff --git a/lib/records/RecCore.cc b/lib/records/RecCore.cc
index 535f5cc..1bce026 100644
--- a/lib/records/RecCore.cc
+++ b/lib/records/RecCore.cc
@@ -1298,8 +1298,9 @@ RecConfigWarnIfUnregistered()
{
RecDumpRecords(RECT_CONFIG,
[](RecT, void *, int registered_p, const char *name, int, RecData *) -> void {
- if (!registered_p)
+ if (!registered_p) {
Warning("Unrecognized configuration value '%s'", name);
+ }
},
nullptr);
}
diff --git a/lib/ts/BaseLogFile.cc b/lib/ts/BaseLogFile.cc
index c9bbe79..bc3abca 100644
--- a/lib/ts/BaseLogFile.cc
+++ b/lib/ts/BaseLogFile.cc
@@ -68,10 +68,11 @@ BaseLogFile::~BaseLogFile()
{
log_log_trace("entering BaseLogFile destructor, m_name=%s, this=%p\n", m_name.get(), this);
- if (m_is_regfile)
+ if (m_is_regfile) {
close_file();
- else
+ } else {
log_log_trace("not a regular file, not closing, m_name=%s, this=%p\n", m_name.get(), this);
+ }
log_log_trace("exiting BaseLogFile destructor, this=%p\n", this);
}
@@ -157,10 +158,11 @@ BaseLogFile::roll(long interval_start, long interval_end)
// no easy way of keeping track of the timestamp of the first
// transaction
log_log_trace("in BaseLogFile::roll(..), didn't use metadata starttime, used earlist available starttime\n");
- if (interval_start == 0)
+ if (interval_start == 0) {
start = m_start_time;
- else
+ } else {
start = (m_start_time < interval_start) ? m_start_time : interval_start;
+ }
}
log_log_trace("in BaseLogFile::roll(..), start = %ld, m_start_time = %ld, interval_start = %ld\n", start, m_start_time,
interval_start);
@@ -222,8 +224,9 @@ BaseLogFile::roll()
time_t start;
time_t now = time(nullptr);
- if (!m_meta_info || !m_meta_info->get_creation_time(&start))
+ if (!m_meta_info || !m_meta_info->get_creation_time(&start)) {
start = 0L;
+ }
return roll(start, now);
}
@@ -300,10 +303,11 @@ BaseLogFile::open_file(int perm)
} else {
// The log file does not exist, so we create a new MetaInfo object
// which will save itself to disk right away (in the constructor)
- if (m_has_signature)
+ if (m_has_signature) {
m_meta_info = new BaseMetaInfo(m_name.get(), (long)time(nullptr), m_signature);
- else
+ } else {
m_meta_info = new BaseMetaInfo(m_name.get(), (long)time(nullptr));
+ }
}
// open actual log file (not metainfo)
@@ -324,8 +328,9 @@ BaseLogFile::open_file(int perm)
if (perm != -1) {
// means LogFile passed in some permissions we need to set
log_log_trace("BaseLogFile attempting to change %s's permissions to %o\n", m_name.get(), perm);
- if (elevating_chmod(m_name.get(), perm) != 0)
+ if (elevating_chmod(m_name.get(), perm) != 0) {
log_log_error("Error changing logfile=%s permissions: %s\n", m_name.get(), strerror(errno));
+ }
}
// set m_bytes_written to force the rolling based on filesize.
diff --git a/lib/ts/CompileParseRules.cc b/lib/ts/CompileParseRules.cc
index 1a1a5c0..6c66a21 100644
--- a/lib/ts/CompileParseRules.cc
+++ b/lib/ts/CompileParseRules.cc
@@ -58,71 +58,103 @@ main()
tparseRulesCTypeToLower[c] = ParseRules::ink_tolower(c);
tparseRulesCTypeToUpper[c] = ParseRules::ink_toupper(c);
- if (ParseRules::is_char(c))
+ if (ParseRules::is_char(c)) {
tparseRulesCType[c] |= is_char_BIT;
- if (ParseRules::is_upalpha(c))
+ }
+ if (ParseRules::is_upalpha(c)) {
tparseRulesCType[c] |= is_upalpha_BIT;
- if (ParseRules::is_loalpha(c))
+ }
+ if (ParseRules::is_loalpha(c)) {
tparseRulesCType[c] |= is_loalpha_BIT;
- if (ParseRules::is_alpha(c))
+ }
+ if (ParseRules::is_alpha(c)) {
tparseRulesCType[c] |= is_alpha_BIT;
- if (ParseRules::is_digit(c))
+ }
+ if (ParseRules::is_digit(c)) {
tparseRulesCType[c] |= is_digit_BIT;
- if (ParseRules::is_ctl(c))
+ }
+ if (ParseRules::is_ctl(c)) {
tparseRulesCType[c] |= is_ctl_BIT;
- if (ParseRules::is_ws(c))
+ }
+ if (ParseRules::is_ws(c)) {
tparseRulesCType[c] |= is_ws_BIT;
- if (ParseRules::is_hex(c))
+ }
+ if (ParseRules::is_hex(c)) {
tparseRulesCType[c] |= is_hex_BIT;
+ }
char cc = c;
- if (ParseRules::is_pchar(&cc))
+ if (ParseRules::is_pchar(&cc)) {
tparseRulesCType[c] |= is_pchar_BIT;
- if (ParseRules::is_extra(c))
+ }
+ if (ParseRules::is_extra(c)) {
tparseRulesCType[c] |= is_extra_BIT;
- if (ParseRules::is_safe(c))
+ }
+ if (ParseRules::is_safe(c)) {
tparseRulesCType[c] |= is_safe_BIT;
- if (ParseRules::is_unsafe(c))
+ }
+ if (ParseRules::is_unsafe(c)) {
tparseRulesCType[c] |= is_unsafe_BIT;
- if (ParseRules::is_national(c))
+ }
+ if (ParseRules::is_national(c)) {
tparseRulesCType[c] |= is_national_BIT;
- if (ParseRules::is_reserved(c))
+ }
+ if (ParseRules::is_reserved(c)) {
tparseRulesCType[c] |= is_reserved_BIT;
- if (ParseRules::is_unreserved(c))
+ }
+ if (ParseRules::is_unreserved(c)) {
tparseRulesCType[c] |= is_unreserved_BIT;
- if (ParseRules::is_punct(c))
+ }
+ if (ParseRules::is_punct(c)) {
tparseRulesCType[c] |= is_punct_BIT;
- if (ParseRules::is_end_of_url(c))
+ }
+ if (ParseRules::is_end_of_url(c)) {
tparseRulesCType[c] |= is_end_of_url_BIT;
- if (ParseRules::is_tspecials(c))
+ }
+ if (ParseRules::is_tspecials(c)) {
tparseRulesCType[c] |= is_tspecials_BIT;
- if (ParseRules::is_spcr(c))
+ }
+ if (ParseRules::is_spcr(c)) {
tparseRulesCType[c] |= is_spcr_BIT;
- if (ParseRules::is_splf(c))
+ }
+ if (ParseRules::is_splf(c)) {
tparseRulesCType[c] |= is_splf_BIT;
- if (ParseRules::is_wslfcr(c))
+ }
+ if (ParseRules::is_wslfcr(c)) {
tparseRulesCType[c] |= is_wslfcr_BIT;
- if (ParseRules::is_eow(c))
+ }
+ if (ParseRules::is_eow(c)) {
tparseRulesCType[c] |= is_eow_BIT;
- if (ParseRules::is_token(c))
+ }
+ if (ParseRules::is_token(c)) {
tparseRulesCType[c] |= is_token_BIT;
- if (ParseRules::is_uri(c))
+ }
+ if (ParseRules::is_uri(c)) {
tparseRulesCType[c] |= is_uri_BIT;
- if (ParseRules::is_sep(c))
+ }
+ if (ParseRules::is_sep(c)) {
tparseRulesCType[c] |= is_sep_BIT;
- if (ParseRules::is_empty(c))
+ }
+ if (ParseRules::is_empty(c)) {
tparseRulesCType[c] |= is_empty_BIT;
- if (ParseRules::is_alnum(c))
+ }
+ if (ParseRules::is_alnum(c)) {
tparseRulesCType[c] |= is_alnum_BIT;
- if (ParseRules::is_space(c))
+ }
+ if (ParseRules::is_space(c)) {
tparseRulesCType[c] |= is_space_BIT;
- if (ParseRules::is_control(c))
+ }
+ if (ParseRules::is_control(c)) {
tparseRulesCType[c] |= is_control_BIT;
- if (ParseRules::is_mime_sep(c))
+ }
+ if (ParseRules::is_mime_sep(c)) {
tparseRulesCType[c] |= is_mime_sep_BIT;
- if (ParseRules::is_http_field_name(c))
+ }
+ if (ParseRules::is_http_field_name(c)) {
tparseRulesCType[c] |= is_http_field_name_BIT;
- if (ParseRules::is_http_field_value(c))
+ }
+ if (ParseRules::is_http_field_value(c)) {
tparseRulesCType[c] |= is_http_field_value_BIT;
+ }
}
FILE *fp = fopen("ParseRulesCType", "w");
@@ -133,12 +165,14 @@ main()
}
fclose(fp);
fp = fopen("ParseRulesCTypeToUpper", "w");
- for (c = 0; c < 256; c++)
+ for (c = 0; c < 256; c++) {
fprintf(fp, "%d%c\n", tparseRulesCTypeToUpper[c], c != 255 ? ',' : ' ');
+ }
fclose(fp);
fp = fopen("ParseRulesCTypeToLower", "w");
- for (c = 0; c < 256; c++)
+ for (c = 0; c < 256; c++) {
fprintf(fp, "%d%c\n", tparseRulesCTypeToLower[c], c != 255 ? ',' : ' ');
+ }
fclose(fp);
return (0);
diff --git a/lib/ts/Diags.cc b/lib/ts/Diags.cc
index 128ad52..f62775b 100644
--- a/lib/ts/Diags.cc
+++ b/lib/ts/Diags.cc
@@ -257,8 +257,9 @@ Diags::print_va(const char *debug_tag, DiagsLevel diags_level, const SourceLocat
// start with the diag level prefix //
//////////////////////////////////////
- for (s = level_name(diags_level); *s; *end_of_format++ = *s++)
+ for (s = level_name(diags_level); *s; *end_of_format++ = *s++) {
;
+ }
*end_of_format++ = ':';
*end_of_format++ = ' ';
@@ -272,8 +273,9 @@ Diags::print_va(const char *debug_tag, DiagsLevel diags_level, const SourceLocat
lp = loc->str(buf, sizeof(buf));
if (lp) {
*end_of_format++ = '<';
- for (s = lp; *s; *end_of_format++ = *s++)
+ for (s = lp; *s; *end_of_format++ = *s++) {
;
+ }
*end_of_format++ = '>';
*end_of_format++ = ' ';
}
@@ -284,8 +286,9 @@ Diags::print_va(const char *debug_tag, DiagsLevel diags_level, const SourceLocat
if (debug_tag) {
*end_of_format++ = '(';
- for (s = debug_tag; *s; *end_of_format++ = *s++)
+ for (s = debug_tag; *s; *end_of_format++ = *s++) {
;
+ }
*end_of_format++ = ')';
*end_of_format++ = ' ';
}
@@ -293,8 +296,9 @@ Diags::print_va(const char *debug_tag, DiagsLevel diags_level, const SourceLocat
// append original format string, and NUL terminate //
//////////////////////////////////////////////////////
- for (s = format_string; *s; *end_of_format++ = *s++)
+ for (s = format_string; *s; *end_of_format++ = *s++) {
;
+ }
*end_of_format++ = NUL;
//////////////////////////////////////////////////////////////////
@@ -310,19 +314,22 @@ Diags::print_va(const char *debug_tag, DiagsLevel diags_level, const SourceLocat
d = format_buf_w_ts;
*d++ = '[';
- for (int i = 4; buffer[i]; i++)
+ for (int i = 4; buffer[i]; i++) {
*d++ = buffer[i];
+ }
*d++ = ']';
*d++ = ' ';
- for (int k = 0; prefix_str[k]; k++)
+ for (int k = 0; prefix_str[k]; k++) {
*d++ = prefix_str[k];
+ }
*d++ = ' ';
- for (s = format_buf; *s; *d++ = *s++)
+ for (s = format_buf; *s; *d++ = *s++) {
;
+ }
*d++ = NUL;
@@ -422,12 +429,14 @@ Diags::tag_activated(const char *tag, DiagsTagType mode) const
{
bool activated = false;
- if (tag == nullptr)
+ if (tag == nullptr) {
return (true);
+ }
lock();
- if (activated_tags[mode])
+ if (activated_tags[mode]) {
activated = (activated_tags[mode]->match(tag) != -1);
+ }
unlock();
return (activated);
@@ -555,10 +564,11 @@ Diags::error_va(DiagsLevel level, const SourceLocation *loc, const char *format_
}
// DL_Emergency means the process cannot recover from a reboot
- if (level == DL_Emergency)
+ if (level == DL_Emergency) {
ink_emergency_va(format_string, ap2);
- else
+ } else {
ink_fatal_va(format_string, ap2);
+ }
}
va_end(ap2);
@@ -630,8 +640,9 @@ Diags::should_roll_diagslog()
diagslog_rolling_enabled == RollingEnabledValues::ROLL_ON_TIME_OR_SIZE) {
// if we can't even check the file, we can forget about rotating
struct stat buf;
- if (fstat(fileno(diags_log->m_fp), &buf) != 0)
+ if (fstat(fileno(diags_log->m_fp), &buf) != 0) {
return false;
+ }
int size = buf.st_size;
if (diagslog_rolling_size != -1 && size >= (diagslog_rolling_size * BYTES_IN_MB)) {
@@ -716,15 +727,17 @@ Diags::should_roll_outputlog()
outputlog_rolling_enabled == RollingEnabledValues::ROLL_ON_TIME_OR_SIZE) {
// if we can't even check the file, we can forget about rotating
struct stat buf;
- if (fstat(fileno(stdout_log->m_fp), &buf) != 0)
+ if (fstat(fileno(stdout_log->m_fp), &buf) != 0) {
return false;
+ }
int size = buf.st_size;
if (outputlog_rolling_size != -1 && size >= outputlog_rolling_size * BYTES_IN_MB) {
// since usually stdout and stderr are the same file on disk, we should just
// play it safe and just flush both BaseLogFiles
- if (stderr_log->is_init())
+ if (stderr_log->is_init()) {
fflush(stderr_log->m_fp);
+ }
fflush(stdout_log->m_fp);
if (stdout_log->roll()) {
@@ -751,8 +764,9 @@ Diags::should_roll_outputlog()
if (outputlog_rolling_interval != -1 && (now - outputlog_time_last_roll) >= outputlog_rolling_interval) {
// since usually stdout and stderr are the same file on disk, we should just
// play it safe and just flush both BaseLogFiles
- if (stderr_log->is_init())
+ if (stderr_log->is_init()) {
fflush(stderr_log->m_fp);
+ }
fflush(stdout_log->m_fp);
if (stdout_log->roll()) {
@@ -784,8 +798,9 @@ Diags::should_roll_outputlog()
// disk, and stderr pointing to a different file on disk, and then also wants both files to
// rotate according to the (same || different) scheme, it would not be difficult to add
// some more config options in records.config and said feature into this function.
- if (ret_val)
+ if (ret_val) {
ink_assert(!need_consider_stderr);
+ }
return ret_val;
}
@@ -802,8 +817,9 @@ Diags::should_roll_outputlog()
bool
Diags::set_stdout_output(const char *stdout_path)
{
- if (strcmp(stdout_path, "") == 0)
+ if (strcmp(stdout_path, "") == 0) {
return false;
+ }
BaseLogFile *old_stdout_log = stdout_log;
BaseLogFile *new_stdout_log = new BaseLogFile(stdout_path);
@@ -834,8 +850,9 @@ Diags::set_stdout_output(const char *stdout_path)
bool ret = rebind_stdout(fileno(new_stdout_log->m_fp));
unlock();
- if (old_stdout_log)
+ if (old_stdout_log) {
delete old_stdout_log;
+ }
// "this should never happen"^{TM}
ink_release_assert(ret);
@@ -852,8 +869,9 @@ Diags::set_stdout_output(const char *stdout_path)
bool
Diags::set_stderr_output(const char *stderr_path)
{
- if (strcmp(stderr_path, "") == 0)
+ if (strcmp(stderr_path, "") == 0) {
return false;
+ }
BaseLogFile *old_stderr_log = stderr_log;
BaseLogFile *new_stderr_log = new BaseLogFile(stderr_path);
@@ -884,8 +902,9 @@ Diags::set_stderr_output(const char *stderr_path)
bool ret = rebind_stderr(fileno(stderr_log->m_fp));
unlock();
- if (old_stderr_log)
+ if (old_stderr_log) {
delete old_stderr_log;
+ }
// "this should never happen"^{TM}
ink_release_assert(ret);
@@ -901,9 +920,9 @@ Diags::set_stderr_output(const char *stderr_path)
bool
Diags::rebind_stdout(int new_fd)
{
- if (new_fd < 0)
+ if (new_fd < 0) {
log_log_error("[Warning]: TS unable to bind stdout to new file descriptor=%d", new_fd);
- else {
+ } else {
dup2(new_fd, STDOUT_FILENO);
return true;
}
@@ -918,9 +937,9 @@ Diags::rebind_stdout(int new_fd)
bool
Diags::rebind_stderr(int new_fd)
{
- if (new_fd < 0)
+ if (new_fd < 0) {
log_log_error("[Warning]: TS unable to bind stderr to new file descriptor=%d", new_fd);
- else {
+ } else {
dup2(new_fd, STDERR_FILENO);
return true;
}
diff --git a/lib/ts/EventNotify.cc b/lib/ts/EventNotify.cc
index c26c465..4ec5cca 100644
--- a/lib/ts/EventNotify.cc
+++ b/lib/ts/EventNotify.cc
@@ -88,14 +88,16 @@ EventNotify::wait()
nr_fd = epoll_wait(m_epoll_fd, &ev, 1, 500000);
} while (nr_fd == -1 && errno == EINTR);
- if (nr_fd == -1)
+ if (nr_fd == -1) {
return errno;
+ }
nr = read(m_event_fd, &value, sizeof(uint64_t));
- if (nr == sizeof(uint64_t))
+ if (nr == sizeof(uint64_t)) {
return 0;
- else
+ } else {
return errno;
+ }
#else
ink_cond_wait(&m_cond, &m_mutex);
return 0;
@@ -114,23 +116,26 @@ int EventNotify::timedwait(int timeout) // milliseconds
// pthread_cond_timedwait() will return ETIMEDOUT immediately.
// We should keep compatible with pthread_cond_timedwait() here.
//
- if (timeout < 0)
+ if (timeout < 0) {
return ETIMEDOUT;
+ }
do {
nr_fd = epoll_wait(m_epoll_fd, &ev, 1, timeout);
} while (nr_fd == -1 && errno == EINTR);
- if (nr_fd == 0)
+ if (nr_fd == 0) {
return ETIMEDOUT;
- else if (nr_fd == -1)
+ } else if (nr_fd == -1) {
return errno;
+ }
nr = read(m_event_fd, &value, sizeof(uint64_t));
- if (nr == sizeof(uint64_t))
+ if (nr == sizeof(uint64_t)) {
return 0;
- else
+ } else {
return errno;
+ }
#else
ink_timestruc abstime;
diff --git a/lib/ts/HostLookup.cc b/lib/ts/HostLookup.cc
index b8be759..cfa4509 100644
--- a/lib/ts/HostLookup.cc
+++ b/lib/ts/HostLookup.cc
@@ -623,8 +623,9 @@ hostArray::Lookup(const char *match_data_in, bool bNotProcess)
if (bNotProcess && '!' == *pMD) {
char *cp = ++pMD;
- if ('\0' == *cp)
+ if ('\0' == *cp) {
continue;
+ }
if (strcmp(cp, match_data_in) != 0) {
r = branch_array[i];
diff --git a/lib/ts/IpMap.cc b/lib/ts/IpMap.cc
index 95ee7ca..8547289 100644
--- a/lib/ts/IpMap.cc
+++ b/lib/ts/IpMap.cc
@@ -282,14 +282,15 @@ namespace detail
N *n = _root; // current node to test.
N *zret = nullptr; // best node so far.
while (n) {
- if (target < n->_min)
+ if (target < n->_min) {
n = left(n);
- else {
+ } else {
zret = n; // this is a better candidate.
- if (n->_max < target)
+ if (n->_max < target) {
n = right(n);
- else
+ } else {
break;
+ }
}
}
return zret;
@@ -413,8 +414,9 @@ namespace detail
y->decrementMax();
this->insertBefore(n, y);
}
- if (max <= n->_max) // nothing past node
+ if (max <= n->_max) { // nothing past node
return *this;
+ }
min = n->_max;
N::inc(min);
n = next(n);
@@ -489,15 +491,16 @@ namespace detail
// min_1 is safe here because n->_min < min so min is not zero.
x = n;
// If the existing span covers the requested span, we're done.
- if (x->_max >= max)
+ if (x->_max >= max) {
return *this;
+ }
x->setMax(max);
} else if (n->_max <= max) {
// Can only have left skew overlap, otherwise disjoint.
// Clip if overlap.
- if (n->_max >= min)
+ if (n->_max >= min) {
n->setMax(min_1);
- else if (next(n) && n->_max <= max) {
+ } else if (next(n) && n->_max <= max) {
// request region covers next span so we can re-use that node.
x = next(n);
x->setMin(min).setMax(max).setData(payload);
@@ -518,10 +521,11 @@ namespace detail
n = next(n); // lower bound span handled, move on.
if (!x) {
x = new N(min, max, payload);
- if (n)
+ if (n) {
this->insertBefore(n, x);
- else
+ } else {
this->append(x); // note that since n == 0 we'll just return.
+ }
}
} else if (nullptr != (n = this->getHead()) && // at least one node in tree.
n->_data == payload && // payload matches
@@ -531,8 +535,9 @@ namespace detail
x = n;
n = next(n);
x->setMin(min);
- if (x->_max < max)
+ if (x->_max < max) {
x->setMax(max);
+ }
} else {
x = new N(min, max, payload);
this->prepend(x);
@@ -605,10 +610,11 @@ namespace detail
IpMapBase<N>::insertAfter(N *spot, N *n)
{
N *c = right(spot);
- if (!c)
+ if (!c) {
spot->setChild(n, N::RIGHT);
- else
+ } else {
spot->_next->setChild(n, N::LEFT);
+ }
_list.insertAfter(spot, n);
_root = static_cast<N *>(n->rebalanceAfterInsert());
@@ -619,10 +625,11 @@ namespace detail
IpMapBase<N>::insertBefore(N *spot, N *n)
{
N *c = left(spot);
- if (!c)
+ if (!c) {
spot->setChild(n, N::LEFT);
- else
+ } else {
spot->_prev->setChild(n, N::RIGHT);
+ }
_list.insertBefore(spot, n);
_root = static_cast<N *>(n->rebalanceAfterInsert());
@@ -632,10 +639,11 @@ namespace detail
void
IpMapBase<N>::prepend(N *n)
{
- if (!_root)
+ if (!_root) {
_root = n;
- else
+ } else {
_root = static_cast<N *>(_list.getHead()->setChild(n, N::LEFT)->rebalanceAfterInsert());
+ }
_list.prepend(n);
}
@@ -643,10 +651,11 @@ namespace detail
void
IpMapBase<N>::append(N *n)
{
- if (!_root)
+ if (!_root) {
_root = n;
- else
+ } else {
_root = static_cast<N *>(_list.getTail()->setChild(n, N::RIGHT)->rebalanceAfterInsert());
+ }
_list.append(n);
}
@@ -666,14 +675,15 @@ namespace detail
bool zret = false;
N *n = _root; // current node to test.
while (n) {
- if (x < n->_min)
+ if (x < n->_min) {
n = left(n);
- else if (n->_max < x)
+ } else if (n->_max < x) {
n = right(n);
- else {
- if (ptr)
+ } else {
+ if (ptr) {
*ptr = n->_data;
- zret = true;
+ }
+ zret = true;
break;
}
}
@@ -1064,16 +1074,18 @@ IpMap::~IpMap()
inline ts::detail::Ip4Map *
IpMap::force4()
{
- if (!_m4)
+ if (!_m4) {
_m4 = new ts::detail::Ip4Map;
+ }
return _m4;
}
inline ts::detail::Ip6Map *
IpMap::force6()
{
- if (!_m6)
+ if (!_m6) {
_m6 = new ts::detail::Ip6Map;
+ }
return _m6;
}
@@ -1119,11 +1131,13 @@ IpMap::unmark(sockaddr const *min, sockaddr const *max)
{
ink_assert(min->sa_family == max->sa_family);
if (AF_INET == min->sa_family) {
- if (_m4)
+ if (_m4) {
_m4->unmark(ntohl(ats_ip4_addr_cast(min)), ntohl(ats_ip4_addr_cast(max)));
+ }
} else if (AF_INET6 == min->sa_family) {
- if (_m6)
+ if (_m6) {
_m6->unmark(ats_ip6_cast(min), ats_ip6_cast(max));
+ }
}
return *this;
}
@@ -1131,8 +1145,9 @@ IpMap::unmark(sockaddr const *min, sockaddr const *max)
IpMap &
IpMap::unmark(in_addr_t min, in_addr_t max)
{
- if (_m4)
+ if (_m4) {
_m4->unmark(ntohl(min), ntohl(max));
+ }
return *this;
}
@@ -1159,20 +1174,24 @@ size_t
IpMap::getCount() const
{
size_t zret = 0;
- if (_m4)
+ if (_m4) {
zret += _m4->getCount();
- if (_m6)
+ }
+ if (_m6) {
zret += _m6->getCount();
+ }
return zret;
}
IpMap &
IpMap::clear()
{
- if (_m4)
+ if (_m4) {
_m4->clear();
- if (_m6)
+ }
+ if (_m6) {
_m6->clear();
+ }
return *this;
}
@@ -1180,10 +1199,12 @@ IpMap::iterator
IpMap::begin() const
{
Node *x = nullptr;
- if (_m4)
+ if (_m4) {
x = _m4->getHead();
- if (!x && _m6)
+ }
+ if (!x && _m6) {
x = _m6->getHead();
+ }
return iterator(this, x);
}
@@ -1193,8 +1214,9 @@ IpMap::iterator &IpMap::iterator::operator++()
// If we go past the end of the list see if it was the v4 list
// and if so, move to the v6 list (if it's there).
Node *x = static_cast<Node *>(_node->_next);
- if (!x && _tree->_m4 && _tree->_m6 && _node == _tree->_m4->getTail())
- x = _tree->_m6->getHead();
+ if (!x && _tree->_m4 && _tree->_m6 && _node == _tree->_m4->getTail()) {
+ x = _tree->_m6->getHead();
+ }
_node = x;
}
return *this;
@@ -1206,15 +1228,18 @@ inline IpMap::iterator &IpMap::iterator::operator--()
// At a node, try to back up. Handle the case where we back over the
// start of the v6 addresses and switch to the v4, if there are any.
Node *x = static_cast<Node *>(_node->_prev);
- if (!x && _tree->_m4 && _tree->_m6 && _node == _tree->_m6->getHead())
- x = _tree->_m4->getTail();
+ if (!x && _tree->_m4 && _tree->_m6 && _node == _tree->_m6->getHead()) {
+ x = _tree->_m4->getTail();
+ }
_node = x;
} else if (_tree) {
// We were at the end. Back up to v6 if possible, v4 if not.
- if (_tree->_m6)
+ if (_tree->_m6) {
_node = _tree->_m6->getTail();
- if (!_node && _tree->_m4)
+ }
+ if (!_node && _tree->_m4) {
_node = _tree->_m4->getTail();
+ }
}
return *this;
}
diff --git a/lib/ts/IpMapConf.cc b/lib/ts/IpMapConf.cc
index 09ac55e..dc5e837 100644
--- a/lib/ts/IpMapConf.cc
+++ b/lib/ts/IpMapConf.cc
@@ -79,8 +79,9 @@ Load_IpMap_From_File(IpMap *map, int fd, const char *key_str)
int fd2 = dup(fd); // dup to avoid closing the original file.
FILE *f = nullptr;
- if (fd2 >= 0)
+ if (fd2 >= 0) {
f = fdopen(fd2, "r");
+ }
if (f != nullptr) {
zret = Load_IpMap_From_File(map, f, key_str);
@@ -101,8 +102,9 @@ Load_IpMap_From_File(IpMap *map, int fd, const char *key_str)
static inline bool
skip_space(char *line, int n, int &offset)
{
- while (offset < n && isspace(line[offset]))
+ while (offset < n && isspace(line[offset])) {
++offset;
+ }
return offset < n;
}
@@ -124,14 +126,17 @@ Load_IpMap_From_File(IpMap *map, FILE *f, const char *key_str)
++line_no;
n = strlen(line);
// Find first white space which terminates the line key.
- for (i = 0; i < n && !isspace(line[i]); ++i)
+ for (i = 0; i < n && !isspace(line[i]); ++i) {
;
- if (i != key_len || 0 != strncmp(line, key_str, key_len))
+ }
+ if (i != key_len || 0 != strncmp(line, key_str, key_len)) {
continue;
+ }
// Now look for IP address
while (true) {
- if (!skip_space(line, n, i))
+ if (!skip_space(line, n, i)) {
break;
+ }
if (0 != read_addr(line, n, &i, &laddr.sa, err_buff)) {
char *error_str = (char *)ats_malloc(ERR_STRING_LEN);
@@ -143,10 +148,11 @@ Load_IpMap_From_File(IpMap *map, FILE *f, const char *key_str)
if (!skip_space(line, n, i) || line[i] == ',') {
// You have read an IP address. Enter it in the table
map->mark(&laddr);
- if (i == n)
+ if (i == n) {
break;
- else
+ } else {
++i;
+ }
} else if (line[i] == '-') {
// What you have just read is the start of the range,
// Now, read the end of the IP range
@@ -161,8 +167,9 @@ Load_IpMap_From_File(IpMap *map, FILE *f, const char *key_str)
return error_str;
}
map->mark(&laddr.sa, &raddr.sa);
- if (!skip_space(line, n, i))
+ if (!skip_space(line, n, i)) {
break;
+ }
if (line[i] != ',') {
char *error_str = (char *)ats_malloc(ERR_STRING_LEN);
snprintf(error_str, ERR_STRING_LEN, "Invalid input (expecting comma) at line %d offset %d - '%s'", line_no, i, line);
diff --git a/lib/ts/MMH.cc b/lib/ts/MMH.cc
index 31d9bd3..12d7fae 100644
--- a/lib/ts/MMH.cc
+++ b/lib/ts/MMH.cc
@@ -236,11 +236,13 @@ ink_code_incr_MMH_update(MMH_CTX *ctx, const char *ainput, int input_length)
memcpy(ctx->buffer + ctx->buffer_size, in, l);
ctx->buffer_size = 0;
in += l;
- if (ctx->buffer_size & 0x0f)
+ if (ctx->buffer_size & 0x0f) {
return 0;
+ }
MMH_update(ctx, ctx->buffer);
- } else
+ } else {
goto Lstore;
+ }
}
{
// check alignment
@@ -265,11 +267,12 @@ ink_code_incr_MMH_update(MMH_CTX *ctx, const char *ainput, int input_length)
MMH_updateb2(ctx, in);
in += 16;
}
- } else if (alignment == 3)
+ } else if (alignment == 3) {
while (in + 16 <= end) {
MMH_updateb3(ctx, in);
in += 16;
}
+ }
} else {
if (alignment == 1) {
while (in + 16 <= end) {
@@ -281,11 +284,12 @@ ink_code_incr_MMH_update(MMH_CTX *ctx, const char *ainput, int input_length)
MMH_updatel2(ctx, in);
in += 16;
}
- } else if (alignment == 3)
+ } else if (alignment == 3) {
while (in + 16 <= end) {
MMH_updatel3(ctx, in);
in += 16;
}
+ }
}
} else {
while (in + 16 <= end) {
diff --git a/lib/ts/MatcherUtils.cc b/lib/ts/MatcherUtils.cc
index 6e155a6..218d9a5 100644
--- a/lib/ts/MatcherUtils.cc
+++ b/lib/ts/MatcherUtils.cc
@@ -147,10 +147,12 @@ ExtractIpRange(char *match_str, in_addr_t *min, in_addr_t *max)
const char *zret = ExtractIpRange(match_str, &ip_min.sa, &ip_max.sa);
if (nullptr == zret) { // success
if (ats_is_ip4(&ip_min) && ats_is_ip4(&ip_max)) {
- if (min)
+ if (min) {
*min = ntohl(ats_ip4_addr_cast(&ip_min));
- if (max)
+ }
+ if (max) {
*max = ntohl(ats_ip4_addr_cast(&ip_max));
+ }
} else {
zret = "The addresses were not IPv4 addresses.";
}
diff --git a/lib/ts/MemView.cc b/lib/ts/MemView.cc
index 19c24cb..3ae7749 100644
--- a/lib/ts/MemView.cc
+++ b/lib/ts/MemView.cc
@@ -41,16 +41,17 @@ memcmp(MemView const &lhs, MemView const &rhs)
size_t n;
// Seems a bit ugly but size comparisons must be done anyway to get the memcmp args.
- if (lhs.size() < rhs.size())
+ if (lhs.size() < rhs.size()) {
zret = 1, n = lhs.size();
- else {
+ } else {
n = rhs.size();
zret = rhs.size() < lhs.size() ? -1 : 0;
}
int r = ::memcmp(lhs.ptr(), rhs.ptr(), n);
- if (0 != r) // If we got a not-equal, override the size based result.
+ if (0 != r) { // If we got a not-equal, override the size based result.
zret = r;
+ }
return zret;
}
@@ -61,10 +62,11 @@ strcasecmp(StringView lhs, StringView rhs)
while (lhs && rhs) {
char l = tolower(*lhs);
char r = tolower(*rhs);
- if (l < r)
+ if (l < r) {
return -1;
- else if (r < l)
+ } else if (r < l) {
return 1;
+ }
++lhs, ++rhs;
}
return lhs ? 1 : rhs ? -1 : 0;
@@ -97,10 +99,12 @@ svtoi(StringView src, StringView *out, int base)
intmax_t zret = 0;
- if (out)
+ if (out) {
out->clear();
- if (!(1 < base && base <= 36))
+ }
+ if (!(1 < base && base <= 36)) {
return 0;
+ }
if (src.ltrim(&isspace)) {
const char *start = src.ptr();
int8_t v;
@@ -117,8 +121,9 @@ svtoi(StringView src, StringView *out, int base)
out->setView(start, src.ptr());
}
- if (neg)
+ if (neg) {
zret = -zret;
+ }
}
return zret;
}
diff --git a/lib/ts/ParseRules.cc b/lib/ts/ParseRules.cc
index 56e4751..e87f8df 100644
--- a/lib/ts/ParseRules.cc
+++ b/lib/ts/ParseRules.cc
@@ -53,13 +53,15 @@ ink_atoi64(const char *str)
int64_t num = 0;
int negative = 0;
- while (*str && ParseRules::is_wslfcr(*str))
+ while (*str && ParseRules::is_wslfcr(*str)) {
str += 1;
+ }
if (unlikely(str[0] == '0' && str[1] == 'x')) {
str += 2;
- while (*str && ParseRules::is_hex(*str))
+ while (*str && ParseRules::is_hex(*str)) {
num = (num << 4) + ink_get_hex(*str++);
+ }
} else {
if (unlikely(*str == '-')) {
negative = 1;
@@ -70,22 +72,25 @@ ink_atoi64(const char *str)
NOTE: we first compute the value as negative then correct the
sign back to positive. This enables us to correctly parse MININT.
*/
- while (*str && ParseRules::is_digit(*str))
+ while (*str && ParseRules::is_digit(*str)) {
num = (num * 10) - (*str++ - '0');
+ }
#if USE_SI_MULTILIERS
if (*str) {
- if (*str == 'K')
+ if (*str == 'K') {
num = num * (1LL << 10);
- else if (*str == 'M')
+ } else if (*str == 'M') {
num = num * (1LL << 20);
- else if (*str == 'G')
+ } else if (*str == 'G') {
num = num * (1LL << 30);
- else if (*str == 'T')
+ } else if (*str == 'T') {
num = num * (1LL << 40);
+ }
}
#endif
- if (!negative)
+ if (!negative) {
num = -num;
+ }
}
return num;
}
@@ -95,26 +100,30 @@ ink_atoui64(const char *str)
{
uint64_t num = 0;
- while (*str && ParseRules::is_wslfcr(*str))
+ while (*str && ParseRules::is_wslfcr(*str)) {
str += 1;
+ }
if (unlikely(str[0] == '0' && str[1] == 'x')) {
str += 2;
- while (*str && ParseRules::is_hex(*str))
+ while (*str && ParseRules::is_hex(*str)) {
num = (num << 4) + ink_get_hex(*str++);
+ }
} else {
- while (*str && ParseRules::is_digit(*str))
+ while (*str && ParseRules::is_digit(*str)) {
num = (num * 10) + (*str++ - '0');
+ }
#if USE_SI_MULTILIERS
if (*str) {
- if (*str == 'K')
+ if (*str == 'K') {
num = num * (1LL << 10);
- else if (*str == 'M')
+ } else if (*str == 'M') {
num = num * (1LL << 20);
- else if (*str == 'G')
+ } else if (*str == 'G') {
num = num * (1LL << 30);
- else if (*str == 'T')
+ } else if (*str == 'T') {
num = num * (1LL << 40);
+ }
}
#endif
}
@@ -132,8 +141,9 @@ ink_atoi64(const char *str, int len)
len--;
}
- if (len < 1)
+ if (len < 1) {
return 0;
+ }
if (unlikely(str[0] == '0' && len > 1 && str[1] == 'x')) {
str += 2;
@@ -157,17 +167,19 @@ ink_atoi64(const char *str, int len)
}
#if USE_SI_MULTILIERS
if (len > 0 && *str) {
- if (*str == 'K')
+ if (*str == 'K') {
num = num * (1 << 10);
- else if (*str == 'M')
+ } else if (*str == 'M') {
num = num * (1 << 20);
- else if (*str == 'G')
+ } else if (*str == 'G') {
num = num * (1 << 30);
+ }
}
#endif
- if (!negative)
+ if (!negative) {
num = -num;
+ }
}
return num;
}
diff --git a/lib/ts/RbTree.cc b/lib/ts/RbTree.cc
index 28ca597..3fda294 100644
--- a/lib/ts/RbTree.cc
+++ b/lib/ts/RbTree.cc
@@ -77,12 +77,14 @@ namespace detail
RBNode *
RBNode::setChild(self *n, Direction d)
{
- if (n)
+ if (n) {
n->_parent = this;
- if (d == RIGHT)
+ }
+ if (d == RIGHT) {
_right = n;
- else if (d == LEFT)
+ } else if (d == LEFT) {
_left = n;
+ }
return n;
}
@@ -107,16 +109,19 @@ namespace detail
if (_parent) {
Direction d = _parent->getChildDirection(this);
_parent->setChild(nullptr, d);
- if (_parent != n)
+ if (_parent != n) {
_parent->setChild(n, d);
+ }
} else {
n->_parent = nullptr;
}
n->_left = n->_right = nullptr;
- if (_left && _left != n)
+ if (_left && _left != n) {
n->setChild(_left, LEFT);
- if (_right && _right != n)
+ }
+ if (_right && _right != n) {
n->setChild(_right, RIGHT);
+ }
_left = _right = nullptr;
}
@@ -129,10 +134,11 @@ namespace detail
while (x && x->_parent == RED) {
Direction child_dir = NONE;
- if (x->_parent->_parent)
+ if (x->_parent->_parent) {
child_dir = x->_parent->_parent->getChildDirection(x->_parent);
- else
+ } else {
break;
+ }
Direction other_dir(flip(child_dir));
self *y = x->_parent->_parent->getChild(other_dir);
@@ -230,8 +236,9 @@ namespace detail
// node in liu of copying the data over.
if (remove_node != this) {
// Don't leave @a splice_node referring to a removed node
- if (splice_node == this)
+ if (splice_node == this) {
splice_node = remove_node;
+ }
this->replaceWith(remove_node);
}
diff --git a/lib/ts/Regex.cc b/lib/ts/Regex.cc
index b6f2ac4..4aa3230 100644
--- a/lib/ts/Regex.cc
+++ b/lib/ts/Regex.cc
@@ -56,8 +56,9 @@ Regex::compile(const char *pattern, const unsigned flags)
int options = 0;
int study_opts = 0;
- if (regex)
+ if (regex) {
return false;
+ }
if (flags & RE_CASE_INSENSITIVE) {
options |= PCRE_CASELESS;
@@ -80,8 +81,9 @@ Regex::compile(const char *pattern, const unsigned flags)
regex_extra = pcre_study(regex, study_opts, &error);
#ifdef PCRE_CONFIG_JIT
- if (regex_extra)
+ if (regex_extra) {
pcre_assign_jit_stack(regex_extra, &get_jit_stack, nullptr);
+ }
#endif
return true;
@@ -122,14 +124,16 @@ Regex::exec(const char *str, int length, int *ovector, int ovecsize)
Regex::~Regex()
{
- if (regex_extra)
+ if (regex_extra) {
#ifdef PCRE_CONFIG_JIT
pcre_free_study(regex_extra);
+ }
#else
pcre_free(regex_extra);
#endif
- if (regex)
+ if (regex) {
pcre_free(regex);
+ }
}
DFA::~DFA()
@@ -138,10 +142,12 @@ DFA::~DFA()
dfa_pattern *t;
while (p) {
- if (p->_re)
+ if (p->_re) {
delete p->_re;
- if (p->_p)
+ }
+ if (p->_p) {
ats_free(p->_p);
+ }
t = p->_next;
ats_free(p);
p = t;
@@ -180,10 +186,11 @@ DFA::compile(const char *pattern, unsigned flags)
{
ink_assert(_my_patterns == nullptr);
_my_patterns = build(pattern, flags);
- if (_my_patterns)
+ if (_my_patterns) {
return 0;
- else
+ } else {
return -1;
+ }
}
int
diff --git a/lib/ts/Regression.cc b/lib/ts/Regression.cc
index 5ce8255..34ba7bf 100644
--- a/lib/ts/Regression.cc
+++ b/lib/ts/Regression.cc
@@ -62,13 +62,15 @@ RegressionTest::RegressionTest(const char *_n, const SourceLocation &_l, TestFun
: name(_n), location(_l), function(_f), next(nullptr), status(REGRESSION_TEST_NOT_RUN), printed(false), opt(_o)
{
if (opt == REGRESSION_OPT_EXCLUSIVE) {
- if (exclusive_test)
- this->next = exclusive_test;
+ if (exclusive_test) {
+ this->next = exclusive_test;
+ }
exclusive_test = this;
} else {
- if (test)
+ if (test) {
this->next = test;
- test = this;
+ }
+ test = this;
}
}
@@ -91,18 +93,20 @@ start_test(RegressionTest *t, int regression_level)
int
RegressionTest::run(const char *atest, int regression_level)
{
- if (atest)
+ if (atest) {
dfa.compile(atest);
- else
+ } else {
dfa.compile(".*");
+ }
fprintf(stderr, "REGRESSION_TEST initialization begun\n");
// start the non exclusive tests
for (RegressionTest *t = test; t; t = t->next) {
if ((dfa.match(t->name) >= 0)) {
int res = start_test(t, regression_level);
- if (res == REGRESSION_TEST_FAILED)
+ if (res == REGRESSION_TEST_FAILED) {
final_status = REGRESSION_TEST_FAILED;
+ }
}
}
@@ -151,10 +155,12 @@ RegressionTest::run_some(int regression_level)
for (; current; current = current->next) {
if ((dfa.match(current->name) >= 0)) {
int res = start_test(current, regression_level);
- if (res == REGRESSION_TEST_INPROGRESS)
+ if (res == REGRESSION_TEST_INPROGRESS) {
return res;
- if (res == REGRESSION_TEST_FAILED)
+ }
+ if (res == REGRESSION_TEST_FAILED) {
final_status = REGRESSION_TEST_FAILED;
+ }
}
}
return REGRESSION_TEST_INPROGRESS;
@@ -166,8 +172,9 @@ RegressionTest::check_status(int regression_level)
int status = REGRESSION_TEST_PASSED;
if (current) {
status = run_some(regression_level);
- if (!current)
+ if (!current) {
return status;
+ }
}
RegressionTest *t = test;
@@ -265,8 +272,9 @@ REGRESSION_TEST(Regression)(RegressionTest *t, int atype, int *status)
(void)atype;
rprintf(t, "regression test\n");
rperf(t, "speed", 100.0);
- if (!test)
+ if (!test) {
*status = REGRESSION_TEST_FAILED;
- else
+ } else {
*status = REGRESSION_TEST_PASSED;
+ }
}
diff --git a/lib/ts/SourceLocation.cc b/lib/ts/SourceLocation.cc
index 8621e9e..b2ac79d 100644
--- a/lib/ts/SourceLocation.cc
+++ b/lib/ts/SourceLocation.cc
@@ -38,8 +38,9 @@ SourceLocation::str(char *buf, int buflen) const
{
const char *shortname;
- if (!this->valid() || buflen < 1)
+ if (!this->valid() || buflen < 1) {
return (nullptr);
+ }
shortname = strrchr(file, '/');
shortname = shortname ? (shortname + 1) : file;
diff --git a/lib/ts/Tokenizer.cc b/lib/ts/Tokenizer.cc
index 74f3738..13a3330 100644
--- a/lib/ts/Tokenizer.cc
+++ b/lib/ts/Tokenizer.cc
@@ -71,8 +71,9 @@ Tokenizer::~Tokenizer()
while (cur != nullptr) {
if (options & COPY_TOKS) {
- for (auto &i : cur->el)
+ for (auto &i : cur->el) {
ats_free(i);
+ }
}
next = cur->next;
@@ -100,8 +101,9 @@ Tokenizer::isDelimiter(char c)
quoteFound = !quoteFound;
}
- if (quoteFound)
+ if (quoteFound) {
return 0;
+ }
while (strOfDelimit[i] != '\0') {
if (c == strOfDelimit[i]) {
@@ -196,14 +198,16 @@ Tokenizer::Initialize(char *str, unsigned opt)
// Go till either we hit a delimiter or we've
// come to the end of the string, then
// set for copying
- for (; *str != '\0' && !isDelimiter(*str); str++)
+ for (; *str != '\0' && !isDelimiter(*str); str++) {
;
+ }
priorCharWasDelimit = 0;
} else {
// First, skip the delimiters
- for (; *str != '\0' && isDelimiter(*str); str++)
+ for (; *str != '\0' && isDelimiter(*str); str++) {
;
+ }
// If there are only delimiters remaining, bail and set
// so that we do not add the empty token
@@ -215,12 +219,14 @@ Tokenizer::Initialize(char *str, unsigned opt)
priorCharWasDelimit = 0;
// Advance until the end of the string
- for (; *str != '\0'; str++)
+ for (; *str != '\0'; str++) {
;
+ }
// Now back off all trailing delimiters
- for (; isDelimiter(*(str - 1)); str--)
+ for (; isDelimiter(*(str - 1)); str--) {
;
+ }
}
}
}
@@ -356,8 +362,9 @@ Tokenizer::ReUse()
while (cur_node != nullptr) {
if (options & COPY_TOKS) {
- for (auto &i : cur_node->el)
+ for (auto &i : cur_node->el) {
ats_free(i);
+ }
}
memset(cur_node->el, 0, sizeof(char *) * TOK_NODE_ELEMENTS);
cur_node = cur_node->next;
diff --git a/lib/ts/Vec.cc b/lib/ts/Vec.cc
index 43a1b60..1076683 100644
--- a/lib/ts/Vec.cc
+++ b/lib/ts/Vec.cc
@@ -66,10 +66,12 @@ i_find(const Intervals *i, int x)
int l = 0, h = i->n;
Lrecurse:
if (h <= l + 2) {
- if (h <= l)
+ if (h <= l) {
return -(l + 1);
- if (x < i->v[l] || x > i->v[l + 1])
+ }
+ if (x < i->v[l] || x > i->v[l + 1]) {
return -(l + 1);
+ }
return h;
}
int m = (((h - l) / 4) * 2) + l;
@@ -87,10 +89,12 @@ Lrecurse:
bool
Intervals::in(int x) const
{
- if (!n)
+ if (!n) {
return false;
- if (i_find(this, x) > 0)
+ }
+ if (i_find(this, x) > 0) {
return true;
+ }
return false;
}
@@ -104,8 +108,9 @@ Intervals::insert(int x)
return;
}
int l = i_find(this, x);
- if (l > 0)
+ if (l > 0) {
return;
+ }
l = -l - 1;
if (x > v[l + 1]) {
@@ -127,8 +132,9 @@ Intervals::insert(int x)
v[l]--;
goto Lmerge;
}
- if (!l)
+ if (!l) {
goto Lmore;
+ }
l -= 2;
if (x == v[l + 1] + 1) {
v[l + 1]++;
@@ -137,8 +143,9 @@ Intervals::insert(int x)
}
Lmore:
fill(n + 2);
- if (n - 2 - l > 0)
+ if (n - 2 - l > 0) {
memmove(v + l + 2, v + l, sizeof(int) * (n - 2 - l));
+ }
v[l] = x;
v[l + 1] = x;
return;
@@ -150,8 +157,9 @@ Lmerge:
}
}
if (l < (int)(n - 2)) {
- if (v[l + 2] - v[l + 1] < 2)
+ if (v[l + 2] - v[l + 1] < 2) {
goto Ldomerge;
+ }
}
return;
Ldomerge:
@@ -165,16 +173,18 @@ UnionFind::size(int s)
{
size_t nn = n;
fill(s);
- for (size_t i = nn; i < n; i++)
- v[i] = -1;
+ for (size_t i = nn; i < n; i++) {
+ v[i] = -1;
+ }
}
int
UnionFind::find(int n)
{
int i, t;
- for (i = n; v[i] >= 0; i = v[i])
+ for (i = n; v[i] >= 0; i = v[i]) {
;
+ }
while (v[n] >= 0) {
t = n;
n = v[n];
diff --git a/lib/ts/Version.cc b/lib/ts/Version.cc
index 258b0bb..7af00bb 100644
--- a/lib/ts/Version.cc
+++ b/lib/ts/Version.cc
@@ -56,8 +56,9 @@ AppVersionInfo::setup(const char *pkg_name, const char *app_name, const char *ap
// Jan=1, Feb=2 ... Dec=12, ???=13
for (month = 0; month < 11; month++) {
- if (strcasecmp(months[month], month_name) == 0)
+ if (strcasecmp(months[month], month_name) == 0) {
break;
+ }
}
month++;
@@ -87,26 +88,36 @@ AppVersionInfo::setup(const char *pkg_name, const char *app_name, const char *ap
/////////////////////////////////////////////////////////////
// the manager doesn't like empty strings, so prevent them //
/////////////////////////////////////////////////////////////
- if (PkgStr[0] == '\0')
+ if (PkgStr[0] == '\0') {
ink_strlcpy(PkgStr, "?", sizeof(PkgStr));
- if (AppStr[0] == '\0')
+ }
+ if (AppStr[0] == '\0') {
ink_strlcpy(AppStr, "?", sizeof(AppStr));
- if (VersionStr[0] == '\0')
+ }
+ if (VersionStr[0] == '\0') {
ink_strlcpy(VersionStr, "?", sizeof(VersionStr));
- if (BldNumStr[0] == '\0')
+ }
+ if (BldNumStr[0] == '\0') {
ink_strlcpy(BldNumStr, "?", sizeof(BldNumStr));
- if (BldTimeStr[0] == '\0')
+ }
+ if (BldTimeStr[0] == '\0') {
ink_strlcpy(BldTimeStr, "?", sizeof(BldTimeStr));
- if (BldDateStr[0] == '\0')
+ }
+ if (BldDateStr[0] == '\0') {
ink_strlcpy(BldDateStr, "?", sizeof(BldDateStr));
- if (BldMachineStr[0] == '\0')
+ }
+ if (BldMachineStr[0] == '\0') {
ink_strlcpy(BldMachineStr, "?", sizeof(BldMachineStr));
- if (BldPersonStr[0] == '\0')
+ }
+ if (BldPersonStr[0] == '\0') {
ink_strlcpy(BldPersonStr, "?", sizeof(BldPersonStr));
- if (BldCompileFlagsStr[0] == '\0')
+ }
+ if (BldCompileFlagsStr[0] == '\0') {
ink_strlcpy(BldCompileFlagsStr, "?", sizeof(BldCompileFlagsStr));
- if (FullVersionInfoStr[0] == '\0')
+ }
+ if (FullVersionInfoStr[0] == '\0') {
ink_strlcpy(FullVersionInfoStr, "?", sizeof(FullVersionInfoStr));
+ }
snprintf(FullVersionInfoStr, sizeof(FullVersionInfoStr), "%s - %s - %s - (build # %s on %s at %s)", PkgStr, AppStr, VersionStr,
BldNumStr, BldDateStr, BldTimeStr);
diff --git a/lib/ts/X509HostnameValidator.cc b/lib/ts/X509HostnameValidator.cc
index efa7fda..0d1f61d 100644
--- a/lib/ts/X509HostnameValidator.cc
+++ b/lib/ts/X509HostnameValidator.cc
@@ -61,8 +61,9 @@ find_wildcard_in_hostname(const unsigned char *p, size_t len, bool idna_subject)
}
}
// Final dot minimal pos is a.b.xxxxxx
- if (final_dot_pos < 3)
+ if (final_dot_pos < 3) {
return nullptr;
+ }
for (i = 0; i < final_dot_pos; i++) {
/*
@@ -76,8 +77,9 @@ find_wildcard_in_hostname(const unsigned char *p, size_t len, bool idna_subject)
((i < final_dot_pos - 1) && (p[i + 1] == '.'))) { // Found a trailing wildcard in the first label
// IDNA hostnames must match a full label
- if (idna_subject && (i != 0 || p[i + 1] != '.'))
+ if (idna_subject && (i != 0 || p[i + 1] != '.')) {
break;
+ }
wildcard_pos = i;
} else {
@@ -87,8 +89,9 @@ find_wildcard_in_hostname(const unsigned char *p, size_t len, bool idna_subject)
}
// String contains at least two dots.
if (p[i] == '.') {
- if (wildcard_pos != -1)
+ if (wildcard_pos != -1) {
return &p[wildcard_pos];
+ }
// Only valid wildcard is in the first label
break;
}
@@ -106,8 +109,9 @@ find_wildcard_in_hostname(const unsigned char *p, size_t len, bool idna_subject)
static bool
equal_nocase(const unsigned char *pattern, size_t pattern_len, const unsigned char *subject, size_t subject_len)
{
- if (pattern_len != subject_len)
+ if (pattern_len != subject_len) {
return false;
+ }
return (strncasecmp((char *)pattern, (char *)subject, pattern_len) == 0);
}
@@ -115,8 +119,9 @@ equal_nocase(const unsigned char *pattern, size_t pattern_len, const unsigned ch
static bool
equal_case(const unsigned char *pattern, size_t pattern_len, const unsigned char *subject, size_t subject_len)
{
- if (pattern_len != subject_len)
+ if (pattern_len != subject_len) {
return false;
+ }
return (memcmp(pattern, subject, pattern_len) == 0);
}
@@ -132,32 +137,39 @@ wildcard_match(const unsigned char *prefix, size_t prefix_len, const unsigned ch
const unsigned char *wildcard_end;
const unsigned char *p;
- if (subject_len < prefix_len + suffix_len)
+ if (subject_len < prefix_len + suffix_len) {
return false;
- if (!equal_nocase(prefix, prefix_len, subject, prefix_len))
+ }
+ if (!equal_nocase(prefix, prefix_len, subject, prefix_len)) {
return false;
+ }
wildcard_start = subject + prefix_len;
wildcard_end = subject + (subject_len - suffix_len);
- if (!equal_nocase(wildcard_end, suffix_len, suffix, suffix_len))
+ if (!equal_nocase(wildcard_end, suffix_len, suffix, suffix_len)) {
return false;
+ }
/*
* If the wildcard makes up the entire first label, it must match at
* least one character.
*/
if (prefix_len == 0 && *suffix == '.') {
- if (wildcard_start == wildcard_end)
+ if (wildcard_start == wildcard_end) {
return false;
+ }
}
/* The wildcard may match a literal '*' */
- if (wildcard_end == wildcard_start + 1 && *wildcard_start == '*')
+ if (wildcard_end == wildcard_start + 1 && *wildcard_start == '*') {
return true;
+ }
/*
* Check that the part matched by the wildcard contains only
* permitted characters and only matches a single label
*/
- for (p = wildcard_start; p != wildcard_end; ++p)
- if (!(('0' <= *p && *p <= '9') || ('A' <= *p && *p <= 'Z') || ('a' <= *p && *p <= 'z') || *p == '-'))
+ for (p = wildcard_start; p != wildcard_end; ++p) {
+ if (!(('0' <= *p && *p <= '9') || ('A' <= *p && *p <= 'Z') || ('a' <= *p && *p <= 'z') || *p == '-')) {
return false;
+ }
+ }
return true;
}
@@ -172,11 +184,13 @@ equal_wildcard(const unsigned char *pattern, size_t pattern_len, const unsigned
* Subject names starting with '.' can only match a wildcard pattern
* via a subject sub-domain pattern suffix match (that we don't allow).
*/
- if (subject_len > 5 && subject[0] != '.')
+ if (subject_len > 5 && subject[0] != '.') {
wildcard = find_wildcard_in_hostname(pattern, pattern_len, is_idna);
+ }
- if (wildcard == nullptr)
+ if (wildcard == nullptr) {
return equal_nocase(pattern, pattern_len, subject, subject_len);
+ }
return wildcard_match(pattern, wildcard - pattern, wildcard + 1, (pattern + pattern_len) - wildcard - 1, subject, subject_len);
}
@@ -191,11 +205,13 @@ do_check_string(ASN1_STRING *a, int cmp_type, equal_fn equal, const unsigned cha
{
bool retval = false;
- if (!a->data || !a->length || cmp_type != a->type)
+ if (!a->data || !a->length || cmp_type != a->type) {
return false;
+ }
retval = equal(a->data, a->length, b, blen);
- if (retval && peername)
+ if (retval && peername) {
*peername = ats_strndup((char *)a->data, a->length);
+ }
return retval;
}
@@ -236,13 +252,15 @@ validate_hostname(X509 *x, const unsigned char *hostname, bool is_ip, char **pee
continue;
}
- if ((retval = do_check_string(cstr, alt_type, equal, hostname, hostname_len, peername)) == true)
+ if ((retval = do_check_string(cstr, alt_type, equal, hostname, hostname_len, peername)) == true) {
// We got a match
break;
+ }
}
GENERAL_NAMES_free(gens);
- if (retval)
+ if (retval) {
return retval;
+ }
}
// No SAN match -- check the subject
i = -1;
@@ -256,11 +274,13 @@ validate_hostname(X509 *x, const unsigned char *hostname, bool is_ip, char **pee
// Convert to UTF-8
astrlen = ASN1_STRING_to_UTF8(&astr, str);
- if (astrlen < 0)
+ if (astrlen < 0) {
return -1;
+ }
retval = equal(astr, astrlen, hostname, hostname_len);
- if (retval && peername)
+ if (retval && peername) {
*peername = ats_strndup((char *)astr, astrlen);
+ }
OPENSSL_free(astr);
return retval;
}
diff --git a/lib/ts/ink_args.cc b/lib/ts/ink_args.cc
index 7c58592..b2a61c1 100644
--- a/lib/ts/ink_args.cc
+++ b/lib/ts/ink_args.cc
@@ -176,12 +176,13 @@ process_args_ex(const AppVersionInfo *appinfo, const ArgumentDescription *argume
//
// Grab Environment Variables
//
- for (i = 0; i < n_argument_descriptions; i++)
+ for (i = 0; i < n_argument_descriptions; i++) {
if (argument_descriptions[i].env) {
char type = argument_descriptions[i].type[0];
char *env = getenv(argument_descriptions[i].env);
- if (!env)
+ if (!env) {
continue;
+ }
switch (type) {
case 'f':
case 'F':
@@ -199,6 +200,7 @@ process_args_ex(const AppVersionInfo *appinfo, const ArgumentDescription *argume
break;
}
}
+ }
//
// Grab Command Line Arguments
//
@@ -218,7 +220,7 @@ process_args_ex(const AppVersionInfo *appinfo, const ArgumentDescription *argume
if ((*argv)[1] == '-') {
// Deal with long options ...
- for (i = 0; i < n_argument_descriptions; i++)
+ for (i = 0; i < n_argument_descriptions; i++) {
if (!strcmp(argument_descriptions[i].name, (*argv) + 2)) {
*argv += strlen(*argv) - 1;
if (!process_arg(appinfo, argument_descriptions, n_argument_descriptions, i, &argv)) {
@@ -226,6 +228,7 @@ process_args_ex(const AppVersionInfo *appinfo, const ArgumentDescription *argume
}
break;
}
+ }
if (i >= n_argument_descriptions) {
return false;
}
@@ -264,21 +267,24 @@ usage(const ArgumentDescription *argument_descriptions, unsigned n_argument_desc
(void)argument_descriptions;
(void)n_argument_descriptions;
(void)usage_string;
- if (usage_string)
+ if (usage_string) {
fprintf(stderr, "%s\n", usage_string);
- else
+ } else {
fprintf(stderr, "Usage: %s [--SWITCH [ARG]]\n", program_name);
+ }
fprintf(stderr, " switch__________________type__default___description\n");
for (unsigned i = 0; i < n_argument_descriptions; i++) {
- if (!argument_descriptions[i].description)
+ if (!argument_descriptions[i].description) {
continue;
+ }
fprintf(stderr, " ");
- if ('-' == argument_descriptions[i].key)
+ if ('-' == argument_descriptions[i].key) {
fprintf(stderr, " ");
- else
+ } else {
fprintf(stderr, "-%c,", argument_descriptions[i].key);
+ }
fprintf(stderr, " --%-17s %s", argument_descriptions[i].name,
argument_types_descriptions[argument_descriptions[i].type ?
diff --git a/lib/ts/ink_base64.cc b/lib/ts/ink_base64.cc
index aa0f566..2aee516 100644
--- a/lib/ts/ink_base64.cc
+++ b/lib/ts/ink_base64.cc
@@ -44,8 +44,9 @@ ats_base64_encode(const unsigned char *inBuffer, size_t inBufferSize, char *outB
char *obuf = outBuffer;
char in_tail[4];
- if (outBufSize < ATS_BASE64_ENCODE_DSTLEN(inBufferSize))
+ if (outBufSize < ATS_BASE64_ENCODE_DSTLEN(inBufferSize)) {
return false;
+ }
while (inBufferSize > 2) {
*obuf++ = _codes[(inBuffer[0] >> 2) & 077];
@@ -67,8 +68,9 @@ ats_base64_encode(const unsigned char *inBuffer, size_t inBufferSize, char *outB
*/
if (inBufferSize == 0) {
*obuf = '\0';
- if (length)
+ if (length) {
*length = (obuf - outBuffer);
+ }
} else {
memset(in_tail, 0, sizeof(in_tail));
memcpy(in_tail, inBuffer, inBufferSize);
@@ -78,13 +80,15 @@ ats_base64_encode(const unsigned char *inBuffer, size_t inBufferSize, char *outB
*(obuf + 2) = _codes[((in_tail[1] & 017) << 2) | ((in_tail[2] >> 6) & 017)];
*(obuf + 3) = _codes[in_tail[2] & 077];
- if (inBufferSize == 1)
+ if (inBufferSize == 1) {
*(obuf + 2) = '=';
- *(obuf + 3) = '=';
- *(obuf + 4) = '\0';
+ }
+ *(obuf + 3) = '=';
+ *(obuf + 4) = '\0';
- if (length)
+ if (length) {
*length = (obuf + 4) - outBuffer;
+ }
}
return true;
@@ -126,13 +130,15 @@ ats_base64_decode(const char *inBuffer, size_t inBufferSize, unsigned char *outB
int inputBytesDecoded = 0;
// Make sure there is sufficient space in the output buffer
- if (outBufSize < ATS_BASE64_DECODE_DSTLEN(inBufferSize))
+ if (outBufSize < ATS_BASE64_DECODE_DSTLEN(inBufferSize)) {
return false;
+ }
// Ignore any trailing ='s or other undecodable characters.
// TODO: Perhaps that ought to be an error instead?
- while (printableToSixBit[(uint8_t)inBuffer[inBytes]] <= MAX_PRINT_VAL)
+ while (printableToSixBit[(uint8_t)inBuffer[inBytes]] <= MAX_PRINT_VAL) {
++inBytes;
+ }
for (size_t i = 0; i < inBytes; i += 4) {
buf[0] = (unsigned char)(DECODE(inBuffer[0]) << 2 | DECODE(inBuffer[1]) >> 4);
@@ -156,8 +162,9 @@ ats_base64_decode(const char *inBuffer, size_t inBufferSize, unsigned char *outB
}
outBuffer[decodedBytes] = '\0';
- if (length)
+ if (length) {
*length = decodedBytes;
+ }
return true;
}
diff --git a/lib/ts/ink_defs.cc b/lib/ts/ink_defs.cc
index 2dfa331..6d63a02 100644
--- a/lib/ts/ink_defs.cc
+++ b/lib/ts/ink_defs.cc
@@ -94,18 +94,21 @@ ink_sys_name_release(char *name, int namelen, char *release, int releaselen)
struct utsname buf;
int n;
- if (uname(&buf))
+ if (uname(&buf)) {
return -1;
+ }
n = strlen(buf.sysname);
- if (namelen <= n)
+ if (namelen <= n) {
n = namelen - 1;
+ }
memcpy(name, buf.sysname, n);
name[n] = 0;
n = strlen(buf.release);
- if (releaselen <= n)
+ if (releaselen <= n) {
n = releaselen - 1;
+ }
memcpy(release, buf.release, n);
release[n] = 0;
diff --git a/lib/ts/ink_file.cc b/lib/ts/ink_file.cc
index dcd46db..4bcbbe8 100644
--- a/lib/ts/ink_file.cc
+++ b/lib/ts/ink_file.cc
@@ -67,11 +67,13 @@ ink_fputln(FILE *stream, const char *s)
{
if (stream && s) {
int rc = fputs(s, stream);
- if (rc > 0)
+ if (rc > 0) {
rc += fputc('\n', stream);
+ }
return rc;
- } else
+ } else {
return -EINVAL;
+ }
} /* End ink_fgets */
/*---------------------------------------------------------------------------*
@@ -99,18 +101,22 @@ ink_file_fd_readline(int fd, int bufsz, char *buf)
char c;
int i = 0;
- if (bufsz < 2)
+ if (bufsz < 2) {
return (-EINVAL); /* bufsz must by >= 2 */
+ }
while (i < bufsz - 1) { /* leave 1 byte for NUL */
int n = read(fd, &c, 1); /* read 1 byte */
- if (n == 0)
+ if (n == 0) {
break; /* EOF */
- if (n < 0)
+ }
+ if (n < 0) {
return (n); /* error */
+ }
buf[i++] = c; /* store in buffer */
- if (c == '\n')
+ if (c == '\n') {
break; /* stop if stored a LF */
+ }
}
buf[i] = '\0'; /* NUL terminate buffer */
@@ -123,8 +129,9 @@ ink_file_fd_writestring(int fd, const char *buf)
{
int len, i = 0;
- if (buf && (len = strlen(buf)) > 0 && (i = (int)write(fd, buf, (size_t)len) != len))
+ if (buf && (len = strlen(buf)) > 0 && (i = (int)write(fd, buf, (size_t)len) != len)) {
i = -1;
+ }
return i; /* return chars written */
} /* End ink_file_fd_writestring */
@@ -141,25 +148,29 @@ ink_filepath_merge(char *path, int pathsz, const char *rootpath, const char *add
/* Treat null as an empty path.
*/
- if (!addpath)
+ if (!addpath) {
addpath = "";
+ }
if (addpath[0] == '/') {
// If addpath is rooted, then rootpath is unused.
// Ths violates any INK_FILEPATH_SECUREROOTTEST and
// INK_FILEPATH_NOTABSOLUTE flags specified.
//
- if (flags & INK_FILEPATH_SECUREROOTTEST)
+ if (flags & INK_FILEPATH_SECUREROOTTEST) {
return EACCES; // APR_EABOVEROOT;
- if (flags & INK_FILEPATH_NOTABSOLUTE)
+ }
+ if (flags & INK_FILEPATH_NOTABSOLUTE) {
return EISDIR; // APR_EABSOLUTE;
+ }
// If INK_FILEPATH_NOTABOVEROOT wasn't specified,
// we won't test the root again, it's ignored.
// Waste no CPU retrieving the working path.
//
- if (!rootpath && !(flags & INK_FILEPATH_NOTABOVEROOT))
+ if (!rootpath && !(flags & INK_FILEPATH_NOTABOVEROOT)) {
rootpath = "";
+ }
} else {
// If INK_FILEPATH_NOTABSOLUTE is specified, the caller
// requires a relative result. If the rootpath is
@@ -167,10 +178,11 @@ ink_filepath_merge(char *path, int pathsz, const char *rootpath, const char *add
// if rootpath was supplied as absolute then fail.
//
if (flags & INK_FILEPATH_NOTABSOLUTE) {
- if (!rootpath)
+ if (!rootpath) {
rootpath = "";
- else if (rootpath[0] == '/')
+ } else if (rootpath[0] == '/') {
return EISDIR; // APR_EABSOLUTE;
+ }
}
}
if (!rootpath) {
@@ -196,15 +208,17 @@ ink_filepath_merge(char *path, int pathsz, const char *rootpath, const char *add
// and leave addpath at the first non-'/' character.
//
keptlen = 0;
- while (addpath[0] == '/')
+ while (addpath[0] == '/') {
++addpath;
+ }
path[0] = '/';
pathlen = 1;
} else {
// If both paths are relative, fail early
//
- if (rootpath[0] != '/' && (flags & INK_FILEPATH_NOTRELATIVE))
+ if (rootpath[0] != '/' && (flags & INK_FILEPATH_NOTRELATIVE)) {
return EBADF; // APR_ERELATIVE;
+ }
// Base the result path on the rootpath
//
@@ -330,8 +344,9 @@ ink_filepath_make(char *path, int pathsz, const char *rootpath, const char *addp
/* Treat null as an empty path.
*/
- if (!addpath)
+ if (!addpath) {
addpath = "";
+ }
if (addpath[0] == '/') {
// If addpath is rooted, then rootpath is unused.
@@ -517,32 +532,41 @@ ink_fileperm_parse(const char *perms)
if (perms && strlen(perms) == 9) {
int re = 0;
char *c = (char *)perms;
- if (*c == 'r')
+ if (*c == 'r') {
re |= S_IRUSR;
+ }
c++;
- if (*c == 'w')
+ if (*c == 'w') {
re |= S_IWUSR;
+ }
c++;
- if (*c == 'x')
+ if (*c == 'x') {
re |= S_IXUSR;
+ }
c++;
- if (*c == 'r')
+ if (*c == 'r') {
re |= S_IRGRP;
+ }
c++;
- if (*c == 'w')
+ if (*c == 'w') {
re |= S_IWGRP;
+ }
c++;
- if (*c == 'x')
+ if (*c == 'x') {
re |= S_IXGRP;
+ }
c++;
- if (*c == 'r')
+ if (*c == 'r') {
re |= S_IROTH;
+ }
c++;
- if (*c == 'w')
+ if (*c == 'w') {
re |= S_IWOTH;
+ }
c++;
- if (*c == 'x')
+ if (*c == 'x') {
re |= S_IXOTH;
+ }
return re;
}
return -1;
diff --git a/lib/ts/ink_hash_table.cc b/lib/ts/ink_hash_table.cc
index 03a226c..808c367 100644
--- a/lib/ts/ink_hash_table.cc
+++ b/lib/ts/ink_hash_table.cc
@@ -60,12 +60,13 @@ ink_hash_table_create(InkHashTableKeyType key_type)
tcl_ht_ptr = (Tcl_HashTable *)ats_malloc(sizeof(Tcl_HashTable));
- if (key_type == InkHashTableKeyType_String)
+ if (key_type == InkHashTableKeyType_String) {
tcl_key_type = TCL_STRING_KEYS;
- else if (key_type == InkHashTableKeyType_Word)
+ } else if (key_type == InkHashTableKeyType_Word) {
tcl_key_type = TCL_ONE_WORD_KEYS;
- else
+ } else {
ink_fatal("ink_hash_table_create: bad key_type %d", key_type);
+ }
Tcl_InitHashTable(tcl_ht_ptr, tcl_key_type);
@@ -159,8 +160,9 @@ ink_hash_table_lookup(InkHashTable *ht_ptr, const char *key, InkHashTableValue *
InkHashTableValue value;
he_ptr = ink_hash_table_lookup_entry(ht_ptr, key);
- if (he_ptr == nullptr)
+ if (he_ptr == nullptr) {
return (0);
+ }
value = ink_hash_table_entry_value(ht_ptr, he_ptr);
*value_ptr = value;
@@ -188,8 +190,9 @@ ink_hash_table_delete(InkHashTable *ht_ptr, const char *key)
tcl_ht_ptr = (Tcl_HashTable *)ht_ptr;
tcl_he_ptr = Tcl_FindHashEntry(tcl_ht_ptr, tcl_key);
- if (!tcl_he_ptr)
+ if (!tcl_he_ptr) {
return (0);
+ }
Tcl_DeleteHashEntry(tcl_he_ptr);
return (1);
@@ -310,8 +313,9 @@ ink_hash_table_map(InkHashTable *ht_ptr, InkHashTableEntryFunction map)
for (e = ink_hash_table_iterator_first(ht_ptr, &state); e != nullptr; e = ink_hash_table_iterator_next(ht_ptr, &state)) {
retcode = (*map)(ht_ptr, e);
- if (retcode != 0)
+ if (retcode != 0) {
break;
+ }
}
} /* End ink_hash_table_map */
@@ -412,8 +416,9 @@ ink_hash_table_replace_string(InkHashTable *ht_ptr, char *string_key, char *stri
he_ptr = ink_hash_table_get_entry(ht_ptr, (InkHashTableKey)string_key, &new_value);
if (new_value == 0) {
old_str = (char *)ink_hash_table_entry_value(ht_ptr, he_ptr);
- if (old_str)
+ if (old_str) {
ats_free(old_str);
+ }
}
ink_hash_table_set_entry(ht_ptr, he_ptr, (InkHashTableValue)(ats_strdup(string_value)));
diff --git a/lib/ts/ink_hrtime.cc b/lib/ts/ink_hrtime.cc
index 4c62d76..78dc4d3 100644
--- a/lib/ts/ink_hrtime.cc
+++ b/lib/ts/ink_hrtime.cc
@@ -85,8 +85,9 @@ int64_to_str(char *buf, unsigned int buf_size, int64_t val, unsigned int *total_
} else {
out_buf++;
}
- if (req_width > buf_size)
- req_width = buf_size;
+ if (req_width > buf_size) {
+ req_width = buf_size;
+ }
unsigned int num_padding = 0;
if (req_width > num_chars) {
num_padding = req_width - num_chars;
@@ -99,8 +100,9 @@ int64_to_str(char *buf, unsigned int buf_size, int64_t val, unsigned int *total_
*--out_buf = pad_char;
break;
default:
- for (unsigned int i = 0; i < num_padding; ++i, *--out_buf = pad_char)
+ for (unsigned int i = 0; i < num_padding; ++i, *--out_buf = pad_char) {
;
+ }
}
num_chars += num_padding;
}
@@ -130,8 +132,9 @@ int64_to_str(char *buf, unsigned int buf_size, int64_t val, unsigned int *total_
}
}
- if (total_chars)
+ if (total_chars) {
*total_chars = num_chars;
+ }
return out_buf;
}
diff --git a/lib/ts/ink_inet.cc b/lib/ts/ink_inet.cc
index c6907f8..2e940c6 100644
--- a/lib/ts/ink_inet.cc
+++ b/lib/ts/ink_inet.cc
@@ -64,10 +64,11 @@ ink_inet_addr(const char *s)
// handle hex, octal
if (*pc == '0') {
- if (*++pc == 'x' || *pc == 'X')
+ if (*++pc == 'x' || *pc == 'X') {
base = 16, pc++;
- else
+ } else {
base = 8;
+ }
}
// handle hex, octal, decimal
@@ -84,29 +85,34 @@ ink_inet_addr(const char *s)
}
n++;
- if (*pc == '.')
+ if (*pc == '.') {
pc++;
- else
+ } else {
break;
+ }
}
- if (*pc && !ParseRules::is_wslfcr(*pc))
+ if (*pc && !ParseRules::is_wslfcr(*pc)) {
return htonl((uint32_t)-1);
+ }
switch (n) {
case 1:
return htonl(u[0]);
case 2:
- if (u[0] > 0xff || u[1] > 0xffffff)
+ if (u[0] > 0xff || u[1] > 0xffffff) {
return htonl((uint32_t)-1);
+ }
return htonl((u[0] << 24) | u[1]);
case 3:
- if (u[0] > 0xff || u[1] > 0xff || u[2] > 0xffff)
+ if (u[0] > 0xff || u[1] > 0xff || u[2] > 0xffff) {
return htonl((uint32_t)-1);
+ }
return htonl((u[0] << 24) | (u[1] << 16) | u[2]);
case 4:
- if (u[0] > 0xff || u[1] > 0xff || u[2] > 0xff || u[3] > 0xff)
+ if (u[0] > 0xff || u[1] > 0xff || u[2] > 0xff || u[3] > 0xff) {
return htonl((uint32_t)-1);
+ }
return htonl((u[0] << 24) | (u[1] << 16) | (u[2] << 8) | u[3]);
}
return htonl((uint32_t)-1);
@@ -152,20 +158,24 @@ ats_ip_parse(ts::ConstBuffer src, ts::ConstBuffer *addr, ts::ConstBuffer *port,
{
// In case the incoming arguments are null.
ts::ConstBuffer localAddr, localPort;
- if (!addr)
+ if (!addr) {
addr = &localAddr;
- if (!port)
+ }
+ if (!port) {
port = &localPort;
+ }
addr->reset();
port->reset();
- if (rest)
+ if (rest) {
rest->reset();
+ }
// Let's see if we can find out what's in the address string.
if (src) {
bool colon_p = false;
- while (src && ParseRules::is_ws(*src))
+ while (src && ParseRules::is_ws(*src)) {
++src;
+ }
// Check for brackets.
if ('[' == *src) {
/* Ugly. In a number of places we must use bracket notation
@@ -200,8 +210,9 @@ ats_ip_parse(ts::ConstBuffer src, ts::ConstBuffer *addr, ts::ConstBuffer *port,
}
if (colon_p) {
ts::ConstBuffer tmp(src);
- while (src && ParseRules::is_digit(*src))
+ while (src && ParseRules::is_digit(*src)) {
++src;
+ }
if (tmp.data() == src.data()) { // no digits at all
src.set(tmp.data() - 1, tmp.size() + 1); // back up to include colon
@@ -209,8 +220,9 @@ ats_ip_parse(ts::ConstBuffer src, ts::ConstBuffer *addr, ts::ConstBuffer *port,
*port = tmp.clip(src.data());
}
}
- if (rest)
+ if (rest) {
*rest = src;
+ }
}
return *addr ? 0 : -1; // true if we found an address.
}
@@ -244,8 +256,9 @@ ats_ip_pton(const ts::ConstBuffer &src, sockaddr *ip)
}
}
// If we had a successful conversion, set the port.
- if (ats_is_ip(ip))
+ if (ats_is_ip(ip)) {
ats_ip_port_cast(ip) = port ? htons(atoi(port.data())) : 0;
+ }
}
return zret;
@@ -311,12 +324,13 @@ ats_ip_to_hex(sockaddr const *src, char *dst, size_t len)
sockaddr *
ats_ip_set(sockaddr *dst, IpAddr const &addr, uint16_t port)
{
- if (AF_INET == addr._family)
+ if (AF_INET == addr._family) {
ats_ip4_set(dst, addr._addr._ip4, port);
- else if (AF_INET6 == addr._family)
+ } else if (AF_INET6 == addr._family) {
ats_ip6_set(dst, addr._addr._ip6, port);
- else
+ } else {
ats_ip_invalidate(dst);
+ }
return dst;
}
@@ -397,12 +411,13 @@ IpAddr::cmp(self const &that) const
if (AF_INET == rtype) {
in_addr_t la = ntohl(_addr._ip4);
in_addr_t ra = ntohl(that._addr._ip4);
- if (la < ra)
+ if (la < ra) {
zret = -1;
- else if (la > ra)
+ } else if (la > ra) {
zret = 1;
- else
+ } else {
zret = 0;
+ }
} else if (AF_INET6 == rtype) { // IPv4 < IPv6
zret = -1;
} else { // IP > not IP
@@ -434,10 +449,12 @@ ats_ip_getbestaddrinfo(const char *host, IpEndpoint *ip4, IpEndpoint *ip6)
ts::ConstBuffer addr_text, port_text;
ts::ConstBuffer src(host, strlen(host) + 1);
- if (ip4)
+ if (ip4) {
ats_ip_invalidate(ip4);
- if (ip6)
+ }
+ if (ip6) {
ats_ip_invalidate(ip6);
+ }
if (0 == ats_ip_parse(src, &addr_text, &port_text)) {
// Copy if not terminated.
@@ -468,21 +485,23 @@ ats_ip_getbestaddrinfo(const char *host, IpEndpoint *ip4, IpEndpoint *ip6)
for (addrinfo *ai_spot = ai_result; ai_spot; ai_spot = ai_spot->ai_next) {
sockaddr const *ai_ip = ai_spot->ai_addr;
- if (!ats_is_ip(ai_ip))
+ if (!ats_is_ip(ai_ip)) {
spot_type = NA;
- else if (ats_is_ip_loopback(ai_ip))
+ } else if (ats_is_ip_loopback(ai_ip)) {
spot_type = LO;
- else if (ats_is_ip_linklocal(ai_ip))
+ } else if (ats_is_ip_linklocal(ai_ip)) {
spot_type = LL;
- else if (ats_is_ip_private(ai_ip))
+ } else if (ats_is_ip_private(ai_ip)) {
spot_type = PR;
- else if (ats_is_ip_multicast(ai_ip))
+ } else if (ats_is_ip_multicast(ai_ip)) {
spot_type = MC;
- else
+ } else {
spot_type = GL;
+ }
- if (spot_type == NA)
+ if (spot_type == NA) {
continue; // Next!
+ }
if (ats_is_ip4(ai_ip)) {
if (spot_type > ip4_type) {
@@ -496,10 +515,12 @@ ats_ip_getbestaddrinfo(const char *host, IpEndpoint *ip4, IpEndpoint *ip6)
}
}
}
- if (ip4_type > NA)
+ if (ip4_type > NA) {
ats_ip_copy(ip4, ip4_src);
- if (ip6_type > NA)
+ }
+ if (ip6_type > NA) {
ats_ip_copy(ip6, ip6_src);
+ }
freeaddrinfo(ai_result); // free *after* the copy.
}
}
@@ -507,15 +528,19 @@ ats_ip_getbestaddrinfo(const char *host, IpEndpoint *ip4, IpEndpoint *ip6)
// We don't really care if the port is null terminated - the parser
// would get all the digits so the next character is a non-digit (null or
// not) and atoi will do the right thing in either case.
- if (port_text.size())
+ if (port_text.size()) {
port = htons(atoi(port_text.data()));
- if (ats_is_ip(ip4))
+ }
+ if (ats_is_ip(ip4)) {
ats_ip_port_cast(ip4) = port;
- if (ats_is_ip(ip6))
+ }
+ if (ats_is_ip(ip6)) {
ats_ip_port_cast(ip6) = port;
+ }
- if (!ats_is_ip(ip4) && !ats_is_ip(ip6))
+ if (!ats_is_ip(ip4) && !ats_is_ip(ip6)) {
zret = -1;
+ }
return zret;
}
@@ -525,15 +550,17 @@ ats_ip_check_characters(ts::ConstBuffer text)
{
bool found_colon = false;
bool found_hex = false;
- for (const char *p = text.data(), *limit = p + text.size(); p < limit; ++p)
- if (':' == *p)
+ for (const char *p = text.data(), *limit = p + text.size(); p < limit; ++p) {
+ if (':' == *p) {
found_colon = true;
- else if ('.' == *p || isdigit(*p)) /* empty */
+ } else if ('.' == *p || isdigit(*p)) { /* empty */
;
- else if (isxdigit(*p))
+ } else if (isxdigit(*p)) {
found_hex = true;
- else
+ } else {
return AF_UNSPEC;
+ }
+ }
return found_hex && !found_colon ? AF_UNSPEC : found_colon ? AF_INET6 : AF_INET;
}
diff --git a/lib/ts/ink_memory.cc b/lib/ts/ink_memory.cc
index dbce761..6811c4e 100644
--- a/lib/ts/ink_memory.cc
+++ b/lib/ts/ink_memory.cc
@@ -91,8 +91,9 @@ ats_memalign(size_t alignment, size_t size)
void *ptr;
#if HAVE_POSIX_MEMALIGN || TS_HAS_JEMALLOC
- if (alignment <= 8)
+ if (alignment <= 8) {
return ats_malloc(size);
+ }
#if defined(openbsd)
if (alignment > PAGE_SIZE)
@@ -122,23 +123,26 @@ ats_memalign(size_t alignment, size_t size)
void
ats_free(void *ptr)
{
- if (likely(ptr != nullptr))
+ if (likely(ptr != nullptr)) {
free(ptr);
+ }
} /* End ats_free */
void *
ats_free_null(void *ptr)
{
- if (likely(ptr != nullptr))
+ if (likely(ptr != nullptr)) {
free(ptr);
+ }
return nullptr;
} /* End ats_free_null */
void
ats_memalign_free(void *ptr)
{
- if (likely(ptr))
+ if (likely(ptr)) {
free(ptr);
+ }
}
// This effectively makes mallopt() a no-op (currently) when tcmalloc
@@ -172,8 +176,9 @@ ats_msync(caddr_t addr, size_t len, caddr_t end, int flags)
caddr_t a = (caddr_t)(((uintptr_t)addr) & ~(pagesize - 1));
// align length to page boundry covering region
size_t l = (len + (addr - a) + (pagesize - 1)) & ~(pagesize - 1);
- if ((a + l) > end)
+ if ((a + l) > end) {
l = end - a; // strict limit
+ }
#if defined(linux)
/* Fix INKqa06500
Under Linux, msync(..., MS_SYNC) calls are painfully slow, even on
@@ -262,8 +267,9 @@ _xstrdup(const char *str, int length, const char * /* path ATS_UNUSED */)
char *newstr;
if (likely(str)) {
- if (length < 0)
+ if (length < 0) {
length = strlen(str);
+ }
newstr = (char *)ats_malloc(length + 1);
// If this is a zero length string just null terminate and return.
diff --git a/lib/ts/ink_queue.cc b/lib/ts/ink_queue.cc
index 14a1220..844a67c 100644
--- a/lib/ts/ink_queue.cc
+++ b/lib/ts/ink_queue.cc
@@ -135,8 +135,9 @@ ink_freelist_init(InkFreeList **fl, const char *name, uint32_t type_size, uint32
// It is never useful to have alignment requirement looser than a page size
// so clip it. This makes the item alignment checks in the actual allocator simpler.
f->alignment = alignment;
- if (f->alignment > ats_pagesize())
+ if (f->alignment > ats_pagesize()) {
f->alignment = ats_pagesize();
+ }
Debug(DEBUG_TAG "_init", "<%s> Alignment request/actual (%" PRIu32 "/%" PRIu32 ")", name, alignment, f->alignment);
// Make sure we align *all* the objects in the allocation, not just the first one
f->type_size = INK_ALIGN(type_size, f->alignment);
@@ -318,10 +319,11 @@ freelist_free(InkFreeList *f, void *item)
static void
malloc_free(InkFreeList *f, void *item)
{
- if (f->alignment)
+ if (f->alignment) {
ats_memalign_free(item);
- else
+ } else {
ats_free(item);
+ }
}
void
@@ -413,8 +415,9 @@ void
ink_freelists_dump_baselinerel(FILE *f)
{
ink_freelist_list *fll;
- if (f == nullptr)
+ if (f == nullptr) {
f = stderr;
+ }
fprintf(f, " allocated | in-use | count | type size | free list name\n");
fprintf(f, " relative to base | relative to base | | | \n");
@@ -438,8 +441,9 @@ void
ink_freelists_dump(FILE *f)
{
ink_freelist_list *fll;
- if (f == nullptr)
+ if (f == nullptr) {
f = stderr;
+ }
fprintf(f, " Allocated | In-Use | Type Size | Free List Name\n");
fprintf(f, "--------------------|--------------------|------------|----------------------------------\n");
@@ -475,8 +479,9 @@ ink_atomiclist_pop(InkAtomicList *l)
int result = 0;
do {
INK_QUEUE_LD(item, l->head);
- if (TO_PTR(FREELIST_POINTER(item)) == nullptr)
+ if (TO_PTR(FREELIST_POINTER(item)) == nullptr) {
return nullptr;
+ }
SET_FREELIST_POINTER_VERSION(next, *ADDRESS_OF_NEXT(TO_PTR(FREELIST_POINTER(item)), l->offset), FREELIST_VERSION(item) + 1);
result = ink_atomic_cas(&l->head.data, item.data, next.data);
} while (result == 0);
@@ -495,8 +500,9 @@ ink_atomiclist_popall(InkAtomicList *l)
int result = 0;
do {
INK_QUEUE_LD(item, l->head);
- if (TO_PTR(FREELIST_POINTER(item)) == nullptr)
+ if (TO_PTR(FREELIST_POINTER(item)) == nullptr) {
return nullptr;
+ }
SET_FREELIST_POINTER_VERSION(next, FROM_PTR(nullptr), FREELIST_VERSION(item) + 1);
result = ink_atomic_cas(&l->head.data, item.data, next.data);
} while (result == 0);
diff --git a/lib/ts/ink_rand.cc b/lib/ts/ink_rand.cc
index 7a0134f..379b0b4 100644
--- a/lib/ts/ink_rand.cc
+++ b/lib/ts/ink_rand.cc
@@ -74,8 +74,9 @@ void
InkRand::seed(uint64_t seed)
{
mt[0] = seed;
- for (mti = 1; mti < NN; mti++)
+ for (mti = 1; mti < NN; mti++) {
mt[mti] = (6364136223846793005ULL * (mt[mti - 1] ^ (mt[mti - 1] >> 62)) + mti);
+ }
}
uint64_t
diff --git a/lib/ts/ink_res_init.cc b/lib/ts/ink_res_init.cc
index d676252..8bcf4d3 100644
--- a/lib/ts/ink_res_init.cc
+++ b/lib/ts/ink_res_init.cc
@@ -136,8 +136,9 @@ ink_res_setservers(ink_res_state statp, IpEndpoint const *set, int cnt)
IpEndpoint *dst = &statp->nsaddr_list[nserv];
if (dst == set) {
- if (ats_is_ip(&set->sa))
+ if (ats_is_ip(&set->sa)) {
++nserv;
+ }
} else if (ats_ip_copy(&dst->sa, &set->sa)) {
++nserv;
}
@@ -172,25 +173,28 @@ ink_res_setoptions(ink_res_state statp, const char *options, const char *source
#endif
while (*cp) {
/* skip leading and inner runs of spaces */
- while (*cp == ' ' || *cp == '\t')
+ while (*cp == ' ' || *cp == '\t') {
cp++;
+ }
/* search for and process individual options */
if (!strncmp(cp, "ndots:", sizeof("ndots:") - 1)) {
i = atoi(cp + sizeof("ndots:") - 1);
- if (i <= INK_RES_MAXNDOTS)
+ if (i <= INK_RES_MAXNDOTS) {
statp->ndots = i;
- else
+ } else {
statp->ndots = INK_RES_MAXNDOTS;
+ }
#ifdef DEBUG
if (statp->options & INK_RES_DEBUG)
printf(";;\tndots=%d\n", statp->ndots);
#endif
} else if (!strncmp(cp, "timeout:", sizeof("timeout:") - 1)) {
i = atoi(cp + sizeof("timeout:") - 1);
- if (i <= INK_RES_MAXRETRANS)
+ if (i <= INK_RES_MAXRETRANS) {
statp->retrans = i;
- else
+ } else {
statp->retrans = INK_RES_MAXRETRANS;
+ }
#ifdef DEBUG
if (statp->options & INK_RES_DEBUG)
printf(";;\ttimeout=%d\n", statp->retrans);
@@ -213,10 +217,11 @@ ink_res_setoptions(ink_res_state statp, const char *options, const char *source
#endif /* SOLARIS2 */
} else if (!strncmp(cp, "attempts:", sizeof("attempts:") - 1)) {
i = atoi(cp + sizeof("attempts:") - 1);
- if (i <= INK_RES_MAXRETRY)
+ if (i <= INK_RES_MAXRETRY) {
statp->retry = i;
- else
+ } else {
statp->retry = INK_RES_MAXRETRY;
+ }
#ifdef DEBUG
if (statp->options & INK_RES_DEBUG)
printf(";;\tattempts=%d\n", statp->retry);
@@ -250,8 +255,9 @@ ink_res_setoptions(ink_res_state statp, const char *options, const char *source
/* XXX - print a warning here? */
}
/* skip to next run of spaces */
- while (*cp && *cp != ' ' && *cp != '\t')
+ while (*cp && *cp != ' ' && *cp != '\t') {
cp++;
+ }
}
}
@@ -356,9 +362,9 @@ ink_res_init(ink_res_state statp, ///< State object to update.
pp = statp->dnsrch;
*pp++ = cp;
for (n = 0; *cp && pp < statp->dnsrch + INK_MAXDNSRCH; cp++) {
- if (*cp == '\n') /*%< silly backwards compat */
+ if (*cp == '\n') { /*%< silly backwards compat */
break;
- else if (*cp == ' ' || *cp == '\t') {
+ } else if (*cp == ' ' || *cp == '\t') {
*cp = 0;
n = 1;
} else if (n) {
@@ -368,8 +374,9 @@ ink_res_init(ink_res_state statp, ///< State object to update.
}
}
/* null terminate last domain if there are excess */
- while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n')
+ while (*cp != '\0' && *cp != ' ' && *cp != '\t' && *cp != '\n') {
cp++;
+ }
*cp = '\0';
*pp++ = nullptr;
}
@@ -385,17 +392,19 @@ ink_res_init(ink_res_state statp, ///< State object to update.
if (pDefDomain && '\0' != *pDefDomain && '\n' != *pDefDomain) {
ink_strlcpy(statp->defdname, pDefDomain, sizeof(statp->defdname));
- if ((cp = strpbrk(statp->defdname, " \t\n")) != nullptr)
+ if ((cp = strpbrk(statp->defdname, " \t\n")) != nullptr) {
*cp = '\0';
+ }
}
if (pSearchList && '\0' != *pSearchList && '\n' != *pSearchList) {
ink_strlcpy(statp->defdname, pSearchList, sizeof(statp->defdname));
- if ((cp = strchr(statp->defdname, '\n')) != nullptr)
+ if ((cp = strchr(statp->defdname, '\n')) != nullptr) {
*cp = '\0';
- /*
- * Set search list to be blank-separated strings
- * on rest of line.
- */
+ /*
+ * Set search list to be blank-separated strings
+ * on rest of line.
+ */
+ }
cp = statp->defdname;
pp = statp->dnsrch;
*pp++ = cp;
@@ -409,8 +418,9 @@ ink_res_init(ink_res_state statp, ///< State object to update.
}
}
/* null terminate last domain if there are excess */
- while (*cp != '\0' && *cp != ' ' && *cp != '\t')
+ while (*cp != '\0' && *cp != ' ' && *cp != '\t') {
cp++;
+ }
*cp = '\0';
*pp++ = nullptr;
havesearch = 1;
@@ -420,8 +430,9 @@ ink_res_init(ink_res_state statp, ///< State object to update.
we must be provided with atleast a named!
------------------------------------------- */
if (pHostList) {
- if (pHostListSize > INK_MAXNS)
+ if (pHostListSize > INK_MAXNS) {
pHostListSize = INK_MAXNS;
+ }
for (; nserv < pHostListSize && ats_is_ip(&pHostList[nserv].sa); ++nserv) {
ats_ip_copy(&statp->nsaddr_list[nserv].sa, &pHostList[nserv].sa);
}
@@ -434,39 +445,48 @@ ink_res_init(ink_res_state statp, ///< State object to update.
/* read the config file */
while (fgets(buf, sizeof(buf), fp) != nullptr) {
/* skip comments */
- if (*buf == ';' || *buf == '#')
+ if (*buf == ';' || *buf == '#') {
continue;
+ }
/* read default domain name */
if (MATCH(buf, "domain")) {
- if (haveenv) /*%< skip if have from environ */
+ if (haveenv) { /*%< skip if have from environ */
continue;
+ }
cp = buf + sizeof("domain") - 1;
- while (*cp == ' ' || *cp == '\t')
+ while (*cp == ' ' || *cp == '\t') {
cp++;
- if ((*cp == '\0') || (*cp == '\n'))
+ }
+ if ((*cp == '\0') || (*cp == '\n')) {
continue;
+ }
ink_strlcpy(statp->defdname, cp, sizeof(statp->defdname));
- if ((cp = strpbrk(statp->defdname, " \t\n")) != nullptr)
- *cp = '\0';
+ if ((cp = strpbrk(statp->defdname, " \t\n")) != nullptr) {
+ *cp = '\0';
+ }
havesearch = 0;
continue;
}
/* set search list */
if (MATCH(buf, "search")) {
- if (haveenv) /*%< skip if have from environ */
+ if (haveenv) { /*%< skip if have from environ */
continue;
+ }
cp = buf + sizeof("search") - 1;
- while (*cp == ' ' || *cp == '\t')
+ while (*cp == ' ' || *cp == '\t') {
cp++;
- if ((*cp == '\0') || (*cp == '\n'))
+ }
+ if ((*cp == '\0') || (*cp == '\n')) {
continue;
+ }
ink_strlcpy(statp->defdname, cp, sizeof(statp->defdname));
- if ((cp = strchr(statp->defdname, '\n')) != nullptr)
+ if ((cp = strchr(statp->defdname, '\n')) != nullptr) {
*cp = '\0';
- /*
- * Set search list to be blank-separated strings
- * on rest of line.
- */
+ /*
+ * Set search list to be blank-separated strings
+ * on rest of line.
+ */
+ }
cp = statp->defdname;
pp = statp->dnsrch;
*pp++ = cp;
@@ -480,8 +500,9 @@ ink_res_init(ink_res_state statp, ///< State object to update.
}
}
/* null terminate last domain if there are excess */
- while (*cp != '\0' && *cp != ' ' && *cp != '\t')
+ while (*cp != '\0' && *cp != ' ' && *cp != '\t') {
cp++;
+ }
*cp = '\0';
*pp++ = nullptr;
havesearch = 1;
@@ -490,8 +511,9 @@ ink_res_init(ink_res_state statp, ///< State object to update.
/* read nameservers to query */
if (MATCH(buf, "nameserver") && nserv < maxns) {
cp = buf + sizeof("nameserver") - 1;
- while (*cp == ' ' || *cp == '\t')
+ while (*cp == ' ' || *cp == '\t') {
cp++;
+ }
if ((*cp != '\0') && (*cp != '\n')) {
ts::ConstBuffer host(cp, strcspn(cp, ";# \t\n"));
if (0 == ats_ip_pton(host, &statp->nsaddr_list[nserv].sa)) {
@@ -512,11 +534,13 @@ ink_res_init(ink_res_state statp, ///< State object to update.
(void)fclose(fp);
}
- if (nserv > 0)
+ if (nserv > 0) {
statp->nscount = nserv;
+ }
- if (statp->defdname[0] == 0 && gethostname(buf, sizeof(statp->defdname) - 1) == 0 && (cp = strchr(buf, '.')) != nullptr)
+ if (statp->defdname[0] == 0 && gethostname(buf, sizeof(statp->defdname) - 1) == 0 && (cp = strchr(buf, '.')) != nullptr) {
ink_strlcpy(statp->defdname, cp + 1, sizeof(statp->defdname));
+ }
/* find components of local domain that might be searched */
if (havesearch == 0) {
@@ -526,13 +550,15 @@ ink_res_init(ink_res_state statp, ///< State object to update.
if (dnsSearch == 1) {
dots = 0;
- for (cp = statp->defdname; *cp; cp++)
+ for (cp = statp->defdname; *cp; cp++) {
dots += (*cp == '.');
+ }
cp = statp->defdname;
while (pp < statp->dnsrch + INK_MAXDFLSRCH) {
- if (dots < INK_LOCALDOMAINPARTS)
+ if (dots < INK_LOCALDOMAINPARTS) {
break;
+ }
cp = strchr(cp, '.') + 1; /*%< we know there is one */
*pp++ = cp;
dots--;
@@ -552,8 +578,9 @@ ink_res_init(ink_res_state statp, ///< State object to update.
/* export all ns servers to DNSprocessor. */
ink_res_setservers(statp, &statp->nsaddr_list[0], statp->nscount);
- if ((cp = getenv("RES_OPTIONS")) != nullptr)
+ if ((cp = getenv("RES_OPTIONS")) != nullptr) {
ink_res_setoptions(statp, cp, "env");
+ }
statp->options |= INK_RES_INIT;
return (statp->res_h_errno);
}
@@ -570,8 +597,9 @@ parse_host_res_preference(const char *value, HostResPreferenceOrder order)
n = tokens.Initialize(value);
- for (i = 0; i < N_HOST_RES_PREFERENCE; ++i)
+ for (i = 0; i < N_HOST_RES_PREFERENCE; ++i) {
found[i] = false;
+ }
for (i = 0; i < n && np < N_HOST_RES_PREFERENCE_ORDER; ++i) {
const char *elt = tokens[i];
@@ -598,12 +626,15 @@ parse_host_res_preference(const char *value, HostResPreferenceOrder order)
if (!found[HOST_RES_PREFER_NONE]) {
// If 'only' wasn't explicit, fill in the rest by default.
- if (!found[HOST_RES_PREFER_IPV4])
+ if (!found[HOST_RES_PREFER_IPV4]) {
order[np++] = HOST_RES_PREFER_IPV4;
- if (!found[HOST_RES_PREFER_IPV6])
+ }
+ if (!found[HOST_RES_PREFER_IPV6]) {
order[np++] = HOST_RES_PREFER_IPV6;
- if (np < N_HOST_RES_PREFERENCE_ORDER) // was N_HOST_RES_PREFERENCE)
+ }
+ if (np < N_HOST_RES_PREFERENCE_ORDER) { // was N_HOST_RES_PREFERENCE)
order[np] = HOST_RES_PREFER_NONE;
+ }
}
}
@@ -619,8 +650,9 @@ ts_host_res_order_to_string(HostResPreferenceOrder const &order, char *out, int
* resolution key words.
*/
zret += snprintf(out + zret, size - zret, "%s%s", !first ? ";" : "", HOST_RES_PREFERENCE_STRING[i]);
- if (HOST_RES_PREFER_NONE == i)
+ if (HOST_RES_PREFER_NONE == i) {
break;
+ }
first = false;
}
return zret;
diff --git a/lib/ts/ink_res_mkquery.cc b/lib/ts/ink_res_mkquery.cc
index 63e012a..2741991 100644
--- a/lib/ts/ink_res_mkquery.cc
+++ b/lib/ts/ink_res_mkquery.cc
@@ -105,8 +105,9 @@ int ink_res_mkquery(ink_res_state statp, int op, /*!< opcode of qu
/*
* Initialize header fields.
*/
- if ((buf == nullptr) || (buflen < HFIXEDSZ))
+ if ((buf == nullptr) || (buflen < HFIXEDSZ)) {
return (-1);
+ }
memset(buf, 0, HFIXEDSZ);
hp = (HEADER *)buf;
hp->id = htons(++statp->id);
@@ -125,24 +126,29 @@ int ink_res_mkquery(ink_res_state statp, int op, /*!< opcode of qu
switch (op) {
case QUERY: /*FALLTHROUGH*/
case NS_NOTIFY_OP:
- if (ep - cp < QFIXEDSZ)
+ if (ep - cp < QFIXEDSZ) {
return (-1);
- if ((n = dn_comp(dname, cp, ep - cp - QFIXEDSZ, dnptrs, lastdnptr)) < 0)
+ }
+ if ((n = dn_comp(dname, cp, ep - cp - QFIXEDSZ, dnptrs, lastdnptr)) < 0) {
return (-1);
+ }
cp += n;
NS_PUT16(type, cp);
NS_PUT16(_class, cp);
hp->qdcount = htons(1);
- if (op == QUERY || data == nullptr)
+ if (op == QUERY || data == nullptr) {
break;
+ }
/*
* Make an additional record for completion domain.
*/
- if ((ep - cp) < RRFIXEDSZ)
+ if ((ep - cp) < RRFIXEDSZ) {
return (-1);
+ }
n = dn_comp((const char *)data, cp, ep - cp - RRFIXEDSZ, dnptrs, lastdnptr);
- if (n < 0)
+ if (n < 0) {
return (-1);
+ }
cp += n;
NS_PUT16(T_NULL, cp);
NS_PUT16(_class, cp);
@@ -155,8 +161,9 @@ int ink_res_mkquery(ink_res_state statp, int op, /*!< opcode of qu
/*
* Initialize answer section
*/
- if (ep - cp < 1 + RRFIXEDSZ + datalen)
+ if (ep - cp < 1 + RRFIXEDSZ + datalen) {
return (-1);
+ }
*cp++ = '\0'; /*%< no domain name */
NS_PUT16(type, cp);
NS_PUT16(_class, cp);
@@ -205,8 +212,9 @@ labellen(const u_char *lp)
if ((l & NS_CMPRSFLGS) == INK_NS_TYPE_ELT) {
if (l == INK_DNS_LABELTYPE_BITSTRING) {
- if ((bitlen = *(lp + 1)) == 0)
+ if ((bitlen = *(lp + 1)) == 0) {
bitlen = 256;
+ }
return ((bitlen + 7) / 8 + 1);
}
return (-1); /*%< unknwon ELT */
@@ -221,40 +229,47 @@ decode_bitstring(const unsigned char **cpp, char *dn, const char *eom)
char *beg = dn, tc;
int b, blen, plen, i;
- if ((blen = (*cp & 0xff)) == 0)
+ if ((blen = (*cp & 0xff)) == 0) {
blen = 256;
- plen = (blen + 3) / 4;
+ }
+ plen = (blen + 3) / 4;
plen += sizeof("\\[x/]") + (blen > 99 ? 3 : (blen > 9) ? 2 : 1);
- if (dn + plen >= eom)
+ if (dn + plen >= eom) {
return (-1);
+ }
cp++;
i = SPRINTF((dn, "\\[x"));
- if (i < 0)
+ if (i < 0) {
return (-1);
+ }
dn += i;
for (b = blen; b > 7; b -= 8, cp++) {
i = SPRINTF((dn, "%02x", *cp & 0xff));
- if (i < 0)
+ if (i < 0) {
return (-1);
+ }
dn += i;
}
if (b > 4) {
tc = *cp++;
i = SPRINTF((dn, "%02x", tc & (0xff << (8 - b))));
- if (i < 0)
+ if (i < 0) {
return (-1);
+ }
dn += i;
} else if (b > 0) {
tc = *cp++;
i = SPRINTF((dn, "%1x", ((tc >> 4) & 0x0f) & (0x0f << (4 - b))));
- if (i < 0)
+ if (i < 0) {
return (-1);
+ }
dn += i;
}
i = SPRINTF((dn, "/%d]", blen));
- if (i < 0)
+ if (i < 0) {
return (-1);
+ }
dn += i;
*cpp = cp;
@@ -502,26 +517,30 @@ ats_host_res_from(int family, HostResPreferenceOrder order)
for (int i = 0; i < N_HOST_RES_PREFERENCE_ORDER; ++i) {
HostResPreference p = order[i];
- if (HOST_RES_PREFER_CLIENT == p)
+ if (HOST_RES_PREFER_CLIENT == p) {
p = client; // CLIENT -> actual value
+ }
if (HOST_RES_PREFER_IPV4 == p) {
- if (v6)
+ if (v6) {
return HOST_RES_IPV6;
- else
+ } else {
v4 = true;
+ }
} else if (HOST_RES_PREFER_IPV6 == p) {
- if (v4)
+ if (v4) {
return HOST_RES_IPV4;
- else
+ } else {
v6 = true;
+ }
} else {
break;
}
}
- if (v4)
+ if (v4) {
return HOST_RES_IPV4_ONLY;
- else if (v6)
+ } else if (v6) {
return HOST_RES_IPV6_ONLY;
+ }
return HOST_RES_NONE;
}
@@ -529,9 +548,10 @@ HostResStyle
ats_host_res_match(sockaddr const *addr)
{
HostResStyle zret = HOST_RES_NONE;
- if (ats_is_ip6(addr))
+ if (ats_is_ip6(addr)) {
zret = HOST_RES_IPV6_ONLY;
- else if (ats_is_ip4(addr))
+ } else if (ats_is_ip4(addr)) {
zret = HOST_RES_IPV4_ONLY;
+ }
return zret;
}
diff --git a/lib/ts/ink_rwlock.cc b/lib/ts/ink_rwlock.cc
index a4a9af8..4dd21b7 100644
--- a/lib/ts/ink_rwlock.cc
+++ b/lib/ts/ink_rwlock.cc
@@ -52,10 +52,12 @@ ink_rwlock_init(ink_rwlock *rw)
int
ink_rwlock_destroy(ink_rwlock *rw)
{
- if (rw->rw_magic != RW_MAGIC)
+ if (rw->rw_magic != RW_MAGIC) {
return EINVAL;
- if (rw->rw_refcount != 0 || rw->rw_nwaitreaders != 0 || rw->rw_nwaitwriters != 0)
+ }
+ if (rw->rw_refcount != 0 || rw->rw_nwaitreaders != 0 || rw->rw_nwaitwriters != 0) {
return EBUSY;
+ }
ink_mutex_destroy(&rw->rw_mutex);
ink_cond_destroy(&rw->rw_condreaders);
@@ -72,8 +74,9 @@ ink_rwlock_destroy(ink_rwlock *rw)
int
ink_rwlock_rdlock(ink_rwlock *rw)
{
- if (rw->rw_magic != RW_MAGIC)
+ if (rw->rw_magic != RW_MAGIC) {
return EINVAL;
+ }
ink_mutex_acquire(&rw->rw_mutex);
@@ -97,8 +100,9 @@ ink_rwlock_rdlock(ink_rwlock *rw)
int
ink_rwlock_wrlock(ink_rwlock *rw)
{
- if (rw->rw_magic != RW_MAGIC)
+ if (rw->rw_magic != RW_MAGIC) {
return EINVAL;
+ }
ink_mutex_acquire(&rw->rw_mutex);
@@ -121,8 +125,9 @@ ink_rwlock_wrlock(ink_rwlock *rw)
int
ink_rwlock_unlock(ink_rwlock *rw)
{
- if (rw->rw_magic != RW_MAGIC)
+ if (rw->rw_magic != RW_MAGIC) {
return EINVAL;
+ }
ink_mutex_acquire(&rw->rw_mutex);
@@ -136,10 +141,12 @@ ink_rwlock_unlock(ink_rwlock *rw)
/* give preference to waiting writers over waiting readers */
if (rw->rw_nwaitwriters > 0) {
- if (rw->rw_refcount == 0)
+ if (rw->rw_refcount == 0) {
ink_cond_signal(&rw->rw_condwriters);
- } else if (rw->rw_nwaitreaders > 0)
+ }
+ } else if (rw->rw_nwaitreaders > 0) {
ink_cond_broadcast(&rw->rw_condreaders);
+ }
ink_mutex_release(&rw->rw_mutex);
diff --git a/lib/ts/ink_sock.cc b/lib/ts/ink_sock.cc
index 7621f21..6f694d2 100644
--- a/lib/ts/ink_sock.cc
+++ b/lib/ts/ink_sock.cc
@@ -91,8 +91,9 @@ int
safe_set_fl(int fd, int arg)
{
int flags = safe_fcntl(fd, F_GETFL, 0);
- if (flags < 0)
+ if (flags < 0) {
return flags;
+ }
flags |= arg;
flags = safe_fcntl(fd, F_SETFL, flags);
return flags;
@@ -102,8 +103,9 @@ int
safe_clr_fl(int fd, int arg)
{
int flags = safe_fcntl(fd, F_GETFL, 0);
- if (flags < 0)
+ if (flags < 0) {
return flags;
+ }
flags &= ~arg;
flags = safe_fcntl(fd, F_SETFL, flags);
return flags;
@@ -128,12 +130,15 @@ write_ready(int fd, int timeout_msec)
p.events = POLLOUT;
p.fd = fd;
int r = poll(&p, 1, timeout_msec);
- if (r <= 0)
+ if (r <= 0) {
return r;
- if (p.revents & (POLLERR | POLLNVAL))
+ }
+ if (p.revents & (POLLERR | POLLNVAL)) {
return -1;
- if (p.revents & (POLLOUT | POLLHUP))
+ }
+ if (p.revents & (POLLOUT | POLLHUP)) {
return 1;
+ }
return 0;
}
@@ -144,12 +149,15 @@ read_ready(int fd, int timeout_msec)
p.events = POLLIN;
p.fd = fd;
int r = poll(&p, 1, timeout_msec);
- if (r <= 0)
+ if (r <= 0) {
return r;
- if (p.revents & (POLLERR | POLLNVAL))
+ }
+ if (p.revents & (POLLERR | POLLNVAL)) {
return -1;
- if (p.revents & (POLLIN | POLLHUP))
+ }
+ if (p.revents & (POLLIN | POLLHUP)) {
return 1;
+ }
return 0;
}
@@ -211,8 +219,9 @@ fd_read_char(int fd)
int r;
do {
r = read(fd, &c, 1);
- if (r > 0)
+ if (r > 0) {
return c;
+ }
} while (r < 0 && (errno == EAGAIN || errno == EINTR));
perror("fd_read_char");
ink_assert(!"fd_read_char");
@@ -226,18 +235,21 @@ fd_read_line(int fd, char *s, int len)
int numread = 0, r;
// char *buf = s;
do {
- do
+ do {
r = read(fd, &c, 1);
- while (r < 0 && (errno == EAGAIN || errno == EINTR));
+ } while (r < 0 && (errno == EAGAIN || errno == EINTR));
- if (r <= 0 && numread)
+ if (r <= 0 && numread) {
break;
+ }
- if (r <= 0)
+ if (r <= 0) {
return r;
+ }
- if (c == '\n')
+ if (c == '\n') {
break;
+ }
s[numread++] = c;
} while (numread < len - 1);
diff --git a/lib/ts/ink_sprintf.cc b/lib/ts/ink_sprintf.cc
index b6ced6e..0053384 100644
--- a/lib/ts/ink_sprintf.cc
+++ b/lib/ts/ink_sprintf.cc
@@ -79,22 +79,24 @@ ink_bvsprintf(char *buffer, const char *format, va_list ap)
// handle non-% characters //
/////////////////////////////
- if (buffer) // if have output buffer
+ if (buffer) { // if have output buffer
while (*s && (*s != '%')) {
*d++ = *s++;
} // really copy, else
- else
+ } else {
while (*s && (*s != '%')) {
d++;
s++;
} // pass over string
+ }
///////////////////////////
// handle NUL characters //
///////////////////////////
- if (*s == NUL)
+ if (*s == NUL) {
break; // end of string
+ }
/////////////////////////
// handle % characters //
@@ -108,42 +110,46 @@ ink_bvsprintf(char *buffer, const char *format, va_list ap)
++s; // consume 's'
s_val = va_arg(ap_local, char *); // grab string argument
p = s_val; // temporary pointer
- if (buffer) // if have output buffer
+ if (buffer) { // if have output buffer
while (*p) {
*d++ = *p++;
- } // copy value
- else // else
+ } // copy value
+ } else { // else
while (*p) {
d++;
p++;
} // pass over value
+ }
break;
case 'd': // %d pattern
++s; // consume 'd'
d_val = va_arg(ap_local, int); // grab integer argument
snprintf(d_buffer, sizeof(d_buffer), "%d", d_val); // stringify integer
p = d_buffer; // temporary pointer
- if (buffer) // if have output buffer
+ if (buffer) { // if have output buffer
while (*p) {
*d++ = *p++;
- } // copy value
- else // else
+ } // copy value
+ } else { // else
while (*p) {
d++;
p++;
} // pass over value
+ }
break;
default: // something else
- if (buffer)
+ if (buffer) {
*d = *s; // copy unknown character
+ }
++d;
++s;
break;
}
}
- if (buffer)
+ if (buffer) {
*d = NUL;
+ }
++d;
va_end(ap_local);
diff --git a/lib/ts/ink_stack_trace.cc b/lib/ts/ink_stack_trace.cc
index 88cdd35..7df57fc 100644
--- a/lib/ts/ink_stack_trace.cc
+++ b/lib/ts/ink_stack_trace.cc
@@ -46,10 +46,12 @@ ink_stack_trace_dump()
// Recopy and re-terminate the app name in case it has been trashed.
const char *msg = " - STACK TRACE: \n";
- if (write(STDERR_FILENO, program_name, strlen(program_name)) == -1)
+ if (write(STDERR_FILENO, program_name, strlen(program_name)) == -1) {
return;
- if (write(STDERR_FILENO, msg, strlen(msg)) == -1)
+ }
+ if (write(STDERR_FILENO, msg, strlen(msg)) == -1) {
return;
+ }
// In certain situations you can get stuck in malloc waiting for a lock
// that your program held when it segfaulted. We set an alarm so that
diff --git a/lib/ts/ink_string++.cc b/lib/ts/ink_string++.cc
index 7e3509f..9fba742 100644
--- a/lib/ts/ink_string++.cc
+++ b/lib/ts/ink_string++.cc
@@ -50,8 +50,9 @@ StrList::dump(FILE *fp)
{
Str *str;
- for (str = head; str != nullptr; str = str->next)
+ for (str = head; str != nullptr; str = str->next) {
str->dump(fp);
+ }
}
/*-------------------------------------------------------------------------
@@ -69,8 +70,9 @@ StrList::_new_cell(const char *s, int len_not_counting_nul)
cell = &(base_cells[cells_allocated]);
} else {
p = (char *)alloc(sizeof(Str) + 7);
- if (p == nullptr)
- return (nullptr); // FIX: scale heap
+ if (p == nullptr) {
+ return (nullptr); // FIX: scale heap
+ }
p = (char *)((((uintptr_t)p) + 7) & ~7); // round up to multiple of 8
cell = (Str *)p;
}
@@ -79,8 +81,9 @@ StrList::_new_cell(const char *s, int len_not_counting_nul)
// are we supposed to copy the string?
if (copy_when_adding_string) {
char *buf = (char *)alloc(l + 1);
- if (buf == nullptr)
+ if (buf == nullptr) {
return (nullptr); // FIX: need to grow heap!
+ }
memcpy(buf, s, l);
buf[l] = '\0';
@@ -113,8 +116,9 @@ StrList::overflow_heap_alloc(int size)
void
StrList::overflow_heap_clean()
{
- if (overflow_first)
+ if (overflow_first) {
overflow_first->clean();
+ }
}
#define INIT_OVERFLOW_ALIGNMENT 8
diff --git a/lib/ts/ink_string.cc b/lib/ts/ink_string.cc
index 6ee87eb..cbc4de1 100644
--- a/lib/ts/ink_string.cc
+++ b/lib/ts/ink_string.cc
@@ -37,8 +37,9 @@ char *
ink_memcpy_until_char(char *dst, char *src, unsigned int n, unsigned char c)
{
unsigned int i = 0;
- for (; ((i < n) && (((unsigned char)src[i]) != c)); i++)
+ for (; ((i < n) && (((unsigned char)src[i]) != c)); i++) {
dst[i] = src[i];
+ }
return &src[i];
}
@@ -64,11 +65,13 @@ ink_string_concatenate_strings(char *dest, ...)
while (true) {
s = va_arg(ap, char *);
- if (s == nullptr)
+ if (s == nullptr) {
break;
+ }
- while (*s)
+ while (*s) {
*d++ = *s++;
+ }
}
*d++ = '\0';
va_end(ap);
@@ -98,15 +101,17 @@ ink_string_concatenate_strings_n(char *dest, int n, ...)
while (n > 1) {
s = va_arg(ap, char *);
- if (s == nullptr)
+ if (s == nullptr) {
break;
+ }
while (*s && (n > 1)) {
*d++ = *s++;
n--;
}
}
- if (n >= 1)
+ if (n >= 1) {
*d = '\0';
+ }
va_end(ap);
return (dest);
} /* End ink_string_concatenate_strings_n */
@@ -130,15 +135,17 @@ ink_string_append(char *dest, char *src, int n)
ink_assert(dest != nullptr);
ink_assert(n >= 0);
- if (n == 0)
+ if (n == 0) {
return (dest);
+ }
last_valid_char = dest + n - 1;
/* Scan For End Of Dest */
- for (d = dest; (d <= last_valid_char) && (*d != '\0'); d++)
+ for (d = dest; (d <= last_valid_char) && (*d != '\0'); d++) {
;
+ }
/* If At End Of String, NUL Terminate & Exit */
@@ -150,16 +157,17 @@ ink_string_append(char *dest, char *src, int n)
/* Append src To String */
s = src;
- while ((d < last_valid_char) && (*s != '\0'))
+ while ((d < last_valid_char) && (*s != '\0')) {
*d++ = *s++;
+ }
/* If At End Of String, NUL Terminate & Exit */
- if (d > last_valid_char)
+ if (d > last_valid_char) {
dest[n - 1] = '\0';
- else
+ } else {
*d = '\0';
-
+ }
return (dest);
} /* End ink_string_append */
@@ -174,17 +182,20 @@ ink_strlcpy(char *dst, const char *src, size_t siz)
/* Copy as many bytes as will fit */
if (n != 0) {
while (--n != 0) {
- if ((*d++ = *s++) == '\0')
+ if ((*d++ = *s++) == '\0') {
break;
+ }
}
}
/* Not enough room in dst, add NUL and traverse rest of src */
if (n == 0) {
- if (siz != 0)
+ if (siz != 0) {
*d = '\0'; /* NUL-terminate dst */
- while (*s++)
+ }
+ while (*s++) {
;
+ }
}
return (s - src - 1); /* count does not include NUL */
@@ -201,13 +212,15 @@ ink_strlcat(char *dst, const char *src, size_t siz)
size_t dlen;
/* Find the end of dst and adjust bytes left but don't go past end */
- while (n-- != 0 && *d != '\0')
+ while (n-- != 0 && *d != '\0') {
d++;
+ }
dlen = d - dst;
n = siz - dlen;
- if (n == 0)
+ if (n == 0) {
return (dlen + strlen(s));
+ }
while (*s != '\0') {
if (n != 1) {
*d++ = *s;
diff --git a/lib/ts/ink_thread.cc b/lib/ts/ink_thread.cc
index 33db2ab..3ed086e 100644
--- a/lib/ts/ink_thread.cc
+++ b/lib/ts/ink_thread.cc
@@ -78,8 +78,9 @@ void
ink_sem_wait(ink_semaphore *sp)
{
int r;
- while (EINTR == (r = sem_wait(sp->get())))
+ while (EINTR == (r = sem_wait(sp->get()))) {
;
+ }
ink_assert(!r);
}
@@ -87,8 +88,9 @@ bool
ink_sem_trywait(ink_semaphore *sp)
{
int r;
- while (EINTR == (r = sem_trywait(sp->get())))
+ while (EINTR == (r = sem_trywait(sp->get()))) {
;
+ }
ink_assert(r == 0 || (errno == EAGAIN));
return r == 0;
}
diff --git a/lib/ts/ink_time.cc b/lib/ts/ink_time.cc
index 8741baa..7507dc3 100644
--- a/lib/ts/ink_time.cc
+++ b/lib/ts/ink_time.cc
@@ -149,13 +149,15 @@ convert_tm(const struct tm *tp)
mday = tp->tm_mday;
/* what should we do? */
- if ((year < 70) || (year > 137))
+ if ((year < 70) || (year > 137)) {
return (ink_time_t)UNDEFINED_TIME;
+ }
mday += days[month];
/* month base == march */
- if (month < 2)
+ if (month < 2) {
year -= 1;
+ }
mday += (year * 365) + (year / 4) - (year / 100) + (year / 100 + 3) / 4;
mday -= DAYS_OFFSET;
diff --git a/lib/ts/llqueue.cc b/lib/ts/llqueue.cc
index e5b04fa..faea16a 100644
--- a/lib/ts/llqueue.cc
+++ b/lib/ts/llqueue.cc
@@ -108,16 +108,19 @@ enqueue(LLQ *Q, void *data)
new_val->data = data;
new_val->next = nullptr;
- if (Q->tail)
+ if (Q->tail) {
Q->tail->next = new_val;
- Q->tail = new_val;
+ }
+ Q->tail = new_val;
- if (Q->head == nullptr)
+ if (Q->head == nullptr) {
Q->head = Q->tail;
+ }
Q->len++;
- if (Q->len > Q->highwater)
+ if (Q->len > Q->highwater) {
Q->highwater = Q->len;
+ }
ink_mutex_release(&(Q->mux));
ink_sem_post(&(Q->sema));
return 1;
@@ -193,8 +196,9 @@ dequeue(LLQ *Q)
rec = Q->head;
Q->head = Q->head->next;
- if (Q->head == nullptr)
+ if (Q->head == nullptr) {
Q->tail = nullptr;
+ }
d = rec->data;
// freerec(Q, rec);
diff --git a/lib/ts/lockfile.cc b/lib/ts/lockfile.cc
index 5187139..d8947be 100644
--- a/lib/ts/lockfile.cc
+++ b/lib/ts/lockfile.cc
@@ -53,8 +53,9 @@ Lockfile::Open(pid_t *holding_pid)
fd = open(fname, O_RDWR | O_CREAT, 0644);
} while ((fd < 0) && (errno == EINTR));
- if (fd < 0)
+ if (fd < 0) {
return (-errno);
+ }
// Lock it. Note that if we can't get the lock EAGAIN will be the
// error we receive.
@@ -79,8 +80,9 @@ Lockfile::Open(pid_t *holding_pid)
if (err < 0)
FAIL(-errno);
- if (err == 0)
+ if (err == 0) {
break;
+ }
size -= err;
t += err;
@@ -135,8 +137,9 @@ Lockfile::Get(pid_t *holding_pid)
// Open the Lockfile and get the lock. If we are successful, the
// return value will be the file descriptor of the opened Lockfile.
err = Open(holding_pid);
- if (err != 1)
+ if (err != 1) {
return err;
+ }
if (fd < 0) {
return -1;
@@ -204,8 +207,9 @@ lockfile_kill_internal(pid_t init_pid, int init_sig, pid_t pid, const char * /*
// Wait for children to exit
do {
err = waitpid(-1, &status, WNOHANG);
- if (err == -1)
+ if (err == -1) {
break;
+ }
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
diff --git a/lib/ts/test_Map.cc b/lib/ts/test_Map.cc
index 27d35b9..9a5ab0e 100644
--- a/lib/ts/test_Map.cc
+++ b/lib/ts/test_Map.cc
@@ -87,10 +87,11 @@ test_TSHashTable()
ink_assert(!(t.find(N * 2).isValid()));
loc = t.find(N / 2 | 1);
- if (loc)
+ if (loc) {
t.remove(loc);
- else
+ } else {
ink_assert(!"Did not find expected value");
+ }
if (!loc) {
; // compiler check.
@@ -104,10 +105,11 @@ test_TSHashTable()
for (uint32_t i = 1; i <= N; ++i) {
Table::Location l = t.find(i);
- if (1 & i)
+ if (1 & i) {
ink_assert(!l.isValid());
- else
+ } else {
ink_assert(l.isValid());
+ }
}
int n = 0;
diff --git a/lib/ts/test_Scalar.cc b/lib/ts/test_Scalar.cc
index 65946ae..f021ec1 100644
--- a/lib/ts/test_Scalar.cc
+++ b/lib/ts/test_Scalar.cc
@@ -369,10 +369,12 @@ test_Compile()
KBytes x(12);
KiBytes y(12);
- if (x > 12)
+ if (x > 12) {
std::cout << "Operator > works" << std::endl;
- if (y > 12)
+ }
+ if (y > 12) {
std::cout << "Operator > works" << std::endl;
+ }
(void)(x += 10);
(void)(x += static_cast<int>(10));
diff --git a/lib/ts/test_Vec.cc b/lib/ts/test_Vec.cc
index 8109999..e1c7f02 100644
--- a/lib/ts/test_Vec.cc
+++ b/lib/ts/test_Vec.cc
@@ -59,32 +59,41 @@ test_basic()
Vec<void *> v, vv, vvv;
int tt = 99 * 50, t = 0;
- for (size_t i = 0; i < 100; i++)
+ for (size_t i = 0; i < 100; i++) {
v.add((void *)(intptr_t)i);
- for (size_t i = 0; i < 100; i++)
+ }
+ for (size_t i = 0; i < 100; i++) {
t += (int)(intptr_t)v.v[i];
+ }
ink_assert(t == tt);
t = 0;
- for (size_t i = 1; i < 100; i++)
+ for (size_t i = 1; i < 100; i++) {
vv.set_add((void *)(intptr_t)i);
- for (size_t i = 1; i < 100; i++)
+ }
+ for (size_t i = 1; i < 100; i++) {
vvv.set_add((void *)(intptr_t)i);
- for (size_t i = 1; i < 100; i++)
+ }
+ for (size_t i = 1; i < 100; i++) {
vvv.set_add((void *)(intptr_t)(i * 1000));
+ }
vv.set_union(vvv);
- for (size_t i = 0; i < vv.n; i++)
- if (vv.v[i])
+ for (size_t i = 0; i < vv.n; i++) {
+ if (vv.v[i]) {
t += (int)(intptr_t)vv.v[i];
+ }
+ }
ink_assert(t == tt + 1000 * tt);
v.clear();
v.reserve(1000);
t = 0;
- for (size_t i = 0; i < 1000; i++)
+ for (size_t i = 0; i < 1000; i++) {
v.add((void *)(intptr_t)i);
- for (size_t i = 0; i < 1000; i++)
+ }
+ for (size_t i = 0; i < 1000; i++) {
t += (int)(intptr_t)v.v[i];
+ }
ink_assert(t == 999 * 500);
printf("%zu %zu\n", v.n, v.i);
@@ -133,11 +142,13 @@ static void
test_sort()
{
Vec<void *> v;
- for (long i = 1; i <= 1000; ++i)
+ for (long i = 1; i <= 1000; ++i) {
v.add(reinterpret_cast<void *>(static_cast<intptr_t>(((i * 149) % 1000) + 1)));
+ }
v.qsort(&compare);
- for (int i = 0; i < 1000; ++i)
+ for (int i = 0; i < 1000; ++i) {
ink_assert(reinterpret_cast<void *>(static_cast<intptr_t>(i + 1)) == v[i]);
+ }
v.clear();
for (long i = 1; i <= 1000000; ++i) {
@@ -162,19 +173,23 @@ test_sort()
// Very long array, already sorted. This is what broke before.
v.clear();
- for (long i = 1; i <= 10000000; ++i)
+ for (long i = 1; i <= 10000000; ++i) {
v.add(reinterpret_cast<void *>(static_cast<intptr_t>(i)));
+ }
v.qsort(&compare);
- for (long i = 0; i < 10000000; ++i)
+ for (long i = 0; i < 10000000; ++i) {
ink_assert(reinterpret_cast<void *>(static_cast<intptr_t>(i + 1)) == v[i]);
+ }
// very long, reverse sorted.
v.clear();
- for (long i = 10000000; i >= 1; --i)
+ for (long i = 10000000; i >= 1; --i) {
v.add(reinterpret_cast<void *>(static_cast<intptr_t>(i)));
+ }
v.qsort(&compare);
- for (long i = 0; i < 10000000; ++i)
+ for (long i = 0; i < 10000000; ++i) {
ink_assert(reinterpret_cast<void *>(static_cast<intptr_t>(i + 1)) == v[i]);
+ }
}
int
diff --git a/lib/ts/test_atomic.cc b/lib/ts/test_atomic.cc
index 90f2347..5f611a1 100644
--- a/lib/ts/test_atomic.cc
+++ b/lib/ts/test_atomic.cc
@@ -44,12 +44,15 @@ testalist(void *ame)
{
int me = (int)(uintptr_t)ame;
int j, k;
- for (k = 0; k < MAX_ALIST_ARRAY; k++)
+ for (k = 0; k < MAX_ALIST_ARRAY; k++) {
ink_atomiclist_push(&al[k % MAX_ALIST_TEST], &al_test[me][k]);
+ }
void *x;
- for (j = 0; j < 1000000; j++)
- if ((x = ink_atomiclist_pop(&al[me])))
+ for (j = 0; j < 1000000; j++) {
+ if ((x = ink_atomiclist_pop(&al[me]))) {
ink_atomiclist_push(&al[rand() % MAX_ALIST_TEST], x);
+ }
+ }
ink_atomic_increment((int *)&al_done, 1);
return nullptr;
}
@@ -177,8 +180,9 @@ main(int /* argc ATS_UNUSED */, const char * /* argv ATS_UNUSED */ [])
srand(time(nullptr));
printf("sizeof(al_test) = %d\n", (int)sizeof(al_test));
memset(&al_test[0][0], 0, sizeof(al_test));
- for (ali = 0; ali < MAX_ALIST_TEST; ali++)
+ for (ali = 0; ali < MAX_ALIST_TEST; ali++) {
ink_atomiclist_init(&al[ali], "foo", 0);
+ }
for (ali = 0; ali < MAX_ALIST_TEST; ali++) {
ink_thread tid;
pthread_attr_t attr;
@@ -189,8 +193,9 @@ main(int /* argc ATS_UNUSED */, const char * /* argv ATS_UNUSED */ [])
#endif
ink_assert(pthread_create(&tid, &attr, testalist, (void *)((intptr_t)ali)) == 0);
}
- while (al_done != MAX_ALIST_TEST)
+ while (al_done != MAX_ALIST_TEST) {
sleep(1);
+ }
}
#endif // !LONG_ATOMICLIST_TEST
diff --git a/lib/tsconfig/Errata.cc b/lib/tsconfig/Errata.cc
index 6352219..488c2dc 100644
--- a/lib/tsconfig/Errata.cc
+++ b/lib/tsconfig/Errata.cc
@@ -113,7 +113,8 @@ Errata::pre_write() {
// Just create an instance if needed.
Errata::Data*
Errata::instance() {
- if (!m_data) m_data = new Data;
+ if (!m_data) { m_data = new Data;
+}
return m_data.get();
}
@@ -220,15 +221,17 @@ Errata::write(
spot != limit;
++spot
) {
- if ((offset + indent) > 0)
+ if ((offset + indent) > 0) {
out << std::setw(indent + offset) << std::setfill(' ')
<< ((indent > 0 && lead) ? lead : " ");
+}
out << spot->m_id << " [" << spot->m_code << "]: " << spot->m_text
<< std::endl
;
- if (spot->getErrata().size())
+ if (spot->getErrata().size()) {
spot->getErrata().write(out, offset, indent+shift, shift, lead);
+}
}
return out;
diff --git a/lib/tsconfig/TsBuilder.cc b/lib/tsconfig/TsBuilder.cc
index 56a4e96..969e37b 100644
--- a/lib/tsconfig/TsBuilder.cc
+++ b/lib/tsconfig/TsBuilder.cc
@@ -41,11 +41,13 @@ size_t unescape_string(char* text, size_t len) {
if (dst) {
char* limit = text + len;
char* src = dst + 1; // skip escape char
- for ( *dst++ = *src++ ; src < limit ; ++src )
- if ('\\' != *src) *dst++ = *src;
- else if (++src < limit) *dst++ = *src;
- else *dst++ = '\\'; // trailing backslash.
- zret = dst - text;
+ for ( *dst++ = *src++ ; src < limit ; ++src ) {
+ if ('\\' != *src) { *dst++ = *src;
+ } else if (++src < limit) { *dst++ = *src;
+ } else { *dst++ = '\\'; // trailing backslash.
+
+}
+}zret = dst - text;
}
return zret;
}
@@ -167,8 +169,9 @@ void Builder::pathIndex(Token const& token){
// digit string that is followed by a non-digit or the FLEX
// required double null at the end of the input buffer.
_path.append(Buffer(nullptr, static_cast<size_t>(atol(token._s))));
- if (_extent._ptr) _extent._size = token._s - _extent._ptr + token._n;
- else _extent.set(token._s, token._n);
+ if (_extent._ptr) { _extent._size = token._s - _extent._ptr + token._n;
+ } else { _extent.set(token._s, token._n);
+}
}
void Builder::pathClose(Token const&) {
@@ -206,8 +209,10 @@ void Builder::literalValue(Token const& token) {
} else {
msg::logf(_errata, msg::WARN, PRE "Unexpected literal type %d.", token._type);
}
- if (!cv.isOK()) _errata.pull(cv.errata());
- if (cv.result()) cv.result().setSource(token._loc._line, token._loc._col);
+ if (!cv.isOK()) { _errata.pull(cv.errata());
+}
+ if (cv.result()) { cv.result().setSource(token._loc._line, token._loc._col);
+}
_name.set(nullptr,0); // used, so clear it.
}
void Builder::invalidToken(Token const&) { }
diff --git a/lib/tsconfig/TsValue.cc b/lib/tsconfig/TsValue.cc
index d877090..0aea522 100644
--- a/lib/tsconfig/TsValue.cc
+++ b/lib/tsconfig/TsValue.cc
@@ -55,21 +55,24 @@ unsigned int const detail::Type_Property[N_VALUE_TYPES] = {
// ---------------------------------------------------------------------------
detail::ValueTableImpl::ValueTableImpl() : _generation(0) { }
detail::ValueTableImpl::~ValueTableImpl() {
- for (auto & _buffer : _buffers)
+ for (auto & _buffer : _buffers) {
free(_buffer._ptr);
}
+}
// ---------------------------------------------------------------------------
detail::ValueTable::ImplType*
detail::ValueTable::instance() {
- if (! _ptr) _ptr.reset(new ImplType);
+ if (! _ptr) { _ptr.reset(new ImplType);
+}
return _ptr.get();
}
detail::ValueTable&
detail::ValueTable::forceRootItem() {
ImplType* imp = this->instance();
- if (0 == imp->_values.size())
+ if (0 == imp->_values.size()) {
imp->_values.push_back(ValueItem(GroupValue));
+}
return *this;
}
@@ -91,7 +94,8 @@ detail::ValueTable::make(ValueIndex pidx, ValueType type, ConstBuffer const& nam
parent->_children.push_back(n);
item->_local_index = parent->_children.size() - 1;
// Only use the name if the parent is a group.
- if (GroupValue == parent->_type) item->_name = name;
+ if (GroupValue == parent->_type) { item->_name = name;
+}
zret = n; // mark for return to caller.
} else {
msg::log(zret.errata(), msg::WARN, "Add child failed because parent is not a container.");
@@ -114,7 +118,8 @@ Buffer
detail::ValueTable::alloc(size_t n) {
ImplType* imp = this->instance();
Buffer zret(static_cast<char*>(malloc(n)), n);
- if (zret._ptr) imp->_buffers.push_back(zret);
+ if (zret._ptr) { imp->_buffers.push_back(zret);
+}
return zret;
}
@@ -125,7 +130,8 @@ Value::operator [] (size_t idx) const {
detail::ValueItem const* item = this->item();
if (item && idx < item->_children.size()) {
zret = Value(_config, item->_children[idx]);
- if (PathValue == zret.getType()) zret = _config.getRoot().find(_config._table[zret._vidx]._path);
+ if (PathValue == zret.getType()) { zret = _config.getRoot().find(_config._table[zret._vidx]._path);
+}
}
return zret;
}
@@ -138,7 +144,8 @@ Value::operator [] (ConstBuffer const& name) const {
for (const auto & spot : item->_children) {
if (_config._table[spot]._name == name) {
zret = Value(_config, spot);
- if (PathValue == zret.getType()) zret = _config.getRoot().find(_config._table[zret._vidx]._path);
+ if (PathValue == zret.getType()) { zret = _config.getRoot().find(_config._table[zret._vidx]._path);
+}
break;
}
}
@@ -153,11 +160,13 @@ Value::find( ConstBuffer const& path ) {
Rv<Path::Parser::Result> x;
ConstBuffer elt;
for ( x = parser.parse(&elt) ; zret && Path::Parser::EOP != x && Path::Parser::ERROR != x ; x = parser.parse(&elt) ) {
- if (Path::Parser::TAG == x) zret = zret[elt];
- else if (Path::Parser::INDEX == x) zret = zret[elt._size];
- else zret.reset();
+ if (Path::Parser::TAG == x) { zret = zret[elt];
+ } else if (Path::Parser::INDEX == x) { zret = zret[elt._size];
+ } else { zret.reset();
+}
}
- if (Path::Parser::EOP != x) zret.reset();
+ if (Path::Parser::EOP != x) { zret.reset();
+}
return zret;
}
@@ -166,8 +175,9 @@ Value::find(Path const& path ) {
Value zret = *this;
for ( size_t i = 0, n = path.count() ; i < n && zret ; ++i ) {
ConstBuffer const& elt = path[i];
- if (elt._ptr) zret = zret[elt];
- else zret = zret[elt._size];
+ if (elt._ptr) { zret = zret[elt];
+ } else { zret = zret[elt._size];
+}
}
return zret;
}
@@ -176,8 +186,9 @@ Rv<Value>
Value::makeChild(ValueType type, ConstBuffer const& name) {
Rv<Value> zret;
Rv<detail::ValueIndex> vr = _config._table.make(this->_vidx, type, name);
- if (vr.isOK()) zret = Value(_config, vr.result());
- else zret.errata() = vr.errata();
+ if (vr.isOK()) { zret = Value(_config, vr.result());
+ } else { zret.errata() = vr.errata();
+}
return zret;
}
@@ -194,29 +205,32 @@ Value::makeList(ConstBuffer const& name) {
Rv<Value>
Value::makeString(ConstBuffer const& text, ConstBuffer const& name) {
Rv<Value> zret = this->makeChild(StringValue, name);
- if (zret.isOK()) zret.result().setText(text);
+ if (zret.isOK()) { zret.result().setText(text);
+}
return zret;
}
Rv<Value>
Value::makeInteger(ConstBuffer const& text, ConstBuffer const& name) {
Rv<Value> zret = this->makeChild(IntegerValue, name);
- if (zret.isOK()) zret.result().setText(text);
+ if (zret.isOK()) { zret.result().setText(text);
+}
return zret;
}
Rv<Value>
Value::makePath(Path const& path, ConstBuffer const& name) {
Rv<Value> zret = this->makeChild(PathValue, name);
- if (zret.isOK()) _config._table[zret.result()._vidx]._path = path;
+ if (zret.isOK()) { _config._table[zret.result()._vidx]._path = path;
+}
return zret;
}
// ---------------------------------------------------------------------------
Path& Path::reset() {
if (_ptr) {
// If we're sharing the instance, make a new one for us.
- if (_ptr.isShared()) _ptr = new ImplType;
- else { // clear out the existing instance.
+ if (_ptr.isShared()) { _ptr = new ImplType;
+ } else { // clear out the existing instance.
_ptr->_elements.clear();
}
}
@@ -242,22 +256,24 @@ Path::Parser::parse(ConstBuffer *cbuff) {
C_DOT, // A dot (period).
};
- if (cbuff) cbuff->reset();
+ if (cbuff) { cbuff->reset();
+}
char const* start = _c; // save starting character location.
size_t idx = 0; // accumulator for index value.
bool final = false;
while (! final && this->hasInput()) {
Bucket cb;
- if (isdigit(*_c)) cb = C_DIGIT;
- else if ('_' == *_c || isalpha(*_c)) cb = C_IDENT;
- else if ('-' == *_c) cb = C_DASH;
- else if ('.' == *_c) cb = C_DOT;
- else cb = C_INVALID;
+ if (isdigit(*_c)) { cb = C_DIGIT;
+ } else if ('_' == *_c || isalpha(*_c)) { cb = C_IDENT;
+ } else if ('-' == *_c) { cb = C_DASH;
+ } else if ('.' == *_c) { cb = C_DOT;
+ } else { cb = C_INVALID;
+}
if (C_INVALID == cb) {
msg::logf(zret, msg::WARN, "Invalid character '%c' [%u] in path.", *_c, *_c);
- } else switch (state) {
+ } else { switch (state) {
case S_INIT:
switch (cb) {
case C_DIGIT: state = S_INDEX; idx = *_c - '0'; break;
@@ -268,25 +284,25 @@ Path::Parser::parse(ConstBuffer *cbuff) {
}
break;
case S_INDEX: // reading an index.
- if (C_DIGIT == cb) idx = 10 * idx + *_c - '0';
- else if (C_DOT == cb) { final = true; }
+ if (C_DIGIT == cb) { idx = 10 * idx + *_c - '0';
+ } else if (C_DOT == cb) { final = true; }
else {
msg::logf(zret, msg::WARN, "Invalid character '%c' [%u] in index element.", *_c, *_c);
final = true;
}
break;
case S_TAG: // reading a tag.
- if (C_IDENT == cb || C_DIGIT == cb) ; // continue
- else if (C_DASH == cb) state = S_DASH;
- else if (C_DOT == cb) { final = true; }
+ if (C_IDENT == cb || C_DIGIT == cb) { ; // continue
+ } else if (C_DASH == cb) { state = S_DASH;
+ } else if (C_DOT == cb) { final = true; }
else { // should never happen, but be safe.
msg::logf(zret, msg::WARN, "Invalid character '%c' [%u] in index element.", *_c, *_c);
final = true;
}
break;
case S_DASH: // dashes inside tag.
- if (C_IDENT == cb || C_DIGIT == cb) state = S_TAG;
- else if (C_DOT == cb) {
+ if (C_IDENT == cb || C_DIGIT == cb) { state = S_TAG;
+ } else if (C_DOT == cb) {
msg::log(zret, msg::WARN, "Trailing dash not allowed in tag element.");
final = true;
} else if (C_DASH != cb) { // should never happen, but be safe.
@@ -295,11 +311,13 @@ Path::Parser::parse(ConstBuffer *cbuff) {
}
break;
}
+}
++_c;
}
if (!zret.isOK()) {
zret = ERROR;
- if (cbuff) cbuff->set(_c - 1, 1);
+ if (cbuff) { cbuff->set(_c - 1, 1);
+}
_c = nullptr;
_input.reset();
} else if (S_INIT == state) {
@@ -310,15 +328,18 @@ Path::Parser::parse(ConstBuffer *cbuff) {
cbuff->set(start, _c - start);
// if @a final is set, then we parsed a dot separator.
// don't include it in the returned tag.
- if (final) cbuff->_size -= 1;
+ if (final) { cbuff->_size -= 1;
+}
}
} else if (S_INDEX == state) {
zret = INDEX;
- if (cbuff) cbuff->_size = idx;
+ if (cbuff) { cbuff->_size = idx;
+}
} else if (S_DASH == state) {
zret = ERROR;
msg::log(zret, msg::WARN, "Trailing dash not allowed in tag element.");
- if (cbuff) cbuff->set(start, _c - start);
+ if (cbuff) { cbuff->set(start, _c - start);
+}
}
return zret;
}
diff --git a/lib/tsconfig/test-tsconfig.cc b/lib/tsconfig/test-tsconfig.cc
index 8b507c3..41bbf02 100644
--- a/lib/tsconfig/test-tsconfig.cc
+++ b/lib/tsconfig/test-tsconfig.cc
@@ -26,8 +26,9 @@ using ts::config::Configuration;
using ts::config::Value;
inline std::ostream& operator << ( std::ostream& s, ts::ConstBuffer const& b ) {
- if (b._ptr) s.write(b._ptr, b._size);
- else s << b._size;
+ if (b._ptr) { s.write(b._ptr, b._size);
+ } else { s << b._size;
+}
return s;
}
diff --git a/mgmt/ProcessManager.cc b/mgmt/ProcessManager.cc
index 091bc70..128711f 100644
--- a/mgmt/ProcessManager.cc
+++ b/mgmt/ProcessManager.cc
@@ -53,8 +53,9 @@ startProcessManager(void *arg)
pmgmt->initLMConnection();
}
- if (pmgmt->init)
+ if (pmgmt->init) {
pmgmt->init();
+ }
for (;;) {
if (unlikely(shutdown_event_system == true)) {
diff --git a/mgmt/utils/MgmtSocket.cc b/mgmt/utils/MgmtSocket.cc
index e5ce6ef..6a51538 100644
--- a/mgmt/utils/MgmtSocket.cc
+++ b/mgmt/utils/MgmtSocket.cc
@@ -173,10 +173,12 @@ mgmt_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struc
int r, retries;
for (retries = 0; retries < MGMT_MAX_TRANSIENT_ERRORS; retries++) {
r = ::select(nfds, readfds, writefds, errorfds, timeout);
- if (r >= 0)
+ if (r >= 0) {
return r;
- if (!mgmt_transient_error())
+ }
+ if (!mgmt_transient_error()) {
break;
+ }
}
return r;
#else
diff --git a/plugins/esi/combo_handler.cc b/plugins/esi/combo_handler.cc
index 1e22a43..15fe99e 100644
--- a/plugins/esi/combo_handler.cc
+++ b/plugins/esi/combo_handler.cc
@@ -231,8 +231,9 @@ CacheControlHeader::update(TSMBuffer bufp, TSMLoc hdr_loc)
unsigned int max_age = 0;
char *ptr = const_cast<char *>(val);
ptr += TS_HTTP_LEN_MAX_AGE;
- while ((*ptr == ' ') || (*ptr == '\t'))
+ while ((*ptr == ' ') || (*ptr == '\t')) {
ptr++;
+ }
if (*ptr == '=') {
ptr++;
max_age = atoi(ptr);
diff --git a/plugins/experimental/cache_key_genid/cache_key_genid.c b/plugins/experimental/cache_key_genid/cache_key_genid.c
index 63bb2be..020b4b1 100644
--- a/plugins/experimental/cache_key_genid/cache_key_genid.c
+++ b/plugins/experimental/cache_key_genid/cache_key_genid.c
@@ -133,10 +133,12 @@ handle_hook(TSCont *contp, TSEvent event, void *edata)
}
/* Clean up */
- if (url)
+ if (url) {
TSfree(url);
- if (host)
+ }
+ if (host) {
TSfree(host);
+ }
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
break;
diff --git a/plugins/experimental/cachekey/pattern.cc b/plugins/experimental/cachekey/pattern.cc
index 870dd60..35ef0dd 100644
--- a/plugins/experimental/cachekey/pattern.cc
+++ b/plugins/experimental/cachekey/pattern.cc
@@ -215,8 +215,9 @@ Pattern::match(const String &subject)
matchCount = pcre_exec(_re, _extra, subject.c_str(), subject.length(), 0, PCRE_NOTEMPTY, nullptr, 0);
if (matchCount < 0) {
- if (matchCount != PCRE_ERROR_NOMATCH)
+ if (matchCount != PCRE_ERROR_NOMATCH) {
CacheKeyError("matching error %d", matchCount);
+ }
return false;
}
@@ -242,8 +243,9 @@ Pattern::capture(const String &subject, StringVector &result)
matchCount = pcre_exec(_re, nullptr, subject.c_str(), subject.length(), 0, PCRE_NOTEMPTY, ovector, OVECOUNT);
if (matchCount < 0) {
- if (matchCount != PCRE_ERROR_NOMATCH)
+ if (matchCount != PCRE_ERROR_NOMATCH) {
CacheKeyError("matching error %d", matchCount);
+ }
return false;
}
@@ -280,8 +282,9 @@ Pattern::replace(const String &subject, String &result)
matchCount = pcre_exec(_re, nullptr, subject.c_str(), subject.length(), 0, PCRE_NOTEMPTY, ovector, OVECOUNT);
if (matchCount < 0) {
- if (matchCount != PCRE_ERROR_NOMATCH)
+ if (matchCount != PCRE_ERROR_NOMATCH) {
CacheKeyError("matching error %d", matchCount);
+ }
return false;
}
diff --git a/plugins/experimental/header_freq/header_freq.cc b/plugins/experimental/header_freq/header_freq.cc
index 56f787a..6de6620 100644
--- a/plugins/experimental/header_freq/header_freq.cc
+++ b/plugins/experimental/header_freq/header_freq.cc
@@ -85,8 +85,9 @@ CB_Command_Log(TSCont contp, TSEvent event, void *edata)
if (std::string::npos != (colon_idx = command->find(':'))) {
std::string path = command->substr(colon_idx + 1);
// The length of the data can include a trailing null, clip it.
- if (path.length() > 0 && path.back() == '\0')
+ if (path.length() > 0 && path.back() == '\0') {
path.pop_back();
+ }
if (path.length() > 0) {
std::ofstream out;
out.open(path, std::ios::out | std::ios::app);
@@ -127,8 +128,9 @@ count_all_headers(TSMBuffer &bufp, TSMLoc &hdr_loc, std::map<std::string, unsign
std::string str = std::string(hdr_name, hdr_len);
// make case-insensitive by converting to lowercase
- for (auto &c : str)
+ for (auto &c : str) {
c = tolower(c);
+ }
++map[str];
diff --git a/plugins/experimental/memcached_remap/memcached_remap.cc b/plugins/experimental/memcached_remap/memcached_remap.cc
index 88d07cd..336b23a 100644
--- a/plugins/experimental/memcached_remap/memcached_remap.cc
+++ b/plugins/experimental/memcached_remap/memcached_remap.cc
@@ -128,14 +128,17 @@ free_stuff:
TSHandleStringRelease(reqp, hdr_loc, request_scheme);
#endif
release_field:
- if (field_loc)
+ if (field_loc) {
TSHandleMLocRelease(reqp, hdr_loc, field_loc);
+ }
release_url:
- if (url_loc)
+ if (url_loc) {
TSHandleMLocRelease(reqp, hdr_loc, url_loc);
+ }
release_hdr:
- if (hdr_loc)
+ if (hdr_loc) {
TSHandleMLocRelease(reqp, TS_NULL_MLOC, hdr_loc);
+ }
return ret_val;
}
diff --git a/plugins/experimental/mysql_remap/lib/dictionary.c b/plugins/experimental/mysql_remap/lib/dictionary.c
index 24ffaa2..ad5a510 100644
--- a/plugins/experimental/mysql_remap/lib/dictionary.c
+++ b/plugins/experimental/mysql_remap/lib/dictionary.c
@@ -92,8 +92,9 @@ static char *
xstrdup(char *s)
{
char *t;
- if (!s)
+ if (!s) {
return NULL;
+ }
t = (char *)malloc(strlen(s) + 1);
if (t) {
strcpy(t, s);
@@ -152,8 +153,9 @@ dictionary_new(int size)
dictionary *d;
/* If no size was specified, allocate space for DICTMINSZ */
- if (size < DICTMINSZ)
+ if (size < DICTMINSZ) {
size = DICTMINSZ;
+ }
if (!(d = (dictionary *)calloc(1, sizeof(dictionary)))) {
return NULL;
@@ -179,13 +181,16 @@ dictionary_del(dictionary *d)
{
int i;
- if (d == NULL)
+ if (d == NULL) {
return;
+ }
for (i = 0; i < d->size; i++) {
- if (d->key[i] != NULL)
+ if (d->key[i] != NULL) {
free(d->key[i]);
- if (d->val[i] != NULL)
+ }
+ if (d->val[i] != NULL) {
free(d->val[i]);
+ }
}
free(d->val);
free(d->key);
@@ -216,8 +221,9 @@ dictionary_get(dictionary *d, char *key, char *def)
hash = dictionary_hash(key);
for (i = 0; i < d->size; i++) {
- if (d->key[i] == NULL)
+ if (d->key[i] == NULL) {
continue;
+ }
/* Compare hash */
if (hash == d->hash[i]) {
/* Compare string, to avoid hash collisions */
@@ -261,21 +267,24 @@ dictionary_set(dictionary *d, char *key, char *val)
int i;
unsigned hash;
- if (d == NULL || key == NULL)
+ if (d == NULL || key == NULL) {
return -1;
+ }
/* Compute hash for this key */
hash = dictionary_hash(key);
/* Find if value is already in dictionary */
if (d->n > 0) {
for (i = 0; i < d->size; i++) {
- if (d->key[i] == NULL)
+ if (d->key[i] == NULL) {
continue;
+ }
if (hash == d->hash[i]) { /* Same hash value */
if (!strcmp(key, d->key[i])) { /* Same key */
/* Found a value: modify and return */
- if (d->val[i] != NULL)
+ if (d->val[i] != NULL) {
free(d->val[i]);
+ }
d->val[i] = val ? xstrdup(val) : NULL;
/* Value has been modified: return */
return 0;
@@ -336,8 +345,9 @@ dictionary_unset(dictionary *d, char *key)
hash = dictionary_hash(key);
for (i = 0; i < d->size; i++) {
- if (d->key[i] == NULL)
+ if (d->key[i] == NULL) {
continue;
+ }
/* Compare hash */
if (hash == d->hash[i]) {
/* Compare string, to avoid hash collisions */
@@ -347,9 +357,10 @@ dictionary_unset(dictionary *d, char *key)
}
}
}
- if (i >= d->size)
+ if (i >= d->size) {
/* Key not found */
return;
+ }
free(d->key[i]);
d->key[i] = NULL;
@@ -379,8 +390,9 @@ dictionary_dump(dictionary *d, FILE *out)
{
int i;
- if (d == NULL || out == NULL)
+ if (d == NULL || out == NULL) {
return;
+ }
if (d->n < 1) {
fprintf(out, "empty dictionary\n");
return;
diff --git a/plugins/experimental/mysql_remap/lib/iniparser.c b/plugins/experimental/mysql_remap/lib/iniparser.c
index 007ae78..bb9b3e7 100644
--- a/plugins/experimental/mysql_remap/lib/iniparser.c
+++ b/plugins/experimental/mysql_remap/lib/iniparser.c
@@ -76,8 +76,9 @@ strlwc(const char *s)
static char l[ASCIILINESZ + 1];
int i;
- if (s == NULL)
+ if (s == NULL) {
return NULL;
+ }
memset(l, 0, ASCIILINESZ + 1);
i = 0;
while (s[i] && i < ASCIILINESZ) {
@@ -108,17 +109,20 @@ strstrip(char *s)
static char l[ASCIILINESZ + 1];
char *last;
- if (s == NULL)
+ if (s == NULL) {
return NULL;
+ }
- while (isspace((int)*s) && *s)
+ while (isspace((int)*s) && *s) {
s++;
+ }
memset(l, 0, ASCIILINESZ + 1);
strcpy(l, s);
last = l + strlen(l);
while (last > l) {
- if (!isspace((int)*(last - 1)))
+ if (!isspace((int)*(last - 1))) {
break;
+ }
last--;
}
*last = (char)0;
@@ -149,12 +153,14 @@ iniparser_getnsec(dictionary *d)
int i;
int nsec;
- if (d == NULL)
+ if (d == NULL) {
return -1;
+ }
nsec = 0;
for (i = 0; i < d->size; i++) {
- if (d->key[i] == NULL)
+ if (d->key[i] == NULL) {
continue;
+ }
if (strchr(d->key[i], ':') == NULL) {
nsec++;
}
@@ -182,16 +188,19 @@ iniparser_getsecname(dictionary *d, int n)
int i;
int foundsec;
- if (d == NULL || n < 0)
+ if (d == NULL || n < 0) {
return NULL;
+ }
foundsec = 0;
for (i = 0; i < d->size; i++) {
- if (d->key[i] == NULL)
+ if (d->key[i] == NULL) {
continue;
+ }
if (strchr(d->key[i], ':') == NULL) {
foundsec++;
- if (foundsec > n)
+ if (foundsec > n) {
break;
+ }
}
}
if (foundsec <= n) {
@@ -218,11 +227,13 @@ iniparser_dump(dictionary *d, FILE *f)
{
int i;
- if (d == NULL || f == NULL)
+ if (d == NULL || f == NULL) {
return;
+ }
for (i = 0; i < d->size; i++) {
- if (d->key[i] == NULL)
+ if (d->key[i] == NULL) {
continue;
+ }
if (d->val[i] != NULL) {
fprintf(f, "[%s]=[%s]\n", d->key[i], d->val[i]);
} else {
@@ -252,15 +263,17 @@ iniparser_dump_ini(dictionary *d, FILE *f)
char *secname;
int seclen;
- if (d == NULL || f == NULL)
+ if (d == NULL || f == NULL) {
return;
+ }
nsec = iniparser_getnsec(d);
if (nsec < 1) {
/* No section in file: dump all keys as they are */
for (i = 0; i < d->size; i++) {
- if (d->key[i] == NULL)
+ if (d->key[i] == NULL) {
continue;
+ }
fprintf(f, "%s = %s\n", d->key[i], d->val[i]);
}
return;
@@ -271,8 +284,9 @@ iniparser_dump_ini(dictionary *d, FILE *f)
fprintf(f, "\n[%s]\n", secname);
sprintf(keym, "%s:", secname);
for (j = 0; j < d->size; j++) {
- if (d->key[j] == NULL)
+ if (d->key[j] == NULL) {
continue;
+ }
if (!strncmp(d->key[j], keym, seclen + 1)) {
fprintf(f, "%-30s = %s\n", d->key[j] + seclen + 1, d->val[j] ? d->val[j] : "");
}
@@ -303,8 +317,9 @@ iniparser_getstring(dictionary *d, const char *key, char *def)
char *lc_key;
char *sval;
- if (d == NULL || key == NULL)
+ if (d == NULL || key == NULL) {
return def;
+ }
lc_key = strlwc(key);
sval = dictionary_get(d, lc_key, def);
@@ -344,8 +359,9 @@ iniparser_getint(dictionary *d, const char *key, int notfound)
char *str;
str = iniparser_getstring(d, key, INI_INVALID_KEY);
- if (str == INI_INVALID_KEY)
+ if (str == INI_INVALID_KEY) {
return notfound;
+ }
return (int)strtol(str, NULL, 0);
}
@@ -368,8 +384,9 @@ iniparser_getdouble(dictionary *d, char *key, double notfound)
char *str;
str = iniparser_getstring(d, key, INI_INVALID_KEY);
- if (str == INI_INVALID_KEY)
+ if (str == INI_INVALID_KEY) {
return notfound;
+ }
return atof(str);
}
@@ -412,8 +429,9 @@ iniparser_getboolean(dictionary *d, const char *key, int notfound)
int ret;
c = iniparser_getstring(d, key, INI_INVALID_KEY);
- if (c == INI_INVALID_KEY)
+ if (c == INI_INVALID_KEY) {
return notfound;
+ }
if (c[0] == 'y' || c[0] == 'Y' || c[0] == '1' || c[0] == 't' || c[0] == 'T') {
ret = 1;
} else if (c[0] == 'n' || c[0] == 'N' || c[0] == '0' || c[0] == 'f' || c[0] == 'F') {
diff --git a/plugins/experimental/mysql_remap/mysql_remap.cc b/plugins/experimental/mysql_remap/mysql_remap.cc
index 2f2324b..a8eaee8 100644
--- a/plugins/experimental/mysql_remap/mysql_remap.cc
+++ b/plugins/experimental/mysql_remap/mysql_remap.cc
@@ -137,14 +137,17 @@ not_found:
TSHandleStringRelease(reqp, hdr_loc, request_scheme);
#endif
release_field:
- if (field_loc)
+ if (field_loc) {
TSHandleMLocRelease(reqp, hdr_loc, field_loc);
+ }
release_url:
- if (url_loc)
+ if (url_loc) {
TSHandleMLocRelease(reqp, hdr_loc, url_loc);
+ }
release_hdr:
- if (hdr_loc)
+ if (hdr_loc) {
TSHandleMLocRelease(reqp, TS_NULL_MLOC, hdr_loc);
+ }
return ret_val;
}
diff --git a/plugins/gzip/configuration.cc b/plugins/gzip/configuration.cc
index c27352e..4271478 100644
--- a/plugins/gzip/configuration.cc
+++ b/plugins/gzip/configuration.cc
@@ -220,12 +220,13 @@ HostConfiguration::add_compression_algorithms(const string &algorithms)
#else
error("supported-algorithms: brotli support not compiled in.");
#endif
- } else if (token.find("gzip") != string::npos)
+ } else if (token.find("gzip") != string::npos) {
compression_algorithms_ |= ALGORITHM_GZIP;
- else if (token.find("deflate") != string::npos)
+ } else if (token.find("deflate") != string::npos) {
compression_algorithms_ |= ALGORITHM_DEFLATE;
- else
+ } else {
error("Unknown compression type. Supported compression-algorithms <br,gzip,deflate>.");
+ }
}
}
diff --git a/plugins/gzip/gzip.cc b/plugins/gzip/gzip.cc
index 51718f8..a5d8249 100644
--- a/plugins/gzip/gzip.cc
+++ b/plugins/gzip/gzip.cc
@@ -93,8 +93,9 @@ data_alloc(int compression_type, int compression_algorithms)
data->zstrm.data_type = Z_ASCII;
int window_bits = WINDOW_BITS_GZIP;
- if (compression_type & COMPRESSION_TYPE_DEFLATE)
+ if (compression_type & COMPRESSION_TYPE_DEFLATE) {
window_bits = WINDOW_BITS_DEFLATE;
+ }
err = deflateInit2(&data->zstrm, ZLIB_COMPRESSION_LEVEL, Z_DEFLATED, window_bits, ZLIB_MEMLEVEL, Z_DEFAULT_STRATEGY);
@@ -697,16 +698,19 @@ transformable(TSHttpTxn txnp, bool server, HostConfiguration *host_configuration
}
if (strncasecmp(value, "br", sizeof("br") - 1) == 0) {
- if (*algorithms & ALGORITHM_BROTLI)
+ if (*algorithms & ALGORITHM_BROTLI) {
compression_acceptable = 1;
+ }
*compress_type |= COMPRESSION_TYPE_BROTLI;
} else if (strncasecmp(value, "deflate", sizeof("deflate") - 1) == 0) {
- if (*algorithms & ALGORITHM_DEFLATE)
+ if (*algorithms & ALGORITHM_DEFLATE) {
compression_acceptable = 1;
+ }
*compress_type |= COMPRESSION_TYPE_DEFLATE;
} else if (strncasecmp(value, "gzip", sizeof("gzip") - 1) == 0) {
- if (*algorithms & ALGORITHM_GZIP)
+ if (*algorithms & ALGORITHM_GZIP) {
compression_acceptable = 1;
+ }
*compress_type |= COMPRESSION_TYPE_GZIP;
}
}
diff --git a/proxy/IPAllow.cc b/proxy/IPAllow.cc
index 6f5c46e..82a0afa 100644
--- a/proxy/IPAllow.cc
+++ b/proxy/IPAllow.cc
@@ -305,10 +305,12 @@ IpAllow::BuildTable()
Warning("%s No entries in %s. All IP Addresses will be blocked", module_name, config_file_path);
} else {
// convert the coloring from indices to pointers.
- for (auto &item : _src_map)
+ for (auto &item : _src_map) {
item.setData(&_src_acls[reinterpret_cast<size_t>(item.data())]);
- for (auto &item : _dest_map)
+ }
+ for (auto &item : _dest_map) {
item.setData(&_dest_acls[reinterpret_cast<size_t>(item.data())]);
+ }
}
if (is_debug_tag_set("ip-allow")) {
diff --git a/proxy/InkAPI.cc b/proxy/InkAPI.cc
index 5e23d2a..33436b4 100644
--- a/proxy/InkAPI.cc
+++ b/proxy/InkAPI.cc
@@ -5763,8 +5763,9 @@ TSHttpTxnParentSelectionUrlGet(TSHttpTxn txnp, TSMBuffer bufp, TSMLoc obj)
u.m_heap = ((HdrHeapSDKHandle *)bufp)->m_heap;
u.m_url_impl = (URLImpl *)obj;
- if (!u.valid())
+ if (!u.valid()) {
return TS_ERROR;
+ }
l_url = sm->t_state.cache_info.parent_selection_url;
if (l_url && l_url->valid()) {
@@ -9339,8 +9340,9 @@ TSHttpTxnClientProtocolStackGet(TSHttpTxn txnp, int n, const char **result, int
if (sm && n > 0) {
auto mem = static_cast<ts::StringView *>(alloca(sizeof(ts::StringView) * n));
count = sm->populate_client_protocol(mem, n);
- for (int i = 0; i < count; ++i)
+ for (int i = 0; i < count; ++i) {
result[i] = mem[i].ptr();
+ }
}
if (actual) {
*actual = count;
@@ -9358,8 +9360,9 @@ TSHttpSsnClientProtocolStackGet(TSHttpSsn ssnp, int n, const char **result, int
if (cs && n > 0) {
auto mem = static_cast<ts::StringView *>(alloca(sizeof(ts::StringView) * n));
count = cs->populate_protocol(mem, n);
- for (int i = 0; i < count; ++i)
+ for (int i = 0; i < count; ++i) {
result[i] = mem[i].ptr();
+ }
}
if (actual) {
*actual = count;
diff --git a/proxy/Main.cc b/proxy/Main.cc
index 1f48517..4242c6e 100644
--- a/proxy/Main.cc
+++ b/proxy/Main.cc
@@ -1675,8 +1675,9 @@ main(int /* argc ATS_UNUSED */, const char **argv)
if (mlock_flags == 2) {
if (0 != mlockall(MCL_CURRENT | MCL_FUTURE)) {
Warning("Unable to mlockall() on startup");
- } else
+ } else {
Debug("server", "Successfully called mlockall()");
+ }
}
#endif
diff --git a/proxy/http/Http1ClientSession.cc b/proxy/http/Http1ClientSession.cc
index ba7cbf2..923350c 100644
--- a/proxy/http/Http1ClientSession.cc
+++ b/proxy/http/Http1ClientSession.cc
@@ -230,8 +230,9 @@ Http1ClientSession::do_io_write(Continuation *c, int64_t nbytes, IOBufferReader
void
Http1ClientSession::set_tcp_init_cwnd()
{
- if (!trans.get_sm())
+ if (!trans.get_sm()) {
return;
+ }
int desired_tcp_init_cwnd = trans.get_sm()->t_state.txn_conf->server_tcp_init_cwnd;
DebugHttpSsn("desired TCP congestion window is %d", desired_tcp_init_cwnd);
if (desired_tcp_init_cwnd == 0) {
@@ -251,8 +252,9 @@ Http1ClientSession::do_io_shutdown(ShutdownHowTo_t howto)
void
Http1ClientSession::do_io_close(int alerrno)
{
- if (read_state == HCS_CLOSED)
+ if (read_state == HCS_CLOSED) {
return; // Don't double call session close
+ }
if (read_state == HCS_ACTIVE_READER) {
clear_session_active();
}
diff --git a/proxy/http/HttpBodyFactory.cc b/proxy/http/HttpBodyFactory.cc
index 13af659..ae38535 100644
--- a/proxy/http/HttpBodyFactory.cc
+++ b/proxy/http/HttpBodyFactory.cc
@@ -723,8 +723,9 @@ HttpBodyFactory::load_body_set_from_directory(char *set_name, char *tmpl_dir)
///////////////////////////////////////////////////////////////
if (!(nullptr != strchr(dirEntry->d_name, '#') || (0 == strcmp(dirEntry->d_name, "default")) ||
- (d_len >= sizeof(BASED_DEFAULT) && 0 == strcmp(dirEntry->d_name + d_len - (sizeof(BASED_DEFAULT) - 1), BASED_DEFAULT))))
+ (d_len >= sizeof(BASED_DEFAULT) && 0 == strcmp(dirEntry->d_name + d_len - (sizeof(BASED_DEFAULT) - 1), BASED_DEFAULT)))) {
continue;
+ }
snprintf(path, sizeof(path), "%s/%s", tmpl_dir, dirEntry->d_name);
status = stat(path, &stat_buf);
diff --git a/proxy/http/HttpTransact.cc b/proxy/http/HttpTransact.cc
index f3cb179..bdeb6d0 100644
--- a/proxy/http/HttpTransact.cc
+++ b/proxy/http/HttpTransact.cc
@@ -7644,9 +7644,10 @@ HttpTransact::build_request(State *s, HTTPHdr *base_request, HTTPHdr *outgoing_r
DebugTxn("http_trans", "[build_request] "
"request like cacheable and conditional headers removed");
HttpTransactHeaders::remove_conditional_headers(outgoing_request);
- } else
+ } else {
DebugTxn("http_trans", "[build_request] "
"request like cacheable but keep conditional headers");
+ }
} else {
// In this case, we send a conditional request
// instead of the normal non-conditional request.
@@ -7773,8 +7774,9 @@ HttpTransact::build_response(State *s, HTTPHdr *base_response, HTTPHdr *outgoing
// If the response is prohibited from containing a body,
// we know the content length is trustable for keep-alive
- if (is_response_body_precluded(status_code, s->method))
+ if (is_response_body_precluded(status_code, s->method)) {
s->hdr_info.trust_response_cl = true;
+ }
handle_response_keep_alive_headers(s, outgoing_version, outgoing_response);
diff --git a/proxy/http/HttpTransactHeaders.cc b/proxy/http/HttpTransactHeaders.cc
index 7a26643..7bcf31f 100644
--- a/proxy/http/HttpTransactHeaders.cc
+++ b/proxy/http/HttpTransactHeaders.cc
@@ -693,8 +693,9 @@ write_client_protocol_stack(HttpTransact::State *s, char *via_string, size_t len
char *limit = via_string + len;
ts::StringView *v = proto_buf.data();
for (int i = 0; i < retval && (via + v->size() + 1) < limit; ++i, ++v) {
- if (i)
+ if (i) {
*via++ = '-';
+ }
memcpy(via, v->ptr(), v->size());
via += v->size();
}
diff --git a/proxy/http/HttpTunnel.cc b/proxy/http/HttpTunnel.cc
index eb4b1dd..fa66b2b 100644
--- a/proxy/http/HttpTunnel.cc
+++ b/proxy/http/HttpTunnel.cc
@@ -1308,8 +1308,9 @@ HttpTunnel::consumer_reenable(HttpTunnelConsumer *c)
HttpTunnelProducer *srcp = p->flow_control_source;
if (backlog >= flow_state.high_water) {
- if (is_debug_tag_set("http_tunnel"))
+ if (is_debug_tag_set("http_tunnel")) {
Debug("http_tunnel", "Throttle %p %" PRId64 " / %" PRId64, p, backlog, p->backlog());
+ }
p->throttle(); // p becomes srcp for future calls to this method
} else {
if (srcp && srcp->alive && c->is_sink()) {
@@ -1322,8 +1323,9 @@ HttpTunnel::consumer_reenable(HttpTunnelConsumer *c)
backlog = srcp->backlog(flow_state.low_water);
}
if (backlog < flow_state.low_water) {
- if (is_debug_tag_set("http_tunnel"))
+ if (is_debug_tag_set("http_tunnel")) {
Debug("http_tunnel", "Unthrottle %p %" PRId64 " / %" PRId64, p, backlog, p->backlog());
+ }
srcp->unthrottle();
if (srcp->read_vio) {
srcp->read_vio->reenable();
@@ -1430,8 +1432,9 @@ HttpTunnel::consumer_handler(int event, HttpTunnelConsumer *c)
}
// [amc] I don't think this happens but we'll leave a debug trap
// here just in case.
- if (p->is_throttled())
+ if (p->is_throttled()) {
Debug("http_tunnel", "Special event %s on %p with flow control on", HttpDebugNames::get_event_name(event), p);
+ }
break;
case VC_EVENT_READ_READY:
diff --git a/proxy/http/remap/RemapConfig.cc b/proxy/http/remap/RemapConfig.cc
index d461b30..b9e3ade 100644
--- a/proxy/http/remap/RemapConfig.cc
+++ b/proxy/http/remap/RemapConfig.cc
@@ -847,8 +847,9 @@ remap_load_plugin(const char **argv, int argc, url_mapping *mp, char *errbuf, in
retcode = -13;
}
if (retcode) {
- if (errbuf && errbufsize > 0)
+ if (errbuf && errbufsize > 0) {
Debug("remap_plugin", "%s", errbuf);
+ }
dlclose(pi->dlh);
pi->dlh = nullptr;
return retcode;
diff --git a/proxy/http/remap/RemapProcessor.cc b/proxy/http/remap/RemapProcessor.cc
index d24fa5b..952fff4 100644
--- a/proxy/http/remap/RemapProcessor.cc
+++ b/proxy/http/remap/RemapProcessor.cc
@@ -243,8 +243,9 @@ RemapProcessor::finish_remap(HttpTransact::State *s)
if (is_debug_tag_set("url_rewrite")) {
int old_host_hdr_len;
char *old_host_hdr = (char *)request_header->value_get(MIME_FIELD_HOST, MIME_LEN_HOST, &old_host_hdr_len);
- if (old_host_hdr)
+ if (old_host_hdr) {
Debug("url_rewrite", "Host: Header before rewrite %.*s", old_host_hdr_len, old_host_hdr);
+ }
}
//
// Create the new host header field being careful that our
diff --git a/proxy/http2/Http2Stream.cc b/proxy/http2/Http2Stream.cc
index 626f784..26ddd92 100644
--- a/proxy/http2/Http2Stream.cc
+++ b/proxy/http2/Http2Stream.cc
@@ -356,8 +356,9 @@ Http2Stream::transaction_done()
cross_thread_event = nullptr;
}
- if (!closed)
+ if (!closed) {
do_io_close(); // Make sure we've been closed. If we didn't close the parent session better still be open
+ }
ink_release_assert(closed || !static_cast<Http2ClientSession *>(parent)->connection_state.is_state_closed());
current_reader = nullptr;
@@ -480,8 +481,9 @@ Http2Stream::update_read_request(int64_t read_len, bool call_update)
int send_event = (read_vio.nbytes == read_vio.ndone) ? VC_EVENT_READ_COMPLETE : VC_EVENT_READ_READY;
if (call_update) { // Safe to call vio handler directly
inactive_timeout_at = Thread::get_hrtime() + inactive_timeout;
- if (read_vio._cont && this->current_reader)
+ if (read_vio._cont && this->current_reader) {
read_vio._cont->handleEvent(send_event, &read_vio);
+ }
} else { // Called from do_io_read. Still setting things up. Send event to handle this after the dust settles
read_event = send_tracked_event(read_event, send_event, &read_vio);
}
@@ -493,8 +495,9 @@ Http2Stream::update_read_request(int64_t read_len, bool call_update)
if (request_reader->read_avail() > 0 || send_event == VC_EVENT_READ_COMPLETE) {
if (call_update) { // Safe to call vio handler directly
inactive_timeout_at = Thread::get_hrtime() + inactive_timeout;
- if (read_vio._cont && this->current_reader)
+ if (read_vio._cont && this->current_reader) {
read_vio._cont->handleEvent(send_event, &read_vio);
+ }
} else { // Called from do_io_read. Still setting things up. Send event
// to handle this after the dust settles
read_event = send_tracked_event(read_event, send_event, &read_vio);
@@ -575,8 +578,9 @@ Http2Stream::update_write_request(IOBufferReader *buf_reader, int64_t write_len,
// As with update_read_request, should be safe to call handler directly here if
// call_update is true. Commented out for now while tracking a performance regression
if (call_update) { // Coming from reenable. Safe to call the handler directly
- if (write_vio._cont && this->current_reader)
+ if (write_vio._cont && this->current_reader) {
write_vio._cont->handleEvent(send_event, &write_vio);
+ }
} else { // Called from do_io_write. Might still be setting up state. Send an event to let the dust settle
write_event = send_tracked_event(write_event, send_event, &write_vio);
}
@@ -604,8 +608,9 @@ Http2Stream::update_write_request(IOBufferReader *buf_reader, int64_t write_len,
} else {
send_response_body();
if (call_update) { // Coming from reenable. Safe to call the handler directly
- if (write_vio._cont && this->current_reader)
+ if (write_vio._cont && this->current_reader) {
write_vio._cont->handleEvent(send_event, &write_vio);
+ }
} else { // Called from do_io_write. Might still be setting up state. Send an event to let the dust settle
write_event = send_tracked_event(write_event, send_event, &write_vio);
}
--
To stop receiving notification emails like this one, please contact
['"commits@trafficserver.apache.org" <co...@trafficserver.apache.org>'].