ma_key_recover.c 42.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* Copyright (C) 2007 Michael Widenius

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

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

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/* Redo of index */

#include "maria_def.h"
#include "ma_blockrec.h"
#include "trnman.h"
#include "ma_key_recover.h"
unknown's avatar
unknown committed
22
#include "ma_rt_index.h"
23 24 25 26 27

/****************************************************************************
  Some helper functions used both by key page loggin and block page loggin
****************************************************************************/

28
/**
29 30 31 32 33 34 35
  @brief Unpin all pinned pages

  @fn _ma_unpin_all_pages()
  @param info	   Maria handler
  @param undo_lsn  LSN for undo pages. LSN_IMPOSSIBLE if we shouldn't write
                   undo (like on duplicate key errors)

unknown's avatar
unknown committed
36 37 38
  info->pinned_pages is the list of pages to unpin. Each member of the list
  must have its 'changed' saying if the page was changed or not.

39
  @note
40 41
    We unpin pages in the reverse order as they where pinned; This is not
    necessary now, but may simplify things in the future.
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

  @return
  @retval   0   ok
  @retval   1   error (fatal disk error)
*/

void _ma_unpin_all_pages(MARIA_HA *info, LSN undo_lsn)
{
  MARIA_PINNED_PAGE *page_link= ((MARIA_PINNED_PAGE*)
                                 dynamic_array_ptr(&info->pinned_pages, 0));
  MARIA_PINNED_PAGE *pinned_page= page_link + info->pinned_pages.elements;
  DBUG_ENTER("_ma_unpin_all_pages");
  DBUG_PRINT("info", ("undo_lsn: %lu", (ulong) undo_lsn));

  if (!info->s->now_transactional)
57
    DBUG_ASSERT(undo_lsn == LSN_IMPOSSIBLE || maria_in_recovery);
58 59 60

  while (pinned_page-- != page_link)
  {
61 62 63 64 65 66
    /*
      Note this assert fails if we got a disk error or the record file
      is corrupted, which means we should have this enabled only in debug
      builds.
    */
#ifdef EXTRA_DEBUG
67 68
    DBUG_ASSERT(!pinned_page->changed ||
                undo_lsn != LSN_IMPOSSIBLE || !info->s->now_transactional);
69
#endif
70 71 72 73 74 75 76 77 78 79 80 81 82 83
    pagecache_unlock_by_link(info->s->pagecache, pinned_page->link,
                             pinned_page->unlock, PAGECACHE_UNPIN,
                             info->trn->rec_lsn, undo_lsn,
                             pinned_page->changed);
  }

  info->pinned_pages.elements= 0;
  DBUG_VOID_RETURN;
}


my_bool _ma_write_clr(MARIA_HA *info, LSN undo_lsn,
                      enum translog_record_type undo_type,
                      my_bool store_checksum, ha_checksum checksum,
84
                      LSN *res_lsn, void *extra_msg)
85
{
unknown's avatar
unknown committed
86
  uchar log_data[LSN_STORE_SIZE + FILEID_STORE_SIZE + CLR_TYPE_STORE_SIZE +
87 88
                 HA_CHECKSUM_STORE_SIZE+ KEY_NR_STORE_SIZE + PAGE_STORE_SIZE];
  uchar *log_pos;
89
  LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 1];
90 91 92 93 94 95
  struct st_msg_to_write_hook_for_clr_end msg;
  my_bool res;
  DBUG_ENTER("_ma_write_clr");

  /* undo_lsn must be first for compression to work */
  lsn_store(log_data, undo_lsn);
96 97
  clr_type_store(log_data + LSN_STORE_SIZE + FILEID_STORE_SIZE, undo_type);
  log_pos= log_data + LSN_STORE_SIZE + FILEID_STORE_SIZE + CLR_TYPE_STORE_SIZE;
98 99

  /* Extra_msg is handled in write_hook_for_clr_end() */
100 101
  msg.undone_record_type= undo_type;
  msg.previous_undo_lsn=  undo_lsn;
102 103
  msg.extra_msg= extra_msg;
  msg.checksum_delta= 0;
104 105 106

  if (store_checksum)
  {
107
    msg.checksum_delta= checksum;
108 109
    ha_checksum_store(log_pos, checksum);
    log_pos+= HA_CHECKSUM_STORE_SIZE;
110
  }
111 112 113 114 115
  else if (undo_type == LOGREC_UNDO_KEY_INSERT_WITH_ROOT ||
           undo_type == LOGREC_UNDO_KEY_DELETE_WITH_ROOT)
  {
    /* Key root changed. Store new key root */
    struct st_msg_to_write_hook_for_undo_key *undo_msg= extra_msg;
116
    pgcache_page_no_t page;
117 118 119 120 121 122
    key_nr_store(log_pos, undo_msg->keynr);
    page= (undo_msg->value == HA_OFFSET_ERROR ? IMPOSSIBLE_PAGE_NO :
           undo_msg->value / info->s->block_size);
    page_store(log_pos + KEY_NR_STORE_SIZE, page);
    log_pos+= KEY_NR_STORE_SIZE + PAGE_STORE_SIZE;
  }
123
  log_array[TRANSLOG_INTERNAL_PARTS + 0].str=    log_data;
124
  log_array[TRANSLOG_INTERNAL_PARTS + 0].length= (uint) (log_pos - log_data);
125 126

  res= translog_write_record(res_lsn, LOGREC_CLR_END,
127 128 129
                             info->trn, info,
                             (translog_size_t)
                             log_array[TRANSLOG_INTERNAL_PARTS + 0].length,
130 131 132 133 134 135
                             TRANSLOG_INTERNAL_PARTS + 1, log_array,
                             log_data + LSN_STORE_SIZE, &msg);
  DBUG_RETURN(res);
}


136 137 138 139 140 141 142 143
/**
   @brief Sets transaction's undo_lsn, first_undo_lsn if needed

   @return Operation status, always 0 (success)
*/

my_bool write_hook_for_clr_end(enum translog_record_type type
                               __attribute__ ((unused)),
144
                               TRN *trn, MARIA_HA *tbl_info,
145 146 147 148 149 150
                               LSN *lsn __attribute__ ((unused)),
                               void *hook_arg)
{
  MARIA_SHARE *share= tbl_info->s;
  struct st_msg_to_write_hook_for_clr_end *msg=
    (struct st_msg_to_write_hook_for_clr_end *)hook_arg;
unknown's avatar
unknown committed
151
  my_bool error= FALSE;
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
  DBUG_ASSERT(trn->trid != 0);
  trn->undo_lsn= msg->previous_undo_lsn;

  switch (msg->undone_record_type) {
  case LOGREC_UNDO_ROW_DELETE:
    share->state.state.records++;
    share->state.state.checksum+= msg->checksum_delta;
    break;
  case LOGREC_UNDO_ROW_INSERT:
    share->state.state.records--;
    share->state.state.checksum+= msg->checksum_delta;
    break;
  case LOGREC_UNDO_ROW_UPDATE:
    share->state.state.checksum+= msg->checksum_delta;
    break;
167 168
  case LOGREC_UNDO_KEY_INSERT_WITH_ROOT:
  case LOGREC_UNDO_KEY_DELETE_WITH_ROOT:
169 170 171 172 173 174 175
  {
    /* Update key root */
    struct st_msg_to_write_hook_for_undo_key *extra_msg=
      (struct st_msg_to_write_hook_for_undo_key *) msg->extra_msg;
    *extra_msg->root= extra_msg->value;
    break;
  }
176 177 178
  case LOGREC_UNDO_KEY_INSERT:
  case LOGREC_UNDO_KEY_DELETE:
    break;
179
  case LOGREC_UNDO_BULK_INSERT:
unknown's avatar
unknown committed
180 181 182 183 184
    error= (maria_enable_indexes(tbl_info) ||
            /* we enabled indices, need '2' below */
            _ma_state_info_write(share, 1|2|4));
    /* no need for _ma_reset_status(): REDO_DELETE_ALL is just before us */
    break;
185 186 187 188 189
  default:
    DBUG_ASSERT(0);
  }
  if (trn->undo_lsn == LSN_IMPOSSIBLE) /* has fully rolled back */
    trn->first_undo_lsn= LSN_WITH_FLAGS_TO_FLAGS(trn->first_undo_lsn);
unknown's avatar
unknown committed
190
  return error;
191 192 193 194
}


/**
unknown's avatar
unknown committed
195
  @brief write hook for undo key
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
*/

my_bool write_hook_for_undo_key(enum translog_record_type type,
                                TRN *trn, MARIA_HA *tbl_info,
                                LSN *lsn, void *hook_arg)
{
  struct st_msg_to_write_hook_for_undo_key *msg=
    (struct st_msg_to_write_hook_for_undo_key *) hook_arg;

  *msg->root= msg->value;
  _ma_fast_unlock_key_del(tbl_info);
  return write_hook_for_undo(type, trn, tbl_info, lsn, 0);
}


211
/**
212
   Updates "auto_increment" and calls the generic UNDO_KEY hook
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228

   @return Operation status, always 0 (success)
*/

my_bool write_hook_for_undo_key_insert(enum translog_record_type type,
                                       TRN *trn, MARIA_HA *tbl_info,
                                       LSN *lsn, void *hook_arg)
{
  struct st_msg_to_write_hook_for_undo_key *msg=
    (struct st_msg_to_write_hook_for_undo_key *) hook_arg;
  MARIA_SHARE *share= tbl_info->s;
  if (msg->auto_increment > 0)
  {
    /*
      Only reason to set it here is to have a mutex protect from checkpoint
      reading at the same time (would see a corrupted value).
229 230 231 232 233 234 235 236 237

      The purpose of the following code is to set auto_increment if the row
      has a with auto_increment value higher than the current one. We also
      want to be able to restore the old value, in case of rollback,
      if no one else has tried to set the value.

      The logic used is that we only restore the auto_increment value if
      tbl_info->last_auto_increment == share->last_auto_increment
      when it's time to do the rollback.
238 239 240 241
    */
    DBUG_PRINT("info",("auto_inc: %lu new auto_inc: %lu",
                       (ulong)share->state.auto_increment,
                       (ulong)msg->auto_increment));
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    if (share->state.auto_increment < msg->auto_increment)
    {
      /* Remember the original value, in case of rollback */
      tbl_info->last_auto_increment= share->last_auto_increment=
        share->state.auto_increment;
      share->state.auto_increment= msg->auto_increment;
    }
    else
    {
      /*
        If the current value would have affected the original auto_increment
        value, set it to an impossible value so that it's not restored on
        rollback
      */
      if (msg->auto_increment > share->last_auto_increment)
        share->last_auto_increment= ~(ulonglong) 0;
    }
259 260 261 262 263
  }
  return write_hook_for_undo_key(type, trn, tbl_info, lsn, hook_arg);
}


264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
/**
   @brief Updates "share->auto_increment" in case of abort and calls
   generic UNDO_KEY hook

   @return Operation status, always 0 (success)
*/

my_bool write_hook_for_undo_key_delete(enum translog_record_type type,
                                       TRN *trn, MARIA_HA *tbl_info,
                                       LSN *lsn, void *hook_arg)
{
  struct st_msg_to_write_hook_for_undo_key *msg=
    (struct st_msg_to_write_hook_for_undo_key *) hook_arg;
  MARIA_SHARE *share= tbl_info->s;
  if (msg->auto_increment > 0)                  /* If auto increment key */
  {
    /* Restore auto increment if no one has changed it in between */
    if (share->last_auto_increment == tbl_info->last_auto_increment &&
        tbl_info->last_auto_increment != ~(ulonglong) 0)
      share->state.auto_increment= tbl_info->last_auto_increment;
  }
  return write_hook_for_undo_key(type, trn, tbl_info, lsn, hook_arg);
}


289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
/*****************************************************************************
  Functions for logging of key page changes
*****************************************************************************/

/**
   @brief
   Write log entry for page that has got data added or deleted at start of page
*/

my_bool _ma_log_prefix(MARIA_HA *info, my_off_t page,
                       uchar *buff, uint changed_length,
                       int move_length)
{
  uint translog_parts;
  LSN lsn;
304
  uchar log_data[FILEID_STORE_SIZE + PAGE_STORE_SIZE + 7 + 7 + 2], *log_pos;
305
  LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 3];
306 307 308 309 310 311 312 313 314
  DBUG_ENTER("_ma_log_prefix");
  DBUG_PRINT("enter", ("page: %lu  changed_length: %u  move_length: %d",
                        (ulong) page, changed_length, move_length));

  page/= info->s->block_size;
  log_pos= log_data + FILEID_STORE_SIZE;
  page_store(log_pos, page);
  log_pos+= PAGE_STORE_SIZE;

315 316 317 318
  /* Store keypage_flag */
  *log_pos++= KEY_OP_SET_PAGEFLAG;
  *log_pos++= buff[KEYPAGE_TRANSFLAG_OFFSET];

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
  if (move_length < 0)
  {
    /* Delete prefix */
    log_pos[0]= KEY_OP_DEL_PREFIX;
    int2store(log_pos+1, -move_length);
    log_pos+= 3;
    if (changed_length)
    {
      /*
        We don't need a KEY_OP_OFFSET as KEY_OP_DEL_PREFIX has an implicit
        offset
      */
      log_pos[0]= KEY_OP_CHANGE;
      int2store(log_pos+1, changed_length);
      log_pos+= 3;
    }
  }
  else
  {
    /* Add prefix */
    DBUG_ASSERT(changed_length >0 && (int) changed_length >= move_length);
    log_pos[0]= KEY_OP_ADD_PREFIX;
    int2store(log_pos+1, move_length);
    int2store(log_pos+3, changed_length);
    log_pos+= 5;
  }
345 346

  translog_parts= 1;
347
  log_array[TRANSLOG_INTERNAL_PARTS + 0].str=    log_data;
348 349 350 351
  log_array[TRANSLOG_INTERNAL_PARTS + 0].length= (uint) (log_pos -
                                                         log_data);
  if (changed_length)
  {
352
    log_array[TRANSLOG_INTERNAL_PARTS + 1].str=    (buff +
353 354 355 356 357
                                                    info->s->keypage_header);
    log_array[TRANSLOG_INTERNAL_PARTS + 1].length= changed_length;
    translog_parts= 2;
  }

358 359
#ifdef EXTRA_DEBUG_KEY_CHANGES
  {
360
    int page_length= _ma_get_page_used(info->s, buff);
361 362 363 364 365 366
    ha_checksum crc;
    crc= my_checksum(0, buff + LSN_STORE_SIZE, page_length - LSN_STORE_SIZE);
    log_pos[0]= KEY_OP_CHECK;
    int2store(log_pos+1, page_length);
    int4store(log_pos+3, crc);

367
    log_array[TRANSLOG_INTERNAL_PARTS + translog_parts].str= log_pos;
368 369 370 371 372 373
    log_array[TRANSLOG_INTERNAL_PARTS + translog_parts].length= 7;
    changed_length+= 7;
    translog_parts++;
  }
#endif

374 375
  DBUG_RETURN(translog_write_record(&lsn, LOGREC_REDO_INDEX,
                                    info->trn, info,
376
                                    (translog_size_t)
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
                                    log_array[TRANSLOG_INTERNAL_PARTS +
                                              0].length + changed_length,
                                    TRANSLOG_INTERNAL_PARTS + translog_parts,
                                    log_array, log_data, NULL));
}


/**
   @brief
   Write log entry for page that has got data added or deleted at end of page
*/

my_bool _ma_log_suffix(MARIA_HA *info, my_off_t page,
                       uchar *buff, uint org_length, uint new_length)
{
  LSN lsn;
393
  LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 3];
394
  uchar log_data[FILEID_STORE_SIZE + PAGE_STORE_SIZE + 10 + 7 + 2], *log_pos;
395 396 397 398 399 400 401 402 403 404 405 406
  int diff;
  uint translog_parts, extra_length;
  DBUG_ENTER("_ma_log_suffix");
  DBUG_PRINT("enter", ("page: %lu  org_length: %u  new_length: %u",
                       (ulong) page, org_length, new_length));

  page/= info->s->block_size;

  log_pos= log_data + FILEID_STORE_SIZE;
  page_store(log_pos, page);
  log_pos+= PAGE_STORE_SIZE;

407 408 409 410
  /* Store keypage_flag */
  *log_pos++= KEY_OP_SET_PAGEFLAG;
  *log_pos++= buff[KEYPAGE_TRANSFLAG_OFFSET];

411 412 413 414 415 416 417 418 419 420 421 422 423
  if ((diff= (int) (new_length - org_length)) < 0)
  {
    log_pos[0]= KEY_OP_DEL_SUFFIX;
    int2store(log_pos+1, -diff);
    log_pos+= 3;
    translog_parts= 1;
    extra_length= 0;
  }
  else
  {
    log_pos[0]= KEY_OP_ADD_SUFFIX;
    int2store(log_pos+1, diff);
    log_pos+= 3;
424
    log_array[TRANSLOG_INTERNAL_PARTS + 1].str=    buff + org_length;
425 426 427 428
    log_array[TRANSLOG_INTERNAL_PARTS + 1].length= (uint) diff;
    translog_parts= 2;
    extra_length= (uint) diff;
  }
429

430
  log_array[TRANSLOG_INTERNAL_PARTS + 0].str=    log_data;
431 432 433
  log_array[TRANSLOG_INTERNAL_PARTS + 0].length= (uint) (log_pos -
                                                         log_data);

434 435 436 437 438 439 440 441
#ifdef EXTRA_DEBUG_KEY_CHANGES
  {
    ha_checksum crc;
    crc= my_checksum(0, buff + LSN_STORE_SIZE, new_length - LSN_STORE_SIZE);
    log_pos[0]= KEY_OP_CHECK;
    int2store(log_pos+1, new_length);
    int4store(log_pos+3, crc);

442
    log_array[TRANSLOG_INTERNAL_PARTS + translog_parts].str= log_pos;
443 444 445 446 447 448
    log_array[TRANSLOG_INTERNAL_PARTS + translog_parts].length= 7;
    extra_length+= 7;
    translog_parts++;
  }
#endif

449 450
  DBUG_RETURN(translog_write_record(&lsn, LOGREC_REDO_INDEX,
                                    info->trn, info,
451
                                    (translog_size_t)
452 453 454 455 456 457 458 459 460 461
                                    log_array[TRANSLOG_INTERNAL_PARTS +
                                              0].length + extra_length,
                                    TRANSLOG_INTERNAL_PARTS + translog_parts,
                                    log_array, log_data, NULL));
}


/**
   @brief Log that a key was added to the page

462 463 464
   @param buff         Page buffer
   @param buff_length  Original length of buff (before key was added)

465 466 467 468 469 470 471 472 473 474 475 476 477
   @note
     If handle_overflow is set, then we have to protect against
     logging changes that is outside of the page.
     This may happen during underflow() handling where the buffer
     in memory temporary contains more data than block_size
*/

my_bool _ma_log_add(MARIA_HA *info, my_off_t page, uchar *buff,
                    uint buff_length, uchar *key_pos,
                    uint changed_length, int move_length,
                    my_bool handle_overflow __attribute__ ((unused)))
{
  LSN lsn;
478
  uchar log_data[FILEID_STORE_SIZE + PAGE_STORE_SIZE + 3 + 3 + 3 + 3 + 7 + 2];
479
  uchar *log_pos;
480
  LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 3];
481 482
  uint offset= (uint) (key_pos - buff);
  uint page_length= info->s->block_size - KEYPAGE_CHECKSUM_SIZE;
483
  uint translog_parts;
484
  DBUG_ENTER("_ma_log_add");
485
  DBUG_PRINT("enter", ("page: %lu  org_page_length: %u  changed_length: %u  "
486 487 488 489 490 491 492 493 494 495 496 497 498 499
                       "move_length: %d",
                       (ulong) page, buff_length, changed_length,
                       move_length));
  DBUG_ASSERT(info->s->now_transactional);

  /*
    Write REDO entry that contains the logical operations we need
    to do the page
  */
  log_pos= log_data + FILEID_STORE_SIZE;
  page/= info->s->block_size;
  page_store(log_pos, page);
  log_pos+= PAGE_STORE_SIZE;

500 501 502 503
  /* Store keypage_flag */
  *log_pos++= KEY_OP_SET_PAGEFLAG;
  *log_pos++= buff[KEYPAGE_TRANSFLAG_OFFSET];

504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
  if (buff_length + move_length > page_length)
  {
    /*
      Overflow. Cut either key or data from page end so that key fits
      The code that splits the too big page will ignore logging any
      data over page_length
    */
    DBUG_ASSERT(handle_overflow);
    if (offset + changed_length > page_length)
    {
      changed_length= page_length - offset;
      move_length= 0;
    }
    else
    {
      uint diff= buff_length + move_length - page_length;
      log_pos[0]= KEY_OP_DEL_SUFFIX;
      int2store(log_pos+1, diff);
      log_pos+= 3;
      buff_length= page_length - move_length;
    }
  }

  if (offset == buff_length)
    log_pos[0]= KEY_OP_ADD_SUFFIX;
  else
  {
    log_pos[0]= KEY_OP_OFFSET;
    int2store(log_pos+1, offset);
    log_pos+= 3;
    if (move_length)
    {
      log_pos[0]= KEY_OP_SHIFT;
      int2store(log_pos+1, move_length);
      log_pos+= 3;
    }
    log_pos[0]= KEY_OP_CHANGE;
  }
  int2store(log_pos+1, changed_length);
  log_pos+= 3;
544
  translog_parts= 2;
545

546
  log_array[TRANSLOG_INTERNAL_PARTS + 0].str=    log_data;
547 548
  log_array[TRANSLOG_INTERNAL_PARTS + 0].length= (uint) (log_pos -
                                                         log_data);
549
  log_array[TRANSLOG_INTERNAL_PARTS + 1].str=    key_pos;
550 551
  log_array[TRANSLOG_INTERNAL_PARTS + 1].length= changed_length;

552 553
#ifdef EXTRA_DEBUG_KEY_CHANGES
  {
554
    MARIA_SHARE *share= info->s;
555
    ha_checksum crc;
556
    uint save_page_length= _ma_get_page_used(share, buff);
557
    uint new_length= buff_length + move_length;
558
    _ma_store_page_used(share, buff, new_length);
559 560 561 562 563
    crc= my_checksum(0, buff + LSN_STORE_SIZE, new_length - LSN_STORE_SIZE);
    log_pos[0]= KEY_OP_CHECK;
    int2store(log_pos+1, new_length);
    int4store(log_pos+3, crc);

564
    log_array[TRANSLOG_INTERNAL_PARTS + translog_parts].str= log_pos;
565 566 567
    log_array[TRANSLOG_INTERNAL_PARTS + translog_parts].length= 7;
    changed_length+= 7;
    translog_parts++;
568
    _ma_store_page_used(share, buff, save_page_length);
569 570 571
  }
#endif

572 573
  if (translog_write_record(&lsn, LOGREC_REDO_INDEX,
                            info->trn, info,
574 575 576
                            (translog_size_t)
                            log_array[TRANSLOG_INTERNAL_PARTS + 0].length +
                            changed_length,
577 578
                            TRANSLOG_INTERNAL_PARTS + translog_parts,
                            log_array, log_data, NULL))
579 580 581 582 583
    DBUG_RETURN(-1);
  DBUG_RETURN(0);
}


584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
/****************************************************************************
  Redo of key pages
****************************************************************************/

/**
   @brief Apply LOGREC_REDO_INDEX_NEW_PAGE

   @param  info            Maria handler
   @param  header          Header (without FILEID)

   @return Operation status
     @retval 0      OK
     @retval 1      Error
*/

uint _ma_apply_redo_index_new_page(MARIA_HA *info, LSN lsn,
                                   const uchar *header, uint length)
{
602 603
  pgcache_page_no_t root_page= page_korr(header);
  pgcache_page_no_t free_page= page_korr(header + PAGE_STORE_SIZE);
604 605 606 607 608 609 610 611 612 613
  uint      key_nr=    key_nr_korr(header + PAGE_STORE_SIZE * 2);
  my_bool   page_type_flag= header[PAGE_STORE_SIZE * 2 + KEY_NR_STORE_SIZE];
  enum pagecache_page_lock unlock_method;
  enum pagecache_page_pin unpin_method;
  MARIA_PINNED_PAGE page_link;
  my_off_t file_size;
  uchar *buff;
  uint result;
  MARIA_SHARE *share= info->s;
  DBUG_ENTER("_ma_apply_redo_index_new_page");
614 615
  DBUG_PRINT("enter", ("root_page: %lu  free_page: %lu",
                       (ulong) root_page, (ulong) free_page));
616 617 618 619

  /* Set header to point at key data */

  share->state.changed|= (STATE_CHANGED | STATE_NOT_OPTIMIZED_KEYS |
unknown's avatar
unknown committed
620 621
                          STATE_NOT_SORTED_PAGES | STATE_NOT_ZEROFILLED |
                          STATE_NOT_MOVABLE);
622 623 624 625

  header+= PAGE_STORE_SIZE * 2 + KEY_NR_STORE_SIZE + 1;
  length-= PAGE_STORE_SIZE * 2 + KEY_NR_STORE_SIZE + 1;

unknown's avatar
unknown committed
626 627
  file_size= (my_off_t) (root_page + 1) * share->block_size;
  if (cmp_translog_addr(lsn, share->state.is_of_horizon) >= 0)
628
  {
unknown's avatar
unknown committed
629 630 631 632 633 634 635 636 637 638
    /* free_page is 0 if we shouldn't set key_del */
    if (free_page)
    {
      if (free_page != IMPOSSIBLE_PAGE_NO)
        share->state.key_del= (my_off_t) free_page * share->block_size;
      else
        share->state.key_del= HA_OFFSET_ERROR;
    }
    if (page_type_flag)     /* root page */
      share->state.key_root[key_nr]= file_size - share->block_size;
639 640
  }

641
  if (file_size > share->state.state.key_file_length)
642
  {
643
    share->state.state.key_file_length= file_size;
644 645
    buff= info->keyread_buff;
    info->keyread_buff_used= 1;
646 647
    unlock_method= PAGECACHE_LOCK_WRITE;
    unpin_method=  PAGECACHE_PIN;
648 649 650 651 652 653 654 655
  }
  else
  {
    if (!(buff= pagecache_read(share->pagecache, &share->kfile,
                               root_page, 0, 0,
                               PAGECACHE_PLAIN_PAGE, PAGECACHE_LOCK_WRITE,
                               &page_link.link)))
    {
656 657 658 659 660 661 662
      if (my_errno != HA_ERR_FILE_TOO_SHORT &&
          my_errno != HA_ERR_WRONG_CRC)
      {
        result= 1;
        goto err;
      }
      buff= pagecache_block_link_to_buffer(page_link.link);
663
    }
664
    else if (lsn_korr(buff) >= lsn)
665 666
    {
      /* Already applied */
667
      DBUG_PRINT("info", ("Page is up to date, skipping redo"));
668 669 670
      result= 0;
      goto err;
    }
671 672
    unlock_method= PAGECACHE_LOCK_LEFT_WRITELOCKED;
    unpin_method=  PAGECACHE_PIN_LEFT_PINNED;
673 674 675
  }

  /* Write modified page */
676
  bzero(buff, LSN_STORE_SIZE);
677 678 679 680 681
  memcpy(buff + LSN_STORE_SIZE, header, length);
  bzero(buff + LSN_STORE_SIZE + length,
        share->block_size - LSN_STORE_SIZE - KEYPAGE_CHECKSUM_SIZE - length);
  bfill(buff + share->block_size - KEYPAGE_CHECKSUM_SIZE,
        KEYPAGE_CHECKSUM_SIZE, (uchar) 255);
682 683 684 685

  result= 0;
  if (unlock_method == PAGECACHE_LOCK_WRITE &&
      pagecache_write(share->pagecache,
686 687 688
                      &share->kfile, root_page, 0,
                      buff, PAGECACHE_PLAIN_PAGE,
                      unlock_method, unpin_method,
689 690 691 692 693 694 695 696 697
                      PAGECACHE_WRITE_DELAY, &page_link.link,
                      LSN_IMPOSSIBLE))
    result= 1;

  /* Mark page to be unlocked and written at _ma_unpin_all_pages() */
  page_link.unlock= PAGECACHE_LOCK_WRITE_UNLOCK;
  page_link.changed= 1;
  push_dynamic(&info->pinned_pages, (void*) &page_link);
  DBUG_RETURN(result);
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722

err:
  pagecache_unlock_by_link(share->pagecache, page_link.link,
                           PAGECACHE_LOCK_WRITE_UNLOCK,
                           PAGECACHE_UNPIN, LSN_IMPOSSIBLE,
                           LSN_IMPOSSIBLE, 0);
  DBUG_RETURN(result);
}


/**
   @brief Apply LOGREC_REDO_INDEX_FREE_PAGE

   @param  info            Maria handler
   @param  header          Header (without FILEID)

   @return Operation status
     @retval 0      OK
     @retval 1      Error
*/

uint _ma_apply_redo_index_free_page(MARIA_HA *info,
                                    LSN lsn,
                                    const uchar *header)
{
723 724
  pgcache_page_no_t page= page_korr(header);
  pgcache_page_no_t free_page= page_korr(header + PAGE_STORE_SIZE);
725 726 727 728 729 730
  my_off_t old_link;
  MARIA_PINNED_PAGE page_link;
  MARIA_SHARE *share= info->s;
  uchar *buff;
  int result;
  DBUG_ENTER("_ma_apply_redo_index_free_page");
731 732
  DBUG_PRINT("enter", ("page: %lu  free_page: %lu",
                       (ulong) page, (ulong) free_page));
733 734

  share->state.changed|= (STATE_CHANGED | STATE_NOT_OPTIMIZED_KEYS |
unknown's avatar
unknown committed
735 736
                          STATE_NOT_SORTED_PAGES | STATE_NOT_ZEROFILLED |
                          STATE_NOT_MOVABLE);
737

unknown's avatar
unknown committed
738 739 740
  if (cmp_translog_addr(lsn, share->state.is_of_horizon) >= 0)
    share->state.key_del= (my_off_t) page * share->block_size;

741 742 743
  old_link=  ((free_page != IMPOSSIBLE_PAGE_NO) ?
              (my_off_t) free_page * share->block_size :
              HA_OFFSET_ERROR);
744
  if (!(buff= pagecache_read(share->pagecache, &share->kfile,
745 746 747 748 749 750 751 752 753 754 755 756 757
                             page, 0, 0,
                             PAGECACHE_PLAIN_PAGE, PAGECACHE_LOCK_WRITE,
                             &page_link.link)))
  {
    result= (uint) my_errno;
    goto err;
  }
  if (lsn_korr(buff) >= lsn)
  {
    /* Already applied */
    result= 0;
    goto err;
  }
758
  /* Free page */
759
  bzero(buff + LSN_STORE_SIZE, share->keypage_header - LSN_STORE_SIZE);
760 761
  _ma_store_keynr(share, buff, (uchar) MARIA_DELETE_KEY_NR);
  _ma_store_page_used(share, buff, share->keypage_header + 8);
762 763
  mi_sizestore(buff + share->keypage_header, old_link);

764 765 766 767 768 769 770 771 772 773 774 775
#ifdef IDENTICAL_PAGES_AFTER_RECOVERY
  {
    bzero(buff + share->keypage_header + 8,
          share->block_size - share->keypage_header - 8 -
          KEYPAGE_CHECKSUM_SIZE);
  }
#endif

  /* Mark page to be unlocked and written at _ma_unpin_all_pages() */
  page_link.unlock= PAGECACHE_LOCK_WRITE_UNLOCK;
  page_link.changed= 1;
  push_dynamic(&info->pinned_pages, (void*) &page_link);
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
  DBUG_RETURN(0);

err:
  pagecache_unlock_by_link(share->pagecache, page_link.link,
                           PAGECACHE_LOCK_WRITE_UNLOCK,
                           PAGECACHE_UNPIN, LSN_IMPOSSIBLE,
                           LSN_IMPOSSIBLE, 0);
  DBUG_RETURN(result);
}


/**
   @brief Apply LOGREC_REDO_INDEX

   @fn ma_apply_redo_index()
   @param  info            Maria handler
   @param  header          Header (without FILEID)

   @notes
     Data for this part is a set of logical instructions of how to
     construct the key page.

   Information of the layout of the components for REDO_INDEX:

   Name              Parameters (in byte) Information
   KEY_OP_OFFSET     2                    Set position for next operations
   KEY_OP_SHIFT      2 (signed int)       How much to shift down or up
   KEY_OP_CHANGE     2 length,  data      Data to replace at 'pos'
   KEY_OP_ADD_PREFIX 2 move-length        How much data should be moved up
                     2 change-length      Data to be replaced at page start
   KEY_OP_DEL_PREFIX 2 length             Bytes to be deleted at page start
   KEY_OP_ADD_SUFFIX 2 length, data       Add data to end of page
   KEY_OP_DEL_SUFFIX 2 length             Reduce page length with this
809
				          Sets position to start of page
810
   KEY_OP_CHECK      6 page_length[2},CRC Used only when debugging
811 812
   KEY_OP_COMPACT_PAGE  6 transid
   KEY_OP_SET_PAGEFLAG  1 flag for page
813

814 815 816 817 818
   @return Operation status
     @retval 0      OK
     @retval 1      Error
*/

819 820
long my_counter= 0;

821 822 823 824
uint _ma_apply_redo_index(MARIA_HA *info,
                          LSN lsn, const uchar *header, uint head_length)
{
  MARIA_SHARE *share= info->s;
825
  pgcache_page_no_t page= page_korr(header);
826 827 828 829 830 831 832 833
  MARIA_PINNED_PAGE page_link;
  uchar *buff;
  const uchar *header_end= header + head_length;
  uint page_offset= 0;
  uint nod_flag, page_length, keypage_header;
  int result;
  uint org_page_length;
  DBUG_ENTER("_ma_apply_redo_index");
834
  DBUG_PRINT("enter", ("page: %lu", (ulong) page));
835 836 837 838

  /* Set header to point at key data */
  header+= PAGE_STORE_SIZE;

839
  if (!(buff= pagecache_read(share->pagecache, &share->kfile,
840 841 842 843 844 845 846 847 848 849
                             page, 0, 0,
                             PAGECACHE_PLAIN_PAGE, PAGECACHE_LOCK_WRITE,
                             &page_link.link)))
  {
    result= 1;
    goto err;
  }
  if (lsn_korr(buff) >= lsn)
  {
    /* Already applied */
850
    DBUG_PRINT("info", ("Page is up to date, skipping redo"));
851 852 853 854
    result= 0;
    goto err;
  }

855
  _ma_get_used_and_nod(share, buff, page_length, nod_flag);
856 857
  keypage_header= share->keypage_header;
  org_page_length= page_length;
858
  DBUG_PRINT("redo", ("page_length: %u", page_length));
859 860 861 862 863

  /* Apply modifications to page */
  do
  {
    switch ((enum en_key_op) (*header++)) {
864
    case KEY_OP_OFFSET:                         /* 1 */
865 866
      page_offset= uint2korr(header);
      header+= 2;
867
      DBUG_PRINT("redo", ("key_op_offset: %u", page_offset));
868 869
      DBUG_ASSERT(page_offset >= keypage_header && page_offset <= page_length);
      break;
870
    case KEY_OP_SHIFT:                          /* 2 */
871 872 873
    {
      int length= sint2korr(header);
      header+= 2;
874
      DBUG_PRINT("redo", ("key_op_shift: %d", length));
875
      DBUG_ASSERT(page_offset != 0 && page_offset <= page_length &&
876 877 878 879 880 881 882 883 884 885 886
                  page_length + length < share->block_size);

      if (length < 0)
        bmove(buff + page_offset, buff + page_offset - length,
              page_length - page_offset + length);
      else
        bmove_upp(buff + page_length + length, buff + page_length,
                  page_length - page_offset);
      page_length+= length;
      break;
    }
887
    case KEY_OP_CHANGE:                         /* 3 */
888 889
    {
      uint length= uint2korr(header);
890
      DBUG_PRINT("redo", ("key_op_change: %u", length));
891 892 893 894 895 896
      DBUG_ASSERT(page_offset != 0 && page_offset + length <= page_length);

      memcpy(buff + page_offset, header + 2 , length);
      header+= 2 + length;
      break;
    }
897
    case KEY_OP_ADD_PREFIX:                     /* 4 */
898 899
    {
      uint insert_length= uint2korr(header);
900
      uint changed_length= uint2korr(header+2);
901 902 903
      DBUG_PRINT("redo", ("key_op_add_prefix: %u  %u",
                          insert_length, changed_length));

904 905
      DBUG_ASSERT(insert_length <= changed_length &&
                  page_length + changed_length <= share->block_size);
906 907 908

      bmove_upp(buff + page_length + insert_length, buff + page_length,
                page_length - keypage_header);
909 910
      memcpy(buff + keypage_header, header + 4 , changed_length);
      header+= 4 + changed_length;
911 912 913
      page_length+= insert_length;
      break;
    }
914
    case KEY_OP_DEL_PREFIX:                     /* 5 */
915 916 917
    {
      uint length= uint2korr(header);
      header+= 2;
918
      DBUG_PRINT("redo", ("key_op_del_prefix: %u", length));
919 920 921 922 923
      DBUG_ASSERT(length <= page_length - keypage_header);

      bmove(buff + keypage_header, buff + keypage_header +
            length, page_length - keypage_header - length);
      page_length-= length;
924 925

      page_offset= keypage_header;              /* Prepare for change */
926 927
      break;
    }
928
    case KEY_OP_ADD_SUFFIX:                     /* 6 */
929 930
    {
      uint insert_length= uint2korr(header);
931
      DBUG_PRINT("redo", ("key_op_add_prefix: %u", insert_length));
932 933 934 935 936 937 938
      DBUG_ASSERT(page_length + insert_length <= share->block_size);
      memcpy(buff + page_length, header+2, insert_length);

      page_length+= insert_length;
      header+= 2 + insert_length;
      break;
    }
939
    case KEY_OP_DEL_SUFFIX:                     /* 7 */
940 941 942
    {
      uint del_length= uint2korr(header);
      header+= 2;
943
      DBUG_PRINT("redo", ("key_op_del_suffix: %u", del_length));
944 945 946 947
      DBUG_ASSERT(page_length - del_length >= keypage_header);
      page_length-= del_length;
      break;
    }
948 949
    case KEY_OP_CHECK:                          /* 8 */
    {
unknown's avatar
unknown committed
950
#ifdef EXTRA_DEBUG_KEY_CHANGES
951 952 953 954
      uint check_page_length;
      ha_checksum crc;
      check_page_length= uint2korr(header);
      crc=               uint4korr(header+2);
955
      _ma_store_page_used(share, buff, page_length);
956
      DBUG_ASSERT(check_page_length == page_length);
unknown's avatar
unknown committed
957 958 959
      if (crc != (uint32) my_checksum(0, buff + LSN_STORE_SIZE,
                                      page_length - LSN_STORE_SIZE))
      {
960
        DBUG_PRINT("error", ("page_length %u",page_length));
unknown's avatar
unknown committed
961 962 963
        DBUG_DUMP("KEY_OP_CHECK bad page", buff, share->block_size);
        DBUG_ASSERT("crc" == "failure in REDO_INDEX");
      }
964
#endif
965
      DBUG_PRINT("redo", ("key_op_check"));
966 967 968
      header+= 6;
      break;
    }
unknown's avatar
unknown committed
969 970 971 972 973 974 975 976 977 978 979 980 981
    case KEY_OP_MULTI_COPY:                     /* 9 */
    {
      /*
        List of fixed-len memcpy() operations with their source located inside
        the page. The log record's piece looks like:
        first the length 'full_length' to be used by memcpy()
        then the number of bytes used by the list of (to,from) pairs
        then the (to,from) pairs, so we do:
        for (t,f) in [list of (to,from) pairs]:
            memcpy(t, f, full_length).
      */
      uint full_length, log_memcpy_length;
      const uchar *log_memcpy_end;
982 983

      DBUG_PRINT("redo", ("key_op_multi_copy"));
unknown's avatar
unknown committed
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
      full_length= uint2korr(header);
      header+= 2;
      log_memcpy_length= uint2korr(header);
      header+= 2;
      log_memcpy_end= header + log_memcpy_length;
      DBUG_ASSERT(full_length < share->block_size);
      while (header < log_memcpy_end)
      {
        uint to, from;
        to= uint2korr(header);
        header+= 2;
        from= uint2korr(header);
        header+= 2;
        /* "from" is a place in the existing page */
        DBUG_ASSERT(max(from, to) < share->block_size);
        memcpy(buff + to, buff + from, full_length);
      }
      break;
    }
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
    case KEY_OP_SET_PAGEFLAG:
      DBUG_PRINT("redo", ("key_op_set_pageflag"));
      buff[KEYPAGE_TRANSFLAG_OFFSET]= *header++;
      break;
    case KEY_OP_COMPACT_PAGE:
    {
      TrID transid= transid_korr(header);
      uint keynr= _ma_get_keynr(share, buff);

      DBUG_PRINT("redo", ("key_op_compact_page"));
      header+= TRANSID_SIZE;
      if (_ma_compact_keypage(info, share->keyinfo + keynr, (my_off_t) 0,
                              buff, transid))
      {
        result= 1;
        goto err;
      }
    }
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    case KEY_OP_NONE:
    default:
      DBUG_ASSERT(0);
      result= 1;
      goto err;
    }
  } while (header < header_end);
  DBUG_ASSERT(header == header_end);

  /* Write modified page */
1031
  _ma_store_page_used(share, buff, page_length);
1032 1033 1034 1035 1036 1037 1038 1039

  /*
    Clean old stuff up. Gives us better compression of we archive things
    and makes things easer to debug
  */
  if (page_length < org_page_length)
    bzero(buff + page_length, org_page_length-page_length);

1040 1041 1042 1043
  /* Mark page to be unlocked and written at _ma_unpin_all_pages() */
  page_link.unlock= PAGECACHE_LOCK_WRITE_UNLOCK;
  page_link.changed= 1;
  push_dynamic(&info->pinned_pages, (void*) &page_link);
1044 1045 1046 1047 1048 1049 1050
  DBUG_RETURN(0);

err:
  pagecache_unlock_by_link(share->pagecache, page_link.link,
                           PAGECACHE_LOCK_WRITE_UNLOCK,
                           PAGECACHE_UNPIN, LSN_IMPOSSIBLE,
                           LSN_IMPOSSIBLE, 0);
1051 1052
  if (result)
    _ma_mark_file_crashed(share);
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
  DBUG_RETURN(result);
}


/****************************************************************************
  Undo of key block changes
****************************************************************************/

/**
   @brief Undo of insert of key (ie, delete the inserted key)
*/

my_bool _ma_apply_undo_key_insert(MARIA_HA *info, LSN undo_lsn,
                                  const uchar *header, uint length)
{
  LSN lsn;
  my_bool res;
  uint keynr;
1071
  uchar key_buff[MARIA_MAX_KEY_BUFF];
1072
  MARIA_SHARE *share= info->s;
1073
  MARIA_KEY key;
1074 1075
  my_off_t new_root;
  struct st_msg_to_write_hook_for_undo_key msg;
1076 1077 1078
  DBUG_ENTER("_ma_apply_undo_key_insert");

  share->state.changed|= (STATE_CHANGED | STATE_NOT_OPTIMIZED_KEYS |
unknown's avatar
unknown committed
1079 1080
                          STATE_NOT_SORTED_PAGES | STATE_NOT_ZEROFILLED |
                          STATE_NOT_MOVABLE);
1081 1082 1083 1084
  keynr= key_nr_korr(header);
  length-= KEY_NR_STORE_SIZE;

  /* We have to copy key as _ma_ck_real_delete() may change it */
1085 1086
  memcpy(key_buff, header + KEY_NR_STORE_SIZE, length);
  DBUG_DUMP("key_buff", key_buff, length);
1087 1088

  new_root= share->state.key_root[keynr];
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
  /*
    Change the key to an internal structure.
    It's safe to have SEARCH_USER_KEY_HAS_TRANSID even if there isn't
    a transaction id, as ha_key_cmp() will stop comparison when key length
    is reached.
    For index with transid flag, the ref_length of the key is not correct.
    This should however be safe as long as this key is only used for
    comparsion against other keys (not for packing or for read-next etc as
    in this case we use data_length + ref_length, which is correct.
  */
  key.keyinfo=     share->keyinfo + keynr;
  key.data=        key_buff;
  key.data_length= length - share->rec_reflength;
  key.ref_length=  share->rec_reflength;
  key.flag=        SEARCH_USER_KEY_HAS_TRANSID;

  res= ((share->keyinfo[keynr].key_alg == HA_KEY_ALG_RTREE) ?
        maria_rtree_real_delete(info, &key, &new_root) :
        _ma_ck_real_delete(info, &key, &new_root));
1108 1109
  if (res)
    _ma_mark_file_crashed(share);
1110 1111
  msg.root= &share->state.key_root[keynr];
  msg.value= new_root;
1112
  msg.keynr= keynr;
1113

1114 1115 1116
  if (_ma_write_clr(info, undo_lsn, *msg.root == msg.value ?
                    LOGREC_UNDO_KEY_INSERT : LOGREC_UNDO_KEY_INSERT_WITH_ROOT,
                    0, 0, &lsn, (void*) &msg))
1117 1118
    res= 1;

1119
  _ma_fast_unlock_key_del(info);
1120 1121 1122 1123 1124 1125
  _ma_unpin_all_pages_and_finalize_row(info, lsn);
  DBUG_RETURN(res);
}


/**
1126
   @brief Undo of delete of key (ie, insert the deleted key)
unknown's avatar
unknown committed
1127 1128

   @param  with_root       If the UNDO is UNDO_KEY_DELETE_WITH_ROOT
1129 1130 1131
*/

my_bool _ma_apply_undo_key_delete(MARIA_HA *info, LSN undo_lsn,
unknown's avatar
unknown committed
1132 1133
                                  const uchar *header, uint length,
                                  my_bool with_root)
1134 1135 1136
{
  LSN lsn;
  my_bool res;
unknown's avatar
unknown committed
1137
  uint keynr, skip_bytes;
1138
  uchar key_buff[MARIA_MAX_KEY_BUFF];
1139
  MARIA_SHARE *share= info->s;
1140 1141
  my_off_t new_root;
  struct st_msg_to_write_hook_for_undo_key msg;
1142
  MARIA_KEY key;
1143 1144 1145
  DBUG_ENTER("_ma_apply_undo_key_delete");

  share->state.changed|= (STATE_CHANGED | STATE_NOT_OPTIMIZED_KEYS |
unknown's avatar
unknown committed
1146 1147
                          STATE_NOT_SORTED_PAGES | STATE_NOT_ZEROFILLED |
                          STATE_NOT_MOVABLE);
1148
  keynr= key_nr_korr(header);
unknown's avatar
unknown committed
1149 1150 1151
  skip_bytes= KEY_NR_STORE_SIZE + (with_root ? PAGE_STORE_SIZE : 0);
  header+= skip_bytes;
  length-= skip_bytes;
1152

1153
  /* We have to copy key as _ma_ck_real_write_btree() may change it */
1154 1155 1156 1157 1158 1159 1160 1161
  memcpy(key_buff, header, length);
  DBUG_DUMP("key", key_buff, length);

  key.keyinfo=     share->keyinfo + keynr;
  key.data=        key_buff;
  key.data_length= length - share->rec_reflength;
  key.ref_length=  share->rec_reflength;
  key.flag=        SEARCH_USER_KEY_HAS_TRANSID;
1162

1163
  new_root= share->state.key_root[keynr];
unknown's avatar
unknown committed
1164
  res= (share->keyinfo[keynr].key_alg == HA_KEY_ALG_RTREE) ?
1165 1166 1167 1168
    maria_rtree_insert_level(info, &key, -1, &new_root) :
    _ma_ck_real_write_btree(info, &key, &new_root,
                            share->keyinfo[keynr].write_comp_flag |
                            key.flag);
1169 1170
  if (res)
    _ma_mark_file_crashed(share);
1171

1172 1173
  msg.root= &share->state.key_root[keynr];
  msg.value= new_root;
1174 1175 1176 1177 1178
  msg.keynr= keynr;
  if (_ma_write_clr(info, undo_lsn,
                    *msg.root == msg.value ?
                    LOGREC_UNDO_KEY_DELETE : LOGREC_UNDO_KEY_DELETE_WITH_ROOT,
                    0, 0, &lsn,
1179
                    (void*) &msg))
1180 1181
    res= 1;

1182
  _ma_fast_unlock_key_del(info);
1183 1184 1185 1186 1187 1188 1189 1190 1191
  _ma_unpin_all_pages_and_finalize_row(info, lsn);
  DBUG_RETURN(res);
}


/****************************************************************************
  Handle some local variables
****************************************************************************/

1192
/**
1193 1194 1195 1196 1197 1198
  @brief lock key_del for other threads usage

  @fn     _ma_lock_key_del()
  @param  info            Maria handler
  @param  insert_at_end   Set to 1 if we are doing an insert

unknown's avatar
unknown committed
1199
  @note
1200 1201
    To allow higher concurrency in the common case where we do inserts
    and we don't have any linked blocks we do the following:
1202
    - Mark in info->key_del_used that we are not using key_del
1203 1204
    - Return at once (without marking key_del as used)

1205
    This is safe as we in this case don't write key_del_current into
1206
    the redo log and during recover we are not updating key_del.
1207 1208

  @retval 1  Use page at end of file
1209
  @retval 0  Use page at share->key_del_current
1210 1211 1212 1213 1214 1215
*/

my_bool _ma_lock_key_del(MARIA_HA *info, my_bool insert_at_end)
{
  MARIA_SHARE *share= info->s;

unknown's avatar
unknown committed
1216
  /*
1217
    info->key_del_used is 0 initially.
unknown's avatar
unknown committed
1218 1219
    If the caller needs a block (_ma_new()), we look at the free list:
    - looks empty? then caller will create a new block at end of file and
1220
    remember (through info->key_del_used==2) that it will not change
unknown's avatar
unknown committed
1221 1222 1223
    state.key_del and does not need to wake up waiters as nobody will wait for
    it.
    - non-empty? then we wait for other users of the state.key_del list to
1224
    have finished, then we lock this list (through share->key_del_used==1)
unknown's avatar
unknown committed
1225
    because we need to prevent some other thread to also read state.key_del
1226
    and use the same page as ours. We remember through info->key_del_used==1
unknown's avatar
unknown committed
1227 1228 1229 1230
    that we will have to set state.key_del at unlock time and wake up
    waiters.
    If the caller wants to free a block (_ma_dispose()), "empty" and
    "non-empty" are treated as "non-empty" is treated above.
1231
    When we are ready to unlock, we copy share->key_del_current into
unknown's avatar
unknown committed
1232 1233 1234
    state.key_del. Unlocking happens when writing the UNDO log record, that
    can make a long lock time.
    Why we wrote "*looks* empty": because we are looking at state.key_del
1235
    which may be slightly old (share->key_del_current may be more recent and
unknown's avatar
unknown committed
1236 1237 1238 1239
    exact): when we want a new page, we tolerate to treat "there was no free
    page 1 millisecond ago"  as "there is no free page". It's ok to non-pop
    (_ma_new(), page will be found later anyway) but it's not ok to non-push
    (_ma_dispose(), page would be lost).
1240
    When we leave this function, info->key_del_used is always 1 or 2.
unknown's avatar
unknown committed
1241
  */
1242
  if (info->key_del_used != 1)
1243
  {
1244
    pthread_mutex_lock(&share->key_del_lock);
1245 1246
    if (share->state.key_del == HA_OFFSET_ERROR && insert_at_end)
    {
1247 1248
      pthread_mutex_unlock(&share->key_del_lock);
      info->key_del_used= 2;                  /* insert-with-append */
1249 1250 1251
      return 1;
    }
#ifdef THREAD
1252 1253
    while (share->key_del_used)
      pthread_cond_wait(&share->key_del_cond, &share->key_del_lock);
1254
#endif
1255 1256 1257 1258
    info->key_del_used= 1;
    share->key_del_used= 1;
    share->key_del_current= share->state.key_del;
    pthread_mutex_unlock(&share->key_del_lock);
1259
  }
1260
  return share->key_del_current == HA_OFFSET_ERROR;
1261 1262 1263
}


1264
/**
1265
  @brief copy changes to key_del and unlock it
1266 1267 1268 1269

  @notes
  In case of many threads using the maria table, we always have a lock
  on the translog when comming here.
1270 1271 1272 1273
*/

void _ma_unlock_key_del(MARIA_HA *info)
{
1274 1275
  DBUG_ASSERT(info->key_del_used);
  if (info->key_del_used == 1)                  /* Ignore insert-with-append */
1276
  {
1277
    MARIA_SHARE *share= info->s;
1278 1279 1280 1281 1282
    pthread_mutex_lock(&share->key_del_lock);
    share->key_del_used= 0;
    share->state.key_del= share->key_del_current;
    pthread_mutex_unlock(&share->key_del_lock);
    pthread_cond_signal(&share->key_del_cond);
1283
  }
1284
  info->key_del_used= 0;
1285
}