DbtupExecQuery.cpp 93.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* Copyright (C) 2003 MySQL AB

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

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


#define DBTUP_C
19
#include <Dblqh.hpp>
20 21 22 23 24 25 26 27 28 29
#include "Dbtup.hpp"
#include <RefConvert.hpp>
#include <ndb_limits.h>
#include <pc.hpp>
#include <AttributeDescriptor.hpp>
#include "AttributeOffset.hpp"
#include <AttributeHeader.hpp>
#include <Interpreter.hpp>
#include <signaldata/TupCommit.hpp>
#include <signaldata/TupKey.hpp>
30
#include <signaldata/AttrInfo.hpp>
31 32 33 34 35
#include <NdbSqlUtil.hpp>

/* ----------------------------------------------------------------- */
/* -----------       INIT_STORED_OPERATIONREC         -------------- */
/* ----------------------------------------------------------------- */
36
int Dbtup::initStoredOperationrec(Operationrec* regOperPtr,
37
                                  KeyReqStruct* req_struct,
38 39 40 41 42 43 44 45
                                  Uint32 storedId) 
{
  jam();
  StoredProcPtr storedPtr;
  c_storedProcPool.getPtr(storedPtr, storedId);
  if (storedPtr.i != RNIL) {
    if (storedPtr.p->storedCode == ZSCAN_PROCEDURE) {
      storedPtr.p->storedCounter++;
46 47 48 49
      regOperPtr->firstAttrinbufrec= storedPtr.p->storedLinkFirst;
      regOperPtr->lastAttrinbufrec= storedPtr.p->storedLinkLast;
      regOperPtr->currentAttrinbufLen= storedPtr.p->storedProcLength;
      req_struct->attrinfo_len= storedPtr.p->storedProcLength;
50
      return ZOK;
51 52 53
    }
  }
  terrorCode= ZSTORED_PROC_ID_ERROR;
54
  return terrorCode;
55
}
56

57
void Dbtup::copyAttrinfo(Operationrec * regOperPtr,
58 59 60
                         Uint32* inBuffer)
{
  AttrbufrecPtr copyAttrBufPtr;
61
  Uint32 RnoOfAttrBufrec= cnoOfAttrbufrec;
62
  int RbufLen;
63
  Uint32 RinBufIndex= 0;
64 65
  Uint32 Rnext;
  Uint32 Rfirst;
66 67
  Uint32 TstoredProcedure= (regOperPtr->storedProcedureId != ZNIL);
  Uint32 RnoFree= cnoFreeAttrbufrec;
68 69 70 71 72 73 74

//-------------------------------------------------------------------------
// As a prelude to the execution of the TUPKEYREQ we will copy the program
// into the inBuffer to enable easy execution without any complex jumping
// between the buffers. In particular this will make the interpreter less
// complex. Hopefully it does also improve performance.
//-------------------------------------------------------------------------
75
  copyAttrBufPtr.i= regOperPtr->firstAttrinbufrec;
76 77 78 79
  while (copyAttrBufPtr.i != RNIL) {
    jam();
    ndbrequire(copyAttrBufPtr.i < RnoOfAttrBufrec);
    ptrAss(copyAttrBufPtr, attrbufrec);
80 81 82
    RbufLen= copyAttrBufPtr.p->attrbuf[ZBUF_DATA_LEN];
    Rnext= copyAttrBufPtr.p->attrbuf[ZBUF_NEXT];
    Rfirst= cfirstfreeAttrbufrec;
83 84 85 86 87
    MEMCOPY_NO_WORDS(&inBuffer[RinBufIndex],
                     &copyAttrBufPtr.p->attrbuf[0],
                     RbufLen);
    RinBufIndex += RbufLen;
    if (!TstoredProcedure) {
88 89
      copyAttrBufPtr.p->attrbuf[ZBUF_NEXT]= Rfirst;
      cfirstfreeAttrbufrec= copyAttrBufPtr.i;
90
      RnoFree++;
91 92 93 94
    }
    copyAttrBufPtr.i= Rnext;
  }
  cnoFreeAttrbufrec= RnoFree;
95 96 97 98 99 100
  if (TstoredProcedure) {
    jam();
    StoredProcPtr storedPtr;
    c_storedProcPool.getPtr(storedPtr, (Uint32)regOperPtr->storedProcedureId);
    ndbrequire(storedPtr.p->storedCode == ZSCAN_PROCEDURE);
    storedPtr.p->storedCounter--;
101
  }
102
  // Release the ATTRINFO buffers
103 104 105 106
  regOperPtr->storedProcedureId= RNIL;
  regOperPtr->firstAttrinbufrec= RNIL;
  regOperPtr->lastAttrinbufrec= RNIL;
}
107 108

void Dbtup::handleATTRINFOforTUPKEYREQ(Signal* signal,
109 110
                                       const Uint32 *data,
				       Uint32 len,
111
                                       Operationrec * regOperPtr) 
112
{
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
  while(len)
  {
    Uint32 length = len > AttrInfo::DataLength ? AttrInfo::DataLength : len;

    AttrbufrecPtr TAttrinbufptr;
    TAttrinbufptr.i= cfirstfreeAttrbufrec;
    if ((cfirstfreeAttrbufrec < cnoOfAttrbufrec) &&
	(cnoFreeAttrbufrec > MIN_ATTRBUF)) {
      ptrAss(TAttrinbufptr, attrbufrec);
      MEMCOPY_NO_WORDS(&TAttrinbufptr.p->attrbuf[0],
		       data,
		       length);
      Uint32 RnoFree= cnoFreeAttrbufrec;
      Uint32 Rnext= TAttrinbufptr.p->attrbuf[ZBUF_NEXT];
      TAttrinbufptr.p->attrbuf[ZBUF_DATA_LEN]= length;
      TAttrinbufptr.p->attrbuf[ZBUF_NEXT]= RNIL;
      
      AttrbufrecPtr locAttrinbufptr;
      Uint32 RnewLen= regOperPtr->currentAttrinbufLen;
      
      locAttrinbufptr.i= regOperPtr->lastAttrinbufrec;
      cfirstfreeAttrbufrec= Rnext;
      cnoFreeAttrbufrec= RnoFree - 1;
      RnewLen += length;
      regOperPtr->lastAttrinbufrec= TAttrinbufptr.i;
      regOperPtr->currentAttrinbufLen= RnewLen;
      if (locAttrinbufptr.i == RNIL) {
	regOperPtr->firstAttrinbufrec= TAttrinbufptr.i;
      } else {
	jam();
	ptrCheckGuard(locAttrinbufptr, cnoOfAttrbufrec, attrbufrec);
	locAttrinbufptr.p->attrbuf[ZBUF_NEXT]= TAttrinbufptr.i;
      }
      if (RnewLen < ZATTR_BUFFER_SIZE) {
      } else {
	jam();
	set_trans_state(regOperPtr, TRANS_TOO_MUCH_AI);
	return;
      }
    } else if (cnoFreeAttrbufrec <= MIN_ATTRBUF) {
153
      jam();
154
      set_trans_state(regOperPtr, TRANS_ERROR_WAIT_TUPKEYREQ);
155
    } else {
156 157 158 159 160 161 162
      ndbrequire(false);
    }
    
    len -= length;
    data += length;    
  }
}
163 164 165

void Dbtup::execATTRINFO(Signal* signal) 
{
166 167
  Uint32 Rsig0= signal->theData[0];
  Uint32 Rlen= signal->length();
168 169
  jamEntry();

170 171 172 173 174 175 176 177 178 179 180 181 182
  receive_attrinfo(signal, Rsig0, signal->theData+3, Rlen-3);
}
 
void
Dbtup::receive_attrinfo(Signal* signal, Uint32 op, 
			const Uint32* data, Uint32 Rlen)
{ 
  OperationrecPtr regOpPtr;
  regOpPtr.i= op;
  c_operation_pool.getPtr(regOpPtr, op);
  TransState trans_state= get_trans_state(regOpPtr.p);
  if (trans_state == TRANS_IDLE) {
    handleATTRINFOforTUPKEYREQ(signal, data, Rlen, regOpPtr.p);
183
    return;
184 185
  } else if (trans_state == TRANS_WAIT_STORED_PROCEDURE_ATTR_INFO) {
    storedProcedureAttrInfo(signal, regOpPtr.p, data, Rlen, false);
186
    return;
187 188 189
  }
  switch (trans_state) {
  case TRANS_ERROR_WAIT_STORED_PROCREQ:
190
    jam();
191
  case TRANS_TOO_MUCH_AI:
192
    jam();
193
  case TRANS_ERROR_WAIT_TUPKEYREQ:
194 195
    jam();
    return;	/* IGNORE ATTRINFO IN THOSE STATES, WAITING FOR ABORT SIGNAL */
196
  case TRANS_DISCONNECTED:
197
    jam();
198
  case TRANS_STARTED:
199 200 201
    jam();
  default:
    ndbrequire(false);
202 203
  }
}
204 205

void
206
Dbtup::setChecksum(Tuple_header* tuple_ptr,
207
                   Tablerec* regTabPtr)
208
{
209 210 211
  tuple_ptr->m_checksum= 0;
  tuple_ptr->m_checksum= calculateChecksum(tuple_ptr, regTabPtr);
}
212 213

Uint32
214
Dbtup::calculateChecksum(Tuple_header* tuple_ptr,
215
                         Tablerec* regTabPtr)
216
{
217 218 219 220 221
  Uint32 checksum;
  Uint32 i, rec_size, *tuple_header;
  rec_size= regTabPtr->m_offsets[MM].m_fix_header_size;
  tuple_header= tuple_ptr->m_data;
  checksum= 0;
222
  // includes tupVersion
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
  //printf("%p - ", tuple_ptr);
  
  if (regTabPtr->m_attributes[MM].m_no_of_varsize)
    rec_size += Tuple_header::HeaderSize;
  
  for (i= 0; i < rec_size-2; i++) {
    checksum ^= tuple_header[i];
    //printf("%.8x ", tuple_header[i]);
  }
  
  //printf("-> %.8x\n", checksum);

#if 0
  if (var_sized) {
    /*
    if (! req_struct->fix_var_together) {
      jam();
      checksum ^= tuple_header[rec_size];
    }
    */
    jam();
    var_data_part= req_struct->var_data_start;
    vsize_words= calculate_total_var_size(req_struct->var_len_array,
                                          regTabPtr->no_var_attr);
    ndbassert(req_struct->var_data_end >= &var_data_part[vsize_words]);
    for (i= 0; i < vsize_words; i++) {
      checksum ^= var_data_part[i];
    }
  }
#endif
253
  return checksum;
254
}
255 256 257 258

/* ----------------------------------------------------------------- */
/* -----------       INSERT_ACTIVE_OP_LIST            -------------- */
/* ----------------------------------------------------------------- */
259 260 261
bool 
Dbtup::insertActiveOpList(OperationrecPtr regOperPtr,
			  KeyReqStruct* req_struct)
262
{
263 264 265 266 267 268 269 270 271 272
  OperationrecPtr prevOpPtr;
  ndbrequire(!regOperPtr.p->op_struct.in_active_list);
  regOperPtr.p->op_struct.in_active_list= true;
  req_struct->prevOpPtr.i= 
    prevOpPtr.i= req_struct->m_tuple_ptr->m_operation_ptr_i;
  regOperPtr.p->prevActiveOp= prevOpPtr.i;
  regOperPtr.p->nextActiveOp= RNIL;
  regOperPtr.p->m_undo_buffer_space= 0;
  req_struct->m_tuple_ptr->m_operation_ptr_i= regOperPtr.i;
  if (prevOpPtr.i == RNIL) {
273 274 275
    set_change_mask_state(regOperPtr.p, USE_SAVED_CHANGE_MASK);
    regOperPtr.p->saved_change_mask[0] = 0;
    regOperPtr.p->saved_change_mask[1] = 0;
276
    return true;
277
  } else {
278 279 280 281 282 283 284 285
    req_struct->prevOpPtr.p= prevOpPtr.p= c_operation_pool.getPtr(prevOpPtr.i);
    prevOpPtr.p->nextActiveOp= regOperPtr.i;

    regOperPtr.p->op_struct.m_wait_log_buffer= 
      prevOpPtr.p->op_struct.m_wait_log_buffer;
    regOperPtr.p->op_struct.m_load_diskpage_on_commit= 
      prevOpPtr.p->op_struct.m_load_diskpage_on_commit;
    regOperPtr.p->m_undo_buffer_space= prevOpPtr.p->m_undo_buffer_space;
286 287 288 289
    // start with prev mask (matters only for UPD o UPD)
    set_change_mask_state(regOperPtr.p, get_change_mask_state(prevOpPtr.p));
    regOperPtr.p->saved_change_mask[0] = prevOpPtr.p->saved_change_mask[0];
    regOperPtr.p->saved_change_mask[1] = prevOpPtr.p->saved_change_mask[1];
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

    prevOpPtr.p->op_struct.m_wait_log_buffer= 0;
    prevOpPtr.p->op_struct.m_load_diskpage_on_commit= 0;

    if(prevOpPtr.p->op_struct.tuple_state == TUPLE_PREPARED)
    {
      Uint32 op= regOperPtr.p->op_struct.op_type;
      Uint32 prevOp= prevOpPtr.p->op_struct.op_type;
      if (prevOp == ZDELETE)
      {
	if(op == ZINSERT)
	{
	  // mark both
	  prevOpPtr.p->op_struct.delete_insert_flag= true;
	  regOperPtr.p->op_struct.delete_insert_flag= true;
	  return true;
	} else {
	  terrorCode= ZTUPLE_DELETED_ERROR;
	  return false;
	}
      } 
      else if(op == ZINSERT && prevOp != ZDELETE)
      {
	terrorCode= ZINSERT_ERROR;
	return false;
      }
      return true;
317
    }
318 319 320 321 322 323 324
    else
    {
      terrorCode= ZMUST_BE_ABORTED_ERROR;
      return false;
    }
  }
}
325 326

bool
327
Dbtup::setup_read(KeyReqStruct *req_struct,
328 329 330
		  Operationrec* regOperPtr,
		  Fragrecord* regFragPtr,
		  Tablerec* regTabPtr,
331
		  bool disk)
332
{
333 334 335 336 337 338
  OperationrecPtr currOpPtr;
  currOpPtr.i= req_struct->m_tuple_ptr->m_operation_ptr_i;
  if (currOpPtr.i == RNIL)
  {
    if (regTabPtr->need_expand(disk))
      prepare_read(req_struct, regTabPtr, disk);
339 340 341
    return true;
  }

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
  do {
    Uint32 savepointId= regOperPtr->savepointId;
    bool dirty= req_struct->dirty_op;
    
    c_operation_pool.getPtr(currOpPtr);
    bool sameTrans= c_lqh->is_same_trans(currOpPtr.p->userpointer,
					 req_struct->trans_id1,
					 req_struct->trans_id2);
    /**
     * Read committed in same trans reads latest copy
     */
    if(dirty && !sameTrans)
    {
      savepointId= 0;
    }
    else if(sameTrans)
    {
      // Use savepoint even in read committed mode
      dirty= false;
361
    }
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384

    OperationrecPtr prevOpPtr = currOpPtr;  
    bool found= false;
    while(true) 
    {
      if (savepointId > currOpPtr.p->savepointId) {
	found= true;
	break;
      }
      if (currOpPtr.p->is_first_operation()){
	break;
      }
      prevOpPtr= currOpPtr;
      currOpPtr.i = currOpPtr.p->prevActiveOp;
      c_operation_pool.getPtr(currOpPtr);
    }
    
    Uint32 currOp= currOpPtr.p->op_struct.op_type;
    
    if((found && currOp == ZDELETE) || 
       ((dirty || !found) && currOp == ZINSERT))
    {
      terrorCode= ZTUPLE_DELETED_ERROR;
385 386
      break;
    }
387 388 389 390 391 392 393 394 395 396 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 425 426 427 428 429 430 431 432 433 434
    
    if(dirty || !found)
    {
      
    }
    else
    {
      req_struct->m_tuple_ptr= (Tuple_header*)
	c_undo_buffer.get_ptr(&currOpPtr.p->m_copy_tuple_location);
    }      

    if (regTabPtr->need_expand(disk))
      prepare_read(req_struct, regTabPtr, disk);
    
#if 0
    ndbout_c("reading copy");
    Uint32 *var_ptr = fixed_ptr+regTabPtr->var_offset;
    req_struct->m_tuple_ptr= fixed_ptr;
    req_struct->fix_var_together= true;  
    req_struct->var_len_array= (Uint16*)var_ptr;
    req_struct->var_data_start= var_ptr+regTabPtr->var_array_wsize;
    Uint32 var_sz32= init_var_pos_array((Uint16*)var_ptr,
					req_struct->var_pos_array,
					regTabPtr->no_var_attr);
    req_struct->var_data_end= var_ptr+regTabPtr->var_array_wsize + var_sz32;
#endif
    return true;
  } while(0);
  
  return false;
}

int
Dbtup::load_diskpage(Signal* signal, 
		     Uint32 opRec, Uint32 fragPtrI, 
		     Uint32 local_key, Uint32 flags)
{
  c_operation_pool.getPtr(operPtr, opRec);
  fragptr.i= fragPtrI;
  ptrCheckGuard(fragptr, cnoOfFragrec, fragrecord);
  
  Operationrec *  regOperPtr= operPtr.p;
  Fragrecord * regFragPtr= fragptr.p;
  
  tabptr.i = regFragPtr->fragTableId;
  ptrCheckGuard(tabptr, cnoOfTablerec, tablerec);
  Tablerec* regTabPtr = tabptr.p;
  
435
  if(local_key == ~(Uint32)0)
436
  {
437
    jam();
438 439 440
    regOperPtr->op_struct.m_wait_log_buffer= 1;
    regOperPtr->op_struct.m_load_diskpage_on_commit= 1;
    return 1;
441
  }
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
  
  jam();
  Uint32 page_idx= local_key & MAX_TUPLES_PER_PAGE;
  Uint32 frag_page_id= local_key >> MAX_TUPLES_BITS;
  regOperPtr->m_tuple_location.m_page_no= getRealpid(regFragPtr,
						     frag_page_id);
  regOperPtr->m_tuple_location.m_page_idx= page_idx;
  
  PagePtr page_ptr;
  Uint32* tmp= get_ptr(&page_ptr, &regOperPtr->m_tuple_location, regTabPtr);
  Tuple_header* ptr= (Tuple_header*)tmp;
  
  int res= 1;
  Uint32 opPtr= ptr->m_operation_ptr_i;
  if(ptr->m_header_bits & Tuple_header::DISK_PART)
  {
    Page_cache_client::Request req;
    memcpy(&req.m_page, ptr->get_disk_ref_ptr(regTabPtr), sizeof(Local_key));
    req.m_callback.m_callbackData= opRec;
    req.m_callback.m_callbackFunction= 
      safe_cast(&Dbtup::disk_page_load_callback);
463

464
#ifdef ERROR_INSERT
465 466 467 468 469 470
    if (ERROR_INSERTED(4022))
    {
      flags |= Page_cache_client::DELAY_REQ;
      req.m_delay_until_time = NdbTick_CurrentMillisecond()+(Uint64)3000;
    }
#endif
471 472 473 474 475 476 477 478 479 480
    
    if((res= m_pgman.get_page(signal, req, flags)) > 0)
    {
      //ndbout_c("in cache");
      // In cache
    } 
    else if(res == 0)
    {
      //ndbout_c("waiting for callback");
      // set state
481
    }
482 483 484
    else 
    {
      // Error
485
    }
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
  }

  switch(flags & 7)
  {
  case ZREAD:
  case ZREAD_EX:
    break;
  case ZDELETE:
  case ZUPDATE:
  case ZINSERT:
  case ZWRITE:
    regOperPtr->op_struct.m_wait_log_buffer= 1;
    regOperPtr->op_struct.m_load_diskpage_on_commit= 1;
  }
  return res;
}

void
Dbtup::disk_page_load_callback(Signal* signal, Uint32 opRec, Uint32 page_id)
{
  c_operation_pool.getPtr(operPtr, opRec);
  c_lqh->acckeyconf_load_diskpage_callback(signal, 
					   operPtr.p->userpointer, page_id);
}

int
Dbtup::load_diskpage_scan(Signal* signal, 
			  Uint32 opRec, Uint32 fragPtrI, 
			  Uint32 local_key, Uint32 flags)
{
  c_operation_pool.getPtr(operPtr, opRec);
  fragptr.i= fragPtrI;
  ptrCheckGuard(fragptr, cnoOfFragrec, fragrecord);
  
  Operationrec *  regOperPtr= operPtr.p;
  Fragrecord * regFragPtr= fragptr.p;
  
  tabptr.i = regFragPtr->fragTableId;
  ptrCheckGuard(tabptr, cnoOfTablerec, tablerec);
  Tablerec* regTabPtr = tabptr.p;
  
  jam();
  Uint32 page_idx= local_key & MAX_TUPLES_PER_PAGE;
  Uint32 frag_page_id= local_key >> MAX_TUPLES_BITS;
  regOperPtr->m_tuple_location.m_page_no= getRealpid(regFragPtr,
						     frag_page_id);
  regOperPtr->m_tuple_location.m_page_idx= page_idx;
  regOperPtr->op_struct.m_load_diskpage_on_commit= 0;
  
  PagePtr page_ptr;
  Uint32* tmp= get_ptr(&page_ptr, &regOperPtr->m_tuple_location, regTabPtr);
  Tuple_header* ptr= (Tuple_header*)tmp;
  
  int res= 1;
  Uint32 opPtr= ptr->m_operation_ptr_i;
  if(ptr->m_header_bits & Tuple_header::DISK_PART)
  {
    Page_cache_client::Request req;
    memcpy(&req.m_page, ptr->get_disk_ref_ptr(regTabPtr), sizeof(Local_key));
    req.m_callback.m_callbackData= opRec;
    req.m_callback.m_callbackFunction= 
      safe_cast(&Dbtup::disk_page_load_scan_callback);
    
    if((res= m_pgman.get_page(signal, req, flags)) > 0)
    {
      // ndbout_c("in cache");
      // In cache
    } 
    else if(res == 0)
    {
      //ndbout_c("waiting for callback");
      // set state
558
    }
559 560 561
    else 
    {
      // Error
562 563
    }
  }
564
  return res;
565 566
}

567 568 569
void
Dbtup::disk_page_load_scan_callback(Signal* signal, 
				    Uint32 opRec, Uint32 page_id)
570
{
571 572 573 574
  c_operation_pool.getPtr(operPtr, opRec);
  c_lqh->next_scanconf_load_diskpage_callback(signal, 
					      operPtr.p->userpointer, page_id);
}
575 576 577

void Dbtup::execTUPKEYREQ(Signal* signal) 
{
578
   TupKeyReq * tupKeyReq= (TupKeyReq *)signal->getDataPtr();
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
   KeyReqStruct req_struct;
   Uint32 sig1, sig2, sig3, sig4;

   Uint32 RoperPtr= tupKeyReq->connectPtr;
   Uint32 Rfragptr= tupKeyReq->fragPtr;

   Uint32 RnoOfFragrec= cnoOfFragrec;
   Uint32 RnoOfTablerec= cnoOfTablerec;

   jamEntry();
   fragptr.i= Rfragptr;

   ndbrequire(Rfragptr < RnoOfFragrec);

   c_operation_pool.getPtr(operPtr, RoperPtr);
   ptrAss(fragptr, fragrecord);

   Uint32 TrequestInfo= tupKeyReq->request;

   Operationrec *  regOperPtr= operPtr.p;
   Fragrecord * regFragPtr= fragptr.p;

   tabptr.i = regFragPtr->fragTableId;
   ptrCheckGuard(tabptr, RnoOfTablerec, tablerec);
   Tablerec* regTabPtr = tabptr.p;

   req_struct.signal= signal;
   req_struct.dirty_op= TrequestInfo & 1;
   req_struct.interpreted_exec= (TrequestInfo >> 10) & 1;
   req_struct.no_fired_triggers= 0;
   req_struct.read_length= 0;
   req_struct.max_attr_id_updated= 0;
   req_struct.no_changed_attrs= 0;
   req_struct.last_row= false;
   req_struct.changeMask.clear();

   if (unlikely(get_trans_state(regOperPtr) != TRANS_IDLE))
   {
     TUPKEY_abort(signal, 39);
     return;
   }

 /* ----------------------------------------------------------------- */
 // Operation is ZREAD when we arrive here so no need to worry about the
 // abort process.
 /* ----------------------------------------------------------------- */
 /* -----------    INITIATE THE OPERATION RECORD       -------------- */
 /* ----------------------------------------------------------------- */
   Uint32 Rstoredid= tupKeyReq->storedProcedure;

   regOperPtr->fragmentPtr= Rfragptr;
   regOperPtr->op_struct.op_type= (TrequestInfo >> 6) & 0xf;
   regOperPtr->op_struct.delete_insert_flag = false;
   regOperPtr->storedProcedureId= Rstoredid;

   regOperPtr->m_copy_tuple_location.setNull();
   regOperPtr->tupVersion= ZNIL;

   sig1= tupKeyReq->savePointId;
   sig2= tupKeyReq->primaryReplica;
   sig3= tupKeyReq->keyRef2;
   
   regOperPtr->savepointId= sig1;
   regOperPtr->op_struct.primary_replica= sig2;
643
   Uint32 pageidx = regOperPtr->m_tuple_location.m_page_idx= sig3;
644 645 646 647 648 649 650 651 652

   sig1= tupKeyReq->opRef;
   sig2= tupKeyReq->tcOpIndex;
   sig3= tupKeyReq->coordinatorTC;
   sig4= tupKeyReq->keyRef1;

   req_struct.tc_operation_ptr= sig1;
   req_struct.TC_index= sig2;
   req_struct.TC_ref= sig3;
653
   Uint32 pageid = req_struct.frag_page_id= sig4;
654 655
   req_struct.m_use_rowid = (TrequestInfo >> 11) & 1;

656 657 658 659 660 661 662 663 664 665 666 667 668 669
   sig1= tupKeyReq->attrBufLen;
   sig2= tupKeyReq->applRef;
   sig3= tupKeyReq->transId1;
   sig4= tupKeyReq->transId2;

   Uint32 disk_page= tupKeyReq->disk_page;
   
   req_struct.log_size= sig1;
   req_struct.attrinfo_len= sig1;
   req_struct.rec_blockref= sig2;
   req_struct.trans_id1= sig3;
   req_struct.trans_id2= sig4;
   req_struct.m_disk_page_ptr.i= disk_page;

670 671 672 673 674 675
   sig1 = tupKeyReq->m_row_id_page_no;
   sig2 = tupKeyReq->m_row_id_page_idx;

   req_struct.m_row_id.m_page_no = sig1;
   req_struct.m_row_id.m_page_idx = sig2;
   
676 677 678 679 680 681 682 683 684 685
   Uint32 Roptype = regOperPtr->op_struct.op_type;

   if (Rstoredid != ZNIL) {
     ndbrequire(initStoredOperationrec(regOperPtr,
				       &req_struct,
				       Rstoredid) == ZOK);
   }

   copyAttrinfo(regOperPtr, &cinBuffer[0]);
   
686 687
   Uint32 localkey = (pageid << MAX_TUPLES_BITS) + pageidx;
   if(Roptype == ZINSERT && localkey == ~0)
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
   {
     // No tuple allocatated yet
     goto do_insert;
   }

   /**
    * Get pointer to tuple
    */
   regOperPtr->m_tuple_location.m_page_no= getRealpid(regFragPtr, 
						      req_struct.frag_page_id);
   
   setup_fixed_part(&req_struct, regOperPtr, regTabPtr);
   
   /**
    * Check operation
    */
   if (Roptype == ZREAD) {
     jam();
     
     if (setup_read(&req_struct, regOperPtr, regFragPtr, regTabPtr, 
		    disk_page != RNIL))
     {
       if(handleReadReq(signal, regOperPtr, regTabPtr, &req_struct) != -1) 
       {
	 req_struct.log_size= 0;
	 sendTUPKEYCONF(signal, &req_struct, regOperPtr);
	 /* ---------------------------------------------------------------- */
	 // Read Operations need not to be taken out of any lists. 
	 // We also do not need to wait for commit since there is no changes 
	 // to commit. Thus we
	 // prepare the operation record already now for the next operation.
	 // Write operations have set the state to STARTED above indicating 
	 // that they are waiting for the Commit or Abort decision.
	 /* ---------------------------------------------------------------- */
	 set_trans_state(regOperPtr, TRANS_IDLE);
	 regOperPtr->currentAttrinbufLen= 0;
       }
       return;
     }
     tupkeyErrorLab(signal);
     return;
   }
   
   if(insertActiveOpList(operPtr, &req_struct))
   {
     if(Roptype == ZINSERT)
     {
       jam();
   do_insert:
       if (handleInsertReq(signal, operPtr,
			   fragptr, regTabPtr, &req_struct) == -1) 
       {
	 return;
       }
       if (!regTabPtr->tuxCustomTriggers.isEmpty()) 
       {
	 jam();
	 if (executeTuxInsertTriggers(signal,
				      regOperPtr,
				      regFragPtr,
				      regTabPtr) != 0) {
	   jam();
750
           /*
751 752 753 754 755 756 757 758 759 760
            * TUP insert succeeded but add of TUX entries failed.  All
            * TUX changes have been rolled back at this point.
            *
            * We will abort via tupkeyErrorLab() as usual.  This routine
            * however resets the operation to ZREAD.  The TUP_ABORTREQ
            * arriving later cannot then undo the insert.
            *
            * Therefore we call TUP_ABORTREQ already now.  Diskdata etc
            * should be in memory and timeslicing cannot occur.  We must
            * skip TUX abort triggers since TUX is already aborted.
761 762
            */
           signal->theData[0] = operPtr.i;
763
           do_tup_abortreq(signal, ZSKIP_TUX_TRIGGERS);
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
	   tupkeyErrorLab(signal);
	   return;
	 }
       }
       checkImmediateTriggersAfterInsert(&req_struct,
					 regOperPtr,
					 regTabPtr);
       set_change_mask_state(regOperPtr, SET_ALL_MASK);
       sendTUPKEYCONF(signal, &req_struct, regOperPtr);
       return;
     }

     if (Roptype == ZUPDATE) {
       jam();
       if (handleUpdateReq(signal, regOperPtr,
			   regFragPtr, regTabPtr, &req_struct, disk_page != RNIL) == -1) {
	 return;
       }
       // If update operation is done on primary, 
       // check any after op triggers
       terrorCode= 0;
       if (!regTabPtr->tuxCustomTriggers.isEmpty()) {
	 jam();
	 if (executeTuxUpdateTriggers(signal,
				      regOperPtr,
				      regFragPtr,
				      regTabPtr) != 0) {
	   jam();
792
           /*
793
            * See insert case.
794 795
            */
           signal->theData[0] = operPtr.i;
796
           do_tup_abortreq(signal, ZSKIP_TUX_TRIGGERS);
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
	   tupkeyErrorLab(signal);
	   return;
	 }
       }
       checkImmediateTriggersAfterUpdate(&req_struct,
					 regOperPtr,
					 regTabPtr);
       // XXX use terrorCode for now since all methods are void
       if (terrorCode != 0) 
       {
	 tupkeyErrorLab(signal);
	 return;
       }
       update_change_mask_info(&req_struct, regOperPtr);
       sendTUPKEYCONF(signal, &req_struct, regOperPtr);
       return;
     } 
     else if(Roptype == ZDELETE)
     {
       jam();
       if (handleDeleteReq(signal, regOperPtr,
			   regFragPtr, regTabPtr, &req_struct) == -1) {
	 return;
       }
       /*
	* TUX doesn't need to check for triggers at delete since entries in
	* the index are kept until commit time.
	*/

       /*
	* Secondary index triggers fire on the primary after a delete.
	*/
       checkImmediateTriggersAfterDelete(&req_struct,
					 regOperPtr, 
					 regTabPtr);
       set_change_mask_state(regOperPtr, DELETE_CHANGES);
       req_struct.log_size= 0;
       sendTUPKEYCONF(signal, &req_struct, regOperPtr);
       return;
     }
     else
     {
       ndbrequire(false); // Invalid op type
     }
   }

   tupkeyErrorLab(signal);
 }
845

846 847
void
Dbtup::setup_fixed_part(KeyReqStruct* req_struct,
848 849
			Operationrec* regOperPtr,
			Tablerec* regTabPtr)
850 851 852
{
  PagePtr page_ptr;
  Uint32* ptr= get_ptr(&page_ptr, &regOperPtr->m_tuple_location, regTabPtr);
853 854 855 856
  req_struct->m_page_ptr = page_ptr;
  req_struct->m_tuple_ptr = (Tuple_header*)ptr;
  
  ndbassert(regOperPtr->op_struct.op_type == ZINSERT || (! (req_struct->m_tuple_ptr->m_header_bits & Tuple_header::FREE)));
857
  
858 859 860 861 862 863 864 865 866
  req_struct->check_offset[MM]= regTabPtr->get_check_offset(MM);
  req_struct->check_offset[DD]= regTabPtr->get_check_offset(DD);
  
  Uint32 num_attr= regTabPtr->m_no_of_attributes;
  Uint32 descr_start= regTabPtr->tabDescriptor;
  TableDescriptor *tab_descr= &tableDescriptor[descr_start];
  ndbrequire(descr_start + (num_attr << ZAD_LOG_SIZE) <= cnoOfTabDescrRec);
  req_struct->attr_descr= tab_descr; 
}
867

868 869 870 871 872
 /* ---------------------------------------------------------------- */
 /* ------------------------ CONFIRM REQUEST ----------------------- */
 /* ---------------------------------------------------------------- */
 void Dbtup::sendTUPKEYCONF(Signal* signal,
			    KeyReqStruct *req_struct,
873
			    Operationrec * regOperPtr)
874
{
875
  TupKeyConf * tupKeyConf= (TupKeyConf *)signal->getDataPtrSend();  
876
  
877
  Uint32 Rcreate_rowid = req_struct->m_use_rowid;
878 879 880 881 882 883 884 885 886 887 888 889 890
  Uint32 RuserPointer= regOperPtr->userpointer;
  Uint32 RnoFiredTriggers= req_struct->no_fired_triggers;
  Uint32 log_size= req_struct->log_size;
  Uint32 read_length= req_struct->read_length;
  Uint32 last_row= req_struct->last_row;
  
  set_trans_state(regOperPtr, TRANS_STARTED);
  set_tuple_state(regOperPtr, TUPLE_PREPARED);
  tupKeyConf->userPtr= RuserPointer;
  tupKeyConf->readLength= read_length;
  tupKeyConf->writeLength= log_size;
  tupKeyConf->noFiredTriggers= RnoFiredTriggers;
  tupKeyConf->lastRow= last_row;
891
  tupKeyConf->rowid = Rcreate_rowid;
892 893
  
  EXECUTE_DIRECT(DBLQH, GSN_TUPKEYCONF, signal,
894
		 TupKeyConf::SignalLength);
895 896 897
  
}

898

899 900
#define MAX_READ (sizeof(signal->theData) > MAX_MESSAGE_SIZE ? MAX_MESSAGE_SIZE : sizeof(signal->theData))

901 902 903 904
/* ---------------------------------------------------------------- */
/* ----------------------------- READ  ---------------------------- */
/* ---------------------------------------------------------------- */
int Dbtup::handleReadReq(Signal* signal,
905 906
                         Operationrec* regOperPtr,
                         Tablerec* regTabPtr,
907
                         KeyReqStruct* req_struct)
908
{
909 910 911
  Uint32 *dst;
  Uint32 dstLen, start_index;
  const BlockReference sendBref= req_struct->rec_blockref;
912
  if ((regTabPtr->m_bits & Tablerec::TR_Checksum) &&
913
      (calculateChecksum(req_struct->m_tuple_ptr, regTabPtr) != 0)) {
914
    jam();
915 916
    ndbout_c("here2");
    terrorCode= ZTUPLE_CORRUPTED_ERROR;
917 918
    tupkeyErrorLab(signal);
    return -1;
919
  }
920

joreland@mysql.com's avatar
joreland@mysql.com committed
921 922
  const Uint32 node = refToNode(sendBref);
  if(node != 0 && node != getOwnNodeId()) {
923
    start_index= 25;
joreland@mysql.com's avatar
joreland@mysql.com committed
924 925 926 927 928
  } else {
    jam();
    /**
     * execute direct
     */
929
    start_index= 3;
joreland@mysql.com's avatar
joreland@mysql.com committed
930
  }
931 932 933
  dst= &signal->theData[start_index];
  dstLen= (MAX_READ / 4) - start_index;
  if (!req_struct->interpreted_exec) {
934
    jam();
935
    int ret = readAttributes(req_struct,
936
			     &cinBuffer[0],
937
			     req_struct->attrinfo_len,
938 939 940
			     dst,
			     dstLen,
			     false);
941
    if (likely(ret != -1)) {
942 943 944 945
/* ------------------------------------------------------------------------- */
// We have read all data into coutBuffer. Now send it to the API.
/* ------------------------------------------------------------------------- */
      jam();
946
      Uint32 TnoOfDataRead= (Uint32) ret;
947 948
      req_struct->read_length= TnoOfDataRead;
      sendReadAttrinfo(signal, req_struct, TnoOfDataRead, regOperPtr);
949
      return 0;
950
    }
951 952
  } else {
    jam();
jonas@perch.ndb.mysql.com's avatar
merge  
jonas@perch.ndb.mysql.com committed
953
    if (likely(interpreterStartLab(signal, req_struct) != -1)) {
954
      return 0;
955
    }
jonas@perch.ndb.mysql.com's avatar
merge  
jonas@perch.ndb.mysql.com committed
956
    return -1;
957
  }
958 959 960 961

  jam();
  tupkeyErrorLab(signal);
  return -1;
962
}
963 964 965 966 967

/* ---------------------------------------------------------------- */
/* ---------------------------- UPDATE ---------------------------- */
/* ---------------------------------------------------------------- */
int Dbtup::handleUpdateReq(Signal* signal,
968 969 970
                           Operationrec* operPtrP,
                           Fragrecord* regFragPtr,
                           Tablerec* regTabPtr,
971 972
                           KeyReqStruct* req_struct,
			   bool disk) 
973
{
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
  Uint32 *dst;
  Tuple_header *base= req_struct->m_tuple_ptr, *org;
  if ((dst= c_undo_buffer.alloc_copy_tuple(&operPtrP->m_copy_tuple_location,
					   regTabPtr->total_rec_size)) == 0)
  {
    terrorCode= ZMEM_NOMEM_ERROR;
    goto error;
  }

  Uint32 tup_version;
  if(operPtrP->is_first_operation())
  {
    org= req_struct->m_tuple_ptr;
    tup_version= org->get_tuple_version();
  }
  else
  {
    Operationrec* prevOp= req_struct->prevOpPtr.p;
    tup_version= prevOp->tupVersion;
    org= (Tuple_header*)c_undo_buffer.get_ptr(&prevOp->m_copy_tuple_location);
  }

  /**
   * Check consistency before update/delete
   */
  req_struct->m_tuple_ptr= org;
1000
  if ((regTabPtr->m_bits & Tablerec::TR_Checksum) &&
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
      (calculateChecksum(req_struct->m_tuple_ptr, regTabPtr) != 0)) 
  {
    terrorCode= ZTUPLE_CORRUPTED_ERROR;
    goto error;
  }

  req_struct->m_tuple_ptr= (Tuple_header*)dst;

  union {
    Uint32 sizes[4];
    Uint64 cmp[2];
  };
  
  disk = disk || (org->m_header_bits & Tuple_header::DISK_INLINE);
  if (regTabPtr->need_expand(disk))
  {
    expand_tuple(req_struct, sizes, org, regTabPtr, disk);
    if(disk && operPtrP->m_undo_buffer_space == 0)
    {
      operPtrP->op_struct.m_wait_log_buffer = 1;
      operPtrP->op_struct.m_load_diskpage_on_commit = 1;
      Uint32 sz= operPtrP->m_undo_buffer_space= 
	(sizeof(Dbtup::Disk_undo::Update) >> 2) + sizes[DD] - 1;
      
      terrorCode= c_lgman->alloc_log_space(regFragPtr->m_logfile_group_id,
					   sz);
1027
      if(unlikely(terrorCode))
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
      {
	operPtrP->m_undo_buffer_space= 0;
	goto error;
      }
    }
  }
  else
  {
    memcpy(dst, org, 4*regTabPtr->m_offsets[MM].m_fix_header_size);
  }
  
  tup_version= (tup_version + 1) & ZTUP_VERSION_MASK;
  operPtrP->tupVersion= tup_version;
  
  int retValue;
  if (!req_struct->interpreted_exec) {
1044
    jam();
1045 1046 1047
    retValue= updateAttributes(req_struct,
                               &cinBuffer[0],
                               req_struct->attrinfo_len);
1048 1049
  } else {
    jam();
jonas@perch.ndb.mysql.com's avatar
merge  
jonas@perch.ndb.mysql.com committed
1050 1051
    if (unlikely(interpreterStartLab(signal, req_struct) == -1))
      return -1;
1052
  }
jonas@perch.ndb.mysql.com's avatar
merge  
jonas@perch.ndb.mysql.com committed
1053
  
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
  if (retValue == -1) {
    goto error;
  }
  
  if (regTabPtr->need_shrink())
  {  
    shrink_tuple(req_struct, sizes+2, regTabPtr, disk);
    if (cmp[0] != cmp[1] && handle_size_change_after_update(req_struct,
							    base,
							    operPtrP,
							    regFragPtr,
							    regTabPtr,
							    sizes)) {
      goto error;
    }
  }
  
  req_struct->m_tuple_ptr->set_tuple_version(tup_version);
1072
  if (regTabPtr->m_bits & Tablerec::TR_Checksum) {
1073 1074 1075 1076 1077 1078 1079 1080 1081
    jam();
    setChecksum(req_struct->m_tuple_ptr, regTabPtr);
  }
  return retValue;
  
error:
  tupkeyErrorLab(signal);  
  return -1;
}
1082 1083 1084 1085

/* ---------------------------------------------------------------- */
/* ----------------------------- INSERT --------------------------- */
/* ---------------------------------------------------------------- */
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
void
Dbtup::prepare_initial_insert(KeyReqStruct *req_struct, 
			      Operationrec* regOperPtr,
			      Tablerec* regTabPtr)
{
  Uint32 disk_undo = regTabPtr->m_no_of_disk_attributes ? 
    sizeof(Dbtup::Disk_undo::Alloc) >> 2 : 0;
  regOperPtr->nextActiveOp= RNIL;
  regOperPtr->prevActiveOp= RNIL;
  regOperPtr->op_struct.in_active_list= true;
  regOperPtr->m_undo_buffer_space= disk_undo; 
  
  req_struct->check_offset[MM]= regTabPtr->get_check_offset(MM);
  req_struct->check_offset[DD]= regTabPtr->get_check_offset(DD);
  
  Uint32 num_attr= regTabPtr->m_no_of_attributes;
  Uint32 descr_start= regTabPtr->tabDescriptor;
  Uint32 order_desc= regTabPtr->m_real_order_descriptor;
  TableDescriptor *tab_descr= &tableDescriptor[descr_start];
  ndbrequire(descr_start + (num_attr << ZAD_LOG_SIZE) <= cnoOfTabDescrRec);
  req_struct->attr_descr= tab_descr; 
  Uint16* order= (Uint16*)&tableDescriptor[order_desc];

  const Uint32 cnt1= regTabPtr->m_attributes[MM].m_no_of_varsize;
  const Uint32 cnt2= regTabPtr->m_attributes[DD].m_no_of_varsize;
  Uint32 *ptr= req_struct->m_tuple_ptr->get_var_part_ptr(regTabPtr);

  if(cnt1)
  {
    KeyReqStruct::Var_data* dst= &req_struct->m_var_data[MM];
    dst->m_data_ptr= (char*)(((Uint16*)ptr)+cnt1+1);
    dst->m_offset_array_ptr= req_struct->var_pos_array;
    dst->m_var_len_offset= cnt1;
    dst->m_max_var_offset= regTabPtr->m_offsets[MM].m_max_var_offset;
    // Disk part is 32-bit aligned
    ptr= ALIGN_WORD(dst->m_data_ptr+regTabPtr->m_offsets[MM].m_max_var_offset);
    order += regTabPtr->m_attributes[MM].m_no_of_fixsize;
    Uint32 pos= 0;
1124 1125
    Uint16 *pos_ptr = req_struct->var_pos_array;
    Uint16 *len_ptr = pos_ptr + cnt1;
1126 1127
    for(Uint32 i= 0; i<cnt1; i++)
    {
1128 1129
      * pos_ptr++ = pos;
      * len_ptr++ = pos;
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
      pos += AttributeDescriptor::getSizeInBytes(tab_descr[*order++].tabDescr);
    }
  } 
  else
  {
    ptr -= Tuple_header::HeaderSize;
  }

  req_struct->m_disk_ptr= (Tuple_header*)ptr;
  
  if(cnt2)
  {
    KeyReqStruct::Var_data *dst= &req_struct->m_var_data[DD];
    ptr=((Tuple_header*)ptr)->m_data+regTabPtr->m_offsets[DD].m_varpart_offset;
    dst->m_data_ptr= (char*)(((Uint16*)ptr)+cnt2+1);
    dst->m_offset_array_ptr= req_struct->var_pos_array + (cnt1 << 1);
    dst->m_var_len_offset= cnt2;
    dst->m_max_var_offset= regTabPtr->m_offsets[DD].m_max_var_offset;
  }
  
  // Set all null bits
  memset(req_struct->m_tuple_ptr->m_null_bits+
	 regTabPtr->m_offsets[MM].m_null_offset, 0xFF, 
	 4*regTabPtr->m_offsets[MM].m_null_words);
  memset(req_struct->m_disk_ptr->m_null_bits+
	 regTabPtr->m_offsets[DD].m_null_offset, 0xFF, 
	 4*regTabPtr->m_offsets[DD].m_null_words);
  req_struct->m_tuple_ptr->m_header_bits= 
    disk_undo ? (Tuple_header::DISK_ALLOC | Tuple_header::DISK_INLINE) : 0;
}

1161
int Dbtup::handleInsertReq(Signal* signal,
1162 1163
                           Ptr<Operationrec> regOperPtr,
                           Ptr<Fragrecord> fragPtr,
1164
                           Tablerec* regTabPtr,
1165
                           KeyReqStruct *req_struct)
1166
{
1167
  Uint32 tup_version = 1;
1168 1169 1170 1171
  Fragrecord* regFragPtr = fragPtr.p;
  Uint32 *dst, *ptr= 0;
  Tuple_header *base= req_struct->m_tuple_ptr, *org= base;
  Tuple_header *tuple_ptr;
1172 1173
    
  bool disk = regTabPtr->m_no_of_disk_attributes > 0;
1174 1175
  bool mem_insert = regOperPtr.p->is_first_operation();
  bool disk_insert = mem_insert && disk;
1176 1177 1178 1179
  bool varsize = regTabPtr->m_attributes[MM].m_no_of_varsize;
  bool rowid = req_struct->m_use_rowid;
  Uint32 real_page_id = regOperPtr.p->m_tuple_location.m_page_no;
  Uint32 frag_page_id = req_struct->frag_page_id;
1180 1181 1182 1183 1184

  union {
    Uint32 sizes[4];
    Uint64 cmp[2];
  };
1185

1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
  if (ERROR_INSERTED(4014))
  {
    dst = 0;
    goto undo_buffer_error;
  }

  dst= c_undo_buffer.alloc_copy_tuple(&regOperPtr.p->m_copy_tuple_location,
				      regTabPtr->total_rec_size);
  if (unlikely(dst == 0))
  {
    goto undo_buffer_error;
  }
  tuple_ptr= req_struct->m_tuple_ptr= (Tuple_header*)dst;

1200
  if(mem_insert)
1201
  {
1202
    jam();
1203 1204 1205 1206
    prepare_initial_insert(req_struct, regOperPtr.p, regTabPtr);
  }
  else
  {
1207 1208 1209 1210 1211 1212
    Operationrec* prevOp= req_struct->prevOpPtr.p;
    ndbassert(prevOp->op_struct.op_type == ZDELETE);
    tup_version= prevOp->tupVersion + 1;
    
    if(!prevOp->is_first_operation())
      org= (Tuple_header*)c_undo_buffer.get_ptr(&prevOp->m_copy_tuple_location);
1213
    if (regTabPtr->need_expand())
1214
      expand_tuple(req_struct, sizes, org, regTabPtr, !disk_insert);
1215 1216 1217 1218
    else
      memcpy(dst, org, 4*regTabPtr->m_offsets[MM].m_fix_header_size);
  }
  
1219 1220 1221
  if (disk_insert)
  {
    int res;
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
    
    if (ERROR_INSERTED(4015))
    {
      terrorCode = 1501;
      goto log_space_error;
    }

    res= c_lgman->alloc_log_space(regFragPtr->m_logfile_group_id,
				  regOperPtr.p->m_undo_buffer_space);
    if(unlikely(res))
1232 1233 1234 1235 1236 1237
    {
      terrorCode= res;
      goto log_space_error;
    }
  }
  
1238 1239
  regOperPtr.p->tupVersion= tup_version & ZTUP_VERSION_MASK;
  tuple_ptr->set_tuple_version(tup_version);
1240

1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
  if (ERROR_INSERTED(4016))
  {
    terrorCode = ZAI_INCONSISTENCY_ERROR;
    goto update_error;
  }

  if(unlikely(updateAttributes(req_struct, &cinBuffer[0], 
			       req_struct->attrinfo_len) == -1))
  {
    goto update_error;
  }

  if (ERROR_INSERTED(4017))
  {
    goto null_check_error;
  }
  if (unlikely(checkNullAttributes(req_struct, regTabPtr) == false))
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
  {
    goto null_check_error;
  }
  
  if (regTabPtr->need_shrink())
  {  
    shrink_tuple(req_struct, sizes+2, regTabPtr, true);
  }
  
  /**
   * Alloc memory
   */
1270
  if(mem_insert)
1271
  {
1272
    if (!rowid)
1273
    {
1274
      if (ERROR_INSERTED(4018))
1275
      {
1276
	goto mem_error;
1277
      }
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297

      if (!varsize)
      {
	jam();
	ptr= alloc_fix_rec(regFragPtr,
			   regTabPtr,
			   &regOperPtr.p->m_tuple_location,
			   &frag_page_id);
      } 
      else 
      {
	jam();
	regOperPtr.p->m_tuple_location.m_file_no= sizes[2+MM];
	ptr= alloc_var_rec(regFragPtr, regTabPtr,
			   sizes[2+MM],
			   &regOperPtr.p->m_tuple_location,
			   &frag_page_id);
      }
      if (unlikely(ptr == 0))
      {
1298
	goto mem_error;
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
      }
      req_struct->m_use_rowid = true;
    }
    else
    {
      regOperPtr.p->m_tuple_location = req_struct->m_row_id;
      if (ERROR_INSERTED(4019))
      {
	terrorCode = ZROWID_ALLOCATED;
	goto alloc_rowid_error;
      }
      
      if (!varsize)
      {
	jam();
	ptr= alloc_fix_rowid(regFragPtr,
			     regTabPtr,
			     &regOperPtr.p->m_tuple_location,
			     &frag_page_id);
      } 
      else 
      {
	jam();
	regOperPtr.p->m_tuple_location.m_file_no= sizes[2+MM];
	ptr= alloc_var_rowid(regFragPtr, regTabPtr,
			     sizes[2+MM],
			     &regOperPtr.p->m_tuple_location,
			     &frag_page_id);
      }
      if (unlikely(ptr == 0))
      {
1330
	jam();
1331 1332
	goto alloc_rowid_error;
      }
1333
    }
1334 1335 1336 1337 1338
    real_page_id = regOperPtr.p->m_tuple_location.m_page_no;
    regOperPtr.p->m_tuple_location.m_page_no= frag_page_id;
    c_lqh->accminupdate(signal,
			regOperPtr.p->userpointer,
			&regOperPtr.p->m_tuple_location);
1339
    
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
1340 1341 1342
    base = (Tuple_header*)ptr;
    base->m_operation_ptr_i= regOperPtr.i;
    base->m_header_bits= Tuple_header::ALLOC | 
1343
      (varsize ? Tuple_header::CHAINED_ROW : 0);
1344
    regOperPtr.p->m_tuple_location.m_page_no = real_page_id;
1345
  }
1346
  else 
1347
  {
1348
    int ret;
1349 1350 1351 1352 1353
    if (ERROR_INSERTED(4020))
    {
      goto size_change_error;
    }

1354
    if (regTabPtr->need_shrink() && cmp[0] != cmp[1] &&
1355 1356 1357 1358 1359 1360
	unlikely(ret = handle_size_change_after_update(req_struct,
						       base,
						       regOperPtr.p,
						       regFragPtr,
						       regTabPtr,
						       sizes)))
1361
    {
1362 1363 1364 1365 1366
      goto size_change_error;
    }
    req_struct->m_use_rowid = false;
    base->m_header_bits &= ~(Uint32)Tuple_header::FREE;
  }
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
1367 1368 1369

  base->m_header_bits |= Tuple_header::ALLOC & 
    (regOperPtr.p->is_first_operation() ? ~0 : 1);
1370 1371 1372 1373 1374 1375
  
  if (disk_insert)
  {
    Local_key tmp;
    Uint32 size= regTabPtr->m_attributes[DD].m_no_of_varsize == 0 ? 
      1 : sizes[2+DD];
1376
    
1377 1378 1379 1380 1381 1382
    if (ERROR_INSERTED(4021))
    {
      terrorCode = 1601;
      goto disk_prealloc_error;
    }
    
1383
    int ret= disk_page_prealloc(signal, fragPtr, &tmp, size);
1384 1385
    if (unlikely(ret < 0))
    {
1386
      terrorCode = -ret;
1387 1388
      goto disk_prealloc_error;
    }
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
    
    regOperPtr.p->op_struct.m_disk_preallocated= 1;
    tmp.m_page_idx= size;
    memcpy(tuple_ptr->get_disk_ref_ptr(regTabPtr), &tmp, sizeof(tmp));
    
    /**
     * Set ref from disk to mm
     */
    Local_key ref = regOperPtr.p->m_tuple_location;
    ref.m_page_no = frag_page_id;
    
    Tuple_header* disk_ptr= req_struct->m_disk_ptr;
    disk_ptr->m_header_bits = 0;
    disk_ptr->m_base_record_ref= ref.ref();
1403
  }
1404
  
1405
  if (regTabPtr->m_bits & Tablerec::TR_Checksum) 
1406 1407 1408 1409 1410
  {
    jam();
    setChecksum(req_struct->m_tuple_ptr, regTabPtr);
  }
  return 0;
1411
  
1412 1413 1414
size_change_error:
  jam();
  terrorCode = ZMEM_NOMEM_ERROR;
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
1415
  goto exit_error;
1416 1417 1418
  
undo_buffer_error:
  jam();
1419
  terrorCode= ZMEM_NOMEM_ERROR;
1420 1421 1422 1423 1424 1425
  regOperPtr.p->m_undo_buffer_space = 0;
  if (mem_insert)
    regOperPtr.p->m_tuple_location.setNull();
  regOperPtr.p->m_copy_tuple_location.setNull();
  tupkeyErrorLab(signal);  
  return -1;
1426 1427
  
null_check_error:
1428
  jam();
1429
  terrorCode= ZNO_ILLEGAL_NULL_ATTR;
1430
  goto update_error;
1431

1432 1433 1434 1435
mem_error:
  jam();
  terrorCode= ZMEM_NOMEM_ERROR;
  goto update_error;
1436 1437

log_space_error:
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
  jam();
  regOperPtr.p->m_undo_buffer_space = 0;
alloc_rowid_error:
  jam();
update_error:
  jam();
  if (mem_insert)
  {
    regOperPtr.p->op_struct.in_active_list = false;
    regOperPtr.p->m_tuple_location.setNull();
  }
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
1449
exit_error:
1450
  tupkeyErrorLab(signal);
1451
  return -1;
jonas@perch.ndb.mysql.com's avatar
ndb -  
jonas@perch.ndb.mysql.com committed
1452 1453 1454 1455

disk_prealloc_error:
  base->m_header_bits |= Tuple_header::FREED;
  goto exit_error;
1456
}
1457 1458 1459 1460 1461

/* ---------------------------------------------------------------- */
/* ---------------------------- DELETE ---------------------------- */
/* ---------------------------------------------------------------- */
int Dbtup::handleDeleteReq(Signal* signal,
1462 1463 1464
                           Operationrec* regOperPtr,
                           Fragrecord* regFragPtr,
                           Tablerec* regTabPtr,
1465
                           KeyReqStruct *req_struct)
1466 1467
{
  // delete must set but not increment tupVersion
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
  if (!regOperPtr->is_first_operation())
  {
    Operationrec* prevOp= req_struct->prevOpPtr.p;
    regOperPtr->tupVersion= prevOp->tupVersion;
    regOperPtr->m_copy_tuple_location= prevOp->m_copy_tuple_location;
  } 
  else 
  {
    regOperPtr->tupVersion= req_struct->m_tuple_ptr->get_tuple_version();
    if(regTabPtr->m_no_of_disk_attributes)
    {
      Uint32 sz;
      if(regTabPtr->m_attributes[DD].m_no_of_varsize)
      {
	/**
	 * Need to have page in memory to read size 
	 *   to alloc undo space
	 */
	abort();
      }
      else
	sz= (sizeof(Dbtup::Disk_undo::Free) >> 2) + 
	  regTabPtr->m_offsets[DD].m_fix_header_size - 1;
      
      regOperPtr->m_undo_buffer_space= sz;
      
      int res;
      if((res= c_lgman->alloc_log_space(regFragPtr->m_logfile_group_id, 
					sz)))
      {
	terrorCode= res;
	regOperPtr->m_undo_buffer_space= 0;
	goto error;
      }
      
    }
1504
  }
1505 1506
  if (req_struct->attrinfo_len == 0)
  {
1507 1508
    return 0;
  }
1509 1510
  
  return handleReadReq(signal, regOperPtr, regTabPtr, req_struct);
1511

1512 1513 1514 1515
error:
  tupkeyErrorLab(signal);
  return -1;
}
1516 1517

bool
1518 1519
Dbtup::checkNullAttributes(KeyReqStruct * req_struct,
                           Tablerec* regTabPtr)
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
{
// Implement checking of updating all not null attributes in an insert here.
  Bitmask<MAXNROFATTRIBUTESINWORDS> attributeMask;  
  /* 
   * The idea here is maybe that changeMask is not-null attributes
   * and must contain notNullAttributeMask.  But:
   *
   * 1. changeMask has all bits set on insert
   * 2. not-null is checked in each UpdateFunction
   * 3. the code below does not work except trivially due to 1.
   *
   * XXX remove or fix
   */
  attributeMask.clear();
1534
  attributeMask.bitOR(req_struct->changeMask);
1535 1536 1537 1538
  attributeMask.bitAND(regTabPtr->notNullAttributeMask);
  attributeMask.bitXOR(regTabPtr->notNullAttributeMask);
  if (!attributeMask.isclear()) {
    return false;
1539
  }
1540
  return true;
1541
}
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588

/* ---------------------------------------------------------------- */
/* THIS IS THE START OF THE INTERPRETED EXECUTION OF UPDATES. WE    */
/* START BY LINKING ALL ATTRINFO'S IN A DOUBLY LINKED LIST (THEY ARE*/
/* ALREADY IN A LINKED LIST). WE ALLOCATE A REGISTER MEMORY (EQUAL  */
/* TO AN ATTRINFO RECORD). THE INTERPRETER GOES THROUGH FOUR  PHASES*/
/* DURING THE FIRST PHASE IT IS ONLY ALLOWED TO READ ATTRIBUTES THAT*/
/* ARE SENT TO THE CLIENT APPLICATION. DURING THE SECOND PHASE IT IS*/
/* ALLOWED TO READ FROM ATTRIBUTES INTO REGISTERS, TO UPDATE        */
/* ATTRIBUTES BASED ON EITHER A CONSTANT VALUE OR A REGISTER VALUE, */
/* A DIVERSE SET OF OPERATIONS ON REGISTERS ARE AVAILABLE AS WELL.  */
/* IT IS ALSO POSSIBLE TO PERFORM JUMPS WITHIN THE INSTRUCTIONS THAT*/
/* BELONGS TO THE SECOND PHASE. ALSO SUBROUTINES CAN BE CALLED IN   */
/* THIS PHASE. THE THIRD PHASE IS TO AGAIN READ ATTRIBUTES AND      */
/* FINALLY THE FOURTH PHASE READS SELECTED REGISTERS AND SEND THEM  */
/* TO THE CLIENT APPLICATION.                                       */
/* THERE IS A FIFTH REGION WHICH CONTAINS SUBROUTINES CALLABLE FROM */
/* THE INTERPRETER EXECUTION REGION.                                */
/* THE FIRST FIVE WORDS WILL GIVE THE LENGTH OF THE FIVEE REGIONS   */
/*                                                                  */
/* THIS MEANS THAT FROM THE APPLICATIONS POINT OF VIEW THE DATABASE */
/* CAN HANDLE SUBROUTINE CALLS WHERE THE CODE IS SENT IN THE REQUEST*/
/* THE RETURN PARAMETERS ARE FIXED AND CAN EITHER BE GENERATED      */
/* BEFORE THE EXECUTION OF THE ROUTINE OR AFTER.                    */
/*                                                                  */
/* IN LATER VERSIONS WE WILL ADD MORE THINGS LIKE THE POSSIBILITY   */
/* TO ALLOCATE MEMORY AND USE THIS AS LOCAL STORAGE. IT IS ALSO     */
/* IMAGINABLE TO HAVE SPECIAL ROUTINES THAT CAN PERFORM CERTAIN     */
/* OPERATIONS ON BLOB'S DEPENDENT ON WHAT THE BLOB REPRESENTS.      */
/*                                                                  */
/*                                                                  */
/*       -----------------------------------------                  */
/*       +   INITIAL READ REGION                 +                  */
/*       -----------------------------------------                  */
/*       +   INTERPRETED EXECUTE  REGION         +                  */
/*       -----------------------------------------                  */
/*       +   FINAL UPDATE REGION                 +                  */
/*       -----------------------------------------                  */
/*       +   FINAL READ REGION                   +                  */
/*       -----------------------------------------                  */
/*       +   SUBROUTINE REGION                   +                  */
/*       -----------------------------------------                  */
/* ---------------------------------------------------------------- */
/* ---------------------------------------------------------------- */
/* ----------------- INTERPRETED EXECUTION  ----------------------- */
/* ---------------------------------------------------------------- */
int Dbtup::interpreterStartLab(Signal* signal,
1589
                               KeyReqStruct *req_struct)
1590
{
1591
  Operationrec *  const regOperPtr= operPtr.p;
1592
  int TnoDataRW;
1593 1594
  Uint32 RtotalLen, start_index, dstLen;
  Uint32 *dst;
1595

1596 1597 1598 1599 1600
  Uint32 RinitReadLen= cinBuffer[0];
  Uint32 RexecRegionLen= cinBuffer[1];
  Uint32 RfinalUpdateLen= cinBuffer[2];
  Uint32 RfinalRLen= cinBuffer[3];
  Uint32 RsubLen= cinBuffer[4];
1601

1602 1603
  Uint32 RattrinbufLen= req_struct->attrinfo_len;
  const BlockReference sendBref= req_struct->rec_blockref;
1604 1605 1606

  const Uint32 node = refToNode(sendBref);
  if(node != 0 && node != getOwnNodeId()) {
1607
    start_index= 25;
1608 1609 1610 1611 1612
  } else {
    jam();
    /**
     * execute direct
     */
1613
    start_index= 3;
1614
  }
1615 1616
  dst= &signal->theData[start_index];
  dstLen= (MAX_READ / 4) - start_index;
1617
  
1618
  RtotalLen= RinitReadLen;
1619 1620 1621 1622 1623
  RtotalLen += RexecRegionLen;
  RtotalLen += RfinalUpdateLen;
  RtotalLen += RfinalRLen;
  RtotalLen += RsubLen;

1624 1625 1626
  Uint32 RattroutCounter= 0;
  Uint32 RinstructionCounter= 5;
  Uint32 RlogSize= 0;
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
  if (((RtotalLen + 5) == RattrinbufLen) &&
      (RattrinbufLen >= 5) &&
      (RattrinbufLen < ZATTR_BUFFER_SIZE)) {
    /* ---------------------------------------------------------------- */
    // We start by checking consistency. We must have the first five
    // words of the ATTRINFO to give us the length of the regions. The
    // size of these regions must be the same as the total ATTRINFO
    // length and finally the total length must be within the limits.
    /* ---------------------------------------------------------------- */

    if (RinitReadLen > 0) {
      jam();
      /* ---------------------------------------------------------------- */
      // The first step that can be taken in the interpreter is to read
      // data of the tuple before any updates have been applied.
      /* ---------------------------------------------------------------- */
1643
      TnoDataRW= readAttributes(req_struct,
1644 1645 1646
				 &cinBuffer[5],
				 RinitReadLen,
				 &dst[0],
1647 1648
				 dstLen,
                                 false);
1649
      if (TnoDataRW != -1) {
1650
	RattroutCounter= TnoDataRW;
1651 1652 1653 1654 1655
	RinstructionCounter += RinitReadLen;
      } else {
	jam();
	tupkeyErrorLab(signal);
	return -1;
1656 1657
      }
    }
1658 1659 1660 1661 1662 1663 1664
    if (RexecRegionLen > 0) {
      jam();
      /* ---------------------------------------------------------------- */
      // The next step is the actual interpreted execution. This executes
      // a register-based virtual machine which can read and write attributes
      // to and from registers.
      /* ---------------------------------------------------------------- */
1665 1666 1667
      Uint32 RsubPC= RinstructionCounter + RfinalUpdateLen + RfinalRLen;     
      TnoDataRW= interpreterNextLab(signal,
                                     req_struct,
1668 1669 1670 1671 1672
				     &clogMemBuffer[0],
				     &cinBuffer[RinstructionCounter],
				     RexecRegionLen,
				     &cinBuffer[RsubPC],
				     RsubLen,
joreland@mysql.com's avatar
joreland@mysql.com committed
1673 1674
				     &coutBuffer[0],
				     sizeof(coutBuffer) / 4);
1675
      if (TnoDataRW != -1) {
1676
	RinstructionCounter += RexecRegionLen;
1677
	RlogSize= TnoDataRW;
1678 1679
      } else {
	jam();
1680
	tupkeyErrorLab(signal);
1681
	return -1;
1682 1683
      }
    }
1684 1685 1686 1687 1688 1689
    if (RfinalUpdateLen > 0) {
      jam();
      /* ---------------------------------------------------------------- */
      // We can also apply a set of updates without any conditions as part
      // of the interpreted execution.
      /* ---------------------------------------------------------------- */
1690 1691
      if (regOperPtr->op_struct.op_type == ZUPDATE) {
	TnoDataRW= updateAttributes(req_struct,
1692 1693
				     &cinBuffer[RinstructionCounter],
				     RfinalUpdateLen);
1694
	if (TnoDataRW != -1) {
1695 1696 1697 1698 1699 1700 1701 1702 1703
	  MEMCOPY_NO_WORDS(&clogMemBuffer[RlogSize],
			   &cinBuffer[RinstructionCounter],
			   RfinalUpdateLen);
	  RinstructionCounter += RfinalUpdateLen;
	  RlogSize += RfinalUpdateLen;
	} else {
	  jam();
	  tupkeyErrorLab(signal);
	  return -1;
1704
	}
1705 1706
      } else {
	return TUPKEY_abort(signal, 19);
1707 1708
      }
    }
1709 1710 1711 1712 1713 1714
    if (RfinalRLen > 0) {
      jam();
      /* ---------------------------------------------------------------- */
      // The final action is that we can also read the tuple after it has
      // been updated.
      /* ---------------------------------------------------------------- */
1715
      TnoDataRW= readAttributes(req_struct,
1716 1717 1718
				 &cinBuffer[RinstructionCounter],
				 RfinalRLen,
				 &dst[RattroutCounter],
1719 1720
				 (dstLen - RattroutCounter),
                                 false);
1721
      if (TnoDataRW != -1) {
1722 1723 1724 1725 1726
	RattroutCounter += TnoDataRW;
      } else {
	jam();
	tupkeyErrorLab(signal);
	return -1;
1727 1728 1729 1730 1731
      }
    }
    req_struct->log_size= RlogSize;
    req_struct->read_length= RattroutCounter;
    sendReadAttrinfo(signal, req_struct, RattroutCounter, regOperPtr);
1732 1733
    if (RlogSize > 0) {
      sendLogAttrinfo(signal, RlogSize, regOperPtr);
1734
    }
1735 1736 1737
    return 0;
  } else {
    return TUPKEY_abort(signal, 22);
1738 1739
  }
}
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753

/* ---------------------------------------------------------------- */
/*       WHEN EXECUTION IS INTERPRETED WE NEED TO SEND SOME ATTRINFO*/
/*       BACK TO LQH FOR LOGGING AND SENDING TO BACKUP AND STANDBY  */
/*       NODES.                                                     */
/*       INPUT:  LOG_ATTRINFOPTR         WHERE TO FETCH DATA FROM   */
/*               TLOG_START              FIRST INDEX TO LOG         */
/*               TLOG_END                LAST INDEX + 1 TO LOG      */
/* ---------------------------------------------------------------- */
void Dbtup::sendLogAttrinfo(Signal* signal,
                            Uint32 TlogSize,
                            Operationrec *  const regOperPtr)

{
1754 1755
  Uint32 TbufferIndex= 0;
  signal->theData[0]= regOperPtr->userpointer;
1756 1757 1758 1759
  while (TlogSize > 22) {
    MEMCOPY_NO_WORDS(&signal->theData[3],
                     &clogMemBuffer[TbufferIndex],
                     22);
1760
    EXECUTE_DIRECT(DBLQH, GSN_TUP_ATTRINFO, signal, 25);
1761 1762
    TbufferIndex += 22;
    TlogSize -= 22;
1763
  }
1764 1765 1766
  MEMCOPY_NO_WORDS(&signal->theData[3],
                   &clogMemBuffer[TbufferIndex],
                   TlogSize);
1767 1768
  EXECUTE_DIRECT(DBLQH, GSN_TUP_ATTRINFO, signal, 3 + TlogSize);
}
1769 1770 1771 1772 1773

inline
Uint32 
brancher(Uint32 TheInstruction, Uint32 TprogramCounter)
{         
1774 1775
  Uint32 TbranchDirection= TheInstruction >> 31;
  Uint32 TbranchLength= (TheInstruction >> 16) & 0x7fff;
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
  TprogramCounter--;
  if (TbranchDirection == 1) {
    jam();
    /* ---------------------------------------------------------------- */
    /*       WE JUMP BACKWARDS.                                         */
    /* ---------------------------------------------------------------- */
    return (TprogramCounter - TbranchLength);
  } else {
    jam();
    /* ---------------------------------------------------------------- */
    /*       WE JUMP FORWARD.                                           */
    /* ---------------------------------------------------------------- */
    return (TprogramCounter + TbranchLength);
1789 1790
  }
}
1791 1792

int Dbtup::interpreterNextLab(Signal* signal,
1793
                              KeyReqStruct* req_struct,
1794 1795 1796 1797 1798 1799 1800 1801
                              Uint32* logMemory,
                              Uint32* mainProgram,
                              Uint32 TmainProgLen,
                              Uint32* subroutineProg,
                              Uint32 TsubroutineLen,
			      Uint32 * tmpArea,
			      Uint32 tmpAreaSz)
{
1802 1803 1804 1805
  register Uint32* TcurrentProgram= mainProgram;
  register Uint32 TcurrentSize= TmainProgLen;
  register Uint32 RnoOfInstructions= 0;
  register Uint32 TprogramCounter= 0;
1806 1807
  register Uint32 theInstruction;
  register Uint32 theRegister;
1808 1809
  Uint32 TdataWritten= 0;
  Uint32 RstackPtr= 0;
1810 1811 1812 1813
  union {
    Uint32 TregMemBuffer[32];
    Uint64 Tdummy[16];
  };
1814 1815 1816 1817 1818 1819 1820 1821
  Uint32 TstackMemBuffer[32];

  /* ---------------------------------------------------------------- */
  // Initialise all 8 registers to contain the NULL value.
  // In this version we can handle 32 and 64 bit unsigned integers.
  // They are handled as 64 bit values. Thus the 32 most significant
  // bits are zeroed for 32 bit values.
  /* ---------------------------------------------------------------- */
1822 1823 1824 1825 1826 1827 1828 1829 1830
  TregMemBuffer[0]= 0;
  TregMemBuffer[4]= 0;
  TregMemBuffer[8]= 0;
  TregMemBuffer[12]= 0;
  TregMemBuffer[16]= 0;
  TregMemBuffer[20]= 0;
  TregMemBuffer[24]= 0;
  TregMemBuffer[28]= 0;
  Uint32 tmpHabitant= ~0;
1831 1832 1833 1834 1835 1836

  while (RnoOfInstructions < 8000) {
    /* ---------------------------------------------------------------- */
    /* EXECUTE THE NEXT INTERPRETER INSTRUCTION.                        */
    /* ---------------------------------------------------------------- */
    RnoOfInstructions++;
1837 1838
    theInstruction= TcurrentProgram[TprogramCounter];
    theRegister= Interpreter::getReg1(theInstruction) << 2;
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
    if (TprogramCounter < TcurrentSize) {
      TprogramCounter++;
      switch (Interpreter::getOpCode(theInstruction)) {
      case Interpreter::READ_ATTR_INTO_REG:
	jam();
	/* ---------------------------------------------------------------- */
	// Read an attribute from the tuple into a register.
	// While reading an attribute we allow the attribute to be an array
	// as long as it fits in the 64 bits of the register.
	/* ---------------------------------------------------------------- */
	{
1850 1851 1852 1853 1854 1855 1856
	  Uint32 theAttrinfo= theInstruction;
	  int TnoDataRW= readAttributes(req_struct,
				     &theAttrinfo,
				     (Uint32)1,
				     &TregMemBuffer[theRegister],
				     (Uint32)3,
                                     false);
1857 1858 1859 1860 1861
	  if (TnoDataRW == 2) {
	    /* ------------------------------------------------------------- */
	    // Two words read means that we get the instruction plus one 32 
	    // word read. Thus we set the register to be a 32 bit register.
	    /* ------------------------------------------------------------- */
1862
	    TregMemBuffer[theRegister]= 0x50;
1863
            // arithmetic conversion if big-endian
1864
            * (Int64*)(TregMemBuffer+theRegister+2)= TregMemBuffer[theRegister+1];
1865 1866 1867 1868 1869
	  } else if (TnoDataRW == 3) {
	    /* ------------------------------------------------------------- */
	    // Three words read means that we get the instruction plus two 
	    // 32 words read. Thus we set the register to be a 64 bit register.
	    /* ------------------------------------------------------------- */
1870 1871 1872
	    TregMemBuffer[theRegister]= 0x60;
            TregMemBuffer[theRegister+3]= TregMemBuffer[theRegister+2];
            TregMemBuffer[theRegister+2]= TregMemBuffer[theRegister+1];
1873 1874 1875 1876 1877
	  } else if (TnoDataRW == 1) {
	    /* ------------------------------------------------------------- */
	    // One word read means that we must have read a NULL value. We set
	    // the register to indicate a NULL value.
	    /* ------------------------------------------------------------- */
1878 1879 1880
	    TregMemBuffer[theRegister]= 0;
	    TregMemBuffer[theRegister + 2]= 0;
	    TregMemBuffer[theRegister + 3]= 0;
1881
	  } else if (TnoDataRW == -1) {
1882 1883 1884 1885 1886 1887 1888 1889 1890
	    jam();
	    tupkeyErrorLab(signal);
	    return -1;
	  } else {
	    /* ------------------------------------------------------------- */
	    // Any other return value from the read attribute here is not 
	    // allowed and will lead to a system crash.
	    /* ------------------------------------------------------------- */
	    ndbrequire(false);
1891
	  }
1892 1893 1894 1895 1896 1897
	  break;
	}

      case Interpreter::WRITE_ATTR_FROM_REG:
	jam();
	{
1898 1899
	  Uint32 TattrId= theInstruction >> 16;
	  Uint32 TattrDescrIndex= tabptr.p->tabDescriptor +
1900
	    (TattrId << ZAD_LOG_SIZE);
1901 1902
	  Uint32 TattrDesc1= tableDescriptor[TattrDescrIndex].tabDescr;
	  Uint32 TregType= TregMemBuffer[theRegister];
1903 1904 1905 1906 1907 1908

	  /* --------------------------------------------------------------- */
	  // Calculate the number of words of this attribute.
	  // We allow writes into arrays as long as they fit into the 64 bit
	  // register size.
	  /* --------------------------------------------------------------- */
1909
          Uint32 TattrNoOfWords = AttributeDescriptor::getSizeInWords(TattrDesc1);
1910
	  Uint32 Toptype = operPtr.p->op_struct.op_type;
1911 1912 1913
	  Uint32 TdataForUpdate[3];
	  Uint32 Tlen;

1914
	  AttributeHeader& ah= AttributeHeader::init(&TdataForUpdate[0], 
1915 1916
						      TattrId,
                                                      TattrNoOfWords << 2);
1917 1918 1919
	  TdataForUpdate[1]= TregMemBuffer[theRegister + 2];
	  TdataForUpdate[2]= TregMemBuffer[theRegister + 3];
	  Tlen= TattrNoOfWords + 1;
1920 1921
	  if (Toptype == ZUPDATE) {
	    if (TattrNoOfWords <= 2) {
1922 1923 1924 1925 1926
              if (TattrNoOfWords == 1) {
                // arithmetic conversion if big-endian
                TdataForUpdate[1] = *(Int64*)&TregMemBuffer[theRegister + 2];
                TdataForUpdate[2] = 0;
              }
1927 1928 1929 1930 1931
	      if (TregType == 0) {
		/* --------------------------------------------------------- */
		// Write a NULL value into the attribute
		/* --------------------------------------------------------- */
		ah.setNULL();
1932 1933 1934 1935 1936
		Tlen= 1;
	      }
	      int TnoDataRW= updateAttributes(req_struct,
					   &TdataForUpdate[0],
					   Tlen);
1937
	      if (TnoDataRW != -1) {
1938 1939 1940 1941
		/* --------------------------------------------------------- */
		// Write the written data also into the log buffer so that it 
		// will be logged.
		/* --------------------------------------------------------- */
1942 1943 1944
		logMemory[TdataWritten + 0]= TdataForUpdate[0];
		logMemory[TdataWritten + 1]= TdataForUpdate[1];
		logMemory[TdataWritten + 2]= TdataForUpdate[2];
1945 1946 1947 1948
		TdataWritten += Tlen;
	      } else {
		tupkeyErrorLab(signal);
		return -1;
1949
	      }
1950 1951
	    } else {
	      return TUPKEY_abort(signal, 15);
1952
	    }
1953 1954
	  } else {
	    return TUPKEY_abort(signal, 16);
1955
	  }
1956 1957 1958 1959 1960
	  break;
	}

      case Interpreter::LOAD_CONST_NULL:
	jam();
1961
	TregMemBuffer[theRegister]= 0;	/* NULL INDICATOR */
1962 1963 1964 1965
	break;

      case Interpreter::LOAD_CONST16:
	jam();
1966 1967
	TregMemBuffer[theRegister]= 0x50;	/* 32 BIT UNSIGNED CONSTANT */
	* (Int64*)(TregMemBuffer+theRegister+2)= theInstruction >> 16;
1968 1969 1970 1971
	break;

      case Interpreter::LOAD_CONST32:
	jam();
1972 1973
	TregMemBuffer[theRegister]= 0x50;	/* 32 BIT UNSIGNED CONSTANT */
	* (Int64*)(TregMemBuffer+theRegister+2)= * 
1974
	  (TcurrentProgram+TprogramCounter);
1975 1976 1977 1978 1979
	TprogramCounter++;
	break;

      case Interpreter::LOAD_CONST64:
	jam();
1980 1981 1982 1983 1984
	TregMemBuffer[theRegister]= 0x60;	/* 64 BIT UNSIGNED CONSTANT */
        TregMemBuffer[theRegister + 2 ]= * (TcurrentProgram +
                                             TprogramCounter++);
        TregMemBuffer[theRegister + 3 ]= * (TcurrentProgram +
                                             TprogramCounter++);
1985 1986 1987 1988 1989
	break;

      case Interpreter::ADD_REG_REG:
	jam();
	{
1990 1991
	  Uint32 TrightRegister= Interpreter::getReg2(theInstruction) << 2;
	  Uint32 TdestRegister= Interpreter::getReg3(theInstruction) << 2;
1992

1993 1994
	  Uint32 TrightType= TregMemBuffer[TrightRegister];
	  Int64 Tright0= * (Int64*)(TregMemBuffer + TrightRegister + 2);
1995
	  
1996

1997 1998
	  Uint32 TleftType= TregMemBuffer[theRegister];
	  Int64 Tleft0= * (Int64*)(TregMemBuffer + theRegister + 2);
1999 2000
         
	  if ((TleftType | TrightType) != 0) {
2001 2002 2003
	    Uint64 Tdest0= Tleft0 + Tright0;
	    * (Int64*)(TregMemBuffer+TdestRegister+2)= Tdest0;
	    TregMemBuffer[TdestRegister]= 0x60;
2004 2005 2006 2007 2008 2009 2010 2011 2012
	  } else {
	    return TUPKEY_abort(signal, 20);
	  }
	  break;
	}

      case Interpreter::SUB_REG_REG:
	jam();
	{
2013 2014
	  Uint32 TrightRegister= Interpreter::getReg2(theInstruction) << 2;
	  Uint32 TdestRegister= Interpreter::getReg3(theInstruction) << 2;
2015

2016 2017
	  Uint32 TrightType= TregMemBuffer[TrightRegister];
	  Int64 Tright0= * (Int64*)(TregMemBuffer + TrightRegister + 2);
2018
	  
2019 2020
	  Uint32 TleftType= TregMemBuffer[theRegister];
	  Int64 Tleft0= * (Int64*)(TregMemBuffer + theRegister + 2);
2021 2022
         
	  if ((TleftType | TrightType) != 0) {
2023 2024 2025
	    Int64 Tdest0= Tleft0 - Tright0;
	    * (Int64*)(TregMemBuffer+TdestRegister+2)= Tdest0;
	    TregMemBuffer[TdestRegister]= 0x60;
2026
	  } else {
2027 2028
	    return TUPKEY_abort(signal, 20);
	  }
2029 2030 2031 2032
	  break;
	}

      case Interpreter::BRANCH:
2033
	TprogramCounter= brancher(theInstruction, TprogramCounter);
2034 2035 2036 2037 2038 2039 2040 2041
	break;

      case Interpreter::BRANCH_REG_EQ_NULL:
	if (TregMemBuffer[theRegister] != 0) {
	  jam();
	  continue;
	} else {
	  jam();
2042 2043
	  TprogramCounter= brancher(theInstruction, TprogramCounter);
	}
2044 2045 2046 2047 2048 2049 2050 2051
	break;

      case Interpreter::BRANCH_REG_NE_NULL:
	if (TregMemBuffer[theRegister] == 0) {
	  jam();
	  continue;
	} else {
	  jam();
2052 2053
	  TprogramCounter= brancher(theInstruction, TprogramCounter);
	}
2054 2055 2056 2057 2058
	break;


      case Interpreter::BRANCH_EQ_REG_REG:
	{
2059
	  Uint32 TrightRegister= Interpreter::getReg2(theInstruction) << 2;
2060

2061 2062 2063
	  Uint32 TleftType= TregMemBuffer[theRegister];
	  Uint32 Tleft0= TregMemBuffer[theRegister + 2];
	  Uint32 Tleft1= TregMemBuffer[theRegister + 3];
2064

2065 2066 2067
	  Uint32 TrightType= TregMemBuffer[TrightRegister];
	  Uint32 Tright0= TregMemBuffer[TrightRegister + 2];
	  Uint32 Tright1= TregMemBuffer[TrightRegister + 3];
2068 2069 2070
	  if ((TrightType | TleftType) != 0) {
	    jam();
	    if ((Tleft0 == Tright0) && (Tleft1 == Tright1)) {
2071 2072
	      TprogramCounter= brancher(theInstruction, TprogramCounter);
	    }
2073 2074
	  } else {
	    return TUPKEY_abort(signal, 23);
2075
	  }
2076 2077 2078 2079 2080
	  break;
	}

      case Interpreter::BRANCH_NE_REG_REG:
	{
2081
	  Uint32 TrightRegister= Interpreter::getReg2(theInstruction) << 2;
2082

2083 2084 2085
	  Uint32 TleftType= TregMemBuffer[theRegister];
	  Uint32 Tleft0= TregMemBuffer[theRegister + 2];
	  Uint32 Tleft1= TregMemBuffer[theRegister + 3];
2086

2087 2088 2089
	  Uint32 TrightType= TregMemBuffer[TrightRegister];
	  Uint32 Tright0= TregMemBuffer[TrightRegister + 2];
	  Uint32 Tright1= TregMemBuffer[TrightRegister + 3];
2090 2091 2092
	  if ((TrightType | TleftType) != 0) {
	    jam();
	    if ((Tleft0 != Tright0) || (Tleft1 != Tright1)) {
2093 2094
	      TprogramCounter= brancher(theInstruction, TprogramCounter);
	    }
2095 2096
	  } else {
	    return TUPKEY_abort(signal, 24);
2097
	  }
2098 2099 2100 2101 2102
	  break;
	}

      case Interpreter::BRANCH_LT_REG_REG:
	{
2103
	  Uint32 TrightRegister= Interpreter::getReg2(theInstruction) << 2;
2104

2105 2106
	  Uint32 TrightType= TregMemBuffer[TrightRegister];
	  Int64 Tright0= * (Int64*)(TregMemBuffer + TrightRegister + 2);
2107
	  
2108 2109
	  Uint32 TleftType= TregMemBuffer[theRegister];
	  Int64 Tleft0= * (Int64*)(TregMemBuffer + theRegister + 2);
2110
         
2111 2112 2113

	  if ((TrightType | TleftType) != 0) {
	    jam();
2114
	    if (Tleft0 < Tright0) {
2115 2116
	      TprogramCounter= brancher(theInstruction, TprogramCounter);
	    }
2117 2118
	  } else {
	    return TUPKEY_abort(signal, 24);
2119
	  }
2120 2121 2122 2123 2124
	  break;
	}

      case Interpreter::BRANCH_LE_REG_REG:
	{
2125
	  Uint32 TrightRegister= Interpreter::getReg2(theInstruction) << 2;
2126

2127 2128
	  Uint32 TrightType= TregMemBuffer[TrightRegister];
	  Int64 Tright0= * (Int64*)(TregMemBuffer + TrightRegister + 2);
2129
	  
2130 2131
	  Uint32 TleftType= TregMemBuffer[theRegister];
	  Int64 Tleft0= * (Int64*)(TregMemBuffer + theRegister + 2);
2132
	  
2133 2134 2135

	  if ((TrightType | TleftType) != 0) {
	    jam();
2136
	    if (Tleft0 <= Tright0) {
2137 2138
	      TprogramCounter= brancher(theInstruction, TprogramCounter);
	    }
2139 2140
	  } else {
	    return TUPKEY_abort(signal, 26);
2141
	  }
2142 2143 2144 2145 2146
	  break;
	}

      case Interpreter::BRANCH_GT_REG_REG:
	{
2147
	  Uint32 TrightRegister= Interpreter::getReg2(theInstruction) << 2;
2148

2149 2150
	  Uint32 TrightType= TregMemBuffer[TrightRegister];
	  Int64 Tright0= * (Int64*)(TregMemBuffer + TrightRegister + 2);
2151
	  
2152 2153
	  Uint32 TleftType= TregMemBuffer[theRegister];
	  Int64 Tleft0= * (Int64*)(TregMemBuffer + theRegister + 2);
2154
	  
2155 2156 2157

	  if ((TrightType | TleftType) != 0) {
	    jam();
2158
	    if (Tleft0 > Tright0){
2159 2160
	      TprogramCounter= brancher(theInstruction, TprogramCounter);
	    }
2161 2162
	  } else {
	    return TUPKEY_abort(signal, 27);
2163
	  }
2164 2165 2166 2167 2168
	  break;
	}

      case Interpreter::BRANCH_GE_REG_REG:
	{
2169
	  Uint32 TrightRegister= Interpreter::getReg2(theInstruction) << 2;
2170

2171 2172
	  Uint32 TrightType= TregMemBuffer[TrightRegister];
	  Int64 Tright0= * (Int64*)(TregMemBuffer + TrightRegister + 2);
2173
	  
2174 2175
	  Uint32 TleftType= TregMemBuffer[theRegister];
	  Int64 Tleft0= * (Int64*)(TregMemBuffer + theRegister + 2);
2176
	  
2177 2178 2179

	  if ((TrightType | TleftType) != 0) {
	    jam();
2180
	    if (Tleft0 >= Tright0){
2181 2182
	      TprogramCounter= brancher(theInstruction, TprogramCounter);
	    }
2183 2184
	  } else {
	    return TUPKEY_abort(signal, 28);
2185
	  }
2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
	  break;
	}

      case Interpreter::BRANCH_ATTR_OP_ARG:{
	jam();
	Uint32 cond = Interpreter::getBinaryCondition(theInstruction);
	Uint32 ins2 = TcurrentProgram[TprogramCounter];
	Uint32 attrId = Interpreter::getBranchCol_AttrId(ins2) << 16;
	Uint32 argLen = Interpreter::getBranchCol_Len(ins2);

	if(tmpHabitant != attrId){
2197
	  Int32 TnoDataR = readAttributes(req_struct,
2198
					  &attrId, 1,
2199 2200
					  tmpArea, tmpAreaSz,
                                          false);
2201 2202 2203 2204 2205 2206
	  
	  if (TnoDataR == -1) {
	    jam();
	    tupkeyErrorLab(signal);
	    return -1;
	  }
2207
	  tmpHabitant= attrId;
2208 2209
	}

2210
        // get type
2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223
	attrId >>= 16;
	Uint32 TattrDescrIndex = tabptr.p->tabDescriptor +
	  (attrId << ZAD_LOG_SIZE);
	Uint32 TattrDesc1 = tableDescriptor[TattrDescrIndex].tabDescr;
	Uint32 TattrDesc2 = tableDescriptor[TattrDescrIndex+1].tabDescr;
	Uint32 typeId = AttributeDescriptor::getType(TattrDesc1);
	void * cs = 0;
	if(AttributeOffset::getCharsetFlag(TattrDesc2))
	{
	  Uint32 pos = AttributeOffset::getCharsetPos(TattrDesc2);
	  cs = tabptr.p->charsetArray[pos];
	}
	const NdbSqlUtil::Type& sqlType = NdbSqlUtil::getType(typeId);
2224 2225 2226 2227 2228 2229 2230 2231

        // get data
	AttributeHeader ah(tmpArea[0]);
        const char* s1 = (char*)&tmpArea[1];
        const char* s2 = (char*)&TcurrentProgram[TprogramCounter+1];
        // fixed length in 5.0
	Uint32 attrLen = AttributeDescriptor::getSizeInBytes(TattrDesc1);

2232 2233
	bool r1_null = ah.isNULL();
	bool r2_null = argLen == 0;
2234
	int res1;
2235 2236 2237 2238
        if (cond != Interpreter::LIKE &&
            cond != Interpreter::NOT_LIKE) {
          if (r1_null || r2_null) {
            // NULL==NULL and NULL<not-NULL
2239
            res1 = r1_null && r2_null ? 0 : r1_null ? -1 : 1;
2240
          } else {
2241
            res1 = (*sqlType.m_cmp)(cs, s1, attrLen, s2, argLen, true);
2242 2243 2244 2245
          }
	} else {
          if (r1_null || r2_null) {
            // NULL like NULL is true (has no practical use)
2246
            res1 =  r1_null && r2_null ? 0 : -1;
2247
          } else {
2248
            res1 = (*sqlType.m_like)(cs, s1, attrLen, s2, argLen);
2249
          }
2250 2251
        }

2252
        int res = 0;
2253 2254
        switch ((Interpreter::BinaryCondition)cond) {
        case Interpreter::EQ:
2255
          res = (res1 == 0);
2256 2257
          break;
        case Interpreter::NE:
2258
          res = (res1 != 0);
2259 2260 2261
          break;
        // note the condition is backwards
        case Interpreter::LT:
2262
          res = (res1 > 0);
2263 2264
          break;
        case Interpreter::LE:
2265
          res = (res1 >= 0);
2266 2267
          break;
        case Interpreter::GT:
2268
          res = (res1 < 0);
2269 2270
          break;
        case Interpreter::GE:
2271
          res = (res1 <= 0);
2272 2273
          break;
        case Interpreter::LIKE:
2274
          res = (res1 == 0);
2275 2276
          break;
        case Interpreter::NOT_LIKE:
2277
          res = (res1 == 1);
2278
          break;
2279
	  // XXX handle invalid value
2280 2281
        }
#ifdef TRACE_INTERPRETER
2282 2283 2284
	ndbout_c("cond=%u attr(%d)='%.*s'(%d) str='%.*s'(%d) res1=%d res=%d",
		 cond, attrId >> 16,
                 attrLen, s1, attrLen, argLen, s2, argLen, res1, res);
2285 2286 2287
#endif
        if (res)
          TprogramCounter = brancher(theInstruction, TprogramCounter);
2288 2289 2290
        else 
	{
          Uint32 tmp = ((argLen + 3) >> 2) + 1;
2291 2292 2293 2294
          TprogramCounter += tmp;
        }
	break;
      }
2295
	
2296 2297
      case Interpreter::BRANCH_ATTR_EQ_NULL:{
	jam();
2298 2299
	Uint32 ins2= TcurrentProgram[TprogramCounter];
	Uint32 attrId= Interpreter::getBranchCol_AttrId(ins2) << 16;
2300
	
2301 2302
	if (tmpHabitant != attrId){
	  Int32 TnoDataR= readAttributes(req_struct,
2303
					  &attrId, 1,
2304 2305
					  tmpArea, tmpAreaSz,
                                          false);
2306 2307 2308 2309 2310 2311
	  
	  if (TnoDataR == -1) {
	    jam();
	    tupkeyErrorLab(signal);
	    return -1;
	  }
2312
	  tmpHabitant= attrId;
2313 2314 2315
	}
	
	AttributeHeader ah(tmpArea[0]);
2316 2317
	if (ah.isNULL()){
	  TprogramCounter= brancher(theInstruction, TprogramCounter);
2318 2319 2320 2321 2322 2323 2324 2325
	} else {
	  TprogramCounter ++;
	}
	break;
      }

      case Interpreter::BRANCH_ATTR_NE_NULL:{
	jam();
2326 2327
	Uint32 ins2= TcurrentProgram[TprogramCounter];
	Uint32 attrId= Interpreter::getBranchCol_AttrId(ins2) << 16;
2328
	
2329 2330
	if (tmpHabitant != attrId){
	  Int32 TnoDataR= readAttributes(req_struct,
2331
					  &attrId, 1,
2332 2333
					  tmpArea, tmpAreaSz,
                                          false);
2334 2335 2336 2337 2338 2339
	  
	  if (TnoDataR == -1) {
	    jam();
	    tupkeyErrorLab(signal);
	    return -1;
	  }
2340
	  tmpHabitant= attrId;
2341 2342 2343
	}
	
	AttributeHeader ah(tmpArea[0]);
2344
	if (ah.isNULL()){
2345 2346
	  TprogramCounter ++;
	} else {
2347
	  TprogramCounter= brancher(theInstruction, TprogramCounter);
2348 2349 2350 2351 2352 2353 2354 2355 2356 2357
	}
	break;
      }
	
      case Interpreter::EXIT_OK:
	jam();
#ifdef TRACE_INTERPRETER
	ndbout_c(" - exit_ok");
#endif
	return TdataWritten;
2358 2359 2360

      case Interpreter::EXIT_OK_LAST:
	jam();
joreland@mysql.com's avatar
joreland@mysql.com committed
2361
#ifdef TRACE_INTERPRETER
2362 2363
	ndbout_c(" - exit_ok_last");
#endif
2364
	req_struct->last_row= true;
2365
	return TdataWritten;
2366 2367 2368 2369 2370 2371
	
      case Interpreter::EXIT_REFUSE:
	jam();
#ifdef TRACE_INTERPRETER
	ndbout_c(" - exit_nok");
#endif
2372
	terrorCode= theInstruction >> 16;
2373 2374 2375 2376 2377 2378
	return TUPKEY_abort(signal, 29);

      case Interpreter::CALL:
	jam();
	RstackPtr++;
	if (RstackPtr < 32) {
2379 2380
	  TstackMemBuffer[RstackPtr]= TprogramCounter + 1;
	  TprogramCounter= theInstruction >> 16;
2381
	  if (TprogramCounter < TsubroutineLen) {
2382 2383
	    TcurrentProgram= subroutineProg;
	    TcurrentSize= TsubroutineLen;
2384 2385
	  } else {
	    return TUPKEY_abort(signal, 30);
2386
	  }
2387 2388
	} else {
	  return TUPKEY_abort(signal, 31);
2389
	}
2390 2391 2392 2393 2394
	break;

      case Interpreter::RETURN:
	jam();
	if (RstackPtr > 0) {
2395
	  TprogramCounter= TstackMemBuffer[RstackPtr];
2396 2397 2398 2399 2400 2401
	  RstackPtr--;
	  if (RstackPtr == 0) {
	    jam();
	    /* ------------------------------------------------------------- */
	    // We are back to the main program.
	    /* ------------------------------------------------------------- */
2402 2403 2404
	    TcurrentProgram= mainProgram;
	    TcurrentSize= TmainProgLen;
	  }
2405 2406
	} else {
	  return TUPKEY_abort(signal, 32);
2407
	}
2408 2409 2410 2411
	break;

      default:
	return TUPKEY_abort(signal, 33);
2412
      }
2413 2414
    } else {
      return TUPKEY_abort(signal, 34);
2415 2416
    }
  }
2417
  return TUPKEY_abort(signal, 35);
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
}

/**
 * expand_var_part - copy packed variable attributes to fully expanded size
 * 
 * dst:        where to start writing attribute data
 * dst_off_ptr where to write attribute offsets
 * src         pointer to packed attributes
 * tabDesc     array of attribute descriptors (used for getting max size)
 * no_of_attr  no of atributes to expand
 */
Uint32*
expand_var_part(Dbtup::KeyReqStruct::Var_data *dst, 
		const Uint32* src, 
2432
		const Uint32 * tabDesc, 
2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
		const Uint16* order)
{
  char* dst_ptr= dst->m_data_ptr;
  Uint32 no_attr= dst->m_var_len_offset;
  Uint16* dst_off_ptr= dst->m_offset_array_ptr;
  Uint16* dst_len_ptr= dst_off_ptr + no_attr;
  const Uint16* src_off_ptr= (const Uint16*)src;
  const char* src_ptr= (const char*)(src_off_ptr + no_attr + 1);
  
  Uint16 tmp= *src_off_ptr++, next_pos, len, max_len, dst_off= 0;
  for(Uint32 i = 0; i<no_attr; i++)
  {
    next_pos= *src_off_ptr++;
    len= next_pos - tmp;
    
    *dst_off_ptr++ = dst_off; 
    *dst_len_ptr++ = dst_off + len;
    memcpy(dst_ptr, src_ptr, len);
    src_ptr += len;
    
    max_len= AttributeDescriptor::getSizeInBytes(tabDesc[* order++]);
    dst_ptr += max_len; // Max size
    dst_off += max_len;
    
    tmp= next_pos;
  }
  
  return ALIGN_WORD(dst_ptr);
}

void
Dbtup::expand_tuple(KeyReqStruct* req_struct, 
		    Uint32 sizes[2],
		    Tuple_header* src, 
		    const Tablerec* tabPtrP,
		    bool disk)
{
  Uint32 bits= src->m_header_bits;
  Tuple_header* ptr= req_struct->m_tuple_ptr;
  
  Uint16 dd_tot= tabPtrP->m_no_of_disk_attributes;
  Uint16 mm_vars= tabPtrP->m_attributes[MM].m_no_of_varsize;
  Uint32 fix_size= tabPtrP->m_offsets[MM].m_varpart_offset;
  Uint32 order_desc= tabPtrP->m_real_order_descriptor;

  Uint32 *dst_ptr= ptr->get_var_part_ptr(tabPtrP);
  const Uint32 *disk_ref= src->get_disk_ref_ptr(tabPtrP);
  const Uint32 *src_ptr= src->get_var_part_ptr(tabPtrP);
2481
  const Uint32 * desc= (Uint32*)req_struct->attr_descr;
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
  const Uint16 *order = (Uint16*)(&tableDescriptor[order_desc]);
  order += tabPtrP->m_attributes[MM].m_no_of_fixsize;
  
  if(mm_vars)
  {

    Uint32 step; // in bytes
    const Uint32 *src_data= src_ptr;
    KeyReqStruct::Var_data* dst= &req_struct->m_var_data[MM];
    if(bits & Tuple_header::CHAINED_ROW)
    {
2493
      Ptr<Page> var_page;
2494 2495 2496
      src_data= get_ptr(&var_page, * (Var_part_ref*)src_ptr);
      step= 4;
      sizes[MM]= (2 + (mm_vars << 1) + ((Uint16*)src_data)[mm_vars] + 3) >> 2;
2497
      req_struct->m_varpart_page_ptr = var_page;
2498 2499 2500 2501 2502
    }
    else
    {
      step= (2 + (mm_vars << 1) + ((Uint16*)src_ptr)[mm_vars]);
      sizes[MM]= (step + 3) >> 2;
2503
      req_struct->m_varpart_page_ptr = req_struct->m_page_ptr;
2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544
    }
    dst->m_data_ptr= (char*)(((Uint16*)dst_ptr)+mm_vars+1);
    dst->m_offset_array_ptr= req_struct->var_pos_array;
    dst->m_var_len_offset= mm_vars;
    dst->m_max_var_offset= tabPtrP->m_offsets[MM].m_max_var_offset;
    
    dst_ptr= expand_var_part(dst, src_data, desc, order);
    ndbassert(dst_ptr == ALIGN_WORD(dst->m_data_ptr + dst->m_max_var_offset));
    ndbassert((UintPtr(src_ptr) & 3) == 0);
    src_ptr = ALIGN_WORD(((char*)src_ptr)+step);
    
    sizes[MM] += fix_size + Tuple_header::HeaderSize;
    memcpy(ptr, src, 4*(fix_size + Tuple_header::HeaderSize));
  } 
  else 
  {
    sizes[MM]= 1;
    dst_ptr -= Tuple_header::HeaderSize;
    src_ptr -= Tuple_header::HeaderSize;
    memcpy(ptr, src, 4*fix_size);
  }

  src->m_header_bits= bits & 
    ~(Uint32)(Tuple_header::MM_SHRINK | Tuple_header::MM_GROWN);
  
  sizes[DD]= 0;
  if(disk && dd_tot)
  {
    const Uint16 dd_vars= tabPtrP->m_attributes[DD].m_no_of_varsize;
    order += mm_vars;
    
    if(bits & Tuple_header::DISK_INLINE)
    {
      // Only on copy tuple
      ndbassert((bits & Tuple_header::CHAINED_ROW) == 0);
    }
    else
    {
      Local_key key;
      memcpy(&key, disk_ref, sizeof(key));
      key.m_page_no= req_struct->m_disk_page_ptr.i;
2545
      src_ptr= get_dd_ptr(&req_struct->m_disk_page_ptr, &key, tabPtrP);
2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576
    }
    bits |= Tuple_header::DISK_INLINE;

    // Fix diskpart
    req_struct->m_disk_ptr= (Tuple_header*)dst_ptr;
    memcpy(dst_ptr, src_ptr, 4*tabPtrP->m_offsets[DD].m_fix_header_size);
    sizes[DD] = tabPtrP->m_offsets[DD].m_fix_header_size;
    
    ndbassert(! (req_struct->m_disk_ptr->m_header_bits & Tuple_header::FREE));
    
    if(dd_vars)
    {
      KeyReqStruct::Var_data* dst= &req_struct->m_var_data[DD];
      dst_ptr += tabPtrP->m_offsets[DD].m_varpart_offset;
      src_ptr += tabPtrP->m_offsets[DD].m_varpart_offset;
      order += tabPtrP->m_attributes[DD].m_no_of_fixsize;
      
      dst->m_data_ptr= (char*)(char*)(((Uint16*)dst_ptr)+dd_vars+1);
      dst->m_offset_array_ptr= req_struct->var_pos_array + (mm_vars << 1);
      dst->m_var_len_offset= dd_vars;
      dst->m_max_var_offset= tabPtrP->m_offsets[DD].m_max_var_offset;

      expand_var_part(dst, src_ptr, desc, order);
    }
  }
  
  ptr->m_header_bits= (bits & ~(Uint32)(Tuple_header::CHAINED_ROW));
}

void
Dbtup::prepare_read(KeyReqStruct* req_struct, 
2577
		    Tablerec* tabPtrP, bool disk)
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
{
  Tuple_header* ptr= req_struct->m_tuple_ptr;
  
  Uint32 bits= ptr->m_header_bits;
  Uint16 dd_tot= tabPtrP->m_no_of_disk_attributes;
  Uint16 mm_vars= tabPtrP->m_attributes[MM].m_no_of_varsize;
  
  const Uint32 *src_ptr= ptr->get_var_part_ptr(tabPtrP);
  const Uint32 *disk_ref= ptr->get_disk_ref_ptr(tabPtrP);
  
  if(mm_vars)
  {
    const Uint32 *src_data= src_ptr;
    KeyReqStruct::Var_data* dst= &req_struct->m_var_data[MM];
    if(bits & Tuple_header::CHAINED_ROW)
    {
#if VM_TRACE
      
#endif
      src_data= get_ptr(* (Var_part_ref*)src_ptr);
    }
    dst->m_data_ptr= (char*)(((Uint16*)src_data)+mm_vars+1);
    dst->m_offset_array_ptr= (Uint16*)src_data;
    dst->m_var_len_offset= 1;
    dst->m_max_var_offset= ((Uint16*)src_data)[mm_vars];
    
    // disk part start after varsize (aligned)
    src_ptr = ALIGN_WORD(dst->m_data_ptr + dst->m_max_var_offset);
  } 
  else
  {
    // disk part if after fixsize part...
    src_ptr -= Tuple_header::HeaderSize; 
  }
  
  if(disk && dd_tot)
  {
    const Uint16 dd_vars= tabPtrP->m_attributes[DD].m_no_of_varsize;
    
    if(bits & Tuple_header::DISK_INLINE)
    {
      // Only on copy tuple
      ndbassert((bits & Tuple_header::CHAINED_ROW) == 0);
    }
    else
    {
      // XXX
      Local_key key;
      memcpy(&key, disk_ref, sizeof(key));
      key.m_page_no= req_struct->m_disk_page_ptr.i;
2628
      src_ptr= get_dd_ptr(&req_struct->m_disk_page_ptr, &key, tabPtrP);
2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
    }
    // Fix diskpart
    req_struct->m_disk_ptr= (Tuple_header*)src_ptr;
    ndbassert(! (req_struct->m_disk_ptr->m_header_bits & Tuple_header::FREE));
    if(dd_vars)
    {
      KeyReqStruct::Var_data* dst= &req_struct->m_var_data[DD];
      src_ptr += tabPtrP->m_offsets[DD].m_varpart_offset;
      
      dst->m_data_ptr= (char*)(char*)(((Uint16*)src_ptr)+dd_vars+1);
      dst->m_offset_array_ptr= (Uint16*)src_ptr;
      dst->m_var_len_offset= 1;
      dst->m_max_var_offset= ((Uint16*)src_ptr)[dd_vars];
    }
  }
}
2645

2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704
void
Dbtup::shrink_tuple(KeyReqStruct* req_struct, Uint32 sizes[2],
		    const Tablerec* tabPtrP, bool disk)
{
  ndbassert(tabPtrP->need_shrink());
  Tuple_header* ptr= req_struct->m_tuple_ptr;
  
  Uint16 dd_tot= tabPtrP->m_no_of_disk_attributes;
  Uint16 mm_vars= tabPtrP->m_attributes[MM].m_no_of_varsize;
  Uint16 dd_vars= tabPtrP->m_attributes[DD].m_no_of_varsize;
  
  Uint32 *dst_ptr= ptr->get_var_part_ptr(tabPtrP);
  Uint16* src_off_ptr= req_struct->var_pos_array;

  sizes[MM]= sizes[DD]= 0;
  if(mm_vars)
  {
    Uint16* dst_off_ptr= (Uint16*)dst_ptr;
    char*  dst_data_ptr= (char*)(dst_off_ptr + mm_vars + 1);
    char*  src_data_ptr= dst_data_ptr;
    Uint32 off= 0;
    for(Uint32 i= 0; i<mm_vars; i++)
    {
      const char* data_ptr= src_data_ptr + *src_off_ptr;
      Uint32 len= src_off_ptr[mm_vars] - *src_off_ptr;
      * dst_off_ptr++= off;
      memmove(dst_data_ptr, data_ptr, len);
      off += len;
      src_off_ptr++;
      dst_data_ptr += len;
    }
    *dst_off_ptr= off;
    ndbassert(dst_data_ptr <= ((char*)ptr) + 8192);
    ndbassert((UintPtr(ptr) & 3) == 0);
    sizes[MM]= (dst_data_ptr + 3 - ((char*)ptr)) >> 2;

    dst_ptr = ALIGN_WORD(dst_data_ptr);
  }
  else
  {
    sizes[MM] = 1;
    dst_ptr -= Tuple_header::HeaderSize;
  }
  
  if(disk && dd_tot)
  {
    Uint32 * src_ptr = (Uint32*)req_struct->m_disk_ptr;
    req_struct->m_disk_ptr = (Tuple_header*)dst_ptr;
    if (unlikely(dd_vars))
    {
      abort();
    }
    else
    {
      sizes[DD] = tabPtrP->m_offsets[DD].m_fix_header_size;
      memmove(dst_ptr, src_ptr, 4*tabPtrP->m_offsets[DD].m_fix_header_size);
    }
  }
}
2705

2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726
void
Dbtup::validate_page(Tablerec* regTabPtr, Var_page* p)
{
  Uint32 mm_vars= regTabPtr->m_attributes[MM].m_no_of_varsize;
  Uint32 fix_sz= regTabPtr->m_offsets[MM].m_fix_header_size + 
    Tuple_header::HeaderSize;
    
  if(mm_vars == 0)
    return;
  
  for(Uint32 F= 0; F<MAX_FRAG_PER_NODE; F++)
  {
    FragrecordPtr fragPtr;

    if((fragPtr.i = regTabPtr->fragrec[F]) == RNIL)
      continue;

    ptrCheckGuard(fragPtr, cnoOfFragrec, fragrecord);
    for(Uint32 P= 0; P<fragPtr.p->noOfPages; P++)
    {
      Uint32 real= getRealpid(fragPtr.p, P);
2727
      Var_page* page= (Var_page*)c_page_pool.getPtr(real);
2728 2729 2730

      for(Uint32 i=1; i<page->high_index; i++)
      {
2731 2732 2733
	Uint32 idx= page->get_index_word(i);
	Uint32 len = (idx & Var_page::LEN_MASK) >> Var_page::LEN_SHIFT;
	if(!(idx & Var_page::FREE) && !(idx & Var_page::CHAIN))
2734 2735 2736 2737 2738
	{
	  Tuple_header *ptr= (Tuple_header*)page->get_ptr(i);
	  Uint32 *part= ptr->get_var_part_ptr(regTabPtr);
	  if(ptr->m_header_bits & Tuple_header::CHAINED_ROW)
	  {
2739
	    ndbassert(len == fix_sz + 1);
2740
	    Local_key tmp; tmp.assref(*part);
2741
	    Ptr<Page> tmpPage;
2742
	    part= get_ptr(&tmpPage, *(Var_part_ref*)part);
2743
	    len= ((Var_page*)tmpPage.p)->get_entry_len(tmp.m_page_idx);
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
	    Uint32 sz= ((mm_vars + 1) << 1) + (((Uint16*)part)[mm_vars]);
	    ndbassert(len >= ((sz + 3) >> 2));
	  } 
	  else
	  {
	    Uint32 sz= ((mm_vars + 1) << 1) + (((Uint16*)part)[mm_vars]);
	    ndbassert(len >= ((sz+3)>>2)+fix_sz);
	  }
	  if(ptr->m_operation_ptr_i != RNIL)
	  {
	    c_operation_pool.getPtr(ptr->m_operation_ptr_i);
	  }
	} 
2757
	else if(!(idx & Var_page::FREE))
2758 2759 2760 2761 2762 2763
	{
	  /**
	   * Chain
	   */
	  Uint32 *part= page->get_ptr(i);
	  Uint32 sz= ((mm_vars + 1) << 1) + (((Uint16*)part)[mm_vars]);
2764
	  ndbassert(len >= ((sz + 3) >> 2));
2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
	} 
	else 
	{
	  
	}
      }
      if(p == 0 && page->high_index > 1)
	page->reorg((Var_page*)ctemp_page);
    }
  }
  
  if(p == 0)
  {
    validate_page(regTabPtr, (Var_page*)1);
  }
}

int
Dbtup::handle_size_change_after_update(KeyReqStruct* req_struct,
				       Tuple_header* org,
				       Operationrec* regOperPtr,
				       Fragrecord* regFragPtr,
				       Tablerec* regTabPtr,
				       Uint32 sizes[4])
{
  ndbrequire(sizes[1] == sizes[3]);
  //ndbout_c("%d %d %d %d", sizes[0], sizes[1], sizes[2], sizes[3]);
  if(0)
    printf("%p %d %d - handle_size_change_after_update ",
	   req_struct->m_tuple_ptr,
	   regOperPtr->m_tuple_location.m_page_no,
	   regOperPtr->m_tuple_location.m_page_idx);
  
  Uint32 bits= org->m_header_bits;
  Uint32 copy_bits= req_struct->m_tuple_ptr->m_header_bits;
  Uint32 fix_sz = Tuple_header::HeaderSize + 
    regTabPtr->m_offsets[MM].m_fix_header_size;
  
  if(sizes[MM] == sizes[2+MM])
    ;
  else if(sizes[MM] > sizes[2+MM])
  {
    if(0) ndbout_c("shrink");
    copy_bits |= Tuple_header::MM_SHRINK;
  }
  else
  {
    if(0) printf("grow - ");
2813 2814
    Ptr<Page> pagePtr = req_struct->m_varpart_page_ptr;
    Var_page* pageP= (Var_page*)pagePtr.p;
2815
    Uint32 idx, alloc, needed;
2816 2817 2818 2819 2820 2821 2822
    Uint32 *refptr = org->get_var_part_ptr(regTabPtr);
    ndbassert(bits & Tuple_header::CHAINED_ROW);

    Local_key ref;
    ref.assref(*refptr);
    idx= ref.m_page_idx;
    if (! (copy_bits & Tuple_header::CHAINED_ROW))
2823
    {
2824 2825
      c_page_pool.getPtr(pagePtr, ref.m_page_no);
      pageP = (Var_page*)pagePtr.p;
2826
    }
2827 2828 2829 2830 2831 2832 2833
    alloc= pageP->get_entry_len(idx);
#ifdef VM_TRACE
    if(!pageP->get_entry_chain(idx))
      ndbout << *pageP << endl;
#endif
    ndbassert(pageP->get_entry_chain(idx));
    needed= sizes[2+MM] - fix_sz;
2834 2835 2836
    
    if(needed <= alloc)
    {
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2837
      //ndbassert(!regOperPtr->is_first_operation());
2838 2839 2840 2841
      ndbout_c(" no grow");
      return 0;
    }
    copy_bits |= Tuple_header::MM_GROWN;
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883
    if (unlikely(realloc_var_part(regFragPtr, regTabPtr, pagePtr, 
				  (Var_part_ref*)refptr, alloc, needed)))
      return -1;
  }
  req_struct->m_tuple_ptr->m_header_bits = copy_bits;
  return 0;
}

int
Dbtup::nr_update_gci(Uint32 fragPtrI, const Local_key* key, Uint32 gci)
{
  FragrecordPtr fragPtr;
  fragPtr.i= fragPtrI;
  ptrCheckGuard(fragPtr, cnoOfFragrec, fragrecord);
  TablerecPtr tablePtr;
  tablePtr.i= fragPtr.p->fragTableId;
  ptrCheckGuard(tablePtr, cnoOfTablerec, tablerec);

  if (tablePtr.p->m_bits & Tablerec::TR_RowGCI)
  {
    Local_key tmp = *key;
    PagePtr page_ptr;

    int ret;
    if (tablePtr.p->m_attributes[MM].m_no_of_varsize)
    {
      tablePtr.p->m_offsets[MM].m_fix_header_size += 
	Tuple_header::HeaderSize+1;
      ret = alloc_page(tablePtr.p, fragPtr.p, &page_ptr, tmp.m_page_no);
      tablePtr.p->m_offsets[MM].m_fix_header_size -= 
	Tuple_header::HeaderSize+1;
    } 
    else
    {
      ret = alloc_page(tablePtr.p, fragPtr.p, &page_ptr, tmp.m_page_no);  
    }

    if (ret)
      return -1;
    
    Tuple_header* ptr = (Tuple_header*)
      ((Fix_page*)page_ptr.p)->get_ptr(tmp.m_page_idx, 0);
2884
    
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932
    ndbrequire(ptr->m_header_bits & Tuple_header::FREE);
    *ptr->get_mm_gci(tablePtr.p) = gci;
  }
  return 0;
}

int
Dbtup::nr_read_pk(Uint32 fragPtrI, 
		  const Local_key* key, Uint32* dst, bool& copy)
{
  
  FragrecordPtr fragPtr;
  fragPtr.i= fragPtrI;
  ptrCheckGuard(fragPtr, cnoOfFragrec, fragrecord);
  TablerecPtr tablePtr;
  tablePtr.i= fragPtr.p->fragTableId;
  ptrCheckGuard(tablePtr, cnoOfTablerec, tablerec);

  Local_key tmp = *key;
  Uint32 pages = fragPtr.p->noOfPages;
  
  int ret;
  PagePtr page_ptr;
  if (tablePtr.p->m_attributes[MM].m_no_of_varsize)
  {
    tablePtr.p->m_offsets[MM].m_fix_header_size += Tuple_header::HeaderSize+1;
    ret = alloc_page(tablePtr.p, fragPtr.p, &page_ptr, tmp.m_page_no);
    tablePtr.p->m_offsets[MM].m_fix_header_size -= Tuple_header::HeaderSize+1;
  } 
  else
  {
    ret = alloc_page(tablePtr.p, fragPtr.p, &page_ptr, tmp.m_page_no);  
  }
  if (ret)
    return -1;
  
  KeyReqStruct req_struct;
  Uint32* ptr= ((Fix_page*)page_ptr.p)->get_ptr(key->m_page_idx, 0);
  
  req_struct.m_page_ptr = page_ptr;
  req_struct.m_tuple_ptr = (Tuple_header*)ptr;
  Uint32 bits = req_struct.m_tuple_ptr->m_header_bits;

  ret = 0;
  copy = false;
  if (! (bits & Tuple_header::FREE))
  {
    if (bits & Tuple_header::ALLOC)
2933
    {
2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983
      Uint32 opPtrI= req_struct.m_tuple_ptr->m_operation_ptr_i;
      Operationrec* opPtrP= c_operation_pool.getPtr(opPtrI);
      ndbassert(!opPtrP->m_copy_tuple_location.isNull());
      req_struct.m_tuple_ptr= (Tuple_header*)
	c_undo_buffer.get_ptr(&opPtrP->m_copy_tuple_location);
      copy = true;
    }
    req_struct.check_offset[MM]= tablePtr.p->get_check_offset(MM);
    req_struct.check_offset[DD]= tablePtr.p->get_check_offset(DD);
    
    Uint32 num_attr= tablePtr.p->m_no_of_attributes;
    Uint32 descr_start= tablePtr.p->tabDescriptor;
    TableDescriptor *tab_descr= &tableDescriptor[descr_start];
    ndbrequire(descr_start + (num_attr << ZAD_LOG_SIZE) <= cnoOfTabDescrRec);
    req_struct.attr_descr= tab_descr; 

    if (tablePtr.p->need_expand())
      prepare_read(&req_struct, tablePtr.p, false);
    
    const Uint32* attrIds= &tableDescriptor[tablePtr.p->readKeyArray].tabDescr;
    const Uint32 numAttrs= tablePtr.p->noOfKeyAttr;
    // read pk attributes from original tuple
    
    // new globals
    tabptr= tablePtr;
    fragptr= fragPtr;
    operPtr.i= RNIL;
    operPtr.p= NULL;
    
    // do it
    ret = readAttributes(&req_struct,
			 attrIds,
			 numAttrs,
			 dst,
			 ZNIL, false);
    
    // done
    if (likely(ret != -1)) {
      // remove headers
      Uint32 n= 0;
      Uint32 i= 0;
      while (n < numAttrs) {
	const AttributeHeader ah(dst[i]);
	Uint32 size= ah.getDataSize();
	ndbrequire(size != 0);
	for (Uint32 j= 0; j < size; j++) {
	  dst[i + j - n]= dst[i + j + 1];
	}
	n+= 1;
	i+= 1 + size;
2984
      }
2985 2986 2987 2988
      ndbrequire((int)i == ret);
      ret -= numAttrs;
    } else {
      return terrorCode ? (-(int)terrorCode) : -1;
2989
    }
2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 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 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067
  }
    
  if (tablePtr.p->m_bits & Tablerec::TR_RowGCI)
  {
    dst[ret] = *req_struct.m_tuple_ptr->get_mm_gci(tablePtr.p);
  }
  else
  {
    dst[ret] = 0;
  }
  return ret;
}

#include <signaldata/TuxMaint.hpp>

int
Dbtup::nr_delete(Signal* signal, Uint32 senderData,
		 Uint32 fragPtrI, const Local_key* key, Uint32 gci)
{
  FragrecordPtr fragPtr;
  fragPtr.i= fragPtrI;
  ptrCheckGuard(fragPtr, cnoOfFragrec, fragrecord);
  TablerecPtr tablePtr;
  tablePtr.i= fragPtr.p->fragTableId;
  ptrCheckGuard(tablePtr, cnoOfTablerec, tablerec);

  Local_key tmp = * key;
  tmp.m_page_no= getRealpid(fragPtr.p, tmp.m_page_no); 
  
  PagePtr pagePtr;
  Tuple_header* ptr= (Tuple_header*)get_ptr(&pagePtr, &tmp, tablePtr.p);

  if (!tablePtr.p->tuxCustomTriggers.isEmpty()) 
  {
    jam();
    TuxMaintReq* req = (TuxMaintReq*)signal->getDataPtrSend();
    req->tableId = fragPtr.p->fragTableId;
    req->fragId = fragPtr.p->fragmentId;
    req->pageId = tmp.m_page_no;
    req->pageIndex = tmp.m_page_idx;
    req->tupVersion = ptr->get_tuple_version();
    req->opInfo = TuxMaintReq::OpRemove;
    removeTuxEntries(signal, tablePtr.p);
  }
  
  Local_key disk;
  memcpy(&disk, ptr->get_disk_ref_ptr(tablePtr.p), sizeof(disk));
  
  if (tablePtr.p->m_attributes[MM].m_no_of_varsize)
  {
    jam();
    free_var_rec(fragPtr.p, tablePtr.p, &tmp, pagePtr);
  } else {
    jam();
    free_fix_rec(fragPtr.p, tablePtr.p, &tmp, (Fix_page*)pagePtr.p);
  }

  if (tablePtr.p->m_no_of_disk_attributes)
  {
    jam();

    Uint32 sz = (sizeof(Dbtup::Disk_undo::Free) >> 2) + 
      tablePtr.p->m_offsets[DD].m_fix_header_size - 1;
    
    int res = c_lgman->alloc_log_space(fragPtr.p->m_logfile_group_id, sz);
    ndbrequire(res == 0);
    
    /**
     * 1) alloc log buffer
     * 2) get page
     * 3) get log buffer
     * 4) delete tuple
     */
    Page_cache_client::Request preq;
    preq.m_page = disk;
    preq.m_callback.m_callbackData = senderData;
    preq.m_callback.m_callbackFunction =
      safe_cast(&Dbtup::nr_delete_page_callback);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
3068
    int flags = Page_cache_client::COMMIT_REQ;
3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097
    
#ifdef ERROR_INSERT
    if (ERROR_INSERTED(4023) || ERROR_INSERTED(4024))
    {
      int rnd = rand() % 100;
      int slp = 0;
      if (ERROR_INSERTED(4024))
      {
	slp = 3000;
      }
      else if (rnd > 90)
      {
	slp = 3000;
      }
      else if (rnd > 70)
      {
	slp = 100;
      }
      
      ndbout_c("rnd: %d slp: %d", rnd, slp);
      
      if (slp)
      {
	flags |= Page_cache_client::DELAY_REQ;
	preq.m_delay_until_time = NdbTick_CurrentMillisecond()+(Uint64)slp;
      }
    }
#endif
    
3098 3099
    res = m_pgman.get_page(signal, preq, flags);
    if (res == 0)
3100
    {
3101 3102 3103 3104 3105 3106
      goto timeslice;
    }
    else if (unlikely(res == -1))
    {
      return -1;
    }
3107

3108
    PagePtr disk_page = *(PagePtr*)&m_pgman.m_ptr;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
3109
    disk_page_set_dirty(disk_page);
3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121

    preq.m_callback.m_callbackFunction =
      safe_cast(&Dbtup::nr_delete_logbuffer_callback);      
    Logfile_client lgman(this, c_lgman, fragPtr.p->m_logfile_group_id);
    res= lgman.get_log_buffer(signal, sz, &preq.m_callback);
    switch(res){
    case 0:
      signal->theData[2] = disk_page.i;
      goto timeslice;
    case -1:
      ndbrequire("NOT YET IMPLEMENTED" == 0);
      break;
3122
    }
3123 3124 3125 3126 3127

    ndbout << "DIRECT DISK DELETE: " << disk << endl;
    disk_page_free(signal, tablePtr.p, fragPtr.p,
		   &disk, *(PagePtr*)&disk_page, gci);
    return 0;
3128
  }
3129
  
3130
  return 0;
3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143

timeslice:
  memcpy(signal->theData, &disk, sizeof(disk));
  return 1;
}

void
Dbtup::nr_delete_page_callback(Signal* signal, 
			       Uint32 userpointer, Uint32 page_id)
{
  Ptr<GlobalPage> gpage;
  m_global_page_pool.getPtr(gpage, page_id);
  PagePtr pagePtr= *(PagePtr*)&gpage;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
3144
  disk_page_set_dirty(pagePtr);
3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213
  Dblqh::Nr_op_info op;
  op.m_ptr_i = userpointer;
  op.m_disk_ref.m_page_no = pagePtr.p->m_page_no;
  op.m_disk_ref.m_file_no = pagePtr.p->m_file_no;
  c_lqh->get_nr_op_info(&op, page_id);

  Ptr<Fragrecord> fragPtr;
  fragPtr.i= op.m_tup_frag_ptr_i;
  ptrCheckGuard(fragPtr, cnoOfFragrec, fragrecord);

  Ptr<Tablerec> tablePtr;
  tablePtr.i = fragPtr.p->fragTableId;
  ptrCheckGuard(tablePtr, cnoOfTablerec, tablerec);
  
  Uint32 sz = (sizeof(Dbtup::Disk_undo::Free) >> 2) + 
    tablePtr.p->m_offsets[DD].m_fix_header_size - 1;
  
  Callback cb;
  cb.m_callbackData = userpointer;
  cb.m_callbackFunction =
    safe_cast(&Dbtup::nr_delete_logbuffer_callback);      
  Logfile_client lgman(this, c_lgman, fragPtr.p->m_logfile_group_id);
  int res= lgman.get_log_buffer(signal, sz, &cb);
  switch(res){
  case 0:
    return;
  case -1:
    ndbrequire("NOT YET IMPLEMENTED" == 0);
    break;
  }
    
  ndbout << "PAGE CALLBACK DISK DELETE: " << op.m_disk_ref << endl;
  disk_page_free(signal, tablePtr.p, fragPtr.p,
		 &op.m_disk_ref, pagePtr, op.m_gci);
  
  c_lqh->nr_delete_complete(signal, &op);
  return;
}

void
Dbtup::nr_delete_logbuffer_callback(Signal* signal, 
				    Uint32 userpointer, 
				    Uint32 unused)
{
  Dblqh::Nr_op_info op;
  op.m_ptr_i = userpointer;
  c_lqh->get_nr_op_info(&op, RNIL);
  
  Ptr<Fragrecord> fragPtr;
  fragPtr.i= op.m_tup_frag_ptr_i;
  ptrCheckGuard(fragPtr, cnoOfFragrec, fragrecord);

  Ptr<Tablerec> tablePtr;
  tablePtr.i = fragPtr.p->fragTableId;
  ptrCheckGuard(tablePtr, cnoOfTablerec, tablerec);

  Ptr<GlobalPage> gpage;
  m_global_page_pool.getPtr(gpage, op.m_page_id);
  PagePtr pagePtr= *(PagePtr*)&gpage;

  /**
   * reset page no
   */
  ndbout << "LOGBUFFER CALLBACK DISK DELETE: " << op.m_disk_ref << endl;
  
  disk_page_free(signal, tablePtr.p, fragPtr.p,
		 &op.m_disk_ref, pagePtr, op.m_gci);
  
  c_lqh->nr_delete_complete(signal, &op);
3214
}