lock.cc 26.3 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
unknown's avatar
unknown committed
2

unknown's avatar
unknown committed
3 4 5 6
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
unknown's avatar
unknown committed
7

unknown's avatar
unknown committed
8 9 10 11
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
unknown's avatar
unknown committed
12

unknown's avatar
unknown committed
13 14 15 16 17 18 19 20 21 22 23
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


/* locking functions for mysql */
/*
  Because of the new concurrent inserts, we must first get external locks
  before getting internal locks.  If we do it in the other order, the status
  information is not up to date when called from the lock handler.

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
  GENERAL DESCRIPTION OF LOCKING

  When not using LOCK TABLES:

  - For each SQL statement mysql_lock_tables() is called for all involved
    tables.
    - mysql_lock_tables() will call
      table_handler->external_lock(thd,locktype) for each table.
      This is followed by a call to thr_multi_lock() for all tables.

  - When statement is done, we call mysql_unlock_tables().
    This will call thr_multi_unlock() followed by
    table_handler->external_lock(thd, F_UNLCK) for each table.

  - Note that mysql_unlock_tables() may be called several times as
    MySQL in some cases can free some tables earlier than others.

  - The above is true both for normal and temporary tables.

  - Temporary non transactional tables are never passed to thr_multi_lock()
    and we never call external_lock(thd, F_UNLOCK) on these.

  When using LOCK TABLES:

  - LOCK TABLE will call mysql_lock_tables() for all tables.
    mysql_lock_tables() will call
    table_handler->external_lock(thd,locktype) for each table.
    This is followed by a call to thr_multi_lock() for all tables.

  - For each statement, we will call table_handler->start_stmt(THD)
    to inform the table handler that we are using the table.

    The tables used can only be tables used in LOCK TABLES or a
    temporary table.

  - When statement is done, we will call ha_commit_stmt(thd);

  - When calling UNLOCK TABLES we call mysql_unlock_tables() for all
    tables used in LOCK TABLES

unknown's avatar
unknown committed
64 65 66 67 68 69 70
TODO:
  Change to use my_malloc() ONLY when using LOCK TABLES command or when
  we are forced to use mysql_lock_merge.
*/

#include "mysql_priv.h"
#include <hash.h>
unknown's avatar
unknown committed
71
#include "ha_myisammrg.h"
unknown's avatar
unknown committed
72 73 74 75 76
#ifndef MASTER
#include "../srclib/myisammrg/myrg_def.h"
#else
#include "../myisammrg/myrg_def.h"
#endif
unknown's avatar
unknown committed
77 78 79

static MYSQL_LOCK *get_lock_data(THD *thd, TABLE **table,uint count,
				 bool unlock, TABLE **write_locked);
80
static int lock_external(THD *thd, TABLE **table,uint count);
unknown's avatar
unknown committed
81
static int unlock_external(THD *thd, TABLE **table,uint count);
82
static void print_lock_error(int error, const char *);
unknown's avatar
unknown committed
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101


MYSQL_LOCK *mysql_lock_tables(THD *thd,TABLE **tables,uint count)
{
  MYSQL_LOCK *sql_lock;
  TABLE *write_lock_used;
  DBUG_ENTER("mysql_lock_tables");

  for (;;)
  {
    if (!(sql_lock = get_lock_data(thd,tables,count, 0,&write_lock_used)))
      break;

    if (global_read_lock && write_lock_used)
    {
      /*
	Someone has issued LOCK ALL TABLES FOR READ and we want a write lock
	Wait until the lock is gone
      */
102
      if (wait_if_global_read_lock(thd, 1, 1))
unknown's avatar
unknown committed
103 104 105 106 107
      {
	my_free((gptr) sql_lock,MYF(0));
	sql_lock=0;
	break;
      }	
108
      if (thd->version != refresh_version)
unknown's avatar
unknown committed
109 110 111 112 113 114 115
      {
	my_free((gptr) sql_lock,MYF(0));
	goto retry;
      }
    }

    thd->proc_info="System lock";
116
    if (lock_external(thd, tables, count))
unknown's avatar
unknown committed
117 118 119 120 121 122
    {
      my_free((gptr) sql_lock,MYF(0));
      sql_lock=0;
      thd->proc_info=0;
      break;
    }
123
    thd->proc_info="Table lock";
unknown's avatar
unknown committed
124 125 126 127 128 129 130 131 132 133 134
    thd->locked=1;
    if (thr_multi_lock(sql_lock->locks,sql_lock->lock_count))
    {
      thd->some_tables_deleted=1;		// Try again
      sql_lock->lock_count=0;			// Locks are alread freed
    }
    else if (!thd->some_tables_deleted)
    {
      thd->locked=0;
      break;
    }
135 136 137 138 139 140 141
    else if (!thd->open_tables)
    {
      // Only using temporary tables, no need to unlock
      thd->some_tables_deleted=0;
      thd->locked=0;
      break;
    }
142
    thd->proc_info=0;
unknown's avatar
unknown committed
143 144 145 146 147 148 149 150 151

    /* some table was altered or deleted. reopen tables marked deleted */
    mysql_unlock_tables(thd,sql_lock);
    thd->locked=0;
retry:
    sql_lock=0;
    if (wait_for_tables(thd))
      break;					// Couldn't open tables
  }
152
  thd->proc_info=0;
unknown's avatar
unknown committed
153 154
  if (thd->killed)
  {
unknown's avatar
SCRUM  
unknown committed
155
    thd->send_kill_message();
unknown's avatar
unknown committed
156 157 158 159 160 161
    if (sql_lock)
    {
      mysql_unlock_tables(thd,sql_lock);
      sql_lock=0;
    }
  }
unknown's avatar
unknown committed
162

163
  thd->lock_time();
unknown's avatar
unknown committed
164 165 166 167
  DBUG_RETURN (sql_lock);
}


168
static int lock_external(THD *thd, TABLE **tables, uint count)
unknown's avatar
unknown committed
169 170 171 172 173 174 175
{
  reg1 uint i;
  int lock_type,error;
  DBUG_ENTER("lock_external");

  for (i=1 ; i <= count ; i++, tables++)
  {
unknown's avatar
unknown committed
176
    DBUG_ASSERT((*tables)->reginfo.lock_type >= TL_READ);
unknown's avatar
unknown committed
177 178 179 180 181 182 183 184
    lock_type=F_WRLCK;				/* Lock exclusive */
    if ((*tables)->db_stat & HA_READ_ONLY ||
	((*tables)->reginfo.lock_type >= TL_READ &&
	 (*tables)->reginfo.lock_type <= TL_READ_NO_INSERT))
      lock_type=F_RDLCK;

    if ((error=(*tables)->file->external_lock(thd,lock_type)))
    {
185
      print_lock_error(error, (*tables)->file->table_type());
186
      for (; i-- ; tables--)
unknown's avatar
unknown committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
      {
	(*tables)->file->external_lock(thd, F_UNLCK);
	(*tables)->current_lock=F_UNLCK;
      }
      DBUG_RETURN(error);
    }
    else
    {
      (*tables)->db_stat &= ~ HA_BLOCK_LOCK;
      (*tables)->current_lock= lock_type;
    }
  }
  DBUG_RETURN(0);
}


void mysql_unlock_tables(THD *thd, MYSQL_LOCK *sql_lock)
{
  DBUG_ENTER("mysql_unlock_tables");
unknown's avatar
unknown committed
206 207
  if (sql_lock->lock_count)
    thr_multi_unlock(sql_lock->locks,sql_lock->lock_count);
208
  if (sql_lock->table_count)
unknown's avatar
unknown committed
209
    VOID(unlock_external(thd,sql_lock->table,sql_lock->table_count));
unknown's avatar
unknown committed
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
  my_free((gptr) sql_lock,MYF(0));
  DBUG_VOID_RETURN;
}

/*
  Unlock some of the tables locked by mysql_lock_tables
  This will work even if get_lock_data fails (next unlock will free all)
  */

void mysql_unlock_some_tables(THD *thd, TABLE **table,uint count)
{
  MYSQL_LOCK *sql_lock;
  TABLE *write_lock_used;
  if ((sql_lock = get_lock_data(thd, table, count, 1, &write_lock_used)))
    mysql_unlock_tables(thd, sql_lock);
}


/*
** unlock all tables locked for read.
*/

void mysql_unlock_read_tables(THD *thd, MYSQL_LOCK *sql_lock)
{
  uint i,found;
  DBUG_ENTER("mysql_unlock_read_tables");

  /* Move all write locks first */
  THR_LOCK_DATA **lock=sql_lock->locks;
  for (i=found=0 ; i < sql_lock->lock_count ; i++)
  {
    if (sql_lock->locks[i]->type >= TL_WRITE_ALLOW_READ)
    {
243
      swap_variables(THR_LOCK_DATA *, *lock, sql_lock->locks[i]);
unknown's avatar
unknown committed
244 245 246 247 248 249 250 251
      lock++;
      found++;
    }
  }
  /* unlock the read locked tables */
  if (i != found)
  {
    thr_multi_unlock(lock,i-found);
unknown's avatar
unknown committed
252
    sql_lock->lock_count= found;
unknown's avatar
unknown committed
253 254
  }

255
  /* Then do the same for the external locks */
unknown's avatar
unknown committed
256 257 258 259 260 261
  /* Move all write locked tables first */
  TABLE **table=sql_lock->table;
  for (i=found=0 ; i < sql_lock->table_count ; i++)
  {
    if ((uint) sql_lock->table[i]->reginfo.lock_type >= TL_WRITE_ALLOW_READ)
    {
262
      swap_variables(TABLE *, *table, sql_lock->table[i]);
unknown's avatar
unknown committed
263 264 265 266 267 268 269 270
      table++;
      found++;
    }
  }
  /* Unlock all read locked tables */
  if (i != found)
  {
    VOID(unlock_external(thd,table,i-found));
unknown's avatar
unknown committed
271
    sql_lock->table_count=found;
unknown's avatar
unknown committed
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
  }
  DBUG_VOID_RETURN;
}



void mysql_lock_remove(THD *thd, MYSQL_LOCK *locked,TABLE *table)
{
  mysql_unlock_some_tables(thd, &table,1);
  if (locked)
  {
    reg1 uint i;
    for (i=0; i < locked->table_count; i++)
    {
      if (locked->table[i] == table)
      {
	locked->table_count--;
	bmove((char*) (locked->table+i),
	      (char*) (locked->table+i+1),
	      (locked->table_count-i)* sizeof(TABLE*));
	break;
      }
    }
    THR_LOCK_DATA **prev=locked->locks;
    for (i=0 ; i < locked->lock_count ; i++)
    {
      if (locked->locks[i]->type != TL_UNLOCK)
	*prev++ = locked->locks[i];
    }
unknown's avatar
unknown committed
301
    locked->lock_count=(uint) (prev - locked->locks);
unknown's avatar
unknown committed
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
  }
}

/* abort all other threads waiting to get lock in table */

void mysql_lock_abort(THD *thd, TABLE *table)
{
  MYSQL_LOCK *locked;
  TABLE *write_lock_used;
  if ((locked = get_lock_data(thd,&table,1,1,&write_lock_used)))
  {
    for (uint i=0; i < locked->lock_count; i++)
      thr_abort_locks(locked->locks[i]->lock);
    my_free((gptr) locked,MYF(0));
  }
}


320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
/* Abort one thread / table combination */

void mysql_lock_abort_for_thread(THD *thd, TABLE *table)
{
  MYSQL_LOCK *locked;
  TABLE *write_lock_used;
  DBUG_ENTER("mysql_lock_abort_for_thread");

  if ((locked = get_lock_data(thd,&table,1,1,&write_lock_used)))
  {
    for (uint i=0; i < locked->lock_count; i++)
      thr_abort_locks_for_thread(locked->locks[i]->lock,
				 table->in_use->real_id);
    my_free((gptr) locked,MYF(0));
  }
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
MYSQL_LOCK *mysql_lock_merge(MYSQL_LOCK *a,MYSQL_LOCK *b)
{
  MYSQL_LOCK *sql_lock;
  DBUG_ENTER("mysql_lock_merge");
  if (!(sql_lock= (MYSQL_LOCK*)
	my_malloc(sizeof(*sql_lock)+
		  sizeof(THR_LOCK_DATA*)*(a->lock_count+b->lock_count)+
		  sizeof(TABLE*)*(a->table_count+b->table_count),MYF(MY_WME))))
    DBUG_RETURN(0);				// Fatal error
  sql_lock->lock_count=a->lock_count+b->lock_count;
  sql_lock->table_count=a->table_count+b->table_count;
  sql_lock->locks=(THR_LOCK_DATA**) (sql_lock+1);
  sql_lock->table=(TABLE**) (sql_lock->locks+sql_lock->lock_count);
  memcpy(sql_lock->locks,a->locks,a->lock_count*sizeof(*a->locks));
  memcpy(sql_lock->locks+a->lock_count,b->locks,
	 b->lock_count*sizeof(*b->locks));
  memcpy(sql_lock->table,a->table,a->table_count*sizeof(*a->table));
  memcpy(sql_lock->table+a->table_count,b->table,
	 b->table_count*sizeof(*b->table));
  my_free((gptr) a,MYF(0));
  my_free((gptr) b,MYF(0));
  DBUG_RETURN(sql_lock);
}


	/* unlock a set of external */

static int unlock_external(THD *thd, TABLE **table,uint count)
{
  int error,error_code;
  DBUG_ENTER("unlock_external");

  error_code=0;
372
  do
unknown's avatar
unknown committed
373 374 375 376 377
  {
    if ((*table)->current_lock != F_UNLCK)
    {
      (*table)->current_lock = F_UNLCK;
      if ((error=(*table)->file->external_lock(thd, F_UNLCK)))
378
      {
unknown's avatar
unknown committed
379
	error_code=error;
380 381
	print_lock_error(error_code, (*table)->file->table_type());
      }
unknown's avatar
unknown committed
382
    }
383 384
    table++;
  } while (--count);
unknown's avatar
unknown committed
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
  DBUG_RETURN(error_code);
}


/*
** Get lock structures from table structs and initialize locks
*/


static MYSQL_LOCK *get_lock_data(THD *thd, TABLE **table_ptr, uint count,
				 bool get_old_locks, TABLE **write_lock_used)
{
  uint i,tables,lock_count;
  MYSQL_LOCK *sql_lock;
  THR_LOCK_DATA **locks;
  TABLE **to;

  *write_lock_used=0;
  for (i=tables=lock_count=0 ; i < count ; i++)
  {
405
    if (table_ptr[i]->s->tmp_table != TMP_TABLE)
unknown's avatar
unknown committed
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
    {
      tables+=table_ptr[i]->file->lock_count();
      lock_count++;
    }
  }

  if (!(sql_lock= (MYSQL_LOCK*)
	my_malloc(sizeof(*sql_lock)+
		  sizeof(THR_LOCK_DATA*)*tables+sizeof(table_ptr)*lock_count,
		  MYF(0))))
    return 0;
  locks=sql_lock->locks=(THR_LOCK_DATA**) (sql_lock+1);
  to=sql_lock->table=(TABLE**) (locks+tables);
  sql_lock->table_count=lock_count;
  sql_lock->lock_count=tables;

  for (i=0 ; i < count ; i++)
  {
    TABLE *table;
425
    if ((table=table_ptr[i])->s->tmp_table == TMP_TABLE)
unknown's avatar
unknown committed
426 427 428 429 430 431 432 433
      continue;
    *to++=table;
    enum thr_lock_type lock_type= table->reginfo.lock_type;
    if (lock_type >= TL_WRITE_ALLOW_WRITE)
    {
      *write_lock_used=table;
      if (table->db_stat & HA_READ_ONLY)
      {
434
	my_error(ER_OPEN_AS_READONLY, MYF(0), table->alias);
unknown's avatar
unknown committed
435 436 437 438
	my_free((gptr) sql_lock,MYF(0));
	return 0;
      }
    }
unknown's avatar
unknown committed
439
    THR_LOCK_DATA **org_locks = locks;
unknown's avatar
unknown committed
440 441
    locks=table->file->store_lock(thd, locks, get_old_locks ? TL_IGNORE :
				  lock_type);
unknown's avatar
unknown committed
442 443 444
    if (locks)
      for ( ; org_locks != locks ; org_locks++)
	(*org_locks)->debug_print_param= (void *) table;
unknown's avatar
unknown committed
445 446 447
  }
  return sql_lock;
}
448

449

450
/*****************************************************************************
451 452
  Lock table based on the name.
  This is used when we need total access to a closed, not open table
453 454
*****************************************************************************/

455 456
/*
  Lock and wait for the named lock.
457 458 459 460 461 462 463 464 465 466 467 468 469

  SYNOPSIS
    lock_and_wait_for_table_name()
    thd			Thread handler
    table_list		Lock first table in this list


  NOTES
    Works together with global read lock.

  RETURN
    0	ok
    1	error
470 471 472 473 474 475 476 477
*/

int lock_and_wait_for_table_name(THD *thd, TABLE_LIST *table_list)
{
  int lock_retcode;
  int error= -1;
  DBUG_ENTER("lock_and_wait_for_table_name");

478
  if (wait_if_global_read_lock(thd, 0, 1))
479 480 481 482 483 484 485 486 487 488 489 490 491
    DBUG_RETURN(1);
  VOID(pthread_mutex_lock(&LOCK_open));
  if ((lock_retcode = lock_table_name(thd, table_list)) < 0)
    goto end;
  if (lock_retcode && wait_for_locked_table_names(thd, table_list))
  {
    unlock_table_name(thd, table_list);
    goto end;
  }
  error=0;

end:
  pthread_mutex_unlock(&LOCK_open);
unknown's avatar
unknown committed
492
  start_waiting_global_read_lock(thd);
493 494 495 496
  DBUG_RETURN(error);
}


497 498
/*
  Put a not open table with an old refresh version in the table cache.
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520

  SYNPOSIS
    lock_table_name()
    thd			Thread handler
    table_list		Lock first table in this list

  WARNING
    If you are going to update the table, you should use
    lock_and_wait_for_table_name instead of this function as this works
    together with 'FLUSH TABLES WITH READ LOCK'

  NOTES
    This will force any other threads that uses the table to release it
    as soon as possible.

  REQUIREMENTS
    One must have a lock on LOCK_open !

  RETURN:
    < 0 error
    == 0 table locked
    > 0  table locked, but someone is using it
521 522 523 524 525 526
*/

int lock_table_name(THD *thd, TABLE_LIST *table_list)
{
  TABLE *table;
  char  key[MAX_DBKEY_LENGTH];
unknown's avatar
unknown committed
527
  char *db= table_list->db;
528
  uint  key_length;
unknown's avatar
unknown committed
529
  DBUG_ENTER("lock_table_name");
530
  DBUG_PRINT("enter",("db: %s  name: %s", db, table_list->table_name));
531

532
  safe_mutex_assert_owner(&LOCK_open);
unknown's avatar
unknown committed
533

534
  key_length=(uint) (strmov(strmov(key,db)+1,table_list->table_name)
unknown's avatar
unknown committed
535
		     -key)+ 1;
536

537

538 539 540 541 542
  /* Only insert the table if we haven't insert it already */
  for (table=(TABLE*) hash_search(&open_cache,(byte*) key,key_length) ;
       table ;
       table = (TABLE*) hash_next(&open_cache,(byte*) key,key_length))
    if (table->in_use == thd)
unknown's avatar
unknown committed
543
      DBUG_RETURN(0);
544

unknown's avatar
unknown committed
545 546 547 548 549
  /*
    Create a table entry with the right key and with an old refresh version
    Note that we must use my_malloc() here as this is freed by the table
    cache
  */
unknown's avatar
unknown committed
550 551
  if (!(table= (TABLE*) my_malloc(sizeof(*table)+key_length,
				  MYF(MY_WME | MY_ZEROFILL))))
unknown's avatar
unknown committed
552
    DBUG_RETURN(-1);
553 554 555
  table->s= &table->share_not_to_be_used;
  memcpy((table->s->table_cache_key= (char*) (table+1)), key, key_length);
  table->s->key_length=key_length;
556
  table->in_use=thd;
unknown's avatar
unknown committed
557
  table->locked_by_name=1;
558 559
  table_list->table=table;

unknown's avatar
SCRUM  
unknown committed
560
  if (my_hash_insert(&open_cache, (byte*) table))
561 562
  {
    my_free((gptr) table,MYF(0));
unknown's avatar
unknown committed
563
    DBUG_RETURN(-1);
564
  }
565
  if (remove_table_from_cache(thd, db, table_list->table_name))
unknown's avatar
unknown committed
566 567
    DBUG_RETURN(1);					// Table is in use
  DBUG_RETURN(0);
568 569
}

570

571 572 573
void unlock_table_name(THD *thd, TABLE_LIST *table_list)
{
  if (table_list->table)
unknown's avatar
unknown committed
574
  {
unknown's avatar
unknown committed
575
    hash_delete(&open_cache, (byte*) table_list->table);
unknown's avatar
unknown committed
576 577
    (void) pthread_cond_broadcast(&COND_refresh);
  }
578 579
}

580

581 582
static bool locked_named_table(THD *thd, TABLE_LIST *table_list)
{
unknown's avatar
VIEW  
unknown committed
583
  for (; table_list ; table_list=table_list->next_local)
584
  {
unknown's avatar
unknown committed
585
    if (table_list->table && table_is_used(table_list->table,0))
586 587 588 589 590 591 592 593 594
      return 1;
  }
  return 0;					// All tables are locked
}


bool wait_for_locked_table_names(THD *thd, TABLE_LIST *table_list)
{
  bool result=0;
unknown's avatar
unknown committed
595
  DBUG_ENTER("wait_for_locked_table_names");
596
  safe_mutex_assert_owner(&LOCK_open);
597 598 599 600 601 602 603 604 605

  while (locked_named_table(thd,table_list))
  {
    if (thd->killed)
    {
      result=1;
      break;
    }
    wait_for_refresh(thd);
unknown's avatar
unknown committed
606
    pthread_mutex_lock(&LOCK_open);
607
  }
unknown's avatar
unknown committed
608
  DBUG_RETURN(result);
609
}
610

611 612 613 614 615 616 617 618 619 620

/*
  Lock all tables in list with a name lock

  SYNOPSIS
    lock_table_names()
    thd			Thread handle
    table_list		Names of tables to lock

  NOTES
621 622 623 624
    If you are just locking one table, you should use
    lock_and_wait_for_table_name().

  REQUIREMENTS
625 626 627 628 629 630 631 632 633 634 635 636
    One must have a lock on LOCK_open when calling this

  RETURN
    0	ok
    1	Fatal error (end of memory ?)
*/

bool lock_table_names(THD *thd, TABLE_LIST *table_list)
{
  bool got_all_locks=1;
  TABLE_LIST *lock_table;

unknown's avatar
VIEW  
unknown committed
637
  for (lock_table= table_list; lock_table; lock_table= lock_table->next_local)
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
  {
    int got_lock;
    if ((got_lock=lock_table_name(thd,lock_table)) < 0)
      goto end;					// Fatal error
    if (got_lock)
      got_all_locks=0;				// Someone is using table
  }

  /* If some table was in use, wait until we got the lock */
  if (!got_all_locks && wait_for_locked_table_names(thd, table_list))
    goto end;
  return 0;

end:
  unlock_table_names(thd, table_list, lock_table);
  return 1;
}


/*
  Unlock all tables in list with a name lock

  SYNOPSIS
    unlock_table_names()
    thd			Thread handle
    table_list		Names of tables to unlock
    last_table		Don't unlock any tables after this one.
			(default 0, which will unlock all tables)

  NOTES
    One must have a lock on LOCK_open when calling this
    This function will send a COND_refresh signal to inform other threads
    that the name locks are removed

  RETURN
    0	ok
    1	Fatal error (end of memory ?)
*/

void unlock_table_names(THD *thd, TABLE_LIST *table_list,
			TABLE_LIST *last_table)
{
unknown's avatar
VIEW  
unknown committed
680 681 682
  for (TABLE_LIST *table= table_list;
       table != last_table;
       table= table->next_local)
683 684 685 686 687
    unlock_table_name(thd,table);
  pthread_cond_broadcast(&COND_refresh);
}


688
static void print_lock_error(int error, const char *table)
689 690 691 692 693 694 695 696 697 698 699
{
  int textno;
  DBUG_ENTER("print_lock_error");

  switch (error) {
  case HA_ERR_LOCK_WAIT_TIMEOUT:
    textno=ER_LOCK_WAIT_TIMEOUT;
    break;
  case HA_ERR_READ_ONLY_TRANSACTION:
    textno=ER_READ_ONLY_TRANSACTION;
    break;
700 701 702
  case HA_ERR_LOCK_DEADLOCK:
    textno=ER_LOCK_DEADLOCK;
    break;
703 704 705
  case HA_ERR_WRONG_COMMAND:
    textno=ER_ILLEGAL_HA;
    break;
706 707 708 709
  default:
    textno=ER_CANT_LOCK;
    break;
  }
710 711 712 713 714 715

  if ( textno == ER_ILLEGAL_HA )
    my_error(textno, MYF(ME_BELL+ME_OLDWIN+ME_WAITTANG), table);
  else
    my_error(textno, MYF(ME_BELL+ME_OLDWIN+ME_WAITTANG), error);

716 717 718
  DBUG_VOID_RETURN;
}

719 720 721 722

/****************************************************************************
  Handling of global read locks

723 724 725 726
  Taking the global read lock is TWO steps (2nd step is optional; without
  it, COMMIT of existing transactions will be allowed):
  lock_global_read_lock() THEN make_global_read_lock_block_commit().

727 728
  The global locks are handled through the global variables:
  global_read_lock
729 730
    count of threads which have the global read lock (i.e. have completed at
    least the first step above)
731
  global_read_lock_blocks_commit
732 733 734 735
    count of threads which have the global read lock and block
    commits (i.e. have completed the second step above)
  waiting_for_read_lock
    count of threads which want to take a global read lock but cannot
736
  protect_against_global_read_lock
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
    count of threads which have set protection against global read lock.

  How blocking of threads by global read lock is achieved: that's
  advisory. Any piece of code which should be blocked by global read lock must
  be designed like this:
  - call to wait_if_global_read_lock(). When this returns 0, no global read
  lock is owned; if argument abort_on_refresh was 0, none can be obtained.
  - job
  - if abort_on_refresh was 0, call to start_waiting_global_read_lock() to
  allow other threads to get the global read lock. I.e. removal of the
  protection.
  (Note: it's a bit like an implementation of rwlock).

  [ I am sorry to mention some SQL syntaxes below I know I shouldn't but found
  no better descriptive way ]

  Why does FLUSH TABLES WITH READ LOCK need to block COMMIT: because it's used
  to read a non-moving SHOW MASTER STATUS, and a COMMIT writes to the binary
  log.

  Why getting the global read lock is two steps and not one. Because FLUSH
  TABLES WITH READ LOCK needs to insert one other step between the two:
  flushing tables. So the order is
  1) lock_global_read_lock() (prevents any new table write locks, i.e. stalls
  all new updates)
  2) close_cached_tables() (the FLUSH TABLES), which will wait for tables
  currently opened and being updated to close (so it's possible that there is
  a moment where all new updates of server are stalled *and* FLUSH TABLES WITH
  READ LOCK is, too).
  3) make_global_read_lock_block_commit().
  If we have merged 1) and 3) into 1), we would have had this deadlock:
  imagine thread 1 and 2, in non-autocommit mode, thread 3, and an InnoDB
  table t.
  thd1: SELECT * FROM t FOR UPDATE;
  thd2: UPDATE t SET a=1; # blocked by row-level locks of thd1
  thd3: FLUSH TABLES WITH READ LOCK; # blocked in close_cached_tables() by the
  table instance of thd2
  thd1: COMMIT; # blocked by thd3.
  thd1 blocks thd2 which blocks thd3 which blocks thd1: deadlock.
  
  Note that we need to support that one thread does
  FLUSH TABLES WITH READ LOCK; and then COMMIT;
  (that's what innobackup does, for some good reason).
  So in this exceptional case the COMMIT should not be blocked by the FLUSH
  TABLES WITH READ LOCK.

  TODO in MySQL 5.x: make_global_read_lock_block_commit() should be
  killable. Normally CPU does not spend a long time in this function (COMMITs
  are quite fast), but it would still be nice.
786

787 788 789
****************************************************************************/

volatile uint global_read_lock=0;
790
volatile uint global_read_lock_blocks_commit=0;
791 792 793
static volatile uint protect_against_global_read_lock=0;
static volatile uint waiting_for_read_lock=0;

794 795 796
#define GOT_GLOBAL_READ_LOCK               1
#define MADE_GLOBAL_READ_LOCK_BLOCK_COMMIT 2

797 798 799 800 801 802 803 804 805
bool lock_global_read_lock(THD *thd)
{
  DBUG_ENTER("lock_global_read_lock");

  if (!thd->global_read_lock)
  {
    (void) pthread_mutex_lock(&LOCK_open);
    const char *old_message=thd->enter_cond(&COND_refresh, &LOCK_open,
					    "Waiting to get readlock");
unknown's avatar
unknown committed
806 807 808 809
    DBUG_PRINT("info",
	       ("waiting_for: %d  protect_against: %d",
		waiting_for_read_lock, protect_against_global_read_lock));

810 811 812 813 814 815
    waiting_for_read_lock++;
    while (protect_against_global_read_lock && !thd->killed)
      pthread_cond_wait(&COND_refresh, &LOCK_open);
    waiting_for_read_lock--;
    if (thd->killed)
    {
unknown's avatar
unknown committed
816
      thd->exit_cond(old_message);
817 818
      DBUG_RETURN(1);
    }
819
    thd->global_read_lock= GOT_GLOBAL_READ_LOCK;
820
    global_read_lock++;
unknown's avatar
unknown committed
821
    thd->exit_cond(old_message);
822
  }
823 824 825 826 827 828 829 830
  /*
    We DON'T set global_read_lock_blocks_commit now, it will be set after
    tables are flushed (as the present function serves for FLUSH TABLES WITH
    READ LOCK only). Doing things in this order is necessary to avoid
    deadlocks (we must allow COMMIT until all tables are closed; we should not
    forbid it before, or we can have a 3-thread deadlock if 2 do SELECT FOR
    UPDATE and one does FLUSH TABLES WITH READ LOCK).
  */
831 832 833 834 835 836 837 838
  DBUG_RETURN(0);
}

void unlock_global_read_lock(THD *thd)
{
  uint tmp;
  pthread_mutex_lock(&LOCK_open);
  tmp= --global_read_lock;
839 840
  if (thd->global_read_lock == MADE_GLOBAL_READ_LOCK_BLOCK_COMMIT)
    --global_read_lock_blocks_commit;
841 842 843 844
  pthread_mutex_unlock(&LOCK_open);
  /* Send the signal outside the mutex to avoid a context switch */
  if (!tmp)
    pthread_cond_broadcast(&COND_refresh);
845
  thd->global_read_lock= 0;
846 847
}

848 849 850
#define must_wait (global_read_lock &&                             \
                   (is_not_commit ||                               \
                    global_read_lock_blocks_commit))
851

852 853
bool wait_if_global_read_lock(THD *thd, bool abort_on_refresh,
                              bool is_not_commit)
854 855
{
  const char *old_message;
unknown's avatar
unknown committed
856
  bool result= 0, need_exit_cond;
857 858
  DBUG_ENTER("wait_if_global_read_lock");

unknown's avatar
unknown committed
859
  LINT_INIT(old_message);
860
  (void) pthread_mutex_lock(&LOCK_open);
861
  if ((need_exit_cond= must_wait))
862 863 864
  {
    if (thd->global_read_lock)		// This thread had the read locks
    {
865
      if (is_not_commit)
unknown's avatar
merge  
unknown committed
866 867
        my_message(ER_CANT_UPDATE_WITH_READLOCK,
                   ER(ER_CANT_UPDATE_WITH_READLOCK), MYF(0));
unknown's avatar
unknown committed
868
      (void) pthread_mutex_unlock(&LOCK_open);
869 870 871 872 873 874
      /*
        We allow FLUSHer to COMMIT; we assume FLUSHer knows what it does.
        This allowance is needed to not break existing versions of innobackup
        which do a BEGIN; INSERT; FLUSH TABLES WITH READ LOCK; COMMIT.
      */
      DBUG_RETURN(is_not_commit);
unknown's avatar
unknown committed
875
    }
876 877
    old_message=thd->enter_cond(&COND_refresh, &LOCK_open,
				"Waiting for release of readlock");
878
    while (must_wait && ! thd->killed &&
879 880 881 882 883 884 885
	   (!abort_on_refresh || thd->version == refresh_version))
      (void) pthread_cond_wait(&COND_refresh,&LOCK_open);
    if (thd->killed)
      result=1;
  }
  if (!abort_on_refresh && !result)
    protect_against_global_read_lock++;
886 887 888 889 890
  /*
    The following is only true in case of a global read locks (which is rare)
    and if old_message is set
  */
  if (unlikely(need_exit_cond)) 
unknown's avatar
unknown committed
891 892 893
    thd->exit_cond(old_message);
  else
    pthread_mutex_unlock(&LOCK_open);
894 895 896 897 898 899 900
  DBUG_RETURN(result);
}


void start_waiting_global_read_lock(THD *thd)
{
  bool tmp;
unknown's avatar
unknown committed
901
  DBUG_ENTER("start_waiting_global_read_lock");
902 903
  if (unlikely(thd->global_read_lock))
    DBUG_VOID_RETURN;
904 905 906 907 908
  (void) pthread_mutex_lock(&LOCK_open);
  tmp= (!--protect_against_global_read_lock && waiting_for_read_lock);
  (void) pthread_mutex_unlock(&LOCK_open);
  if (tmp)
    pthread_cond_broadcast(&COND_refresh);
unknown's avatar
unknown committed
909
  DBUG_VOID_RETURN;
910
}
911 912


913
bool make_global_read_lock_block_commit(THD *thd)
914
{
915 916 917
  bool error;
  const char *old_message;
  DBUG_ENTER("make_global_read_lock_block_commit");
918 919 920 921 922
  /*
    If we didn't succeed lock_global_read_lock(), or if we already suceeded
    make_global_read_lock_block_commit(), do nothing.
  */
  if (thd->global_read_lock != GOT_GLOBAL_READ_LOCK)
923
    DBUG_RETURN(1);
924 925 926
  pthread_mutex_lock(&LOCK_open);
  /* increment this BEFORE waiting on cond (otherwise race cond) */
  global_read_lock_blocks_commit++;
927 928 929 930 931 932
  /* For testing we set up some blocking, to see if we can be killed */
  DBUG_EXECUTE_IF("make_global_read_lock_block_commit_loop",
                  protect_against_global_read_lock++;);
  old_message= thd->enter_cond(&COND_refresh, &LOCK_open,
                               "Waiting for all running commits to finish");
  while (protect_against_global_read_lock && !thd->killed)
933
    pthread_cond_wait(&COND_refresh, &LOCK_open);
934 935 936 937 938 939 940 941
  DBUG_EXECUTE_IF("make_global_read_lock_block_commit_loop",
                  protect_against_global_read_lock--;);
  if (error= thd->killed)
    global_read_lock_blocks_commit--; // undo what we did
  else
    thd->global_read_lock= MADE_GLOBAL_READ_LOCK_BLOCK_COMMIT;
  thd->exit_cond(old_message);
  DBUG_RETURN(error);
942
}
943