ma_loghandler.c 279 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (C) 2007 MySQL AB & Sanja Belkin

   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 */

16
#include "maria_def.h"
17
#include "trnman.h"
18 19
#include "ma_blockrec.h" /* for some constants and in-write hooks */
#include "ma_key_recover.h" /* For some in-write hooks */
20

unknown's avatar
unknown committed
21 22 23 24 25 26 27 28 29 30 31
/*
  On Windows, neither my_open() nor my_sync() work for directories.
  Also there is no need to flush filesystem changes ,i.e to sync()
  directories.
*/
#ifdef __WIN__
#define sync_dir(A,B) 0
#else
#define sync_dir(A,B) my_sync(A,B)
#endif

32 33 34 35 36
/**
   @file
   @brief Module which writes and reads to a transaction log
*/

37
/* 0xFF can never be valid first byte of a chunk */
unknown's avatar
unknown committed
38 39
#define TRANSLOG_FILLER 0xFF

unknown's avatar
unknown committed
40
/* number of opened log files in the pagecache (should be at least 2) */
41
#define OPENED_FILES_NUM 3
unknown's avatar
unknown committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
#define CACHED_FILES_NUM 5
#define CACHED_FILES_NUM_DIRECT_SEARCH_LIMIT 7
#if CACHED_FILES_NUM > CACHED_FILES_NUM_DIRECT_SEARCH_LIMIT
#include <hash.h>
#include <m_ctype.h>
#endif

/* transaction log file descriptor */
typedef struct st_translog_file
{
  uint32 number;
  PAGECACHE_FILE handler;
  my_bool was_recovered;
  my_bool is_sync;
} TRANSLOG_FILE;
57

unknown's avatar
unknown committed
58
/* records buffer size (should be TRANSLOG_PAGE_SIZE * n) */
59
#define TRANSLOG_WRITE_BUFFER (1024*1024)
60 61 62 63 64 65 66 67 68 69
/*
  pagecache_read/write/inject() use bmove512() on their buffers so those must
  be long-aligned, which we guarantee by using the type below:
*/
typedef union
{
  ulonglong dummy;
  uchar buffer[TRANSLOG_PAGE_SIZE];
} TRANSLOG_PAGE_SIZE_BUFF;

70 71 72 73 74 75 76 77
/* min chunk length */
#define TRANSLOG_MIN_CHUNK 3
/*
  Number of buffers used by loghandler

  Should be at least 4, because one thread can block up to 2 buffers in
  normal circumstances (less then half of one and full other, or just
  switched one and other), But if we met end of the file in the middle and
unknown's avatar
unknown committed
78 79
  have to switch buffer it will be 3.  + 1 buffer for flushing/writing.
  We have a bigger number here for higher concurrency.
80 81
*/
#define TRANSLOG_BUFFERS_NO 5
unknown's avatar
unknown committed
82
/* number of bytes (+ header) which can be unused on first page in sequence */
83 84
#define TRANSLOG_MINCHUNK_CONTENT 1
/* version of log file */
unknown's avatar
unknown committed
85
#define TRANSLOG_VERSION_ID 10000               /* 1.00.00 */
86

unknown's avatar
unknown committed
87 88
#define TRANSLOG_PAGE_FLAGS 6 /* transaction log page flags offset */

89 90 91
/* Maximum length of compressed LSNs (the worst case of whole LSN storing) */
#define COMPRESSED_LSN_MAX_STORE_SIZE (2 + LSN_STORE_SIZE)
#define MAX_NUMBER_OF_LSNS_PER_RECORD 2
unknown's avatar
unknown committed
92

unknown's avatar
unknown committed
93

94 95 96
/* log write buffer descriptor */
struct st_translog_buffer
{
97 98 99 100 101
  /*
    Cache for current log. Comes first to be aligned for bmove512() in
    pagecache_inject()
  */
  uchar buffer[TRANSLOG_WRITE_BUFFER];
102 103 104
  LSN last_lsn;
  /* This buffer offset in the file */
  TRANSLOG_ADDRESS offset;
105 106 107 108 109
  /*
    Next buffer offset in the file (it is not always offset + size,
    in case of flush by LSN it can be offset + size - TRANSLOG_PAGE_SIZE)
  */
  TRANSLOG_ADDRESS next_buffer_offset;
110
  /*
111
     How much is written (or will be written when copy_to_buffer_in_progress
112 113
     become 0) to this buffer
  */
unknown's avatar
unknown committed
114 115
  translog_size_t size;
  /* File handler for this buffer */
unknown's avatar
unknown committed
116
  TRANSLOG_FILE *file;
117
  /* Threads which are waiting for buffer filling/freeing */
unknown's avatar
unknown committed
118
  pthread_cond_t waiting_filling_buffer;
119
  /* Number of records which are in copy progress */
unknown's avatar
unknown committed
120
  uint copy_to_buffer_in_progress;
121 122
  /* list of waiting buffer ready threads */
  struct st_my_thread_var *waiting_flush;
123 124
  /*
    Pointer on the buffer which overlap with this one (due to flush of
unknown's avatar
unknown committed
125 126 127
    loghandler, the last page of that buffer is the same as the first page
    of this buffer) and have to be written first (because contain old
    content of page which present in both buffers)
128
  */
129 130
  struct st_translog_buffer *overlay;
#ifndef DBUG_OFF
unknown's avatar
unknown committed
131
  uint buffer_no;
132
#endif
133 134
  /*
    Lock for the buffer.
unknown's avatar
unknown committed
135

136
    Current buffer also lock the whole handler (if one want lock the handler
unknown's avatar
unknown committed
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    one should lock the current buffer).

    Buffers are locked only in one direction (with overflow and beginning
    from the first buffer). If we keep lock on buffer N we can lock only
    buffer N+1 (never N-1).

    One thread do not lock more then 2 buffer in a time, so to make dead
    lock it should be N thread (where N equal number of buffers) takes one
    buffer and try to lock next. But it is impossible because there is only
    2 cases when thread take 2 buffers: 1) one thread finishes current
    buffer (where horizon is) and start next (to which horizon moves).  2)
    flush start from buffer after current (oldest) and go till the current
    crabbing by buffer sequence. And there is  only one flush in a moment
    (they are serialised).

   Because of above and number of buffers equal 5 we can't get dead lock (it is
   impossible to get all 5 buffers locked simultaneously).
154
  */
unknown's avatar
unknown committed
155
  pthread_mutex_t mutex;
156 157 158 159 160 161 162 163 164 165
  /*
    Some thread is going to close the buffer and it should be
    done only by that thread
  */
  my_bool is_closing_buffer;
  /*
    Version of the buffer increases every time buffer the buffer flushed.
    With file and offset it allow detect buffer changes
  */
  uint8 ver;
166 167 168 169 170
};


struct st_buffer_cursor
{
171
  /* pointer into the buffer */
unknown's avatar
unknown committed
172
  uchar *ptr;
unknown's avatar
unknown committed
173 174
  /* current buffer */
  struct st_translog_buffer *buffer;
175
  /* How many bytes we wrote on the current page */
unknown's avatar
unknown committed
176
  uint16 current_page_fill;
177 178 179 180
  /*
    How many times we write the page on the disk during flushing process
    (for sector protection).
  */
181 182 183
  uint16 write_counter;
  /* previous write offset */
  uint16 previous_offset;
unknown's avatar
unknown committed
184
  /* Number of current buffer */
185
  uint8 buffer_no;
186 187 188 189 190 191 192 193 194 195
  /*
    True if it is just filling buffer after advancing the pointer to
    the horizon.
  */
  my_bool chaser;
  /*
    Is current page of the cursor already finished (sector protection
    should be applied if it is needed)
  */
  my_bool protected;
196 197 198 199 200 201 202
};


struct st_translog_descriptor
{
  /* *** Parameters of the log handler *** */

unknown's avatar
unknown committed
203 204 205
  /* Page cache for the log reads */
  PAGECACHE *pagecache;
  uint flags;
206 207
  /* File open flags */
  uint open_flags;
208 209 210
  /* max size of one log size (for new logs creation) */
  uint32 log_file_max_size;
  uint32 server_version;
211
  /* server ID (used for replication) */
212 213 214
  uint32 server_id;
  /* Loghandler's buffer capacity in case of chunk 2 filling */
  uint32 buffer_capacity_chunk_2;
215 216 217 218 219 220
  /*
    Half of the buffer capacity in case of chunk 2 filling,
    used to decide will we write a record in one group or many.
    It is written to the variable just to avoid devision every
    time we need it.
  */
221
  uint32 half_buffer_capacity_chunk_2;
222
  /* Page overhead calculated by flags (whether CRC is enabled, etc) */
unknown's avatar
unknown committed
223
  uint16 page_overhead;
224 225 226 227
  /*
    Page capacity ("useful load") calculated by flags
    (TRANSLOG_PAGE_SIZE - page_overhead-1)
  */
unknown's avatar
unknown committed
228
  uint16 page_capacity_chunk_2;
229
  /* Path to the directory where we store log store files */
unknown's avatar
unknown committed
230
  char directory[FN_REFLEN];
231 232

  /* *** Current state of the log handler *** */
unknown's avatar
unknown committed
233 234 235 236 237 238 239
  /* list of opened files */
  DYNAMIC_ARRAY open_files;
  /* min/max number of file in the array */
  uint32 max_file, min_file;
  /* the opened files list guard */
  rw_lock_t open_files_lock;

240 241 242 243
  /*
    File descriptor of the directory where we store log files for syncing
    it.
  */
unknown's avatar
unknown committed
244
  File directory_fd;
245 246 247 248 249 250 251 252 253
  /* buffers for log writing */
  struct st_translog_buffer buffers[TRANSLOG_BUFFERS_NO];
  /*
     horizon - visible end of the log (here is absolute end of the log:
     position where next chunk can start
  */
  TRANSLOG_ADDRESS horizon;
  /* horizon buffer cursor */
  struct st_buffer_cursor bc;
254 255
  /* maximum LSN of the current (not finished) file */
  LSN max_lsn;
256

257 258 259 260 261 262
  /*
    Last flushed LSN (protected by log_flush_lock).
    Pointers in the log ordered like this:
    last_lsn_checked <= flushed <= sent_to_disk <= in_buffers_only <=
    max_lsn <= horizon
  */
263
  LSN flushed;
264
  /* Last LSN sent to the disk (but maybe not written yet) */
265
  LSN sent_to_disk;
266 267
  /* Horizon from which log started after initialization */
  TRANSLOG_ADDRESS log_start;
268
  TRANSLOG_ADDRESS previous_flush_horizon;
269
  /* All what is after this address is not sent to disk yet */
270
  TRANSLOG_ADDRESS in_buffers_only;
271
  /* protection of sent_to_disk and in_buffers_only */
272
  pthread_mutex_t sent_to_disk_lock;
unknown's avatar
unknown committed
273 274 275 276
  /*
    Protect flushed (see above) and for flush serialization (will
    be removed in v1.5
  */
277
  pthread_mutex_t log_flush_lock;
278 279 280 281 282 283 284 285 286 287

  /* Protects changing of headers of finished files (max_lsn) */
  pthread_mutex_t file_header_lock;

  /*
    Sorted array (with protection) of files where we started writing process
    and so we can't give last LSN yet
  */
  pthread_mutex_t unfinished_files_lock;
  DYNAMIC_ARRAY unfinished_files;
288

289 290 291 292 293
  /*
    minimum number of still need file calculeted during last
    translog_purge call
  */
  uint32 min_need_file;
294 295 296 297 298 299
  /* Purger data: minimum file in the log (or 0 if unknown) */
  uint32 min_file_number;
  /* Protect purger from many calls and it's data */
  pthread_mutex_t purger_lock;
  /* last low water mark checked */
  LSN last_lsn_checked;
300 301 302 303 304
  /**
    Must be set to 0 under loghandler lock every time a new LSN
    is generated.
  */
  my_bool is_everything_flushed;
305 306 307 308
};

static struct st_translog_descriptor log_descriptor;

309 310
ulong log_purge_type= TRANSLOG_PURGE_IMMIDIATE;
ulong log_file_size= TRANSLOG_FILE_SIZE;
311 312
ulong sync_log_dir= TRANSLOG_SYNC_DIR_NEWFILE;

unknown's avatar
unknown committed
313
/* Marker for end of log */
unknown's avatar
unknown committed
314
static uchar end_of_log= 0;
unknown's avatar
unknown committed
315
#define END_OF_LOG &end_of_log
316

317
enum enum_translog_status translog_status= TRANSLOG_UNINITED;
318

319
/* chunk types */
unknown's avatar
unknown committed
320 321 322 323 324
#define TRANSLOG_CHUNK_LSN   0x00      /* 0 chunk refer as LSN (head or tail */
#define TRANSLOG_CHUNK_FIXED (1 << 6)  /* 1 (pseudo)fixed record (also LSN) */
#define TRANSLOG_CHUNK_NOHDR (2 << 6)  /* 2 no head chunk (till page end) */
#define TRANSLOG_CHUNK_LNGTH (3 << 6)  /* 3 chunk with chunk length */
#define TRANSLOG_CHUNK_TYPE  (3 << 6)  /* Mask to get chunk type */
325 326
#define TRANSLOG_REC_TYPE    0x3F      /* Mask to get record type */
#define TRANSLOG_CHUNK_0_CONT 0x3F     /* the type to mark chunk 0 continue */
327 328

/* compressed (relative) LSN constants */
unknown's avatar
unknown committed
329
#define TRANSLOG_CLSN_LEN_BITS 0xC0    /* Mask to get compressed LSN length */
330 331


332 333 334 335 336 337
#include <my_atomic.h>
/* an array that maps id of a MARIA_SHARE to this MARIA_SHARE */
static MARIA_SHARE **id_to_share= NULL;
/* lock for id_to_share */
static my_atomic_rwlock_t LOCK_id_to_share;

unknown's avatar
unknown committed
338 339 340 341 342 343
static my_bool translog_dummy_callback(uchar *page,
                                       pgcache_page_no_t page_no,
                                       uchar* data_ptr);
static my_bool translog_page_validator(uchar *page,
                                       pgcache_page_no_t page_no,
                                       uchar* data_ptr);
344

345
static my_bool translog_get_next_chunk(TRANSLOG_SCANNER_DATA *scanner);
unknown's avatar
unknown committed
346
static uint32 translog_first_file(TRANSLOG_ADDRESS horizon, int is_protected);
347
LSN translog_next_LSN(TRANSLOG_ADDRESS addr, TRANSLOG_ADDRESS horizon);
unknown's avatar
unknown committed
348

349

350 351 352 353
/*
  Initialize log_record_type_descriptors
*/

unknown's avatar
unknown committed
354
LOG_DESC log_record_type_descriptor[LOGREC_NUMBER_OF_TYPES];
355

356 357

#ifndef DBUG_OFF
unknown's avatar
unknown committed
358 359

#define translog_buffer_lock_assert_owner(B) \
360 361 362 363
  safe_mutex_assert_owner(&(B)->mutex)
#define translog_lock_assert_owner() \
  safe_mutex_assert_owner(&log_descriptor.bc.buffer->mutex)
void translog_lock_handler_assert_owner()
unknown's avatar
unknown committed
364
{
365
  translog_lock_assert_owner();
unknown's avatar
unknown committed
366 367
}

368 369 370 371 372 373 374 375 376 377 378 379 380 381
/**
  @brief check the description table validity

  @param num             how many records should be filled
*/

static void check_translog_description_table(int num)
{
  int i;
  DBUG_ENTER("check_translog_description_table");
  DBUG_PRINT("enter", ("last record: %d", num));
  DBUG_ASSERT(num > 0);
  /* last is reserved for extending the table */
  DBUG_ASSERT(num < LOGREC_NUMBER_OF_TYPES - 1);
unknown's avatar
unknown committed
382
  DBUG_ASSERT(log_record_type_descriptor[0].rclass == LOGRECTYPE_NOT_ALLOWED);
383 384

  for (i= 0; i <= num; i++)
385 386 387 388
  {
    DBUG_PRINT("info",
               ("record type: %d  class: %d  fixed: %u  header: %u  LSNs: %u  "
                "name: %s",
unknown's avatar
unknown committed
389
                i, log_record_type_descriptor[i].rclass,
390 391 392 393
                (uint)log_record_type_descriptor[i].fixed_length,
                (uint)log_record_type_descriptor[i].read_header_len,
                (uint)log_record_type_descriptor[i].compressed_LSN,
                log_record_type_descriptor[i].name));
unknown's avatar
unknown committed
394
    switch (log_record_type_descriptor[i].rclass) {
395
    case LOGRECTYPE_NOT_ALLOWED:
396
      DBUG_ASSERT(i == 0);
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
      break;
    case LOGRECTYPE_VARIABLE_LENGTH:
      DBUG_ASSERT(log_record_type_descriptor[i].fixed_length == 0);
      DBUG_ASSERT((log_record_type_descriptor[i].compressed_LSN == 0) ||
                  ((log_record_type_descriptor[i].compressed_LSN == 1) &&
                   (log_record_type_descriptor[i].read_header_len >=
                    LSN_STORE_SIZE)) ||
                  ((log_record_type_descriptor[i].compressed_LSN == 2) &&
                   (log_record_type_descriptor[i].read_header_len >=
                    LSN_STORE_SIZE * 2)));
      break;
    case LOGRECTYPE_PSEUDOFIXEDLENGTH:
      DBUG_ASSERT(log_record_type_descriptor[i].fixed_length ==
                  log_record_type_descriptor[i].read_header_len);
      DBUG_ASSERT(log_record_type_descriptor[i].compressed_LSN > 0);
      DBUG_ASSERT(log_record_type_descriptor[i].compressed_LSN <= 2);
      break;
    case LOGRECTYPE_FIXEDLENGTH:
      DBUG_ASSERT(log_record_type_descriptor[i].fixed_length ==
                  log_record_type_descriptor[i].read_header_len);
      DBUG_ASSERT(log_record_type_descriptor[i].compressed_LSN == 0);
      break;
    default:
      DBUG_ASSERT(0);
    }
  }
  for (i= num + 1; i < LOGREC_NUMBER_OF_TYPES; i++)
  {
unknown's avatar
unknown committed
425 426
    DBUG_ASSERT(log_record_type_descriptor[i].rclass ==
                LOGRECTYPE_NOT_ALLOWED);
427 428 429
  }
  DBUG_VOID_RETURN;
}
unknown's avatar
unknown committed
430
#else
431 432
#define translog_buffer_lock_assert_owner(B) {}
#define translog_lock_assert_owner() {}
433 434
#endif

435
static LOG_DESC INIT_LOGREC_RESERVED_FOR_CHUNKS23=
unknown's avatar
unknown committed
436
{LOGRECTYPE_NOT_ALLOWED, 0, 0, NULL, NULL, NULL, 0,
unknown's avatar
unknown committed
437
 "reserved", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL };
438 439 440

static LOG_DESC INIT_LOGREC_REDO_INSERT_ROW_HEAD=
{LOGRECTYPE_VARIABLE_LENGTH, 0,
441
 FILEID_STORE_SIZE + PAGE_STORE_SIZE + DIRPOS_STORE_SIZE, NULL,
unknown's avatar
unknown committed
442
 write_hook_for_redo, NULL, 0,
unknown's avatar
unknown committed
443
 "redo_insert_row_head", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};
444 445

static LOG_DESC INIT_LOGREC_REDO_INSERT_ROW_TAIL=
446 447
{LOGRECTYPE_VARIABLE_LENGTH, 0,
 FILEID_STORE_SIZE + PAGE_STORE_SIZE + DIRPOS_STORE_SIZE, NULL,
unknown's avatar
unknown committed
448
 write_hook_for_redo, NULL, 0,
unknown's avatar
unknown committed
449
 "redo_insert_row_tail", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};
450

451 452 453 454 455 456 457 458 459 460 461
static LOG_DESC INIT_LOGREC_REDO_NEW_ROW_HEAD=
{LOGRECTYPE_VARIABLE_LENGTH, 0,
 FILEID_STORE_SIZE + PAGE_STORE_SIZE + DIRPOS_STORE_SIZE, NULL,
 write_hook_for_redo, NULL, 0,
 "redo_new_row_head", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};

static LOG_DESC INIT_LOGREC_REDO_NEW_ROW_TAIL=
{LOGRECTYPE_VARIABLE_LENGTH, 0,
 FILEID_STORE_SIZE + PAGE_STORE_SIZE + DIRPOS_STORE_SIZE, NULL,
 write_hook_for_redo, NULL, 0,
 "redo_new_row_tail", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};
462 463

static LOG_DESC INIT_LOGREC_REDO_INSERT_ROW_BLOBS=
unknown's avatar
unknown committed
464 465
{LOGRECTYPE_VARIABLE_LENGTH, 0, FILEID_STORE_SIZE, NULL,
 write_hook_for_redo, NULL, 0,
unknown's avatar
unknown committed
466
 "redo_insert_row_blobs", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};
467 468 469 470 471

static LOG_DESC INIT_LOGREC_REDO_PURGE_ROW_HEAD=
{LOGRECTYPE_FIXEDLENGTH,
 FILEID_STORE_SIZE + PAGE_STORE_SIZE + DIRPOS_STORE_SIZE,
 FILEID_STORE_SIZE + PAGE_STORE_SIZE + DIRPOS_STORE_SIZE,
unknown's avatar
unknown committed
472
 NULL, write_hook_for_redo, NULL, 0,
unknown's avatar
unknown committed
473
 "redo_purge_row_head", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};
474 475 476 477 478

static LOG_DESC INIT_LOGREC_REDO_PURGE_ROW_TAIL=
{LOGRECTYPE_FIXEDLENGTH,
 FILEID_STORE_SIZE + PAGE_STORE_SIZE + DIRPOS_STORE_SIZE,
 FILEID_STORE_SIZE + PAGE_STORE_SIZE + DIRPOS_STORE_SIZE,
unknown's avatar
unknown committed
479
 NULL, write_hook_for_redo, NULL, 0,
unknown's avatar
unknown committed
480
 "redo_purge_row_tail", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};
481

482
static LOG_DESC INIT_LOGREC_REDO_FREE_BLOCKS=
483 484
{LOGRECTYPE_VARIABLE_LENGTH, 0,
 FILEID_STORE_SIZE + PAGERANGE_STORE_SIZE,
unknown's avatar
unknown committed
485
 NULL, write_hook_for_redo, NULL, 0,
486 487 488 489 490 491 492 493
 "redo_free_blocks", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};

static LOG_DESC INIT_LOGREC_REDO_FREE_HEAD_OR_TAIL=
{LOGRECTYPE_FIXEDLENGTH,
 FILEID_STORE_SIZE + PAGE_STORE_SIZE,
 FILEID_STORE_SIZE + PAGE_STORE_SIZE,
 NULL, write_hook_for_redo, NULL, 0,
 "redo_free_head_or_tail", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};
494

unknown's avatar
unknown committed
495
/* not yet used; for when we have versioning */
496
static LOG_DESC INIT_LOGREC_REDO_DELETE_ROW=
unknown's avatar
unknown committed
497
{LOGRECTYPE_FIXEDLENGTH, 16, 16, NULL, write_hook_for_redo, NULL, 0,
unknown's avatar
unknown committed
498
 "redo_delete_row", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};
499

unknown's avatar
unknown committed
500
/** @todo RECOVERY BUG unused, remove? */
501
static LOG_DESC INIT_LOGREC_REDO_UPDATE_ROW_HEAD=
unknown's avatar
unknown committed
502
{LOGRECTYPE_VARIABLE_LENGTH, 0, 9, NULL, write_hook_for_redo, NULL, 0,
unknown's avatar
unknown committed
503
 "redo_update_row_head", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};
504 505

static LOG_DESC INIT_LOGREC_REDO_INDEX=
unknown's avatar
unknown committed
506
{LOGRECTYPE_VARIABLE_LENGTH, 0, 9, NULL, write_hook_for_redo, NULL, 0,
unknown's avatar
unknown committed
507
 "redo_index", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};
508

509 510 511 512 513 514 515 516 517 518 519 520
static LOG_DESC INIT_LOGREC_REDO_INDEX_NEW_PAGE=
{LOGRECTYPE_VARIABLE_LENGTH, 0,
 FILEID_STORE_SIZE + PAGE_STORE_SIZE * 2 + KEY_NR_STORE_SIZE + 1,
 NULL, write_hook_for_redo, NULL, 0,
 "redo_index_new_page", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};

static LOG_DESC INIT_LOGREC_REDO_INDEX_FREE_PAGE=
{LOGRECTYPE_FIXEDLENGTH, FILEID_STORE_SIZE + PAGE_STORE_SIZE * 2,
 FILEID_STORE_SIZE + PAGE_STORE_SIZE * 2,
 NULL, write_hook_for_redo, NULL, 0,
 "redo_index_free_page", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};

521
static LOG_DESC INIT_LOGREC_REDO_UNDELETE_ROW=
unknown's avatar
unknown committed
522
{LOGRECTYPE_FIXEDLENGTH, 16, 16, NULL, write_hook_for_redo, NULL, 0,
unknown's avatar
unknown committed
523
 "redo_undelete_row", LOGREC_NOT_LAST_IN_GROUP, NULL, NULL};
524 525

static LOG_DESC INIT_LOGREC_CLR_END=
unknown's avatar
unknown committed
526 527
{LOGRECTYPE_VARIABLE_LENGTH, 0, LSN_STORE_SIZE + FILEID_STORE_SIZE +
 CLR_TYPE_STORE_SIZE, NULL, write_hook_for_clr_end, NULL, 1,
unknown's avatar
unknown committed
528
 "clr_end", LOGREC_LAST_IN_GROUP, NULL, NULL};
529 530

static LOG_DESC INIT_LOGREC_PURGE_END=
unknown's avatar
unknown committed
531
{LOGRECTYPE_PSEUDOFIXEDLENGTH, 5, 5, NULL, NULL, NULL, 1,
unknown's avatar
unknown committed
532
 "purge_end", LOGREC_LAST_IN_GROUP, NULL, NULL};
533 534

static LOG_DESC INIT_LOGREC_UNDO_ROW_INSERT=
unknown's avatar
unknown committed
535
{LOGRECTYPE_VARIABLE_LENGTH, 0,
536
 LSN_STORE_SIZE + FILEID_STORE_SIZE + PAGE_STORE_SIZE + DIRPOS_STORE_SIZE,
unknown's avatar
unknown committed
537
 NULL, write_hook_for_undo_row_insert, NULL, 1,
unknown's avatar
unknown committed
538
 "undo_row_insert", LOGREC_LAST_IN_GROUP, NULL, NULL};
539 540 541 542

static LOG_DESC INIT_LOGREC_UNDO_ROW_DELETE=
{LOGRECTYPE_VARIABLE_LENGTH, 0,
 LSN_STORE_SIZE + FILEID_STORE_SIZE + PAGE_STORE_SIZE + DIRPOS_STORE_SIZE,
unknown's avatar
unknown committed
543
 NULL, write_hook_for_undo_row_delete, NULL, 1,
unknown's avatar
unknown committed
544
 "undo_row_delete", LOGREC_LAST_IN_GROUP, NULL, NULL};
545 546 547 548

static LOG_DESC INIT_LOGREC_UNDO_ROW_UPDATE=
{LOGRECTYPE_VARIABLE_LENGTH, 0,
 LSN_STORE_SIZE + FILEID_STORE_SIZE + PAGE_STORE_SIZE + DIRPOS_STORE_SIZE,
unknown's avatar
unknown committed
549
 NULL, write_hook_for_undo_row_update, NULL, 1,
unknown's avatar
unknown committed
550
 "undo_row_update", LOGREC_LAST_IN_GROUP, NULL, NULL};
551 552

static LOG_DESC INIT_LOGREC_UNDO_KEY_INSERT=
553 554
{LOGRECTYPE_VARIABLE_LENGTH, 0,
 LSN_STORE_SIZE + FILEID_STORE_SIZE + KEY_NR_STORE_SIZE,
555
 NULL, write_hook_for_undo_key_insert, NULL, 1,
unknown's avatar
unknown committed
556
 "undo_key_insert", LOGREC_LAST_IN_GROUP, NULL, NULL};
557

558 559 560 561 562 563 564
/* This will never be in the log, only in the clr */
static LOG_DESC INIT_LOGREC_UNDO_KEY_INSERT_WITH_ROOT=
{LOGRECTYPE_VARIABLE_LENGTH, 0,
 LSN_STORE_SIZE + FILEID_STORE_SIZE + KEY_NR_STORE_SIZE + PAGE_STORE_SIZE,
 NULL, write_hook_for_undo_key, NULL, 1,
 "undo_key_insert_with_root", LOGREC_LAST_IN_GROUP, NULL, NULL};

565
static LOG_DESC INIT_LOGREC_UNDO_KEY_DELETE=
566 567
{LOGRECTYPE_VARIABLE_LENGTH, 0,
 LSN_STORE_SIZE + FILEID_STORE_SIZE + KEY_NR_STORE_SIZE,
568
 NULL, write_hook_for_undo_key_delete, NULL, 1,
unknown's avatar
unknown committed
569
 "undo_key_delete", LOGREC_LAST_IN_GROUP, NULL, NULL};
570

571 572 573
static LOG_DESC INIT_LOGREC_UNDO_KEY_DELETE_WITH_ROOT=
{LOGRECTYPE_VARIABLE_LENGTH, 0,
 LSN_STORE_SIZE + FILEID_STORE_SIZE + KEY_NR_STORE_SIZE + PAGE_STORE_SIZE,
574
 NULL, write_hook_for_undo_key_delete, NULL, 1,
575 576
 "undo_key_delete_with_root", LOGREC_LAST_IN_GROUP, NULL, NULL};

577
static LOG_DESC INIT_LOGREC_PREPARE=
unknown's avatar
unknown committed
578
{LOGRECTYPE_VARIABLE_LENGTH, 0, 0, NULL, NULL, NULL, 0,
unknown's avatar
unknown committed
579
 "prepare", LOGREC_IS_GROUP_ITSELF, NULL, NULL};
580 581

static LOG_DESC INIT_LOGREC_PREPARE_WITH_UNDO_PURGE=
582
{LOGRECTYPE_VARIABLE_LENGTH, 0, LSN_STORE_SIZE, NULL, NULL, NULL, 1,
unknown's avatar
unknown committed
583
 "prepare_with_undo_purge", LOGREC_IS_GROUP_ITSELF, NULL, NULL};
584 585

static LOG_DESC INIT_LOGREC_COMMIT=
unknown's avatar
unknown committed
586 587 588
{LOGRECTYPE_FIXEDLENGTH, 0, 0, NULL,
 NULL, NULL, 0, "commit", LOGREC_IS_GROUP_ITSELF, NULL,
 NULL};
589 590

static LOG_DESC INIT_LOGREC_COMMIT_WITH_UNDO_PURGE=
unknown's avatar
unknown committed
591
{LOGRECTYPE_PSEUDOFIXEDLENGTH, 5, 5, NULL, NULL, NULL, 1,
unknown's avatar
unknown committed
592
 "commit_with_undo_purge", LOGREC_IS_GROUP_ITSELF, NULL, NULL};
593

594
static LOG_DESC INIT_LOGREC_CHECKPOINT=
unknown's avatar
unknown committed
595
{LOGRECTYPE_VARIABLE_LENGTH, 0, 0, NULL, NULL, NULL, 0,
unknown's avatar
unknown committed
596
 "checkpoint", LOGREC_IS_GROUP_ITSELF, NULL, NULL};
597 598

static LOG_DESC INIT_LOGREC_REDO_CREATE_TABLE=
unknown's avatar
unknown committed
599
{LOGRECTYPE_VARIABLE_LENGTH, 0, 1 + 2, NULL, NULL, NULL, 0,
unknown's avatar
unknown committed
600
"redo_create_table", LOGREC_IS_GROUP_ITSELF, NULL, NULL};
601 602

static LOG_DESC INIT_LOGREC_REDO_RENAME_TABLE=
unknown's avatar
unknown committed
603
{LOGRECTYPE_VARIABLE_LENGTH, 0, 0, NULL, NULL, NULL, 0,
unknown's avatar
unknown committed
604
 "redo_rename_table", LOGREC_IS_GROUP_ITSELF, NULL, NULL};
605 606

static LOG_DESC INIT_LOGREC_REDO_DROP_TABLE=
607
{LOGRECTYPE_VARIABLE_LENGTH, 0, 0, NULL, NULL, NULL, 0,
unknown's avatar
unknown committed
608
 "redo_drop_table", LOGREC_IS_GROUP_ITSELF, NULL, NULL};
609

610 611
static LOG_DESC INIT_LOGREC_REDO_DELETE_ALL=
{LOGRECTYPE_FIXEDLENGTH, FILEID_STORE_SIZE, FILEID_STORE_SIZE,
unknown's avatar
unknown committed
612
 NULL, write_hook_for_redo_delete_all, NULL, 0,
unknown's avatar
unknown committed
613
 "redo_delete_all", LOGREC_IS_GROUP_ITSELF, NULL, NULL};
614 615

static LOG_DESC INIT_LOGREC_REDO_REPAIR_TABLE=
unknown's avatar
unknown committed
616
{LOGRECTYPE_FIXEDLENGTH, FILEID_STORE_SIZE + 8 + 8, FILEID_STORE_SIZE + 8 + 8,
unknown's avatar
unknown committed
617
 NULL, NULL, NULL, 0,
unknown's avatar
unknown committed
618
 "redo_repair_table", LOGREC_IS_GROUP_ITSELF, NULL, NULL};
619 620

static LOG_DESC INIT_LOGREC_FILE_ID=
unknown's avatar
unknown committed
621
{LOGRECTYPE_VARIABLE_LENGTH, 0, 2, NULL, write_hook_for_file_id, NULL, 0,
unknown's avatar
unknown committed
622
 "file_id", LOGREC_IS_GROUP_ITSELF, NULL, NULL};
623 624

static LOG_DESC INIT_LOGREC_LONG_TRANSACTION_ID=
unknown's avatar
unknown committed
625
{LOGRECTYPE_FIXEDLENGTH, 6, 6, NULL, NULL, NULL, 0,
unknown's avatar
unknown committed
626
 "long_transaction_id", LOGREC_IS_GROUP_ITSELF, NULL, NULL};
627

unknown's avatar
unknown committed
628 629 630 631 632
static LOG_DESC INIT_LOGREC_INCOMPLETE_LOG=
{LOGRECTYPE_FIXEDLENGTH, FILEID_STORE_SIZE, FILEID_STORE_SIZE,
 NULL, NULL, NULL, 0,
 "incomplete_log", LOGREC_IS_GROUP_ITSELF, NULL, NULL};

unknown's avatar
unknown committed
633 634 635 636 637
static LOG_DESC INIT_LOGREC_INCOMPLETE_GROUP=
{LOGRECTYPE_FIXEDLENGTH, 0, 0,
 NULL, NULL, NULL, 0,
 "incomplete_group", LOGREC_IS_GROUP_ITSELF, NULL, NULL};

638
static LOG_DESC INIT_LOGREC_UNDO_BULK_INSERT=
unknown's avatar
unknown committed
639 640
{LOGRECTYPE_VARIABLE_LENGTH, 0,
 LSN_STORE_SIZE + FILEID_STORE_SIZE,
641
 NULL, write_hook_for_undo_bulk_insert, NULL, 1,
642
 "undo_bulk_insert", LOGREC_LAST_IN_GROUP, NULL, NULL};
unknown's avatar
unknown committed
643 644 645 646 647 648 649

static LOG_DESC INIT_LOGREC_REDO_BITMAP_NEW_PAGE=
{LOGRECTYPE_FIXEDLENGTH, FILEID_STORE_SIZE + PAGE_STORE_SIZE * 2,
 FILEID_STORE_SIZE + PAGE_STORE_SIZE * 2,
 NULL, NULL, NULL, 0,
 "redo_create_bitmap", LOGREC_IS_GROUP_ITSELF, NULL, NULL};

650
const myf log_write_flags= MY_WME | MY_NABP | MY_WAIT_IF_FULL;
651

652
void translog_table_init()
653
{
654
  int i;
655 656 657 658 659 660
  log_record_type_descriptor[LOGREC_RESERVED_FOR_CHUNKS23]=
    INIT_LOGREC_RESERVED_FOR_CHUNKS23;
  log_record_type_descriptor[LOGREC_REDO_INSERT_ROW_HEAD]=
    INIT_LOGREC_REDO_INSERT_ROW_HEAD;
  log_record_type_descriptor[LOGREC_REDO_INSERT_ROW_TAIL]=
    INIT_LOGREC_REDO_INSERT_ROW_TAIL;
661 662 663 664
  log_record_type_descriptor[LOGREC_REDO_NEW_ROW_HEAD]=
    INIT_LOGREC_REDO_NEW_ROW_HEAD;
  log_record_type_descriptor[LOGREC_REDO_NEW_ROW_TAIL]=
    INIT_LOGREC_REDO_NEW_ROW_TAIL;
665 666 667 668 669 670
  log_record_type_descriptor[LOGREC_REDO_INSERT_ROW_BLOBS]=
    INIT_LOGREC_REDO_INSERT_ROW_BLOBS;
  log_record_type_descriptor[LOGREC_REDO_PURGE_ROW_HEAD]=
    INIT_LOGREC_REDO_PURGE_ROW_HEAD;
  log_record_type_descriptor[LOGREC_REDO_PURGE_ROW_TAIL]=
    INIT_LOGREC_REDO_PURGE_ROW_TAIL;
671 672 673 674
  log_record_type_descriptor[LOGREC_REDO_FREE_BLOCKS]=
    INIT_LOGREC_REDO_FREE_BLOCKS;
  log_record_type_descriptor[LOGREC_REDO_FREE_HEAD_OR_TAIL]=
    INIT_LOGREC_REDO_FREE_HEAD_OR_TAIL;
675 676 677 678 679 680
  log_record_type_descriptor[LOGREC_REDO_DELETE_ROW]=
    INIT_LOGREC_REDO_DELETE_ROW;
  log_record_type_descriptor[LOGREC_REDO_UPDATE_ROW_HEAD]=
    INIT_LOGREC_REDO_UPDATE_ROW_HEAD;
  log_record_type_descriptor[LOGREC_REDO_INDEX]=
    INIT_LOGREC_REDO_INDEX;
681 682 683 684
  log_record_type_descriptor[LOGREC_REDO_INDEX_NEW_PAGE]=
    INIT_LOGREC_REDO_INDEX_NEW_PAGE;
  log_record_type_descriptor[LOGREC_REDO_INDEX_FREE_PAGE]=
    INIT_LOGREC_REDO_INDEX_FREE_PAGE;
685 686 687 688 689 690 691 692 693 694 695 696 697 698
  log_record_type_descriptor[LOGREC_REDO_UNDELETE_ROW]=
    INIT_LOGREC_REDO_UNDELETE_ROW;
  log_record_type_descriptor[LOGREC_CLR_END]=
    INIT_LOGREC_CLR_END;
  log_record_type_descriptor[LOGREC_PURGE_END]=
    INIT_LOGREC_PURGE_END;
  log_record_type_descriptor[LOGREC_UNDO_ROW_INSERT]=
    INIT_LOGREC_UNDO_ROW_INSERT;
  log_record_type_descriptor[LOGREC_UNDO_ROW_DELETE]=
    INIT_LOGREC_UNDO_ROW_DELETE;
  log_record_type_descriptor[LOGREC_UNDO_ROW_UPDATE]=
    INIT_LOGREC_UNDO_ROW_UPDATE;
  log_record_type_descriptor[LOGREC_UNDO_KEY_INSERT]=
    INIT_LOGREC_UNDO_KEY_INSERT;
699 700
  log_record_type_descriptor[LOGREC_UNDO_KEY_INSERT_WITH_ROOT]=
    INIT_LOGREC_UNDO_KEY_INSERT_WITH_ROOT;
701 702
  log_record_type_descriptor[LOGREC_UNDO_KEY_DELETE]=
    INIT_LOGREC_UNDO_KEY_DELETE;
703 704
  log_record_type_descriptor[LOGREC_UNDO_KEY_DELETE_WITH_ROOT]=
    INIT_LOGREC_UNDO_KEY_DELETE_WITH_ROOT;
705 706 707 708 709 710 711 712
  log_record_type_descriptor[LOGREC_PREPARE]=
    INIT_LOGREC_PREPARE;
  log_record_type_descriptor[LOGREC_PREPARE_WITH_UNDO_PURGE]=
    INIT_LOGREC_PREPARE_WITH_UNDO_PURGE;
  log_record_type_descriptor[LOGREC_COMMIT]=
    INIT_LOGREC_COMMIT;
  log_record_type_descriptor[LOGREC_COMMIT_WITH_UNDO_PURGE]=
    INIT_LOGREC_COMMIT_WITH_UNDO_PURGE;
713 714
  log_record_type_descriptor[LOGREC_CHECKPOINT]=
    INIT_LOGREC_CHECKPOINT;
715 716 717 718 719 720
  log_record_type_descriptor[LOGREC_REDO_CREATE_TABLE]=
    INIT_LOGREC_REDO_CREATE_TABLE;
  log_record_type_descriptor[LOGREC_REDO_RENAME_TABLE]=
    INIT_LOGREC_REDO_RENAME_TABLE;
  log_record_type_descriptor[LOGREC_REDO_DROP_TABLE]=
    INIT_LOGREC_REDO_DROP_TABLE;
721 722 723 724
  log_record_type_descriptor[LOGREC_REDO_DELETE_ALL]=
    INIT_LOGREC_REDO_DELETE_ALL;
  log_record_type_descriptor[LOGREC_REDO_REPAIR_TABLE]=
    INIT_LOGREC_REDO_REPAIR_TABLE;
725 726 727 728
  log_record_type_descriptor[LOGREC_FILE_ID]=
    INIT_LOGREC_FILE_ID;
  log_record_type_descriptor[LOGREC_LONG_TRANSACTION_ID]=
    INIT_LOGREC_LONG_TRANSACTION_ID;
unknown's avatar
unknown committed
729 730
  log_record_type_descriptor[LOGREC_INCOMPLETE_LOG]=
    INIT_LOGREC_INCOMPLETE_LOG;
unknown's avatar
unknown committed
731 732
  log_record_type_descriptor[LOGREC_INCOMPLETE_GROUP]=
    INIT_LOGREC_INCOMPLETE_GROUP;
733 734
  log_record_type_descriptor[LOGREC_UNDO_BULK_INSERT]=
    INIT_LOGREC_UNDO_BULK_INSERT;
unknown's avatar
unknown committed
735 736 737
  log_record_type_descriptor[LOGREC_REDO_BITMAP_NEW_PAGE]=
    INIT_LOGREC_REDO_BITMAP_NEW_PAGE;
  for (i= LOGREC_FIRST_FREE; i < LOGREC_NUMBER_OF_TYPES; i++)
unknown's avatar
unknown committed
738
    log_record_type_descriptor[i].rclass= LOGRECTYPE_NOT_ALLOWED;
unknown's avatar
unknown committed
739
#ifndef DBUG_OFF
unknown's avatar
unknown committed
740
  check_translog_description_table(LOGREC_FIRST_FREE -1);
unknown's avatar
unknown committed
741
#endif
742
}
743

744

unknown's avatar
unknown committed
745 746
/* all possible flags page overheads */
static uint page_overhead[TRANSLOG_FLAGS_NUM];
747 748 749 750 751 752 753 754

typedef struct st_translog_validator_data
{
  TRANSLOG_ADDRESS *addr;
  my_bool was_recovered;
} TRANSLOG_VALIDATOR_DATA;


unknown's avatar
unknown committed
755 756 757 758 759 760 761 762
/*
  Check cursor/buffer consistence

  SYNOPSIS
    translog_check_cursor
    cursor               cursor which will be checked
*/

763 764
static void translog_check_cursor(struct st_buffer_cursor *cursor
                                 __attribute__((unused)))
unknown's avatar
unknown committed
765 766 767 768 769 770 771 772 773 774
{
  DBUG_ASSERT(cursor->chaser ||
              ((ulong) (cursor->ptr - cursor->buffer->buffer) ==
               cursor->buffer->size));
  DBUG_ASSERT(cursor->buffer->buffer_no == cursor->buffer_no);
  DBUG_ASSERT((cursor->ptr -cursor->buffer->buffer) %TRANSLOG_PAGE_SIZE ==
              cursor->current_page_fill % TRANSLOG_PAGE_SIZE);
  DBUG_ASSERT(cursor->current_page_fill <= TRANSLOG_PAGE_SIZE);
}

775 776 777 778 779 780 781

/**
  @brief switch the loghandler in read only mode in case of write error
*/

void translog_stop_writing()
{
unknown's avatar
unknown committed
782 783
  DBUG_ENTER("translog_stop_writing");
  DBUG_PRINT("error", ("errno: %d   my_errno: %d", errno, my_errno));
unknown's avatar
unknown committed
784 785 786
  translog_status= (translog_status == TRANSLOG_SHUTDOWN ?
                    TRANSLOG_UNINITED :
                    TRANSLOG_READONLY);
787
  log_descriptor.open_flags= O_BINARY | O_RDONLY;
unknown's avatar
unknown committed
788 789
  DBUG_ASSERT(0);
  DBUG_VOID_RETURN;
790 791 792
}


793
/*
794
  @brief Get file name of the log by log number
795

796 797
  @param file_no         Number of the log we want to open
  @param path            Pointer to buffer where file name will be
unknown's avatar
unknown committed
798
                         stored (must be FN_REFLEN bytes at least)
799 800

  @return pointer to path
801 802
*/

803
char *translog_filename_by_fileno(uint32 file_no, char *path)
804
{
unknown's avatar
unknown committed
805 806
  char buff[11], *end;
  uint length;
807
  DBUG_ENTER("translog_filename_by_fileno");
unknown's avatar
unknown committed
808
  DBUG_ASSERT(file_no <= 0xfffffff);
unknown's avatar
unknown committed
809 810 811 812

  /* log_descriptor.directory is already formated */
  end= strxmov(path, log_descriptor.directory, "maria_log.0000000", NullS);
  length= (uint) (int10_to_str(file_no, buff, 10) - buff);
813
  strmov(end - length +1, buff);
unknown's avatar
unknown committed
814

unknown's avatar
unknown committed
815
  DBUG_PRINT("info", ("Path: '%s'  path: 0x%lx", path, (ulong) path));
unknown's avatar
unknown committed
816
  DBUG_RETURN(path);
817 818 819
}


820 821
/**
  @brief Create log file with given number without cache
822

823
  @param file_no         Number of the log we want to open
824

825 826 827 828 829 830 831 832 833 834
  retval -1  error
  retval # file descriptor number
*/

static File create_logfile_by_number_no_cache(uint32 file_no)
{
  File file;
  char path[FN_REFLEN];
  DBUG_ENTER("create_logfile_by_number_no_cache");

835
  if (translog_status != TRANSLOG_OK)
unknown's avatar
unknown committed
836
     DBUG_RETURN(-1);
837

838 839 840 841
  /* TODO: add O_DIRECT to open flags (when buffer is aligned) */
  if ((file= my_create(translog_filename_by_fileno(file_no, path),
                       0, O_BINARY | O_RDWR, MYF(MY_WME))) < 0)
  {
unknown's avatar
unknown committed
842 843
    DBUG_PRINT("error", ("Error %d during creating file '%s'", errno, path));
    translog_stop_writing();
844 845 846
    DBUG_RETURN(-1);
  }
  if (sync_log_dir >= TRANSLOG_SYNC_DIR_NEWFILE &&
unknown's avatar
unknown committed
847
      sync_dir(log_descriptor.directory_fd, MYF(MY_WME | MY_IGNORE_BADFD)))
848
  {
unknown's avatar
unknown committed
849
    DBUG_PRINT("error", ("Error %d during syncing directory '%s'",
850
                         errno, log_descriptor.directory));
unknown's avatar
unknown committed
851
    translog_stop_writing();
852 853 854 855 856 857 858 859 860 861 862 863 864
    DBUG_RETURN(-1);
  }
  DBUG_PRINT("info", ("File: '%s'  handler: %d", path, file));
  DBUG_RETURN(file);
}

/**
  @brief Open (not create) log file with given number without cache

  @param file_no         Number of the log we want to open

  retval -1  error
  retval # file descriptor number
865 866
*/

867
static File open_logfile_by_number_no_cache(uint32 file_no)
868 869 870 871 872
{
  File file;
  char path[FN_REFLEN];
  DBUG_ENTER("open_logfile_by_number_no_cache");

873
  /* TODO: add O_DIRECT to open flags (when buffer is aligned) */
874
  /* TODO: use my_create() */
unknown's avatar
unknown committed
875
  if ((file= my_open(translog_filename_by_fileno(file_no, path),
876
                     log_descriptor.open_flags,
877 878
                     MYF(MY_WME))) < 0)
  {
879
    DBUG_PRINT("error", ("Error %d during opening file '%s'", errno, path));
unknown's avatar
unknown committed
880
    DBUG_RETURN(-1);
881
  }
unknown's avatar
unknown committed
882
  DBUG_PRINT("info", ("File: '%s'  handler: %d", path, file));
883 884 885 886
  DBUG_RETURN(file);
}


unknown's avatar
unknown committed
887 888 889 890 891 892
/**
  @brief get file descriptor by given number using cache

  @param file_no         Number of the log we want to open

  retval # file descriptor
893
  retval NULL file is not opened
unknown's avatar
unknown committed
894 895 896 897 898 899 900
*/

static TRANSLOG_FILE *get_logfile_by_number(uint32 file_no)
{
  TRANSLOG_FILE *file;
  DBUG_ENTER("get_logfile_by_number");
  rw_rdlock(&log_descriptor.open_files_lock);
901 902 903 904
  if (log_descriptor.max_file - file_no >=
      log_descriptor.open_files.elements)
  {
    DBUG_PRINT("info", ("File #%u is not opened", file_no));
905
    rw_unlock(&log_descriptor.open_files_lock);
906 907
    DBUG_RETURN(NULL);
  }
unknown's avatar
unknown committed
908 909 910 911
  DBUG_ASSERT(log_descriptor.max_file - log_descriptor.min_file + 1 ==
              log_descriptor.open_files.elements);
  DBUG_ASSERT(log_descriptor.max_file >= file_no);
  DBUG_ASSERT(log_descriptor.min_file <= file_no);
912

unknown's avatar
unknown committed
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
  file= *dynamic_element(&log_descriptor.open_files,
                         log_descriptor.max_file - file_no, TRANSLOG_FILE **);
  rw_unlock(&log_descriptor.open_files_lock);
  DBUG_PRINT("info", ("File 0x%lx File no: %lu, File handler: %d",
                      (ulong)file, (ulong)file_no,
                      (file ? file->handler.file : -1)));
  DBUG_ASSERT(!file || file->number == file_no);
  DBUG_RETURN(file);
}


/**
  @brief get current file descriptor

  retval # file descriptor
*/

static TRANSLOG_FILE *get_current_logfile()
{
  TRANSLOG_FILE *file;
  rw_rdlock(&log_descriptor.open_files_lock);
  DBUG_ASSERT(log_descriptor.max_file - log_descriptor.min_file + 1 ==
              log_descriptor.open_files.elements);
  file= *dynamic_element(&log_descriptor.open_files, 0, TRANSLOG_FILE **);
  rw_unlock(&log_descriptor.open_files_lock);
  return (file);
}

941 942 943 944 945 946 947 948
uchar	NEAR maria_trans_file_magic[]=
{ (uchar) 254, (uchar) 254, (uchar) 11, '\001', 'M', 'A', 'R', 'I', 'A',
 'L', 'O', 'G' };
#define LOG_HEADER_DATA_SIZE (sizeof(maria_trans_file_magic) + \
                              8 + 4 + 4 + 4 + 2 + 3 + \
                              LSN_STORE_SIZE)


949 950 951 952 953 954
/*
  Write log file page header in the just opened new log file

  SYNOPSIS
    translog_write_file_header();

unknown's avatar
unknown committed
955 956 957
   NOTES
    First page is just a marker page; We don't store any real log data in it.

958 959 960 961 962
  RETURN
    0 OK
    1 ERROR
*/

963
static my_bool translog_write_file_header()
964
{
unknown's avatar
unknown committed
965
  TRANSLOG_FILE *file;
966
  ulonglong timestamp;
unknown's avatar
unknown committed
967
  uchar page_buff[TRANSLOG_PAGE_SIZE], *page= page_buff;
unknown's avatar
unknown committed
968
  my_bool rc;
969 970 971
  DBUG_ENTER("translog_write_file_header");

  /* file tag */
unknown's avatar
unknown committed
972 973
  memcpy(page, maria_trans_file_magic, sizeof(maria_trans_file_magic));
  page+= sizeof(maria_trans_file_magic);
974 975
  /* timestamp */
  timestamp= my_getsystime();
unknown's avatar
unknown committed
976 977
  int8store(page, timestamp);
  page+= 8;
978
  /* maria version */
unknown's avatar
unknown committed
979 980
  int4store(page, TRANSLOG_VERSION_ID);
  page+= 4;
981
  /* mysql version (MYSQL_VERSION_ID) */
unknown's avatar
unknown committed
982 983
  int4store(page, log_descriptor.server_version);
  page+= 4;
984
  /* server ID */
unknown's avatar
unknown committed
985 986
  int4store(page, log_descriptor.server_id);
  page+= 4;
987 988
  /* loghandler page_size */
  int2store(page, TRANSLOG_PAGE_SIZE - 1);
unknown's avatar
unknown committed
989
  page+= 2;
990
  /* file number */
unknown's avatar
unknown committed
991 992
  int3store(page, LSN_FILE_NO(log_descriptor.horizon));
  page+= 3;
unknown's avatar
unknown committed
993
  lsn_store(page, LSN_IMPOSSIBLE);
994
  page+= LSN_STORE_SIZE;
unknown's avatar
unknown committed
995
  memset(page, TRANSLOG_FILLER, sizeof(page_buff) - (page- page_buff));
996

unknown's avatar
unknown committed
997 998 999 1000 1001 1002 1003 1004 1005 1006
  file= get_current_logfile();
  rc= my_pwrite(file->handler.file, page_buff, sizeof(page_buff), 0,
                log_write_flags) != 0;
  /*
    Dropping the flag in such way can make false alarm: signalling than the
    file in not sync when it is sync, but the situation is quite rare and
    protections with mutexes give much more overhead to the whole engine
  */
  file->is_sync= 0;
  DBUG_RETURN(rc);
1007 1008
}

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
/*
  @brief write the new LSN on the given file header

  @param file            The file descriptor
  @param lsn             That LSN which should be written

  @retval 0 OK
  @retval 1 Error
*/

static my_bool translog_max_lsn_to_header(File file, LSN lsn)
{
  uchar lsn_buff[LSN_STORE_SIZE];
  DBUG_ENTER("translog_max_lsn_to_header");
  DBUG_PRINT("enter", ("File descriptor: %ld  "
                       "lsn: (%lu,0x%lx)",
                       (long) file,
unknown's avatar
unknown committed
1026
                       LSN_IN_PARTS(lsn)));
1027 1028 1029 1030 1031

  lsn_store(lsn_buff, lsn);

  DBUG_RETURN(my_pwrite(file, lsn_buff,
                        LSN_STORE_SIZE,
1032
                        (LOG_HEADER_DATA_SIZE - LSN_STORE_SIZE),
1033 1034 1035 1036
                        log_write_flags) != 0 ||
              my_sync(file, MYF(MY_WME)) != 0);
}

1037

1038 1039 1040 1041 1042 1043
/*
  Information from transaction log file header
*/

typedef struct st_loghandler_file_info
{
1044
  /*
1045 1046 1047
    LSN_IMPOSSIBLE for current file (not finished file).
    Maximum LSN of the record which parts stored in the
    file.
1048 1049
  */
  LSN max_lsn;
1050 1051
  ulonglong timestamp;   /* Time stamp */
  ulong maria_version;   /* Version of maria loghandler */
1052
  ulong mysql_version;   /* Version of mysql server */
1053
  ulong server_id;       /* Server ID */
1054 1055
  ulong page_size;       /* Loghandler page size */
  ulong file_number;     /* Number of the file (from the file header) */
1056 1057
} LOGHANDLER_FILE_INFO;

1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
/*
  @brief Extract hander file information from loghandler file page

  @param desc header information descriptor to be filled with information
  @param page_buff buffer with the page content
*/

static void translog_interpret_file_header(LOGHANDLER_FILE_INFO *desc,
                                           uchar *page_buff)
{
  uchar *ptr;

  ptr= page_buff + sizeof(maria_trans_file_magic);
  desc->timestamp= uint8korr(ptr);
  ptr+= 8;
  desc->maria_version= uint4korr(ptr);
  ptr+= 4;
  desc->mysql_version= uint4korr(ptr);
  ptr+= 4;
  desc->server_id= uint4korr(ptr + 4);
  ptr+= 4;
  desc->page_size= uint2korr(ptr) + 1;
  ptr+= 2;
  desc->file_number= uint3korr(ptr);
  ptr+=3;
  desc->max_lsn= lsn_korr(ptr);
}


1087
/*
1088
  @brief Read hander file information from loghandler file
1089 1090

  @param desc header information descriptor to be filled with information
1091
  @param file file descriptor to read
1092 1093 1094 1095 1096

  @retval 0 OK
  @retval 1 Error
*/

1097
my_bool translog_read_file_header(LOGHANDLER_FILE_INFO *desc, File file)
1098
{
1099
  uchar page_buff[LOG_HEADER_DATA_SIZE];
1100 1101
  DBUG_ENTER("translog_read_file_header");

1102
  if (my_pread(file, page_buff,
1103 1104 1105 1106 1107
               sizeof(page_buff), 0, MYF(MY_FNABP | MY_WME)))
  {
    DBUG_PRINT("info", ("log read fail error: %d", my_errno));
    DBUG_RETURN(1);
  }
1108
  translog_interpret_file_header(desc, page_buff);
unknown's avatar
unknown committed
1109
  DBUG_PRINT("info", ("timestamp: %llu  maria ver: %lu mysql ver: %lu  "
1110
                      "server id %lu page size %lu file number %lu  "
unknown's avatar
unknown committed
1111 1112 1113 1114 1115 1116 1117
                      "max lsn: (%lu,0x%lx)",
                      (ulonglong) desc->timestamp,
                      (ulong) desc->maria_version,
                      (ulong) desc->mysql_version,
                      (ulong) desc->server_id,
                      desc->page_size, (ulong) desc->file_number,
                      LSN_IN_PARTS(desc->max_lsn)));
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
  DBUG_RETURN(0);
}


/*
  @brief set the lsn to the files from_file - to_file if it is greater
  then written in the file

  @param from_file       first file number (min)
  @param to_file         last file number (max)
  @param lsn             the lsn for writing
  @param is_locked       true if current thread locked the log handler

  @retval 0 OK
  @retval 1 Error
*/

1135
static my_bool translog_set_lsn_for_files(uint32 from_file, uint32 to_file,
1136 1137
                                          LSN lsn, my_bool is_locked)
{
1138
  uint32 file;
1139 1140
  DBUG_ENTER("translog_set_lsn_for_files");
  DBUG_PRINT("enter", ("From: %lu  to: %lu  lsn: (%lu,0x%lx)  locked: %d",
1141
                       (ulong) from_file, (ulong) to_file,
unknown's avatar
unknown committed
1142
                       LSN_IN_PARTS(lsn),
1143 1144 1145 1146 1147 1148 1149
                       is_locked));
  DBUG_ASSERT(from_file <= to_file);
  DBUG_ASSERT(from_file > 0); /* we have not file 0 */

  /* Checks the current file (not finished yet file) */
  if (!is_locked)
    translog_lock();
1150
  if (to_file == (uint32) LSN_FILE_NO(log_descriptor.horizon))
1151 1152 1153 1154 1155 1156 1157 1158 1159
  {
    if (likely(cmp_translog_addr(lsn, log_descriptor.max_lsn) > 0))
      log_descriptor.max_lsn= lsn;
    to_file--;
  }
  if (!is_locked)
    translog_unlock();

  /* Checks finished files if they are */
1160
  pthread_mutex_lock(&log_descriptor.file_header_lock);
1161 1162 1163 1164
  for (file= from_file; file <= to_file; file++)
  {
    LOGHANDLER_FILE_INFO info;
    File fd= open_logfile_by_number_no_cache(file);
1165 1166 1167 1168 1169
    if ((fd < 0) ||
        ((translog_read_file_header(&info, fd) ||
          (cmp_translog_addr(lsn, info.max_lsn) > 0 &&
           translog_max_lsn_to_header(fd, lsn))) |
          my_close(fd, MYF(MY_WME))))
1170 1171
    {
      translog_stop_writing();
1172
      DBUG_RETURN(1);
1173
    }
1174
  }
1175
  pthread_mutex_unlock(&log_descriptor.file_header_lock);
1176

1177 1178 1179 1180
  DBUG_RETURN(0);
}


1181 1182 1183
/* descriptor of file in unfinished_files */
struct st_file_counter
{
1184 1185
  uint32 file;            /* file number */
  uint32 counter;         /* counter for started writes */
1186 1187 1188 1189 1190 1191 1192 1193 1194
};


/*
  @brief mark file "in progress" (for multi-group records)

  @param file            log file number
*/

1195
static void translog_mark_file_unfinished(uint32 file)
1196 1197 1198 1199 1200
{
  int place, i;
  struct st_file_counter fc, *fc_ptr;

  DBUG_ENTER("translog_mark_file_unfinished");
1201
  DBUG_PRINT("enter", ("file: %lu", (ulong) file));
1202

unknown's avatar
unknown committed
1203
  fc.file= file; fc.counter= 1;
1204
  pthread_mutex_lock(&log_descriptor.unfinished_files_lock);
1205 1206 1207 1208 1209 1210 1211 1212

  if (log_descriptor.unfinished_files.elements == 0)
  {
    insert_dynamic(&log_descriptor.unfinished_files, (uchar*) &fc);
    DBUG_PRINT("info", ("The first element inserted"));
    goto end;
  }

1213
  for (place= log_descriptor.unfinished_files.elements - 1;
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
       place >= 0;
       place--)
  {
    fc_ptr= dynamic_element(&log_descriptor.unfinished_files,
                            place, struct st_file_counter *);
    if (fc_ptr->file <= file)
      break;
  }

  if (place >= 0 && fc_ptr->file == file)
  {
     fc_ptr->counter++;
     DBUG_PRINT("info", ("counter increased"));
     goto end;
  }

  if (place == (int)log_descriptor.unfinished_files.elements)
  {
    insert_dynamic(&log_descriptor.unfinished_files, (uchar*) &fc);
    DBUG_PRINT("info", ("The last element inserted"));
    goto end;
  }
  /* shift and assign new element */
  insert_dynamic(&log_descriptor.unfinished_files,
                 (uchar*)
                 dynamic_element(&log_descriptor.unfinished_files,
                                 log_descriptor.unfinished_files.elements- 1,
                                 struct st_file_counter *));
  for(i= log_descriptor.unfinished_files.elements - 1; i > place; i--)
  {
    /* we do not use set_dynamic() to avoid unneeded checks */
    memcpy(dynamic_element(&log_descriptor.unfinished_files,
                           i, struct st_file_counter *),
           dynamic_element(&log_descriptor.unfinished_files,
                           i + 1, struct st_file_counter *),
           sizeof(struct st_file_counter));
  }
  memcpy(dynamic_element(&log_descriptor.unfinished_files,
                         place + 1, struct st_file_counter *),
         &fc, sizeof(struct st_file_counter));
end:
1255
  pthread_mutex_unlock(&log_descriptor.unfinished_files_lock);
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
  DBUG_VOID_RETURN;
}


/*
  @brief remove file mark "in progress" (for multi-group records)

  @param file            log file number
*/

1266
static void translog_mark_file_finished(uint32 file)
1267 1268 1269 1270
{
  int i;
  struct st_file_counter *fc_ptr;
  DBUG_ENTER("translog_mark_file_finished");
1271
  DBUG_PRINT("enter", ("file: %lu", (ulong) file));
1272

unknown's avatar
unknown committed
1273 1274
  LINT_INIT(fc_ptr);

1275
  pthread_mutex_lock(&log_descriptor.unfinished_files_lock);
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292

  DBUG_ASSERT(log_descriptor.unfinished_files.elements > 0);
  for (i= 0;
       i < (int) log_descriptor.unfinished_files.elements;
       i++)
  {
    fc_ptr= dynamic_element(&log_descriptor.unfinished_files,
                            i, struct st_file_counter *);
    if (fc_ptr->file == file)
    {
      break;
    }
  }
  DBUG_ASSERT(i < (int) log_descriptor.unfinished_files.elements);

  if (! --fc_ptr->counter)
    delete_dynamic_element(&log_descriptor.unfinished_files, i);
1293
  pthread_mutex_unlock(&log_descriptor.unfinished_files_lock);
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
  DBUG_VOID_RETURN;
}


/*
  @brief get max LSN of the record which parts stored in this file

  @param file            file number

  @return requested LSN or LSN_IMPOSSIBLE/LSN_ERROR
    @retval LSN_IMPOSSIBLE File is still not finished
    @retval LSN_ERROR Error opening file
    @retval # LSN of the record which parts stored in this file
*/

1309
LSN translog_get_file_max_lsn_stored(uint32 file)
1310
{
1311
  uint32 limit= FILENO_IMPOSSIBLE;
1312
  DBUG_ENTER("translog_get_file_max_lsn_stored");
1313
  DBUG_PRINT("enter", ("file: %lu", (ulong)file));
1314 1315
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
1316

1317
  pthread_mutex_lock(&log_descriptor.unfinished_files_lock);
1318 1319 1320 1321 1322 1323 1324 1325 1326

  /* find file with minimum file number "in progress" */
  if (log_descriptor.unfinished_files.elements > 0)
  {
    struct st_file_counter *fc_ptr;
    fc_ptr= dynamic_element(&log_descriptor.unfinished_files,
                            0, struct st_file_counter *);
    limit= fc_ptr->file; /* minimal file number "in progress" */
  }
1327
  pthread_mutex_unlock(&log_descriptor.unfinished_files_lock);
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347

  /*
    if there is no "in progress file" then unfinished file is in progress
    for sure
  */
  if (limit == FILENO_IMPOSSIBLE)
  {
    TRANSLOG_ADDRESS horizon= translog_get_horizon();
    limit= LSN_FILE_NO(horizon);
  }

  if (file >= limit)
  {
    DBUG_PRINT("info", ("The file in in progress"));
    DBUG_RETURN(LSN_IMPOSSIBLE);
  }

  {
    LOGHANDLER_FILE_INFO info;
    File fd= open_logfile_by_number_no_cache(file);
1348 1349
    if ((fd < 0) ||
        (translog_read_file_header(&info, fd) | my_close(fd, MYF(MY_WME))))
1350 1351 1352 1353
    {
      DBUG_PRINT("error", ("Can't read file header"));
      DBUG_RETURN(LSN_ERROR);
    }
unknown's avatar
unknown committed
1354
    DBUG_PRINT("info", ("Max lsn: (%lu,0x%lx)",
unknown's avatar
unknown committed
1355
                         LSN_IN_PARTS(info.max_lsn)));
1356 1357 1358 1359
    DBUG_RETURN(info.max_lsn);
  }
}

1360 1361 1362 1363 1364 1365 1366 1367
/*
  Initialize transaction log file buffer

  SYNOPSIS
    translog_buffer_init()
    buffer               The buffer to initialize

  RETURN
unknown's avatar
unknown committed
1368 1369
    0  OK
    1  Error
1370 1371
*/

1372
static my_bool translog_buffer_init(struct st_translog_buffer *buffer)
1373 1374
{
  DBUG_ENTER("translog_buffer_init");
unknown's avatar
unknown committed
1375
  buffer->last_lsn= LSN_IMPOSSIBLE;
1376
  /* This Buffer File */
unknown's avatar
unknown committed
1377
  buffer->file= NULL;
1378
  buffer->overlay= 0;
1379
  /* cache for current log */
unknown's avatar
unknown committed
1380
  memset(buffer->buffer, TRANSLOG_FILLER, TRANSLOG_WRITE_BUFFER);
1381 1382 1383
  /* Buffer size */
  buffer->size= 0;
  /* cond of thread which is waiting for buffer filling */
unknown's avatar
unknown committed
1384 1385
  if (pthread_cond_init(&buffer->waiting_filling_buffer, 0))
    DBUG_RETURN(1);
1386
  /* Number of records which are in copy progress */
1387 1388 1389 1390 1391 1392
  buffer->copy_to_buffer_in_progress= 0;
  /* list of waiting buffer ready threads */
  buffer->waiting_flush= 0;
  /* lock for the buffer. Current buffer also lock the handler */
  if (pthread_mutex_init(&buffer->mutex, MY_MUTEX_INIT_FAST))
    DBUG_RETURN(1);
1393 1394
  buffer->is_closing_buffer= 0;
  buffer->ver= 0;
1395 1396 1397 1398 1399
  DBUG_RETURN(0);
}


/*
unknown's avatar
unknown committed
1400
  @brief close transaction log file by descriptor
1401

unknown's avatar
unknown committed
1402
  @param file            pagegecache file descriptor reference
1403

unknown's avatar
unknown committed
1404 1405 1406
  @return Operation status
    @retval 0  OK
    @retval 1  Error
1407 1408
*/

unknown's avatar
unknown committed
1409
static my_bool translog_close_log_file(TRANSLOG_FILE *file)
1410
{
unknown's avatar
unknown committed
1411 1412 1413
  int rc= 0;
  flush_pagecache_blocks(log_descriptor.pagecache, &file->handler,
                         FLUSH_RELEASE);
unknown's avatar
unknown committed
1414 1415 1416 1417
  /*
    Sync file when we close it
    TODO: sync only we have changed the log
  */
unknown's avatar
unknown committed
1418 1419 1420 1421
  if (!file->is_sync)
    rc= my_sync(file->handler.file, MYF(MY_WME));
  rc|= my_close(file->handler.file, MYF(MY_WME));
  my_free(file, MYF(0));
unknown's avatar
unknown committed
1422
  return test(rc);
1423 1424 1425
}


unknown's avatar
unknown committed
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
/**
  @brief Dummy function for write failure (the log to not use
  pagecache writing)
*/

void translog_dummy_write_failure(uchar *data __attribute__((unused)))
{
  return;
}


unknown's avatar
unknown committed
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
/**
  @brief Initializes TRANSLOG_FILE structure

  @param file            reference on the file to initialize
  @param number          file number
  @param is_sync         is file synced on disk
*/

static void translog_file_init(TRANSLOG_FILE *file, uint32 number,
                               my_bool is_sync)
{
  pagecache_file_init(file->handler, &translog_page_validator,
unknown's avatar
unknown committed
1449
                      &translog_dummy_callback,
1450 1451
                      &translog_dummy_write_failure,
                      maria_flush_log_for_page_none, file);
unknown's avatar
unknown committed
1452 1453 1454 1455 1456 1457
  file->number= number;
  file->was_recovered= 0;
  file->is_sync= is_sync;
}


1458 1459
/**
  @brief Create and fill header of new file.
1460

1461 1462 1463
  @note the caller must call it right after it has increased
   log_descriptor.horizon to the new file
   (log_descriptor.horizon+= LSN_ONE_FILE)
1464

1465 1466 1467

  @retval 0 OK
  @retval 1 Error
1468 1469
*/

1470
static my_bool translog_create_new_file()
1471
{
unknown's avatar
unknown committed
1472 1473 1474 1475
  TRANSLOG_FILE *file= (TRANSLOG_FILE*)my_malloc(sizeof(TRANSLOG_FILE),
                                                 MYF(0));

  TRANSLOG_FILE *old= get_current_logfile();
1476
  uint32 file_no= LSN_FILE_NO(log_descriptor.horizon);
1477 1478
  DBUG_ENTER("translog_create_new_file");

unknown's avatar
unknown committed
1479
  if (file == NULL)
1480
    goto error;
1481 1482

  /*
1483 1484 1485 1486
    Writes max_lsn to the file header before finishing it (there is no need
    to lock file header buffer because it is still unfinished file, so only
    one thread can finish the file and nobody interested of LSN of current
    (unfinished) file, because no one can purge it).
1487
  */
unknown's avatar
unknown committed
1488
  if (translog_max_lsn_to_header(old->handler.file, log_descriptor.max_lsn))
1489
    goto error;
1490

unknown's avatar
unknown committed
1491 1492 1493 1494 1495 1496
  rw_wrlock(&log_descriptor.open_files_lock);
  DBUG_ASSERT(log_descriptor.max_file - log_descriptor.min_file + 1 ==
              log_descriptor.open_files.elements);
  DBUG_ASSERT(file_no == log_descriptor.max_file + 1);
  if (allocate_dynamic(&log_descriptor.open_files,
                       log_descriptor.max_file - log_descriptor.min_file + 2))
1497
    goto error_lock;
unknown's avatar
unknown committed
1498 1499
  if ((file->handler.file=
       create_logfile_by_number_no_cache(file_no)) == -1)
1500
    goto error_lock;
unknown's avatar
unknown committed
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
  translog_file_init(file, file_no, 0);

  /* this call just expand the array */
  insert_dynamic(&log_descriptor.open_files, (uchar*)&file);
  log_descriptor.max_file++;
  {
    char *start= (char*) dynamic_element(&log_descriptor.open_files, 0,
                                         TRANSLOG_FILE**);
    memmove(start + sizeof(TRANSLOG_FILE*), start,
            sizeof(TRANSLOG_FILE*) *
            (log_descriptor.max_file - log_descriptor.min_file + 1 - 1));
  }
  /* can't fail we because we expanded array */
  set_dynamic(&log_descriptor.open_files, (uchar*)&file, 0);
  DBUG_ASSERT(log_descriptor.max_file - log_descriptor.min_file + 1 ==
              log_descriptor.open_files.elements);
  rw_unlock(&log_descriptor.open_files_lock);

  DBUG_PRINT("info", ("file_no: %lu", (ulong)file_no));

  if (translog_write_file_header())
1522 1523
    DBUG_RETURN(1);

1524 1525
  if (ma_control_file_write_and_force(last_checkpoint_lsn, file_no,
                                      max_trid_in_control_file))
1526 1527
  {
    translog_stop_writing();
1528
    DBUG_RETURN(1);
1529
  }
1530 1531

  DBUG_RETURN(0);
unknown's avatar
unknown committed
1532

1533
error_lock:
unknown's avatar
unknown committed
1534
  rw_unlock(&log_descriptor.open_files_lock);
1535 1536
error:
  translog_stop_writing();
unknown's avatar
unknown committed
1537
  DBUG_RETURN(1);
1538 1539 1540
}


unknown's avatar
unknown committed
1541 1542
/**
  @brief Locks the loghandler buffer.
1543

unknown's avatar
unknown committed
1544
  @param buffer          This buffer which should be locked
1545

unknown's avatar
unknown committed
1546 1547 1548 1549
  @note See comment before buffer 'mutex' variable.

  @retval 0 OK
  @retval 1 Error
1550 1551
*/

1552
static void translog_buffer_lock(struct st_translog_buffer *buffer)
1553 1554
{
  DBUG_ENTER("translog_buffer_lock");
unknown's avatar
unknown committed
1555
  DBUG_PRINT("enter",
1556 1557
             ("Lock buffer #%u: (0x%lx)", (uint) buffer->buffer_no,
              (ulong) buffer));
1558 1559
  pthread_mutex_lock(&buffer->mutex);
  DBUG_VOID_RETURN;
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
}


/*
  Unlock the loghandler buffer

  SYNOPSIS
    translog_buffer_unlock()
    buffer               This buffer which should be unlocked

  RETURN
unknown's avatar
unknown committed
1571 1572
    0  OK
    1  Error
1573 1574
*/

1575
static void translog_buffer_unlock(struct st_translog_buffer *buffer)
1576 1577
{
  DBUG_ENTER("translog_buffer_unlock");
1578 1579
  DBUG_PRINT("enter", ("Unlock buffer... #%u (0x%lx)",
                       (uint) buffer->buffer_no, (ulong) buffer));
1580

1581 1582
  pthread_mutex_unlock(&buffer->mutex);
  DBUG_VOID_RETURN;
1583 1584 1585 1586
}


/*
unknown's avatar
unknown committed
1587
  Write a header on the page
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597

  SYNOPSIS
    translog_new_page_header()
    horizon              Where to write the page
    cursor               Where to write the page

  NOTE
    - space for page header should be checked before
*/

1598 1599
static uchar translog_sector_random;

1600 1601 1602
static void translog_new_page_header(TRANSLOG_ADDRESS *horizon,
                                     struct st_buffer_cursor *cursor)
{
unknown's avatar
unknown committed
1603
  uchar *ptr;
1604 1605

  DBUG_ENTER("translog_new_page_header");
unknown's avatar
unknown committed
1606
  DBUG_ASSERT(cursor->ptr);
1607 1608 1609 1610 1611

  cursor->protected= 0;

  ptr= cursor->ptr;
  /* Page number */
1612 1613
  int3store(ptr, LSN_OFFSET(*horizon) / TRANSLOG_PAGE_SIZE);
  ptr+= 3;
1614
  /* File number */
1615 1616
  int3store(ptr, LSN_FILE_NO(*horizon));
  ptr+= 3;
unknown's avatar
unknown committed
1617 1618 1619
  DBUG_ASSERT(TRANSLOG_PAGE_FLAGS == (ptr - cursor->ptr));
  cursor->ptr[TRANSLOG_PAGE_FLAGS]= (uchar) log_descriptor.flags;
  ptr++;
1620 1621 1622 1623
  if (log_descriptor.flags & TRANSLOG_PAGE_CRC)
  {
#ifndef DBUG_OFF
    DBUG_PRINT("info", ("write  0x11223344 CRC to (%lu,0x%lx)",
unknown's avatar
unknown committed
1624
                        LSN_IN_PARTS(*horizon)));
unknown's avatar
unknown committed
1625
    /* This will be overwritten by real CRC; This is just for debugging */
1626 1627
    int4store(ptr, 0x11223344);
#endif
unknown's avatar
unknown committed
1628
    /* CRC will be put when page is finished */
unknown's avatar
unknown committed
1629
    ptr+= CRC_SIZE;
1630 1631 1632
  }
  if (log_descriptor.flags & TRANSLOG_SECTOR_PROTECTION)
  {
1633
    /*
1634 1635 1636
      translog_sector_randmo works like "random" values producer because
      it is enough to have such "random" for this purpose and it will
      not interfere with higher level pseudo random value generator
1637
    */
1638
    ptr[0]= translog_sector_random++;
unknown's avatar
unknown committed
1639
    ptr+= TRANSLOG_PAGE_SIZE / DISK_DRIVE_SECTOR_SIZE;
1640 1641
  }
  {
unknown's avatar
unknown committed
1642
    uint len= (ptr - cursor->ptr);
1643
    (*horizon)+= len; /* increasing the offset part of the address */
unknown's avatar
unknown committed
1644
    cursor->current_page_fill= len;
1645 1646 1647 1648
    if (!cursor->chaser)
      cursor->buffer->size+= len;
  }
  cursor->ptr= ptr;
unknown's avatar
unknown committed
1649 1650
  DBUG_PRINT("info", ("NewP buffer #%u: 0x%lx  chaser: %d  Size: %lu (%lu)  "
                      "Horizon: (%lu,0x%lu)",
1651 1652
                      (uint) cursor->buffer->buffer_no, (ulong) cursor->buffer,
                      cursor->chaser, (ulong) cursor->buffer->size,
unknown's avatar
unknown committed
1653 1654
                      (ulong) (cursor->ptr - cursor->buffer->buffer),
                      LSN_IN_PARTS(*horizon)));
unknown's avatar
unknown committed
1655
  translog_check_cursor(cursor);
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
  DBUG_VOID_RETURN;
}


/*
  Put sector protection on the page image

  SYNOPSIS
    translog_put_sector_protection()
    page                 reference on the page content
    cursor               cursor of the buffer
unknown's avatar
unknown committed
1667 1668 1669 1670

  NOTES
    We put a sector protection on all following sectors on the page,
    except the first sector that is protected by page header.
1671 1672
*/

unknown's avatar
unknown committed
1673
static void translog_put_sector_protection(uchar *page,
1674 1675
                                           struct st_buffer_cursor *cursor)
{
unknown's avatar
unknown committed
1676
  uchar *table= page + log_descriptor.page_overhead -
unknown's avatar
unknown committed
1677 1678
    TRANSLOG_PAGE_SIZE / DISK_DRIVE_SECTOR_SIZE;
  uint i, offset;
unknown's avatar
unknown committed
1679 1680 1681
  uint16 last_protected_sector= ((cursor->previous_offset - 1) /
                                 DISK_DRIVE_SECTOR_SIZE);
  uint16 start_sector= cursor->previous_offset / DISK_DRIVE_SECTOR_SIZE;
unknown's avatar
unknown committed
1682
  uint8 value= table[0] + cursor->write_counter;
1683
  DBUG_ENTER("translog_put_sector_protection");
unknown's avatar
unknown committed
1684

1685
  if (start_sector == 0)
unknown's avatar
unknown committed
1686 1687 1688 1689
  {
    /* First sector is protected by file & page numbers in the page header. */
    start_sector= 1;
  }
1690

unknown's avatar
unknown committed
1691 1692
  DBUG_PRINT("enter", ("Write counter:%u  value:%u  offset:%u, "
                       "last protected:%u  start sector:%u",
1693 1694 1695 1696 1697 1698
                       (uint) cursor->write_counter,
                       (uint) value,
                       (uint) cursor->previous_offset,
                       (uint) last_protected_sector, (uint) start_sector));
  if (last_protected_sector == start_sector)
  {
unknown's avatar
unknown committed
1699
    i= last_protected_sector;
unknown's avatar
unknown committed
1700
    offset= last_protected_sector * DISK_DRIVE_SECTOR_SIZE;
1701 1702 1703 1704
    /* restore data, because we modified sector which was protected */
    if (offset < cursor->previous_offset)
      page[offset]= table[i];
  }
unknown's avatar
unknown committed
1705 1706 1707
  for (i= start_sector, offset= start_sector * DISK_DRIVE_SECTOR_SIZE;
       i < TRANSLOG_PAGE_SIZE / DISK_DRIVE_SECTOR_SIZE;
       i++, (offset+= DISK_DRIVE_SECTOR_SIZE))
1708
  {
unknown's avatar
unknown committed
1709 1710
    DBUG_PRINT("info", ("sector:%u  offset:%u  data 0x%x",
                        i, offset, (uint) page[offset]));
1711
    table[i]= page[offset];
unknown's avatar
unknown committed
1712 1713 1714
    page[offset]= value;
    DBUG_PRINT("info", ("sector:%u  offset:%u  data 0x%x",
                        i, offset, (uint) page[offset]));
1715 1716 1717 1718 1719 1720
  }
  DBUG_VOID_RETURN;
}


/*
unknown's avatar
unknown committed
1721
  Calculate CRC32 of given area
1722 1723

  SYNOPSIS
unknown's avatar
unknown committed
1724
    translog_crc()
1725 1726 1727 1728
    area                 Pointer of the area beginning
    length               The Area length

  RETURN
unknown's avatar
unknown committed
1729
    CRC32
1730 1731
*/

unknown's avatar
unknown committed
1732
static uint32 translog_crc(uchar *area, uint length)
1733
{
1734 1735
  DBUG_ENTER("translog_crc");
  DBUG_RETURN(crc32(0L, (unsigned char*) area, length));
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
}


/*
  Finish current page with zeros

  SYNOPSIS
    translog_finish_page()
    horizon              \ horizon & buffer pointers
    cursor               /
*/

static void translog_finish_page(TRANSLOG_ADDRESS *horizon,
                                 struct st_buffer_cursor *cursor)
{
unknown's avatar
unknown committed
1751
  uint16 left= TRANSLOG_PAGE_SIZE - cursor->current_page_fill;
unknown's avatar
unknown committed
1752
  uchar *page= cursor->ptr - cursor->current_page_fill;
1753
  DBUG_ENTER("translog_finish_page");
unknown's avatar
unknown committed
1754 1755 1756 1757
  DBUG_PRINT("enter", ("Buffer: #%u 0x%lx  "
                       "Buffer addr: (%lu,0x%lx)  "
                       "Page addr: (%lu,0x%lx)  "
                       "size:%lu (%lu)  Pg:%u  left:%u",
1758
                       (uint) cursor->buffer_no, (ulong) cursor->buffer,
unknown's avatar
unknown committed
1759
                       LSN_IN_PARTS(cursor->buffer->offset),
1760 1761
                       (ulong) LSN_FILE_NO(*horizon),
                       (ulong) (LSN_OFFSET(*horizon) -
unknown's avatar
unknown committed
1762
                                cursor->current_page_fill),
1763 1764
                       (ulong) cursor->buffer->size,
                       (ulong) (cursor->ptr -cursor->buffer->buffer),
unknown's avatar
unknown committed
1765
                       (uint) cursor->current_page_fill, (uint) left));
1766
  DBUG_ASSERT(LSN_FILE_NO(*horizon) == LSN_FILE_NO(cursor->buffer->offset));
unknown's avatar
unknown committed
1767
  translog_check_cursor(cursor);
1768 1769 1770 1771 1772
  if (cursor->protected)
  {
    DBUG_PRINT("info", ("Already protected and finished"));
    DBUG_VOID_RETURN;
  }
unknown's avatar
unknown committed
1773 1774 1775 1776
  cursor->protected= 1;

  DBUG_ASSERT(left < TRANSLOG_PAGE_SIZE);
  if (left != 0)
1777
  {
unknown's avatar
unknown committed
1778
    DBUG_PRINT("info", ("left: %u", (uint) left));
unknown's avatar
unknown committed
1779
    memset(cursor->ptr, TRANSLOG_FILLER, left);
1780
    cursor->ptr+= left;
unknown's avatar
unknown committed
1781
    (*horizon)+= left; /* offset increasing */
1782 1783
    if (!cursor->chaser)
      cursor->buffer->size+= left;
1784
    /* We are finishing the page so reset the counter */
unknown's avatar
unknown committed
1785 1786 1787
    cursor->current_page_fill= 0;
    DBUG_PRINT("info", ("Finish Page buffer #%u: 0x%lx  "
                        "chaser: %d  Size: %lu (%lu)",
1788 1789 1790
                        (uint) cursor->buffer->buffer_no,
                        (ulong) cursor->buffer, cursor->chaser,
                        (ulong) cursor->buffer->size,
unknown's avatar
unknown committed
1791
                        (ulong) (cursor->ptr - cursor->buffer->buffer)));
unknown's avatar
unknown committed
1792
    translog_check_cursor(cursor);
1793
  }
unknown's avatar
unknown committed
1794 1795
  /*
    When we are finishing the page other thread might not finish the page
1796 1797
    header yet (in case if we started from the middle of the page) so we
    have to read log_descriptor.flags but not the flags from the page.
unknown's avatar
unknown committed
1798 1799
  */
  if (log_descriptor.flags & TRANSLOG_SECTOR_PROTECTION)
1800 1801 1802 1803 1804 1805
  {
    translog_put_sector_protection(page, cursor);
    DBUG_PRINT("info", ("drop write_counter"));
    cursor->write_counter= 0;
    cursor->previous_offset= 0;
  }
unknown's avatar
unknown committed
1806
  if (log_descriptor.flags & TRANSLOG_PAGE_CRC)
1807
  {
unknown's avatar
unknown committed
1808 1809 1810 1811 1812
    uint32 crc= translog_crc(page + log_descriptor.page_overhead,
                             TRANSLOG_PAGE_SIZE -
                             log_descriptor.page_overhead);
    DBUG_PRINT("info", ("CRC: %lx", (ulong) crc));
    /* We have page number, file number and flag before crc */
1813 1814 1815 1816 1817 1818
    int4store(page + 3 + 3 + 1, crc);
  }
  DBUG_VOID_RETURN;
}


1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
/*
  @brief Wait until all threads have finished closing this buffer.

  @param buffer          This buffer should be check
*/

static void translog_wait_for_closing(struct st_translog_buffer *buffer)
{
  DBUG_ENTER("translog_wait_for_closing");
  DBUG_PRINT("enter", ("Buffer #%u 0x%lx  copies in progress: %u  "
                       "is closing %u  File: %d  size: %lu",
                       (uint) buffer->buffer_no, (ulong) buffer,
                       (uint) buffer->copy_to_buffer_in_progress,
                       (uint) buffer->is_closing_buffer,
                       (buffer->file ? buffer->file->handler.file : -1),
                       (ulong) buffer->size));
  translog_buffer_lock_assert_owner(buffer);

  while (buffer->is_closing_buffer)
  {
    DBUG_PRINT("info", ("wait for writers... buffer: #%u  0x%lx",
                        (uint) buffer->buffer_no, (ulong) buffer));
    DBUG_ASSERT(buffer->file != NULL);
    pthread_cond_wait(&buffer->waiting_filling_buffer, &buffer->mutex);
    DBUG_PRINT("info", ("wait for writers done buffer: #%u  0x%lx",
                        (uint) buffer->buffer_no, (ulong) buffer));
  }

  DBUG_VOID_RETURN;
}


1851
/*
1852
  @brief Wait until all threads have finished filling this buffer.
1853

1854
  @param buffer          This buffer should be check
1855
*/
1856

1857 1858 1859
static void translog_wait_for_writers(struct st_translog_buffer *buffer)
{
  DBUG_ENTER("translog_wait_for_writers");
1860 1861
  DBUG_PRINT("enter", ("Buffer #%u 0x%lx  copies in progress: %u  "
                       "is closing %u  File: %d  size: %lu",
1862
                       (uint) buffer->buffer_no, (ulong) buffer,
1863 1864 1865 1866
                       (uint) buffer->copy_to_buffer_in_progress,
                       (uint) buffer->is_closing_buffer,
                       (buffer->file ? buffer->file->handler.file : -1),
                       (ulong) buffer->size));
1867
  translog_buffer_lock_assert_owner(buffer);
1868

unknown's avatar
unknown committed
1869
  while (buffer->copy_to_buffer_in_progress)
1870
  {
1871 1872
    DBUG_PRINT("info", ("wait for writers... buffer: #%u  0x%lx",
                        (uint) buffer->buffer_no, (ulong) buffer));
unknown's avatar
unknown committed
1873
    DBUG_ASSERT(buffer->file != NULL);
unknown's avatar
unknown committed
1874
    pthread_cond_wait(&buffer->waiting_filling_buffer, &buffer->mutex);
1875 1876
    DBUG_PRINT("info", ("wait for writers done buffer: #%u  0x%lx",
                        (uint) buffer->buffer_no, (ulong) buffer));
unknown's avatar
unknown committed
1877
  }
1878 1879 1880 1881 1882 1883 1884

  DBUG_VOID_RETURN;
}


/*

unknown's avatar
unknown committed
1885
  Wait for buffer to become free
1886 1887 1888

  SYNOPSIS
    translog_wait_for_buffer_free()
unknown's avatar
unknown committed
1889
    buffer               The buffer we are waiting for
1890 1891 1892 1893 1894 1895 1896

  NOTE
    - this buffer should be locked
*/

static void translog_wait_for_buffer_free(struct st_translog_buffer *buffer)
{
1897 1898 1899
  TRANSLOG_ADDRESS offset= buffer->offset;
  TRANSLOG_FILE *file= buffer->file;
  uint8 ver= buffer->ver;
1900
  DBUG_ENTER("translog_wait_for_buffer_free");
1901 1902
  DBUG_PRINT("enter", ("Buffer #%u 0x%lx  copies in progress: %u  "
                       "is closing %u  File: %d  size: %lu",
1903
                       (uint) buffer->buffer_no, (ulong) buffer,
1904 1905
                       (uint) buffer->copy_to_buffer_in_progress,
                       (uint) buffer->is_closing_buffer,
unknown's avatar
unknown committed
1906 1907
                       (buffer->file ? buffer->file->handler.file : -1),
                       (ulong) buffer->size));
1908 1909 1910

  translog_wait_for_writers(buffer);

1911 1912 1913
  if (offset != buffer->offset || file != buffer->file || ver != buffer->ver)
    DBUG_VOID_RETURN; /* the buffer if already freed */

unknown's avatar
unknown committed
1914
  while (buffer->file != NULL)
1915
  {
1916 1917
    DBUG_PRINT("info", ("wait for writers... buffer: #%u  0x%lx",
                        (uint) buffer->buffer_no, (ulong) buffer));
unknown's avatar
unknown committed
1918
    pthread_cond_wait(&buffer->waiting_filling_buffer, &buffer->mutex);
1919 1920
    DBUG_PRINT("info", ("wait for writers done. buffer: #%u  0x%lx",
                        (uint) buffer->buffer_no, (ulong) buffer));
unknown's avatar
unknown committed
1921 1922
  }
  DBUG_ASSERT(buffer->copy_to_buffer_in_progress == 0);
1923 1924 1925 1926 1927
  DBUG_VOID_RETURN;
}


/*
unknown's avatar
unknown committed
1928
  Initialize the cursor for a buffer
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944

  SYNOPSIS
    translog_cursor_init()
    buffer               The buffer
    cursor               It's cursor
    buffer_no            Number of buffer
*/

static void translog_cursor_init(struct st_buffer_cursor *cursor,
                                 struct st_translog_buffer *buffer,
                                 uint8 buffer_no)
{
  DBUG_ENTER("translog_cursor_init");
  cursor->ptr= buffer->buffer;
  cursor->buffer= buffer;
  cursor->buffer_no= buffer_no;
unknown's avatar
unknown committed
1945
  cursor->current_page_fill= 0;
1946 1947 1948 1949 1950 1951 1952 1953 1954
  cursor->chaser= (cursor != &log_descriptor.bc);
  cursor->write_counter= 0;
  cursor->previous_offset= 0;
  cursor->protected= 0;
  DBUG_VOID_RETURN;
}


/*
1955
  @brief Initialize buffer for the current file, and a cursor for this buffer.
1956

1957 1958 1959
  @param buffer          The buffer
  @param cursor          It's cursor
  @param buffer_no       Number of buffer
1960
*/
1961

1962 1963
static void translog_start_buffer(struct st_translog_buffer *buffer,
                                  struct st_buffer_cursor *cursor,
unknown's avatar
unknown committed
1964
                                  uint buffer_no)
1965 1966 1967
{
  DBUG_ENTER("translog_start_buffer");
  DBUG_PRINT("enter",
unknown's avatar
unknown committed
1968
             ("Assign buffer: #%u (0x%lx) offset: 0x%lx(%lu)",
1969
              (uint) buffer->buffer_no, (ulong) buffer,
1970 1971
              (ulong) LSN_OFFSET(log_descriptor.horizon),
              (ulong) LSN_OFFSET(log_descriptor.horizon)));
1972
  DBUG_ASSERT(buffer_no == buffer->buffer_no);
unknown's avatar
unknown committed
1973
  buffer->last_lsn= LSN_IMPOSSIBLE;
1974
  buffer->offset= log_descriptor.horizon;
1975
  buffer->next_buffer_offset= LSN_IMPOSSIBLE;
unknown's avatar
unknown committed
1976
  buffer->file= get_current_logfile();
1977 1978 1979
  buffer->overlay= 0;
  buffer->size= 0;
  translog_cursor_init(cursor, buffer, buffer_no);
unknown's avatar
unknown committed
1980 1981 1982 1983
  DBUG_PRINT("info", ("file: #%ld (%d)  init cursor #%u: 0x%lx  "
                      "chaser: %d  Size: %lu (%lu)",
                      (long) (buffer->file ? buffer->file->number : 0),
                      (buffer->file ? buffer->file->handler.file : -1),
1984 1985
                      (uint) cursor->buffer->buffer_no, (ulong) cursor->buffer,
                      cursor->chaser, (ulong) cursor->buffer->size,
unknown's avatar
unknown committed
1986
                      (ulong) (cursor->ptr - cursor->buffer->buffer)));
unknown's avatar
unknown committed
1987
  translog_check_cursor(cursor);
1988 1989 1990 1991 1992
  DBUG_VOID_RETURN;
}


/*
1993
  @brief Switch to the next buffer in a chain.
1994

1995 1996 1997
  @param horizon         \ Pointers on current position in file and buffer
  @param cursor          /
  @param new_file        Also start new file
1998

1999
  @note
2000 2001 2002
   - loghandler should be locked
   - after return new and old buffer still are locked

2003 2004
  @retval 0 OK
  @retval 1 Error
2005 2006 2007 2008 2009 2010
*/

static my_bool translog_buffer_next(TRANSLOG_ADDRESS *horizon,
                                    struct st_buffer_cursor *cursor,
                                    my_bool new_file)
{
unknown's avatar
unknown committed
2011 2012
  uint old_buffer_no= cursor->buffer_no;
  uint new_buffer_no= (old_buffer_no + 1) % TRANSLOG_BUFFERS_NO;
2013 2014 2015 2016
  struct st_translog_buffer *new_buffer= log_descriptor.buffers + new_buffer_no;
  my_bool chasing= cursor->chaser;
  DBUG_ENTER("translog_buffer_next");

unknown's avatar
unknown committed
2017
  DBUG_PRINT("info", ("horizon: (%lu,0x%lx)  chasing: %d",
unknown's avatar
unknown committed
2018
                      LSN_IN_PARTS(log_descriptor.horizon), chasing));
2019 2020 2021 2022 2023 2024 2025 2026

  DBUG_ASSERT(cmp_translog_addr(log_descriptor.horizon, *horizon) >= 0);

  translog_finish_page(horizon, cursor);

  if (!chasing)
  {
    translog_buffer_lock(new_buffer);
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
#ifndef DBUG_OFF
    {
      TRANSLOG_ADDRESS offset= new_buffer->offset;
      TRANSLOG_FILE *file= new_buffer->file;
      uint8 ver= new_buffer->ver;
      translog_lock_assert_owner();
#endif
      translog_wait_for_buffer_free(new_buffer);
#ifndef DBUG_OFF
      /* We keep the handler locked so nobody can start this new buffer */
unknown's avatar
unknown committed
2037 2038
      DBUG_ASSERT(offset == new_buffer->offset && new_buffer->file == NULL &&
                  (file == NULL ? ver : (uint8)(ver + 1)) == new_buffer->ver);
2039 2040
    }
#endif
2041 2042
  }
  else
unknown's avatar
unknown committed
2043
    DBUG_ASSERT(new_buffer->file != NULL);
2044

2045 2046
  if (new_file)
  {
2047

2048
    /* move the horizon to the next file and its header page */
unknown's avatar
unknown committed
2049 2050
    (*horizon)+= LSN_ONE_FILE;
    (*horizon)= LSN_REPLACE_OFFSET(*horizon, TRANSLOG_PAGE_SIZE);
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060
    if (!chasing && translog_create_new_file())
    {
      DBUG_RETURN(1);
    }
  }

  /* prepare next page */
  if (chasing)
    translog_cursor_init(cursor, new_buffer, new_buffer_no);
  else
2061 2062
  {
    translog_lock_assert_owner();
2063
    translog_start_buffer(new_buffer, cursor, new_buffer_no);
2064
  }
2065
  log_descriptor.buffers[old_buffer_no].next_buffer_offset= new_buffer->offset;
2066 2067 2068 2069 2070 2071
  translog_new_page_header(horizon, cursor);
  DBUG_RETURN(0);
}


/*
2072
  Sets max LSN sent to file, and address from which data is only in the buffer
2073 2074

  SYNOPSIS
2075
    translog_set_sent_to_disk()
2076
    lsn                  LSN to assign
2077 2078 2079
    in_buffers           to assign to in_buffers_only

  TODO: use atomic operations if possible (64bit architectures?)
2080 2081
*/

2082
static void translog_set_sent_to_disk(LSN lsn, TRANSLOG_ADDRESS in_buffers)
2083
{
2084
  DBUG_ENTER("translog_set_sent_to_disk");
2085
  pthread_mutex_lock(&log_descriptor.sent_to_disk_lock);
2086
  DBUG_PRINT("enter", ("lsn: (%lu,0x%lx) in_buffers: (%lu,0x%lx)  "
2087
                       "in_buffers_only: (%lu,0x%lx)  start: (%lu,0x%lx)  "
unknown's avatar
unknown committed
2088
                       "sent_to_disk: (%lu,0x%lx)",
unknown's avatar
unknown committed
2089 2090
                       LSN_IN_PARTS(lsn),
                       LSN_IN_PARTS(in_buffers),
2091
                       LSN_IN_PARTS(log_descriptor.log_start),
unknown's avatar
unknown committed
2092 2093
                       LSN_IN_PARTS(log_descriptor.in_buffers_only),
                       LSN_IN_PARTS(log_descriptor.sent_to_disk)));
2094 2095 2096 2097 2098 2099 2100
  /*
    We write sequentially (first part of following assert) but we rewrite
    the same page in case we started mysql and shut it down immediately
    (second part of the following assert)
  */
  DBUG_ASSERT(cmp_translog_addr(lsn, log_descriptor.sent_to_disk) >= 0 ||
              cmp_translog_addr(lsn, log_descriptor.log_start) < 0);
2101
  log_descriptor.sent_to_disk= lsn;
2102 2103 2104 2105 2106 2107
  /* LSN_IMPOSSIBLE == 0 => it will work for very first time */
  if (cmp_translog_addr(in_buffers, log_descriptor.in_buffers_only) > 0)
  {
    log_descriptor.in_buffers_only= in_buffers;
    DBUG_PRINT("info", ("set new in_buffers_only"));
  }
2108
  pthread_mutex_unlock(&log_descriptor.sent_to_disk_lock);
2109 2110 2111 2112 2113
  DBUG_VOID_RETURN;
}


/*
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
  Sets address from which data is only in the buffer

  SYNOPSIS
    translog_set_only_in_buffers()
    lsn                  LSN to assign
    in_buffers           to assign to in_buffers_only
*/

static void translog_set_only_in_buffers(TRANSLOG_ADDRESS in_buffers)
{
  DBUG_ENTER("translog_set_only_in_buffers");
2125
  pthread_mutex_lock(&log_descriptor.sent_to_disk_lock);
2126 2127
  DBUG_PRINT("enter", ("in_buffers: (%lu,0x%lx)  "
                       "in_buffers_only: (%lu,0x%lx)",
unknown's avatar
unknown committed
2128 2129
                       LSN_IN_PARTS(in_buffers),
                       LSN_IN_PARTS(log_descriptor.in_buffers_only)));
2130 2131 2132
  /* LSN_IMPOSSIBLE == 0 => it will work for very first time */
  if (cmp_translog_addr(in_buffers, log_descriptor.in_buffers_only) > 0)
  {
2133 2134
    if (translog_status != TRANSLOG_OK)
      DBUG_VOID_RETURN;
2135 2136 2137
    log_descriptor.in_buffers_only= in_buffers;
    DBUG_PRINT("info", ("set new in_buffers_only"));
  }
2138
  pthread_mutex_unlock(&log_descriptor.sent_to_disk_lock);
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
  DBUG_VOID_RETURN;
}


/*
  Gets address from which data is only in the buffer

  SYNOPSIS
    translog_only_in_buffers()

  RETURN
    address from which data is only in the buffer
*/

static TRANSLOG_ADDRESS translog_only_in_buffers()
{
  register TRANSLOG_ADDRESS addr;
  DBUG_ENTER("translog_only_in_buffers");
2157
  pthread_mutex_lock(&log_descriptor.sent_to_disk_lock);
2158
  addr= log_descriptor.in_buffers_only;
2159
  pthread_mutex_unlock(&log_descriptor.sent_to_disk_lock);
2160 2161 2162 2163 2164 2165
  DBUG_RETURN(addr);
}


/*
  Get max LSN sent to file
2166 2167

  SYNOPSIS
2168
    translog_get_sent_to_disk()
2169 2170 2171

  RETURN
    max LSN send to file
2172 2173
*/

2174
static LSN translog_get_sent_to_disk()
2175
{
2176
  register LSN lsn;
2177
  DBUG_ENTER("translog_get_sent_to_disk");
2178
  pthread_mutex_lock(&log_descriptor.sent_to_disk_lock);
2179
  lsn= log_descriptor.sent_to_disk;
2180
  pthread_mutex_unlock(&log_descriptor.sent_to_disk_lock);
2181
  DBUG_RETURN(lsn);
2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
}


/*
  Get first chunk address on the given page

  SYNOPSIS
    translog_get_first_chunk_offset()
    page                 The page where to find first chunk

  RETURN
    first chunk offset
*/

unknown's avatar
unknown committed
2196
static my_bool translog_get_first_chunk_offset(uchar *page)
2197 2198
{
  DBUG_ENTER("translog_get_first_chunk_offset");
2199 2200
  DBUG_ASSERT(page[TRANSLOG_PAGE_FLAGS] < TRANSLOG_FLAGS_NUM);
  DBUG_RETURN(page_overhead[page[TRANSLOG_PAGE_FLAGS]]);
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
}


/*
  Write coded length of record

  SYNOPSIS
    translog_write_variable_record_1group_code_len
    dst                  Destination buffer pointer
    length               Length which should be coded
    header_len           Calculated total header length
*/

static void
unknown's avatar
unknown committed
2215
translog_write_variable_record_1group_code_len(uchar *dst,
2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
                                               translog_size_t length,
                                               uint16 header_len)
{
  switch (header_len) {
  case 6:                                      /* (5 + 1) */
    DBUG_ASSERT(length <= 250);
    *dst= (uint8) length;
    return;
  case 8:                                      /* (5 + 3) */
    DBUG_ASSERT(length <= 0xFFFF);
    *dst= 251;
    int2store(dst + 1, length);
    return;
  case 9:                                      /* (5 + 4) */
unknown's avatar
unknown committed
2230
    DBUG_ASSERT(length <= (ulong) 0xFFFFFF);
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
    *dst= 252;
    int3store(dst + 1, length);
    return;
  case 10:                                     /* (5 + 5) */
    *dst= 253;
    int4store(dst + 1, length);
    return;
  default:
    DBUG_ASSERT(0);
  }
  return;
}


/*
  Decode record data length and advance given pointer to the next field

  SYNOPSIS
    translog_variable_record_1group_decode_len()
    src                  The pointer to the pointer to the length beginning

  RETURN
    decoded length
*/

unknown's avatar
unknown committed
2256
static translog_size_t translog_variable_record_1group_decode_len(uchar **src)
2257 2258 2259 2260
{
  uint8 first= (uint8) (**src);
  switch (first) {
  case 251:
unknown's avatar
unknown committed
2261
    (*src)+= 3;
2262 2263
    return (uint2korr((*src) - 2));
  case 252:
unknown's avatar
unknown committed
2264
    (*src)+= 4;
2265 2266
    return (uint3korr((*src) - 3));
  case 253:
unknown's avatar
unknown committed
2267
    (*src)+= 5;
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291
    return (uint4korr((*src) - 4));
  case 254:
  case 255:
    DBUG_ASSERT(0);                             /* reserved for future use */
    return (0);
  default:
    (*src)++;
    return (first);
  }
}


/*
  Get total length of this chunk (not only body)

  SYNOPSIS
    translog_get_total_chunk_length()
    page                 The page where chunk placed
    offset               Offset of the chunk on this place

  RETURN
    total length of the chunk
*/

unknown's avatar
unknown committed
2292
static uint16 translog_get_total_chunk_length(uchar *page, uint16 offset)
2293 2294 2295
{
  DBUG_ENTER("translog_get_total_chunk_length");
  switch (page[offset] & TRANSLOG_CHUNK_TYPE) {
unknown's avatar
unknown committed
2296
  case TRANSLOG_CHUNK_LSN:
2297
  {
unknown's avatar
unknown committed
2298
    /* 0 chunk referred as LSN (head or tail) */
2299
    translog_size_t rec_len;
unknown's avatar
unknown committed
2300
    uchar *start= page + offset;
2301
    uchar *ptr= start + 1 + 2; /* chunk type and short trid */
2302 2303 2304 2305
    uint16 chunk_len, header_len, page_rest;
    DBUG_PRINT("info", ("TRANSLOG_CHUNK_LSN"));
    rec_len= translog_variable_record_1group_decode_len(&ptr);
    chunk_len= uint2korr(ptr);
2306
    header_len= (uint16) (ptr -start) + 2;
unknown's avatar
unknown committed
2307
    DBUG_PRINT("info", ("rec len: %lu  chunk len: %u  header len: %u",
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321
                        (ulong) rec_len, (uint) chunk_len, (uint) header_len));
    if (chunk_len)
    {
      DBUG_PRINT("info", ("chunk len: %u + %u = %u",
                          (uint) header_len, (uint) chunk_len,
                          (uint) (chunk_len + header_len)));
      DBUG_RETURN(chunk_len + header_len);
    }
    page_rest= TRANSLOG_PAGE_SIZE - offset;
    DBUG_PRINT("info", ("page_rest %u", (uint) page_rest));
    if (rec_len + header_len < page_rest)
      DBUG_RETURN(rec_len + header_len);
    DBUG_RETURN(page_rest);
  }
unknown's avatar
unknown committed
2322
  case TRANSLOG_CHUNK_FIXED:
2323
  {
unknown's avatar
unknown committed
2324
    uchar *ptr;
2325
    uint type= page[offset] & TRANSLOG_REC_TYPE;
unknown's avatar
unknown committed
2326 2327 2328 2329
    uint length;
    int i;
    /* 1 (pseudo)fixed record (also LSN) */
    DBUG_PRINT("info", ("TRANSLOG_CHUNK_FIXED"));
unknown's avatar
unknown committed
2330
    DBUG_ASSERT(log_record_type_descriptor[type].rclass ==
2331
                LOGRECTYPE_FIXEDLENGTH ||
unknown's avatar
unknown committed
2332
                log_record_type_descriptor[type].rclass ==
2333
                LOGRECTYPE_PSEUDOFIXEDLENGTH);
unknown's avatar
unknown committed
2334
    if (log_record_type_descriptor[type].rclass == LOGRECTYPE_FIXEDLENGTH)
2335 2336 2337 2338 2339 2340
    {
      DBUG_PRINT("info",
                 ("Fixed length: %u",
                  (uint) (log_record_type_descriptor[type].fixed_length + 3)));
      DBUG_RETURN(log_record_type_descriptor[type].fixed_length + 3);
    }
unknown's avatar
unknown committed
2341 2342 2343 2344

    ptr= page + offset + 3;            /* first compressed LSN */
    length= log_record_type_descriptor[type].fixed_length + 3;
    for (i= 0; i < log_record_type_descriptor[type].compressed_LSN; i++)
2345
    {
unknown's avatar
unknown committed
2346
      /* first 2 bits is length - 2 */
2347
      uint len= (((uint8) (*ptr)) >> 6) + 2;
2348 2349
      if (ptr[0] == 0 && ((uint8) ptr[1]) == 1)
        len+= LSN_STORE_SIZE; /* case of full LSN storing */
unknown's avatar
unknown committed
2350
      ptr+= len;
2351
      /* subtract saved bytes */
2352
      length-= (LSN_STORE_SIZE - len);
2353
    }
unknown's avatar
unknown committed
2354 2355
    DBUG_PRINT("info", ("Pseudo-fixed length: %u", length));
    DBUG_RETURN(length);
2356
  }
unknown's avatar
unknown committed
2357 2358 2359
  case TRANSLOG_CHUNK_NOHDR:
    /* 2 no header chunk (till page end) */
    DBUG_PRINT("info", ("TRANSLOG_CHUNK_NOHDR  length: %u",
2360 2361 2362 2363 2364
                        (uint) (TRANSLOG_PAGE_SIZE - offset)));
    DBUG_RETURN(TRANSLOG_PAGE_SIZE - offset);
  case TRANSLOG_CHUNK_LNGTH:                   /* 3 chunk with chunk length */
    DBUG_PRINT("info", ("TRANSLOG_CHUNK_LNGTH"));
    DBUG_ASSERT(TRANSLOG_PAGE_SIZE - offset >= 3);
unknown's avatar
unknown committed
2365
    DBUG_PRINT("info", ("length: %u", uint2korr(page + offset + 1) + 3));
2366 2367 2368
    DBUG_RETURN(uint2korr(page + offset + 1) + 3);
  default:
    DBUG_ASSERT(0);
unknown's avatar
unknown committed
2369
    DBUG_RETURN(0);
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381
  }
}


/*
  Flush given buffer

  SYNOPSIS
    translog_buffer_flush()
    buffer               This buffer should be flushed

  RETURN
unknown's avatar
unknown committed
2382 2383
    0  OK
    1  Error
2384 2385 2386 2387
*/

static my_bool translog_buffer_flush(struct st_translog_buffer *buffer)
{
2388
  uint32 i, pg;
2389 2390 2391
  TRANSLOG_ADDRESS offset= buffer->offset;
  TRANSLOG_FILE *file= buffer->file;
  uint8 ver= buffer->ver;
2392
  DBUG_ENTER("translog_buffer_flush");
unknown's avatar
unknown committed
2393
  DBUG_ASSERT(buffer->file != NULL);
2394
  DBUG_PRINT("enter",
2395
             ("Buffer: #%u 0x%lx file: %d  offset: (%lu,0x%lx)  size: %lu",
2396
              (uint) buffer->buffer_no, (ulong) buffer,
unknown's avatar
unknown committed
2397
              buffer->file->handler.file,
unknown's avatar
unknown committed
2398
              LSN_IN_PARTS(buffer->offset),
2399
              (ulong) buffer->size));
2400
  translog_buffer_lock_assert_owner(buffer);
2401 2402

  translog_wait_for_writers(buffer);
2403

2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415
  if (buffer->file != file || buffer->offset != offset || buffer->ver != ver)
    DBUG_RETURN(0); /* some the thread flushed the buffer already */

  if (buffer->is_closing_buffer)
  {
    /* some other flush in progress */
    translog_wait_for_closing(buffer);
  }

  if (buffer->file != file || buffer->offset != offset || buffer->ver != ver)
    DBUG_RETURN(0); /* some the thread flushed the buffer already */

2416 2417 2418
  if (buffer->overlay && buffer->overlay->file == buffer->file &&
      cmp_translog_addr(buffer->overlay->offset + buffer->overlay->size,
                        buffer->offset) > 0)
2419
  {
2420 2421 2422 2423
    /*
      This can't happen for normal translog_flush,
      only during destroying the loghandler
    */
2424
    struct st_translog_buffer *overlay= buffer->overlay;
2425
    TRANSLOG_ADDRESS buffer_offset= buffer->offset;
unknown's avatar
unknown committed
2426
    TRANSLOG_FILE *fl= buffer->file;
2427
    uint8 ver= buffer->ver;
2428 2429
    translog_buffer_unlock(buffer);
    translog_buffer_lock(overlay);
2430
    /* rechecks under mutex protection that overlay is still our overlay */
unknown's avatar
unknown committed
2431
    if (buffer->overlay->file == fl &&
2432 2433 2434 2435 2436
        cmp_translog_addr(buffer->overlay->offset + buffer->overlay->size,
                          buffer_offset) > 0)
    {
      translog_wait_for_buffer_free(overlay);
    }
2437 2438
    translog_buffer_unlock(overlay);
    translog_buffer_lock(buffer);
2439 2440
    if (buffer->file != fl || buffer_offset != buffer->offset ||
        ver != buffer->ver)
2441 2442 2443 2444 2445 2446 2447
    {
      /*
        This means that somebody else flushed the buffer while we was
        waiting for overlay then for locking buffer again.
      */
      DBUG_RETURN(0);
    }
2448 2449
  }

unknown's avatar
unknown committed
2450 2451 2452 2453
  /*
    Send page by page in the pagecache what we are going to write on the
    disk
  */
unknown's avatar
unknown committed
2454
  file= buffer->file;
unknown's avatar
unknown committed
2455
  for (i= 0, pg= LSN_OFFSET(buffer->offset) / TRANSLOG_PAGE_SIZE;
2456 2457
       i < buffer->size;
       i+= TRANSLOG_PAGE_SIZE, pg++)
2458
  {
2459 2460 2461
    TRANSLOG_ADDRESS addr= (buffer->offset + i);
    TRANSLOG_VALIDATOR_DATA data;
    data.addr= &addr;
unknown's avatar
unknown committed
2462
    DBUG_ASSERT(log_descriptor.pagecache->block_size == TRANSLOG_PAGE_SIZE);
2463
    DBUG_ASSERT(i + TRANSLOG_PAGE_SIZE <= buffer->size);
unknown's avatar
unknown committed
2464
    if (translog_status != TRANSLOG_OK && translog_status != TRANSLOG_SHUTDOWN)
2465
      DBUG_RETURN(1);
2466
    if (pagecache_inject(log_descriptor.pagecache,
unknown's avatar
unknown committed
2467
                        &file->handler, pg, 3,
2468 2469 2470
                        buffer->buffer + i,
                        PAGECACHE_PLAIN_PAGE,
                        PAGECACHE_LOCK_LEFT_UNLOCKED,
2471
                        PAGECACHE_PIN_LEFT_UNPINNED, 0,
unknown's avatar
unknown committed
2472
                        LSN_IMPOSSIBLE))
2473
    {
unknown's avatar
unknown committed
2474 2475
      DBUG_PRINT("error",
                 ("Can't write page (%lu,0x%lx) to pagecache, error: %d",
unknown's avatar
unknown committed
2476
                  (ulong) buffer->file->number,
unknown's avatar
unknown committed
2477 2478
                  (ulong) (LSN_OFFSET(buffer->offset)+ i),
                  my_errno));
2479 2480
      translog_stop_writing();
      DBUG_RETURN(1);
2481 2482
    }
  }
unknown's avatar
unknown committed
2483
  file->is_sync= 0;
2484
  if (my_pwrite(file->handler.file, buffer->buffer,
2485
                buffer->size, LSN_OFFSET(buffer->offset),
2486
                log_write_flags))
2487
  {
2488
    DBUG_PRINT("error", ("Can't write buffer (%lu,0x%lx) size %lu "
unknown's avatar
unknown committed
2489
                         "to the disk (%d)",
unknown's avatar
unknown committed
2490
                         (ulong) file->handler.file,
2491
                         (ulong) LSN_OFFSET(buffer->offset),
2492
                         (ulong) buffer->size, errno));
2493
    translog_stop_writing();
2494 2495
    DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
2496 2497 2498 2499 2500 2501
  /*
    Dropping the flag in such way can make false alarm: signalling than the
    file in not sync when it is sync, but the situation is quite rare and
    protections with mutexes give much more overhead to the whole engine
  */
  file->is_sync= 0;
unknown's avatar
unknown committed
2502

2503
  if (LSN_OFFSET(buffer->last_lsn) != 0)    /* if buffer->last_lsn is set */
2504
    translog_set_sent_to_disk(buffer->last_lsn,
2505 2506 2507
                              buffer->next_buffer_offset);
  else
    translog_set_only_in_buffers(buffer->next_buffer_offset);
2508
  /* Free buffer */
unknown's avatar
unknown committed
2509
  buffer->file= NULL;
2510
  buffer->overlay= 0;
2511
  buffer->ver++;
unknown's avatar
unknown committed
2512
  pthread_cond_broadcast(&buffer->waiting_filling_buffer);
2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
  DBUG_RETURN(0);
}


/*
  Recover page with sector protection (wipe out failed chunks)

  SYNOPSYS
    translog_recover_page_up_to_sector()
    page                 reference on the page
    offset               offset of failed sector

  RETURN
unknown's avatar
unknown committed
2526 2527
    0  OK
    1  Error
2528 2529
*/

unknown's avatar
unknown committed
2530
static my_bool translog_recover_page_up_to_sector(uchar *page, uint16 offset)
2531 2532 2533
{
  uint16 chunk_offset= translog_get_first_chunk_offset(page), valid_chunk_end;
  DBUG_ENTER("translog_recover_page_up_to_sector");
unknown's avatar
unknown committed
2534
  DBUG_PRINT("enter", ("offset: %u  first chunk: %u",
2535 2536
                       (uint) offset, (uint) chunk_offset));

unknown's avatar
unknown committed
2537
  while (page[chunk_offset] != TRANSLOG_FILLER && chunk_offset < offset)
2538 2539 2540 2541 2542
  {
    uint16 chunk_length;
    if ((chunk_length=
         translog_get_total_chunk_length(page, chunk_offset)) == 0)
    {
2543
      DBUG_PRINT("error", ("cant get chunk length (offset %u)",
2544 2545 2546
                           (uint) chunk_offset));
      DBUG_RETURN(1);
    }
unknown's avatar
unknown committed
2547
    DBUG_PRINT("info", ("chunk: offset: %u  length %u",
2548 2549 2550
                        (uint) chunk_offset, (uint) chunk_length));
    if (((ulong) chunk_offset) + ((ulong) chunk_length) > TRANSLOG_PAGE_SIZE)
    {
2551
      DBUG_PRINT("error", ("damaged chunk (offset %u) in trusted area",
2552 2553 2554 2555 2556 2557 2558
                           (uint) chunk_offset));
      DBUG_RETURN(1);
    }
    chunk_offset+= chunk_length;
  }

  valid_chunk_end= chunk_offset;
unknown's avatar
unknown committed
2559
  /* end of trusted area - sector parsing */
unknown's avatar
unknown committed
2560
  while (page[chunk_offset] != TRANSLOG_FILLER)
2561 2562 2563 2564 2565
  {
    uint16 chunk_length;
    if ((chunk_length=
         translog_get_total_chunk_length(page, chunk_offset)) == 0)
      break;
unknown's avatar
unknown committed
2566 2567

    DBUG_PRINT("info", ("chunk: offset: %u  length %u",
2568
                        (uint) chunk_offset, (uint) chunk_length));
unknown's avatar
unknown committed
2569 2570
    if (((ulong) chunk_offset) + ((ulong) chunk_length) >
        (uint) (offset + DISK_DRIVE_SECTOR_SIZE))
2571
      break;
unknown's avatar
unknown committed
2572

2573 2574 2575 2576 2577
    chunk_offset+= chunk_length;
    valid_chunk_end= chunk_offset;
  }
  DBUG_PRINT("info", ("valid chunk end offset: %u", (uint) valid_chunk_end));

unknown's avatar
unknown committed
2578 2579
  memset(page + valid_chunk_end, TRANSLOG_FILLER,
         TRANSLOG_PAGE_SIZE - valid_chunk_end);
2580 2581 2582 2583 2584

  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
2585 2586 2587
/**
  @brief Dummy write callback.
*/
2588

unknown's avatar
unknown committed
2589
static my_bool
unknown's avatar
unknown committed
2590 2591 2592
translog_dummy_callback(uchar *page __attribute__((unused)),
                        pgcache_page_no_t page_no __attribute__((unused)),
                        uchar* data_ptr __attribute__((unused)))
unknown's avatar
unknown committed
2593 2594 2595
{
  return 0;
}
2596

unknown's avatar
unknown committed
2597

unknown's avatar
unknown committed
2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612
/**
  @brief Checks and removes sector protection.

  @param page            reference on the page content.
  @param file            transaction log descriptor.

  @retvat 0 OK
  @retval 1 Error
*/

static my_bool
translog_check_sector_protection(uchar *page, TRANSLOG_FILE *file)
{
  uint i, offset;
  uchar *table= page + page_overhead[page[TRANSLOG_PAGE_FLAGS]] -
unknown's avatar
unknown committed
2613
    TRANSLOG_PAGE_SIZE / DISK_DRIVE_SECTOR_SIZE;
unknown's avatar
unknown committed
2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637
  uint8 current= table[0];
  DBUG_ENTER("translog_check_sector_protection");

  for (i= 1, offset= DISK_DRIVE_SECTOR_SIZE;
       i < TRANSLOG_PAGE_SIZE / DISK_DRIVE_SECTOR_SIZE;
       i++, offset+= DISK_DRIVE_SECTOR_SIZE)
  {
    /*
      TODO: add chunk counting for "suspecting" sectors (difference is
      more than 1-2), if difference more then present chunks then it is
      the problem.
    */
    uint8 test= page[offset];
    DBUG_PRINT("info", ("sector: #%u  offset: %u  current: %lx "
                        "read: 0x%x  stored: 0x%x%x",
                        i, offset, (ulong) current,
                        (uint) uint2korr(page + offset), (uint) table[i],
                        (uint) table[i + 1]));
    /*
      3 is minimal possible record length. So we can have "distance"
      between 2 sectors value more then DISK_DRIVE_SECTOR_SIZE / 3
      only if it is old value, i.e. the sector was not written.
    */
    if (((test < current) &&
2638
         ((uint)(0xFFL - current + test) > DISK_DRIVE_SECTOR_SIZE / 3)) ||
unknown's avatar
unknown committed
2639
        ((test >= current) &&
2640
         ((uint)(test - current) > DISK_DRIVE_SECTOR_SIZE / 3)))
unknown's avatar
unknown committed
2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659
    {
      if (translog_recover_page_up_to_sector(page, offset))
        DBUG_RETURN(1);
      file->was_recovered= 1;
      DBUG_RETURN(0);
    }

    /* Restore value on the page */
    page[offset]= table[i];
    current= test;
    DBUG_PRINT("info", ("sector: #%u  offset: %u  current: %lx  "
                        "read: 0x%x  stored: 0x%x",
                        i, offset, (ulong) current,
                        (uint) page[offset], (uint) table[i]));
  }
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671
/**
  @brief Log page validator (read callback)

  @param page            The page data to check
  @param page_no         The page number (<offset>/<page length>)
  @param data_ptr        Read callback data pointer (pointer to TRANSLOG_FILE)

  @todo: add turning loghandler to read-only mode after merging with
  that patch.

  @retval 0 OK
  @retval 1 Error
2672
*/
unknown's avatar
unknown committed
2673 2674 2675 2676

static my_bool translog_page_validator(uchar *page,
                                       pgcache_page_no_t page_no,
                                       uchar* data_ptr)
2677
{
unknown's avatar
unknown committed
2678 2679
  uint this_page_page_overhead;
  uint flags;
unknown's avatar
unknown committed
2680 2681 2682
  uchar *page_pos;
  TRANSLOG_FILE *data= (TRANSLOG_FILE *) data_ptr;
#ifndef DBUG_OFF
2683
  pgcache_page_no_t offset= page_no * TRANSLOG_PAGE_SIZE;
unknown's avatar
unknown committed
2684
#endif
2685 2686
  DBUG_ENTER("translog_page_validator");

unknown's avatar
unknown committed
2687
  data->was_recovered= 0;
2688

unknown's avatar
unknown committed
2689 2690
  if (uint3korr(page) != page_no ||
      uint3korr(page + 3) != data->number)
2691
  {
2692
    DBUG_PRINT("error", ("Page (%lu,0x%lx): "
unknown's avatar
unknown committed
2693
                         "page address written in the page is incorrect: "
2694
                         "File %lu instead of %lu or page %lu instead of %lu",
unknown's avatar
unknown committed
2695 2696
                         (ulong) data->number, (ulong) offset,
                         (ulong) uint3korr(page + 3), (ulong) data->number,
2697
                         (ulong) uint3korr(page),
unknown's avatar
unknown committed
2698
                         (ulong) page_no));
2699 2700
    DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
2701 2702
  flags= (uint)(page[TRANSLOG_PAGE_FLAGS]);
  this_page_page_overhead= page_overhead[flags];
2703 2704 2705
  if (flags & ~(TRANSLOG_PAGE_CRC | TRANSLOG_SECTOR_PROTECTION |
                TRANSLOG_RECORD_CRC))
  {
2706
    DBUG_PRINT("error", ("Page (%lu,0x%lx): "
2707
                         "Garbage in the page flags field detected : %x",
unknown's avatar
unknown committed
2708 2709
                         (ulong) data->number, (ulong) offset,
                         (uint) flags));
2710 2711
    DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
2712
  page_pos= page + (3 + 3 + 1);
2713 2714
  if (flags & TRANSLOG_PAGE_CRC)
  {
unknown's avatar
unknown committed
2715 2716 2717 2718
    uint32 crc= translog_crc(page + this_page_page_overhead,
                             TRANSLOG_PAGE_SIZE -
                             this_page_page_overhead);
    if (crc != uint4korr(page_pos))
2719
    {
2720
      DBUG_PRINT("error", ("Page (%lu,0x%lx): "
2721
                           "CRC mismatch: calculated: %lx on the page %lx",
unknown's avatar
unknown committed
2722
                           (ulong) data->number, (ulong) offset,
unknown's avatar
unknown committed
2723
                           (ulong) crc, (ulong) uint4korr(page_pos)));
2724 2725
      DBUG_RETURN(1);
    }
unknown's avatar
unknown committed
2726
    page_pos+= CRC_SIZE;                      /* Skip crc */
2727
  }
unknown's avatar
unknown committed
2728 2729
  if (flags & TRANSLOG_SECTOR_PROTECTION &&
      translog_check_sector_protection(page, data))
2730
  {
unknown's avatar
unknown committed
2731
    DBUG_RETURN(1);
2732 2733 2734 2735
  }
  DBUG_RETURN(0);
}

2736

unknown's avatar
unknown committed
2737 2738
/**
  @brief Locks the loghandler.
2739 2740
*/

2741
void translog_lock()
2742
{
2743
  uint8 current_buffer;
2744 2745 2746 2747 2748 2749 2750 2751
  DBUG_ENTER("translog_lock");

  /*
     Locking the loghandler mean locking current buffer, but it can change
     during locking, so we should check it
  */
  for (;;)
  {
2752 2753 2754 2755 2756
    /*
      log_descriptor.bc.buffer_no is only one byte so its reading is
      an atomic operation
    */
    current_buffer= log_descriptor.bc.buffer_no;
2757
    translog_buffer_lock(log_descriptor.buffers + current_buffer);
2758
    if (log_descriptor.bc.buffer_no == current_buffer)
2759
      break;
2760
    translog_buffer_unlock(log_descriptor.buffers + current_buffer);
2761
  }
2762
  DBUG_VOID_RETURN;
2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776
}


/*
  Unlock the loghandler

  SYNOPSIS
    translog_unlock()

  RETURN
    0  OK
    1  Error
*/

2777
void translog_unlock()
2778 2779 2780 2781 2782
{
  translog_buffer_unlock(log_descriptor.bc.buffer);
}


2783 2784
/**
  @brief Get log page by file number and offset of the beginning of the page
2785

2786 2787
  @param data            validator data, which contains the page address
  @param buffer          buffer for page placing
2788
                         (might not be used in some cache implementations)
2789 2790
  @param direct_link     if it is not NULL then caller can accept direct
                         link to the page cache
2791

2792 2793
  @retval NULL Error
  @retval #    pointer to the page cache which should be used to read this page
2794 2795
*/

2796
static uchar *translog_get_page(TRANSLOG_VALIDATOR_DATA *data, uchar *buffer,
unknown's avatar
unknown committed
2797
                                PAGECACHE_BLOCK_LINK **direct_link)
2798
{
2799
  TRANSLOG_ADDRESS addr= *(data->addr), in_buffers;
2800
  uint32 file_no= LSN_FILE_NO(addr);
unknown's avatar
unknown committed
2801
  TRANSLOG_FILE *file;
2802
  DBUG_ENTER("translog_get_page");
unknown's avatar
unknown committed
2803
  DBUG_PRINT("enter", ("File: %lu  Offset: %lu(0x%lx)",
2804 2805 2806
                       (ulong) file_no,
                       (ulong) LSN_OFFSET(addr),
                       (ulong) LSN_OFFSET(addr)));
2807 2808

  /* it is really page address */
2809
  DBUG_ASSERT(LSN_OFFSET(addr) % TRANSLOG_PAGE_SIZE == 0);
2810 2811 2812
  if (direct_link)
    *direct_link= NULL;

2813 2814
restart:

2815 2816
  in_buffers= translog_only_in_buffers();
  DBUG_PRINT("info", ("in_buffers: (%lu,0x%lx)",
unknown's avatar
unknown committed
2817
                      LSN_IN_PARTS(in_buffers)));
2818 2819 2820 2821
  if (in_buffers != LSN_IMPOSSIBLE &&
      cmp_translog_addr(addr, in_buffers) >= 0)
  {
    translog_lock();
2822
    DBUG_ASSERT(cmp_translog_addr(addr, log_descriptor.horizon) < 0);
2823 2824 2825 2826 2827
    /* recheck with locked loghandler */
    in_buffers= translog_only_in_buffers();
    if (cmp_translog_addr(addr, in_buffers) >= 0)
    {
      uint16 buffer_no= log_descriptor.bc.buffer_no;
2828
#ifndef DBUG_OFF
2829
      uint16 buffer_start= buffer_no;
2830
#endif
2831 2832 2833 2834 2835 2836
      struct st_translog_buffer *buffer_unlock= log_descriptor.bc.buffer;
      struct st_translog_buffer *curr_buffer= log_descriptor.bc.buffer;
      for (;;)
      {
        /*
          if the page is in the buffer and it is the last version of the
2837
          page (in case of division the page by buffer flush)
2838
        */
unknown's avatar
unknown committed
2839
        if (curr_buffer->file != NULL &&
2840 2841 2842 2843 2844 2845
            cmp_translog_addr(addr, curr_buffer->offset) >= 0 &&
            cmp_translog_addr(addr,
                              (curr_buffer->next_buffer_offset ?
                               curr_buffer->next_buffer_offset:
                               curr_buffer->offset + curr_buffer->size)) < 0)
        {
2846 2847 2848
          TRANSLOG_ADDRESS offset= curr_buffer->offset;
          TRANSLOG_FILE *fl= curr_buffer->file;
          uchar *from, *table= NULL;
2849 2850
          int is_last_unfinished_page;
          uint last_protected_sector= 0;
unknown's avatar
unknown committed
2851
          TRANSLOG_FILE file_copy;
2852
          uint8 ver= curr_buffer->ver;
2853
          translog_wait_for_writers(curr_buffer);
2854 2855 2856 2857 2858 2859 2860
          if (offset != curr_buffer->offset || fl != curr_buffer->file ||
              ver != curr_buffer->ver)
          {
            DBUG_ASSERT(buffer_unlock == curr_buffer);
            translog_buffer_unlock(buffer_unlock);
            goto restart;
          }
2861 2862 2863
          DBUG_ASSERT(LSN_FILE_NO(addr) ==  LSN_FILE_NO(curr_buffer->offset));
          from= curr_buffer->buffer + (addr - curr_buffer->offset);
          memcpy(buffer, from, TRANSLOG_PAGE_SIZE);
unknown's avatar
unknown committed
2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
          /*
            We can use copy then in translog_page_validator() because it
            do not put it permanently somewhere.
            We have to use copy because after releasing log lock we can't
            guaranty that the file still be present (in real life it will be
            present but theoretically possible that it will be released
            already from last files cache);
          */
          file_copy= *(curr_buffer->file);
          file_copy.handler.callback_data= (uchar*) &file_copy;
2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884
          is_last_unfinished_page= ((log_descriptor.bc.buffer ==
                                     curr_buffer) &&
                                    (log_descriptor.bc.ptr >= from) &&
                                    (log_descriptor.bc.ptr <
                                     from + TRANSLOG_PAGE_SIZE));
          if (is_last_unfinished_page &&
              (buffer[TRANSLOG_PAGE_FLAGS] & TRANSLOG_SECTOR_PROTECTION))
          {
            last_protected_sector= ((log_descriptor.bc.previous_offset - 1) /
                                    DISK_DRIVE_SECTOR_SIZE);
            table= buffer + log_descriptor.page_overhead -
unknown's avatar
unknown committed
2885
              TRANSLOG_PAGE_SIZE / DISK_DRIVE_SECTOR_SIZE;
2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908
          }

          DBUG_ASSERT(buffer_unlock == curr_buffer);
          translog_buffer_unlock(buffer_unlock);
          if (is_last_unfinished_page)
          {
            uint i;
            /*
              This is last unfinished page => we should not check CRC and
              remove only that protection which already installed (no need
              to check it)

              We do not check the flag of sector protection, because if
              (buffer[TRANSLOG_PAGE_FLAGS] & TRANSLOG_SECTOR_PROTECTION) is
              not set then last_protected_sector will be 0 so following loop
              will be never executed
            */
            DBUG_PRINT("info", ("This is last unfinished page, "
                                "last protected sector %u",
                                last_protected_sector));
            for (i= 1; i <= last_protected_sector; i++)
            {
              uint offset= i * DISK_DRIVE_SECTOR_SIZE;
unknown's avatar
unknown committed
2909 2910 2911 2912
              DBUG_PRINT("info", ("Sector %u: 0x%02x <- 0x%02x",
                                  i, buffer[offset],
                                  table[i]));
              buffer[offset]= table[i];
2913 2914 2915 2916 2917 2918 2919 2920
            }
          }
          else
          {
            /*
              This IF should be true because we use in-memory data which
              supposed to be correct.
            */
unknown's avatar
unknown committed
2921
            if (translog_page_validator((uchar*) buffer,
2922
                                        LSN_OFFSET(addr) / TRANSLOG_PAGE_SIZE,
unknown's avatar
unknown committed
2923
                                        (uchar*) &file_copy))
2924
            {
unknown's avatar
unknown committed
2925
              DBUG_ASSERT(0);
2926
              buffer= NULL;
2927
            }
2928 2929 2930 2931 2932 2933 2934 2935
          }
          DBUG_RETURN(buffer);
        }
        buffer_no= (buffer_no + 1) % TRANSLOG_BUFFERS_NO;
        curr_buffer= log_descriptor.buffers + buffer_no;
        translog_buffer_lock(curr_buffer);
        translog_buffer_unlock(buffer_unlock);
        buffer_unlock= curr_buffer;
unknown's avatar
unknown committed
2936
        /* we can't make a full circle */
2937 2938 2939 2940 2941
        DBUG_ASSERT(buffer_start != buffer_no);
      }
    }
    translog_unlock();
  }
unknown's avatar
unknown committed
2942
  file= get_logfile_by_number(file_no);
2943
  DBUG_ASSERT(file != NULL);
unknown's avatar
unknown committed
2944
  buffer=
unknown's avatar
unknown committed
2945 2946
    (uchar*) pagecache_read(log_descriptor.pagecache, &file->handler,
                            LSN_OFFSET(addr) / TRANSLOG_PAGE_SIZE,
2947
                            3, (direct_link ? NULL : buffer),
unknown's avatar
unknown committed
2948 2949 2950 2951 2952
                            PAGECACHE_PLAIN_PAGE,
                            (direct_link ?
                             PAGECACHE_LOCK_READ :
                             PAGECACHE_LOCK_LEFT_UNLOCKED),
                            direct_link);
unknown's avatar
unknown committed
2953 2954 2955 2956
  DBUG_PRINT("info", ("Direct link is assigned to : 0x%lx * 0x%lx",
                      (ulong) direct_link,
                      (ulong)(direct_link ? *direct_link : NULL)));
  data->was_recovered= file->was_recovered;
2957 2958 2959
  DBUG_RETURN(buffer);
}

2960

2961 2962 2963 2964 2965 2966 2967
/**
  @brief free direct log page link

  @param direct_link the direct log page link to be freed

*/

unknown's avatar
unknown committed
2968
static void translog_free_link(PAGECACHE_BLOCK_LINK *direct_link)
2969 2970 2971 2972 2973 2974 2975
{
  DBUG_ENTER("translog_free_link");
  DBUG_PRINT("info", ("Direct link: 0x%lx",
                      (ulong) direct_link));
  if (direct_link)
    pagecache_unlock_by_link(log_descriptor.pagecache, direct_link,
                             PAGECACHE_LOCK_READ_UNLOCK, PAGECACHE_UNPIN,
2976
                             LSN_IMPOSSIBLE, LSN_IMPOSSIBLE, 0);
2977 2978
  DBUG_VOID_RETURN;
}
2979

2980

unknown's avatar
unknown committed
2981 2982
/**
  @brief Finds last full page of the given log file.
2983

unknown's avatar
unknown committed
2984
  @param addr            address structure to fill with data, which contain
2985
                         file number of the log file
unknown's avatar
unknown committed
2986 2987 2988
  @param last_page_ok    Result of the check whether last page OK.
                         (for now only we check only that file length
                         divisible on page length).
2989
  @param no_errors       suppress messages about non-critical errors
2990

unknown's avatar
unknown committed
2991 2992
  @retval 0 OK
  @retval 1 Error
2993 2994 2995
*/

static my_bool translog_get_last_page_addr(TRANSLOG_ADDRESS *addr,
2996 2997
                                           my_bool *last_page_ok,
                                           my_bool no_errors)
2998 2999
{
  char path[FN_REFLEN];
3000 3001
  uint32 rec_offset;
  my_off_t file_size;
3002
  uint32 file_no= LSN_FILE_NO(*addr);
3003 3004 3005 3006
  TRANSLOG_FILE *file;
#ifndef DBUG_OFF
  char buff[21];
#endif
3007 3008
  DBUG_ENTER("translog_get_last_page_addr");

3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038
  if (likely((file= get_logfile_by_number(file_no)) != NULL))
  {
    /*
      This function used only during initialization of loghandler or in
      scanner (which mean we need read that part of the log), so the
      requested log file have to be opened and can't be freed after
      returning pointer on it (file_size).
    */
    file_size= my_seek(file->handler.file, 0, SEEK_END, MYF(0));
  }
  else
  {
    /*
      This branch is used only during very early initialization
      when files are not opened.
    */
    File fd;
    if ((fd= my_open(translog_filename_by_fileno(file_no, path),
                     O_RDONLY, (no_errors ? MYF(0) : MYF(MY_WME)))) < 0)
    {
      my_errno= errno;
      DBUG_PRINT("error", ("Error %d during opening file #%d",
                           errno, file_no));
      DBUG_RETURN(1);
    }
    file_size= my_seek(fd, 0, SEEK_END, MYF(0));
    my_close(fd, MYF(0));
  }
  DBUG_PRINT("info", ("File size: %s", llstr(file_size, buff)));
  if (file_size == MY_FILEPOS_ERROR)
3039
    DBUG_RETURN(1);
3040 3041
  DBUG_ASSERT(file_size < ULL(0xffffffff));
  if (((uint32)file_size) > TRANSLOG_PAGE_SIZE)
3042
  {
3043
    rec_offset= (((((uint32)file_size) / TRANSLOG_PAGE_SIZE) - 1) *
3044
                       TRANSLOG_PAGE_SIZE);
3045
    *last_page_ok= (((uint32)file_size) == rec_offset + TRANSLOG_PAGE_SIZE);
3046 3047 3048 3049
  }
  else
  {
    *last_page_ok= 0;
3050
    rec_offset= 0;
3051
  }
3052
  *addr= MAKE_LSN(file_no, rec_offset);
unknown's avatar
unknown committed
3053
  DBUG_PRINT("info", ("Last page: 0x%lx  ok: %d", (ulong) rec_offset,
3054 3055 3056 3057 3058
                      *last_page_ok));
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
3059 3060
/**
  @brief Get number bytes for record length storing
3061

unknown's avatar
unknown committed
3062
  @param length          Record length which will be encoded
3063

unknown's avatar
unknown committed
3064
  @return 1,3,4,5 - number of bytes to store given length
3065
*/
3066

3067 3068 3069 3070
static uint translog_variable_record_length_bytes(translog_size_t length)
{
  if (length < 250)
    return 1;
unknown's avatar
unknown committed
3071
  if (length < 0xFFFF)
3072
    return 3;
unknown's avatar
unknown committed
3073
  if (length < (ulong) 0xFFFFFF)
3074 3075 3076 3077 3078
    return 4;
  return 5;
}


unknown's avatar
unknown committed
3079
/**
unknown's avatar
unknown committed
3080
  @brief Gets header of this chunk.
3081

unknown's avatar
unknown committed
3082
  @param chunk           The pointer to the chunk beginning
3083

unknown's avatar
unknown committed
3084 3085
  @retval # total length of the chunk
  @retval 0 Error
3086 3087
*/

unknown's avatar
unknown committed
3088
static uint16 translog_get_chunk_header_length(uchar *chunk)
3089 3090
{
  DBUG_ENTER("translog_get_chunk_header_length");
unknown's avatar
unknown committed
3091
  switch (*chunk & TRANSLOG_CHUNK_TYPE) {
unknown's avatar
unknown committed
3092
  case TRANSLOG_CHUNK_LSN:
3093
  {
unknown's avatar
unknown committed
3094
    /* 0 chunk referred as LSN (head or tail) */
3095
    translog_size_t rec_len;
unknown's avatar
unknown committed
3096
    uchar *start= chunk;
unknown's avatar
unknown committed
3097
    uchar *ptr= start + 1 + 2;
3098 3099 3100 3101
    uint16 chunk_len, header_len;
    DBUG_PRINT("info", ("TRANSLOG_CHUNK_LSN"));
    rec_len= translog_variable_record_1group_decode_len(&ptr);
    chunk_len= uint2korr(ptr);
3102
    header_len= (uint16) (ptr - start) +2;
unknown's avatar
unknown committed
3103
    DBUG_PRINT("info", ("rec len: %lu  chunk len: %u  header len: %u",
3104 3105 3106
                        (ulong) rec_len, (uint) chunk_len, (uint) header_len));
    if (chunk_len)
    {
unknown's avatar
unknown committed
3107
      /* TODO: fine header end */
unknown's avatar
unknown committed
3108 3109 3110 3111 3112
      /*
        The last chunk of multi-group record can be base for it header
        calculation (we skip to the first group to read the header) so if we
        stuck here something is wrong.
      */
3113
      DBUG_ASSERT(0);
unknown's avatar
unknown committed
3114
      DBUG_RETURN(0);                               /* Keep compiler happy */
3115 3116 3117
    }
    DBUG_RETURN(header_len);
  }
unknown's avatar
unknown committed
3118
  case TRANSLOG_CHUNK_FIXED:
3119
  {
unknown's avatar
unknown committed
3120
    /* 1 (pseudo)fixed record (also LSN) */
3121 3122 3123
    DBUG_PRINT("info", ("TRANSLOG_CHUNK_FIXED = 3"));
    DBUG_RETURN(3);
  }
unknown's avatar
unknown committed
3124 3125
  case TRANSLOG_CHUNK_NOHDR:
    /* 2 no header chunk (till page end) */
3126 3127 3128
    DBUG_PRINT("info", ("TRANSLOG_CHUNK_NOHDR = 1"));
    DBUG_RETURN(1);
    break;
unknown's avatar
unknown committed
3129 3130
  case TRANSLOG_CHUNK_LNGTH:
    /* 3 chunk with chunk length */
3131 3132 3133 3134 3135
    DBUG_PRINT("info", ("TRANSLOG_CHUNK_LNGTH = 3"));
    DBUG_RETURN(3);
    break;
  default:
    DBUG_ASSERT(0);
unknown's avatar
unknown committed
3136
    DBUG_RETURN(0);                               /* Keep compiler happy */
3137 3138 3139 3140
  }
}


3141
/**
unknown's avatar
unknown committed
3142 3143
  @brief Truncate the log to the given address. Used during the startup if the
         end of log if corrupted.
3144 3145 3146 3147 3148 3149 3150 3151 3152

  @param addr            new horizon

  @retval 0 OK
  @retval 1 Error
*/

static my_bool translog_truncate_log(TRANSLOG_ADDRESS addr)
{
3153 3154
  uchar *page;
  TRANSLOG_ADDRESS current_page;
3155 3156 3157
  uint32 next_page_offset, page_rest;
  uint32 i;
  File fd;
3158 3159 3160
  TRANSLOG_VALIDATOR_DATA data;
  char path[FN_REFLEN];
  uchar page_buff[TRANSLOG_PAGE_SIZE];
3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181
  DBUG_ENTER("translog_truncate_log");
  /* TODO: write warning to the client */
  DBUG_PRINT("warning", ("removing all records from (%lx,0x%lx) "
                         "till (%lx,0x%lx)",
                         LSN_IN_PARTS(addr),
                         LSN_IN_PARTS(log_descriptor.horizon)));
  DBUG_ASSERT(cmp_translog_addr(addr, log_descriptor.horizon) < 0);
  /* remove files between the address and horizon */
  for (i= LSN_FILE_NO(addr) + 1; i <= LSN_FILE_NO(log_descriptor.horizon); i++)
    if (my_delete(translog_filename_by_fileno(i, path),  MYF(MY_WME)))
    {
      translog_unlock();
      DBUG_RETURN(1);
    }

  /* truncate the last file up to the last page */
  next_page_offset= LSN_OFFSET(addr);
  next_page_offset= (next_page_offset -
                     ((next_page_offset - 1) % TRANSLOG_PAGE_SIZE + 1) +
                     TRANSLOG_PAGE_SIZE);
  page_rest= next_page_offset - LSN_OFFSET(addr);
3182
  memset(page_buff, TRANSLOG_FILLER, page_rest);
3183
  if ((fd= open_logfile_by_number_no_cache(LSN_FILE_NO(addr))) < 0 ||
3184 3185 3186 3187 3188
      ((my_chsize(fd, next_page_offset, TRANSLOG_FILLER, MYF(MY_WME)) ||
        (page_rest && my_pwrite(fd, page_buff, page_rest, LSN_OFFSET(addr),
                                log_write_flags)) ||
        my_sync(fd, MYF(MY_WME))) |
       my_close(fd, MYF(MY_WME))) ||
unknown's avatar
unknown committed
3189
      (sync_log_dir >= TRANSLOG_SYNC_DIR_ALWAYS &&
unknown's avatar
unknown committed
3190
       sync_dir(log_descriptor.directory_fd, MYF(MY_WME | MY_IGNORE_BADFD))))
3191
    DBUG_RETURN(1);
unknown's avatar
unknown committed
3192

3193
  /* fix the horizon */
3194
  log_descriptor.horizon= addr;
3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
  /* fix the buffer data */
  current_page= MAKE_LSN(LSN_FILE_NO(addr), (next_page_offset -
                                             TRANSLOG_PAGE_SIZE));
  data.addr= &current_page;
  if ((page= translog_get_page(&data, log_descriptor.buffers->buffer, NULL)) ==
      NULL)
    DBUG_RETURN(1);
  if (page != log_descriptor.buffers->buffer)
    memcpy(log_descriptor.buffers->buffer, page, TRANSLOG_PAGE_SIZE);
  log_descriptor.bc.buffer->offset= current_page;
  log_descriptor.bc.buffer->size= LSN_OFFSET(addr) - LSN_OFFSET(current_page);
  log_descriptor.bc.ptr=
    log_descriptor.buffers->buffer + log_descriptor.bc.buffer->size;
  log_descriptor.bc.current_page_fill= log_descriptor.bc.buffer->size;
3209 3210 3211
  DBUG_RETURN(0);
}

unknown's avatar
unknown committed
3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252

/**
  @brief Check log files presence

  @retval 0 no log files.
  @retval 1 there is at least 1 log file in the directory
*/

my_bool translog_is_log_files()
{
  MY_DIR *dirp;
  uint i;
  my_bool rc= FALSE;

  /* Finds and removes transaction log files */
  if (!(dirp = my_dir(log_descriptor.directory, MYF(MY_DONT_SORT))))
    return 1;

  for (i= 0; i < dirp->number_off_files; i++)
  {
    char *file= dirp->dir_entry[i].name;
    if (strncmp(file, "maria_log.", 10) == 0 &&
        file[10] >= '0' && file[10] <= '9' &&
        file[11] >= '0' && file[11] <= '9' &&
        file[12] >= '0' && file[12] <= '9' &&
        file[13] >= '0' && file[13] <= '9' &&
        file[14] >= '0' && file[14] <= '9' &&
        file[15] >= '0' && file[15] <= '9' &&
        file[16] >= '0' && file[16] <= '9' &&
        file[17] >= '0' && file[17] <= '9' &&
        file[18] == '\0')
    {
      rc= TRUE;
      break;
    }
  }
  my_dirend(dirp);
  return FALSE;
}


3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271
/**
  @brief Fills table of dependence length of page header from page flags
*/

static void translog_fill_overhead_table()
{
  uint i;
  for (i= 0; i < TRANSLOG_FLAGS_NUM; i++)
  {
     page_overhead[i]= 7;
     if (i & TRANSLOG_PAGE_CRC)
       page_overhead[i]+= CRC_SIZE;
     if (i & TRANSLOG_SECTOR_PROTECTION)
       page_overhead[i]+= TRANSLOG_PAGE_SIZE /
                           DISK_DRIVE_SECTOR_SIZE;
  }
}


3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291
/**
  @brief Checks that chunk is LSN one

  @param type            type of the chunk

  @retval 1 the chunk is LNS
  @retval 0 the chunk is not LSN
*/

static my_bool translog_is_LSN_chunk(uchar type)
{
  DBUG_ENTER("translog_is_LSN_chunk");
  DBUG_PRINT("info", ("byte: %x  chunk type: %u  record type: %u",
                      type, type >> 6, type & TRANSLOG_REC_TYPE));
  DBUG_RETURN(((type & TRANSLOG_CHUNK_TYPE) == TRANSLOG_CHUNK_FIXED) ||
              (((type & TRANSLOG_CHUNK_TYPE) == TRANSLOG_CHUNK_LSN)  &&
               ((type & TRANSLOG_REC_TYPE)) != TRANSLOG_CHUNK_0_CONT));
}


3292 3293 3294 3295 3296 3297 3298 3299 3300
/**
  @brief Initialize transaction log

  @param directory       Directory where log files are put
  @param log_file_max_size max size of one log size (for new logs creation)
  @param server_version  version of MySQL server (MYSQL_VERSION_ID)
  @param server_id       server ID (replication & Co)
  @param pagecache       Page cache for the log reads
  @param flags           flags (TRANSLOG_PAGE_CRC, TRANSLOG_SECTOR_PROTECTION
3301
                           TRANSLOG_RECORD_CRC)
3302 3303
  @param read_only       Put transaction log in read-only mode
  @param init_table_func function to initialize record descriptors table
3304
  @param no_errors       suppress messages about non-critical errors
3305

3306
  @todo
3307 3308
    Free used resources in case of error.

3309 3310
  @retval 0 OK
  @retval 1 Error
3311 3312
*/

3313 3314 3315 3316 3317
my_bool translog_init_with_table(const char *directory,
                                 uint32 log_file_max_size,
                                 uint32 server_version,
                                 uint32 server_id, PAGECACHE *pagecache,
                                 uint flags, my_bool readonly,
3318 3319
                                 void (*init_table_func)(),
                                 my_bool no_errors)
3320 3321 3322
{
  int i;
  int old_log_was_recovered= 0, logs_found= 0;
unknown's avatar
unknown committed
3323
  uint old_flags= flags;
unknown's avatar
unknown committed
3324
  uint32 start_file_num= 1;
3325
  TRANSLOG_ADDRESS sure_page, last_page, last_valid_page, checkpoint_lsn;
3326
  my_bool version_changed= 0;
unknown's avatar
unknown committed
3327 3328 3329
  DBUG_ENTER("translog_init_with_table");

  id_to_share= NULL;
unknown's avatar
unknown committed
3330
  log_descriptor.directory_fd= -1;
3331
  log_descriptor.is_everything_flushed= 1;
unknown's avatar
unknown committed
3332 3333 3334

  (*init_table_func)();

3335 3336 3337
  if (readonly)
    log_descriptor.open_flags= O_BINARY | O_RDONLY;
  else
3338
    log_descriptor.open_flags= O_BINARY | O_RDWR;
3339
  if (pthread_mutex_init(&log_descriptor.sent_to_disk_lock,
3340 3341 3342 3343 3344
                         MY_MUTEX_INIT_FAST) ||
      pthread_mutex_init(&log_descriptor.file_header_lock,
                         MY_MUTEX_INIT_FAST) ||
      pthread_mutex_init(&log_descriptor.unfinished_files_lock,
                         MY_MUTEX_INIT_FAST) ||
3345 3346
      pthread_mutex_init(&log_descriptor.purger_lock,
                         MY_MUTEX_INIT_FAST) ||
3347 3348
      pthread_mutex_init(&log_descriptor.log_flush_lock,
                         MY_MUTEX_INIT_FAST) ||
unknown's avatar
unknown committed
3349 3350 3351 3352
      my_rwlock_init(&log_descriptor.open_files_lock,
                     NULL) ||
      my_init_dynamic_array(&log_descriptor.open_files,
                            sizeof(TRANSLOG_FILE*), 10, 10) ||
unknown's avatar
unknown committed
3353 3354 3355
      my_init_dynamic_array(&log_descriptor.unfinished_files,
                            sizeof(struct st_file_counter),
                            10, 10))
3356
    DBUG_RETURN(1);
3357
  log_descriptor.min_need_file= 0;
3358 3359
  log_descriptor.min_file_number= 0;
  log_descriptor.last_lsn_checked= LSN_IMPOSSIBLE;
3360 3361 3362

  /* Directory to store files */
  unpack_dirname(log_descriptor.directory, directory);
unknown's avatar
unknown committed
3363
#ifndef __WIN__
3364 3365 3366
  if ((log_descriptor.directory_fd= my_open(log_descriptor.directory,
                                            O_RDONLY, MYF(MY_WME))) < 0)
  {
3367 3368
    my_errno= errno;
    DBUG_PRINT("error", ("Error %d during opening directory '%s'",
3369 3370 3371
                         errno, log_descriptor.directory));
    DBUG_RETURN(1);
  }
unknown's avatar
unknown committed
3372
#endif
3373
  log_descriptor.in_buffers_only= LSN_IMPOSSIBLE;
unknown's avatar
unknown committed
3374
  DBUG_ASSERT(log_file_max_size % TRANSLOG_PAGE_SIZE == 0 &&
unknown's avatar
unknown committed
3375
              log_file_max_size >= TRANSLOG_MIN_FILE_SIZE);
3376
  /* max size of one log size (for new logs creation) */
3377
  log_file_size= log_descriptor.log_file_max_size=
unknown's avatar
unknown committed
3378
    log_file_max_size;
3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389
  /* server version */
  log_descriptor.server_version= server_version;
  /* server ID */
  log_descriptor.server_id= server_id;
  /* Page cache for the log reads */
  log_descriptor.pagecache= pagecache;
  /* Flags */
  DBUG_ASSERT((flags &
               ~(TRANSLOG_PAGE_CRC | TRANSLOG_SECTOR_PROTECTION |
                 TRANSLOG_RECORD_CRC)) == 0);
  log_descriptor.flags= flags;
3390
  translog_fill_overhead_table();
unknown's avatar
unknown committed
3391
  log_descriptor.page_overhead= page_overhead[flags];
3392 3393
  log_descriptor.page_capacity_chunk_2=
    TRANSLOG_PAGE_SIZE - log_descriptor.page_overhead - 1;
unknown's avatar
unknown committed
3394
  compile_time_assert(TRANSLOG_WRITE_BUFFER % TRANSLOG_PAGE_SIZE == 0);
3395 3396 3397 3398 3399 3400
  log_descriptor.buffer_capacity_chunk_2=
    (TRANSLOG_WRITE_BUFFER / TRANSLOG_PAGE_SIZE) *
    log_descriptor.page_capacity_chunk_2;
  log_descriptor.half_buffer_capacity_chunk_2=
    log_descriptor.buffer_capacity_chunk_2 / 2;
  DBUG_PRINT("info",
unknown's avatar
unknown committed
3401
             ("Overhead: %u  pc2: %u  bc2: %u,  bc2/2: %u",
3402 3403 3404 3405 3406
              log_descriptor.page_overhead,
              log_descriptor.page_capacity_chunk_2,
              log_descriptor.buffer_capacity_chunk_2,
              log_descriptor.half_buffer_capacity_chunk_2));

unknown's avatar
unknown committed
3407 3408 3409 3410 3411 3412 3413 3414
  /* Just to init it somehow (hack for bootstrap)*/
  {
    TRANSLOG_FILE *file= 0;
    log_descriptor.min_file = log_descriptor.max_file= 1;
    insert_dynamic(&log_descriptor.open_files, (uchar *)&file);
    translog_start_buffer(log_descriptor.buffers, &log_descriptor.bc, 0);
    pop_dynamic(&log_descriptor.open_files);
  }
3415 3416 3417 3418

  /* Buffers for log writing */
  for (i= 0; i < TRANSLOG_BUFFERS_NO; i++)
  {
unknown's avatar
unknown committed
3419 3420
    if (translog_buffer_init(log_descriptor.buffers + i))
      DBUG_RETURN(1);
3421 3422 3423
#ifndef DBUG_OFF
    log_descriptor.buffers[i].buffer_no= (uint8) i;
#endif
unknown's avatar
unknown committed
3424 3425
    DBUG_PRINT("info", ("translog_buffer buffer #%u: 0x%lx",
                        i, (ulong) log_descriptor.buffers + i));
3426 3427
  }

unknown's avatar
unknown committed
3428 3429 3430 3431
  /*
    last_logno and last_checkpoint_lsn were set in
    ma_control_file_create_or_open()
  */
unknown's avatar
unknown committed
3432
  logs_found= (last_logno != FILENO_IMPOSSIBLE);
3433

unknown's avatar
unknown committed
3434
  translog_status= (readonly ? TRANSLOG_READONLY : TRANSLOG_OK);
3435
  checkpoint_lsn= last_checkpoint_lsn;
unknown's avatar
unknown committed
3436

3437 3438 3439
  if (logs_found)
  {
    my_bool pageok;
unknown's avatar
unknown committed
3440
    DBUG_PRINT("info", ("log found..."));
3441
    /*
unknown's avatar
unknown committed
3442
      TODO: scan directory for maria_log.XXXXXXXX files and find
3443
       highest XXXXXXXX & set logs_found
unknown's avatar
unknown committed
3444
      TODO: check that last checkpoint within present log addresses space
3445

unknown's avatar
unknown committed
3446
      find the log end
unknown's avatar
unknown committed
3447
    */
unknown's avatar
unknown committed
3448
    if (LSN_FILE_NO(last_checkpoint_lsn) == FILENO_IMPOSSIBLE)
3449
    {
3450
      DBUG_ASSERT(LSN_OFFSET(last_checkpoint_lsn) == 0);
3451 3452
      /* only last log needs to be checked */
      sure_page= MAKE_LSN(last_logno, TRANSLOG_PAGE_SIZE);
3453 3454 3455 3456
    }
    else
    {
      sure_page= last_checkpoint_lsn;
3457 3458
      DBUG_ASSERT(LSN_OFFSET(sure_page) % TRANSLOG_PAGE_SIZE != 0);
      sure_page-= LSN_OFFSET(sure_page) % TRANSLOG_PAGE_SIZE;
3459
    }
unknown's avatar
unknown committed
3460
    /* Set horizon to the beginning of the last file first */
unknown's avatar
unknown committed
3461
    log_descriptor.horizon= last_page= MAKE_LSN(last_logno, 0);
3462
    if (translog_get_last_page_addr(&last_page, &pageok, no_errors))
unknown's avatar
unknown committed
3463 3464 3465
    {
      if (!translog_is_log_files())
      {
3466 3467 3468 3469
        /*
          Files was deleted, just start from the next log number, so that
          existing tables are in the past.
        */
unknown's avatar
unknown committed
3470
        start_file_num= last_logno + 1;
3471
        checkpoint_lsn= LSN_IMPOSSIBLE; /* no log so no checkpoint */
unknown's avatar
unknown committed
3472 3473 3474 3475 3476 3477
        logs_found= 0;
      }
      else
        DBUG_RETURN(1);
    }
    else if (LSN_OFFSET(last_page) == 0)
3478
    {
3479
      if (LSN_FILE_NO(last_page) == 1)
3480 3481
      {
        logs_found= 0;                          /* file #1 has no pages */
unknown's avatar
unknown committed
3482
        DBUG_PRINT("info", ("log found. But is is empty => no log assumed"));
3483 3484 3485
      }
      else
      {
3486
        last_page-= LSN_ONE_FILE;
3487
        if (translog_get_last_page_addr(&last_page, &pageok, 0))
3488 3489 3490
          DBUG_RETURN(1);
      }
    }
unknown's avatar
unknown committed
3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508
    if (logs_found)
    {
      uint32 i;
      log_descriptor.min_file= translog_first_file(log_descriptor.horizon, 1);
      log_descriptor.max_file= last_logno;
      /* Open all files */
      if (allocate_dynamic(&log_descriptor.open_files,
                           log_descriptor.max_file -
                           log_descriptor.min_file + 1))
        DBUG_RETURN(1);
      for (i = log_descriptor.max_file; i >= log_descriptor.min_file; i--)
      {
        /*
          We can't allocate all file together because they will be freed
          one by one
        */
        TRANSLOG_FILE *file= (TRANSLOG_FILE *)my_malloc(sizeof(TRANSLOG_FILE),
                                                        MYF(0));
3509 3510

        compile_time_assert(MY_FILEPOS_ERROR > ULL(0xffffffff));
unknown's avatar
unknown committed
3511 3512
        if (file == NULL ||
            (file->handler.file=
3513 3514 3515
             open_logfile_by_number_no_cache(i)) < 0 ||
            my_seek(file->handler.file, 0, SEEK_END, MYF(0)) >=
            ULL(0xffffffff))
unknown's avatar
unknown committed
3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540
        {
          int j;
          for (j= i - log_descriptor.min_file - 1; j > 0; j--)
          {
            TRANSLOG_FILE *el=
              *dynamic_element(&log_descriptor.open_files, j,
                               TRANSLOG_FILE **);
            my_close(el->handler.file, MYF(MY_WME));
            my_free(el, MYF(0));
          }
          if (file)
          {
            free(file);
            DBUG_RETURN(1);
          }
          else
            DBUG_RETURN(1);
        }
        translog_file_init(file, i, 1);
        /* we allocated space so it can't fail */
        insert_dynamic(&log_descriptor.open_files, (uchar *)&file);
      }
      DBUG_ASSERT(log_descriptor.max_file - log_descriptor.min_file + 1 ==
                  log_descriptor.open_files.elements);
    }
3541
  }
3542 3543 3544 3545 3546 3547 3548
  else if (readonly)
  {
    /* There is no logs and there is read-only mode => nothing to read */
    DBUG_PRINT("error", ("No logs and read-only mode"));
    DBUG_RETURN(1);
  }

3549 3550 3551 3552 3553
  if (logs_found)
  {
    TRANSLOG_ADDRESS current_page= sure_page;
    my_bool pageok;

unknown's avatar
unknown committed
3554
    DBUG_PRINT("info", ("The log is really present"));
3555
    DBUG_ASSERT(sure_page <= last_page);
3556 3557 3558

    /* TODO: check page size */

unknown's avatar
unknown committed
3559
    last_valid_page= LSN_IMPOSSIBLE;
unknown's avatar
unknown committed
3560 3561 3562 3563 3564 3565
    /*
      Scans and validate pages. We need it to show "outside" only for sure
      valid part of the log. If the log was damaged then fixed we have to
      cut off damaged part before some other process start write something
      in the log.
    */
3566 3567 3568
    do
    {
      TRANSLOG_ADDRESS current_file_last_page;
3569
      current_file_last_page= current_page;
3570
      if (translog_get_last_page_addr(&current_file_last_page, &pageok, 0))
3571 3572 3573
        DBUG_RETURN(1);
      if (!pageok)
      {
3574 3575
        DBUG_PRINT("error", ("File %lu have no complete last page",
                             (ulong) LSN_FILE_NO(current_file_last_page)));
3576 3577 3578 3579 3580 3581 3582
        old_log_was_recovered= 1;
        /* This file is not written till the end so it should be last */
        last_page= current_file_last_page;
        /* TODO: issue warning */
      }
      do
      {
unknown's avatar
unknown committed
3583
        TRANSLOG_VALIDATOR_DATA data;
3584 3585
        TRANSLOG_PAGE_SIZE_BUFF psize_buff;
        uchar *page;
unknown's avatar
unknown committed
3586
        data.addr= &current_page;
3587
        if ((page= translog_get_page(&data, psize_buff.buffer, NULL)) == NULL)
3588 3589 3590
          DBUG_RETURN(1);
        if (data.was_recovered)
        {
unknown's avatar
unknown committed
3591 3592 3593
          DBUG_PRINT("error", ("file no: %lu (%d)  "
                               "rec_offset: 0x%lx (%lu) (%d)",
                               (ulong) LSN_FILE_NO(current_page),
3594 3595 3596 3597
                               (uint3korr(page + 3) !=
                                LSN_FILE_NO(current_page)),
                               (ulong) LSN_OFFSET(current_page),
                               (ulong) (LSN_OFFSET(current_page) /
3598 3599
                                        TRANSLOG_PAGE_SIZE),
                               (uint3korr(page) !=
3600 3601
                                LSN_OFFSET(current_page) /
                                TRANSLOG_PAGE_SIZE)));
3602 3603 3604
          old_log_was_recovered= 1;
          break;
        }
unknown's avatar
unknown committed
3605
        old_flags= page[TRANSLOG_PAGE_FLAGS];
3606
        last_valid_page= current_page;
3607 3608 3609 3610 3611
        current_page+= TRANSLOG_PAGE_SIZE; /* increase offset */
      } while (current_page <= current_file_last_page);
      current_page+= LSN_ONE_FILE;
      current_page= LSN_REPLACE_OFFSET(current_page, TRANSLOG_PAGE_SIZE);
    } while (LSN_FILE_NO(current_page) <= LSN_FILE_NO(last_page) &&
3612
             !old_log_was_recovered);
unknown's avatar
unknown committed
3613
    if (last_valid_page == LSN_IMPOSSIBLE)
3614 3615 3616 3617 3618
    {
      /* Panic!!! Even page which should be valid is invalid */
      /* TODO: issue error */
      DBUG_RETURN(1);
    }
unknown's avatar
unknown committed
3619 3620 3621 3622
    DBUG_PRINT("info", ("Last valid page is in file: %lu  "
                        "offset: %lu (0x%lx)  "
                        "Logs found: %d  was recovered: %d  "
                        "flags match: %d",
3623 3624 3625
                        (ulong) LSN_FILE_NO(last_valid_page),
                        (ulong) LSN_OFFSET(last_valid_page),
                        (ulong) LSN_OFFSET(last_valid_page),
unknown's avatar
unknown committed
3626 3627
                        logs_found, old_log_was_recovered,
                        (old_flags == flags)));
3628 3629

    /* TODO: check server ID */
unknown's avatar
unknown committed
3630
    if (logs_found && !old_log_was_recovered && old_flags == flags)
3631
    {
unknown's avatar
unknown committed
3632
      TRANSLOG_VALIDATOR_DATA data;
3633 3634
      TRANSLOG_PAGE_SIZE_BUFF psize_buff;
      uchar *page;
3635
      uint16 chunk_offset;
unknown's avatar
unknown committed
3636
      data.addr= &last_valid_page;
3637
      /* continue old log */
3638 3639
      DBUG_ASSERT(LSN_FILE_NO(last_valid_page)==
                  LSN_FILE_NO(log_descriptor.horizon));
3640
      if ((page= translog_get_page(&data, psize_buff.buffer, NULL)) == NULL ||
3641 3642 3643 3644 3645 3646 3647
          (chunk_offset= translog_get_first_chunk_offset(page)) == 0)
        DBUG_RETURN(1);

      /* Puts filled part of old page in the buffer */
      log_descriptor.horizon= last_valid_page;
      translog_start_buffer(log_descriptor.buffers, &log_descriptor.bc, 0);
      /*
unknown's avatar
unknown committed
3648 3649
         Free space if filled with TRANSLOG_FILLER and first uchar of
         real chunk can't be TRANSLOG_FILLER
3650
      */
unknown's avatar
unknown committed
3651 3652
      while (chunk_offset < TRANSLOG_PAGE_SIZE &&
             page[chunk_offset] != TRANSLOG_FILLER)
3653 3654 3655 3656 3657
      {
        uint16 chunk_length;
        if ((chunk_length=
             translog_get_total_chunk_length(page, chunk_offset)) == 0)
          DBUG_RETURN(1);
unknown's avatar
unknown committed
3658
        DBUG_PRINT("info", ("chunk: offset: %u  length: %u",
3659 3660 3661 3662 3663 3664
                            (uint) chunk_offset, (uint) chunk_length));
        chunk_offset+= chunk_length;

        /* chunk can't cross the page border */
        DBUG_ASSERT(chunk_offset <= TRANSLOG_PAGE_SIZE);
      }
unknown's avatar
unknown committed
3665
      memcpy(log_descriptor.buffers->buffer, page, chunk_offset);
3666 3667
      log_descriptor.bc.buffer->size+= chunk_offset;
      log_descriptor.bc.ptr+= chunk_offset;
unknown's avatar
unknown committed
3668
      log_descriptor.bc.current_page_fill= chunk_offset;
3669 3670 3671
      log_descriptor.horizon= LSN_REPLACE_OFFSET(log_descriptor.horizon,
                                                 (chunk_offset +
                                                  LSN_OFFSET(last_valid_page)));
unknown's avatar
unknown committed
3672
      DBUG_PRINT("info", ("Move Page #%u: 0x%lx  chaser: %d  Size: %lu (%lu)",
3673 3674 3675 3676
                          (uint) log_descriptor.bc.buffer_no,
                          (ulong) log_descriptor.bc.buffer,
                          log_descriptor.bc.chaser,
                          (ulong) log_descriptor.bc.buffer->size,
unknown's avatar
unknown committed
3677
                          (ulong) (log_descriptor.bc.ptr - log_descriptor.bc.
3678
                                   buffer->buffer)));
unknown's avatar
unknown committed
3679
      translog_check_cursor(&log_descriptor.bc);
3680
    }
3681 3682 3683
    if (!old_log_was_recovered && old_flags == flags)
    {
      LOGHANDLER_FILE_INFO info;
unknown's avatar
unknown committed
3684 3685 3686 3687 3688 3689 3690 3691 3692
      /*
        Accessing &log_descriptor.open_files without mutex is safe
        because it is initialization
      */
      if (translog_read_file_header(&info,
                                    (*dynamic_element(&log_descriptor.
                                                      open_files,
                                                      0, TRANSLOG_FILE **))->
                                    handler.file))
3693 3694 3695
        DBUG_RETURN(1);
      version_changed= (info.maria_version != TRANSLOG_VERSION_ID);
    }
3696
  }
unknown's avatar
unknown committed
3697
  DBUG_PRINT("info", ("Logs found: %d  was recovered: %d",
3698 3699 3700
                      logs_found, old_log_was_recovered));
  if (!logs_found)
  {
unknown's avatar
unknown committed
3701 3702
    TRANSLOG_FILE *file= (TRANSLOG_FILE*)my_malloc(sizeof(TRANSLOG_FILE),
                                                   MYF(0));
unknown's avatar
unknown committed
3703
    DBUG_PRINT("info", ("The log is not found => we will create new log"));
unknown's avatar
unknown committed
3704 3705
    if (file == NULL)
       DBUG_RETURN(1);
3706
    /* Start new log system from scratch */
unknown's avatar
unknown committed
3707 3708 3709 3710 3711 3712 3713 3714 3715 3716
    log_descriptor.horizon= MAKE_LSN(start_file_num,
                                     TRANSLOG_PAGE_SIZE); /* header page */
    if ((file->handler.file=
         create_logfile_by_number_no_cache(start_file_num)) == -1)
      DBUG_RETURN(1);
    translog_file_init(file, start_file_num, 0);
    if (insert_dynamic(&log_descriptor.open_files, (uchar*)&file))
      DBUG_RETURN(1);
    log_descriptor.min_file= log_descriptor.max_file= start_file_num;
    if (translog_write_file_header())
3717
      DBUG_RETURN(1);
unknown's avatar
unknown committed
3718 3719 3720
    DBUG_ASSERT(log_descriptor.max_file - log_descriptor.min_file + 1 ==
                log_descriptor.open_files.elements);

3721
    if (ma_control_file_write_and_force(checkpoint_lsn, start_file_num,
3722
                                        max_trid_in_control_file))
3723 3724 3725 3726 3727
      DBUG_RETURN(1);
    /* assign buffer 0 */
    translog_start_buffer(log_descriptor.buffers, &log_descriptor.bc, 0);
    translog_new_page_header(&log_descriptor.horizon, &log_descriptor.bc);
  }
3728 3729
  else if ((old_log_was_recovered || old_flags != flags || version_changed) &&
           !readonly)
unknown's avatar
unknown committed
3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743
  {
    /* leave the damaged file untouched */
    log_descriptor.horizon+= LSN_ONE_FILE;
    /* header page */
    log_descriptor.horizon= LSN_REPLACE_OFFSET(log_descriptor.horizon,
                                               TRANSLOG_PAGE_SIZE);
    if (translog_create_new_file())
      DBUG_RETURN(1);
    /*
      Buffer system left untouched after recovery => we should init it
      (starting from buffer 0)
    */
    translog_start_buffer(log_descriptor.buffers, &log_descriptor.bc, 0);
    translog_new_page_header(&log_descriptor.horizon, &log_descriptor.bc);
3744 3745 3746
  }

  /* all LSNs that are on disk are flushed */
3747
  log_descriptor.log_start= log_descriptor.sent_to_disk=
3748 3749
    log_descriptor.flushed= log_descriptor.horizon;
  log_descriptor.in_buffers_only= log_descriptor.bc.buffer->offset;
3750
  log_descriptor.max_lsn= LSN_IMPOSSIBLE; /* set to 0 */
3751
  log_descriptor.previous_flush_horizon= log_descriptor.horizon;
unknown's avatar
unknown committed
3752
  /*
unknown's avatar
unknown committed
3753 3754 3755 3756 3757 3758
    Now 'flushed' is set to 'horizon' value, but 'horizon' is (potentially)
    address of the next LSN and we want indicate that all LSNs that are
    already on the disk are flushed so we need decrease horizon on 1 (we are
    sure that there is no LSN on the disk which is greater then 'flushed'
    and there will not be LSN created that is equal or less then the value
    of the 'flushed').
unknown's avatar
unknown committed
3759
  */
3760
  log_descriptor.flushed--; /* offset decreased */
3761
  log_descriptor.sent_to_disk--; /* offset decreased */
3762 3763 3764 3765 3766
  /*
    Log records will refer to a MARIA_SHARE by a unique 2-byte id; set up
    structures for generating 2-byte ids:
  */
  my_atomic_rwlock_init(&LOCK_id_to_share);
unknown's avatar
unknown committed
3767 3768
  id_to_share= (MARIA_SHARE **) my_malloc(SHARE_ID_MAX * sizeof(MARIA_SHARE*),
                                          MYF(MY_WME | MY_ZEROFILL));
3769 3770 3771
  if (unlikely(!id_to_share))
    DBUG_RETURN(1);
  id_to_share--; /* min id is 1 */
3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784

  /* Check the last LSN record integrity */
  if (logs_found)
  {
    TRANSLOG_SCANNER_DATA scanner;
    TRANSLOG_ADDRESS page_addr;
    LSN last_lsn= LSN_IMPOSSIBLE;
    /*
      take very last page address and try to find LSN record on it
      if it fail take address of previous page and so on
    */
    page_addr= (log_descriptor.horizon -
                ((log_descriptor.horizon - 1) % TRANSLOG_PAGE_SIZE + 1));
unknown's avatar
unknown committed
3785
    if (translog_scanner_init(page_addr, 1, &scanner, 1))
3786 3787 3788 3789
      DBUG_RETURN(1);
    scanner.page_offset= page_overhead[scanner.page[TRANSLOG_PAGE_FLAGS]];
    for (;;)
    {
3790 3791 3792
      uint chunk_1byte;
      chunk_1byte= scanner.page[scanner.page_offset];
      while (!translog_is_LSN_chunk(chunk_1byte) &&
3793 3794 3795 3796 3797 3798 3799 3800 3801 3802
             scanner.page != END_OF_LOG &&
             scanner.page[scanner.page_offset] != TRANSLOG_FILLER &&
             scanner.page_addr == page_addr)
      {
        if (translog_get_next_chunk(&scanner))
        {
          translog_destroy_scanner(&scanner);
          DBUG_RETURN(1);
        }
        if (scanner.page != END_OF_LOG)
3803
          chunk_1byte= scanner.page[scanner.page_offset];
3804
      }
3805
      if (translog_is_LSN_chunk(chunk_1byte))
3806 3807 3808 3809 3810 3811 3812 3813 3814
      {
        last_lsn= scanner.page_addr + scanner.page_offset;
        if (translog_get_next_chunk(&scanner))
        {
          translog_destroy_scanner(&scanner);
          DBUG_RETURN(1);
        }
        if (scanner.page == END_OF_LOG)
          break; /* it was the last record */
3815
        chunk_1byte= scanner.page[scanner.page_offset];
3816 3817 3818 3819 3820 3821 3822 3823 3824 3825
        continue; /* try to find other record on this page */
      }

      if (last_lsn != LSN_IMPOSSIBLE)
        break; /* there is no more records on the page */

      /* We have to make step back */
      if (unlikely(LSN_OFFSET(page_addr) == TRANSLOG_PAGE_SIZE))
      {
        uint32 file_no= LSN_FILE_NO(page_addr);
unknown's avatar
unknown committed
3826
        my_bool last_page_ok;
3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837
        /* it is beginning of the current file */
        if (unlikely(file_no == 1))
        {
          /*
            It is beginning of the log => there is no LSNs in the log =>
            There is no harm in leaving it "as-is".
          */
          DBUG_RETURN(0);
        }
        file_no--;
        page_addr= MAKE_LSN(file_no, TRANSLOG_PAGE_SIZE);
3838
        translog_get_last_page_addr(&page_addr, &last_page_ok, 0);
3839 3840 3841 3842 3843 3844 3845 3846
        /* page should be OK as it is not the last file */
        DBUG_ASSERT(last_page_ok);
      }
      else
      {
         page_addr-= TRANSLOG_PAGE_SIZE;
      }
      translog_destroy_scanner(&scanner);
unknown's avatar
unknown committed
3847
      if (translog_scanner_init(page_addr, 1, &scanner, 1))
3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869
        DBUG_RETURN(1);
      scanner.page_offset= page_overhead[scanner.page[TRANSLOG_PAGE_FLAGS]];
    }
    translog_destroy_scanner(&scanner);

    /* Now scanner points to the last LSN chunk, lets check it */
    {
      TRANSLOG_HEADER_BUFFER rec;
      translog_size_t rec_len;
      int len;
      uchar buffer[1];
      DBUG_PRINT("info", ("going to check the last found record (%lu,0x%lx)",
                          LSN_IN_PARTS(last_lsn)));

      len=
        translog_read_record_header(last_lsn, &rec);
      if (unlikely (len == RECHEADER_READ_ERROR ||
                    len == RECHEADER_READ_EOF))
      {
        DBUG_PRINT("error", ("unexpected end of log or record during "
                             "reading record header: (%lu,0x%lx)  len: %d",
                             LSN_IN_PARTS(last_lsn), len));
3870
        if (readonly)
3871
          log_descriptor.log_start= log_descriptor.horizon= last_lsn;
3872
        else if (translog_truncate_log(last_lsn))
unknown's avatar
unknown committed
3873 3874
        {
          translog_free_record_header(&rec);
3875
          DBUG_RETURN(1);
unknown's avatar
unknown committed
3876
        }
3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894
      }
      else
      {
        DBUG_ASSERT(last_lsn == rec.lsn);
        if (likely(rec.record_length != 0))
        {
          /*
            Reading the last byte of record will trigger scanning all
            record chunks for now
          */
          rec_len= translog_read_record(rec.lsn, rec.record_length - 1, 1,
                                        buffer, NULL);
          if (rec_len != 1)
          {
            DBUG_PRINT("error", ("unexpected end of log or record during "
                                 "reading record body: (%lu,0x%lx)  len: %d",
                                 LSN_IN_PARTS(rec.lsn),
                                 len));
3895
            if (readonly)
3896 3897
              log_descriptor.log_start= log_descriptor.horizon= last_lsn;

3898
            else if (translog_truncate_log(last_lsn))
unknown's avatar
unknown committed
3899 3900
            {
              translog_free_record_header(&rec);
3901
              DBUG_RETURN(1);
unknown's avatar
unknown committed
3902
            }
3903 3904 3905
          }
        }
      }
unknown's avatar
unknown committed
3906
      translog_free_record_header(&rec);
3907 3908
    }
  }
3909 3910 3911 3912 3913
  DBUG_RETURN(0);
}


/*
unknown's avatar
unknown committed
3914
  @brief Free transaction log file buffer.
3915

unknown's avatar
unknown committed
3916
  @param buffer_no       The buffer to free
3917 3918 3919 3920 3921 3922
*/

static void translog_buffer_destroy(struct st_translog_buffer *buffer)
{
  DBUG_ENTER("translog_buffer_destroy");
  DBUG_PRINT("enter",
unknown's avatar
unknown committed
3923
             ("Buffer #%u: 0x%lx  file: %d  offset: (%lu,0x%lx)  size: %lu",
3924
              (uint) buffer->buffer_no, (ulong) buffer,
unknown's avatar
unknown committed
3925
              (buffer->file ? buffer->file->handler.file : -1),
unknown's avatar
unknown committed
3926
              LSN_IN_PARTS(buffer->offset),
3927
              (ulong) buffer->size));
unknown's avatar
unknown committed
3928
  if (buffer->file != NULL)
3929 3930
  {
    /*
3931 3932 3933 3934 3935 3936
      We ignore errors here, because we can't do something about it
      (it is shutting down)

      We also have to take the locks even if there can't be any other
      threads running, because translog_buffer_flush()
      requires that we have the buffer locked.
3937
    */
3938
    translog_buffer_lock(buffer);
3939
    translog_buffer_flush(buffer);
3940
    translog_buffer_unlock(buffer);
3941
  }
unknown's avatar
unknown committed
3942
  DBUG_PRINT("info", ("Destroy mutex: 0x%lx", (ulong) &buffer->mutex));
3943
  pthread_mutex_destroy(&buffer->mutex);
unknown's avatar
unknown committed
3944
  pthread_cond_destroy(&buffer->waiting_filling_buffer);
3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957
  DBUG_VOID_RETURN;
}


/*
  Free log handler resources

  SYNOPSIS
    translog_destroy()
*/

void translog_destroy()
{
unknown's avatar
unknown committed
3958
  TRANSLOG_FILE **file;
unknown's avatar
unknown committed
3959
  uint i;
3960
  uint8 current_buffer;
3961
  DBUG_ENTER("translog_destroy");
3962

unknown's avatar
unknown committed
3963 3964
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
3965
  translog_lock();
3966
  current_buffer= log_descriptor.bc.buffer_no;
unknown's avatar
unknown committed
3967 3968 3969
  translog_status= (translog_status == TRANSLOG_READONLY ?
                    TRANSLOG_UNINITED :
                    TRANSLOG_SHUTDOWN);
unknown's avatar
unknown committed
3970
  if (log_descriptor.bc.buffer->file != NULL)
3971 3972
    translog_finish_page(&log_descriptor.horizon, &log_descriptor.bc);
  translog_unlock();
3973

3974 3975
  for (i= 0; i < TRANSLOG_BUFFERS_NO; i++)
  {
3976 3977 3978
    struct st_translog_buffer *buffer= (log_descriptor.buffers +
                                        ((i + current_buffer + 1) %
                                         TRANSLOG_BUFFERS_NO));
3979 3980
    translog_buffer_destroy(buffer);
  }
unknown's avatar
unknown committed
3981
  translog_status= TRANSLOG_UNINITED;
3982

3983
  /* close files */
unknown's avatar
unknown committed
3984 3985
  while ((file= (TRANSLOG_FILE **)pop_dynamic(&log_descriptor.open_files)))
    translog_close_log_file(*file);
3986 3987 3988 3989 3990
  pthread_mutex_destroy(&log_descriptor.sent_to_disk_lock);
  pthread_mutex_destroy(&log_descriptor.file_header_lock);
  pthread_mutex_destroy(&log_descriptor.unfinished_files_lock);
  pthread_mutex_destroy(&log_descriptor.purger_lock);
  pthread_mutex_destroy(&log_descriptor.log_flush_lock);
unknown's avatar
unknown committed
3991 3992
  rwlock_destroy(&log_descriptor.open_files_lock);
  delete_dynamic(&log_descriptor.open_files);
3993 3994
  delete_dynamic(&log_descriptor.unfinished_files);

unknown's avatar
unknown committed
3995 3996
  if (log_descriptor.directory_fd >= 0)
    my_close(log_descriptor.directory_fd, MYF(MY_WME));
3997
  my_atomic_rwlock_destroy(&LOCK_id_to_share);
3998 3999
  if (id_to_share != NULL)
    my_free((uchar*)(id_to_share + 1), MYF(MY_WME));
4000 4001 4002 4003 4004
  DBUG_VOID_RETURN;
}


/*
unknown's avatar
unknown committed
4005
  @brief Starts new page.
4006

unknown's avatar
unknown committed
4007 4008 4009 4010
  @param horizon         \ Position in file and buffer where we are
  @param cursor          /
  @param prev_buffer     Buffer which should be flushed will be assigned here.
                         This is always set (to NULL if nothing to flush).
4011

unknown's avatar
unknown committed
4012 4013 4014
  @note We do not want to flush the buffer immediately because we want to
  let caller of this function first advance 'horizon' pointer and unlock the
  loghandler and only then flush the log which can take some time.
4015

unknown's avatar
unknown committed
4016 4017
  @retval 0 OK
  @retval 1 Error
4018 4019 4020 4021 4022 4023 4024 4025 4026
*/

static my_bool translog_page_next(TRANSLOG_ADDRESS *horizon,
                                  struct st_buffer_cursor *cursor,
                                  struct st_translog_buffer **prev_buffer)
{
  struct st_translog_buffer *buffer= cursor->buffer;
  DBUG_ENTER("translog_page_next");

4027
  *prev_buffer= NULL;
unknown's avatar
unknown committed
4028
  if ((cursor->ptr + TRANSLOG_PAGE_SIZE >
4029
       cursor->buffer->buffer + TRANSLOG_WRITE_BUFFER) ||
4030 4031
      (LSN_OFFSET(*horizon) >
       log_descriptor.log_file_max_size - TRANSLOG_PAGE_SIZE))
4032
  {
unknown's avatar
unknown committed
4033 4034
    DBUG_PRINT("info", ("Switch to next buffer  Buffer Size: %lu (%lu) => %d  "
                        "File size: %lu  max: %lu => %d",
4035
                        (ulong) cursor->buffer->size,
unknown's avatar
unknown committed
4036
                        (ulong) (cursor->ptr - cursor->buffer->buffer),
4037
                        (cursor->ptr + TRANSLOG_PAGE_SIZE >
4038
                         cursor->buffer->buffer + TRANSLOG_WRITE_BUFFER),
4039
                        (ulong) LSN_OFFSET(*horizon),
4040
                        (ulong) log_descriptor.log_file_max_size,
4041 4042 4043
                        (LSN_OFFSET(*horizon) >
                         (log_descriptor.log_file_max_size -
                          TRANSLOG_PAGE_SIZE))));
4044
    if (translog_buffer_next(horizon, cursor,
4045 4046 4047
                             LSN_OFFSET(*horizon) >
                             (log_descriptor.log_file_max_size -
                              TRANSLOG_PAGE_SIZE)))
4048 4049
      DBUG_RETURN(1);
    *prev_buffer= buffer;
unknown's avatar
unknown committed
4050
    DBUG_PRINT("info", ("Buffer #%u (0x%lu): have to be flushed",
4051 4052 4053 4054
                        (uint) buffer->buffer_no, (ulong) buffer));
  }
  else
  {
unknown's avatar
unknown committed
4055 4056
    DBUG_PRINT("info", ("Use the same buffer #%u (0x%lu): "
                        "Buffer Size: %lu (%lu)",
4057 4058 4059
                        (uint) buffer->buffer_no,
                        (ulong) buffer,
                        (ulong) cursor->buffer->size,
unknown's avatar
unknown committed
4060
                        (ulong) (cursor->ptr - cursor->buffer->buffer)));
4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078
    translog_finish_page(horizon, cursor);
    translog_new_page_header(horizon, cursor);
  }
  DBUG_RETURN(0);
}


/*
  Write data of given length to the current page

  SYNOPSIS
    translog_write_data_on_page()
    horizon              \ Pointers on file and buffer
    cursor               /
    length               IN     length of the chunk
    buffer               buffer with data

  RETURN
unknown's avatar
unknown committed
4079 4080
    0  OK
    1  Error
4081 4082
*/

4083 4084 4085
static my_bool translog_write_data_on_page(TRANSLOG_ADDRESS *horizon,
                                           struct st_buffer_cursor *cursor,
                                           translog_size_t length,
unknown's avatar
unknown committed
4086
                                           uchar *buffer)
4087 4088
{
  DBUG_ENTER("translog_write_data_on_page");
unknown's avatar
unknown committed
4089 4090
  DBUG_PRINT("enter", ("Chunk length: %lu  Page size %u",
                       (ulong) length, (uint) cursor->current_page_fill));
4091
  DBUG_ASSERT(length > 0);
unknown's avatar
unknown committed
4092
  DBUG_ASSERT(length + cursor->current_page_fill <= TRANSLOG_PAGE_SIZE);
unknown's avatar
unknown committed
4093
  DBUG_ASSERT(length + cursor->ptr <= cursor->buffer->buffer +
4094 4095
              TRANSLOG_WRITE_BUFFER);

unknown's avatar
unknown committed
4096
  memcpy(cursor->ptr, buffer, length);
4097
  cursor->ptr+= length;
unknown's avatar
unknown committed
4098 4099
  (*horizon)+= length; /* adds offset */
  cursor->current_page_fill+= length;
4100 4101
  if (!cursor->chaser)
    cursor->buffer->size+= length;
unknown's avatar
unknown committed
4102 4103
  DBUG_PRINT("info", ("Write data buffer #%u: 0x%lx  "
                      "chaser: %d  Size: %lu (%lu)",
4104 4105
                      (uint) cursor->buffer->buffer_no, (ulong) cursor->buffer,
                      cursor->chaser, (ulong) cursor->buffer->size,
unknown's avatar
unknown committed
4106
                      (ulong) (cursor->ptr - cursor->buffer->buffer)));
unknown's avatar
unknown committed
4107
  translog_check_cursor(cursor);
4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123

  DBUG_RETURN(0);
}


/*
  Write data from parts of given length to the current page

  SYNOPSIS
    translog_write_parts_on_page()
    horizon              \ Pointers on file and buffer
    cursor               /
    length               IN     length of the chunk
    parts                IN/OUT chunk source

  RETURN
unknown's avatar
unknown committed
4124 4125
    0  OK
    1  Error
4126 4127
*/

4128 4129 4130 4131
static my_bool translog_write_parts_on_page(TRANSLOG_ADDRESS *horizon,
                                            struct st_buffer_cursor *cursor,
                                            translog_size_t length,
                                            struct st_translog_parts *parts)
4132 4133 4134 4135
{
  translog_size_t left= length;
  uint cur= (uint) parts->current;
  DBUG_ENTER("translog_write_parts_on_page");
unknown's avatar
unknown committed
4136
  DBUG_PRINT("enter", ("Chunk length: %lu  parts: %u of %u. Page size: %u  "
4137 4138
                       "Buffer size: %lu (%lu)",
                       (ulong) length,
4139
                       (uint) (cur + 1), (uint) parts->elements,
unknown's avatar
unknown committed
4140
                       (uint) cursor->current_page_fill,
4141
                       (ulong) cursor->buffer->size,
unknown's avatar
unknown committed
4142
                       (ulong) (cursor->ptr - cursor->buffer->buffer)));
4143
  DBUG_ASSERT(length > 0);
unknown's avatar
unknown committed
4144
  DBUG_ASSERT(length + cursor->current_page_fill <= TRANSLOG_PAGE_SIZE);
unknown's avatar
unknown committed
4145
  DBUG_ASSERT(length + cursor->ptr <= cursor->buffer->buffer +
4146 4147 4148 4149 4150
              TRANSLOG_WRITE_BUFFER);

  do
  {
    translog_size_t len;
4151 4152
    LEX_CUSTRING *part;
    const uchar *buff;
4153

4154 4155
    DBUG_ASSERT(cur < parts->elements);
    part= parts->parts + cur;
4156
    buff= part->str;
4157 4158 4159
    DBUG_PRINT("info", ("Part: %u  Length: %lu  left: %lu  buff: 0x%lx",
                        (uint) (cur + 1), (ulong) part->length, (ulong) left,
                        (ulong) buff));
4160

4161
    if (part->length > left)
4162 4163 4164
    {
      /* we should write less then the current part */
      len= left;
4165 4166
      part->length-= len;
      part->str+= len;
unknown's avatar
unknown committed
4167
      DBUG_PRINT("info", ("Set new part: %u  Length: %lu",
4168
                          (uint) (cur + 1), (ulong) part->length));
4169 4170 4171
    }
    else
    {
4172
      len= (translog_size_t) part->length;
4173 4174 4175 4176 4177
      cur++;
      DBUG_PRINT("info", ("moved to next part (len: %lu)", (ulong) len));
    }
    DBUG_PRINT("info", ("copy: 0x%lx <- 0x%lx  %u",
                        (ulong) cursor->ptr, (ulong)buff, (uint)len));
4178 4179 4180 4181 4182 4183
    if (likely(len))
    {
      memcpy(cursor->ptr, buff, len);
      left-= len;
      cursor->ptr+= len;
    }
4184 4185
  } while (left);

unknown's avatar
unknown committed
4186
  DBUG_PRINT("info", ("Horizon: (%lu,0x%lx)  Length %lu(0x%lx)",
unknown's avatar
unknown committed
4187
                      LSN_IN_PARTS(*horizon),
4188
                      (ulong) length, (ulong) length));
4189
  parts->current= cur;
unknown's avatar
unknown committed
4190 4191
  (*horizon)+= length; /* offset increasing */
  cursor->current_page_fill+= length;
4192 4193
  if (!cursor->chaser)
    cursor->buffer->size+= length;
unknown's avatar
unknown committed
4194 4195 4196 4197
  /*
    We do not not updating parts->total_record_length here because it is
    need only before writing record to have total length
  */
4198 4199
  DBUG_PRINT("info", ("Write parts buffer #%u: 0x%lx  "
                      "chaser: %d  Size: %lu (%lu)  "
unknown's avatar
unknown committed
4200
                      "Horizon: (%lu,0x%lx)  buff offset: 0x%lx",
4201 4202
                      (uint) cursor->buffer->buffer_no, (ulong) cursor->buffer,
                      cursor->chaser, (ulong) cursor->buffer->size,
unknown's avatar
unknown committed
4203
                      (ulong) (cursor->ptr - cursor->buffer->buffer),
unknown's avatar
unknown committed
4204
                      LSN_IN_PARTS(*horizon),
4205 4206
                      (ulong) (LSN_OFFSET(cursor->buffer->offset) +
                               cursor->buffer->size)));
unknown's avatar
unknown committed
4207
  translog_check_cursor(cursor);
4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218

  DBUG_RETURN(0);
}


/*
  Put 1 group chunk type 0 header into parts array

  SYNOPSIS
    translog_write_variable_record_1group_header()
    parts                Descriptor of record source parts
unknown's avatar
unknown committed
4219
    type                 The log record type
4220
    short_trid           Short transaction ID or 0 if it has no sense
4221 4222 4223 4224 4225 4226 4227 4228 4229
    header_length        Calculated header length of chunk type 0
    chunk0_header        Buffer for the chunk header writing
*/

static void
translog_write_variable_record_1group_header(struct st_translog_parts *parts,
                                             enum translog_record_type type,
                                             SHORT_TRANSACTION_ID short_trid,
                                             uint16 header_length,
unknown's avatar
unknown committed
4230
                                             uchar *chunk0_header)
4231
{
4232
  LEX_CUSTRING *part;
unknown's avatar
unknown committed
4233
  DBUG_ASSERT(parts->current != 0);     /* first part is left for header */
4234
  part= parts->parts + (--parts->current);
4235
  parts->total_record_length+= (translog_size_t) (part->length= header_length);
4236
  part->str= chunk0_header;
unknown's avatar
unknown committed
4237
  /* puts chunk type */
unknown's avatar
unknown committed
4238
  *chunk0_header= (uchar) (type | TRANSLOG_CHUNK_LSN);
4239
  int2store(chunk0_header + 1, short_trid);
unknown's avatar
unknown committed
4240
  /* puts record length */
4241 4242 4243
  translog_write_variable_record_1group_code_len(chunk0_header + 3,
                                                 parts->record_length,
                                                 header_length);
unknown's avatar
unknown committed
4244
  /* puts 0 as chunk length which indicate 1 group record */
4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256
  int2store(chunk0_header + header_length - 2, 0);
}


/*
  Increase number of writers for this buffer

  SYNOPSIS
    translog_buffer_increase_writers()
    buffer               target buffer
*/

unknown's avatar
unknown committed
4257 4258
static inline void
translog_buffer_increase_writers(struct st_translog_buffer *buffer)
4259 4260
{
  DBUG_ENTER("translog_buffer_increase_writers");
unknown's avatar
unknown committed
4261
  translog_buffer_lock_assert_owner(buffer);
4262
  buffer->copy_to_buffer_in_progress++;
4263
  DBUG_PRINT("info", ("copy_to_buffer_in_progress. Buffer #%u  0x%lx  progress: %d",
4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280
                      (uint) buffer->buffer_no, (ulong) buffer,
                      buffer->copy_to_buffer_in_progress));
  DBUG_VOID_RETURN;
}


/*
  Decrease number of writers for this buffer

  SYNOPSIS
    translog_buffer_decrease_writers()
    buffer               target buffer
*/

static void translog_buffer_decrease_writers(struct st_translog_buffer *buffer)
{
  DBUG_ENTER("translog_buffer_decrease_writers");
unknown's avatar
unknown committed
4281
  translog_buffer_lock_assert_owner(buffer);
4282
  buffer->copy_to_buffer_in_progress--;
4283 4284 4285 4286
  DBUG_PRINT("info",
             ("copy_to_buffer_in_progress. Buffer #%u  0x%lx  progress: %d",
              (uint) buffer->buffer_no, (ulong) buffer,
              buffer->copy_to_buffer_in_progress));
unknown's avatar
unknown committed
4287 4288
  if (buffer->copy_to_buffer_in_progress == 0)
    pthread_cond_broadcast(&buffer->waiting_filling_buffer);
4289 4290 4291 4292
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322
/**
  @brief Skip to the next page for chaser (thread which advanced horizon
  pointer and now feeling the buffer)

  @param horizon         \ Pointers on file position and buffer
  @param cursor          /

  @retval 1 OK
  @retval 0 Error
*/

static my_bool translog_chaser_page_next(TRANSLOG_ADDRESS *horizon,
                                         struct st_buffer_cursor *cursor)
{
  struct st_translog_buffer *buffer_to_flush;
  my_bool rc;
  DBUG_ENTER("translog_chaser_page_next");
  DBUG_ASSERT(cursor->chaser);
  rc= translog_page_next(horizon, cursor, &buffer_to_flush);
  if (buffer_to_flush != NULL)
  {
    translog_buffer_lock(buffer_to_flush);
    translog_buffer_decrease_writers(buffer_to_flush);
    if (!rc)
      rc= translog_buffer_flush(buffer_to_flush);
    translog_buffer_unlock(buffer_to_flush);
  }
  DBUG_RETURN(rc);
}

4323 4324 4325 4326 4327 4328 4329 4330 4331 4332
/*
  Put chunk 2 from new page beginning

  SYNOPSIS
    translog_write_variable_record_chunk2_page()
    parts                Descriptor of record source parts
    horizon              \ Pointers on file position and buffer
    cursor               /

  RETURN
unknown's avatar
unknown committed
4333 4334
    0  OK
    1  Error
4335 4336 4337 4338 4339 4340 4341
*/

static my_bool
translog_write_variable_record_chunk2_page(struct st_translog_parts *parts,
                                           TRANSLOG_ADDRESS *horizon,
                                           struct st_buffer_cursor *cursor)
{
unknown's avatar
unknown committed
4342
  uchar chunk2_header[1];
4343
  DBUG_ENTER("translog_write_variable_record_chunk2_page");
unknown's avatar
unknown committed
4344
  chunk2_header[0]= TRANSLOG_CHUNK_NOHDR;
4345

unknown's avatar
unknown committed
4346
  if (translog_chaser_page_next(horizon, cursor))
4347 4348
    DBUG_RETURN(1);

unknown's avatar
unknown committed
4349
  /* Puts chunk type */
4350
  translog_write_data_on_page(horizon, cursor, 1, chunk2_header);
unknown's avatar
unknown committed
4351
  /* Puts chunk body */
4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368
  translog_write_parts_on_page(horizon, cursor,
                               log_descriptor.page_capacity_chunk_2, parts);
  DBUG_RETURN(0);
}


/*
  Put chunk 3 of requested length in the buffer from new page beginning

  SYNOPSIS
    translog_write_variable_record_chunk3_page()
    parts                Descriptor of record source parts
    length               Length of this chunk
    horizon              \ Pointers on file position and buffer
    cursor               /

  RETURN
unknown's avatar
unknown committed
4369 4370
    0  OK
    1  Error
4371 4372 4373 4374 4375 4376 4377 4378
*/

static my_bool
translog_write_variable_record_chunk3_page(struct st_translog_parts *parts,
                                           uint16 length,
                                           TRANSLOG_ADDRESS *horizon,
                                           struct st_buffer_cursor *cursor)
{
4379
  LEX_CUSTRING *part;
unknown's avatar
unknown committed
4380
  uchar chunk3_header[1 + 2];
4381 4382
  DBUG_ENTER("translog_write_variable_record_chunk3_page");

unknown's avatar
unknown committed
4383
  if (translog_chaser_page_next(horizon, cursor))
4384
    DBUG_RETURN(1);
unknown's avatar
unknown committed
4385

4386 4387 4388 4389 4390 4391 4392
  if (length == 0)
  {
    /* It was call to write page header only (no data for chunk 3) */
    DBUG_PRINT("info", ("It is a call to make page header only"));
    DBUG_RETURN(0);
  }

unknown's avatar
unknown committed
4393
  DBUG_ASSERT(parts->current != 0);       /* first part is left for header */
4394
  part= parts->parts + (--parts->current);
4395
  parts->total_record_length+= (translog_size_t) (part->length= 1 + 2);
4396
  part->str= chunk3_header;
unknown's avatar
unknown committed
4397
  /* Puts chunk type */
unknown's avatar
unknown committed
4398
  *chunk3_header= (uchar) (TRANSLOG_CHUNK_LNGTH);
unknown's avatar
unknown committed
4399
  /* Puts chunk length */
4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415
  int2store(chunk3_header + 1, length);

  translog_write_parts_on_page(horizon, cursor, length + 1 + 2, parts);
  DBUG_RETURN(0);
}

/*
  Move log pointer (horizon) on given number pages starting from next page,
  and given offset on the last page

  SYNOPSIS
    translog_advance_pointer()
    pages                Number of full pages starting from the next one
    last_page_data       Plus this data on the last page

  RETURN
unknown's avatar
unknown committed
4416 4417
    0  OK
    1  Error
4418 4419
*/

unknown's avatar
unknown committed
4420
static my_bool translog_advance_pointer(int pages, uint16 last_page_data)
4421
{
unknown's avatar
unknown committed
4422 4423
  translog_size_t last_page_offset= (log_descriptor.page_overhead +
                                     last_page_data);
4424
  translog_size_t offset= (TRANSLOG_PAGE_SIZE -
unknown's avatar
unknown committed
4425
                           log_descriptor.bc.current_page_fill +
4426
                           pages * TRANSLOG_PAGE_SIZE + last_page_offset);
4427 4428
  translog_size_t buffer_end_offset, file_end_offset, min_offset;
  DBUG_ENTER("translog_advance_pointer");
4429
  DBUG_PRINT("enter", ("Pointer:  (%lu, 0x%lx) + %u + %u pages + %u + %u",
unknown's avatar
unknown committed
4430
                       LSN_IN_PARTS(log_descriptor.horizon),
4431
                       (uint) (TRANSLOG_PAGE_SIZE -
unknown's avatar
unknown committed
4432
                               log_descriptor.bc.current_page_fill),
4433 4434
                       pages, (uint) log_descriptor.page_overhead,
                       (uint) last_page_data));
4435
  translog_lock_assert_owner();
4436

unknown's avatar
unknown committed
4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451
  if (pages == -1)
  {
    /*
      It is special case when we advance the pointer on the same page.
      It can happened when we write last part of multi-group record.
    */
    DBUG_ASSERT(last_page_data + log_descriptor.bc.current_page_fill <=
                TRANSLOG_PAGE_SIZE);
    offset= last_page_data;
    last_page_offset= log_descriptor.bc.current_page_fill + last_page_data;
    goto end;
  }
  DBUG_PRINT("info", ("last_page_offset %lu", (ulong) last_page_offset));
  DBUG_ASSERT(last_page_offset <= TRANSLOG_PAGE_SIZE);

unknown's avatar
unknown committed
4452 4453 4454 4455 4456 4457 4458 4459
  /*
    The loop will be executed 1-3 times. Usually we advance the
    pointer to fill only the current buffer (if we have more then 1/2 of
    buffer free or 2 buffers (rest of current and all next). In case of
    really huge record end where we write last group with "table of
    content" of all groups and ignore buffer borders we can occupy
    3 buffers.
  */
4460 4461
  for (;;)
  {
unknown's avatar
unknown committed
4462
    uint8 new_buffer_no;
4463 4464 4465
    struct st_translog_buffer *new_buffer;
    struct st_translog_buffer *old_buffer;
    buffer_end_offset= TRANSLOG_WRITE_BUFFER - log_descriptor.bc.buffer->size;
4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478
    if (likely(log_descriptor.log_file_max_size >=
               LSN_OFFSET(log_descriptor.horizon)))
      file_end_offset= (log_descriptor.log_file_max_size -
                        LSN_OFFSET(log_descriptor.horizon));
    else
    {
      /*
        We already have written more then current file limit allow,
        So we will finish this page and start new file
      */
      file_end_offset= (TRANSLOG_PAGE_SIZE -
                        log_descriptor.bc.current_page_fill);
    }
unknown's avatar
unknown committed
4479
    DBUG_PRINT("info", ("offset: %lu  buffer_end_offs: %lu, "
4480 4481 4482 4483 4484 4485 4486 4487
                        "file_end_offs:  %lu",
                        (ulong) offset, (ulong) buffer_end_offset,
                        (ulong) file_end_offset));
    DBUG_PRINT("info", ("Buff #%u %u (0x%lx) offset 0x%lx + size 0x%lx = "
                        "0x%lx (0x%lx)",
                        (uint) log_descriptor.bc.buffer->buffer_no,
                        (uint) log_descriptor.bc.buffer_no,
                        (ulong) log_descriptor.bc.buffer,
4488
                        (ulong) LSN_OFFSET(log_descriptor.bc.buffer->offset),
4489
                        (ulong) log_descriptor.bc.buffer->size,
4490
                        (ulong) (LSN_OFFSET(log_descriptor.bc.buffer->offset) +
4491
                                 log_descriptor.bc.buffer->size),
4492 4493
                        (ulong) LSN_OFFSET(log_descriptor.horizon)));
    DBUG_ASSERT(LSN_OFFSET(log_descriptor.bc.buffer->offset) +
4494
                log_descriptor.bc.buffer->size ==
4495
                LSN_OFFSET(log_descriptor.horizon));
4496 4497 4498 4499 4500 4501 4502 4503

    if (offset <= buffer_end_offset && offset <= file_end_offset)
      break;
    old_buffer= log_descriptor.bc.buffer;
    new_buffer_no= (log_descriptor.bc.buffer_no + 1) % TRANSLOG_BUFFERS_NO;
    new_buffer= log_descriptor.buffers + new_buffer_no;

    translog_buffer_lock(new_buffer);
4504 4505 4506 4507 4508 4509 4510 4511 4512 4513
#ifndef DBUG_OFF
    {
      TRANSLOG_ADDRESS offset= new_buffer->offset;
      TRANSLOG_FILE *file= new_buffer->file;
      uint8 ver= new_buffer->ver;
      translog_lock_assert_owner();
#endif
      translog_wait_for_buffer_free(new_buffer);
#ifndef DBUG_OFF
      /* We keep the handler locked so nobody can start this new buffer */
unknown's avatar
unknown committed
4514 4515
      DBUG_ASSERT(offset == new_buffer->offset && new_buffer->file == NULL &&
                  (file == NULL ? ver : (uint8)(ver + 1)) == new_buffer->ver);
4516 4517
    }
#endif
4518

unknown's avatar
unknown committed
4519
    min_offset= min(buffer_end_offset, file_end_offset);
unknown's avatar
unknown committed
4520
    /* TODO: check is it ptr or size enough */
4521
    log_descriptor.bc.buffer->size+= min_offset;
4522
    log_descriptor.bc.ptr+= min_offset;
unknown's avatar
unknown committed
4523
    DBUG_PRINT("info", ("NewP buffer #%u: 0x%lx  chaser: %d  Size: %lu (%lu)",
4524 4525 4526 4527 4528 4529
                        (uint) log_descriptor.bc.buffer->buffer_no,
                        (ulong) log_descriptor.bc.buffer,
                        log_descriptor.bc.chaser,
                        (ulong) log_descriptor.bc.buffer->size,
                        (ulong) (log_descriptor.bc.ptr -log_descriptor.bc.
                                 buffer->buffer)));
unknown's avatar
unknown committed
4530 4531
    DBUG_ASSERT((ulong) (log_descriptor.bc.ptr -
                         log_descriptor.bc.buffer->buffer) ==
4532 4533 4534 4535 4536 4537 4538
                log_descriptor.bc.buffer->size);
    DBUG_ASSERT(log_descriptor.bc.buffer->buffer_no ==
                log_descriptor.bc.buffer_no);
    translog_buffer_increase_writers(log_descriptor.bc.buffer);

    if (file_end_offset <= buffer_end_offset)
    {
4539 4540 4541
      log_descriptor.horizon+= LSN_ONE_FILE;
      log_descriptor.horizon= LSN_REPLACE_OFFSET(log_descriptor.horizon,
                                                 TRANSLOG_PAGE_SIZE);
unknown's avatar
unknown committed
4542
      DBUG_PRINT("info", ("New file: %lu",
4543
                          (ulong) LSN_FILE_NO(log_descriptor.horizon)));
4544 4545 4546 4547 4548 4549 4550 4551
      if (translog_create_new_file())
      {
        DBUG_RETURN(1);
      }
    }
    else
    {
      DBUG_PRINT("info", ("The same file"));
4552
      log_descriptor.horizon+= min_offset; /* offset increasing */
4553 4554
    }
    translog_start_buffer(new_buffer, &log_descriptor.bc, new_buffer_no);
4555
    old_buffer->next_buffer_offset= new_buffer->offset;
4556
    translog_buffer_unlock(old_buffer);
4557 4558
    offset-= min_offset;
  }
unknown's avatar
unknown committed
4559 4560 4561 4562
  DBUG_PRINT("info", ("drop write_counter"));
  log_descriptor.bc.write_counter= 0;
  log_descriptor.bc.previous_offset= 0;
end:
4563 4564 4565
  log_descriptor.bc.ptr+= offset;
  log_descriptor.bc.buffer->size+= offset;
  translog_buffer_increase_writers(log_descriptor.bc.buffer);
4566
  log_descriptor.horizon+= offset; /* offset increasing */
unknown's avatar
unknown committed
4567 4568 4569
  log_descriptor.bc.current_page_fill= last_page_offset;
  DBUG_PRINT("info", ("NewP buffer #%u: 0x%lx  chaser: %d  Size: %lu (%lu)  "
                      "offset: %u  last page: %u",
4570 4571 4572 4573
                      (uint) log_descriptor.bc.buffer->buffer_no,
                      (ulong) log_descriptor.bc.buffer,
                      log_descriptor.bc.chaser,
                      (ulong) log_descriptor.bc.buffer->size,
unknown's avatar
unknown committed
4574 4575
                      (ulong) (log_descriptor.bc.ptr -
                               log_descriptor.bc.buffer->
4576 4577 4578
                               buffer), (uint) offset,
                      (uint) last_page_offset));
  DBUG_PRINT("info",
4579
             ("pointer moved to: (%lu, 0x%lx)",
unknown's avatar
unknown committed
4580
              LSN_IN_PARTS(log_descriptor.horizon)));
unknown's avatar
unknown committed
4581
  translog_check_cursor(&log_descriptor.bc);
4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598
  log_descriptor.bc.protected= 0;
  DBUG_RETURN(0);
}


/*
  Get page rest

  SYNOPSIS
    translog_get_current_page_rest()

  NOTE loghandler should be locked

  RETURN
    number of bytes left on the current page
*/

unknown's avatar
unknown committed
4599 4600 4601 4602 4603
static uint translog_get_current_page_rest()
{
  return (TRANSLOG_PAGE_SIZE - log_descriptor.bc.current_page_fill);
}

4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616

/*
  Get buffer rest in full pages

  SYNOPSIS
     translog_get_current_buffer_rest()

  NOTE loghandler should be locked

  RETURN
    number of full pages left on the current buffer
*/

unknown's avatar
unknown committed
4617 4618 4619 4620 4621 4622
static uint translog_get_current_buffer_rest()
{
  return ((log_descriptor.bc.buffer->buffer + TRANSLOG_WRITE_BUFFER -
           log_descriptor.bc.ptr) /
          TRANSLOG_PAGE_SIZE);
}
4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640

/*
  Calculate possible group size without first (current) page

  SYNOPSIS
    translog_get_current_group_size()

  NOTE loghandler should be locked

  RETURN
    group size without first (current) page
*/

static translog_size_t translog_get_current_group_size()
{
  /* buffer rest in full pages */
  translog_size_t buffer_rest= translog_get_current_buffer_rest();
  DBUG_ENTER("translog_get_current_group_size");
unknown's avatar
unknown committed
4641
  DBUG_PRINT("info", ("buffer_rest in pages: %u", buffer_rest));
4642 4643 4644 4645 4646

  buffer_rest*= log_descriptor.page_capacity_chunk_2;
  /* in case of only half of buffer free we can write this and next buffer */
  if (buffer_rest < log_descriptor.half_buffer_capacity_chunk_2)
  {
unknown's avatar
unknown committed
4647 4648
    DBUG_PRINT("info", ("buffer_rest: %lu -> add %lu",
                        (ulong) buffer_rest,
4649 4650 4651 4652
                        (ulong) log_descriptor.buffer_capacity_chunk_2));
    buffer_rest+= log_descriptor.buffer_capacity_chunk_2;
  }

unknown's avatar
unknown committed
4653
  DBUG_PRINT("info", ("buffer_rest: %lu", (ulong) buffer_rest));
4654 4655 4656 4657 4658

  DBUG_RETURN(buffer_rest);
}


4659 4660 4661 4662 4663 4664 4665 4666 4667
static inline void set_lsn(LSN *lsn, LSN value)
{
  translog_lock_assert_owner();
  *lsn= value;
  /* we generate LSN so something is not flushed in log */
  log_descriptor.is_everything_flushed= 0;
}


unknown's avatar
unknown committed
4668 4669
/**
   @brief Write variable record in 1 group.
4670

unknown's avatar
unknown committed
4671 4672 4673 4674 4675 4676 4677 4678 4679 4680
   @param  lsn             LSN of the record will be written here
   @param  type            the log record type
   @param  short_trid      Short transaction ID or 0 if it has no sense
   @param  parts           Descriptor of record source parts
   @param  buffer_to_flush Buffer which have to be flushed if it is not 0
   @param  header_length   Calculated header length of chunk type 0
   @param  trn             Transaction structure pointer for hooks by
                           record log type, for short_id
   @param  hook_arg        Argument which will be passed to pre-write and
                           in-write hooks of this record.
4681

4682 4683 4684 4685
   @note
     We must have a translog_lock() when entering this function
     We must have buffer_to_flush locked (if not null)

unknown's avatar
unknown committed
4686 4687 4688
   @return Operation status
     @retval 0      OK
     @retval 1      Error
4689 4690 4691 4692 4693
*/

static my_bool
translog_write_variable_record_1group(LSN *lsn,
                                      enum translog_record_type type,
unknown's avatar
unknown committed
4694
                                      MARIA_HA *tbl_info,
4695 4696 4697 4698
                                      SHORT_TRANSACTION_ID short_trid,
                                      struct st_translog_parts *parts,
                                      struct st_translog_buffer
                                      *buffer_to_flush, uint16 header_length,
unknown's avatar
unknown committed
4699
                                      TRN *trn, void *hook_arg)
4700 4701 4702 4703 4704 4705 4706
{
  TRANSLOG_ADDRESS horizon;
  struct st_buffer_cursor cursor;
  int rc= 0;
  uint i;
  translog_size_t record_rest, full_pages, first_page;
  uint additional_chunk3_page= 0;
unknown's avatar
unknown committed
4707
  uchar chunk0_header[1 + 2 + 5 + 2];
4708
  DBUG_ENTER("translog_write_variable_record_1group");
unknown's avatar
unknown committed
4709
  translog_lock_assert_owner();
4710 4711
  if (buffer_to_flush)
    translog_buffer_lock_assert_owner(buffer_to_flush);
4712

4713
  set_lsn(lsn, horizon= log_descriptor.horizon);
4714
  if (translog_set_lsn_for_files(LSN_FILE_NO(*lsn), LSN_FILE_NO(*lsn),
unknown's avatar
unknown committed
4715
                                 *lsn, TRUE) ||
4716 4717
      (log_record_type_descriptor[type].inwrite_hook &&
       (*log_record_type_descriptor[type].inwrite_hook)(type, trn, tbl_info,
unknown's avatar
unknown committed
4718
                                                        lsn, hook_arg)))
4719
  {
unknown's avatar
unknown committed
4720
    translog_unlock();
4721 4722 4723 4724 4725
    DBUG_RETURN(1);
  }
  cursor= log_descriptor.bc;
  cursor.chaser= 1;

unknown's avatar
unknown committed
4726
  /* Advance pointer to be able unlock the loghandler */
4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739
  first_page= translog_get_current_page_rest();
  record_rest= parts->record_length - (first_page - header_length);
  full_pages= record_rest / log_descriptor.page_capacity_chunk_2;
  record_rest= (record_rest % log_descriptor.page_capacity_chunk_2);

  if (record_rest + 1 == log_descriptor.page_capacity_chunk_2)
  {
    DBUG_PRINT("info", ("2 chunks type 3 is needed"));
    /* We will write 2 chunks type 3 at the end of this group */
    additional_chunk3_page= 1;
    record_rest= 1;
  }

unknown's avatar
unknown committed
4740 4741
  DBUG_PRINT("info", ("first_page: %u (%u)  full_pages: %u (%lu)  "
                      "additional: %u (%u)  rest %u = %u",
4742 4743 4744 4745 4746 4747 4748 4749 4750
                      first_page, first_page - header_length,
                      full_pages,
                      (ulong) full_pages *
                      log_descriptor.page_capacity_chunk_2,
                      additional_chunk3_page,
                      additional_chunk3_page *
                      (log_descriptor.page_capacity_chunk_2 - 1),
                      record_rest, parts->record_length));
  /* record_rest + 3 is chunk type 3 overhead + record_rest */
unknown's avatar
unknown committed
4751
  rc|= translog_advance_pointer((int)(full_pages + additional_chunk3_page),
unknown's avatar
unknown committed
4752
                                (record_rest ? record_rest + 3 : 0));
4753 4754
  log_descriptor.bc.buffer->last_lsn= *lsn;

4755
  translog_unlock();
4756 4757

  /*
unknown's avatar
unknown committed
4758
     Check if we switched buffer and need process it (current buffer is
4759 4760 4761 4762 4763 4764
     unlocked already => we will not delay other threads
  */
  if (buffer_to_flush != NULL)
  {
    if (!rc)
      rc= translog_buffer_flush(buffer_to_flush);
4765
    translog_buffer_unlock(buffer_to_flush);
4766 4767 4768 4769 4770 4771 4772 4773 4774 4775
  }
  if (rc)
    DBUG_RETURN(1);

  translog_write_variable_record_1group_header(parts, type, short_trid,
                                               header_length, chunk0_header);

  /* fill the pages */
  translog_write_parts_on_page(&horizon, &cursor, first_page, parts);

unknown's avatar
unknown committed
4776
  DBUG_PRINT("info", ("absolute horizon: (%lu,0x%lx)  local: (%lu,0x%lx)",
unknown's avatar
unknown committed
4777 4778
                      LSN_IN_PARTS(log_descriptor.horizon),
                      LSN_IN_PARTS(horizon)));
4779 4780 4781 4782 4783 4784

  for (i= 0; i < full_pages; i++)
  {
    if (translog_write_variable_record_chunk2_page(parts, &horizon, &cursor))
      DBUG_RETURN(1);

unknown's avatar
unknown committed
4785
    DBUG_PRINT("info", ("absolute horizon: (%lu,0x%lx)  local: (%lu,0x%lx)",
unknown's avatar
unknown committed
4786 4787
                        LSN_IN_PARTS(log_descriptor.horizon),
                        LSN_IN_PARTS(horizon)));
4788 4789 4790 4791 4792 4793 4794 4795 4796
  }

  if (additional_chunk3_page)
  {
    if (translog_write_variable_record_chunk3_page(parts,
                                                   log_descriptor.
                                                   page_capacity_chunk_2 - 2,
                                                   &horizon, &cursor))
      DBUG_RETURN(1);
unknown's avatar
unknown committed
4797
    DBUG_PRINT("info", ("absolute horizon: (%lu,0x%lx)  local: (%lu,0x%lx)",
unknown's avatar
unknown committed
4798 4799
                        LSN_IN_PARTS(log_descriptor.horizon),
                        LSN_IN_PARTS(horizon)));
unknown's avatar
unknown committed
4800
    DBUG_ASSERT(cursor.current_page_fill == TRANSLOG_PAGE_SIZE);
4801 4802 4803 4804 4805 4806
  }

  if (translog_write_variable_record_chunk3_page(parts,
                                                 record_rest,
                                                 &horizon, &cursor))
    DBUG_RETURN(1);
unknown's avatar
unknown committed
4807
    DBUG_PRINT("info", ("absolute horizon: (%lu,0x%lx)  local: (%lu,0x%lx)",
4808 4809 4810 4811
                        (ulong) LSN_FILE_NO(log_descriptor.horizon),
                        (ulong) LSN_OFFSET(log_descriptor.horizon),
                        (ulong) LSN_FILE_NO(horizon),
                        (ulong) LSN_OFFSET(horizon)));
4812

4813 4814 4815
  translog_buffer_lock(cursor.buffer);
  translog_buffer_decrease_writers(cursor.buffer);
  translog_buffer_unlock(cursor.buffer);
4816 4817 4818 4819
  DBUG_RETURN(rc);
}


unknown's avatar
unknown committed
4820 4821
/**
   @brief Write variable record in 1 chunk.
4822

unknown's avatar
unknown committed
4823 4824 4825 4826 4827 4828 4829 4830 4831 4832
   @param  lsn             LSN of the record will be written here
   @param  type            the log record type
   @param  short_trid      Short transaction ID or 0 if it has no sense
   @param  parts           Descriptor of record source parts
   @param  buffer_to_flush Buffer which have to be flushed if it is not 0
   @param  header_length   Calculated header length of chunk type 0
   @param  trn             Transaction structure pointer for hooks by
                           record log type, for short_id
   @param  hook_arg        Argument which will be passed to pre-write and
                           in-write hooks of this record.
4833

4834 4835 4836 4837
   @note
     We must have a translog_lock() when entering this function
     We must have buffer_to_flush locked (if not null)

unknown's avatar
unknown committed
4838 4839 4840
   @return Operation status
     @retval 0      OK
     @retval 1      Error
4841 4842 4843 4844 4845
*/

static my_bool
translog_write_variable_record_1chunk(LSN *lsn,
                                      enum translog_record_type type,
unknown's avatar
unknown committed
4846
                                      MARIA_HA *tbl_info,
4847 4848 4849 4850
                                      SHORT_TRANSACTION_ID short_trid,
                                      struct st_translog_parts *parts,
                                      struct st_translog_buffer
                                      *buffer_to_flush, uint16 header_length,
unknown's avatar
unknown committed
4851
                                      TRN *trn, void *hook_arg)
4852 4853
{
  int rc;
unknown's avatar
unknown committed
4854
  uchar chunk0_header[1 + 2 + 5 + 2];
4855
  DBUG_ENTER("translog_write_variable_record_1chunk");
unknown's avatar
unknown committed
4856
  translog_lock_assert_owner();
4857 4858
  if (buffer_to_flush)
    translog_buffer_lock_assert_owner(buffer_to_flush);
4859 4860 4861

  translog_write_variable_record_1group_header(parts, type, short_trid,
                                               header_length, chunk0_header);
4862
  set_lsn(lsn, log_descriptor.horizon);
4863 4864 4865 4866
  if (translog_set_lsn_for_files(LSN_FILE_NO(*lsn), LSN_FILE_NO(*lsn),
                                 *lsn, TRUE) ||
      (log_record_type_descriptor[type].inwrite_hook &&
       (*log_record_type_descriptor[type].inwrite_hook)(type, trn, tbl_info,
unknown's avatar
unknown committed
4867
                                                        lsn, hook_arg)))
4868
  {
unknown's avatar
unknown committed
4869
    translog_unlock();
4870 4871 4872 4873 4874 4875 4876
    DBUG_RETURN(1);
  }

  rc= translog_write_parts_on_page(&log_descriptor.horizon,
                                   &log_descriptor.bc,
                                   parts->total_record_length, parts);
  log_descriptor.bc.buffer->last_lsn= *lsn;
4877
  translog_unlock();
4878 4879 4880 4881 4882 4883 4884 4885 4886

  /*
     check if we switched buffer and need process it (current buffer is
     unlocked already => we will not delay other threads
  */
  if (buffer_to_flush != NULL)
  {
    if (!rc)
      rc= translog_buffer_flush(buffer_to_flush);
4887
    translog_buffer_unlock(buffer_to_flush);
4888 4889 4890 4891 4892 4893 4894
  }

  DBUG_RETURN(rc);
}


/*
unknown's avatar
unknown committed
4895
  @brief Calculates and write LSN difference (compressed LSN).
4896

unknown's avatar
unknown committed
4897 4898 4899
  @param base_lsn        LSN from which we calculate difference
  @param lsn             LSN for codding
  @param dst             Result will be written to dst[-pack_length] .. dst[-1]
4900

unknown's avatar
unknown committed
4901 4902
  @note To store an LSN in a compact way we will use the following compression:
    If a log record has LSN1, and it contains the LSN2 as a back reference,
unknown's avatar
unknown committed
4903
    Instead of LSN2 we write LSN1-LSN2, encoded as:
4904 4905 4906
     two bits     the number N (see below)
     14 bits
     N bytes
unknown's avatar
unknown committed
4907
     That is, LSN is encoded in 2..5 bytes, and the number of bytes minus 2
4908 4909
     is stored in the first two bits.

unknown's avatar
unknown committed
4910 4911 4912
  @note function made to write the result in backward direction with no
  special sense or tricks both directions are equal in complicity

unknown's avatar
unknown committed
4913
  @retval #    pointer on coded LSN
4914 4915
*/

unknown's avatar
unknown committed
4916
static uchar *translog_put_LSN_diff(LSN base_lsn, LSN lsn, uchar *dst)
4917
{
unknown's avatar
unknown committed
4918
  uint64 diff;
4919
  DBUG_ENTER("translog_put_LSN_diff");
unknown's avatar
unknown committed
4920
  DBUG_PRINT("enter", ("Base: (0x%lu,0x%lx)  val: (0x%lu,0x%lx)  dst: 0x%lx",
unknown's avatar
unknown committed
4921 4922
                       LSN_IN_PARTS(base_lsn), LSN_IN_PARTS(lsn),
                       (ulong) dst));
unknown's avatar
unknown committed
4923 4924 4925 4926
  DBUG_ASSERT(base_lsn > lsn);
  diff= base_lsn - lsn;
  DBUG_PRINT("info", ("Diff: 0x%llx", (ulonglong) diff));
  if (diff <= 0x3FFF)
4927
  {
unknown's avatar
unknown committed
4928 4929 4930 4931 4932
    dst-= 2;
    /*
      Note we store this high uchar first to ensure that first uchar has
      0 in the 3 upper bits.
    */
4933 4934
    dst[0]= (uchar)(diff >> 8);
    dst[1]= (uchar)(diff & 0xFF);
4935
  }
unknown's avatar
unknown committed
4936
  else if (diff <= 0x3FFFFFL)
4937
  {
unknown's avatar
unknown committed
4938
    dst-= 3;
4939
    dst[0]= (uchar)(0x40 | (diff >> 16));
unknown's avatar
unknown committed
4940 4941 4942 4943 4944
    int2store(dst + 1, diff & 0xFFFF);
  }
  else if (diff <= 0x3FFFFFFFL)
  {
    dst-= 4;
4945
    dst[0]= (uchar)(0x80 | (diff >> 24));
unknown's avatar
unknown committed
4946 4947 4948
    int3store(dst + 1, diff & 0xFFFFFFL);
  }
  else if (diff <= LL(0x3FFFFFFFFF))
unknown's avatar
unknown committed
4949

unknown's avatar
unknown committed
4950 4951
  {
    dst-= 5;
4952
    dst[0]= (uchar)(0xC0 | (diff >> 32));
unknown's avatar
unknown committed
4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964
    int4store(dst + 1, diff & 0xFFFFFFFFL);
  }
  else
  {
    /*
      It is full LSN after special 1 diff (which is impossible
      in real life)
    */
    dst-= 2 + LSN_STORE_SIZE;
    dst[0]= 0;
    dst[1]= 1;
    lsn_store(dst + 2, lsn);
4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980
  }
  DBUG_PRINT("info", ("new dst: 0x%lx", (ulong) dst));
  DBUG_RETURN(dst);
}


/*
  Get LSN from LSN-difference (compressed LSN)

  SYNOPSIS
    translog_get_LSN_from_diff()
    base_lsn             LSN from which we calculate difference
    src                  pointer to coded lsn
    dst                  pointer to buffer where to write 7byte LSN

  NOTE:
unknown's avatar
unknown committed
4981
    To store an LSN in a compact way we will use the following compression:
4982 4983

    If a log record has LSN1, and it contains the lSN2 as a back reference,
unknown's avatar
unknown committed
4984
    Instead of LSN2 we write LSN1-LSN2, encoded as:
4985 4986 4987 4988 4989

     two bits     the number N (see below)
     14 bits
     N bytes

unknown's avatar
unknown committed
4990 4991
    That is, LSN is encoded in 2..5 bytes, and the number of bytes minus 2
    is stored in the first two bits.
4992 4993 4994 4995 4996

  RETURN
    pointer to buffer after decoded LSN
*/

unknown's avatar
unknown committed
4997
static uchar *translog_get_LSN_from_diff(LSN base_lsn, uchar *src, uchar *dst)
4998 4999 5000 5001
{
  LSN lsn;
  uint32 diff;
  uint32 first_byte;
unknown's avatar
unknown committed
5002
  uint32 file_no, rec_offset;
5003 5004
  uint8 code;
  DBUG_ENTER("translog_get_LSN_from_diff");
unknown's avatar
unknown committed
5005
  DBUG_PRINT("enter", ("Base: (0x%lx,0x%lx)  src: 0x%lx  dst 0x%lx",
unknown's avatar
unknown committed
5006
                       LSN_IN_PARTS(base_lsn), (ulong) src, (ulong) dst));
5007
  first_byte= *((uint8*) src);
5008
  code= first_byte >> 6; /* Length is in 2 most significant bits */
unknown's avatar
unknown committed
5009 5010 5011 5012 5013
  first_byte&= 0x3F;
  src++;                                        /* Skip length + encode */
  file_no= LSN_FILE_NO(base_lsn);               /* Assume relative */
  DBUG_PRINT("info", ("code: %u  first byte: %lu",
                      (uint) code, (ulong) first_byte));
5014
  switch (code) {
unknown's avatar
unknown committed
5015
  case 0:
5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026
    if (first_byte == 0 && *((uint8*)src) == 1)
    {
      /*
        It is full LSN after special 1 diff (which is impossible
        in real life)
      */
      memcpy(dst, src + 1, LSN_STORE_SIZE);
      DBUG_PRINT("info", ("Special case of full LSN, new src: 0x%lx",
                          (ulong) (src + 1 + LSN_STORE_SIZE)));
      DBUG_RETURN(src + 1 + LSN_STORE_SIZE);
    }
unknown's avatar
unknown committed
5027
    rec_offset= LSN_OFFSET(base_lsn) - ((first_byte << 8) + *((uint8*)src));
5028
    break;
unknown's avatar
unknown committed
5029 5030 5031
  case 1:
    diff= uint2korr(src);
    rec_offset= LSN_OFFSET(base_lsn) - ((first_byte << 16) + diff);
5032
    break;
unknown's avatar
unknown committed
5033 5034 5035
  case 2:
    diff= uint3korr(src);
    rec_offset= LSN_OFFSET(base_lsn) - ((first_byte << 24) + diff);
5036
    break;
unknown's avatar
unknown committed
5037
  case 3:
5038
  {
5039
    ulonglong base_offset= LSN_OFFSET(base_lsn);
unknown's avatar
unknown committed
5040
    diff= uint4korr(src);
5041
    if (diff > LSN_OFFSET(base_lsn))
5042 5043 5044
    {
      /* take 1 from file offset */
      first_byte++;
unknown's avatar
unknown committed
5045
      base_offset+= LL(0x100000000);
5046
    }
unknown's avatar
unknown committed
5047
    file_no= LSN_FILE_NO(base_lsn) - first_byte;
5048 5049
    DBUG_ASSERT(base_offset - diff <= UINT_MAX);
    rec_offset= (uint32)(base_offset - diff);
5050 5051 5052 5053 5054 5055
    break;
  }
  default:
    DBUG_ASSERT(0);
    DBUG_RETURN(NULL);
  }
unknown's avatar
unknown committed
5056 5057 5058
  lsn= MAKE_LSN(file_no, rec_offset);
  src+= code + 1;
  lsn_store(dst, lsn);
5059
  DBUG_PRINT("info", ("new src: 0x%lx", (ulong) src));
5060 5061 5062 5063
  DBUG_RETURN(src);
}


unknown's avatar
unknown committed
5064 5065
/**
  @brief Encodes relative LSNs listed in the parameters.
5066

unknown's avatar
unknown committed
5067 5068 5069 5070
  @param parts           Parts list with encoded LSN(s)
  @param base_lsn        LSN which is base for encoding
  @param lsns            number of LSN(s) to encode
  @param compressed_LSNs buffer which can be used for storing compressed LSN(s)
5071 5072
*/

unknown's avatar
unknown committed
5073 5074 5075
static void  translog_relative_LSN_encode(struct st_translog_parts *parts,
                                          LSN base_lsn,
                                          uint lsns, uchar *compressed_LSNs)
5076
{
5077
  LEX_CUSTRING *part;
unknown's avatar
unknown committed
5078
  uint lsns_len= lsns * LSN_STORE_SIZE;
5079 5080
  char buffer_src[MAX_NUMBER_OF_LSNS_PER_RECORD * LSN_STORE_SIZE];
  char *buffer= buffer_src;
5081
  const char *cbuffer;
5082 5083 5084

  DBUG_ENTER("translog_relative_LSN_encode");

5085
  DBUG_ASSERT(parts->current != 0);
5086
  part= parts->parts + parts->current;
5087

5088
  /* collect all LSN(s) in one chunk if it (they) is (are) divided */
5089
  if (part->length < lsns_len)
5090
  {
5091
    uint copied= part->length;
5092
    LEX_CUSTRING *next_part;
unknown's avatar
unknown committed
5093
    DBUG_PRINT("info", ("Using buffer: 0x%lx", (ulong) compressed_LSNs));
5094
    memcpy(buffer, part->str, part->length);
5095
    next_part= parts->parts + parts->current + 1;
5096 5097
    do
    {
5098 5099
      DBUG_ASSERT(next_part < parts->parts + parts->elements);
      if ((next_part->length + copied) < lsns_len)
5100
      {
5101
        memcpy(buffer + copied, next_part->str,
5102 5103 5104 5105 5106
               next_part->length);
        copied+= next_part->length;
        next_part->length= 0; next_part->str= 0;
        /* delete_dynamic_element(&parts->parts, parts->current + 1); */
        next_part++;
5107 5108
        parts->current++;
        part= parts->parts + parts->current;
5109 5110 5111 5112
      }
      else
      {
        uint len= lsns_len - copied;
5113
        memcpy(buffer + copied, next_part->str, len);
5114
        copied= lsns_len;
5115 5116
        next_part->str+= len;
        next_part->length-= len;
5117 5118
      }
    } while (copied < lsns_len);
5119
    cbuffer= buffer;
5120
  }
5121 5122
  else
  {
5123
    cbuffer= part->str;
5124 5125 5126 5127 5128 5129
    part->str+= lsns_len;
    part->length-= lsns_len;
    parts->current--;
    part= parts->parts + parts->current;
  }

5130 5131 5132
  {
    /* Compress */
    LSN ref;
5133
    int economy;
5134
    const uchar *src_ptr;
unknown's avatar
unknown committed
5135
    uchar *dst_ptr= compressed_LSNs + (MAX_NUMBER_OF_LSNS_PER_RECORD *
5136
                                      COMPRESSED_LSN_MAX_STORE_SIZE);
unknown's avatar
unknown committed
5137 5138 5139 5140
    /*
      We write the result in backward direction with no special sense or
      tricks both directions are equal in complicity
    */
5141 5142
    for (src_ptr= cbuffer + lsns_len - LSN_STORE_SIZE;
         src_ptr >= (const uchar*)cbuffer;
5143
         src_ptr-= LSN_STORE_SIZE)
5144
    {
5145
      ref= lsn_korr(src_ptr);
unknown's avatar
unknown committed
5146
      dst_ptr= translog_put_LSN_diff(base_lsn, ref, dst_ptr);
5147
    }
5148 5149 5150 5151 5152
    part->length= (uint)((compressed_LSNs +
                          (MAX_NUMBER_OF_LSNS_PER_RECORD *
                           COMPRESSED_LSN_MAX_STORE_SIZE)) -
                         dst_ptr);
    parts->record_length-= (economy= lsns_len - part->length);
5153 5154
    DBUG_PRINT("info", ("new length of LSNs: %lu  economy: %d",
                        (ulong)part->length, economy));
5155
    parts->total_record_length-= economy;
5156
    part->str= (char*)dst_ptr;
5157
  }
unknown's avatar
unknown committed
5158
  DBUG_VOID_RETURN;
5159 5160 5161
}


unknown's avatar
unknown committed
5162 5163
/**
   @brief Write multi-group variable-size record.
5164

unknown's avatar
unknown committed
5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175
   @param  lsn             LSN of the record will be written here
   @param  type            the log record type
   @param  short_trid      Short transaction ID or 0 if it has no sense
   @param  parts           Descriptor of record source parts
   @param  buffer_to_flush Buffer which have to be flushed if it is not 0
   @param  header_length   Header length calculated for 1 group
   @param  buffer_rest     Beginning from which we plan to write in full pages
   @param  trn             Transaction structure pointer for hooks by
                           record log type, for short_id
   @param  hook_arg        Argument which will be passed to pre-write and
                           in-write hooks of this record.
5176

5177 5178 5179 5180 5181 5182 5183 5184
   @note
     We must have a translog_lock() when entering this function

     We must have buffer_to_flush locked (if not null)
     buffer_to_flush should *NOT* be locked when calling this function.
     (This is note is here as this is different from most other
     translog_write...() functions which require the buffer to be locked)

unknown's avatar
unknown committed
5185 5186 5187
   @return Operation status
     @retval 0      OK
     @retval 1      Error
5188 5189 5190 5191 5192
*/

static my_bool
translog_write_variable_record_mgroup(LSN *lsn,
                                      enum translog_record_type type,
unknown's avatar
unknown committed
5193
                                      MARIA_HA *tbl_info,
5194 5195 5196 5197 5198 5199
                                      SHORT_TRANSACTION_ID short_trid,
                                      struct st_translog_parts *parts,
                                      struct st_translog_buffer
                                      *buffer_to_flush,
                                      uint16 header_length,
                                      translog_size_t buffer_rest,
unknown's avatar
unknown committed
5200
                                      TRN *trn, void *hook_arg)
5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214
{
  TRANSLOG_ADDRESS horizon;
  struct st_buffer_cursor cursor;
  int rc= 0;
  uint i, chunk2_page, full_pages;
  uint curr_group= 0;
  translog_size_t record_rest, first_page, chunk3_pages, chunk0_pages= 1;
  translog_size_t done= 0;
  struct st_translog_group_descriptor group;
  DYNAMIC_ARRAY groups;
  uint16 chunk3_size;
  uint16 page_capacity= log_descriptor.page_capacity_chunk_2 + 1;
  uint16 last_page_capacity;
  my_bool new_page_before_chunk0= 1, first_chunk0= 1;
unknown's avatar
unknown committed
5215 5216
  uchar chunk0_header[1 + 2 + 5 + 2 + 2], group_desc[7 + 1];
  uchar chunk2_header[1];
5217 5218
  uint header_fixed_part= header_length + 2;
  uint groups_per_page= (page_capacity - header_fixed_part) / (7 + 1);
5219
  uint file_of_the_first_group;
unknown's avatar
unknown committed
5220
  int pages_to_skip;
5221
  DBUG_ENTER("translog_write_variable_record_mgroup");
unknown's avatar
unknown committed
5222
  translog_lock_assert_owner();
5223

unknown's avatar
unknown committed
5224 5225
  chunk2_header[0]= TRANSLOG_CHUNK_NOHDR;

unknown's avatar
unknown committed
5226 5227 5228
  if (my_init_dynamic_array(&groups,
                            sizeof(struct st_translog_group_descriptor),
                            10, 10))
5229
  {
unknown's avatar
unknown committed
5230
    translog_unlock();
5231
    DBUG_PRINT("error", ("init array failed"));
5232 5233 5234 5235 5236 5237 5238 5239 5240
    DBUG_RETURN(1);
  }

  first_page= translog_get_current_page_rest();
  record_rest= parts->record_length - (first_page - 1);
  DBUG_PRINT("info", ("Record Rest: %lu", (ulong) record_rest));

  if (record_rest < buffer_rest)
  {
unknown's avatar
unknown committed
5241 5242 5243 5244 5245 5246 5247
    /*
      The record (group 1 type) is larger than the free space on the page
      - we need to split it in two. But when we split it in two, the first
      part is big enough to hold all the data of the record (because the
      header of the first part of the split is smaller than the header of
      the record as a whole when it takes only one chunk)
    */
5248 5249 5250 5251 5252
    DBUG_PRINT("info", ("too many free space because changing header"));
    buffer_rest-= log_descriptor.page_capacity_chunk_2;
    DBUG_ASSERT(record_rest >= buffer_rest);
  }

5253 5254
  file_of_the_first_group= LSN_FILE_NO(log_descriptor.horizon);
  translog_mark_file_unfinished(file_of_the_first_group);
5255 5256 5257 5258 5259 5260 5261
  do
  {
    group.addr= horizon= log_descriptor.horizon;
    cursor= log_descriptor.bc;
    cursor.chaser= 1;
    if ((full_pages= buffer_rest / log_descriptor.page_capacity_chunk_2) > 255)
    {
unknown's avatar
unknown committed
5262
      /* sizeof(uint8) == 256 is max number of chunk in multi-chunks group */
5263 5264 5265 5266 5267
      full_pages= 255;
      buffer_rest= full_pages * log_descriptor.page_capacity_chunk_2;
    }
    /*
       group chunks =
unknown's avatar
unknown committed
5268
       full pages + first page (which actually can be full, too).
5269 5270 5271
       But here we assign number of chunks - 1
    */
    group.num= full_pages;
unknown's avatar
unknown committed
5272
    if (insert_dynamic(&groups, (uchar*) &group))
5273
    {
5274
      DBUG_PRINT("error", ("insert into array failed"));
unknown's avatar
unknown committed
5275
      goto err_unlock;
5276 5277
    }

unknown's avatar
unknown committed
5278 5279
    DBUG_PRINT("info", ("chunk: #%u  first_page: %u (%u)  "
                        "full_pages: %lu (%lu)  "
5280 5281 5282
                        "Left %lu",
                        groups.elements,
                        first_page, first_page - 1,
5283
                        (ulong) full_pages,
unknown's avatar
unknown committed
5284 5285 5286 5287 5288
                        (ulong) (full_pages *
                                 log_descriptor.page_capacity_chunk_2),
                        (ulong)(parts->record_length - (first_page - 1 +
                                                        buffer_rest) -
                                done)));
unknown's avatar
unknown committed
5289
    rc|= translog_advance_pointer((int)full_pages, 0);
5290

5291
    translog_unlock();
5292 5293 5294 5295 5296 5297

    if (buffer_to_flush != NULL)
    {
      translog_buffer_decrease_writers(buffer_to_flush);
      if (!rc)
        rc= translog_buffer_flush(buffer_to_flush);
5298
      translog_buffer_unlock(buffer_to_flush);
5299 5300 5301 5302
      buffer_to_flush= NULL;
    }
    if (rc)
    {
5303
      DBUG_PRINT("error", ("flush of unlock buffer failed"));
unknown's avatar
unknown committed
5304
      goto err;
5305 5306 5307 5308
    }

    translog_write_data_on_page(&horizon, &cursor, 1, chunk2_header);
    translog_write_parts_on_page(&horizon, &cursor, first_page - 1, parts);
unknown's avatar
unknown committed
5309 5310
    DBUG_PRINT("info", ("absolute horizon: (%lu,0x%lx)  local: (%lu,0x%lx)  "
                        "Left  %lu",
unknown's avatar
unknown committed
5311 5312
                        LSN_IN_PARTS(log_descriptor.horizon),
                        LSN_IN_PARTS(horizon),
5313 5314 5315 5316 5317 5318
                        (ulong) (parts->record_length - (first_page - 1) -
                                 done)));

    for (i= 0; i < full_pages; i++)
    {
      if (translog_write_variable_record_chunk2_page(parts, &horizon, &cursor))
unknown's avatar
unknown committed
5319
        goto err;
5320

unknown's avatar
unknown committed
5321 5322
      DBUG_PRINT("info", ("absolute horizon: (%lu,0x%lx)  "
                          "local: (%lu,0x%lx)  "
5323
                          "Left: %lu",
unknown's avatar
unknown committed
5324 5325
                          LSN_IN_PARTS(log_descriptor.horizon),
                          LSN_IN_PARTS(horizon),
5326 5327 5328 5329 5330 5331 5332
                          (ulong) (parts->record_length - (first_page - 1) -
                                   i * log_descriptor.page_capacity_chunk_2 -
                                   done)));
    }

    done+= (first_page - 1 + buffer_rest);

unknown's avatar
unknown committed
5333
    if (translog_chaser_page_next(&horizon, &cursor))
5334
    {
5335
      DBUG_PRINT("error", ("flush of unlock buffer failed"));
unknown's avatar
unknown committed
5336
      goto err;
5337
    }
5338 5339 5340
    translog_buffer_lock(cursor.buffer);
    translog_buffer_decrease_writers(cursor.buffer);
    translog_buffer_unlock(cursor.buffer);
5341 5342 5343

    translog_lock();

unknown's avatar
unknown committed
5344
    /* Check that we have place for chunk type 2 */
5345
    first_page= translog_get_current_page_rest();
unknown's avatar
unknown committed
5346 5347 5348 5349 5350 5351 5352
    if (first_page <= 1)
    {
      if (translog_page_next(&log_descriptor.horizon, &log_descriptor.bc,
                             &buffer_to_flush))
        goto err_unlock;
      first_page= translog_get_current_page_rest();
    }
5353
    buffer_rest= translog_get_current_group_size();
unknown's avatar
unknown committed
5354 5355
  } while ((translog_size_t)(first_page + buffer_rest) <
           (translog_size_t)(parts->record_length - done));
5356 5357 5358 5359

  group.addr= horizon= log_descriptor.horizon;
  cursor= log_descriptor.bc;
  cursor.chaser= 1;
5360
  group.num= 0;                       /* 0 because it does not matter */
unknown's avatar
unknown committed
5361
  if (insert_dynamic(&groups, (uchar*) &group))
5362
  {
5363
    DBUG_PRINT("error", ("insert into array failed"));
unknown's avatar
unknown committed
5364
    goto err_unlock;
5365 5366 5367
  }
  record_rest= parts->record_length - done;
  DBUG_PRINT("info", ("Record rest: %lu", (ulong) record_rest));
unknown's avatar
unknown committed
5368
  if (first_page > record_rest + 1)
5369
  {
unknown's avatar
unknown committed
5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393
    /*
      We have not so much data to fill all first page
      (no speaking about full pages)
      so it will be:
      <chunk0 <data>>
      or
      <chunk0>...<chunk0><chunk0 <data>>
      or
      <chunk3 <data>><chunk0>...<chunk0><chunk0 <possible data of 1 byte>>
    */
    chunk2_page= full_pages= 0;
    last_page_capacity= first_page;
    pages_to_skip= -1;
  }
  else
  {
    /*
      We will have:
      <chunk2 <data>>...<chunk2 <data>><chunk0 <data>>
      or
      <chunk2 <data>>...<chunk2 <data>><chunk0>...<chunk0><chunk0 <data>>
      or
      <chunk3 <data>><chunk0>...<chunk0><chunk0 <possible data of 1 byte>>
    */
5394 5395
    chunk2_page= 1;
    record_rest-= (first_page - 1);
unknown's avatar
unknown committed
5396 5397
    pages_to_skip= full_pages=
      record_rest / log_descriptor.page_capacity_chunk_2;
5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412
    record_rest= (record_rest % log_descriptor.page_capacity_chunk_2);
    last_page_capacity= page_capacity;
  }
  chunk3_size= 0;
  chunk3_pages= 0;
  if (last_page_capacity > record_rest + 1 && record_rest != 0)
  {
    if (last_page_capacity >
        record_rest + header_fixed_part + groups.elements * (7 + 1))
    {
      /* 1 record of type 0 */
      chunk3_pages= 0;
    }
    else
    {
unknown's avatar
unknown committed
5413
      pages_to_skip++;
5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434
      chunk3_pages= 1;
      if (record_rest + 2 == last_page_capacity)
      {
        chunk3_size= record_rest - 1;
        record_rest= 1;
      }
      else
      {
        chunk3_size= record_rest;
        record_rest= 0;
      }
    }
  }
  /*
     A first non-full page will hold type 0 chunk only if it fit in it with
     all its headers
  */
  while (page_capacity <
         record_rest + header_fixed_part +
         (groups.elements - groups_per_page * (chunk0_pages - 1)) * (7 + 1))
    chunk0_pages++;
unknown's avatar
unknown committed
5435 5436
  DBUG_PRINT("info", ("chunk0_pages: %u  groups %u  groups per full page: %u  "
                      "Group on last page: %u",
5437 5438 5439 5440 5441
                      chunk0_pages, groups.elements,
                      groups_per_page,
                      (groups.elements -
                       ((page_capacity - header_fixed_part) / (7 + 1)) *
                       (chunk0_pages - 1))));
unknown's avatar
unknown committed
5442 5443
  DBUG_PRINT("info", ("first_page: %u  chunk2: %u  full_pages: %u (%lu)  "
                      "chunk3: %u (%u)  rest: %u",
5444 5445 5446 5447 5448
                      first_page,
                      chunk2_page, full_pages,
                      (ulong) full_pages *
                      log_descriptor.page_capacity_chunk_2,
                      chunk3_pages, (uint) chunk3_size, (uint) record_rest));
unknown's avatar
unknown committed
5449
  rc= translog_advance_pointer(pages_to_skip + (int)(chunk0_pages - 1),
unknown's avatar
unknown committed
5450 5451 5452 5453 5454
                               record_rest + header_fixed_part +
                               (groups.elements -
                                ((page_capacity -
                                  header_fixed_part) / (7 + 1)) *
                                (chunk0_pages - 1)) * (7 + 1));
5455
  translog_unlock();
unknown's avatar
unknown committed
5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470

  if (buffer_to_flush != NULL)
  {
    translog_buffer_decrease_writers(buffer_to_flush);
    if (!rc)
      rc= translog_buffer_flush(buffer_to_flush);
    translog_buffer_unlock(buffer_to_flush);
    buffer_to_flush= NULL;
  }
  if (rc)
  {
    DBUG_PRINT("error", ("flush of unlock buffer failed"));
    goto err;
  }

unknown's avatar
unknown committed
5471 5472
  if (rc)
    goto err;
5473 5474 5475 5476 5477 5478

  if (chunk2_page)
  {
    DBUG_PRINT("info", ("chunk 2 to finish first page"));
    translog_write_data_on_page(&horizon, &cursor, 1, chunk2_header);
    translog_write_parts_on_page(&horizon, &cursor, first_page - 1, parts);
unknown's avatar
unknown committed
5479
    DBUG_PRINT("info", ("absolute horizon: (%lu,0x%lx)  local: (%lu,0x%lx) "
5480
                        "Left: %lu",
unknown's avatar
unknown committed
5481 5482
                        LSN_IN_PARTS(log_descriptor.horizon),
                        LSN_IN_PARTS(horizon),
5483 5484 5485 5486 5487
                        (ulong) (parts->record_length - (first_page - 1) -
                                 done)));
  }
  else if (chunk3_pages)
  {
unknown's avatar
unknown committed
5488
    uchar chunk3_header[3];
5489 5490
    DBUG_PRINT("info", ("chunk 3"));
    DBUG_ASSERT(full_pages == 0);
unknown's avatar
unknown committed
5491
    chunk3_pages= 0;
5492 5493 5494 5495
    chunk3_header[0]= TRANSLOG_CHUNK_LNGTH;
    int2store(chunk3_header + 1, chunk3_size);
    translog_write_data_on_page(&horizon, &cursor, 3, chunk3_header);
    translog_write_parts_on_page(&horizon, &cursor, chunk3_size, parts);
unknown's avatar
unknown committed
5496
    DBUG_PRINT("info", ("absolute horizon: (%lu,0x%lx)  local: (%lu,0x%lx) "
5497
                        "Left: %lu",
unknown's avatar
unknown committed
5498 5499
                        LSN_IN_PARTS(log_descriptor.horizon),
                        LSN_IN_PARTS(horizon),
5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511
                        (ulong) (parts->record_length - chunk3_size - done)));
  }
  else
  {
    DBUG_PRINT("info", ("no new_page_before_chunk0"));
    new_page_before_chunk0= 0;
  }

  for (i= 0; i < full_pages; i++)
  {
    DBUG_ASSERT(chunk2_page != 0);
    if (translog_write_variable_record_chunk2_page(parts, &horizon, &cursor))
unknown's avatar
unknown committed
5512
      goto err;
5513

unknown's avatar
unknown committed
5514
    DBUG_PRINT("info", ("absolute horizon: (%lu,0x%lx)  local: (%lu,0x%lx) "
5515
                        "Left: %lu",
unknown's avatar
unknown committed
5516 5517
                        LSN_IN_PARTS(log_descriptor.horizon),
                        LSN_IN_PARTS(horizon),
5518 5519 5520 5521 5522 5523 5524 5525 5526
                        (ulong) (parts->record_length - (first_page - 1) -
                                 i * log_descriptor.page_capacity_chunk_2 -
                                 done)));
  }

  if (chunk3_pages &&
      translog_write_variable_record_chunk3_page(parts,
                                                 chunk3_size,
                                                 &horizon, &cursor))
unknown's avatar
unknown committed
5527 5528
    goto err;
  DBUG_PRINT("info", ("absolute horizon: (%lu,0x%lx)  local: (%lu,0x%lx)",
unknown's avatar
unknown committed
5529 5530
                      LSN_IN_PARTS(log_descriptor.horizon),
                      LSN_IN_PARTS(horizon)));
5531

5532
  *chunk0_header= (uchar) (type | TRANSLOG_CHUNK_LSN);
5533 5534 5535 5536 5537 5538 5539
  int2store(chunk0_header + 1, short_trid);
  translog_write_variable_record_1group_code_len(chunk0_header + 3,
                                                 parts->record_length,
                                                 header_length);
  do
  {
    int limit;
unknown's avatar
unknown committed
5540 5541
    if (new_page_before_chunk0 &&
        translog_chaser_page_next(&horizon, &cursor))
5542
    {
unknown's avatar
unknown committed
5543 5544
      DBUG_PRINT("error", ("flush of unlock buffer failed"));
      goto err;
5545 5546 5547 5548 5549
    }
    new_page_before_chunk0= 1;

    if (first_chunk0)
    {
unknown's avatar
unknown committed
5550
      first_chunk0= 0;
5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561

      /*
        We can drop "log_descriptor.is_everything_flushed" earlier when have
        lock on loghandler and assign initial value of "horizon" variable or
        before unlocking loghandler (because we will increase writers
        counter on the buffer and every thread which wanted flush the buffer
        will wait till we finish with it). But IMHO better here take short
        lock and do not bother other threads with waiting.
      */
      translog_lock();
      set_lsn(lsn, horizon);
5562
      if (log_record_type_descriptor[type].inwrite_hook &&
unknown's avatar
unknown committed
5563 5564
          (*log_record_type_descriptor[type].inwrite_hook) (type, trn,
                                                            tbl_info,
unknown's avatar
unknown committed
5565
                                                            lsn, hook_arg))
5566 5567
        goto err_unlock;
      translog_unlock();
5568 5569 5570 5571 5572 5573 5574 5575 5576
    }

    /*
       A first non-full page will hold type 0 chunk only if it fit in it with
       all its headers => the fist page is full or number of groups less then
       possible number of full page.
    */
    limit= (groups_per_page < groups.elements - curr_group ?
            groups_per_page : groups.elements - curr_group);
unknown's avatar
unknown committed
5577
    DBUG_PRINT("info", ("Groups: %u  curr: %u  limit: %u",
5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599
                        (uint) groups.elements, (uint) curr_group,
                        (uint) limit));

    if (chunk0_pages == 1)
    {
      DBUG_PRINT("info", ("chunk_len: 2 + %u * (7+1) + %u = %u",
                          (uint) limit, (uint) record_rest,
                          (uint) (2 + limit * (7 + 1) + record_rest)));
      int2store(chunk0_header + header_length - 2,
                2 + limit * (7 + 1) + record_rest);
    }
    else
    {
      DBUG_PRINT("info", ("chunk_len: 2 + %u * (7+1) = %u",
                          (uint) limit, (uint) (2 + limit * (7 + 1))));
      int2store(chunk0_header + header_length - 2, 2 + limit * (7 + 1));
    }
    int2store(chunk0_header + header_length, groups.elements - curr_group);
    translog_write_data_on_page(&horizon, &cursor, header_fixed_part,
                                chunk0_header);
    for (i= curr_group; i < limit + curr_group; i++)
    {
unknown's avatar
unknown committed
5600 5601 5602 5603 5604
      struct st_translog_group_descriptor *grp_ptr;
      grp_ptr= dynamic_element(&groups, i,
                               struct st_translog_group_descriptor *);
      lsn_store(group_desc, grp_ptr->addr);
      group_desc[7]= grp_ptr->num;
5605 5606 5607 5608 5609 5610 5611 5612
      translog_write_data_on_page(&horizon, &cursor, (7 + 1), group_desc);
    }

    if (chunk0_pages == 1 && record_rest != 0)
      translog_write_parts_on_page(&horizon, &cursor, record_rest, parts);

    chunk0_pages--;
    curr_group+= limit;
5613 5614
    /* put special type to indicate that it is not LSN chunk */
    *chunk0_header= (uchar) (TRANSLOG_CHUNK_LSN | TRANSLOG_CHUNK_0_CONT);
5615
  } while (chunk0_pages != 0);
5616
  translog_buffer_lock(cursor.buffer);
5617 5618 5619
  if (cmp_translog_addr(cursor.buffer->last_lsn, *lsn) < 0)
    cursor.buffer->last_lsn= *lsn;
  translog_buffer_decrease_writers(cursor.buffer);
5620 5621
  translog_buffer_unlock(cursor.buffer);
  rc= 0;
5622

5623 5624 5625 5626
  if (translog_set_lsn_for_files(file_of_the_first_group, LSN_FILE_NO(*lsn),
                                 *lsn, FALSE))
    goto err;

unknown's avatar
unknown committed
5627
  translog_mark_file_finished(file_of_the_first_group);
5628

5629 5630
  delete_dynamic(&groups);
  DBUG_RETURN(rc);
unknown's avatar
unknown committed
5631 5632

err_unlock:
unknown's avatar
unknown committed
5633

unknown's avatar
unknown committed
5634
  translog_unlock();
unknown's avatar
unknown committed
5635

unknown's avatar
unknown committed
5636
err:
unknown's avatar
unknown committed
5637 5638 5639 5640 5641 5642 5643 5644 5645 5646
  if (buffer_to_flush != NULL)
  {
    /* This is to prevent locking buffer forever in case of error */
    translog_buffer_decrease_writers(buffer_to_flush);
    if (!rc)
      rc= translog_buffer_flush(buffer_to_flush);
    translog_buffer_unlock(buffer_to_flush);
    buffer_to_flush= NULL;
  }

unknown's avatar
unknown committed
5647 5648 5649

  translog_mark_file_finished(file_of_the_first_group);

unknown's avatar
unknown committed
5650 5651
  delete_dynamic(&groups);
  DBUG_RETURN(1);
5652 5653 5654
}


unknown's avatar
unknown committed
5655 5656
/**
   @brief Write the variable length log record.
5657

unknown's avatar
unknown committed
5658 5659 5660 5661 5662 5663 5664 5665
   @param  lsn             LSN of the record will be written here
   @param  type            the log record type
   @param  short_trid      Short transaction ID or 0 if it has no sense
   @param  parts           Descriptor of record source parts
   @param  trn             Transaction structure pointer for hooks by
                           record log type, for short_id
   @param  hook_arg        Argument which will be passed to pre-write and
                           in-write hooks of this record.
5666

unknown's avatar
unknown committed
5667 5668 5669
   @return Operation status
     @retval 0      OK
     @retval 1      Error
5670 5671 5672 5673
*/

static my_bool translog_write_variable_record(LSN *lsn,
                                              enum translog_record_type type,
unknown's avatar
unknown committed
5674
                                              MARIA_HA *tbl_info,
5675 5676
                                              SHORT_TRANSACTION_ID short_trid,
                                              struct st_translog_parts *parts,
unknown's avatar
unknown committed
5677
                                              TRN *trn, void *hook_arg)
5678 5679 5680 5681 5682 5683
{
  struct st_translog_buffer *buffer_to_flush= NULL;
  uint header_length1= 1 + 2 + 2 +
    translog_variable_record_length_bytes(parts->record_length);
  ulong buffer_rest;
  uint page_rest;
unknown's avatar
unknown committed
5684
  /* Max number of such LSNs per record is 2 */
unknown's avatar
unknown committed
5685
  uchar compressed_LSNs[MAX_NUMBER_OF_LSNS_PER_RECORD *
5686
    COMPRESSED_LSN_MAX_STORE_SIZE];
unknown's avatar
unknown committed
5687
  my_bool res;
5688 5689 5690
  DBUG_ENTER("translog_write_variable_record");

  translog_lock();
unknown's avatar
unknown committed
5691
  DBUG_PRINT("info", ("horizon: (%lu,0x%lx)",
unknown's avatar
unknown committed
5692
                      LSN_IN_PARTS(log_descriptor.horizon)));
unknown's avatar
unknown committed
5693 5694
  page_rest= TRANSLOG_PAGE_SIZE - log_descriptor.bc.current_page_fill;
  DBUG_PRINT("info", ("header length: %u  page_rest: %u",
5695 5696 5697
                      header_length1, page_rest));

  /*
5698 5699
    header and part which we should read have to fit in one chunk
    TODO: allow to divide readable header
5700 5701 5702 5703 5704
  */
  if (page_rest <
      (header_length1 + log_record_type_descriptor[type].read_header_len))
  {
    DBUG_PRINT("info",
unknown's avatar
unknown committed
5705 5706
               ("Next page, size: %u  header: %u + %u",
                log_descriptor.bc.current_page_fill,
5707 5708 5709 5710
                header_length1,
                log_record_type_descriptor[type].read_header_len));
    translog_page_next(&log_descriptor.horizon, &log_descriptor.bc,
                       &buffer_to_flush);
unknown's avatar
unknown committed
5711
    /* Chunk 2 header is 1 byte, so full page capacity will be one uchar more */
5712 5713 5714 5715 5716 5717 5718 5719
    page_rest= log_descriptor.page_capacity_chunk_2 + 1;
    DBUG_PRINT("info", ("page_rest: %u", page_rest));
  }

  /*
     To minimize compressed size we will compress always relative to
     very first chunk address (log_descriptor.horizon for now)
  */
unknown's avatar
unknown committed
5720
  if (log_record_type_descriptor[type].compressed_LSN > 0)
5721
  {
unknown's avatar
unknown committed
5722 5723 5724
    translog_relative_LSN_encode(parts, log_descriptor.horizon,
                                 log_record_type_descriptor[type].
                                 compressed_LSN, compressed_LSNs);
5725 5726 5727
    /* recalculate header length after compression */
    header_length1= 1 + 2 + 2 +
      translog_variable_record_length_bytes(parts->record_length);
unknown's avatar
unknown committed
5728 5729
    DBUG_PRINT("info", ("after compressing LSN(s) header length: %u  "
                        "record length: %lu",
5730
                        header_length1, (ulong)parts->record_length));
5731 5732 5733 5734 5735 5736
  }

  /* TODO: check space on current page for header + few bytes */
  if (page_rest >= parts->record_length + header_length1)
  {
    /* following function makes translog_unlock(); */
unknown's avatar
unknown committed
5737
    res= translog_write_variable_record_1chunk(lsn, type, tbl_info,
unknown's avatar
unknown committed
5738 5739
                                               short_trid,
                                               parts, buffer_to_flush,
unknown's avatar
unknown committed
5740
                                               header_length1, trn, hook_arg);
unknown's avatar
unknown committed
5741
    DBUG_RETURN(res);
5742 5743 5744 5745 5746 5747 5748
  }

  buffer_rest= translog_get_current_group_size();

  if (buffer_rest >= parts->record_length + header_length1 - page_rest)
  {
    /* following function makes translog_unlock(); */
unknown's avatar
unknown committed
5749
    res= translog_write_variable_record_1group(lsn, type, tbl_info,
unknown's avatar
unknown committed
5750 5751
                                               short_trid,
                                               parts, buffer_to_flush,
unknown's avatar
unknown committed
5752
                                               header_length1, trn, hook_arg);
unknown's avatar
unknown committed
5753
    DBUG_RETURN(res);
5754 5755
  }
  /* following function makes translog_unlock(); */
unknown's avatar
unknown committed
5756
  res= translog_write_variable_record_mgroup(lsn, type, tbl_info,
unknown's avatar
unknown committed
5757 5758 5759
                                             short_trid,
                                             parts, buffer_to_flush,
                                             header_length1,
unknown's avatar
unknown committed
5760
                                             buffer_rest, trn, hook_arg);
unknown's avatar
unknown committed
5761
  DBUG_RETURN(res);
5762 5763 5764
}


unknown's avatar
unknown committed
5765 5766
/**
   @brief Write the fixed and pseudo-fixed log record.
5767

unknown's avatar
unknown committed
5768 5769 5770 5771 5772 5773 5774 5775
   @param  lsn             LSN of the record will be written here
   @param  type            the log record type
   @param  short_trid      Short transaction ID or 0 if it has no sense
   @param  parts           Descriptor of record source parts
   @param  trn             Transaction structure pointer for hooks by
                           record log type, for short_id
   @param  hook_arg        Argument which will be passed to pre-write and
                           in-write hooks of this record.
5776

unknown's avatar
unknown committed
5777 5778 5779
   @return Operation status
     @retval 0      OK
     @retval 1      Error
5780 5781 5782 5783
*/

static my_bool translog_write_fixed_record(LSN *lsn,
                                           enum translog_record_type type,
unknown's avatar
unknown committed
5784
                                           MARIA_HA *tbl_info,
5785 5786
                                           SHORT_TRANSACTION_ID short_trid,
                                           struct st_translog_parts *parts,
unknown's avatar
unknown committed
5787
                                           TRN *trn, void *hook_arg)
5788 5789
{
  struct st_translog_buffer *buffer_to_flush= NULL;
unknown's avatar
unknown committed
5790
  uchar chunk1_header[1 + 2];
unknown's avatar
unknown committed
5791
  /* Max number of such LSNs per record is 2 */
unknown's avatar
unknown committed
5792
  uchar compressed_LSNs[MAX_NUMBER_OF_LSNS_PER_RECORD *
5793
    COMPRESSED_LSN_MAX_STORE_SIZE];
5794
  LEX_CUSTRING *part;
5795
  int rc= 1;
5796
  DBUG_ENTER("translog_write_fixed_record");
unknown's avatar
unknown committed
5797
  DBUG_ASSERT((log_record_type_descriptor[type].rclass ==
5798 5799 5800
               LOGRECTYPE_FIXEDLENGTH &&
               parts->record_length ==
               log_record_type_descriptor[type].fixed_length) ||
unknown's avatar
unknown committed
5801
              (log_record_type_descriptor[type].rclass ==
5802
               LOGRECTYPE_PSEUDOFIXEDLENGTH &&
5803
               parts->record_length ==
5804 5805 5806
               log_record_type_descriptor[type].fixed_length));

  translog_lock();
unknown's avatar
unknown committed
5807
  DBUG_PRINT("info", ("horizon: (%lu,0x%lx)",
unknown's avatar
unknown committed
5808
                      LSN_IN_PARTS(log_descriptor.horizon)));
5809

unknown's avatar
unknown committed
5810
  DBUG_ASSERT(log_descriptor.bc.current_page_fill <= TRANSLOG_PAGE_SIZE);
5811
  DBUG_PRINT("info",
unknown's avatar
unknown committed
5812 5813
             ("Page size: %u  record: %u  next cond: %d",
              log_descriptor.bc.current_page_fill,
5814
              (parts->record_length +
unknown's avatar
unknown committed
5815 5816
               log_record_type_descriptor[type].compressed_LSN * 2 + 3),
              ((((uint) log_descriptor.bc.current_page_fill) +
5817
                (parts->record_length +
unknown's avatar
unknown committed
5818
                 log_record_type_descriptor[type].compressed_LSN * 2 + 3)) >
5819 5820
               TRANSLOG_PAGE_SIZE)));
  /*
5821 5822
    check that there is enough place on current page.
    NOTE: compressing may increase page LSN size on two bytes for every LSN
5823
  */
unknown's avatar
unknown committed
5824
  if ((((uint) log_descriptor.bc.current_page_fill) +
5825
       (parts->record_length +
unknown's avatar
unknown committed
5826
        log_record_type_descriptor[type].compressed_LSN * 2 + 3)) >
5827 5828 5829
      TRANSLOG_PAGE_SIZE)
  {
    DBUG_PRINT("info", ("Next page"));
5830 5831 5832 5833 5834
    if (translog_page_next(&log_descriptor.horizon, &log_descriptor.bc,
                           &buffer_to_flush))
      goto err;                                 /* rc == 1 */
    if (buffer_to_flush)
      translog_buffer_lock_assert_owner(buffer_to_flush);
5835 5836
  }

5837
  set_lsn(lsn, log_descriptor.horizon);
5838 5839 5840
  if (translog_set_lsn_for_files(LSN_FILE_NO(*lsn), LSN_FILE_NO(*lsn),
                             *lsn, TRUE) ||
      (log_record_type_descriptor[type].inwrite_hook &&
5841 5842
       (*log_record_type_descriptor[type].inwrite_hook)(type, trn, tbl_info,
                                                        lsn, hook_arg)))
unknown's avatar
unknown committed
5843
    goto err;
5844 5845

  /* compress LSNs */
unknown's avatar
unknown committed
5846 5847
  if (log_record_type_descriptor[type].rclass ==
      LOGRECTYPE_PSEUDOFIXEDLENGTH)
5848
  {
unknown's avatar
unknown committed
5849
    DBUG_ASSERT(log_record_type_descriptor[type].compressed_LSN > 0);
unknown's avatar
unknown committed
5850 5851 5852
    translog_relative_LSN_encode(parts, *lsn,
                                 log_record_type_descriptor[type].
                                 compressed_LSN, compressed_LSNs);
5853 5854 5855
  }

  /*
unknown's avatar
unknown committed
5856 5857
    Write the whole record at once (we know that there is enough place on
    the destination page)
5858
  */
unknown's avatar
unknown committed
5859
  DBUG_ASSERT(parts->current != 0);       /* first part is left for header */
5860
  part= parts->parts + (--parts->current);
5861
  parts->total_record_length+= (translog_size_t) (part->length= 1 + 2);
5862
  part->str= (char*)chunk1_header;
unknown's avatar
unknown committed
5863
  *chunk1_header= (uchar) (type | TRANSLOG_CHUNK_FIXED);
5864 5865 5866 5867 5868 5869 5870
  int2store(chunk1_header + 1, short_trid);

  rc= translog_write_parts_on_page(&log_descriptor.horizon,
                                   &log_descriptor.bc,
                                   parts->total_record_length, parts);

  log_descriptor.bc.buffer->last_lsn= *lsn;
unknown's avatar
unknown committed
5871

5872
err:
5873
  translog_unlock();
5874 5875

  /*
5876 5877
    check if we switched buffer and need process it (current buffer is
    unlocked already => we will not delay other threads
5878 5879 5880 5881 5882
  */
  if (buffer_to_flush != NULL)
  {
    if (!rc)
      rc= translog_buffer_flush(buffer_to_flush);
5883
    translog_buffer_unlock(buffer_to_flush);
5884 5885 5886 5887 5888 5889
  }

  DBUG_RETURN(rc);
}


5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900
/**
   @brief Writes the log record

   If share has no 2-byte-id yet, gives an id to the share and logs
   LOGREC_FILE_ID. If transaction has not logged LOGREC_LONG_TRANSACTION_ID
   yet, logs it.

   @param  lsn             LSN of the record will be written here
   @param  type            the log record type
   @param  trn             Transaction structure pointer for hooks by
                           record log type, for short_id
unknown's avatar
unknown committed
5901
   @param  tbl_info        MARIA_HA of table or NULL
5902 5903 5904 5905 5906 5907
   @param  rec_len         record length or 0 (count it)
   @param  part_no         number of parts or 0 (count it)
   @param  parts_data      zero ended (in case of number of parts is 0)
                           array of LEX_STRINGs (parts), first
                           TRANSLOG_INTERNAL_PARTS positions in the log
                           should be unused (need for loghandler)
unknown's avatar
unknown committed
5908 5909 5910
   @param  store_share_id  if tbl_info!=NULL then share's id will
                           automatically be stored in the two first bytes
                           pointed (so pointer is assumed to be !=NULL)
unknown's avatar
unknown committed
5911 5912 5913
   @param  hook_arg        argument which will be passed to pre-write and
                           in-write hooks of this record.

5914 5915 5916
   @return Operation status
     @retval 0      OK
     @retval 1      Error
5917 5918 5919 5920
*/

my_bool translog_write_record(LSN *lsn,
                              enum translog_record_type type,
unknown's avatar
unknown committed
5921
                              TRN *trn, MARIA_HA *tbl_info,
5922 5923
                              translog_size_t rec_len,
                              uint part_no,
5924
                              LEX_CUSTRING *parts_data,
unknown's avatar
unknown committed
5925 5926
                              uchar *store_share_id,
                              void *hook_arg)
5927 5928
{
  struct st_translog_parts parts;
5929
  LEX_CUSTRING *part;
5930
  int rc;
5931
  uint short_trid= trn->short_id;
5932
  DBUG_ENTER("translog_write_record");
5933 5934 5935
  DBUG_PRINT("enter", ("type: %u (%s)  ShortTrID: %u  rec_len: %lu",
                       (uint) type, log_record_type_descriptor[type].name,
                       (uint) short_trid, (ulong) rec_len));
5936 5937 5938 5939 5940 5941 5942 5943
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
  if (unlikely(translog_status != TRANSLOG_OK))
  {
    DBUG_PRINT("error", ("Transaction log is write protected"));
    DBUG_RETURN(1);
  }

unknown's avatar
unknown committed
5944
  if (tbl_info)
5945
  {
unknown's avatar
unknown committed
5946
    MARIA_SHARE *share= tbl_info->s;
unknown's avatar
unknown committed
5947
    DBUG_ASSERT(share->now_transactional);
5948 5949 5950 5951 5952 5953 5954 5955 5956
    if (unlikely(share->id == 0))
    {
      /*
        First log write for this MARIA_SHARE; give it a short id.
        When the lock manager is enabled and needs a short id, it should be
        assigned in the lock manager (because row locks will be taken before
        log records are written; for example SELECT FOR UPDATE takes locks but
        writes no log record.
      */
unknown's avatar
unknown committed
5957
      if (unlikely(translog_assign_id_to_share(tbl_info, trn)))
5958 5959 5960 5961 5962 5963
        DBUG_RETURN(1);
    }
    fileid_store(store_share_id, share->id);
  }
  if (unlikely(!(trn->first_undo_lsn & TRANSACTION_LOGGED_LONG_ID)))
  {
unknown's avatar
unknown committed
5964
    LSN dummy_lsn;
5965
    LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 1];
5966 5967
    uchar log_data[6];
    int6store(log_data, trn->trid);
5968
    log_array[TRANSLOG_INTERNAL_PARTS + 0].str=    log_data;
5969 5970
    log_array[TRANSLOG_INTERNAL_PARTS + 0].length= sizeof(log_data);
    trn->first_undo_lsn|= TRANSACTION_LOGGED_LONG_ID; /* no recursion */
unknown's avatar
unknown committed
5971
    if (unlikely(translog_write_record(&dummy_lsn, LOGREC_LONG_TRANSACTION_ID,
5972 5973
                                       trn, NULL, sizeof(log_data),
                                       sizeof(log_array)/sizeof(log_array[0]),
unknown's avatar
unknown committed
5974
                                       log_array, NULL, NULL)))
5975
      DBUG_RETURN(1);
5976
  }
unknown's avatar
unknown committed
5977

5978
  parts.parts= parts_data;
5979

5980 5981
  /* count parts if they are not counted by upper level */
  if (part_no == 0)
unknown's avatar
unknown committed
5982
  {
5983 5984 5985
    for (part_no= TRANSLOG_INTERNAL_PARTS;
         parts_data[part_no].length != 0;
         part_no++);
unknown's avatar
unknown committed
5986
  }
5987 5988
  parts.elements= part_no;
  parts.current= TRANSLOG_INTERNAL_PARTS;
5989

5990
  /* clear TRANSLOG_INTERNAL_PARTS */
unknown's avatar
unknown committed
5991
  compile_time_assert(TRANSLOG_INTERNAL_PARTS != 0);
5992 5993 5994 5995 5996
  parts_data[0].str= 0;
  parts_data[0].length= 0;

  /* count length of the record */
  if (rec_len == 0)
unknown's avatar
unknown committed
5997
  {
5998 5999 6000
    for(part= parts_data + TRANSLOG_INTERNAL_PARTS;\
        part < parts_data + part_no;
        part++)
6001
    {
6002
      rec_len+= (translog_size_t) part->length;
6003 6004
    }
  }
6005
  parts.record_length= rec_len;
unknown's avatar
unknown committed
6006

6007 6008 6009 6010
#ifndef DBUG_OFF
  {
    uint i;
    uint len= 0;
6011
#ifdef HAVE_purify
unknown's avatar
unknown committed
6012 6013
    ha_checksum checksum= 0;
#endif
6014
    for (i= TRANSLOG_INTERNAL_PARTS; i < part_no; i++)
unknown's avatar
unknown committed
6015
    {
6016
#ifdef HAVE_purify
unknown's avatar
unknown committed
6017 6018 6019 6020
      /* Find unitialized bytes early */
      checksum+= my_checksum(checksum, parts_data[i].str,
                             parts_data[i].length);
#endif
6021
      len+= parts_data[i].length;
unknown's avatar
unknown committed
6022
    }
6023 6024 6025
    DBUG_ASSERT(len == rec_len);
  }
#endif
unknown's avatar
unknown committed
6026 6027 6028 6029 6030
  /*
    Start total_record_length from record_length then overhead will
    be add
  */
  parts.total_record_length= parts.record_length;
unknown's avatar
unknown committed
6031
  DBUG_PRINT("info", ("record length: %lu", (ulong) parts.record_length));
6032 6033 6034

  /* process this parts */
  if (!(rc= (log_record_type_descriptor[type].prewrite_hook &&
6035
             (*log_record_type_descriptor[type].prewrite_hook) (type, trn,
unknown's avatar
unknown committed
6036
                                                                tbl_info,
unknown's avatar
unknown committed
6037
                                                                hook_arg))))
6038
  {
unknown's avatar
unknown committed
6039
    switch (log_record_type_descriptor[type].rclass) {
6040
    case LOGRECTYPE_VARIABLE_LENGTH:
unknown's avatar
unknown committed
6041
      rc= translog_write_variable_record(lsn, type, tbl_info,
unknown's avatar
unknown committed
6042
                                         short_trid, &parts, trn, hook_arg);
6043 6044 6045
      break;
    case LOGRECTYPE_PSEUDOFIXEDLENGTH:
    case LOGRECTYPE_FIXEDLENGTH:
unknown's avatar
unknown committed
6046
      rc= translog_write_fixed_record(lsn, type, tbl_info,
unknown's avatar
unknown committed
6047
                                      short_trid, &parts, trn, hook_arg);
6048 6049 6050 6051 6052 6053 6054 6055
      break;
    case LOGRECTYPE_NOT_ALLOWED:
    default:
      DBUG_ASSERT(0);
      rc= 1;
    }
  }

unknown's avatar
unknown committed
6056
  DBUG_PRINT("info", ("LSN: (%lu,0x%lx)", LSN_IN_PARTS(*lsn)));
6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074
  DBUG_RETURN(rc);
}


/*
  Decode compressed (relative) LSN(s)

  SYNOPSIS
   translog_relative_lsn_decode()
   base_lsn              LSN for encoding
   src                   Decode LSN(s) from here
   dst                   Put decoded LSNs here
   lsns                  number of LSN(s)

   RETURN
     position in sources after decoded LSN(s)
*/

unknown's avatar
unknown committed
6075 6076
static uchar *translog_relative_LSN_decode(LSN base_lsn,
                                          uchar *src, uchar *dst, uint lsns)
6077 6078
{
  uint i;
unknown's avatar
unknown committed
6079
  for (i= 0; i < lsns; i++, dst+= LSN_STORE_SIZE)
6080 6081 6082 6083 6084 6085
  {
    src= translog_get_LSN_from_diff(base_lsn, src, dst);
  }
  return src;
}

6086 6087 6088
/**
   @brief Get header of fixed/pseudo length record and call hook for
   it processing
6089

6090 6091 6092 6093
   @param page            Pointer to the buffer with page where LSN chunk is
                          placed
   @param page_offset     Offset of the first chunk in the page
   @param buff            Buffer to be filled with header data
6094

6095 6096 6097
   @return Length of header or operation status
     @retval #  number of bytes in TRANSLOG_HEADER_BUFFER::header where
                stored decoded part of the header
6098 6099
*/

6100 6101 6102
static int translog_fixed_length_header(uchar *page,
                                        translog_size_t page_offset,
                                        TRANSLOG_HEADER_BUFFER *buff)
6103 6104 6105
{
  struct st_log_record_type_descriptor *desc=
    log_record_type_descriptor + buff->type;
unknown's avatar
unknown committed
6106 6107 6108
  uchar *src= page + page_offset + 3;
  uchar *dst= buff->header;
  uchar *start= src;
6109
  int lsns= desc->compressed_LSN;
6110
  uint length= desc->fixed_length;
6111 6112 6113 6114
  DBUG_ENTER("translog_fixed_length_header");

  buff->record_length= length;

unknown's avatar
unknown committed
6115
  if (desc->rclass == LOGRECTYPE_PSEUDOFIXEDLENGTH)
6116 6117
  {
    DBUG_ASSERT(lsns > 0);
6118
    src= translog_relative_LSN_decode(buff->lsn, src, dst, lsns);
unknown's avatar
unknown committed
6119
    lsns*= LSN_STORE_SIZE;
6120 6121
    dst+= lsns;
    length-= lsns;
6122
    buff->compressed_LSN_economy= (lsns - (int) (src - start));
6123 6124 6125 6126
  }
  else
    buff->compressed_LSN_economy= 0;

unknown's avatar
unknown committed
6127
  memcpy(dst, src, length);
6128 6129 6130
  buff->non_header_data_start_offset= (uint16) (page_offset +
                                                ((src + length) -
                                                 (page + page_offset)));
6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147
  buff->non_header_data_len= 0;
  DBUG_RETURN(buff->record_length);
}


/*
  Free resources used by TRANSLOG_HEADER_BUFFER

  SYNOPSIS
    translog_free_record_header();
*/

void translog_free_record_header(TRANSLOG_HEADER_BUFFER *buff)
{
  DBUG_ENTER("translog_free_record_header");
  if (buff->groups_no != 0)
  {
unknown's avatar
unknown committed
6148
    my_free((uchar*) buff->groups, MYF(0));
6149 6150 6151 6152 6153 6154
    buff->groups_no= 0;
  }
  DBUG_VOID_RETURN;
}


6155 6156
/**
   @brief Returns the current horizon at the end of the current log
6157

6158
   @return Horizon
6159 6160
   @retval LSN_ERROR     error
   @retvar #             Horizon
6161 6162
*/

6163
TRANSLOG_ADDRESS translog_get_horizon()
6164
{
6165
  TRANSLOG_ADDRESS res;
6166 6167
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
6168
  translog_lock();
6169
  res= log_descriptor.horizon;
6170
  translog_unlock();
6171
  return res;
6172 6173 6174
}


unknown's avatar
unknown committed
6175 6176 6177 6178 6179
/**
   @brief Returns the current horizon at the end of the current log, caller is
   assumed to already hold the lock

   @return Horizon
6180 6181
   @retval LSN_ERROR     error
   @retvar #             Horizon
unknown's avatar
unknown committed
6182 6183 6184 6185
*/

TRANSLOG_ADDRESS translog_get_horizon_no_lock()
{
6186 6187
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
unknown's avatar
unknown committed
6188 6189 6190 6191 6192
  translog_lock_assert_owner();
  return log_descriptor.horizon;
}


6193 6194 6195 6196 6197 6198 6199 6200
/*
  Set last page in the scanner data structure

  SYNOPSIS
    translog_scanner_set_last_page()
    scanner              Information about current chunk during scanning

  RETURN
unknown's avatar
unknown committed
6201 6202
    0  OK
    1  Error
6203 6204
*/

unknown's avatar
unknown committed
6205
static my_bool translog_scanner_set_last_page(TRANSLOG_SCANNER_DATA *scanner)
6206 6207
{
  my_bool page_ok;
6208 6209 6210 6211 6212 6213 6214 6215
  if (LSN_FILE_NO(scanner->page_addr) == LSN_FILE_NO(scanner->horizon))
  {
    /* It is last file => we can easy find last page address by horizon */
    uint pagegrest= LSN_OFFSET(scanner->horizon) % TRANSLOG_PAGE_SIZE;
    scanner->last_file_page= (scanner->horizon -
                              (pagegrest ? pagegrest : TRANSLOG_PAGE_SIZE));
    return (0);
  }
6216
  scanner->last_file_page= scanner->page_addr;
6217
  return (translog_get_last_page_addr(&scanner->last_file_page, &page_ok, 0));
6218 6219 6220
}


6221 6222
/**
  @brief Get page from page cache according to requested method
6223

6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251
  @param scanner         The scanner data

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

static my_bool
translog_scanner_get_page(TRANSLOG_SCANNER_DATA *scanner)
{
  TRANSLOG_VALIDATOR_DATA data;
  DBUG_ENTER("translog_scanner_get_page");
  data.addr= &scanner->page_addr;
  data.was_recovered= 0;
  DBUG_RETURN((scanner->page=
               translog_get_page(&data, scanner->buffer,
                                 (scanner->use_direct_link ?
                                  &scanner->direct_link :
                                  NULL))) ==
               NULL);
}


/**
  @brief Initialize reader scanner.

  @param lsn             LSN with which it have to be inited
  @param fixed_horizon   true if it is OK do not read records which was written
6252
                         after scanning beginning
6253 6254 6255
  @param scanner         scanner which have to be inited
  @param use_direct      prefer using direct lings from page handler
                         where it is possible.
6256

6257 6258 6259 6260 6261 6262
  @note If direct link was used translog_destroy_scanner should be
        called after it using

  @return status of the operation
  @retval 0 OK
  @retval 1 Error
6263 6264
*/

unknown's avatar
unknown committed
6265
my_bool translog_scanner_init(LSN lsn,
unknown's avatar
unknown committed
6266
                              my_bool fixed_horizon,
6267 6268
                              TRANSLOG_SCANNER_DATA *scanner,
                              my_bool use_direct)
unknown's avatar
unknown committed
6269 6270
{
  TRANSLOG_VALIDATOR_DATA data;
unknown's avatar
unknown committed
6271
  DBUG_ENTER("translog_scanner_init");
6272 6273
  DBUG_PRINT("enter", ("Scanner: 0x%lx  LSN: (0x%lu,0x%lx)",
                       (ulong) scanner, LSN_IN_PARTS(lsn)));
6274 6275
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
unknown's avatar
unknown committed
6276 6277 6278 6279

  data.addr= &scanner->page_addr;
  data.was_recovered= 0;

6280
  scanner->page_offset= LSN_OFFSET(lsn) % TRANSLOG_PAGE_SIZE;
6281 6282

  scanner->fixed_horizon= fixed_horizon;
6283 6284
  scanner->use_direct_link= use_direct;
  scanner->direct_link= NULL;
6285

6286
  scanner->horizon= translog_get_horizon();
unknown's avatar
unknown committed
6287
  DBUG_PRINT("info", ("horizon: (0x%lu,0x%lx)",
unknown's avatar
unknown committed
6288
                      LSN_IN_PARTS(scanner->horizon)));
6289 6290

  /* lsn < horizon */
unknown's avatar
unknown committed
6291
  DBUG_ASSERT(lsn <= scanner->horizon);
6292

6293 6294
  scanner->page_addr= lsn;
  scanner->page_addr-= scanner->page_offset; /*decrease offset */
6295 6296 6297 6298

  if (translog_scanner_set_last_page(scanner))
    DBUG_RETURN(1);

6299
  if (translog_scanner_get_page(scanner))
6300 6301 6302 6303 6304
    DBUG_RETURN(1);
  DBUG_RETURN(0);
}


6305 6306 6307 6308 6309 6310 6311 6312
/**
  @brief Destroy scanner object;

  @param scanner         The scanner object to destroy
*/

void translog_destroy_scanner(TRANSLOG_SCANNER_DATA *scanner)
{
6313 6314
  DBUG_ENTER("translog_destroy_scanner");
  DBUG_PRINT("enter", ("Scanner: 0x%lx", (ulong)scanner));
6315
  translog_free_link(scanner->direct_link);
6316
  DBUG_VOID_RETURN;
6317 6318 6319
}


6320 6321 6322 6323 6324 6325 6326 6327
/*
  Checks End of the Log

  SYNOPSIS
    translog_scanner_eol()
    scanner              Information about current chunk during scanning

  RETURN
unknown's avatar
unknown committed
6328 6329
    1  End of the Log
    0  OK
6330
*/
6331

unknown's avatar
unknown committed
6332
static my_bool translog_scanner_eol(TRANSLOG_SCANNER_DATA *scanner)
6333 6334 6335
{
  DBUG_ENTER("translog_scanner_eol");
  DBUG_PRINT("enter",
unknown's avatar
unknown committed
6336
             ("Horizon: (%lu, 0x%lx)  Current: (%lu, 0x%lx+0x%x=0x%lx)",
unknown's avatar
unknown committed
6337 6338
              LSN_IN_PARTS(scanner->horizon),
              LSN_IN_PARTS(scanner->page_addr),
6339
              (uint) scanner->page_offset,
6340 6341 6342
              (ulong) (LSN_OFFSET(scanner->page_addr) + scanner->page_offset)));
  if (scanner->horizon > (scanner->page_addr +
                          scanner->page_offset))
6343 6344 6345 6346 6347 6348 6349 6350 6351
  {
    DBUG_PRINT("info", ("Horizon is not reached"));
    DBUG_RETURN(0);
  }
  if (scanner->fixed_horizon)
  {
    DBUG_PRINT("info", ("Horizon is fixed and reached"));
    DBUG_RETURN(1);
  }
6352
  scanner->horizon= translog_get_horizon();
6353 6354
  DBUG_PRINT("info",
             ("Horizon is re-read, EOL: %d",
6355 6356 6357 6358
              scanner->horizon <= (scanner->page_addr +
                                   scanner->page_offset)));
  DBUG_RETURN(scanner->horizon <= (scanner->page_addr +
                                   scanner->page_offset));
6359 6360 6361
}


unknown's avatar
unknown committed
6362 6363
/**
  @brief Cheks End of the Page
6364

unknown's avatar
unknown committed
6365
  @param scanner         Information about current chunk during scanning
6366

unknown's avatar
unknown committed
6367 6368
  @retval 1  End of the Page
  @retval 0  OK
6369
*/
6370

unknown's avatar
unknown committed
6371
static my_bool translog_scanner_eop(TRANSLOG_SCANNER_DATA *scanner)
6372 6373 6374
{
  DBUG_ENTER("translog_scanner_eop");
  DBUG_RETURN(scanner->page_offset >= TRANSLOG_PAGE_SIZE ||
unknown's avatar
unknown committed
6375
              scanner->page[scanner->page_offset] == TRANSLOG_FILLER);
6376 6377 6378
}


unknown's avatar
unknown committed
6379 6380 6381
/**
  @brief Checks End of the File (i.e. we are scanning last page, which do not
    mean end of this page)
6382

unknown's avatar
unknown committed
6383
  @param scanner         Information about current chunk during scanning
6384

unknown's avatar
unknown committed
6385 6386
  @retval 1 End of the File
  @retval 0 OK
6387
*/
6388

unknown's avatar
unknown committed
6389
static my_bool translog_scanner_eof(TRANSLOG_SCANNER_DATA *scanner)
6390 6391
{
  DBUG_ENTER("translog_scanner_eof");
6392 6393
  DBUG_ASSERT(LSN_FILE_NO(scanner->page_addr) ==
              LSN_FILE_NO(scanner->last_file_page));
unknown's avatar
unknown committed
6394 6395
  DBUG_PRINT("enter", ("curr Page: 0x%lx  last page: 0x%lx  "
                       "normal EOF: %d",
6396 6397 6398 6399
                       (ulong) LSN_OFFSET(scanner->page_addr),
                       (ulong) LSN_OFFSET(scanner->last_file_page),
                       LSN_OFFSET(scanner->page_addr) ==
                       LSN_OFFSET(scanner->last_file_page)));
6400 6401 6402 6403
  /*
     TODO: detect damaged file EOF,
     TODO: issue warning if damaged file EOF detected
  */
6404 6405
  DBUG_RETURN(scanner->page_addr ==
              scanner->last_file_page);
6406 6407 6408 6409 6410 6411 6412 6413 6414 6415
}

/*
  Move scanner to the next chunk

  SYNOPSIS
    translog_get_next_chunk()
    scanner              Information about current chunk during scanning

  RETURN
unknown's avatar
unknown committed
6416 6417
    0  OK
    1  Error
6418 6419
*/

unknown's avatar
unknown committed
6420 6421
static my_bool
translog_get_next_chunk(TRANSLOG_SCANNER_DATA *scanner)
6422
{
unknown's avatar
unknown committed
6423
  uint16 len;
6424
  DBUG_ENTER("translog_get_next_chunk");
unknown's avatar
unknown committed
6425

6426 6427 6428 6429
  if (translog_scanner_eop(scanner))
    len= TRANSLOG_PAGE_SIZE - scanner->page_offset;
  else if ((len= translog_get_total_chunk_length(scanner->page,
                                                 scanner->page_offset)) == 0)
6430 6431 6432 6433 6434
    DBUG_RETURN(1);
  scanner->page_offset+= len;

  if (translog_scanner_eol(scanner))
  {
unknown's avatar
unknown committed
6435
    scanner->page= END_OF_LOG;
6436 6437 6438 6439 6440
    scanner->page_offset= 0;
    DBUG_RETURN(0);
  }
  if (translog_scanner_eop(scanner))
  {
6441 6442
    /* before reading next page we should unpin current one if it was pinned */
    translog_free_link(scanner->direct_link);
6443 6444
    if (translog_scanner_eof(scanner))
    {
unknown's avatar
unknown committed
6445
      DBUG_PRINT("info", ("horizon: (%lu,0x%lx)  pageaddr: (%lu,0x%lx)",
unknown's avatar
unknown committed
6446 6447
                          LSN_IN_PARTS(scanner->horizon),
                          LSN_IN_PARTS(scanner->page_addr)));
6448
      /* if it is log end it have to be caught before */
6449 6450 6451 6452 6453
      DBUG_ASSERT(LSN_FILE_NO(scanner->horizon) >
                  LSN_FILE_NO(scanner->page_addr));
      scanner->page_addr+= LSN_ONE_FILE;
      scanner->page_addr= LSN_REPLACE_OFFSET(scanner->page_addr,
                                             TRANSLOG_PAGE_SIZE);
6454 6455 6456 6457 6458
      if (translog_scanner_set_last_page(scanner))
        DBUG_RETURN(1);
    }
    else
    {
6459
      scanner->page_addr+= TRANSLOG_PAGE_SIZE; /* offset increased */
6460
    }
unknown's avatar
unknown committed
6461

6462
    if (translog_scanner_get_page(scanner))
unknown's avatar
unknown committed
6463 6464
      DBUG_RETURN(1);

6465 6466 6467
    scanner->page_offset= translog_get_first_chunk_offset(scanner->page);
    if (translog_scanner_eol(scanner))
    {
unknown's avatar
unknown committed
6468
      scanner->page= END_OF_LOG;
6469 6470 6471
      scanner->page_offset= 0;
      DBUG_RETURN(0);
    }
unknown's avatar
unknown committed
6472
    DBUG_ASSERT(scanner->page[scanner->page_offset] != TRANSLOG_FILLER);
6473 6474 6475 6476 6477
  }
  DBUG_RETURN(0);
}


6478 6479
/**
   @brief Get header of variable length record and call hook for it processing
6480

6481 6482 6483 6484 6485
   @param page            Pointer to the buffer with page where LSN chunk is
                          placed
   @param page_offset     Offset of the first chunk in the page
   @param buff            Buffer to be filled with header data
   @param scanner         If present should be moved to the header page if
6486 6487 6488
                          it differ from LSN page

   @return                Length of header or operation status
6489
     @retval RECHEADER_READ_ERROR  error
unknown's avatar
unknown committed
6490
     @retval RECHEADER_READ_EOF    End of the log reached during the read
6491 6492 6493
     @retval #                     number of bytes in
                                   TRANSLOG_HEADER_BUFFER::header where
                                   stored decoded part of the header
6494 6495
*/

unknown's avatar
unknown committed
6496 6497 6498 6499
static int
translog_variable_length_header(uchar *page, translog_size_t page_offset,
                                TRANSLOG_HEADER_BUFFER *buff,
                                TRANSLOG_SCANNER_DATA *scanner)
6500
{
unknown's avatar
unknown committed
6501 6502
  struct st_log_record_type_descriptor *desc= (log_record_type_descriptor +
                                               buff->type);
unknown's avatar
unknown committed
6503 6504
  uchar *src= page + page_offset + 1 + 2;
  uchar *dst= buff->header;
6505
  LSN base_lsn;
unknown's avatar
unknown committed
6506
  uint lsns= desc->compressed_LSN;
6507
  uint16 chunk_len;
6508
  uint16 length= desc->read_header_len;
6509 6510
  uint16 buffer_length= length;
  uint16 body_len;
unknown's avatar
unknown committed
6511
  int rc;
unknown's avatar
unknown committed
6512
  TRANSLOG_SCANNER_DATA internal_scanner;
6513 6514 6515 6516
  DBUG_ENTER("translog_variable_length_header");

  buff->record_length= translog_variable_record_1group_decode_len(&src);
  chunk_len= uint2korr(src);
unknown's avatar
unknown committed
6517
  DBUG_PRINT("info", ("rec len: %lu  chunk len: %u  length: %u  bufflen: %u",
6518 6519 6520 6521 6522 6523 6524
                      (ulong) buff->record_length, (uint) chunk_len,
                      (uint) length, (uint) buffer_length));
  if (chunk_len == 0)
  {
    uint16 page_rest;
    DBUG_PRINT("info", ("1 group"));
    src+= 2;
6525
    page_rest= (uint16) (TRANSLOG_PAGE_SIZE - (src - page));
6526 6527

    base_lsn= buff->lsn;
unknown's avatar
unknown committed
6528
    body_len= min(page_rest, buff->record_length);
6529 6530 6531 6532 6533 6534 6535 6536 6537
  }
  else
  {
    uint grp_no, curr;
    uint header_to_skip;
    uint16 page_rest;

    DBUG_PRINT("info", ("multi-group"));
    grp_no= buff->groups_no= uint2korr(src + 2);
unknown's avatar
unknown committed
6538 6539 6540
    if (!(buff->groups=
          (TRANSLOG_GROUP*) my_malloc(sizeof(TRANSLOG_GROUP) * grp_no,
                                      MYF(0))))
6541
      DBUG_RETURN(RECHEADER_READ_ERROR);
6542 6543
    DBUG_PRINT("info", ("Groups: %u", (uint) grp_no));
    src+= (2 + 2);
6544
    page_rest= (uint16) (TRANSLOG_PAGE_SIZE - (src - page));
6545 6546 6547 6548 6549 6550
    curr= 0;
    header_to_skip= src - (page + page_offset);
    buff->chunk0_pages= 0;

    for (;;)
    {
6551
      uint i, read_length= grp_no;
6552 6553 6554

      buff->chunk0_pages++;
      if (page_rest < grp_no * (7 + 1))
6555
        read_length= page_rest / (7 + 1);
unknown's avatar
unknown committed
6556 6557
      DBUG_PRINT("info", ("Read chunk0 page#%u  read: %u  left: %u  "
                          "start from: %u",
6558 6559
                          buff->chunk0_pages, read_length, grp_no, curr));
      for (i= 0; i < read_length; i++, curr++)
6560 6561
      {
        DBUG_ASSERT(curr < buff->groups_no);
unknown's avatar
unknown committed
6562
        buff->groups[curr].addr= lsn_korr(src + i * (7 + 1));
6563
        buff->groups[curr].num= src[i * (7 + 1) + 7];
unknown's avatar
unknown committed
6564
        DBUG_PRINT("info", ("group #%u (%lu,0x%lx)  chunks: %u",
6565
                            curr,
unknown's avatar
unknown committed
6566
                            LSN_IN_PARTS(buff->groups[curr].addr),
6567 6568
                            (uint) buff->groups[curr].num));
      }
6569
      grp_no-= read_length;
6570 6571 6572 6573 6574
      if (grp_no == 0)
      {
        if (scanner)
        {
          buff->chunk0_data_addr= scanner->page_addr;
6575
          /* offset increased */
6576
          buff->chunk0_data_addr+= (page_offset + header_to_skip +
6577
                                    read_length * (7 + 1));
6578 6579 6580 6581
        }
        else
        {
          buff->chunk0_data_addr= buff->lsn;
6582
          /* offset increased */
6583
          buff->chunk0_data_addr+= (header_to_skip + read_length * (7 + 1));
6584
        }
6585
        buff->chunk0_data_len= chunk_len - 2 - read_length * (7 + 1);
unknown's avatar
unknown committed
6586
        DBUG_PRINT("info", ("Data address: (%lu,0x%lx)  len: %u",
unknown's avatar
unknown committed
6587
                            LSN_IN_PARTS(buff->chunk0_data_addr),
6588 6589 6590 6591 6592
                            buff->chunk0_data_len));
        break;
      }
      if (scanner == NULL)
      {
unknown's avatar
unknown committed
6593
        DBUG_PRINT("info", ("use internal scanner for header reading"));
6594
        scanner= &internal_scanner;
unknown's avatar
unknown committed
6595
        if (translog_scanner_init(buff->lsn, 1, scanner, 0))
unknown's avatar
unknown committed
6596 6597 6598 6599
        {
          rc= RECHEADER_READ_ERROR;
          goto exit_and_free;
        }
6600
      }
6601
      if (translog_get_next_chunk(scanner))
unknown's avatar
unknown committed
6602 6603 6604
      {
        if (scanner == &internal_scanner)
          translog_destroy_scanner(scanner);
unknown's avatar
unknown committed
6605 6606
        rc= RECHEADER_READ_ERROR;
        goto exit_and_free;
unknown's avatar
unknown committed
6607 6608 6609 6610 6611
      }
      if (scanner->page == END_OF_LOG)
      {
        if (scanner == &internal_scanner)
          translog_destroy_scanner(scanner);
unknown's avatar
unknown committed
6612 6613
        rc= RECHEADER_READ_EOF;
        goto exit_and_free;
unknown's avatar
unknown committed
6614
      }
6615 6616 6617 6618 6619
      page= scanner->page;
      page_offset= scanner->page_offset;
      src= page + page_offset + header_to_skip;
      chunk_len= uint2korr(src - 2 - 2);
      DBUG_PRINT("info", ("Chunk len: %u", (uint) chunk_len));
6620
      page_rest= (uint16) (TRANSLOG_PAGE_SIZE - (src - page));
6621 6622 6623 6624 6625 6626 6627
    }

    if (scanner == NULL)
    {
      DBUG_PRINT("info", ("use internal scanner"));
      scanner= &internal_scanner;
    }
6628 6629 6630 6631
    else
    {
      translog_destroy_scanner(scanner);
    }
6632
    base_lsn= buff->groups[0].addr;
unknown's avatar
unknown committed
6633
    translog_scanner_init(base_lsn, 1, scanner, scanner == &internal_scanner);
6634 6635 6636 6637
    /* first group chunk is always chunk type 2 */
    page= scanner->page;
    page_offset= scanner->page_offset;
    src= page + page_offset + 1;
6638
    page_rest= (uint16) (TRANSLOG_PAGE_SIZE - (src - page));
6639
    body_len= page_rest;
6640 6641
    if (scanner == &internal_scanner)
      translog_destroy_scanner(scanner);
6642 6643 6644
  }
  if (lsns)
  {
unknown's avatar
unknown committed
6645
    uchar *start= src;
6646
    src= translog_relative_LSN_decode(base_lsn, src, dst, lsns);
unknown's avatar
unknown committed
6647
    lsns*= LSN_STORE_SIZE;
6648 6649 6650
    dst+= lsns;
    length-= lsns;
    buff->record_length+= (buff->compressed_LSN_economy=
6651
                           (int) (lsns - (src - start)));
6652
    DBUG_PRINT("info", ("lsns: %u  length: %u  economy: %d  new length: %lu",
unknown's avatar
unknown committed
6653
                        lsns / LSN_STORE_SIZE, (uint) length,
6654
                        (int) buff->compressed_LSN_economy,
6655
                        (ulong) buff->record_length));
6656
    body_len-= (uint16) (src - start);
6657 6658 6659 6660 6661 6662
  }
  else
    buff->compressed_LSN_economy= 0;

  DBUG_ASSERT(body_len >= length);
  body_len-= length;
unknown's avatar
unknown committed
6663
  memcpy(dst, src, length);
6664
  buff->non_header_data_start_offset= (uint16) (src + length - page);
6665
  buff->non_header_data_len= body_len;
unknown's avatar
unknown committed
6666
  DBUG_PRINT("info", ("non_header_data_start_offset: %u  len: %u  buffer: %u",
6667 6668 6669
                      buff->non_header_data_start_offset,
                      buff->non_header_data_len, buffer_length));
  DBUG_RETURN(buffer_length);
unknown's avatar
unknown committed
6670 6671 6672 6673 6674

exit_and_free:
  my_free(buff->groups, MYF(0));
  buff->groups_no= 0; /* prevent try to use of buff->groups */
  DBUG_RETURN(rc);
6675 6676 6677
}


6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690
/**
   @brief Read record header from the given buffer

   @param page            page content buffer
   @param page_offset     offset of the chunk in the page
   @param buff            destination buffer
   @param scanner         If this is set the scanner will be moved to the
                          record header page (differ from LSN page in case of
                          multi-group records)

   @return Length of header or operation status
     @retval RECHEADER_READ_ERROR  error
     @retval #                     number of bytes in
unknown's avatar
unknown committed
6691
                                   TRANSLOG_HEADER_BUFFER::header where
6692
                                   stored decoded part of the header
6693 6694
*/

6695 6696 6697 6698
int translog_read_record_header_from_buffer(uchar *page,
                                            uint16 page_offset,
                                            TRANSLOG_HEADER_BUFFER *buff,
                                            TRANSLOG_SCANNER_DATA *scanner)
6699
{
unknown's avatar
unknown committed
6700
  translog_size_t res;
6701
  DBUG_ENTER("translog_read_record_header_from_buffer");
6702
  DBUG_ASSERT(translog_is_LSN_chunk(page[page_offset]));
6703 6704
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
6705 6706
  DBUG_PRINT("info", ("page byte: 0x%x  offset: %u",
                      (uint) page[page_offset], (uint) page_offset));
6707 6708
  buff->type= (page[page_offset] & TRANSLOG_REC_TYPE);
  buff->short_trid= uint2korr(page + page_offset + 1);
6709
  DBUG_PRINT("info", ("Type %u, Short TrID %u, LSN (%lu,0x%lx)",
6710
                      (uint) buff->type, (uint)buff->short_trid,
unknown's avatar
unknown committed
6711
                      LSN_IN_PARTS(buff->lsn)));
6712
  /* Read required bytes from the header and call hook */
unknown's avatar
unknown committed
6713
  switch (log_record_type_descriptor[buff->type].rclass) {
6714
  case LOGRECTYPE_VARIABLE_LENGTH:
unknown's avatar
unknown committed
6715 6716 6717
    res= translog_variable_length_header(page, page_offset, buff,
                                         scanner);
    break;
6718 6719
  case LOGRECTYPE_PSEUDOFIXEDLENGTH:
  case LOGRECTYPE_FIXEDLENGTH:
unknown's avatar
unknown committed
6720 6721
    res= translog_fixed_length_header(page, page_offset, buff);
    break;
6722
  default:
unknown's avatar
unknown committed
6723
    DBUG_ASSERT(0); /* we read some junk (got no LSN) */
6724
    res= RECHEADER_READ_ERROR;
6725
  }
unknown's avatar
unknown committed
6726
  DBUG_RETURN(res);
6727 6728 6729
}


6730 6731 6732
/**
   @brief Read record header and some fixed part of a record (the part depend
   on record type).
6733

6734 6735
   @param lsn             log record serial number (address of the record)
   @param buff            log record header buffer
6736

6737 6738 6739 6740 6741 6742 6743 6744 6745 6746
   @note Some type of record can be read completely by this call
   @note "Decoded" header stored in TRANSLOG_HEADER_BUFFER::header (relative
   LSN can be translated to absolute one), some fields can be added (like
   actual header length in the record if the header has variable length)

   @return Length of header or operation status
     @retval RECHEADER_READ_ERROR  error
     @retval #                     number of bytes in
                                   TRANSLOG_HEADER_BUFFER::header where
                                   stored decoded part of the header
6747 6748
*/

6749
int translog_read_record_header(LSN lsn, TRANSLOG_HEADER_BUFFER *buff)
6750
{
6751 6752
  TRANSLOG_PAGE_SIZE_BUFF psize_buff;
  uchar *page;
unknown's avatar
unknown committed
6753
  translog_size_t res, page_offset= LSN_OFFSET(lsn) % TRANSLOG_PAGE_SIZE;
unknown's avatar
unknown committed
6754
  PAGECACHE_BLOCK_LINK *direct_link;
unknown's avatar
unknown committed
6755 6756
  TRANSLOG_ADDRESS addr;
  TRANSLOG_VALIDATOR_DATA data;
6757
  DBUG_ENTER("translog_read_record_header");
unknown's avatar
unknown committed
6758
  DBUG_PRINT("enter", ("LSN: (0x%lu,0x%lx)", LSN_IN_PARTS(lsn)));
6759
  DBUG_ASSERT(LSN_OFFSET(lsn) % TRANSLOG_PAGE_SIZE != 0);
6760 6761
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
6762

6763
  buff->lsn= lsn;
6764
  buff->groups_no= 0;
unknown's avatar
unknown committed
6765 6766 6767 6768
  data.addr= &addr;
  data.was_recovered= 0;
  addr= lsn;
  addr-= page_offset; /* offset decreasing */
6769
  res= (!(page= translog_get_page(&data, psize_buff.buffer, &direct_link))) ?
6770
    RECHEADER_READ_ERROR :
unknown's avatar
unknown committed
6771
    translog_read_record_header_from_buffer(page, page_offset, buff, 0);
6772
  translog_free_link(direct_link);
unknown's avatar
unknown committed
6773
  DBUG_RETURN(res);
6774 6775 6776
}


6777 6778 6779
/**
   @brief Read record header and some fixed part of a record (the part depend
   on record type).
6780

6781 6782 6783
   @param scan            scanner position to read
   @param buff            log record header buffer
   @param move_scanner    request to move scanner to the header position
6784

6785 6786 6787 6788 6789 6790 6791 6792 6793 6794
   @note Some type of record can be read completely by this call
   @note "Decoded" header stored in TRANSLOG_HEADER_BUFFER::header (relative
   LSN can be translated to absolute one), some fields can be added (like
   actual header length in the record if the header has variable length)

   @return Length of header or operation status
     @retval RECHEADER_READ_ERROR  error
     @retval #                     number of bytes in
                                   TRANSLOG_HEADER_BUFFER::header where stored
                                   decoded part of the header
6795 6796
*/

6797 6798 6799
int translog_read_record_header_scan(TRANSLOG_SCANNER_DATA *scanner,
                                     TRANSLOG_HEADER_BUFFER *buff,
                                     my_bool move_scanner)
6800
{
unknown's avatar
unknown committed
6801
  translog_size_t res;
6802
  DBUG_ENTER("translog_read_record_header_scan");
unknown's avatar
unknown committed
6803 6804
  DBUG_PRINT("enter", ("Scanner: Cur: (%lu,0x%lx)  Hrz: (%lu,0x%lx)  "
                       "Lst: (%lu,0x%lx)  Offset: %u(%x)  fixed %d",
unknown's avatar
unknown committed
6805 6806 6807
                       LSN_IN_PARTS(scanner->page_addr),
                       LSN_IN_PARTS(scanner->horizon),
                       LSN_IN_PARTS(scanner->last_file_page),
6808 6809
                       (uint) scanner->page_offset,
                       (uint) scanner->page_offset, scanner->fixed_horizon));
6810 6811
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
6812 6813
  buff->groups_no= 0;
  buff->lsn= scanner->page_addr;
6814
  buff->lsn+= scanner->page_offset; /* offset increasing */
unknown's avatar
unknown committed
6815 6816 6817 6818 6819 6820
  res= translog_read_record_header_from_buffer(scanner->page,
                                               scanner->page_offset,
                                               buff,
                                               (move_scanner ?
                                                scanner : 0));
  DBUG_RETURN(res);
6821 6822 6823
}


6824 6825 6826
/**
   @brief Read record header and some fixed part of the next record (the part
   depend on record type).
6827

6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839
   @param scanner         data for scanning if lsn is NULL scanner data
                          will be used for continue scanning.
                          The scanner can be NULL.

   @param buff            log record header buffer

   @return Length of header or operation status
     @retval RECHEADER_READ_ERROR  error
     @retval RECHEADER_READ_EOF    EOF
     @retval #                     number of bytes in
                                   TRANSLOG_HEADER_BUFFER::header where
                                   stored decoded part of the header
6840
*/
6841

6842 6843
int translog_read_next_record_header(TRANSLOG_SCANNER_DATA *scanner,
                                     TRANSLOG_HEADER_BUFFER *buff)
6844
{
unknown's avatar
unknown committed
6845
  translog_size_t res;
6846 6847

  DBUG_ENTER("translog_read_next_record_header");
unknown's avatar
unknown committed
6848
  buff->groups_no= 0;        /* to be sure that we will free it right */
6849
  DBUG_PRINT("enter", ("scanner: 0x%lx", (ulong) scanner));
unknown's avatar
unknown committed
6850 6851
  DBUG_PRINT("info", ("Scanner: Cur: (%lu,0x%lx)  Hrz: (%lu,0x%lx)  "
                      "Lst: (%lu,0x%lx)  Offset: %u(%x)  fixed: %d",
unknown's avatar
unknown committed
6852 6853 6854
                      LSN_IN_PARTS(scanner->page_addr),
                      LSN_IN_PARTS(scanner->horizon),
                      LSN_IN_PARTS(scanner->last_file_page),
6855 6856
                      (uint) scanner->page_offset,
                      (uint) scanner->page_offset, scanner->fixed_horizon));
6857 6858
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
6859 6860 6861 6862

  do
  {
    if (translog_get_next_chunk(scanner))
6863
      DBUG_RETURN(RECHEADER_READ_ERROR);
unknown's avatar
unknown committed
6864 6865 6866 6867 6868 6869 6870
    if (scanner->page == END_OF_LOG)
    {
       DBUG_PRINT("info", ("End of file from the scanner"));
       /* Last record was read */
       buff->lsn= LSN_IMPOSSIBLE;
       DBUG_RETURN(RECHEADER_READ_EOF);
    }
6871
    DBUG_PRINT("info", ("Page: (%lu,0x%lx)  offset: %lu  byte: %x",
unknown's avatar
unknown committed
6872 6873
                        LSN_IN_PARTS(scanner->page_addr),
                        (ulong) scanner->page_offset,
6874
                        (uint) scanner->page[scanner->page_offset]));
6875
  } while (!translog_is_LSN_chunk(scanner->page[scanner->page_offset]) &&
unknown's avatar
unknown committed
6876
           scanner->page[scanner->page_offset] != TRANSLOG_FILLER);
6877

unknown's avatar
unknown committed
6878
  if (scanner->page[scanner->page_offset] == TRANSLOG_FILLER)
6879
  {
unknown's avatar
unknown committed
6880
    DBUG_PRINT("info", ("End of file"));
6881
    /* Last record was read */
unknown's avatar
unknown committed
6882
    buff->lsn= LSN_IMPOSSIBLE;
unknown's avatar
unknown committed
6883
    /* Return 'end of log' marker */
6884
    res= RECHEADER_READ_EOF;
6885
  }
unknown's avatar
unknown committed
6886 6887 6888
  else
    res= translog_read_record_header_scan(scanner, buff, 0);
  DBUG_RETURN(res);
6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900
}


/*
  Moves record data reader to the next chunk and fill the data reader
  information about that chunk.

  SYNOPSIS
    translog_record_read_next_chunk()
    data                 data cursor

  RETURN
unknown's avatar
unknown committed
6901 6902
    0  OK
    1  Error
6903
*/
6904

unknown's avatar
unknown committed
6905
static my_bool translog_record_read_next_chunk(TRANSLOG_READER_DATA *data)
6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924
{
  translog_size_t new_current_offset= data->current_offset + data->chunk_size;
  uint16 chunk_header_len, chunk_len;
  uint8 type;
  DBUG_ENTER("translog_record_read_next_chunk");

  if (data->eor)
  {
    DBUG_PRINT("info", ("end of the record flag set"));
    DBUG_RETURN(1);
  }

  if (data->header.groups_no &&
      data->header.groups_no - 1 != data->current_group &&
      data->header.groups[data->current_group].num == data->current_chunk)
  {
    /* Goto next group */
    data->current_group++;
    data->current_chunk= 0;
unknown's avatar
unknown committed
6925
    DBUG_PRINT("info", ("skip to group: #%u", data->current_group));
6926
    translog_destroy_scanner(&data->scanner);
unknown's avatar
unknown committed
6927
    translog_scanner_init(data->header.groups[data->current_group].addr,
6928
                          1, &data->scanner, 1);
6929 6930 6931 6932 6933 6934
  }
  else
  {
    data->current_chunk++;
    if (translog_get_next_chunk(&data->scanner))
      DBUG_RETURN(1);
unknown's avatar
unknown committed
6935 6936 6937
     if (data->scanner.page == END_OF_LOG)
     {
       /*
unknown's avatar
unknown committed
6938 6939
         Actually it should not happened, but we want to quit nicely in case
         of a truncated log
unknown's avatar
unknown committed
6940 6941 6942
       */
       DBUG_RETURN(1);
     }
6943 6944 6945 6946 6947 6948
  }
  type= data->scanner.page[data->scanner.page_offset] & TRANSLOG_CHUNK_TYPE;

  if (type == TRANSLOG_CHUNK_LSN && data->header.groups_no)
  {
    DBUG_PRINT("info",
unknown's avatar
unknown committed
6949
               ("Last chunk: data len: %u  offset: %u  group: %u of %u",
6950 6951 6952
                data->header.chunk0_data_len, data->scanner.page_offset,
                data->current_group, data->header.groups_no - 1));
    DBUG_ASSERT(data->header.groups_no - 1 == data->current_group);
6953 6954
    DBUG_ASSERT(data->header.lsn ==
                data->scanner.page_addr + data->scanner.page_offset);
6955
    translog_destroy_scanner(&data->scanner);
unknown's avatar
unknown committed
6956
    translog_scanner_init(data->header.chunk0_data_addr, 1, &data->scanner, 1);
6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970
    data->chunk_size= data->header.chunk0_data_len;
    data->body_offset= data->scanner.page_offset;
    data->current_offset= new_current_offset;
    data->eor= 1;
    DBUG_RETURN(0);
  }

  if (type == TRANSLOG_CHUNK_LSN || type == TRANSLOG_CHUNK_FIXED)
  {
    data->eor= 1;
    DBUG_RETURN(1);                             /* End of record */
  }

  chunk_header_len=
unknown's avatar
unknown committed
6971
    translog_get_chunk_header_length(data->scanner.page +
6972 6973 6974 6975 6976 6977
                                     data->scanner.page_offset);
  chunk_len= translog_get_total_chunk_length(data->scanner.page,
                                             data->scanner.page_offset);
  data->chunk_size= chunk_len - chunk_header_len;
  data->body_offset= data->scanner.page_offset + chunk_header_len;
  data->current_offset= new_current_offset;
unknown's avatar
unknown committed
6978 6979
  DBUG_PRINT("info", ("grp: %u  chunk: %u  body_offset: %u  chunk_size: %u  "
                      "current_offset: %lu",
6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996
                      (uint) data->current_group,
                      (uint) data->current_chunk,
                      (uint) data->body_offset,
                      (uint) data->chunk_size, (ulong) data->current_offset));
  DBUG_RETURN(0);
}


/*
  Initialize record reader data from LSN

  SYNOPSIS
    translog_init_reader_data()
    lsn                  reference to LSN we should start from
    data                 reader data to initialize

  RETURN
unknown's avatar
unknown committed
6997 6998
    0  OK
    1  Error
6999 7000
*/

7001
static my_bool translog_init_reader_data(LSN lsn,
unknown's avatar
unknown committed
7002
                                         TRANSLOG_READER_DATA *data)
7003
{
unknown's avatar
unknown committed
7004
  int read_header;
7005
  DBUG_ENTER("translog_init_reader_data");
unknown's avatar
unknown committed
7006
  if (translog_scanner_init(lsn, 1, &data->scanner, 1) ||
unknown's avatar
unknown committed
7007 7008 7009
      ((read_header=
        translog_read_record_header_scan(&data->scanner, &data->header, 1))
       == RECHEADER_READ_ERROR))
7010
    DBUG_RETURN(1);
unknown's avatar
unknown committed
7011
  data->read_header= read_header;
7012 7013 7014 7015 7016 7017
  data->body_offset= data->header.non_header_data_start_offset;
  data->chunk_size= data->header.non_header_data_len;
  data->current_offset= data->read_header;
  data->current_group= 0;
  data->current_chunk= 0;
  data->eor= 0;
unknown's avatar
unknown committed
7018 7019
  DBUG_PRINT("info", ("read_header: %u  "
                      "body_offset: %u  chunk_size: %u  current_offset: %lu",
7020 7021 7022 7023 7024 7025 7026
                      (uint) data->read_header,
                      (uint) data->body_offset,
                      (uint) data->chunk_size, (ulong) data->current_offset));
  DBUG_RETURN(0);
}


7027 7028 7029 7030
/**
  @brief Destroy reader data object
*/

unknown's avatar
unknown committed
7031
static void translog_destroy_reader_data(TRANSLOG_READER_DATA *data)
7032 7033
{
  translog_destroy_scanner(&data->scanner);
unknown's avatar
unknown committed
7034
  translog_free_record_header(&data->header);
7035 7036 7037
}


7038 7039 7040 7041 7042 7043
/*
  Read a part of the record.

  SYNOPSIS
    translog_read_record_header()
    lsn                  log record serial number (address of the record)
unknown's avatar
unknown committed
7044
    offset               From the beginning of the record beginning (read
7045
                         by translog_read_record_header).
unknown's avatar
unknown committed
7046 7047
    length               Length of record part which have to be read.
    buffer               Buffer where to read the record part (have to be at
7048 7049 7050 7051 7052 7053
                         least 'length' bytes length)

  RETURN
    length of data actually read
*/

7054
translog_size_t translog_read_record(LSN lsn,
7055 7056
                                     translog_size_t offset,
                                     translog_size_t length,
unknown's avatar
unknown committed
7057
                                     uchar *buffer,
unknown's avatar
unknown committed
7058
                                     TRANSLOG_READER_DATA *data)
7059 7060 7061
{
  translog_size_t requested_length= length;
  translog_size_t end= offset + length;
unknown's avatar
unknown committed
7062
  TRANSLOG_READER_DATA internal_data;
7063
  DBUG_ENTER("translog_read_record");
7064 7065
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
7066 7067 7068

  if (data == NULL)
  {
unknown's avatar
unknown committed
7069
    DBUG_ASSERT(lsn != LSN_IMPOSSIBLE);
7070 7071 7072 7073 7074 7075 7076 7077 7078
    data= &internal_data;
  }
  if (lsn ||
      (offset < data->current_offset &&
       !(offset < data->read_header && offset + length < data->read_header)))
  {
    if (translog_init_reader_data(lsn, data))
      DBUG_RETURN(0);
  }
unknown's avatar
unknown committed
7079 7080 7081
  DBUG_PRINT("info", ("Offset: %lu  length: %lu  "
                      "Scanner: Cur: (%lu,0x%lx)  Hrz: (%lu,0x%lx)  "
                      "Lst: (%lu,0x%lx)  Offset: %u(%x)  fixed: %d",
7082
                      (ulong) offset, (ulong) length,
unknown's avatar
unknown committed
7083 7084 7085
                      LSN_IN_PARTS(data->scanner.page_addr),
                      LSN_IN_PARTS(data->scanner.horizon),
                      LSN_IN_PARTS(data->scanner.last_file_page),
7086 7087 7088 7089 7090
                      (uint) data->scanner.page_offset,
                      (uint) data->scanner.page_offset,
                      data->scanner.fixed_horizon));
  if (offset < data->read_header)
  {
unknown's avatar
unknown committed
7091
    uint16 len= min(data->read_header, end) - offset;
7092
    DBUG_PRINT("info",
unknown's avatar
unknown committed
7093
               ("enter header offset: %lu  length: %lu",
7094
                (ulong) offset, (ulong) length));
unknown's avatar
unknown committed
7095
    memcpy(buffer, data->header.header + offset, len);
7096 7097
    length-= len;
    if (length == 0)
7098 7099
    {
      translog_destroy_reader_data(data);
7100
      DBUG_RETURN(requested_length);
7101
    }
7102 7103 7104
    offset+= len;
    buffer+= len;
    DBUG_PRINT("info",
unknown's avatar
unknown committed
7105
               ("len: %u  offset: %lu   curr: %lu  length: %lu",
7106 7107 7108 7109 7110 7111
                len, (ulong) offset, (ulong) data->current_offset,
                (ulong) length));
  }
  /* TODO: find first page which we should read by offset */

  /* read the record chunk by chunk */
unknown's avatar
unknown committed
7112
  for(;;)
7113 7114 7115
  {
    uint page_end= data->current_offset + data->chunk_size;
    DBUG_PRINT("info",
unknown's avatar
unknown committed
7116 7117
               ("enter body offset: %lu  curr: %lu  "
                "length: %lu  page_end: %lu",
7118 7119 7120 7121 7122
                (ulong) offset, (ulong) data->current_offset, (ulong) length,
                (ulong) page_end));
    if (offset < page_end)
    {
      uint len= page_end - offset;
unknown's avatar
unknown committed
7123
      set_if_smaller(len, length); /* in case we read beyond record's end */
unknown's avatar
unknown committed
7124 7125
      DBUG_ASSERT(offset >= data->current_offset);
      memcpy(buffer,
7126 7127 7128 7129
              data->scanner.page + data->body_offset +
              (offset - data->current_offset), len);
      length-= len;
      if (length == 0)
7130 7131
      {
        translog_destroy_reader_data(data);
7132
        DBUG_RETURN(requested_length);
7133
      }
7134 7135 7136
      offset+= len;
      buffer+= len;
      DBUG_PRINT("info",
unknown's avatar
unknown committed
7137
                 ("len: %u  offset: %lu  curr: %lu  length: %lu",
7138 7139 7140 7141
                  len, (ulong) offset, (ulong) data->current_offset,
                  (ulong) length));
    }
    if (translog_record_read_next_chunk(data))
7142 7143
    {
      translog_destroy_reader_data(data);
7144
      DBUG_RETURN(requested_length - length);
7145
    }
unknown's avatar
unknown committed
7146
  }
7147 7148 7149 7150
}


/*
7151
  @brief Force skipping to the next buffer
7152

7153 7154
  @todo Do not copy old page content if all page protections are switched off
  (because we do not need calculate something or change old parts of the page)
7155 7156 7157 7158
*/

static void translog_force_current_buffer_to_finish()
{
unknown's avatar
unknown committed
7159
  TRANSLOG_ADDRESS new_buff_beginning;
unknown's avatar
unknown committed
7160 7161 7162 7163
  uint16 old_buffer_no= log_descriptor.bc.buffer_no;
  uint16 new_buffer_no= (old_buffer_no + 1) % TRANSLOG_BUFFERS_NO;
  struct st_translog_buffer *new_buffer= (log_descriptor.buffers +
                                          new_buffer_no);
7164
  struct st_translog_buffer *old_buffer= log_descriptor.bc.buffer;
7165
  uchar *data= log_descriptor.bc.ptr - log_descriptor.bc.current_page_fill;
unknown's avatar
unknown committed
7166 7167
  uint16 left= TRANSLOG_PAGE_SIZE - log_descriptor.bc.current_page_fill;
  uint16 current_page_fill, write_counter, previous_offset;
7168
  DBUG_ENTER("translog_force_current_buffer_to_finish");
unknown's avatar
unknown committed
7169 7170 7171
  DBUG_PRINT("enter", ("Buffer #%u 0x%lx  "
                       "Buffer addr: (%lu,0x%lx)  "
                       "Page addr: (%lu,0x%lx)  "
7172
                       "size: %lu (%lu)  Pg: %u  left: %u  in progress %u",
7173 7174
                       (uint) log_descriptor.bc.buffer_no,
                       (ulong) log_descriptor.bc.buffer,
unknown's avatar
unknown committed
7175
                       LSN_IN_PARTS(log_descriptor.bc.buffer->offset),
7176 7177
                       (ulong) LSN_FILE_NO(log_descriptor.horizon),
                       (ulong) (LSN_OFFSET(log_descriptor.horizon) -
unknown's avatar
unknown committed
7178
                                log_descriptor.bc.current_page_fill),
7179 7180 7181
                       (ulong) log_descriptor.bc.buffer->size,
                       (ulong) (log_descriptor.bc.ptr -log_descriptor.bc.
                                buffer->buffer),
unknown's avatar
unknown committed
7182
                       (uint) log_descriptor.bc.current_page_fill,
7183 7184 7185 7186
                       (uint) left,
                       (uint) log_descriptor.bc.buffer->
                       copy_to_buffer_in_progress));
  translog_lock_assert_owner();
unknown's avatar
unknown committed
7187 7188 7189
  LINT_INIT(current_page_fill);
  new_buff_beginning= log_descriptor.bc.buffer->offset;
  new_buff_beginning+= log_descriptor.bc.buffer->size; /* increase offset */
unknown's avatar
unknown committed
7190

7191
  DBUG_ASSERT(log_descriptor.bc.ptr !=NULL);
7192 7193
  DBUG_ASSERT(LSN_FILE_NO(log_descriptor.horizon) ==
              LSN_FILE_NO(log_descriptor.bc.buffer->offset));
unknown's avatar
unknown committed
7194
  translog_check_cursor(&log_descriptor.bc);
unknown's avatar
unknown committed
7195 7196
  DBUG_ASSERT(left < TRANSLOG_PAGE_SIZE);
  if (left != 0)
7197 7198 7199 7200 7201
  {
    /*
       TODO: if 'left' is so small that can't hold any other record
       then do not move the page
    */
unknown's avatar
unknown committed
7202
    DBUG_PRINT("info", ("left: %u", (uint) left));
7203

7204
    /* decrease offset */
unknown's avatar
unknown committed
7205
    new_buff_beginning-= log_descriptor.bc.current_page_fill;
unknown's avatar
unknown committed
7206
    current_page_fill= log_descriptor.bc.current_page_fill;
7207

unknown's avatar
unknown committed
7208
    memset(log_descriptor.bc.ptr, TRANSLOG_FILLER, left);
7209
    log_descriptor.bc.buffer->size+= left;
unknown's avatar
unknown committed
7210
    DBUG_PRINT("info", ("Finish Page buffer #%u: 0x%lx  "
7211 7212 7213 7214 7215 7216 7217 7218 7219
                        "Size: %lu",
                        (uint) log_descriptor.bc.buffer->buffer_no,
                        (ulong) log_descriptor.bc.buffer,
                        (ulong) log_descriptor.bc.buffer->size));
    DBUG_ASSERT(log_descriptor.bc.buffer->buffer_no ==
                log_descriptor.bc.buffer_no);
  }
  else
  {
unknown's avatar
unknown committed
7220
    log_descriptor.bc.current_page_fill= 0;
7221 7222 7223
  }

  translog_buffer_lock(new_buffer);
7224 7225 7226 7227 7228 7229 7230 7231 7232 7233
#ifndef DBUG_OFF
  {
    TRANSLOG_ADDRESS offset= new_buffer->offset;
    TRANSLOG_FILE *file= new_buffer->file;
    uint8 ver= new_buffer->ver;
    translog_lock_assert_owner();
#endif
    translog_wait_for_buffer_free(new_buffer);
#ifndef DBUG_OFF
    /* We keep the handler locked so nobody can start this new buffer */
unknown's avatar
unknown committed
7234 7235
    DBUG_ASSERT(offset == new_buffer->offset && new_buffer->file == NULL &&
                (file == NULL ? ver : (uint8)(ver + 1)) == new_buffer->ver);
7236 7237
  }
#endif
7238

unknown's avatar
unknown committed
7239 7240 7241
  write_counter= log_descriptor.bc.write_counter;
  previous_offset= log_descriptor.bc.previous_offset;
  translog_start_buffer(new_buffer, &log_descriptor.bc, new_buffer_no);
unknown's avatar
unknown committed
7242
  /* Fix buffer offset (which was incorrectly set to horizon) */
unknown's avatar
unknown committed
7243
  log_descriptor.bc.buffer->offset= new_buff_beginning;
unknown's avatar
unknown committed
7244 7245
  log_descriptor.bc.write_counter= write_counter;
  log_descriptor.bc.previous_offset= previous_offset;
7246

unknown's avatar
unknown committed
7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267
  /*
    Advances this log pointer, increases writers and let other threads to
    write to the log while we process old page content
  */
  if (left)
  {
    log_descriptor.bc.ptr+= current_page_fill;
    log_descriptor.bc.buffer->size= log_descriptor.bc.current_page_fill=
      current_page_fill;
    new_buffer->overlay= old_buffer;
  }
  else
    translog_new_page_header(&log_descriptor.horizon, &log_descriptor.bc);
  translog_buffer_increase_writers(new_buffer);
  translog_buffer_unlock(new_buffer);

  /*
    We have to wait until all writers finish before start changing the
    pages by applying protection and copying the page content in the
    new buffer.
  */
7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288
#ifndef DBUG_OFF
  {
    TRANSLOG_ADDRESS offset= old_buffer->offset;
    TRANSLOG_FILE *file= old_buffer->file;
    uint8 ver= old_buffer->ver;
#endif
    /*
      Now only one thread can flush log (buffer can flush many threads but
      log flush is serialized) so no other thread can set is_closing_buffer
    */
    DBUG_ASSERT(!old_buffer->is_closing_buffer);
    old_buffer->is_closing_buffer= 1; /* Other flushes will wait */
    DBUG_PRINT("enter", ("Buffer #%u 0x%lx  is_closing_buffer set",
                         (uint) old_buffer->buffer_no, (ulong) old_buffer));
    translog_wait_for_writers(old_buffer);
#ifndef DBUG_OFF
    /* We blocked flushing this buffer so the buffer should not changed */
    DBUG_ASSERT(offset == old_buffer->offset && file == old_buffer->file &&
                ver == old_buffer->ver);
  }
#endif
unknown's avatar
unknown committed
7289

unknown's avatar
unknown committed
7290
  if (log_descriptor.flags & TRANSLOG_SECTOR_PROTECTION)
7291 7292 7293 7294 7295
  {
    translog_put_sector_protection(data, &log_descriptor.bc);
    if (left)
    {
      log_descriptor.bc.write_counter++;
unknown's avatar
unknown committed
7296
      log_descriptor.bc.previous_offset= current_page_fill;
7297 7298 7299 7300 7301 7302 7303 7304 7305
    }
    else
    {
      DBUG_PRINT("info", ("drop write_counter"));
      log_descriptor.bc.write_counter= 0;
      log_descriptor.bc.previous_offset= 0;
    }
  }

unknown's avatar
unknown committed
7306
  if (log_descriptor.flags & TRANSLOG_PAGE_CRC)
7307
  {
unknown's avatar
unknown committed
7308 7309 7310
    uint32 crc= translog_crc(data + log_descriptor.page_overhead,
                             TRANSLOG_PAGE_SIZE -
                             log_descriptor.page_overhead);
7311 7312 7313
    DBUG_PRINT("info", ("CRC: 0x%lx", (ulong) crc));
    int4store(data + 3 + 3 + 1, crc);
  }
7314 7315 7316 7317
  old_buffer->is_closing_buffer= 0;
  DBUG_PRINT("enter", ("Buffer #%u 0x%lx  is_closing_buffer cleared",
                       (uint) old_buffer->buffer_no, (ulong) old_buffer));
  pthread_cond_broadcast(&old_buffer->waiting_filling_buffer);
7318 7319 7320

  if (left)
  {
7321
    /*
unknown's avatar
unknown committed
7322
      TODO: do not copy beginning of the page if we have no CRC or sector
7323 7324
      checks on
    */
unknown's avatar
unknown committed
7325
    memcpy(new_buffer->buffer, data, current_page_fill);
7326
  }
7327
  old_buffer->next_buffer_offset= new_buffer->offset;
7328

unknown's avatar
unknown committed
7329 7330 7331 7332
  translog_buffer_lock(new_buffer);
  translog_buffer_decrease_writers(new_buffer);
  translog_buffer_unlock(new_buffer);

7333 7334 7335
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
7336

7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361
/**
   @brief Flush the log up to given LSN (included)

   @param  lsn             log record serial number up to which (inclusive)
                           the log has to be flushed

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

  @todo LOG: when a log write fails, we should not write to this log anymore
  (if we add more log records to this log they will be unreadable: we will hit
  the broken log record): all translog_flush() should be made to fail (because
  translog_flush() is when a a transaction wants something durable and we
  cannot make anything durable as log is corrupted). For that, a "my_bool
  st_translog_descriptor::write_error" could be set to 1 when a
  translog_write_record() or translog_flush() fails, and translog_flush()
  would test this var (and translog_write_record() could also test this var if
  it wants, though it's not absolutely needed).
  Then, either shut Maria down immediately, or switch to a new log (but if we
  get write error after write error, that would create too many logs).
  A popular open-source transactional engine intentionally crashes as soon as
  a log flush fails (we however don't want to crash the entire mysqld, but
  stopping all engine's operations immediately would make sense).
  Same applies to translog_write_record().
7362 7363

  @todo: remove serialization and make group commit.
7364 7365
*/

unknown's avatar
unknown committed
7366
my_bool translog_flush(TRANSLOG_ADDRESS lsn)
7367
{
7368
  LSN old_flushed, sent_to_disk;
7369
  TRANSLOG_ADDRESS flush_horizon;
7370
  int rc= 0;
7371
  /* We can't have more different files then buffers */
unknown's avatar
unknown committed
7372
  TRANSLOG_FILE *file_handlers[TRANSLOG_BUFFERS_NO];
7373 7374
  int current_file_handler= -1;
  uint32 prev_file= 0;
7375 7376
  my_bool full_circle= 0;
  DBUG_ENTER("translog_flush");
unknown's avatar
unknown committed
7377
  DBUG_PRINT("enter", ("Flush up to LSN: (%lu,0x%lx)", LSN_IN_PARTS(lsn)));
7378 7379
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
7380
  LINT_INIT(sent_to_disk);
7381

7382
  pthread_mutex_lock(&log_descriptor.log_flush_lock);
7383
  translog_lock();
7384 7385 7386 7387 7388 7389
  if (log_descriptor.is_everything_flushed)
  {
    DBUG_PRINT("info", ("everything is flushed"));
    translog_unlock();
    goto out;
  }
7390
  flush_horizon= LSN_IMPOSSIBLE;
7391 7392 7393
  old_flushed= log_descriptor.flushed;
  for (;;)
  {
unknown's avatar
unknown committed
7394 7395
    uint16 buffer_no= log_descriptor.bc.buffer_no;
    uint16 buffer_start= buffer_no;
7396 7397
    struct st_translog_buffer *buffer_unlock= log_descriptor.bc.buffer;
    struct st_translog_buffer *buffer= log_descriptor.bc.buffer;
7398
    if (cmp_translog_addr(log_descriptor.flushed, lsn) >= 0)
7399
    {
unknown's avatar
unknown committed
7400
      DBUG_PRINT("info", ("already flushed: (%lu,0x%lx)",
unknown's avatar
unknown committed
7401
                          LSN_IN_PARTS(log_descriptor.flushed)));
7402 7403
      translog_unlock();
      goto out;
7404 7405
    }
    /* send to the file if it is not sent */
7406 7407 7408 7409 7410
    if (translog_status != TRANSLOG_OK)
    {
      rc= 1;
      goto out;
    }
7411
    sent_to_disk= translog_get_sent_to_disk();
7412
    if (cmp_translog_addr(sent_to_disk, lsn) >= 0 || full_circle)
7413 7414 7415 7416 7417 7418 7419 7420 7421
      break;

    do
    {
      buffer_no= (buffer_no + 1) % TRANSLOG_BUFFERS_NO;
      buffer= log_descriptor.buffers + buffer_no;
      translog_buffer_lock(buffer);
      translog_buffer_unlock(buffer_unlock);
      buffer_unlock= buffer;
unknown's avatar
unknown committed
7422
      if (buffer->file != NULL)
7423 7424 7425 7426 7427 7428
      {
        buffer_unlock= NULL;
        if (buffer_start == buffer_no)
        {
          /* we made a circle */
          full_circle= 1;
7429 7430 7431 7432 7433 7434
          /*
            If buffer from which we started still current we have to
            finish it (we will not flush intentionally more records
            then was at the moment of start flushing);
          */
          if (buffer_start == log_descriptor.bc.buffer_no)
7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448
          {
            translog_lock_assert_owner();
            /*
              Here we have loghandler locked.

              We are going to flush last buffer, and will not release
              log_flush_lock until it happened, so we can set the flag here
              and other process which going to flush will not be able read
              it and return earlier then we finish the flush process. (But
              other process can drop the flag if new LSN appeared (only
              after translog_force_current_buffer_to_finish() call and
              transaction log unlock of course))
            */
            log_descriptor.is_everything_flushed= 1;
7449
            translog_force_current_buffer_to_finish();
7450
          }
7451 7452 7453 7454
        }
        break;
      }
    } while ((buffer_start != buffer_no) &&
7455
             cmp_translog_addr(log_descriptor.flushed, lsn) < 0);
7456
    if (buffer_unlock != NULL && buffer_unlock != buffer)
7457
      translog_buffer_unlock(buffer_unlock);
7458 7459 7460

    if (prev_file != LSN_FILE_NO(buffer->offset))
    {
unknown's avatar
unknown committed
7461
      TRANSLOG_FILE *file;
7462 7463
      uint32 fn= LSN_FILE_NO(buffer->offset);
      prev_file= fn;
unknown's avatar
unknown committed
7464
      file= get_logfile_by_number(fn);
7465
      DBUG_ASSERT(file != NULL);
unknown's avatar
unknown committed
7466
      if (!file->is_sync)
7467 7468
      {
        current_file_handler++;
unknown's avatar
unknown committed
7469
        file_handlers[current_file_handler]= file;
7470 7471 7472 7473 7474
      }
      /* We sync file when we are closing it => do nothing if file closed */
    }
    DBUG_ASSERT(flush_horizon <= buffer->offset + buffer->size);
    flush_horizon= buffer->offset + buffer->size;
unknown's avatar
unknown committed
7475
    rc= translog_buffer_flush(buffer);
7476
    translog_buffer_unlock(buffer);
unknown's avatar
unknown committed
7477
    if (rc)
7478
      goto out;                                 /* rc is 1 */
unknown's avatar
unknown committed
7479
    translog_lock();
7480
  }
unknown's avatar
unknown committed
7481
  translog_unlock();
7482 7483

  {
unknown's avatar
unknown committed
7484 7485 7486
    TRANSLOG_FILE **cur= file_handlers;
    TRANSLOG_FILE **end= file_handlers + current_file_handler;
    for (; cur <= end; cur++)
7487
    {
unknown's avatar
unknown committed
7488
      (*cur)->is_sync= 1;
7489
      if (my_sync((*cur)->handler.file, MYF(MY_WME)))
7490 7491
      {
        rc= 1;
7492
        translog_stop_writing();
7493 7494
        goto out;
      }
7495 7496
    }
  }
7497
  log_descriptor.flushed= sent_to_disk;
7498 7499 7500 7501 7502 7503 7504 7505 7506 7507
  /*
    If we should flush (due to directory flush mode) and
    previous flush horizon was not within one page border with this one.
  */
  if (sync_log_dir >= TRANSLOG_SYNC_DIR_ALWAYS &&
      (LSN_FILE_NO(log_descriptor.previous_flush_horizon) !=
       LSN_FILE_NO(flush_horizon) ||
       ((LSN_OFFSET(log_descriptor.previous_flush_horizon) - 1) /
        TRANSLOG_PAGE_SIZE) !=
       ((LSN_OFFSET(flush_horizon) - 1) / TRANSLOG_PAGE_SIZE)))
unknown's avatar
unknown committed
7508
    rc|= sync_dir(log_descriptor.directory_fd, MYF(MY_WME | MY_IGNORE_BADFD));
7509
  log_descriptor.previous_flush_horizon= flush_horizon;
7510
out:
7511
  pthread_mutex_unlock(&log_descriptor.log_flush_lock);
7512 7513
  DBUG_RETURN(rc);
}
7514 7515


7516 7517 7518 7519 7520 7521 7522
/**
   @brief Gives a 2-byte-id to MARIA_SHARE and logs this fact

   If a MARIA_SHARE does not yet have a 2-byte-id (unique over all currently
   open MARIA_SHAREs), give it one and record this assignment in the log
   (LOGREC_FILE_ID log record).

unknown's avatar
unknown committed
7523
   @param  tbl_info        table
7524 7525 7526 7527 7528 7529 7530 7531 7532
   @param  trn             calling transaction

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

   @note Can be called even if share already has an id (then will do nothing)
*/

unknown's avatar
unknown committed
7533
int translog_assign_id_to_share(MARIA_HA *tbl_info, TRN *trn)
7534
{
unknown's avatar
unknown committed
7535
  MARIA_SHARE *share= tbl_info->s;
7536 7537 7538 7539 7540 7541
  /*
    If you give an id to a non-BLOCK_RECORD table, you also need to release
    this id somewhere. Then you can change the assertion.
  */
  DBUG_ASSERT(share->data_file_type == BLOCK_RECORD);
  /* re-check under mutex to avoid having 2 ids for the same share */
7542
  pthread_mutex_lock(&share->intern_lock);
7543 7544
  if (likely(share->id == 0))
  {
unknown's avatar
unknown committed
7545
    LSN lsn;
7546
    LEX_CUSTRING log_array[TRANSLOG_INTERNAL_PARTS + 2];
unknown's avatar
unknown committed
7547
    uchar log_data[FILEID_STORE_SIZE];
7548
    /* Inspired by set_short_trid() of trnman.c */
unknown's avatar
unknown committed
7549 7550
    uint i= share->kfile.file % SHARE_ID_MAX + 1;
    do
7551
    {
unknown's avatar
unknown committed
7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565
      my_atomic_rwlock_wrlock(&LOCK_id_to_share);
      for ( ; i <= SHARE_ID_MAX ; i++) /* the range is [1..SHARE_ID_MAX] */
      {
        void *tmp= NULL;
        if (id_to_share[i] == NULL &&
            my_atomic_casptr((void **)&id_to_share[i], &tmp, share))
        {
          share->id= (uint16)i;
          break;
        }
      }
      my_atomic_rwlock_wrunlock(&LOCK_id_to_share);
      i= 1; /* scan the whole array */
    } while (share->id == 0);
unknown's avatar
unknown committed
7566
    DBUG_PRINT("info", ("id_to_share: 0x%lx -> %u", (ulong)share, share->id));
7567
    log_array[TRANSLOG_INTERNAL_PARTS + 0].str=    log_data;
7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579
    log_array[TRANSLOG_INTERNAL_PARTS + 0].length= sizeof(log_data);
    /*
      open_file_name is an unresolved name (symlinks are not resolved, datadir
      is not realpath-ed, etc) which is good: the log can be moved to another
      directory and continue working.
    */
    log_array[TRANSLOG_INTERNAL_PARTS + 1].str= share->open_file_name;
    /**
       @todo if we had the name's length in MARIA_SHARE we could avoid this
       strlen()
    */
    log_array[TRANSLOG_INTERNAL_PARTS + 1].length=
unknown's avatar
unknown committed
7580
      strlen(share->open_file_name) + 1;
unknown's avatar
unknown committed
7581
    if (unlikely(translog_write_record(&lsn, LOGREC_FILE_ID, trn, tbl_info,
7582 7583 7584 7585
                                       (translog_size_t)
                                       (sizeof(log_data) +
                                        log_array[TRANSLOG_INTERNAL_PARTS +
                                                  1].length),
7586
                                       sizeof(log_array)/sizeof(log_array[0]),
unknown's avatar
unknown committed
7587
                                       log_array, log_data, NULL)))
7588 7589
    {
      pthread_mutex_unlock(&share->intern_lock);
7590
      return 1;
7591
    }
7592
  }
7593
  pthread_mutex_unlock(&share->intern_lock);
7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611
  return 0;
}


/**
   @brief Recycles a MARIA_SHARE's short id.

   @param  share           table

   @note Must be called only if share has an id (i.e. id != 0)
*/

void translog_deassign_id_from_share(MARIA_SHARE *share)
{
  DBUG_PRINT("info", ("id_to_share: 0x%lx id %u -> 0",
                      (ulong)share, share->id));
  /*
    We don't need any mutex as we are called only when closing the last
unknown's avatar
unknown committed
7612 7613 7614
    instance of the table or at the end of REPAIR: no writes can be
    happening. But a Checkpoint may be reading share->id, so we require this
    mutex:
7615
  */
unknown's avatar
unknown committed
7616
  safe_mutex_assert_owner(&share->intern_lock);
7617 7618 7619
  my_atomic_rwlock_rdlock(&LOCK_id_to_share);
  my_atomic_storeptr((void **)&id_to_share[share->id], 0);
  my_atomic_rwlock_rdunlock(&LOCK_id_to_share);
unknown's avatar
unknown committed
7620
  share->id= 0;
unknown's avatar
unknown committed
7621 7622
  /* useless but safety: */
  share->lsn_of_file_id= LSN_IMPOSSIBLE;
7623
}
unknown's avatar
unknown committed
7624 7625


unknown's avatar
unknown committed
7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636
void translog_assign_id_to_share_from_recovery(MARIA_SHARE *share,
                                               uint16 id)
{
  DBUG_ASSERT(maria_in_recovery && !maria_multi_threaded);
  DBUG_ASSERT(share->data_file_type == BLOCK_RECORD);
  DBUG_ASSERT(share->id == 0);
  DBUG_ASSERT(id_to_share[id] == NULL);
  id_to_share[share->id= id]= share;
}


7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650
/**
   @brief check if such log file exists

   @param file_no number of the file to test

   @retval 0 no such file
   @retval 1 there is file with such number
*/

my_bool translog_is_file(uint file_no)
{
  MY_STAT stat_buff;
  char path[FN_REFLEN];
  return (test(my_stat(translog_filename_by_fileno(file_no, path),
7651
                       &stat_buff, MYF(0))));
7652 7653 7654
}


unknown's avatar
unknown committed
7655
/**
7656
  @brief returns minimum log file number
unknown's avatar
unknown committed
7657

7658 7659 7660 7661 7662
  @param horizon         the end of the log
  @param is_protected    true if it is under purge_log protection

  @retval minimum file number
  @retval 0 no files found
unknown's avatar
unknown committed
7663 7664
*/

7665
static uint32 translog_first_file(TRANSLOG_ADDRESS horizon, int is_protected)
unknown's avatar
unknown committed
7666
{
7667
  uint min_file= 0, max_file;
7668 7669
  DBUG_ENTER("translog_first_file");
  if (!is_protected)
7670
    pthread_mutex_lock(&log_descriptor.purger_lock);
7671 7672 7673 7674 7675 7676
  if (log_descriptor.min_file_number &&
      translog_is_file(log_descriptor.min_file_number))
  {
    DBUG_PRINT("info", ("cached %lu",
                        (ulong) log_descriptor.min_file_number));
    if (!is_protected)
7677
      pthread_mutex_unlock(&log_descriptor.purger_lock);
7678 7679
    DBUG_RETURN(log_descriptor.min_file_number);
  }
7680

7681 7682
  max_file= LSN_FILE_NO(horizon);

7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695
  /* binary search for last file */
  while (min_file != max_file && min_file != (max_file - 1))
  {
    uint test= (min_file + max_file) / 2;
    DBUG_PRINT("info", ("min_file: %u  test: %u  max_file: %u",
                        min_file, test, max_file));
    if (test == max_file)
      test--;
    if (translog_is_file(test))
      max_file= test;
    else
      min_file= test;
  }
7696 7697
  log_descriptor.min_file_number= max_file;
  if (!is_protected)
7698
    pthread_mutex_unlock(&log_descriptor.purger_lock);
unknown's avatar
unknown committed
7699 7700
  DBUG_PRINT("info", ("first file :%lu", (ulong) max_file));
  DBUG_ASSERT(max_file >= 1);
7701 7702 7703 7704
  DBUG_RETURN(max_file);
}


7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718
/**
  @brief returns the most close LSN higher the given chunk address

  @param addr the chunk address to start from
  @param horizon the horizon if it is known or LSN_IMPOSSIBLE

  @retval LSN_ERROR Error
  @retval LSN_IMPOSSIBLE no LSNs after the address
  @retval # LSN of the most close LSN higher the given chunk address
*/

LSN translog_next_LSN(TRANSLOG_ADDRESS addr, TRANSLOG_ADDRESS horizon)
{
  TRANSLOG_SCANNER_DATA scanner;
7719
  LSN result;
7720 7721 7722 7723 7724 7725 7726 7727
  DBUG_ENTER("translog_next_LSN");

  if (horizon == LSN_IMPOSSIBLE)
    horizon= translog_get_horizon();

  if (addr == horizon)
    DBUG_RETURN(LSN_IMPOSSIBLE);

unknown's avatar
unknown committed
7728
  translog_scanner_init(addr, 0, &scanner, 1);
unknown's avatar
unknown committed
7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748
  /*
    addr can point not to a chunk beginning but page end so next
    page beginning.
  */
  if (addr % TRANSLOG_PAGE_SIZE == 0)
  {
    /*
      We are emulating the page end which cased such horizon value to
      trigger translog_scanner_eop().

      We can't just increase addr on page header overhead because it
      can be file end so we allow translog_get_next_chunk() to skip
      to the next page in correct way
    */
    scanner.page_addr-= TRANSLOG_PAGE_SIZE;
    scanner.page_offset= TRANSLOG_PAGE_SIZE;
#ifndef DBUG_OFF
    scanner.page= NULL; /* prevent using incorrect page content */
#endif
  }
7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762
  /* addr can point not to a chunk beginning but to a page end */
  if (translog_scanner_eop(&scanner))
  {
    if (translog_get_next_chunk(&scanner))
    {
      result= LSN_ERROR;
      goto out;
    }
    if (scanner.page == END_OF_LOG)
    {
      result= LSN_IMPOSSIBLE;
      goto out;
    }
  }
7763

7764
  while (!translog_is_LSN_chunk(scanner.page[scanner.page_offset]) &&
unknown's avatar
unknown committed
7765
         scanner.page[scanner.page_offset] != TRANSLOG_FILLER)
7766 7767
  {
    if (translog_get_next_chunk(&scanner))
unknown's avatar
unknown committed
7768 7769 7770 7771 7772 7773 7774 7775 7776
    {
      result= LSN_ERROR;
      goto out;
    }
    if (scanner.page == END_OF_LOG)
    {
      result= LSN_IMPOSSIBLE;
      goto out;
    }
7777
  }
7778

unknown's avatar
unknown committed
7779
  if (scanner.page[scanner.page_offset] == TRANSLOG_FILLER)
7780 7781 7782
    result= LSN_IMPOSSIBLE; /* reached page filler */
  else
    result= scanner.page_addr + scanner.page_offset;
unknown's avatar
unknown committed
7783
out:
7784 7785
  translog_destroy_scanner(&scanner);
  DBUG_RETURN(result);
7786 7787
}

7788

7789 7790 7791 7792
/**
   @brief returns the LSN of the first record starting in this log

   @retval LSN_ERROR Error
unknown's avatar
unknown committed
7793
   @retval LSN_IMPOSSIBLE no log or the log is empty
7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804
   @retval # LSN of the first record
*/

LSN translog_first_lsn_in_log()
{
  TRANSLOG_ADDRESS addr, horizon= translog_get_horizon();
  TRANSLOG_VALIDATOR_DATA data;
  uint file;
  uint16 chunk_offset;
  uchar *page;
  DBUG_ENTER("translog_first_lsn_in_log");
7805
  DBUG_PRINT("info", ("Horizon: (%lu,0x%lx)", LSN_IN_PARTS(horizon)));
7806 7807
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
7808 7809 7810 7811 7812 7813

  if (!(file= translog_first_file(horizon, 0)))
  {
    /* log has no records yet */
    DBUG_RETURN(LSN_IMPOSSIBLE);
  }
7814

7815
  addr= MAKE_LSN(file, TRANSLOG_PAGE_SIZE); /* the first page of the file */
7816 7817
  data.addr= &addr;
  {
7818 7819
    TRANSLOG_PAGE_SIZE_BUFF psize_buff;
    if ((page= translog_get_page(&data, psize_buff.buffer, NULL)) == NULL ||
7820
        (chunk_offset= translog_get_first_chunk_offset(page)) == 0)
7821 7822
      DBUG_RETURN(LSN_ERROR);
  }
7823 7824 7825
  addr+= chunk_offset;

  DBUG_RETURN(translog_next_LSN(addr, horizon));
7826 7827 7828 7829
}


/**
7830
   @brief Returns theoretical first LSN if first log is present
7831 7832 7833 7834 7835 7836 7837 7838 7839

   @retval LSN_ERROR Error
   @retval LSN_IMPOSSIBLE no log
   @retval # LSN of the first record
*/

LSN translog_first_theoretical_lsn()
{
  TRANSLOG_ADDRESS addr= translog_get_horizon();
7840 7841
  TRANSLOG_PAGE_SIZE_BUFF psize_buff;
  uchar *page;
7842 7843
  TRANSLOG_VALIDATOR_DATA data;
  DBUG_ENTER("translog_first_theoretical_lsn");
unknown's avatar
unknown committed
7844
  DBUG_PRINT("info", ("Horizon: (%lu,0x%lx)", LSN_IN_PARTS(addr)));
7845 7846
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
7847 7848 7849 7850 7851

  if (!translog_is_file(1))
    DBUG_RETURN(LSN_IMPOSSIBLE);
  if (addr == MAKE_LSN(1, TRANSLOG_PAGE_SIZE))
  {
7852
    /* log has no records yet */
7853 7854 7855 7856 7857 7858
    DBUG_RETURN(MAKE_LSN(1, TRANSLOG_PAGE_SIZE +
                         log_descriptor.page_overhead));
  }

  addr= MAKE_LSN(1, TRANSLOG_PAGE_SIZE); /* the first page of the file */
  data.addr= &addr;
7859
  if ((page= translog_get_page(&data, psize_buff.buffer, NULL)) == NULL)
7860 7861 7862 7863
    DBUG_RETURN(LSN_ERROR);

  DBUG_RETURN(MAKE_LSN(1, TRANSLOG_PAGE_SIZE +
                       page_overhead[page[TRANSLOG_PAGE_FLAGS]]));
unknown's avatar
unknown committed
7864
}
7865 7866 7867


/**
7868
  @brief Checks given low water mark and purge files if it is need
7869

unknown's avatar
unknown committed
7870
  @param low the last (minimum) address which is need
7871 7872 7873 7874 7875

  @retval 0 OK
  @retval 1 Error
*/

unknown's avatar
unknown committed
7876
my_bool translog_purge(TRANSLOG_ADDRESS low)
7877 7878 7879 7880 7881
{
  uint32 last_need_file= LSN_FILE_NO(low);
  TRANSLOG_ADDRESS horizon= translog_get_horizon();
  int rc= 0;
  DBUG_ENTER("translog_purge");
unknown's avatar
unknown committed
7882
  DBUG_PRINT("enter", ("low: (%lu,0x%lx)", LSN_IN_PARTS(low)));
7883 7884
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);
7885

7886
  pthread_mutex_lock(&log_descriptor.purger_lock);
7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903
  if (LSN_FILE_NO(log_descriptor.last_lsn_checked) < last_need_file)
  {
    uint32 i;
    uint32 min_file= translog_first_file(horizon, 1);
    DBUG_ASSERT(min_file != 0); /* log is already started */
    for(i= min_file; i < last_need_file && rc == 0; i++)
    {
      LSN lsn= translog_get_file_max_lsn_stored(i);
      if (lsn == LSN_IMPOSSIBLE)
        break;   /* files are still in writing */
      if (lsn == LSN_ERROR)
      {
        rc= 1;
        break;
      }
      if (cmp_translog_addr(lsn, low) >= 0)
        break;
unknown's avatar
unknown committed
7904

7905
      DBUG_PRINT("info", ("purge file %lu", (ulong) i));
unknown's avatar
unknown committed
7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927

      /* remove file descriptor from the cache */
      /*
        log_descriptor.min_file can be changed only here during execution
        and the function is serialized, so we can access it without problems
      */
      if (i >= log_descriptor.min_file)
      {
        TRANSLOG_FILE *file;
        rw_wrlock(&log_descriptor.open_files_lock);
        DBUG_ASSERT(log_descriptor.max_file - log_descriptor.min_file + 1 ==
                    log_descriptor.open_files.elements);
        DBUG_ASSERT(log_descriptor.min_file == i);
        file= *((TRANSLOG_FILE **)pop_dynamic(&log_descriptor.open_files));
        DBUG_PRINT("info", ("Files : %d", log_descriptor.open_files.elements));
        DBUG_ASSERT(i == file->number);
        log_descriptor.min_file++;
        DBUG_ASSERT(log_descriptor.max_file - log_descriptor.min_file + 1 ==
                    log_descriptor.open_files.elements);
        rw_unlock(&log_descriptor.open_files_lock);
        translog_close_log_file(file);
      }
7928
      if (log_purge_type == TRANSLOG_PURGE_IMMIDIATE)
7929 7930 7931 7932 7933 7934
      {
        char path[FN_REFLEN], *file_name;
        file_name= translog_filename_by_fileno(i, path);
        rc= test(my_delete(file_name, MYF(MY_WME)));
      }
    }
7935 7936 7937 7938 7939 7940
    if (unlikely(rc == 1))
      log_descriptor.min_need_file= 0; /* impossible value */
    else
      log_descriptor.min_need_file= i;
  }

unknown's avatar
unknown committed
7941
  pthread_mutex_unlock(&log_descriptor.purger_lock);
7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962
  DBUG_RETURN(rc);
}


/**
  @brief Purges files by stored min need file in case of
    "ondemend" purge type

  @note This function do real work only if it is "ondemend" purge type
    and translog_purge() was called at least once and last time without
    errors

  @retval 0 OK
  @retval 1 Error
*/

my_bool translog_purge_at_flush()
{
  uint32 i, min_file;
  int rc= 0;
  DBUG_ENTER("translog_purge_at_flush");
unknown's avatar
unknown committed
7963 7964 7965 7966 7967
  DBUG_ASSERT(translog_status == TRANSLOG_OK ||
              translog_status == TRANSLOG_READONLY);

  if (unlikely(translog_status == TRANSLOG_READONLY))
  {
unknown's avatar
unknown committed
7968
    DBUG_PRINT("info", ("The log is read only => exit"));
unknown's avatar
unknown committed
7969 7970
    DBUG_RETURN(0);
  }
7971 7972 7973 7974 7975 7976 7977

  if (log_purge_type != TRANSLOG_PURGE_ONDEMAND)
  {
    DBUG_PRINT("info", ("It is not \"at_flush\" => exit"));
    DBUG_RETURN(0);
  }

unknown's avatar
unknown committed
7978
  pthread_mutex_lock(&log_descriptor.purger_lock);
7979 7980 7981 7982

  if (unlikely(log_descriptor.min_need_file == 0))
  {
    DBUG_PRINT("info", ("No info about min need file => exit"));
unknown's avatar
unknown committed
7983
    pthread_mutex_unlock(&log_descriptor.purger_lock);
7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994
    DBUG_RETURN(0);
  }

  min_file= translog_first_file(translog_get_horizon(), 1);
  DBUG_ASSERT(min_file != 0); /* log is already started */
  for(i= min_file; i < log_descriptor.min_need_file && rc == 0; i++)
  {
    char path[FN_REFLEN], *file_name;
    DBUG_PRINT("info", ("purge file %lu\n", (ulong) i));
    file_name= translog_filename_by_fileno(i, path);
    rc= test(my_delete(file_name, MYF(MY_WME)));
7995 7996
  }

7997
  pthread_mutex_unlock(&log_descriptor.purger_lock);
7998 7999
  DBUG_RETURN(rc);
}
8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026


/**
  @brief Gets min file number

  @param horizon         the end of the log

  @retval minimum file number
  @retval 0 no files found
*/

uint32 translog_get_first_file(TRANSLOG_ADDRESS horizon)
{
  return translog_first_file(horizon, 0);
}


/**
  @brief Gets min file number which is needed

  @retval minimum file number
  @retval 0 unknown
*/

uint32 translog_get_first_needed_file()
{
  uint32 file_no;
unknown's avatar
unknown committed
8027
  pthread_mutex_lock(&log_descriptor.purger_lock);
8028
  file_no= log_descriptor.min_need_file;
unknown's avatar
unknown committed
8029
  pthread_mutex_unlock(&log_descriptor.purger_lock);
8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055
  return file_no;
}


/**
  @brief Gets transaction log file size

  @return transaction log file size
*/

uint32 translog_get_file_size()
{
  uint32 res;
  translog_lock();
  res= log_descriptor.log_file_max_size;
  translog_unlock();
  return (res);
}


/**
  @brief Sets transaction log file size

  @return Returns actually set transaction log size
*/

unknown's avatar
unknown committed
8056
void translog_set_file_size(uint32 size)
8057
{
8058
  struct st_translog_buffer *old_buffer= NULL;
unknown's avatar
unknown committed
8059
  DBUG_ENTER("translog_set_file_size");
8060
  translog_lock();
unknown's avatar
unknown committed
8061 8062
  DBUG_PRINT("enter", ("Size: %lu", (ulong) size));
  DBUG_ASSERT(size % TRANSLOG_PAGE_SIZE == 0 &&
unknown's avatar
unknown committed
8063
              size >= TRANSLOG_MIN_FILE_SIZE);
unknown's avatar
unknown committed
8064
  log_descriptor.log_file_max_size= size;
8065 8066 8067
  /* if current file longer then finish it*/
  if (LSN_OFFSET(log_descriptor.horizon) >=  log_descriptor.log_file_max_size)
  {
8068
    old_buffer= log_descriptor.bc.buffer;
8069 8070 8071 8072
    translog_buffer_next(&log_descriptor.horizon, &log_descriptor.bc, 1);
    translog_buffer_unlock(old_buffer);
  }
  translog_unlock();
8073 8074 8075 8076 8077 8078
  if (old_buffer)
  {
    translog_buffer_lock(old_buffer);
    translog_buffer_flush(old_buffer);
    translog_buffer_unlock(old_buffer);
  }
unknown's avatar
unknown committed
8079
  DBUG_VOID_RETURN;
8080
}
8081 8082 8083

#ifdef MARIA_DUMP_LOG
#include <my_getopt.h>
8084
extern void translog_example_table_init();
8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097
static const char *load_default_groups[]= { "maria_dump_log",0 };
static void get_options(int *argc,char * * *argv);
#ifndef DBUG_OFF
#if defined(__WIN__)
const char *default_dbug_option= "d:t:i:O,\\maria_dump_log.trace";
#else
const char *default_dbug_option= "d:t:i:o,/tmp/maria_dump_log.trace";
#endif
#endif
static ulonglong opt_offset;
static ulong opt_pages;
static const char *opt_file= NULL;
static File handler= -1;
8098
static my_bool opt_unit= 0;
8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122
static struct my_option my_long_options[] =
{
#ifdef IMPLTMENTED
  {"body", 'b',
   "Print chunk body dump",
   (uchar **) &opt_body, (uchar **) &opt_body, 0,
   GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
#endif
#ifndef DBUG_OFF
  {"debug", '#', "Output debug log. Often the argument is 'd:t:o,filename'.",
   0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
#endif
  {"file", 'f', "Path to file which will be read",
    (uchar**) &opt_file, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"help", '?', "Display this help and exit.",
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
  { "offset", 'o', "Start reading log from this offset",
    (uchar**) &opt_offset, (uchar**) &opt_offset,
    0, GET_ULL, REQUIRED_ARG, 0, 0, ~(longlong) 0, 0, 0, 0 },
  { "pages", 'n', "Number of pages to read",
    (uchar**) &opt_pages, (uchar**) &opt_pages, 0,
    GET_ULONG, REQUIRED_ARG, (long) ~(ulong) 0,
    (long) 1, (long) ~(ulong) 0, (long) 0,
    (long) 1, 0},
8123 8124 8125 8126
  {"unit-test", 'U',
   "Use unit test record table (for logs created by unittests",
   (uchar **) &opt_unit, (uchar **) &opt_unit, 0,
   GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199
  {"version", 'V', "Print version and exit.",
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
  { 0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
};


static void print_version(void)
{
  VOID(printf("%s Ver 1.0 for %s on %s\n",
              my_progname_short, SYSTEM_TYPE, MACHINE_TYPE));
  NETWARE_SET_SCREEN_MODE(1);
}


static void usage(void)
{
  print_version();
  puts("Copyright (C) 2008 MySQL AB");
  puts("This software comes with ABSOLUTELY NO WARRANTY. This is free software,");
  puts("and you are welcome to modify and redistribute it under the GPL license\n");

  puts("Dump content of maria log pages.");
  VOID(printf("\nUsage: %s -f file OPTIONS\n", my_progname_short));
  my_print_help(my_long_options);
  print_defaults("my", load_default_groups);
  my_print_variables(my_long_options);
}


static my_bool
get_one_option(int optid __attribute__((unused)),
               const struct my_option *opt __attribute__((unused)),
               char *argument __attribute__((unused)))
{
  switch (optid) {
  case '?':
    usage();
    exit(0);
  case 'V':
    print_version();
    exit(0);
#ifndef DBUG_OFF
  case '#':
    DBUG_SET_INITIAL(argument ? argument : default_dbug_option);
    break;
#endif
  }
  return 0;
}


static void get_options(int *argc,char ***argv)
{
  int ho_error;

  if ((ho_error=handle_options(argc, argv, my_long_options, get_one_option)))
    exit(ho_error);

  if (opt_file == NULL)
  {
    usage();
    exit(1);
  }
}


/**
  @brief Dump information about file header page.
*/

static void dump_header_page(uchar *buff)
{
  LOGHANDLER_FILE_INFO desc;
8200
  char strbuff[21];
8201 8202
  translog_interpret_file_header(&desc, buff);
  printf("  This can be header page:\n"
8203
         "    Timestamp: %s\n"
8204 8205 8206 8207
         "    Maria log version: %lu\n"
         "    Server version: %lu\n"
         "    Server id %lu\n"
         "    Page size %lu\n",
8208
         llstr(desc.timestamp, strbuff),
8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267
         desc.maria_version,
         desc.mysql_version,
         desc.server_id,
         desc.page_size);
  if (desc.page_size != TRANSLOG_PAGE_SIZE)
    printf("      WARNING: page size is not equal compiled in one %lu!!!\n",
           (ulong) TRANSLOG_PAGE_SIZE);
  printf("    File number %lu\n"
         "    Max lsn: (%lu,0x%lx)\n",
         desc.file_number,
         LSN_IN_PARTS(desc.max_lsn));
}

static const char *record_class_string[]=
{
  "LOGRECTYPE_NOT_ALLOWED",
  "LOGRECTYPE_VARIABLE_LENGTH",
  "LOGRECTYPE_PSEUDOFIXEDLENGTH",
  "LOGRECTYPE_FIXEDLENGTH"
};


/**
  @brief dump information about transaction log chunk

  @param buffer          reference to the whole page
  @param ptr             pointer to the chunk

  @reval # reference to the next chunk
  @retval NULL can't interpret data
*/

static uchar *dump_chunk(uchar *buffer, uchar *ptr)
{
  uint length;
  if (*ptr == TRANSLOG_FILLER)
  {
    printf("  Filler till the page end\n");
    for (; ptr < buffer + TRANSLOG_PAGE_SIZE; ptr++)
    {
      if (*ptr != TRANSLOG_FILLER)
      {
        printf("    WARNING: non filler character met before page end "
               "(page + 0x%04x: 0x%02x) (stop interpretation)!!!",
               (uint) (ptr - buffer), (uint) ptr[0]);
        return NULL;
      }
    }
    return ptr;
  }
  if (*ptr == 0 || *ptr == 0xFF)
  {
    printf("    WARNING: chunk can't start from 0x0 "
           "(stop interpretation)!!!\n");
    return NULL;
  }
  switch (ptr[0] & TRANSLOG_CHUNK_TYPE) {
  case TRANSLOG_CHUNK_LSN:
    printf("    LSN chunk type 0 (variable length)\n");
8268
    if (likely((ptr[0] & TRANSLOG_REC_TYPE) != TRANSLOG_CHUNK_0_CONT))
8269
    {
8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286
      printf("      Record type %u: %s  record class %s compressed LSNs: %u\n",
             ptr[0] & TRANSLOG_REC_TYPE,
             (log_record_type_descriptor[ptr[0] & TRANSLOG_REC_TYPE].name ?
              log_record_type_descriptor[ptr[0] & TRANSLOG_REC_TYPE].name :
              "NULL"),
             record_class_string[log_record_type_descriptor[ptr[0] &
                                                            TRANSLOG_REC_TYPE].
                                                            rclass],
             log_record_type_descriptor[ptr[0] & TRANSLOG_REC_TYPE].
             compressed_LSN);
      if (log_record_type_descriptor[ptr[0] & TRANSLOG_REC_TYPE].rclass !=
          LOGRECTYPE_VARIABLE_LENGTH)
      {
        printf("        WARNING: this record class here can't be used "
               "(stop interpretation)!!!\n");
        break;
      }
8287
    }
8288 8289
    else
      printf("      Continuation of previous chunk 0 header \n");
8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361
    printf("      Short transaction id: %u\n", (uint) uint2korr(ptr + 1));
    {
      uchar *hdr_ptr= ptr + 1 + 2; /* chunk type and short trid */
      uint16 chunk_len;
      printf ("      Record length: %lu\n",
              (ulong) translog_variable_record_1group_decode_len(&hdr_ptr));
      chunk_len= uint2korr(hdr_ptr);
      if (chunk_len == 0)
        printf ("      It is 1 group record (chunk length == 0)\n");
      else
      {
        uint16 groups, i;

        printf ("      Chunk length %u\n", (uint) chunk_len);
        groups= uint2korr(hdr_ptr + 2);
        hdr_ptr+= 4;
        printf ("      Number of groups left to the end %u:\n", (uint) groups);
        for(i= 0;
            i < groups && hdr_ptr < buffer + TRANSLOG_PAGE_SIZE;
            i++, hdr_ptr+= LSN_STORE_SIZE + 1)
        {
          TRANSLOG_ADDRESS gpr_addr= lsn_korr(hdr_ptr);
          uint pages= hdr_ptr[LSN_STORE_SIZE];
          printf ("        Group +#%u: (%lu,0x%lx)  pages: %u\n",
                  (uint) i, LSN_IN_PARTS(gpr_addr), pages);
        }
      }
    }
    break;
  case TRANSLOG_CHUNK_FIXED:
    printf("    LSN chunk type 1 (fixed size)\n");
    printf("      Record type %u: %s  record class %s compressed LSNs: %u\n",
           ptr[0] & TRANSLOG_REC_TYPE,
           (log_record_type_descriptor[ptr[0] & TRANSLOG_REC_TYPE].name ?
            log_record_type_descriptor[ptr[0] & TRANSLOG_REC_TYPE].name :
            "NULL"),
           record_class_string[log_record_type_descriptor[ptr[0] &
                                                          TRANSLOG_REC_TYPE].
                                                          rclass],
           log_record_type_descriptor[ptr[0] & TRANSLOG_REC_TYPE].
           compressed_LSN);
    if (log_record_type_descriptor[ptr[0] & TRANSLOG_REC_TYPE].rclass !=
        LOGRECTYPE_PSEUDOFIXEDLENGTH &&
        log_record_type_descriptor[ptr[0] & TRANSLOG_REC_TYPE].rclass !=
        LOGRECTYPE_FIXEDLENGTH)
    {
      printf("        WARNING: this record class here can't be used "
             "(stop interpretation)!!!\n");
    }
    printf("      Short transaction id: %u\n", (uint) uint2korr(ptr + 1));
    break;
  case TRANSLOG_CHUNK_NOHDR:
    printf("    No header chunk type 2(till the end of the page)\n");
    if (ptr[0] & TRANSLOG_REC_TYPE)
    {
      printf("      WARNING: chunk header content record type: 0x%02x "
             "(dtop interpretation)!!!",
             (uint) ptr[0]);
      return NULL;
    }
    break;
  case TRANSLOG_CHUNK_LNGTH:
    printf("    Chunk with length type 3\n");
    if (ptr[0] & TRANSLOG_REC_TYPE)
    {
      printf("      WARNING: chunk header content record type: 0x%02x "
             "(dtop interpretation)!!!",
             (uint) ptr[0]);
      return NULL;
    }
    break;
  }
8362 8363 8364 8365 8366
  {
    intptr offset= ptr - buffer;
    DBUG_ASSERT(offset >= 0 && offset <= UINT_MAX16);
    length= translog_get_total_chunk_length(buffer, (uint16)offset);
  }
8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459
  printf("      Length %u\n", length);
  ptr+= length;
  return ptr;
}


/**
  @brief Dump information about page with data.
*/

static void dump_datapage(uchar *buffer)
{
  uchar *ptr;
  ulong offset;
  uint32 page, file;
  uint header_len;
  printf("  Page: %ld  File number: %ld\n",
         (ulong) (page= uint3korr(buffer)),
         (ulong) (file= uint3korr(buffer + 3)));
  if (page == 0)
    printf("    WARNING: page == 0!!!\n");
  if (file == 0)
    printf("    WARNING: file == 0!!!\n");
  offset= page * TRANSLOG_PAGE_SIZE;
  printf("  Flags (0x%x):\n", (uint) buffer[TRANSLOG_PAGE_FLAGS]);
  if (buffer[TRANSLOG_PAGE_FLAGS])
  {
    if (buffer[TRANSLOG_PAGE_FLAGS] & TRANSLOG_PAGE_CRC)
      printf("    Page CRC\n");
    if (buffer[TRANSLOG_PAGE_FLAGS] & TRANSLOG_SECTOR_PROTECTION)
      printf("    Sector protection\n");
    if (buffer[TRANSLOG_PAGE_FLAGS] & TRANSLOG_RECORD_CRC)
      printf("    Record CRC (WARNING: not yet implemented!!!)\n");
    if (buffer[TRANSLOG_PAGE_FLAGS] & ~(TRANSLOG_PAGE_CRC |
                                        TRANSLOG_SECTOR_PROTECTION |
                                        TRANSLOG_RECORD_CRC))
    {
      printf("    WARNING: unknown flags (stop interpretation)!!!\n");
      return;
    }
  }
  else
    printf("    No flags\n");
  printf("  Page header length: %u\n",
         (header_len= page_overhead[buffer[TRANSLOG_PAGE_FLAGS]]));
  if (buffer[TRANSLOG_PAGE_FLAGS] & TRANSLOG_RECORD_CRC)
  {
    uint32 crc= uint4korr(buffer + TRANSLOG_PAGE_FLAGS + 1);
    uint32 ccrc;
    printf ("  Page CRC 0x%04lx\n", (ulong) crc);
    ccrc= translog_crc(buffer + header_len, TRANSLOG_PAGE_SIZE - header_len);
    if (crc != ccrc)
      printf("    WARNING: calculated CRC: 0x%04lx!!!\n", (ulong) ccrc);
  }
  if (buffer[TRANSLOG_PAGE_FLAGS] & TRANSLOG_SECTOR_PROTECTION)
  {
    TRANSLOG_FILE tfile;
    {
      uchar *table= buffer + header_len -
        TRANSLOG_PAGE_SIZE / DISK_DRIVE_SECTOR_SIZE;
      uint i;
      printf("    Sector protection current value: 0x%02x\n", (uint) table[0]);
      for (i= 1; i < TRANSLOG_PAGE_SIZE / DISK_DRIVE_SECTOR_SIZE; i++)
      {
         printf("    Sector protection in sector: 0x%02x  saved value 0x%02x\n",
                (uint)buffer[i * DISK_DRIVE_SECTOR_SIZE],
                (uint)table[i]);
      }
    }
    tfile.number= file;
    tfile.handler.file= handler;
    pagecache_file_init(tfile.handler, NULL, NULL, NULL, NULL, NULL);
    tfile.was_recovered= 0;
    tfile.is_sync= 1;
    if (translog_check_sector_protection(buffer, &tfile))
      printf("    WARNING: sector protection found problems!!!\n");
  }
  ptr= buffer + header_len;
  while (ptr && ptr < buffer + TRANSLOG_PAGE_SIZE)
  {
    printf("  Chunk (%lu,0x%lx):\n",
           (ulong)file, (ulong) offset + (ptr - buffer));
    ptr= dump_chunk(buffer, ptr);
  }
}


/**
  @brief Dump information about page.
*/

static void dump_page(uchar *buffer)
{
8460
  printf("Page by offset %llu (0x%llx)\n", opt_offset, opt_offset);
8461
  if (strncmp((char*)maria_trans_file_magic, (char*)buffer,
8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483
              sizeof(maria_trans_file_magic)) == 0)
  {
    dump_header_page(buffer);
  }
  dump_datapage(buffer);
}


/**
  @brief maria_dump_log main function.
*/

int main(int argc, char **argv)
{
  char **default_argv;
  uchar buffer[TRANSLOG_PAGE_SIZE];
  MY_INIT(argv[0]);

  load_defaults("my", load_default_groups, &argc, &argv);
  default_argv= argv;
  get_options(&argc, &argv);

8484 8485 8486 8487 8488 8489
  if (opt_unit)
    translog_example_table_init();
  else
    translog_table_init();
  translog_fill_overhead_table();

unknown's avatar
unknown committed
8490
  maria_data_root= (char *)".";
8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509

  if ((handler= my_open(opt_file, O_RDONLY, MYF(MY_WME))) < 0)
  {
    fprintf(stderr, "Can't open file: '%s'  errno: %d\n",
            opt_file, my_errno);
    goto err;
  }
  if (my_seek(handler, opt_offset, SEEK_SET, MYF(MY_WME)) !=
      opt_offset)
  {
     fprintf(stderr, "Can't set position %lld  file: '%s'  errno: %d\n",
             opt_offset, opt_file, my_errno);
     goto err;
  }
  for (;
       opt_pages;
       opt_offset+= TRANSLOG_PAGE_SIZE, opt_pages--)
  {
    if (my_pread(handler, buffer, TRANSLOG_PAGE_SIZE, opt_offset,
8510
                 MYF(MY_NABP)))
8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533
    {
      if (my_errno == HA_ERR_FILE_TOO_SHORT)
        goto end;
      fprintf(stderr, "Can't read page at position %lld  file: '%s'  "
              "errno: %d\n", opt_offset, opt_file, my_errno);
      goto err;
    }
    dump_page(buffer);
  }

end:
  my_close(handler, MYF(0));
  free_defaults(default_argv);
  exit(0);
  return 0;				/* No compiler warning */

err:
  my_close(handler, MYF(0));
  fprintf(stderr, "%s: FAILED\n", my_progname_short);
  free_defaults(default_argv);
  exit(1);
}
#endif