Eine aufbereitete Darstellung der Quelle

 
     
 
 
 
Anforderungen  |   Konzepte  |   Entwurf  |   Entwicklung  |   Qualitätssicherung  |   Lebenszyklus  |   Steuerung


Quelle  log0log.cc   Sprache: C

 

/*****************************************************************************

Copyright (c) 1995, 2017, Oracle and/or its affiliates. All Rights Reserved.
Copyright (c) 2014, 2023, MariaDB Corporation.

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA

*****************************************************************************/


/**************************************************//**
@file log/log0log.cc
Database log

Created 12/9/1995 Heikki Tuuri
*******************************************************/

#include "univ.i"
#include <debug_sync.h>
#include <my_service_manager.h>

#include "log0log.h"
#include "log0crypt.h"
#include "buf0buf.h"
#include "buf0flu.h"
#include "lock0lock.h"
#include "log0recv.h"
#include "fil0fil.h"
#include "dict0stats_bg.h"
#include "srv0srv.h"
#include "srv0start.h"
#include "trx0sys.h"
#include "trx0trx.h"
#include "trx0roll.h"
#include "srv0mon.h"
#include "buf0dump.h"
#include "log0sync.h"
#include "log.h"
#include "tpool.h"

/*
General philosophy of InnoDB redo-logs:

Every change to a contents of a data page must be done
through mtr_t, and mtr_t::commit() will write log records
to the InnoDB redo log. */


alignas(CPU_LEVEL1_DCACHE_LINESIZE)
static group_commit_lock flush_lock;
alignas(CPU_LEVEL1_DCACHE_LINESIZE)
static group_commit_lock write_lock;

/** Redo log system */
log_t log_sys;

/* Margins for free space in the log buffer after a log entry is catenated */
#define LOG_BUF_FLUSH_RATIO 2
#define LOG_BUF_FLUSH_MARGIN ((4 * 4096) /* cf. log_t::append_prepare() */ \
     + (4U << srv_page_size_shift))

void log_t::set_capacity() noexcept
{
 ut_ad(log_sys.latch_have_wr());
 /* Margin for the free space in the smallest log, before a new query
step which modifies the database, is started */


 lsn_t smallest_capacity = srv_log_file_size - log_t::START_OFFSET;
 /* Add extra safety */
 smallest_capacity -= smallest_capacity / 10;

 lsn_t margin = smallest_capacity - (48 << srv_page_size_shift);
 margin -= margin / 10; /* Add still some extra safety */

 log_sys.log_capacity = smallest_capacity;

 log_sys.max_modified_age_async = margin - margin / 8;
 log_sys.max_checkpoint_age = margin;
}

void log_t::create() noexcept
{
  ut_ad(this == &log_sys);
  ut_ad(!is_initialised());

  latch.init();
  write_lsn_offset= 0;
  /* LSN 0 and 1 are reserved; @see buf_page_t::oldest_modification_ */
  base_lsn.store(FIRST_LSN, std::memory_order_relaxed);
  flushed_to_disk_lsn.store(FIRST_LSN, std::memory_order_relaxed);
  need_checkpoint.store(false, std::memory_order_relaxed);
  write_lsn= FIRST_LSN;

  ut_ad(!checkpoint_buf);
  ut_ad(!buf);
  ut_ad(!flush_buf);
  ut_ad(!writer);

#ifdef HAVE_PMEM
  resize_wrap_mutex.init();
#endif

  last_checkpoint_lsn= 0;
  first_lsn= FIRST_LSN;
  end_lsn= FIRST_LSN;
  log_capacity= 0;
  max_modified_age_async= 0;
  max_checkpoint_age= 0;

  ut_ad(is_initialised());
}

dberr_t log_file_t::close() noexcept
{
  ut_a(is_opened());

  if (!os_file_close_func(m_file))
    return DB_ERROR;

  m_file= OS_FILE_CLOSED;
  return DB_SUCCESS;
}

__attribute__((warn_unused_result))
dberr_t log_file_t::read(os_offset_t offset, span<byte> buf) noexcept
{
  ut_ad(is_opened());
  byte *data= buf.data();
  size_t size= buf.size();
  ut_ad(size);
  ssize_t s;

  for (;;)
  {
    s= IF_WIN(tpool::pread(m_file, data, size, offset),
              pread(m_file, data, size, offset));
    if (UNIV_UNLIKELY(s <= 0))
      break;
    size-= size_t(s);
    if (!size)
      return DB_SUCCESS;
    offset+= s;
    data+= s;
    ut_a(size < buf.size());
  }

  sql_print_error("InnoDB: pread(log) returned %zd,"
                  " operating system error %u",
                  s, unsigned(IF_WIN(GetLastError(), errno)));
  return DB_IO_ERROR;
}

void log_file_t::write(os_offset_t offset, span<const byte> buf) noexcept
{
  ut_ad(is_opened());
  const byte *data= buf.data();
  size_t size= buf.size();
  ut_ad(size);
  ssize_t s;

  for (;;)
  {
    s= IF_WIN(tpool::pwrite(m_file, data, size, offset),
              pwrite(m_file, data, size, offset));
    if (UNIV_UNLIKELY(s <= 0))
      break;
    ut_ad(size >= size_t(s));
    size-= size_t(s);
    if (!size)
      return;
    offset+= s;
    data+= s;
    /* Out-of-bounds buffer access should make pwrite(2) report EFAULT */
    ut_ad(offset + size < buf.size());
  }

  sql_print_error("[FATAL] InnoDB: pwrite(log) returned %zd,"
                  " operating system error %u",
                  s, unsigned(IF_WIN(GetLastError(), errno)));
  abort();
}

# ifdef HAVE_PMEM
#  include "cache.h"
# endif

/** Attempt to memory map a file.
@param file        log file handle
@param size        file size
@param access      how to access the file
@return pointer to memory mapping
@retval MAP_FAILED  if the memory cannot be mapped */

static void *log_mmap(os_file_t file,
# ifdef HAVE_PMEM
                      bool &is_pmem, /*!< whether the file is on pmem */
# endif
                      os_offset_t size, log_t::log_access access) noexcept
{
#if SIZEOF_SIZE_T < 8
  if (size != os_offset_t(size_t(size)))
    return MAP_FAILED;
#endif
#ifndef HAVE_PMEM
  if (!log_sys.log_mmap)
    /* If support for persistent memory (Linux: mount -o dax) is enabled,
    we always attempt to open a MAP_SYNC memory mapping to the log.
    This mapping will be read-only during crash recovery, and read-write
    during normal operation.

    A regular read-only memory mapping may be attempted if
    innodb_log_file_mmap=ON. This may benefit mariadb-backup
    and crash recovery. */

    return MAP_FAILED;
#endif

  /* For now, InnoDB does not support memory-mapped writes to
  a regular log file.

  If PMEM is supported, the initially attempted memory mapping may
  be read-write, but the fallback will be read-only.

  The mapping will always be read-only if innodb_read_only=ON or
  if mariadb-backup is running in any other mode than --prepare --export. */

  ut_ad(access == log_t::READ_ONLY ||
        (!srv_read_only_mode && srv_operation < SRV_OPERATION_BACKUP));

#ifdef _WIN32
  if (access < log_t::READ_ONLY);
  else if (HANDLE h=
           CreateFileMappingA(file, nullptr, PAGE_READONLY,
                              DWORD(size >> 32), DWORD(size), nullptr))
  {
    if (h != INVALID_HANDLE_VALUE)
    {
      void *ptr= MapViewOfFileEx(h, FILE_MAP_READ, 0, 0, size, nullptr);
      CloseHandle(h);
      if (ptr)
        return ptr;
    }
  }
  return MAP_FAILED;
#else
  int flags=
# ifdef HAVE_PMEM
    MAP_SHARED_VALIDATE | MAP_SYNC,
# else
    MAP_SHARED,
# endif
    prot= PROT_READ;

# ifdef HAVE_PMEM
  if (access < log_t::READ_ONLY)
    prot= PROT_READ | PROT_WRITE;

#  ifdef __linux__ /* On Linux, we pretend that /dev/shm is PMEM */
remap:
#  endif
# else
  if (access < log_t::READ_ONLY)
    return MAP_FAILED;
# endif

  void *ptr= my_mmap(0, size_t(size), prot, flags, file, 0);

#  ifdef HAVE_PMEM
  is_pmem= ptr != MAP_FAILED;
#  endif

  if (ptr != MAP_FAILED)
    return ptr;

#  ifdef HAVE_PMEM
#   ifdef __linux__ /* On Linux, we pretend that /dev/shm is PMEM */
  if (flags != MAP_SHARED && srv_operation < SRV_OPERATION_BACKUP)
  {
    flags= MAP_SHARED;
    struct stat st;
    if (!fstat(file, &st))
    {
      const auto st_dev= st.st_dev;
      if (!stat("/dev/shm", &st))
      {
        is_pmem= st.st_dev == st_dev;
        if (is_pmem)
          goto remap;
      }
    }
  }
#   endif /* __linux__ */
  if (access == log_t::READ_ONLY && log_sys.log_mmap)
    ptr= my_mmap(0, size_t(size), PROT_READ, MAP_SHARED, file, 0);
#  endif /* HAVE_PMEM */
  return ptr;
# endif
}

#if defined __linux__ || defined _WIN32
/** Display a message about opening the log */
ATTRIBUTE_COLD static void log_file_message() noexcept
{
  sql_print_information("InnoDB: %s (block size=%u bytes)",
                        log_sys.log_mmap
                        ? (log_sys.log_buffered
                           ? "Memory-mapped log"
                           : "Memory-mapped unbuffered log")
                        :
                        log_sys.log_buffered
                        ? "Buffered log writes"
                        : "File system buffers for log disabled",
                        log_sys.write_size);
}
#else
static inline void log_file_message() noexcept {}
#endif

bool log_t::attach(log_file_t file, os_offset_t size,
                   log_t::log_access access) noexcept
{
  ut_ad(file.is_opened());
  ut_ad(!log.is_opened() ||
        (log.m_file == file.m_file && (archive || recv_sys.was_archive)));
  ut_ad(archive || !resize_log.is_opened());
  ut_ad(archive || !buf);
  ut_ad(archive || !resize_buf);
  ut_ad(archive || !flush_buf);
  ut_ad(archive || !resize_flush_buf);
  ut_ad(!size || size >= START_OFFSET + SIZE_OF_FILE_CHECKPOINT);
  ut_ad(!writer);

  file_size= size; /* for HAVE_PMEM, clear_mmap() will assign buf_size later */

  if (size)
  {
# ifdef HAVE_PMEM
    bool is_pmem;
    void *ptr= ::log_mmap(file.m_file, is_pmem, size, access);
# else
    void *ptr= ::log_mmap(file.m_file, size, access);
# endif
    if (ptr != MAP_FAILED)
    {
      if (archive)
        log= file;
      else
        file.close();
# ifdef HAVE_PMEM
      this->is_pmem= is_pmem;
      if (is_pmem)
      {
        log_buffered= false;
        log_maybe_unbuffered= true;
      }
# endif
      IF_WIN(,mprotect(ptr, size_t(size), PROT_READ));
      buf= static_cast<byte*>(ptr);
      writer_update(false);
# ifdef HAVE_PMEM
      if (is_pmem)
        goto func_exit_no_message;
# endif
      goto func_exit;
    }

    if (buf)
    {
      ut_ad(archive);
      log= file;
      log_mmap= false;
      goto func_exit_no_message;
    }
  }
  else
    ut_ad(!archive);

  log= file;
  log_mmap= false;
  buf= static_cast<byte*>(ut_malloc_dontdump(buf_size, PSI_INSTRUMENT_ME));
  if (!buf)
  {
  alloc_fail:
    base_lsn.store(0, std::memory_order_relaxed);
    sql_print_error("InnoDB: Cannot allocate memory;"
                    " too large innodb_log_buffer_size?");
    return false;
  }
  flush_buf= static_cast<byte*>(ut_malloc_dontdump(buf_size,
                                                   PSI_INSTRUMENT_ME));
  if (!flush_buf)
  {
  alloc_fail2:
    ut_free_dodump(buf, buf_size);
    buf= nullptr;
    goto alloc_fail;
  }

  ut_ad(ut_is_2pow(write_size));
  ut_ad(write_size >= 512);
  ut_ad(write_size <= 4096);
  checkpoint_buf= static_cast<byte*>(aligned_malloc(write_size, write_size));
  if (!checkpoint_buf)
  {
  alloc_fail3:
    ut_free_dodump(flush_buf, buf_size);
    flush_buf= nullptr;
    goto alloc_fail2;
  }

  TRASH_ALLOC(buf, buf_size);
  TRASH_ALLOC(flush_buf, buf_size);
  memset_aligned<512>(checkpoint_buf, 0, write_size);
  if (archive)
  {
    const size_t offset=
      std::min(size_t(START_OFFSET - 8), size_t(next_checkpoint_no * 8));
    const size_t bs{write_size}, bs_1{bs - 1}, tail{offset & bs_1};
    if (!tail);
    else if (file.read(offset & ~bs_1, {checkpoint_buf, bs}) != DB_SUCCESS)
    {
      aligned_free(checkpoint_buf);
      checkpoint_buf= nullptr;
      goto alloc_fail3;
    }
    else
      /* Clear any garbage that may have been left behind by a crash
      during write_checkpoint() or set_archive(). See also clear_mmap(). */

      memset(checkpoint_buf + tail, 0, bs - tail);
  }

 func_exit:
  log_file_message();
 func_exit_no_message:
  writer_update(false);
  return true;
}

/** Write a log file header.
@param buf        log header buffer
@param lsn        log sequence number corresponding to log_sys.START_OFFSET
@param encrypted  whether the log is encrypted */

void log_t::header_write(byte *buf, lsn_t lsn, bool encrypted) noexcept
{
  mach_write_to_4(my_assume_aligned<4>(buf) + LOG_HEADER_FORMAT,
                  log_sys.format);
  mach_write_to_8(my_assume_aligned<8>(buf + LOG_HEADER_START_LSN), lsn);

#if defined __GNUC__ && __GNUC__ > 7
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wstringop-truncation"
#endif
  strncpy(reinterpret_cast<char*>(buf) + LOG_HEADER_CREATOR,
          "MariaDB " PACKAGE_VERSION,
          LOG_HEADER_CREATOR_END - LOG_HEADER_CREATOR);
#if defined __GNUC__ && __GNUC__ > 7
# pragma GCC diagnostic pop
#endif

  if (encrypted)
    log_crypt_write_header(buf + LOG_HEADER_CREATOR_END, false);
  mach_write_to_4(my_assume_aligned<4>(508 + buf), my_crc32c(0, buf, 508));
}

void log_t::create(lsn_t lsn) noexcept
{
  ut_ad(latch_have_wr());
  ut_ad(!recv_no_log_write);
  ut_ad(is_latest());
  ut_ad(this == &log_sys);

  next_checkpoint_no= uint16_t(4 * is_encrypted());
  write_lsn_offset= 0;
  base_lsn.store(lsn, std::memory_order_relaxed);
  flushed_to_disk_lsn.store(lsn, std::memory_order_relaxed);
  first_lsn= lsn;
  end_lsn= lsn;
  write_lsn= lsn;
  if (!archived_lsn)
    archived_lsn= lsn;

  last_checkpoint_lsn= lsn;

  DBUG_PRINT("ib_log", ("write header " LSN_PF, lsn));

#ifdef HAVE_PMEM
  if (is_mmap())
  {
    ut_ad(is_mmap_writeable());
    ut_ad(is_opened() == archive);
    mprotect(buf, size_t(file_size), PROT_READ | PROT_WRITE);
    if (archive)
      goto create_archive_header;
    memset_aligned<4096>(buf, 0, 4096);
    header_write(buf, lsn, is_encrypted());
    pmem_persist(buf, 512);
  }
  else
#endif
  {
    ut_ad(!is_mmap());
    memset_aligned<4096>(flush_buf, 0, buf_size);
    memset_aligned<4096>(buf, 0, buf_size);
    if (!archive)
    {
      header_write(buf, lsn, is_encrypted());
      log.write(0, {buf, 4096});
      memset_aligned<512>(buf, 0, 512);
    }
    else
#ifdef HAVE_PMEM
    create_archive_header:
#endif
      if (is_encrypted())
        log_crypt_write_header(buf, true);
  }
}

ATTRIBUTE_COLD static void log_close_failed(dberr_t err) noexcept
{
  ib::fatal() << "closing log failed: " << err;
}

void log_t::close_file(bool really_close) noexcept
{
  if (is_mmap())
  {
    ut_ad(!checkpoint_buf);
    ut_ad(!flush_buf);
    if (buf)
    {
      my_munmap(buf, size_t(file_size));
      buf= nullptr;
    }
  }
  else
  {
    ut_ad(!buf == !flush_buf);
    ut_ad(!buf == !checkpoint_buf);
    if (buf)
    {
      ut_free_dodump(buf, buf_size);
      buf= nullptr;
      ut_free_dodump(flush_buf, buf_size);
      flush_buf= nullptr;
    }
    aligned_free(checkpoint_buf);
    checkpoint_buf= nullptr;
  }

  writer= nullptr;

  if (really_close)
    if (is_opened())
      if (const dberr_t err= log.close())
        log_close_failed(err);
}

/** @return the current log sequence number (may be stale) */
lsn_t log_get_lsn() noexcept
{
  log_sys.latch.wr_lock();
  lsn_t lsn= log_sys.get_lsn();
  log_sys.latch.wr_unlock();
  return lsn;
}

/** Acquire all latches that protect the log. */
static void log_resize_acquire() noexcept
{
#ifdef HAVE_PMEM
  if (!log_sys.is_mmap())
#endif
  {
    while (flush_lock.acquire(log_get_lsn() + 1, nullptr) !=
           group_commit_lock::ACQUIRED);
    while (write_lock.acquire(log_get_lsn() + 1, nullptr) !=
           group_commit_lock::ACQUIRED);
  }

  log_sys.latch.wr_lock();
}

static void log_resize_release_locks() noexcept
{
#ifdef HAVE_PMEM
  if (!log_sys.is_mmap())
#endif
  {
    lsn_t lsn1= write_lock.release(write_lock.value());
    lsn_t lsn2= flush_lock.release(flush_lock.value());
    if (lsn1 || lsn2)
      log_write_up_to(std::max(lsn1, lsn2), true, nullptr);
  }
}

/** Release the latches that protect the log. */
void log_resize_release() noexcept
{
  log_sys.latch.wr_unlock();
  log_resize_release_locks();
}

#if defined __linux__ || defined _WIN32
/** Try to enable or disable file system caching (update log_buffered) */
void log_t::set_buffered(bool buffered) noexcept
{
  if (!log_maybe_unbuffered ||
#ifdef HAVE_PMEM
      is_mmap() ||
#endif
      recv_sys.rpo ||
      high_level_read_only)
    return;
  log_resize_acquire();
  if (!resize_in_progress() && is_opened() && !resize_log.is_opened() &&
      bool(log_buffered) != buffered)
  {
    if (const dberr_t err= log.close())
      log_close_failed(err);
    log_buffered= buffered;
    bool success;
    log.m_file= os_file_create_func(get_path().c_str(),
                                    OS_FILE_OPEN, OS_LOG_FILE,
                                    false, &success);
    ut_a(log.m_file != OS_FILE_CLOSED);
    log_file_message();
  }
  log_resize_release();
}
#endif

  /** Try to enable or disable durable writes (update log_write_through) */
void log_t::set_write_through(bool write_through)
{
  if (is_mmap() || high_level_read_only || recv_sys.rpo)
    return;
  log_resize_acquire();
  if (!resize_in_progress() && is_opened() && !resize_log.is_opened() &&
      bool(log_write_through) != write_through)
  {
    os_file_close_func(log.m_file);
    log= OS_FILE_CLOSED;
    log_write_through= write_through;
    bool success;
    log.m_file= os_file_create_func(get_path().c_str(),
                                    OS_FILE_OPEN, OS_LOG_FILE,
                                    false, &success);
    ut_a(log.is_opened());
    sql_print_information(log_write_through
                          ? "InnoDB: Log writes write through"
                          : "InnoDB: Log writes may be cached");
  }
  log_resize_release();
}

/** Rewrite the log file header in set_archive()
@param archive  the new value of innodb_log_archive */

void log_t::header_rewrite(my_bool archive) noexcept
{
  ut_ad(!resize_buf);
  ut_ad(this->archive == !archive);

  /* We will rewrite the log file header while the file
  name is not ib_logfile0. That is, the archived log file
  recovery will accept both the circular and the archived
  format for the last file. */

  sql_print_information("InnoDB: setting innodb_log_archive=%u"
                        " at innodb_log_recovery_start=" LSN_PF,
                        archive, end_lsn);

  byte* c= checkpoint_buf;
  ut_ad(end_lsn >= first_lsn);
  ut_ad(!archive || end_lsn <= first_lsn + ~0U);
  ut_ad(format == (is_encrypted() ? FORMAT_ENC_11 : FORMAT_10_8));
#ifdef HAVE_PMEM
  if (!c)
  {
    ut_ad(is_mmap());
    ut_ad(is_mmap_writeable());
    if (!archive)
    {
      memset_aligned<512>(buf + 512, 0, START_OFFSET - 512);
      c= buf + CHECKPOINT_1;
      mach_write_to_8(my_assume_aligned<8>(c), last_checkpoint_lsn);
      mach_write_to_8(my_assume_aligned<8>(c + 8), end_lsn);
      mach_write_to_4(my_assume_aligned<4>(c + 60), my_crc32c(0, c, 60));
      pmem_persist(buf + 512, START_OFFSET - 512);
      memset_aligned<512>(buf, 0, 512);
      header_write(buf, first_lsn, is_encrypted());
      memset_aligned<512>(buf + 512, 0, CHECKPOINT_1 - 512);
      pmem_persist(buf, CHECKPOINT_1);
    }
    else
    {
      next_checkpoint_no= uint16_t(4 * is_encrypted() + 1);
      uint64_t *C= reinterpret_cast<uint64_t*>(buf);
      const uint64_t d{my_htobe64(end_lsn - first_lsn + START_OFFSET)};
      if (!is_encrypted())
      {
        *C= d;
        memset_aligned<8>(buf + 8, 0, 64 - 8);
      }
      else
      {
        log_crypt_write_header(buf, true);
        C[4]= d;
        memset_aligned<8>(buf + 40, 0, 64 - 40);
      }
      pmem_persist(buf, 64);
      memset_aligned<64>(buf + 64, 0, START_OFFSET - 64);
      pmem_persist(buf, START_OFFSET);
    }
    return;
  }
#endif
  memset_aligned<512>(c, 0, write_size);

  if (!archive)
  {
    uint64_t *C= reinterpret_cast<uint64_t*>(c);
    C[0]= my_htobe64(last_checkpoint_lsn);
    C[1]= my_htobe64(end_lsn);
    *reinterpret_cast<uint32_t*>(c + 60)= my_htobe32(my_crc32c(0, c, 60));
    log.write(CHECKPOINT_1, {c, write_size});
    os_file_flush(log.m_file);
    memset_aligned<512>(c, 0, write_size);
    for (size_t offset= CHECKPOINT_1; (offset+= write_size) < START_OFFSET;)
      log.write(offset, {c, write_size});
    header_write(c, first_lsn, is_encrypted());
    if (write_size > 512)
      memset_aligned<512>(c + 512, 0, write_size - 512);
    log.write(0, {c, write_size});
    os_file_flush(log.m_file);
    memset_aligned<512>(c, 0, write_size);
    for (size_t offset= 0; (offset+= write_size) < CHECKPOINT_1;)
      log.write(offset, {c, write_size});
  }
  else
  {
    next_checkpoint_no= uint16_t(4 * is_encrypted() + 1);
    const uint64_t d{my_htobe64(end_lsn - first_lsn + START_OFFSET)};
    uint64_t *C= reinterpret_cast<uint64_t*>(c);
    if (!is_encrypted())
      *C= d;
    else
    {
      log_crypt_write_header(c, true);
      C[4]= d;
    }
    log.write(0, {c, write_size});
    os_file_flush(log.m_file);
    for (size_t offset= 0; (offset+= write_size) < START_OFFSET;)
      log.write(offset, {field_ref_zero, write_size});
  }

  os_file_flush(log.m_file);
}

/** SET GLOBAL innodb_log_archive
@param archive  the new value of innodb_log_archive
@param thd      SQL connection */

void log_t::set_archive(my_bool archive, THD *thd) noexcept
{
  if (UNIV_UNLIKELY(recv_sys.rpo != 0))
  {
    my_error(ER_INNODB_READ_ONLY, MYF(0));
    return;
  }

  thd_wait_begin(thd, THD_WAIT_DISKIO);
  tpool::tpool_wait_begin();
  lsn_t wait_lsn;

  for (;;)
  {
    wait_lsn= 0;
    IF_WIN(log_resize_acquire(), latch.wr_lock());
    if (resize_in_progress())
    {
      my_printf_error(ER_WRONG_USAGE,
                      "SET GLOBAL innodb_log_file_size is in progress",
                      MYF(0));
      break;
    }
    if (archive == this->archive)
      break;
    if (thd_kill_level(thd))
      break;

    if (resize_log.is_opened())
    {
      /* Prevent a race condition with write_checkpoint() */
#ifdef HAVE_PMEM
    retry:
#endif
      wait_lsn= 0;
    retry_after_checkpoint:
      IF_WIN(log_resize_release_locks(),);
      if (wait_lsn)
      {
        mysql_mutex_lock(&buf_pool.flush_list_mutex);
        buf_flush_wait(wait_lsn, circular_recovery_from_sequence_bit_0);
        mysql_mutex_unlock(&buf_pool.flush_list_mutex);
      }
      latch.wr_unlock();
      continue;
    }

    wait_lsn= get_lsn();
    const lsn_t checkpoint{last_checkpoint_lsn};

    if (archive)
    {
      const lsn_t limit{wait_lsn - (wait_lsn - first_lsn) % capacity()};
      ut_ad(get_sequence_bit(limit) == get_sequence_bit(wait_lsn));
      if (checkpoint < limit)
        /*
          The circular ib_logfile0 is currently wrapped around between
          the checkpoint and the current position. Wait for a checkpoint,
          because innodb_log_archive=ON does not allow any wrap-around.
        */

        goto retry_after_checkpoint;
      ut_ad(get_sequence_bit(checkpoint) == get_sequence_bit(wait_lsn));
      wait_lsn= limit;
      /*
        The innodb_log_archive=ON recovery ignores the sequence bit,
        so this transition is clear.

        However, a future set_archive(false) must ensure that recovery
        will not observe any get_sequence_bit() == 0 residue from the
        previous time this log file was in innodb_log_archive=OFF
        format.

        The following assignment controls the condition in the "else if"
        below, in a subsequent invocation of set_archive(false).
      */

      circular_recovery_from_sequence_bit_0= !get_sequence_bit(wait_lsn);
    }
    else if (circular_recovery_from_sequence_bit_0 ||
             checkpoint < first_lsn ||
             get_sequence_bit(checkpoint) != get_sequence_bit(wait_lsn))
    {
      /*
        Some records after the latest checkpoint may have been written
        with get_sequence_bit() == 0 in innodb_log_archive=OFF
        mode. Since then we may have switched to innodb_log_archive=ON
        without advancing the checkpoint (see the above "if" body),
        and now back to innodb_log_archive=OFF again.

        Wait for write_checkpoint() to ensure that recovery will only
        find get_sequence_bit() == 1, consistent with our first_lsn.

        Alternatively, before we can switch to innodb_log_archive=OFF,
        we must ensure that the checkpoint resides within the last file.

        Progress is guaranteed by setting a checkpoint target right
        after the latest written FILE_CHECKPOINT record.
      */

      wait_lsn= end_lsn;
      goto retry_after_checkpoint;
    }

#ifdef HAVE_PMEM
    if (is_mmap())
    {
      ut_ad(is_mmap_writeable());
      ut_ad(this->archive == log.is_opened());
      if (is_backoff())
        /* Prevent a race condition with append_prepare() */
        goto retry;
      if (archive);
      else if (resize_buf)
        /* Wait for a call to archived_mmap_switch_complete() */
        goto retry;
      else if (checkpoint_buf)
        /* Wait for write_checkpoint() */
        goto retry;
      else
        log.close();
    }
#endif

    ut_ad(!resize_buf);
    ut_ad(!resize_log.is_opened());

    const lsn_t old_first_lsn{first_lsn};
    if (archive)
    {
      first_lsn= wait_lsn;
      resize_target= file_size;
    }
    std::string normal_name{get_circular_path()};
    std::string arch_name{get_archive_path()};

    const char *old_name= normal_name.c_str();
    const char *new_name= arch_name.c_str();
    if (!archive)
    {
      std::swap(old_name, new_name);
      std::string spare{get_archive_path(first_lsn + capacity())};
      if (!get_sequence_bit(checkpoint))
        /*
          In the innodb_log_archive=ON format, mtr_t::finish_writer()
          always writes the sequence bit as 1. Ensure that the
          innodb_log_archive=OFF recovery will expect this value.
        */

        first_lsn-= capacity();
      ut_ad(get_sequence_bit(checkpoint));
      ut_ad(get_sequence_bit(get_lsn()));
      header_rewrite(false);
      IF_WIN(DeleteFile(spare.c_str()), unlink(spare.c_str()));
    }
#if defined HAVE_PMEM && !defined _WIN32
    else if (is_mmap())
    {
      /* Open the file so that write_checkpoint()
      will be able to flag it read-only */

      bool success;
      log.m_file=
        os_file_create_func(old_name, OS_FILE_OPEN, OS_LOG_FILE,
                            false, &success);
      if (!log.is_opened())
      {
        my_error(ER_ERROR_ON_READ, MYF(0), old_name, errno);
        break;
      }
    }
#endif

#ifdef _WIN32
    /* On Microsoft Windows, there must be no open file handles to a
    file that is being renamed. */

    if (const dberr_t err= log.close())
      log_close_failed(err);
#endif
    int fail= my_rename(old_name, new_name, MY_SYNC_DIR);
#ifdef _WIN32
    {
      bool success;
      log.m_file= os_file_create_func(fail ? old_name : new_name,
                                      OS_FILE_OPEN, OS_LOG_FILE,
                                      false, &success);
      ut_a(log.m_file != OS_FILE_CLOSED);
    }
#endif
    if (fail)
    {
      my_error(ER_ERROR_ON_RENAME, MYF(0), old_name, new_name, my_errno);
      first_lsn= old_first_lsn;
      break;
    }

    if (archive)
    {
      header_rewrite(true);
      archive_set_size();
      wait_lsn= 0;
    }
    else
    {
      ut_ad(wait_lsn == get_lsn());
      /* apply similar logic as log_close() */
      const lsn_t checkpoint_age{wait_lsn - checkpoint};
      if (checkpoint_age < max_modified_age_async)
        wait_lsn= 0;
      else
        wait_lsn= ((wait_lsn - max_checkpoint_age) & ~lsn_t{1}) |
          lsn_t{checkpoint_age >= max_checkpoint_age};
    }

    archived_lsn= end_lsn;
    this->archive= archive;
    mtr_t::finisher_update();
    break;
  }

  IF_WIN(log_resize_release(), latch.wr_unlock());
  tpool::tpool_wait_end();
  thd_wait_end(thd);
  if (wait_lsn)
    mtr_flush_ahead(wait_lsn);
}

/** Start resizing the log and release the exclusive latch.
@param size  requested new file_size
@param thd   the current thread identifier
@return whether the resizing was started successfully */

log_t::resize_start_status log_t::resize_start(os_offset_t size, void *thd)
  noexcept
{
  ut_ad(size >= 4U << 20);
  ut_ad(!(size & 4095));
  ut_ad(!srv_read_only_mode);
  ut_ad(!recv_sys.rpo);
  ut_ad(thd);
  log_resize_acquire();

  resize_start_status status;

  if (size == file_size)
    status= RESIZE_NO_CHANGE;
  else if (resize_in_progress())
    status= RESIZE_IN_PROGRESS;
  else if (archive)
  {
    if (resize_log.is_opened())
      /* The resize_target must not be changed after
      archive_new_write() or archived_mmap_switch_prepare() and before
      write_checkpoint() has been invoked. */

      status= RESIZE_IN_PROGRESS;
    else
    {
      status= RESIZE_NO_CHANGE;
      /* When the current log becomes full and a new archivable log file
      is being created, it will be of this size. At that point we will assign
      file_size= resize_target for HAVE_PMEM). */

      resize_target= size;
    }
  }
  else
  {
    lsn_t start_lsn;
    ut_ad(!resize_in_progress());
    ut_ad(!resize_log.is_opened() || resize_log.m_file == log.m_file);
    ut_ad(!resize_buf);
    ut_ad(!resize_flush_buf);
    ut_ad(!resize_initiator);
    const std::string path{get_circular_path(101)};
    bool success;
    resize_initiator= thd;
    resize_lsn.store(1, std::memory_order_relaxed);
    resize_target= 0;
    resize_log.m_file=
      os_file_create_func(path.c_str(), OS_FILE_CREATE,
                          OS_LOG_FILE, false, &success);
    if (success)
    {
      ut_ad(!(size_t(file_size) & (write_size - 1)));
      ut_ad(!(size_t(size) & (write_size - 1)));
      log_resize_release();

      void *ptr= nullptr, *ptr2= nullptr;
      success= os_file_set_size(path.c_str(), resize_log.m_file, size);
      if (!success);
#ifdef HAVE_PMEM
      else if (is_mmap())
      {
        ut_ad(is_mmap_writeable());
        bool is_pmem{false};
        ptr= ::log_mmap(resize_log.m_file, is_pmem, size, READ_WRITE);

        if (ptr == MAP_FAILED)
          goto alloc_fail;
        ut_ad(is_pmem == this->is_pmem);
      }
#endif
      else
      {
        ut_ad(!is_mmap());
        ptr= ut_malloc_dontdump(buf_size, PSI_INSTRUMENT_ME);
        if (ptr)
        {
          TRASH_ALLOC(ptr, buf_size);
          ptr2= ut_malloc_dontdump(buf_size, PSI_INSTRUMENT_ME);
          if (ptr2)
            TRASH_ALLOC(ptr2, buf_size);
          else
          {
            ut_free_dodump(ptr, buf_size);
            ptr= nullptr;
            goto alloc_fail;
          }
        }
        else
        alloc_fail:
          success= false;
      }

      log_resize_acquire();

      if (!success)
      {
        resize_log.close();
        IF_WIN(DeleteFile(path.c_str()), unlink(path.c_str()));
      }
      else
      {
        resize_target= size;
        resize_buf= static_cast<byte*>(ptr);
        resize_flush_buf= static_cast<byte*>(ptr2);
        start_lsn= get_lsn();

        if (!is_mmap())
          start_lsn= first_lsn +
            (~lsn_t{write_size - 1} &
             (lsn_t{write_size - 1} + start_lsn - first_lsn));
        else if (!is_opened())
          resize_log.close();

        resize_lsn.store(start_lsn, std::memory_order_relaxed);
        writer_update(true);
        log_resize_release();

        mysql_mutex_lock(&buf_pool.flush_list_mutex);
        lsn_t target_lsn= buf_pool.get_oldest_modification(0);
        mysql_mutex_unlock(&buf_pool.flush_list_mutex);
        buf_flush_ahead(start_lsn < target_lsn ? target_lsn + 1 : start_lsn,
                        false);
        return RESIZE_STARTED;
      }
    }
    resize_initiator= nullptr;
    resize_lsn.store(0, std::memory_order_relaxed);
    status= RESIZE_FAILED;
  }

  log_resize_release();
  return status;
}

/** Abort a resize_start() that we started. */
void log_t::resize_abort(void *thd) noexcept
{
  log_resize_acquire();

  if (resize_running(thd))
  {
#ifdef HAVE_PMEM
    const bool is_mmap{this->is_mmap()};
#else
    constexpr bool is_mmap{false};
#endif
    if (!is_mmap)
    {
      ut_free_dodump(resize_buf, buf_size);
      ut_free_dodump(resize_flush_buf, buf_size);
      resize_flush_buf= nullptr;
    }
    else
    {
      ut_ad(!resize_log.is_opened());
      ut_ad(!resize_flush_buf);
#ifdef HAVE_PMEM
      if (resize_buf)
        my_munmap(resize_buf, resize_target);
#endif /* HAVE_PMEM */
    }
    if (resize_log.is_opened())
      resize_log.close();
    resize_buf= nullptr;
    resize_target= 0;
    resize_lsn.store(0, std::memory_order_relaxed);
    resize_initiator= nullptr;
    IF_WIN(DeleteFile(get_circular_path(101).c_str()),
           unlink(get_circular_path(101).c_str()));
    writer_update(false);
  }

  log_resize_release();
}

/** Write an aligned buffer to ib_logfile0.
@param max_length the maximum length that can be written to the file
@param buf        buffer to be written
@param length     length of data to be written
@param offset     log file offset */

static void log_write_buf(lsn_t max_length,
                          const byte *buf, size_t length, lsn_t offset)
  noexcept
{
  ut_ad(write_lock.is_owner());
  ut_ad(!recv_no_log_write);
  ut_d(const size_t block_size_1= log_sys.write_size - 1);
  ut_ad(!(offset & block_size_1));
  ut_ad(!(length & block_size_1));
  ut_ad(!(size_t(buf) & block_size_1));
  ut_ad(length);
  ut_ad(max_length == log_sys.file_size - offset);

  if (UNIV_UNLIKELY(length > max_length))
  {
    ut_ad(!log_sys.archive);
    log_sys.log.write(offset, {buf, size_t(max_length)});
    length-= size_t(max_length);
    buf+= size_t(max_length);
    ut_ad(log_sys.START_OFFSET + length < offset);
    offset= log_sys.START_OFFSET;
  }
  log_sys.log.write(offset, {buf, length});
}

ATTRIBUTE_COLD
std::string &log_t::append_archive_name(std::string &path, lsn_t lsn)
{
  path.append("ib_");
  for (int i= 16; i--; lsn<<= 4)
    path.push_back("0123456789abcdef"[lsn >> 60]);
  path.append(".log");
  return path;
}

ATTRIBUTE_COLD std::string log_t::get_archive_path(lsn_t lsn) const
{
  size_t size= strlen(srv_log_group_home_dir);
 retry:
  switch (srv_log_group_home_dir[size - !!size]) {
#ifdef _WIN32
  case '\\':
#endif
  case '/':
    size--;
    goto retry;
  }
  if (size == 1 && *srv_log_group_home_dir == '.')
    size= 0;
  std::string path;
  path.reserve(size + sizeof "/ib_0000000000000000.log");
  path.assign(srv_log_group_home_dir, size);
  if (size)
    path.push_back('/');
  return append_archive_name(path, lsn);
}

ATTRIBUTE_COLD void log_t::archive_new_write(const byte *buf, size_t length,
                                             lsn_t offset) noexcept
{
  ut_ad(latch_have_wr());
  ut_ad(write_lock.is_owner());
  ut_ad(archive);
  ut_ad(!resize_buf);
  ut_ad(!resize_in_progress());
  ut_ad(resize_target >= FILE_SIZE_MIN);
  ut_ad(length);
  ut_ad(!is_mmap());
  ut_ad(is_latest());

  if (!resize_log.is_opened());
  else if (UNIV_UNLIKELY(resize_log.m_file == log.m_file))
    /* write_checkpoint() is waiting in log_write_and_flush_prepare()
    for us to finish. Let us create a new file normally. */

    resize_log.m_file= OS_FILE_CLOSED;
  else
  {
    /* We had already created a new log file in a previous invocation
    of this function. The old log file (now pointed by resize_log)
    will be closed in write_checkpoint() once the first checkpoint in
    this new log file has been written. */

    ut_ad(offset >= file_size);
    offset-= file_size - START_OFFSET;
    log.write(offset, {buf, length});
    offset+= length;
    if (UNIV_UNLIKELY(offset > resize_target))
    {
      set_check_for_checkpoint(true);
      /* Allow the new log file to grow, because we did not complete a
      checkpoint quickly enough. Automatically adjust
      innodb_log_file_size to a larger size. */

      resize_target= (offset + 4095) & ~off_t{4095};
      sql_print_warning("InnoDB: Adjusting innodb_log_file_size="
                        LSN_PF "k", resize_target >> 10);
      length= size_t(offset) & 4095;
      if (length)
        log.write(offset, {field_ref_zero, 4096 - length});
    }
    return;
  }

  if (const size_t first{size_t(file_size - offset)})
  {
    log.write(offset, {buf, first});
    length-= first;
    buf+= first;
  }

  ut_a(offset + length + START_OFFSET <= file_size + resize_target);

  archive_create(first_lsn + capacity(), true);
  if (length)
    log.write(START_OFFSET, {buf, length});
}

ATTRIBUTE_COLD void log_t::archive_create(lsn_t lsn, bool ex) noexcept
{
  ut_ad(ex ? latch_have_wr() : latch_have_rd());
  ut_ad(archive);

  if (UNIV_UNLIKELY(resize_log.is_opened()))
  {
    ut_a(!ex);
    return;
  }

  ut_ad(lsn == first_lsn + os_file_get_size(log.m_file) - START_OFFSET);
  std::string path{get_archive_path(lsn)};
  bool success;
  os_file_t file=
    os_file_create_func(path.c_str(), OS_FILE_CREATE, OS_LOG_FILE,
                        false, &success);
  ut_ad(success == (file != OS_FILE_CLOSED));

  if (file == OS_FILE_CLOSED)
  {
    if (!ex)
      /* The file already exists, and we were only attempting to
      create and allocate it in advance. Assume that our work is
      already done. */

      return;

    file= os_file_create_func(path.c_str(), OS_FILE_OPEN, OS_LOG_FILE,
                              false, &success);
    ut_ad(success == (file != OS_FILE_CLOSED));
  }

  if (file != OS_FILE_CLOSED)
  {
    /* On Windows, os_file_set_size() sets the exact size;
    on POSIX, it sets the minimum. write_checkpoint() needs the exact size. */

    success= os_file_set_size(path.c_str(), file, resize_target);
    if (success && ex && IF_WIN(true, !ftruncate(file, resize_target)))
    {
      ut_ad(os_file_get_size(file) == resize_target);
#ifdef HAVE_PMEM
      if (is_mmap())
      {
        ut_ad(is_mmap_writeable());
        ut_ad(!resize_buf);
        bool is_pmem;
        resize_buf=
          static_cast<byte*>(::log_mmap(file, is_pmem,
                                        resize_target, READ_WRITE));
        if (resize_buf == MAP_FAILED);
        else if (!is_pmem)
          my_munmap(resize_buf, resize_target);
        else
          goto success;
        resize_buf= nullptr;
      }
      else
      {
      success:
#endif
        /* Will be closed in write_checkpoint() */
        resize_log= log;
        log= file;
        return;
#ifdef HAVE_PMEM
      }
#endif
    }
    os_file_close(file);
    if (!ex)
      return;
  }
  else if (!ex)
    return;

  sql_print_error("[FATAL] InnoDB: Failed to create %s of %" PRIu64
                  " bytes", path.c_str(), resize_target);
  abort();
}

/** Invoke commit_checkpoint_notify_ha() to notify that outstanding
log writes have been completed. */
void log_flush_notify(lsn_t flush_lsn);

#if 0 // Currently we overwrite the last log block until it is complete.
/** CRC-32C of pad messages using between 1 and 15 bytes of NUL bytes
in the payload */
static const unsigned char pad_crc[15][4]= {
  {0xA6,0x59,0xC1,0xDB}, {0xF2,0xAF,0x80,0x73}, {0xED,0x02,0xF1,0x90},
  {0x68,0x4E,0xA3,0xF3}, {0x5D,0x1B,0xEA,0x6A}, {0xE0,0x01,0x86,0xB9},
  {0xD1,0x06,0x86,0xF5}, {0xEB,0x20,0x12,0x33}, {0xBA,0x73,0xB2,0xA3},
  {0x5F,0xA2,0x08,0x03}, {0x70,0x03,0xD6,0x9D}, {0xED,0xB3,0x49,0x78},
  {0xFD,0xD6,0xB9,0x9C}, {0x25,0xF8,0xB1,0x2C}, {0xCD,0xAA,0xE7,0x10}
};

/** Pad the log with some dummy bytes
@param lsn    desired log sequence number
@param pad    number of bytes to append to the log
@param begin  buffer to write 'pad' bytes to
@param extra  buffer for additional pad bytes (up to 15 bytes)
@return additional bytes used in extra[] */
ATTRIBUTE_NOINLINE
static size_t log_pad(lsn_t lsn, size_t pad, byte *begin, byte *extra)
{
  ut_ad(!(size_t(begin + pad) & (log_sys.get_block_size() - 1)));
  byte *b= begin;
  const byte seq{log_sys.get_sequence_bit(lsn)};
  /* The caller should never request padding such that the
  file would wrap around to the beginning. That is, the sequence
  bit must be the same for all records. */
  ut_ad(seq == log_sys.get_sequence_bit(lsn + pad));

  if (log_sys.is_encrypted())
  {
    /* The lengths of our pad messages vary between 15 and 29 bytes
    (FILE_CHECKPOINT byte, 1 to 15 NUL bytes, sequence byte,
    4 bytes checksum, 8 NUL bytes nonce). */
    if (pad < 15)
    {
      extra[0]= FILE_CHECKPOINT | 1;
      extra[1]= 0;
      extra[2]= seq;
      memcpy(extra + 3, pad_crc[0], 4);
      memset(extra + 7, 0, 8);
      memcpy(b, extra, pad);
      memmove(extra, extra + pad, 15 - pad);
      return 15 - pad;
    }

    /* Pad first with 29-byte messages until the remaining size is
    less than 29+15 bytes, and then write 1 or 2 shorter messages. */
    const byte *const end= begin + pad;
    for (; b + (29 + 15) < end; b+= 29)
    {
      b[0]= FILE_CHECKPOINT | 15;
      memset(b + 1, 0, 15);
      b[16]= seq;
      memcpy(b + 17, pad_crc[14], 4);
      memset(b + 21, 0, 8);
    }
    if (b + 29 < end)
    {
      b[0]= FILE_CHECKPOINT | 1;
      b[1]= 0;
      b[2]= seq;
      memcpy(b + 3, pad_crc[0], 4);
      memset(b + 7, 0, 8);
      b+= 15;
    }
    const size_t last_pad(end - b);
    ut_ad(last_pad >= 15);
    ut_ad(last_pad <= 29);
    b[0]= FILE_CHECKPOINT | byte(last_pad - 14);
    memset(b + 1, 0, last_pad - 14);
    b[last_pad - 13]= seq;
    memcpy(b + last_pad - 12, pad_crc[last_pad - 15], 4);
    memset(b + last_pad - 8, 0, 8);
  }
  else
  {
    /* The lengths of our pad messages vary between 7 and 21 bytes
    (FILE_CHECKPOINT byte, 1 to 15 NUL bytes, sequence byte,
    4 bytes checksum). */
    if (pad < 7)
    {
      extra[0]= FILE_CHECKPOINT | 1;
      extra[1]= 0;
      extra[2]= seq;
      memcpy(extra + 3, pad_crc[0], 4);
      memcpy(b, extra, pad);
      memmove(extra, extra + pad, 7 - pad);
      return 7 - pad;
    }

    /* Pad first with 21-byte messages until the remaining size is
    less than 21+7 bytes, and then write 1 or 2 shorter messages. */
    const byte *const end= begin + pad;
    for (; b + (21 + 7) < end; b+= 21)
    {
      b[0]= FILE_CHECKPOINT | 15;
      memset(b + 1, 0, 15);
      b[16]= seq;
      memcpy(b + 17, pad_crc[14], 4);
    }
    if (b + 21 < end)
    {
      b[0]= FILE_CHECKPOINT | 1;
      b[1]= 0;
      b[2]= seq;
      memcpy(b + 3, pad_crc[0], 4);
      b+= 7;
    }
    const size_t last_pad(end - b);
    ut_ad(last_pad >= 7);
    ut_ad(last_pad <= 21);
    b[0]= FILE_CHECKPOINT | byte(last_pad - 6);
    memset(b + 1, 0, last_pad - 6);
    b[last_pad - 5]= seq;
    memcpy(b + last_pad - 4, pad_crc[last_pad - 7], 4);
  }

  return 0;
}
#endif

#ifdef HAVE_PMEM
ATTRIBUTE_COLD
void log_t::archived_mmap_switch_prepare(bool late, bool ex) noexcept
{
  ut_ad(archive);
  ut_ad(is_mmap());
  ut_ad(is_mmap_writeable());
  ut_ad(log.is_opened());
  ut_ad(!resize_log.is_opened());
  ut_ad(!resize_buf);
  ut_ad(!checkpoint_buf);
  ut_ad(!resize_in_progress());
  ut_ad(resize_target >= 4U << 20);
  ut_ad(is_latest());

  if (UNIV_LIKELY(!ex))
  {
    latch.rd_unlock();
    if (!late)
    {
      /* Wait for all threads to back off. */
      latch.wr_lock();
      goto got_ex;
    }

    const auto delay= my_cpu_relax_multiplier / 4 * srv_spin_wait_delay;
    const auto rounds= srv_n_spin_wait_rounds;

    for (;;)
    {
      HMT_low();
      for (auto r= rounds + 1; r--; )
      {
        if (write_lsn_offset.load(std::memory_order_relaxed) & WRITE_BACKOFF)
        {
          for (auto d= delay; d--; )
            MY_RELAX_CPU();
        }
        else
        {
          HMT_medium();
          goto done;
        }
      }
      HMT_medium();
      std::this_thread::sleep_for(std::chrono::microseconds(100));
    }
  }
  else
  {
  got_ex:
    const uint64_t l= write_lsn_offset.load(std::memory_order_relaxed);
    const lsn_t lsn= base_lsn.load(std::memory_order_relaxed) +
      (l & (WRITE_BACKOFF - 1));
    waits++;
    ut_ad(archive);
    ut_ad(!resize_in_progress());
    ut_ad(resize_target >= 4U << 20);
    ut_ad(is_latest());
    ut_ad(log.is_opened());
    ut_ad((checkpoint_buf || resize_buf) == resize_log.is_opened());

    if (resize_buf)
      /* archive_create(..., false) had recently succeeded in another thread */
      ut_ad(!checkpoint_buf);
    else if (UNIV_LIKELY_NULL(checkpoint_buf))
      /* Both archived_mmap_switch_prepare() and
      archived_mmap_switch_complete() were invoked by another thread,
      but write_checkpoint() did not clean up yet. */
      ut_ad(last_checkpoint_lsn < first_lsn);
    else
      archive_create(first_lsn + capacity(), true);

    ut_ad(lsn - get_flushed_lsn(std::memory_order_relaxed) < capacity());
    persist(lsn);
    /* Above we cleared the WRITE_BACKOFF flag,
    which our caller will recheck. */
    if (ex)
      return;
    latch.wr_unlock();
  }

done:
  latch.rd_lock();
}

void log_t::persist(lsn_t lsn) noexcept
{
  ut_ad(!write_lock.is_owner());
  ut_ad(!flush_lock.is_owner());
  ut_ad(latch_have_wr());

  lsn_t old= flushed_to_disk_lsn.load(std::memory_order_relaxed);

  if (old > lsn)
    return;

  ut_ad(is_mmap_writeable());
  ut_ad(is_opened() == archive);
  const size_t start(calc_lsn_offset(old));
  const size_t end(calc_lsn_offset(lsn));

  if (UNIV_UNLIKELY(end < start))
  {
    pmem_persist(buf + start, file_size - start);
    byte *b= archive ? resize_buf : buf;
    ut_ad(b || end == START_OFFSET);
    /* pmem_persist(nullptr, 0) is a no-op */
    pmem_persist(b + START_OFFSET, end - START_OFFSET);
  }
  else
    pmem_persist(buf + start, end - start);

  uint64_t offset{write_lsn_offset};
  const lsn_t new_base_lsn= base_lsn.load(std::memory_order_relaxed) +
    (offset & (WRITE_BACKOFF - 1));
  ut_ad(new_base_lsn >= lsn);
  write_to_buf+= size_t(offset >> WRITE_TO_BUF_SHIFT);
  /* This synchronizes with get_lsn_approx();
  we must store write_lsn_offset before base_lsn. */
  write_lsn_offset.store(0, std::memory_order_relaxed);
  base_lsn.store(new_base_lsn, std::memory_order_release);
  flushed_to_disk_lsn.store(lsn, std::memory_order_relaxed);
  log_flush_notify(lsn);
  DBUG_EXECUTE_IF("crash_after_log_write_upto", DBUG_SUICIDE(););
}

ATTRIBUTE_NOINLINE
static void log_write_persist(lsn_t lsn) noexcept
{
  log_sys.latch.wr_lock();
  log_sys.persist(lsn);
  log_sys.latch.wr_unlock();
}
#endif

void log_t::resize_write_buf(const byte *b, size_t length) noexcept
{
  const size_t block_size_1= write_size - 1;
  ut_ad(b == resize_buf || b == resize_flush_buf);
  ut_ad(!(resize_target & block_size_1));
  ut_ad(!(length & block_size_1));
  ut_ad(length > block_size_1);
  ut_ad(length <= resize_target);

  int64_t d= int64_t(write_lsn - resize_in_progress());
  if (UNIV_UNLIKELY(d < 0))
  {
    d&= ~int64_t(block_size_1);
    if (int64_t(d + length) <= 0)
      return;
    length+= ssize_t(d);
    b-= ssize_t(d);
    d= 0;
  }
  lsn_t offset= START_OFFSET + (lsn_t(d) & ~lsn_t{block_size_1}) %
    (resize_target - START_OFFSET);

  if (UNIV_UNLIKELY(offset + length > resize_target))
  {
    offset= START_OFFSET;
    resize_lsn.store(first_lsn +
                     (~lsn_t{block_size_1} & (write_lsn - first_lsn)),
                     std::memory_order_relaxed);
  }

  ut_a(os_file_write_func(IORequestWrite, "ib_logfile101", resize_log.m_file,
                          b, offset, length) == DB_SUCCESS);
}

/** Write buf to ib_logfile0 and possibly ib_logfile101.
@tparam resizing whether to release latch and whether resize_in_progress()>1
@return the current log sequence number */
template<log_t::resizing_and_latch resizing>
inline __attribute__((always_inline))
lsn_t log_t::write_buf() noexcept
{
  ut_ad(latch_have_wr());
  ut_ad(!is_mmap());
  ut_ad(!srv_read_only_mode);
  ut_ad(resizing == RETAIN_LATCH ||
        (resizing == RESIZING) == (resize_in_progress() > 1));
  ut_ad(write_lsn >= first_lsn);

  const lsn_t lsn{get_lsn()};

  if (write_lsn >= lsn)
  {
    if (resizing != RETAIN_LATCH)
      latch.wr_unlock();
    ut_ad(write_lsn == lsn);
  }
  else
  {
    ut_ad(!recv_sys.rpo);
    ut_ad(write_lock.is_owner());
    ut_ad(!recv_no_log_write);
    write_lock.set_pending(lsn);
    ut_ad(write_lsn >= get_flushed_lsn());
    const size_t write_size_1{write_size - 1};
    ut_ad(ut_is_2pow(write_size));
    lsn_t base= base_lsn.load(std::memory_order_relaxed);
    size_t length{size_t(lsn - base)};
    lsn_t offset{write_lsn - first_lsn};
    if (resizing == RESIZING || !archive)
      offset%= capacity();
    offset+= START_OFFSET;
    ut_ad(length >= (offset & write_size_1));
    ut_ad(write_size_1 >= 511);

    const byte *const write_buf{buf};
    byte *const re_write_buf{resizing == NOT_RESIZING ? nullptr : resize_buf};
    ut_ad(resizing == RETAIN_LATCH ||
          (resizing == NOT_RESIZING) == !re_write_buf);
    ut_ad(!re_write_buf == !resize_flush_buf);
    if (resizing == RESIZING)
#ifdef _MSC_VER
      __assume(re_write_buf != nullptr);
#else
      if (!re_write_buf) __builtin_unreachable();
#endif
    offset&= ~lsn_t{write_size_1};

    if (length <= write_size_1)
    {
      ut_ad(!((length ^ (size_t(lsn) - size_t(first_lsn))) & write_size_1));
      /* Keep filling the same buffer until we have more than one block. */
      MEM_MAKE_DEFINED(buf + length, (write_size_1 + 1) - length);
      buf[length]= 0; /* ensure that recovery catches EOF */
      if (UNIV_LIKELY_NULL(re_write_buf))
      {
        MEM_MAKE_DEFINED(re_write_buf + length, (write_size_1 + 1) - length);
        re_write_buf[length]= 0;
      }
      length= write_size_1 + 1;
    }
    else
    {
      const size_t new_buf_free{length & write_size_1};
      base+= length & ~write_size_1;
      ut_ad(new_buf_free == ((lsn - first_lsn) & write_size_1));
      write_to_buf+= size_t(write_lsn_offset >> WRITE_TO_BUF_SHIFT);
      /* This synchronizes with get_lsn_approx();
      we must store write_lsn_offset before base_lsn. */
      write_lsn_offset.store(new_buf_free, std::memory_order_relaxed);
      base_lsn.store(base, std::memory_order_release);

      if (new_buf_free)
      {
        /* The rest of the block will be written as garbage.
        (We want to avoid memset() while holding exclusive log_sys.latch)
        This block will be overwritten later, once records beyond
        the current LSN are generated. */
        MEM_MAKE_DEFINED(buf + length, (write_size_1 + 1) - new_buf_free);
        buf[length]= 0; /* allow recovery to catch EOF faster */
        if (UNIV_LIKELY_NULL(re_write_buf))
          MEM_MAKE_DEFINED(re_write_buf + length, (write_size_1 + 1) -
                           new_buf_free);
        length&= ~write_size_1;
        memcpy_aligned<16>(flush_buf, buf + length, (new_buf_free + 15) & ~15);
        if (UNIV_LIKELY_NULL(re_write_buf))
        {
          memcpy_aligned<16>(resize_flush_buf, re_write_buf + length,
                             (new_buf_free + 15) & ~15);
          re_write_buf[length + new_buf_free]= 0;
        }
        length+= write_size_1 + 1;
      }

      std::swap(buf, flush_buf);
      if (UNIV_LIKELY_NULL(re_write_buf))
        std::swap(resize_buf, resize_flush_buf);
    }

    ut_ad(base + (write_lsn_offset & (WRITE_TO_BUF - 1)) == lsn);
    write_to_log++;
    DBUG_PRINT("ib_log", ("write " LSN_PF " to " LSN_PF " at " LSN_PF,
                          write_lsn, lsn, offset));

    if (resizing != RESIZING && archive && offset + length > file_size)
    {
      archive_new_write(write_buf, length, offset);
      if (resizing != RETAIN_LATCH)
        latch.wr_unlock();
      goto written;
    }

    if (resizing != RETAIN_LATCH)
      latch.wr_unlock();

    /* Do the write to the log file */
    ut_ad(file_size - offset <= capacity());
    log_write_buf(file_size - offset, write_buf, length, offset);

    if (UNIV_LIKELY_NULL(re_write_buf))
      resize_write_buf(re_write_buf, length);
  written:
    write_lsn= lsn;

    if (UNIV_UNLIKELY(srv_shutdown_state > SRV_SHUTDOWN_INITIATED))
    {
      service_manager_extend_timeout(INNODB_EXTEND_TIMEOUT_INTERVAL,
                                     "InnoDB log write: " LSN_PF, write_lsn);
    }
  }

  return lsn;
}

bool log_t::flush(lsn_t lsn) noexcept
{
  ut_ad(lsn >= get_flushed_lsn());
  flush_lock.set_pending(lsn);
  const bool success{log_write_through || log.flush()};
  if (UNIV_LIKELY(success))
  {
    flushed_to_disk_lsn.store(lsn, std::memory_order_release);
    log_flush_notify(lsn);
  }
  return success;
}

/** Ensure that previous log writes are durable.
@param lsn  previously written LSN
@return new durable lsn target
@retval 0  if there are no pending callbacks on flush_lock
           or there is another group commit lead.
*/
static lsn_t log_flush(lsn_t lsn) noexcept
{
  ut_ad(!log_sys.is_mmap());
  ut_a(log_sys.flush(lsn));
  DBUG_EXECUTE_IF("crash_after_log_write_upto", DBUG_SUICIDE(););
  return flush_lock.release(lsn);
}

static const completion_callback dummy_callback{[](void *) {},nullptr};

/** Ensure that the log has been written to the log file up to a given
log entry (such as that of a transaction commit). Start a new write, or
wait and check if an already running write is covering the request.
@param lsn      log sequence number that should be included in the file write
@param durable  whether the write needs to be durable
@param callback log write completion callback */
void log_write_up_to(lsn_t lsn, bool durable,
                     const completion_callback *callback) noexcept
{
  ut_ad(!srv_read_only_mode);
  ut_ad(lsn != LSN_MAX);
  ut_ad(lsn != 0);
#ifdef HAVE_PMEM
  if (log_sys.is_mmap())
  {
    if (durable)
      log_write_persist(lsn);
    else
      ut_ad(!callback);
    return;
  }
#endif

repeat:
  if (durable)
  {
    if (flush_lock.acquire(lsn, callback) != group_commit_lock::ACQUIRED)
      return;
    /* Promise to other concurrent flush_lock.acquire() that we
    will be durable at least up to the current LSN. The LSN may still
    advance when we acquire log_sys.latch below. */
    if (lsn > log_sys.get_flushed_lsn())
      flush_lock.set_pending(lsn);
  }

  lsn_t pending_write_lsn= 0, pending_flush_lsn= 0, flush_ahead= 0;

  if (write_lock.acquire(lsn, durable ? nullptr : callback) ==
      group_commit_lock::ACQUIRED)
  {
    ut_ad(!recv_no_log_write || srv_operation != SRV_OPERATION_NORMAL);
    log_sys.latch.wr_lock();
    ut_ad(!log_sys.is_mmap());
    if (log_sys.archive)
    {
      flush_ahead= log_sys.get_lsn();
      if (flush_ahead <= log_sys.get_first_lsn() + log_sys.capacity())
        flush_ahead= 0;
    }

    pending_write_lsn= write_lock.release(log_sys.writer());
  }

  if (durable)
    pending_flush_lsn= log_flush(write_lock.value());

  if (UNIV_UNLIKELY(flush_ahead != 0))
    /* Ensure that a call to log_t::archive_new_write() will be
    completed by log_t::write_checkpoint(). */
    buf_flush_ahead(lsn, false);

  if (pending_write_lsn || pending_flush_lsn)
  {
    /* There is no new group commit lead; some async waiters could stall. */
    callback= &dummy_callback;
    lsn= std::max(pending_write_lsn, pending_flush_lsn);
    goto repeat;
  }
}

void log_t::set_recovered_lsn(lsn_t lsn) noexcept
{
  ut_ad(latch_have_wr());
  if (archive)
    unstash_archive_file();
  uint64_t lsn_offset= ((write_size - 1) & (lsn - first_lsn));
  write_lsn_offset= lsn_offset;
  base_lsn.store(lsn - lsn_offset, std::memory_order_relaxed);
  flushed_to_disk_lsn.store(lsn, std::memory_order_relaxed);
  write_lsn= lsn;
  latch.wr_unlock();
  /* Ensure that log_write_up_to(lsn) will be a no-op. */
  if (flush_lock.acquire(lsn, nullptr) == group_commit_lock::ACQUIRED)
    flush_lock.release(lsn);
  if (write_lock.acquire(lsn, nullptr) == group_commit_lock::ACQUIRED)
    write_lock.release(lsn);
  latch.wr_lock();
}

static lsn_t log_writer() noexcept
{
  return log_sys.write_buf<log_t::NOT_RESIZING>();
}

ATTRIBUTE_COLD static lsn_t log_writer_resizing() noexcept
{
  return log_sys.write_buf<log_t::RESIZING>();
}

void log_t::writer_update(bool resizing) noexcept
{
  ut_ad(latch_have_wr());
  ut_ad(resizing == (resize_in_progress() > 1));
  writer= resizing ? log_writer_resizing : log_writer;
  mtr_t::finisher_update();
}

/** Write to the log file up to the last log entry.
@param durable  whether to wait for a durable write to complete */
void log_buffer_flush_to_disk(bool durable) noexcept
{
  log_write_up_to(log_get_lsn(), durable);
}

/** Prepare to invoke log_write_and_flush(), before acquiring log_sys.latch. */
ATTRIBUTE_COLD void log_write_and_flush_prepare() noexcept
{
#ifdef HAVE_PMEM
  if (log_sys.is_mmap())
    return;
#endif

  while (flush_lock.acquire(log_get_lsn() + 1, nullptr) !=
         group_commit_lock::ACQUIRED);
  while (write_lock.acquire(log_get_lsn() + 1, nullptr) !=
         group_commit_lock::ACQUIRED);
}

void log_t::clear_mmap() noexcept
{
  ut_ad(latch_have_wr());
  ut_ad(is_mmap());
  ut_ad(!srv_read_only_mode || recv_sys.rpo);

  if (recv_sys.rpo && recv_sys.rpo < get_flushed_lsn())
    return;

  latch.wr_unlock();
  log_resize_acquire();
  ut_ad(!resize_in_progress());
  ut_d(extern bool ibuf_upgrade_was_needed;)
  ut_ad(get_lsn() == get_flushed_lsn(std::memory_order_relaxed) ||
        ibuf_upgrade_was_needed);
#ifdef HAVE_PMEM
  if (is_mmap_writeable())
  {
    ut_ad(next_checkpoint_no <= START_OFFSET / 8);
    if (!recv_sys.rpo)
    {
      mprotect(buf, size_t(file_size), PROT_READ | PROT_WRITE);
      if (archive)
        /* Clear any garbage that may have been left behind by a
        crash during write_checkpoint() or set_archive(). */
        memset_aligned<4>(buf + next_checkpoint_no * 8, 0,
                          START_OFFSET - (next_checkpoint_no * 8));
    }
  }
  else if (is_opened())
#endif
  {
    ut_ad(write_lsn == get_lsn());

    if (buf) /* this may be invoked while creating a new database */
    {
      alignas(16) byte log_block[log_t::WRITE_SIZE_MAX];
      const size_t bs{write_size};
      {
        ut_ad(write_lsn >= first_lsn);
        uint64_t bf{write_lsn - first_lsn};
        if (!archive && bf > capacity())
          bf%= capacity();
        bf+= START_OFFSET;
        const size_t bs_1{bs - 1};
        write_lsn_offset= bf & bs_1;
        base_lsn.store(write_lsn - write_lsn_offset,
                       std::memory_order_relaxed);
        memcpy_aligned<16>(log_block, buf + (bf & ~uint64_t{bs_1}), bs);
      }

      close_file(false);
      log_mmap= false;
      buf_size= unsigned(std::min(uint64_t{buf_size}, capacity()));
      ut_a(attach(log, file_size, READ_WRITE));
      ut_ad(!is_mmap());

      memcpy_aligned<16>(buf, log_block, bs);
    }
  }

  write_lock.release(write_lock.value());
  flush_lock.release(flush_lock.value());
}

/** Durably write the log up to log_sys.get_lsn(). */
ATTRIBUTE_COLD void log_write_and_flush() noexcept
{
  ut_ad(!srv_read_only_mode);
  ut_ad(!recv_sys.rpo);
#ifdef HAVE_PMEM
  if (log_sys.is_mmap())
    log_sys.persist(log_sys.get_lsn());
  else
#endif
  {
    const lsn_t lsn{log_sys.write_buf<log_t::RETAIN_LATCH>()};
    write_lock.release(lsn);
    log_flush(lsn);
  }
}

ATTRIBUTE_COLD void log_t::checkpoint_margin() noexcept
{
  ut_ad(this == &log_sys);
  ut_ad(!recv_no_log_write);
  ut_ad(!recv_sys.rpo);

  thd_wait_begin(nullptr, THD_WAIT_DISKIO);
  tpool::tpool_wait_begin();

  while (check_for_checkpoint())
  {
    latch.wr_lock();
    ut_ad(!recv_no_log_write);

    if (!check_for_checkpoint())
    {
    func_exit:
      latch.wr_unlock();
      break;
    }

    const lsn_t last{last_checkpoint_lsn};
    const lsn_t max_age{checkpoint_age_max()};
    lsn_t lsn{first_lsn};

    if (last < lsn);
    else if (!archive)
    {
      lsn= get_lsn();
      if (lsn - last <= max_age || DBUG_IF("ib_log_checkpoint_avoid_hard"))
      {
      done:
        set_check_for_checkpoint(false);
        goto func_exit;
      }
      lsn-= max_age;
    }
    else if (resize_log.is_opened())
      lsn+= file_size;
    else
      goto done;

    mysql_mutex_lock(&buf_pool.flush_list_mutex);

    /* We must wait to prevent the tail of the log overwriting the head. */
    buf_flush_wait(lsn, false);
    latch.wr_unlock();
    mysql_mutex_unlock(&buf_pool.flush_list_mutex);
  }

  tpool::tpool_wait_end();
  thd_wait_end(nullptr);
}

/** Wait for a log checkpoint if needed.
NOTE that this function may only be called while not holding
any synchronization objects except dict_sys.latch. */
void log_free_check() noexcept
{
  ut_ad(!lock_sys.is_holder());
  if (log_sys.check_for_checkpoint())
    log_sys.checkpoint_margin();
}

/** Make a checkpoint at the latest lsn on shutdown.
@return the shutdown LSN */
ATTRIBUTE_COLD lsn_t logs_empty_and_mark_files_at_shutdown() noexcept
{
 ulint   count = 0;

 sql_print_information("InnoDB: Starting shutdown...");
 ut_ad(buf_pool.is_initialised() || !srv_was_started);
 ut_ad(!srv_read_only_mode || recv_sys.rpo);

 /* Wait until the master task and all other operations are idle: our
 algorithm only works if the server is idle at shutdown */
 if (srv_master_timer) {
  srv_master_timer.reset();
 }

 buf_mem_pressure_shutdown();
 dict_stats_shutdown();

 srv_shutdown_state = SRV_SHUTDOWN_CLEANUP;

 if (srv_buffer_pool_dump_at_shutdown &&
  !recv_sys.rpo && srv_fast_shutdown < 2) {
  buf_dump_start();
 }
 srv_monitor_timer.reset();

 constexpr ulint COUNT_INTERVAL{600};
 if (false) {
 loop:
  std::this_thread::sleep_for(std::chrono::milliseconds(100));
  count++;
 }

 ut_ad(lock_sys.is_initialised() || !srv_was_started);
 ut_ad(log_sys.is_initialised() || !srv_was_started);
 ut_ad(fil_system.is_initialised() || !srv_was_started);

 /* Check that there are no longer transactions, except for
 PREPARED ones. We need this wait even for the 'very fast'
 shutdown, because the InnoDB layer may have committed or
 prepared transactions and we don't want to lose them. */

 if (ulint total_trx = srv_was_started && !recv_sys.rpo
     && srv_force_recovery < SRV_FORCE_NO_TRX_UNDO
     ? trx_sys.any_active_transactions() : 0) {

  if (srv_print_verbose_log && count > COUNT_INTERVAL) {
   service_manager_extend_timeout(
    unsigned(COUNT_INTERVAL / 5),
    "Waiting for %zu active transactions to finish",
    total_trx);
   sql_print_information("InnoDB: Waiting for %zu active"
           " transactions to finish",
           total_trx);
   count = 0;
  }

  goto loop;
 }

 /* We need these threads to stop early in shutdown. */
 const char* thread_name= nullptr;

 if (thread_name) {
  ut_ad(!recv_sys.rpo);
wait_suspend_loop:
  service_manager_extend_timeout(
   unsigned(COUNT_INTERVAL / 5),
   "Waiting for %s to exit", thread_name);
  if (srv_print_verbose_log && count > COUNT_INTERVAL) {
   sql_print_information("InnoDB: Waiting for %s to exit",
           thread_name);
   count = 0;
  }
  goto loop;
 }

 /* Check that the background threads are suspended */

 ut_ad(!srv_any_background_activity());
 if (srv_n_fil_crypt_threads_started) {
  fil_crypt_threads_signal(true);
  thread_name = "fil_crypt_thread";
  goto wait_suspend_loop;
 }

 if (buf_pool.is_initialised()) {
  if (srv_fast_shutdown != 2 && !srv_read_only_mode
      && srv_was_started) {
   buf_flush_sync_batch(0, !recv_sys.rpo);
  }

  buf_load_dump_end();
  rollback_all_recovered_task.wait();

  mysql_mutex_lock(&buf_pool.flush_list_mutex);
  srv_shutdown_state = SRV_SHUTDOWN_LAST_PHASE;
  while (buf_page_cleaner_is_active) {
   pthread_cond_signal(&buf_pool.do_flush_list);
   my_cond_wait(&buf_pool.done_flush_list,
         &buf_pool.flush_list_mutex.m_mutex);
  }
  mysql_mutex_unlock(&buf_pool.flush_list_mutex);

  if (srv_fast_shutdown == 2 && !recv_sys.rpo) {
   sql_print_information(
    "InnoDB: Executing innodb_fast_shutdown=2."
    " Next startup will execute crash recovery!");
   log_buffer_flush_to_disk();
  }
 }

 const lsn_t lsn{log_get_lsn()};
 if (srv_fast_shutdown == 2 || !srv_was_started) {
  return lsn;
 }
 srv_shutdown_state = SRV_SHUTDOWN_LAST_PHASE;

 /* Make some checks that the server really is quiet */
 ut_ad(!srv_any_background_activity());

 service_manager_extend_timeout(INNODB_EXTEND_TIMEOUT_INTERVAL,
           "Free innodb buffer pool");
 /* There could be pending writes to the temporary tablespace. */
 os_aio_wait_until_no_pending_writes(false);
 /* Some recently triggered read-ahead may be pending. */
 os_aio_wait_until_no_pending_reads(false);
 ut_d(mysql_mutex_lock(&buf_pool.mutex));
 ut_d(buf_pool.assert_all_freed());
 ut_d(mysql_mutex_unlock(&buf_pool.mutex));
 ut_a(lsn == log_sys.last_checkpoint_lsn + SIZE_OF_FILE_CHECKPOINT
      + 8 * log_sys.is_encrypted()
      || recv_sys.rpo
      || srv_force_recovery == SRV_FORCE_NO_LOG_REDO);
 ut_a(lsn >= recv_sys.lsn);
 return lsn;
}

/******************************************************//**
Prints info of the log. */
void
log_print(
/*======*/
 FILE* file) /*!< in: file where to print */
{
 log_sys.latch.wr_lock();

 const lsn_t lsn= log_sys.get_lsn();
 mysql_mutex_lock(&buf_pool.flush_list_mutex);
 const lsn_t pages_flushed = buf_pool.get_oldest_modification(lsn);
 mysql_mutex_unlock(&buf_pool.flush_list_mutex);
 const lsn_t flushed_lsn{log_sys.get_flushed_lsn()};
 const lsn_t checkpoint_lsn{log_sys.last_checkpoint_lsn};
 log_sys.latch.wr_unlock();

 fprintf(file,
  "Log sequence number " LSN_PF "\n"
  "Log flushed up to   " LSN_PF "\n"
  "Pages flushed up to " LSN_PF "\n"
  "Last checkpoint at  " LSN_PF "\n",
  lsn, flushed_lsn, pages_flushed, checkpoint_lsn);
}

/** Shut down the redo log subsystem. */
void log_t::close()
{
  ut_ad(this == &log_sys);
  if (!is_initialised()) return;
  close_file();

  ut_ad(!checkpoint_buf);
  ut_ad(!buf);
  ut_ad(!flush_buf);
  base_lsn.store(0, std::memory_order_relaxed);

  latch.destroy();
#ifdef HAVE_PMEM
  resize_wrap_mutex.destroy();
#endif

  recv_sys.close();
}

ATTRIBUTE_COLD std::string log_t::get_circular_path(size_t i)
{
  ut_ad(i <= 101);
  const size_t size= strlen(srv_log_group_home_dir) + sizeof "/ib_logfile101";
  std::string path;
  path.reserve(size);
  path.assign(srv_log_group_home_dir);

  switch (path.back()) {
#ifdef _WIN32
  case '\\':
#endif
  case '/':
    break;
  default:
    path.push_back('/');
  }
  return path.append("ib_logfile").append(std::to_string(i));
}

ATTRIBUTE_COLD std::string log_t::get_path() const
{
  return archive ? get_archive_path() : get_circular_path();
}

Messung
CHZG
929610095

¤ Dauer der Verarbeitung: 0.68 Sekunden  ¤

*© Formatika GbR, Deutschland







                                                                                                                                                                                                                                                                                                                                                                                                     

 

Neuigkeiten

Aktuelles
Motto des Tages

Open Source Software


Gedichte
Musik
Bilder

Jenseits des Üblichen

Besucherstatistik

Besucherstatistik

Statistik
#Sources=1,188,274
#Domains=934,867