[Pkg-mysql-commits] [mariadb-5.5] 02/04: Imported Upstream version 5.5.52

Otto Kekäläinen otto at moszumanska.debian.org
Wed Sep 14 18:40:49 UTC 2016


This is an automated email from the git hooks/post-receive script.

otto pushed a commit to branch ubuntu-14.04
in repository mariadb-5.5.

commit 4d305fb965e36693713a162666255fbdcb95b04c
Author: Otto Kekäläinen <otto at seravo.fi>
Date:   Wed Sep 14 20:54:15 2016 +0300

    Imported Upstream version 5.5.52
---
 Docs/INFO_SRC                                      |  10 +-
 VERSION                                            |   2 +-
 client/mysqlcheck.c                                |  71 ++++-----
 client/mysqlimport.c                               |  58 +++++--
 include/my_sys.h                                   |   4 +-
 libmysqld/lib_sql.cc                               |   6 +
 mysql-test/include/report-features.test            |  12 --
 mysql-test/mysql-test-run.pl                       |  18 ---
 mysql-test/r/ctype_utf32.result                    |   3 +
 mysql-test/r/func_group.result                     |  39 +++++
 mysql-test/r/func_math.result                      |  12 ++
 mysql-test/r/func_misc.result                      |   7 +
 mysql-test/r/group_min_max_innodb.result           |  16 ++
 mysql-test/r/loaddata.result                       |  26 ++-
 mysql-test/r/merge.result                          |  17 ++
 mysql-test/r/myisam_enable_keys-10506.result       | 114 ++++++++++++++
 mysql-test/r/mysqlcheck.result                     |  81 +++++++++-
 mysql-test/r/ps.result                             |  33 +++-
 mysql-test/r/ps_1general.result                    |   2 +
 mysql-test/r/range.result                          |  31 ++++
 mysql-test/r/range_mrr_icp.result                  |  31 ++++
 mysql-test/r/sp-prelocking.result                  |  20 +++
 mysql-test/r/type_date.result                      |   2 +
 mysql-test/r/type_uint.result                      |  19 +++
 mysql-test/r/view.result                           |  15 ++
 mysql-test/r/xtradb_mrr.result                     |   4 +-
 mysql-test/std_data/bug20683959loaddata.txt        |   1 +
 .../r/binlog_dmls_on_tmp_tables_readonly.result    |  58 +++++++
 .../t/binlog_dmls_on_tmp_tables_readonly.test      |  91 +++++++++++
 .../suite/funcs_1/datadict/processlist_priv.inc    |   2 +-
 mysql-test/suite/innodb/r/innodb-fkcheck.result    |  87 +++++++++++
 mysql-test/suite/innodb/r/innodb_bug54044.result   |  13 +-
 mysql-test/suite/innodb/t/innodb-fkcheck.test      | 115 ++++++++++++++
 mysql-test/suite/innodb/t/innodb_bug54044.test     |  10 +-
 mysql-test/suite/perfschema/r/aggregate.result     | 102 ------------
 mysql-test/suite/perfschema/t/aggregate.test       | 174 ---------------------
 mysql-test/suite/plugins/r/pam_cleartext.result    |   3 +
 mysql-test/suite/plugins/t/pam.test                |   3 +-
 mysql-test/suite/plugins/t/pam_cleartext.test      |  16 +-
 .../suite/sys_vars/r/general_log_file_basic.result |  10 ++
 .../sys_vars/r/slow_query_log_file_basic.result    |  10 ++
 .../suite/sys_vars/t/general_log_file_basic.test   |  14 ++
 .../sys_vars/t/slow_query_log_file_basic.test      |  14 ++
 mysql-test/t/ctype_utf32.test                      |   5 +
 mysql-test/t/func_group.test                       |  31 ++++
 mysql-test/t/func_math.test                        |  12 ++
 mysql-test/t/func_misc.test                        |  10 ++
 mysql-test/t/group_min_max_innodb.test             |  13 ++
 mysql-test/t/loaddata.test                         |  25 ++-
 mysql-test/t/merge.test                            |  13 ++
 mysql-test/t/myisam_enable_keys-10506.test         | 117 ++++++++++++++
 mysql-test/t/mysqlcheck.test                       |  52 +++++-
 mysql-test/t/named_pipe.test                       |   9 ++
 mysql-test/t/ps.test                               |  29 +++-
 mysql-test/t/ps_1general.test                      |   7 +
 mysql-test/t/range.test                            |  29 ++++
 mysql-test/t/sp-prelocking.test                    |  26 +++
 mysql-test/t/type_date.test                        |  15 +-
 mysql-test/t/type_uint.test                        |   8 +
 mysql-test/t/view.test                             |  15 ++
 mysql-test/t/xtradb_mrr.test                       |   4 +-
 mysys/my_context.c                                 |  17 +-
 mysys/my_redel.c                                   |   7 +-
 mysys/my_static.c                                  |   1 +
 plugin/feedback/url_http.cc                        |   1 +
 regex/split.c                                      |   4 +
 scripts/mysql_secure_installation.pl.in            |   2 +-
 scripts/mysql_secure_installation.sh               |   2 +-
 sql/event_scheduler.cc                             |  33 +---
 sql/field.cc                                       |   2 +-
 sql/handler.cc                                     |   3 +-
 sql/item.cc                                        |  28 +++-
 sql/item_func.cc                                   |   3 +
 sql/item_subselect.cc                              |  66 +++++---
 sql/item_subselect.h                               |  39 +++--
 sql/item_sum.cc                                    |   4 +-
 sql/mysqld.cc                                      |  32 ++--
 sql/net_serv.cc                                    |   6 +-
 sql/opt_range.cc                                   |   2 +
 sql/sql_admin.cc                                   |  14 +-
 sql/sql_base.cc                                    |  11 +-
 sql/sql_class.cc                                   |   2 +
 sql/sql_class.h                                    |   8 +-
 sql/sql_insert.cc                                  |   2 +-
 sql/sql_load.cc                                    |  77 +++++----
 sql/sql_plugin.cc                                  | 126 +++++++--------
 sql/sql_plugin.h                                   |   2 +
 sql/sql_select.cc                                  |  30 +++-
 sql/sql_show.cc                                    |  19 ++-
 sql/sql_union.cc                                   |   6 +
 sql/sys_vars.cc                                    |  21 ++-
 storage/innobase/dict/dict0crea.c                  |   8 +-
 storage/innobase/handler/ha_innodb.cc              |   3 +-
 storage/innobase/include/os0sync.h                 |  11 +-
 storage/innobase/include/row0mysql.h               |   5 +-
 storage/innobase/include/sync0sync.ic              |   5 +
 storage/innobase/page/page0cur.c                   |  20 +++
 storage/innobase/row/row0merge.c                   |   2 +-
 storage/innobase/row/row0mysql.c                   |  23 ++-
 storage/innobase/trx/trx0roll.c                    |   2 +-
 storage/myisam/ha_myisam.cc                        |   3 +-
 storage/tokudb/ft-index/ft/txn/txn.cc              |  15 +-
 storage/xtradb/dict/dict0crea.c                    |   8 +-
 storage/xtradb/handler/ha_innodb.cc                |   4 +-
 storage/xtradb/include/log0online.h                |   4 +-
 storage/xtradb/include/os0sync.h                   |  11 +-
 storage/xtradb/include/row0mysql.h                 |   5 +-
 storage/xtradb/include/sync0sync.ic                |   5 +
 storage/xtradb/include/univ.i                      |   2 +-
 storage/xtradb/log/log0online.c                    |   4 +-
 storage/xtradb/log/log0recv.c                      |  46 ++++--
 storage/xtradb/page/page0cur.c                     |  20 +++
 storage/xtradb/row/row0merge.c                     |   2 +-
 storage/xtradb/row/row0mysql.c                     |  23 ++-
 storage/xtradb/trx/trx0roll.c                      |   2 +-
 strings/ctype-ucs2.c                               |  14 +-
 strings/ctype-utf8.c                               |   8 +-
 strings/decimal.c                                  |   4 +
 support-files/mysql.server.sh                      |   2 +-
 win/packaging/CMakeLists.txt                       |  11 +-
 win/packaging/create_msi.cmake.in                  |   1 +
 121 files changed, 1923 insertions(+), 716 deletions(-)

diff --git a/Docs/INFO_SRC b/Docs/INFO_SRC
index 75b6356..f2751c3 100644
--- a/Docs/INFO_SRC
+++ b/Docs/INFO_SRC
@@ -1,8 +1,8 @@
-commit: 12ae840375fe30da1c23647facaa0678858d6d92
-date: 2016-06-16 22:04:24 +0300
-build-date: 2016-06-16 21:08:07 +0200 
-short: 12ae840
+commit: 0da39caceea7733a94d898427d63ba2670160af4
+date: 2016-09-12 16:42:05 +0200
+build-date: 2016-09-12 16:54:58 +0200 
+short: 0da39ca
 branch: HEAD
 
 
-MySQL source 5.5.50
+MySQL source 5.5.52
diff --git a/VERSION b/VERSION
index 58a6b36..acabf9b 100644
--- a/VERSION
+++ b/VERSION
@@ -1,4 +1,4 @@
 MYSQL_VERSION_MAJOR=5
 MYSQL_VERSION_MINOR=5
-MYSQL_VERSION_PATCH=50
+MYSQL_VERSION_PATCH=52
 MYSQL_VERSION_EXTRA=
diff --git a/client/mysqlcheck.c b/client/mysqlcheck.c
index 011a0e2..a07fc77 100644
--- a/client/mysqlcheck.c
+++ b/client/mysqlcheck.c
@@ -232,7 +232,7 @@ static int process_selected_tables(char *db, char **table_names, int tables);
 static int process_all_tables_in_db(char *database);
 static int process_one_db(char *database);
 static int use_db(char *database);
-static int handle_request_for_tables(char *tables, size_t length, my_bool view);
+static int handle_request_for_tables(char *, size_t, my_bool, my_bool);
 static int dbConnect(char *host, char *user,char *passwd);
 static void dbDisconnect(char *host);
 static void DBerror(MYSQL *mysql, const char *when);
@@ -566,7 +566,7 @@ static int process_selected_tables(char *db, char **table_names, int tables)
     }
     *--end = 0;
     handle_request_for_tables(table_names_comma_sep + 1, tot_length - 1,
-                              opt_do_views != 0);
+                              opt_do_views != 0, opt_all_in_1);
     my_free(table_names_comma_sep);
   }
   else
@@ -577,7 +577,7 @@ static int process_selected_tables(char *db, char **table_names, int tables)
       view= is_view(table);
       if (view < 0)
         continue;
-      handle_request_for_tables(table, table_len, (view == 1));
+      handle_request_for_tables(table, table_len, view == 1, opt_all_in_1);
     }
   DBUG_RETURN(0);
 } /* process_selected_tables */
@@ -605,13 +605,9 @@ static char *fix_table_name(char *dest, char *src)
   *dest++= '`';
   for (; *src; src++)
   {
-    switch (*src) {
-    case '`':            /* escape backtick character */
+    if (*src == '`')
       *dest++= '`';
-      /* fall through */
-    default:
-      *dest++= *src;
-    }
+    *dest++= *src;
   }
   *dest++= '`';
 
@@ -700,9 +696,9 @@ static int process_all_tables_in_db(char *database)
     *--end = 0;
     *--views_end = 0;
     if (tot_length)
-      handle_request_for_tables(tables + 1, tot_length - 1, FALSE);
+      handle_request_for_tables(tables + 1, tot_length - 1, FALSE, opt_all_in_1);
     if (tot_views_length)
-      handle_request_for_tables(views + 1, tot_views_length - 1, TRUE);
+      handle_request_for_tables(views + 1, tot_views_length - 1, TRUE, opt_all_in_1);
     my_free(tables);
     my_free(views);
   }
@@ -728,7 +724,7 @@ static int process_all_tables_in_db(char *database)
            !strcmp(row[0], "slow_log")))
         continue;                               /* Skip logging tables */
 
-      handle_request_for_tables(row[0], fixed_name_length(row[0]), view);
+      handle_request_for_tables(row[0], fixed_name_length(row[0]), view, opt_all_in_1);
     }
   }
   mysql_free_result(res);
@@ -756,7 +752,7 @@ static int fix_table_storage_name(const char *name)
 
   if (strncmp(name, "#mysql50#", 9))
     DBUG_RETURN(1);
-  my_snprintf(qbuf, sizeof(qbuf), "RENAME TABLE `%s` TO `%s`",
+  my_snprintf(qbuf, sizeof(qbuf), "RENAME TABLE %`s TO %`s",
               name, name + 9);
 
   rc= run_query(qbuf);
@@ -773,7 +769,7 @@ static int fix_database_storage_name(const char *name)
 
   if (strncmp(name, "#mysql50#", 9))
     DBUG_RETURN(1);
-  my_snprintf(qbuf, sizeof(qbuf), "ALTER DATABASE `%s` UPGRADE DATA DIRECTORY "
+  my_snprintf(qbuf, sizeof(qbuf), "ALTER DATABASE %`s UPGRADE DATA DIRECTORY "
               "NAME", name);
   rc= run_query(qbuf);
   if (verbose)
@@ -787,13 +783,11 @@ static int rebuild_table(char *name)
   int rc= 0;
   DBUG_ENTER("rebuild_table");
 
-  query= (char*)my_malloc(sizeof(char) * (12 + fixed_name_length(name) + 6 + 1),
+  query= (char*)my_malloc(sizeof(char) * (12 + strlen(name) + 6 + 1),
                           MYF(MY_WME));
   if (!query)
     DBUG_RETURN(1);
-  ptr= strmov(query, "ALTER TABLE ");
-  ptr= fix_table_name(ptr, name);
-  ptr= strxmov(ptr, " FORCE", NullS);
+  ptr= strxmov(query, "ALTER TABLE ", name, " FORCE", NullS);
   if (mysql_real_query(sock, query, (ulong)(ptr - query)))
   {
     fprintf(stderr, "Failed to %s\n", query);
@@ -849,7 +843,8 @@ static int disable_binlog()
   return run_query(stmt);
 }
 
-static int handle_request_for_tables(char *tables, size_t length, my_bool view)
+static int handle_request_for_tables(char *tables, size_t length,
+                                     my_bool view, my_bool dont_quote)
 {
   char *query, *end, options[100], message[100];
   char table_name_buff[NAME_CHAR_LEN*2*2+1], *table_name;
@@ -907,7 +902,7 @@ static int handle_request_for_tables(char *tables, size_t length, my_bool view)
 
   if (!(query =(char *) my_malloc(query_size, MYF(MY_WME))))
     DBUG_RETURN(1);
-  if (opt_all_in_1)
+  if (dont_quote)
   {
     DBUG_ASSERT(strlen(op)+strlen(tables)+strlen(options)+8+1 <= query_size);
 
@@ -950,6 +945,13 @@ static int handle_request_for_tables(char *tables, size_t length, my_bool view)
   DBUG_RETURN(0);
 }
 
+static void insert_table_name(DYNAMIC_ARRAY *arr, char *in, size_t dblen)
+{
+  char buf[NAME_LEN*2+2];
+  in[dblen]= 0;
+  my_snprintf(buf, sizeof(buf), "%`s.%`s", in, in + dblen + 1);
+  insert_dynamic(arr, (uchar*) buf);
+}
 
 static void print_result()
 {
@@ -957,16 +959,13 @@ static void print_result()
   MYSQL_ROW row;
   char prev[(NAME_LEN+9)*3+2];
   char prev_alter[MAX_ALTER_STR_SIZE];
-  char *db_name;
-  uint length_of_db;
+  size_t length_of_db= strlen(sock->db);
   uint i;
   my_bool found_error=0, table_rebuild=0;
   DYNAMIC_ARRAY *array4repair= &tables4repair;
   DBUG_ENTER("print_result");
 
   res = mysql_use_result(sock);
-  db_name= sock->db;
-  length_of_db= strlen(db_name);
 
   prev[0] = '\0';
   prev_alter[0]= 0;
@@ -990,16 +989,10 @@ static void print_result()
           if (prev_alter[0])
             insert_dynamic(&alter_table_cmds, (uchar*) prev_alter);
           else
-          {
-            char *table_name= prev + (length_of_db+1);
-            insert_dynamic(&tables4rebuild, (uchar*) table_name);
-          }
+            insert_table_name(&tables4rebuild, prev, length_of_db);
         }
         else
-        {
-          char *table_name= prev + (length_of_db+1);
-          insert_dynamic(array4repair, (uchar*) table_name);
-        }
+          insert_table_name(array4repair, prev, length_of_db);
       }
       array4repair= &tables4repair;
       found_error=0;
@@ -1066,16 +1059,10 @@ static void print_result()
       if (prev_alter[0])
         insert_dynamic(&alter_table_cmds, (uchar*) prev_alter);
       else
-      {
-        char *table_name= prev + (length_of_db+1);
-        insert_dynamic(&tables4rebuild, (uchar*) table_name);
-      }
+        insert_table_name(&tables4rebuild, prev, length_of_db);
     }
     else
-    {
-      char *table_name= prev + (length_of_db+1);
-      insert_dynamic(array4repair, (uchar*) table_name);
-    }
+      insert_table_name(array4repair, prev, length_of_db);
   }
   mysql_free_result(res);
   DBUG_VOID_RETURN;
@@ -1209,7 +1196,7 @@ int main(int argc, char **argv)
     for (i = 0; i < tables4repair.elements ; i++)
     {
       char *name= (char*) dynamic_array_ptr(&tables4repair, i);
-      handle_request_for_tables(name, fixed_name_length(name), FALSE);
+      handle_request_for_tables(name, fixed_name_length(name), FALSE, TRUE);
     }
     for (i = 0; i < tables4rebuild.elements ; i++)
       rebuild_table((char*) dynamic_array_ptr(&tables4rebuild, i));
@@ -1220,7 +1207,7 @@ int main(int argc, char **argv)
     for (i = 0; i < views4repair.elements ; i++)
     {
       char *name= (char*) dynamic_array_ptr(&views4repair, i);
-      handle_request_for_tables(name, fixed_name_length(name), TRUE);
+      handle_request_for_tables(name, fixed_name_length(name), TRUE, TRUE);
     }
   }
   ret= test(first_error);
diff --git a/client/mysqlimport.c b/client/mysqlimport.c
index 8fab3f2..850a851 100644
--- a/client/mysqlimport.c
+++ b/client/mysqlimport.c
@@ -37,6 +37,7 @@
 
 /* Global Thread counter */
 uint counter= 0;
+pthread_mutex_t init_mutex;
 pthread_mutex_t counter_mutex;
 pthread_cond_t count_threshhold;
 
@@ -421,8 +422,19 @@ static MYSQL *db_connect(char *host, char *database,
   MYSQL *mysql;
   if (verbose)
     fprintf(stdout, "Connecting to %s\n", host ? host : "localhost");
-  if (!(mysql= mysql_init(NULL)))
-    return 0;
+  if (opt_use_threads && !lock_tables)
+  {
+    pthread_mutex_lock(&init_mutex);
+    if (!(mysql= mysql_init(NULL)))
+    {
+      pthread_mutex_unlock(&init_mutex);
+      return 0;
+    }
+    pthread_mutex_unlock(&init_mutex);
+  }
+  else
+    if (!(mysql= mysql_init(NULL)))
+      return 0;
   if (opt_compress)
     mysql_options(mysql,MYSQL_OPT_COMPRESS,NullS);
   if (opt_local_file)
@@ -605,7 +617,7 @@ error:
   pthread_cond_signal(&count_threshhold);
   pthread_mutex_unlock(&counter_mutex);
   mysql_thread_end();
-
+  pthread_exit(0);
   return 0;
 }
 
@@ -629,15 +641,31 @@ int main(int argc, char **argv)
 
   if (opt_use_threads && !lock_tables)
   {
-    pthread_t mainthread;            /* Thread descriptor */
-    pthread_attr_t attr;          /* Thread attributes */
+    char **save_argv;
+    uint worker_thread_count= 0, table_count= 0, i= 0;
+    pthread_t *worker_threads;       /* Thread descriptor */
+    pthread_attr_t attr;             /* Thread attributes */
     pthread_attr_init(&attr);
     pthread_attr_setdetachstate(&attr,
-                                PTHREAD_CREATE_DETACHED);
+                                PTHREAD_CREATE_JOINABLE);
 
+    pthread_mutex_init(&init_mutex, NULL);
     pthread_mutex_init(&counter_mutex, NULL);
     pthread_cond_init(&count_threshhold, NULL);
 
+    /* Count the number of tables. This number denotes the total number
+       of threads spawn.
+    */
+    save_argv= argv;
+    for (table_count= 0; *argv != NULL; argv++)
+      table_count++;
+    argv= save_argv;
+
+    if (!(worker_threads= (pthread_t*) my_malloc(table_count *
+                                                 sizeof(*worker_threads),
+                                                 MYF(0))))
+      return -2;
+
     for (counter= 0; *argv != NULL; argv++) /* Loop through tables */
     {
       pthread_mutex_lock(&counter_mutex);
@@ -652,15 +680,16 @@ int main(int argc, char **argv)
       counter++;
       pthread_mutex_unlock(&counter_mutex);
       /* now create the thread */
-      if (pthread_create(&mainthread, &attr, worker_thread, 
-                         (void *)*argv) != 0)
+      if (pthread_create(&worker_threads[worker_thread_count], &attr,
+                         worker_thread, (void *)*argv) != 0)
       {
         pthread_mutex_lock(&counter_mutex);
         counter--;
         pthread_mutex_unlock(&counter_mutex);
-        fprintf(stderr,"%s: Could not create thread\n",
-                my_progname);
+        fprintf(stderr,"%s: Could not create thread\n", my_progname);
+        continue;
       }
+      worker_thread_count++;
     }
 
     /*
@@ -675,9 +704,18 @@ int main(int argc, char **argv)
       pthread_cond_timedwait(&count_threshhold, &counter_mutex, &abstime);
     }
     pthread_mutex_unlock(&counter_mutex);
+    pthread_mutex_destroy(&init_mutex);
     pthread_mutex_destroy(&counter_mutex);
     pthread_cond_destroy(&count_threshhold);
     pthread_attr_destroy(&attr);
+
+    for(i= 0; i < worker_thread_count; i++)
+    {
+      if (pthread_join(worker_threads[i], NULL))
+        fprintf(stderr,"%s: Could not join worker thread.\n", my_progname);
+    }
+
+    my_free(worker_threads);
   }
   else
   {
diff --git a/include/my_sys.h b/include/my_sys.h
index 7e37fe5..001769a 100644
--- a/include/my_sys.h
+++ b/include/my_sys.h
@@ -1,5 +1,5 @@
 /* Copyright (c) 2000, 2013, Oracle and/or its affiliates.
-   Copyright (c) 2010, 2013, Monty Program Ab.
+   Copyright (c) 2010, 2016, Monty Program Ab.
 
    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
@@ -246,7 +246,7 @@ extern my_bool my_use_symdir;
 extern ulong	my_default_record_cache_size;
 extern my_bool  my_disable_locking, my_disable_async_io,
                 my_disable_flush_key_blocks, my_disable_symlinks;
-extern my_bool my_disable_sync;
+extern my_bool my_disable_sync, my_disable_copystat_in_redel;
 extern char	wild_many,wild_one,wild_prefix;
 extern const char *charsets_dir;
 /* from default.c */
diff --git a/libmysqld/lib_sql.cc b/libmysqld/lib_sql.cc
index 3d6ca5a..623569c 100644
--- a/libmysqld/lib_sql.cc
+++ b/libmysqld/lib_sql.cc
@@ -341,6 +341,12 @@ static int emb_stmt_execute(MYSQL_STMT *stmt)
   THD *thd;
   my_bool res;
 
+  if (stmt->param_count && !stmt->bind_param_done)
+  {
+    set_stmt_error(stmt, CR_PARAMS_NOT_BOUND, unknown_sqlstate, NULL);
+    DBUG_RETURN(1);
+  }
+
   int4store(header, stmt->stmt_id);
   header[4]= (uchar) stmt->flags;
   thd= (THD*)stmt->mysql->thd;
diff --git a/mysql-test/include/report-features.test b/mysql-test/include/report-features.test
deleted file mode 100644
index 75879f6..0000000
--- a/mysql-test/include/report-features.test
+++ /dev/null
@@ -1,12 +0,0 @@
-#
-# show server variables
-#
-
---disable_query_log
---echo ===== ENGINES =====
-show engines; 
---echo ===== VARIABLES =====
-show variables; 
---echo ===== STOP =====
---enable_query_log
-exit;
diff --git a/mysql-test/mysql-test-run.pl b/mysql-test/mysql-test-run.pl
index a85bed8..7bbbcea 100755
--- a/mysql-test/mysql-test-run.pl
+++ b/mysql-test/mysql-test-run.pl
@@ -276,7 +276,6 @@ my $opt_port_base= $ENV{'MTR_PORT_BASE'} || "auto";
 my $build_thread= 0;
 
 my $opt_record;
-my $opt_report_features;
 
 our $opt_resfile= $ENV{'MTR_RESULT_FILE'} || 0;
 
@@ -422,21 +421,6 @@ sub main {
   my $tests= collect_test_cases($opt_reorder, $opt_suites, \@opt_cases, \@opt_skip_test_list);
   mark_time_used('collect');
 
-  if ( $opt_report_features ) {
-    # Put "report features" as the first test to run
-    my $tinfo = My::Test->new
-      (
-       name           => 'report_features',
-       # No result_file => Prints result
-       path           => 'include/report-features.test',
-       template_path  => "include/default_my.cnf",
-       master_opt     => [],
-       slave_opt      => [],
-       suite          => 'main',
-      );
-    unshift(@$tests, $tinfo);
-  }
-
   #######################################################################
   my $num_tests= @$tests;
   if ( $opt_parallel eq "auto" ) {
@@ -1203,7 +1187,6 @@ sub command_line_setup {
              'client-libdir=s'          => \$path_client_libdir,
 
              # Misc
-             'report-features'          => \$opt_report_features,
              'comment=s'                => \$opt_comment,
              'fast'                     => \$opt_fast,
 	     'force-restart'            => \$opt_force_restart,
@@ -6569,7 +6552,6 @@ Misc options
   gprof                 Collect profiling information using gprof.
   experimental=<file>   Refer to list of tests considered experimental;
                         failures will be marked exp-fail instead of fail.
-  report-features       First run a "test" that reports mysql features
   timestamp             Print timestamp before each test report line
   timediff              With --timestamp, also print time passed since
                         *previous* test started
diff --git a/mysql-test/r/ctype_utf32.result b/mysql-test/r/ctype_utf32.result
index 1f316b7..ae55f2c 100644
--- a/mysql-test/r/ctype_utf32.result
+++ b/mysql-test/r/ctype_utf32.result
@@ -1269,6 +1269,9 @@ CHAR_LENGTH(TRIM(BOTH 0x61 FROM _utf32 0x00000061))
 SELECT CHAR_LENGTH(TRIM(BOTH 0x00 FROM _utf32 0x00000061));
 CHAR_LENGTH(TRIM(BOTH 0x00 FROM _utf32 0x00000061))
 1
+select hex(lower(cast(0xffff0000 as char character set utf32))) as c;
+c
+FFFF0000
 #
 # End of 5.5 tests
 #
diff --git a/mysql-test/r/func_group.result b/mysql-test/r/func_group.result
index ac076ec..38fae2f 100644
--- a/mysql-test/r/func_group.result
+++ b/mysql-test/r/func_group.result
@@ -2270,3 +2270,42 @@ t2_id	GROUP_CONCAT(IF (t6.b, t6.f, t5.f) ORDER BY 1)
 EXECUTE stmt;
 t2_id	GROUP_CONCAT(IF (t6.b, t6.f, t5.f) ORDER BY 1)
 DROP TABLE t1,t2,t3,t4,t5,t6;
+#
+# MDEV-10500 CASE/IF Statement returns multiple values and shifts further result values to the next column
+#
+CREATE TABLE t1 (
+id int not null AUTO_INCREMENT,
+active bool not null,
+data1 bigint,
+data2 bigint,
+data3 bigint,
+primary key (id)
+);
+INSERT INTO t1 (active,data1,data2,data3) VALUES (1,null,100,200);
+SELECT
+CASE WHEN active THEN SUM(data1) END AS C_1,
+SUM(data2) AS C_2,
+SUM(data3) AS C_3
+FROM t1;
+C_1	C_2	C_3
+NULL	100	200
+SELECT
+IF(active, SUM(data1), 5) AS C_1,
+SUM(data2) AS C_2,
+SUM(data3) AS C_3
+FROM t1;
+C_1	C_2	C_3
+NULL	100	200
+DROP TABLE t1;
+#
+# MDEV-10468 Assertion `nr >= 0.0' failed in Item_sum_std::val_real()
+#
+SELECT STDDEV_POP(f) FROM (SELECT "1e+309" AS f UNION SELECT "-1e+309" AS f) tbl;
+STDDEV_POP(f)
+1.7976931348623157e308
+Warnings:
+Warning	1292	Truncated incorrect DOUBLE value: '1e+309'
+Warning	1292	Truncated incorrect DOUBLE value: '-1e+309'
+SELECT STDDEV(f) FROM (SELECT 1.7976931348623157e+308 AS f UNION SELECT -1.7976931348623157e+308 AS f) tbl;
+STDDEV(f)
+1.7976931348623157e308
diff --git a/mysql-test/r/func_math.result b/mysql-test/r/func_math.result
index d122d43..66bbb25 100644
--- a/mysql-test/r/func_math.result
+++ b/mysql-test/r/func_math.result
@@ -761,3 +761,15 @@ select 5 div 2.0;
 select 5.9 div 2, 1.23456789e3 DIV 2, 1.23456789e9 DIV 2, 1.23456789e19 DIV 2;
 5.9 div 2	1.23456789e3 DIV 2	1.23456789e9 DIV 2	1.23456789e19 DIV 2
 2	617	617283945	6172839450000000000
+#
+# MDEV-10467 Assertion `nr >= 0.0' failed in Item_sum_std::val_real()
+#
+CREATE TABLE t1 (i INT);
+INSERT INTO t1 VALUES (1),(2);
+SELECT STDDEV_SAMP(ROUND('0', 309)) FROM t1;
+STDDEV_SAMP(ROUND('0', 309))
+0
+DROP TABLE t1;
+#
+# End of 5.5 tests
+#
diff --git a/mysql-test/r/func_misc.result b/mysql-test/r/func_misc.result
index a121bd3..1c106ac 100644
--- a/mysql-test/r/func_misc.result
+++ b/mysql-test/r/func_misc.result
@@ -574,3 +574,10 @@ drop table t1;
 #
 # End of 5.5 tests
 #
+SELECT NAME_CONST('a', -(1 OR 2)) OR 1;
+ERROR HY000: Incorrect arguments to NAME_CONST
+SELECT NAME_CONST('a', -(1 AND 2)) OR 1;
+ERROR HY000: Incorrect arguments to NAME_CONST
+SELECT NAME_CONST('a', -(1)) OR 1;
+NAME_CONST('a', -(1)) OR 1
+1
diff --git a/mysql-test/r/group_min_max_innodb.result b/mysql-test/r/group_min_max_innodb.result
index c4d2fb8..1e3ee79 100644
--- a/mysql-test/r/group_min_max_innodb.result
+++ b/mysql-test/r/group_min_max_innodb.result
@@ -286,3 +286,19 @@ F	28	28
 F	29	29
 F	30	30
 DROP TABLE t0,t1,t2;
+#
+# MDEV-MariaDB daemon leaks memory with specific query
+#
+CREATE TABLE t1 (`voter_id` int(11) unsigned NOT NULL,
+`language_id` int(11) unsigned NOT NULL DEFAULT '1'
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+CREATE TABLE t2 (`voter_id` int(10) unsigned NOT NULL DEFAULT '0',
+`serialized_c` mediumblob) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+insert into t2 values (1,repeat("a",1000)),(2,repeat("a",1000)),(3,repeat("b",1000)),(4,repeat("c",1000)),(4,repeat("b",1000));
+SELECT GROUP_CONCAT(t1.language_id SEPARATOR ',') AS `translation_resources`, `d`.`serialized_c` FROM t2 AS `d` LEFT JOIN t1 ON `d`.`voter_id` = t1.`voter_id` GROUP BY `d`.`voter_id` ORDER BY 10-d.voter_id+RAND()*0;
+translation_resources	serialized_c
+NULL	ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc [...]
+NULL	bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb [...]
+NULL	aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa [...]
+NULL	aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa [...]
+drop table t1,t2;
diff --git a/mysql-test/r/loaddata.result b/mysql-test/r/loaddata.result
index 8ccc1a3..ba5c763 100644
--- a/mysql-test/r/loaddata.result
+++ b/mysql-test/r/loaddata.result
@@ -507,7 +507,7 @@ DROP TABLE t1;
 # Bug#11765139  58069: LOAD DATA INFILE: VALGRIND REPORTS INVALID MEMORY READS AND WRITES WITH U
 #
 CREATE TABLE t1(f1 INT);
-SELECT 0xE1BB30 INTO OUTFILE 't1.dat';
+SELECT 0xE1C330 INTO OUTFILE 't1.dat';
 LOAD DATA INFILE 't1.dat' IGNORE INTO TABLE t1 CHARACTER SET utf8;
 DROP TABLE t1;
 #
@@ -532,3 +532,27 @@ FIELDS TERMINATED BY 't' LINES TERMINATED BY '';
 Got one of the listed errors
 SET @@sql_mode= @old_mode;
 DROP TABLE t1;
+
+#
+#  Bug#23080148 - Backport of Bug#20683959.
+#  Bug#20683959 LOAD DATA INFILE IGNORES A SPECIFIC ROW SILENTLY
+#               UNDER DB CHARSET IS UTF8.
+#
+CREATE DATABASE d1 CHARSET latin1;
+USE d1;
+CREATE TABLE t1 (val TEXT);
+LOAD DATA INFILE '../../std_data/bug20683959loaddata.txt' INTO TABLE t1;
+SELECT COUNT(*) FROM t1;
+COUNT(*)
+1
+SELECT HEX(val) FROM t1;
+HEX(val)
+C38322525420406E696F757A656368756E3A20E98198E2889AF58081AEE7B99DE4B88AE383A3E7B99DE69690F58087B3E7B9A7EFBDA8E7B99DEFBDB3E7B99DE78999E880B3E7B8BAEFBDAAE7B9A7E89699E296A1E7B8BAE4BBA3EFBD8CE7B8BAEFBDA9E7B8B2E2889AE38184E7B99DEFBDB3E7B99DE4B88AE383A3E7B99DE69690F58087B3E7B9A7EFBDA8E7B99DEFBDB3E7B99DE5B3A8EFBD84E8ABA0EFBDA8E89C89F580948EE599AAE7B8BAEFBDAAE7B8BAE9A198EFBDA9EFBDB1E7B9A7E581B5E289A0E7B8BAEFBDBEE7B9A7E9A194EFBDA9E882B4EFBDA5EFBDB5E980A7F5808B96E28693E99EABE38287E58F99E7B8BAE58AB1 [...]
+CREATE DATABASE d2 CHARSET utf8;
+USE d2;
+CREATE TABLE t1 (val TEXT);
+LOAD DATA INFILE '../../std_data/bug20683959loaddata.txt' INTO TABLE t1;
+ERROR HY000: Invalid utf8 character string: '�"RT @niouzechun: \9058\221A'
+DROP TABLE d1.t1, d2.t1;
+DROP DATABASE d1;
+DROP DATABASE d2;
diff --git a/mysql-test/r/merge.result b/mysql-test/r/merge.result
index 41ee148..66ba6ce 100644
--- a/mysql-test/r/merge.result
+++ b/mysql-test/r/merge.result
@@ -3832,4 +3832,21 @@ test.m1	repair	error	Corrupt
 # Clean-up.
 drop tables m1, t1, t4;
 drop view t3;
+#
+# MDEV-10424 - Assertion `ticket == __null' failed in
+#              MDL_request::set_type
+#
+CREATE TABLE t1 (f1 INT) ENGINE=MyISAM;
+CREATE TABLE tmerge (f1 INT) ENGINE=MERGE UNION=(t1);
+PREPARE stmt FROM "ANALYZE TABLE tmerge, t1";
+EXECUTE stmt;
+Table	Op	Msg_type	Msg_text
+test.tmerge	analyze	note	The storage engine for the table doesn't support analyze
+test.t1	analyze	status	Table is already up to date
+EXECUTE stmt;
+Table	Op	Msg_type	Msg_text
+test.tmerge	analyze	note	The storage engine for the table doesn't support analyze
+test.t1	analyze	status	Table is already up to date
+DEALLOCATE PREPARE stmt;
+DROP TABLE t1, tmerge;
 End of 5.5 tests
diff --git a/mysql-test/r/myisam_enable_keys-10506.result b/mysql-test/r/myisam_enable_keys-10506.result
new file mode 100644
index 0000000..547f001
--- /dev/null
+++ b/mysql-test/r/myisam_enable_keys-10506.result
@@ -0,0 +1,114 @@
+CREATE TABLE t1 (
+pk INT AUTO_INCREMENT,
+i INT,
+d DATE,
+dt DATETIME,
+v VARCHAR(1),
+PRIMARY KEY (pk),
+KEY (dt)
+) ENGINE=MyISAM;
+INSERT INTO t1 (i, d, dt, v) VALUES 
+(9, '2005-07-23', '2004-05-13 01:01:39', 't'),
+(2, '2009-11-01', '2003-12-24 07:39:29', 'h'),
+(6, NULL, '2008-07-03 05:32:22', 'l'),
+(6, '2007-07-16', '2008-08-28 18:46:11', 'j'),
+(5, NULL, '2001-07-12 21:27:00', 'h'),
+(3, '2007-07-22', '1900-01-01 00:00:00', 'p'),
+(2, '2000-11-21', '2007-05-25 11:58:54', 'g'),
+(6, '1900-01-01', '2009-06-03 17:11:10', 'i'),
+(2, '2008-02-10', '2001-06-15 16:20:07', 'p'),
+(3, '2009-06-04', '1900-01-01 00:00:00', 'h'),
+(9, '2007-04-25', '1900-01-01 00:00:00', 'e'),
+(9, '2006-03-02', '1900-01-01 00:00:00', 'e'),
+(1, '1900-01-01', '2002-11-08 09:33:27', 'u'),
+(7, '2008-07-13', '2007-08-07 17:35:52', 'j'),
+(0, '2004-11-12', '2006-05-01 00:00:00', 'e'),
+(0, '1900-01-01', '2003-05-01 00:00:00', 'z'),
+(1, '2009-09-02', '2007-02-12 09:30:49', 'w'),
+(0, '2004-11-06', '1900-01-01 00:00:00', 't'),
+(4, '2003-01-06', '2002-07-03 02:51:11', 'i'),
+(6, '2006-01-14', '2008-02-26 04:57:32', 'i'),
+(0, '2002-01-19', '2009-02-12 00:00:00', 'i'),
+(8, '2007-02-12', '1900-01-01 00:00:00', 'b'),
+(4, '1900-01-01', '2001-05-16 05:28:40', 'm'),
+(2, '2005-07-16', NULL, 'j'),
+(1, '2004-09-04', '2001-01-24 21:45:18', 'v'),
+(3, '2009-07-01', NULL, NULL),
+(2, '2009-07-21', '2002-07-24 00:00:00', 'h'),
+(4, NULL, '2001-11-03 12:22:30', 'q'),
+(1, '2002-06-22', '2008-06-17 03:17:59', 'f'),
+(7, '2005-06-23', '2005-12-24 00:00:00', 'p'),
+(6, '2001-05-20', '2008-10-23 00:00:00',  NULL),
+(3, '2001-10-01', '2000-10-12 16:32:35', 'o'),
+(3, '2001-01-07', '2005-09-11 10:09:54', 'w'),
+(6, '2007-11-02', '2009-09-10 01:44:18', 'l'),
+(6, NULL, NULL, 'i'),
+(9, NULL, '2002-05-18 15:21:55', 'd'),
+(4, '2008-12-21', '2004-10-15 10:09:54', 'j'),
+(6, '2003-10-05', '2009-07-13 03:51:02', 'e'),
+(2, '2001-03-03', '1900-01-01 00:00:00', 'e'),
+(2, '2007-04-04', '2001-11-08 21:14:52', 'q'),
+(5, NULL, '2006-12-02 00:00:00', 'm'),
+(0, '2009-01-04', '1900-01-01 00:00:00', NULL),
+(8, '2008-04-03', '2005-01-01 11:55:18', 'q'),
+(8, NULL, '2005-02-28 03:44:02', 'w'),
+(0, '2003-08-22', NULL, 'c'),
+(9, '1900-01-01', NULL, 'y'),
+(NULL, NULL, '2006-08-25 16:28:09', 'g'),
+(5, '2004-07-04', '2002-08-11 00:00:00', 'z'),
+(1, '1900-01-01', '2007-07-22 21:19:18', 'm'),
+(2, '2007-02-04', '2006-02-10 18:41:38', 't'),
+(2, '1900-01-01', '2009-02-16 14:58:58', 'd'),
+(7, '2001-03-14', '2007-08-14 00:00:00', 'h'),
+(0, NULL, '1900-01-01 00:00:00', NULL),
+(1, '2008-10-05', NULL, 'f'),
+(6, '2001-11-25', '2008-12-03 06:59:23', 'l'),
+(NULL, '2003-01-27', '2008-10-04 00:00:00', 'g'),
+(8, '2008-08-08', '2009-07-07 07:00:21', 'v'),
+(8, '2006-07-03', '2001-04-15 00:00:00', NULL),
+(5, '2002-11-21', '2007-07-08 04:01:58', 'm'),
+(5, '2006-04-08', '2007-09-23 00:01:35', 'i'),
+(5, '2001-05-06', '2008-05-15 00:00:00', 'h'),
+(7, '1900-01-01', '1900-01-01 00:00:00', 'u'),
+(30, '2007-04-16', '2004-03-05 23:35:38', 'o'),
+(NULL, '1900-01-01', '2007-08-25 01:32:47', 'z'),
+(6, '2004-12-03', '1900-01-01 00:00:00', 'o'),
+(8, '2001-06-23', '1900-01-01 00:00:00', 'f'),
+(NULL, '2008-12-15', '2001-05-19 08:28:28', 'a'),
+(9, '2000-02-15', '2009-09-03 06:07:22', 'd'),
+(2, '2001-08-05', '2006-10-08 07:17:27', 'k'),
+(5, '2004-01-17', '2003-09-06 20:36:01', 'd'),
+(4, '2003-10-01', '2001-02-05 18:10:49', 'u'),
+(4, '2003-07-28', '2001-01-07 16:11:37', 'h'),
+(0, '1900-01-01', '2008-08-01 05:26:38', 'w'),
+(9, '1900-01-01', '2001-05-08 00:00:00', 't'),
+(1, '2000-04-17', '2008-07-10 21:26:28', 'i'),
+(8, '2002-01-05', '2006-08-06 20:56:35', 'k'),
+(9, '2001-04-10', '2003-02-17 00:00:00', 'z'),
+(0, '2009-12-04', NULL, 'h'),
+(7, NULL, '2004-10-27 00:29:57', 'h'),
+(2, '2006-03-07', '2008-03-04 06:14:13', 'b'),
+(0, '2001-10-15', '2001-03-17 00:00:00', 'm'),
+(5, '1900-01-01', '2009-02-21 11:35:50', 'i'),
+(4, NULL, '1900-01-01 00:00:00', 'w'),
+(5, '2009-04-05', '1900-01-01 00:00:00', 'm'),
+(6, '2001-03-19', '2001-04-12 00:00:00', 'q'),
+(NULL, '2009-12-08', '2001-12-04 20:21:01', 'k'),
+(2, '2005-02-09', '2001-05-27 08:41:01', 'l'),
+(9, '2004-05-25', '2004-09-18 00:00:00', 'c'),
+(3, '2005-01-17', '2002-09-12 11:18:48', 'd'),
+(0, '2003-08-28', '1900-01-01 00:00:00', 'k'),
+(6, '2006-10-11', '2003-10-28 03:31:02', 'a'),
+(5, '1900-01-01', '2001-08-22 10:20:09', 'p'),
+(8, '1900-01-01', '2008-04-24 00:00:00', 'o'),
+(4, '2005-08-18', '2006-11-10 10:08:49', 'e'),
+(NULL, '2007-03-12', '2007-10-16 00:00:00', 'n'),
+(1, '2000-11-18', '2009-05-27 12:25:07', 't'),
+(4, '2001-03-03', NULL, 'u'),
+(3, '2003-09-11', '2001-09-10 18:10:10', 'f'),
+(4, '2007-06-17', '1900-01-01 00:00:00', 't'),
+(NULL, '2008-09-11', '2004-06-07 23:17:09', 'k');
+ALTER TABLE t1 ADD UNIQUE KEY ind1 (pk, d, i, v);
+ALTER TABLE t1 ADD UNIQUE KEY ind2 (d, v);
+ERROR 23000: Duplicate entry '1900-01-01-m' for key 'ind2'
+DROP TABLE t1;
diff --git a/mysql-test/r/mysqlcheck.result b/mysql-test/r/mysqlcheck.result
index c5ba3e7..56556ff 100644
--- a/mysql-test/r/mysqlcheck.result
+++ b/mysql-test/r/mysqlcheck.result
@@ -312,10 +312,37 @@ DROP TABLE bug47205;
 #
 #MDEV-6128:[PATCH] mysqlcheck wrongly escapes '.' in table names
 #
-CREATE TABLE test.`t.1` (id int);
+create table `t.1` (id int);
+create view `v.1` as select 1;
 mysqlcheck test t.1
 test.t.1                                           OK
-drop table test.`t.1`;
+mysqlcheck --all-in-1 test t.1
+test.t.1                                           OK
+mysqlcheck --all-in-1 --databases --process-views test
+test.t.1                                           OK
+test.v.1                                           OK
+create table `t.2`(a varchar(20) primary key) default character set utf8 collate utf8_general_ci engine=innodb;
+flush table `t.2`;
+mysqlcheck --check-upgrade --auto-repair test
+test.t.1                                           OK
+test.t.2
+error    : Table rebuild required. Please do "ALTER TABLE `t.2` FORCE" or dump/reload to fix it!
+test.t.3                                           Needs upgrade
+
+Repairing tables
+test.t.3                                           OK
+check table `t.1`, `t.2`, `t.3`;
+Table	Op	Msg_type	Msg_text
+test.t.1	check	status	OK
+test.t.2	check	status	OK
+test.t.3	check	status	OK
+check table `t.1`, `t.2`, `t.3` for upgrade;
+Table	Op	Msg_type	Msg_text
+test.t.1	check	status	OK
+test.t.2	check	status	OK
+test.t.3	check	status	OK
+drop view `v.1`;
+drop table test.`t.1`, `t.2`, `t.3`;
 create view v1 as select 1;
 mysqlcheck --process-views test
 test.v1                                            OK
@@ -339,3 +366,53 @@ Repairing views
 test.v1                                            OK
 drop view v1;
 drop table t1;
+create table `#mysql50#t1``1` (a int) engine=myisam;
+show tables;
+Tables_in_test
+t1`1
+drop table `t1``1`;
+call mtr.add_suppression("ha_myisam");
+call mtr.add_suppression("Checking table");
+create database mysqltest1;
+create table mysqltest1.t1 (a int) engine=myisam;
+create table t2 (a int);
+check table mysqltest1.t1;
+Table	Op	Msg_type	Msg_text
+mysqltest1.t1	check	warning	Size of datafile is: 4       Should be: 0
+mysqltest1.t1	check	error	got error: 0 when reading datafile at record: 0
+mysqltest1.t1	check	error	Corrupt
+mtr.global_suppressions                            Table is already up to date
+mtr.test_suppressions                              Table is already up to date
+mysql.columns_priv                                 Table is already up to date
+mysql.db                                           Table is already up to date
+mysql.event                                        Table is already up to date
+mysql.func                                         Table is already up to date
+mysql.help_category                                Table is already up to date
+mysql.help_keyword                                 Table is already up to date
+mysql.help_relation                                Table is already up to date
+mysql.help_topic                                   Table is already up to date
+mysql.host                                         Table is already up to date
+mysql.ndb_binlog_index                             Table is already up to date
+mysql.plugin                                       Table is already up to date
+mysql.proc                                         Table is already up to date
+mysql.procs_priv                                   Table is already up to date
+mysql.proxies_priv                                 Table is already up to date
+mysql.servers                                      Table is already up to date
+mysql.tables_priv                                  Table is already up to date
+mysql.time_zone                                    Table is already up to date
+mysql.time_zone_leap_second                        Table is already up to date
+mysql.time_zone_name                               Table is already up to date
+mysql.time_zone_transition                         Table is already up to date
+mysql.time_zone_transition_type                    Table is already up to date
+mysql.user                                         Table is already up to date
+mysqltest1.t1
+warning  : Table is marked as crashed
+warning  : Size of datafile is: 4       Should be: 0
+error    : got error: 0 when reading datafile at record: 0
+error    : Corrupt
+test.t2                                            Table is already up to date
+
+Repairing tables
+mysqltest1.t1                                      OK
+drop table t2;
+drop database mysqltest1;
diff --git a/mysql-test/r/ps.result b/mysql-test/r/ps.result
index 04a19d3..bb8b76f 100644
--- a/mysql-test/r/ps.result
+++ b/mysql-test/r/ps.result
@@ -4072,4 +4072,35 @@ id	value
 deallocate prepare stmt;
 SET SESSION sql_mode = @save_sql_mode;
 DROP TABLE t1,t2;
-# End of 10.0 tests
+#
+# MDEV-8833: Crash of server on prepared statement with
+# conversion to semi-join
+#
+CREATE TABLE t1 (column1 INT);
+INSERT INTO t1 VALUES (3),(9);
+CREATE TABLE t2 (column2 INT);
+INSERT INTO t2 VALUES (1),(4);
+CREATE TABLE t3 (column3 INT);
+INSERT INTO t3 VALUES (6),(8);
+CREATE TABLE t4 (column4 INT);
+INSERT INTO t4 VALUES (2),(5);
+PREPARE stmt FROM "SELECT ( SELECT MAX( table1.column1 ) AS field1 
+FROM t1 AS table1
+WHERE table3.column3 IN ( SELECT table2.column2 AS field2 FROM t2 AS table2 ) 
+) AS sq
+FROM t3 AS table3, t4 AS table4";
+EXECUTE stmt;
+sq
+NULL
+NULL
+NULL
+NULL
+EXECUTE stmt;
+sq
+NULL
+NULL
+NULL
+NULL
+deallocate prepare stmt;
+drop table t1,t2,t3,t4;
+# End of 5.5 tests
diff --git a/mysql-test/r/ps_1general.result b/mysql-test/r/ps_1general.result
index 0a3d16c..cc31944 100644
--- a/mysql-test/r/ps_1general.result
+++ b/mysql-test/r/ps_1general.result
@@ -788,3 +788,5 @@ execute stmt1;
 1
 drop prepare stmt1;
 drop table t1;
+select ?+1;
+Got one of the listed errors
diff --git a/mysql-test/r/range.result b/mysql-test/r/range.result
index a19d906..630a692 100644
--- a/mysql-test/r/range.result
+++ b/mysql-test/r/range.result
@@ -2113,3 +2113,34 @@ a	b
 0	0
 1	1
 drop table t2;
+#
+# MDEV-10228: Delete missing rows with OR conditions
+#  (The example uses UPDATE, because UPDATE allows to use index hints
+#   and so it's possible to make an example that works with any storage
+#   engine)
+#
+CREATE TABLE t1 (
+key1varchar varchar(14) NOT NULL,
+key2int int(11) NOT NULL DEFAULT '0',
+col1 int,
+PRIMARY KEY (key1varchar,key2int),
+KEY key1varchar (key1varchar),
+KEY key2int (key2int)
+) DEFAULT CHARSET=utf8;
+insert into t1 values 
+('value1',0, 0),
+('value1',1, 0),
+('value1',1000685, 0),
+('value1',1003560, 0),
+('value1',1004807, 0);
+update t1 force index (PRIMARY) set col1=12345
+where (key1varchar='value1' AND (key2int <=1 OR  key2int > 1));
+# The following must show col1=12345 for all rows:
+select * from t1;
+key1varchar	key2int	col1
+value1	0	12345
+value1	1	12345
+value1	1000685	12345
+value1	1003560	12345
+value1	1004807	12345
+drop table t1;
diff --git a/mysql-test/r/range_mrr_icp.result b/mysql-test/r/range_mrr_icp.result
index 9a08910..3f5de5b 100644
--- a/mysql-test/r/range_mrr_icp.result
+++ b/mysql-test/r/range_mrr_icp.result
@@ -2115,4 +2115,35 @@ a	b
 0	0
 1	1
 drop table t2;
+#
+# MDEV-10228: Delete missing rows with OR conditions
+#  (The example uses UPDATE, because UPDATE allows to use index hints
+#   and so it's possible to make an example that works with any storage
+#   engine)
+#
+CREATE TABLE t1 (
+key1varchar varchar(14) NOT NULL,
+key2int int(11) NOT NULL DEFAULT '0',
+col1 int,
+PRIMARY KEY (key1varchar,key2int),
+KEY key1varchar (key1varchar),
+KEY key2int (key2int)
+) DEFAULT CHARSET=utf8;
+insert into t1 values 
+('value1',0, 0),
+('value1',1, 0),
+('value1',1000685, 0),
+('value1',1003560, 0),
+('value1',1004807, 0);
+update t1 force index (PRIMARY) set col1=12345
+where (key1varchar='value1' AND (key2int <=1 OR  key2int > 1));
+# The following must show col1=12345 for all rows:
+select * from t1;
+key1varchar	key2int	col1
+value1	0	12345
+value1	1	12345
+value1	1000685	12345
+value1	1003560	12345
+value1	1004807	12345
+drop table t1;
 set optimizer_switch=@mrr_icp_extra_tmp;
diff --git a/mysql-test/r/sp-prelocking.result b/mysql-test/r/sp-prelocking.result
index 186b2c0..ac48459 100644
--- a/mysql-test/r/sp-prelocking.result
+++ b/mysql-test/r/sp-prelocking.result
@@ -320,3 +320,23 @@ c2
 DROP TRIGGER t1_ai;
 DROP TABLE t1, t2;
 End of 5.0 tests
+#
+# Bug#21142859: FUNCTION UPDATING A VIEW FAILS TO FIND TABLE THAT ACTUALLY EXISTS
+#
+CREATE TABLE t1 SELECT 1 AS fld1, 'A' AS fld2;
+CREATE TABLE t2 (fld3 INT, fld4 CHAR(1));
+CREATE VIEW v1 AS SELECT * FROM t1;
+CREATE TRIGGER t1_au AFTER UPDATE ON t1
+FOR EACH ROW INSERT INTO t2 VALUES (new.fld1, new.fld2);
+CREATE FUNCTION f1() RETURNS INT
+BEGIN
+UPDATE v1 SET fld2='B' WHERE fld1=1;
+RETURN row_count();
+END !
+# Without the patch, an error was getting reported.
+SELECT f1();
+f1()
+1
+DROP FUNCTION f1;
+DROP VIEW v1;
+DROP TABLE t1,t2;
diff --git a/mysql-test/r/type_date.result b/mysql-test/r/type_date.result
index ecbda1d..ad7560f 100644
--- a/mysql-test/r/type_date.result
+++ b/mysql-test/r/type_date.result
@@ -165,6 +165,7 @@ str_to_date( '', a )
 NULL
 DROP TABLE t1;
 CREATE TABLE t1 (a DATE, b INT, PRIMARY KEY (a,b));
+SET timestamp=UNIX_TIMESTAMP('2016-07-21 14:48:18');
 INSERT INTO t1 VALUES (DATE(NOW()), 1);
 SELECT COUNT(*) FROM t1 WHERE a = NOW();
 COUNT(*)
@@ -192,6 +193,7 @@ COUNT(*)
 EXPLAIN SELECT COUNT(*) FROM t1 WHERE a = NOW();
 id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
 1	SIMPLE	t1	ALL	NULL	NULL	NULL	NULL	2	Using where
+SET timestamp=DEFAULT;
 DROP TABLE t1;
 CREATE TABLE t1 (a DATE);
 CREATE TABLE t2 (a DATE);
diff --git a/mysql-test/r/type_uint.result b/mysql-test/r/type_uint.result
index e08605f..d67c735 100644
--- a/mysql-test/r/type_uint.result
+++ b/mysql-test/r/type_uint.result
@@ -14,3 +14,22 @@ this
 0
 4294967295
 drop table t1;
+create table t1 (a bigint unsigned, b mediumint unsigned);
+insert t1 values (1,2),(0xffffffffffffffff,0xffffff);
+select coalesce(a,b), coalesce(b,a) from t1;
+coalesce(a,b)	coalesce(b,a)
+1	2
+18446744073709551615	16777215
+create table t2 as select a from t1 union select b from t1;
+show create table t2;
+Table	Create Table
+t2	CREATE TABLE `t2` (
+  `a` bigint(20) unsigned DEFAULT NULL
+) ENGINE=MyISAM DEFAULT CHARSET=latin1
+select * from t2;
+a
+1
+18446744073709551615
+2
+16777215
+drop table t1, t2;
diff --git a/mysql-test/r/view.result b/mysql-test/r/view.result
index dbfdf3f..6848ba3 100644
--- a/mysql-test/r/view.result
+++ b/mysql-test/r/view.result
@@ -5520,6 +5520,21 @@ test.v1	check	Error	'test.v1' is not BASE TABLE
 test.v1	check	status	Operation failed
 drop view v1;
 drop table t1;
+#
+# MDEV-10419: crash in mariadb 10.1.16-MariaDB-1~trusty
+#
+CREATE TABLE t1 (c1 CHAR(13));
+CREATE TABLE t2 (c2 CHAR(13));
+CREATE FUNCTION f() RETURNS INT RETURN 0;
+CREATE OR REPLACE VIEW v1 AS select f() from t1 where c1 in (select c2 from t2);
+DROP FUNCTION f;
+SHOW CREATE VIEW v1;
+View	Create View	character_set_client	collation_connection
+v1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v1` AS select `f`() AS `f()` from `t1` where `test`.`t1`.`c1` in (select `test`.`t2`.`c2` from `t2`)	latin1	latin1_swedish_ci
+Warnings:
+Warning	1356	View 'test.v1' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+drop view v1;
+drop table t1,t2;
 # -----------------------------------------------------------------
 # -- End of 5.5 tests.
 # -----------------------------------------------------------------
diff --git a/mysql-test/r/xtradb_mrr.result b/mysql-test/r/xtradb_mrr.result
index 15b750d..c238d05 100644
--- a/mysql-test/r/xtradb_mrr.result
+++ b/mysql-test/r/xtradb_mrr.result
@@ -311,10 +311,10 @@ concat('c-', 1000 + C.a, '-c'),
 'filler'
 from t1 A, t1 B, t1 C;
 explain
-select count(length(a) + length(filler)) from t2 where a>='a-1000-a' and a <'a-1001-a';
+select count(length(a) + length(filler)) from t2 force index (a) where a>='a-1000-a' and a <'a-1001-a';
 id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
 1	SIMPLE	t2	range	a	a	9	NULL	99	Using index condition; Rowid-ordered scan
-select count(length(a) + length(filler)) from t2 where a>='a-1000-a' and a <'a-1001-a';
+select count(length(a) + length(filler)) from t2 force index (a) where a>='a-1000-a' and a <'a-1001-a';
 count(length(a) + length(filler))
 100
 drop table t2;
diff --git a/mysql-test/std_data/bug20683959loaddata.txt b/mysql-test/std_data/bug20683959loaddata.txt
new file mode 100644
index 0000000..1878cc7
--- /dev/null
+++ b/mysql-test/std_data/bug20683959loaddata.txt
@@ -0,0 +1 @@
+Ã"RT @niouzechun: 遘√����繝上ャ繝斐����繧ィ繝ウ繝牙耳縺ェ繧薙□縺代l縺ゥ縲√い繝ウ繝上ャ繝斐����繧ィ繝ウ繝峨d諠ィ蜉����噪縺ェ縺願ゥア繧偵≠縺セ繧顔ゥ肴・オ逧����↓鞫ょ叙縺励↑縺����炊逕ア縺ッ縲∫樟螳溘����莠コ逕溘����蝓コ譛ャ逧����↓縺����∪縺上>縺九↑縺����@荳榊ケウ遲峨□縺礼炊荳榊ース縺�縺苓セ帙>
diff --git a/mysql-test/suite/binlog/r/binlog_dmls_on_tmp_tables_readonly.result b/mysql-test/suite/binlog/r/binlog_dmls_on_tmp_tables_readonly.result
new file mode 100644
index 0000000..1dfac08
--- /dev/null
+++ b/mysql-test/suite/binlog/r/binlog_dmls_on_tmp_tables_readonly.result
@@ -0,0 +1,58 @@
+DROP TABLE IF EXISTS t1 ;
+# READ_ONLY does nothing to SUPER users
+# so we use a non-SUPER one:
+GRANT CREATE, SELECT, DROP ON *.* TO test at localhost;
+connect  con1,localhost,test,,test;
+connection default;
+SET GLOBAL READ_ONLY=1;
+connection con1;
+CREATE TEMPORARY TABLE t1 (a INT) ENGINE=INNODB;
+# Test INSERTS with autocommit being off and on.
+BEGIN;
+INSERT INTO t1 VALUES (10);
+COMMIT;
+INSERT INTO t1 VALUES (20);
+# Test UPDATES with autocommit being off and on.
+BEGIN;
+UPDATE t1 SET a=30 WHERE a=10;
+COMMIT;
+UPDATE t1 SET a=40 WHERE a=20;
+connection default;
+SET GLOBAL READ_ONLY=0;
+# Test scenario where global read_only is enabled in the middle of transaction.
+# Test INSERT operations on temporary tables, INSERTs should be successful even
+# when global read_only is enabled.
+connection con1;
+BEGIN;
+INSERT INTO t1 VALUES(50);
+connection default;
+SET GLOBAL READ_ONLY=1;
+connection con1;
+SELECT @@GLOBAL.READ_ONLY;
+@@GLOBAL.READ_ONLY
+1
+COMMIT;
+connection default;
+SET GLOBAL READ_ONLY=0;
+# Test UPDATE operations on temporary tables, UPDATEs should be successful even
+# when global read_only is enabled.
+connection con1;
+BEGIN;
+UPDATE t1 SET a=60 WHERE a=50;
+connection default;
+SET GLOBAL READ_ONLY=1;
+connection con1;
+SELECT @@GLOBAL.READ_ONLY;
+@@GLOBAL.READ_ONLY
+1
+COMMIT;
+SELECT * FROM t1;
+a
+30
+40
+60
+# Clean up
+connection default;
+SET GLOBAL READ_ONLY=0;
+disconnect con1;
+DROP USER test at localhost;
diff --git a/mysql-test/suite/binlog/t/binlog_dmls_on_tmp_tables_readonly.test b/mysql-test/suite/binlog/t/binlog_dmls_on_tmp_tables_readonly.test
new file mode 100644
index 0000000..cf3910e
--- /dev/null
+++ b/mysql-test/suite/binlog/t/binlog_dmls_on_tmp_tables_readonly.test
@@ -0,0 +1,91 @@
+# ==== Purpose ====
+#
+# Check that DMLs are allowed on temporary tables, when server is in read only
+# mode and binary log is enabled with binlog-format being stmt/mixed mode.
+#
+# ==== Implementation ====
+#
+# Start the server with binary log being enabled. Mark the server as read only.
+# Create a non-SUPER user and let the user to create a temporary table and
+# perform DML operations on that temporary table. DMLs should not be blocked
+# with a 'server read-only mode' error.
+#
+# ==== References ====
+#
+# Bug#12818255: READ-ONLY OPTION DOES NOT ALLOW INSERTS/UPDATES ON TEMPORARY
+# TABLES
+# Bug#14294223: CHANGES NOT ALLOWED TO TEMPORARY TABLES ON READ-ONLY SERVERS
+###############################################################################
+--source include/have_log_bin.inc
+--source include/have_innodb.inc
+--disable_warnings
+DROP TABLE IF EXISTS t1 ;
+--enable_warnings
+
+--enable_connect_log
+--echo # READ_ONLY does nothing to SUPER users
+--echo # so we use a non-SUPER one:
+GRANT CREATE, SELECT, DROP ON *.* TO test at localhost;
+
+connect (con1,localhost,test,,test);
+
+connection default;
+SET GLOBAL READ_ONLY=1;
+
+connection con1;
+CREATE TEMPORARY TABLE t1 (a INT) ENGINE=INNODB;
+
+--echo # Test INSERTS with autocommit being off and on.
+BEGIN;
+INSERT INTO t1 VALUES (10);
+COMMIT;
+INSERT INTO t1 VALUES (20);
+
+--echo # Test UPDATES with autocommit being off and on.
+BEGIN;
+UPDATE t1 SET a=30 WHERE a=10;
+COMMIT;
+UPDATE t1 SET a=40 WHERE a=20;
+
+connection default;
+SET GLOBAL READ_ONLY=0;
+
+--echo # Test scenario where global read_only is enabled in the middle of transaction.
+--echo # Test INSERT operations on temporary tables, INSERTs should be successful even
+--echo # when global read_only is enabled.
+connection con1;
+BEGIN;
+INSERT INTO t1 VALUES(50);
+
+connection default;
+SET GLOBAL READ_ONLY=1;
+
+connection con1;
+SELECT @@GLOBAL.READ_ONLY;
+COMMIT;
+
+connection default;
+SET GLOBAL READ_ONLY=0;
+
+--echo # Test UPDATE operations on temporary tables, UPDATEs should be successful even
+--echo # when global read_only is enabled.
+connection con1;
+BEGIN;
+UPDATE t1 SET a=60 WHERE a=50;
+
+connection default;
+SET GLOBAL READ_ONLY=1;
+
+connection con1;
+SELECT @@GLOBAL.READ_ONLY;
+COMMIT;
+
+SELECT * FROM t1;
+
+--echo # Clean up
+connection default;
+SET GLOBAL READ_ONLY=0;
+
+disconnect con1;
+DROP USER test at localhost;
+--disable_connect_log
diff --git a/mysql-test/suite/funcs_1/datadict/processlist_priv.inc b/mysql-test/suite/funcs_1/datadict/processlist_priv.inc
index b863b98..38b9a3e 100644
--- a/mysql-test/suite/funcs_1/datadict/processlist_priv.inc
+++ b/mysql-test/suite/funcs_1/datadict/processlist_priv.inc
@@ -153,7 +153,7 @@ connection default;
 let $wait_timeout= 10;
 let $wait_condition=
 SELECT COUNT(*) = 1 FROM INFORMATION_SCHEMA.PROCESSLIST
-WHERE DB = 'information_schema' AND COMMAND = 'Sleep' AND USER = 'ddicttestuser1';
+WHERE DB = 'information_schema' AND COMMAND = 'Sleep' AND USER = 'ddicttestuser1' AND state='';
 --source include/wait_condition.inc
 --replace_result ENGINE=MyISAM "" ENGINE=Aria "" " PAGE_CHECKSUM=1" "" " PAGE_CHECKSUM=0" ""
 eval SHOW CREATE TABLE $table;
diff --git a/mysql-test/suite/innodb/r/innodb-fkcheck.result b/mysql-test/suite/innodb/r/innodb-fkcheck.result
new file mode 100644
index 0000000..a6bbcc9
--- /dev/null
+++ b/mysql-test/suite/innodb/r/innodb-fkcheck.result
@@ -0,0 +1,87 @@
+set global innodb_file_per_table = 1;
+drop table if exists b;
+drop database if exists bug_fk;
+create database bug_fk;
+use bug_fk;
+CREATE TABLE b (
+b int unsigned NOT NULL,
+d1 datetime NOT NULL,
+PRIMARY KEY (b,d1)
+) ENGINE=InnoDB;
+CREATE TABLE c (
+b int unsigned NOT NULL,
+d1 datetime NOT NULL,
+d2 datetime NOT NULL,
+PRIMARY KEY (b,d1),
+CONSTRAINT b_fk FOREIGN KEY (b) REFERENCES b (b)
+) ENGINE=InnoDB;
+show warnings;
+Level	Code	Message
+set foreign_key_checks = 0;
+DROP TABLE IF EXISTS b;
+show create table c;
+Table	Create Table
+c	CREATE TABLE `c` (
+  `b` int(10) unsigned NOT NULL,
+  `d1` datetime NOT NULL,
+  `d2` datetime NOT NULL,
+  PRIMARY KEY (`b`,`d1`),
+  CONSTRAINT `b_fk` FOREIGN KEY (`b`) REFERENCES `b` (`b`)
+) ENGINE=InnoDB DEFAULT CHARSET=latin1
+CREATE TABLE b (
+b bigint unsigned NOT NULL,
+d1 date NOT NULL,
+PRIMARY KEY (b,d1)
+) ENGINE=InnoDB;
+ERROR HY000: Can't create table 'bug_fk.b' (errno: 150)
+show warnings;
+Level	Code	Message
+Error	1005	Can't create table 'bug_fk.b' (errno: 150)
+DROP TABLE IF EXISTS d;
+Warnings:
+Note	1051	Unknown table 'd'
+CREATE TABLE d (
+b bigint unsigned NOT NULL,
+d1 date NOT NULL,
+PRIMARY KEY (b,d1),
+CONSTRAINT bd_fk FOREIGN KEY (b) REFERENCES b (b)
+) ENGINE=InnoDB;
+show warnings;
+Level	Code	Message
+set foreign_key_checks = 1;
+show create table c;
+Table	Create Table
+c	CREATE TABLE `c` (
+  `b` int(10) unsigned NOT NULL,
+  `d1` datetime NOT NULL,
+  `d2` datetime NOT NULL,
+  PRIMARY KEY (`b`,`d1`),
+  CONSTRAINT `b_fk` FOREIGN KEY (`b`) REFERENCES `b` (`b`)
+) ENGINE=InnoDB DEFAULT CHARSET=latin1
+show create table d;
+Table	Create Table
+d	CREATE TABLE `d` (
+  `b` bigint(20) unsigned NOT NULL,
+  `d1` date NOT NULL,
+  PRIMARY KEY (`b`,`d1`),
+  CONSTRAINT `bd_fk` FOREIGN KEY (`b`) REFERENCES `b` (`b`)
+) ENGINE=InnoDB DEFAULT CHARSET=latin1
+CREATE TABLE b (
+b bigint unsigned NOT NULL,
+d1 date NOT NULL,
+PRIMARY KEY (b,d1)
+) ENGINE=InnoDB;
+ERROR HY000: Can't create table 'bug_fk.b' (errno: 150)
+show warnings;
+Level	Code	Message
+Error	1005	Can't create table 'bug_fk.b' (errno: 150)
+set foreign_key_checks=0;
+drop table c;
+drop table d;
+create table b(id int) engine=innodb;
+show warnings;
+Level	Code	Message
+b.frm
+b.ibd
+drop table if exists b;
+drop database if exists bug_fk;
diff --git a/mysql-test/suite/innodb/r/innodb_bug54044.result b/mysql-test/suite/innodb/r/innodb_bug54044.result
index 47aa880..29b0127 100644
--- a/mysql-test/suite/innodb/r/innodb_bug54044.result
+++ b/mysql-test/suite/innodb/r/innodb_bug54044.result
@@ -5,5 +5,14 @@ Table	Create Table
 table_54044	CREATE TEMPORARY TABLE `table_54044` (
   `IF(NULL  IS NOT NULL, NULL, NULL)` binary(0) DEFAULT NULL
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1
-CREATE TEMPORARY TABLE tmp1 ENGINE = INNODB AS SELECT COALESCE(NULL, NULL, NULL);
-CREATE TEMPORARY TABLE tmp2 ENGINE = INNODB AS SELECT GREATEST(NULL, NULL);
+DROP TABLE table_54044;
+CREATE TABLE tmp ENGINE = INNODB
+AS SELECT COALESCE(NULL, NULL, NULL), GREATEST(NULL, NULL), NULL;
+SHOW CREATE TABLE tmp;
+Table	Create Table
+tmp	CREATE TABLE `tmp` (
+  `COALESCE(NULL, NULL, NULL)` binary(0) DEFAULT NULL,
+  `GREATEST(NULL, NULL)` binary(0) DEFAULT NULL,
+  `NULL` binary(0) DEFAULT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=latin1
+DROP TABLE tmp;
diff --git a/mysql-test/suite/innodb/t/innodb-fkcheck.test b/mysql-test/suite/innodb/t/innodb-fkcheck.test
new file mode 100644
index 0000000..51e36ae
--- /dev/null
+++ b/mysql-test/suite/innodb/t/innodb-fkcheck.test
@@ -0,0 +1,115 @@
+--source include/have_innodb.inc
+
+#
+# MDEV-10083: Orphan ibd file when playing with foreign keys
+#
+--disable_query_log
+SET @start_global_fpt = @@global.innodb_file_per_table;
+SET @start_global_fkc = @@global.foreign_key_checks;
+--enable_query_log
+
+set global innodb_file_per_table = 1;
+
+--disable_warnings
+drop table if exists b;
+drop database if exists bug_fk;
+--enable_warnings
+
+let $MYSQLD_DATADIR = `select @@datadir`;
+
+create database bug_fk;
+use bug_fk;
+
+CREATE TABLE b (
+  b int unsigned NOT NULL,
+  d1 datetime NOT NULL,
+  PRIMARY KEY (b,d1)
+) ENGINE=InnoDB;
+
+CREATE TABLE c (
+  b int unsigned NOT NULL,
+  d1 datetime NOT NULL,
+  d2 datetime NOT NULL,
+  PRIMARY KEY (b,d1),
+  CONSTRAINT b_fk FOREIGN KEY (b) REFERENCES b (b)
+) ENGINE=InnoDB;
+
+show warnings;
+
+set foreign_key_checks = 0;
+
+DROP TABLE IF EXISTS b;
+
+show create table c;
+
+#
+# Note that column b has different type in parent table
+#
+--error 1005
+CREATE TABLE b (
+  b bigint unsigned NOT NULL,
+  d1 date NOT NULL,
+  PRIMARY KEY (b,d1)
+) ENGINE=InnoDB;
+
+show warnings;
+
+DROP TABLE IF EXISTS d;
+
+CREATE TABLE d (
+  b bigint unsigned NOT NULL,
+  d1 date NOT NULL,
+  PRIMARY KEY (b,d1),
+  CONSTRAINT bd_fk FOREIGN KEY (b) REFERENCES b (b)
+) ENGINE=InnoDB;
+
+show warnings; 
+
+set foreign_key_checks = 1;
+
+show create table c;
+show create table d;
+
+#
+# Table c column b used on foreign key has different type
+# compared referenced column b in table b, but this
+# create still produced b.ibd file. This is because
+# we row_drop_table_for_mysql was called and referenced
+# table is not allowed to be dropped even in case
+# when actual create is not successfull.
+#
+--error 1005
+CREATE TABLE b (
+  b bigint unsigned NOT NULL,
+  d1 date NOT NULL,
+  PRIMARY KEY (b,d1)
+) ENGINE=InnoDB;
+
+show warnings;
+
+--list_files $MYSQLD_DATADIR/bug_fk b*
+
+set foreign_key_checks=0;
+
+drop table c;
+drop table d;
+
+--list_files $MYSQLD_DATADIR/bug_fk b*
+
+create table b(id int) engine=innodb;
+show warnings;
+
+--list_files $MYSQLD_DATADIR/bug_fk b*
+
+#
+# Cleanup
+#
+--disable_query_log
+SET @@global.innodb_file_per_table = @start_global_fpt;
+SET @@global.foreign_key_checks = @start_global_fkc;
+--enable_query_log
+
+--disable_warnings
+drop table if exists b;
+drop database if exists bug_fk;
+--enable_warnings
diff --git a/mysql-test/suite/innodb/t/innodb_bug54044.test b/mysql-test/suite/innodb/t/innodb_bug54044.test
index 013a7ff..e79e34b 100644
--- a/mysql-test/suite/innodb/t/innodb_bug54044.test
+++ b/mysql-test/suite/innodb/t/innodb_bug54044.test
@@ -8,5 +8,11 @@
 CREATE TEMPORARY TABLE table_54044 ENGINE = INNODB
  AS SELECT IF(NULL  IS NOT NULL, NULL, NULL); 
 SHOW CREATE TABLE table_54044;
-CREATE TEMPORARY TABLE tmp1 ENGINE = INNODB AS SELECT COALESCE(NULL, NULL, NULL);
-CREATE TEMPORARY TABLE tmp2 ENGINE = INNODB AS SELECT GREATEST(NULL, NULL);
+DROP TABLE table_54044;
+
+# This 'create table' should pass since it uses a Field_string of size 0.
+
+CREATE TABLE tmp ENGINE = INNODB
+ AS SELECT COALESCE(NULL, NULL, NULL), GREATEST(NULL, NULL), NULL;
+SHOW CREATE TABLE tmp;
+DROP TABLE tmp;
diff --git a/mysql-test/suite/perfschema/r/aggregate.result b/mysql-test/suite/perfschema/r/aggregate.result
deleted file mode 100644
index edc7ce0..0000000
--- a/mysql-test/suite/perfschema/r/aggregate.result
+++ /dev/null
@@ -1,102 +0,0 @@
-"General cleanup"
-drop table if exists t1;
-update performance_schema.setup_instruments set enabled = 'NO';
-update performance_schema.setup_consumers set enabled = 'NO';
-truncate table performance_schema.file_summary_by_event_name;
-truncate table performance_schema.file_summary_by_instance;
-truncate table performance_schema.events_waits_summary_global_by_event_name;
-truncate table performance_schema.events_waits_summary_by_instance;
-truncate table performance_schema.events_waits_summary_by_thread_by_event_name;
-update performance_schema.setup_consumers set enabled = 'YES';
-update performance_schema.setup_instruments
-set enabled = 'YES', timed = 'YES';
-create table t1 (
-id INT PRIMARY KEY,
-b CHAR(100) DEFAULT 'initial value')
-ENGINE=MyISAM;
-insert into t1 (id) values (1), (2), (3), (4), (5), (6), (7), (8);
-update performance_schema.setup_instruments SET enabled = 'NO';
-update performance_schema.setup_consumers set enabled = 'NO';
-set @dump_all=FALSE;
-"Verifying file aggregate consistency"
-SELECT EVENT_NAME, e.COUNT_READ, SUM(i.COUNT_READ)
-FROM performance_schema.file_summary_by_event_name AS e
-JOIN performance_schema.file_summary_by_instance AS i USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.COUNT_READ <> SUM(i.COUNT_READ))
-OR @dump_all;
-EVENT_NAME	COUNT_READ	SUM(i.COUNT_READ)
-SELECT EVENT_NAME, e.COUNT_WRITE, SUM(i.COUNT_WRITE)
-FROM performance_schema.file_summary_by_event_name AS e
-JOIN performance_schema.file_summary_by_instance AS i USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.COUNT_WRITE <> SUM(i.COUNT_WRITE))
-OR @dump_all;
-EVENT_NAME	COUNT_WRITE	SUM(i.COUNT_WRITE)
-SELECT EVENT_NAME, e.SUM_NUMBER_OF_BYTES_READ, SUM(i.SUM_NUMBER_OF_BYTES_READ)
-FROM performance_schema.file_summary_by_event_name AS e
-JOIN performance_schema.file_summary_by_instance AS i USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.SUM_NUMBER_OF_BYTES_READ <> SUM(i.SUM_NUMBER_OF_BYTES_READ))
-OR @dump_all;
-EVENT_NAME	SUM_NUMBER_OF_BYTES_READ	SUM(i.SUM_NUMBER_OF_BYTES_READ)
-SELECT EVENT_NAME, e.SUM_NUMBER_OF_BYTES_WRITE, SUM(i.SUM_NUMBER_OF_BYTES_WRITE)
-FROM performance_schema.file_summary_by_event_name AS e
-JOIN performance_schema.file_summary_by_instance AS i USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.SUM_NUMBER_OF_BYTES_WRITE <> SUM(i.SUM_NUMBER_OF_BYTES_WRITE))
-OR @dump_all;
-EVENT_NAME	SUM_NUMBER_OF_BYTES_WRITE	SUM(i.SUM_NUMBER_OF_BYTES_WRITE)
-"Verifying waits aggregate consistency (instance)"
-SELECT EVENT_NAME, e.SUM_TIMER_WAIT, SUM(i.SUM_TIMER_WAIT)
-FROM performance_schema.events_waits_summary_global_by_event_name AS e
-JOIN performance_schema.events_waits_summary_by_instance AS i USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.SUM_TIMER_WAIT < SUM(i.SUM_TIMER_WAIT))
-OR @dump_all;
-EVENT_NAME	SUM_TIMER_WAIT	SUM(i.SUM_TIMER_WAIT)
-SELECT EVENT_NAME, e.MIN_TIMER_WAIT, MIN(i.MIN_TIMER_WAIT)
-FROM performance_schema.events_waits_summary_global_by_event_name AS e
-JOIN performance_schema.events_waits_summary_by_instance AS i USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.MIN_TIMER_WAIT > MIN(i.MIN_TIMER_WAIT))
-AND (MIN(i.MIN_TIMER_WAIT) != 0)
-OR @dump_all;
-EVENT_NAME	MIN_TIMER_WAIT	MIN(i.MIN_TIMER_WAIT)
-SELECT EVENT_NAME, e.MAX_TIMER_WAIT, MAX(i.MAX_TIMER_WAIT)
-FROM performance_schema.events_waits_summary_global_by_event_name AS e
-JOIN performance_schema.events_waits_summary_by_instance AS i USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.MAX_TIMER_WAIT < MAX(i.MAX_TIMER_WAIT))
-OR @dump_all;
-EVENT_NAME	MAX_TIMER_WAIT	MAX(i.MAX_TIMER_WAIT)
-"Verifying waits aggregate consistency (thread)"
-SELECT EVENT_NAME, e.SUM_TIMER_WAIT, SUM(t.SUM_TIMER_WAIT)
-FROM performance_schema.events_waits_summary_global_by_event_name AS e
-JOIN performance_schema.events_waits_summary_by_thread_by_event_name AS t
-USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.SUM_TIMER_WAIT < SUM(t.SUM_TIMER_WAIT))
-OR @dump_all;
-EVENT_NAME	SUM_TIMER_WAIT	SUM(t.SUM_TIMER_WAIT)
-SELECT EVENT_NAME, e.MIN_TIMER_WAIT, MIN(t.MIN_TIMER_WAIT)
-FROM performance_schema.events_waits_summary_global_by_event_name AS e
-JOIN performance_schema.events_waits_summary_by_thread_by_event_name AS t
-USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.MIN_TIMER_WAIT > MIN(t.MIN_TIMER_WAIT))
-AND (MIN(t.MIN_TIMER_WAIT) != 0)
-OR @dump_all;
-EVENT_NAME	MIN_TIMER_WAIT	MIN(t.MIN_TIMER_WAIT)
-SELECT EVENT_NAME, e.MAX_TIMER_WAIT, MAX(t.MAX_TIMER_WAIT)
-FROM performance_schema.events_waits_summary_global_by_event_name AS e
-JOIN performance_schema.events_waits_summary_by_thread_by_event_name AS t
-USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.MAX_TIMER_WAIT < MAX(t.MAX_TIMER_WAIT))
-OR @dump_all;
-EVENT_NAME	MAX_TIMER_WAIT	MAX(t.MAX_TIMER_WAIT)
-update performance_schema.setup_consumers set enabled = 'YES';
-update performance_schema.setup_instruments
-set enabled = 'YES', timed = 'YES';
-drop table test.t1;
diff --git a/mysql-test/suite/perfschema/t/aggregate.test b/mysql-test/suite/perfschema/t/aggregate.test
deleted file mode 100644
index 91794f0..0000000
--- a/mysql-test/suite/perfschema/t/aggregate.test
+++ /dev/null
@@ -1,174 +0,0 @@
-# Tests for PERFORMANCE_SCHEMA
-# Verify that statistics aggregated by different criteria are consistent.
-
---source include/not_embedded.inc
---source include/have_perfschema.inc
-
---echo "General cleanup"
-
---disable_warnings
-drop table if exists t1;
---enable_warnings
-
-update performance_schema.setup_instruments set enabled = 'NO';
-update performance_schema.setup_consumers set enabled = 'NO';
-
-# Cleanup statistics
-truncate table performance_schema.file_summary_by_event_name;
-truncate table performance_schema.file_summary_by_instance;
-truncate table performance_schema.events_waits_summary_global_by_event_name;
-truncate table performance_schema.events_waits_summary_by_instance;
-truncate table performance_schema.events_waits_summary_by_thread_by_event_name;
-
-# Start recording data
-update performance_schema.setup_consumers set enabled = 'YES';
-update performance_schema.setup_instruments
-  set enabled = 'YES', timed = 'YES';
-
-
-create table t1 (
-  id INT PRIMARY KEY,
-  b CHAR(100) DEFAULT 'initial value')
-  ENGINE=MyISAM;
-
-insert into t1 (id) values (1), (2), (3), (4), (5), (6), (7), (8);
-
-# Stop recording data, so the select below don't add noise.
-update performance_schema.setup_instruments SET enabled = 'NO';
-# Disable all consumers, for long standing waits
-update performance_schema.setup_consumers set enabled = 'NO';
-
-# Helper to debug
-set @dump_all=FALSE;
-
-# Note that in general:
-# - COUNT/SUM/MAX(file_summary_by_event_name) >=
-#   COUNT/SUM/MAX(file_summary_by_instance).
-# - MIN(file_summary_by_event_name) <=
-#   MIN(file_summary_by_instance).
-# There will be equality only when file instances are not removed,
-# aka when a file is not deleted from the file system,
-# because doing so removes a row in file_summary_by_instance.
-
-# Likewise:
-# - COUNT/SUM/MAX(events_waits_summary_global_by_event_name) >=
-#   COUNT/SUM/MAX(events_waits_summary_by_instance)
-# - MIN(events_waits_summary_global_by_event_name) <=
-#   MIN(events_waits_summary_by_instance)
-# There will be equality only when an instrument instance
-# is not removed, which is next to impossible to predictably guarantee
-# in the server.
-# For example, a MyISAM table removed from the table cache
-# will cause a mysql_mutex_destroy on myisam/MYISAM_SHARE::intern_lock.
-# Another example, a thread terminating will cause a mysql_mutex_destroy
-# on sql/LOCK_delete
-# Both cause a row to be deleted from events_waits_summary_by_instance.
-
-# Likewise:
-# - COUNT/SUM/MAX(events_waits_summary_global_by_event_name) >=
-#   COUNT/SUM/MAX(events_waits_summary_by_thread_by_event_name)
-# - MIN(events_waits_summary_global_by_event_name) <=
-#   MIN(events_waits_summary_by_thread_by_event_name)
-# There will be equality only when no thread is removed,
-# that is if no thread disconnects, or no sub thread (for example insert
-# delayed) ever completes.
-# A thread completing will cause rows in
-# events_waits_summary_by_thread_by_event_name to be removed.
-
---echo "Verifying file aggregate consistency"
-
-# Since the code generating the load in this test does:
-# - create table
-# - insert
-# - does not cause temporary tables to be used
-# we can test for equality here for file aggregates.
-
-# If any of these queries returns data, the test failed.
-
-SELECT EVENT_NAME, e.COUNT_READ, SUM(i.COUNT_READ)
-FROM performance_schema.file_summary_by_event_name AS e
-JOIN performance_schema.file_summary_by_instance AS i USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.COUNT_READ <> SUM(i.COUNT_READ))
-OR @dump_all;
-
-SELECT EVENT_NAME, e.COUNT_WRITE, SUM(i.COUNT_WRITE)
-FROM performance_schema.file_summary_by_event_name AS e
-JOIN performance_schema.file_summary_by_instance AS i USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.COUNT_WRITE <> SUM(i.COUNT_WRITE))
-OR @dump_all;
-
-SELECT EVENT_NAME, e.SUM_NUMBER_OF_BYTES_READ, SUM(i.SUM_NUMBER_OF_BYTES_READ)
-FROM performance_schema.file_summary_by_event_name AS e
-JOIN performance_schema.file_summary_by_instance AS i USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.SUM_NUMBER_OF_BYTES_READ <> SUM(i.SUM_NUMBER_OF_BYTES_READ))
-OR @dump_all;
-
-SELECT EVENT_NAME, e.SUM_NUMBER_OF_BYTES_WRITE, SUM(i.SUM_NUMBER_OF_BYTES_WRITE)
-FROM performance_schema.file_summary_by_event_name AS e
-JOIN performance_schema.file_summary_by_instance AS i USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.SUM_NUMBER_OF_BYTES_WRITE <> SUM(i.SUM_NUMBER_OF_BYTES_WRITE))
-OR @dump_all;
-
---echo "Verifying waits aggregate consistency (instance)"
-
-SELECT EVENT_NAME, e.SUM_TIMER_WAIT, SUM(i.SUM_TIMER_WAIT)
-FROM performance_schema.events_waits_summary_global_by_event_name AS e
-JOIN performance_schema.events_waits_summary_by_instance AS i USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.SUM_TIMER_WAIT < SUM(i.SUM_TIMER_WAIT))
-OR @dump_all;
-
-SELECT EVENT_NAME, e.MIN_TIMER_WAIT, MIN(i.MIN_TIMER_WAIT)
-FROM performance_schema.events_waits_summary_global_by_event_name AS e
-JOIN performance_schema.events_waits_summary_by_instance AS i USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.MIN_TIMER_WAIT > MIN(i.MIN_TIMER_WAIT))
-AND (MIN(i.MIN_TIMER_WAIT) != 0)
-OR @dump_all;
-
-SELECT EVENT_NAME, e.MAX_TIMER_WAIT, MAX(i.MAX_TIMER_WAIT)
-FROM performance_schema.events_waits_summary_global_by_event_name AS e
-JOIN performance_schema.events_waits_summary_by_instance AS i USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.MAX_TIMER_WAIT < MAX(i.MAX_TIMER_WAIT))
-OR @dump_all;
-
---echo "Verifying waits aggregate consistency (thread)"
-
-SELECT EVENT_NAME, e.SUM_TIMER_WAIT, SUM(t.SUM_TIMER_WAIT)
-FROM performance_schema.events_waits_summary_global_by_event_name AS e
-JOIN performance_schema.events_waits_summary_by_thread_by_event_name AS t
-USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.SUM_TIMER_WAIT < SUM(t.SUM_TIMER_WAIT))
-OR @dump_all;
-
-SELECT EVENT_NAME, e.MIN_TIMER_WAIT, MIN(t.MIN_TIMER_WAIT)
-FROM performance_schema.events_waits_summary_global_by_event_name AS e
-JOIN performance_schema.events_waits_summary_by_thread_by_event_name AS t
-USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.MIN_TIMER_WAIT > MIN(t.MIN_TIMER_WAIT))
-AND (MIN(t.MIN_TIMER_WAIT) != 0)
-OR @dump_all;
-
-SELECT EVENT_NAME, e.MAX_TIMER_WAIT, MAX(t.MAX_TIMER_WAIT)
-FROM performance_schema.events_waits_summary_global_by_event_name AS e
-JOIN performance_schema.events_waits_summary_by_thread_by_event_name AS t
-USING (EVENT_NAME)
-GROUP BY EVENT_NAME
-HAVING (e.MAX_TIMER_WAIT < MAX(t.MAX_TIMER_WAIT))
-OR @dump_all;
-
-
-# Cleanup
-
-update performance_schema.setup_consumers set enabled = 'YES';
-update performance_schema.setup_instruments
-  set enabled = 'YES', timed = 'YES';
-
-drop table test.t1;
diff --git a/mysql-test/suite/plugins/r/pam_cleartext.result b/mysql-test/suite/plugins/r/pam_cleartext.result
index 00e0e94..b9eee74 100644
--- a/mysql-test/suite/plugins/r/pam_cleartext.result
+++ b/mysql-test/suite/plugins/r/pam_cleartext.result
@@ -5,6 +5,9 @@ grant proxy on pam_test to test_pam;
 show variables like 'pam%';
 Variable_name	Value
 pam_use_cleartext_plugin	ON
+#
+# same test as in pam.test now fails
+#
 drop user test_pam;
 drop user pam_test;
 uninstall plugin pam;
diff --git a/mysql-test/suite/plugins/t/pam.test b/mysql-test/suite/plugins/t/pam.test
index 1871e58..8a95d6b 100644
--- a/mysql-test/suite/plugins/t/pam.test
+++ b/mysql-test/suite/plugins/t/pam.test
@@ -29,5 +29,6 @@ EOF
 --remove_file $MYSQLTEST_VARDIR/tmp/pam_bad.txt
 drop user test_pam;
 drop user pam_test;
+let $count_sessions= 1;
+--source include/wait_until_count_sessions.inc
 uninstall plugin pam;
-
diff --git a/mysql-test/suite/plugins/t/pam_cleartext.test b/mysql-test/suite/plugins/t/pam_cleartext.test
index e80cff5..8476c39 100644
--- a/mysql-test/suite/plugins/t/pam_cleartext.test
+++ b/mysql-test/suite/plugins/t/pam_cleartext.test
@@ -3,10 +3,22 @@
 
 show variables like 'pam%';
 
+--write_file $MYSQLTEST_VARDIR/tmp/pam_good.txt
+not very secret challenge
+9225
+select user(), current_user(), database();
+EOF
+
+--echo #
+--echo # same test as in pam.test now fails
+--echo #
 --error 1
---exec echo FAIL | $MYSQL_TEST -u test_pam --plugin-dir=$plugindir
+--exec $MYSQL_TEST -u test_pam --plugin-dir=$plugindir < $MYSQLTEST_VARDIR/tmp/pam_good.txt
+
+--remove_file $MYSQLTEST_VARDIR/tmp/pam_good.txt
 
 drop user test_pam;
 drop user pam_test;
+let $count_sessions= 1;
+--source include/wait_until_count_sessions.inc
 uninstall plugin pam;
-
diff --git a/mysql-test/suite/sys_vars/r/general_log_file_basic.result b/mysql-test/suite/sys_vars/r/general_log_file_basic.result
index 369ef78..c7c24f1 100644
--- a/mysql-test/suite/sys_vars/r/general_log_file_basic.result
+++ b/mysql-test/suite/sys_vars/r/general_log_file_basic.result
@@ -12,6 +12,16 @@ SET @@global.general_log_file = mytest.log;
 ERROR 42000: Incorrect argument type to variable 'general_log_file'
 SET @@global.general_log_file = 12;
 ERROR 42000: Incorrect argument type to variable 'general_log_file'
+SET @@global.general_log_file = 'my.cnf';
+ERROR 42000: Variable 'general_log_file' can't be set to the value of 'my.cnf'
+SET @@global.general_log_file = '/tmp/my.cnf';
+ERROR 42000: Variable 'general_log_file' can't be set to the value of '/tmp/my.cnf'
+SET @@global.general_log_file = '.my.cnf';
+ERROR 42000: Variable 'general_log_file' can't be set to the value of '.my.cnf'
+SET @@global.general_log_file = 'my.cnf\0foo';
+ERROR 42000: Variable 'general_log_file' can't be set to the value of 'my.cnf'
+SET @@global.general_log_file = 'my.ini';
+ERROR 42000: Variable 'general_log_file' can't be set to the value of 'my.ini'
 '#----------------------FN_DYNVARS_004_03------------------------#'
 SELECT @@global.general_log_file = VARIABLE_VALUE 
 FROM INFORMATION_SCHEMA.GLOBAL_VARIABLES 
diff --git a/mysql-test/suite/sys_vars/r/slow_query_log_file_basic.result b/mysql-test/suite/sys_vars/r/slow_query_log_file_basic.result
index f45c568..a64666f 100644
--- a/mysql-test/suite/sys_vars/r/slow_query_log_file_basic.result
+++ b/mysql-test/suite/sys_vars/r/slow_query_log_file_basic.result
@@ -9,6 +9,16 @@ SET @@global.slow_query_log_file = mytest.log;
 ERROR 42000: Incorrect argument type to variable 'slow_query_log_file'
 SET @@global.slow_query_log_file = 12;
 ERROR 42000: Incorrect argument type to variable 'slow_query_log_file'
+SET @@global.slow_query_log_file = 'my.cnf';
+ERROR 42000: Variable 'slow_query_log_file' can't be set to the value of 'my.cnf'
+SET @@global.slow_query_log_file = '/tmp/my.cnf';
+ERROR 42000: Variable 'slow_query_log_file' can't be set to the value of '/tmp/my.cnf'
+SET @@global.general_log_file = '.my.cnf';
+ERROR 42000: Variable 'general_log_file' can't be set to the value of '.my.cnf'
+SET @@global.general_log_file = 'my.cnf\0foo';
+ERROR 42000: Variable 'general_log_file' can't be set to the value of 'my.cnf'
+SET @@global.general_log_file = 'my.ini';
+ERROR 42000: Variable 'general_log_file' can't be set to the value of 'my.ini'
 '#----------------------FN_DYNVARS_004_03------------------------#'
 SELECT @@global.slow_query_log_file = VARIABLE_VALUE 
 FROM INFORMATION_SCHEMA.GLOBAL_VARIABLES 
diff --git a/mysql-test/suite/sys_vars/t/general_log_file_basic.test b/mysql-test/suite/sys_vars/t/general_log_file_basic.test
index 12362fa..0a169b4 100644
--- a/mysql-test/suite/sys_vars/t/general_log_file_basic.test
+++ b/mysql-test/suite/sys_vars/t/general_log_file_basic.test
@@ -58,6 +58,20 @@ SET @@global.general_log_file = mytest.log;
 --error ER_WRONG_TYPE_FOR_VAR
 SET @@global.general_log_file = 12;
 
+#
+# MDEV-10465
+#
+--error ER_WRONG_VALUE_FOR_VAR
+SET @@global.general_log_file = 'my.cnf';
+--error ER_WRONG_VALUE_FOR_VAR
+SET @@global.general_log_file = '/tmp/my.cnf';
+--error ER_WRONG_VALUE_FOR_VAR
+SET @@global.general_log_file = '.my.cnf';
+--error ER_WRONG_VALUE_FOR_VAR
+SET @@global.general_log_file = 'my.cnf\0foo';
+--error ER_WRONG_VALUE_FOR_VAR
+SET @@global.general_log_file = 'my.ini';
+
 
 --echo '#----------------------FN_DYNVARS_004_03------------------------#'
 ############################################################################## 
diff --git a/mysql-test/suite/sys_vars/t/slow_query_log_file_basic.test b/mysql-test/suite/sys_vars/t/slow_query_log_file_basic.test
index 28fc17f..69ca5f2 100644
--- a/mysql-test/suite/sys_vars/t/slow_query_log_file_basic.test
+++ b/mysql-test/suite/sys_vars/t/slow_query_log_file_basic.test
@@ -56,6 +56,20 @@ SET @@global.slow_query_log_file = mytest.log;
 --error ER_WRONG_TYPE_FOR_VAR
 SET @@global.slow_query_log_file = 12;
 
+#
+# MDEV-10465
+#
+--error ER_WRONG_VALUE_FOR_VAR
+SET @@global.slow_query_log_file = 'my.cnf';
+--error ER_WRONG_VALUE_FOR_VAR
+SET @@global.slow_query_log_file = '/tmp/my.cnf';
+--error ER_WRONG_VALUE_FOR_VAR
+SET @@global.general_log_file = '.my.cnf';
+--error ER_WRONG_VALUE_FOR_VAR
+SET @@global.general_log_file = 'my.cnf\0foo';
+--error ER_WRONG_VALUE_FOR_VAR
+SET @@global.general_log_file = 'my.ini';
+
 --echo '#----------------------FN_DYNVARS_004_03------------------------#'
 ############################################################################## 
 # Check if the value in GLOBAL Tables matches values in variable             #
diff --git a/mysql-test/t/ctype_utf32.test b/mysql-test/t/ctype_utf32.test
index 1be8925..8cbb8e2 100644
--- a/mysql-test/t/ctype_utf32.test
+++ b/mysql-test/t/ctype_utf32.test
@@ -876,6 +876,11 @@ SELECT CHAR_LENGTH(TRIM(BOTH 0x0001 FROM _utf32 0x00000061));
 SELECT CHAR_LENGTH(TRIM(BOTH 0x61 FROM _utf32 0x00000061));
 SELECT CHAR_LENGTH(TRIM(BOTH 0x00 FROM _utf32 0x00000061));
 
+#
+# potential signedness issue
+#
+select hex(lower(cast(0xffff0000 as char character set utf32))) as c;
+
 --echo #
 --echo # End of 5.5 tests
 --echo #
diff --git a/mysql-test/t/func_group.test b/mysql-test/t/func_group.test
index bd3ed4a..7013009 100644
--- a/mysql-test/t/func_group.test
+++ b/mysql-test/t/func_group.test
@@ -1565,3 +1565,34 @@ EXECUTE stmt;
 EXECUTE stmt;
 
 DROP TABLE t1,t2,t3,t4,t5,t6;
+
+--echo #
+--echo # MDEV-10500 CASE/IF Statement returns multiple values and shifts further result values to the next column
+--echo #
+
+CREATE TABLE t1 (
+  id int not null AUTO_INCREMENT,
+  active bool not null,
+  data1 bigint,
+  data2 bigint,
+  data3 bigint,
+  primary key (id)
+);
+INSERT INTO t1 (active,data1,data2,data3) VALUES (1,null,100,200);
+SELECT
+  CASE WHEN active THEN SUM(data1) END AS C_1,
+  SUM(data2) AS C_2,
+  SUM(data3) AS C_3
+FROM t1;
+SELECT
+  IF(active, SUM(data1), 5) AS C_1,
+  SUM(data2) AS C_2,
+  SUM(data3) AS C_3
+FROM t1;
+DROP TABLE t1;
+
+--echo #
+--echo # MDEV-10468 Assertion `nr >= 0.0' failed in Item_sum_std::val_real()
+--echo #
+SELECT STDDEV_POP(f) FROM (SELECT "1e+309" AS f UNION SELECT "-1e+309" AS f) tbl;
+SELECT STDDEV(f) FROM (SELECT 1.7976931348623157e+308 AS f UNION SELECT -1.7976931348623157e+308 AS f) tbl;
diff --git a/mysql-test/t/func_math.test b/mysql-test/t/func_math.test
index cd90184..d31b33b 100644
--- a/mysql-test/t/func_math.test
+++ b/mysql-test/t/func_math.test
@@ -567,3 +567,15 @@ select 5.0 div 2.0;
 select 5.0 div 2;
 select 5 div 2.0;
 select 5.9 div 2, 1.23456789e3 DIV 2, 1.23456789e9 DIV 2, 1.23456789e19 DIV 2;
+
+--echo #
+--echo # MDEV-10467 Assertion `nr >= 0.0' failed in Item_sum_std::val_real()
+--echo #
+CREATE TABLE t1 (i INT);
+INSERT INTO t1 VALUES (1),(2);
+SELECT STDDEV_SAMP(ROUND('0', 309)) FROM t1;
+DROP TABLE t1;
+
+--echo #
+--echo # End of 5.5 tests
+--echo #
diff --git a/mysql-test/t/func_misc.test b/mysql-test/t/func_misc.test
index 5991220..d7eda5e 100644
--- a/mysql-test/t/func_misc.test
+++ b/mysql-test/t/func_misc.test
@@ -599,3 +599,13 @@ drop table t1;
 --echo #
 --echo # End of 5.5 tests
 --echo #
+
+#
+# Bug#12735545 - PARSER STACK OVERFLOW WITH NAME_CONST
+#                CONTAINING OR EXPRESSION
+#
+--error ER_WRONG_ARGUMENTS
+SELECT NAME_CONST('a', -(1 OR 2)) OR 1;
+--error ER_WRONG_ARGUMENTS
+SELECT NAME_CONST('a', -(1 AND 2)) OR 1;
+SELECT NAME_CONST('a', -(1)) OR 1;
diff --git a/mysql-test/t/group_min_max_innodb.test b/mysql-test/t/group_min_max_innodb.test
index 6967f84..91e0bd3 100644
--- a/mysql-test/t/group_min_max_innodb.test
+++ b/mysql-test/t/group_min_max_innodb.test
@@ -230,3 +230,16 @@ eval EXPLAIN $query;
 eval $query;
 
 DROP TABLE t0,t1,t2;
+
+--echo #
+--echo # MDEV-MariaDB daemon leaks memory with specific query
+--echo #
+
+CREATE TABLE t1 (`voter_id` int(11) unsigned NOT NULL,
+  `language_id` int(11) unsigned NOT NULL DEFAULT '1'
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+CREATE TABLE t2 (`voter_id` int(10) unsigned NOT NULL DEFAULT '0',
+  `serialized_c` mediumblob) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+insert into t2 values (1,repeat("a",1000)),(2,repeat("a",1000)),(3,repeat("b",1000)),(4,repeat("c",1000)),(4,repeat("b",1000));
+SELECT GROUP_CONCAT(t1.language_id SEPARATOR ',') AS `translation_resources`, `d`.`serialized_c` FROM t2 AS `d` LEFT JOIN t1 ON `d`.`voter_id` = t1.`voter_id` GROUP BY `d`.`voter_id` ORDER BY 10-d.voter_id+RAND()*0;
+drop table t1,t2;
diff --git a/mysql-test/t/loaddata.test b/mysql-test/t/loaddata.test
index 3524386..7d0f385 100644
--- a/mysql-test/t/loaddata.test
+++ b/mysql-test/t/loaddata.test
@@ -612,7 +612,7 @@ disconnect con1;
 --echo #
 
 CREATE TABLE t1(f1 INT);
-EVAL SELECT 0xE1BB30 INTO OUTFILE 't1.dat';
+EVAL SELECT 0xE1C330 INTO OUTFILE 't1.dat';
 --disable_warnings
 LOAD DATA INFILE 't1.dat' IGNORE INTO TABLE t1 CHARACTER SET utf8;
 --enable_warnings
@@ -658,3 +658,26 @@ SET @@sql_mode= @old_mode;
 --remove_file $MYSQLTEST_VARDIR/mysql
 DROP TABLE t1;
 
+--echo
+--echo #
+--echo #  Bug#23080148 - Backport of Bug#20683959.
+--echo #  Bug#20683959 LOAD DATA INFILE IGNORES A SPECIFIC ROW SILENTLY
+--echo #               UNDER DB CHARSET IS UTF8.
+--echo #
+
+CREATE DATABASE d1 CHARSET latin1;
+USE d1;
+CREATE TABLE t1 (val TEXT);
+LOAD DATA INFILE '../../std_data/bug20683959loaddata.txt' INTO TABLE t1;
+SELECT COUNT(*) FROM t1;
+SELECT HEX(val) FROM t1;
+
+CREATE DATABASE d2 CHARSET utf8;
+USE d2;
+CREATE TABLE t1 (val TEXT);
+--error ER_INVALID_CHARACTER_STRING
+LOAD DATA INFILE '../../std_data/bug20683959loaddata.txt' INTO TABLE t1;
+
+DROP TABLE d1.t1, d2.t1;
+DROP DATABASE d1;
+DROP DATABASE d2;
diff --git a/mysql-test/t/merge.test b/mysql-test/t/merge.test
index 6573c2b..9d0ddd0 100644
--- a/mysql-test/t/merge.test
+++ b/mysql-test/t/merge.test
@@ -2880,6 +2880,19 @@ drop tables m1, t1, t4;
 drop view t3;
 
 
+--echo #
+--echo # MDEV-10424 - Assertion `ticket == __null' failed in
+--echo #              MDL_request::set_type
+--echo #
+CREATE TABLE t1 (f1 INT) ENGINE=MyISAM;
+CREATE TABLE tmerge (f1 INT) ENGINE=MERGE UNION=(t1);
+PREPARE stmt FROM "ANALYZE TABLE tmerge, t1";
+EXECUTE stmt;
+EXECUTE stmt;
+DEALLOCATE PREPARE stmt;
+DROP TABLE t1, tmerge;
+
+
 --echo End of 5.5 tests
 
 --disable_result_log
diff --git a/mysql-test/t/myisam_enable_keys-10506.test b/mysql-test/t/myisam_enable_keys-10506.test
new file mode 100644
index 0000000..8e1c058
--- /dev/null
+++ b/mysql-test/t/myisam_enable_keys-10506.test
@@ -0,0 +1,117 @@
+#
+# MDEV-10506 Protocol::end_statement(): Assertion `0' failed upon ALTER TABLE
+#
+CREATE TABLE t1 (
+    pk INT AUTO_INCREMENT,
+    i INT,
+    d DATE,
+    dt DATETIME,
+    v VARCHAR(1),
+    PRIMARY KEY (pk),
+    KEY (dt)
+) ENGINE=MyISAM;
+INSERT INTO t1 (i, d, dt, v) VALUES 
+    (9, '2005-07-23', '2004-05-13 01:01:39', 't'),
+    (2, '2009-11-01', '2003-12-24 07:39:29', 'h'),
+    (6, NULL, '2008-07-03 05:32:22', 'l'),
+    (6, '2007-07-16', '2008-08-28 18:46:11', 'j'),
+    (5, NULL, '2001-07-12 21:27:00', 'h'),
+    (3, '2007-07-22', '1900-01-01 00:00:00', 'p'),
+    (2, '2000-11-21', '2007-05-25 11:58:54', 'g'),
+    (6, '1900-01-01', '2009-06-03 17:11:10', 'i'),
+    (2, '2008-02-10', '2001-06-15 16:20:07', 'p'),
+    (3, '2009-06-04', '1900-01-01 00:00:00', 'h'),
+    (9, '2007-04-25', '1900-01-01 00:00:00', 'e'),
+    (9, '2006-03-02', '1900-01-01 00:00:00', 'e'),
+    (1, '1900-01-01', '2002-11-08 09:33:27', 'u'),
+    (7, '2008-07-13', '2007-08-07 17:35:52', 'j'),
+    (0, '2004-11-12', '2006-05-01 00:00:00', 'e'),
+    (0, '1900-01-01', '2003-05-01 00:00:00', 'z'),
+    (1, '2009-09-02', '2007-02-12 09:30:49', 'w'),
+    (0, '2004-11-06', '1900-01-01 00:00:00', 't'),
+    (4, '2003-01-06', '2002-07-03 02:51:11', 'i'),
+    (6, '2006-01-14', '2008-02-26 04:57:32', 'i'),
+    (0, '2002-01-19', '2009-02-12 00:00:00', 'i'),
+    (8, '2007-02-12', '1900-01-01 00:00:00', 'b'),
+    (4, '1900-01-01', '2001-05-16 05:28:40', 'm'),
+    (2, '2005-07-16', NULL, 'j'),
+    (1, '2004-09-04', '2001-01-24 21:45:18', 'v'),
+    (3, '2009-07-01', NULL, NULL),
+    (2, '2009-07-21', '2002-07-24 00:00:00', 'h'),
+    (4, NULL, '2001-11-03 12:22:30', 'q'),
+    (1, '2002-06-22', '2008-06-17 03:17:59', 'f'),
+    (7, '2005-06-23', '2005-12-24 00:00:00', 'p'),
+    (6, '2001-05-20', '2008-10-23 00:00:00',  NULL),
+    (3, '2001-10-01', '2000-10-12 16:32:35', 'o'),
+    (3, '2001-01-07', '2005-09-11 10:09:54', 'w'),
+    (6, '2007-11-02', '2009-09-10 01:44:18', 'l'),
+    (6, NULL, NULL, 'i'),
+    (9, NULL, '2002-05-18 15:21:55', 'd'),
+    (4, '2008-12-21', '2004-10-15 10:09:54', 'j'),
+    (6, '2003-10-05', '2009-07-13 03:51:02', 'e'),
+    (2, '2001-03-03', '1900-01-01 00:00:00', 'e'),
+    (2, '2007-04-04', '2001-11-08 21:14:52', 'q'),
+    (5, NULL, '2006-12-02 00:00:00', 'm'),
+    (0, '2009-01-04', '1900-01-01 00:00:00', NULL),
+    (8, '2008-04-03', '2005-01-01 11:55:18', 'q'),
+    (8, NULL, '2005-02-28 03:44:02', 'w'),
+    (0, '2003-08-22', NULL, 'c'),
+    (9, '1900-01-01', NULL, 'y'),
+    (NULL, NULL, '2006-08-25 16:28:09', 'g'),
+    (5, '2004-07-04', '2002-08-11 00:00:00', 'z'),
+    (1, '1900-01-01', '2007-07-22 21:19:18', 'm'),
+    (2, '2007-02-04', '2006-02-10 18:41:38', 't'),
+    (2, '1900-01-01', '2009-02-16 14:58:58', 'd'),
+    (7, '2001-03-14', '2007-08-14 00:00:00', 'h'),
+    (0, NULL, '1900-01-01 00:00:00', NULL),
+    (1, '2008-10-05', NULL, 'f'),
+    (6, '2001-11-25', '2008-12-03 06:59:23', 'l'),
+    (NULL, '2003-01-27', '2008-10-04 00:00:00', 'g'),
+    (8, '2008-08-08', '2009-07-07 07:00:21', 'v'),
+    (8, '2006-07-03', '2001-04-15 00:00:00', NULL),
+    (5, '2002-11-21', '2007-07-08 04:01:58', 'm'),
+    (5, '2006-04-08', '2007-09-23 00:01:35', 'i'),
+    (5, '2001-05-06', '2008-05-15 00:00:00', 'h'),
+    (7, '1900-01-01', '1900-01-01 00:00:00', 'u'),
+    (30, '2007-04-16', '2004-03-05 23:35:38', 'o'),
+    (NULL, '1900-01-01', '2007-08-25 01:32:47', 'z'),
+    (6, '2004-12-03', '1900-01-01 00:00:00', 'o'),
+    (8, '2001-06-23', '1900-01-01 00:00:00', 'f'),
+    (NULL, '2008-12-15', '2001-05-19 08:28:28', 'a'),
+    (9, '2000-02-15', '2009-09-03 06:07:22', 'd'),
+    (2, '2001-08-05', '2006-10-08 07:17:27', 'k'),
+    (5, '2004-01-17', '2003-09-06 20:36:01', 'd'),
+    (4, '2003-10-01', '2001-02-05 18:10:49', 'u'),
+    (4, '2003-07-28', '2001-01-07 16:11:37', 'h'),
+    (0, '1900-01-01', '2008-08-01 05:26:38', 'w'),
+    (9, '1900-01-01', '2001-05-08 00:00:00', 't'),
+    (1, '2000-04-17', '2008-07-10 21:26:28', 'i'),
+    (8, '2002-01-05', '2006-08-06 20:56:35', 'k'),
+    (9, '2001-04-10', '2003-02-17 00:00:00', 'z'),
+    (0, '2009-12-04', NULL, 'h'),
+    (7, NULL, '2004-10-27 00:29:57', 'h'),
+    (2, '2006-03-07', '2008-03-04 06:14:13', 'b'),
+    (0, '2001-10-15', '2001-03-17 00:00:00', 'm'),
+    (5, '1900-01-01', '2009-02-21 11:35:50', 'i'),
+    (4, NULL, '1900-01-01 00:00:00', 'w'),
+    (5, '2009-04-05', '1900-01-01 00:00:00', 'm'),
+    (6, '2001-03-19', '2001-04-12 00:00:00', 'q'),
+    (NULL, '2009-12-08', '2001-12-04 20:21:01', 'k'),
+    (2, '2005-02-09', '2001-05-27 08:41:01', 'l'),
+    (9, '2004-05-25', '2004-09-18 00:00:00', 'c'),
+    (3, '2005-01-17', '2002-09-12 11:18:48', 'd'),
+    (0, '2003-08-28', '1900-01-01 00:00:00', 'k'),
+    (6, '2006-10-11', '2003-10-28 03:31:02', 'a'),
+    (5, '1900-01-01', '2001-08-22 10:20:09', 'p'),
+    (8, '1900-01-01', '2008-04-24 00:00:00', 'o'),
+    (4, '2005-08-18', '2006-11-10 10:08:49', 'e'),
+    (NULL, '2007-03-12', '2007-10-16 00:00:00', 'n'),
+    (1, '2000-11-18', '2009-05-27 12:25:07', 't'),
+    (4, '2001-03-03', NULL, 'u'),
+    (3, '2003-09-11', '2001-09-10 18:10:10', 'f'),
+    (4, '2007-06-17', '1900-01-01 00:00:00', 't'),
+    (NULL, '2008-09-11', '2004-06-07 23:17:09', 'k');
+ALTER TABLE t1 ADD UNIQUE KEY ind1 (pk, d, i, v);
+--error ER_DUP_ENTRY
+ALTER TABLE t1 ADD UNIQUE KEY ind2 (d, v);
+DROP TABLE t1;
diff --git a/mysql-test/t/mysqlcheck.test b/mysql-test/t/mysqlcheck.test
index ac42e1e..781af35 100644
--- a/mysql-test/t/mysqlcheck.test
+++ b/mysql-test/t/mysqlcheck.test
@@ -310,15 +310,36 @@ CHECK TABLE bug47205 FOR UPGRADE;
 
 DROP TABLE bug47205;
 
+
 --echo #
 --echo #MDEV-6128:[PATCH] mysqlcheck wrongly escapes '.' in table names
 --echo #
-CREATE TABLE test.`t.1` (id int);
+create table `t.1` (id int);
+create view `v.1` as select 1;
 
 --echo mysqlcheck test t.1
 --exec $MYSQL_CHECK test t.1
+--echo mysqlcheck --all-in-1 test t.1
+--exec $MYSQL_CHECK --all-in-1 test t.1
+--echo mysqlcheck --all-in-1 --databases --process-views test
+--exec $MYSQL_CHECK --all-in-1 --databases --process-views test
+
+create table `t.2`(a varchar(20) primary key) default character set utf8 collate utf8_general_ci engine=innodb;
+flush table `t.2`;
+--remove_file $MYSQLD_DATADIR/test/t at 002e2.frm
+--copy_file std_data/bug47205.frm $MYSQLD_DATADIR/test/t at 002e2.frm
+
+--copy_file std_data/bug36055.frm $MYSQLD_DATADIR/test/t at 002e3.frm
+--copy_file std_data/bug36055.MYD $MYSQLD_DATADIR/test/t at 002e3.MYD
+--copy_file std_data/bug36055.MYI $MYSQLD_DATADIR/test/t at 002e3.MYI
+
+--echo mysqlcheck --check-upgrade --auto-repair test
+--exec $MYSQL_CHECK --check-upgrade --auto-repair test
 
-drop table test.`t.1`;
+check table `t.1`, `t.2`, `t.3`;
+check table `t.1`, `t.2`, `t.3` for upgrade;
+drop view `v.1`;
+drop table test.`t.1`, `t.2`, `t.3`;
 
 #
 # MDEV-8123 mysqlcheck: new --process-views option conflicts with --quick, --extended and such
@@ -350,3 +371,30 @@ create table t1(a int);
 --exec $MYSQL_CHECK --process-views --check-upgrade --auto-repair test
 drop view v1;
 drop table t1;
+
+create table `#mysql50#t1``1` (a int) engine=myisam;
+--exec $MYSQL_CHECK --fix-table-names --databases test
+show tables;
+drop table `t1``1`;
+
+#
+#     MDEV-9440 mysqlcheck -A --auto-repair selects wrong database when trying to repair broken table
+#
+call mtr.add_suppression("ha_myisam");
+call mtr.add_suppression("Checking table");
+create database mysqltest1;
+create table mysqltest1.t1 (a int) engine=myisam;
+create table t2 (a int);
+
+let $datadir= `select @@datadir`;
+remove_file $datadir/mysqltest1/t1.MYD;
+write_file $datadir/mysqltest1/t1.MYD;
+foo
+EOF
+
+check table mysqltest1.t1;
+
+--exec $MYSQL_CHECK -A --auto-repair --fast
+
+drop table t2;
+drop database mysqltest1;
diff --git a/mysql-test/t/named_pipe.test b/mysql-test/t/named_pipe.test
index 8dcab33..af74c20 100644
--- a/mysql-test/t/named_pipe.test
+++ b/mysql-test/t/named_pipe.test
@@ -22,3 +22,12 @@ connect(pipe_con,localhost,root,,,,,PIPE);
 
 connection default;
 disconnect pipe_con;
+
+# MDEV-10383 : check that other server cannot 'bind' on the same pipe
+let $MYSQLD_DATADIR= `select @@datadir`;
+--error  1
+--exec $MYSQLD_CMD --enable-named-pipe --skip-networking --log-error=second-mysqld.err
+let SEARCH_FILE=$MYSQLD_DATADIR/second-mysqld.err;
+let SEARCH_RANGE= -50;
+let SEARCH_PATTERN=\[ERROR\] Create named pipe failed;
+source include/search_pattern_in_file.inc;
diff --git a/mysql-test/t/ps.test b/mysql-test/t/ps.test
index 2ed5bb1..1516acca 100644
--- a/mysql-test/t/ps.test
+++ b/mysql-test/t/ps.test
@@ -3653,5 +3653,32 @@ deallocate prepare stmt;
 SET SESSION sql_mode = @save_sql_mode;
 DROP TABLE t1,t2;
 
+--echo #
+--echo # MDEV-8833: Crash of server on prepared statement with
+--echo # conversion to semi-join
+--echo #
+
+CREATE TABLE t1 (column1 INT);
+INSERT INTO t1 VALUES (3),(9);
+
+CREATE TABLE t2 (column2 INT);
+INSERT INTO t2 VALUES (1),(4);
+
+CREATE TABLE t3 (column3 INT);
+INSERT INTO t3 VALUES (6),(8);
+
+CREATE TABLE t4 (column4 INT);
+INSERT INTO t4 VALUES (2),(5);
+
+PREPARE stmt FROM "SELECT ( SELECT MAX( table1.column1 ) AS field1 
+FROM t1 AS table1
+WHERE table3.column3 IN ( SELECT table2.column2 AS field2 FROM t2 AS table2 ) 
+) AS sq
+FROM t3 AS table3, t4 AS table4";
+EXECUTE stmt;
+EXECUTE stmt;
+deallocate prepare stmt;
+drop table t1,t2,t3,t4;
+
 
---echo # End of 10.0 tests
+--echo # End of 5.5 tests
diff --git a/mysql-test/t/ps_1general.test b/mysql-test/t/ps_1general.test
index 812b1b5..7b7b87e 100644
--- a/mysql-test/t/ps_1general.test
+++ b/mysql-test/t/ps_1general.test
@@ -936,3 +936,10 @@ drop table t1;
 #     Matthias
 
 # End of 4.1 tests
+
+#
+# MDEV-10318 unset params in --ps --embedded
+#
+--error ER_PARSE_ERROR,2031
+select ?+1;
+
diff --git a/mysql-test/t/range.test b/mysql-test/t/range.test
index b73b09d..393ca68 100644
--- a/mysql-test/t/range.test
+++ b/mysql-test/t/range.test
@@ -1689,3 +1689,32 @@ insert into t2 values (0, 0, 0, 0), (1, 1, 1, 1);
 analyze table t2;
 select a, b from t2 where (a, b) in ((0, 0), (1, 1));
 drop table t2;
+
+--echo #
+--echo # MDEV-10228: Delete missing rows with OR conditions
+--echo #  (The example uses UPDATE, because UPDATE allows to use index hints
+--echo #   and so it's possible to make an example that works with any storage
+--echo #   engine)
+--echo #
+
+CREATE TABLE t1 (
+  key1varchar varchar(14) NOT NULL,
+  key2int int(11) NOT NULL DEFAULT '0',
+  col1 int,
+  PRIMARY KEY (key1varchar,key2int),
+  KEY key1varchar (key1varchar),
+  KEY key2int (key2int)
+) DEFAULT CHARSET=utf8;
+ 
+insert into t1 values 
+  ('value1',0, 0),
+  ('value1',1, 0),
+  ('value1',1000685, 0),
+  ('value1',1003560, 0),
+  ('value1',1004807, 0);
+
+update t1 force index (PRIMARY) set col1=12345
+where (key1varchar='value1' AND (key2int <=1 OR  key2int > 1));
+--echo # The following must show col1=12345 for all rows:
+select * from t1;
+drop table t1;
diff --git a/mysql-test/t/sp-prelocking.test b/mysql-test/t/sp-prelocking.test
index 966c59a..c1378d5 100644
--- a/mysql-test/t/sp-prelocking.test
+++ b/mysql-test/t/sp-prelocking.test
@@ -388,3 +388,29 @@ DROP TABLE t1, t2;
 
 --echo End of 5.0 tests
 
+--echo #
+--echo # Bug#21142859: FUNCTION UPDATING A VIEW FAILS TO FIND TABLE THAT ACTUALLY EXISTS
+--echo #
+
+CREATE TABLE t1 SELECT 1 AS fld1, 'A' AS fld2;
+CREATE TABLE t2 (fld3 INT, fld4 CHAR(1));
+
+CREATE VIEW v1 AS SELECT * FROM t1;
+
+CREATE TRIGGER t1_au AFTER UPDATE ON t1
+FOR EACH ROW INSERT INTO t2 VALUES (new.fld1, new.fld2);
+
+DELIMITER !;
+CREATE FUNCTION f1() RETURNS INT
+BEGIN
+ UPDATE v1 SET fld2='B' WHERE fld1=1;
+ RETURN row_count();
+END !
+DELIMITER ;!
+
+--echo # Without the patch, an error was getting reported.
+SELECT f1();
+
+DROP FUNCTION f1;
+DROP VIEW v1;
+DROP TABLE t1,t2;
diff --git a/mysql-test/t/type_date.test b/mysql-test/t/type_date.test
index 8b0c5dc..832e725 100644
--- a/mysql-test/t/type_date.test
+++ b/mysql-test/t/type_date.test
@@ -169,18 +169,8 @@ DROP TABLE t1;
 #
 
 CREATE TABLE t1 (a DATE, b INT, PRIMARY KEY (a,b));
-## The current sub test could fail (difference to expected result) if we
-## have just reached midnight.
-## (Bug#41776 type_date.test may fail if run around midnight)
-## Therefore we sleep a bit if we are too close to midnight.
-## The complete test itself needs in average less than 1 second.
-## Therefore a time_distance to midnight of 5 seconds should be sufficient.
-if (`SELECT CURTIME() > SEC_TO_TIME(24 * 3600 - 5)`)
-{
-   # We are here when CURTIME() is between '23:59:56' and '23:59:59'.
-   # So a sleep time of 5 seconds brings us between '00:00:01' and '00:00:04'.
-   --real_sleep 5
-}
+
+SET timestamp=UNIX_TIMESTAMP('2016-07-21 14:48:18');
 INSERT INTO t1 VALUES (DATE(NOW()), 1);
 SELECT COUNT(*) FROM t1 WHERE a = NOW();
 EXPLAIN SELECT COUNT(*) FROM t1 WHERE a = NOW();
@@ -192,6 +182,7 @@ EXPLAIN SELECT COUNT(*) FROM t1 WHERE a = NOW() AND b = 1;
 ALTER TABLE t1 DROP PRIMARY KEY;
 SELECT COUNT(*) FROM t1 WHERE a = NOW();
 EXPLAIN SELECT COUNT(*) FROM t1 WHERE a = NOW();
+SET timestamp=DEFAULT;
 
 DROP TABLE t1;
 
diff --git a/mysql-test/t/type_uint.test b/mysql-test/t/type_uint.test
index a921218..14e5e3b 100644
--- a/mysql-test/t/type_uint.test
+++ b/mysql-test/t/type_uint.test
@@ -15,3 +15,11 @@ select * from t1;
 drop table t1;
 
 # End of 4.1 tests
+
+create table t1 (a bigint unsigned, b mediumint unsigned);
+insert t1 values (1,2),(0xffffffffffffffff,0xffffff);
+select coalesce(a,b), coalesce(b,a) from t1;
+create table t2 as select a from t1 union select b from t1;
+show create table t2;
+select * from t2;
+drop table t1, t2;
diff --git a/mysql-test/t/view.test b/mysql-test/t/view.test
index a25a4d1..ebd6858 100644
--- a/mysql-test/t/view.test
+++ b/mysql-test/t/view.test
@@ -5490,6 +5490,21 @@ alter table v1 check partition p1;
 drop view v1;
 drop table t1;
 
+
+--echo #
+--echo # MDEV-10419: crash in mariadb 10.1.16-MariaDB-1~trusty
+--echo #
+CREATE TABLE t1 (c1 CHAR(13));
+CREATE TABLE t2 (c2 CHAR(13));
+ 
+CREATE FUNCTION f() RETURNS INT RETURN 0;
+CREATE OR REPLACE VIEW v1 AS select f() from t1 where c1 in (select c2 from t2);
+DROP FUNCTION f;
+ 
+SHOW CREATE VIEW v1;
+
+drop view v1;
+drop table t1,t2;
 --echo # -----------------------------------------------------------------
 --echo # -- End of 5.5 tests.
 --echo # -----------------------------------------------------------------
diff --git a/mysql-test/t/xtradb_mrr.test b/mysql-test/t/xtradb_mrr.test
index 260eb9f..d994c18 100644
--- a/mysql-test/t/xtradb_mrr.test
+++ b/mysql-test/t/xtradb_mrr.test
@@ -33,8 +33,8 @@ insert into t2 select
 from t1 A, t1 B, t1 C;
 
 explain
-select count(length(a) + length(filler)) from t2 where a>='a-1000-a' and a <'a-1001-a';
-select count(length(a) + length(filler)) from t2 where a>='a-1000-a' and a <'a-1001-a';
+select count(length(a) + length(filler)) from t2 force index (a) where a>='a-1000-a' and a <'a-1001-a';
+select count(length(a) + length(filler)) from t2 force index (a) where a>='a-1000-a' and a <'a-1001-a';
 drop table t2;
 
 # Try a very big rowid
diff --git a/mysys/my_context.c b/mysys/my_context.c
index 01d6f40..5ddb2cc 100644
--- a/mysys/my_context.c
+++ b/mysys/my_context.c
@@ -698,30 +698,27 @@ my_context_destroy(struct my_context *c)
 int
 my_context_spawn(struct my_context *c, void (*f)(void *), void *d)
 {
-  void *current_fiber;
   c->user_func= f;
   c->user_arg= d;
+  return my_context_continue(c);
+}
+
+int
+my_context_continue(struct my_context *c)
+{
   /*
     This seems to be a common trick to run ConvertThreadToFiber() only on the
     first occurence in a thread, in a way that works on multiple Windows
     versions.
   */
-  current_fiber= GetCurrentFiber();
+  void *current_fiber= GetCurrentFiber();
   if (current_fiber == NULL || current_fiber == (void *)0x1e00)
     current_fiber= ConvertThreadToFiber(c);
   c->app_fiber= current_fiber;
   DBUG_SWAP_CODE_STATE(&c->dbug_state);
   SwitchToFiber(c->lib_fiber);
   DBUG_SWAP_CODE_STATE(&c->dbug_state);
-  return c->return_value;
-}
 
-int
-my_context_continue(struct my_context *c)
-{
-  DBUG_SWAP_CODE_STATE(&c->dbug_state);
-  SwitchToFiber(c->lib_fiber);
-  DBUG_SWAP_CODE_STATE(&c->dbug_state);
   return c->return_value;
 }
 
diff --git a/mysys/my_redel.c b/mysys/my_redel.c
index b285bb2..e5e4f48 100644
--- a/mysys/my_redel.c
+++ b/mysys/my_redel.c
@@ -1,5 +1,5 @@
-/*
-   Copyright (c) 2000, 2010, Oracle and/or its affiliates
+/* Copyright (c) 2000, 2010, Oracle and/or its affiliates
+   Copyright (c) 2009, 2016, MariaDB
 
    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
@@ -49,7 +49,8 @@ int my_redel(const char *org_name, const char *tmp_name,
   DBUG_PRINT("my",("org_name: '%s' tmp_name: '%s'  MyFlags: %d",
 		   org_name,tmp_name,MyFlags));
 
-  if (my_copystat(org_name,tmp_name,MyFlags) < 0)
+  if (!my_disable_copystat_in_redel &&
+      my_copystat(org_name,tmp_name,MyFlags) < 0)
     goto end;
   if (MyFlags & MY_REDEL_MAKE_BACKUP)
   {
diff --git a/mysys/my_static.c b/mysys/my_static.c
index fdc01b1..48b1e5b 100644
--- a/mysys/my_static.c
+++ b/mysys/my_static.c
@@ -99,6 +99,7 @@ my_bool my_disable_sync=0;
 my_bool my_disable_async_io=0;
 my_bool my_disable_flush_key_blocks=0;
 my_bool my_disable_symlinks=0;
+my_bool my_disable_copystat_in_redel=0;
 
 /*
   Note that PSI_hook and PSI_server are unconditionally
diff --git a/plugin/feedback/url_http.cc b/plugin/feedback/url_http.cc
index dff5da5..fbea38c 100644
--- a/plugin/feedback/url_http.cc
+++ b/plugin/feedback/url_http.cc
@@ -190,6 +190,7 @@ int Url_http::send(const char* data, size_t data_length)
       break;
 
     closesocket(fd);
+    fd= INVALID_SOCKET;
   }
 
   freeaddrinfo(addrs);
diff --git a/regex/split.c b/regex/split.c
index a3a11f7..abae74e 100644
--- a/regex/split.c
+++ b/regex/split.c
@@ -159,6 +159,10 @@ char *argv[];
 
 	if (argc > 4)
 		for (n = atoi(argv[3]); n > 0; n--) {
+                        if(sizeof(buf)-1 < strlen(argv[1]))
+                        {
+                          exit(EXIT_FAILURE);
+                        }
 			(void) strcpy(buf, argv[1]);
 		}
 	else if (argc > 3)
diff --git a/scripts/mysql_secure_installation.pl.in b/scripts/mysql_secure_installation.pl.in
index 188a6bd..32331c3 100644
--- a/scripts/mysql_secure_installation.pl.in
+++ b/scripts/mysql_secure_installation.pl.in
@@ -217,7 +217,7 @@ sub remove_remote_root {
 
 sub remove_test_database {
   print " - Dropping test database...\n";
-  if (do_query("DROP DATABASE test;")) {
+  if (do_query("DROP DATABASE IF EXISTS test;")) {
     print " ... Success!\n";
   } else {
     print " ... Failed!  Not critical, keep moving...\n";
diff --git a/scripts/mysql_secure_installation.sh b/scripts/mysql_secure_installation.sh
index 9e9bce9..7fb8b73 100644
--- a/scripts/mysql_secure_installation.sh
+++ b/scripts/mysql_secure_installation.sh
@@ -324,7 +324,7 @@ remove_remote_root() {
 
 remove_test_database() {
     echo " - Dropping test database..."
-    do_query "DROP DATABASE test;"
+    do_query "DROP DATABASE IF EXISTS test;"
     if [ $? -eq 0 ]; then
 	echo " ... Success!"
     else
diff --git a/sql/event_scheduler.cc b/sql/event_scheduler.cc
index beb3c86..a5a3f71 100644
--- a/sql/event_scheduler.cc
+++ b/sql/event_scheduler.cc
@@ -131,12 +131,6 @@ post_init_event_thread(THD *thd)
     thd->cleanup();
     return TRUE;
   }
-
-  mysql_mutex_lock(&LOCK_thread_count);
-  threads.append(thd);
-  thread_count++;
-  inc_thread_running();
-  mysql_mutex_unlock(&LOCK_thread_count);
   return FALSE;
 }
 
@@ -158,7 +152,6 @@ deinit_event_thread(THD *thd)
   DBUG_PRINT("exit", ("Event thread finishing"));
   mysql_mutex_lock(&LOCK_thread_count);
   thread_count--;
-  dec_thread_running();
   delete thd;
   mysql_cond_broadcast(&COND_thread_count);
   mysql_mutex_unlock(&LOCK_thread_count);
@@ -195,6 +188,8 @@ pre_init_event_thread(THD* thd)
   thd->client_capabilities|= CLIENT_MULTI_RESULTS;
   mysql_mutex_lock(&LOCK_thread_count);
   thd->thread_id= thd->variables.pseudo_thread_id= thread_id++;
+  threads.append(thd);
+  thread_count++;
   mysql_mutex_unlock(&LOCK_thread_count);
 
   /*
@@ -241,13 +236,8 @@ event_scheduler_thread(void *arg)
   my_free(arg);
   if (!res)
     scheduler->run(thd);
-  else
-  {
-    thd->proc_info= "Clearing";
-    net_end(&thd->net);
-    delete thd;
-  }
 
+  deinit_event_thread(thd);
   DBUG_LEAVE;                               // Against gcc warnings
   my_thread_end();
   return 0;
@@ -308,6 +298,7 @@ Event_worker_thread::run(THD *thd, Event_queue_element_for_exec *event)
   DBUG_ENTER("Event_worker_thread::run");
   DBUG_PRINT("info", ("Time is %ld, THD: 0x%lx", (long) my_time(0), (long) thd));
 
+  inc_thread_running();
   if (res)
     goto end;
 
@@ -334,6 +325,7 @@ end:
              event->name.str));
 
   delete event;
+  dec_thread_running();
   deinit_event_thread(thd);
 
   DBUG_VOID_RETURN;
@@ -432,13 +424,9 @@ Event_scheduler::start(int *err_no)
                     " Can not create thread for event scheduler (errno=%d)",
                     *err_no);
 
-    new_thd->proc_info= "Clearing";
-    DBUG_ASSERT(new_thd->net.buff != 0);
-    net_end(&new_thd->net);
-
     state= INITIALIZED;
     scheduler_thd= NULL;
-    delete new_thd;
+    deinit_event_thread(new_thd);
 
     delete scheduler_param_value;
     ret= true;
@@ -505,7 +493,6 @@ Event_scheduler::run(THD *thd)
   }
 
   LOCK_DATA();
-  deinit_event_thread(thd);
   scheduler_thd= NULL;
   state= INITIALIZED;
   DBUG_PRINT("info", ("Broadcasting COND_state back to the stoppers"));
@@ -564,10 +551,7 @@ Event_scheduler::execute_top(Event_queue_element_for_exec *event_name)
     sql_print_error("Event_scheduler::execute_top: Can not create event worker"
                     " thread (errno=%d). Stopping event scheduler", res);
 
-    new_thd->proc_info= "Clearing";
-    DBUG_ASSERT(new_thd->net.buff != 0);
-    net_end(&new_thd->net);
-
+    deinit_event_thread(new_thd);
     goto error;
   }
 
@@ -579,9 +563,6 @@ Event_scheduler::execute_top(Event_queue_element_for_exec *event_name)
 
 error:
   DBUG_PRINT("error", ("Event_scheduler::execute_top() res: %d", res));
-  if (new_thd)
-    delete new_thd;
-
   delete event_name;
   DBUG_RETURN(TRUE);
 }
diff --git a/sql/field.cc b/sql/field.cc
index a0686fb..878e3d3 100644
--- a/sql/field.cc
+++ b/sql/field.cc
@@ -359,7 +359,7 @@ static enum_field_types field_types_merge_rules [FIELDTYPE_NUM][FIELDTYPE_NUM]=
   //MYSQL_TYPE_NULL         MYSQL_TYPE_TIMESTAMP
     MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_VARCHAR,
   //MYSQL_TYPE_LONGLONG     MYSQL_TYPE_INT24
-    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_LONG,
+    MYSQL_TYPE_LONGLONG,    MYSQL_TYPE_LONGLONG,
   //MYSQL_TYPE_DATE         MYSQL_TYPE_TIME
     MYSQL_TYPE_VARCHAR,     MYSQL_TYPE_VARCHAR,
   //MYSQL_TYPE_DATETIME     MYSQL_TYPE_YEAR
diff --git a/sql/handler.cc b/sql/handler.cc
index d528c0a..5fc7560 100644
--- a/sql/handler.cc
+++ b/sql/handler.cc
@@ -1238,7 +1238,8 @@ int ha_commit_trans(THD *thd, bool all)
 
   uint rw_ha_count= ha_check_and_coalesce_trx_read_only(thd, ha_info, all);
   /* rw_trans is TRUE when we in a transaction changing data */
-  bool rw_trans= is_real_trans && (rw_ha_count > 0);
+  bool rw_trans= is_real_trans &&
+                 (rw_ha_count > !thd->is_current_stmt_binlog_disabled());
   MDL_request mdl_request;
 
   if (rw_trans)
diff --git a/sql/item.cc b/sql/item.cc
index 5861766..3448b23 100644
--- a/sql/item.cc
+++ b/sql/item.cc
@@ -2778,9 +2778,28 @@ void Item_field::fix_after_pullout(st_select_lex *new_parent, Item **ref)
   if (context)
   {
     Name_resolution_context *ctx= new Name_resolution_context();
-    ctx->outer_context= NULL; // We don't build a complete name resolver
-    ctx->table_list= NULL;    // We rely on first_name_resolution_table instead
+    if (context->select_lex == new_parent)
+    {
+      /*
+        This field was pushed in then pulled out
+        (for example left part of IN)
+      */
+      ctx->outer_context= context->outer_context;
+    }
+    else if (context->outer_context)
+    {
+      /* just pull to the upper context */
+      ctx->outer_context= context->outer_context->outer_context;
+    }
+    else
+    {
+      /* No upper context (merging Derived/VIEW where context chain ends) */
+      ctx->outer_context= NULL;
+    }
+    ctx->table_list= context->first_name_resolution_table;
     ctx->select_lex= new_parent;
+    if (context->select_lex == NULL)
+      ctx->select_lex= NULL;
     ctx->first_name_resolution_table= context->first_name_resolution_table;
     ctx->last_name_resolution_table=  context->last_name_resolution_table;
     ctx->error_processor=             context->error_processor;
@@ -5883,10 +5902,6 @@ Field *Item::tmp_table_field_from_field_type(TABLE *table, bool fixed_length)
     field= new Field_double((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
 			    name, decimals, 0, unsigned_flag);
     break;
-  case MYSQL_TYPE_NULL:
-    field= new Field_null((uchar*) 0, max_length, Field::NONE,
-			  name, &my_charset_bin);
-    break;
   case MYSQL_TYPE_INT24:
     field= new Field_medium((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
 			    name, 0, unsigned_flag);
@@ -5920,6 +5935,7 @@ Field *Item::tmp_table_field_from_field_type(TABLE *table, bool fixed_length)
     DBUG_ASSERT(0);
     /* If something goes awfully wrong, it's better to get a string than die */
   case MYSQL_TYPE_STRING:
+  case MYSQL_TYPE_NULL:
     if (fixed_length && !too_big_for_varchar())
     {
       field= new Field_string(max_length, maybe_null, name,
diff --git a/sql/item_func.cc b/sql/item_func.cc
index 4b5f96c..6c80c7d 100644
--- a/sql/item_func.cc
+++ b/sql/item_func.cc
@@ -2661,6 +2661,9 @@ double my_double_round(double value, longlong dec, bool dec_unsigned,
   volatile double value_div_tmp= value / tmp;
   volatile double value_mul_tmp= value * tmp;
 
+  if (!dec_negative && my_isinf(tmp)) // "dec" is too large positive number
+    return value;
+
   if (dec_negative && my_isinf(tmp))
     tmp2= 0.0;
   else if (!dec_negative && my_isinf(value_mul_tmp))
diff --git a/sql/item_subselect.cc b/sql/item_subselect.cc
index ba67474..3727711 100644
--- a/sql/item_subselect.cc
+++ b/sql/item_subselect.cc
@@ -79,7 +79,6 @@ void Item_subselect::init(st_select_lex *select_lex,
   DBUG_PRINT("enter", ("select_lex: 0x%lx  this: 0x%lx",
                        (ulong) select_lex, (ulong) this));
   unit= select_lex->master_unit();
-  thd= unit->thd;
 
   if (unit->item)
   {
@@ -90,7 +89,7 @@ void Item_subselect::init(st_select_lex *select_lex,
     engine= unit->item->engine;
     own_engine= FALSE;
     parsing_place= unit->item->parsing_place;
-    thd->change_item_tree((Item**)&unit->item, this);
+    unit->thd->change_item_tree((Item**)&unit->item, this);
     engine->change_result(this, result, TRUE);
   }
   else
@@ -104,9 +103,9 @@ void Item_subselect::init(st_select_lex *select_lex,
                     NO_MATTER :
                     outer_select->parsing_place);
     if (unit->is_union())
-      engine= new subselect_union_engine(thd, unit, result, this);
+      engine= new subselect_union_engine(unit, result, this);
     else
-      engine= new subselect_single_select_engine(thd, select_lex, result, this);
+      engine= new subselect_single_select_engine(select_lex, result, this);
   }
   {
     SELECT_LEX *upper= unit->outer_select();
@@ -220,6 +219,10 @@ bool Item_subselect::fix_fields(THD *thd_param, Item **ref)
   uint8 uncacheable;
   bool res;
 
+  thd= thd_param;
+
+  DBUG_ASSERT(unit->thd == thd);
+
   status_var_increment(thd_param->status_var.feature_subquery);
 
   DBUG_ASSERT(fixed == 0);
@@ -242,7 +245,7 @@ bool Item_subselect::fix_fields(THD *thd_param, Item **ref)
     return TRUE;
   
   
-  if (!(res= engine->prepare()))
+  if (!(res= engine->prepare(thd)))
   {
     // all transformation is done (used by prepared statements)
     changed= 1;
@@ -2651,7 +2654,10 @@ bool Item_in_subselect::fix_fields(THD *thd_arg, Item **ref)
 {
   uint outer_cols_num;
   List<Item> *inner_cols;
-  char const *save_where= thd->where;
+  char const *save_where= thd_arg->where;
+
+  thd= thd_arg;
+  DBUG_ASSERT(unit->thd == thd);
 
   if (test_strategy(SUBS_SEMI_JOIN))
     return !( (*ref)= new Item_int(1));
@@ -2769,7 +2775,8 @@ bool Item_in_subselect::setup_mat_engine()
   if (!(mat_engine= new subselect_hash_sj_engine(thd, this, select_engine)))
     DBUG_RETURN(TRUE);
 
-  if (mat_engine->init(&select_engine->join->fields_list,
+  if (mat_engine->prepare(thd) ||
+      mat_engine->init(&select_engine->join->fields_list,
                        engine->get_identifier()))
     DBUG_RETURN(TRUE);
 
@@ -2885,10 +2892,10 @@ void subselect_engine::set_thd(THD *thd_arg)
 
 
 subselect_single_select_engine::
-subselect_single_select_engine(THD *thd_arg, st_select_lex *select,
+subselect_single_select_engine(st_select_lex *select,
 			       select_result_interceptor *result_arg,
 			       Item_subselect *item_arg)
-  :subselect_engine(thd_arg, item_arg, result_arg),
+  :subselect_engine(item_arg, result_arg),
    prepared(0), executed(0),
    select_lex(select), join(0)
 {
@@ -2966,10 +2973,10 @@ void subselect_uniquesubquery_engine::cleanup()
 }
 
 
-subselect_union_engine::subselect_union_engine(THD *thd_arg, st_select_lex_unit *u,
+subselect_union_engine::subselect_union_engine(st_select_lex_unit *u,
 					       select_result_interceptor *result_arg,
 					       Item_subselect *item_arg)
-  :subselect_engine(thd_arg, item_arg, result_arg)
+  :subselect_engine(item_arg, result_arg)
 {
   unit= u;
   unit->item= item_arg;
@@ -3002,10 +3009,11 @@ subselect_union_engine::subselect_union_engine(THD *thd_arg, st_select_lex_unit
   @retval 1  if error
 */
 
-int subselect_single_select_engine::prepare()
+int subselect_single_select_engine::prepare(THD *thd)
 {
   if (prepared)
     return 0;
+  set_thd(thd);
   if (select_lex->join)
   {
     select_lex->cleanup();
@@ -3034,12 +3042,13 @@ int subselect_single_select_engine::prepare()
   return 0;
 }
 
-int subselect_union_engine::prepare()
+int subselect_union_engine::prepare(THD *thd_arg)
 {
+  set_thd(thd_arg);
   return unit->prepare(thd, result, SELECT_NO_UNLOCK);
 }
 
-int subselect_uniquesubquery_engine::prepare()
+int subselect_uniquesubquery_engine::prepare(THD *)
 {
   /* Should never be called. */
   DBUG_ASSERT(FALSE);
@@ -3299,7 +3308,7 @@ int subselect_uniquesubquery_engine::scan_table()
   }
 
   table->file->extra_opt(HA_EXTRA_CACHE,
-                         current_thd->variables.read_buff_size);
+                         get_thd()->variables.read_buff_size);
   table->null_row= 0;
   for (;;)
   {
@@ -3737,7 +3746,7 @@ table_map subselect_union_engine::upper_select_const_tables()
 void subselect_single_select_engine::print(String *str,
                                            enum_query_type query_type)
 {
-  select_lex->print(thd, str, query_type);
+  select_lex->print(get_thd(), str, query_type);
 }
 
 
@@ -4267,6 +4276,7 @@ bitmap_init_memroot(MY_BITMAP *map, uint n_bits, MEM_ROOT *mem_root)
 
 bool subselect_hash_sj_engine::init(List<Item> *tmp_columns, uint subquery_id)
 {
+  THD *thd= get_thd();
   select_union *result_sink;
   /* Options to create_tmp_table. */
   ulonglong tmp_create_options= thd->variables.option_bits | TMP_TABLE_ALL_COLUMNS;
@@ -4499,13 +4509,14 @@ subselect_hash_sj_engine::~subselect_hash_sj_engine()
 }
 
 
-int subselect_hash_sj_engine::prepare()
+int subselect_hash_sj_engine::prepare(THD *thd_arg)
 {
   /*
     Create and optimize the JOIN that will be used to materialize
     the subquery if not yet created.
   */
-  return materialize_engine->prepare();
+  set_thd(thd_arg);
+  return materialize_engine->prepare(thd);
 }
 
 
@@ -4877,7 +4888,7 @@ int subselect_hash_sj_engine::exec()
     if (strategy == PARTIAL_MATCH_MERGE)
     {
       pm_engine=
-        new subselect_rowid_merge_engine(thd, (subselect_uniquesubquery_engine*)
+        new subselect_rowid_merge_engine((subselect_uniquesubquery_engine*)
                                          lookup_engine, tmp_table,
                                          count_pm_keys,
                                          has_covering_null_row,
@@ -4886,6 +4897,7 @@ int subselect_hash_sj_engine::exec()
                                          item, result,
                                          semi_join_conds->argument_list());
       if (!pm_engine ||
+          pm_engine->prepare(thd) ||
           ((subselect_rowid_merge_engine*) pm_engine)->
             init(nn_key_parts, &partial_match_key_parts))
       {
@@ -4903,13 +4915,14 @@ int subselect_hash_sj_engine::exec()
     if (strategy == PARTIAL_MATCH_SCAN)
     {
       if (!(pm_engine=
-            new subselect_table_scan_engine(thd, (subselect_uniquesubquery_engine*)
+            new subselect_table_scan_engine((subselect_uniquesubquery_engine*)
                                             lookup_engine, tmp_table,
                                             item, result,
                                             semi_join_conds->argument_list(),
                                             has_covering_null_row,
                                             has_covering_null_columns,
-                                            count_columns_with_nulls)))
+                                            count_columns_with_nulls)) ||
+          pm_engine->prepare(thd))
       {
         /* This is an irrecoverable error. */
         res= 1;
@@ -5356,14 +5369,14 @@ void Ordered_key::print(String *str)
 
 
 subselect_partial_match_engine::subselect_partial_match_engine(
-  THD *thd_arg, subselect_uniquesubquery_engine *engine_arg,
+  subselect_uniquesubquery_engine *engine_arg,
   TABLE *tmp_table_arg, Item_subselect *item_arg,
   select_result_interceptor *result_arg,
   List<Item> *equi_join_conds_arg,
   bool has_covering_null_row_arg,
   bool has_covering_null_columns_arg,
   uint count_columns_with_nulls_arg)
-  :subselect_engine(thd_arg, item_arg, result_arg),
+  :subselect_engine(item_arg, result_arg),
    tmp_table(tmp_table_arg), lookup_engine(engine_arg),
    equi_join_conds(equi_join_conds_arg),
    has_covering_null_row(has_covering_null_row_arg),
@@ -5488,6 +5501,7 @@ bool
 subselect_rowid_merge_engine::init(MY_BITMAP *non_null_key_parts,
                                    MY_BITMAP *partial_match_key_parts)
 {
+  THD *thd= get_thd();
   /* The length in bytes of the rowids (positions) of tmp_table. */
   uint rowid_length= tmp_table->file->ref_length;
   ha_rows row_count= tmp_table->file->stats.records;
@@ -5976,7 +5990,7 @@ end:
 
 
 subselect_table_scan_engine::subselect_table_scan_engine(
-  THD *thd_arg, subselect_uniquesubquery_engine *engine_arg,
+  subselect_uniquesubquery_engine *engine_arg,
   TABLE *tmp_table_arg,
   Item_subselect *item_arg,
   select_result_interceptor *result_arg,
@@ -5984,7 +5998,7 @@ subselect_table_scan_engine::subselect_table_scan_engine(
   bool has_covering_null_row_arg,
   bool has_covering_null_columns_arg,
   uint count_columns_with_nulls_arg)
-  :subselect_partial_match_engine(thd_arg, engine_arg, tmp_table_arg, item_arg,
+  :subselect_partial_match_engine(engine_arg, tmp_table_arg, item_arg,
                                   result_arg, equi_join_conds_arg,
                                   has_covering_null_row_arg,
                                   has_covering_null_columns_arg,
@@ -6026,7 +6040,7 @@ bool subselect_table_scan_engine::partial_match()
   }
 
   tmp_table->file->extra_opt(HA_EXTRA_CACHE,
-                             current_thd->variables.read_buff_size);
+                             get_thd()->variables.read_buff_size);
   for (;;)
   {
     error= tmp_table->file->ha_rnd_next(tmp_table->record[0]);
diff --git a/sql/item_subselect.h b/sql/item_subselect.h
index 0ee5f73..a44503b 100644
--- a/sql/item_subselect.h
+++ b/sql/item_subselect.h
@@ -715,15 +715,15 @@ public:
                          INDEXSUBQUERY_ENGINE, HASH_SJ_ENGINE,
                          ROWID_MERGE_ENGINE, TABLE_SCAN_ENGINE};
 
-  subselect_engine(THD *thd_arg, Item_subselect *si,
-                   select_result_interceptor *res)
+  subselect_engine(Item_subselect *si,
+                   select_result_interceptor *res):
+    thd(NULL)
   {
     result= res;
     item= si;
     cmp_type= res_type= STRING_RESULT;
     res_field_type= MYSQL_TYPE_VAR_STRING;
     maybe_null= 0;
-    set_thd(thd_arg);
   }
   virtual ~subselect_engine() {}; // to satisfy compiler
   virtual void cleanup()= 0;
@@ -733,8 +733,8 @@ public:
     Should be called before prepare().
   */
   void set_thd(THD *thd_arg);
-  THD * get_thd() { return thd; }
-  virtual int prepare()= 0;
+  THD * get_thd() { return thd ? thd : current_thd; }
+  virtual int prepare(THD *)= 0;
   virtual void fix_length_and_dec(Item_cache** row)= 0;
   /*
     Execute the engine
@@ -789,11 +789,11 @@ class subselect_single_select_engine: public subselect_engine
   st_select_lex *select_lex; /* corresponding select_lex */
   JOIN * join; /* corresponding JOIN structure */
 public:
-  subselect_single_select_engine(THD *thd_arg, st_select_lex *select,
+  subselect_single_select_engine(st_select_lex *select,
 				 select_result_interceptor *result,
 				 Item_subselect *item);
   void cleanup();
-  int prepare();
+  int prepare(THD *thd);
   void fix_length_and_dec(Item_cache** row);
   int exec();
   uint cols();
@@ -823,11 +823,11 @@ class subselect_union_engine: public subselect_engine
 {
   st_select_lex_unit *unit;  /* corresponding unit structure */
 public:
-  subselect_union_engine(THD *thd_arg, st_select_lex_unit *u,
+  subselect_union_engine(st_select_lex_unit *u,
 			 select_result_interceptor *result,
 			 Item_subselect *item);
   void cleanup();
-  int prepare();
+  int prepare(THD *);
   void fix_length_and_dec(Item_cache** row);
   int exec();
   uint cols();
@@ -880,11 +880,11 @@ public:
   // constructor can assign THD because it will be called after JOIN::prepare
   subselect_uniquesubquery_engine(THD *thd_arg, st_join_table *tab_arg,
 				  Item_subselect *subs, Item *where)
-    :subselect_engine(thd_arg, subs, 0), tab(tab_arg), cond(where)
+    :subselect_engine(subs, 0), tab(tab_arg), cond(where)
   {}
   ~subselect_uniquesubquery_engine();
   void cleanup();
-  int prepare();
+  int prepare(THD *);
   void fix_length_and_dec(Item_cache** row);
   int exec();
   uint cols() { return 1; }
@@ -1012,7 +1012,7 @@ public:
 
   subselect_hash_sj_engine(THD *thd, Item_subselect *in_predicate,
                            subselect_single_select_engine *old_engine)
-    : subselect_engine(thd, in_predicate, NULL), 
+    : subselect_engine(in_predicate, NULL), 
       tmp_table(NULL), is_materialized(FALSE), materialize_engine(old_engine),
       materialize_join(NULL),  semi_join_conds(NULL), lookup_engine(NULL),
       count_partial_match_columns(0), count_null_only_columns(0),
@@ -1022,7 +1022,7 @@ public:
 
   bool init(List<Item> *tmp_columns, uint subquery_id);
   void cleanup();
-  int prepare();
+  int prepare(THD *);
   int exec();
   virtual void print(String *str, enum_query_type query_type);
   uint cols()
@@ -1301,15 +1301,14 @@ protected:
 protected:
   virtual bool partial_match()= 0;
 public:
-  subselect_partial_match_engine(THD *thd_arg,
-                                 subselect_uniquesubquery_engine *engine_arg,
+  subselect_partial_match_engine(subselect_uniquesubquery_engine *engine_arg,
                                  TABLE *tmp_table_arg, Item_subselect *item_arg,
                                  select_result_interceptor *result_arg,
                                  List<Item> *equi_join_conds_arg,
                                  bool has_covering_null_row_arg,
                                  bool has_covering_null_columns_arg,
                                  uint count_columns_with_nulls_arg);
-  int prepare() { return 0; }
+  int prepare(THD *thd_arg) { set_thd(thd_arg); return 0; }
   int exec();
   void fix_length_and_dec(Item_cache**) {}
   uint cols() { /* TODO: what is the correct value? */ return 1; }
@@ -1396,8 +1395,7 @@ protected:
   bool exists_complementing_null_row(MY_BITMAP *keys_to_complement);
   bool partial_match();
 public:
-  subselect_rowid_merge_engine(THD *thd_arg,
-                               subselect_uniquesubquery_engine *engine_arg,
+  subselect_rowid_merge_engine(subselect_uniquesubquery_engine *engine_arg,
                                TABLE *tmp_table_arg, uint merge_keys_count_arg,
                                bool has_covering_null_row_arg,
                                bool has_covering_null_columns_arg,
@@ -1405,7 +1403,7 @@ public:
                                Item_subselect *item_arg,
                                select_result_interceptor *result_arg,
                                List<Item> *equi_join_conds_arg)
-    :subselect_partial_match_engine(thd_arg, engine_arg, tmp_table_arg,
+    :subselect_partial_match_engine(engine_arg, tmp_table_arg,
                                     item_arg, result_arg, equi_join_conds_arg,
                                     has_covering_null_row_arg,
                                     has_covering_null_columns_arg,
@@ -1424,8 +1422,7 @@ class subselect_table_scan_engine: public subselect_partial_match_engine
 protected:
   bool partial_match();
 public:
-  subselect_table_scan_engine(THD *thd_arg,
-                              subselect_uniquesubquery_engine *engine_arg,
+  subselect_table_scan_engine(subselect_uniquesubquery_engine *engine_arg,
                               TABLE *tmp_table_arg, Item_subselect *item_arg,
                               select_result_interceptor *result_arg,
                               List<Item> *equi_join_conds_arg,
diff --git a/sql/item_sum.cc b/sql/item_sum.cc
index adf48f6..02d2875 100644
--- a/sql/item_sum.cc
+++ b/sql/item_sum.cc
@@ -1462,7 +1462,7 @@ my_decimal *Item_sum_sum::val_decimal(my_decimal *val)
   if (aggr)
     aggr->endup();
   if (hybrid_type == DECIMAL_RESULT)
-    return (dec_buffs + curr_dec_buff);
+    return null_value ? NULL : (dec_buffs + curr_dec_buff);
   return val_decimal_from_real(val);
 }
 
@@ -1762,6 +1762,8 @@ double Item_sum_std::val_real()
 {
   DBUG_ASSERT(fixed == 1);
   double nr= Item_sum_variance::val_real();
+  if (my_isinf(nr))
+    return DBL_MAX;
   DBUG_ASSERT(nr >= 0.0);
   return sqrt(nr);
 }
diff --git a/sql/mysqld.cc b/sql/mysqld.cc
index 3450447..be9e21d 100644
--- a/sql/mysqld.cc
+++ b/sql/mysqld.cc
@@ -2316,26 +2316,17 @@ static void network_init(void)
     saPipeSecurity.lpSecurityDescriptor = &sdPipeDescriptor;
     saPipeSecurity.bInheritHandle = FALSE;
     if ((hPipe= CreateNamedPipe(pipe_name,
-				PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
-				PIPE_TYPE_BYTE |
-				PIPE_READMODE_BYTE |
-				PIPE_WAIT,
-				PIPE_UNLIMITED_INSTANCES,
-				(int) global_system_variables.net_buffer_length,
-				(int) global_system_variables.net_buffer_length,
-				NMPWAIT_USE_DEFAULT_WAIT,
-				&saPipeSecurity)) == INVALID_HANDLE_VALUE)
-      {
-	LPVOID lpMsgBuf;
-	int error=GetLastError();
-	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
-		      FORMAT_MESSAGE_FROM_SYSTEM,
-		      NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-		      (LPTSTR) &lpMsgBuf, 0, NULL );
-	sql_perror((char *)lpMsgBuf);
-	LocalFree(lpMsgBuf);
-	unireg_abort(1);
-      }
+        PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
+        PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
+        PIPE_UNLIMITED_INSTANCES,
+        (int) global_system_variables.net_buffer_length,
+        (int) global_system_variables.net_buffer_length,
+        NMPWAIT_USE_DEFAULT_WAIT,
+        &saPipeSecurity)) == INVALID_HANDLE_VALUE)
+    {
+      sql_perror("Create named pipe failed");
+      unireg_abort(1);
+    }
   }
 #endif
 
@@ -3464,6 +3455,7 @@ static int init_common_variables()
 
   max_system_variables.pseudo_thread_id= (ulong)~0;
   server_start_time= flush_status_time= my_time(0);
+  my_disable_copystat_in_redel= 1;
 
   rpl_filter= new Rpl_filter;
   binlog_filter= new Rpl_filter;
diff --git a/sql/net_serv.cc b/sql/net_serv.cc
index 4b78492..a280fcf 100644
--- a/sql/net_serv.cc
+++ b/sql/net_serv.cc
@@ -1,5 +1,5 @@
-/* Copyright (c) 2000, 2013, Oracle and/or its affiliates.
-   Copyright (c) 2012, Monty Program Ab
+/* Copyright (c) 2000, 2016, Oracle and/or its affiliates.
+   Copyright (c) 2012, 2016, MariaDB
 
    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
@@ -885,7 +885,7 @@ my_real_read(NET *net, size_t *complen)
 		    my_progname,vio_errno(net->vio));
 	  }
 #ifndef MYSQL_SERVER
-	  if (vio_errno(net->vio) == SOCKET_EINTR)
+	  if ((long)length < 0 && vio_errno(net->vio) == SOCKET_EINTR)
 	  {
 	    DBUG_PRINT("warning",("Interrupted read. Retrying..."));
 	    continue;
diff --git a/sql/opt_range.cc b/sql/opt_range.cc
index f4ac47f..a40363f 100644
--- a/sql/opt_range.cc
+++ b/sql/opt_range.cc
@@ -10409,8 +10409,10 @@ get_quick_keys(PARAM *param,QUICK_RANGE_SELECT *quick,KEY_PART *key,
       KEY *table_key=quick->head->key_info+quick->index;
       flag=EQ_RANGE;
       if ((table_key->flags & HA_NOSAME) &&
+          min_part == key_tree->part &&
           key_tree->part == table_key->key_parts-1)
       {
+        DBUG_ASSERT(min_part == max_part);
         if ((table_key->flags & HA_NULL_PART_KEY) &&
             null_part_in_key(key,
                              param->min_key,
diff --git a/sql/sql_admin.cc b/sql/sql_admin.cc
index 12a59fa..55effcd 100644
--- a/sql/sql_admin.cc
+++ b/sql/sql_admin.cc
@@ -441,7 +441,19 @@ static bool mysql_admin_table(THD* thd, TABLE_LIST* tables,
       }
       thd->prepare_derived_at_open= FALSE;
 
-      table->next_global= save_next_global;
+      /*
+        MERGE engine may adjust table->next_global chain, thus we have to
+        append save_next_global after merge children.
+      */
+      if (save_next_global)
+      {
+        TABLE_LIST *table_list_iterator= table;
+        while (table_list_iterator->next_global)
+          table_list_iterator= table_list_iterator->next_global;
+        table_list_iterator->next_global= save_next_global;
+        save_next_global->prev_global= &table_list_iterator->next_global;
+      }
+
       table->next_local= save_next_local;
       thd->open_options&= ~extra_open_options;
 
diff --git a/sql/sql_base.cc b/sql/sql_base.cc
index cb302de..d281758 100644
--- a/sql/sql_base.cc
+++ b/sql/sql_base.cc
@@ -1,4 +1,4 @@
-/* Copyright (c) 2000, 2015, Oracle and/or its affiliates.
+/* Copyright (c) 2000, 2016, Oracle and/or its affiliates.
    Copyright (c) 2010, 2016, MariaDB
 
    This program is free software; you can redistribute it and/or modify
@@ -5371,6 +5371,15 @@ handle_view(THD *thd, Query_tables_list *prelocking_ctx,
                                  &table_list->view->sroutines_list,
                                  table_list->top_table());
   }
+
+  /*
+    If a trigger was defined on one of the associated tables then assign the
+    'trg_event_map' value of the view to the next table in table_list. When a
+    Stored function is invoked, all the associated tables including the tables
+    associated with the trigger are prelocked.
+  */
+  if (table_list->trg_event_map && table_list->next_global)
+    table_list->next_global->trg_event_map= table_list->trg_event_map;
   return FALSE;
 }
 
diff --git a/sql/sql_class.cc b/sql/sql_class.cc
index 05a8ee8..62339b2 100644
--- a/sql/sql_class.cc
+++ b/sql/sql_class.cc
@@ -4736,9 +4736,11 @@ int THD::decide_logging_format(TABLE_LIST *tables)
     {
       static const char *prelocked_mode_name[] = {
         "NON_PRELOCKED",
+        "LOCK_TABLES",
         "PRELOCKED",
         "PRELOCKED_UNDER_LOCK_TABLES",
       };
+      compile_time_assert(array_elements(prelocked_mode_name) == LTM_always_last);
       DBUG_PRINT("debug", ("prelocked_mode: %s",
                            prelocked_mode_name[locked_tables_mode]));
     }
diff --git a/sql/sql_class.h b/sql/sql_class.h
index d24dad7..27bc40e 100644
--- a/sql/sql_class.h
+++ b/sql/sql_class.h
@@ -1075,7 +1075,8 @@ enum enum_locked_tables_mode
   LTM_NONE= 0,
   LTM_LOCK_TABLES,
   LTM_PRELOCKED,
-  LTM_PRELOCKED_UNDER_LOCK_TABLES
+  LTM_PRELOCKED_UNDER_LOCK_TABLES,
+  LTM_always_last
 };
 
 
@@ -3607,6 +3608,11 @@ public:
       save_copy_field_end= copy_field_end= NULL;
     }
   }
+  void free_copy_field_data()
+  {
+    for (Copy_field *ptr= copy_field ; ptr != copy_field_end ; ptr++)
+      ptr->tmp.free();
+  }
 };
 
 class select_union :public select_result_interceptor
diff --git a/sql/sql_insert.cc b/sql/sql_insert.cc
index c60ef6f..70a12fa 100644
--- a/sql/sql_insert.cc
+++ b/sql/sql_insert.cc
@@ -3238,6 +3238,7 @@ bool Delayed_insert::handle_inserts(void)
   max_rows= 0;                                  // For DBUG output
 #endif
   /* Remove all not used rows */
+  mysql_mutex_lock(&mutex);
   while ((row=rows.get()))
   {
     if (table->s->blob_fields)
@@ -3254,7 +3255,6 @@ bool Delayed_insert::handle_inserts(void)
   }
   DBUG_PRINT("error", ("dropped %lu rows after an error", max_rows));
   thread_safe_increment(delayed_insert_errors, &LOCK_delayed_status);
-  mysql_mutex_lock(&mutex);
   DBUG_RETURN(1);
 }
 #endif /* EMBEDDED_LIBRARY */
diff --git a/sql/sql_load.cc b/sql/sql_load.cc
index fba6dcf..9f300f8 100644
--- a/sql/sql_load.cc
+++ b/sql/sql_load.cc
@@ -1389,8 +1389,8 @@ READ_INFO::READ_INFO(File file_par, uint tot_length, CHARSET_INFO *cs,
   set_if_bigger(length,line_start.length());
   stack=stack_pos=(int*) sql_alloc(sizeof(int)*length);
 
-  if (!(buffer=(uchar*) my_malloc(buff_length+1,MYF(0))))
-    error=1; /* purecov: inspected */
+  if (!(buffer=(uchar*) my_malloc(buff_length+1,MYF(MY_WME))))
+    error= true; /* purecov: inspected */
   else
   {
     end_of_buff=buffer+buff_length;
@@ -1581,37 +1581,50 @@ int READ_INFO::read_field()
 	}
       }
 #ifdef USE_MB
-      if (my_mbcharlen(read_charset, chr) > 1 &&
-          to + my_mbcharlen(read_charset, chr) <= end_of_buff)
-      {
-        uchar* p= to;
-        int ml, i;
-        *to++ = chr;
-
-        ml= my_mbcharlen(read_charset, chr);
+        uint ml= my_mbcharlen(read_charset, chr);
+        if (ml == 0)
+        {
+          *to= '\0';
+          my_error(ER_INVALID_CHARACTER_STRING, MYF(0),
+                   read_charset->csname, buffer);
+          error= true;
+          return 1;
+        }
 
-        for (i= 1; i < ml; i++) 
+        if (ml > 1 &&
+            to + ml <= end_of_buff)
         {
-          chr= GET;
-          if (chr == my_b_EOF)
+          uchar* p= to;
+          *to++ = chr;
+
+          for (uint i= 1; i < ml; i++)
           {
-            /*
-             Need to back up the bytes already ready from illformed
-             multi-byte char 
-            */
-            to-= i;
-            goto found_eof;
+            chr= GET;
+            if (chr == my_b_EOF)
+            {
+              /*
+                Need to back up the bytes already ready from illformed
+                multi-byte char 
+              */
+              to-= i;
+              goto found_eof;
+            }
+            *to++ = chr;
           }
-          *to++ = chr;
-        }
-        if (my_ismbchar(read_charset,
+          if (my_ismbchar(read_charset,
                         (const char *)p,
                         (const char *)to))
-          continue;
-        for (i= 0; i < ml; i++)
-          PUSH(*--to);
-        chr= GET;
-      }
+            continue;
+          for (uint i= 0; i < ml; i++)
+            PUSH(*--to);
+          chr= GET;
+        }
+        else if (ml > 1)
+        {
+          // Buffer is too small, exit while loop, and reallocate.
+          PUSH(chr);
+          break;
+        }
 #endif
       *to++ = (uchar) chr;
     }
@@ -1855,7 +1868,15 @@ int READ_INFO::read_value(int delim, String *val)
   for (chr= GET; my_tospace(chr) != delim && chr != my_b_EOF;)
   {
 #ifdef USE_MB
-    if (my_mbcharlen(read_charset, chr) > 1)
+    uint ml= my_mbcharlen(read_charset, chr);
+    if (ml == 0)
+    {
+      chr= my_b_EOF;
+      val->length(0);
+      return chr;
+    }
+
+    if (ml > 1)
     {
       DBUG_PRINT("read_xml",("multi byte"));
       int i, ml= my_mbcharlen(read_charset, chr);
diff --git a/sql/sql_plugin.cc b/sql/sql_plugin.cc
index dbbc262..c8c8c8b 100644
--- a/sql/sql_plugin.cc
+++ b/sql/sql_plugin.cc
@@ -2896,68 +2896,8 @@ static uchar *intern_sys_var_ptr(THD* thd, int offset, bool global_lock)
   if (!thd->variables.dynamic_variables_ptr ||
       (uint)offset > thd->variables.dynamic_variables_head)
   {
-    uint idx;
-
     mysql_rwlock_rdlock(&LOCK_system_variables_hash);
-
-    thd->variables.dynamic_variables_ptr= (char*)
-      my_realloc(thd->variables.dynamic_variables_ptr,
-                 global_variables_dynamic_size,
-                 MYF(MY_WME | MY_FAE | MY_ALLOW_ZERO_PTR));
-
-    if (global_lock)
-      mysql_mutex_lock(&LOCK_global_system_variables);
-
-    mysql_mutex_assert_owner(&LOCK_global_system_variables);
-
-    memcpy(thd->variables.dynamic_variables_ptr +
-             thd->variables.dynamic_variables_size,
-           global_system_variables.dynamic_variables_ptr +
-             thd->variables.dynamic_variables_size,
-           global_system_variables.dynamic_variables_size -
-             thd->variables.dynamic_variables_size);
-
-    /*
-      now we need to iterate through any newly copied 'defaults'
-      and if it is a string type with MEMALLOC flag, we need to strdup
-    */
-    for (idx= 0; idx < bookmark_hash.records; idx++)
-    {
-      sys_var_pluginvar *pi;
-      sys_var *var;
-      st_bookmark *v= (st_bookmark*) my_hash_element(&bookmark_hash,idx);
-
-      if (v->version <= thd->variables.dynamic_variables_version)
-        continue; /* already in thd->variables */
-
-      if (!(var= intern_find_sys_var(v->key + 1, v->name_len)) ||
-          !(pi= var->cast_pluginvar()) ||
-          v->key[0] != plugin_var_bookmark_key(pi->plugin_var->flags))
-        continue;
-
-      /* Here we do anything special that may be required of the data types */
-
-      if ((pi->plugin_var->flags & PLUGIN_VAR_TYPEMASK) == PLUGIN_VAR_STR &&
-          pi->plugin_var->flags & PLUGIN_VAR_MEMALLOC)
-      {
-         char **pp= (char**) (thd->variables.dynamic_variables_ptr +
-                             *(int*)(pi->plugin_var + 1));
-         if ((*pp= *(char**) (global_system_variables.dynamic_variables_ptr +
-                             *(int*)(pi->plugin_var + 1))))
-           *pp= my_strdup(*pp, MYF(MY_WME|MY_FAE));
-      }
-    }
-
-    if (global_lock)
-      mysql_mutex_unlock(&LOCK_global_system_variables);
-
-    thd->variables.dynamic_variables_version=
-           global_system_variables.dynamic_variables_version;
-    thd->variables.dynamic_variables_head=
-           global_system_variables.dynamic_variables_head;
-    thd->variables.dynamic_variables_size=
-           global_system_variables.dynamic_variables_size;
-
+    sync_dynamic_session_variables(thd, global_lock);
     mysql_rwlock_unlock(&LOCK_system_variables_hash);
   }
   DBUG_RETURN((uchar*)thd->variables.dynamic_variables_ptr + offset);
@@ -3037,6 +2977,70 @@ void plugin_thdvar_init(THD *thd)
 }
 
 
+
+void sync_dynamic_session_variables(THD* thd, bool global_lock)
+{
+  uint idx;
+
+  thd->variables.dynamic_variables_ptr= (char*)
+    my_realloc(thd->variables.dynamic_variables_ptr,
+               global_variables_dynamic_size,
+               MYF(MY_WME | MY_FAE | MY_ALLOW_ZERO_PTR));
+
+  if (global_lock)
+    mysql_mutex_lock(&LOCK_global_system_variables);
+
+  mysql_mutex_assert_owner(&LOCK_global_system_variables);
+
+  memcpy(thd->variables.dynamic_variables_ptr +
+           thd->variables.dynamic_variables_size,
+         global_system_variables.dynamic_variables_ptr +
+           thd->variables.dynamic_variables_size,
+         global_system_variables.dynamic_variables_size -
+           thd->variables.dynamic_variables_size);
+
+  /*
+    now we need to iterate through any newly copied 'defaults'
+    and if it is a string type with MEMALLOC flag, we need to strdup
+  */
+  for (idx= 0; idx < bookmark_hash.records; idx++)
+  {
+    sys_var_pluginvar *pi;
+    sys_var *var;
+    st_bookmark *v= (st_bookmark*) my_hash_element(&bookmark_hash,idx);
+
+    if (v->version <= thd->variables.dynamic_variables_version)
+      continue; /* already in thd->variables */
+
+    if (!(var= intern_find_sys_var(v->key + 1, v->name_len)) ||
+        !(pi= var->cast_pluginvar()) ||
+        v->key[0] != plugin_var_bookmark_key(pi->plugin_var->flags))
+      continue;
+
+    /* Here we do anything special that may be required of the data types */
+
+    if ((pi->plugin_var->flags & PLUGIN_VAR_TYPEMASK) == PLUGIN_VAR_STR &&
+        pi->plugin_var->flags & PLUGIN_VAR_MEMALLOC)
+    {
+      int offset= ((thdvar_str_t *)(pi->plugin_var))->offset;
+      char **pp= (char**) (thd->variables.dynamic_variables_ptr + offset);
+      if (*pp)
+        *pp= my_strdup(*pp, MYF(MY_WME|MY_FAE));
+    }
+  }
+
+  if (global_lock)
+    mysql_mutex_unlock(&LOCK_global_system_variables);
+
+  thd->variables.dynamic_variables_version=
+         global_system_variables.dynamic_variables_version;
+  thd->variables.dynamic_variables_head=
+         global_system_variables.dynamic_variables_head;
+  thd->variables.dynamic_variables_size=
+         global_system_variables.dynamic_variables_size;
+}
+
+
 /*
   Unlocks all system variables which hold a reference
 */
diff --git a/sql/sql_plugin.h b/sql/sql_plugin.h
index be1cfcd..fcc73c8 100644
--- a/sql/sql_plugin.h
+++ b/sql/sql_plugin.h
@@ -174,4 +174,6 @@ typedef my_bool (plugin_foreach_func)(THD *thd,
 #define plugin_foreach(A,B,C,D) plugin_foreach_with_mask(A,B,C,PLUGIN_IS_READY,D)
 extern bool plugin_foreach_with_mask(THD *thd, plugin_foreach_func *func,
                                      int type, uint state_mask, void *arg);
+
+extern void sync_dynamic_session_variables(THD* thd, bool global_lock);
 #endif
diff --git a/sql/sql_select.cc b/sql/sql_select.cc
index 613cbb2..8c99496 100644
--- a/sql/sql_select.cc
+++ b/sql/sql_select.cc
@@ -8275,9 +8275,26 @@ JOIN::make_simple_join(JOIN *parent, TABLE *temp_table)
     We need to destruct the copy_field (allocated in create_tmp_table())
     before setting it to 0 if the join is not "reusable".
   */
-  if (!tmp_join || tmp_join != this) 
-    tmp_table_param.cleanup(); 
-  tmp_table_param.copy_field= tmp_table_param.copy_field_end=0;
+  if (!tmp_join || tmp_join != this)
+    tmp_table_param.cleanup();
+  else
+  {
+    /*
+      Free data buffered in copy_fields, but keep data pointed by copy_field
+      around for next iteration (possibly stored in save_copy_fields).
+
+      It would be logically simpler to not clear copy_field
+      below, but as we have loops that runs over copy_field to
+      copy_field_end that should not be done anymore, it's simpler to
+      just clear the pointers.
+
+      Another option would be to just clear copy_field_end and not run
+      the loops if this is not set or to have tmp_table_param.cleanup()
+      to run cleanup on save_copy_field if copy_field is not set.
+    */
+    tmp_table_param.free_copy_field_data();
+    tmp_table_param.copy_field= tmp_table_param.copy_field_end=0;
+  }
   first_record= sort_and_group=0;
   send_records= (ha_rows) 0;
 
@@ -10866,7 +10883,7 @@ void JOIN::join_free()
 /**
   Free resources of given join.
 
-  @param fill   true if we should free all resources, call with full==1
+  @param full   true if we should free all resources, call with full==1
                 should be last, before it this function can be called with
                 full==0
 
@@ -10982,7 +10999,7 @@ void JOIN::cleanup(bool full)
     /*
       If we have tmp_join and 'this' JOIN is not tmp_join and
       tmp_table_param.copy_field's  of them are equal then we have to remove
-      pointer to  tmp_table_param.copy_field from tmp_join, because it qill
+      pointer to  tmp_table_param.copy_field from tmp_join, because it will
       be removed in tmp_table_param.cleanup().
     */
     if (tmp_join &&
@@ -14816,6 +14833,7 @@ Field *create_tmp_field(THD *thd, TABLE *table,Item *item, Item::Type type,
   case Item::VARBIN_ITEM:
   case Item::CACHE_ITEM:
   case Item::EXPR_CACHE_ITEM:
+  case Item::PARAM_ITEM:
     if (make_copy_field)
     {
       DBUG_ASSERT(((Item_result_field*)item)->result_field);
@@ -21397,7 +21415,7 @@ setup_copy_fields(THD *thd, TMP_TABLE_PARAM *param,
  err:
   if (copy)
     delete [] param->copy_field;			// This is never 0
-  param->copy_field=0;
+  param->copy_field= 0;
 err2:
   DBUG_RETURN(TRUE);
 }
diff --git a/sql/sql_show.cc b/sql/sql_show.cc
index 98cade4..d8ea232 100644
--- a/sql/sql_show.cc
+++ b/sql/sql_show.cc
@@ -6937,19 +6937,30 @@ int fill_variables(THD *thd, TABLE_LIST *tables, COND *cond)
   const char *wild= lex->wild ? lex->wild->ptr() : NullS;
   enum enum_schema_tables schema_table_idx=
     get_schema_table_idx(tables->schema_table);
-  enum enum_var_type option_type= OPT_SESSION;
+  enum enum_var_type scope= OPT_SESSION;
   bool upper_case_names= (schema_table_idx != SCH_VARIABLES);
   bool sorted_vars= (schema_table_idx == SCH_VARIABLES);
 
   if ((sorted_vars && lex->option_type == OPT_GLOBAL) ||
       schema_table_idx == SCH_GLOBAL_VARIABLES)
-    option_type= OPT_GLOBAL;
+    scope= OPT_GLOBAL;
 
   COND *partial_cond= make_cond_for_info_schema(cond, tables);
 
   mysql_rwlock_rdlock(&LOCK_system_variables_hash);
-  res= show_status_array(thd, wild, enumerate_sys_vars(thd, sorted_vars, option_type),
-                         option_type, NULL, "", tables->table,
+
+  /*
+    Avoid recursive LOCK_system_variables_hash acquisition in
+    intern_sys_var_ptr() by pre-syncing dynamic session variables.
+  */
+  if (scope == OPT_SESSION &&
+      (!thd->variables.dynamic_variables_ptr ||
+       global_system_variables.dynamic_variables_head >
+       thd->variables.dynamic_variables_head))
+    sync_dynamic_session_variables(thd, true);
+
+  res= show_status_array(thd, wild, enumerate_sys_vars(thd, sorted_vars, scope),
+                         scope, NULL, "", tables->table,
                          upper_case_names, partial_cond);
   mysql_rwlock_unlock(&LOCK_system_variables_hash);
   DBUG_RETURN(res);
diff --git a/sql/sql_union.cc b/sql/sql_union.cc
index 87d3e86..95ce1c9 100644
--- a/sql/sql_union.cc
+++ b/sql/sql_union.cc
@@ -887,6 +887,12 @@ bool st_select_lex_unit::cleanup()
       join->tables_list= 0;
       join->table_count= 0;
       join->top_join_tab_count= 0;
+      if (join->tmp_join && join->tmp_join != join)
+      {
+        join->tmp_join->tables_list= 0;
+        join->tmp_join->table_count= 0;
+        join->tmp_join->top_join_tab_count= 0;
+      }
     }
     error|= fake_select_lex->cleanup();
     /*
diff --git a/sql/sys_vars.cc b/sql/sys_vars.cc
index 63d3b38..7b89890 100644
--- a/sql/sys_vars.cc
+++ b/sql/sys_vars.cc
@@ -3025,18 +3025,31 @@ static bool check_log_path(sys_var *self, THD *thd, set_var *var)
   if (!var->save_result.string_value.str)
     return true;
 
-  if (var->save_result.string_value.length > FN_REFLEN)
+  LEX_STRING *val= &var->save_result.string_value;
+
+  if (val->length > FN_REFLEN)
   { // path is too long
     my_error(ER_PATH_LENGTH, MYF(0), self->name.str);
     return true;
   }
 
   char path[FN_REFLEN];
-  size_t path_length= unpack_filename(path, var->save_result.string_value.str);
+  size_t path_length= unpack_filename(path, val->str);
 
   if (!path_length)
     return true;
 
+  static const LEX_CSTRING my_cnf= { STRING_WITH_LEN("my.cnf") };
+  static const LEX_CSTRING my_ini= { STRING_WITH_LEN("my.ini") };
+  if (path_length >= my_cnf.length)
+  {
+    if (strcasecmp(path + path_length - my_cnf.length, my_cnf.str) == 0)
+      return true; // log file name ends with "my.cnf"
+    DBUG_ASSERT(my_cnf.length == my_ini.length);
+    if (strcasecmp(path + path_length - my_ini.length, my_ini.str) == 0)
+      return true; // log file name ends with "my.ini"
+  }
+
   MY_STAT f_stat;
 
   if (my_stat(path, &f_stat, MYF(0)))
@@ -3046,9 +3059,9 @@ static bool check_log_path(sys_var *self, THD *thd, set_var *var)
     return false;
   }
 
-  (void) dirname_part(path, var->save_result.string_value.str, &path_length);
+  (void) dirname_part(path, val->str, &path_length);
 
-  if (var->save_result.string_value.length - path_length >= FN_LEN)
+  if (val->length - path_length >= FN_LEN)
   { // filename is too long
       my_error(ER_PATH_LENGTH, MYF(0), self->name.str);
       return true;
diff --git a/storage/innobase/dict/dict0crea.c b/storage/innobase/dict/dict0crea.c
index 8102f57..f8bcc6f 100644
--- a/storage/innobase/dict/dict0crea.c
+++ b/storage/innobase/dict/dict0crea.c
@@ -1242,14 +1242,14 @@ dict_create_or_check_foreign_constraint_tables(void)
 		fprintf(stderr,
 			"InnoDB: dropping incompletely created"
 			" SYS_FOREIGN table\n");
-		row_drop_table_for_mysql("SYS_FOREIGN", trx, TRUE);
+		row_drop_table_for_mysql("SYS_FOREIGN", trx, TRUE, TRUE);
 	}
 
 	if (table2) {
 		fprintf(stderr,
 			"InnoDB: dropping incompletely created"
 			" SYS_FOREIGN_COLS table\n");
-		row_drop_table_for_mysql("SYS_FOREIGN_COLS", trx, TRUE);
+		row_drop_table_for_mysql("SYS_FOREIGN_COLS", trx, TRUE, TRUE);
 	}
 
 	fprintf(stderr,
@@ -1298,8 +1298,8 @@ dict_create_or_check_foreign_constraint_tables(void)
 			"InnoDB: dropping incompletely created"
 			" SYS_FOREIGN tables\n");
 
-		row_drop_table_for_mysql("SYS_FOREIGN", trx, TRUE);
-		row_drop_table_for_mysql("SYS_FOREIGN_COLS", trx, TRUE);
+		row_drop_table_for_mysql("SYS_FOREIGN", trx, TRUE, TRUE);
+		row_drop_table_for_mysql("SYS_FOREIGN_COLS", trx, TRUE, TRUE);
 
 		error = DB_MUST_GET_MORE_FILE_SPACE;
 	}
diff --git a/storage/innobase/handler/ha_innodb.cc b/storage/innobase/handler/ha_innodb.cc
index 734dbe1..780f3a6 100644
--- a/storage/innobase/handler/ha_innodb.cc
+++ b/storage/innobase/handler/ha_innodb.cc
@@ -7644,7 +7644,8 @@ ha_innobase::delete_table(
 
 	error = row_drop_table_for_mysql(norm_name, trx,
 					 thd_sql_command(thd)
-					 == SQLCOM_DROP_DB);
+					 == SQLCOM_DROP_DB,
+					 FALSE);
 
 	/* Flush the log to reduce probability that the .frm files and
 	the InnoDB data dictionary get out-of-sync if the user runs
diff --git a/storage/innobase/include/os0sync.h b/storage/innobase/include/os0sync.h
index 213974b..af58a23 100644
--- a/storage/innobase/include/os0sync.h
+++ b/storage/innobase/include/os0sync.h
@@ -348,20 +348,13 @@ os_atomic_test_and_set(volatile lock_word_t* ptr)
 }
 
 /** Do an atomic release.
-
-In theory __sync_lock_release should be used to release the lock.
-Unfortunately, it does not work properly alone. The workaround is
-that more conservative __sync_lock_test_and_set is used instead.
-
-Performance regression was observed at some conditions for Intel
-architecture. Disable release barrier on Intel architecture for now.
 @param[in,out]	ptr		Memory location to write to
 @return the previous value */
 static inline
-lock_word_t
+void
 os_atomic_clear(volatile lock_word_t* ptr)
 {
-	return(__sync_lock_test_and_set(ptr, 0));
+	__sync_lock_release(ptr);
 }
 
 # elif defined(HAVE_IB_GCC_ATOMIC_TEST_AND_SET)
diff --git a/storage/innobase/include/row0mysql.h b/storage/innobase/include/row0mysql.h
index 7abb0b6..0f66644 100644
--- a/storage/innobase/include/row0mysql.h
+++ b/storage/innobase/include/row0mysql.h
@@ -454,7 +454,10 @@ row_drop_table_for_mysql(
 /*=====================*/
 	const char*	name,	/*!< in: table name */
 	trx_t*		trx,	/*!< in: transaction handle */
-	ibool		drop_db);/*!< in: TRUE=dropping whole database */
+	ibool		drop_db,/*!< in: TRUE=dropping whole database */
+	ibool		create_failed);/*!<in: TRUE=create table failed
+				       because e.g. foreign key column
+				       type mismatch. */
 /*********************************************************************//**
 Drop all temporary tables during crash recovery. */
 UNIV_INTERN
diff --git a/storage/innobase/include/sync0sync.ic b/storage/innobase/include/sync0sync.ic
index 1120da8..d0f2663 100644
--- a/storage/innobase/include/sync0sync.ic
+++ b/storage/innobase/include/sync0sync.ic
@@ -178,6 +178,11 @@ mutex_exit_func(
 	to wake up possible hanging threads if
 	they are missed in mutex_signal_object. */
 
+	/* We add a memory barrier to prevent reading of the
+	number of waiters before releasing the lock. */
+
+	os_mb;
+
 	if (mutex_get_waiters(mutex) != 0) {
 
 		mutex_signal_object(mutex);
diff --git a/storage/innobase/page/page0cur.c b/storage/innobase/page/page0cur.c
index a722f5b..4b6a155 100644
--- a/storage/innobase/page/page0cur.c
+++ b/storage/innobase/page/page0cur.c
@@ -1048,6 +1048,26 @@ use_heap:
 	insert_rec = rec_copy(insert_buf, rec, offsets);
 	rec_offs_make_valid(insert_rec, index, offsets);
 
+	/* This is because assertion below is debug assertion */
+#ifdef UNIV_DEBUG
+	if (UNIV_UNLIKELY(current_rec == insert_rec)) {
+		ulint extra_len, data_len;
+		extra_len = rec_offs_extra_size(offsets);
+		data_len = rec_offs_data_size(offsets);
+
+		fprintf(stderr, "InnoDB: Error: current_rec == insert_rec "
+			" extra_len %lu data_len %lu insert_buf %p rec %p\n",
+			extra_len, data_len, insert_buf, rec);
+		fprintf(stderr, "InnoDB; Physical record: \n");
+		rec_print(stderr, rec, index);
+		fprintf(stderr, "InnoDB: Inserted record: \n");
+		rec_print(stderr, insert_rec, index);
+		fprintf(stderr, "InnoDB: Current record: \n");
+		rec_print(stderr, current_rec, index);
+		ut_a(current_rec != insert_rec);
+	}
+#endif /* UNIV_DEBUG */
+
 	/* 4. Insert the record in the linked list of records */
 	ut_ad(current_rec != insert_rec);
 
diff --git a/storage/innobase/row/row0merge.c b/storage/innobase/row/row0merge.c
index f7d546c..7d87d1f 100644
--- a/storage/innobase/row/row0merge.c
+++ b/storage/innobase/row/row0merge.c
@@ -2685,7 +2685,7 @@ row_merge_drop_table(
 	/* There must be no open transactions on the table. */
 	ut_a(table->n_mysql_handles_opened == 0);
 
-	return(row_drop_table_for_mysql(table->name, trx, FALSE));
+	return(row_drop_table_for_mysql(table->name, trx, FALSE, FALSE));
 }
 
 /*********************************************************************//**
diff --git a/storage/innobase/row/row0mysql.c b/storage/innobase/row/row0mysql.c
index 1a11e39..6206bef 100644
--- a/storage/innobase/row/row0mysql.c
+++ b/storage/innobase/row/row0mysql.c
@@ -1987,7 +1987,7 @@ err_exit:
 
 		if (dict_table_get_low(table->name, DICT_ERR_IGNORE_NONE)) {
 
-			row_drop_table_for_mysql(table->name, trx, FALSE);
+			row_drop_table_for_mysql(table->name, trx, FALSE, TRUE);
 			trx_commit_for_mysql(trx);
 		} else {
 			dict_mem_table_free(table);
@@ -2117,7 +2117,7 @@ error_handling:
 
 		trx_general_rollback_for_mysql(trx, NULL);
 
-		row_drop_table_for_mysql(table_name, trx, FALSE);
+		row_drop_table_for_mysql(table_name, trx, FALSE, TRUE);
 
 		trx_commit_for_mysql(trx);
 
@@ -2187,7 +2187,7 @@ row_table_add_foreign_constraints(
 
 		trx_general_rollback_for_mysql(trx, NULL);
 
-		row_drop_table_for_mysql(name, trx, FALSE);
+		row_drop_table_for_mysql(name, trx, FALSE, TRUE);
 
 		trx_commit_for_mysql(trx);
 
@@ -2228,7 +2228,7 @@ row_drop_table_for_mysql_in_background(
 
 	/* Try to drop the table in InnoDB */
 
-	error = row_drop_table_for_mysql(name, trx, FALSE);
+	error = row_drop_table_for_mysql(name, trx, FALSE, FALSE);
 
 	/* Flush the log to reduce probability that the .frm files and
 	the InnoDB data dictionary get out-of-sync if the user runs
@@ -3078,7 +3078,10 @@ row_drop_table_for_mysql(
 /*=====================*/
 	const char*	name,	/*!< in: table name */
 	trx_t*		trx,	/*!< in: transaction handle */
-	ibool		drop_db)/*!< in: TRUE=dropping whole database */
+	ibool		drop_db,/*!< in: TRUE=dropping whole database */
+	ibool		create_failed) /*!<in: TRUE=create table failed
+				       because e.g. foreign key column
+				       type mismatch. */
 {
 	dict_foreign_t*	foreign;
 	dict_table_t*	table;
@@ -3193,7 +3196,11 @@ check_next_foreign:
 		foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
 	}
 
-	if (foreign && trx->check_foreigns
+	/* We should allow dropping a referenced table if creating
+	that referenced table has failed for some reason. For example
+	if referenced table is created but it column types that are
+	referenced do not match. */
+	if (foreign && trx->check_foreigns && !create_failed
 	    && !(drop_db && dict_tables_have_same_db(
 			 name, foreign->foreign_table_name_lookup))) {
 		FILE*	ef	= dict_foreign_err_file;
@@ -3578,7 +3585,7 @@ row_mysql_drop_temp_tables(void)
 		table = dict_load_table(table_name, TRUE, DICT_ERR_IGNORE_NONE);
 
 		if (table) {
-			row_drop_table_for_mysql(table_name, trx, FALSE);
+			row_drop_table_for_mysql(table_name, trx, FALSE, FALSE);
 			trx_commit_for_mysql(trx);
 		}
 
@@ -3708,7 +3715,7 @@ loop:
 			goto loop;
 		}
 
-		err = row_drop_table_for_mysql(table_name, trx, TRUE);
+		err = row_drop_table_for_mysql(table_name, trx, TRUE, FALSE);
 		trx_commit_for_mysql(trx);
 
 		if (err != DB_SUCCESS) {
diff --git a/storage/innobase/trx/trx0roll.c b/storage/innobase/trx/trx0roll.c
index ffd7bb3..877a478 100644
--- a/storage/innobase/trx/trx0roll.c
+++ b/storage/innobase/trx/trx0roll.c
@@ -504,7 +504,7 @@ trx_rollback_active(
 			ut_print_name(stderr, trx, TRUE, table->name);
 			fputs(" in recovery\n", stderr);
 
-			err = row_drop_table_for_mysql(table->name, trx, TRUE);
+			err = row_drop_table_for_mysql(table->name, trx, TRUE, FALSE);
 			trx_commit_for_mysql(trx);
 
 			ut_a(err == (int) DB_SUCCESS);
diff --git a/storage/myisam/ha_myisam.cc b/storage/myisam/ha_myisam.cc
index a2e62d8..784da17 100644
--- a/storage/myisam/ha_myisam.cc
+++ b/storage/myisam/ha_myisam.cc
@@ -1433,6 +1433,7 @@ int ha_myisam::enable_indexes(uint mode)
   else if (mode == HA_KEY_SWITCH_NONUNIQ_SAVE)
   {
     THD *thd= table->in_use;
+    int was_error= thd->is_error();
     HA_CHECK &param= *(HA_CHECK*) thd->alloc(sizeof(param));
     const char *save_proc_info=thd->proc_info;
 
@@ -1475,7 +1476,7 @@ int ha_myisam::enable_indexes(uint mode)
         might have been set by the first repair. They can still be seen
         with SHOW WARNINGS then.
       */
-      if (! error)
+      if (! error && ! was_error)
         thd->clear_error();
     }
     info(HA_STATUS_CONST);
diff --git a/storage/tokudb/ft-index/ft/txn/txn.cc b/storage/tokudb/ft-index/ft/txn/txn.cc
index 9aa9337..34c7e0f 100644
--- a/storage/tokudb/ft-index/ft/txn/txn.cc
+++ b/storage/tokudb/ft-index/ft/txn/txn.cc
@@ -336,17 +336,26 @@ static txn_child_manager tcm;
         .xa_xid = {0, 0, 0, {}},
         .progress_poll_fun = NULL,
         .progress_poll_fun_extra = NULL,
-        .txn_lock = TOKU_MUTEX_INITIALIZER,
+        .txn_lock = {}, // Needs to be set to 0 after initialization.
+                        // See:
+                        // https://llvm.org/bugs/show_bug.cgi?id=21689
+                        // and MDEV-10229
         .open_fts = open_fts,
         .roll_info = roll_info,
-        .state_lock = TOKU_MUTEX_INITIALIZER,
-        .state_cond = TOKU_COND_INITIALIZER,
+        .state_lock = {}, // Needs to be set to 0.
+        .state_cond = {}, // Needs to be set to 0.
         .state = TOKUTXN_LIVE,
         .num_pin = 0,
         .client_id = 0,
         .start_time = time(NULL),
     };
 
+    // We initialize the locks afterwards, but to prevent undefined behaviour
+    // we zero-out the structures containing them.
+    ZERO_STRUCT(new_txn.txn_lock);
+    ZERO_STRUCT(new_txn.state_lock);
+    ZERO_STRUCT(new_txn.state_cond);
+
     TOKUTXN result = NULL;
     XMEMDUP(result, &new_txn);
     invalidate_xa_xid(&result->xa_xid);
diff --git a/storage/xtradb/dict/dict0crea.c b/storage/xtradb/dict/dict0crea.c
index a77acf8..b44fdc1 100644
--- a/storage/xtradb/dict/dict0crea.c
+++ b/storage/xtradb/dict/dict0crea.c
@@ -1444,14 +1444,14 @@ dict_create_or_check_foreign_constraint_tables(void)
 		fprintf(stderr,
 			"InnoDB: dropping incompletely created"
 			" SYS_FOREIGN table\n");
-		row_drop_table_for_mysql("SYS_FOREIGN", trx, TRUE);
+		row_drop_table_for_mysql("SYS_FOREIGN", trx, TRUE, TRUE);
 	}
 
 	if (table2) {
 		fprintf(stderr,
 			"InnoDB: dropping incompletely created"
 			" SYS_FOREIGN_COLS table\n");
-		row_drop_table_for_mysql("SYS_FOREIGN_COLS", trx, TRUE);
+		row_drop_table_for_mysql("SYS_FOREIGN_COLS", trx, TRUE, TRUE);
 	}
 
 	fprintf(stderr,
@@ -1500,8 +1500,8 @@ dict_create_or_check_foreign_constraint_tables(void)
 			"InnoDB: dropping incompletely created"
 			" SYS_FOREIGN tables\n");
 
-		row_drop_table_for_mysql("SYS_FOREIGN", trx, TRUE);
-		row_drop_table_for_mysql("SYS_FOREIGN_COLS", trx, TRUE);
+		row_drop_table_for_mysql("SYS_FOREIGN", trx, TRUE, TRUE);
+		row_drop_table_for_mysql("SYS_FOREIGN_COLS", trx, TRUE, TRUE);
 
 		error = DB_MUST_GET_MORE_FILE_SPACE;
 	}
diff --git a/storage/xtradb/handler/ha_innodb.cc b/storage/xtradb/handler/ha_innodb.cc
index 8148c3e..d5da382 100644
--- a/storage/xtradb/handler/ha_innodb.cc
+++ b/storage/xtradb/handler/ha_innodb.cc
@@ -8773,7 +8773,8 @@ ha_innobase::delete_table(
 
 	error = row_drop_table_for_mysql(norm_name, trx,
 					 thd_sql_command(thd)
-					 == SQLCOM_DROP_DB);
+					 == SQLCOM_DROP_DB,
+					 FALSE);
 
 	/* Flush the log to reduce probability that the .frm files and
 	the InnoDB data dictionary get out-of-sync if the user runs
@@ -8858,6 +8859,7 @@ innobase_drop_database(
 		trx_free_for_mysql(trx);
 		return; /* ignore */
 	}
+
 	row_drop_database_for_mysql(namebuf, trx);
 	my_free(namebuf);
 
diff --git a/storage/xtradb/include/log0online.h b/storage/xtradb/include/log0online.h
index a20eef5..02d7500 100644
--- a/storage/xtradb/include/log0online.h
+++ b/storage/xtradb/include/log0online.h
@@ -11,8 +11,8 @@ 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., 59 Temple
-Place, Suite 330, Boston, MA 02111-1307 USA
+this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
+Street, Fifth Floor, Boston, MA 02110-1301, USA
 
 *****************************************************************************/
 
diff --git a/storage/xtradb/include/os0sync.h b/storage/xtradb/include/os0sync.h
index b52c078..08da9df 100644
--- a/storage/xtradb/include/os0sync.h
+++ b/storage/xtradb/include/os0sync.h
@@ -381,20 +381,13 @@ os_atomic_test_and_set(volatile lock_word_t* ptr)
 }
 
 /** Do an atomic release.
-
-In theory __sync_lock_release should be used to release the lock.
-Unfortunately, it does not work properly alone. The workaround is
-that more conservative __sync_lock_test_and_set is used instead.
-
-Performance regression was observed at some conditions for Intel
-architecture. Disable release barrier on Intel architecture for now.
 @param[in,out]	ptr		Memory location to write to
 @return the previous value */
 static inline
-lock_word_t
+void
 os_atomic_clear(volatile lock_word_t* ptr)
 {
-	return(__sync_lock_test_and_set(ptr, 0));
+	__sync_lock_release(ptr);
 }
 
 # elif defined(HAVE_IB_GCC_ATOMIC_TEST_AND_SET)
diff --git a/storage/xtradb/include/row0mysql.h b/storage/xtradb/include/row0mysql.h
index 35378bf..e228289 100644
--- a/storage/xtradb/include/row0mysql.h
+++ b/storage/xtradb/include/row0mysql.h
@@ -470,7 +470,10 @@ row_drop_table_for_mysql(
 /*=====================*/
 	const char*	name,	/*!< in: table name */
 	trx_t*		trx,	/*!< in: transaction handle */
-	ibool		drop_db);/*!< in: TRUE=dropping whole database */
+	ibool		drop_db,/*!< in: TRUE=dropping whole database */
+	ibool		create_failed);/*!<in: TRUE=create table failed
+				       because e.g. foreign key column
+				       type mismatch. */
 /*********************************************************************//**
 Drop all temporary tables during crash recovery. */
 UNIV_INTERN
diff --git a/storage/xtradb/include/sync0sync.ic b/storage/xtradb/include/sync0sync.ic
index 48039c8..c733bec 100644
--- a/storage/xtradb/include/sync0sync.ic
+++ b/storage/xtradb/include/sync0sync.ic
@@ -178,6 +178,11 @@ mutex_exit_func(
 	to wake up possible hanging threads if
 	they are missed in mutex_signal_object. */
 
+	/* We add a memory barrier to prevent reading of the
+	number of waiters before releasing the lock. */
+
+	os_mb;
+
 	if (mutex_get_waiters(mutex) != 0) {
 
 		mutex_signal_object(mutex);
diff --git a/storage/xtradb/include/univ.i b/storage/xtradb/include/univ.i
index 2aaabf6..9d4b3e5 100644
--- a/storage/xtradb/include/univ.i
+++ b/storage/xtradb/include/univ.i
@@ -64,7 +64,7 @@ component, i.e. we show M.N.P as M.N */
 	(INNODB_VERSION_MAJOR << 8 | INNODB_VERSION_MINOR)
 
 #ifndef PERCONA_INNODB_VERSION
-#define PERCONA_INNODB_VERSION 37.9
+#define PERCONA_INNODB_VERSION 38.0
 #endif
 
 #define INNODB_VERSION_STR	"5.5.49-MariaDB-" IB_TO_STR(PERCONA_INNODB_VERSION)
diff --git a/storage/xtradb/log/log0online.c b/storage/xtradb/log/log0online.c
index a844419..d012748 100644
--- a/storage/xtradb/log/log0online.c
+++ b/storage/xtradb/log/log0online.c
@@ -11,8 +11,8 @@ 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., 59 Temple
-Place, Suite 330, Boston, MA 02111-1307 USA
+this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
+Street, Fifth Floor, Boston, MA 02110-1301, USA
 
 *****************************************************************************/
 
diff --git a/storage/xtradb/log/log0recv.c b/storage/xtradb/log/log0recv.c
index 479f50d..1e670d5 100644
--- a/storage/xtradb/log/log0recv.c
+++ b/storage/xtradb/log/log0recv.c
@@ -666,6 +666,7 @@ recv_check_cp_is_consistent(
 }
 
 #ifndef UNIV_HOTBACKUP
+
 /********************************************************//**
 Looks for the maximum consistent checkpoint from the log groups.
 @return	error code or DB_SUCCESS */
@@ -692,8 +693,37 @@ recv_find_max_checkpoint(
 	buf = log_sys->checkpoint_buf;
 
 	while (group) {
+
+		ulint	log_hdr_log_block_size;
+
 		group->state = LOG_GROUP_CORRUPTED;
 
+		/* Assert that we can reuse log_sys->checkpoint_buf to read the
+		part of the header that contains the log block size. */
+		ut_ad(LOG_FILE_OS_FILE_LOG_BLOCK_SIZE + 4
+		      < OS_FILE_LOG_BLOCK_SIZE);
+
+		fil_io(OS_FILE_READ | OS_FILE_LOG, TRUE, group->space_id, 0,
+		       0, 0, OS_FILE_LOG_BLOCK_SIZE,
+		       log_sys->checkpoint_buf, NULL);
+		log_hdr_log_block_size
+			= mach_read_from_4(log_sys->checkpoint_buf
+					   + LOG_FILE_OS_FILE_LOG_BLOCK_SIZE);
+		if (log_hdr_log_block_size == 0) {
+			/* 0 means default value */
+			log_hdr_log_block_size = 512;
+		}
+		if (log_hdr_log_block_size != srv_log_block_size) {
+			fprintf(stderr,
+				"InnoDB: Error: The block size of ib_logfile "
+				"%lu is not equal to innodb_log_block_size "
+				"%lu.\n"
+				"InnoDB: Error: Suggestion - Recreate log "
+				"files.\n",
+				log_hdr_log_block_size, srv_log_block_size);
+			return(DB_ERROR);
+		}
+
 		for (field = LOG_CHECKPOINT_1; field <= LOG_CHECKPOINT_2;
 		     field += LOG_CHECKPOINT_2 - LOG_CHECKPOINT_1) {
 
@@ -2989,7 +3019,6 @@ recv_recovery_from_checkpoint_start_func(
 	log_group_t*	max_cp_group;
 	log_group_t*	up_to_date_group;
 	ulint		max_cp_field;
-	ulint		log_hdr_log_block_size;
 	ib_uint64_t	checkpoint_lsn;
 	ib_uint64_t	checkpoint_no;
 	ib_uint64_t	old_scanned_lsn;
@@ -3092,21 +3121,6 @@ recv_recovery_from_checkpoint_start_func(
 		       log_hdr_buf, max_cp_group);
 	}
 
-	log_hdr_log_block_size
-		= mach_read_from_4(log_hdr_buf + LOG_FILE_OS_FILE_LOG_BLOCK_SIZE);
-	if (log_hdr_log_block_size == 0) {
-		/* 0 means default value */
-		log_hdr_log_block_size = 512;
-	}
-	if (log_hdr_log_block_size != srv_log_block_size) {
-		fprintf(stderr,
-			"InnoDB: Error: The block size of ib_logfile (%lu) "
-			"is not equal to innodb_log_block_size.\n"
-			"InnoDB: Error: Suggestion - Recreate log files.\n",
-			log_hdr_log_block_size);
-		return(DB_ERROR);
-	}
-
 #ifdef UNIV_LOG_ARCHIVE
 	group = UT_LIST_GET_FIRST(log_sys->log_groups);
 
diff --git a/storage/xtradb/page/page0cur.c b/storage/xtradb/page/page0cur.c
index a722f5b..4b6a155 100644
--- a/storage/xtradb/page/page0cur.c
+++ b/storage/xtradb/page/page0cur.c
@@ -1048,6 +1048,26 @@ use_heap:
 	insert_rec = rec_copy(insert_buf, rec, offsets);
 	rec_offs_make_valid(insert_rec, index, offsets);
 
+	/* This is because assertion below is debug assertion */
+#ifdef UNIV_DEBUG
+	if (UNIV_UNLIKELY(current_rec == insert_rec)) {
+		ulint extra_len, data_len;
+		extra_len = rec_offs_extra_size(offsets);
+		data_len = rec_offs_data_size(offsets);
+
+		fprintf(stderr, "InnoDB: Error: current_rec == insert_rec "
+			" extra_len %lu data_len %lu insert_buf %p rec %p\n",
+			extra_len, data_len, insert_buf, rec);
+		fprintf(stderr, "InnoDB; Physical record: \n");
+		rec_print(stderr, rec, index);
+		fprintf(stderr, "InnoDB: Inserted record: \n");
+		rec_print(stderr, insert_rec, index);
+		fprintf(stderr, "InnoDB: Current record: \n");
+		rec_print(stderr, current_rec, index);
+		ut_a(current_rec != insert_rec);
+	}
+#endif /* UNIV_DEBUG */
+
 	/* 4. Insert the record in the linked list of records */
 	ut_ad(current_rec != insert_rec);
 
diff --git a/storage/xtradb/row/row0merge.c b/storage/xtradb/row/row0merge.c
index 752e941..3a03c7c 100644
--- a/storage/xtradb/row/row0merge.c
+++ b/storage/xtradb/row/row0merge.c
@@ -2747,7 +2747,7 @@ row_merge_drop_table(
 	/* There must be no open transactions on the table. */
 	ut_a(table->n_mysql_handles_opened == 0);
 
-	return(row_drop_table_for_mysql(table->name, trx, FALSE));
+	return(row_drop_table_for_mysql(table->name, trx, FALSE, FALSE));
 }
 
 /*********************************************************************//**
diff --git a/storage/xtradb/row/row0mysql.c b/storage/xtradb/row/row0mysql.c
index e6ccf44..0182752 100644
--- a/storage/xtradb/row/row0mysql.c
+++ b/storage/xtradb/row/row0mysql.c
@@ -2013,7 +2013,7 @@ err_exit:
 
 		if (dict_table_get_low(table->name, DICT_ERR_IGNORE_NONE)) {
 
-			row_drop_table_for_mysql(table->name, trx, FALSE);
+			row_drop_table_for_mysql(table->name, trx, FALSE, TRUE);
 			trx_commit_for_mysql(trx);
 		} else {
 			dict_mem_table_free(table);
@@ -2143,7 +2143,7 @@ error_handling:
 
 		trx_general_rollback_for_mysql(trx, NULL);
 
-		row_drop_table_for_mysql(table_name, trx, FALSE);
+		row_drop_table_for_mysql(table_name, trx, FALSE, TRUE);
 
 		trx_commit_for_mysql(trx);
 
@@ -2278,7 +2278,7 @@ row_table_add_foreign_constraints(
 
 		trx_general_rollback_for_mysql(trx, NULL);
 
-		row_drop_table_for_mysql(name, trx, FALSE);
+		row_drop_table_for_mysql(name, trx, FALSE, TRUE);
 
 		trx_commit_for_mysql(trx);
 
@@ -2319,7 +2319,7 @@ row_drop_table_for_mysql_in_background(
 
 	/* Try to drop the table in InnoDB */
 
-	error = row_drop_table_for_mysql(name, trx, FALSE);
+	error = row_drop_table_for_mysql(name, trx, FALSE, FALSE);
 
 	/* Flush the log to reduce probability that the .frm files and
 	the InnoDB data dictionary get out-of-sync if the user runs
@@ -3216,7 +3216,10 @@ row_drop_table_for_mysql(
 /*=====================*/
 	const char*	name,	/*!< in: table name */
 	trx_t*		trx,	/*!< in: transaction handle */
-	ibool		drop_db)/*!< in: TRUE=dropping whole database */
+	ibool		drop_db,/*!< in: TRUE=dropping whole database */
+	ibool		create_failed) /*!<in: TRUE=create table failed
+				       because e.g. foreign key column
+				       type mismatch. */
 {
 	dict_foreign_t*	foreign;
 	dict_table_t*	table;
@@ -3331,7 +3334,11 @@ check_next_foreign:
 		foreign = UT_LIST_GET_NEXT(referenced_list, foreign);
 	}
 
-	if (foreign && trx->check_foreigns
+	/* We should allow dropping a referenced table if creating
+	that referenced table has failed for some reason. For example
+	if referenced table is created but it column types that are
+	referenced do not match. */
+	if (foreign && trx->check_foreigns && !create_failed
 	    && !(drop_db && dict_tables_have_same_db(
 			 name, foreign->foreign_table_name_lookup))) {
 		FILE*	ef	= dict_foreign_err_file;
@@ -3718,7 +3725,7 @@ row_mysql_drop_temp_tables(void)
 		table = dict_table_get_low(table_name, DICT_ERR_IGNORE_ALL);
 
 		if (table) {
-			row_drop_table_for_mysql(table_name, trx, FALSE);
+			row_drop_table_for_mysql(table_name, trx, FALSE, FALSE);
 			trx_commit_for_mysql(trx);
 		}
 
@@ -3848,7 +3855,7 @@ loop:
 			goto loop;
 		}
 
-		err = row_drop_table_for_mysql(table_name, trx, TRUE);
+		err = row_drop_table_for_mysql(table_name, trx, TRUE, FALSE);
 		trx_commit_for_mysql(trx);
 
 		if (err != DB_SUCCESS) {
diff --git a/storage/xtradb/trx/trx0roll.c b/storage/xtradb/trx/trx0roll.c
index 25c1d5d..236eb88 100644
--- a/storage/xtradb/trx/trx0roll.c
+++ b/storage/xtradb/trx/trx0roll.c
@@ -504,7 +504,7 @@ trx_rollback_active(
 			ut_print_name(stderr, trx, TRUE, table->name);
 			fputs(" in recovery\n", stderr);
 
-			err = row_drop_table_for_mysql(table->name, trx, TRUE);
+			err = row_drop_table_for_mysql(table->name, trx, TRUE, FALSE);
 			trx_commit_for_mysql(trx);
 
 			ut_a(err == (int) DB_SUCCESS);
diff --git a/strings/ctype-ucs2.c b/strings/ctype-ucs2.c
index a79f589..ca6f53f 100644
--- a/strings/ctype-ucs2.c
+++ b/strings/ctype-ucs2.c
@@ -1,5 +1,5 @@
 /* Copyright (c) 2003, 2013, Oracle and/or its affiliates
-   Copyright (c) 2009, 2014, SkySQL Ab.
+   Copyright (c) 2009, 2016, MariaDB
 
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
@@ -1098,7 +1098,7 @@ my_uni_utf16(CHARSET_INFO *cs __attribute__((unused)),
 static inline void
 my_tolower_utf16(MY_UNICASE_INFO * const* uni_plane, my_wc_t *wc)
 {
-  int page= *wc >> 8;
+  uint page= *wc >> 8;
   if (page < 256 && uni_plane[page])
     *wc= uni_plane[page][*wc & 0xFF].tolower;
 }
@@ -1107,7 +1107,7 @@ my_tolower_utf16(MY_UNICASE_INFO * const* uni_plane, my_wc_t *wc)
 static inline void
 my_toupper_utf16(MY_UNICASE_INFO * const* uni_plane, my_wc_t *wc)
 {
-  int page= *wc >> 8;
+  uint page= *wc >> 8;
   if (page < 256 && uni_plane[page])
     *wc= uni_plane[page][*wc & 0xFF].toupper;
 }
@@ -1116,7 +1116,7 @@ my_toupper_utf16(MY_UNICASE_INFO * const* uni_plane, my_wc_t *wc)
 static inline void
 my_tosort_utf16(MY_UNICASE_INFO * const* uni_plane, my_wc_t *wc)
 {
-  int page= *wc >> 8;
+  uint page= *wc >> 8;
   if (page < 256)
   {
     if (uni_plane[page])
@@ -1727,7 +1727,7 @@ my_uni_utf32(CHARSET_INFO *cs __attribute__((unused)),
 static inline void
 my_tolower_utf32(MY_UNICASE_INFO * const* uni_plane, my_wc_t *wc)
 {
-  int page= *wc >> 8;
+  uint page= *wc >> 8;
   if (page < 256 && uni_plane[page])
     *wc= uni_plane[page][*wc & 0xFF].tolower;
 }
@@ -1736,7 +1736,7 @@ my_tolower_utf32(MY_UNICASE_INFO * const* uni_plane, my_wc_t *wc)
 static inline void
 my_toupper_utf32(MY_UNICASE_INFO * const* uni_plane, my_wc_t *wc)
 {
-  int page= *wc >> 8;
+  uint page= *wc >> 8;
   if (page < 256 && uni_plane[page])
     *wc= uni_plane[page][*wc & 0xFF].toupper;
 }
@@ -1745,7 +1745,7 @@ my_toupper_utf32(MY_UNICASE_INFO * const* uni_plane, my_wc_t *wc)
 static inline void
 my_tosort_utf32(MY_UNICASE_INFO *const* uni_plane, my_wc_t *wc)
 {
-  int page= *wc >> 8;
+  uint page= *wc >> 8;
   if (page < 256)
   {
     if (uni_plane[page])
diff --git a/strings/ctype-utf8.c b/strings/ctype-utf8.c
index 2dd7f5e..f278265 100644
--- a/strings/ctype-utf8.c
+++ b/strings/ctype-utf8.c
@@ -1,5 +1,5 @@
 /* Copyright (c) 2000, 2013, Oracle and/or its affiliates.
-   Copyright (c) 2009, 2013, Monty Program Ab
+   Copyright (c) 2009, 2016, MariaDB
 
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
@@ -1939,7 +1939,7 @@ MY_UNICASE_INFO *const my_unicase_turkish[256]=
 static inline void
 my_tosort_unicode(MY_UNICASE_INFO * const* uni_plane, my_wc_t *wc)
 {
-  int page= *wc >> 8;
+  uint page= *wc >> 8;
   if (page < 256)
   {
     if (uni_plane[page])
@@ -5024,7 +5024,7 @@ my_wc_mb_utf8mb4_no_range(CHARSET_INFO *cs __attribute__((unused)),
 static inline void
 my_tolower_utf8mb4(MY_UNICASE_INFO * const* uni_plane, my_wc_t *wc)
 {
-  int page= *wc >> 8;
+  uint page= *wc >> 8;
   if (page < 256 && uni_plane[page])
     *wc= uni_plane[page][*wc & 0xFF].tolower;
 }
@@ -5033,7 +5033,7 @@ my_tolower_utf8mb4(MY_UNICASE_INFO * const* uni_plane, my_wc_t *wc)
 static inline void
 my_toupper_utf8mb4(MY_UNICASE_INFO * const* uni_plane, my_wc_t *wc)
 {
-  int page= *wc >> 8;
+  uint page= *wc >> 8;
   if (page < 256 && uni_plane[page])
     *wc= uni_plane[page][*wc & 0xFF].toupper;
 }
diff --git a/strings/decimal.c b/strings/decimal.c
index 8dbe1bd..b0c57d3 100644
--- a/strings/decimal.c
+++ b/strings/decimal.c
@@ -1025,7 +1025,11 @@ int ulonglong2decimal(ulonglong from, decimal_t *to)
 int longlong2decimal(longlong from, decimal_t *to)
 {
   if ((to->sign= from < 0))
+  {
+    if (from == LONGLONG_MIN) // avoid undefined behavior
+      return ull2dec((ulonglong)LONGLONG_MIN, to);
     return ull2dec(-from, to);
+  }
   return ull2dec(from, to);
 }
 
diff --git a/support-files/mysql.server.sh b/support-files/mysql.server.sh
index 63cef2a..e5c8814 100644
--- a/support-files/mysql.server.sh
+++ b/support-files/mysql.server.sh
@@ -308,7 +308,7 @@ case "$mode" in
     then
       # Give extra arguments to mysqld with the my.cnf file. This script
       # may be overwritten at next upgrade.
-      $bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" $other_args >/dev/null 2>&1 &
+      $bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" $other_args >/dev/null &
       wait_for_ready; return_value=$?
 
       # Make lock for RedHat / SuSE
diff --git a/win/packaging/CMakeLists.txt b/win/packaging/CMakeLists.txt
index 0535a48..1682bae 100644
--- a/win/packaging/CMakeLists.txt
+++ b/win/packaging/CMakeLists.txt
@@ -24,10 +24,13 @@ ENDIF()
 
 
 SET(MANUFACTURER "MariaDB Corporation Ab")
-FIND_PATH(WIX_DIR heat.exe
-  "$ENV{ProgramFiles}/WiX Toolset v3.9/bin"
-  "$ENV{ProgramFiles}/WiX Toolset v3.10/bin"
-)
+SET(WIX_BIN_PATHS)
+FOREACH(WIX_VER 3.9 3.10 3.11)
+  LIST(APPEND WIX_BIN_PATHS "$ENV{ProgramFiles}/WiX Toolset v${WIX_VER}/bin")
+  LIST(APPEND WIX_BIN_PATHS "$ENV{ProgramFiles} (x86)/WiX Toolset v${WIX_VER}/bin")
+ENDFOREACH()
+
+FIND_PATH(WIX_DIR heat.exe ${WIX_BIN_PATHS})
 SET(CPACK_WIX_PACKAGE_BASE_NAME "MariaDB")
 IF(CMAKE_SIZEOF_VOID_P EQUAL 4)
  SET(CPACK_WIX_UPGRADE_CODE "49EB7A6A-1CEF-4A1E-9E89-B9A4993963E3")
diff --git a/win/packaging/create_msi.cmake.in b/win/packaging/create_msi.cmake.in
index a8ca359..fceea04 100644
--- a/win/packaging/create_msi.cmake.in
+++ b/win/packaging/create_msi.cmake.in
@@ -430,6 +430,7 @@ EXECUTE_PROCESS(
 IF(SIGNCODE)
   EXECUTE_PROCESS(
   COMMAND ${SIGNTOOL_EXECUTABLE} sign ${SIGNTOOL_PARAMETERS} 
+  /d ${CPACK_PACKAGE_FILE_NAME}.msi
   ${CPACK_PACKAGE_FILE_NAME}.msi
 )
 ENDIF()

-- 
Alioth's hooks/post-receive on /srv/git.debian.org/git/pkg-mysql/mariadb-5.5.git



More information about the Pkg-mysql-commits mailing list