From 2a25b2617a3e049d5a0b56213703dba6aee83c1e Mon Sep 17 00:00:00 2001
From: "konstantin@oak.local" <>
Date: Sat, 20 Dec 2003 02:16:10 +0300
Subject: [PATCH 1/9] Prepared_statement deployed instead of PREP_STMT.

---
 libmysqld/lib_sql.cc |  87 -------
 sql/mysql_priv.h     |   4 +-
 sql/slave.cc         |   1 -
 sql/sql_class.cc     | 140 +++++++---
 sql/sql_class.h      | 208 ++++++++++++---
 sql/sql_parse.cc     |   8 +-
 sql/sql_prepare.cc   | 593 ++++++++++++++++++++++++-------------------
 tests/client_test.c  |   2 +-
 8 files changed, 613 insertions(+), 430 deletions(-)

diff --git a/libmysqld/lib_sql.cc b/libmysqld/lib_sql.cc
index 89012a84857..365e9bc820a 100644
--- a/libmysqld/lib_sql.cc
+++ b/libmysqld/lib_sql.cc
@@ -743,90 +743,3 @@ bool Protocol::convert_str(const char *from, uint length)
 }
 #endif
 
-bool setup_params_data(st_prep_stmt *stmt)
-{                                       
-  THD *thd= stmt->thd;
-  List<Item> &params= thd->lex->param_list;
-  List_iterator<Item> param_iterator(params);
-  Item_param *param;
-  ulong param_no= 0;
-  MYSQL_BIND *client_param= thd->client_params;
-
-  DBUG_ENTER("setup_params_data");
-
-  for (;(param= (Item_param *)param_iterator++); client_param++)
-  {       
-    setup_param_functions(param, client_param->buffer_type);
-    if (!param->long_data_supplied)
-    {
-      if (*client_param->is_null)
-        param->maybe_null= param->null_value= 1;
-      else
-      {
-	uchar *buff= (uchar*)client_param->buffer;
-        param->maybe_null= param->null_value= 0;
-        param->setup_param_func(param,&buff, 
-				client_param->length ? 
-				*client_param->length : 
-				client_param->buffer_length);
-      }
-    }
-    param_no++;
-  }
-  DBUG_RETURN(0);
-}
-
-bool setup_params_data_withlog(st_prep_stmt *stmt)
-{                                       
-  THD *thd= stmt->thd;
-  List<Item> &params= thd->lex->param_list;
-  List_iterator<Item> param_iterator(params);
-  Item_param *param;
-  MYSQL_BIND *client_param= thd->client_params;
-
-  DBUG_ENTER("setup_params_data");
-
-  String str, *res, *query= new String(stmt->query->alloced_length());  
-  query->copy(*stmt->query);
-  
-  ulong param_no= 0;  
-  uint32 length= 0;
-
-  for (;(param= (Item_param *)param_iterator++); client_param++)
-  {       
-    setup_param_functions(param, client_param->buffer_type);
-    if (param->long_data_supplied)
-      res= param->query_val_str(&str);       
-    
-    else
-    {
-      if (*client_param->is_null)
-      {
-        param->maybe_null= param->null_value= 1;
-        res= &my_null_string;
-      }
-      else
-      {
-	uchar *buff= (uchar*)client_param->buffer;
-        param->maybe_null= param->null_value= 0;
-        param->setup_param_func(param,&buff,
-				client_param->length ? 
-				*client_param->length : 
-				client_param->buffer_length);
-        res= param->query_val_str(&str);
-      }
-    }
-    if (query->replace(param->pos_in_query+length, 1, *res))
-      DBUG_RETURN(1);
-    
-    length+= res->length()-1;
-    param_no++;
-  }
-  
-  if (alloc_query(stmt->thd, (char *)query->ptr(), query->length()+1))
-    DBUG_RETURN(1);
-  
-  query->free();
-  DBUG_RETURN(0);
-}
-
diff --git a/sql/mysql_priv.h b/sql/mysql_priv.h
index 863c1bdd419..ff50993ad50 100644
--- a/sql/mysql_priv.h
+++ b/sql/mysql_priv.h
@@ -612,8 +612,6 @@ int mysqld_show_column_types(THD *thd);
 int mysqld_help (THD *thd, const char *text);
 
 /* sql_prepare.cc */
-int compare_prep_stmt(void *not_used, PREP_STMT *stmt, ulong *key);
-void free_prep_stmt(PREP_STMT *stmt, TREE_FREE mode, void *not_used);
 bool mysql_stmt_prepare(THD *thd, char *packet, uint packet_length);
 void mysql_stmt_execute(THD *thd, char *packet);
 void mysql_stmt_free(THD *thd, char *packet);
@@ -855,7 +853,7 @@ extern I_List<THD> threads;
 extern I_List<NAMED_LIST> key_caches;
 extern MY_BITMAP temp_pool;
 extern String my_empty_string;
-extern String my_null_string;
+extern const String my_null_string;
 extern SHOW_VAR init_vars[],status_vars[], internal_vars[];
 extern SHOW_COMP_OPTION have_isam;
 extern SHOW_COMP_OPTION have_innodb;
diff --git a/sql/slave.cc b/sql/slave.cc
index 8af38624df6..d2a7d397fa7 100644
--- a/sql/slave.cc
+++ b/sql/slave.cc
@@ -3111,7 +3111,6 @@ slave_begin:
     sql_print_error("Failed during slave thread initialization");
     goto err;
   }
-  thd->init_for_queries();
   rli->sql_thd= thd;
   thd->temporary_tables = rli->save_temporary_tables; // restore temp tables
   pthread_mutex_lock(&LOCK_thread_count);
diff --git a/sql/sql_class.cc b/sql/sql_class.cc
index 0469497790a..606ecdbecbb 100644
--- a/sql/sql_class.cc
+++ b/sql/sql_class.cc
@@ -88,21 +88,20 @@ THD::THD():user_time(0), is_fatal_error(0),
 	   insert_id_used(0), rand_used(0), in_lock_tables(0),
 	   global_read_lock(0), bootstrap(0)
 {
-  host=user=priv_user=db=query=ip=0;
-  lex= &main_lex;
+  host= user= priv_user= db= ip=0;
   host_or_ip= "connecting host";
   locked=killed=some_tables_deleted=no_errors=password= 0;
   query_start_used= 0;
   count_cuted_fields= CHECK_FIELD_IGNORE;
-  db_length=query_length=col_access=0;
+  db_length= col_access= 0;
   query_error= tmp_table_used= 0;
   next_insert_id=last_insert_id=0;
   open_tables= temporary_tables= handler_tables= derived_tables= 0;
-  handler_items=0;
   tmp_table=0;
   lock=locked_tables=0;
   used_tables=0;
-  cuted_fields= sent_row_count= current_stmt_id= 0L;
+  cuted_fields= sent_row_count= 0L;
+  statement_id_counter= 0UL;
   // Must be reset to handle error with THD's created for init of mysqld
   lex->current_select= 0;
   start_time=(time_t) 0;
@@ -138,7 +137,6 @@ THD::THD():user_time(0), is_fatal_error(0),
   server_id = ::server_id;
   slave_net = 0;
   command=COM_CONNECT;
-  set_query_id=1;
 #ifndef NO_EMBEDDED_ACCESS_CHECKS
   db_access=NO_ACCESS;
 #endif
@@ -146,10 +144,11 @@ THD::THD():user_time(0), is_fatal_error(0),
   *scramble= '\0';
 
   init();
+  init_sql_alloc(&mem_root,                    // must be after init()
+                 variables.query_alloc_block_size,
+                 variables.query_prealloc_size);
   /* Initialize sub structures */
-  bzero((char*) &mem_root,sizeof(mem_root));
   bzero((char*) &transaction.mem_root,sizeof(transaction.mem_root));
-  bzero((char*) &con_root,sizeof(con_root));
   bzero((char*) &warn_root,sizeof(warn_root));
   init_alloc_root(&warn_root, WARN_ALLOC_BLOCK_SIZE, WARN_ALLOC_PREALLOC_SIZE);
   user_connect=(USER_CONN *)0;
@@ -166,12 +165,6 @@ THD::THD():user_time(0), is_fatal_error(0),
   else
     bzero((char*) &user_var_events, sizeof(user_var_events));
 
-  /* Prepared statements */
-  last_prepared_stmt= 0;
-  init_tree(&prepared_statements, 0, 0, sizeof(PREP_STMT),
-	    (qsort_cmp2) compare_prep_stmt, 1,
-	    (tree_element_free) free_prep_stmt, 0);
-
   /* Protocol */
   protocol= &protocol_simple;			// Default protocol
   protocol_simple.init(this);
@@ -189,7 +182,9 @@ THD::THD():user_time(0), is_fatal_error(0),
     transaction.trans_log.end_of_file= max_binlog_cache_size;
   }
 #endif
-
+  init_sql_alloc(&transaction.mem_root,         
+		 variables.trans_alloc_block_size, 
+		 variables.trans_prealloc_size);
   /*
     We need good random number initialization for new thread
     Just coping global one will not work
@@ -232,22 +227,6 @@ void THD::init(void)
 }
 
 
-/*
-  Init THD for query processing
-
-  This has to be called once before we call mysql_parse()
-*/
-
-void THD::init_for_queries()
-{
-  init_sql_alloc(&mem_root, variables.query_alloc_block_size,
-		 variables.query_prealloc_size);
-  init_sql_alloc(&transaction.mem_root,
-		 variables.trans_alloc_block_size,
-		 variables.trans_prealloc_size);
-}
-
-
 /*
   Do what's needed when one invokes change user
 
@@ -276,7 +255,6 @@ void THD::cleanup(void)
 {
   DBUG_ENTER("THD::cleanup");
   ha_rollback(this);
-  delete_tree(&prepared_statements);
   if (locked_tables)
   {
     lock=locked_tables; locked_tables=0;
@@ -340,8 +318,6 @@ THD::~THD()
     safeFree(user);
   safeFree(db);
   safeFree(ip);
-  free_root(&mem_root,MYF(0));
-  free_root(&con_root,MYF(0));
   free_root(&warn_root,MYF(0));
   free_root(&transaction.mem_root,MYF(0));
   mysys_var=0;					// Safety (shouldn't be needed)
@@ -1193,6 +1169,102 @@ int select_dumpvar::prepare(List<Item> &list, SELECT_LEX_UNIT *u)
   }
   return 0;
 }
+
+
+/*
+  Statement functions 
+*/
+
+Statement::Statement(THD *thd)
+  :id(++thd->statement_id_counter),
+  query_id(thd->query_id),
+  set_query_id(1),
+  allow_sum_func(0),
+  command(thd->command),
+  lex(&main_lex),
+  query(0),
+  query_length(0),
+  free_list(0)
+{
+  init_sql_alloc(&mem_root,
+                 thd->variables.query_alloc_block_size,
+                 thd->variables.query_prealloc_size);
+}
+
+/*
+  This constructor is called when statement is a subobject of THD:
+  Some variables are initialized in THD::init due to locking problems
+  This statement object will be used to 
+*/
+
+Statement::Statement()
+  :id(0),
+  query_id(0),                                  /* initialized later */
+  set_query_id(1),
+  allow_sum_func(0),                            /* initialized later */
+  command(COM_SLEEP),                           /* initialized later */ 
+  lex(&main_lex),
+  query(0),                                     /* these two are set */ 
+  query_length(0),                              /* in alloc_query() */
+  free_list(0)
+{
+  bzero((char *) &mem_root, sizeof(mem_root));
+}
+
+
+Statement::Type Statement::type() const
+{
+  return STATEMENT;
+}
+
+
+void Statement::set_statement(Statement *stmt)
+{
+  id=             stmt->id;
+  query_id=       stmt->query_id;
+  set_query_id=   stmt->set_query_id;
+  allow_sum_func= stmt->allow_sum_func;
+  command=        stmt->command;
+  lex=            stmt->lex;
+  query=          stmt->query;
+  query_length=   stmt->query_length;
+  free_list=      stmt->free_list;
+  mem_root=       stmt->mem_root;
+}
+
+
+Statement::~Statement()
+{
+  free_root(&mem_root, MYF(0));
+}
+
+C_MODE_START
+
+static byte *
+get_statement_id_as_hash_key(const byte *record, uint *key_length,
+                             my_bool not_used __attribute__((unused)))
+{
+  const Statement *statement= (const Statement *) record; 
+  *key_length= sizeof(statement->id);
+  return (byte *) &((const Statement *) statement)->id;
+}
+
+static void delete_statement_as_hash_key(void *key)
+{
+  delete (Statement *) key;
+}
+
+C_MODE_END
+
+Statement_map::Statement_map() :
+  last_found_statement(0)
+{
+  enum { START_HASH_SIZE = 16 };
+  hash_init(&st_hash, default_charset_info, START_HASH_SIZE, 0, 0,
+            get_statement_id_as_hash_key,
+            delete_statement_as_hash_key, MYF(0));
+}
+
 bool select_dumpvar::send_data(List<Item> &items)
 {
   List_iterator_fast<Item_func_set_user_var> li(vars);
diff --git a/sql/sql_class.h b/sql/sql_class.h
index 2a7523c890b..d663521b296 100644
--- a/sql/sql_class.h
+++ b/sql/sql_class.h
@@ -328,30 +328,6 @@ public:
 };
 
 
-/* This is a struct as it's allocated in tree_insert */
-
-typedef struct st_prep_stmt
-{
-  THD *thd;
-  LEX  lex; 
-  Item_param **param;
-  Item *free_list;
-  MEM_ROOT mem_root;
-  String *query;
-  ulong stmt_id;
-  uint param_count;
-  uint last_errno;
-  char last_error[MYSQL_ERRMSG_SIZE];
-  bool error_in_prepare, long_data_used;
-  bool log_full_query;
-#ifndef EMBEDDED_LIBRARY
-  bool (*setup_params)(st_prep_stmt *stmt, uchar *pos, uchar *read_pos);
-#else
-  bool (*setup_params_data)(st_prep_stmt *stmt);
-#endif
-} PREP_STMT;
-
-
 class delayed_insert;
 class select_result;
 
@@ -428,12 +404,158 @@ struct system_variables
 };
 
 void free_tmp_table(THD *thd, TABLE *entry);
+
+class Prepared_statement;
+
+/*
+  State of a single command executed against this connection.
+  One connection can contain a lot of simultaneously running statements,
+  some of which could be:
+   - prepared, that is, contain placeholders,
+   - opened as cursors. We maintain 1 to 1 relationship between
+     statement and cursor - if user wants to create another cursor for his
+     query, we create another statement for it. 
+  To perform some action with statement we reset THD part to the state  of
+  that statement, do the action, and then save back modified state from THD
+  to the statement. It will be changed in near future, and Statement will
+  be used explicitly.
+*/
+
+class Statement
+{
+  Statement(const Statement &rhs);              /* not implemented: */
+  Statement &operator=(const Statement &rhs);   /* non-copyable */
+public:
+  /* FIXME: must be private */
+  LEX     main_lex;
+public:
+  /*
+    Uniquely identifies each statement object in thread scope; change during
+    statement lifetime. FIXME: must be const
+  */
+   ulong id;
+
+  /*
+    Id of current query. Statement can be reused to execute several queries
+    query_id is global in context of the whole MySQL server.
+    ID is automatically generated from mutex-protected counter.
+    It's used in handler code for various purposes: to check which columns
+    from table are necessary for this select, to check if it's necessary to
+    update auto-updatable fields (like auto_increment and timestamp).
+  */
+  ulong query_id;
+  /*
+    - if set_query_id=1, we set field->query_id for all fields. In that case 
+    field list can not contain duplicates.
+  */
+  bool set_query_id;
+  /*
+    This variable is used in post-parse stage to declare that sum-functions,
+    or functions which have sense only if GROUP BY is present, are allowed.
+    For example in queries
+    SELECT MIN(i) FROM foo
+    SELECT GROUP_CONCAT(a, b, MIN(i)) FROM ... GROUP BY ...
+    MIN(i) have no sense.
+    Though it's grammar-related issue, it's hard to catch it out during the
+    parse stage because GROUP BY clause goes in the end of query. This
+    variable is mainly used in setup_fields/fix_fields.
+    See item_sum.cc for details.
+  */
+  bool allow_sum_func;
+  /*
+    Type of current query: COM_PREPARE, COM_QUERY, etc. Set from 
+    first byte of the packet in do_command()
+  */
+  enum enum_server_command command;
+
+  LEX *lex;                                     // parse tree descriptor
+  /*
+    Points to the query associated with this statement. It's const, but
+    we need to declare it char * because all table handlers are written
+    in C and need to point to it.
+  */
+  char *query;
+  uint32 query_length;                          // current query length
+  /*
+    List of items created in the parser for this query. Every item puts 
+    itself to the list on creation (see Item::Item() for details))
+  */
+  Item *free_list;
+  MEM_ROOT mem_root;
+
+public:
+  /* We build without RTTI, so dynamic_cast can't be used. */
+  enum Type
+  {
+    STATEMENT,
+    PREPARED_STATEMENT
+  };
+
+  /*
+    This constructor is called when statement is a subobject of THD:
+    some variables are initialized in THD::init due to locking problems
+  */
+  Statement();
+
+  Statement(THD *thd);
+  virtual ~Statement();
+
+  /* Assign execution context (note: not all members) of given stmt to self */
+  void set_statement(Statement *stmt);
+  /* return class type */
+  virtual Type type() const;
+};
+
+
+/*
+  Used to seek all existing statements in the connection
+  Deletes all statements in destructor.
+*/
+
+class Statement_map
+{
+public:
+  Statement_map();
+  
+  int insert(Statement *statement)
+  {
+    int rc= my_hash_insert(&st_hash, (byte *) statement);
+    if (rc == 0)
+      last_found_statement= statement;
+    return rc;
+  }
+
+  Statement *find(ulong id)
+  {
+    if (last_found_statement == 0 || id != last_found_statement->id)
+      last_found_statement= (Statement *) hash_search(&st_hash, (byte *) &id,
+                                                      sizeof(id));
+    return last_found_statement;
+  }
+  void erase(Statement *statement)
+  {
+    if (statement == last_found_statement)
+      last_found_statement= 0;
+    hash_delete(&st_hash, (byte *) statement);
+  }
+
+  ~Statement_map()
+  {
+    hash_free(&st_hash);
+  }
+private:
+  HASH st_hash;
+  Statement *last_found_statement;
+};
+
+
 /*
   For each client connection we create a separate thread with THD serving as
   a thread/connection descriptor
 */
 
-class THD :public ilink
+class THD :public ilink, 
+           public Statement
 {
 public:
 #ifdef EMBEDDED_LIBRARY
@@ -446,23 +568,25 @@ public:
   ulong extra_length;
 #endif
   NET	  net;				// client connection descriptor
-  LEX     main_lex;
-  LEX	  *lex;				// parse tree descriptor
-  MEM_ROOT mem_root;			// 1 command-life memory pool
-  MEM_ROOT con_root;                    // connection-life memory
   MEM_ROOT warn_root;			// For warnings and errors
   Protocol *protocol;			// Current protocol
   Protocol_simple protocol_simple;	// Normal protocol
   Protocol_prep protocol_prep;		// Binary protocol
   HASH    user_vars;			// hash for user variables
-  TREE	  prepared_statements;
   String  packet;			// dynamic buffer for network I/O
   struct  sockaddr_in remote;		// client socket address
   struct  rand_struct rand;		// used for authentication
   struct  system_variables variables;	// Changeable local variables
   pthread_mutex_t LOCK_delete;		// Locked before thd is deleted
 
-  char	  *query;			// Points to the current query,
+  /* all prepared statements and cursors of this connection */
+  Statement_map stmt_map; 
+  /*
+    keeps THD state while it is used for active statement
+    Note, that double free_root() is safe, so we don't need to do any
+    special cleanup for it in THD destructor.
+  */
+  Statement stmt_backup;
   /*
     A pointer to the stack frame of handle_one_connection(),
     which is called first in the thread for handling a client
@@ -502,7 +626,6 @@ public:
      and are still in use by this thread
   */
   TABLE   *open_tables,*temporary_tables, *handler_tables, *derived_tables;
-  // TODO: document the variables below
   MYSQL_LOCK	*lock;				/* Current locks */
   MYSQL_LOCK	*locked_tables;			/* Tables locked with LOCK */
   /*
@@ -511,12 +634,10 @@ public:
     chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK. 
   */
   ULL		*ull;
-  PREP_STMT	*last_prepared_stmt;
 #ifndef DBUG_OFF
   uint dbug_sentry; // watch out for memory corruption
 #endif
   struct st_my_thread_var *mysys_var;
-  enum enum_server_command command;
   uint32     server_id;
   uint32     file_id;			// for LOAD DATA INFILE
   /*
@@ -549,7 +670,6 @@ public:
       free_root(&mem_root,MYF(MY_KEEP_PREALLOC));
     }
   } transaction;
-  Item	     *free_list, *handler_items;
   Field      *dupp_field;
 #ifndef __WIN__
   sigset_t signals,block_signals;
@@ -580,18 +700,25 @@ public:
   USER_CONN *user_connect;
   CHARSET_INFO *db_charset;
   List<TABLE> temporary_tables_should_be_free; // list of temporary tables
+  /*
+    FIXME: this, and some other variables like 'count_cuted_fields'
+    maybe should be statement/cursor local, that is, moved to Statement
+    class. With current implementation warnings produced in each prepared
+    statement/cursor settle here.
+  */
   List	     <MYSQL_ERROR> warn_list;
   uint	     warn_count[(uint) MYSQL_ERROR::WARN_LEVEL_END];
   uint	     total_warn_count;
-  ulong	     query_id, warn_id, version, options, thread_id, col_access;
-  ulong      current_stmt_id;
+  ulong	     warn_id, version, options, thread_id, col_access;
+
+  /* Statement id is thread-wide. This counter is used to generate ids */
+  ulong      statement_id_counter;
   ulong	     rand_saved_seed1, rand_saved_seed2;
   ulong      row_count;  // Row counter, mainly for errors and warnings
   long	     dbug_thread_id;
   pthread_t  real_id;
   uint	     current_tablenr,tmp_table;
   uint	     server_status,open_options,system_thread;
-  uint32     query_length;
   uint32     db_length;
   uint       select_number;             //number of select (used for EXPLAIN)
   /* variables.transaction_isolation is reset to this after each commit */
@@ -604,9 +731,9 @@ public:
   char	     scramble[SCRAMBLE_LENGTH+1];
 
   bool       slave_thread;
-  bool	     set_query_id,locked,some_tables_deleted;
+  bool	     locked, some_tables_deleted;
   bool       last_cuted_field;
-  bool	     no_errors, allow_sum_func, password, is_fatal_error;
+  bool	     no_errors, password, is_fatal_error;
   bool	     query_start_used,last_insert_id_used,insert_id_used,rand_used;
   bool	     in_lock_tables,global_read_lock;
   bool       query_error, bootstrap, cleanup_done;
@@ -634,7 +761,6 @@ public:
 
   void init(void);
   void change_user(void);
-  void init_for_queries();
   void cleanup(void);
   bool store_globals();
 #ifdef SIGNAL_WITH_VIO_CLOSE
diff --git a/sql/sql_parse.cc b/sql/sql_parse.cc
index 3f2325de703..85659f2d2a2 100644
--- a/sql/sql_parse.cc
+++ b/sql/sql_parse.cc
@@ -974,7 +974,6 @@ pthread_handler_decl(handle_one_connection,arg)
 
     thd->proc_info=0;
     thd->set_time();
-    thd->init_for_queries();
     while (!net->error && net->vio != 0 && !thd->killed)
     {
       if (do_command(thd))
@@ -1055,7 +1054,6 @@ extern "C" pthread_handler_decl(handle_bootstrap,arg)
   thd->priv_user=thd->user=(char*) my_strdup("boot", MYF(MY_WME));
 
   buff= (char*) thd->net.buff;
-  thd->init_for_queries();
   while (fgets(buff, thd->net.max_packet, file))
   {
     uint length=(uint) strlen(buff);
@@ -1221,13 +1219,13 @@ bool dispatch_command(enum enum_server_command command, THD *thd,
 {
   NET *net= &thd->net;
   bool error= 0;
+  DBUG_ENTER("dispatch_command");
+
+  thd->command=command;
   /*
     Commands which will always take a long time should be marked with
     this so that they will not get logged to the slow query log
   */
-  DBUG_ENTER("dispatch_command");
-
-  thd->command=command;
   thd->slow_command=FALSE;
   thd->set_time();
   VOID(pthread_mutex_lock(&LOCK_thread_count));
diff --git a/sql/sql_prepare.cc b/sql/sql_prepare.cc
index bb5f27672fe..f60e0db58d0 100644
--- a/sql/sql_prepare.cc
+++ b/sql/sql_prepare.cc
@@ -71,10 +71,50 @@ Long data handling:
 #include "sql_acl.h"
 #include "sql_select.h" // for JOIN
 #include <m_ctype.h>  // for isspace()
+#ifdef EMBEDDED_LIBRARY
+/* include MYSQL_BIND headers */
+#include <mysql.h>
+#endif
 
-#define IS_PARAM_NULL(pos, param_no) (pos[param_no/8] & (1 << (param_no & 7)))
+const String my_null_string("NULL", 4, default_charset_info);
 
-#define STMT_QUERY_LOG_LENGTH 8192
+/******************************************************************************
+  Prepared_statement: statement which can contain placeholders
+******************************************************************************/
+
+class Prepared_statement: public Statement
+{
+public:
+  THD *thd;
+  Item_param **param;                           /* array of all placeholders */
+  uint param_count;
+  uint last_errno;
+  char last_error[MYSQL_ERRMSG_SIZE];
+  bool error_in_prepare, long_data_used;
+  bool log_full_query;
+#ifndef EMBEDDED_LIBRARY
+  bool (*setup_params)(Prepared_statement *st, uchar *pos, uchar *read_pos);
+#else
+  bool (*setup_params_data)(Prepared_statement *st);
+#endif
+public:
+  Prepared_statement(THD *thd_arg);
+  virtual ~Prepared_statement();
+  virtual Statement::Type type() const;
+};
+
+
+/******************************************************************************
+  Implementation
+******************************************************************************/
+
+
+inline bool is_param_null(const uchar *pos, ulong param_no)
+{
+  return pos[param_no/8] & (1 << (param_no & 7));
+}
+
+enum { STMT_QUERY_LOG_LENGTH= 8192 };
 
 #ifdef EMBEDDED_LIBRARY
 #define SETUP_PARAM_FUNCTION(fn_name) \
@@ -84,114 +124,57 @@ static void fn_name(Item_param *param, uchar **pos, ulong data_len)
 static void fn_name(Item_param *param, uchar **pos)
 #endif
 
-String my_null_string("NULL", 4, default_charset_info);
 
 /*
-  Find prepared statement in thd
-
-  SYNOPSIS
-    find_prepared_statement()
-    thd		Thread handler
-    stmt_id	Statement id server specified to the client on prepare
-
-  RETURN VALUES
-    0		error.  In this case the error is sent with my_error()
-    ptr 	Pointer to statement
+  Seek prepared statement in statement map by id: returns zero if statement
+  was not found, pointer otherwise.
 */
 
-static PREP_STMT *find_prepared_statement(THD *thd, ulong stmt_id,
-					  const char *when)
+static Prepared_statement *
+find_prepared_statement(THD *thd, ulong id, const char *where)
 {
-  PREP_STMT *stmt;
-  DBUG_ENTER("find_prepared_statement");
-  DBUG_PRINT("enter",("stmt_id: %d", stmt_id));
+  Statement *stmt= thd->stmt_map.find(id);
 
-  if (thd->last_prepared_stmt && thd->last_prepared_stmt->stmt_id == stmt_id)
-    DBUG_RETURN(thd->last_prepared_stmt);
-  if ((stmt= (PREP_STMT*) tree_search(&thd->prepared_statements, &stmt_id,
-				      (void*) 0)))
-    DBUG_RETURN (thd->last_prepared_stmt= stmt);
-  my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), stmt_id, when);
-  DBUG_RETURN(0);
+  if (stmt == 0 || stmt->type() != Statement::PREPARED_STATEMENT)
+  {
+    my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), id, where);
+    send_error(thd);
+    return 0;
+  }
+  return (Prepared_statement *) stmt;
 }
 
-/*
-  Compare two prepared statements;  Used to find a prepared statement
-*/
-
-int compare_prep_stmt(void *not_used, PREP_STMT *stmt, ulong *key)
-{
-  return (stmt->stmt_id == *key) ? 0 : (stmt->stmt_id < *key) ? -1 : 1;
-}
-
-
-/*
-  Free prepared statement.
-
-  SYNOPSIS
-    standard tree_element_free function.
-
-  DESCRIPTION
-    We don't have to free the stmt itself as this was stored in the tree
-    and will be freed when the node is deleted
-*/
-
-void free_prep_stmt(PREP_STMT *stmt, TREE_FREE mode, void *not_used)
-{     
-  my_free((char *)stmt->param, MYF(MY_ALLOW_ZERO_PTR));
-  if (stmt->query)
-    stmt->query->free();
-  free_items(stmt->free_list);
-  free_root(&stmt->mem_root, MYF(0));
-}
 
 /*
   Send prepared stmt info to client after prepare
 */
 
 #ifndef EMBEDDED_LIBRARY
-static bool send_prep_stmt(PREP_STMT *stmt, uint columns)
+static bool send_prep_stmt(Prepared_statement *stmt, uint columns)
 {
-  NET  *net=&stmt->thd->net;
+  NET *net= &stmt->thd->net;
   char buff[9];
   buff[0]= 0;
-  int4store(buff+1, stmt->stmt_id);
+  int4store(buff+1, stmt->id);
   int2store(buff+5, columns);
   int2store(buff+7, stmt->param_count);
-  /* This should be fixed to work with prepared statements
-   */
+  /* This should be fixed to work with prepared statements */
   return (my_net_write(net, buff, sizeof(buff)) || net_flush(net));
 }
 #else
-static bool send_prep_stmt(PREP_STMT *stmt, uint columns __attribute__((unused)))
+static bool send_prep_stmt(Prepared_statement *stmt,
+                           uint columns __attribute__((unused)))
 {
   THD *thd= stmt->thd;
 
-  thd->client_stmt_id= stmt->stmt_id;
+  thd->client_stmt_id= stmt->id;
   thd->client_param_count= stmt->param_count;
   thd->net.last_errno= 0;
 
   return 0;
 }
-#endif /*!EMBEDDED_LIBRAYR*/
+#endif /*!EMBEDDED_LIBRARY*/
 
-/*
-  Send information about all item parameters
-
-  TODO: Not yet ready
-*/
-
-static bool send_item_params(PREP_STMT *stmt)
-{
-#if 0
-  char buff[1];
-  buff[0]=0;
-  if (my_net_write(&stmt->thd->net, buff, sizeof(buff))) 
-    return 1;
-  send_eof(stmt->thd);
-#endif
-  return 0;
-}
 
 /*
   Read the length of the parameter data and retun back to   
@@ -418,17 +401,20 @@ void setup_param_functions(Item_param *param, uchar param_type)
   and if binary/update log is set, generate the valid query.
 */
 
-static bool insert_params_withlog(PREP_STMT *stmt, uchar *pos, uchar *read_pos)
+static bool insert_params_withlog(Prepared_statement *stmt, uchar *pos,
+                                  uchar *read_pos)
 {
   THD *thd= stmt->thd;
-  List<Item> &params= thd->lex->param_list;
+  List<Item> &params= stmt->lex->param_list;
   List_iterator<Item> param_iterator(params);
   Item_param *param;
-  DBUG_ENTER("insert_params_withlog"); 
   
-  String str, query, *res;
+  String str, query;
+  const String *res;
 
-  if (query.copy(*stmt->query))
+  DBUG_ENTER("insert_params_withlog"); 
+
+  if (query.copy(stmt->query, stmt->query_length, default_charset_info))
     DBUG_RETURN(1);
   
   ulong param_no= 0;  
@@ -438,10 +424,9 @@ static bool insert_params_withlog(PREP_STMT *stmt, uchar *pos, uchar *read_pos)
   {
     if (param->long_data_supplied)
       res= param->query_val_str(&str);       
-    
     else
     {
-      if (IS_PARAM_NULL(pos,param_no))
+      if (is_param_null(pos,param_no))
       {
         param->maybe_null= param->null_value= 1;
         res= &my_null_string;
@@ -461,23 +446,26 @@ static bool insert_params_withlog(PREP_STMT *stmt, uchar *pos, uchar *read_pos)
   }
   if (alloc_query(thd, (char *)query.ptr(), query.length()+1))
     DBUG_RETURN(1);
+
   DBUG_RETURN(0);
 }
 
-static bool insert_params(PREP_STMT *stmt, uchar *pos, uchar *read_pos)
+
+static bool insert_params(Prepared_statement *stmt, uchar *pos,
+                          uchar *read_pos)
 {
-  THD *thd= stmt->thd;
-  List<Item> &params= thd->lex->param_list;
+  List<Item> &params= stmt->lex->param_list;
   List_iterator<Item> param_iterator(params);
   Item_param *param;
-  DBUG_ENTER("insert_params"); 
-  
   ulong param_no= 0;  
+
+  DBUG_ENTER("insert_params"); 
+
   while ((param= (Item_param *)param_iterator++))
   {
     if (!param->long_data_supplied)   
     {
-      if (IS_PARAM_NULL(pos,param_no))
+      if (is_param_null(pos,param_no))
         param->maybe_null= param->null_value= 1;
       else
       {
@@ -490,17 +478,18 @@ static bool insert_params(PREP_STMT *stmt, uchar *pos, uchar *read_pos)
   DBUG_RETURN(0);
 }
 
-static bool setup_params_data(PREP_STMT *stmt)
+static bool setup_params_data(Prepared_statement *stmt)
 {                                       
-  THD *thd= stmt->thd;
-  List<Item> &params= thd->lex->param_list;
+  List<Item> &params= stmt->lex->param_list;
   List_iterator<Item> param_iterator(params);
   Item_param *param;
-  DBUG_ENTER("setup_params_data");
 
-  uchar *pos=(uchar*) thd->net.read_pos+1+MYSQL_STMT_HEADER; //skip header
+  uchar *pos= (uchar*) stmt->thd->net.read_pos + 1 +
+              MYSQL_STMT_HEADER;                //skip header
   uchar *read_pos= pos+(stmt->param_count+7) / 8; //skip null bits   
 
+  DBUG_ENTER("setup_params_data");
+
   if (*read_pos++) //types supplied / first execute
   {              
     /*
@@ -518,6 +507,91 @@ static bool setup_params_data(PREP_STMT *stmt)
   DBUG_RETURN(0);
 }
 
+#else
+
+bool setup_params_data(Prepared_statement *stmt)
+{                                       
+  List<Item> &params= stmt->lex->param_list;
+  List_iterator<Item> param_iterator(params);
+  Item_param *param;
+  MYSQL_BIND *client_param= stmt->thd->client_params;
+
+  DBUG_ENTER("setup_params_data");
+
+  for (;(param= (Item_param *)param_iterator++); client_param++)
+  {       
+    setup_param_functions(param, client_param->buffer_type);
+    if (!param->long_data_supplied)
+    {
+      if (*client_param->is_null)
+        param->maybe_null= param->null_value= 1;
+      else
+      {
+	uchar *buff= (uchar*)client_param->buffer;
+        param->maybe_null= param->null_value= 0;
+        param->setup_param_func(param,&buff, 
+				client_param->length ? 
+				*client_param->length : 
+				client_param->buffer_length);
+      }
+    }
+  }
+  DBUG_RETURN(0);
+}
+
+bool setup_params_data_withlog(Prepared_statement *stmt)
+{                                       
+  THD *thd= stmt->thd;
+  List<Item> &params= stmt->lex->param_list;
+  List_iterator<Item> param_iterator(params);
+  Item_param *param;
+  MYSQL_BIND *client_param= thd->client_params;
+
+  String str, query;
+  const String *res;
+
+  DBUG_ENTER("setup_params_data_withlog");
+
+  if (query.copy(stmt->query, stmt->query_length, default_charset_info))
+    DBUG_RETURN(1);
+  
+  uint32 length= 0;
+
+  for (;(param= (Item_param *)param_iterator++); client_param++)
+  {       
+    setup_param_functions(param, client_param->buffer_type);
+    if (param->long_data_supplied)
+      res= param->query_val_str(&str);       
+    else
+    {
+      if (*client_param->is_null)
+      {
+        param->maybe_null= param->null_value= 1;
+        res= &my_null_string;
+      }
+      else
+      {
+	uchar *buff= (uchar*)client_param->buffer;
+        param->maybe_null= param->null_value= 0;
+        param->setup_param_func(param,&buff,
+				client_param->length ? 
+				*client_param->length : 
+				client_param->buffer_length);
+        res= param->query_val_str(&str);
+      }
+    }
+    if (query.replace(param->pos_in_query+length, 1, *res))
+      DBUG_RETURN(1);
+    
+    length+= res->length()-1;
+  }
+  
+  if (alloc_query(thd, (char *) query.ptr(), query.length()+1))
+    DBUG_RETURN(1);
+
+  DBUG_RETURN(0);
+}
+
 #endif /*!EMBEDDED_LIBRARY*/
 
 /*
@@ -526,7 +600,7 @@ static bool setup_params_data(PREP_STMT *stmt)
     - fields count                          
 */
 
-static bool mysql_test_insert_fields(PREP_STMT *stmt,
+static bool mysql_test_insert_fields(Prepared_statement *stmt,
 				     TABLE_LIST *table_list,
 				     List<Item> &fields, 
 				     List<List_item> &values_list)
@@ -535,18 +609,18 @@ static bool mysql_test_insert_fields(PREP_STMT *stmt,
   TABLE *table;
   List_iterator_fast<List_item> its(values_list);
   List_item *values;
+
   DBUG_ENTER("mysql_test_insert_fields");
 
 #ifndef NO_EMBEDDED_ACCESS_CHECKS
-  my_bool update=(thd->lex->value_list.elements ? UPDATE_ACL : 0);
-  ulong privilege= (thd->lex->duplicates == DUP_REPLACE ?
+  my_bool update=(stmt->lex->value_list.elements ? UPDATE_ACL : 0);
+  ulong privilege= (stmt->lex->duplicates == DUP_REPLACE ?
                     INSERT_ACL | DELETE_ACL : INSERT_ACL | update);
-
   if (check_access(thd,privilege,table_list->db,
                    &table_list->grant.privilege,0,0) || 
       (grant_option && check_grant(thd,privilege,table_list,0,0)))
     DBUG_RETURN(1); 
-#endif  
+#endif
   if (open_and_lock_tables(thd, table_list))
     DBUG_RETURN(1); 
   table= table_list->table;
@@ -574,7 +648,7 @@ static bool mysql_test_insert_fields(PREP_STMT *stmt,
       }
     }
   }
-  if (send_prep_stmt(stmt, 0) || send_item_params(stmt))
+  if (send_prep_stmt(stmt, 0))
     DBUG_RETURN(1);
   DBUG_RETURN(0);
 }
@@ -589,13 +663,14 @@ static bool mysql_test_insert_fields(PREP_STMT *stmt,
   and return no fields information back to client.
 */
 
-static bool mysql_test_upd_fields(PREP_STMT *stmt, TABLE_LIST *table_list,
+static bool mysql_test_upd_fields(Prepared_statement *stmt,
+                                  TABLE_LIST *table_list,
 				  List<Item> &fields, List<Item> &values,
 				  COND *conds)
 {
   THD *thd= stmt->thd;
-  DBUG_ENTER("mysql_test_upd_fields");
 
+  DBUG_ENTER("mysql_test_upd_fields");
 #ifndef NO_EMBEDDED_ACCESS_CHECKS
   if (check_access(thd,UPDATE_ACL,table_list->db,
                    &table_list->grant.privilege,0,0) || 
@@ -613,7 +688,7 @@ static bool mysql_test_upd_fields(PREP_STMT *stmt, TABLE_LIST *table_list,
      Currently return only column list info only, and we are not
      sending any info on where clause.
   */
-  if (send_prep_stmt(stmt, 0) || send_item_params(stmt))
+  if (send_prep_stmt(stmt, 0))
     DBUG_RETURN(1);
   DBUG_RETURN(0);
 }
@@ -630,7 +705,9 @@ static bool mysql_test_upd_fields(PREP_STMT *stmt, TABLE_LIST *table_list,
                                                            
   And send column list fields info back to client. 
 */
-static bool mysql_test_select_fields(PREP_STMT *stmt, TABLE_LIST *tables,
+
+static bool mysql_test_select_fields(Prepared_statement *stmt,
+                                     TABLE_LIST *tables,
 				     uint wild_num,
                                      List<Item> &fields, COND *conds, 
                                      uint og_num, ORDER *order, ORDER *group,
@@ -640,8 +717,9 @@ static bool mysql_test_select_fields(PREP_STMT *stmt, TABLE_LIST *tables,
                                      SELECT_LEX *select_lex)
 {
   THD *thd= stmt->thd;
-  LEX *lex= &thd->main_lex;
-  select_result *result= thd->lex->result;
+  LEX *lex= stmt->lex;
+  select_result *result= lex->result;
+
   DBUG_ENTER("mysql_test_select_fields");
 
 #ifndef NO_EMBEDDED_ACCESS_CHECKS
@@ -663,12 +741,12 @@ static bool mysql_test_select_fields(PREP_STMT *stmt, TABLE_LIST *tables,
 
   if (lex->describe)
   {
-    if (send_prep_stmt(stmt, 0) ||  send_item_params(stmt))
+    if (send_prep_stmt(stmt, 0))
       DBUG_RETURN(1);      
-  }   
+  }
   else 
   {
-    fix_tables_pointers(thd->lex->all_selects_list);
+    fix_tables_pointers(lex->all_selects_list);
     if (!result && !(result= new select_send()))
     {
       send_error(thd, ER_OUT_OF_RESOURCES);
@@ -683,11 +761,11 @@ static bool mysql_test_select_fields(PREP_STMT *stmt, TABLE_LIST *tables,
                       select_lex, unit))
       DBUG_RETURN(1);
     if (send_prep_stmt(stmt, fields.elements) ||
-        thd->protocol_simple.send_fields(&fields, 0) ||
+        thd->protocol_simple.send_fields(&fields, 0)
 #ifndef EMBEDDED_LIBRARY
-        net_flush(&thd->net) ||
+         || net_flush(&thd->net)
 #endif
-        send_item_params(stmt))
+       )
       DBUG_RETURN(1);
     join->cleanup();
   }
@@ -699,19 +777,18 @@ static bool mysql_test_select_fields(PREP_STMT *stmt, TABLE_LIST *tables,
   Send the prepare query results back to client              
 */
                      
-static bool send_prepare_results(PREP_STMT *stmt)     
+static bool send_prepare_results(Prepared_statement *stmt)     
 {   
   THD *thd= stmt->thd;
-  LEX *lex= &thd->main_lex;
-  enum enum_sql_command sql_command= thd->lex->sql_command;
+  LEX *lex= stmt->lex;
+  enum enum_sql_command sql_command= lex->sql_command;
+
   DBUG_ENTER("send_prepare_results");
   DBUG_PRINT("enter",("command: %d, param_count: %ld",
                       sql_command, lex->param_count));
   
   /* Setup prepared stmt */
   stmt->param_count= lex->param_count;
-  stmt->free_list= thd->free_list;		// Save items used in stmt
-  thd->free_list= 0;
 
   SELECT_LEX *select_lex= &lex->select_lex;
   TABLE_LIST *tables=(TABLE_LIST*) select_lex->table_list.first;
@@ -768,57 +845,14 @@ abort:
   DBUG_RETURN(1);
 }
 
-/*
-  Parse the prepare query                                    
-*/
-
-static bool parse_prepare_query(PREP_STMT *stmt,
-		char *packet, uint length)
-{
-  bool error= 1;
-  THD *thd= stmt->thd;
-  DBUG_ENTER("parse_prepare_query");
-
-  mysql_log.write(thd,COM_PREPARE,"%s",packet);       
-  mysql_init_query(thd);   
-  LEX *lex=lex_start(thd, (uchar*) packet, length);
-  lex->safe_to_cache_query= 0;
-  thd->lex->param_count= 0;
-  if (!yyparse((void *)thd) && !thd->is_fatal_error) 
-    error= send_prepare_results(stmt);
-  lex_end(lex);
-  DBUG_RETURN(error);
-}
-
 /*
   Initialize parameter items in statement
 */
 
-static bool init_param_items(PREP_STMT *stmt)
+static bool init_param_items(Prepared_statement *stmt)
 {
-  THD *thd= stmt->thd;
-  List<Item> &params= thd->lex->param_list;
   Item_param **to;
-  uint32 length= thd->query_length;
  
-  stmt->lex=  thd->main_lex;
-
-  if (mysql_bin_log.is_open() || mysql_update_log.is_open())
-  {
-    stmt->log_full_query= 1;
-#ifndef EMBEDDED_LIBRARY
-    stmt->setup_params= insert_params_withlog;
-#else
-    stmt->setup_params_data= setup_params_data_withlog;
-#endif
-  }
-  else
-#ifndef EMBEDDED_LIBRARY
-    stmt->setup_params= insert_params; // not fully qualified query
-#else
-    stmt->setup_params_data= setup_params_data;
-#endif
-   
   if (!stmt->param_count)
     stmt->param= (Item_param **)0;
   else
@@ -828,44 +862,12 @@ static bool init_param_items(PREP_STMT *stmt)
                     MYF(MY_WME))))
       return 1;
 
-    if (stmt->log_full_query)
-    {
-      length= thd->query_length+(stmt->param_count*2)+1;
- 
-      if ( length < STMT_QUERY_LOG_LENGTH ) 
-        length= STMT_QUERY_LOG_LENGTH;
-    }
-    List_iterator<Item> param_iterator(params);
+    List_iterator<Item> param_iterator(stmt->lex->param_list);
     while ((*(to++)= (Item_param *)param_iterator++));
   }  
-  stmt->query= new String(length);
-  stmt->query->copy(thd->query, thd->query_length, default_charset_info);
   return 0;
 }
 
-/*
-  Initialize stmt execution
-*/
-
-static void init_stmt_execute(PREP_STMT *stmt)
-{
-  THD *thd= stmt->thd;
-  TABLE_LIST *tables= (TABLE_LIST*) thd->lex->select_lex.table_list.first;
-  
-  /*
-  TODO: When the new table structure is ready, then have a status bit 
-        to indicate the table is altered, and re-do the setup_* 
-        and open the tables back.
-  */  
-  for (; tables ; tables= tables->next)
-    tables->table= 0; //safety - nasty init
-  
-  if (!(stmt->log_full_query && stmt->param_count))
-  {
-    thd->query= stmt->query->c_ptr();
-    thd->query_length= stmt->query->length();
-  }
-}
 
 /*
   Parse the query and send the total number of parameters 
@@ -877,58 +879,73 @@ static void init_stmt_execute(PREP_STMT *stmt)
   If parameter markers are found in the query, then store    
   the information using Item_param along with maintaining a  
   list in lex->param_list, so that a fast and direct         
-  retrieveal can be made without going through all field     
+  retrieval can be made without going through all field     
   items.                                                     
 */
 
 bool mysql_stmt_prepare(THD *thd, char *packet, uint packet_length)
 {
-  MEM_ROOT thd_root= thd->mem_root;
-  PREP_STMT stmt;
-  SELECT_LEX *sl;
+  LEX *lex;
+  Prepared_statement *stmt= new Prepared_statement(thd);
+
   DBUG_ENTER("mysql_stmt_prepare");
 
-  bzero((char*) &stmt, sizeof(stmt));
-  
-  stmt.stmt_id= ++thd->current_stmt_id;
-  init_sql_alloc(&stmt.mem_root,
-		 thd->variables.query_alloc_block_size,
-		 thd->variables.query_prealloc_size);
-  
-  stmt.thd= thd;
-  stmt.thd->mem_root= stmt.mem_root;
+  if (stmt == 0)
+    DBUG_RETURN(0);
 
-  if (alloc_query(stmt.thd, packet, packet_length))
-    goto err;
+  if (thd->stmt_map.insert(stmt))
+    goto insert_stmt_err;
 
-  if (parse_prepare_query(&stmt, thd->query, thd->query_length))
-    goto err;
+  thd->stmt_backup.set_statement(thd);
+  thd->set_statement(stmt);
+
+  if (alloc_query(thd, packet, packet_length))
+    goto alloc_query_err;
+
+  mysql_log.write(thd, COM_PREPARE, "%s", packet);       
+
+  lex= lex_start(thd, (uchar *) thd->query, thd->query_length);
+  mysql_init_query(thd);
+  lex->safe_to_cache_query= 0;
+  lex->param_count= 0;
+
+  if (yyparse((void *)thd) || thd->is_fatal_error || send_prepare_results(stmt))
+    goto yyparse_err;
+
+  lex_end(lex);
 
   if (!(specialflag & SPECIAL_NO_PRIOR))
     my_pthread_setprio(pthread_self(),WAIT_PRIOR);
 
   // save WHERE clause pointers to avoid damaging they by optimisation
-  for (sl= thd->lex->all_selects_list;
+  for (SELECT_LEX *sl= thd->lex->all_selects_list;
        sl;
        sl= sl->next_select_in_list())
   {
     sl->prep_where= sl->where;
   }
 
-  
-  if (init_param_items(&stmt))
-    goto err;
+  stmt->set_statement(thd);
+  thd->set_statement(&thd->stmt_backup);
+
+  if (init_param_items(stmt))
+    goto init_param_err;
+
+  stmt->command= COM_EXECUTE;                   // set it only once here 
 
-  
-  stmt.mem_root= stmt.thd->mem_root;
-  tree_insert(&thd->prepared_statements, (void *)&stmt, 0, (void *)0);
-  thd->mem_root= thd_root; // restore main mem_root
   DBUG_RETURN(0);
 
-err:
-  stmt.mem_root= stmt.thd->mem_root;  
-  free_prep_stmt(&stmt, free_free, (void*) 0);
-  thd->mem_root= thd_root;	// restore main mem_root
+yyparse_err:
+  lex_end(lex);
+  stmt->set_statement(thd);
+  thd->set_statement(&thd->stmt_backup);
+init_param_err:
+alloc_query_err:
+  /* Statement map deletes statement on erase */
+  thd->stmt_map.erase(stmt);
+  DBUG_RETURN(1);
+insert_stmt_err:
+  delete stmt;
   DBUG_RETURN(1);
 }
 
@@ -936,7 +953,7 @@ err:
 /*
   Executes previously prepared query
 
-  If there is any parameters(thd->param_count), then replace 
+  If there is any parameters (stmt->param_count), then replace 
   markers with the data supplied from client, and then       
   execute the query                                            
 */
@@ -944,15 +961,12 @@ err:
 void mysql_stmt_execute(THD *thd, char *packet)
 {
   ulong stmt_id= uint4korr(packet);
-  PREP_STMT *stmt;
-  SELECT_LEX *sl;
-  DBUG_ENTER("mysql_stmt_execute");
+  Prepared_statement *stmt;
 
-  if (!(stmt=find_prepared_statement(thd, stmt_id, "execute")))
-  {
-    send_error(thd);
+  DBUG_ENTER("mysql_stmt_execute");
+  
+  if (!(stmt= find_prepared_statement(thd, stmt_id, "execute")))
     DBUG_VOID_RETURN;
-  }
 
   /* Check if we got an error when sending long data */
   if (stmt->error_in_prepare)
@@ -961,10 +975,28 @@ void mysql_stmt_execute(THD *thd, char *packet)
     DBUG_VOID_RETURN;
   }
 
-  LEX thd_lex= thd->main_lex;
-  thd->main_lex= stmt->lex;
-  
-  for (sl= stmt->lex.all_selects_list;
+  /*
+    XXX: while thd->query_id is incremented for each command, stmt->query_id
+    holds query_id of prepare stage. Keeping old query_id seems to be more
+    natural, but differs from the way prepared statements work in 4.1:
+  */ 
+  /* stmt->query_id= thd->query_id; */
+  thd->stmt_backup.set_statement(thd);
+  thd->set_statement(stmt);
+
+  /*
+    To make sure that all runtime data is stored in its own memory root and 
+    does not interfere with data possibly present in thd->mem_root.
+    This root is cleaned up in the end of execution.
+    FIXME: to be replaced with more efficient approach, and verified why we
+    can not use thd->mem_root safely.
+  */
+  init_sql_alloc(&thd->mem_root,
+                 thd->variables.query_alloc_block_size,
+                 thd->variables.query_prealloc_size);
+
+
+  for (SELECT_LEX *sl= stmt->lex->all_selects_list;
        sl;
        sl= sl->next_select_in_list())
   {
@@ -975,7 +1007,16 @@ void mysql_stmt_execute(THD *thd, char *packet)
       sl->where= sl->prep_where->copy_andor_structure(thd);
     DBUG_ASSERT(sl->join == 0);
   }
-  init_stmt_execute(stmt);
+
+  /*
+    TODO: When the new table structure is ready, then have a status bit 
+    to indicate the table is altered, and re-do the setup_* 
+    and open the tables back.
+  */
+  for (TABLE_LIST *tables= (TABLE_LIST*) stmt->lex->select_lex.table_list.first;
+       tables;
+       tables= tables->next)
+    tables->table= 0; // safety - nasty init
 
 #ifndef EMBEDDED_LIBRARY
   if (stmt->param_count && setup_params_data(stmt))
@@ -1001,7 +1042,8 @@ void mysql_stmt_execute(THD *thd, char *packet)
   if (!(specialflag & SPECIAL_NO_PRIOR))
     my_pthread_setprio(pthread_self(), WAIT_PRIOR);
 
-  thd->main_lex= thd_lex;
+  free_root(&thd->mem_root, MYF(0));
+  thd->set_statement(&thd->stmt_backup);
   DBUG_VOID_RETURN;
 }
 
@@ -1023,14 +1065,12 @@ void mysql_stmt_execute(THD *thd, char *packet)
 void mysql_stmt_reset(THD *thd, char *packet)
 {
   ulong stmt_id= uint4korr(packet);
-  PREP_STMT *stmt;
+  Prepared_statement *stmt;
+  
   DBUG_ENTER("mysql_stmt_reset");
 
   if (!(stmt= find_prepared_statement(thd, stmt_id, "reset")))
-  {
-    send_error(thd);
     DBUG_VOID_RETURN;
-  }
 
   stmt->error_in_prepare= 0;
   Item_param *item= *stmt->param, *end= item + stmt->param_count;
@@ -1053,15 +1093,15 @@ void mysql_stmt_reset(THD *thd, char *packet)
 void mysql_stmt_free(THD *thd, char *packet)
 {
   ulong stmt_id= uint4korr(packet);
+  Prepared_statement *stmt;
+
   DBUG_ENTER("mysql_stmt_free");
 
-  if (!find_prepared_statement(thd, stmt_id, "close"))
-  {
-    send_error(thd); // Not seen by the client
+  if (!(stmt= find_prepared_statement(thd, stmt_id, "close")))
     DBUG_VOID_RETURN;
-  }
-  tree_delete(&thd->prepared_statements, (void*) &stmt_id, (void *)0);
-  thd->last_prepared_stmt= (PREP_STMT *)0;
+
+  /* Statement map deletes statement on erase */
+  thd->stmt_map.erase(stmt);
   DBUG_VOID_RETURN;
 }
 
@@ -1087,7 +1127,8 @@ void mysql_stmt_free(THD *thd, char *packet)
 
 void mysql_stmt_get_longdata(THD *thd, char *pos, ulong packet_length)
 {
-  PREP_STMT *stmt;
+  Prepared_statement *stmt;
+  
   DBUG_ENTER("mysql_stmt_get_longdata");
 
 #ifndef EMBEDDED_LIBRARY
@@ -1103,14 +1144,7 @@ void mysql_stmt_get_longdata(THD *thd, char *pos, ulong packet_length)
   uint param_number= uint2korr(pos+4);
 
   if (!(stmt=find_prepared_statement(thd, stmt_id, "get_longdata")))
-  {
-    /*
-      There is a chance that the client will never see this as
-      it doesn't expect an answer from this call...
-    */
-    send_error(thd);
     DBUG_VOID_RETURN;
-  }
 
 #ifndef EMBEDDED_LIBRARY
   if (param_number >= stmt->param_count)
@@ -1134,3 +1168,46 @@ void mysql_stmt_get_longdata(THD *thd, char *pos, ulong packet_length)
   DBUG_VOID_RETURN;
 }
 
+
+Prepared_statement::Prepared_statement(THD *thd_arg)
+  :Statement(thd_arg),
+  thd(thd_arg),
+  param(0),
+  param_count(0),
+  last_errno(0),
+  error_in_prepare(0),
+  long_data_used(0),
+  log_full_query(0)
+{
+  *last_error= '\0';
+  if (mysql_bin_log.is_open())
+  {
+    log_full_query= 1;
+#ifndef EMBEDDED_LIBRARY
+    setup_params= insert_params_withlog;
+#else
+    setup_params_data= setup_params_data_withlog;
+#endif
+  }
+  else
+#ifndef EMBEDDED_LIBRARY
+    setup_params= insert_params; // not fully qualified query
+#else
+    setup_params_data= setup_params_data;
+#endif
+}
+
+
+Prepared_statement::~Prepared_statement()
+{
+  my_free((char *) param, MYF(MY_ALLOW_ZERO_PTR));
+  free_items(free_list);
+}
+
+
+Statement::Type Prepared_statement::type() const
+{
+  return PREPARED_STATEMENT;
+}
+
+
diff --git a/tests/client_test.c b/tests/client_test.c
index 464d5b632ae..66637dcb04b 100644
--- a/tests/client_test.c
+++ b/tests/client_test.c
@@ -7350,7 +7350,7 @@ static void test_fetch_column()
   rc = mysql_query(mysql, "insert into test_column(c2) values('venu'),('mysql')");
   myquery(rc);
 
-  stmt = mysql_prepare(mysql,"select * from test_column",50);
+  stmt = mysql_prepare(mysql,"select * from test_column order by c2 desc", 50);
   mystmt_init(stmt);
 
   bind[0].buffer_type= MYSQL_TYPE_LONG;

From 34c03bdf99f5e69c80ae1e1fd5a0b618d0e7df3d Mon Sep 17 00:00:00 2001
From: "konstantin@oak.local" <>
Date: Sat, 20 Dec 2003 03:06:33 +0300
Subject: [PATCH 2/9] one line was removed during merge

---
 sql/sql_delete.cc | 1 +
 1 file changed, 1 insertion(+)

diff --git a/sql/sql_delete.cc b/sql/sql_delete.cc
index 78512f705a9..a8b13288bf3 100644
--- a/sql/sql_delete.cc
+++ b/sql/sql_delete.cc
@@ -131,6 +131,7 @@ int mysql_delete(THD *thd, TABLE_LIST *table_list, COND *conds, SQL_LIST *order,
     table->sort.io_cache = (IO_CACHE *) my_malloc(sizeof(IO_CACHE),
                                              MYF(MY_FAE | MY_ZEROFILL));
       if (thd->lex->select_lex.setup_ref_array(thd, order->elements) ||
+          setup_order(thd, thd->lex->select_lex.ref_pointer_array, &tables,
 		      fields, all_fields, (ORDER*) order->first) ||
 	  !(sortorder=make_unireg_sortorder((ORDER*) order->first, &length)) ||
 	  (table->sort.found_records = filesort(thd, table, sortorder, length,

From 0448a3f4c01fdbc1d3ae0c26dddba7874b652394 Mon Sep 17 00:00:00 2001
From: "monty@mysql.com" <>
Date: Sat, 20 Dec 2003 03:41:04 +0200
Subject: [PATCH 3/9] Add cast of integer/longlong to (ulong) to make
 printf/sprintf 64 bit safe A after merge fix for last merge

---
 innobase/btr/btr0btr.c    |  13 ++--
 innobase/btr/btr0sea.c    |  22 ++++---
 innobase/buf/buf0buf.c    | 125 ++++++++++++++++++++------------------
 innobase/buf/buf0flu.c    |  12 ++--
 innobase/buf/buf0lru.c    |  44 ++++++++------
 innobase/buf/buf0rea.c    |  24 +++++---
 innobase/com/com0shm.c    |   5 +-
 innobase/data/data0data.c |  18 +++---
 innobase/data/data0type.c |   6 +-
 innobase/dict/dict0crea.c |  23 +++----
 innobase/dict/dict0dict.c |  27 ++++----
 innobase/fil/fil0fil.c    | 106 ++++++++++++++++++--------------
 innobase/fsp/fsp0fsp.c    |  48 ++++++++-------
 innobase/fut/fut0lst.c    |   5 +-
 innobase/ha/ha0ha.c       |   7 ++-
 innobase/ibuf/ibuf0ibuf.c |  30 +++++----
 innobase/include/univ.i   |   3 +-
 innobase/lock/lock0lock.c |  55 +++++++++--------
 innobase/log/log0log.c    |  89 ++++++++++++++-------------
 innobase/log/log0recv.c   | 118 ++++++++++++++++++-----------------
 innobase/mem/mem0dbg.c    |  30 ++++-----
 innobase/mem/mem0pool.c   |  17 +++---
 innobase/mtr/mtr0log.c    |   8 +--
 innobase/mtr/mtr0mtr.c    |  10 +--
 innobase/os/os0file.c     |  47 +++++++-------
 innobase/os/os0sync.c     |   6 +-
 innobase/page/page0cur.c  |   6 +-
 innobase/page/page0page.c | 118 ++++++++++++++++++-----------------
 innobase/read/read0read.c |  16 ++---
 innobase/rem/rem0cmp.c    |   3 +-
 innobase/rem/rem0rec.c    |  22 ++++---
 innobase/row/row0mysql.c  |  29 +++++----
 innobase/row/row0sel.c    |  31 +++++-----
 innobase/row/row0undo.c   |   3 +-
 innobase/srv/srv0srv.c    |  59 +++++++++---------
 innobase/srv/srv0start.c  |  52 ++++++++--------
 innobase/sync/sync0arr.c  |  35 ++++++-----
 innobase/sync/sync0rw.c   |  21 ++++---
 innobase/sync/sync0sync.c |  30 +++++----
 innobase/trx/trx0purge.c  |  25 ++++----
 innobase/trx/trx0rec.c    |  36 +++++------
 innobase/trx/trx0roll.c   |  26 ++++----
 innobase/trx/trx0sys.c    |  24 ++++----
 innobase/trx/trx0trx.c    |  24 ++++----
 innobase/trx/trx0undo.c   |  15 +++--
 innobase/usr/usr0sess.c   |   4 +-
 innobase/ut/ut0mem.c      |  14 +++--
 innobase/ut/ut0ut.c       |  10 +--
 sql/sql_delete.cc         |   1 +
 49 files changed, 816 insertions(+), 686 deletions(-)

diff --git a/innobase/btr/btr0btr.c b/innobase/btr/btr0btr.c
index 686c35d1300..eb18fecb368 100644
--- a/innobase/btr/btr0btr.c
+++ b/innobase/btr/btr0btr.c
@@ -2217,7 +2217,8 @@ btr_print_recursive(
 	ut_ad(mtr_memo_contains(mtr, buf_block_align(page),
 							MTR_MEMO_PAGE_X_FIX));
 	printf("NODE ON LEVEL %lu page number %lu\n",
-		btr_page_get_level(page, mtr), buf_frame_get_page_no(page));
+	       (ulong) btr_page_get_level(page, mtr),
+	       (ulong) buf_frame_get_page_no(page));
 	
 	page_print(page, width, width);
 	
@@ -2513,8 +2514,8 @@ loop:
 	if (!page_validate(page, index)) {
 		fprintf(stderr,
 "InnoDB: Error in page %lu in index %s table %s, index tree level %lu\n",
-			buf_frame_get_page_no(page), index->name,
-			index->table_name, level);
+			(ulong) buf_frame_get_page_no(page), index->name,
+			index->table_name, (ulong) level);
 
 		ret = FALSE;
 	} else if (level == 0) {
@@ -2546,8 +2547,8 @@ loop:
 
  			fprintf(stderr,
 		"InnoDB: Error on pages %lu and %lu in index %s table %s\n",
-				buf_frame_get_page_no(page),
-				(unsigned long) right_page_no,
+				(ulong) buf_frame_get_page_no(page),
+				(ulong) right_page_no,
 				index->name, index->table_name);
 
 			fprintf(stderr,
@@ -2630,7 +2631,7 @@ loop:
 
 	 			fprintf(stderr,
 			"InnoDB: Error on page %lu in index %s table %s\n",
-					buf_frame_get_page_no(page),
+					(ulong) buf_frame_get_page_no(page),
 					index->name, index->table_name);
 
 				buf_page_print(father_page);
diff --git a/innobase/btr/btr0sea.c b/innobase/btr/btr0sea.c
index e49ee15f5ea..207ebcfb641 100644
--- a/innobase/btr/btr0sea.c
+++ b/innobase/btr/btr0sea.c
@@ -1532,11 +1532,11 @@ btr_search_index_print_info(
 	info = btr_search_get_info(index);
 
 	printf("Searches %lu, hash succ %lu, fail %lu, patt succ %lu\n",
-		info->n_searches, info->n_hash_succ, info->n_hash_fail,
-		info->n_patt_succ);
+	       (ulong) info->n_searches, (ulong) info->n_hash_succ,
+	       (ulong) info->n_hash_fail, (ulong) info->n_patt_succ);
 
 	printf("Total of page cur short succ for all indexes %lu\n",
-							page_cur_short_succ);
+	       (ulong) page_cur_short_succ);
 	rw_lock_x_unlock(&btr_search_latch);
 }
 
@@ -1604,11 +1604,12 @@ btr_search_validate(void)
 				fprintf(stderr,
 "  InnoDB: Error in an adaptive hash index pointer to page %lu\n"
 "ptr mem address %lu index id %lu %lu, node fold %lu, rec fold %lu\n",
-				buf_frame_get_page_no(page),
-				(ulint)(node->data),
-			ut_dulint_get_high(btr_page_get_index_id(page)),
-			ut_dulint_get_low(btr_page_get_index_id(page)),
-			node->fold, rec_fold((rec_t*)(node->data),
+				(ulong) buf_frame_get_page_no(page),
+				(ulong)(node->data),
+			(ulong) ut_dulint_get_high(btr_page_get_index_id(page)),
+			(ulong) ut_dulint_get_low(btr_page_get_index_id(page)),
+			(ulong) node->fold,
+			(ulong) rec_fold((rec_t*)(node->data),
 					block->curr_n_fields,
 					block->curr_n_bytes,
 					btr_page_get_index_id(page)));
@@ -1622,8 +1623,9 @@ btr_search_validate(void)
 				fprintf(stderr,
 "Page mem address %lu, is hashed %lu, n fields %lu, n bytes %lu\n"
 "side %lu\n",
-			(ulint)page, block->is_hashed, block->curr_n_fields,
-			block->curr_n_bytes, block->curr_side);
+			(ulong) page, (ulong) block->is_hashed,
+			(ulong) block->curr_n_fields,
+			(ulong) block->curr_n_bytes, (ulong) block->curr_side);
 
 				if (n_page_dumps < 20) {	
 					buf_page_print(page);
diff --git a/innobase/buf/buf0buf.c b/innobase/buf/buf0buf.c
index 946020acd11..cbf12c9e55d 100644
--- a/innobase/buf/buf0buf.c
+++ b/innobase/buf/buf0buf.c
@@ -321,13 +321,13 @@ buf_page_is_corrupted(
 "  InnoDB: Error: page %lu log sequence number %lu %lu\n"
 "InnoDB: is in the future! Current system log sequence number %lu %lu.\n"
 "InnoDB: Your database may be corrupt.\n",
-		        mach_read_from_4(read_buf + FIL_PAGE_OFFSET),
-			ut_dulint_get_high(
+		        (ulong) mach_read_from_4(read_buf + FIL_PAGE_OFFSET),
+			(ulong) ut_dulint_get_high(
 				mach_read_from_8(read_buf + FIL_PAGE_LSN)),
-			ut_dulint_get_low(
+			(ulong) ut_dulint_get_low(
 				mach_read_from_8(read_buf + FIL_PAGE_LSN)),
-			ut_dulint_get_high(current_lsn),
-			ut_dulint_get_low(current_lsn));
+			(ulong) ut_dulint_get_high(current_lsn),
+			(ulong) ut_dulint_get_low(current_lsn));
 		}
 	}
 #endif
@@ -381,7 +381,7 @@ buf_page_print(
 	ut_print_timestamp(stderr);
 	fprintf(stderr,
 "  InnoDB: Page dump in ascii and hex (%lu bytes):\n%s",
-					(ulint)UNIV_PAGE_SIZE, buf);
+					(ulong) UNIV_PAGE_SIZE, buf);
 	fprintf(stderr, "InnoDB: End of page dump\n");
 
 	mem_free(buf);
@@ -393,20 +393,20 @@ buf_page_print(
 	fprintf(stderr, 
 "  InnoDB: Page checksum %lu, prior-to-4.0.14-form checksum %lu\n"
 "InnoDB: stored checksum %lu, prior-to-4.0.14-form stored checksum %lu\n",
-			checksum, old_checksum,
-			mach_read_from_4(read_buf + FIL_PAGE_SPACE_OR_CHKSUM),
-			mach_read_from_4(read_buf + UNIV_PAGE_SIZE
+			(ulong) checksum, (ulong) old_checksum,
+			(ulong) mach_read_from_4(read_buf + FIL_PAGE_SPACE_OR_CHKSUM),
+			(ulong) mach_read_from_4(read_buf + UNIV_PAGE_SIZE
 					- FIL_PAGE_END_LSN_OLD_CHKSUM));
 	fprintf(stderr,
 "InnoDB: Page lsn %lu %lu, low 4 bytes of lsn at page end %lu\n"
 "InnoDB: Page number (if stored to page already) %lu,\n"
 "InnoDB: space id (if created with >= MySQL-4.1.1 and stored already) %lu\n",
-		mach_read_from_4(read_buf + FIL_PAGE_LSN),
-		mach_read_from_4(read_buf + FIL_PAGE_LSN + 4),
-		mach_read_from_4(read_buf + UNIV_PAGE_SIZE
+		(ulong) mach_read_from_4(read_buf + FIL_PAGE_LSN),
+		(ulong) mach_read_from_4(read_buf + FIL_PAGE_LSN + 4),
+		(ulong) mach_read_from_4(read_buf + UNIV_PAGE_SIZE
 					- FIL_PAGE_END_LSN_OLD_CHKSUM + 4),
-		mach_read_from_4(read_buf + FIL_PAGE_OFFSET),
-		mach_read_from_4(read_buf + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID));
+		(ulong) mach_read_from_4(read_buf + FIL_PAGE_OFFSET),
+		(ulong) mach_read_from_4(read_buf + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID));
 
 	if (mach_read_from_2(read_buf + TRX_UNDO_PAGE_HDR + TRX_UNDO_PAGE_TYPE)
 	    == TRX_UNDO_INSERT) {
@@ -422,8 +422,8 @@ buf_page_print(
 	if (fil_page_get_type(read_buf) == FIL_PAGE_INDEX) {
 	    	fprintf(stderr,
 "InnoDB: Page may be an index page where index id is %lu %lu\n",
-			ut_dulint_get_high(btr_page_get_index_id(read_buf)),
-			ut_dulint_get_low(btr_page_get_index_id(read_buf)));
+			(ulong) ut_dulint_get_high(btr_page_get_index_id(read_buf)),
+			(ulong) ut_dulint_get_low(btr_page_get_index_id(read_buf)));
 
 		/* If the code is in ibbackup, dict_sys may be uninitialized,
 		i.e., NULL */
@@ -513,7 +513,7 @@ buf_pool_init(
 	        fprintf(stderr,
 "InnoDB: AWE: Error: you must specify in my.cnf .._awe_mem_mb larger\n"
 "InnoDB: than .._buffer_pool_size. Now the former is %lu pages,\n"
-"InnoDB: the latter %lu pages.\n", curr_size, n_frames);
+"InnoDB: the latter %lu pages.\n", (ulong) curr_size, (ulong) n_frames);
 
 		return(NULL);
 	}
@@ -543,7 +543,7 @@ buf_pool_init(
 		        fprintf(stderr,
 "InnoDB: AWE: Error: physical memory must be allocated in full megabytes.\n"
 "InnoDB: Trying to allocate %lu database pages.\n", 
-			  curr_size);
+			  (ulong) curr_size);
 
 		        return(NULL);
 		}
@@ -780,7 +780,7 @@ buf_awe_map_page_to_frame(
 	fprintf(stderr,
 "InnoDB: AWE: Fatal error: cannot find a page to unmap\n"
 "InnoDB: awe_LRU_free_mapped list length %lu\n",
-		UT_LIST_GET_LEN(buf_pool->awe_LRU_free_mapped));
+		(ulong) UT_LIST_GET_LEN(buf_pool->awe_LRU_free_mapped));
 
 	ut_a(0);
 }
@@ -1546,8 +1546,9 @@ buf_page_init(
 
         if (buf_page_hash_get(space, offset)) {
                 fprintf(stderr,
-"InnoDB: Error: page %lu %lu already found from the hash table\n", space,
-							offset);
+"InnoDB: Error: page %lu %lu already found from the hash table\n",
+			(ulong) space,
+			(ulong) offset);
                 buf_print();
                 buf_LRU_print();
                 buf_validate();
@@ -1730,8 +1731,9 @@ buf_page_create(
 	/* If we get here, the page was not in buf_pool: init it there */
 
 	if (buf_debug_prints) {
-		printf("Creating space %lu page %lu to buffer\n", space,
-								offset);
+		printf("Creating space %lu page %lu to buffer\n",
+		       (ulong) space,
+		       (ulong) offset);
 	}
 
 	block = free_block;
@@ -1809,7 +1811,7 @@ buf_page_io_complete(
 
 			fprintf(stderr,
 "InnoDB: Error: page n:o stored in the page read in is %lu, should be %lu!\n",
-				read_page_no, block->offset);
+				(ulong) read_page_no, (ulong) block->offset);
 		}
 #ifdef notdefined
 		if (block->offset != 0 && read_page_no == 0) {
@@ -1832,7 +1834,7 @@ buf_page_io_complete(
 		if (buf_page_is_corrupted(block->frame)) {
 		  	fprintf(stderr,
 		"InnoDB: Database page corruption on disk or a failed\n"
-		"InnoDB: file read of page %lu.\n", block->offset);
+		"InnoDB: file read of page %lu.\n", (ulong) block->offset);
 			  
 		  	fprintf(stderr,
 		"InnoDB: You may have to recover from a backup.\n");
@@ -1841,7 +1843,7 @@ buf_page_io_complete(
 
 		  	fprintf(stderr,
 		"InnoDB: Database page corruption on disk or a failed\n"
-		"InnoDB: file read of page %lu.\n", block->offset);
+		"InnoDB: file read of page %lu.\n", (ulong) block->offset);
 		  	fprintf(stderr,
 		"InnoDB: You may have to recover from a backup.\n");
 			fprintf(stderr,
@@ -1922,8 +1924,8 @@ buf_page_io_complete(
 	mutex_exit(&(buf_pool->mutex));
 
 	if (buf_debug_prints) {
-		printf("page space %lu page no %lu", block->space,
-								block->offset);
+		printf("page space %lu page no %lu", (ulong) block->space,
+						     (ulong) block->offset);
 		id = btr_page_get_index_id(block->frame);
 
 		index = NULL;
@@ -2038,14 +2040,16 @@ buf_validate(void)
  	}
 
 	if (n_lru + n_free > buf_pool->curr_size) {
-		printf("n LRU %lu, n free %lu\n", n_lru, n_free);
+		printf("n LRU %lu, n free %lu\n", (ulong) n_lru,
+		       (ulong) n_free);
 		ut_error;
 	}
 
 	ut_a(UT_LIST_GET_LEN(buf_pool->LRU) == n_lru);
 	if (UT_LIST_GET_LEN(buf_pool->free) != n_free) {
 		printf("Free list len %lu, free blocks %lu\n",
-		    UT_LIST_GET_LEN(buf_pool->free), n_free);
+		       (ulong) UT_LIST_GET_LEN(buf_pool->free),
+		       (ulong) n_free);
 		ut_error;
 	}
 	ut_a(UT_LIST_GET_LEN(buf_pool->flush_list) == n_flush);
@@ -2088,22 +2092,23 @@ buf_print(void)
 
 	mutex_enter(&(buf_pool->mutex));
 	
-	printf("buf_pool size %lu \n", size);
-	printf("database pages %lu \n", UT_LIST_GET_LEN(buf_pool->LRU));
-	printf("free pages %lu \n", UT_LIST_GET_LEN(buf_pool->free));
+	printf("buf_pool size %lu \n", (ulong) size);
+	printf("database pages %lu \n", (ulong) UT_LIST_GET_LEN(buf_pool->LRU));
+	printf("free pages %lu \n", (ulong) UT_LIST_GET_LEN(buf_pool->free));
 	printf("modified database pages %lu \n",
-				UT_LIST_GET_LEN(buf_pool->flush_list));
+				(ulong) UT_LIST_GET_LEN(buf_pool->flush_list));
 
-	printf("n pending reads %lu \n", buf_pool->n_pend_reads);
+	printf("n pending reads %lu \n", (ulong) buf_pool->n_pend_reads);
 
 	printf("n pending flush LRU %lu list %lu single page %lu\n",
-		buf_pool->n_flush[BUF_FLUSH_LRU],
-		buf_pool->n_flush[BUF_FLUSH_LIST],
-		buf_pool->n_flush[BUF_FLUSH_SINGLE_PAGE]);
+	       (ulong) buf_pool->n_flush[BUF_FLUSH_LRU],
+	       (ulong) buf_pool->n_flush[BUF_FLUSH_LIST],
+	       (ulong) buf_pool->n_flush[BUF_FLUSH_SINGLE_PAGE]);
 
 	printf("pages read %lu, created %lu, written %lu\n",
-			buf_pool->n_pages_read, buf_pool->n_pages_created,
-						buf_pool->n_pages_written);
+	       (ulong) buf_pool->n_pages_read,
+	       (ulong) buf_pool->n_pages_created,
+	       (ulong) buf_pool->n_pages_written);
 
 	/* Count the number of blocks belonging to each index in the buffer */
 	
@@ -2147,7 +2152,8 @@ buf_print(void)
 		index = dict_index_get_if_in_cache(index_ids[i]);
 
 		printf("Block count for index %lu in buffer is about %lu",
-			ut_dulint_get_low(index_ids[i]), counts[i]);
+		       (ulong) ut_dulint_get_low(index_ids[i]),
+		       (ulong) counts[i]);
 
 		if (index) {
 			printf(" index name %s table %s", index->name,
@@ -2224,39 +2230,39 @@ buf_print_io(
 	mutex_enter(&(buf_pool->mutex));
 	
 	buf += sprintf(buf,
-		"Buffer pool size   %lu\n", size);
+		"Buffer pool size   %lu\n", (ulong) size);
 	buf += sprintf(buf,
-		"Free buffers       %lu\n", UT_LIST_GET_LEN(buf_pool->free));
+		"Free buffers       %lu\n", (ulong) UT_LIST_GET_LEN(buf_pool->free));
 	buf += sprintf(buf,
-		"Database pages     %lu\n", UT_LIST_GET_LEN(buf_pool->LRU));
+		"Database pages     %lu\n", (ulong) UT_LIST_GET_LEN(buf_pool->LRU));
 /*
 	buf += sprintf(buf,
-		"Lock heap buffers  %lu\n", buf_pool->n_lock_heap_pages);
+		"Lock heap buffers  %lu\n", (ulong) buf_pool->n_lock_heap_pages);
 	buf += sprintf(buf,
-		"Hash index buffers %lu\n", buf_pool->n_adaptive_hash_pages);
+		"Hash index buffers %lu\n", (ulong) buf_pool->n_adaptive_hash_pages);
 */
 	buf += sprintf(buf,
 		"Modified db pages  %lu\n",
-				UT_LIST_GET_LEN(buf_pool->flush_list));
+				(ulong) UT_LIST_GET_LEN(buf_pool->flush_list));
 	if (srv_use_awe) {
 		buf += sprintf(buf,
 		"AWE: Buffer pool memory frames                        %lu\n",
-				buf_pool->n_frames);
+				(ulong) buf_pool->n_frames);
 		
 		buf += sprintf(buf,
 		"AWE: Database pages and free buffers mapped in frames %lu\n",
-				UT_LIST_GET_LEN(buf_pool->awe_LRU_free_mapped));
+				(ulong) UT_LIST_GET_LEN(buf_pool->awe_LRU_free_mapped));
 	}
 
-	buf += sprintf(buf, "Pending reads %lu \n", buf_pool->n_pend_reads);
+	buf += sprintf(buf, "Pending reads %lu \n", (ulong) buf_pool->n_pend_reads);
 
 	buf += sprintf(buf,
 		"Pending writes: LRU %lu, flush list %lu, single page %lu\n",
-		buf_pool->n_flush[BUF_FLUSH_LRU]
-				+ buf_pool->init_flush[BUF_FLUSH_LRU],
-		buf_pool->n_flush[BUF_FLUSH_LIST]
-				+ buf_pool->init_flush[BUF_FLUSH_LIST],
-		buf_pool->n_flush[BUF_FLUSH_SINGLE_PAGE]);
+		(ulong) (buf_pool->n_flush[BUF_FLUSH_LRU]
+				+ buf_pool->init_flush[BUF_FLUSH_LRU]),
+		(ulong) (buf_pool->n_flush[BUF_FLUSH_LIST]
+				+ buf_pool->init_flush[BUF_FLUSH_LIST]),
+		(ulong) buf_pool->n_flush[BUF_FLUSH_SINGLE_PAGE]);
 
 	current_time = time(NULL);
 	time_elapsed = 0.001 + difftime(current_time,
@@ -2264,8 +2270,9 @@ buf_print_io(
 	buf_pool->last_printout_time = current_time;
 
 	buf += sprintf(buf, "Pages read %lu, created %lu, written %lu\n",
-			buf_pool->n_pages_read, buf_pool->n_pages_created,
-						buf_pool->n_pages_written);
+		       (ulong) buf_pool->n_pages_read,
+		       (ulong) buf_pool->n_pages_created,
+		       (ulong) buf_pool->n_pages_written);
 	buf += sprintf(buf, "%.2f reads/s, %.2f creates/s, %.2f writes/s\n",
 		(buf_pool->n_pages_read - buf_pool->n_pages_read_old)
 		/ time_elapsed,
@@ -2283,10 +2290,10 @@ buf_print_io(
 		
 	if (buf_pool->n_page_gets > buf_pool->n_page_gets_old) {
 		buf += sprintf(buf, "Buffer pool hit rate %lu / 1000\n",
-		1000
+       (ulong) (1000
 		- ((1000 *
 		    (buf_pool->n_pages_read - buf_pool->n_pages_read_old))
-		/ (buf_pool->n_page_gets - buf_pool->n_page_gets_old)));
+		/ (buf_pool->n_page_gets - buf_pool->n_page_gets_old))));
 	} else {
 		buf += sprintf(buf,
 			"No buffer pool page gets since the last printout\n");
diff --git a/innobase/buf/buf0flu.c b/innobase/buf/buf0flu.c
index 27a1829942d..cdea764971e 100644
--- a/innobase/buf/buf0flu.c
+++ b/innobase/buf/buf0flu.c
@@ -246,7 +246,7 @@ buf_flush_buffered_writes(void)
 	"InnoDB: to be written to data file. We intentionally crash server\n"
 	"InnoDB: to prevent corrupt data from ending up in data\n"
 	"InnoDB: files.\n",
-			block->offset, block->space);
+			(ulong) block->offset, (ulong) block->space);
 
 			ut_a(0);
 		}
@@ -504,7 +504,8 @@ buf_flush_try_page(
 
 		if (buf_debug_prints) {
 			printf("Flushing page space %lu, page no %lu \n",
-					block->space, block->offset);
+			       (ulong) block->space,
+			       (ulong) block->offset);
 		}
 
 		buf_flush_write_block_low(block);
@@ -592,7 +593,8 @@ buf_flush_try_page(
 		if (buf_debug_prints) {
 			printf(
 			"Flushing single page space %lu, page no %lu \n",
-						block->space, block->offset);
+						(ulong) block->space,
+			                        (ulong) block->offset);
 		}
 
 		buf_flush_write_block_low(block);
@@ -823,10 +825,10 @@ buf_flush_batch(
 	if (buf_debug_prints && page_count > 0) {
 		if (flush_type == BUF_FLUSH_LRU) {
 			printf("Flushed %lu pages in LRU flush\n",
-						page_count);
+						(ulong) page_count);
 		} else if (flush_type == BUF_FLUSH_LIST) {
 			printf("Flushed %lu pages in flush list flush\n",
-						page_count);
+						(ulong) page_count);
 		} else {
 			ut_error;
 		}
diff --git a/innobase/buf/buf0lru.c b/innobase/buf/buf0lru.c
index 55a5ecbeba5..23f399503c8 100644
--- a/innobase/buf/buf0lru.c
+++ b/innobase/buf/buf0lru.c
@@ -100,7 +100,8 @@ scan_again:
 			if (buf_debug_prints) {
 				printf(
 				"Dropping space %lu page %lu\n",
-					block->space, block->offset);
+					(ulong) block->space,
+				        (ulong) block->offset);
 			}
 
 			if (block->is_hashed) {
@@ -209,7 +210,8 @@ buf_LRU_search_and_free_block(
 			if (buf_debug_prints) {
 				printf(
 				"Putting space %lu page %lu to free list\n",
-					block->space, block->offset);
+					(ulong) block->space,
+				        (ulong) block->offset);
 			}
 			buf_LRU_block_remove_hashed_page(block);
 
@@ -329,7 +331,7 @@ loop:
 "InnoDB: the buffer pool bigger?\n"
 "InnoDB: Starting the InnoDB Monitor to print diagnostics, including\n"
 "InnoDB: lock heap and hash index sizes.\n",
-		buf_pool->curr_size / (1024 * 1024 / UNIV_PAGE_SIZE));
+			(ulong) (buf_pool->curr_size / (1024 * 1024 / UNIV_PAGE_SIZE)));
 
 		srv_print_innodb_monitor = TRUE;
 
@@ -396,7 +398,7 @@ loop:
 		"InnoDB: Warning: difficult to find free blocks from\n"
 		"InnoDB: the buffer pool (%lu search iterations)! Consider\n"
 		"InnoDB: increasing the buffer pool size.\n",
-						n_iterations);
+						(ulong) n_iterations);
 		fprintf(stderr,
 		"InnoDB: It is also possible that in your Unix version\n"
 		"InnoDB: fsync is very slow, or completely frozen inside\n"
@@ -406,11 +408,13 @@ loop:
 
 		fprintf(stderr,
 		"InnoDB: Pending flushes (fsync) log: %lu; buffer pool: %lu\n",
-	       			fil_n_pending_log_flushes,
-				fil_n_pending_tablespace_flushes);
+			(ulong) fil_n_pending_log_flushes,
+			(ulong) fil_n_pending_tablespace_flushes);
 		fprintf(stderr,
 	"InnoDB: %lu OS file reads, %lu OS file writes, %lu OS fsyncs\n",
-			os_n_file_reads, os_n_file_writes, os_n_fsyncs);
+			(ulong) os_n_file_reads,
+			(ulong) os_n_file_writes,
+			(ulong) os_n_fsyncs);
 
 		fprintf(stderr,
 		"InnoDB: Starting InnoDB Monitor to print further\n"
@@ -820,15 +824,15 @@ buf_LRU_block_remove_hashed_page(
         if (block != buf_page_hash_get(block->space, block->offset)) {
                 fprintf(stderr,
 "InnoDB: Error: page %lu %lu not found from the hash table\n",
-                                 block->space,
-                                block->offset);
+			(ulong) block->space,
+			(ulong) block->offset);
                 if (buf_page_hash_get(block->space, block->offset)) {
                         fprintf(stderr,
 "InnoDB: From hash table we find block %lx of %lu %lu which is not %lx\n",
-                (ulint)buf_page_hash_get(block->space, block->offset),
-                        buf_page_hash_get(block->space, block->offset)->space,
-                        buf_page_hash_get(block->space, block->offset)->offset,
-                        (ulint)block);
+                (ulong) buf_page_hash_get(block->space, block->offset),
+                (ulong) buf_page_hash_get(block->space, block->offset)->space,
+                (ulong) buf_page_hash_get(block->space, block->offset)->offset,
+		(ulong) block);
                 }
 
                 buf_print();
@@ -949,7 +953,7 @@ buf_LRU_print(void)
 	ut_ad(buf_pool);
 	mutex_enter(&(buf_pool->mutex));
 
-	printf("Pool ulint clock %lu\n", buf_pool->ulint_clock);
+	printf("Pool ulint clock %lu\n", (ulong) buf_pool->ulint_clock);
 
 	block = UT_LIST_GET_FIRST(buf_pool->LRU);
 
@@ -957,18 +961,18 @@ buf_LRU_print(void)
 
 	while (block != NULL) {
 
-		printf("BLOCK %lu ", block->offset);
+		printf("BLOCK %lu ", (ulong) block->offset);
 
 		if (block->old) {
 			printf("old ");
 		}
 
 		if (block->buf_fix_count) {
-			printf("buffix count %lu ", block->buf_fix_count);
+			printf("buffix count %lu ", (ulong) block->buf_fix_count);
 		}
 
 		if (block->io_fix) {
-			printf("io_fix %lu ", block->io_fix);
+			printf("io_fix %lu ", (ulong) block->io_fix);
 		}
 
 		if (ut_dulint_cmp(block->oldest_modification,
@@ -976,12 +980,12 @@ buf_LRU_print(void)
 			printf("modif. ");
 		}
 
-		printf("LRU pos %lu ", block->LRU_position);
+		printf("LRU pos %lu ", (ulong) block->LRU_position);
 		
 		frame = buf_block_get_frame(block);
 
-		printf("type %lu ", fil_page_get_type(frame));
-		printf("index id %lu ", ut_dulint_get_low(
+		printf("type %lu ", (ulong) fil_page_get_type(frame));
+		printf("index id %lu ", (ulong) ut_dulint_get_low(
 					btr_page_get_index_id(frame)));
 
 		block = UT_LIST_GET_NEXT(LRU, block);
diff --git a/innobase/buf/buf0rea.c b/innobase/buf/buf0rea.c
index 0fa6912ba1d..5ba27b8fee8 100644
--- a/innobase/buf/buf0rea.c
+++ b/innobase/buf/buf0rea.c
@@ -85,7 +85,8 @@ buf_read_page_low(
 		     		+ TRX_SYS_DOUBLEWRITE_BLOCK_SIZE))) {
 		ut_print_timestamp(stderr);
 		fprintf(stderr,
-"  InnoDB: Warning: trying to read doublewrite buffer page %lu\n", offset);
+"  InnoDB: Warning: trying to read doublewrite buffer page %lu\n",
+			(ulong) offset);
 
 		return(0);
 	}
@@ -126,7 +127,8 @@ buf_read_page_low(
 
 	if (buf_debug_prints) {
 		printf("Posting read request for page %lu, sync %lu\n",
-							   offset, sync);
+							   (ulong) offset,
+		       					   (ulong) sync);
 	}
 
 	ut_a(block->state == BUF_BLOCK_FILE_PAGE);
@@ -268,7 +270,7 @@ buf_read_ahead_random(
 "  InnoDB: Warning: in random readahead trying to access tablespace\n"
 "InnoDB: %lu page no. %lu,\n"
 "InnoDB: but the tablespace does not exist or is just being dropped.\n",
-				 space, i);
+					(ulong) space, (ulong) i);
 			}
 		}
 	}
@@ -282,7 +284,8 @@ buf_read_ahead_random(
 	if (buf_debug_prints && (count > 0)) {
 	
 		printf("Random read-ahead space %lu offset %lu pages %lu\n",
-						space, offset, count);
+						(ulong) space, (ulong) offset,
+		       				(ulong) count);
 	}
 
 	return(count);
@@ -322,7 +325,7 @@ buf_read_page(
 		fprintf(stderr,
 "  InnoDB: error: trying to access tablespace %lu page no. %lu,\n"
 "InnoDB: but the tablespace does not exist or is just being dropped.\n",
-				 space, offset);
+				 (ulong) space, (ulong) offset);
 	}
 
 	/* Flush pages from the end of the LRU list if necessary */
@@ -549,7 +552,7 @@ buf_read_ahead_linear(
 "  InnoDB: Warning: in linear readahead trying to access tablespace\n"
 "InnoDB: %lu page no. %lu,\n"
 "InnoDB: but the tablespace does not exist or is just being dropped.\n",
-				 space, i);
+				 (ulong) space, (ulong) i);
 			}
 		}
 	}
@@ -566,7 +569,7 @@ buf_read_ahead_linear(
 	if (buf_debug_prints && (count > 0)) {
 		printf(
 		"LINEAR read-ahead space %lu offset %lu pages %lu\n",
-		space, offset, count);
+		(ulong) space, (ulong) offset, (ulong) count);
 	}
 
 	return(count);
@@ -627,7 +630,7 @@ buf_read_ibuf_merge_pages(
 	buf_flush_free_margin();
 
 	if (buf_debug_prints) {
-		printf("Ibuf merge read-ahead pages %lu\n", n_stored);
+		printf("Ibuf merge read-ahead pages %lu\n", (ulong) n_stored);
 	}
 }
 
@@ -669,7 +672,7 @@ buf_read_recv_pages(
 				fprintf(stderr,
 "InnoDB: Error: InnoDB has waited for 50 seconds for pending\n"
 "InnoDB: reads to the buffer pool to be finished.\n"
-"InnoDB: Number of pending reads %lu\n", buf_pool->n_pend_reads);
+"InnoDB: Number of pending reads %lu\n", (ulong) buf_pool->n_pend_reads);
 
 				os_aio_print_debug = TRUE;
 			}
@@ -693,6 +696,7 @@ buf_read_recv_pages(
 	buf_flush_free_margin();
 
 	if (buf_debug_prints) {
-		printf("Recovery applies read-ahead pages %lu\n", n_stored);
+		printf("Recovery applies read-ahead pages %lu\n",
+		       (ulong) n_stored);
 	}
 }
diff --git a/innobase/com/com0shm.c b/innobase/com/com0shm.c
index ed185ccdf47..834ba3a5220 100644
--- a/innobase/com/com0shm.c
+++ b/innobase/com/com0shm.c
@@ -959,7 +959,7 @@ loop:
 	loop_count++;
 
 	if (loop_count > 1) {
-		printf("!!!!!!!!COM_SHM loop count %lu\n", loop_count);
+		printf("!!!!!!!!COM_SHM loop count %lu\n", (ulong) loop_count);
 	}
 
 	ut_ad(loop_count < 2);
@@ -1088,7 +1088,8 @@ loop:
 	loop_count++;
 
 	if (loop_count > 5) {
-		printf("!!!!!!COM_SHM Notempty loop count %lu\n", loop_count);
+		printf("!!!!!!COM_SHM Notempty loop count %lu\n",
+		       (ulong) loop_count);
 	}
 
 	ut_ad(loop_count < 100);
diff --git a/innobase/data/data0data.c b/innobase/data/data0data.c
index f2f94cc47ce..78cee31a29d 100644
--- a/innobase/data/data0data.c
+++ b/innobase/data/data0data.c
@@ -196,7 +196,8 @@ dfield_check_typed_no_assert(
 
 		fprintf(stderr,
 "InnoDB: Error: data field type %lu, len %lu\n",
-			dfield_get_type(field)->mtype, dfield_get_len(field));
+			(ulong) dfield_get_type(field)->mtype,
+			(ulong) dfield_get_len(field));
 		return(FALSE);
 	}
 
@@ -219,7 +220,7 @@ dtuple_check_typed_no_assert(
 	if (dtuple_get_n_fields(tuple) > REC_MAX_N_FIELDS) {
 		fprintf(stderr,
 "InnoDB: Error: index entry has %lu fields\n",
-			dtuple_get_n_fields(tuple));
+			(ulong) dtuple_get_n_fields(tuple));
 
 		dtuple_sprintf(err_buf, 900, tuple);
 		fprintf(stderr,
@@ -259,7 +260,8 @@ dfield_check_typed(
 
 		fprintf(stderr,
 "InnoDB: Error: data field type %lu, len %lu\n",
-			dfield_get_type(field)->mtype, dfield_get_len(field));
+			(ulong) dfield_get_type(field)->mtype,
+			(ulong) dfield_get_len(field));
 
 		ut_a(0);
 	}
@@ -433,7 +435,7 @@ dfield_print_also_hex(
 		data = dfield_get_data(dfield);
 		
 		for (i = 0; i < len; i++) {
-			printf("%02lx", (ulint)*data);
+			printf("%02lx", (ulong)*data);
 
 			data++;
 		}
@@ -459,10 +461,10 @@ dtuple_print(
 
 	n_fields = dtuple_get_n_fields(tuple);
 
-	printf("DATA TUPLE: %lu fields;\n", n_fields);
+	printf("DATA TUPLE: %lu fields;\n", (ulong) n_fields);
 
 	for (i = 0; i < n_fields; i++) {
-		printf(" %lu:", i);	
+		printf(" %lu:", (ulong) i);
 
 		field = dtuple_get_nth_field(tuple, i);
 		
@@ -506,7 +508,7 @@ dtuple_sprintf(
 			return(len);
 		}
 
-		len += sprintf(buf + len, " %lu:", i);	
+		len += sprintf(buf + len, " %lu:", (ulong) i);
 
 		field = dtuple_get_nth_field(tuple, i);
 		
@@ -567,7 +569,7 @@ dtuple_convert_big_rec(
 
 	if (size > 1000000000) {
 		fprintf(stderr,
-"InnoDB: Warning: tuple size very big: %lu\n", size);
+"InnoDB: Warning: tuple size very big: %lu\n", (ulong) size);
 		
 		dtuple_sprintf(err_buf, 900, entry);
 		fprintf(stderr,
diff --git a/innobase/data/data0type.c b/innobase/data/data0type.c
index 268da7eaf5c..f505cdfb0a2 100644
--- a/innobase/data/data0type.c
+++ b/innobase/data/data0type.c
@@ -63,7 +63,7 @@ dtype_print(
 	} else if (mtype == DATA_SYS) {
 		printf("DATA_SYS");
 	} else {
-		printf("type %lu", mtype);
+		printf("type %lu", (ulong) mtype);
 	}
 
 	len = type->len;
@@ -86,9 +86,9 @@ dtype_print(
 		} else if (prtype == DATA_ENGLISH) {
 			printf("DATA_ENGLISH");
 		} else {
-			printf("prtype %lu", mtype);
+			printf("prtype %lu", (ulong) mtype);
 		}
 	}
 
-	printf(" len %lu prec %lu", len, type->prec);
+	printf(" len %lu prec %lu", (ulong) len, (ulong) type->prec);
 }
diff --git a/innobase/dict/dict0crea.c b/innobase/dict/dict0crea.c
index a5077252c6a..038e4803441 100644
--- a/innobase/dict/dict0crea.c
+++ b/innobase/dict/dict0crea.c
@@ -1177,7 +1177,8 @@ dict_create_or_check_foreign_constraint_tables(void)
 	error = trx->error_state;
 
 	if (error != DB_SUCCESS) {
-		fprintf(stderr, "InnoDB: error %lu in creation\n", error);
+		fprintf(stderr, "InnoDB: error %lu in creation\n",
+			(ulong) error);
 		
 		ut_a(error == DB_OUT_OF_FILE_SPACE);
 
@@ -1256,27 +1257,27 @@ loop:
 	/* We allocate the new id from the sequence of table id's */
 	id = dict_hdr_get_new_id(DICT_HDR_TABLE_ID);
 
-	sprintf(buf2, "%lu_%lu", ut_dulint_get_high(id),
-						ut_dulint_get_low(id));
+	sprintf(buf2, "%lu_%lu", (ulong) ut_dulint_get_high(id),
+		                 (ulong) ut_dulint_get_low(id));
 	foreign->id = mem_heap_alloc(foreign->heap, ut_strlen(buf2) + 1);
 	ut_memcpy(foreign->id, buf2, ut_strlen(buf2) + 1);
 	
 	len += sprintf(buf + len,
 	"INSERT INTO SYS_FOREIGN VALUES('%lu_%lu', '%s', '%s', %lu);\n",
-					ut_dulint_get_high(id),
-					ut_dulint_get_low(id),
+					(ulong) ut_dulint_get_high(id),
+					(ulong) ut_dulint_get_low(id),
 					table->name,
 					foreign->referenced_table_name,
-					foreign->n_fields
-					+ (foreign->type << 24));
+					(ulong) (foreign->n_fields
+					+ (foreign->type << 24)));
 
 	for (i = 0; i < foreign->n_fields; i++) {
 
 		len += sprintf(buf + len,
 	"INSERT INTO SYS_FOREIGN_COLS VALUES('%lu_%lu', %lu, '%s', '%s');\n",
-					ut_dulint_get_high(id),
-					ut_dulint_get_low(id),
-					i,
+					(ulong) ut_dulint_get_high(id),
+					(ulong) ut_dulint_get_low(id),
+					(ulong) i,
 					foreign->foreign_col_names[i],
 					foreign->referenced_col_names[i]);
 	}
@@ -1303,7 +1304,7 @@ loop:
 	if (error != DB_SUCCESS) {
 	        fprintf(stderr,
 			"InnoDB: Foreign key constraint creation failed:\n"
-			"InnoDB: internal error number %lu\n", error);
+			"InnoDB: internal error number %lu\n", (ulong) error);
 
 		if (error == DB_DUPLICATE_KEY) {
 			fprintf(stderr,
diff --git a/innobase/dict/dict0dict.c b/innobase/dict/dict0dict.c
index 0ae36eec6dc..da5ffaecf41 100644
--- a/innobase/dict/dict0dict.c
+++ b/innobase/dict/dict0dict.c
@@ -3804,10 +3804,11 @@ dict_table_print_low(
 	printf(
    "TABLE: name %s, id %lu %lu, columns %lu, indexes %lu, appr.rows %lu\n",
 			table->name,
-			ut_dulint_get_high(table->id),
-			ut_dulint_get_low(table->id),
-			table->n_cols, UT_LIST_GET_LEN(table->indexes),
-			(ulint)table->stat_n_rows);
+			(ulong) ut_dulint_get_high(table->id),
+			(ulong) ut_dulint_get_low(table->id),
+			(ulong) table->n_cols,
+		        (ulong) UT_LIST_GET_LEN(table->indexes),
+			(ulong) table->stat_n_rows);
 	printf("  COLUMNS: ");
 
 	for (i = 0; i < table->n_cols - 1; i++) {
@@ -3883,16 +3884,16 @@ dict_index_print_low(
 	printf(
 	"  INDEX: name %s, table name %s, id %lu %lu, fields %lu/%lu, type %lu\n",
 			index->name, index->table_name,
-			ut_dulint_get_high(tree->id),
-			ut_dulint_get_low(tree->id),
-			index->n_user_defined_cols,
-			index->n_fields, index->type);
+			(ulong) ut_dulint_get_high(tree->id),
+			(ulong) ut_dulint_get_low(tree->id),
+			(ulong) index->n_user_defined_cols,
+			(ulong) index->n_fields, (ulong) index->type);
 	printf(
       "   root page %lu, appr.key vals %lu, leaf pages %lu, size pages %lu\n",
-		tree->page,
-		(ulint)n_vals,
-		index->stat_n_leaf_pages,
-		index->stat_index_size);
+		(ulong) tree->page,
+		(ulong) n_vals,
+		(ulong) index->stat_n_leaf_pages,
+		(ulong) index->stat_index_size);
 			
 	printf("   FIELDS: ");
 
@@ -3920,7 +3921,7 @@ dict_field_print_low(
 	printf(" %s", field->name);
 
 	if (field->prefix_len != 0) {
-	        printf("(%lu)", field->prefix_len);
+	        printf("(%lu)", (ulong) field->prefix_len);
 	}
 }
 
diff --git a/innobase/fil/fil0fil.c b/innobase/fil/fil0fil.c
index b45eec8e4cf..ee63df08744 100644
--- a/innobase/fil/fil0fil.c
+++ b/innobase/fil/fil0fil.c
@@ -432,7 +432,7 @@ fil_node_create(
 		ut_print_timestamp(stderr);
 		fprintf(stderr,
 "  InnoDB: Error: Could not find tablespace %lu for\n"
-"InnoDB: file %s from the tablespace memory cache.\n", id, name);
+"InnoDB: file %s from the tablespace memory cache.\n", (ulong) id, name);
 		mem_free(name2);
 
 		mem_free(node);
@@ -583,7 +583,7 @@ fil_try_to_close_file_in_LRU(
 
 	if (print_info) {
 		fprintf(stderr,
-"InnoDB: fil_sys open file LRU len %lu\n", UT_LIST_GET_LEN(system->LRU));
+"InnoDB: fil_sys open file LRU len %lu\n", (ulong) UT_LIST_GET_LEN(system->LRU));
 	}
 
 	while (node != NULL) {
@@ -598,7 +598,7 @@ fil_try_to_close_file_in_LRU(
 		if (print_info && node->n_pending_flushes > 0) {
 			fprintf(stderr,
 "InnoDB: cannot close file %s, because n_pending_flushes %lu\n", node->name,
-				       node->n_pending_flushes);
+				       (ulong) node->n_pending_flushes);
 		}
 
 		if (print_info
@@ -660,7 +660,8 @@ retry:
 		if (count2 > 20000) {
 			fprintf(stderr,
 "InnoDB: Warning: tablespace %s has i/o ops stopped for a long time %lu\n",
-						    space->name, count2);
+						    space->name,
+						    (ulong) count2);
 		}
 
 		mutex_exit(&(system->mutex));
@@ -706,7 +707,7 @@ close_more:
 "  InnoDB: Warning: too many (%lu) files stay open while the maximum\n"
 "InnoDB: allowed value would be %lu.\n"
 "InnoDB: You may need to raise the value of innodb_max_files_open in\n"
-"InnoDB: my.cnf.\n", system->n_open, system->max_n_open);
+"InnoDB: my.cnf.\n", (ulong) system->n_open, (ulong) system->max_n_open);
 
 		return;
 	}
@@ -832,7 +833,8 @@ try_again:
 "InnoDB: a tablespace %lu of name %s,\n"
 "InnoDB: but a tablespace %lu of the same name %s\n"
 "InnoDB: already exists in the tablespace memory cache!\n",
-			       id, name, space->id, space->name);
+			       (ulong) id, name,
+			       (ulong) space->id, space->name);
 
 		if (id == 0 || purpose != FIL_TABLESPACE) {
 
@@ -866,7 +868,7 @@ try_again:
 "InnoDB: Error: trying to add tablespace %lu of name %s\n"
 "InnoDB: to the tablespace memory cache, but tablespace\n"
 "InnoDB: %lu of name %s already exists in the tablespace\n"
-"InnoDB: memory cache!\n", id, name, space->id, space->name);
+"InnoDB: memory cache!\n", (ulong) id, name, (ulong) space->id, space->name);
 
 		mutex_exit(&(system->mutex));
 
@@ -946,8 +948,8 @@ fil_assign_new_space_id(void)
 "InnoDB: Warning: you are running out of new single-table tablespace id's.\n"
 "InnoDB: Current counter is %lu and it must not exceed %lu!\n"
 "InnoDB: To reset the counter to zero you have to dump all your tables and\n"
-"InnoDB: recreate the whole InnoDB installation.\n", id,
-						     SRV_LOG_SPACE_FIRST_ID);
+"InnoDB: recreate the whole InnoDB installation.\n", (ulong) id,
+						     (ulong) SRV_LOG_SPACE_FIRST_ID);
 	}
 
 	if (id >= SRV_LOG_SPACE_FIRST_ID) {
@@ -956,7 +958,7 @@ fil_assign_new_space_id(void)
 "InnoDB: You have run out of single-table tablespace id's!\n"
 "InnoDB: Current counter is %lu.\n"
 "InnoDB: To reset the counter to zero you have to dump all your tables and\n"
-"InnoDB: recreate the whole InnoDB installation.\n", id);
+"InnoDB: recreate the whole InnoDB installation.\n", (ulong) id);
 		system->max_assigned_id--;
 
 		id = ULINT_UNDEFINED;
@@ -991,7 +993,7 @@ fil_space_free(
 		ut_print_timestamp(stderr);
 		fprintf(stderr,
 "  InnoDB: Error: trying to remove tablespace %lu from the cache but\n"
-"InnoDB: it is not there.\n", id);
+"InnoDB: it is not there.\n", (ulong) id);
 
 		mutex_exit(&(system->mutex));
 		
@@ -1214,7 +1216,8 @@ fil_open_log_and_system_tablespace_files(void)
 "InnoDB: tablespace files open for the whole time mysqld is running, and\n"
 "InnoDB: needs to open also some .ibd files if the file-per-table storage\n"
 "InnoDB: model is used. Current open files %lu, max allowed open files %lu.\n",
-				     system->n_open, system->max_n_open);
+				     (ulong) system->n_open,
+				     (ulong) system->max_n_open);
 				}
 				node = UT_LIST_GET_NEXT(chain, node);
 			}
@@ -1269,7 +1272,7 @@ fil_set_max_space_id_if_bigger(
 
 	if (max_id >= SRV_LOG_SPACE_FIRST_ID) {
 		fprintf(stderr,
-"InnoDB: Fatal error: max tablespace id is too high, %lu\n", max_id);
+"InnoDB: Fatal error: max tablespace id is too high, %lu\n", (ulong) max_id);
 		ut_a(0);
 	}
 
@@ -1464,7 +1467,8 @@ fil_inc_pending_ibuf_merges(
 
 	if (space == NULL) {
 		fprintf(stderr,
-"InnoDB: Error: trying to do ibuf merge to a dropped tablespace %lu\n", id);
+"InnoDB: Error: trying to do ibuf merge to a dropped tablespace %lu\n",
+			(ulong) id);
 	}
 
 	if (space == NULL || space->stop_ibuf_merges) {
@@ -1497,7 +1501,8 @@ fil_decr_pending_ibuf_merges(
 
 	if (space == NULL) {
 		fprintf(stderr,
-"InnoDB: Error: decrementing ibuf merge of a dropped tablespace %lu\n", id);
+"InnoDB: Error: decrementing ibuf merge of a dropped tablespace %lu\n",
+			(ulong) id);
 	}
 
 	if (space != NULL) {
@@ -1767,7 +1772,8 @@ stop_ibuf_merges:
 			   fprintf(stderr,
 "  InnoDB: Warning: trying to delete tablespace %s,\n"
 "InnoDB: but there are %lu pending ibuf merges on it.\n"
-"InnoDB: Loop %lu.\n", space->name, space->n_pending_ibuf_merges, count);
+"InnoDB: Loop %lu.\n", space->name, (ulong) space->n_pending_ibuf_merges,
+				   (ulong) count);
 			}
 
 			mutex_exit(&(system->mutex));
@@ -1791,7 +1797,8 @@ try_again:
 		ut_print_timestamp(stderr);
 		fprintf(stderr,
 "  InnoDB: Error: cannot delete tablespace %lu\n"
-"InnoDB: because it is not found in the tablespace memory cache.\n", id);
+"InnoDB: because it is not found in the tablespace memory cache.\n",
+			(ulong) id);
 
 		mutex_exit(&(system->mutex));
 	
@@ -1815,8 +1822,9 @@ try_again:
 			fprintf(stderr,
 "  InnoDB: Warning: trying to delete tablespace %s,\n"
 "InnoDB: but there are %lu flushes and %lu pending i/o's on it\n"
-"InnoDB: Loop %lu.\n", space->name, space->n_pending_flushes, node->n_pending,
-									count);
+"InnoDB: Loop %lu.\n", space->name, (ulong) space->n_pending_flushes,
+				(ulong) node->n_pending,
+				(ulong) count);
 		}
 		mutex_exit(&(system->mutex));
 		os_thread_sleep(20000);
@@ -1892,7 +1900,7 @@ fil_discard_tablespace(
 		fprintf(stderr,
 "InnoDB: Warning: cannot delete tablespace %lu in DISCARD TABLESPACE.\n"
 "InnoDB: But let us remove the insert buffer entries for this tablespace.\n",
-									id); 
+			(ulong) id); 
 	}
 
 	/* Remove all insert buffer entries for the tablespace */
@@ -1989,7 +1997,8 @@ retry:
 		ut_print_timestamp(stderr);
 		fprintf(stderr,
 "  InnoDB: Warning: problems renaming %s to %s, %lu iterations\n",
-						old_name, new_name, count);
+						old_name, new_name,
+					        (ulong) count);
 	}
 
 	mutex_enter(&(system->mutex));
@@ -2000,7 +2009,7 @@ retry:
 		fprintf(stderr,
 "InnoDB: Error: cannot find space id %lu from the tablespace memory cache\n"
 "InnoDB: though the table %s in a rename operation should have that id\n",
-							  id, old_name);
+							  (ulong) id, old_name);
 		mutex_exit(&(system->mutex));
 
 		return(FALSE);
@@ -2351,11 +2360,11 @@ fil_reset_too_high_lsns(
 " InnoDB: Flush lsn in the tablespace file %lu to be imported\n"
 "InnoDB: is %lu %lu, which exceeds current system lsn %lu %lu.\n"
 "InnoDB: We reset the lsn's in the file %s.\n",
-			    space_id,
-			    ut_dulint_get_high(flush_lsn),
-			    ut_dulint_get_low(flush_lsn),
-			    ut_dulint_get_high(current_lsn),
-			    ut_dulint_get_low(current_lsn), filepath);
+			    (ulong) space_id,
+			    (ulong) ut_dulint_get_high(flush_lsn),
+			    (ulong) ut_dulint_get_low(flush_lsn),
+			    (ulong) ut_dulint_get_high(current_lsn),
+			    (ulong) ut_dulint_get_low(current_lsn), filepath);
 
 	/* Loop through all the pages in the tablespace and reset the lsn and
 	the page checksum if necessary */
@@ -2487,7 +2496,7 @@ fil_open_single_table_tablespace(
 
 	        fprintf(stderr,
 "  InnoDB: Error: tablespace id in file %s is %lu, but in the InnoDB\n"
-"InnoDB: data dictionary it is %lu.\n", filepath, space_id, id);
+"InnoDB: data dictionary it is %lu.\n", filepath, (ulong) space_id, (ulong) id);
 		fprintf(stderr,
 "InnoDB: Have you moved InnoDB .ibd files around without using the\n"
 "InnoDB: commands DISCARD TABLESPACE and IMPORT TABLESPACE?\n"
@@ -2587,8 +2596,9 @@ fil_load_single_table_tablespace(
 	if (size < FIL_IBD_FILE_INITIAL_SIZE * UNIV_PAGE_SIZE) {
 	        fprintf(stderr,
 "InnoDB: Error: the size of single-table tablespace file %s\n"
-"InnoDB: is only %lu %lu, should be at least %lu!", filepath, size_high,
-				       size_low, (ulint)4 * UNIV_PAGE_SIZE);
+"InnoDB: is only %lu %lu, should be at least %lu!", filepath,
+			(ulong) size_high,
+			(ulong) size_low, (ulong) (4 * UNIV_PAGE_SIZE));
 		os_file_close(file);
 		ut_free(filepath);
 
@@ -2612,8 +2622,9 @@ fil_load_single_table_tablespace(
 #ifndef UNIV_HOTBACKUP
 	if (space_id == ULINT_UNDEFINED || space_id == 0) {
 	        fprintf(stderr,
-"InnoDB: Error: tablespace id %lu in file %s is not sensible\n", space_id,
-								 filepath);
+"InnoDB: Error: tablespace id %lu in file %s is not sensible\n",
+			(ulong) space_id,
+			filepath);
 		goto func_exit;
 	}
 #else
@@ -2845,7 +2856,7 @@ fil_print_orphaned_tablespaces(void)
 							  && !space->mark) {
 			fprintf(stderr,
 "InnoDB: Warning: tablespace %s of id %lu has no matching table in\n"
-"InnoDB: the InnoDB data dictionary.\n", space->name, space->id);
+"InnoDB: the InnoDB data dictionary.\n", space->name, (ulong) space->id);
 		}
 
 		space = UT_LIST_GET_NEXT(space_list, space);
@@ -2996,7 +3007,7 @@ fil_space_for_table_exists_in_mem(
 "InnoDB: in InnoDB data dictionary has tablespace id %lu,\n"
 "InnoDB: but tablespace with that id or name does not exist. Have\n"
 "InnoDB: you deleted or moved .ibd files?\n",
-			       name, id);
+			       name, (ulong) id);
 		} else {
 		        ut_print_timestamp(stderr);
 			fprintf(stderr,
@@ -3005,7 +3016,8 @@ fil_space_for_table_exists_in_mem(
 "InnoDB: but tablespace with that id does not exist. There is\n"
 "InnoDB: a tablespace of name %s and id %lu, though. Have\n"
 "InnoDB: you deleted or moved .ibd files?\n",
-			       name, id, namespace->name, namespace->id);
+			        name, (ulong) id, namespace->name,
+				(ulong) namespace->id);
 		}
 		fprintf(stderr,
 "InnoDB: You can look from section 15.1 of http://www.innodb.com/ibman.html\n"
@@ -3022,12 +3034,12 @@ fil_space_for_table_exists_in_mem(
 "  InnoDB: Error: table %s\n"
 "InnoDB: in InnoDB data dictionary has tablespace id %lu,\n"
 "InnoDB: but tablespace with that id has name %s.\n"
-"InnoDB: Have you deleted or moved .ibd files?\n", name, id, space->name);
+"InnoDB: Have you deleted or moved .ibd files?\n", name, (ulong) id, space->name);
 
 		if (namespace != NULL) {
 			fprintf(stderr,
 "InnoDB: There is a tablespace with the right name\n"
-"InnoDB: %s, but its id is %lu.\n", namespace->name, namespace->id);
+"InnoDB: %s, but its id is %lu.\n", namespace->name, (ulong) namespace->id);
 		}
 
 		fprintf(stderr,
@@ -3377,7 +3389,8 @@ fil_node_prepare_for_io(
 		ut_print_timestamp(stderr);
 		fprintf(stderr,
 "  InnoDB: Warning: open files %lu exceeds the limit %lu\n",
-					system->n_open, system->max_n_open);
+			(ulong) system->n_open,
+			(ulong) system->max_n_open);
 	}
 
 	if (node->open == FALSE) {
@@ -3520,7 +3533,8 @@ fil_io(
 		fprintf(stderr,
 "  InnoDB: Error: trying to do i/o to a tablespace which does not exist.\n"
 "InnoDB: i/o type %lu, space id %lu, page no. %lu, i/o length %lu bytes\n",
-		       type, space_id, block_offset, len);
+			(ulong) type, (ulong) space_id, (ulong) block_offset,
+			(ulong) len);
 
 		return(DB_TABLESPACE_DELETED);
 	}
@@ -3543,8 +3557,9 @@ fil_io(
 	"InnoDB: space name %s,\n"
 	"InnoDB: which is outside the tablespace bounds.\n"
 	"InnoDB: Byte offset %lu, len %lu, i/o type %lu\n", 
- 			block_offset, space_id, space->name, byte_offset, len,
-			type);
+ 			(ulong) block_offset, (ulong) space_id,
+			space->name, (ulong) byte_offset, (ulong) len,
+			(ulong) type);
  			
 			ut_a(0);
 		}
@@ -3571,8 +3586,9 @@ fil_io(
 	"InnoDB: space name %s,\n"
 	"InnoDB: which is outside the tablespace bounds.\n"
 	"InnoDB: Byte offset %lu, len %lu, i/o type %lu\n", 
- 			block_offset, space_id, space->name, byte_offset, len,
-			type);
+ 			(ulong) block_offset, (ulong) space_id,
+			space->name, (ulong) byte_offset, (ulong) len,
+			(ulong) type);
  		ut_a(0);
 	}
 
@@ -3704,8 +3720,8 @@ fil_aio_wait(
 	if (os_aio_use_native_aio) {
 		srv_io_thread_op_info[segment] = (char *) "handle native aio";
 #ifdef WIN_ASYNC_IO
-		ret = os_aio_windows_handle(segment, 0, &fil_node, &message,
-								&type);
+		ret = os_aio_windows_handle(segment, 0, (void**) &fil_node,
+					    &message, &type);
 #elif defined(POSIX_ASYNC_IO)
 		ret = os_aio_posix_handle(segment, &fil_node, &message);
 #else
diff --git a/innobase/fsp/fsp0fsp.c b/innobase/fsp/fsp0fsp.c
index 8ceea03f34a..9d76387c6cb 100644
--- a/innobase/fsp/fsp0fsp.c
+++ b/innobase/fsp/fsp0fsp.c
@@ -938,7 +938,8 @@ fsp_header_get_space_id(
 	if (id != fsp_id) {
 	        fprintf(stderr,
 "InnoDB: Error: space id in fsp header %lu, but in the page header %lu\n",
-							    fsp_id, id);
+							    (ulong) fsp_id,
+							    (ulong) id);
 		return(ULINT_UNDEFINED);
 	}
 
@@ -1108,8 +1109,8 @@ fsp_try_extend_data_file(
 
 			fprintf(stderr,
 "InnoDB: Error: Last data file size is %lu, max size allowed %lu\n",
-				srv_data_file_sizes[srv_n_data_files - 1],
-				srv_last_file_size_max);
+				(ulong) srv_data_file_sizes[srv_n_data_files - 1],
+				(ulong) srv_last_file_size_max);
 		}
 
 		size_increase = srv_last_file_size_max
@@ -1444,7 +1445,7 @@ fsp_alloc_free_page(
 		        fprintf(stderr,
 "InnoDB: Error: trying to extend a single-table tablespace %lu\n"
 "InnoDB: by single page(s) though the space size %lu. Page no %lu.\n",
-			   space, space_size, page_no);
+			   (ulong) space, (ulong) space_size, (ulong) page_no);
 			return(FIL_NULL);
 		}
 		success = fsp_try_extend_data_file_with_pages(space, page_no,
@@ -1521,7 +1522,8 @@ fsp_free_page(
 	if (state != XDES_FREE_FRAG && state != XDES_FULL_FRAG) {
 		fprintf(stderr,
 "InnoDB: Error: File space extent descriptor of page %lu has state %lu\n",
-								page, state);
+								(ulong) page,
+								(ulong) state);
 		ut_sprintf_buf(buf, ((byte*)descr) - 50, 200);
 
 		fprintf(stderr, "InnoDB: Dump of descriptor: %s\n", buf);
@@ -1540,7 +1542,7 @@ fsp_free_page(
 								== TRUE) {
 		fprintf(stderr,
 "InnoDB: Error: File space extent descriptor of page %lu says it is free\n",
-									page);
+							       (ulong) page);
 		ut_sprintf_buf(buf, ((byte*)descr) - 50, 200);
 
 		fprintf(stderr, "InnoDB: Dump of descriptor: %s\n", buf);
@@ -2487,7 +2489,8 @@ fseg_alloc_free_page_low(
 			        fprintf(stderr,
 "InnoDB: Error (2): trying to extend a single-table tablespace %lu\n"
 "InnoDB: by single page(s) though the space size %lu. Page no %lu.\n",
-					    space, space_size, ret_page);
+					(ulong) space, (ulong) space_size,
+					(ulong) ret_page);
 				return(FIL_NULL);
 			}
 			
@@ -2961,7 +2964,7 @@ fseg_free_page_low(
 "InnoDB: though it is already marked as free in the tablespace!\n"
 "InnoDB: The tablespace free space info is corrupt.\n"
 "InnoDB: You may need to dump your InnoDB tables and recreate the whole\n"
-"InnoDB: database!\n", page);
+"InnoDB: database!\n", (ulong) page);
 
 		fprintf(stderr,
 "InnoDB: If the InnoDB recovery crashes here, see section 6.1\n"
@@ -3016,11 +3019,11 @@ fseg_free_page_low(
 "InnoDB: Serious error: InnoDB is trying to free space %lu page %lu,\n"
 "InnoDB: which does not belong to segment %lu %lu but belongs\n"
 "InnoDB: to segment %lu %lu.\n",
-		   space, page,
-		   ut_dulint_get_high(descr_id),
-		   ut_dulint_get_low(descr_id),
-		   ut_dulint_get_high(seg_id),
-		   ut_dulint_get_low(seg_id));
+		   (ulong) space, (ulong) page,
+		   (ulong) ut_dulint_get_high(descr_id),
+		   (ulong) ut_dulint_get_low(descr_id),
+		   (ulong) ut_dulint_get_high(seg_id),
+		   (ulong) ut_dulint_get_low(seg_id));
 
 		fprintf(stderr,
 "InnoDB: If the InnoDB recovery crashes here, see section 6.1\n"
@@ -3537,11 +3540,13 @@ fseg_print_low(
 
 	printf(
     "SEGMENT id %lu %lu space %lu; page %lu; res %lu used %lu; full ext %lu\n",
-		seg_id_high, seg_id_low, space, page_no, reserved, used,
-		n_full);
+		(ulong) seg_id_high, (ulong) seg_id_low, (ulong) space,
+                (ulong) page_no, (ulong) reserved, (ulong) used,
+                (ulong) n_full);
 	printf(
     "fragm pages %lu; free extents %lu; not full extents %lu: pages %lu\n",
-		n_frag, n_free, n_not_full, n_used);
+		(ulong) n_frag, (ulong) n_free, (ulong) n_not_full,
+                (ulong) n_used);
 }
 
 /***********************************************************************
@@ -3844,15 +3849,16 @@ fsp_print(
 	seg_id_low = ut_dulint_get_low(d_var);
 	seg_id_high = ut_dulint_get_high(d_var);
 
-	printf("FILE SPACE INFO: id %lu\n", space);
+	printf("FILE SPACE INFO: id %lu\n", (ulong) space);
 
 	printf("size %lu, free limit %lu, free extents %lu\n",
-						size, free_limit, n_free);
+	       (ulong) size, (ulong) free_limit, (ulong) n_free);
 	printf(
 	"not full frag extents %lu: used pages %lu, full frag extents %lu\n",
-					n_free_frag, frag_n_used, n_full_frag);
+		(ulong) n_free_frag, (ulong) frag_n_used, (ulong) n_full_frag);
 
-	printf("first seg id not used %lu %lu\n", seg_id_high, seg_id_low);
+	printf("first seg id not used %lu %lu\n", (ulong) seg_id_high,
+	       (ulong) seg_id_low);
 
 	mtr_commit(&mtr);	
 
@@ -3931,5 +3937,5 @@ fsp_print(
 	
 	mtr_commit(&mtr2);
 
-	printf("NUMBER of file segments: %lu\n", n_segs);	
+	printf("NUMBER of file segments: %lu\n", (ulong) n_segs);
 }
diff --git a/innobase/fut/fut0lst.c b/innobase/fut/fut0lst.c
index 4328fc97b33..79830c36eb5 100644
--- a/innobase/fut/fut0lst.c
+++ b/innobase/fut/fut0lst.c
@@ -511,6 +511,7 @@ flst_print(
 
 	printf("FILE-BASED LIST:\n");
 	printf("Base node in space %lu page %lu byte offset %lu; len %lu\n",
-		buf_frame_get_space_id(frame), buf_frame_get_page_no(frame),
-		(ulint) (base - frame), len);
+	       (ulong) buf_frame_get_space_id(frame),
+	       (ulong) buf_frame_get_page_no(frame),
+	       (ulong) (base - frame), (ulong) len);
 }
diff --git a/innobase/ha/ha0ha.c b/innobase/ha/ha0ha.c
index 87c32bf5dbd..3f36879e80b 100644
--- a/innobase/ha/ha0ha.c
+++ b/innobase/ha/ha0ha.c
@@ -323,7 +323,7 @@ ha_validate(
 				fprintf(stderr,
 "InnoDB: Error: hash table node fold value %lu does not\n"
 "InnoDB: match with the cell number %lu.\n",
-					node->fold, i);
+					(ulong) node->fold, (ulong) i);
 
 				ok = FALSE;
 			}
@@ -390,7 +390,8 @@ ha_print_info(
 	}
 
 	buf += sprintf(buf,
-"Hash table size %lu, used cells %lu", hash_get_n_cells(table), cells);
+"Hash table size %lu, used cells %lu", (ulong) hash_get_n_cells(table),
+		       (ulong) cells);
 
 	if (table->heaps == NULL && table->heap != NULL) {
 
@@ -403,6 +404,6 @@ ha_print_info(
 			n_bufs++;
 		}
 				
-	        buf += sprintf(buf, ", node heap has %lu buffer(s)\n", n_bufs);
+	        buf += sprintf(buf, ", node heap has %lu buffer(s)\n", (ulong) n_bufs);
 	}
 }	
diff --git a/innobase/ibuf/ibuf0ibuf.c b/innobase/ibuf/ibuf0ibuf.c
index 95982e57126..b4a28d5fcd8 100644
--- a/innobase/ibuf/ibuf0ibuf.c
+++ b/innobase/ibuf/ibuf0ibuf.c
@@ -509,7 +509,7 @@ ibuf_data_init_for_space(
 
 	ibuf_exit();
 
-	sprintf(buf, "SYS_IBUF_TABLE_%lu", space);
+	sprintf(buf, "SYS_IBUF_TABLE_%lu", (ulong) space);
 	
 	table = dict_mem_table_create(buf, space, 2);
 
@@ -1694,7 +1694,7 @@ ibuf_free_excess_pages(
 	
 	if (space != 0) {
 	        fprintf(stderr,
-"InnoDB: Error: calling ibuf_free_excess_pages for space %lu\n", space);
+"InnoDB: Error: calling ibuf_free_excess_pages for space %lu\n", (ulong) space);
 		return;
 	}
 
@@ -2714,8 +2714,8 @@ ibuf_insert_to_index_page(
 
 				fprintf(stderr,
 "InnoDB: Error: Insert buffer insert fails; page free %lu, dtuple size %lu\n",
-				page_get_max_insert_size(page, 1),
-				rec_get_converted_size(entry));
+				(ulong) page_get_max_insert_size(page, 1),
+				(ulong) rec_get_converted_size(entry));
 
 				dtuple_sprintf(errbuf, 900, entry);
 				
@@ -2733,7 +2733,7 @@ ibuf_insert_to_index_page(
 						buf_frame_get_page_no(page),
 						IBUF_BITMAP_FREE, mtr);
 
-				fprintf(stderr, "Bitmap bits %lu\n", old_bits);
+				fprintf(stderr, "Bitmap bits %lu\n", (ulong) old_bits);
 
 				fprintf(stderr,
 "InnoDB: Send a detailed bug report to mysql@lists.mysql.com!\n");
@@ -2801,7 +2801,8 @@ ibuf_delete_rec(
 		fprintf(stderr,
 "InnoDB: ERROR: Send the output to mysql@lists.mysql.com\n"
 "InnoDB: ibuf cursor restoration fails!\n"
-"InnoDB: ibuf record inserted to space %lu page %lu\n", space, page_no);
+"InnoDB: ibuf record inserted to space %lu page %lu\n", (ulong) space,
+			(ulong) page_no);
 		fflush(stderr);
 
 		rec_print(btr_pcur_get_rec(pcur));
@@ -2998,7 +2999,8 @@ ibuf_merge_or_delete_for_page(
 "InnoDB: to determine if they are corrupt after this.\n\n"
 "InnoDB: Please make a detailed bug report and send it to\n"
 "InnoDB: mysql@lists.mysql.com\n\n",
-				page_no, fil_page_get_type(page));
+				(ulong) page_no,
+				(ulong) fil_page_get_type(page));
 		}
 	}
 
@@ -3237,7 +3239,8 @@ leave_loop:
 
 	mutex_exit(&ibuf_mutex);
 
-	printf("Discarded %lu ibuf entries for space %lu\n", n_inserts, space);
+	printf("Discarded %lu ibuf entries for space %lu\n", (ulong) n_inserts,
+	       (ulong) space);
 
 	ibuf_exit();
 
@@ -3346,7 +3349,9 @@ ibuf_print(
 	while (data) {
 		buf += sprintf(buf,
   	"Ibuf for space %lu: size %lu, free list len %lu, seg size %lu,",
-		data->space, data->size, data->free_list_len, data->seg_size);
+			       (ulong) data->space, (ulong) data->size,
+			       (ulong) data->free_list_len,
+			       (ulong) data->seg_size);
 
 		if (data->empty) {
 			buf += sprintf(buf, " is empty\n");
@@ -3356,13 +3361,16 @@ ibuf_print(
 
 		buf += sprintf(buf,
 			"%lu inserts, %lu merged recs, %lu merges\n",
-			data->n_inserts, data->n_merged_recs, data->n_merges);
+			       (ulong) data->n_inserts,
+			       (ulong) data->n_merged_recs,
+			       (ulong) data->n_merges);
 #ifdef UNIV_IBUF_DEBUG
 		for (i = 0; i < IBUF_COUNT_N_PAGES; i++) {
 			if (ibuf_count_get(data->space, i) > 0) {
 
 				printf("Ibuf count for page %lu is %lu\n",
-					i, ibuf_count_get(data->space, i));
+				       (ulong) i,
+				       (ulong) ibuf_count_get(data->space, i));
 			}
 		}
 #endif
diff --git a/innobase/include/univ.i b/innobase/include/univ.i
index 9e7b6ab3f1b..346b3b3d09f 100644
--- a/innobase/include/univ.i
+++ b/innobase/include/univ.i
@@ -67,6 +67,7 @@ Microsoft Visual C++ */
 
 #endif /* #if (defined(WIN32) || ... */
 
+#ifdef NOT_USED
 /* On the 64-bit Windows we replace printf with ut_printf, etc. so that
 we can use the %lu format string to print a 64-bit ulint */
 #if defined(__WIN__) && (defined(WIN64) || defined(_WIN64))
@@ -74,7 +75,7 @@ we can use the %lu format string to print a 64-bit ulint */
 #define sprintf 	ut_sprintf
 #define fprintf		ut_fprintf
 #endif
-
+#endif
 
 /*			DEBUG VERSION CONTROL
 			===================== */
diff --git a/innobase/lock/lock0lock.c b/innobase/lock/lock0lock.c
index 7fdca02ee94..3541604a09a 100644
--- a/innobase/lock/lock0lock.c
+++ b/innobase/lock/lock0lock.c
@@ -548,10 +548,10 @@ lock_check_trx_id_sanity(
 "InnoDB: is %lu %lu which is higher than the global trx id counter %lu %lu!\n"
 "InnoDB: The table is corrupt. You have to do dump + drop + reimport.\n",
 			       err_buf, index->table_name, index->name,
-			       ut_dulint_get_high(trx_id),
-			       ut_dulint_get_low(trx_id),
-			       ut_dulint_get_high(trx_sys->max_trx_id),
-			       ut_dulint_get_low(trx_sys->max_trx_id));
+			       (ulong) ut_dulint_get_high(trx_id),
+			       (ulong) ut_dulint_get_low(trx_id),
+			       (ulong) ut_dulint_get_high(trx_sys->max_trx_id),
+			       (ulong) ut_dulint_get_low(trx_sys->max_trx_id));
 
 		is_ok = FALSE;
 	}
@@ -1802,7 +1802,8 @@ index->table_name);
 
 	if (lock_print_waits) {
 		printf("Lock wait for trx %lu in index %s\n",
-				ut_dulint_get_low(trx->id), index->name);
+		       (ulong) ut_dulint_get_low(trx->id),
+		       index->name);
 	}
 	
 	return(DB_LOCK_WAIT);	
@@ -2129,7 +2130,7 @@ lock_grant(
 
 	if (lock_print_waits) {
 		printf("Lock wait for trx %lu ends\n",
-					ut_dulint_get_low(lock->trx->id));
+		       (ulong) ut_dulint_get_low(lock->trx->id));
 	}
 
 	/* If we are resolving a deadlock by choosing another transaction
@@ -3814,7 +3815,7 @@ lock_table_print(
 
 	buf += sprintf(buf, "TABLE LOCK table %s trx id %lu %lu",
 		lock->un_member.tab_lock.table->name,
-		(lock->trx)->id.high, (lock->trx)->id.low);
+		(ulong) (lock->trx)->id.high, (ulong) (lock->trx)->id.low);
 
 	if (lock_get_mode(lock) == LOCK_S) {
 		buf += sprintf(buf, " lock mode S");
@@ -3828,7 +3829,7 @@ lock_table_print(
 		buf += sprintf(buf, " lock_mode AUTO-INC");
 	} else {
 		buf += sprintf(buf,
-			" unknown lock_mode %lu", lock_get_mode(lock));
+			" unknown lock_mode %lu", (ulong) lock_get_mode(lock));
 	}
 
 	if (lock_get_wait(lock)) {
@@ -3863,11 +3864,13 @@ lock_rec_print(
  	page_no = lock->un_member.rec_lock.page_no;
 
 	buf += sprintf(buf, "RECORD LOCKS space id %lu page no %lu n bits %lu",
-		    space, page_no, lock_rec_get_n_bits(lock));
+		       (ulong) space, (ulong) page_no,
+		       (ulong) lock_rec_get_n_bits(lock));
 
 	buf += sprintf(buf, " table %s index %s trx id %lu %lu",
-		lock->index->table->name, lock->index->name,
-		(lock->trx)->id.high, (lock->trx)->id.low);
+		       lock->index->table->name, lock->index->name,
+		       (ulong) (lock->trx)->id.high,
+		       (ulong) (lock->trx)->id.low);
 
 	if (lock_get_mode(lock) == LOCK_S) {
 		buf += sprintf(buf, " lock mode S");
@@ -3935,7 +3938,8 @@ lock_rec_print(
 	
 		if (lock_rec_get_nth_bit(lock, i)) {
 
-			buf += sprintf(buf, "Record lock, heap no %lu ", i);
+			buf += sprintf(buf, "Record lock, heap no %lu ",
+				       (ulong) i);
 
 			if (page) {
 				buf += rec_sprintf(buf, 120,
@@ -4038,19 +4042,19 @@ lock_print_info(
 "------------\n");
 
 	buf += sprintf(buf, "Trx id counter %lu %lu\n", 
-		ut_dulint_get_high(trx_sys->max_trx_id),
-		ut_dulint_get_low(trx_sys->max_trx_id));
+		       (ulong) ut_dulint_get_high(trx_sys->max_trx_id),
+		       (ulong) ut_dulint_get_low(trx_sys->max_trx_id));
 
 	buf += sprintf(buf,
 	"Purge done for trx's n:o < %lu %lu undo n:o < %lu %lu\n",
-		ut_dulint_get_high(purge_sys->purge_trx_no),
-		ut_dulint_get_low(purge_sys->purge_trx_no),
-		ut_dulint_get_high(purge_sys->purge_undo_no),
-		ut_dulint_get_low(purge_sys->purge_undo_no));
+		(ulong) ut_dulint_get_high(purge_sys->purge_trx_no),
+		(ulong) ut_dulint_get_low(purge_sys->purge_trx_no),
+		(ulong) ut_dulint_get_high(purge_sys->purge_undo_no),
+		(ulong) ut_dulint_get_low(purge_sys->purge_undo_no));
 
 	buf += sprintf(buf,
 		"Total number of lock structs in row lock hash table %lu\n",
-						lock_get_n_rec_locks());
+					 (ulong) lock_get_n_rec_locks());
 
 	buf += sprintf(buf, "LIST OF TRANSACTIONS FOR EACH SESSION:\n");
 
@@ -4122,16 +4126,16 @@ loop:
 	        if (trx->read_view) {
 	  	        buf += sprintf(buf,
        "Trx read view will not see trx with id >= %lu %lu, sees < %lu %lu\n",
-		       	ut_dulint_get_high(trx->read_view->low_limit_id),
-       			ut_dulint_get_low(trx->read_view->low_limit_id),
-       			ut_dulint_get_high(trx->read_view->up_limit_id),
-       			ut_dulint_get_low(trx->read_view->up_limit_id));
+		      (ulong) ut_dulint_get_high(trx->read_view->low_limit_id),
+       		      (ulong) ut_dulint_get_low(trx->read_view->low_limit_id),
+       		      (ulong) ut_dulint_get_high(trx->read_view->up_limit_id),
+       		      (ulong) ut_dulint_get_low(trx->read_view->up_limit_id));
 	        }
 
 		if (trx->que_state == TRX_QUE_LOCK_WAIT) {
 			buf += sprintf(buf,
  "------- TRX HAS BEEN WAITING %lu SEC FOR THIS LOCK TO BE GRANTED:\n",
-		   (ulint)difftime(time(NULL), trx->wait_started));
+		   (ulong)difftime(time(NULL), trx->wait_started));
 
 			if (lock_get_type(trx->wait_lock) == LOCK_REC) {
 				lock_rec_print(buf, trx->wait_lock);
@@ -4422,7 +4426,8 @@ loop:
 			index = lock->index;
 			rec = page_find_rec_with_heap_no(page, i);
 
-			printf("Validating %lu %lu\n", space, page_no);
+			printf("Validating %lu %lu\n", (ulong) space,
+			       (ulong) page_no);
 
 			lock_mutex_exit_kernel();
 
diff --git a/innobase/log/log0log.c b/innobase/log/log0log.c
index d3309815998..f041137840c 100644
--- a/innobase/log/log0log.c
+++ b/innobase/log/log0log.c
@@ -342,7 +342,8 @@ log_close(void)
 "InnoDB: If you are using big BLOB or TEXT rows, you must set the\n"
 "InnoDB: combined size of log files at least 10 times bigger than the\n"
 "InnoDB: largest such row.\n",
-			checkpoint_age, log->log_group_capacity);
+				(ulong) checkpoint_age,
+				(ulong) log->log_group_capacity);
 		}
 	}
 
@@ -898,7 +899,8 @@ log_group_check_flush_completion(
 	if (!log_sys->one_flushed && group->n_pending_writes == 0) {
 
 		if (log_debug_writes) {
-			printf("Log flushed first to group %lu\n", group->id);
+			printf("Log flushed first to group %lu\n",
+			       (ulong) group->id);
 		}
 	
 		log_sys->written_to_some_lsn = log_sys->write_lsn;
@@ -909,7 +911,7 @@ log_group_check_flush_completion(
 
 	if (log_debug_writes && (group->n_pending_writes == 0)) {
 
-		printf("Log flushed to group %lu\n", group->id);
+		printf("Log flushed to group %lu\n", (ulong) group->id);
 	}
 
 	return(0);
@@ -1049,8 +1051,8 @@ log_group_file_header_flush(
 
 	if (log_debug_writes) {
 		printf(
-		"Writing log file header to group %lu file %lu\n", group->id,
-								nth_file);
+		"Writing log file header to group %lu file %lu\n",
+		(ulong) group->id, (ulong) nth_file);
 	}
 
 	if (log_do_write) {
@@ -1139,13 +1141,14 @@ loop:
 		printf(
 		"Writing log file segment to group %lu offset %lu len %lu\n"
 		"start lsn %lu %lu\n",
-			group->id, next_offset, write_len,
-			ut_dulint_get_high(start_lsn),
-			ut_dulint_get_low(start_lsn));
+			(ulong) group->id, (ulong) next_offset,
+		        (ulong) write_len,
+			(ulong) ut_dulint_get_high(start_lsn),
+			(ulong) ut_dulint_get_low(start_lsn));
 		printf(
 		"First block n:o %lu last block n:o %lu\n",
-			log_block_get_hdr_no(buf),
-			log_block_get_hdr_no(
+			(ulong) log_block_get_hdr_no(buf),
+			(ulong) log_block_get_hdr_no(
 				buf + write_len - OS_FILE_LOG_BLOCK_SIZE));
 		ut_a(log_block_get_hdr_no(buf)
 			== log_block_convert_lsn_to_no(start_lsn));
@@ -1286,10 +1289,10 @@ loop:
 
 	if (log_debug_writes) {
 		printf("Writing log from %lu %lu up to lsn %lu %lu\n",
-			ut_dulint_get_high(log_sys->written_to_all_lsn),
-			ut_dulint_get_low(log_sys->written_to_all_lsn),
-					ut_dulint_get_high(log_sys->lsn),
-					ut_dulint_get_low(log_sys->lsn));
+			(ulong) ut_dulint_get_high(log_sys->written_to_all_lsn),
+			(ulong) ut_dulint_get_low(log_sys->written_to_all_lsn),
+			(ulong) ut_dulint_get_high(log_sys->lsn),
+			(ulong)	ut_dulint_get_low(log_sys->lsn));
 	}
 
 	log_sys->n_pending_writes++;
@@ -1525,7 +1528,8 @@ log_io_complete_checkpoint(
 	log_sys->n_pending_checkpoint_writes--;
 
 	if (log_debug_writes) {
-		printf("Checkpoint info written to group %lu\n", group->id);
+		printf("Checkpoint info written to group %lu\n",
+		       (ulong) group->id);
 	}
 
 	if (log_sys->n_pending_checkpoint_writes == 0) {
@@ -1848,9 +1852,9 @@ log_checkpoint(
 
 	if (log_debug_writes) {
 		printf("Making checkpoint no %lu at lsn %lu %lu\n",
-			ut_dulint_get_low(log_sys->next_checkpoint_no),
-			ut_dulint_get_high(oldest_lsn),
-			ut_dulint_get_low(oldest_lsn));
+			(ulong) ut_dulint_get_low(log_sys->next_checkpoint_no),
+			(ulong) ut_dulint_get_high(oldest_lsn),
+			(ulong) ut_dulint_get_low(oldest_lsn));
 	}
 
 	log_groups_write_checkpoint_info();
@@ -2079,7 +2083,7 @@ log_archived_file_name_gen(
 
 	UT_NOT_USED(id);	/* Currently we only archive the first group */
 	
-	sprintf(buf, "%sib_arch_log_%010lu", srv_arch_dir, file_no);
+	sprintf(buf, "%sib_arch_log_%010lu", srv_arch_dir, (ulong) file_no);
 }
 
 /**********************************************************
@@ -2262,9 +2266,9 @@ loop:
 	if (log_debug_writes) {
 		printf(
 		"Archiving starting at lsn %lu %lu, len %lu to group %lu\n",
-					ut_dulint_get_high(start_lsn),
-					ut_dulint_get_low(start_lsn),
-					len, group->id);
+					(ulong) ut_dulint_get_high(start_lsn),
+					(ulong) ut_dulint_get_low(start_lsn),
+					(ulong) len, (ulong) group->id);
 	}
 
 	log_sys->n_pending_archive_ios++;
@@ -2358,7 +2362,7 @@ log_archive_write_complete_groups(void)
 
 	if (log_debug_writes && trunc_files) {
 		printf("Complete file(s) archived to group %lu\n",
-								group->id);
+							  (ulong) group->id);
 	}
 
 	/* Calculate the archive file space start lsn */
@@ -2554,10 +2558,10 @@ loop:
 
 	if (log_debug_writes) {
 		printf("Archiving from lsn %lu %lu to lsn %lu %lu\n",
-			ut_dulint_get_high(log_sys->archived_lsn),
-			ut_dulint_get_low(log_sys->archived_lsn),
-			ut_dulint_get_high(limit_lsn),
-			ut_dulint_get_low(limit_lsn));
+			(ulong) ut_dulint_get_high(log_sys->archived_lsn),
+			(ulong) ut_dulint_get_low(log_sys->archived_lsn),
+			(ulong) ut_dulint_get_high(limit_lsn),
+			(ulong) ut_dulint_get_low(limit_lsn));
 	}
 
 	/* Read the log segment to the archive buffer */
@@ -2666,7 +2670,8 @@ log_archive_close_groups(
 		if (log_debug_writes) {
 			printf(
 			"Incrementing arch file no to %lu in log group %lu\n",
-				group->archived_file_no + 2, group->id);
+				(ulong) group->archived_file_no + 2,
+			        (ulong) group->id);
 		}
 	}
 }
@@ -3117,10 +3122,10 @@ loop:
 		fprintf(stderr,
 "InnoDB: Error: log sequence number at shutdown %lu %lu\n"
 "InnoDB: is lower than at startup %lu %lu!\n",
-			  ut_dulint_get_high(lsn),
-			  ut_dulint_get_low(lsn),
-			  ut_dulint_get_high(srv_start_lsn),
-			  ut_dulint_get_low(srv_start_lsn));
+			  (ulong) ut_dulint_get_high(lsn),
+			  (ulong) ut_dulint_get_low(lsn),
+			  (ulong) ut_dulint_get_high(srv_start_lsn),
+			  (ulong) ut_dulint_get_low(srv_start_lsn));
 	}
 
 	srv_shutdown_lsn = lsn;
@@ -3232,12 +3237,12 @@ log_print(
 	buf += sprintf(buf, "Log sequence number %lu %lu\n"
 	       "Log flushed up to   %lu %lu\n"
 	       "Last checkpoint at  %lu %lu\n",
-			ut_dulint_get_high(log_sys->lsn),
-			ut_dulint_get_low(log_sys->lsn),
-			ut_dulint_get_high(log_sys->flushed_to_disk_lsn),
-			ut_dulint_get_low(log_sys->flushed_to_disk_lsn),
-			ut_dulint_get_high(log_sys->last_checkpoint_lsn),
-			ut_dulint_get_low(log_sys->last_checkpoint_lsn));
+			(ulong) ut_dulint_get_high(log_sys->lsn),
+			(ulong) ut_dulint_get_low(log_sys->lsn),
+			(ulong) ut_dulint_get_high(log_sys->flushed_to_disk_lsn),
+			(ulong) ut_dulint_get_low(log_sys->flushed_to_disk_lsn),
+			(ulong) ut_dulint_get_high(log_sys->last_checkpoint_lsn),
+			(ulong) ut_dulint_get_low(log_sys->last_checkpoint_lsn));
 
 	current_time = time(NULL);
 			
@@ -3246,10 +3251,10 @@ log_print(
 	buf += sprintf(buf,
 	"%lu pending log writes, %lu pending chkp writes\n"
 	"%lu log i/o's done, %.2f log i/o's/second\n",
-	log_sys->n_pending_writes,
-	log_sys->n_pending_checkpoint_writes,
-	log_sys->n_log_ios,
-	(log_sys->n_log_ios - log_sys->n_log_ios_old) / time_elapsed);
+	(ulong) log_sys->n_pending_writes,
+	(ulong) log_sys->n_pending_checkpoint_writes,
+	(ulong) log_sys->n_log_ios,
+	((log_sys->n_log_ios - log_sys->n_log_ios_old) / time_elapsed));
 
 	log_sys->n_log_ios_old = log_sys->n_log_ios;
 	log_sys->last_printout_time = current_time;
diff --git a/innobase/log/log0recv.c b/innobase/log/log0recv.c
index 942dde78e35..b01474753bd 100644
--- a/innobase/log/log0recv.c
+++ b/innobase/log/log0recv.c
@@ -165,7 +165,8 @@ recv_sys_empty_hash(void)
 		fprintf(stderr,
 "InnoDB: Error: %lu pages with log records were left unprocessed!\n"
 "InnoDB: Maximum page number with log records on it %lu\n",
-			recv_sys->n_addrs, recv_max_parsed_page_no);
+			(ulong) recv_sys->n_addrs, 
+			(ulong) recv_max_parsed_page_no);
 		ut_a(0);
 	}
 	
@@ -480,8 +481,9 @@ recv_find_max_checkpoint(
 				if (log_debug_writes) {
 					fprintf(stderr, 
 	    "InnoDB: Checkpoint in group %lu at %lu invalid, %lu\n",
-						group->id, field,
-                                 mach_read_from_4(buf
+						(ulong) group->id,
+						(ulong) field,
+                                 (ulong) mach_read_from_4(buf
 					      + LOG_CHECKPOINT_CHECKSUM_1));
 
 				}
@@ -501,7 +503,8 @@ recv_find_max_checkpoint(
 			if (log_debug_writes) {
 				fprintf(stderr, 
 			"InnoDB: Checkpoint number %lu found in group %lu\n",
-				ut_dulint_get_low(checkpoint_no), group->id);
+				(ulong) ut_dulint_get_low(checkpoint_no),
+				(ulong) group->id);
 			}
 				
 			if (ut_dulint_cmp(checkpoint_no, max_no) >= 0) {
@@ -1136,8 +1139,9 @@ recv_recover_page(
 			if (log_debug_writes) {
 				fprintf(stderr, 
      "InnoDB: Applying log rec type %lu len %lu to space %lu page no %lu\n",
-			(ulint)recv->type, recv->len, recv_addr->space,
-				recv_addr->page_no);
+					(ulong) recv->type, (ulong) recv->len,
+					(ulong) recv_addr->space,
+					(ulong) recv_addr->page_no);
 			}
 					
 			recv_parse_or_apply_log_rec_body(recv->type, buf,
@@ -1327,7 +1331,7 @@ loop:
 		             / hash_get_n_cells(recv_sys->addr_hash)) {
 
 		        fprintf(stderr, "%lu ",
-			  (i * 100) / hash_get_n_cells(recv_sys->addr_hash));
+				(ulong) ((i * 100) / hash_get_n_cells(recv_sys->addr_hash)));
 		}
 	}
 
@@ -1833,19 +1837,19 @@ recv_report_corrupt_log(
 "InnoDB: ############### CORRUPT LOG RECORD FOUND\n"
 "InnoDB: Log record type %lu, space id %lu, page number %lu\n"
 "InnoDB: Log parsing proceeded successfully up to %lu %lu\n",
-	(ulint)type, space, page_no,
-	ut_dulint_get_high(recv_sys->recovered_lsn),
-	ut_dulint_get_low(recv_sys->recovered_lsn));
+	(ulong) type, (ulong) space, (ulong) page_no,
+	(ulong) ut_dulint_get_high(recv_sys->recovered_lsn),
+	(ulong) ut_dulint_get_low(recv_sys->recovered_lsn));
 
 	err_buf = ut_malloc(1000000);
 
 	fprintf(stderr,
 "InnoDB: Previous log record type %lu, is multi %lu\n"
 "InnoDB: Recv offset %lu, prev %lu\n",
-		recv_previous_parsed_rec_type,
-		recv_previous_parsed_rec_is_multi,
-		(ulint)(ptr - recv_sys->buf),
-		recv_previous_parsed_rec_offset);
+		(ulong) recv_previous_parsed_rec_type,
+		(ulong) recv_previous_parsed_rec_is_multi,
+		(ulong) (ptr - recv_sys->buf),
+		(ulong) recv_previous_parsed_rec_offset);
 
 	if ((ulint)(ptr - recv_sys->buf + 100)
 					> recv_previous_parsed_rec_offset
@@ -1959,7 +1963,8 @@ loop:
 		if (log_debug_writes) {
 			fprintf(stderr, 
 "InnoDB: Parsed a single log rec type %lu len %lu space %lu page no %lu\n",
-			(ulint)type, len, space, page_no);
+				(ulong) type, (ulong) len, (ulong) space,
+				(ulong) page_no);
 		}
 
 		if (type == MLOG_DUMMY_RECORD) {
@@ -2042,7 +2047,8 @@ loop:
 			if (log_debug_writes) {
 				fprintf(stderr, 
 "InnoDB: Parsed a multi log rec type %lu len %lu space %lu page no %lu\n",
-				(ulint)type, len, space, page_no);
+				(ulong) type, (ulong) len, (ulong) space,
+				(ulong) page_no);
 			}
 		
 			total_len += len;
@@ -2272,10 +2278,11 @@ recv_scan_log_recs(
 				fprintf(stderr,
 "InnoDB: Log block no %lu at lsn %lu %lu has\n"
 "InnoDB: ok header, but checksum field contains %lu, should be %lu\n",
-				no, ut_dulint_get_high(scanned_lsn),
-				ut_dulint_get_low(scanned_lsn),
-				log_block_get_checksum(log_block),
-				log_block_calc_checksum(log_block));
+				(ulong) no,
+				(ulong) ut_dulint_get_high(scanned_lsn),
+				(ulong) ut_dulint_get_low(scanned_lsn),
+				(ulong) log_block_get_checksum(log_block),
+				(ulong) log_block_calc_checksum(log_block));
 			}
 
 			/* Garbage or an incompletely written log block */
@@ -2380,8 +2387,8 @@ recv_scan_log_recs(
 
 			fprintf(stderr, 
 "InnoDB: Doing recovery: scanned up to log sequence number %lu %lu\n",
-				ut_dulint_get_high(*group_scanned_lsn),
-				ut_dulint_get_low(*group_scanned_lsn));
+				(ulong) ut_dulint_get_high(*group_scanned_lsn),
+				(ulong) ut_dulint_get_low(*group_scanned_lsn));
 		}
 	}
 
@@ -2451,9 +2458,9 @@ recv_group_scan_log_recs(
 	if (log_debug_writes) {
 		fprintf(stderr,
 	"InnoDB: Scanned group %lu up to log sequence number %lu %lu\n",
-				group->id,
-				ut_dulint_get_high(*group_scanned_lsn),
-				ut_dulint_get_low(*group_scanned_lsn));
+				(ulong) group->id,
+				(ulong) ut_dulint_get_high(*group_scanned_lsn),
+				(ulong) ut_dulint_get_low(*group_scanned_lsn));
 	}
 }
 
@@ -2597,12 +2604,12 @@ recv_recovery_from_checkpoint_start(
 "InnoDB: sequence numbers stamped to ibdata file headers are between\n"
 "InnoDB: %lu %lu and %lu %lu.\n"
 "InnoDB: ##########################################################\n",
-				ut_dulint_get_high(checkpoint_lsn),
-				ut_dulint_get_low(checkpoint_lsn),
-				ut_dulint_get_high(min_flushed_lsn),
-				ut_dulint_get_low(min_flushed_lsn),
-				ut_dulint_get_high(max_flushed_lsn),
-				ut_dulint_get_low(max_flushed_lsn));
+				(ulong) ut_dulint_get_high(checkpoint_lsn),
+				(ulong) ut_dulint_get_low(checkpoint_lsn),
+				(ulong) ut_dulint_get_high(min_flushed_lsn),
+				(ulong) ut_dulint_get_low(min_flushed_lsn),
+				(ulong) ut_dulint_get_high(max_flushed_lsn),
+				(ulong) ut_dulint_get_low(max_flushed_lsn));
 			}
 
 	    	   	recv_needed_recovery = TRUE;
@@ -2637,8 +2644,8 @@ recv_recovery_from_checkpoint_start(
 			fprintf(stderr, 
 "  InnoDB: Starting log scan based on checkpoint at\n"
 "InnoDB: log sequence number %lu %lu.\n",
-		 			ut_dulint_get_high(checkpoint_lsn),
-					ut_dulint_get_low(checkpoint_lsn));
+		 			(ulong) ut_dulint_get_high(checkpoint_lsn),
+					(ulong) ut_dulint_get_low(checkpoint_lsn));
 		} else {
 			/* Init the doublewrite buffer memory structure */
 			trx_sys_doublewrite_init_or_restore_pages(FALSE);
@@ -2722,10 +2729,10 @@ recv_recovery_from_checkpoint_start(
 "  InnoDB: ERROR: We were only able to scan the log up to\n"
 "InnoDB: %lu %lu, but a checkpoint was at %lu %lu.\n"
 "InnoDB: It is possible that the database is now corrupt!\n",
-			 ut_dulint_get_high(group_scanned_lsn),
-			 ut_dulint_get_low(group_scanned_lsn),
-			 ut_dulint_get_high(checkpoint_lsn),
-			 ut_dulint_get_low(checkpoint_lsn));
+			 (ulong) ut_dulint_get_high(group_scanned_lsn),
+			 (ulong) ut_dulint_get_low(group_scanned_lsn),
+			 (ulong) ut_dulint_get_high(checkpoint_lsn),
+			 (ulong) ut_dulint_get_low(checkpoint_lsn));
 	}
 
 	if (ut_dulint_cmp(group_scanned_lsn, recv_max_page_lsn) < 0) {
@@ -2734,10 +2741,10 @@ recv_recovery_from_checkpoint_start(
 "  InnoDB: ERROR: We were only able to scan the log up to %lu %lu\n"
 "InnoDB: but a database page a had an lsn %lu %lu. It is possible that the\n"
 "InnoDB: database is now corrupt!\n",
-			 ut_dulint_get_high(group_scanned_lsn),
-			 ut_dulint_get_low(group_scanned_lsn),
-			 ut_dulint_get_high(recv_max_page_lsn),
-			 ut_dulint_get_low(recv_max_page_lsn));
+			 (ulong) ut_dulint_get_high(group_scanned_lsn),
+			 (ulong) ut_dulint_get_low(group_scanned_lsn),
+			 (ulong) ut_dulint_get_high(recv_max_page_lsn),
+			 (ulong) ut_dulint_get_low(recv_max_page_lsn));
 	}
 
 	if (ut_dulint_cmp(recv_sys->recovered_lsn, checkpoint_lsn) < 0) {
@@ -2770,10 +2777,10 @@ recv_recovery_from_checkpoint_start(
 			fprintf(stderr,
 "InnoDB: Warning: we did not need to do crash recovery, but log scan\n"
 "InnoDB: progressed past the checkpoint lsn %lu %lu up to lsn %lu %lu\n",
-			 ut_dulint_get_high(checkpoint_lsn),
-			 ut_dulint_get_low(checkpoint_lsn),
-			 ut_dulint_get_high(recv_sys->recovered_lsn),
-			 ut_dulint_get_low(recv_sys->recovered_lsn));
+			 (ulong) ut_dulint_get_high(checkpoint_lsn),
+			 (ulong) ut_dulint_get_low(checkpoint_lsn),
+			 (ulong) ut_dulint_get_high(recv_sys->recovered_lsn),
+			 (ulong) ut_dulint_get_low(recv_sys->recovered_lsn));
 		}
 	} else {
 		srv_start_lsn = recv_sys->recovered_lsn;
@@ -2950,7 +2957,7 @@ recv_reset_log_files_for_backup(
 
 	for (i = 0; i < n_log_files; i++) {
 
-		sprintf(name, "%sib_logfile%lu", log_dir, i);
+		sprintf(name, "%sib_logfile%lu", log_dir, (ulong) i);
 
 		log_file = os_file_create_simple(name, OS_FILE_CREATE,
 						OS_FILE_READ_WRITE, &success);
@@ -2962,8 +2969,8 @@ recv_reset_log_files_for_backup(
 		}
 
 		printf(
-"Setting log file size to %lu %lu\n", ut_get_high32(log_file_size),
-						log_file_size & 0xFFFFFFFFUL);
+"Setting log file size to %lu %lu\n", (ulong) ut_get_high32(log_file_size),
+				      (ulong) (log_file_size & 0xFFFFFFFFUL));
 
 		success = os_file_set_size(name, log_file,
 					log_file_size & 0xFFFFFFFFUL,
@@ -2971,8 +2978,9 @@ recv_reset_log_files_for_backup(
 
 		if (!success) {
 			printf(
-"InnoDB: Cannot set %s size to %lu %lu\n", name, ut_get_high32(log_file_size),
-						log_file_size & 0xFFFFFFFFUL);
+"InnoDB: Cannot set %s size to %lu %lu\n", name,
+					  (ulong) ut_get_high32(log_file_size),
+					  (ulong) (log_file_size & 0xFFFFFFFFUL));
 			exit(1);
 		}
 
@@ -2987,7 +2995,7 @@ recv_reset_log_files_for_backup(
 	log_block_init_in_old_format(buf + LOG_FILE_HDR_SIZE, lsn);
 	log_block_set_first_rec_group(buf + LOG_FILE_HDR_SIZE,
 							LOG_BLOCK_HDR_SIZE);
-	sprintf(name, "%sib_logfile%lu", log_dir, 0UL);
+	sprintf(name, "%sib_logfile%lu", log_dir, (ulong) 0);
 
 	log_file = os_file_create_simple(name, OS_FILE_OPEN,
 						OS_FILE_READ_WRITE, &success);
@@ -3151,9 +3159,9 @@ ask_again:
 		if (log_debug_writes) {
 			fprintf(stderr, 
 "InnoDB: Archive read starting at lsn %lu %lu, len %lu from file %s\n",
-					ut_dulint_get_high(start_lsn),
-					ut_dulint_get_low(start_lsn),
-					len, name);
+					(ulong) ut_dulint_get_high(start_lsn),
+					(ulong) ut_dulint_get_low(start_lsn),
+					(ulong) len, name);
 		}
 
 		fil_io(OS_FILE_READ | OS_FILE_LOG, TRUE,
@@ -3234,7 +3242,7 @@ recv_recovery_from_archive_start(
 	if (!group) {
 		fprintf(stderr,
 		"InnoDB: There is no log group defined with id %lu!\n",
-								group_id);
+							   (ulong) group_id);
 		return(DB_ERROR);
 	}
 
diff --git a/innobase/mem/mem0dbg.c b/innobase/mem/mem0dbg.c
index 1ff44bd8967..004197a5b8e 100644
--- a/innobase/mem/mem0dbg.c
+++ b/innobase/mem/mem0dbg.c
@@ -333,7 +333,7 @@ mem_hash_remove(
 	if (node == NULL) {
 		printf(
     	    "Memory heap or buffer freed in %s line %lu did not exist.\n",
-			file_name, line);
+			file_name, (ulong) line);
 		ut_error;
 	}
 
@@ -348,9 +348,10 @@ mem_hash_remove(
 	if (error) {
 	        printf(
 "Inconsistency in memory heap or buffer n:o %lu created\n",
-							node->nth_heap);
+							(ulong) node->nth_heap);
 		printf("in %s line %lu and tried to free in %s line %lu.\n",
-	  			node->file_name, node->line, file_name, line);
+		       node->file_name, (ulong) node->line,
+		       file_name, (ulong) line);
 
 		printf(
 "Hex dump of 400 bytes around memory heap first block start:\n");
@@ -443,8 +444,8 @@ mem_heap_validate_or_print(
 		    && (mem_block_get_len(block) > UNIV_PAGE_SIZE)) {
 
 			fprintf(stderr,
-"InnoDB: Error: mem block %lx length %lu > UNIV_PAGE_SIZE\n", (ulint)block,
-				     mem_block_get_len(block));
+"InnoDB: Error: mem block %lx length %lu > UNIV_PAGE_SIZE\n", (ulong) block,
+				(ulong) mem_block_get_len(block));
 		    	/* error */
 
 		    	return;
@@ -556,7 +557,8 @@ mem_heap_print(
 				&us_size, &phys_size, &n_blocks);
 	printf(
   "\nheap type: %lu; size: user size %lu; physical size %lu; blocks %lu.\n",
-			heap->type, us_size, phys_size, n_blocks);
+			(ulong) heap->type, (ulong) us_size,
+			(ulong) phys_size, (ulong) n_blocks);
 	ut_a(!error);
 }
 
@@ -894,8 +896,8 @@ mem_analyze_corruption(
 			    if (*((ulint*)p) == MEM_BLOCK_MAGIC_N) {
 				fprintf(stderr,
 			"Mem block at - %lu, file %s, line %lu\n",
-				dist, p + sizeof(ulint),
-				*(ulint*)(p + 8 + sizeof(ulint)));
+				(ulong) dist, (p + sizeof(ulint)),
+				(ulong) (*(ulint*)(p + 8 + sizeof(ulint))));
 
 				break;
 			    }
@@ -903,8 +905,8 @@ mem_analyze_corruption(
 			    if (*((ulint*)p) == MEM_FREED_BLOCK_MAGIC_N) {
 				fprintf(stderr,
 			"Freed mem block at - %lu, file %s, line %lu\n",
-				dist, p + sizeof(ulint),
-				*(ulint*)(p + 8 + sizeof(ulint)));
+				(ulong) dist, (p + sizeof(ulint)),
+				(ulong) (*(ulint*)(p + 8 + sizeof(ulint))));
 
 				break;
 			    }
@@ -931,8 +933,8 @@ mem_analyze_corruption(
 			    if (*((ulint*)p) == MEM_BLOCK_MAGIC_N) {
 				fprintf(stderr,
 			"Mem block at + %lu, file %s, line %lu\n",
-				dist, p + sizeof(ulint),
-				*(ulint*)(p + 8 + sizeof(ulint)));
+				(ulong) dist, (p + sizeof(ulint)),
+				(ulong) (*(ulint*)(p + 8 + sizeof(ulint))));
 
 				break;
 			    }
@@ -940,8 +942,8 @@ mem_analyze_corruption(
 			    if (*((ulint*)p) == MEM_FREED_BLOCK_MAGIC_N) {
 				fprintf(stderr,
 			"Freed mem block at + %lu, file %s, line %lu\n",
-				dist, p + sizeof(ulint),
-				*(ulint*)(p + 8 + sizeof(ulint)));
+				(ulong) dist, (p + sizeof(ulint)),
+				(ulong) (*(ulint*)(p + 8 + sizeof(ulint))));
 
 				break;
 			    }
diff --git a/innobase/mem/mem0pool.c b/innobase/mem/mem0pool.c
index 274daae1d4e..2817e1f12d4 100644
--- a/innobase/mem/mem0pool.c
+++ b/innobase/mem/mem0pool.c
@@ -279,7 +279,8 @@ mem_pool_fill_free_list(
 	                fprintf(stderr,
 "  InnoDB: Error: mem pool free list %lu length is %lu\n"
 "InnoDB: though the list is empty!\n",
-			i + 1, UT_LIST_GET_LEN(pool->free_list[i + 1]));
+			(ulong) i + 1,
+			(ulong) UT_LIST_GET_LEN(pool->free_list[i + 1]));
 		}
 
 		ret = mem_pool_fill_free_list(i + 1, pool);
@@ -360,7 +361,7 @@ mem_area_alloc(
 	        fprintf(stderr,
 "InnoDB: Error: Removing element from mem pool free list %lu though the\n"
 "InnoDB: element is not marked free!\n",
-			n);
+			(ulong) n);
 
 		mem_analyze_corruption((byte*)area);
 
@@ -380,7 +381,7 @@ mem_area_alloc(
 	        fprintf(stderr,
 "InnoDB: Error: Removing element from mem pool free list %lu\n"
 "InnoDB: though the list length is 0!\n",
-			n);
+			(ulong) n);
 		mem_analyze_corruption((byte*)area);
 
 		ut_a(0);
@@ -504,7 +505,7 @@ mem_area_free(
 		        fprintf(stderr,
 "InnoDB: Error: Memory area size %lu, next area size %lu not a power of 2!\n"
 "InnoDB: Possibly a memory overrun of the buffer being freed here.\n",
-			  size, next_size);
+			  (ulong) size, (ulong) next_size);
 			mem_analyze_corruption((byte*)area);
 
 			ut_a(0);
@@ -632,13 +633,13 @@ mem_pool_print_info(
 
 			fprintf(outfile,
 			  "Free list length %lu for blocks of size %lu\n",
-			  UT_LIST_GET_LEN(pool->free_list[i]),
-			  ut_2_exp(i));
+			  (ulong) UT_LIST_GET_LEN(pool->free_list[i]),
+			  (ulong) ut_2_exp(i));
 		}	
 	}
 
-	fprintf(outfile, "Pool size %lu, reserved %lu.\n", pool->size,
-							pool->reserved);
+	fprintf(outfile, "Pool size %lu, reserved %lu.\n", (ulong) pool->size,
+						       (ulong) pool->reserved);
 	mutex_exit(&(pool->mutex));
 }
 
diff --git a/innobase/mtr/mtr0log.c b/innobase/mtr/mtr0log.c
index 898778dda53..4b5d7e61de6 100644
--- a/innobase/mtr/mtr0log.c
+++ b/innobase/mtr/mtr0log.c
@@ -58,7 +58,7 @@ mlog_write_initial_log_record(
 	if (ptr < buf_pool->frame_zero || ptr >= buf_pool->high_end) {
 		fprintf(stderr,
 	"InnoDB: Error: trying to write to a stray memory location %lx\n",
-			(ulint)ptr);
+			(ulong) ptr);
 		ut_a(0);
 	}
 
@@ -221,7 +221,7 @@ mlog_write_ulint(
 	if (ptr < buf_pool->frame_zero || ptr >= buf_pool->high_end) {
 		fprintf(stderr,
 	"InnoDB: Error: trying to write to a stray memory location %lx\n",
-			(ulint)ptr);
+			(ulong) ptr);
 		ut_a(0);
 	}
 
@@ -269,7 +269,7 @@ mlog_write_dulint(
 	if (ptr < buf_pool->frame_zero || ptr >= buf_pool->high_end) {
 		fprintf(stderr,
 	"InnoDB: Error: trying to write to a stray memory location %lx\n",
-			(ulint)ptr);
+			(ulong) ptr);
 		ut_a(0);
 	}
 
@@ -313,7 +313,7 @@ mlog_write_string(
 	if (ptr < buf_pool->frame_zero || ptr >= buf_pool->high_end) {
 		fprintf(stderr,
 	"InnoDB: Error: trying to write to a stray memory location %lx\n",
-			(ulint)ptr);
+			(ulong) ptr);
 		ut_a(0);
 	}
 	ut_ad(ptr && mtr);
diff --git a/innobase/mtr/mtr0mtr.c b/innobase/mtr/mtr0mtr.c
index e9a6e39d98f..63ce491523b 100644
--- a/innobase/mtr/mtr0mtr.c
+++ b/innobase/mtr/mtr0mtr.c
@@ -263,11 +263,11 @@ mtr_first_to_modify_page_after_backup(
 							backup_lsn) <= 0) {
 
 				printf("Page %lu newest %lu backup %lu\n",
-					block->offset,
-					ut_dulint_get_low(
+					(ulong) block->offset,
+					(ulong) ut_dulint_get_low(
 					buf_frame_get_newest_modification(
 							block->frame)),
-					ut_dulint_get_low(backup_lsn));
+					(ulong) ut_dulint_get_low(backup_lsn));
 					
 				ret = TRUE;
 			}
@@ -519,6 +519,6 @@ mtr_print(
 {
 	printf(
 	"Mini-transaction handle: memo size %lu bytes log size %lu bytes\n",
-		dyn_array_get_data_size(&(mtr->memo)),
-		dyn_array_get_data_size(&(mtr->log)));
+		(ulong) dyn_array_get_data_size(&(mtr->memo)),
+		(ulong) dyn_array_get_data_size(&(mtr->log)));
 }
diff --git a/innobase/os/os0file.c b/innobase/os/os0file.c
index fe5b4f9c096..a87ab974b83 100644
--- a/innobase/os/os0file.c
+++ b/innobase/os/os0file.c
@@ -216,7 +216,7 @@ os_file_get_last_error(
 
 		ut_print_timestamp(stderr);
 	     	fprintf(stderr,
-  "  InnoDB: Operating system error number %lu in a file operation.\n", err);
+  "  InnoDB: Operating system error number %lu in a file operation.\n", (ulong) err);
 
 		if (err == ERROR_PATH_NOT_FOUND) {
 			fprintf(stderr,
@@ -1499,7 +1499,7 @@ os_file_set_size(
 		    != offset / (ib_longlong)(100 * 1024 * 1024)) {
 
 		        fprintf(stderr, " %lu00",
-				(ulint)((offset + n_bytes)
+				(ulong) ((offset + n_bytes)
 					/ (ib_longlong)(100 * 1024 * 1024)));
 		}
 		
@@ -1858,9 +1858,9 @@ error_handling:
 	fprintf(stderr,
 "InnoDB: Fatal error: cannot read from file. OS error number %lu.\n",
 #ifdef __WIN__
-		(ulint)GetLastError()
+		(ulong) GetLastError()
 #else
-		(ulint)errno
+		(ulong) errno
 #endif
 		);
 	fflush(stderr);
@@ -2013,8 +2013,8 @@ retry:
 "InnoDB: offset %lu %lu. Operating system error number %lu.\n"
 "InnoDB: Look from section 13.2 at http://www.innodb.com/ibman.html\n"
 "InnoDB: what the error number means.\n",
-			name, offset_high, offset,
-			(ulint)GetLastError());
+			name, (ulong) offset_high, (ulong) offset,
+			(ulong) GetLastError());
 
 		return(FALSE);
 	} 
@@ -2060,12 +2060,12 @@ retry:
 "InnoDB: Operating system error number %lu.\n"
 "InnoDB: Check that your OS and file system support files of this size.\n"
 "InnoDB: Check also that the disk is not full or a disk quota exceeded.\n",
-			name, offset_high, offset, n, (ulint)len,
-			err);
+			name, (ulong) offset_high, (ulong) offset,
+			(ulong) n, (ulong) len, (ulong) err);
 
 		if (strerror((int)err) != NULL) {
 			fprintf(stderr,
-"InnoDB: Error number %lu means '%s'.\n", err, strerror((int)err));
+"InnoDB: Error number %lu means '%s'.\n", (ulong) err, strerror((int)err));
 		}
 
 		fprintf(stderr,
@@ -3151,7 +3151,7 @@ restart:
 
 			if (os_aio_print_debug) {
 				fprintf(stderr,
-"InnoDB: i/o for slot %lu already done, returning\n", i);
+"InnoDB: i/o for slot %lu already done, returning\n", (ulong) i);
 			}
 
 			ret = TRUE;
@@ -3298,8 +3298,8 @@ consecutive_loop:
 	if (os_aio_print_debug) {
 		fprintf(stderr,
 "InnoDB: doing i/o of type %lu at offset %lu %lu, length %lu\n",
-			slot->type, slot->offset_high, slot->offset,
-			total_len);
+			(ulong) slot->type, (ulong) slot->offset_high,
+			(ulong) slot->offset, (ulong) total_len);
 	}
 
 	/* Do the i/o with ordinary, synchronous i/o functions: */
@@ -3309,8 +3309,9 @@ consecutive_loop:
 			    || (slot->offset % UNIV_PAGE_SIZE != 0)) {
 				fprintf(stderr,
 "InnoDB: Error: trying a displaced write to %s %lu %lu, len %lu\n",
-					slot->name, slot->offset_high,
-					slot->offset, total_len);
+					slot->name, (ulong) slot->offset_high,
+					(ulong) slot->offset,
+					(ulong) total_len);
 				ut_a(0);
 			}
 			  
@@ -3409,7 +3410,7 @@ recommended_sleep:
 	if (os_aio_print_debug) {
 		fprintf(stderr,
 "InnoDB: i/o handler thread for i/o segment %lu wakes up\n",
-			global_segment);
+			(ulong) global_segment);
 	}
 	
 	goto restart;
@@ -3491,7 +3492,8 @@ os_aio_print(
 	}
 
 	for (i = 0; i < srv_n_file_io_threads; i++) {
-		buf += sprintf(buf, "I/O thread %lu state: %s (%s)\n", i,
+		buf += sprintf(buf, "I/O thread %lu state: %s (%s)\n",
+			                (ulong) i,
 					srv_io_thread_op_info[i],
 					srv_io_thread_function[i]);
 	}
@@ -3523,7 +3525,7 @@ loop:
 
 	ut_a(array->n_reserved == n_reserved);
 
-	buf += sprintf(buf, " %lu", n_reserved);
+	buf += sprintf(buf, " %lu", (ulong) n_reserved);
 	
 	os_mutex_exit(array->mutex);
 
@@ -3563,15 +3565,18 @@ loop:
 
 	buf += sprintf(buf,
 		"Pending flushes (fsync) log: %lu; buffer pool: %lu\n",
-	       fil_n_pending_log_flushes, fil_n_pending_tablespace_flushes);
+	       (ulong) fil_n_pending_log_flushes,
+	       (ulong) fil_n_pending_tablespace_flushes);
 	buf += sprintf(buf,
 		"%lu OS file reads, %lu OS file writes, %lu OS fsyncs\n",
-		os_n_file_reads, os_n_file_writes, os_n_fsyncs);
+		(ulong) os_n_file_reads, (ulong) os_n_file_writes,
+		(ulong) os_n_fsyncs);
 
 	if (os_file_n_pending_preads != 0 || os_file_n_pending_pwrites != 0) {
 	        buf += sprintf(buf,
 		    "%lu pending preads, %lu pending pwrites\n",
-		    os_file_n_pending_preads, os_file_n_pending_pwrites);
+		    (ulong) os_file_n_pending_preads,
+		    (ulong) os_file_n_pending_pwrites);
 	}
 
 	if (os_n_file_reads == os_n_file_reads_old) {
@@ -3585,7 +3590,7 @@ loop:
 "%.2f reads/s, %lu avg bytes/read, %.2f writes/s, %.2f fsyncs/s\n",
 		(os_n_file_reads - os_n_file_reads_old)
 		/ time_elapsed,
-		(ulint)avg_bytes_read,
+		(ulong)avg_bytes_read,
 		(os_n_file_writes - os_n_file_writes_old)
 		/ time_elapsed,
 		(os_n_fsyncs - os_n_fsyncs_old)
diff --git a/innobase/os/os0sync.c b/innobase/os/os0sync.c
index 827d68501db..7cbaf1f5123 100644
--- a/innobase/os/os0sync.c
+++ b/innobase/os/os0sync.c
@@ -125,7 +125,7 @@ os_event_create(
 	if (!event->handle) {
 	        fprintf(stderr,
 "InnoDB: Could not create a Windows event semaphore; Windows error %lu\n",
-		  (ulint)GetLastError());
+		  (ulong) GetLastError());
 	}
 #else /* Unix */
 	os_event_t	event;
@@ -182,7 +182,7 @@ os_event_create_auto(
 	if (!event->handle) {
 	        fprintf(stderr,
 "InnoDB: Could not create a Windows auto event semaphore; Windows error %lu\n",
-		  (ulint)GetLastError());
+		  (ulong) GetLastError());
 	}
 
         /* Put to the list of events */
@@ -412,7 +412,7 @@ os_event_wait_multiple(
 					FALSE,	   /* Wait for any 1 event */
 					INFINITE); /* Infinite wait time
 						   limit */
-	ut_a(index >= WAIT_OBJECT_0);
+	ut_a(index >= WAIT_OBJECT_0);	/* NOTE: Pointless comparision */
 	ut_a(index < WAIT_OBJECT_0 + n);
 
 	if (srv_shutdown_state == SRV_SHUTDOWN_EXIT_THREADS) {
diff --git a/innobase/page/page0cur.c b/innobase/page/page0cur.c
index fa4fa94620a..89dad4f268f 100644
--- a/innobase/page/page0cur.c
+++ b/innobase/page/page0cur.c
@@ -706,8 +706,10 @@ page_cur_parse_insert_rec(
 		"Is short %lu, info_bits %lu, offset %lu, o_offset %lu\n"
                     "mismatch index %lu, end_seg_len %lu\n"
                     "parsed len %lu\n",
-                    is_short, info_bits, offset, origin_offset,
-                    mismatch_index, end_seg_len, (ulint)(ptr - ptr2));
+		    (ulong) is_short, (ulong) info_bits, (ulong) offset,
+		    (ulong) origin_offset,
+		    (ulong) mismatch_index, (ulong) end_seg_len,
+		    (ulong) (ptr - ptr2));
 
 	       printf("Dump of 300 bytes of log:\n");
 	       ut_print_buf(ptr2, 300);
diff --git a/innobase/page/page0page.c b/innobase/page/page0page.c
index 2422f0ff87e..9c9e1f4156c 100644
--- a/innobase/page/page0page.c
+++ b/innobase/page/page0page.c
@@ -97,13 +97,13 @@ page_dir_find_owner_slot(
  		if (i == 0) {
 			fprintf(stderr,
 		"InnoDB: Probable data corruption on page %lu\n",
-			buf_frame_get_page_no(page));
+			(ulong) buf_frame_get_page_no(page));
 
 			rec_sprintf(err_buf, 900, original_rec);
 
 	  		fprintf(stderr,
 		"InnoDB: Original record %s\n"
-		"InnoDB: on that page. Steps %lu.\n", err_buf, steps);
+		"InnoDB: on that page. Steps %lu.\n", err_buf, (ulong) steps);
 
 			rec_sprintf(err_buf, 900, rec);
 
@@ -466,9 +466,9 @@ page_copy_rec_list_end_no_locks(
 
 			fprintf(stderr,
 "InnoDB: rec offset %lu, cur1 offset %lu, cur2 offset %lu\n",
-			      (ulint)(rec - page),
-			      (ulint)(page_cur_get_rec(&cur1) - page),
-			      (ulint)(page_cur_get_rec(&cur2) - new_page));
+			      (ulong)(rec - page),
+			      (ulong)(page_cur_get_rec(&cur1) - page),
+			      (ulong)(page_cur_get_rec(&cur2) - new_page));
 			ut_a(0);
 		}
 
@@ -1152,9 +1152,9 @@ page_rec_print(
 	rec_print(rec);
 	printf(
      		"            n_owned: %lu; heap_no: %lu; next rec: %lu\n",
-		rec_get_n_owned(rec),
-		rec_get_heap_no(rec),
-		rec_get_next_offs(rec));
+		(ulong) rec_get_n_owned(rec),
+		(ulong) rec_get_heap_no(rec),
+		(ulong) rec_get_next_offs(rec));
 
 	page_rec_check(rec);
 	rec_validate(rec);
@@ -1178,9 +1178,9 @@ page_dir_print(
 	
 	printf("--------------------------------\n");
 	printf("PAGE DIRECTORY\n");
-	printf("Page address %lx\n", (ulint)page);
+	printf("Page address %lx\n", (ulong)page);
 	printf("Directory stack top at offs: %lu; number of slots: %lu\n", 
-		(ulint)(page_dir_get_nth_slot(page, n - 1) - page), n);
+		(ulong)(page_dir_get_nth_slot(page, n - 1) - page), (ulong) n);
 	for (i = 0; i < n; i++) {
 		slot = page_dir_get_nth_slot(page, i);
 		if ((i == pr_n) && (i < n - pr_n)) {
@@ -1189,11 +1189,11 @@ page_dir_print(
 	    	if ((i < pr_n) || (i >= n - pr_n)) {
 	   		printf(
 	   	   "Contents of slot: %lu: n_owned: %lu, rec offs: %lu\n",
-			i, page_dir_slot_get_n_owned(slot),
-			(ulint)(page_dir_slot_get_rec(slot) - page));
+			(ulong) i, (ulong) page_dir_slot_get_n_owned(slot),
+			(ulong)(page_dir_slot_get_rec(slot) - page));
 	    	}
 	}
-	printf("Total of %lu records\n", 2 + page_get_n_recs(page));	
+	printf("Total of %lu records\n", (ulong) (2 + page_get_n_recs(page)));
 	printf("--------------------------------\n");
 }	
 	
@@ -1214,7 +1214,7 @@ page_print_list(
 
 	printf("--------------------------------\n");
 	printf("PAGE RECORD LIST\n");
-	printf("Page address %lu\n", (ulint)page);
+	printf("Page address %lu\n", (ulong) page);
 
 	n_recs = page_get_n_recs(page);
 
@@ -1251,7 +1251,7 @@ page_print_list(
 		count++;	
 	}
 
-	printf("Total of %lu records \n", count + 1);	
+	printf("Total of %lu records \n", (ulong) (count + 1));
 	printf("--------------------------------\n");
 }	
 
@@ -1265,22 +1265,22 @@ page_header_print(
 {
 	printf("--------------------------------\n");
 	printf("PAGE HEADER INFO\n");
-	printf("Page address %lx, n records %lu\n", (ulint)page,
-		page_header_get_field(page, PAGE_N_RECS));
+	printf("Page address %lx, n records %lu\n", (ulong) page,
+	        (ulong) page_header_get_field(page, PAGE_N_RECS));
 
 	printf("n dir slots %lu, heap top %lu\n",
-		page_header_get_field(page, PAGE_N_DIR_SLOTS),
-		page_header_get_field(page, PAGE_HEAP_TOP));
+		(ulong) page_header_get_field(page, PAGE_N_DIR_SLOTS),
+		(ulong) page_header_get_field(page, PAGE_HEAP_TOP));
 
 	printf("Page n heap %lu, free %lu, garbage %lu\n",
-		page_header_get_field(page, PAGE_N_HEAP),
-		page_header_get_field(page, PAGE_FREE),
-		page_header_get_field(page, PAGE_GARBAGE));
+		(ulong) page_header_get_field(page, PAGE_N_HEAP),
+		(ulong) page_header_get_field(page, PAGE_FREE),
+		(ulong) page_header_get_field(page, PAGE_GARBAGE));
 
 	printf("Page last insert %lu, direction %lu, n direction %lu\n",
-		page_header_get_field(page, PAGE_LAST_INSERT),
-		page_header_get_field(page, PAGE_DIRECTION),
-		page_header_get_field(page, PAGE_N_DIRECTION));
+		(ulong) page_header_get_field(page, PAGE_LAST_INSERT),
+		(ulong) page_header_get_field(page, PAGE_DIRECTION),
+		(ulong) page_header_get_field(page, PAGE_N_DIRECTION));
 }
 
 /*******************************************************************
@@ -1325,15 +1325,15 @@ page_rec_validate(
 	if (!(n_owned <= PAGE_DIR_SLOT_MAX_N_OWNED)) {
 		fprintf(stderr,
 			"InnoDB: Dir slot of rec %lu, n owned too big %lu\n",
-				(ulint)(rec - page), n_owned);
+				(ulong)(rec - page), (ulong) n_owned);
 		return(FALSE);
 	}
 
 	if (!(heap_no < page_header_get_field(page, PAGE_N_HEAP))) {
 		fprintf(stderr,
 		"InnoDB: Heap no of rec %lu too big %lu %lu\n",
-				(ulint)(rec - page), heap_no,
-				page_header_get_field(page, PAGE_N_HEAP));
+				(ulong)(rec - page), (ulong) heap_no,
+				(ulong) page_header_get_field(page, PAGE_N_HEAP));
 		return(FALSE);
 	}
 	
@@ -1399,7 +1399,7 @@ page_simple_validate(
 
 	if (n_slots > UNIV_PAGE_SIZE / 4) {
 		fprintf(stderr,
-	"InnoDB: Nonsensical number %lu of page dir slots\n", n_slots);
+	"InnoDB: Nonsensical number %lu of page dir slots\n", (ulong) n_slots);
 
 		goto func_exit;
 	}
@@ -1410,8 +1410,8 @@ page_simple_validate(
 
 		fprintf(stderr,
     "InnoDB: Record heap and dir overlap on a page, heap top %lu, dir %lu\n",
-       		(ulint)(page_header_get_ptr(page, PAGE_HEAP_TOP) - page),
-       		(ulint)(page_dir_get_nth_slot(page, n_slots - 1) - page));
+       		(ulong)(page_header_get_ptr(page, PAGE_HEAP_TOP) - page),
+       		(ulong)(page_dir_get_nth_slot(page, n_slots - 1) - page));
 
        		goto func_exit;
        	}
@@ -1432,7 +1432,7 @@ page_simple_validate(
 		if (rec > rec_heap_top) {
 			fprintf(stderr,
 			"InnoDB: Record %lu is above rec heap top %lu\n",
-			(ulint)(rec - page), (ulint)(rec_heap_top - page));
+			(ulong)(rec - page), (ulong)(rec_heap_top - page));
 
 			goto func_exit;
 		}
@@ -1443,8 +1443,9 @@ page_simple_validate(
 
 				fprintf(stderr,
 		"InnoDB: Wrong owned count %lu, %lu, rec %lu\n",
-				rec_get_n_owned(rec), own_count,
-				(ulint)(rec - page));
+				(ulong) rec_get_n_owned(rec),
+				(ulong) own_count,
+				(ulong)(rec - page));
 
 				goto func_exit;
 			}
@@ -1452,7 +1453,7 @@ page_simple_validate(
 			if (page_dir_slot_get_rec(slot) != rec) {
 				fprintf(stderr,
 		"InnoDB: Dir slot does not point to right rec %lu\n",
-					(ulint)(rec - page));
+					(ulong)(rec - page));
 
 				goto func_exit;
 			}
@@ -1474,8 +1475,8 @@ page_simple_validate(
 				|| rec_get_next_offs(rec) >= UNIV_PAGE_SIZE) {
 			fprintf(stderr,
 		"InnoDB: Next record offset nonsensical %lu for rec %lu\n",
-			  rec_get_next_offs(rec),
-			  (ulint)(rec - page));
+			  (ulong) rec_get_next_offs(rec),
+			  (ulong)(rec - page));
 
 			goto func_exit;
 		}
@@ -1485,7 +1486,7 @@ page_simple_validate(
 		if (count > UNIV_PAGE_SIZE) {
 			fprintf(stderr,
 		"InnoDB: Page record list appears to be circular %lu\n",
-								count);
+								(ulong) count);
 			goto func_exit;
 		}
 		
@@ -1501,13 +1502,14 @@ page_simple_validate(
 		
 	if (slot_no != n_slots - 1) {
 		fprintf(stderr, "InnoDB: n slots wrong %lu, %lu\n",
-			slot_no, n_slots - 1);
+			(ulong) slot_no, (ulong) (n_slots - 1));
 		goto func_exit;
 	}		
 
 	if (page_header_get_field(page, PAGE_N_RECS) + 2 != count + 1) {
 		fprintf(stderr, "InnoDB: n recs wrong %lu %lu\n",
-		page_header_get_field(page, PAGE_N_RECS) + 2,  count + 1);
+		(ulong) page_header_get_field(page, PAGE_N_RECS) + 2,
+		(ulong) (count + 1));
 
 		goto func_exit;
 	}
@@ -1520,7 +1522,7 @@ page_simple_validate(
 				|| rec >= page + UNIV_PAGE_SIZE) {
 			fprintf(stderr,
 		"InnoDB: Free list record has a nonsensical offset %lu\n",
-			(ulint)(rec - page));
+			(ulong)(rec - page));
 
 			goto func_exit;
 		}
@@ -1528,7 +1530,7 @@ page_simple_validate(
 		if (rec > rec_heap_top) {
 			fprintf(stderr,
 		"InnoDB: Free list record %lu is above rec heap top %lu\n",
-			(ulint)(rec - page), (ulint)(rec_heap_top - page));
+			(ulong)(rec - page), (ulong)(rec_heap_top - page));
 
 			goto func_exit;
 		}
@@ -1538,7 +1540,7 @@ page_simple_validate(
 		if (count > UNIV_PAGE_SIZE) {
 			fprintf(stderr,
 		"InnoDB: Page free list appears to be circular %lu\n",
-								count);
+							    (ulong) count);
 			goto func_exit;
 		}
 
@@ -1548,7 +1550,8 @@ page_simple_validate(
 	if (page_header_get_field(page, PAGE_N_HEAP) != count + 1) {
 
 		fprintf(stderr, "InnoDB: N heap is wrong %lu, %lu\n",
-		page_header_get_field(page, PAGE_N_HEAP), count + 1);
+		(ulong) page_header_get_field(page, PAGE_N_HEAP),
+		(ulong) (count + 1));
 
 		goto func_exit;
 	}
@@ -1589,7 +1592,7 @@ page_validate(
 	if (!page_simple_validate(page)) {
 		fprintf(stderr,
 "InnoDB: Apparent corruption in page %lu in index %s in table %s\n",
-			buf_frame_get_page_no(page), index->name,
+			(ulong) buf_frame_get_page_no(page), index->name,
 			index->table_name);
 
 		buf_page_print(page);
@@ -1616,8 +1619,8 @@ page_validate(
 			page_dir_get_nth_slot(page, n_slots - 1))) {
 		fprintf(stderr,
 "InnoDB: Record heap and dir overlap on a page in index %s, %lu, %lu\n",
-       		index->name, (ulint)page_header_get_ptr(page, PAGE_HEAP_TOP),
-       		(ulint)page_dir_get_nth_slot(page, n_slots - 1));
+       		index->name, (ulong)page_header_get_ptr(page, PAGE_HEAP_TOP),
+       		(ulong)page_dir_get_nth_slot(page, n_slots - 1));
 
        		goto func_exit;
        	}
@@ -1644,7 +1647,7 @@ page_validate(
 			if (!(1 == cmp_rec_rec(rec, old_rec, index))) {
 				fprintf(stderr,
 "InnoDB: Records in wrong order on page %lu index %s table %s\n",
-					buf_frame_get_page_no(page),
+					(ulong) buf_frame_get_page_no(page),
 					index->name,
 					index->table_name);
 
@@ -1687,7 +1690,8 @@ page_validate(
 			if (rec_get_n_owned(rec) != own_count) {
 				fprintf(stderr,
 			"InnoDB: Wrong owned count %lu, %lu, in index %s\n",
-				rec_get_n_owned(rec), own_count,
+				(ulong) rec_get_n_owned(rec),
+				(ulong) own_count,
 				index->name);
 
 				goto func_exit;
@@ -1718,7 +1722,7 @@ page_validate(
 				|| rec_get_next_offs(rec) >= UNIV_PAGE_SIZE) {
 			fprintf(stderr,
 		"InnoDB: Next record offset wrong %lu in index %s\n",
-			  rec_get_next_offs(rec), index->name);
+			  (ulong) rec_get_next_offs(rec), index->name);
 
 			goto func_exit;
 		}
@@ -1738,13 +1742,14 @@ page_validate(
 		
 	if (slot_no != n_slots - 1) {
 		fprintf(stderr, "InnoDB: n slots wrong %lu %lu in index %s\n",
-			slot_no, n_slots - 1, index->name);
+			(ulong) slot_no, (ulong) (n_slots - 1), index->name);
 		goto func_exit;
 	}		
 
 	if (page_header_get_field(page, PAGE_N_RECS) + 2 != count + 1) {
 		fprintf(stderr, "InnoDB: n recs wrong %lu %lu in index %s\n",
-		page_header_get_field(page, PAGE_N_RECS) + 2,  count + 1,
+		(ulong) page_header_get_field(page, PAGE_N_RECS) + 2,
+		(ulong) (count + 1),
 		index->name);
 
 		goto func_exit;
@@ -1753,7 +1758,7 @@ page_validate(
 	if (data_size != page_get_data_size(page)) {
 		fprintf(stderr,
 		"InnoDB: Summed data size %lu, returned by func %lu\n",
-			data_size, page_get_data_size(page));
+			(ulong) data_size, (ulong) page_get_data_size(page));
 		goto func_exit;
 	}
 
@@ -1789,8 +1794,9 @@ page_validate(
 
 		fprintf(stderr,
 		"InnoDB: N heap is wrong %lu %lu in index %s\n",
-			page_header_get_field(page, PAGE_N_HEAP), count + 1,
-				index->name);
+			(ulong) page_header_get_field(page, PAGE_N_HEAP),
+			(ulong) count + 1,
+			index->name);
 		goto func_exit;
 	}
 
@@ -1802,7 +1808,7 @@ func_exit:
 	if (ret == FALSE) {
 		fprintf(stderr,
 "InnoDB: Apparent corruption in page %lu in index %s in table %s\n",
-			buf_frame_get_page_no(page), index->name,
+			(ulong) buf_frame_get_page_no(page), index->name,
 			index->table_name);
 
 		buf_page_print(page);
diff --git a/innobase/read/read0read.c b/innobase/read/read0read.c
index 5c1d2d5418e..4a8aaee39ca 100644
--- a/innobase/read/read0read.c
+++ b/innobase/read/read0read.c
@@ -234,16 +234,16 @@ read_view_print(
 	ulint	i;
 	
 	fprintf(stderr, "Read view low limit trx n:o %lu %lu\n",
-			ut_dulint_get_high(view->low_limit_no),
-			ut_dulint_get_low(view->low_limit_no));
+			(ulong) ut_dulint_get_high(view->low_limit_no),
+			(ulong) ut_dulint_get_low(view->low_limit_no));
 
 	fprintf(stderr, "Read view up limit trx id %lu %lu\n",
-			ut_dulint_get_high(view->up_limit_id),
-			ut_dulint_get_low(view->up_limit_id));		
+			(ulong) ut_dulint_get_high(view->up_limit_id),
+			(ulong) ut_dulint_get_low(view->up_limit_id));		
 
 	fprintf(stderr, "Read view low limit trx id %lu %lu\n",
-			ut_dulint_get_high(view->low_limit_id),
-			ut_dulint_get_low(view->low_limit_id));
+			(ulong) ut_dulint_get_high(view->low_limit_id),
+			(ulong) ut_dulint_get_low(view->low_limit_id));
 
 	fprintf(stderr, "Read view individually stored trx ids:\n");
 
@@ -251,7 +251,7 @@ read_view_print(
 
 	for (i = 0; i < n_ids; i++) {
 		fprintf(stderr, "Read view trx id %lu %lu\n",
-			ut_dulint_get_high(read_view_get_nth_trx_id(view, i)),
-			ut_dulint_get_low(read_view_get_nth_trx_id(view, i)));
+			(ulong) ut_dulint_get_high(read_view_get_nth_trx_id(view, i)),
+			(ulong) ut_dulint_get_low(read_view_get_nth_trx_id(view, i)));
 	}
 }
diff --git a/innobase/rem/rem0cmp.c b/innobase/rem/rem0cmp.c
index 2e18e68ec43..abfba3a31c9 100644
--- a/innobase/rem/rem0cmp.c
+++ b/innobase/rem/rem0cmp.c
@@ -272,7 +272,8 @@ cmp_whole_field(
 				a, a_length, b, b_length));
 	default:
 	        fprintf(stderr,
-			"InnoDB: unknown type number %lu\n", data_type);
+			"InnoDB: unknown type number %lu\n",
+			(ulong) data_type);
 	        ut_a(0);
 	}
 
diff --git a/innobase/rem/rem0rec.c b/innobase/rem/rem0rec.c
index a151389798d..5a3996c9dce 100644
--- a/innobase/rem/rem0rec.c
+++ b/innobase/rem/rem0rec.c
@@ -107,7 +107,7 @@ rec_get_nth_field(
 
 	if (n > 1024) {
 		fprintf(stderr, "Error: trying to access field %lu in rec\n",
-									n);
+								(ulong) n);
 		ut_a(0);
 	}
 
@@ -474,7 +474,7 @@ rec_validate(
 
 	if ((n_fields == 0) || (n_fields > REC_MAX_N_FIELDS)) {
 		fprintf(stderr, "InnoDB: Error: record has %lu fields\n",
-								n_fields);
+							(ulong) n_fields);
 		return(FALSE);
 	}
 	
@@ -483,8 +483,8 @@ rec_validate(
 		
 		if (!((len < UNIV_PAGE_SIZE) || (len == UNIV_SQL_NULL))) {
 			fprintf(stderr,
-			"InnoDB: Error: record field %lu len %lu\n", i,
-								len);
+			"InnoDB: Error: record field %lu len %lu\n", (ulong) i,
+							(ulong) len);
 			return(FALSE);
 		}	
 
@@ -502,7 +502,8 @@ rec_validate(
 	if (len_sum != (ulint)(rec_get_end(rec) - rec)) {
 		fprintf(stderr,
 		"InnoDB: Error: record len should be %lu, len %lu\n",
-				len_sum, (ulint)(rec_get_end(rec) - rec));
+				(ulong) len_sum,
+			        (ulong) (rec_get_end(rec) - rec));
 		return(FALSE);
 	}	
 
@@ -537,13 +538,13 @@ rec_print(
 
 	printf(
 	    "PHYSICAL RECORD: n_fields %lu; 1-byte offs %s; info bits %lu\n",
-		n, offs, rec_get_info_bits(rec));
+		(ulong) n, offs, (ulong) rec_get_info_bits(rec));
 	
 	for (i = 0; i < n; i++) {
 
 		data = rec_get_nth_field(rec, i, &len);
 
-		printf(" %lu:", i);	
+		printf(" %lu:", (ulong) i);
 	
 		if (len != UNIV_SQL_NULL) {
 			if (len <= 30) {
@@ -556,7 +557,7 @@ rec_print(
 			}
 		} else {
 			printf(" SQL NULL, size %lu ",
-					rec_get_nth_field_size(rec, i));
+				      (ulong) rec_get_nth_field_size(rec, i));
 						
 		}
 		printf(";");
@@ -594,7 +595,8 @@ rec_sprintf(
 		return(k);
 	}
 	
-	k += sprintf(buf + k, "RECORD: info bits %lu", rec_get_info_bits(rec));
+	k += sprintf(buf + k, "RECORD: info bits %lu",
+		     (ulong) rec_get_info_bits(rec));
 	
 	for (i = 0; i < n; i++) {
 
@@ -605,7 +607,7 @@ rec_sprintf(
 		
 		data = rec_get_nth_field(rec, i, &len);
 
-		k += sprintf(buf + k, " %lu:", i);
+		k += sprintf(buf + k, " %lu:", (ulong) i);
 	
 		if (len != UNIV_SQL_NULL) {
 			if (k + 30 + 5 * len > buf_len) {
diff --git a/innobase/row/row0mysql.c b/innobase/row/row0mysql.c
index 61bb41fe3e6..d5472219d09 100644
--- a/innobase/row/row0mysql.c
+++ b/innobase/row/row0mysql.c
@@ -285,7 +285,8 @@ handle_new_error:
 	    "InnoDB: http://www.innodb.com/ibman.html for help.\n");
 
 	} else {
-		fprintf(stderr, "InnoDB: unknown error code %lu\n", err);
+		fprintf(stderr, "InnoDB: unknown error code %lu\n",
+			(ulong) err);
 		ut_a(0);
 	}		
 
@@ -395,7 +396,9 @@ row_prebuilt_free(
 		fprintf(stderr,
 "InnoDB: Error: trying to free a corrupt\n"
 "InnoDB: table handle. Magic n %lu, magic n2 %lu, table name %s\n",
-		prebuilt->magic_n, prebuilt->magic_n2, prebuilt->table->name);
+		(ulong) prebuilt->magic_n,
+		(ulong) prebuilt->magic_n2,
+		prebuilt->table->name);
 
 		mem_analyze_corruption((byte*)prebuilt);
 
@@ -475,7 +478,7 @@ row_update_prebuilt_trx(
 		fprintf(stderr,
 		"InnoDB: Error: trying to use a corrupt\n"
 		"InnoDB: trx handle. Magic n %lu\n",
-		trx->magic_n);
+		(ulong) trx->magic_n);
 
 		mem_analyze_corruption((byte*)trx);
 
@@ -486,7 +489,7 @@ row_update_prebuilt_trx(
 		fprintf(stderr,
 		"InnoDB: Error: trying to use a corrupt\n"
 		"InnoDB: table handle. Magic n %lu, table name %s\n",
-		prebuilt->magic_n, prebuilt->table->name);
+		(ulong) prebuilt->magic_n, prebuilt->table->name);
 
 		mem_analyze_corruption((byte*)prebuilt);
 
@@ -713,7 +716,7 @@ row_insert_for_mysql(
 		fprintf(stderr,
 		"InnoDB: Error: trying to free a corrupt\n"
 		"InnoDB: table handle. Magic n %lu, table name %s\n",
-		prebuilt->magic_n, prebuilt->table->name);
+		(ulong) prebuilt->magic_n, prebuilt->table->name);
 
 		mem_analyze_corruption((byte*)prebuilt);
 
@@ -929,7 +932,7 @@ row_update_for_mysql(
 		fprintf(stderr,
 		"InnoDB: Error: trying to free a corrupt\n"
 		"InnoDB: table handle. Magic n %lu, table name %s\n",
-		prebuilt->magic_n, prebuilt->table->name);
+		(ulong) prebuilt->magic_n, prebuilt->table->name);
 
 		mem_analyze_corruption((byte*)prebuilt);
 
@@ -1898,7 +1901,7 @@ row_discard_tablespace_for_mysql(
 	"SELECT ID INTO old_id\n"
 	"FROM SYS_TABLES\n"
 	"WHERE NAME = table_name;\n"
-	"IF (SQL % NOTFOUND) THEN\n"
+	"IF (SQL %% NOTFOUND) THEN\n"
 	"	COMMIT WORK;\n"
 	"	RETURN;\n"
 	"END IF;\n"
@@ -1909,7 +1912,8 @@ row_discard_tablespace_for_mysql(
 	"UPDATE SYS_INDEXES SET TABLE_ID = new_id\n"
 	"WHERE TABLE_ID = old_id;\n"
 	"COMMIT WORK;\n"
-	"END;\n", name, ut_dulint_get_high(new_id), ut_dulint_get_low(new_id));
+	"END;\n", name, (ulong) ut_dulint_get_high(new_id),
+		(ulong) ut_dulint_get_low(new_id));
 
 	ut_a(strlen(buf) < 2 * OS_FILE_MAX_PATH);
 
@@ -2359,8 +2363,8 @@ row_drop_table_for_mysql(
 			if (!success) {
 				ut_print_timestamp(stderr);
 				fprintf(stderr,
-"  InnoDB: Error: not able to delete tablespace %lu of table %s!\n", space_id,
-								     name);
+"  InnoDB: Error: not able to delete tablespace %lu of table %s!\n",
+					(ulong) space_id, name);
 				err = DB_ERROR;
 			}
 		}
@@ -2439,7 +2443,7 @@ loop:
 		if (err != DB_SUCCESS) {
 			fprintf(stderr,
 	"InnoDB: DROP DATABASE %s failed with error %lu for table %s\n",
-				name, (ulint)err, table_name);
+				name, (ulong) err, table_name);
 			break;
 		}
 	}
@@ -2947,7 +2951,8 @@ row_check_table_for_mysql(
  
 				fprintf(stderr,
 		"Error: index %s contains %lu entries, should be %lu\n",
-					index->name, n_rows, n_rows_in_table);
+					index->name, (ulong) n_rows,
+					(ulong) n_rows_in_table);
 			}
 		}
 
diff --git a/innobase/row/row0sel.c b/innobase/row/row0sel.c
index e6080a5f201..2215e3feff8 100644
--- a/innobase/row/row0sel.c
+++ b/innobase/row/row0sel.c
@@ -1754,7 +1754,7 @@ row_sel_step(
 		return(NULL);
 	} else {
 		/* SQL error detected */
-		printf("SQL error %lu\n", err);
+		printf("SQL error %lu\n", (ulong) err);
 
 		que_thr_handle_error(thr, DB_ERROR, NULL, 0);
 
@@ -1804,7 +1804,7 @@ fetch_step(
 	
 	if (sel_node->state == SEL_NODE_CLOSED) {
 		/* SQL error detected */
-		printf("SQL error %lu\n", (ulint)DB_ERROR);
+		printf("SQL error %lu\n", (ulong) DB_ERROR);
 
 		que_thr_handle_error(thr, DB_ERROR, NULL, 0);
 
@@ -2029,8 +2029,8 @@ row_sel_convert_mysql_key_to_innobase(
   "InnoDB: Table name %s, index name %s. Last data field length %lu bytes,\n"
   "InnoDB: key ptr now exceeds key end by %lu bytes.\n"
   "InnoDB: Key value in the MySQL format:\n", index->table_name, index->name,
-					  data_field_len,
-					  (ulint)(key_ptr - key_end));
+					  (ulong) data_field_len,
+					  (ulong) (key_ptr - key_end));
 			fflush(stderr);
 			ut_print_buf(original_key_ptr, key_len);
 			fflush(stdout);
@@ -2077,8 +2077,8 @@ row_sel_store_row_id_to_prebuilt(
 	        fprintf(stderr,
 "InnoDB: Error: Row id field is wrong length %lu in table %s index %s\n"
 "InnoDB: Field number %lu, record:\n%s\n",
-		      len, index->table_name, index->name,
-		      dict_index_get_sys_col_pos(index, DATA_ROW_ID),
+		      (ulong) len, index->table_name, index->name,
+		      (ulong) dict_index_get_sys_col_pos(index, DATA_ROW_ID),
 		      err_buf);
 		ut_a(0);
 	}
@@ -2233,7 +2233,7 @@ row_sel_store_mysql_rec(
 					ut_print_timestamp(stderr);
 					fprintf(stderr,
 "  InnoDB: Warning: could not allocate %lu + 1000000 bytes to retrieve\n"
-"InnoDB: a big column. Table name %s\n", len, prebuilt->table->name);
+"InnoDB: a big column. Table name %s\n", (ulong) len, prebuilt->table->name);
 
 					if (extern_field_heap) {
 						mem_heap_free(
@@ -2766,7 +2766,7 @@ row_search_for_mysql(
 		fprintf(stderr,
 		"InnoDB: Error: trying to free a corrupt\n"
 		"InnoDB: table handle. Magic n %lu, table name %s\n",
-		prebuilt->magic_n, prebuilt->table->name);
+		(ulong) prebuilt->magic_n, prebuilt->table->name);
 
 		mem_analyze_corruption((byte*)prebuilt);
 
@@ -3147,8 +3147,9 @@ rec_loop:
 "  InnoDB: Index corruption: rec offs %lu next offs %lu, page no %lu,\n"
 "InnoDB: index %s, table %s. Run CHECK TABLE to table. You may need to\n"
 "InnoDB: restore from a backup, or dump + drop + reimport the table.\n",
-			   (ulint)(rec - buf_frame_align(rec)), next_offs,
-			   buf_frame_get_page_no(rec), index->name,
+			   (ulong) (rec - buf_frame_align(rec)),
+			   (ulong) next_offs,
+			   (ulong) buf_frame_get_page_no(rec), index->name,
 			   index->table_name);
 		
 			err = DB_CORRUPTION;
@@ -3161,8 +3162,9 @@ rec_loop:
 			fprintf(stderr,
 "InnoDB: Index corruption: rec offs %lu next offs %lu, page no %lu,\n"
 "InnoDB: index %s, table %s. We try to skip the rest of the page.\n",
-			   (ulint)(rec - buf_frame_align(rec)), next_offs,
-			   buf_frame_get_page_no(rec), index->name,
+			   (ulong) (rec - buf_frame_align(rec)),
+			   (ulong) next_offs,
+			   (ulong) buf_frame_get_page_no(rec), index->name,
 			   index->table_name);
 
 			btr_pcur_move_to_last_on_page(pcur, &mtr);
@@ -3177,8 +3179,9 @@ rec_loop:
 			fprintf(stderr,
 "InnoDB: Index record corruption: rec offs %lu next offs %lu, page no %lu,\n"
 "InnoDB: index %s, table %s. We try to skip the record.\n",
-			   (ulint)(rec - buf_frame_align(rec)), next_offs,
-			   buf_frame_get_page_no(rec), index->name,
+			   (ulong) (rec - buf_frame_align(rec)),
+			   (ulong) next_offs,
+			   (ulong) buf_frame_get_page_no(rec), index->name,
 			   index->table_name);
 
 			goto next_rec;
diff --git a/innobase/row/row0undo.c b/innobase/row/row0undo.c
index 01b0b1ab41e..f223bb5eed5 100644
--- a/innobase/row/row0undo.c
+++ b/innobase/row/row0undo.c
@@ -323,7 +323,8 @@ row_undo_step(
 	if (err != DB_SUCCESS) {
 		/* SQL error detected */
 
-		fprintf(stderr, "InnoDB: Fatal error %lu in rollback.\n", err);
+		fprintf(stderr, "InnoDB: Fatal error %lu in rollback.\n",
+			(ulong) err);
 
 		if (err == DB_OUT_OF_FILE_SPACE) {
 			fprintf(stderr,
diff --git a/innobase/srv/srv0srv.c b/innobase/srv/srv0srv.c
index 1f709025759..2c1cb07c703 100644
--- a/innobase/srv/srv0srv.c
+++ b/innobase/srv/srv0srv.c
@@ -637,7 +637,8 @@ srv_suspend_thread(void)
 	if (srv_print_thread_releases) {
 	
 		printf("Suspending thread %lu to slot %lu meter %lu\n",
-		os_thread_get_curr_id(), slot_no, srv_meter[SRV_RECOVERY]);
+		(ulong) os_thread_get_curr_id(), (ulong) slot_no,
+		(ulong) srv_meter[SRV_RECOVERY]);
 	}
 
 	slot = srv_table_get_nth_slot(slot_no);
@@ -697,7 +698,8 @@ srv_release_threads(
 			if (srv_print_thread_releases) {
 				printf(
 		"Releasing thread %lu type %lu from slot %lu meter %lu\n",
-				slot->id, type, i, srv_meter[SRV_RECOVERY]);
+				(ulong) slot->id, (ulong) type, (ulong) i,
+		                (ulong) srv_meter[SRV_RECOVERY]);
 			}
 
 			count++;
@@ -776,7 +778,7 @@ srv_dec_thread_count(
 	/* FIXME: the following assertion sometimes fails: */
 
 	if (srv_n_threads_active[type] == 0) {
-		printf("Error: thread type %lu\n", type);
+		printf("Error: thread type %lu\n", (ulong) type);
 
 		ut_ad(0);
 	}	
@@ -987,7 +989,7 @@ srv_console(
 
 			printf(
 			"Starting disk access simulation with pct %lu\n",
-							srv_sim_disk_wait_pct);
+						(ulong) srv_sim_disk_wait_pct);
 		} else {
 			printf("\nNot supported!\n");
 		}
@@ -2114,7 +2116,7 @@ srv_table_reserve_slot_for_mysql(void)
 "  InnoDB: There appear to be %lu MySQL threads currently waiting\n"
 "InnoDB: inside InnoDB, which is the upper limit. Cannot continue operation.\n"
 "InnoDB: We intentionally generate a seg fault to print a stack trace\n"
-"InnoDB: on Linux. But first we print a list of waiting threads.\n", i);
+"InnoDB: on Linux. But first we print a list of waiting threads.\n", (ulong) i);
 
 			for (i = 0; i < OS_THREAD_MAX_N; i++) {
 
@@ -2122,10 +2124,10 @@ srv_table_reserve_slot_for_mysql(void)
 
 			        fprintf(stderr,
 "Slot %lu: thread id %lu, type %lu, in use %lu, susp %lu, time %lu\n",
-				  i, os_thread_pf(slot->id),
-				  slot->type, slot->in_use,
-				  slot->suspended,
-			  (ulint)difftime(ut_time(), slot->suspend_time));
+				  (ulong) i, (ulong) os_thread_pf(slot->id),
+				  (ulong) slot->type, (ulong) slot->in_use,
+				  (ulong) slot->suspended,
+			  (ulong) difftime(ut_time(), slot->suspend_time));
 			}
 
 		        ut_a(0);
@@ -2368,7 +2370,7 @@ srv_sprintf_innodb_monitor(
 
 	buf += sprintf(buf,
 "Per second averages calculated from the last %lu seconds\n",
-					(ulint)time_elapsed);
+					(ulong) time_elapsed);
 	       	       
 	buf += sprintf(buf, "----------\n"
 		       "SEMAPHORES\n"
@@ -2446,19 +2448,19 @@ srv_sprintf_innodb_monitor(
 		       "----------------------\n");
 	buf += sprintf(buf,
 	"Total memory allocated %lu; in additional pool allocated %lu\n",
-				ut_total_allocated_memory,
-				mem_pool_get_reserved(mem_comm_pool));
+				(ulong) ut_total_allocated_memory,
+				(ulong) mem_pool_get_reserved(mem_comm_pool));
 
 	if (mem_out_of_mem_err_msg_count > 0) {
 	        buf += sprintf(buf,
 	"Mem allocation has spilled out of additional mem pool %lu times\n",
-					mem_out_of_mem_err_msg_count);
+					(ulong) mem_out_of_mem_err_msg_count);
 	}
 
 	if (srv_use_awe) {
 		buf += sprintf(buf,
 	"In addition to that %lu MB of AWE memory allocated\n",
-		srv_pool_size / ((1024 * 1024) / UNIV_PAGE_SIZE));
+			       (ulong) (srv_pool_size / ((1024 * 1024) / UNIV_PAGE_SIZE)));
 	}
 	
 	buf_print_io(buf, buf_end);
@@ -2470,33 +2472,34 @@ srv_sprintf_innodb_monitor(
 		       "--------------\n");
 	buf += sprintf(buf,
         "%ld queries inside InnoDB, %lu queries in queue\n",
-                        srv_conc_n_threads, srv_conc_n_waiting_threads);
+		       (ulong) srv_conc_n_threads,
+		       (ulong) srv_conc_n_waiting_threads);
 
         n_reserved = fil_space_get_n_reserved_extents(0);
         if (n_reserved > 0) {
                 buf += sprintf(buf,
         "%lu tablespace extents now reserved for B-tree split operations\n",
-                                                    n_reserved);
+                                                    (ulong) n_reserved);
         }
 
 #ifdef UNIV_LINUX
 	buf += sprintf(buf,
 	"Main thread process no. %lu, id %lu, state: %s\n",
-			srv_main_thread_process_no,
-			srv_main_thread_id,
-			srv_main_thread_op_info);
+		       (ulong) srv_main_thread_process_no,
+		       (ulong) srv_main_thread_id,
+		       srv_main_thread_op_info);
 #else
 	buf += sprintf(buf,
 	"Main thread id %lu, state: %s\n",
-			srv_main_thread_id,
+			(ulong) srv_main_thread_id,
 			srv_main_thread_op_info);
 #endif
 	buf += sprintf(buf,
 	"Number of rows inserted %lu, updated %lu, deleted %lu, read %lu\n",
-			srv_n_rows_inserted, 
-			srv_n_rows_updated, 
-			srv_n_rows_deleted, 
-			srv_n_rows_read);
+			(ulong) srv_n_rows_inserted, 
+			(ulong) srv_n_rows_updated, 
+			(ulong) srv_n_rows_deleted, 
+			(ulong) srv_n_rows_read);
 	buf += sprintf(buf,
 	"%.2f inserts/s, %.2f updates/s, %.2f deletes/s, %.2f reads/s\n",
 			(srv_n_rows_inserted - srv_n_rows_inserted_old)
@@ -2746,10 +2749,10 @@ loop:
 "  InnoDB: Error: old log sequence number %lu %lu was greater\n"
 "InnoDB: than the new log sequence number %lu %lu!\n"
 "InnoDB: Please send a bug report to mysql@lists.mysql.com\n",
-		ut_dulint_get_high(old_lsn),
-		ut_dulint_get_low(old_lsn),
-		ut_dulint_get_high(new_lsn),
-		ut_dulint_get_low(new_lsn));
+		(ulong) ut_dulint_get_high(old_lsn),
+		(ulong) ut_dulint_get_low(old_lsn),
+		(ulong) ut_dulint_get_high(new_lsn),
+		(ulong) ut_dulint_get_low(new_lsn));
 	}
 
 	old_lsn = new_lsn;
diff --git a/innobase/srv/srv0start.c b/innobase/srv/srv0start.c
index 69ddaec0619..a2d4d2ba9b8 100644
--- a/innobase/srv/srv0start.c
+++ b/innobase/srv/srv0start.c
@@ -565,7 +565,7 @@ open_or_create_log_file(
 	srv_log_group_home_dirs[k] = srv_add_path_separator_if_needed(
 						srv_log_group_home_dirs[k]);
 
-	sprintf(name, "%s%s%lu", srv_log_group_home_dirs[k], "ib_logfile", i);
+	sprintf(name, "%s%s%lu", srv_log_group_home_dirs[k], "ib_logfile", (ulong) i);
 
 	files[i] = os_file_create(name, OS_FILE_CREATE, OS_FILE_NORMAL,
 						OS_LOG_FILE, &ret);
@@ -595,9 +595,9 @@ open_or_create_log_file(
 			fprintf(stderr,
 "InnoDB: Error: log file %s is of different size %lu %lu bytes\n"
 "InnoDB: than specified in the .cnf file %lu %lu bytes!\n",
-				name, size_high, size,
-				srv_calc_high32(srv_log_file_size),
-				srv_calc_low32(srv_log_file_size));
+				name, (ulong) size_high, (ulong) size,
+				(ulong) srv_calc_high32(srv_log_file_size),
+				(ulong) srv_calc_low32(srv_log_file_size));
 				
 			return(DB_ERROR);
 		}					
@@ -615,7 +615,7 @@ open_or_create_log_file(
 		}
 
 		fprintf(stderr, "InnoDB: Setting log file %s size to %lu MB\n",
-			             name, srv_log_file_size
+			             name, (ulong) srv_log_file_size
 			>> (20 - UNIV_PAGE_SIZE_SHIFT));
 
 		fprintf(stderr,
@@ -702,7 +702,7 @@ open_or_create_data_files(
 	if (srv_n_data_files >= 1000) {
 		fprintf(stderr, "InnoDB: can only have < 1000 data files\n"
 				"InnoDB: you have defined %lu\n",
-				srv_n_data_files);
+				(ulong) srv_n_data_files);
 		return(DB_ERROR);
 	}
 
@@ -814,8 +814,9 @@ open_or_create_data_files(
 "InnoDB: Error: auto-extending data file %s is of a different size\n"
 "InnoDB: %lu pages (rounded down to MB) than specified in the .cnf file:\n"
 "InnoDB: initial %lu pages, max %lu (relevant if non-zero) pages!\n",
-		  name, rounded_size_pages,
-		  srv_data_file_sizes[i], srv_last_file_size_max);
+		  name, (ulong) rounded_size_pages,
+		  (ulong) srv_data_file_sizes[i],
+		  (ulong) srv_last_file_size_max);
 
 					return(DB_ERROR);
 				}
@@ -829,8 +830,8 @@ open_or_create_data_files(
 "InnoDB: Error: data file %s is of a different size\n"
 "InnoDB: %lu pages (rounded down to MB)\n"
 "InnoDB: than specified in the .cnf file %lu pages!\n", name,
-						rounded_size_pages,
-						srv_data_file_sizes[i]);
+					       (ulong) rounded_size_pages,
+					       (ulong) srv_data_file_sizes[i]);
 				
 				return(DB_ERROR);
 			}
@@ -861,7 +862,7 @@ skip_size_check:
 	    		ut_print_timestamp(stderr);
 			fprintf(stderr, 
 				"  InnoDB: Setting file %s size to %lu MB\n",
-			       name, (srv_data_file_sizes[i]
+			       name, (ulong) (srv_data_file_sizes[i]
 				      >> (20 - UNIV_PAGE_SIZE_SHIFT)));
 
 			fprintf(stderr,
@@ -1040,7 +1041,8 @@ innobase_start_or_create_for_mysql(void)
   "InnoDB: Error: trx_t size is %lu in ha_innodb.cc but %lu in srv0start.c\n"
   "InnoDB: Check that pthread_mutex_t is defined in the same way in these\n"
   "InnoDB: compilation modules. Cannot continue.\n",
-		  srv_sizeof_trx_t_in_ha_innodb_cc, (ulint)sizeof(trx_t));
+		 (ulong)  srv_sizeof_trx_t_in_ha_innodb_cc,
+		 (ulong) sizeof(trx_t));
 		return(DB_ERROR);
 	}
 
@@ -1219,8 +1221,8 @@ NetWare. */
 	if (srv_use_awe) {
 		fprintf(stderr,
 "InnoDB: Using AWE: Memory window is %lu MB and AWE memory is %lu MB\n",
-		srv_awe_window_size / ((1024 * 1024) / UNIV_PAGE_SIZE),
-		srv_pool_size / ((1024 * 1024) / UNIV_PAGE_SIZE));
+		(ulong) (srv_awe_window_size / ((1024 * 1024) / UNIV_PAGE_SIZE)),
+		(ulong) (srv_pool_size / ((1024 * 1024) / UNIV_PAGE_SIZE)));
 
 		/* We must disable adaptive hash indexes because they do not
 		tolerate remapping of pages in AWE */
@@ -1545,7 +1547,8 @@ NetWare. */
 		fprintf(stderr,
 "InnoDB: Error: tablespace size stored in header is %lu pages, but\n"
 "InnoDB: the sum of data file sizes is %lu pages\n",
- 			tablespace_size_in_header, sum_of_data_file_sizes);
+ 			(ulong) tablespace_size_in_header,
+			(ulong) sum_of_data_file_sizes);
 	}
 
 	if (srv_auto_extend_last_data_file
@@ -1554,7 +1557,8 @@ NetWare. */
 		fprintf(stderr,
 "InnoDB: Error: tablespace size stored in header is %lu pages, but\n"
 "InnoDB: the sum of data file sizes is only %lu pages\n",
- 			tablespace_size_in_header, sum_of_data_file_sizes);
+ 			(ulong) tablespace_size_in_header,
+			(ulong) sum_of_data_file_sizes);
 	}
 
 	/* Check that os_fast_mutexes work as expected */
@@ -1579,14 +1583,14 @@ NetWare. */
 	  	ut_print_timestamp(stderr);
 	  	fprintf(stderr,
 "  InnoDB: Started; log sequence number %lu %lu\n",
-			ut_dulint_get_high(srv_start_lsn),
-			ut_dulint_get_low(srv_start_lsn));
+			(ulong) ut_dulint_get_high(srv_start_lsn),
+			(ulong) ut_dulint_get_low(srv_start_lsn));
 	}
 
 	if (srv_force_recovery > 0) {
 		fprintf(stderr,
 		"InnoDB: !!! innodb_force_recovery is set to %lu !!!\n",
-			srv_force_recovery);
+			(ulong) srv_force_recovery);
 	}
 
 	fflush(stderr);
@@ -1716,7 +1720,7 @@ innobase_shutdown_for_mysql(void)
 	if (i == 1000) {
 	        fprintf(stderr,
 "InnoDB: Warning: %lu threads created by InnoDB had not exited at shutdown!\n",
-		      os_thread_count);
+		      (ulong) os_thread_count);
 	}
 
 	/* 3. Free all InnoDB's own mutexes and the os_fast_mutexes inside
@@ -1741,16 +1745,16 @@ innobase_shutdown_for_mysql(void)
 	        fprintf(stderr,
 "InnoDB: Warning: some resources were not cleaned up in shutdown:\n"
 "InnoDB: threads %lu, events %lu, os_mutexes %lu, os_fast_mutexes %lu\n",
-		      os_thread_count, os_event_count, os_mutex_count,
-		      os_fast_mutex_count);
+			(ulong) os_thread_count, (ulong) os_event_count,
+			(ulong) os_mutex_count, (ulong) os_fast_mutex_count);
 	}
 
 	if (srv_print_verbose_log) {
 	        ut_print_timestamp(stderr);
 	        fprintf(stderr,
 "  InnoDB: Shutdown completed; log sequence number %lu %lu\n",
-			       ut_dulint_get_high(srv_shutdown_lsn),
-			       ut_dulint_get_low(srv_shutdown_lsn));
+			       (ulong) ut_dulint_get_high(srv_shutdown_lsn),
+			       (ulong) ut_dulint_get_low(srv_shutdown_lsn));
 	}
 
 	return((int) DB_SUCCESS);
diff --git a/innobase/sync/sync0arr.c b/innobase/sync/sync0arr.c
index 4854b40409e..9bcee34a7d1 100644
--- a/innobase/sync/sync0arr.c
+++ b/innobase/sync/sync0arr.c
@@ -454,8 +454,9 @@ sync_array_cell_print(
 
 	buf += sprintf(buf,
 "--Thread %lu has waited at %s line %lu for %.2f seconds the semaphore:\n",
-			os_thread_pf(cell->thread), cell->file, cell->line,
-			difftime(time(NULL), cell->reservation_time));
+			(ulong) os_thread_pf(cell->thread), cell->file,
+		       (ulong) cell->line,
+		       difftime(time(NULL), cell->reservation_time));
 
 	if (type == SYNC_MUTEX) {
 		/* We use old_wait_mutex in case the cell has already
@@ -464,11 +465,12 @@ sync_array_cell_print(
 
 		buf += sprintf(buf,
 		"Mutex at %lx created file %s line %lu, lock var %lu\n",
-			(ulint)mutex, mutex->cfile_name, mutex->cline,
-							mutex->lock_word);
+			       (ulong) mutex, mutex->cfile_name,
+			       (ulong) mutex->cline, (ulong) mutex->lock_word);
 		buf += sprintf(buf,
 		"Last time reserved in file %s line %lu, waiters flag %lu\n",
-			mutex->file_name, mutex->line, mutex->waiters);
+			       mutex->file_name, (ulong) mutex->line,
+			       (ulong) mutex->waiters);
 
 	} else if (type == RW_LOCK_EX || type == RW_LOCK_SHARED) {
 
@@ -482,11 +484,12 @@ sync_array_cell_print(
 
 		buf += sprintf(buf,
 			" RW-latch at %lx created in file %s line %lu\n",
-			(ulint)rwlock, rwlock->cfile_name, rwlock->cline);
+			(ulong) rwlock, rwlock->cfile_name,
+			(ulong) rwlock->cline);
 		if (rwlock->writer != RW_LOCK_NOT_LOCKED) {
 			buf += sprintf(buf,
 			"a writer (thread id %lu) has reserved it in mode",
-				os_thread_pf(rwlock->writer_thread));
+				(ulong) os_thread_pf(rwlock->writer_thread));
 			if (rwlock->writer == RW_LOCK_EX) {
 				buf += sprintf(buf, " exclusive\n");
 			} else {
@@ -496,14 +499,16 @@ sync_array_cell_print(
 		
 		buf += sprintf(buf,
 				"number of readers %lu, waiters flag %lu\n",
-				rwlock->reader_count, rwlock->waiters);
+			       (ulong) rwlock->reader_count,
+			       (ulong) rwlock->waiters);
 	
 		buf += sprintf(buf,
 				"Last time read locked in file %s line %lu\n",
-			rwlock->last_s_file_name, rwlock->last_s_line);
+			rwlock->last_s_file_name,
+			(ulong) rwlock->last_s_line);
 		buf += sprintf(buf,
 			"Last time write locked in file %s line %lu\n",
-			rwlock->last_x_file_name, rwlock->last_x_line);
+			rwlock->last_x_file_name, (ulong) rwlock->last_x_line);
 	} else {
 		ut_error;
 	}
@@ -651,8 +656,8 @@ sync_array_detect_deadlock(
 				sync_array_cell_print(buf, cell);
 				printf(
 	"Mutex %lx owned by thread %lu file %s line %lu\n%s",
-			(ulint)mutex, os_thread_pf(mutex->thread_id),
-				mutex->file_name, mutex->line, buf);
+			(ulong) mutex, (ulong) os_thread_pf(mutex->thread_id),
+				mutex->file_name, (ulong) mutex->line, buf);
 
 				return(TRUE);
 			}
@@ -686,7 +691,7 @@ sync_array_detect_deadlock(
 							depth);
 			if (ret) {
 				sync_array_cell_print(buf, cell);
-				printf("rw-lock %lx %s ", (ulint) lock, buf);
+				printf("rw-lock %lx %s ", (ulong)  lock, buf);
 				rw_lock_debug_print(debug);
 
 				return(TRUE);
@@ -719,7 +724,7 @@ sync_array_detect_deadlock(
 							depth);
 			if (ret) {
 				sync_array_cell_print(buf, cell);
-				printf("rw-lock %lx %s ", (ulint) lock, buf);
+				printf("rw-lock %lx %s ", (ulong) lock, buf);
 				rw_lock_debug_print(debug);
 
 				return(TRUE);
@@ -972,7 +977,7 @@ sync_array_output_info(
 	
 	buf += sprintf(buf,
 		"OS WAIT ARRAY INFO: reservation count %ld, signal count %ld\n",
-						arr->res_count, arr->sg_count);
+						(long) arr->res_count, (long) arr->sg_count);
 	i = 0;
 	count = 0;
 
diff --git a/innobase/sync/sync0rw.c b/innobase/sync/sync0rw.c
index 5c5abebd5e1..f552af1d1f0 100644
--- a/innobase/sync/sync0rw.c
+++ b/innobase/sync/sync0rw.c
@@ -235,8 +235,8 @@ lock_loop:
 	if (srv_print_latch_waits) {
 		printf(
 	"Thread %lu spin wait rw-s-lock at %lx cfile %s cline %lu rnds %lu\n",
-		os_thread_pf(os_thread_get_curr_id()), (ulint)lock,
-				lock->cfile_name, lock->cline, i);
+		(ulong) os_thread_pf(os_thread_get_curr_id()), (ulong) lock,
+		lock->cfile_name, (ulong) lock->cline, (ulong) i);
 	}
 
 	mutex_enter(rw_lock_get_mutex(lock));
@@ -265,8 +265,8 @@ lock_loop:
 		if (srv_print_latch_waits) {
 			printf(
 		"Thread %lu OS wait rw-s-lock at %lx cfile %s cline %lu\n",
-			os_thread_pf(os_thread_get_curr_id()), (ulint)lock,
-				lock->cfile_name, lock->cline);
+			(ulong) os_thread_pf(os_thread_get_curr_id()),
+		        (ulong) lock, lock->cfile_name, (ulong) lock->cline);
 		}
 
 		rw_s_system_call_count++;
@@ -483,8 +483,8 @@ lock_loop:
 	if (srv_print_latch_waits) {
 		printf(
 	"Thread %lu spin wait rw-x-lock at %lx cfile %s cline %lu rnds %lu\n",
-		os_thread_pf(os_thread_get_curr_id()), (ulint)lock,
-					lock->cfile_name, lock->cline, i);
+		(ulong) os_thread_pf(os_thread_get_curr_id()), (ulong) lock,
+		lock->cfile_name, (ulong) lock->cline, (ulong) i);
 	}
 
 	rw_x_spin_wait_count++;
@@ -516,8 +516,8 @@ lock_loop:
 	if (srv_print_latch_waits) {
 		printf(
 		"Thread %lu OS wait for rw-x-lock at %lx cfile %s cline %lu\n",
-		os_thread_pf(os_thread_get_curr_id()), (ulint)lock,
-				lock->cfile_name, lock->cline);
+		(ulong) os_thread_pf(os_thread_get_curr_id()), (ulong) lock,
+		lock->cfile_name, (ulong) lock->cline);
 	}
 
 	rw_x_system_call_count++;
@@ -850,7 +850,8 @@ rw_lock_debug_print(
 	rwt 	  = info->lock_type;	
 			
 	printf("Locked: thread %ld file %s line %ld  ",
-		os_thread_pf(info->thread_id), info->file_name, info->line);
+		(ulong) os_thread_pf(info->thread_id), info->file_name,
+	        (ulong) info->line);
 	if (rwt == RW_LOCK_SHARED) {
 		printf("S-LOCK");
 	} else if (rwt == RW_LOCK_EX) {
@@ -861,7 +862,7 @@ rw_lock_debug_print(
 		ut_error;
 	}
 	if (info->pass != 0) {
-		printf(" pass value %lu", info->pass);
+		printf(" pass value %lu", (ulong) info->pass);
 	}
 	printf("\n");
 }
diff --git a/innobase/sync/sync0sync.c b/innobase/sync/sync0sync.c
index 680582b05b2..424f5b1b35a 100644
--- a/innobase/sync/sync0sync.c
+++ b/innobase/sync/sync0sync.c
@@ -406,8 +406,8 @@ spin_loop:
 	if (srv_print_latch_waits) {
 		printf(
 	"Thread %lu spin wait mutex at %lx cfile %s cline %lu rnds %lu\n",
-		os_thread_pf(os_thread_get_curr_id()), (ulint)mutex,
-				mutex->cfile_name, mutex->cline, i);
+		(ulong) os_thread_pf(os_thread_get_curr_id()), (ulong) mutex,
+		mutex->cfile_name, (ulong) mutex->cline, (ulong) i);
 	}
 
 	mutex_spin_round_count += i;
@@ -472,7 +472,8 @@ spin_loop:
 		if (srv_print_latch_waits) {
 			printf(
 			"Thread %lu spin wait succeeds at 2: mutex at %lx\n",
-			os_thread_pf(os_thread_get_curr_id()), (ulint)mutex);
+			(ulong) os_thread_pf(os_thread_get_curr_id()),
+			(ulong) mutex);
 		}
 		
                 return;
@@ -490,8 +491,8 @@ spin_loop:
 	if (srv_print_latch_waits) {
 		printf(
 	"Thread %lu OS wait mutex at %lx cfile %s cline %lu rnds %lu\n",
-		os_thread_pf(os_thread_get_curr_id()), (ulint)mutex,
-			mutex->cfile_name, mutex->cline, i);
+		(ulong) os_thread_pf(os_thread_get_curr_id()), (ulong) mutex,
+		mutex->cfile_name, (ulong) mutex->cline, (ulong) i);
 	}
 	
 	mutex_system_call_count++;
@@ -813,11 +814,11 @@ sync_thread_levels_g(
 
 				printf(
 	"InnoDB error: sync levels should be > %lu but a level is %lu\n",
-				limit, slot->level);
+				(ulong) limit, (ulong) slot->level);
 
 				if (mutex->magic_n == MUTEX_MAGIC_N) {
 	printf("Mutex created at %s %lu\n", mutex->cfile_name,
-						mutex->cline);
+						(ulong) mutex->cline);
 
 					if (mutex_get_lock_word(mutex) != 0) {
 
@@ -825,8 +826,8 @@ sync_thread_levels_g(
 						&file_name, &line, &thread_id);
 
 	printf("InnoDB: Locked mutex: addr %lx thread %ld file %s line %ld\n",
-		    	(ulint)mutex, os_thread_pf(thread_id),
-						file_name, line);
+		    	(ulong) mutex, (ulong) os_thread_pf(thread_id),
+						file_name, (ulong) line);
 					} else {
 						printf("Not locked\n");
 					}	
@@ -1288,10 +1289,13 @@ sync_print_wait_info(
 	sprintf(buf,
 "Mutex spin waits %lu, rounds %lu, OS waits %lu\n"
 "RW-shared spins %lu, OS waits %lu; RW-excl spins %lu, OS waits %lu\n",
-			mutex_spin_wait_count, mutex_spin_round_count,
-			mutex_os_wait_count,
-			rw_s_spin_wait_count, rw_s_os_wait_count,
-			rw_x_spin_wait_count, rw_x_os_wait_count);
+			(ulong) mutex_spin_wait_count,
+		        (ulong) mutex_spin_round_count,
+			(ulong) mutex_os_wait_count,
+			(ulong) rw_s_spin_wait_count,
+		        (ulong) rw_s_os_wait_count,
+			(ulong) rw_x_spin_wait_count,
+		        (ulong) rw_x_os_wait_count);
 }
 
 /***********************************************************************
diff --git a/innobase/trx/trx0purge.c b/innobase/trx/trx0purge.c
index fa9c287b0ad..31223aa280e 100644
--- a/innobase/trx/trx0purge.c
+++ b/innobase/trx/trx0purge.c
@@ -275,7 +275,7 @@ trx_purge_add_update_undo_to_history(
 
 		if (undo->id >= TRX_RSEG_N_SLOTS) {
 			fprintf(stderr,
-			"InnoDB: Error: undo->id is %lu\n", undo->id);
+			"InnoDB: Error: undo->id is %lu\n", (ulong) undo->id);
 			ut_a(0);
 		}
 
@@ -905,7 +905,7 @@ trx_purge_fetch_next_rec(
 			if (srv_print_thread_releases) {
 				printf(
 	"Purge: No logs left in the history list; pages handled %lu\n",
-					purge_sys->n_pages_handled);
+					(ulong) purge_sys->n_pages_handled);
 			}
 
 			mutex_exit(&(purge_sys->mutex));
@@ -1057,7 +1057,8 @@ trx_purge(void)
 	if (srv_print_thread_releases) {
 
 		printf(
-		"Purge ends; pages handled %lu\n", purge_sys->n_pages_handled);
+		"Purge ends; pages handled %lu\n",
+		(ulong) purge_sys->n_pages_handled);
 	}
 
 	return(purge_sys->n_pages_handled - old_pages_handled);
@@ -1074,16 +1075,16 @@ trx_purge_sys_print(void)
 	read_view_print(purge_sys->view);
 
 	fprintf(stderr, "InnoDB: Purge trx n:o %lu %lu, undo n_o %lu %lu\n",
-			ut_dulint_get_high(purge_sys->purge_trx_no),
-			ut_dulint_get_low(purge_sys->purge_trx_no),
-			ut_dulint_get_high(purge_sys->purge_undo_no),
-			ut_dulint_get_low(purge_sys->purge_undo_no));
+			(ulong) ut_dulint_get_high(purge_sys->purge_trx_no),
+			(ulong) ut_dulint_get_low(purge_sys->purge_trx_no),
+			(ulong) ut_dulint_get_high(purge_sys->purge_undo_no),
+			(ulong) ut_dulint_get_low(purge_sys->purge_undo_no));
 	fprintf(stderr,
 	"InnoDB: Purge next stored %lu, page_no %lu, offset %lu,\n"
 	"InnoDB: Purge hdr_page_no %lu, hdr_offset %lu\n",
-		purge_sys->next_stored,
-		purge_sys->page_no,
-		purge_sys->offset,
-		purge_sys->hdr_page_no,
-		purge_sys->hdr_offset);
+		(ulong) purge_sys->next_stored,
+		(ulong) purge_sys->page_no,
+		(ulong) purge_sys->offset,
+		(ulong) purge_sys->hdr_page_no,
+		(ulong) purge_sys->hdr_offset);
 }
diff --git a/innobase/trx/trx0rec.c b/innobase/trx/trx0rec.c
index 9453189d598..a0f500e51d7 100644
--- a/innobase/trx/trx0rec.c
+++ b/innobase/trx/trx0rec.c
@@ -866,15 +866,16 @@ trx_undo_update_rec_get_update(
 			fprintf(stderr,
    "InnoDB: Error: trying to access update undo rec field %lu in table %s\n"
    "InnoDB: index %s, but index has only %lu fields\n",
-			field_no, index->table_name, index->name,
-			dict_index_get_n_fields(index));
+			(ulong) field_no, index->table_name, index->name,
+			(ulong) dict_index_get_n_fields(index));
   			fprintf(stderr,
    "InnoDB: Send a detailed bug report to mysql@lists.mysql.com");
    
   			fprintf(stderr,
    "InnoDB: Run also CHECK TABLE on table %s\n", index->table_name);
   			fprintf(stderr,
-   "InnoDB: n_fields = %lu, i = %lu, ptr %lx\n", n_fields, i, (ulint)ptr);
+   "InnoDB: n_fields = %lu, i = %lu, ptr %lx\n", (ulong) n_fields, (ulong) i,
+				(ulong) ptr);
 			return(NULL);
 		}
 
@@ -1371,17 +1372,18 @@ trx_undo_prev_version_build(
 		fprintf(stderr,
 			"InnoDB: Table name %s, index name %s, n_uniq %lu\n",
 			index->table_name, index->name,
-			dict_index_get_n_unique(index));
+			(ulong) dict_index_get_n_unique(index));
 		
 		fprintf(stderr,
 		"InnoDB: undo rec address %lx, type %lu cmpl_info %lu\n",
-					(ulint)undo_rec, type, cmpl_info);
+					(ulong) undo_rec, (ulong) type,
+					(ulong) cmpl_info);
 		fprintf(stderr,
 		"InnoDB: undo rec table id %lu %lu, index table id %lu %lu\n",
-			ut_dulint_get_high(table_id),
-			ut_dulint_get_low(table_id),
-			ut_dulint_get_high(index->table->id),
-			ut_dulint_get_low(index->table->id));
+			(ulong) ut_dulint_get_high(table_id),
+			(ulong) ut_dulint_get_low(table_id),
+			(ulong) ut_dulint_get_high(index->table->id),
+			(ulong) ut_dulint_get_low(index->table->id));
 		
 		ut_sprintf_buf(err_buf, undo_rec, 150);
 
@@ -1395,17 +1397,17 @@ trx_undo_prev_version_build(
 
 		fprintf(stderr,
 	"InnoDB: Record trx id %lu %lu, update rec trx id %lu %lu\n",
-		 	ut_dulint_get_high(rec_trx_id),
-		 	ut_dulint_get_low(rec_trx_id),
-		 	ut_dulint_get_high(trx_id),
-		 	ut_dulint_get_low(trx_id));
+		 	(ulong) ut_dulint_get_high(rec_trx_id),
+		 	(ulong) ut_dulint_get_low(rec_trx_id),
+		 	(ulong) ut_dulint_get_high(trx_id),
+		 	(ulong) ut_dulint_get_low(trx_id));
 
 		fprintf(stderr,
 	"InnoDB: Roll ptr in rec %lu %lu, in update rec %lu %lu\n",
-		 	ut_dulint_get_high(old_roll_ptr),
-		 	ut_dulint_get_low(old_roll_ptr),
-		 	ut_dulint_get_high(roll_ptr),
-		 	ut_dulint_get_low(roll_ptr));
+		 	(ulong) ut_dulint_get_high(old_roll_ptr),
+		 	(ulong) ut_dulint_get_low(old_roll_ptr),
+		 	(ulong) ut_dulint_get_high(roll_ptr),
+		 	(ulong) ut_dulint_get_low(roll_ptr));
 		 
 		trx_purge_sys_print();
 		 
diff --git a/innobase/trx/trx0roll.c b/innobase/trx/trx0roll.c
index 7d1b341221c..1f053aeed89 100644
--- a/innobase/trx/trx0roll.c
+++ b/innobase/trx/trx0roll.c
@@ -394,8 +394,8 @@ loop:
 	
 	if (trx->conc_state == TRX_COMMITTED_IN_MEMORY) {	
 		fprintf(stderr, "InnoDB: Cleaning up trx with id %lu %lu\n",
-					ut_dulint_get_high(trx->id),
-					ut_dulint_get_low(trx->id));
+					(ulong) ut_dulint_get_high(trx->id),
+					(ulong) ut_dulint_get_low(trx->id));
 
 		trx_cleanup_at_db_startup(trx);
 					
@@ -430,9 +430,9 @@ loop:
 
 	fprintf(stderr,
 "InnoDB: Rolling back trx with id %lu %lu, %lu%s rows to undo",
-					ut_dulint_get_high(trx->id),
-					ut_dulint_get_low(trx->id),
-					(ulint)rows_to_undo, unit);
+					(ulong) ut_dulint_get_high(trx->id),
+					(ulong) ut_dulint_get_low(trx->id),
+					(ulong) rows_to_undo, unit);
 	mutex_exit(&kernel_mutex);
 
 	if (trx->dict_operation) {
@@ -449,7 +449,7 @@ loop:
 
 		fprintf(stderr,
 		"InnoDB: Waiting for rollback of trx id %lu to end\n",
-						ut_dulint_get_low(trx->id));
+						(ulong) ut_dulint_get_low(trx->id));
 		os_thread_sleep(100000);
 
 		mutex_enter(&kernel_mutex);
@@ -463,8 +463,8 @@ loop:
 
 		fprintf(stderr,
 "InnoDB: Dropping table with id %lu %lu in recovery if it exists\n",
-			ut_dulint_get_high(trx->table_id),
-			ut_dulint_get_low(trx->table_id));
+			(ulong) ut_dulint_get_high(trx->table_id),
+			(ulong) ut_dulint_get_low(trx->table_id));
 
 		table = dict_table_get_on_id_low(trx->table_id, trx);
 
@@ -483,8 +483,8 @@ loop:
 	}
 
 	fprintf(stderr, "\nInnoDB: Rolling back of trx id %lu %lu completed\n",
-					ut_dulint_get_high(trx->id),
-					ut_dulint_get_low(trx->id));
+					(ulong) ut_dulint_get_high(trx->id),
+					(ulong) ut_dulint_get_low(trx->id));
 	mem_heap_free(heap);
 
 	goto loop;
@@ -853,10 +853,10 @@ try_again:
 		if (progress_pct != trx_roll_progress_printed_pct) {
 			if (trx_roll_progress_printed_pct == 0) {
 				fprintf(stderr,
-			"\nInnoDB: Progress in percents: %lu", progress_pct);
+			"\nInnoDB: Progress in percents: %lu", (ulong) progress_pct);
 			} else {
 				fprintf(stderr,
-				" %lu", progress_pct);
+				" %lu", (ulong) progress_pct);
 			}
 			fflush(stderr);
 			trx_roll_progress_printed_pct = progress_pct;
@@ -1130,7 +1130,7 @@ trx_finish_rollback_off_kernel(
 
 	if (lock_print_waits) {			
 		printf("Trx %lu rollback finished\n",
-						ut_dulint_get_low(trx->id));
+						(ulong) ut_dulint_get_low(trx->id));
 	}
 
 	trx_commit_off_kernel(trx);
diff --git a/innobase/trx/trx0sys.c b/innobase/trx/trx0sys.c
index 177c5db7413..d9eace5ad9a 100644
--- a/innobase/trx/trx0sys.c
+++ b/innobase/trx/trx0sys.c
@@ -434,7 +434,7 @@ trx_sys_doublewrite_init_or_restore_pages(
 		  	fprintf(stderr,
 "InnoDB: Warning: a page in the doublewrite buffer is not within space\n"
 "InnoDB: bounds; space id %lu page number %lu, page %lu in doublewrite buf.\n",
-				space_id, page_no, i);
+				(ulong) space_id, (ulong) page_no, (ulong) i);
 		
 		} else if (space_id == TRX_SYS_SPACE
 		    && (  (page_no >= block1
@@ -457,7 +457,7 @@ trx_sys_doublewrite_init_or_restore_pages(
 
 		  		fprintf(stderr,
 		"InnoDB: Warning: database page corruption or a failed\n"
-		"InnoDB: file read of page %lu.\n", page_no);
+		"InnoDB: file read of page %lu.\n", (ulong) page_no);
 		  		fprintf(stderr,
 		"InnoDB: Trying to recover it from the doublewrite buffer.\n");
 				
@@ -628,9 +628,9 @@ trx_sys_print_mysql_binlog_offset_from_page(
 
 		printf(
 	"ibbackup: Last MySQL binlog file position %lu %lu, file name %s\n",
-		mach_read_from_4(sys_header + TRX_SYS_MYSQL_LOG_INFO
+		(ulong) mach_read_from_4(sys_header + TRX_SYS_MYSQL_LOG_INFO
 					+ TRX_SYS_MYSQL_LOG_OFFSET_HIGH),
-		mach_read_from_4(sys_header + TRX_SYS_MYSQL_LOG_INFO
+		(ulong) mach_read_from_4(sys_header + TRX_SYS_MYSQL_LOG_INFO
 					+ TRX_SYS_MYSQL_LOG_OFFSET_LOW),
 		sys_header + TRX_SYS_MYSQL_LOG_INFO + TRX_SYS_MYSQL_LOG_NAME);
 	}
@@ -662,9 +662,9 @@ trx_sys_print_mysql_binlog_offset(void)
 
 	fprintf(stderr,
 	"InnoDB: Last MySQL binlog file position %lu %lu, file name %s\n",
-		mach_read_from_4(sys_header + TRX_SYS_MYSQL_LOG_INFO
+		(ulong) mach_read_from_4(sys_header + TRX_SYS_MYSQL_LOG_INFO
 					+ TRX_SYS_MYSQL_LOG_OFFSET_HIGH),
-		mach_read_from_4(sys_header + TRX_SYS_MYSQL_LOG_INFO
+		(ulong) mach_read_from_4(sys_header + TRX_SYS_MYSQL_LOG_INFO
 					+ TRX_SYS_MYSQL_LOG_OFFSET_LOW),
 		sys_header + TRX_SYS_MYSQL_LOG_INFO + TRX_SYS_MYSQL_LOG_NAME);
 
@@ -698,9 +698,9 @@ trx_sys_print_mysql_master_log_pos(void)
 	fprintf(stderr,
 "InnoDB: In a MySQL replication slave the last master binlog file\n"
 "InnoDB: position %lu %lu, file name %s\n",
-		mach_read_from_4(sys_header + TRX_SYS_MYSQL_MASTER_LOG_INFO
+		(ulong) mach_read_from_4(sys_header + TRX_SYS_MYSQL_MASTER_LOG_INFO
 					+ TRX_SYS_MYSQL_LOG_OFFSET_HIGH),
-		mach_read_from_4(sys_header + TRX_SYS_MYSQL_MASTER_LOG_INFO
+		(ulong) mach_read_from_4(sys_header + TRX_SYS_MYSQL_MASTER_LOG_INFO
 					+ TRX_SYS_MYSQL_LOG_OFFSET_LOW),
 		sys_header + TRX_SYS_MYSQL_MASTER_LOG_INFO
 						+ TRX_SYS_MYSQL_LOG_NAME);
@@ -872,12 +872,12 @@ trx_sys_init_at_db_start(void)
 		fprintf(stderr,
 "InnoDB: %lu transaction(s) which must be rolled back or cleaned up\n"
 "InnoDB: in total %lu%s row operations to undo\n",
-				UT_LIST_GET_LEN(trx_sys->trx_list),
-				(ulint)rows_to_undo, unit);
+				(ulong) UT_LIST_GET_LEN(trx_sys->trx_list),
+				(ulong) rows_to_undo, unit);
 
 		fprintf(stderr, "InnoDB: Trx id counter is %lu %lu\n", 
-			ut_dulint_get_high(trx_sys->max_trx_id),
-			ut_dulint_get_low(trx_sys->max_trx_id));
+			(ulong) ut_dulint_get_high(trx_sys->max_trx_id),
+			(ulong) ut_dulint_get_low(trx_sys->max_trx_id));
 	}
 
 	UT_LIST_INIT(trx_sys->view_list);
diff --git a/innobase/trx/trx0trx.c b/innobase/trx/trx0trx.c
index 292b7cd6f2f..3926cfa03c5 100644
--- a/innobase/trx/trx0trx.c
+++ b/innobase/trx/trx0trx.c
@@ -1589,26 +1589,26 @@ trx_print(
         char*   start_of_line;
 
         buf += sprintf(buf, "TRANSACTION %lu %lu",
-		ut_dulint_get_high(trx->id),
-		 ut_dulint_get_low(trx->id));
+		(ulong) ut_dulint_get_high(trx->id),
+		 (ulong) ut_dulint_get_low(trx->id));
 
   	switch (trx->conc_state) {
   		case TRX_NOT_STARTED:         buf += sprintf(buf,
 						", not started"); break;
   		case TRX_ACTIVE:              buf += sprintf(buf,
 						", ACTIVE %lu sec",
-			 (ulint)difftime(time(NULL), trx->start_time)); break;
+			 (ulong) difftime(time(NULL), trx->start_time)); break;
   		case TRX_COMMITTED_IN_MEMORY: buf += sprintf(buf,
 						", COMMITTED IN MEMORY");
 									break;
-  		default: buf += sprintf(buf, " state %lu", trx->conc_state);
+  		default: buf += sprintf(buf, " state %lu", (ulong) trx->conc_state);
   	}
 
 #ifdef UNIV_LINUX
         buf += sprintf(buf, ", process no %lu", trx->mysql_process_no);
 #endif
         buf += sprintf(buf, ", OS thread id %lu",
-		       os_thread_pf(trx->mysql_thread_id));
+		       (ulong) os_thread_pf(trx->mysql_thread_id));
 
 	if (ut_strlen(trx->op_info) > 0) {
 		buf += sprintf(buf, " %s", trx->op_info);
@@ -1620,7 +1620,7 @@ trx_print(
 
 	if (trx->declared_to_be_inside_innodb) {
 	        buf += sprintf(buf, ", thread declared inside InnoDB %lu",
-			       trx->n_tickets_to_enter_innodb);
+			       (ulong) trx->n_tickets_to_enter_innodb);
 	}
 
 	buf += sprintf(buf, "\n");
@@ -1628,8 +1628,8 @@ trx_print(
         if (trx->n_mysql_tables_in_use > 0 || trx->mysql_n_tables_locked > 0) {
 
                 buf += sprintf(buf, "mysql tables in use %lu, locked %lu\n",
-                                    trx->n_mysql_tables_in_use,
-                                    trx->mysql_n_tables_locked);
+                                    (ulong) trx->n_mysql_tables_in_use,
+                                    (ulong) trx->mysql_n_tables_locked);
         }
 
 	start_of_line = buf;
@@ -1642,7 +1642,7 @@ trx_print(
 						"ROLLING BACK "); break;
   		case TRX_QUE_COMMITTING:      buf += sprintf(buf,
 						"COMMITTING "); break;
-  		default: buf += sprintf(buf, "que state %lu", trx->que_state);
+  		default: buf += sprintf(buf, "que state %lu", (ulong) trx->que_state);
   	}
 
   	if (0 < UT_LIST_GET_LEN(trx->trx_locks) ||
@@ -1650,8 +1650,8 @@ trx_print(
 
   		buf += sprintf(buf,
 "%lu lock struct(s), heap size %lu",
-			       UT_LIST_GET_LEN(trx->trx_locks),
-			       mem_heap_get_size(trx->lock_heap));
+			       (ulong) UT_LIST_GET_LEN(trx->trx_locks),
+			       (ulong) mem_heap_get_size(trx->lock_heap));
 	}
 
   	if (trx->has_search_latch) {
@@ -1660,7 +1660,7 @@ trx_print(
 
 	if (ut_dulint_cmp(trx->undo_no, ut_dulint_zero) != 0) {
 		buf += sprintf(buf, ", undo log entries %lu",
-			ut_dulint_get_low(trx->undo_no));
+			(ulong) ut_dulint_get_low(trx->undo_no));
 	}
 	
 	if (buf != start_of_line) {
diff --git a/innobase/trx/trx0undo.c b/innobase/trx/trx0undo.c
index 82572b82807..f3f93734a49 100644
--- a/innobase/trx/trx0undo.c
+++ b/innobase/trx/trx0undo.c
@@ -1116,7 +1116,7 @@ trx_undo_mem_create_at_db_start(
 	
 	if (id >= TRX_RSEG_N_SLOTS) {
 		fprintf(stderr,
-		"InnoDB: Error: undo->id is %lu\n", id);
+		"InnoDB: Error: undo->id is %lu\n", (ulong) id);
 		ut_a(0);
 	}
 
@@ -1274,7 +1274,7 @@ trx_undo_mem_create(
 
 	if (id >= TRX_RSEG_N_SLOTS) {
 		fprintf(stderr,
-		"InnoDB: Error: undo->id is %lu\n", id);
+		"InnoDB: Error: undo->id is %lu\n", (ulong) id);
 		ut_a(0);
 	}
 
@@ -1317,7 +1317,8 @@ trx_undo_mem_init_for_reuse(
 	ut_ad(mutex_own(&((undo->rseg)->mutex)));
 	
  	if (undo->id >= TRX_RSEG_N_SLOTS) {
-		fprintf(stderr, "InnoDB: Error: undo->id is %lu\n", undo->id);
+		fprintf(stderr, "InnoDB: Error: undo->id is %lu\n",
+			(ulong) undo->id);
 
 		mem_analyze_corruption((byte*)undo);
 		ut_a(0);
@@ -1343,7 +1344,7 @@ trx_undo_mem_free(
 {
 	if (undo->id >= TRX_RSEG_N_SLOTS) {
 		fprintf(stderr,
-		"InnoDB: Error: undo->id is %lu\n", undo->id);
+		"InnoDB: Error: undo->id is %lu\n", (ulong) undo->id);
 		ut_a(0);
 	}
 
@@ -1450,7 +1451,8 @@ trx_undo_reuse_cached(
 	ut_ad(undo->hdr_page_no == undo->top_page_no);
 
 	if (undo->id >= TRX_RSEG_N_SLOTS) {
-		fprintf(stderr, "InnoDB: Error: undo->id is %lu\n", undo->id);
+		fprintf(stderr, "InnoDB: Error: undo->id is %lu\n",
+			(ulong) undo->id);
 		mem_analyze_corruption((byte*)undo);
 		ut_a(0);
 	}
@@ -1582,7 +1584,8 @@ trx_undo_set_state_at_finish(
 	ut_ad(trx && undo && mtr);
 
 	if (undo->id >= TRX_RSEG_N_SLOTS) {
-		fprintf(stderr, "InnoDB: Error: undo->id is %lu\n", undo->id);
+		fprintf(stderr, "InnoDB: Error: undo->id is %lu\n",
+			(ulong) undo->id);
 		mem_analyze_corruption((byte*)undo);
 		ut_a(0);
 	}
diff --git a/innobase/usr/usr0sess.c b/innobase/usr/usr0sess.c
index 0335c8046e2..d74153e323f 100644
--- a/innobase/usr/usr0sess.c
+++ b/innobase/usr/usr0sess.c
@@ -620,10 +620,10 @@ sess_raise_error_low(
 
 	len = 0;
 	
-	len += sprintf(str + len, "Error number: %lu", err_no);
+	len += sprintf(str + len, "Error number: %lu", (ulong) err_no);
 
 	if (type) {
-		len += sprintf(str + len, ", type: %lu", type);
+		len += sprintf(str + len, ", type: %lu", (ulong) type);
 	}
 
 	if (table) {
diff --git a/innobase/ut/ut0mem.c b/innobase/ut/ut0mem.c
index ebead6424c8..c367ea10ee1 100644
--- a/innobase/ut/ut0mem.c
+++ b/innobase/ut/ut0mem.c
@@ -89,11 +89,11 @@ ut_malloc_low(
 		"InnoDB: a big enough maximum process size.\n"
 		"InnoDB: We now intentionally generate a seg fault so that\n"
 		"InnoDB: on Linux we get a stack trace.\n",
-		                  n, ut_total_allocated_memory,
+		                  (ulong) n, (ulong) ut_total_allocated_memory,
 #ifdef __WIN__
-			(ulint)GetLastError()
+			(ulong) GetLastError()
 #else
-			(ulint)errno
+			(ulong) errno
 #endif
 			);
 
@@ -107,7 +107,7 @@ ut_malloc_low(
 
 		/* Make an intentional seg fault so that we get a stack
 		trace */
-		printf("%lu\n", *ut_mem_null_ptr);	
+		printf("%lu\n", (ulong) *ut_mem_null_ptr);
 	}		
 
 	if (set_to_zero) {
@@ -166,7 +166,9 @@ ut_test_malloc(
 		"InnoDB: ulimits of your operating system.\n"
 		"InnoDB: On FreeBSD check you have compiled the OS with\n"
 		"InnoDB: a big enough maximum process size.\n",
-		                  n, ut_total_allocated_memory, errno);
+		                  (ulong) n,
+			          (ulong) ut_total_allocated_memory,
+				  (int) errno);
 		return(FALSE);
 	}
 
@@ -225,7 +227,7 @@ ut_free_all_mem(void)
 	if (ut_total_allocated_memory != 0) {
 		fprintf(stderr,
 "InnoDB: Warning: after shutdown total allocated memory is %lu\n",
-		  ut_total_allocated_memory);
+		  (ulong) ut_total_allocated_memory);
 	}
 }
 
diff --git a/innobase/ut/ut0ut.c b/innobase/ut/ut0ut.c
index 10130717d2d..77f7a997777 100644
--- a/innobase/ut/ut0ut.c
+++ b/innobase/ut/ut0ut.c
@@ -474,7 +474,7 @@ ut_delay(
 	}
 
 	if (ut_always_false) {
-		printf("%lu", j);
+		printf("%lu", (ulong) j);
 	}
 	
 	return(j);
@@ -492,12 +492,12 @@ ut_print_buf(
 	byte*	data;
 	ulint	i;
 
-	printf(" len %lu; hex ", len);
+	printf(" len %lu; hex ", (ulong) len);
 			
 	data = buf;
 
 	for (i = 0; i < len; i++) {
-		printf("%02lx", (ulint)*data);
+		printf("%02lx", (ulong) *data);
 		data++;
 	}
 
@@ -532,12 +532,12 @@ ut_sprintf_buf(
 
 	n = 0;
 	
-	n += sprintf(str + n, " len %lu; hex ", len);
+	n += sprintf(str + n, " len %lu; hex ", (ulong) len);
 			
 	data = buf;
 
 	for (i = 0; i < len; i++) {
-		n += sprintf(str + n, "%02lx", (ulint)*data);
+		n += sprintf(str + n, "%02lx", (ulong) *data);
 		data++;
 	}
 
diff --git a/sql/sql_delete.cc b/sql/sql_delete.cc
index 78512f705a9..9ac7b7596fe 100644
--- a/sql/sql_delete.cc
+++ b/sql/sql_delete.cc
@@ -131,6 +131,7 @@ int mysql_delete(THD *thd, TABLE_LIST *table_list, COND *conds, SQL_LIST *order,
     table->sort.io_cache = (IO_CACHE *) my_malloc(sizeof(IO_CACHE),
                                              MYF(MY_FAE | MY_ZEROFILL));
       if (thd->lex->select_lex.setup_ref_array(thd, order->elements) ||
+	  setup_order(thd, thd->lex->select_lex.ref_pointer_array, &tables,
 		      fields, all_fields, (ORDER*) order->first) ||
 	  !(sortorder=make_unireg_sortorder((ORDER*) order->first, &length)) ||
 	  (table->sort.found_records = filesort(thd, table, sortorder, length,

From 734870d0ce43d21457939f93358a5a95e395b97c Mon Sep 17 00:00:00 2001
From: "heikki@hundin.mysql.fi" <>
Date: Sat, 20 Dec 2003 13:13:55 +0200
Subject: [PATCH 4/9] srv0start.c, univ.i, configure.in:   Check at compilation
 time on Unix that InnoDB ulint is the same size as void*, and also check it
 at runtime

---
 innobase/configure.in    | 1 +
 innobase/include/univ.i  | 6 ++++++
 innobase/srv/srv0start.c | 9 ++++++++-
 3 files changed, 15 insertions(+), 1 deletion(-)

diff --git a/innobase/configure.in b/innobase/configure.in
index 29309a2c0a5..9d57a0f2d91 100644
--- a/innobase/configure.in
+++ b/innobase/configure.in
@@ -37,6 +37,7 @@ AC_PROG_INSTALL
 AC_CHECK_HEADERS(aio.h sched.h)
 AC_CHECK_SIZEOF(int, 4)
 AC_CHECK_SIZEOF(long, 4)
+AC_CHECK_SIZEOF(void*, 4)
 AC_CHECK_FUNCS(sched_yield)
 AC_CHECK_FUNCS(fdatasync)
 #AC_CHECK_FUNCS(localtime_r)	# Already checked by MySQL
diff --git a/innobase/include/univ.i b/innobase/include/univ.i
index 346b3b3d09f..2b0f85884b9 100644
--- a/innobase/include/univ.i
+++ b/innobase/include/univ.i
@@ -204,6 +204,12 @@ typedef __int64       ib_longlong;
 typedef longlong ib_longlong;
 #endif
 
+#ifndef __WIN__
+#if SIZEOF_LONG != SIZEOF_VOIDP
+#error "Error: InnoDB's ulint must be of the same size as void*"
+#endif
+#endif
+
 /* The following type should be at least a 64-bit floating point number */
 typedef double		utfloat;
 
diff --git a/innobase/srv/srv0start.c b/innobase/srv/srv0start.c
index a2d4d2ba9b8..5fe66f515bc 100644
--- a/innobase/srv/srv0start.c
+++ b/innobase/srv/srv0start.c
@@ -57,7 +57,6 @@ Created 2/16/1996 Heikki Tuuri
 #include "srv0start.h"
 #include "que0que.h"
 
-
 /* Log sequence number immediately after startup */
 dulint		srv_start_lsn;
 /* Log sequence number at shutdown */
@@ -1010,6 +1009,14 @@ innobase_start_or_create_for_mysql(void)
 	ibool	srv_file_per_table_original_value  = srv_file_per_table;
 	mtr_t   mtr;
 
+	if (sizeof(ulint) != sizeof(void*)) {
+		fprintf(stderr,
+"InnoDB: Error: size of InnoDB's ulint is %lu, but size of void* is %lu.\n"
+"InnoDB: The sizes should be the same so that on a 64-bit platform you can\n"
+"InnoDB: allocate more than 4 GB of memory.",
+			(ulong)sizeof(ulint), (ulong)sizeof(void*));
+	}
+
 	srv_file_per_table = FALSE; /* system tables are created in tablespace
 									0 */
 #ifdef UNIV_DEBUG

From 947057e7717d0d4778fea557a7746b6187f57228 Mon Sep 17 00:00:00 2001
From: "heikki@hundin.mysql.fi" <>
Date: Sat, 20 Dec 2003 13:48:35 +0200
Subject: [PATCH 5/9] univ.i, srv0srv.c:   Define macro ULINTPF which can be
 used in printf statements as the print format of ulint both on Win64 and
 other platforms

---
 innobase/include/univ.i | 32 +++++++++++++-------------------
 innobase/srv/srv0srv.c  | 27 +++++++++++++++------------
 2 files changed, 28 insertions(+), 31 deletions(-)

diff --git a/innobase/include/univ.i b/innobase/include/univ.i
index 2b0f85884b9..cd471a89607 100644
--- a/innobase/include/univ.i
+++ b/innobase/include/univ.i
@@ -67,16 +67,6 @@ Microsoft Visual C++ */
 
 #endif /* #if (defined(WIN32) || ... */
 
-#ifdef NOT_USED
-/* On the 64-bit Windows we replace printf with ut_printf, etc. so that
-we can use the %lu format string to print a 64-bit ulint */
-#if defined(__WIN__) && (defined(WIN64) || defined(_WIN64))
-#define printf 		ut_printf
-#define sprintf 	ut_sprintf
-#define fprintf		ut_fprintf
-#endif
-#endif
-
 /*			DEBUG VERSION CONTROL
 			===================== */
 
@@ -185,23 +175,27 @@ management to ensure correct alignment for doubles etc. */
 */
 
 /* Note that inside MySQL 'byte' is defined as char on Linux! */
-#define byte	unsigned char
+#define byte			unsigned char
 
-/* Another basic type we use is unsigned long integer which is intended to be
-equal to the word size of the machine. */
+/* Another basic type we use is unsigned long integer which should be equal to
+the word size of the machine, that is on a 32-bit platform 32 bits, and on a
+64-bit platform 64 bits. We also give the printf format for the type as a
+macro PRULINT. */
 
 #ifdef _WIN64
 typedef unsigned __int64	ulint;
+#define ULINTPF			"%I64u"
+typedef __int64			lint;
 #else
 typedef unsigned long int	ulint;
+#define ULINTPF			"%lu"
+typedef long int		lint;
 #endif
 
-typedef long int		lint;
-
 #ifdef __WIN__
-typedef __int64       ib_longlong;
+typedef __int64			ib_longlong;
 #else
-typedef longlong ib_longlong;
+typedef longlong		ib_longlong;
 #endif
 
 #ifndef __WIN__
@@ -211,7 +205,7 @@ typedef longlong ib_longlong;
 #endif
 
 /* The following type should be at least a 64-bit floating point number */
-typedef double		utfloat;
+typedef double			utfloat;
 
 /* The 'undefined' value for a ulint */
 #define ULINT_UNDEFINED		((ulint)(-1))
@@ -224,7 +218,7 @@ typedef double		utfloat;
 
 /* This 'ibool' type is used within Innobase. Remember that different included
 headers may define 'bool' differently. Do not assume that 'bool' is a ulint! */
-#define ibool	ulint
+#define ibool			ulint
 
 #ifndef TRUE
 
diff --git a/innobase/srv/srv0srv.c b/innobase/srv/srv0srv.c
index 2c1cb07c703..027d7c8fb6e 100644
--- a/innobase/srv/srv0srv.c
+++ b/innobase/srv/srv0srv.c
@@ -2447,20 +2447,22 @@ srv_sprintf_innodb_monitor(
 		       "BUFFER POOL AND MEMORY\n"
 		       "----------------------\n");
 	buf += sprintf(buf,
-	"Total memory allocated %lu; in additional pool allocated %lu\n",
-				(ulong) ut_total_allocated_memory,
-				(ulong) mem_pool_get_reserved(mem_comm_pool));
+	"Total memory allocated " ULINTPF
+	"; in additional pool allocated" ULINTPF "\n",
+				ut_total_allocated_memory,
+				mem_pool_get_reserved(mem_comm_pool));
 
 	if (mem_out_of_mem_err_msg_count > 0) {
 	        buf += sprintf(buf,
-	"Mem allocation has spilled out of additional mem pool %lu times\n",
-					(ulong) mem_out_of_mem_err_msg_count);
+	"Mem allocation has spilled out of additional mem pool" ULINTPF
+						"times\n",
+					mem_out_of_mem_err_msg_count);
 	}
 
 	if (srv_use_awe) {
 		buf += sprintf(buf,
 	"In addition to that %lu MB of AWE memory allocated\n",
-			       (ulong) (srv_pool_size / ((1024 * 1024) / UNIV_PAGE_SIZE)));
+		(ulong) (srv_pool_size / ((1024 * 1024) / UNIV_PAGE_SIZE)));
 	}
 	
 	buf_print_io(buf, buf_end);
@@ -2472,7 +2474,7 @@ srv_sprintf_innodb_monitor(
 		       "--------------\n");
 	buf += sprintf(buf,
         "%ld queries inside InnoDB, %lu queries in queue\n",
-		       (ulong) srv_conc_n_threads,
+		       (long) srv_conc_n_threads,
 		       (ulong) srv_conc_n_waiting_threads);
 
         n_reserved = fil_space_get_n_reserved_extents(0);
@@ -2495,11 +2497,12 @@ srv_sprintf_innodb_monitor(
 			srv_main_thread_op_info);
 #endif
 	buf += sprintf(buf,
-	"Number of rows inserted %lu, updated %lu, deleted %lu, read %lu\n",
-			(ulong) srv_n_rows_inserted, 
-			(ulong) srv_n_rows_updated, 
-			(ulong) srv_n_rows_deleted, 
-			(ulong) srv_n_rows_read);
+	"Number of rows inserted " ULINTPF
+	", updated " ULINTPF ", deleted " ULINTPF ", read " ULINTPF "\n",
+			srv_n_rows_inserted, 
+			srv_n_rows_updated, 
+			srv_n_rows_deleted, 
+			srv_n_rows_read);
 	buf += sprintf(buf,
 	"%.2f inserts/s, %.2f updates/s, %.2f deletes/s, %.2f reads/s\n",
 			(srv_n_rows_inserted - srv_n_rows_inserted_old)

From 0279dc42342b662b935838dea177d07dc775f6db Mon Sep 17 00:00:00 2001
From: "monty@mysql.com" <>
Date: Sun, 21 Dec 2003 19:39:32 +0200
Subject: [PATCH 6/9] Portability fixes found during 5.0 test compilation Fixed
 bug in ORDER BY on a small column (Bug #2147) Fixed error from
 pthread_mutex_destroy() when one had wrong errmsg file

---
 client/mysqltest.c                   | 19 ++++++++++++-------
 mysql-test/mysql-test-run.sh         | 10 ++++++++--
 mysql-test/r/init_connect.result     |  2 +-
 mysql-test/r/order_by.result         |  6 ++++++
 mysql-test/t/init_connect-master.opt |  2 +-
 mysql-test/t/init_connect.test       |  2 +-
 mysql-test/t/order_by.test           |  8 ++++++++
 sql/filesort.cc                      | 14 +-------------
 sql/item.h                           |  2 +-
 sql/item_func.cc                     | 14 +++++++++++---
 sql/log_event.cc                     |  4 ++--
 sql/sql_class.h                      |  7 +++++--
 sql/sql_prepare.cc                   |  4 ++--
 13 files changed, 59 insertions(+), 35 deletions(-)

diff --git a/client/mysqltest.c b/client/mysqltest.c
index d034007cb29..bb1151fa178 100644
--- a/client/mysqltest.c
+++ b/client/mysqltest.c
@@ -2154,7 +2154,7 @@ int run_query(MYSQL* mysql, struct st_query* q, int flags)
   DYNAMIC_STRING ds_tmp;
   DYNAMIC_STRING eval_query;
   char* query;
-  int query_len;
+  int query_len, got_error_on_send= 0;
   DBUG_ENTER("run_query");
   
   if (q->type != Q_EVAL)
@@ -2179,9 +2179,13 @@ int run_query(MYSQL* mysql, struct st_query* q, int flags)
   else
     ds= &ds_res;
 
-  if ((flags & QUERY_SEND) && mysql_send_query(mysql, query, query_len))
-    die("At line %u: unable to send query '%s'(mysql_errno=%d,errno=%d)",
-	start_lineno, query, mysql_errno(mysql), errno);
+  if (flags & QUERY_SEND)
+  {
+    got_error_on_send= mysql_send_query(mysql, query, query_len);
+    if (got_error_on_send && !q->expected_errno[0])
+      die("At line %u: unable to send query '%s' (mysql_errno=%d , errno=%d)",
+	  start_lineno, query, mysql_errno(mysql), errno);
+  }
 
   do
   {
@@ -2194,9 +2198,10 @@ int run_query(MYSQL* mysql, struct st_query* q, int flags)
     if (!(flags & QUERY_REAP))
       DBUG_RETURN(0);
 
-    if ((!counter && (*mysql->methods->read_query_result)(mysql)) ||
-	(!(last_result= res= mysql_store_result(mysql)) &&
-	 mysql_field_count(mysql)))
+    if (got_error_on_send ||
+	(!counter && (*mysql->methods->read_query_result)(mysql)) ||
+	 (!(last_result= res= mysql_store_result(mysql)) &&
+	  mysql_field_count(mysql)))
     {
       if (q->require_file)
       {
diff --git a/mysql-test/mysql-test-run.sh b/mysql-test/mysql-test-run.sh
index c3bba8d7a70..265ff036998 100644
--- a/mysql-test/mysql-test-run.sh
+++ b/mysql-test/mysql-test-run.sh
@@ -198,6 +198,8 @@ USER_TEST=
 
 EXTRA_MASTER_OPT=""
 EXTRA_MYSQL_TEST_OPT=""
+EXTRA_MYSQLDUMP_OPT=""
+EXTRA_MYSQLBINLOG_OPT=""
 USE_RUNNING_SERVER=""
 DO_GCOV=""
 DO_GDB=""
@@ -373,6 +375,10 @@ while test $# -gt 0; do
        --debug=d:t:i:A,$MYSQL_TEST_DIR/var/log/slave.trace"
       EXTRA_MYSQL_TEST_OPT="$EXTRA_MYSQL_TEST_OPT \
        --debug=d:t:A,$MYSQL_TEST_DIR/var/log/mysqltest.trace"
+      EXTRA_MYSQLDUMP_OPT="$EXTRA_MYSQLDUMP_OPT \
+       --debug=d:t:A,$MYSQL_TEST_DIR/var/log/mysqldump.trace"
+      EXTRA_MYSQLBINLOG_OPT="$EXTRA_MYSQLBINLOG_OPT \
+       --debug=d:t:A,$MYSQL_TEST_DIR/var/log/mysqlbinlog.trace"
       ;;
     --fast)
       FAST_START=1
@@ -490,8 +496,8 @@ else
   fi
 fi
 
-MYSQL_DUMP="$MYSQL_DUMP --no-defaults -uroot --socket=$MASTER_MYSOCK"
-MYSQL_BINLOG="$MYSQL_BINLOG --no-defaults --local-load=$MYSQL_TMP_DIR"
+MYSQL_DUMP="$MYSQL_DUMP --no-defaults -uroot --socket=$MASTER_MYSOCK  $EXTRA_MYSQLDUMP_OPT"
+MYSQL_BINLOG="$MYSQL_BINLOG --no-defaults --local-load=$MYSQL_TMP_DIR $EXTRA_MYSQLBINLOG_OPT"
 export MYSQL_DUMP
 export MYSQL_BINLOG
 
diff --git a/mysql-test/r/init_connect.result b/mysql-test/r/init_connect.result
index 3f8e726c775..db1e72dfca9 100644
--- a/mysql-test/r/init_connect.result
+++ b/mysql-test/r/init_connect.result
@@ -20,5 +20,5 @@ hex(a)
 616263
 set GLOBAL init_connect="adsfsdfsdfs";
 select @a;
-ERROR HY000: Lost connection to MySQL server during query
+Got one of the listed errors
 drop table t1;
diff --git a/mysql-test/r/order_by.result b/mysql-test/r/order_by.result
index a321e8a44f9..4d166a961f3 100644
--- a/mysql-test/r/order_by.result
+++ b/mysql-test/r/order_by.result
@@ -584,3 +584,9 @@ CREATE TABLE t1 (a INT, b INT);
 SET @id=0;
 UPDATE t1 SET a=0 ORDER BY (a=@id), b;
 DROP TABLE t1;
+CREATE TABLE t1 (  id smallint(6) unsigned NOT NULL default '0',  menu tinyint(4) NOT NULL default '0',  KEY id (id),  KEY menu (menu)) ENGINE=MyISAM;
+INSERT INTO t1 VALUES (11384, 2),(11392, 2);
+SELECT id FROM t1 WHERE id <11984 AND menu =2 ORDER BY id DESC LIMIT 1 ;
+id
+11392
+drop table t1;
diff --git a/mysql-test/t/init_connect-master.opt b/mysql-test/t/init_connect-master.opt
index e3316c2def5..108a8687aa2 100644
--- a/mysql-test/t/init_connect-master.opt
+++ b/mysql-test/t/init_connect-master.opt
@@ -1 +1 @@
---set-variable=init_connect="set @a='a\0c'"
+--set-variable=init_connect="set @a='a\\0c'"
diff --git a/mysql-test/t/init_connect.test b/mysql-test/t/init_connect.test
index 563ec6178d0..29962abc04d 100644
--- a/mysql-test/t/init_connect.test
+++ b/mysql-test/t/init_connect.test
@@ -28,7 +28,7 @@ connection con0;
 set GLOBAL init_connect="adsfsdfsdfs";
 connect (con5,localhost,user_1,,);
 connection con5;
---error 2013
+--error 2013,2006
 select @a;
 connection con0;
 drop table t1;
diff --git a/mysql-test/t/order_by.test b/mysql-test/t/order_by.test
index bb72c5278f9..1db783c212b 100644
--- a/mysql-test/t/order_by.test
+++ b/mysql-test/t/order_by.test
@@ -373,3 +373,11 @@ SET @id=0;
 UPDATE t1 SET a=0 ORDER BY (a=@id), b;
 DROP TABLE t1;
 
+#
+# Bug when doing an order by on a 1 byte string (Bug #2147)
+#
+
+CREATE TABLE t1 (  id smallint(6) unsigned NOT NULL default '0',  menu tinyint(4) NOT NULL default '0',  KEY id (id),  KEY menu (menu)) ENGINE=MyISAM;
+INSERT INTO t1 VALUES (11384, 2),(11392, 2);
+SELECT id FROM t1 WHERE id <11984 AND menu =2 ORDER BY id DESC LIMIT 1 ;
+drop table t1;
diff --git a/sql/filesort.cc b/sql/filesort.cc
index 720c059a70b..b69aaf44e46 100644
--- a/sql/filesort.cc
+++ b/sql/filesort.cc
@@ -151,8 +151,6 @@ ha_rows filesort(THD *thd, TABLE *table, SORT_FIELD *sortorder, uint s_length,
     records=table->file->estimate_number_of_rows();
     selected_records_file= 0;
   }
-  if (param.rec_length == param.ref_length && records > param.max_rows)
-    records=param.max_rows;			/* purecov: inspected */
 
   if (multi_byte_charset &&
       !(param.tmp_buffer=my_malloc(param.sort_length,MYF(MY_WME))))
@@ -182,7 +180,7 @@ ha_rows filesort(THD *thd, TABLE *table, SORT_FIELD *sortorder, uint s_length,
 		       DISK_BUFFER_SIZE, MYF(MY_WME)))
     goto err;
 
-  param.keys--;
+  param.keys--;  			/* TODO: check why we do this */
   param.sort_form= table;
   param.end=(param.local_sortorder=sortorder)+s_length;
   if ((records=find_all_keys(&param,select,sort_keys, &buffpek_pointers,
@@ -408,16 +406,6 @@ static ha_rows find_all_keys(SORTPARAM *param, SQL_SELECT *select,
 	if (write_keys(param,sort_keys,idx,buffpek_pointers,tempfile))
 	  DBUG_RETURN(HA_POS_ERROR);
 	idx=0;
-	if (param->ref_length == param->rec_length &&
-	    my_b_tell(tempfile)/param->rec_length >= param->max_rows)
-	{
-	  /*
-	    We are writing the result index file and have found all
-	    rows that we need.  Abort the sort and return the result.
-	  */
-	  error=HA_ERR_END_OF_FILE;
-	  break;			/* Found enough records */
-	}
 	indexpos++;
       }
       make_sortkey(param,sort_keys[idx++],ref_pos);
diff --git a/sql/item.h b/sql/item.h
index c6258518213..5def1e2b710 100644
--- a/sql/item.h
+++ b/sql/item.h
@@ -128,7 +128,7 @@ public:
   virtual ~Item() { name=0; cleanup(); }		/*lint -e1509 */
   void set_name(const char *str,uint length, CHARSET_INFO *cs);
   void init_make_field(Send_field *tmp_field,enum enum_field_types type);
-  virtual void cleanup() {}
+  virtual void cleanup() { fixed=0; }
   virtual void make_field(Send_field *field);
   virtual bool fix_fields(THD *, struct st_table_list *, Item **);
   virtual int save_in_field(Field *field, bool no_conversions);
diff --git a/sql/item_func.cc b/sql/item_func.cc
index 8d8b77e527e..a251be402ce 100644
--- a/sql/item_func.cc
+++ b/sql/item_func.cc
@@ -1772,17 +1772,25 @@ char *ull_get_key(const ULL *ull,uint *length,
   return (char*) ull->key;
 }
 
+
+static bool item_user_lock_inited= 0;
+
 void item_user_lock_init(void)
 {
   pthread_mutex_init(&LOCK_user_locks,MY_MUTEX_INIT_SLOW);
   hash_init(&hash_user_locks,system_charset_info,
 	    16,0,0,(hash_get_key) ull_get_key,NULL,0);
+  item_user_lock_inited= 1;
 }
 
 void item_user_lock_free(void)
 {
-  hash_free(&hash_user_locks);
-  pthread_mutex_destroy(&LOCK_user_locks);
+  if (item_user_lock_inited)
+  {
+    item_user_lock_inited= 0;
+    hash_free(&hash_user_locks);
+    pthread_mutex_destroy(&LOCK_user_locks);
+  }
 }
 
 void item_user_lock_release(ULL *ull)
@@ -2442,7 +2450,7 @@ Item_func_get_user_var::val_str(String *str)
 {
   DBUG_ENTER("Item_func_get_user_var::val_str");
   if (!var_entry)
-    return (String*) 0;				// No such variable
+    DBUG_RETURN((String*) 0);			// No such variable
   DBUG_RETURN(var_entry->val_str(&null_value, str, decimals));
 }
 
diff --git a/sql/log_event.cc b/sql/log_event.cc
index b609e6c6b11..1f20948aa82 100644
--- a/sql/log_event.cc
+++ b/sql/log_event.cc
@@ -2344,13 +2344,13 @@ int User_var_log_event::exec_event(struct st_relay_log_info* rli)
       float8get(real_val, val);
       it= new Item_real(real_val);
       val= (char*) &real_val;		// Pointer to value in native format
-      val_len= sizeof(real_val);
+      val_len= 8;
       break;
     case INT_RESULT:
       int_val= (longlong) uint8korr(val);
       it= new Item_int(int_val);
       val= (char*) &int_val;		// Pointer to value in native format
-      val_len= sizeof(int_val);
+      val_len= 8;
       break;
     case STRING_RESULT:
       it= new Item_string(val, val_len, charset);
diff --git a/sql/sql_class.h b/sql/sql_class.h
index d663521b296..546a90d2be3 100644
--- a/sql/sql_class.h
+++ b/sql/sql_class.h
@@ -801,8 +801,11 @@ public:
   inline void	end_time()    { time(&start_time); }
   inline void	set_time(time_t t) { time_after_lock=start_time=user_time=t; }
   inline void	lock_time()   { time(&time_after_lock); }
-  inline void	insert_id(ulonglong id)
-  { last_insert_id=id; insert_id_used=1; }
+  inline void	insert_id(ulonglong id_arg)
+  {
+    last_insert_id= id_arg;
+    insert_id_used=1;
+  }
   inline ulonglong insert_id(void)
   {
     if (!last_insert_id_used)
diff --git a/sql/sql_prepare.cc b/sql/sql_prepare.cc
index f60e0db58d0..a513e445db9 100644
--- a/sql/sql_prepare.cc
+++ b/sql/sql_prepare.cc
@@ -887,7 +887,7 @@ bool mysql_stmt_prepare(THD *thd, char *packet, uint packet_length)
 {
   LEX *lex;
   Prepared_statement *stmt= new Prepared_statement(thd);
-
+  SELECT_LEX *sl;
   DBUG_ENTER("mysql_stmt_prepare");
 
   if (stmt == 0)
@@ -918,7 +918,7 @@ bool mysql_stmt_prepare(THD *thd, char *packet, uint packet_length)
     my_pthread_setprio(pthread_self(),WAIT_PRIOR);
 
   // save WHERE clause pointers to avoid damaging they by optimisation
-  for (SELECT_LEX *sl= thd->lex->all_selects_list;
+  for (sl= thd->lex->all_selects_list;
        sl;
        sl= sl->next_select_in_list())
   {

From 9de694e5eb5a0904ade062d2e54da41aff2ff025 Mon Sep 17 00:00:00 2001
From: "konstantin@oak.local" <>
Date: Sun, 21 Dec 2003 22:26:45 +0300
Subject: [PATCH 7/9] THD::init_for_queries() pushed back: see comments to the
 method why

---
 sql/slave.cc     |  1 +
 sql/sql_class.cc | 23 +++++++++++++++++------
 sql/sql_class.h  | 11 ++++++++++-
 sql/sql_parse.cc |  2 ++
 4 files changed, 30 insertions(+), 7 deletions(-)

diff --git a/sql/slave.cc b/sql/slave.cc
index d2a7d397fa7..8af38624df6 100644
--- a/sql/slave.cc
+++ b/sql/slave.cc
@@ -3111,6 +3111,7 @@ slave_begin:
     sql_print_error("Failed during slave thread initialization");
     goto err;
   }
+  thd->init_for_queries();
   rli->sql_thd= thd;
   thd->temporary_tables = rli->save_temporary_tables; // restore temp tables
   pthread_mutex_lock(&LOCK_thread_count);
diff --git a/sql/sql_class.cc b/sql/sql_class.cc
index 606ecdbecbb..12f0cc4ca72 100644
--- a/sql/sql_class.cc
+++ b/sql/sql_class.cc
@@ -144,9 +144,6 @@ THD::THD():user_time(0), is_fatal_error(0),
   *scramble= '\0';
 
   init();
-  init_sql_alloc(&mem_root,                    // must be after init()
-                 variables.query_alloc_block_size,
-                 variables.query_prealloc_size);
   /* Initialize sub structures */
   bzero((char*) &transaction.mem_root,sizeof(transaction.mem_root));
   bzero((char*) &warn_root,sizeof(warn_root));
@@ -182,9 +179,6 @@ THD::THD():user_time(0), is_fatal_error(0),
     transaction.trans_log.end_of_file= max_binlog_cache_size;
   }
 #endif
-  init_sql_alloc(&transaction.mem_root,         
-		 variables.trans_alloc_block_size, 
-		 variables.trans_prealloc_size);
   /*
     We need good random number initialization for new thread
     Just coping global one will not work
@@ -227,6 +221,23 @@ void THD::init(void)
 }
 
 
+/*
+  Init THD for query processing.
+  This has to be called once before we call mysql_parse.
+  See also comments in sql_class.h.
+*/
+
+void THD::init_for_queries()
+{
+  init_sql_alloc(&mem_root,
+                 variables.query_alloc_block_size,
+                 variables.query_prealloc_size);
+  init_sql_alloc(&transaction.mem_root,         
+		 variables.trans_alloc_block_size, 
+		 variables.trans_prealloc_size);
+}
+
+
 /*
   Do what's needed when one invokes change user
 
diff --git a/sql/sql_class.h b/sql/sql_class.h
index d663521b296..1451218f42b 100644
--- a/sql/sql_class.h
+++ b/sql/sql_class.h
@@ -405,7 +405,6 @@ struct system_variables
 
 void free_tmp_table(THD *thd, TABLE *entry);
 
-class Prepared_statement;
 
 /*
   State of a single command executed against this connection.
@@ -760,6 +759,16 @@ public:
   ~THD();
 
   void init(void);
+  /*
+    Initialize memory roots necessary for query processing and (!)
+    pre-allocate memory for it. We can't do that in THD constructor because
+    there are use cases (acl_init, delayed inserts, watcher threads,
+    killing mysqld) where it's vital to not allocate excessive and not used
+    memory. Note, that we still don't return error from init_for_queries():
+    if preallocation fails, we should notice that at the first call to
+    alloc_root. 
+  */
+  void init_for_queries();
   void change_user(void);
   void cleanup(void);
   bool store_globals();
diff --git a/sql/sql_parse.cc b/sql/sql_parse.cc
index 6d975de421f..678d0890136 100644
--- a/sql/sql_parse.cc
+++ b/sql/sql_parse.cc
@@ -974,6 +974,7 @@ pthread_handler_decl(handle_one_connection,arg)
 
     thd->proc_info=0;
     thd->set_time();
+    thd->init_for_queries();
     while (!net->error && net->vio != 0 && !thd->killed)
     {
       if (do_command(thd))
@@ -1054,6 +1055,7 @@ extern "C" pthread_handler_decl(handle_bootstrap,arg)
   thd->priv_user=thd->user=(char*) my_strdup("boot", MYF(MY_WME));
 
   buff= (char*) thd->net.buff;
+  thd->init_for_queries();
   while (fgets(buff, thd->net.max_packet, file))
   {
     uint length=(uint) strlen(buff);

From 0da22d5bd85fa1f438a59fb661f70b12f8ad0559 Mon Sep 17 00:00:00 2001
From: "serg@serg.mylan" <>
Date: Sun, 21 Dec 2003 21:18:59 +0100
Subject: [PATCH 8/9] typo fixed

---
 sql/sql_acl.cc | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/sql/sql_acl.cc b/sql/sql_acl.cc
index 01820917ce9..282a9afa038 100644
--- a/sql/sql_acl.cc
+++ b/sql/sql_acl.cc
@@ -52,7 +52,7 @@ static byte* acl_entry_get_key(acl_entry *entry,uint *length,
   return (byte*) entry->key;
 }
 
-#define IP_ADDR_STRLEN
+#define IP_ADDR_STRLEN (3+1+3+1+3+1+3)
 #define ACL_KEY_LENGTH (IP_ADDR_STRLEN+1+NAME_LEN+1+USERNAME_LENGTH+1)
 
 static DYNAMIC_ARRAY acl_hosts,acl_users,acl_dbs;

From ce88d817966c6703de65ac76ac4873a05cce6681 Mon Sep 17 00:00:00 2001
From: "konstantin@oak.local" <>
Date: Mon, 22 Dec 2003 15:57:34 +0300
Subject: [PATCH 9/9] Names of all client methods (static functions inside
 client.c) now uniform: cli_ + member name.

---
 sql-common/client.c | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)

diff --git a/sql-common/client.c b/sql-common/client.c
index 14b45942e15..08b39d2ca58 100644
--- a/sql-common/client.c
+++ b/sql-common/client.c
@@ -1403,15 +1403,15 @@ mysql_ssl_free(MYSQL *mysql __attribute__((unused)))
   before calling mysql_real_connect !
 */
 
-static my_bool cli_mysql_read_query_result(MYSQL *mysql);
-static MYSQL_RES *cli_mysql_use_result(MYSQL *mysql);
+static my_bool cli_read_query_result(MYSQL *mysql);
+static MYSQL_RES *cli_use_result(MYSQL *mysql);
 
 static MYSQL_METHODS client_methods=
 {
-  cli_mysql_read_query_result,
+  cli_read_query_result,
   cli_advanced_command,
   cli_read_rows,
-  cli_mysql_use_result,
+  cli_use_result,
   cli_fetch_lengths
 #ifndef MYSQL_SERVER
   ,cli_list_fields,
@@ -2022,7 +2022,7 @@ CLI_MYSQL_REAL_CONNECT(MYSQL *mysql,const char *host, const char *user,
 	goto error;
       if (mysql->fields)
       {
-	if (!(res= cli_mysql_use_result(mysql)))
+	if (!(res= cli_use_result(mysql)))
 	  goto error;
 	mysql_free_result(res);
       }
@@ -2240,13 +2240,13 @@ void STDCALL mysql_close(MYSQL *mysql)
   DBUG_VOID_RETURN;
 }
 
-static my_bool cli_mysql_read_query_result(MYSQL *mysql)
+static my_bool cli_read_query_result(MYSQL *mysql)
 {
   uchar *pos;
   ulong field_count;
   MYSQL_DATA *fields;
   ulong length;
-  DBUG_ENTER("cli_mysql_read_query_result");
+  DBUG_ENTER("cli_read_query_result");
 
   /*
     Read from the connection which we actually used, which
@@ -2419,10 +2419,10 @@ MYSQL_RES * STDCALL mysql_store_result(MYSQL *mysql)
   have to wait for the client (and will not wait more than 30 sec/packet).
 **************************************************************************/
 
-static MYSQL_RES * cli_mysql_use_result(MYSQL *mysql)
+static MYSQL_RES * cli_use_result(MYSQL *mysql)
 {
   MYSQL_RES *result;
-  DBUG_ENTER("cli_mysql_use_result");
+  DBUG_ENTER("cli_use_result");
 
   mysql = mysql->last_used_con;