diff --git a/src/posix/platform/configuration.cpp b/src/posix/platform/configuration.cpp index 07f120840..6311bdcb1 100644 --- a/src/posix/platform/configuration.cpp +++ b/src/posix/platform/configuration.cpp @@ -43,6 +43,8 @@ namespace ot { namespace Posix { +const char Configuration::kLogModuleName[] = "Config"; + #if OPENTHREAD_CONFIG_PLATFORM_POWER_CALIBRATION_ENABLE const char Configuration::kKeyCalibratedPower[] = "calibrated_power"; #endif @@ -74,12 +76,12 @@ otError Configuration::SetRegion(uint16_t aRegionCode) exit: if (error == OT_ERROR_NONE) { - otLogInfoPlat("Successfully set region \"%c%c\"", (aRegionCode >> 8) & 0xff, (aRegionCode & 0xff)); + LogInfo("Successfully set region \"%c%c\"", (aRegionCode >> 8) & 0xff, (aRegionCode & 0xff)); } else { - otLogCritPlat("Failed to set region \"%c%c\": %s", (aRegionCode >> 8) & 0xff, (aRegionCode & 0xff), - otThreadErrorToString(error)); + LogCrit("Failed to set region \"%c%c\": %s", (aRegionCode >> 8) & 0xff, (aRegionCode & 0xff), + otThreadErrorToString(error)); } return error; @@ -112,7 +114,7 @@ otError Configuration::GetDomain(uint16_t aRegionCode, Power::Domain &aDomain) exit: if (error != OT_ERROR_NONE) { - otLogCritPlat("Failed to get power domain: %s", otThreadErrorToString(error)); + LogCrit("Failed to get power domain: %s", otThreadErrorToString(error)); } return error; @@ -165,7 +167,7 @@ otError Configuration::UpdateChannelMasks(const Power::Domain &aDomain) exit: if (error != OT_ERROR_NONE) { - otLogCritPlat("Failed to update channel mask: %s", otThreadErrorToString(error)); + LogCrit("Failed to update channel mask: %s", otThreadErrorToString(error)); } return error; @@ -182,7 +184,7 @@ otError Configuration::UpdateTargetPower(const Power::Domain &aDomain) while (GetNextTargetPower(aDomain, iterator, targetPower) == OT_ERROR_NONE) { - otLogInfoPlat("Update target power: %s\r\n", targetPower.ToString().AsCString()); + LogInfo("Update target power: %s\r\n", targetPower.ToString().AsCString()); for (uint8_t ch = targetPower.GetChannelStart(); ch <= targetPower.GetChannelEnd(); ch++) { @@ -193,7 +195,7 @@ otError Configuration::UpdateTargetPower(const Power::Domain &aDomain) exit: if (error != OT_ERROR_NONE) { - otLogCritPlat("Failed to update target power: %s", otThreadErrorToString(error)); + LogCrit("Failed to update target power: %s", otThreadErrorToString(error)); } return error; @@ -222,7 +224,7 @@ otError Configuration::UpdateCalibratedPower(void) while (calibrationFile->Get(kKeyCalibratedPower, iterator, value, sizeof(value)) == OT_ERROR_NONE) { SuccessOrExit(error = calibratedPower.FromString(value)); - otLogInfoPlat("Update calibrated power: %s\r\n", calibratedPower.ToString().AsCString()); + LogInfo("Update calibrated power: %s\r\n", calibratedPower.ToString().AsCString()); for (uint8_t ch = calibratedPower.GetChannelStart(); ch <= calibratedPower.GetChannelEnd(); ch++) { @@ -235,7 +237,7 @@ otError Configuration::UpdateCalibratedPower(void) exit: if (error != OT_ERROR_NONE) { - otLogCritPlat("Failed to update calibrated power table: %s", otThreadErrorToString(error)); + LogCrit("Failed to update calibrated power table: %s", otThreadErrorToString(error)); } return error; @@ -259,7 +261,7 @@ otError Configuration::GetNextTargetPower(const Power::Domain &aDomain, if ((error = aTargetPower.FromString(psave)) != OT_ERROR_NONE) { - otLogCritPlat("Failed to read target power: %s", otThreadErrorToString(error)); + LogCrit("Failed to read target power: %s", otThreadErrorToString(error)); } break; } diff --git a/src/posix/platform/configuration.hpp b/src/posix/platform/configuration.hpp index 0296eb959..e2a294294 100644 --- a/src/posix/platform/configuration.hpp +++ b/src/posix/platform/configuration.hpp @@ -41,7 +41,9 @@ #include #include "config_file.hpp" +#include "logger.hpp" #include "power.hpp" + #include "common/code_utils.hpp" namespace ot { @@ -51,9 +53,11 @@ namespace Posix { * Updates the target power table and calibrated power table to the RCP. * */ -class Configuration +class Configuration : public Logger { public: + static const char kLogModuleName[]; ///< Module name used for logging. + Configuration(void) : mFactoryConfigFile(OPENTHREAD_POSIX_CONFIG_FACTORY_CONFIG_FILE) , mProductConfigFile(OPENTHREAD_POSIX_CONFIG_PRODUCT_CONFIG_FILE) diff --git a/src/posix/platform/daemon.cpp b/src/posix/platform/daemon.cpp index 14c40cf8a..1436e4516 100644 --- a/src/posix/platform/daemon.cpp +++ b/src/posix/platform/daemon.cpp @@ -75,6 +75,8 @@ void GetFilename(Filename &aFilename, const char *aPattern) } // namespace +const char Daemon::kLogModuleName[] = "Daemon"; + int Daemon::OutputFormat(const char *aFormat, ...) { int ret; @@ -97,7 +99,7 @@ int Daemon::OutputFormatV(const char *aFormat, va_list aArguments) "OPENTHREAD_CONFIG_CLI_MAX_LINE_LENGTH is too short!"); rval = vsnprintf(buf, sizeof(buf), aFormat, aArguments); - VerifyOrExit(rval >= 0, otLogWarnPlat("Failed to format CLI output: %s", strerror(errno))); + VerifyOrExit(rval >= 0, LogWarn("Failed to format CLI output: %s", strerror(errno))); if (rval >= static_cast(sizeof(buf))) { @@ -116,7 +118,7 @@ int Daemon::OutputFormatV(const char *aFormat, va_list aArguments) if (rval < 0) { - otLogWarnPlat("Failed to write CLI output: %s", strerror(errno)); + LogWarn("Failed to write CLI output: %s", strerror(errno)); close(mSessionSocket); mSessionSocket = -1; } @@ -160,7 +162,7 @@ void Daemon::InitializeSessionSocket(void) exit: if (rval == -1) { - otLogWarnPlat("Failed to initialize session socket: %s", strerror(errno)); + LogWarn("Failed to initialize session socket: %s", strerror(errno)); if (newSessionSocket != -1) { close(newSessionSocket); @@ -168,7 +170,7 @@ exit: } else { - otLogInfoPlat("Session socket is ready"); + LogInfo("Session socket is ready"); } } @@ -318,7 +320,7 @@ void Daemon::TearDown(void) Filename sockfile; GetFilename(sockfile, OPENTHREAD_POSIX_DAEMON_SOCKET_NAME); - otLogDebgPlat("Removing daemon socket: %s", sockfile); + LogDebg("Removing daemon socket: %s", sockfile); (void)unlink(sockfile); } @@ -400,7 +402,7 @@ void Daemon::Process(const otSysMainloopContext &aContext) { if (rval < 0) { - otLogWarnPlat("Daemon read: %s", strerror(errno)); + LogWarn("Daemon read: %s", strerror(errno)); } close(mSessionSocket); mSessionSocket = -1; diff --git a/src/posix/platform/daemon.hpp b/src/posix/platform/daemon.hpp index 0d4051136..be3738b8f 100644 --- a/src/posix/platform/daemon.hpp +++ b/src/posix/platform/daemon.hpp @@ -31,14 +31,18 @@ #include "openthread-posix-config.h" #include "core/common/non_copyable.hpp" -#include "posix/platform/mainloop.hpp" + +#include "logger.hpp" +#include "mainloop.hpp" namespace ot { namespace Posix { -class Daemon : public Mainloop::Source, private NonCopyable +class Daemon : public Mainloop::Source, public Logger, private NonCopyable { public: + static const char kLogModuleName[]; + static Daemon &Get(void); void SetUp(void); diff --git a/src/posix/platform/firewall.cpp b/src/posix/platform/firewall.cpp index 19ad8c519..7e9d47eae 100644 --- a/src/posix/platform/firewall.cpp +++ b/src/posix/platform/firewall.cpp @@ -124,7 +124,7 @@ void UpdateIpSets(otInstance *aInstance) exit: if (error != OT_ERROR_NONE) { - otLogWarnPlat("Failed to update ipsets: %s", otThreadErrorToString(error)); + otLogWarnPlat("Firewall - failed to update ipsets: %s", otThreadErrorToString(error)); } } diff --git a/src/posix/platform/hdlc_interface.cpp b/src/posix/platform/hdlc_interface.cpp index d2c45e433..12726fc72 100644 --- a/src/posix/platform/hdlc_interface.cpp +++ b/src/posix/platform/hdlc_interface.cpp @@ -128,6 +128,8 @@ namespace ot { namespace Posix { +const char HdlcInterface::kLogModuleName[] = "HdlcIntface"; + HdlcInterface::HdlcInterface(const Url::Url &aRadioUrl) : mReceiveFrameCallback(nullptr) , mReceiveFrameContext(nullptr) @@ -164,7 +166,7 @@ otError HdlcInterface::Init(ReceiveFrameCallback aCallback, void *aCallbackConte #endif // OPENTHREAD_POSIX_CONFIG_RCP_PTY_ENABLE else { - otLogCritPlat("Radio file '%s' not supported", mRadioUrl.GetPath()); + LogCrit("Radio file '%s' not supported", mRadioUrl.GetPath()); ExitNow(error = OT_ERROR_FAILED); } @@ -714,7 +716,7 @@ void HdlcInterface::HandleHdlcFrame(otError aError) { mInterfaceMetrics.mTransferredGarbageFrameCount++; mReceiveFrameBuffer->DiscardFrame(); - otLogWarnPlat("Error decoding hdlc frame: %s", otThreadErrorToString(aError)); + LogWarn("Error decoding hdlc frame: %s", otThreadErrorToString(aError)); } exit: @@ -742,7 +744,7 @@ otError HdlcInterface::ResetConnection(void) usleep(static_cast(kOpenFileDelay) * US_PER_MS); } while (end > otPlatTimeGet()); - otLogCritPlat("Failed to reopen UART connection after resetting the RCP device."); + LogCrit("Failed to reopen UART connection after resetting the RCP device."); error = OT_ERROR_FAILED; } diff --git a/src/posix/platform/hdlc_interface.hpp b/src/posix/platform/hdlc_interface.hpp index bd5c37ea0..c6e01c7b2 100644 --- a/src/posix/platform/hdlc_interface.hpp +++ b/src/posix/platform/hdlc_interface.hpp @@ -34,6 +34,7 @@ #ifndef OT_POSIX_PLATFORM_HDLC_INTERFACE_HPP_ #define OT_POSIX_PLATFORM_HDLC_INTERFACE_HPP_ +#include "logger.hpp" #include "openthread-posix-config.h" #include "platform-posix.h" #include "lib/hdlc/hdlc.hpp" @@ -48,9 +49,11 @@ namespace Posix { * Defines an HDLC interface to the Radio Co-processor (RCP) * */ -class HdlcInterface : public ot::Spinel::SpinelInterface +class HdlcInterface : public ot::Spinel::SpinelInterface, public Logger { public: + static const char kLogModuleName[]; ///< Module name used for logging. + /** * Initializes the object. * diff --git a/src/posix/platform/infra_if.cpp b/src/posix/platform/infra_if.cpp index a843c4103..0c9785228 100644 --- a/src/posix/platform/infra_if.cpp +++ b/src/posix/platform/infra_if.cpp @@ -128,6 +128,8 @@ void otSysCountInfraNetifAddresses(otSysInfraNetIfAddressCounters *aAddressCount namespace ot { namespace Posix { +const char InfraNetif::kLogModuleName[] = "InfraNetif"; + int InfraNetif::CreateIcmp6Socket(const char *aInfraIfName) { int sock; @@ -271,15 +273,16 @@ otError InfraNetif::SendIcmp6Nd(uint32_t aInfraIfIndex, memcpy(CMSG_DATA(cmsgPointer), &hopLimit, sizeof(hopLimit)); rval = sendmsg(mInfraIfIcmp6Socket, &msgHeader, 0); + if (rval < 0) { - otLogWarnPlat("failed to send ICMPv6 message: %s", strerror(errno)); + LogWarn("failed to send ICMPv6 message: %s", strerror(errno)); ExitNow(error = OT_ERROR_FAILED); } if (static_cast(rval) != iov.iov_len) { - otLogWarnPlat("failed to send ICMPv6 message: partially sent"); + LogWarn("failed to send ICMPv6 message: partially sent"); ExitNow(error = OT_ERROR_FAILED); } @@ -311,7 +314,7 @@ uint32_t InfraNetif::GetFlags(void) const if (ioctl(sock, SIOCGIFFLAGS, &ifReq) == -1) { #if OPENTHREAD_POSIX_CONFIG_EXIT_ON_INFRA_NETIF_LOST_ENABLE - otLogCritPlat("The infra link %s may be lost. Exiting.", mInfraIfName); + LogCrit("The infra link %s may be lost. Exiting.", mInfraIfName); DieNow(OT_EXIT_ERROR_ERRNO); #endif ExitNow(); @@ -334,7 +337,7 @@ void InfraNetif::CountAddresses(otSysInfraNetIfAddressCounters &aAddressCounters if (getifaddrs(&ifAddrs) < 0) { - otLogWarnPlat("failed to get netif addresses: %s", strerror(errno)); + LogWarn("failed to get netif addresses: %s", strerror(errno)); ExitNow(); } @@ -381,7 +384,7 @@ bool InfraNetif::HasLinkLocalAddress(void) const if (getifaddrs(&ifAddrs) < 0) { - otLogCritPlat("failed to get netif addresses: %s", strerror(errno)); + LogCrit("failed to get netif addresses: %s", strerror(errno)); DieNow(OT_EXIT_ERROR_ERRNO); } @@ -434,7 +437,7 @@ void InfraNetif::SetInfraNetif(const char *aIfName, int aIcmp6Socket) if (aIfName == nullptr || aIfName[0] == '\0') { - otLogWarnPlat("Border Routing/Backbone Router feature is disabled: infra interface is missing"); + LogWarn("Border Routing/Backbone Router feature is disabled: infra interface is missing"); ExitNow(); } @@ -445,7 +448,7 @@ void InfraNetif::SetInfraNetif(const char *aIfName, int aIcmp6Socket) ifIndex = if_nametoindex(aIfName); if (ifIndex == 0) { - otLogCritPlat("Failed to get the index for infra interface %s", aIfName); + LogCrit("Failed to get the index for infra interface %s", aIfName); DieNow(OT_EXIT_INVALID_ARGUMENTS); } @@ -551,7 +554,7 @@ void InfraNetif::ReceiveNetLinkMessage(void) len = recv(mNetLinkSocket, msgBuffer.mBuffer, sizeof(msgBuffer.mBuffer), 0); if (len < 0) { - otLogCritPlat("Failed to receive netlink message: %s", strerror(errno)); + LogCrit("Failed to receive netlink message: %s", strerror(errno)); ExitNow(); } @@ -576,7 +579,7 @@ void InfraNetif::ReceiveNetLinkMessage(void) struct nlmsgerr *errMsg = reinterpret_cast(NLMSG_DATA(header)); OT_UNUSED_VARIABLE(errMsg); - otLogWarnPlat("netlink NLMSG_ERROR response: seq=%u, error=%d", header->nlmsg_seq, errMsg->error); + LogWarn("netlink NLMSG_ERROR response: seq=%u, error=%d", header->nlmsg_seq, errMsg->error); break; } default: @@ -623,7 +626,7 @@ void InfraNetif::ReceiveIcmp6Message(void) rval = recvmsg(mInfraIfIcmp6Socket, &msg, 0); if (rval < 0) { - otLogWarnPlat("Failed to receive ICMPv6 message: %s", strerror(errno)); + LogWarn("Failed to receive ICMPv6 message: %s", strerror(errno)); ExitNow(error = OT_ERROR_DROP); } @@ -659,7 +662,7 @@ void InfraNetif::ReceiveIcmp6Message(void) exit: if (error != OT_ERROR_NONE) { - otLogDebgPlat("Failed to handle ICMPv6 message: %s", otThreadErrorToString(error)); + LogDebg("Failed to handle ICMPv6 message: %s", otThreadErrorToString(error)); } } #endif // OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE @@ -679,7 +682,7 @@ void InfraNetif::DiscoverNat64PrefixDone(union sigval sv) VerifyOrExit((char *)req->ar_name == kWellKnownIpv4OnlyName); - otLogInfoPlat("Handling host address response for %s", kWellKnownIpv4OnlyName); + LogInfo("Handling host address response for %s", kWellKnownIpv4OnlyName); // We extract the first valid NAT64 prefix from the address look-up response. for (struct addrinfo *rp = res; rp != NULL && prefix.mLength == 0; rp = rp->ai_next) @@ -778,10 +781,10 @@ otError InfraNetif::DiscoverNat64Prefix(uint32_t aInfraIfIndex) if (status != 0) { - otLogNotePlat("getaddrinfo_a failed: %s", gai_strerror(status)); + LogNote("getaddrinfo_a failed: %s", gai_strerror(status)); ExitNow(error = OT_ERROR_FAILED); } - otLogInfoPlat("getaddrinfo_a requested for %s", kWellKnownIpv4OnlyName); + LogInfo("getaddrinfo_a requested for %s", kWellKnownIpv4OnlyName); exit: if (error != OT_ERROR_NONE) { diff --git a/src/posix/platform/infra_if.hpp b/src/posix/platform/infra_if.hpp index db69cbe87..3eee24821 100644 --- a/src/posix/platform/infra_if.hpp +++ b/src/posix/platform/infra_if.hpp @@ -40,9 +40,11 @@ #include #include -#include "multicast_routing.hpp" #include "core/common/non_copyable.hpp" -#include "posix/platform/mainloop.hpp" + +#include "logger.hpp" +#include "mainloop.hpp" +#include "multicast_routing.hpp" #if OPENTHREAD_POSIX_CONFIG_INFRA_IF_ENABLE @@ -53,9 +55,11 @@ namespace Posix { * Manages infrastructure network interface. * */ -class InfraNetif : public Mainloop::Source, private NonCopyable +class InfraNetif : public Mainloop::Source, public Logger, private NonCopyable { public: + static const char kLogModuleName[]; ///< Module name used for logging. + /** * Updates the fd_set and timeout for mainloop. * diff --git a/src/posix/platform/logger.hpp b/src/posix/platform/logger.hpp new file mode 100644 index 000000000..e907b87cb --- /dev/null +++ b/src/posix/platform/logger.hpp @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2024, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file implements the `Logger` class for use by POSIX platform module. + */ + +#ifndef OT_POSIX_PLATFORM_LOGGER_HPP_ +#define OT_POSIX_PLATFORM_LOGGER_HPP_ + +#include "openthread-posix-config.h" + +#include + +namespace ot { +namespace Posix { + +/** + * Provides logging methods for a specific POSIX module. + * + * The `Type` class MUST provide a `static const char kLogModuleName[]` which specifies the POSIX log module name to + * include in the platform logs (using `otLogPlatArgs()`). + * + * Users of this class should follow CRTP-style inheritance, i.e., the `Type` class itself should inherit from + * `Logger`. + * + */ +template class Logger +{ +public: + /** + * Emits a log message at critical log level. + * + * @param[in] aFormat The format string. + * @param[in] ... Arguments for the format specification. + * + */ + static void LogCrit(const char *aFormat, ...) OT_TOOL_PRINTF_STYLE_FORMAT_ARG_CHECK(1, 2) + { + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_CRIT, Type::kLogModuleName, aFormat, args); + va_end(args); + } + + /** + * Emits a log message at warning log level. + * + * @param[in] aFormat The format string. + * @param[in] ... Arguments for the format specification. + * + */ + static void LogWarn(const char *aFormat, ...) OT_TOOL_PRINTF_STYLE_FORMAT_ARG_CHECK(1, 2) + { + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_WARN, Type::kLogModuleName, aFormat, args); + va_end(args); + } + + /** + * Emits a log message at note log level. + * + * @param[in] aFormat The format string. + * @param[in] ... Arguments for the format specification. + * + */ + static void LogNote(const char *aFormat, ...) OT_TOOL_PRINTF_STYLE_FORMAT_ARG_CHECK(1, 2) + { + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_NOTE, Type::kLogModuleName, aFormat, args); + va_end(args); + } + + /** + * Emits a log message at info log level. + * + * @param[in] aFormat The format string. + * @param[in] ... Arguments for the format specification. + * + */ + static void LogInfo(const char *aFormat, ...) OT_TOOL_PRINTF_STYLE_FORMAT_ARG_CHECK(1, 2) + { + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_INFO, Type::kLogModuleName, aFormat, args); + va_end(args); + } + + /** + * Emits a log message at debug log level. + * + * @param[in] aFormat The format string. + * @param[in] ... Arguments for the format specification. + * + */ + static void LogDebg(const char *aFormat, ...) OT_TOOL_PRINTF_STYLE_FORMAT_ARG_CHECK(1, 2) + { + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_DEBG, Type::kLogModuleName, aFormat, args); + va_end(args); + } +}; + +} // namespace Posix +} // namespace ot + +#endif // OT_POSIX_PLATFORM_LOGGER_HPP_ diff --git a/src/posix/platform/multicast_routing.cpp b/src/posix/platform/multicast_routing.cpp index a224ae1ab..864f984d4 100644 --- a/src/posix/platform/multicast_routing.cpp +++ b/src/posix/platform/multicast_routing.cpp @@ -54,19 +54,21 @@ namespace ot { namespace Posix { -#define LogResult(aError, ...) \ - do \ - { \ - otError _err = (aError); \ - \ - if (_err == OT_ERROR_NONE) \ - { \ - otLogInfoPlat(OT_FIRST_ARG(__VA_ARGS__) ": %s" OT_REST_ARGS(__VA_ARGS__), otThreadErrorToString(_err)); \ - } \ - else \ - { \ - otLogWarnPlat(OT_FIRST_ARG(__VA_ARGS__) ": %s" OT_REST_ARGS(__VA_ARGS__), otThreadErrorToString(_err)); \ - } \ +const char MulticastRoutingManager::kLogModuleName[] = "McastRtMgr"; + +#define LogResult(aError, ...) \ + do \ + { \ + otError _err = (aError); \ + \ + if (_err == OT_ERROR_NONE) \ + { \ + LogInfo(OT_FIRST_ARG(__VA_ARGS__) ": %s" OT_REST_ARGS(__VA_ARGS__), otThreadErrorToString(_err)); \ + } \ + else \ + { \ + LogWarn(OT_FIRST_ARG(__VA_ARGS__) ": %s" OT_REST_ARGS(__VA_ARGS__), otThreadErrorToString(_err)); \ + } \ } while (false) void MulticastRoutingManager::SetUp(void) @@ -114,7 +116,7 @@ void MulticastRoutingManager::Enable(void) InitMulticastRouterSock(); - LogResult(OT_ERROR_NONE, "MulticastRoutingManager: %s", __FUNCTION__); + LogResult(OT_ERROR_NONE, "%s", __FUNCTION__); exit: return; } @@ -123,7 +125,7 @@ void MulticastRoutingManager::Disable(void) { FinalizeMulticastRouterSock(); - LogResult(OT_ERROR_NONE, "MulticastRoutingManager: %s", __FUNCTION__); + LogResult(OT_ERROR_NONE, "%s", __FUNCTION__); } void MulticastRoutingManager::Add(const Ip6::Address &aAddress) @@ -133,7 +135,7 @@ void MulticastRoutingManager::Add(const Ip6::Address &aAddress) UnblockInboundMulticastForwardingCache(aAddress); UpdateMldReport(aAddress, true); - LogResult(OT_ERROR_NONE, "MulticastRoutingManager: %s: %s", __FUNCTION__, aAddress.ToString().AsCString()); + LogResult(OT_ERROR_NONE, "%s: %s", __FUNCTION__, aAddress.ToString().AsCString()); exit: return; @@ -148,7 +150,7 @@ void MulticastRoutingManager::Remove(const Ip6::Address &aAddress) RemoveInboundMulticastForwardingCache(aAddress); UpdateMldReport(aAddress, false); - LogResult(error, "MulticastRoutingManager: %s: %s", __FUNCTION__, aAddress.ToString().AsCString()); + LogResult(error, "%s: %s", __FUNCTION__, aAddress.ToString().AsCString()); exit: return; @@ -166,8 +168,7 @@ void MulticastRoutingManager::UpdateMldReport(const Ip6::Address &aAddress, bool ? OT_ERROR_FAILED : OT_ERROR_NONE); - LogResult(error, "MulticastRoutingManager: %s: address %s %s", __FUNCTION__, aAddress.ToString().AsCString(), - (isAdd ? "Added" : "Removed")); + LogResult(error, "%s: address %s %s", __FUNCTION__, aAddress.ToString().AsCString(), (isAdd ? "Added" : "Removed")); } bool MulticastRoutingManager::HasMulticastListener(const Ip6::Address &aAddress) const @@ -283,7 +284,7 @@ void MulticastRoutingManager::ProcessMulticastRouterMessages(void) error = AddMulticastForwardingCache(src, dst, static_cast(mrt6msg->im6_mif)); exit: - LogResult(error, "MulticastRoutingManager: %s", __FUNCTION__); + LogResult(error, "%s", __FUNCTION__); } otError MulticastRoutingManager::AddMulticastForwardingCache(const Ip6::Address &aSrcAddr, @@ -340,9 +341,8 @@ otError MulticastRoutingManager::AddMulticastForwardingCache(const Ip6::Address SaveMulticastForwardingCache(aSrcAddr, aGroupAddr, aIif, forwardMif); exit: - LogResult(error, "MulticastRoutingManager: %s: add dynamic route: %s %s => %s %s", __FUNCTION__, - MifIndexToString(aIif), aSrcAddr.ToString().AsCString(), aGroupAddr.ToString().AsCString(), - MifIndexToString(forwardMif)); + LogResult(error, "%s: add dynamic route: %s %s => %s %s", __FUNCTION__, MifIndexToString(aIif), + aSrcAddr.ToString().AsCString(), aGroupAddr.ToString().AsCString(), MifIndexToString(forwardMif)); return error; } @@ -377,7 +377,7 @@ void MulticastRoutingManager::UnblockInboundMulticastForwardingCache(const Ip6:: mfc.Set(kMifIndexBackbone, kMifIndexThread); - LogResult(error, "MulticastRoutingManager: %s: %s %s => %s %s", __FUNCTION__, MifIndexToString(mfc.mIif), + LogResult(error, "%s: %s %s => %s %s", __FUNCTION__, MifIndexToString(mfc.mIif), mfc.mSrcAddr.ToString().AsCString(), mfc.mGroupAddr.ToString().AsCString(), MifIndexToString(kMifIndexThread)); } @@ -439,9 +439,9 @@ bool MulticastRoutingManager::UpdateMulticastRouteInfo(MulticastForwardingCache { unsigned long validPktCnt; - otLogDebgPlat("MulticastRoutingManager: %s: SIOCGETSGCNT_IN6 %s => %s: bytecnt=%lu, pktcnt=%lu, wrong_if=%lu", - __FUNCTION__, aMfc.mSrcAddr.ToString().AsCString(), aMfc.mGroupAddr.ToString().AsCString(), - sioc_sg_req6.bytecnt, sioc_sg_req6.pktcnt, sioc_sg_req6.wrong_if); + LogDebg("%s: SIOCGETSGCNT_IN6 %s => %s: bytecnt=%lu, pktcnt=%lu, wrong_if=%lu", __FUNCTION__, + aMfc.mSrcAddr.ToString().AsCString(), aMfc.mGroupAddr.ToString().AsCString(), sioc_sg_req6.bytecnt, + sioc_sg_req6.pktcnt, sioc_sg_req6.wrong_if); validPktCnt = sioc_sg_req6.pktcnt - sioc_sg_req6.wrong_if; if (validPktCnt != aMfc.mValidPktCnt) @@ -453,8 +453,8 @@ bool MulticastRoutingManager::UpdateMulticastRouteInfo(MulticastForwardingCache } else { - otLogDebgPlat("MulticastRoutingManager: %s: SIOCGETSGCNT_IN6 %s => %s failed: %s", __FUNCTION__, - aMfc.mSrcAddr.ToString().AsCString(), aMfc.mGroupAddr.ToString().AsCString(), strerror(errno)); + LogDebg("%s: SIOCGETSGCNT_IN6 %s => %s failed: %s", __FUNCTION__, aMfc.mSrcAddr.ToString().AsCString(), + aMfc.mGroupAddr.ToString().AsCString(), strerror(errno)); } return updated; @@ -483,19 +483,18 @@ const char *MulticastRoutingManager::MifIndexToString(MifIndex aMif) void MulticastRoutingManager::DumpMulticastForwardingCache(void) const { #if OPENTHREAD_CONFIG_LOG_PLATFORM && (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_DEBG) - otLogDebgPlat("MulticastRoutingManager: ==================== MFC ENTRIES ===================="); + LogDebg("==================== MFC ENTRIES ===================="); for (const MulticastForwardingCache &mfc : mMulticastForwardingCacheTable) { if (mfc.IsValid()) { - otLogDebgPlat("MulticastRoutingManager: %s %s => %s %s", MifIndexToString(mfc.mIif), - mfc.mSrcAddr.ToString().AsCString(), mfc.mGroupAddr.ToString().AsCString(), - MifIndexToString(mfc.mOif)); + LogDebg("%s %s => %s %s", MifIndexToString(mfc.mIif), mfc.mSrcAddr.ToString().AsCString(), + mfc.mGroupAddr.ToString().AsCString(), MifIndexToString(mfc.mOif)); } } - otLogDebgPlat("MulticastRoutingManager: ====================================================="); + LogDebg("====================================================="); #endif } @@ -605,7 +604,7 @@ void MulticastRoutingManager::RemoveMulticastForwardingCache( ? OT_ERROR_NONE : OT_ERROR_FAILED; - LogResult(error, "MulticastRoutingManager: %s: %s %s => %s %s", __FUNCTION__, MifIndexToString(aMfc.mIif), + LogResult(error, "%s: %s %s => %s %s", __FUNCTION__, MifIndexToString(aMfc.mIif), aMfc.mSrcAddr.ToString().AsCString(), aMfc.mGroupAddr.ToString().AsCString(), MifIndexToString(aMfc.mOif)); diff --git a/src/posix/platform/multicast_routing.hpp b/src/posix/platform/multicast_routing.hpp index c4d7e32fd..9d4e0491e 100644 --- a/src/posix/platform/multicast_routing.hpp +++ b/src/posix/platform/multicast_routing.hpp @@ -39,18 +39,21 @@ #include #include +#include "logger.hpp" +#include "mainloop.hpp" #include "platform-posix.h" #include "core/common/non_copyable.hpp" #include "core/net/ip6_address.hpp" #include "lib/url/url.hpp" -#include "posix/platform/mainloop.hpp" namespace ot { namespace Posix { -class MulticastRoutingManager : public Mainloop::Source, private NonCopyable +class MulticastRoutingManager : public Mainloop::Source, public Logger, private NonCopyable { public: + static const char kLogModuleName[]; + explicit MulticastRoutingManager() : mLastExpireTime(0) diff --git a/src/posix/platform/netif.cpp b/src/posix/platform/netif.cpp index d3b302497..bff6ad511 100644 --- a/src/posix/platform/netif.cpp +++ b/src/posix/platform/netif.cpp @@ -150,12 +150,12 @@ extern int #include #include +#include "logger.hpp" +#include "resolver.hpp" #include "common/code_utils.hpp" #include "common/debug.hpp" #include "net/ip6_address.hpp" -#include "resolver.hpp" - unsigned int gNetifIndex = 0; char gNetifName[IFNAMSIZ]; #if OPENTHREAD_CONFIG_NAT64_TRANSLATOR_ENABLE @@ -167,6 +167,7 @@ const char *otSysGetThreadNetifName(void) { return gNetifName; } unsigned int otSysGetThreadNetifIndex(void) { return gNetifIndex; } #if OPENTHREAD_CONFIG_PLATFORM_NETIF_ENABLE + #if OPENTHREAD_POSIX_CONFIG_FIREWALL_ENABLE #include "firewall.hpp" #endif @@ -191,7 +192,7 @@ using namespace ot::Posix::Ip6Utils; #define OPENTHREAD_POSIX_TUN_DEVICE "/dev/net/tun" #endif -#endif // OPENTHREAD_TUN_DEVICE +#endif // OPENTHREAD_POSIX_TUN_DEVICE #ifdef __linux__ static uint32_t sNetlinkSequence = 0; ///< Netlink message sequence. @@ -291,6 +292,53 @@ static bool sIsSyncingState = false; #define OPENTHREAD_POSIX_LOG_TUN_PACKETS 0 +static const char kLogModuleName[] = "Netif"; + +static void LogCrit(const char *aFormat, ...) +{ + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_CRIT, kLogModuleName, aFormat, args); + va_end(args); +} + +static void LogWarn(const char *aFormat, ...) +{ + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_WARN, kLogModuleName, aFormat, args); + va_end(args); +} + +static void LogNote(const char *aFormat, ...) +{ + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_NOTE, kLogModuleName, aFormat, args); + va_end(args); +} + +static void LogInfo(const char *aFormat, ...) +{ + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_INFO, kLogModuleName, aFormat, args); + va_end(args); +} + +static void LogDebg(const char *aFormat, ...) +{ + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_DEBG, kLogModuleName, aFormat, args); + va_end(args); +} + #if defined(__APPLE__) || defined(__NetBSD__) || defined(__FreeBSD__) static const uint8_t allOnes[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; @@ -317,7 +365,7 @@ static uint8_t NetmaskToPrefixLength(const struct sockaddr_in6 *netmask) return otIp6PrefixMatch(reinterpret_cast(netmask->sin6_addr.s6_addr), reinterpret_cast(allOnes)); } -#endif +#endif // defined(__APPLE__) || defined(__NetBSD__) || defined(__FreeBSD__) #ifdef __linux__ #pragma GCC diagnostic push @@ -421,13 +469,13 @@ static void UpdateUnicastLinux(otInstance *aInstance, const otIp6AddressInfo &aA if (send(sNetlinkFd, &req, req.nh.nlmsg_len, 0) != -1) { - otLogInfoPlat("[netif] Sent request#%u to %s %s/%u", sNetlinkSequence, (aIsAdded ? "add" : "remove"), - Ip6AddressString(aAddressInfo.mAddress).AsCString(), aAddressInfo.mPrefixLength); + LogInfo("Sent request#%u to %s %s/%u", sNetlinkSequence, (aIsAdded ? "add" : "remove"), + Ip6AddressString(aAddressInfo.mAddress).AsCString(), aAddressInfo.mPrefixLength); } else { - otLogWarnPlat("[netif] Failed to send request#%u to %s %s/%u", sNetlinkSequence, (aIsAdded ? "add" : "remove"), - Ip6AddressString(aAddressInfo.mAddress).AsCString(), aAddressInfo.mPrefixLength); + LogWarn("Failed to send request#%u to %s %s/%u", sNetlinkSequence, (aIsAdded ? "add" : "remove"), + Ip6AddressString(aAddressInfo.mAddress).AsCString(), aAddressInfo.mPrefixLength); } } @@ -468,14 +516,13 @@ static void UpdateUnicast(otInstance *aInstance, const otIp6AddressInfo &aAddres rval = ioctl(sIpFd, aIsAdded ? SIOCAIFADDR_IN6 : SIOCDIFADDR_IN6, &ifr6); if (rval == 0) { - otLogInfoPlat("[netif] %s %s/%u", (aIsAdded ? "Added" : "Removed"), - Ip6AddressString(aAddressInfo.mAddress).AsCString(), aAddressInfo.mPrefixLength); + LogInfo("%s %s/%u", (aIsAdded ? "Added" : "Removed"), Ip6AddressString(aAddressInfo.mAddress).AsCString(), + aAddressInfo.mPrefixLength); } else if (errno != EALREADY) { - otLogWarnPlat("[netif] Failed to %s %s/%u: %s", (aIsAdded ? "add" : "remove"), - Ip6AddressString(aAddressInfo.mAddress).AsCString(), aAddressInfo.mPrefixLength, - strerror(errno)); + LogWarn("Failed to %s %s/%u: %s", (aIsAdded ? "add" : "remove"), + Ip6AddressString(aAddressInfo.mAddress).AsCString(), aAddressInfo.mPrefixLength, strerror(errno)); } } #endif @@ -507,21 +554,20 @@ static void UpdateMulticast(otInstance *aInstance, const otIp6Address &aAddress, char addressString[INET6_ADDRSTRLEN + 1]; inet_ntop(AF_INET6, mreq.ipv6mr_multiaddr.s6_addr, addressString, sizeof(addressString)); - otLogWarnPlat("[netif] Ignoring %s failure (EINVAL) for MC LINKLOCAL address (%s)", - aIsAdded ? "IPV6_JOIN_GROUP" : "IPV6_LEAVE_GROUP", addressString); + LogWarn("Ignoring %s failure (EINVAL) for MC LINKLOCAL address (%s)", + aIsAdded ? "IPV6_JOIN_GROUP" : "IPV6_LEAVE_GROUP", addressString); err = 0; } #endif if (err != 0) { - otLogWarnPlat("[netif] %s failure (%d)", aIsAdded ? "IPV6_JOIN_GROUP" : "IPV6_LEAVE_GROUP", errno); + LogWarn("%s failure (%d)", aIsAdded ? "IPV6_JOIN_GROUP" : "IPV6_LEAVE_GROUP", errno); error = OT_ERROR_FAILED; ExitNow(); } - otLogInfoPlat("[netif] %s multicast address %s", aIsAdded ? "Added" : "Removed", - Ip6AddressString(&aAddress).AsCString()); + LogInfo("%s multicast address %s", aIsAdded ? "Added" : "Removed", Ip6AddressString(&aAddress).AsCString()); exit: SuccessOrDie(error); @@ -544,8 +590,8 @@ static void SetLinkState(otInstance *aInstance, bool aState) ifState = ((ifr.ifr_flags & IFF_UP) == IFF_UP) ? true : false; - otLogNotePlat("[netif] Changing interface state to %s%s.", aState ? "up" : "down", - (ifState == aState) ? " (already done, ignoring)" : ""); + LogNote("Changing interface state to %s%s.", aState ? "up" : "down", + (ifState == aState) ? " (already done, ignoring)" : ""); if (ifState != aState) { @@ -560,7 +606,7 @@ static void SetLinkState(otInstance *aInstance, bool aState) exit: if (error != OT_ERROR_NONE) { - otLogWarnPlat("[netif] Failed to update state %s", otThreadErrorToString(error)); + LogWarn("Failed to update state %s", otThreadErrorToString(error)); } } @@ -723,15 +769,14 @@ static void UpdateOmrRoutes(otInstance *aInstance) otIp6PrefixToString(&sAddedOmrRoutes[i], prefixString, sizeof(prefixString)); if ((error = DeleteRoute(sAddedOmrRoutes[i])) != OT_ERROR_NONE) { - otLogWarnPlat("[netif] Failed to delete an OMR route %s in kernel: %s", prefixString, - otThreadErrorToString(error)); + LogWarn("Failed to delete an OMR route %s in kernel: %s", prefixString, otThreadErrorToString(error)); } else { sAddedOmrRoutes[i] = sAddedOmrRoutes[sAddedOmrRoutesNum - 1]; --sAddedOmrRoutesNum; --i; - otLogInfoPlat("[netif] Successfully deleted an OMR route %s in kernel", prefixString); + LogInfo("Successfully deleted an OMR route %s in kernel", prefixString); } } @@ -746,13 +791,12 @@ static void UpdateOmrRoutes(otInstance *aInstance) otIp6PrefixToString(&config.mPrefix, prefixString, sizeof(prefixString)); if ((error = AddOmrRoute(config.mPrefix)) != OT_ERROR_NONE) { - otLogWarnPlat("[netif] Failed to add an OMR route %s in kernel: %s", prefixString, - otThreadErrorToString(error)); + LogWarn("Failed to add an OMR route %s in kernel: %s", prefixString, otThreadErrorToString(error)); } else { sAddedOmrRoutes[sAddedOmrRoutesNum++] = config.mPrefix; - otLogInfoPlat("[netif] Successfully added an OMR route %s in kernel", prefixString); + LogInfo("Successfully added an OMR route %s in kernel", prefixString); } } } @@ -819,15 +863,14 @@ static void UpdateExternalRoutes(otInstance *aInstance) otIp6PrefixToString(&sAddedExternalRoutes[i], prefixString, sizeof(prefixString)); if ((error = DeleteRoute(sAddedExternalRoutes[i])) != OT_ERROR_NONE) { - otLogWarnPlat("[netif] Failed to delete an external route %s in kernel: %s", prefixString, - otThreadErrorToString(error)); + LogWarn("Failed to delete an external route %s in kernel: %s", prefixString, otThreadErrorToString(error)); } else { sAddedExternalRoutes[i] = sAddedExternalRoutes[sAddedExternalRoutesNum - 1]; --sAddedExternalRoutesNum; --i; - otLogWarnPlat("[netif] Successfully deleted an external route %s in kernel", prefixString); + LogWarn("Successfully deleted an external route %s in kernel", prefixString); } } @@ -838,18 +881,17 @@ static void UpdateExternalRoutes(otInstance *aInstance) continue; } VerifyOrExit(sAddedExternalRoutesNum < kMaxExternalRoutesNum, - otLogWarnPlat("[netif] No buffer to add more external routes in kernel")); + LogWarn("No buffer to add more external routes in kernel")); otIp6PrefixToString(&config.mPrefix, prefixString, sizeof(prefixString)); if ((error = AddExternalRoute(config.mPrefix)) != OT_ERROR_NONE) { - otLogWarnPlat("[netif] Failed to add an external route %s in kernel: %s", prefixString, - otThreadErrorToString(error)); + LogWarn("Failed to add an external route %s in kernel: %s", prefixString, otThreadErrorToString(error)); } else { sAddedExternalRoutes[sAddedExternalRoutesNum++] = config.mPrefix; - otLogWarnPlat("[netif] Successfully added an external route %s in kernel", prefixString); + LogWarn("Successfully added an external route %s in kernel", prefixString); } } exit: @@ -914,30 +956,30 @@ static void processNat64StateChange(void) { if ((error = DeleteIp4Route(sActiveNat64Cidr)) != OT_ERROR_NONE) { - otLogWarnPlat("[netif] failed to delete route for NAT64: %s", otThreadErrorToString(error)); + LogWarn("failed to delete route for NAT64: %s", otThreadErrorToString(error)); } } sActiveNat64Cidr = translatorCidr; otIp4CidrToString(&translatorCidr, cidrString, sizeof(cidrString)); - otLogInfoPlat("[netif] NAT64 CIDR updated to %s.", cidrString); + LogInfo("NAT64 CIDR updated to %s.", cidrString); } if (otNat64GetTranslatorState(gInstance) == OT_NAT64_STATE_ACTIVE) { if ((error = AddIp4Route(sActiveNat64Cidr, kNat64RoutePriority)) != OT_ERROR_NONE) { - otLogWarnPlat("[netif] failed to add route for NAT64: %s", otThreadErrorToString(error)); + LogWarn("failed to add route for NAT64: %s", otThreadErrorToString(error)); } - otLogInfoPlat("[netif] Adding route for NAT64"); + LogInfo("Adding route for NAT64"); } else if (sActiveNat64Cidr.mLength > 0) // Translator is not active. { if ((error = DeleteIp4Route(sActiveNat64Cidr)) != OT_ERROR_NONE) { - otLogWarnPlat("[netif] failed to delete route for NAT64: %s", otThreadErrorToString(error)); + LogWarn("failed to delete route for NAT64: %s", otThreadErrorToString(error)); } - otLogInfoPlat("[netif] Deleting route for NAT64"); + LogInfo("Deleting route for NAT64"); } exit: @@ -993,7 +1035,7 @@ static void processReceive(otMessage *aMessage, void *aContext) VerifyOrExit(otMessageRead(aMessage, 0, &packet[offset], maxLength) == length, error = OT_ERROR_NO_BUFS); #if OPENTHREAD_POSIX_LOG_TUN_PACKETS - otLogInfoPlat("[netif] Packet from NCP (%u bytes)", static_cast(length)); + LogInfo("Packet from NCP (%u bytes)", static_cast(length)); otDumpInfoPlat("", &packet[offset], length); #endif @@ -1012,7 +1054,7 @@ exit: if (error != OT_ERROR_NONE) { - otLogWarnPlat("[netif] Failed to receive, error:%s", otThreadErrorToString(error)); + LogWarn("Failed to receive, error:%s", otThreadErrorToString(error)); } } @@ -1069,7 +1111,7 @@ static otError tryProcessIcmp6RaMessage(otInstance *aInstance, const uint8_t *da VerifyOrExit(ra != nullptr, error = OT_ERROR_INVALID_ARGS); #if OPENTHREAD_POSIX_LOG_TUN_PACKETS - otLogInfoPlat("[netif] RA to BorderRouting (%hu bytes)", static_cast(length)); + LogInfo("RA to BorderRouting (%hu bytes)", static_cast(length)); otDumpInfoPlat("", data, static_cast(length)); #endif @@ -1169,7 +1211,7 @@ static void processTransmit(otInstance *aInstance) } #if OPENTHREAD_POSIX_LOG_TUN_PACKETS - otLogInfoPlat("[netif] Packet to NCP (%hu bytes)", static_cast(rval)); + LogInfo("Packet to NCP (%hu bytes)", static_cast(rval)); otDumpInfoPlat("", &packet[offset], static_cast(rval)); #endif @@ -1192,11 +1234,11 @@ exit: { if (error == OT_ERROR_DROP) { - otLogInfoPlat("[netif] Message dropped by Thread"); + LogInfo("Message dropped by Thread"); } else { - otLogWarnPlat("[netif] Failed to transmit, error:%s", otThreadErrorToString(error)); + LogWarn("Failed to transmit, error:%s", otThreadErrorToString(error)); } } } @@ -1208,17 +1250,17 @@ static void logAddrEvent(bool isAdd, const ot::Ip6::Address &aAddress, otError e if ((error == OT_ERROR_NONE) || ((isAdd) && (error == OT_ERROR_ALREADY || error == OT_ERROR_REJECTED)) || ((!isAdd) && (error == OT_ERROR_NOT_FOUND || error == OT_ERROR_REJECTED))) { - otLogInfoPlat("[netif] %s [%s] %s%s", isAdd ? "ADD" : "DEL", aAddress.IsMulticast() ? "M" : "U", - aAddress.ToString().AsCString(), - error == OT_ERROR_ALREADY ? " (already subscribed, ignored)" - : error == OT_ERROR_REJECTED ? " (rejected)" - : error == OT_ERROR_NOT_FOUND ? " (not found, ignored)" - : ""); + LogInfo("%s [%s] %s%s", isAdd ? "ADD" : "DEL", aAddress.IsMulticast() ? "M" : "U", + aAddress.ToString().AsCString(), + error == OT_ERROR_ALREADY ? " (already subscribed, ignored)" + : error == OT_ERROR_REJECTED ? " (rejected)" + : error == OT_ERROR_NOT_FOUND ? " (not found, ignored)" + : ""); } else { - otLogWarnPlat("[netif] %s [%s] %s failed (%s)", isAdd ? "ADD" : "DEL", aAddress.IsMulticast() ? "M" : "U", - aAddress.ToString().AsCString(), otThreadErrorToString(error)); + LogWarn("%s [%s] %s failed (%s)", isAdd ? "ADD" : "DEL", aAddress.IsMulticast() ? "M" : "U", + aAddress.ToString().AsCString(), otThreadErrorToString(error)); } } @@ -1317,7 +1359,7 @@ static void processNetifAddrEvent(otInstance *aInstance, struct nlmsghdr *aNetli } default: - otLogDebgPlat("[netif] Unexpected address type (%d).", (int)rta->rta_type); + LogDebg("Unexpected address type (%d).", (int)rta->rta_type); break; } } @@ -1325,7 +1367,7 @@ static void processNetifAddrEvent(otInstance *aInstance, struct nlmsghdr *aNetli exit: if (error != OT_ERROR_NONE) { - otLogWarnPlat("[netif] Failed to process event, error:%s", otThreadErrorToString(error)); + LogWarn("Failed to process event, error:%s", otThreadErrorToString(error)); } } @@ -1339,13 +1381,13 @@ static void processNetifLinkEvent(otInstance *aInstance, struct nlmsghdr *aNetli isUp = ((ifinfo->ifi_flags & IFF_UP) != 0); - otLogInfoPlat("[netif] Host netif is %s", isUp ? "up" : "down"); + LogInfo("Host netif is %s", isUp ? "up" : "down"); #if defined(RTM_NEWLINK) && defined(RTM_DELLINK) if (sIsSyncingState) { VerifyOrExit(isUp == otIp6IsEnabled(aInstance), - otLogWarnPlat("[netif] Host netif state notification is unexpected (ignore)")); + LogWarn("Host netif state notification is unexpected (ignore)")); sIsSyncingState = false; } else @@ -1353,7 +1395,7 @@ static void processNetifLinkEvent(otInstance *aInstance, struct nlmsghdr *aNetli if (isUp != otIp6IsEnabled(aInstance)) { SuccessOrExit(error = otIp6SetEnabled(aInstance, isUp)); - otLogInfoPlat("[netif] Succeeded to sync netif state with host"); + LogInfo("Succeeded to sync netif state with host"); } #if OPENTHREAD_CONFIG_BORDER_ROUTING_ENABLE && OPENTHREAD_CONFIG_NAT64_TRANSLATOR_ENABLE @@ -1362,7 +1404,7 @@ static void processNetifLinkEvent(otInstance *aInstance, struct nlmsghdr *aNetli // Recover NAT64 route. if ((error = AddIp4Route(sActiveNat64Cidr, kNat64RoutePriority)) != OT_ERROR_NONE) { - otLogWarnPlat("[netif] failed to add route for NAT64: %s", otThreadErrorToString(error)); + LogWarn("failed to add route for NAT64: %s", otThreadErrorToString(error)); } } #endif @@ -1370,7 +1412,7 @@ static void processNetifLinkEvent(otInstance *aInstance, struct nlmsghdr *aNetli exit: if (error != OT_ERROR_NONE) { - otLogWarnPlat("[netif] Failed to sync netif state with host: %s", otThreadErrorToString(error)); + LogWarn("Failed to sync netif state with host: %s", otThreadErrorToString(error)); } } #endif // __linux__ @@ -1519,16 +1561,14 @@ static void processNetifAddrEvent(otInstance *aInstance, struct rt_msghdr *rtm) err = ioctl(sIpFd, SIOCDIFADDR_IN6, &ifr6); if (err != 0) { - otLogWarnPlat( - "[netif] Error (%d) removing stack-addded link-local address %s", errno, - inet_ntop(AF_INET6, addr6.sin6_addr.s6_addr, addressString, sizeof(addressString))); + LogWarn("Error (%d) removing stack-addded link-local address %s", errno, + inet_ntop(AF_INET6, addr6.sin6_addr.s6_addr, addressString, sizeof(addressString))); error = OT_ERROR_FAILED; } else { - otLogNotePlat( - "[netif] %s (removed stack-added link-local)", - inet_ntop(AF_INET6, addr6.sin6_addr.s6_addr, addressString, sizeof(addressString))); + LogNote(" %s (removed stack-added link-local)", + inet_ntop(AF_INET6, addr6.sin6_addr.s6_addr, addressString, sizeof(addressString))); error = OT_ERROR_NONE; } } @@ -1601,7 +1641,7 @@ static void processNetifInfoEvent(otInstance *aInstance, struct rt_msghdr *rtm) exit: if (error != OT_ERROR_NONE) { - otLogWarnPlat("[netif] Failed to process info event: %s", otThreadErrorToString(error)); + LogWarn("Failed to process info event: %s", otThreadErrorToString(error)); } } @@ -1636,7 +1676,7 @@ static void HandleNetlinkResponse(struct nlmsghdr *msg) if (msg->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) { - otLogWarnPlat("[netif] Truncated netlink reply of request#%u", requestSeq); + LogWarn("Truncated netlink reply of request#%u", requestSeq); ExitNow(); } @@ -1645,7 +1685,7 @@ static void HandleNetlinkResponse(struct nlmsghdr *msg) if (err->error == 0) { - otLogInfoPlat("[netif] Succeeded to process request#%u", requestSeq); + LogInfo("Succeeded to process request#%u", requestSeq); ExitNow(); } @@ -1671,11 +1711,11 @@ static void HandleNetlinkResponse(struct nlmsghdr *msg) } else { - otLogDebgPlat("[netif] Ignoring netlink response attribute %d (request#%u)", rta->rta_type, requestSeq); + LogDebg("Ignoring netlink response attribute %d (request#%u)", rta->rta_type, requestSeq); } } - otLogWarnPlat("[netif] Failed to process request#%u: %s", requestSeq, errorMsg); + LogWarn("Failed to process request#%u: %s", requestSeq, errorMsg); exit: return; @@ -1709,7 +1749,7 @@ static void processNetlinkEvent(otInstance *aInstance) // Ensures full netlink header is received if (length < static_cast(HEADER_SIZE)) { - otLogWarnPlat("[netif] Unexpected netlink recv() result: %ld", static_cast(length)); + LogWarn("Unexpected netlink recv() result: %ld", static_cast(length)); ExitNow(); } @@ -1767,7 +1807,7 @@ static void processNetlinkEvent(otInstance *aInstance) #if defined(ROUTE_FILTER) || defined(RO_MSGFILTER) || defined(__linux__) default: - otLogWarnPlat("[netif] Unhandled/Unexpected netlink/route message (%d).", (int)msg->nlmsg_type); + LogWarn("Unhandled/Unexpected netlink/route message (%d).", (int)msg->nlmsg_type); break; #else // this platform doesn't support filtering, so we expect messages of other types...we just ignore them @@ -1912,11 +1952,11 @@ static void SetAddrGenModeToNone(void) if (send(sNetlinkFd, &req, req.nh.nlmsg_len, 0) != -1) { - otLogInfoPlat("[netif] Sent request#%u to set addr_gen_mode to %d", sNetlinkSequence, mode); + LogInfo("Sent request#%u to set addr_gen_mode to %d", sNetlinkSequence, mode); } else { - otLogWarnPlat("[netif] Failed to send request#%u to set addr_gen_mode to %d", sNetlinkSequence, mode); + LogWarn("Failed to send request#%u to set addr_gen_mode to %d", sNetlinkSequence, mode); } } @@ -1997,7 +2037,7 @@ static void platformConfigureTunDevice(otPlatformConfig *aPlatformConfig) err = getsockopt(sTunFd, SYSPROTO_CONTROL, UTUN_OPT_IFNAME, gNetifName, &devNameLen); VerifyOrDie(err == 0, OT_EXIT_ERROR_ERRNO); - otLogInfoPlat("[netif] Tunnel device name = '%s'", gNetifName); + LogInfo("Tunnel device name = '%s'", gNetifName); } #endif @@ -2069,13 +2109,13 @@ static void platformConfigureNetLink(void) #if defined(NETLINK_EXT_ACK) if (setsockopt(sNetlinkFd, SOL_NETLINK, NETLINK_EXT_ACK, &enable, sizeof(enable)) != 0) { - otLogWarnPlat("[netif] Failed to enable NETLINK_EXT_ACK: %s", strerror(errno)); + LogWarn("Failed to enable NETLINK_EXT_ACK: %s", strerror(errno)); } #endif #if defined(NETLINK_CAP_ACK) if (setsockopt(sNetlinkFd, SOL_NETLINK, NETLINK_CAP_ACK, &enable, sizeof(enable)) != 0) { - otLogWarnPlat("[netif] Failed to enable NETLINK_CAP_ACK: %s", strerror(errno)); + LogWarn("Failed to enable NETLINK_CAP_ACK: %s", strerror(errno)); } #endif } @@ -2120,6 +2160,13 @@ static void platformConfigureNetLink(void) void platformNetifInit(otPlatformConfig *aPlatformConfig) { + // To silence "unused function" warning. + (void)LogCrit; + (void)LogWarn; + (void)LogInfo; + (void)LogNote; + (void)LogDebg; + sIpFd = SocketWithCloseExec(AF_INET6, SOCK_DGRAM, IPPROTO_IP, kSocketNonBlock); VerifyOrDie(sIpFd >= 0, OT_EXIT_ERROR_ERRNO); @@ -2148,12 +2195,12 @@ void nat64Init(void) { if ((error = otNat64SetIp4Cidr(gInstance, &cidr)) != OT_ERROR_NONE) { - otLogWarnPlat("[netif] failed to set CIDR for NAT64: %s", otThreadErrorToString(error)); + LogWarn("failed to set CIDR for NAT64: %s", otThreadErrorToString(error)); } } else { - otLogInfoPlat("[netif] No default NAT64 CIDR provided."); + LogInfo("No default NAT64 CIDR provided."); } } #endif diff --git a/src/posix/platform/radio.cpp b/src/posix/platform/radio.cpp index 8828f9bee..f5eb17cc2 100644 --- a/src/posix/platform/radio.cpp +++ b/src/posix/platform/radio.cpp @@ -57,6 +57,8 @@ namespace { extern "C" void platformRadioInit(const char *aUrl) { sRadio.Init(aUrl); } } // namespace +const char Radio::kLogModuleName[] = "Radio"; + Radio::Radio(void) : mRadioUrl(nullptr) , mRadioSpinel() @@ -98,7 +100,7 @@ void Radio::Init(const char *aUrl) mRadioSpinel.SetCallbacks(callbacks); mRadioSpinel.Init(*mSpinelInterface, resetRadio, skipCompatibilityCheck, iidList, OT_ARRAY_LENGTH(iidList)); - otLogDebgPlat("instance init:%p - iid = %d", (void *)&mRadioSpinel, iidList[0]); + LogDebg("instance init:%p - iid = %d", (void *)&mRadioSpinel, iidList[0]); ProcessRadioUrl(mRadioUrl); } @@ -145,7 +147,7 @@ Spinel::SpinelInterface *Radio::CreateSpinelInterface(const char *aInterfaceName #endif else { - otLogCritPlat("The Spinel interface name \"%s\" is not supported!", aInterfaceName); + LogCrit("The Spinel interface name \"%s\" is not supported!", aInterfaceName); DieNow(OT_ERROR_FAILED); } @@ -159,7 +161,7 @@ void Radio::ProcessRadioUrl(const RadioUrl &aRadioUrl) if (aRadioUrl.HasParam("ncp-dataset")) { - otLogCritPlat("The argument \"ncp-dataset\" is no longer supported"); + LogCrit("The argument \"ncp-dataset\" is no longer supported"); DieNow(OT_ERROR_FAILED); } @@ -220,7 +222,7 @@ void Radio::ProcessMaxPowerTable(const RadioUrl &aRadioUrl) VerifyOrDie((error == OT_ERROR_NONE) || (error == OT_ERROR_NOT_IMPLEMENTED), OT_EXIT_FAILURE); if (error == OT_ERROR_NOT_IMPLEMENTED) { - otLogWarnPlat("The RCP doesn't support setting the max transmit power"); + LogWarn("The RCP doesn't support setting the max transmit power"); } ++channel; @@ -233,7 +235,7 @@ void Radio::ProcessMaxPowerTable(const RadioUrl &aRadioUrl) VerifyOrDie((error == OT_ERROR_NONE) || (error == OT_ERROR_NOT_IMPLEMENTED), OT_ERROR_FAILED); if (error == OT_ERROR_NOT_IMPLEMENTED) { - otLogWarnPlat("The RCP doesn't support setting the max transmit power"); + LogWarn("The RCP doesn't support setting the max transmit power"); } ++channel; diff --git a/src/posix/platform/radio.hpp b/src/posix/platform/radio.hpp index 8fe2be781..e4a8b1a9e 100644 --- a/src/posix/platform/radio.hpp +++ b/src/posix/platform/radio.hpp @@ -29,12 +29,13 @@ #ifndef OT_POSIX_PLATFORM_RADIO_HPP_ #define OT_POSIX_PLATFORM_RADIO_HPP_ +#include "hdlc_interface.hpp" +#include "logger.hpp" +#include "radio_url.hpp" +#include "spi_interface.hpp" +#include "vendor_interface.hpp" #include "common/code_utils.hpp" #include "lib/spinel/radio_spinel.hpp" -#include "posix/platform/hdlc_interface.hpp" -#include "posix/platform/radio_url.hpp" -#include "posix/platform/spi_interface.hpp" -#include "posix/platform/vendor_interface.hpp" #if OPENTHREAD_SPINEL_CONFIG_VENDOR_HOOK_ENABLE #ifdef OPENTHREAD_SPINEL_CONFIG_VENDOR_HOOK_HEADER #include OPENTHREAD_SPINEL_CONFIG_VENDOR_HOOK_HEADER @@ -48,9 +49,11 @@ namespace Posix { * Manages Thread radio. * */ -class Radio +class Radio : public Logger { public: + static const char kLogModuleName[]; ///< Module name used for logging. + /** * Creates the radio manager. * diff --git a/src/posix/platform/resolver.cpp b/src/posix/platform/resolver.cpp index c8d80e294..642d77137 100644 --- a/src/posix/platform/resolver.cpp +++ b/src/posix/platform/resolver.cpp @@ -61,6 +61,8 @@ extern ot::Posix::Resolver gResolver; namespace ot { namespace Posix { +const char Resolver::kLogModuleName[] = "Resolver"; + void Resolver::Init(void) { memset(mUpstreamTransaction, 0, sizeof(mUpstreamTransaction)); @@ -95,8 +97,7 @@ void Resolver::LoadDnsServerListFromConf(void) if (inet_pton(AF_INET, &line.c_str()[sizeof(kNameserverItem)], &addr) == 1) { - otLogInfoPlat("Got nameserver #%d: %s", mUpstreamDnsServerCount, - &line.c_str()[sizeof(kNameserverItem)]); + LogInfo("Got nameserver #%d: %s", mUpstreamDnsServerCount, &line.c_str()[sizeof(kNameserverItem)]); mUpstreamDnsServerList[mUpstreamDnsServerCount] = addr; mUpstreamDnsServerCount++; } @@ -105,7 +106,7 @@ void Resolver::LoadDnsServerListFromConf(void) if (mUpstreamDnsServerCount == 0) { - otLogCritPlat("No domain name servers found in %s, default to 127.0.0.1", kResolvConfFullPath); + LogCrit("No domain name servers found in %s, default to 127.0.0.1", kResolvConfFullPath); } mUpstreamDnsServerListFreshness = otPlatTimeGet(); @@ -137,12 +138,12 @@ void Resolver::Query(otPlatDnsUpstreamQuery *aTxn, const otMessage *aQuery) sendto(txn->mUdpFd, packet, length, MSG_DONTWAIT, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) > 0, error = OT_ERROR_NO_ROUTE); } - otLogInfoPlat("Forwarded DNS query %p to %d server(s).", static_cast(aTxn), mUpstreamDnsServerCount); + LogInfo("Forwarded DNS query %p to %d server(s).", static_cast(aTxn), mUpstreamDnsServerCount); exit: if (error != OT_ERROR_NONE) { - otLogCritPlat("Failed to forward DNS query %p to server: %d", static_cast(aTxn), error); + LogCrit("Failed to forward DNS query %p to server: %d", static_cast(aTxn), error); } return; } @@ -171,7 +172,7 @@ Resolver::Transaction *Resolver::AllocateTransaction(otPlatDnsUpstreamQuery *aTh fdOrError = socket(AF_INET, SOCK_DGRAM, 0); if (fdOrError < 0) { - otLogInfoPlat("Failed to create socket for upstream resolver: %d", fdOrError); + LogInfo("Failed to create socket for upstream resolver: %d", fdOrError); break; } ret = &txn; @@ -203,11 +204,11 @@ void Resolver::ForwardResponse(Transaction *aTxn) exit: if (readSize < 0) { - otLogInfoPlat("Failed to read response from upstream resolver socket: %d", errno); + LogInfo("Failed to read response from upstream resolver socket: %d", errno); } if (error != OT_ERROR_NONE) { - otLogInfoPlat("Failed to forward upstream DNS response: %s", otThreadErrorToString(error)); + LogInfo("Failed to forward upstream DNS response: %s", otThreadErrorToString(error)); } if (message != nullptr) { diff --git a/src/posix/platform/resolver.hpp b/src/posix/platform/resolver.hpp index 9b0c1046d..fae0cf9be 100644 --- a/src/posix/platform/resolver.hpp +++ b/src/posix/platform/resolver.hpp @@ -35,14 +35,18 @@ #include #include +#include "logger.hpp" + #if OPENTHREAD_CONFIG_DNS_UPSTREAM_QUERY_ENABLE namespace ot { namespace Posix { -class Resolver +class Resolver : public Logger { public: + static const char kLogModuleName[]; ///< Module name used for logging. + constexpr static ssize_t kMaxDnsMessageSize = 512; constexpr static ssize_t kMaxUpstreamTransactionCount = 16; constexpr static ssize_t kMaxUpstreamServerCount = 3; diff --git a/src/posix/platform/spi_interface.cpp b/src/posix/platform/spi_interface.cpp index 167f4b9c3..9d7860b34 100644 --- a/src/posix/platform/spi_interface.cpp +++ b/src/posix/platform/spi_interface.cpp @@ -62,6 +62,8 @@ namespace ot { namespace Posix { +const char SpiInterface::kLogModuleName[] = "SpiIntface"; + SpiInterface::SpiInterface(const Url::Url &aRadioUrl) : mReceiveFrameCallback(nullptr) , mReceiveFrameContext(nullptr) @@ -153,7 +155,7 @@ otError SpiInterface::Init(ReceiveFrameCallback aCallback, void *aCallbackContex } else { - otLogNotePlat("SPI interface enters polling mode."); + LogNote("SPI interface enters polling mode."); } InitResetPin(spiGpioResetDevice, spiGpioResetLine); @@ -254,7 +256,7 @@ void SpiInterface::InitResetPin(const char *aCharDev, uint8_t aLine) char label[] = "SOC_THREAD_RESET"; int fd; - otLogDebgPlat("InitResetPin: charDev=%s, line=%" PRIu8, aCharDev, aLine); + LogDebg("InitResetPin: charDev=%s, line=%" PRIu8, aCharDev, aLine); VerifyOrDie(aCharDev != nullptr, OT_EXIT_INVALID_ARGUMENTS); VerifyOrDie((fd = open(aCharDev, O_RDWR)) != -1, OT_EXIT_ERROR_ERRNO); @@ -268,7 +270,7 @@ void SpiInterface::InitIntPin(const char *aCharDev, uint8_t aLine) char label[] = "THREAD_SOC_INT"; int fd; - otLogDebgPlat("InitIntPin: charDev=%s, line=%" PRIu8, aCharDev, aLine); + LogDebg("InitIntPin: charDev=%s, line=%" PRIu8, aCharDev, aLine); VerifyOrDie(aCharDev != nullptr, OT_EXIT_INVALID_ARGUMENTS); VerifyOrDie((fd = open(aCharDev, O_RDWR)) != -1, OT_EXIT_ERROR_ERRNO); @@ -283,7 +285,7 @@ void SpiInterface::InitSpiDev(const char *aPath, uint8_t aMode, uint32_t aSpeed) const uint8_t wordBits = kSpiBitsPerWord; int fd; - otLogDebgPlat("InitSpiDev: path=%s, mode=%" PRIu8 ", speed=%" PRIu32, aPath, aMode, aSpeed); + LogDebg("InitSpiDev: path=%s, mode=%" PRIu8 ", speed=%" PRIu32, aPath, aMode, aSpeed); VerifyOrDie((aPath != nullptr) && (aMode <= kSpiModeMax), OT_EXIT_INVALID_ARGUMENTS); VerifyOrDie((fd = open(aPath, O_RDWR | O_CLOEXEC)) != -1, OT_EXIT_ERROR_ERRNO); @@ -314,7 +316,7 @@ void SpiInterface::TriggerReset(void) // Set Reset pin to high level. SetGpioValue(mResetGpioValueFd, 1); - otLogNotePlat("Triggered hardware reset"); + LogNote("Triggered hardware reset"); } uint8_t *SpiInterface::GetRealRxFrameStart(uint8_t *aSpiRxFrameBuffer, uint8_t aAlignAllowance, uint16_t &aSkipLength) @@ -453,12 +455,12 @@ otError SpiInterface::PushPullSpi(void) if (error != OT_ERROR_NONE) { - otLogCritPlat("PushPullSpi:DoSpiTransfer: errno=%s", strerror(errno)); + LogCrit("PushPullSpi:DoSpiTransfer: errno=%s", strerror(errno)); // Print out a helpful error message for a common error. if ((mSpiCsDelayUs != 0) && (errno == EINVAL)) { - otLogWarnPlat("SPI ioctl failed with EINVAL. Try adding `--spi-cs-delay=0` to command line arguments."); + LogWarn("SPI ioctl failed with EINVAL. Try adding `--spi-cs-delay=0` to command line arguments."); } LogStats(); @@ -471,10 +473,10 @@ otError SpiInterface::PushPullSpi(void) { Spinel::SpiFrame rxFrame(spiRxFrame); - otLogDebgPlat("spi_transfer TX: H:%02X ACCEPT:%" PRIu16 " DATA:%" PRIu16, txFrame.GetHeaderFlagByte(), - txFrame.GetHeaderAcceptLen(), txFrame.GetHeaderDataLen()); - otLogDebgPlat("spi_transfer RX: H:%02X ACCEPT:%" PRIu16 " DATA:%" PRIu16, rxFrame.GetHeaderFlagByte(), - rxFrame.GetHeaderAcceptLen(), rxFrame.GetHeaderDataLen()); + LogDebg("spi_transfer TX: H:%02X ACCEPT:%" PRIu16 " DATA:%" PRIu16, txFrame.GetHeaderFlagByte(), + txFrame.GetHeaderAcceptLen(), txFrame.GetHeaderDataLen()); + LogDebg("spi_transfer RX: H:%02X ACCEPT:%" PRIu16 " DATA:%" PRIu16, rxFrame.GetHeaderFlagByte(), + rxFrame.GetHeaderAcceptLen(), rxFrame.GetHeaderDataLen()); slaveHeader = rxFrame.GetHeaderFlagByte(); if ((slaveHeader == 0xFF) || (slaveHeader == 0x00)) @@ -485,11 +487,11 @@ otError SpiInterface::PushPullSpi(void) // Device is off or in a bad state. In some cases may be induced by flow control. if (mSpiSlaveDataLen == 0) { - otLogDebgPlat("Slave did not respond to frame. (Header was all 0x%02X)", slaveHeader); + LogDebg("Slave did not respond to frame. (Header was all 0x%02X)", slaveHeader); } else { - otLogWarnPlat("Slave did not respond to frame. (Header was all 0x%02X)", slaveHeader); + LogWarn("Slave did not respond to frame. (Header was all 0x%02X)", slaveHeader); } mSpiUnresponsiveFrameCount++; @@ -499,8 +501,8 @@ otError SpiInterface::PushPullSpi(void) // Header is full of garbage mInterfaceMetrics.mTransferredGarbageFrameCount++; - otLogWarnPlat("Garbage in header : %02X %02X %02X %02X %02X", spiRxFrame[0], spiRxFrame[1], - spiRxFrame[2], spiRxFrame[3], spiRxFrame[4]); + LogWarn("Garbage in header : %02X %02X %02X %02X %02X", spiRxFrame[0], spiRxFrame[1], spiRxFrame[2], + spiRxFrame[3], spiRxFrame[4]); otDumpDebgPlat("SPI-TX", mSpiTxFrameBuffer, spiTransferBytes); otDumpDebgPlat("SPI-RX", spiRxFrameBuffer, spiTransferBytes); } @@ -518,8 +520,8 @@ otError SpiInterface::PushPullSpi(void) mSpiTxRefusedCount++; mSpiSlaveDataLen = 0; - otLogWarnPlat("Garbage in header : %02X %02X %02X %02X %02X", spiRxFrame[0], spiRxFrame[1], spiRxFrame[2], - spiRxFrame[3], spiRxFrame[4]); + LogWarn("Garbage in header : %02X %02X %02X %02X %02X", spiRxFrame[0], spiRxFrame[1], spiRxFrame[2], + spiRxFrame[3], spiRxFrame[4]); otDumpDebgPlat("SPI-TX", mSpiTxFrameBuffer, spiTransferBytes); otDumpDebgPlat("SPI-RX", spiRxFrameBuffer, spiTransferBytes); @@ -532,7 +534,7 @@ otError SpiInterface::PushPullSpi(void) { mSlaveResetCount++; - otLogNotePlat("Slave did reset (%" PRIu64 " resets so far)", mSlaveResetCount); + LogNote("Slave did reset (%" PRIu64 " resets so far)", mSlaveResetCount); LogStats(); } @@ -634,7 +636,7 @@ void SpiInterface::UpdateFdSet(void *aMainloopContext) // Interrupt pin is asserted, set the timeout to be 0. timeout.tv_sec = 0; timeout.tv_usec = 0; - otLogDebgPlat("UpdateFdSet(): Interrupt."); + LogDebg("UpdateFdSet(): Interrupt."); } else { @@ -677,7 +679,7 @@ void SpiInterface::UpdateFdSet(void *aMainloopContext) { // To avoid printing out this message over and over, we only print it out once the refused count is at two // or higher when we actually have something to send the slave. And then, we only print it once. - otLogInfoPlat("Slave is rate limiting transactions"); + LogInfo("Slave is rate limiting transactions"); mDidPrintRateLimitLog = true; } @@ -686,7 +688,7 @@ void SpiInterface::UpdateFdSet(void *aMainloopContext) { // Ua-oh. The slave hasn't given us a chance to send it anything for over thirty frames. If this ever // happens, print out a warning to the logs. - otLogWarnPlat("Slave seems stuck."); + LogWarn("Slave seems stuck."); } else if (mSpiTxRefusedCount == kSpiTxRefuseExitCount) { @@ -716,7 +718,7 @@ void SpiInterface::Process(const void *aMainloopContext) { struct gpioevent_data event; - otLogDebgPlat("Process(): Interrupt."); + LogDebg("Process(): Interrupt."); // Read event data to clear interrupt. VerifyOrDie(read(mIntGpioValueFd, &event, sizeof(event)) != -1, OT_EXIT_ERROR_ERRNO); @@ -804,21 +806,21 @@ exit: void SpiInterface::LogError(const char *aString) { OT_UNUSED_VARIABLE(aString); - otLogWarnPlat("%s: %s", aString, strerror(errno)); + LogWarn("%s: %s", aString, strerror(errno)); } void SpiInterface::LogStats(void) { - otLogInfoPlat("INFO: SlaveResetCount=%" PRIu64, mSlaveResetCount); - otLogInfoPlat("INFO: SpiDuplexFrameCount=%" PRIu64, mSpiDuplexFrameCount); - otLogInfoPlat("INFO: SpiUnresponsiveFrameCount=%" PRIu64, mSpiUnresponsiveFrameCount); - otLogInfoPlat("INFO: TransferredFrameCount=%" PRIu64, mInterfaceMetrics.mTransferredFrameCount); - otLogInfoPlat("INFO: TransferredValidFrameCount=%" PRIu64, mInterfaceMetrics.mTransferredValidFrameCount); - otLogInfoPlat("INFO: TransferredGarbageFrameCount=%" PRIu64, mInterfaceMetrics.mTransferredGarbageFrameCount); - otLogInfoPlat("INFO: RxFrameCount=%" PRIu64, mInterfaceMetrics.mRxFrameCount); - otLogInfoPlat("INFO: RxFrameByteCount=%" PRIu64, mInterfaceMetrics.mRxFrameByteCount); - otLogInfoPlat("INFO: TxFrameCount=%" PRIu64, mInterfaceMetrics.mTxFrameCount); - otLogInfoPlat("INFO: TxFrameByteCount=%" PRIu64, mInterfaceMetrics.mTxFrameByteCount); + LogInfo("INFO: SlaveResetCount=%" PRIu64, mSlaveResetCount); + LogInfo("INFO: SpiDuplexFrameCount=%" PRIu64, mSpiDuplexFrameCount); + LogInfo("INFO: SpiUnresponsiveFrameCount=%" PRIu64, mSpiUnresponsiveFrameCount); + LogInfo("INFO: TransferredFrameCount=%" PRIu64, mInterfaceMetrics.mTransferredFrameCount); + LogInfo("INFO: TransferredValidFrameCount=%" PRIu64, mInterfaceMetrics.mTransferredValidFrameCount); + LogInfo("INFO: TransferredGarbageFrameCount=%" PRIu64, mInterfaceMetrics.mTransferredGarbageFrameCount); + LogInfo("INFO: RxFrameCount=%" PRIu64, mInterfaceMetrics.mRxFrameCount); + LogInfo("INFO: RxFrameByteCount=%" PRIu64, mInterfaceMetrics.mRxFrameByteCount); + LogInfo("INFO: TxFrameCount=%" PRIu64, mInterfaceMetrics.mTxFrameCount); + LogInfo("INFO: TxFrameByteCount=%" PRIu64, mInterfaceMetrics.mTxFrameByteCount); } } // namespace Posix } // namespace ot diff --git a/src/posix/platform/spi_interface.hpp b/src/posix/platform/spi_interface.hpp index 8986b5ae3..94b55074a 100644 --- a/src/posix/platform/spi_interface.hpp +++ b/src/posix/platform/spi_interface.hpp @@ -36,6 +36,7 @@ #include "openthread-posix-config.h" +#include "logger.hpp" #include "platform-posix.h" #include "lib/hdlc/hdlc.hpp" #include "lib/spinel/multi_frame_buffer.hpp" @@ -51,9 +52,11 @@ namespace Posix { * Defines an SPI interface to the Radio Co-processor (RCP). * */ -class SpiInterface : public ot::Spinel::SpinelInterface +class SpiInterface : public ot::Spinel::SpinelInterface, public Logger { public: + static const char kLogModuleName[]; ///< Module name used for logging. + /** * Initializes the object. * diff --git a/src/posix/platform/trel.cpp b/src/posix/platform/trel.cpp index ea06bca88..6b6e6c086 100644 --- a/src/posix/platform/trel.cpp +++ b/src/posix/platform/trel.cpp @@ -45,6 +45,7 @@ #include #include +#include "logger.hpp" #include "radio_url.hpp" #include "system.hpp" #include "common/code_utils.hpp" @@ -73,6 +74,53 @@ static bool sInitialized = false; static bool sEnabled = false; static int sSocket = -1; +static const char kLogModuleName[] = "Trel"; + +static void LogCrit(const char *aFormat, ...) +{ + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_CRIT, kLogModuleName, aFormat, args); + va_end(args); +} + +static void LogWarn(const char *aFormat, ...) +{ + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_WARN, kLogModuleName, aFormat, args); + va_end(args); +} + +static void LogNote(const char *aFormat, ...) +{ + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_NOTE, kLogModuleName, aFormat, args); + va_end(args); +} + +static void LogInfo(const char *aFormat, ...) +{ + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_INFO, kLogModuleName, aFormat, args); + va_end(args); +} + +static void LogDebg(const char *aFormat, ...) +{ + va_list args; + + va_start(args, aFormat); + otLogPlatArgs(OT_LOG_LEVEL_DEBG, kLogModuleName, aFormat, args); + va_end(args); +} + static const char *Ip6AddrToString(const void *aAddress) { static char string[INET6_ADDRSTRLEN]; @@ -121,7 +169,7 @@ static void PrepareSocket(uint16_t &aUdpPort) struct sockaddr_in6 sockAddr; socklen_t sockLen; - otLogDebgPlat("[trel] PrepareSocket()"); + LogDebg("PrepareSocket()"); sSocket = SocketWithCloseExec(AF_INET6, SOCK_DGRAM, 0, kSocketNonBlock); VerifyOrDie(sSocket >= 0, OT_EXIT_ERROR_ERRNO); @@ -141,7 +189,7 @@ static void PrepareSocket(uint16_t &aUdpPort) if (bind(sSocket, (struct sockaddr *)&sockAddr, sizeof(sockAddr)) == -1) { - otLogCritPlat("[trel] Failed to bind socket"); + LogCrit("Failed to bind socket"); DieNow(OT_EXIT_ERROR_ERRNO); } @@ -149,7 +197,7 @@ static void PrepareSocket(uint16_t &aUdpPort) if (getsockname(sSocket, (struct sockaddr *)&sockAddr, &sockLen) == -1) { - otLogCritPlat("[trel] Failed to get the socket name"); + LogCrit("Failed to get the socket name"); DieNow(OT_EXIT_ERROR_ERRNO); } @@ -173,7 +221,7 @@ static otError SendPacket(const uint8_t *aBuffer, uint16_t aLength, const otSock if (ret != aLength) { - otLogDebgPlat("[trel] SendPacket() -- sendto() failed errno %d", errno); + LogDebg("SendPacket() -- sendto() failed errno %d", errno); switch (errno) { @@ -194,8 +242,8 @@ static otError SendPacket(const uint8_t *aBuffer, uint16_t aLength, const otSock } exit: - otLogDebgPlat("[trel] SendPacket([%s]:%u) err:%s pkt:%s", Ip6AddrToString(&aDestSockAddr->mAddress), - aDestSockAddr->mPort, otThreadErrorToString(error), BufferToString(aBuffer, aLength)); + LogDebg("SendPacket([%s]:%u) err:%s pkt:%s", Ip6AddrToString(&aDestSockAddr->mAddress), aDestSockAddr->mPort, + otThreadErrorToString(error), BufferToString(aBuffer, aLength)); if (error != OT_ERROR_NONE) { ++sCounters.mTxFailure; @@ -222,8 +270,8 @@ static void ReceivePacket(int aSocket, otInstance *aInstance) sRxPacketLength = sizeof(sRxPacketLength); } - otLogDebgPlat("[trel] ReceivePacket() - received from [%s]:%d, id:%d, pkt:%s", Ip6AddrToString(&sockAddr.sin6_addr), - ntohs(sockAddr.sin6_port), sockAddr.sin6_scope_id, BufferToString(sRxPacketBuffer, sRxPacketLength)); + LogDebg("ReceivePacket() - received from [%s]:%d, id:%d, pkt:%s", Ip6AddrToString(&sockAddr.sin6_addr), + ntohs(sockAddr.sin6_port), sockAddr.sin6_scope_id, BufferToString(sRxPacketBuffer, sRxPacketLength)); if (sEnabled) { @@ -257,7 +305,7 @@ static void SendQueuedPackets(void) if (SendPacket(packet->mBuffer, packet->mLength, &packet->mDestSockAddr) == OT_ERROR_INVALID_STATE) { - otLogDebgPlat("[trel] SendQueuedPackets() - SendPacket() would block"); + LogDebg("SendQueuedPackets() - SendPacket() would block"); break; } @@ -287,7 +335,7 @@ static void EnqueuePacket(const uint8_t *aBuffer, uint16_t aLength, const otSock // Allocate an available packet entry (from the free packet list) // and copy the packet content into it. - VerifyOrExit(sFreeTxPacketHead != NULL, otLogWarnPlat("[trel] EnqueuePacket failed, queue is full")); + VerifyOrExit(sFreeTxPacketHead != NULL, LogWarn("EnqueuePacket failed, queue is full")); packet = sFreeTxPacketHead; sFreeTxPacketHead = sFreeTxPacketHead->mNext; @@ -309,8 +357,8 @@ static void EnqueuePacket(const uint8_t *aBuffer, uint16_t aLength, const otSock sTxPacketQueueTail = packet; } - otLogDebgPlat("[trel] EnqueuePacket([%s]:%u) - %s", Ip6AddrToString(&aDestSockAddr->mAddress), aDestSockAddr->mPort, - BufferToString(aBuffer, aLength)); + LogDebg("EnqueuePacket([%s]:%u) - %s", Ip6AddrToString(&aDestSockAddr->mAddress), aDestSockAddr->mPort, + BufferToString(aBuffer, aLength)); exit: return; @@ -518,7 +566,14 @@ void otPlatTrelResetCounters(otInstance *aInstance) void platformTrelInit(const char *aTrelUrl) { - otLogDebgPlat("[trel] platformTrelInit(aTrelUrl:\"%s\")", aTrelUrl != nullptr ? aTrelUrl : ""); + // To silence "unused function" warning. + (void)LogCrit; + (void)LogWarn; + (void)LogInfo; + (void)LogNote; + (void)LogDebg; + + LogDebg("platformTrelInit(aTrelUrl:\"%s\")", aTrelUrl != nullptr ? aTrelUrl : ""); assert(!sInitialized); @@ -545,7 +600,7 @@ void platformTrelDeinit(void) otPlatTrelDisable(nullptr); sInterfaceName[0] = '\0'; sInitialized = false; - otLogDebgPlat("[trel] platformTrelDeinit()"); + LogDebg("platformTrelDeinit()"); exit: return; diff --git a/src/posix/platform/udp.cpp b/src/posix/platform/udp.cpp index 177f4e3ef..89c6d3d8e 100644 --- a/src/posix/platform/udp.cpp +++ b/src/posix/platform/udp.cpp @@ -279,7 +279,7 @@ otError otPlatUdpBind(otUdpSocket *aUdpSocket) exit: if (error == OT_ERROR_FAILED) { - otLogCritPlat("Failed to bind UDP socket: %s", strerror(errno)); + ot::Posix::Udp::LogCrit("Failed to bind UDP socket: %s", strerror(errno)); } return error; @@ -321,7 +321,7 @@ otError otPlatUdpBindToNetif(otUdpSocket *aUdpSocket, otNetifIdentifier aNetifId #if OPENTHREAD_CONFIG_BACKBONE_ROUTER_ENABLE if (otSysGetInfraNetifName() == nullptr || otSysGetInfraNetifName()[0] == '\0') { - otLogWarnPlat("No backbone interface given, %s fails.", __func__); + ot::Posix::Udp::LogWarn("No backbone interface given, %s fails.", __func__); ExitNow(error = OT_ERROR_INVALID_ARGS); } #ifdef __linux__ @@ -378,7 +378,7 @@ otError otPlatUdpConnect(otUdpSocket *aUdpSocket) if (getsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &netifName, &len) != 0) { - otLogWarnPlat("Failed to read socket bound device: %s", strerror(errno)); + ot::Posix::Udp::LogWarn("Failed to read socket bound device: %s", strerror(errno)); len = 0; } @@ -392,7 +392,7 @@ otError otPlatUdpConnect(otUdpSocket *aUdpSocket) { fd = FdFromHandle(aUdpSocket->mHandle); VerifyOrExit(setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &netifName, len) == 0, { - otLogWarnPlat("Failed to bind to device: %s", strerror(errno)); + ot::Posix::Udp::LogWarn("Failed to bind to device: %s", strerror(errno)); error = OT_ERROR_FAILED; }); } @@ -406,8 +406,9 @@ otError otPlatUdpConnect(otUdpSocket *aUdpSocket) #ifdef __APPLE__ VerifyOrExit(errno == EAFNOSUPPORT && isDisconnect); #endif - otLogWarnPlat("Failed to connect to [%s]:%u: %s", Ip6AddressString(&aUdpSocket->mPeerName.mAddress).AsCString(), - aUdpSocket->mPeerName.mPort, strerror(errno)); + ot::Posix::Udp::LogWarn("Failed to connect to [%s]:%u: %s", + Ip6AddressString(&aUdpSocket->mPeerName.mAddress).AsCString(), + aUdpSocket->mPeerName.mPort, strerror(errno)); error = OT_ERROR_FAILED; } @@ -488,8 +489,9 @@ otError otPlatUdpJoinMulticastGroup(otUdpSocket *aUdpSocket, exit: if (error != OT_ERROR_NONE) { - otLogCritPlat("IPV6_JOIN_GROUP failed: %s", strerror(errno)); + ot::Posix::Udp::LogCrit("IPV6_JOIN_GROUP failed: %s", strerror(errno)); } + return error; } @@ -528,14 +530,17 @@ otError otPlatUdpLeaveMulticastGroup(otUdpSocket *aUdpSocket, exit: if (error != OT_ERROR_NONE) { - otLogCritPlat("IPV6_LEAVE_GROUP failed: %s", strerror(errno)); + ot::Posix::Udp::LogCrit("IPV6_LEAVE_GROUP failed: %s", strerror(errno)); } + return error; } namespace ot { namespace Posix { +const char Udp::kLogModuleName[] = "Udp"; + void Udp::Update(otSysMainloopContext &aContext) { VerifyOrExit(gNetifIndex != 0); diff --git a/src/posix/platform/udp.hpp b/src/posix/platform/udp.hpp index adc252ac4..f22a8cf22 100644 --- a/src/posix/platform/udp.hpp +++ b/src/posix/platform/udp.hpp @@ -29,14 +29,18 @@ #define OT_POSIX_PLATFORM_UDP_HPP_ #include "core/common/non_copyable.hpp" -#include "posix/platform/mainloop.hpp" + +#include "logger.hpp" +#include "mainloop.hpp" namespace ot { namespace Posix { -class Udp : public Mainloop::Source, private NonCopyable +class Udp : public Mainloop::Source, public Logger, private NonCopyable { public: + static const char kLogModuleName[]; + static Udp &Get(void); void Init(const char *aIfName);