From c80a75a51ae4dd5a67ac801deefe61fdd112279a Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@gmail.com>
Date: Thu, 20 Feb 2020 11:31:45 +1300
Subject: [PATCH 1/2] Add infrastruction for hardware transactional memory.

If --enable-htm is provided to configure, add support for
using the Intel TSX RTM facilities.  Provide a very simple
abstraction that tries once but requires the caller to
provide a fallback.  In later patches, it should be
possible to map this to the builtins required for other
ISAs including ARM TME and POWER8.

Perform a runtime test at startup to check if the chip
we're running on has those instructions (eg Skylake and
later server-class chips; many mobile/laptop chips don't
have them, unfortunately).

This facility will be used by later patches to perform
hardware memory transactions, to replace LWLocks and
spinlocks optimistically, with a fallback.  If compiled
without --enable-htm, a constant value is provide so that
the HTM path can be removed by constant folding leaving
only the fallback path.

WORK IN PROGRESS: solution looking for a problem

Author: Thomas Munro
---
 configure                           | 40 +++++++++++++++
 configure.in                        | 15 ++++++
 src/backend/port/Makefile           |  1 +
 src/backend/port/htm.c              | 77 +++++++++++++++++++++++++++++
 src/backend/postmaster/postmaster.c |  5 ++
 src/include/pg_config.h.in          |  3 ++
 src/include/port/htm.h              | 60 ++++++++++++++++++++++
 7 files changed, 201 insertions(+)
 create mode 100644 src/backend/port/htm.c
 create mode 100644 src/include/port/htm.h

diff --git a/configure b/configure
index 37aa82dcd4..e44bceb5b0 100755
--- a/configure
+++ b/configure
@@ -829,6 +829,7 @@ with_pgport
 enable_rpath
 enable_spinlocks
 enable_atomics
+enable_htm
 enable_debug
 enable_profiling
 enable_coverage
@@ -1514,6 +1515,7 @@ Optional Features:
                           executables
   --disable-spinlocks     do not use spinlocks
   --disable-atomics       do not use atomic operations
+  --enable-htm            use hardware transactional memory operations
   --enable-debug          build with debugging symbols (-g)
   --enable-profiling      build with profiling enabled
   --enable-coverage       build with coverage testing instrumentation
@@ -3279,6 +3281,33 @@ fi
 
 
 
+#
+# Hardware transactional memory
+#
+
+
+# Check whether --enable-htm was given.
+if test "${enable_htm+set}" = set; then :
+  enableval=$enable_htm;
+  case $enableval in
+    yes)
+      :
+      ;;
+    no)
+      :
+      ;;
+    *)
+      as_fn_error $? "no argument expected for --enable-htm option" "$LINENO" 5
+      ;;
+  esac
+
+else
+  enable_htm=no
+
+fi
+
+
+
 #
 # --enable-debug adds -g to compiler flags
 #
@@ -6885,6 +6914,11 @@ $as_echo "#define PROFILE_PID_DIR 1" >>confdefs.h
   fi
 fi
 
+# enable HTM if --enable-htm
+if test "$enable_htm" = yes; then
+  CFLAGS="$CFLAGS -mrtm"
+fi
+
 # We already have this in Makefile.win32, but configure needs it too
 if test "$PORTNAME" = "win32"; then
   CPPFLAGS="$CPPFLAGS -I$srcdir/src/include/port/win32 -DEXEC_BACKEND"
@@ -11819,6 +11853,12 @@ $as_echo "$as_me: WARNING:
 *** Not using atomic operations will cause poor performance." >&2;}
 fi
 
+if test "$enable_htm" = yes; then
+
+$as_echo "#define HAVE_HTM 1" >>confdefs.h
+
+fi
+
 if test "$with_gssapi" = yes ; then
   if test "$PORTNAME" != "win32"; then
     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing gss_init_sec_context" >&5
diff --git a/configure.in b/configure.in
index 8adb409558..a1365d0986 100644
--- a/configure.in
+++ b/configure.in
@@ -193,6 +193,12 @@ PGAC_ARG_BOOL(enable, spinlocks, yes,
 PGAC_ARG_BOOL(enable, atomics, yes,
               [do not use atomic operations])
 
+#
+# Hardware transactional memory
+#
+PGAC_ARG_BOOL(enable, htm, no,
+              [use hardware transactional memory operations])
+
 #
 # --enable-debug adds -g to compiler flags
 #
@@ -594,6 +600,11 @@ if test "$enable_profiling" = yes && test "$ac_cv_prog_cc_g" = yes; then
   fi
 fi
 
+# enable HTM if --enable-htm
+if test "$enable_htm" = yes; then
+  CFLAGS="$CFLAGS -mrtm"
+fi
+
 # We already have this in Makefile.win32, but configure needs it too
 if test "$PORTNAME" = "win32"; then
   CPPFLAGS="$CPPFLAGS -I$srcdir/src/include/port/win32 -DEXEC_BACKEND"
@@ -1169,6 +1180,10 @@ else
 *** Not using atomic operations will cause poor performance.])
 fi
 
+if test "$enable_htm" = yes; then
+  AC_DEFINE(HAVE_HTM, 1, [Define to 1 if you want to use HTM.])
+fi
+
 if test "$with_gssapi" = yes ; then
   if test "$PORTNAME" != "win32"; then
     AC_SEARCH_LIBS(gss_init_sec_context, [gssapi_krb5 gss 'gssapi -lkrb5 -lcrypto'], [],
diff --git a/src/backend/port/Makefile b/src/backend/port/Makefile
index 2d00b4f05a..d81b03d196 100644
--- a/src/backend/port/Makefile
+++ b/src/backend/port/Makefile
@@ -24,6 +24,7 @@ include $(top_builddir)/src/Makefile.global
 OBJS = \
 	$(TAS) \
 	atomics.o \
+	htm.o \
 	pg_sema.o \
 	pg_shmem.o
 
diff --git a/src/backend/port/htm.c b/src/backend/port/htm.c
new file mode 100644
index 0000000000..aae14ee272
--- /dev/null
+++ b/src/backend/port/htm.c
@@ -0,0 +1,77 @@
+/*-------------------------------------------------------------------------
+ *
+ * htm.c
+ *	  Code to decide whether HTM is available on this micro-architecture.
+ *
+ * Portions Copyright (c) 2020, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ *
+ * IDENTIFICATION
+ *	  src/backend/port/htm.c
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#include "postgres.h"
+
+#include <setjmp.h>
+#include <signal.h>
+
+#include "port/htm.h"
+
+#ifdef HAVE_HTM
+
+/* Global variable to advertise whether HTM is available. */
+bool have_htm_support;
+
+static sigjmp_buf illegal_instruction_jump;
+
+static void
+illegal_instruction_handler(SIGNAL_ARGS)
+{
+	siglongjmp(illegal_instruction_jump, 1);
+}
+
+static bool
+test_memory_transaction(void)
+{
+	/*
+	 * We don't really care if this transaction commits or aborts, we just want
+	 * to exercise the instructions and trigger a SIGILL if they aren't there.
+	 */
+	if (!pg_htm_begin())
+		return false;
+	pg_htm_commit();
+	return true;
+}
+
+/*
+ * Test whether we have HTM support in every backend process.
+ */
+void
+htm_init(void)
+{
+	/*
+	 * You could use the Intel CPUID feature test for this, but perhaps a
+	 * SIGILL-based approach will eventually work on other ISAs that grow HTM
+	 * support.
+	 *
+	 * TODO: Is this going to work on Windows/MSVC?
+	 */
+	pqsignal(SIGILL, illegal_instruction_handler);
+	if (sigsetjmp(illegal_instruction_jump, 1) == 0)
+	{
+		/* Try to use HTM instructions */
+		test_memory_transaction();
+		have_htm_support = true;
+	}
+	else
+	{
+		/* We got the SIGILL trap */
+		have_htm_support = false;
+	}
+	pqsignal(SIGILL, SIG_DFL);
+}
+
+#endif
diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c
index b3986bee75..e3fabaeeb7 100644
--- a/src/backend/postmaster/postmaster.c
+++ b/src/backend/postmaster/postmaster.c
@@ -109,6 +109,7 @@
 #include "pg_getopt.h"
 #include "pgstat.h"
 #include "port/pg_bswap.h"
+#include "port/htm.h"
 #include "postmaster/autovacuum.h"
 #include "postmaster/bgworker_internals.h"
 #include "postmaster/fork_process.h"
@@ -2621,6 +2622,10 @@ InitProcessGlobals(void)
 			((uint64) MyStartTimestamp >> 20);
 	}
 	srandom(rseed);
+
+#ifdef HAVE_HTM
+	htm_init();
+#endif
 }
 
 
diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in
index 60dcf42974..287165c595 100644
--- a/src/include/pg_config.h.in
+++ b/src/include/pg_config.h.in
@@ -295,6 +295,9 @@
 /* Define to 1 if you have the `history_truncate_file' function. */
 #undef HAVE_HISTORY_TRUNCATE_FILE
 
+/* Define to 1 if you want to use HTM. */
+#undef HAVE_HTM
+
 /* Define to 1 if you have the <ieeefp.h> header file. */
 #undef HAVE_IEEEFP_H
 
diff --git a/src/include/port/htm.h b/src/include/port/htm.h
new file mode 100644
index 0000000000..7a1bc199ea
--- /dev/null
+++ b/src/include/port/htm.h
@@ -0,0 +1,60 @@
+/*-------------------------------------------------------------------------
+ *
+ * htm.h
+ *	  Hardware transaction memory operations.
+ *
+ * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * src/include/port/htm.h
+ *
+ *-------------------------------------------------------------------------
+ */
+#ifndef HTM_H
+#define HTM_H
+
+#ifdef FRONTEND
+#error "htm.h may not be included from frontend code"
+#endif
+
+#ifndef HAVE_HTM
+
+/*
+ * Make this a constant, so that if you build without --enable-htm, all
+ * relevant branches are removed by constant folding.
+ */
+#define have_htm_support false
+
+#else
+
+/*
+ * We have to check if the microarchitecture supports HTM instructions
+ * with a runtime check.  We'll store the result in a global variable.
+ */
+extern bool have_htm_support;
+
+/* Function called at startup to set the above variable. */
+extern void htm_init(void);
+
+/*
+ * A future version of the C programming language might standardize
+ * the interface to transactional memory (see eg N1961), but for now we
+ * must use compiler builtins that vary.
+ */
+#if (defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(_MSC_VER)) && !(defined(__IBMC__) || defined(__IBMCPP__))
+/* ICC, GCC, MSVC use Intel's _xbegin() interfaces for x86 instructions. */
+/* TODO: Only tested on GCC; is the header the same on the others?  Is there a minimum version for each compiler? */
+#include <immintrin.h>
+#define pg_htm_begin() (_xbegin() == _XBEGIN_STARTED)
+#define pg_htm_commit() _xend()
+#define pg_htm_abort() _xabort(0)
+#elif (defined(__IBMC__) || defined(__IBMCPP__))
+/* IBM XLC uses __TM_begin() etc for POWER instructions. */
+#error "IBM compiler support for HTM not yet implemented"
+#else
+#error "no hardware transactional memory support"
+#endif
+
+#endif							/* HAVE_HTM */
+
+#endif							/* HTM_H */
-- 
2.20.1

