summaryrefslogtreecommitdiff
path: root/meta-openbmc-mods/meta-common/recipes-phosphor/datetime/pch-time-sync/pch-time-sync.cpp
blob: 454bdc1db8c9432d8f4b4e8e01edf52cdefb7bfb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/* Copyright 2019 Intel
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include <systemd/sd-journal.h>
#include <time.h>

#include <boost/asio/io_service.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <chrono>
#include <filesystem>
#include <iostream>
#include <phosphor-logging/log.hpp>
#include <sdbusplus/asio/object_server.hpp>
extern "C" {
#include <i2c/smbus.h>
#include <linux/i2c-dev.h>
}

static constexpr uint32_t syncIntervalNormalMS = 60000;
static constexpr uint32_t syncIntervalFastMS = (syncIntervalNormalMS / 2);
static constexpr uint32_t syncIntervalBootMS = 5000;

static uint32_t syncIntervalMS = syncIntervalNormalMS;

// will update bmc time if the time difference beyond this value
static constexpr uint8_t timeDiffAllowedSecond = 1;
static uint8_t pchDevI2cBusNo = 0;
static uint8_t pchDevI2cSlaveAddr = 0;
static bool getPCHI2cAddrFlag = false;
static constexpr const char* clockFile = "/var/lib/systemd/timesync/clock";
static inline uint8_t bcd2Decimal(uint8_t hex)
{
    uint8_t dec = ((hex & 0xF0) >> 4) * 10 + (hex & 0x0F);
    return dec;
}

class I2CFile
{
  private:
    int fd = -1;

  public:
    I2CFile(const int& i2cBus, const int& slaveAddr, const int& flags)
    {
        std::string i2cDev = "/dev/i2c-" + std::to_string(i2cBus);

        fd = open(i2cDev.c_str(), flags);
        if (fd < 0)
        {
            throw std::runtime_error("Unable to open i2c device.");
        }

        if (ioctl(fd, I2C_SLAVE_FORCE, slaveAddr) < 0)
        {
            close(fd);
            fd = -1;
            throw std::runtime_error("Unable to set i2c slave address.");
        }
    }

    uint8_t i2cReadByteData(const uint8_t& offset)
    {
        int ret = i2c_smbus_read_byte_data(fd, offset);

        if (ret < 0)
        {
            throw std::runtime_error("i2c read failed");
        }
        return static_cast<uint8_t>(ret);
    }

    ~I2CFile()
    {
        if (!(fd < 0))
        {
            close(fd);
        }
    }
};

static void getPCHI2cAddr(std::shared_ptr<sdbusplus::asio::connection>& conn,
                          const std::string& service, const std::string& object,
                          const std::string& interface)
{
    conn->async_method_call(
        [](boost::system::error_code ec,
           const std::vector<
               std::pair<std::string, std::variant<std::string, uint64_t>>>&
               propertiesList) {
            if (ec)
            {
                phosphor::logging::log<phosphor::logging::level::ERR>(
                    "DBUS response error: cannot get I2c address of PCH timer",
                    phosphor::logging::entry("ECVALUE=%x", ec.value()),
                    phosphor::logging::entry("ECMESSAGE=%s",
                                             ec.message().c_str()));
                return;
            }
            const uint64_t* i2cBusNoValue = nullptr;
            const uint64_t* i2cSlaveAddrValue = nullptr;
            for (const auto& property : propertiesList)
            {

                if (property.first == "PchSmbusSlaveI2cBus")
                {
                    i2cBusNoValue = std::get_if<uint64_t>(&property.second);
                }
                if (property.first == "PchSmbusSlaveI2cAddress")
                {
                    i2cSlaveAddrValue = std::get_if<uint64_t>(&property.second);
                }
            }
            if ((i2cBusNoValue != nullptr) && (i2cSlaveAddrValue != nullptr))
            {
                pchDevI2cBusNo = static_cast<uint8_t>(*i2cBusNoValue);
                pchDevI2cSlaveAddr = static_cast<uint8_t>(*i2cSlaveAddrValue);
                getPCHI2cAddrFlag = true;
            }
        },
        service, object, "org.freedesktop.DBus.Properties", "GetAll",
        interface);
}

static void
    getPCHTimerConfiguration(std::shared_ptr<sdbusplus::asio::connection>& conn)
{
    conn->async_method_call(
        [&conn](
            boost::system::error_code ec,
            const std::vector<std::pair<
                std::string,
                std::vector<std::pair<std::string, std::vector<std::string>>>>>&
                subtree) {
            if (ec)
            {
                phosphor::logging::log<phosphor::logging::level::ERR>(
                    "DBUS response error:cannot get PCH configuration",
                    phosphor::logging::entry("ECVALUE=%x", ec.value()),
                    phosphor::logging::entry("ECMESSAGE=%s",
                                             ec.message().c_str()));
                return;
            }
            if (subtree.empty())
            {
                phosphor::logging::log<phosphor::logging::level::ERR>(
                    "subtree empty");
                return;
            }
            getPCHI2cAddr(conn, subtree[0].second[0].first, subtree[0].first,
                          "xyz.openbmc_project.Configuration.PchSmbusSlave");
            return;
        },
        "xyz.openbmc_project.ObjectMapper",
        "/xyz/openbmc_project/object_mapper",
        "xyz.openbmc_project.ObjectMapper", "GetSubTree",
        "/xyz/openbmc_project/", 0,
        std::array<const char*, 1>{
            "xyz.openbmc_project.Configuration.PchSmbusSlave"});

    return;
}

class PCHSync
{
  private:
    bool getPCHDate(uint8_t& year, uint8_t& month, uint8_t& day, uint8_t& hour,
                    uint8_t& minute, uint8_t& second)
    {
        try
        {
            constexpr uint8_t pchDevRegRTCYear = 0x0f;
            constexpr uint8_t pchDevRegRTCMonth = 0x0e;
            constexpr uint8_t pchDevRegRTCDay = 0x0d;
            constexpr uint8_t pchDevRegRTCHour = 0x0b;
            constexpr uint8_t pchDevRegRTCMinute = 0x0a;
            constexpr uint8_t pchDevRegRTCSecond = 0x09;
            I2CFile pchDev(pchDevI2cBusNo, pchDevI2cSlaveAddr,
                           O_RDWR | O_CLOEXEC);
            year = pchDev.i2cReadByteData(pchDevRegRTCYear);
            year = bcd2Decimal(year);
            if (year > 99)
            {
                return false;
            }

            month = pchDev.i2cReadByteData(pchDevRegRTCMonth);
            month = bcd2Decimal(month);
            if ((month < 1) || (month > 12))
            {
                return false;
            }

            day = pchDev.i2cReadByteData(pchDevRegRTCDay);
            day = bcd2Decimal(day);
            if ((day < 1) || (day > 31))
            {
                return false;
            }

            hour = pchDev.i2cReadByteData(pchDevRegRTCHour);
            hour = bcd2Decimal(hour);
            if (hour >= 24)
            {
                return false;
            }

            minute = pchDev.i2cReadByteData(pchDevRegRTCMinute);
            minute = bcd2Decimal(minute);
            if (minute >= 60)
            {
                return false;
            }

            second = pchDev.i2cReadByteData(pchDevRegRTCSecond);
            second = bcd2Decimal(second);
            if (second >= 60)
            {
                return false;
            }
        }
        catch (const std::exception& e)
        {
            return false;
        }

        return true;
    }

    bool getSystemTime(time_t& timeSeconds)
    {
        struct timespec sTime = {0};
        int ret = 0;

        ret = clock_gettime(CLOCK_REALTIME, &sTime);

        if (ret != 0)
        {
            return false;
        }
        timeSeconds = sTime.tv_sec;
        return true;
    }

    bool updateClockFileTimestamp()
    {
        if (!std::filesystem::exists(clockFile))
        {
            phosphor::logging::log<phosphor::logging::level::WARNING>(
                "The systemd timestamp synchronization file doesn't exist: ",
                phosphor::logging::entry("PATHNAME=%s", clockFile));
            return false;
        }
        int rc = utimensat(AT_FDCWD, clockFile, nullptr, 0);
        if (rc)
        {
            phosphor::logging::log<phosphor::logging::level::ERR>(
                "utimensat systemd timestamp synchronization file fail: ",
                phosphor::logging::entry("PATHNAME=%s", clockFile),
                phosphor::logging::entry("ERRCODE=%x", errno));
            return false;
        }
        return true;
    }
    bool setSystemTime(uint32_t timeSeconds)
    {
        struct timespec sTime = {0};
        int ret = 0;

        sTime.tv_sec = timeSeconds;
        sTime.tv_nsec = 0;

        ret = clock_settime(CLOCK_REALTIME, &sTime);

        return (ret == 0);
    }

    bool updateBMCTime()
    {
        int ret = 0;
        time_t BMCTimeSeconds = 0;
        time_t PCHTimeSeconds = 0;
        struct tm tm = {0};

        // get PCH and system time

        if (!getPCHDate(year, month, day, hour, minute, second))
        {
            return false;
        };
        if (!getSystemTime(BMCTimeSeconds))
        {
            return false;
        }
        // fix error when year is set to 2000-2009.
        std::string dateString =
            std::to_string(2000 + year) + "-" + std::to_string(month) + "-" +
            std::to_string(day) + " " + std::to_string(hour) + ":" +
            std::to_string(minute) + ":" + std::to_string(second);

        strptime(dateString.c_str(), "%Y-%m-%d %H:%M:%S", &tm);

        PCHTimeSeconds = mktime(&tm);
        if (PCHTimeSeconds == -1)
        {
            return false;
        }

        if (std::abs(PCHTimeSeconds - BMCTimeSeconds) > timeDiffAllowedSecond)
        {
            if (!setSystemTime(PCHTimeSeconds))
            {
                return false;
            }
            char newDateString[32] = {0};
            strftime(newDateString, sizeof(newDateString), "%F %T",
                     gmtime(&PCHTimeSeconds));

            struct tm* timeinfo;
            char oldDateString[32] = {0};
            timeinfo = gmtime(&BMCTimeSeconds);
            strftime(oldDateString, sizeof(oldDateString), "%F %T", timeinfo);

            // Log event about BMC time update via PCH
            sd_journal_send(
                "MESSAGE=BMC time updated via PCH: New time=%s, Old time=%s",
                newDateString, oldDateString, "PRIORITY=%i", LOG_INFO,
                "REDFISH_MESSAGE_ID=%s", "OpenBMC.0.1.BMCTimeUpdatedViaHost",
                "REDFISH_MESSAGE_ARGS=%s,%s", newDateString, oldDateString,
                NULL);
        }

        // During the boot time, systemd-timesyncd.service checks
        // "/var/lib/systemd/timesync/clock" and updates the system time with
        // the timestamp of the file
        if (!updateClockFileTimestamp())
        {
            return false;
        }

        return true;
    }

    void startSyncTimer(std::shared_ptr<sdbusplus::asio::connection>& conn)
    {
        // retry 10 times (10 * 5s = 50s ) to get the pch timer
        // configuration.
        static uint8_t retrytimes = 10;
        if (!getPCHI2cAddrFlag)
        {
            if (retrytimes == 0)
            {
                phosphor::logging::log<phosphor::logging::level::ERR>(
                    "Get pch timer configuration fail");
                return;
            }
            syncIntervalMS = syncIntervalBootMS;
            getPCHTimerConfiguration(conn);
            retrytimes--;
        }
        else
        {
            if (updateBMCTime())
            {
                syncIntervalMS = syncIntervalNormalMS;
            }
            else
            {
                phosphor::logging::log<phosphor::logging::level::ERR>(
                    "Update BMC time Fail");
                syncIntervalMS = syncIntervalFastMS;
            }
        }

        syncTimer->expires_after(std::chrono::milliseconds(syncIntervalMS));
        syncTimer->async_wait(
            [this, &conn](const boost::system::error_code& ec) {
                if (ec)
                {
                    phosphor::logging::log<phosphor::logging::level::ERR>(
                        "Timer cancelled",
                        phosphor::logging::entry("ECVALUE=%x", ec.value()),
                        phosphor::logging::entry("ECMESSAGE=%s",
                                                 ec.message().c_str()));
                    return;
                }
                startSyncTimer(conn);
            });
    }

    std::unique_ptr<boost::asio::steady_timer> syncTimer;
    uint8_t year, month, day, hour, minute, second;

  public:
    PCHSync(boost::asio::io_service& io,
            std::shared_ptr<sdbusplus::asio::connection>& conn)
    {
        syncTimer = std::make_unique<boost::asio::steady_timer>(io);
        startSyncTimer(conn);
    }

    ~PCHSync() = default;
};

int main(int argc, char** argv)
{
    boost::asio::io_service io;
    std::shared_ptr<sdbusplus::asio::connection> conn =
        std::make_shared<sdbusplus::asio::connection>(io);
    sdbusplus::asio::object_server server =
        sdbusplus::asio::object_server(conn);
    PCHSync pchSyncer(io, conn);

    phosphor::logging::log<phosphor::logging::level::INFO>(
        "Starting PCH time sync service");

    io.run();
    return 0;
}