You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4593 lines
162 KiB

26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
WL#3817: Simplify string / memory area types and make things more consistent (first part) The following type conversions was done: - Changed byte to uchar - Changed gptr to uchar* - Change my_string to char * - Change my_size_t to size_t - Change size_s to size_t Removed declaration of byte, gptr, my_string, my_size_t and size_s. Following function parameter changes was done: - All string functions in mysys/strings was changed to use size_t instead of uint for string lengths. - All read()/write() functions changed to use size_t (including vio). - All protocoll functions changed to use size_t instead of uint - Functions that used a pointer to a string length was changed to use size_t* - Changed malloc(), free() and related functions from using gptr to use void * as this requires fewer casts in the code and is more in line with how the standard functions work. - Added extra length argument to dirname_part() to return the length of the created string. - Changed (at least) following functions to take uchar* as argument: - db_dump() - my_net_write() - net_write_command() - net_store_data() - DBUG_DUMP() - decimal2bin() & bin2decimal() - Changed my_compress() and my_uncompress() to use size_t. Changed one argument to my_uncompress() from a pointer to a value as we only return one value (makes function easier to use). - Changed type of 'pack_data' argument to packfrm() to avoid casts. - Changed in readfrm() and writefrom(), ha_discover and handler::discover() the type for argument 'frmdata' to uchar** to avoid casts. - Changed most Field functions to use uchar* instead of char* (reduced a lot of casts). - Changed field->val_xxx(xxx, new_ptr) to take const pointers. Other changes: - Removed a lot of not needed casts - Added a few new cast required by other changes - Added some cast to my_multi_malloc() arguments for safety (as string lengths needs to be uint, not size_t). - Fixed all calls to hash-get-key functions to use size_t*. (Needed to be done explicitely as this conflict was often hided by casting the function to hash_get_key). - Changed some buffers to memory regions to uchar* to avoid casts. - Changed some string lengths from uint to size_t. - Changed field->ptr to be uchar* instead of char*. This allowed us to get rid of a lot of casts. - Some changes from true -> TRUE, false -> FALSE, unsigned char -> uchar - Include zlib.h in some files as we needed declaration of crc32() - Changed MY_FILE_ERROR to be (size_t) -1. - Changed many variables to hold the result of my_read() / my_write() to be size_t. This was needed to properly detect errors (which are returned as (size_t) -1). - Removed some very old VMS code - Changed packfrm()/unpackfrm() to not be depending on uint size (portability fix) - Removed windows specific code to restore cursor position as this causes slowdown on windows and we should not mix read() and pread() calls anyway as this is not thread safe. Updated function comment to reflect this. Changed function that depended on original behavior of my_pwrite() to itself restore the cursor position (one such case). - Added some missing checking of return value of malloc(). - Changed definition of MOD_PAD_CHAR_TO_FULL_LENGTH to avoid 'long' overflow. - Changed type of table_def::m_size from my_size_t to ulong to reflect that m_size is the number of elements in the array, not a string/memory length. - Moved THD::max_row_length() to table.cc (as it's not depending on THD). Inlined max_row_length_blob() into this function. - More function comments - Fixed some compiler warnings when compiled without partitions. - Removed setting of LEX_STRING() arguments in declaration (portability fix). - Some trivial indentation/variable name changes. - Some trivial code simplifications: - Replaced some calls to alloc_root + memcpy to use strmake_root()/strdup_root(). - Changed some calls from memdup() to strmake() (Safety fix) - Simpler loops in client-simple.c
19 years ago
Fixed compiler warnings Fixed compile-pentium64 scripts Fixed wrong estimate of update_with_key_prefix in sql-bench Merge bk-internal.mysql.com:/home/bk/mysql-5.1 into mysql.com:/home/my/mysql-5.1 Fixed unsafe define of uint4korr() Fixed that --extern works with mysql-test-run.pl Small trivial cleanups This also fixes a bug in counting number of rows that are updated when we have many simultanous queries Move all connection handling and command exectuion main loop from sql_parse.cc to sql_connection.cc Split handle_one_connection() into reusable sub functions. Split create_new_thread() into reusable sub functions. Added thread_scheduler; Preliminary interface code for future thread_handling code. Use 'my_thread_id' for internal thread id's Make thr_alarm_kill() to depend on thread_id instead of thread Make thr_abort_locks_for_thread() depend on thread_id instead of thread In store_globals(), set my_thread_var->id to be thd->thread_id. Use my_thread_var->id as basis for my_thread_name() The above changes makes the connection we have between THD and threads more soft. Added a lot of DBUG_PRINT() and DBUG_ASSERT() functions Fixed compiler warnings Fixed core dumps when running with --debug Removed setting of signal masks (was never used) Made event code call pthread_exit() (portability fix) Fixed that event code doesn't call DBUG_xxx functions before my_thread_init() is called. Made handling of thread_id and thd->variables.pseudo_thread_id uniform. Removed one common 'not freed memory' warning from mysqltest Fixed a couple of usage of not initialized warnings (unlikely cases) Suppress compiler warnings from bdb and (for the moment) warnings from ndb
19 years ago
25 years ago
25 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
Bug#34043: Server loops excessively in _checkchunk() when safemalloc is enabled Essentially, the problem is that safemalloc is excruciatingly slow as it checks all allocated blocks for overrun at each memory management primitive, yielding a almost exponential slowdown for the memory management functions (malloc, realloc, free). The overrun check basically consists of verifying some bytes of a block for certain magic keys, which catches some simple forms of overrun. Another minor problem is violation of aliasing rules and that its own internal list of blocks is prone to corruption. Another issue with safemalloc is rather the maintenance cost as the tool has a significant impact on the server code. Given the magnitude of memory debuggers available nowadays, especially those that are provided with the platform malloc implementation, maintenance of a in-house and largely obsolete memory debugger becomes a burden that is not worth the effort due to its slowness and lack of support for detecting more common forms of heap corruption. Since there are third-party tools that can provide the same functionality at a lower or comparable performance cost, the solution is to simply remove safemalloc. Third-party tools can provide the same functionality at a lower or comparable performance cost. The removal of safemalloc also allows a simplification of the malloc wrappers, removing quite a bit of kludge: redefinition of my_malloc, my_free and the removal of the unused second argument of my_free. Since free() always check whether the supplied pointer is null, redudant checks are also removed. Also, this patch adds unit testing for my_malloc and moves my_realloc implementation into the same file as the other memory allocation primitives.
16 years ago
26 years ago
26 years ago
26 years ago
WL#3817: Simplify string / memory area types and make things more consistent (first part) The following type conversions was done: - Changed byte to uchar - Changed gptr to uchar* - Change my_string to char * - Change my_size_t to size_t - Change size_s to size_t Removed declaration of byte, gptr, my_string, my_size_t and size_s. Following function parameter changes was done: - All string functions in mysys/strings was changed to use size_t instead of uint for string lengths. - All read()/write() functions changed to use size_t (including vio). - All protocoll functions changed to use size_t instead of uint - Functions that used a pointer to a string length was changed to use size_t* - Changed malloc(), free() and related functions from using gptr to use void * as this requires fewer casts in the code and is more in line with how the standard functions work. - Added extra length argument to dirname_part() to return the length of the created string. - Changed (at least) following functions to take uchar* as argument: - db_dump() - my_net_write() - net_write_command() - net_store_data() - DBUG_DUMP() - decimal2bin() & bin2decimal() - Changed my_compress() and my_uncompress() to use size_t. Changed one argument to my_uncompress() from a pointer to a value as we only return one value (makes function easier to use). - Changed type of 'pack_data' argument to packfrm() to avoid casts. - Changed in readfrm() and writefrom(), ha_discover and handler::discover() the type for argument 'frmdata' to uchar** to avoid casts. - Changed most Field functions to use uchar* instead of char* (reduced a lot of casts). - Changed field->val_xxx(xxx, new_ptr) to take const pointers. Other changes: - Removed a lot of not needed casts - Added a few new cast required by other changes - Added some cast to my_multi_malloc() arguments for safety (as string lengths needs to be uint, not size_t). - Fixed all calls to hash-get-key functions to use size_t*. (Needed to be done explicitely as this conflict was often hided by casting the function to hash_get_key). - Changed some buffers to memory regions to uchar* to avoid casts. - Changed some string lengths from uint to size_t. - Changed field->ptr to be uchar* instead of char*. This allowed us to get rid of a lot of casts. - Some changes from true -> TRUE, false -> FALSE, unsigned char -> uchar - Include zlib.h in some files as we needed declaration of crc32() - Changed MY_FILE_ERROR to be (size_t) -1. - Changed many variables to hold the result of my_read() / my_write() to be size_t. This was needed to properly detect errors (which are returned as (size_t) -1). - Removed some very old VMS code - Changed packfrm()/unpackfrm() to not be depending on uint size (portability fix) - Removed windows specific code to restore cursor position as this causes slowdown on windows and we should not mix read() and pread() calls anyway as this is not thread safe. Updated function comment to reflect this. Changed function that depended on original behavior of my_pwrite() to itself restore the cursor position (one such case). - Added some missing checking of return value of malloc(). - Changed definition of MOD_PAD_CHAR_TO_FULL_LENGTH to avoid 'long' overflow. - Changed type of table_def::m_size from my_size_t to ulong to reflect that m_size is the number of elements in the array, not a string/memory length. - Moved THD::max_row_length() to table.cc (as it's not depending on THD). Inlined max_row_length_blob() into this function. - More function comments - Fixed some compiler warnings when compiled without partitions. - Removed setting of LEX_STRING() arguments in declaration (portability fix). - Some trivial indentation/variable name changes. - Some trivial code simplifications: - Replaced some calls to alloc_root + memcpy to use strmake_root()/strdup_root(). - Changed some calls from memdup() to strmake() (Safety fix) - Simpler loops in client-simple.c
19 years ago
WL#3817: Simplify string / memory area types and make things more consistent (first part) The following type conversions was done: - Changed byte to uchar - Changed gptr to uchar* - Change my_string to char * - Change my_size_t to size_t - Change size_s to size_t Removed declaration of byte, gptr, my_string, my_size_t and size_s. Following function parameter changes was done: - All string functions in mysys/strings was changed to use size_t instead of uint for string lengths. - All read()/write() functions changed to use size_t (including vio). - All protocoll functions changed to use size_t instead of uint - Functions that used a pointer to a string length was changed to use size_t* - Changed malloc(), free() and related functions from using gptr to use void * as this requires fewer casts in the code and is more in line with how the standard functions work. - Added extra length argument to dirname_part() to return the length of the created string. - Changed (at least) following functions to take uchar* as argument: - db_dump() - my_net_write() - net_write_command() - net_store_data() - DBUG_DUMP() - decimal2bin() & bin2decimal() - Changed my_compress() and my_uncompress() to use size_t. Changed one argument to my_uncompress() from a pointer to a value as we only return one value (makes function easier to use). - Changed type of 'pack_data' argument to packfrm() to avoid casts. - Changed in readfrm() and writefrom(), ha_discover and handler::discover() the type for argument 'frmdata' to uchar** to avoid casts. - Changed most Field functions to use uchar* instead of char* (reduced a lot of casts). - Changed field->val_xxx(xxx, new_ptr) to take const pointers. Other changes: - Removed a lot of not needed casts - Added a few new cast required by other changes - Added some cast to my_multi_malloc() arguments for safety (as string lengths needs to be uint, not size_t). - Fixed all calls to hash-get-key functions to use size_t*. (Needed to be done explicitely as this conflict was often hided by casting the function to hash_get_key). - Changed some buffers to memory regions to uchar* to avoid casts. - Changed some string lengths from uint to size_t. - Changed field->ptr to be uchar* instead of char*. This allowed us to get rid of a lot of casts. - Some changes from true -> TRUE, false -> FALSE, unsigned char -> uchar - Include zlib.h in some files as we needed declaration of crc32() - Changed MY_FILE_ERROR to be (size_t) -1. - Changed many variables to hold the result of my_read() / my_write() to be size_t. This was needed to properly detect errors (which are returned as (size_t) -1). - Removed some very old VMS code - Changed packfrm()/unpackfrm() to not be depending on uint size (portability fix) - Removed windows specific code to restore cursor position as this causes slowdown on windows and we should not mix read() and pread() calls anyway as this is not thread safe. Updated function comment to reflect this. Changed function that depended on original behavior of my_pwrite() to itself restore the cursor position (one such case). - Added some missing checking of return value of malloc(). - Changed definition of MOD_PAD_CHAR_TO_FULL_LENGTH to avoid 'long' overflow. - Changed type of table_def::m_size from my_size_t to ulong to reflect that m_size is the number of elements in the array, not a string/memory length. - Moved THD::max_row_length() to table.cc (as it's not depending on THD). Inlined max_row_length_blob() into this function. - More function comments - Fixed some compiler warnings when compiled without partitions. - Removed setting of LEX_STRING() arguments in declaration (portability fix). - Some trivial indentation/variable name changes. - Some trivial code simplifications: - Replaced some calls to alloc_root + memcpy to use strmake_root()/strdup_root(). - Changed some calls from memdup() to strmake() (Safety fix) - Simpler loops in client-simple.c
19 years ago
WL#3817: Simplify string / memory area types and make things more consistent (first part) The following type conversions was done: - Changed byte to uchar - Changed gptr to uchar* - Change my_string to char * - Change my_size_t to size_t - Change size_s to size_t Removed declaration of byte, gptr, my_string, my_size_t and size_s. Following function parameter changes was done: - All string functions in mysys/strings was changed to use size_t instead of uint for string lengths. - All read()/write() functions changed to use size_t (including vio). - All protocoll functions changed to use size_t instead of uint - Functions that used a pointer to a string length was changed to use size_t* - Changed malloc(), free() and related functions from using gptr to use void * as this requires fewer casts in the code and is more in line with how the standard functions work. - Added extra length argument to dirname_part() to return the length of the created string. - Changed (at least) following functions to take uchar* as argument: - db_dump() - my_net_write() - net_write_command() - net_store_data() - DBUG_DUMP() - decimal2bin() & bin2decimal() - Changed my_compress() and my_uncompress() to use size_t. Changed one argument to my_uncompress() from a pointer to a value as we only return one value (makes function easier to use). - Changed type of 'pack_data' argument to packfrm() to avoid casts. - Changed in readfrm() and writefrom(), ha_discover and handler::discover() the type for argument 'frmdata' to uchar** to avoid casts. - Changed most Field functions to use uchar* instead of char* (reduced a lot of casts). - Changed field->val_xxx(xxx, new_ptr) to take const pointers. Other changes: - Removed a lot of not needed casts - Added a few new cast required by other changes - Added some cast to my_multi_malloc() arguments for safety (as string lengths needs to be uint, not size_t). - Fixed all calls to hash-get-key functions to use size_t*. (Needed to be done explicitely as this conflict was often hided by casting the function to hash_get_key). - Changed some buffers to memory regions to uchar* to avoid casts. - Changed some string lengths from uint to size_t. - Changed field->ptr to be uchar* instead of char*. This allowed us to get rid of a lot of casts. - Some changes from true -> TRUE, false -> FALSE, unsigned char -> uchar - Include zlib.h in some files as we needed declaration of crc32() - Changed MY_FILE_ERROR to be (size_t) -1. - Changed many variables to hold the result of my_read() / my_write() to be size_t. This was needed to properly detect errors (which are returned as (size_t) -1). - Removed some very old VMS code - Changed packfrm()/unpackfrm() to not be depending on uint size (portability fix) - Removed windows specific code to restore cursor position as this causes slowdown on windows and we should not mix read() and pread() calls anyway as this is not thread safe. Updated function comment to reflect this. Changed function that depended on original behavior of my_pwrite() to itself restore the cursor position (one such case). - Added some missing checking of return value of malloc(). - Changed definition of MOD_PAD_CHAR_TO_FULL_LENGTH to avoid 'long' overflow. - Changed type of table_def::m_size from my_size_t to ulong to reflect that m_size is the number of elements in the array, not a string/memory length. - Moved THD::max_row_length() to table.cc (as it's not depending on THD). Inlined max_row_length_blob() into this function. - More function comments - Fixed some compiler warnings when compiled without partitions. - Removed setting of LEX_STRING() arguments in declaration (portability fix). - Some trivial indentation/variable name changes. - Some trivial code simplifications: - Replaced some calls to alloc_root + memcpy to use strmake_root()/strdup_root(). - Changed some calls from memdup() to strmake() (Safety fix) - Simpler loops in client-simple.c
19 years ago
WL#3817: Simplify string / memory area types and make things more consistent (first part) The following type conversions was done: - Changed byte to uchar - Changed gptr to uchar* - Change my_string to char * - Change my_size_t to size_t - Change size_s to size_t Removed declaration of byte, gptr, my_string, my_size_t and size_s. Following function parameter changes was done: - All string functions in mysys/strings was changed to use size_t instead of uint for string lengths. - All read()/write() functions changed to use size_t (including vio). - All protocoll functions changed to use size_t instead of uint - Functions that used a pointer to a string length was changed to use size_t* - Changed malloc(), free() and related functions from using gptr to use void * as this requires fewer casts in the code and is more in line with how the standard functions work. - Added extra length argument to dirname_part() to return the length of the created string. - Changed (at least) following functions to take uchar* as argument: - db_dump() - my_net_write() - net_write_command() - net_store_data() - DBUG_DUMP() - decimal2bin() & bin2decimal() - Changed my_compress() and my_uncompress() to use size_t. Changed one argument to my_uncompress() from a pointer to a value as we only return one value (makes function easier to use). - Changed type of 'pack_data' argument to packfrm() to avoid casts. - Changed in readfrm() and writefrom(), ha_discover and handler::discover() the type for argument 'frmdata' to uchar** to avoid casts. - Changed most Field functions to use uchar* instead of char* (reduced a lot of casts). - Changed field->val_xxx(xxx, new_ptr) to take const pointers. Other changes: - Removed a lot of not needed casts - Added a few new cast required by other changes - Added some cast to my_multi_malloc() arguments for safety (as string lengths needs to be uint, not size_t). - Fixed all calls to hash-get-key functions to use size_t*. (Needed to be done explicitely as this conflict was often hided by casting the function to hash_get_key). - Changed some buffers to memory regions to uchar* to avoid casts. - Changed some string lengths from uint to size_t. - Changed field->ptr to be uchar* instead of char*. This allowed us to get rid of a lot of casts. - Some changes from true -> TRUE, false -> FALSE, unsigned char -> uchar - Include zlib.h in some files as we needed declaration of crc32() - Changed MY_FILE_ERROR to be (size_t) -1. - Changed many variables to hold the result of my_read() / my_write() to be size_t. This was needed to properly detect errors (which are returned as (size_t) -1). - Removed some very old VMS code - Changed packfrm()/unpackfrm() to not be depending on uint size (portability fix) - Removed windows specific code to restore cursor position as this causes slowdown on windows and we should not mix read() and pread() calls anyway as this is not thread safe. Updated function comment to reflect this. Changed function that depended on original behavior of my_pwrite() to itself restore the cursor position (one such case). - Added some missing checking of return value of malloc(). - Changed definition of MOD_PAD_CHAR_TO_FULL_LENGTH to avoid 'long' overflow. - Changed type of table_def::m_size from my_size_t to ulong to reflect that m_size is the number of elements in the array, not a string/memory length. - Moved THD::max_row_length() to table.cc (as it's not depending on THD). Inlined max_row_length_blob() into this function. - More function comments - Fixed some compiler warnings when compiled without partitions. - Removed setting of LEX_STRING() arguments in declaration (portability fix). - Some trivial indentation/variable name changes. - Some trivial code simplifications: - Replaced some calls to alloc_root + memcpy to use strmake_root()/strdup_root(). - Changed some calls from memdup() to strmake() (Safety fix) - Simpler loops in client-simple.c
19 years ago
WL#3817: Simplify string / memory area types and make things more consistent (first part) The following type conversions was done: - Changed byte to uchar - Changed gptr to uchar* - Change my_string to char * - Change my_size_t to size_t - Change size_s to size_t Removed declaration of byte, gptr, my_string, my_size_t and size_s. Following function parameter changes was done: - All string functions in mysys/strings was changed to use size_t instead of uint for string lengths. - All read()/write() functions changed to use size_t (including vio). - All protocoll functions changed to use size_t instead of uint - Functions that used a pointer to a string length was changed to use size_t* - Changed malloc(), free() and related functions from using gptr to use void * as this requires fewer casts in the code and is more in line with how the standard functions work. - Added extra length argument to dirname_part() to return the length of the created string. - Changed (at least) following functions to take uchar* as argument: - db_dump() - my_net_write() - net_write_command() - net_store_data() - DBUG_DUMP() - decimal2bin() & bin2decimal() - Changed my_compress() and my_uncompress() to use size_t. Changed one argument to my_uncompress() from a pointer to a value as we only return one value (makes function easier to use). - Changed type of 'pack_data' argument to packfrm() to avoid casts. - Changed in readfrm() and writefrom(), ha_discover and handler::discover() the type for argument 'frmdata' to uchar** to avoid casts. - Changed most Field functions to use uchar* instead of char* (reduced a lot of casts). - Changed field->val_xxx(xxx, new_ptr) to take const pointers. Other changes: - Removed a lot of not needed casts - Added a few new cast required by other changes - Added some cast to my_multi_malloc() arguments for safety (as string lengths needs to be uint, not size_t). - Fixed all calls to hash-get-key functions to use size_t*. (Needed to be done explicitely as this conflict was often hided by casting the function to hash_get_key). - Changed some buffers to memory regions to uchar* to avoid casts. - Changed some string lengths from uint to size_t. - Changed field->ptr to be uchar* instead of char*. This allowed us to get rid of a lot of casts. - Some changes from true -> TRUE, false -> FALSE, unsigned char -> uchar - Include zlib.h in some files as we needed declaration of crc32() - Changed MY_FILE_ERROR to be (size_t) -1. - Changed many variables to hold the result of my_read() / my_write() to be size_t. This was needed to properly detect errors (which are returned as (size_t) -1). - Removed some very old VMS code - Changed packfrm()/unpackfrm() to not be depending on uint size (portability fix) - Removed windows specific code to restore cursor position as this causes slowdown on windows and we should not mix read() and pread() calls anyway as this is not thread safe. Updated function comment to reflect this. Changed function that depended on original behavior of my_pwrite() to itself restore the cursor position (one such case). - Added some missing checking of return value of malloc(). - Changed definition of MOD_PAD_CHAR_TO_FULL_LENGTH to avoid 'long' overflow. - Changed type of table_def::m_size from my_size_t to ulong to reflect that m_size is the number of elements in the array, not a string/memory length. - Moved THD::max_row_length() to table.cc (as it's not depending on THD). Inlined max_row_length_blob() into this function. - More function comments - Fixed some compiler warnings when compiled without partitions. - Removed setting of LEX_STRING() arguments in declaration (portability fix). - Some trivial indentation/variable name changes. - Some trivial code simplifications: - Replaced some calls to alloc_root + memcpy to use strmake_root()/strdup_root(). - Changed some calls from memdup() to strmake() (Safety fix) - Simpler loops in client-simple.c
19 years ago
26 years ago
26 years ago
Bug#34043: Server loops excessively in _checkchunk() when safemalloc is enabled Essentially, the problem is that safemalloc is excruciatingly slow as it checks all allocated blocks for overrun at each memory management primitive, yielding a almost exponential slowdown for the memory management functions (malloc, realloc, free). The overrun check basically consists of verifying some bytes of a block for certain magic keys, which catches some simple forms of overrun. Another minor problem is violation of aliasing rules and that its own internal list of blocks is prone to corruption. Another issue with safemalloc is rather the maintenance cost as the tool has a significant impact on the server code. Given the magnitude of memory debuggers available nowadays, especially those that are provided with the platform malloc implementation, maintenance of a in-house and largely obsolete memory debugger becomes a burden that is not worth the effort due to its slowness and lack of support for detecting more common forms of heap corruption. Since there are third-party tools that can provide the same functionality at a lower or comparable performance cost, the solution is to simply remove safemalloc. Third-party tools can provide the same functionality at a lower or comparable performance cost. The removal of safemalloc also allows a simplification of the malloc wrappers, removing quite a bit of kludge: redefinition of my_malloc, my_free and the removal of the unused second argument of my_free. Since free() always check whether the supplied pointer is null, redudant checks are also removed. Also, this patch adds unit testing for my_malloc and moves my_realloc implementation into the same file as the other memory allocation primitives.
16 years ago
Bug#34043: Server loops excessively in _checkchunk() when safemalloc is enabled Essentially, the problem is that safemalloc is excruciatingly slow as it checks all allocated blocks for overrun at each memory management primitive, yielding a almost exponential slowdown for the memory management functions (malloc, realloc, free). The overrun check basically consists of verifying some bytes of a block for certain magic keys, which catches some simple forms of overrun. Another minor problem is violation of aliasing rules and that its own internal list of blocks is prone to corruption. Another issue with safemalloc is rather the maintenance cost as the tool has a significant impact on the server code. Given the magnitude of memory debuggers available nowadays, especially those that are provided with the platform malloc implementation, maintenance of a in-house and largely obsolete memory debugger becomes a burden that is not worth the effort due to its slowness and lack of support for detecting more common forms of heap corruption. Since there are third-party tools that can provide the same functionality at a lower or comparable performance cost, the solution is to simply remove safemalloc. Third-party tools can provide the same functionality at a lower or comparable performance cost. The removal of safemalloc also allows a simplification of the malloc wrappers, removing quite a bit of kludge: redefinition of my_malloc, my_free and the removal of the unused second argument of my_free. Since free() always check whether the supplied pointer is null, redudant checks are also removed. Also, this patch adds unit testing for my_malloc and moves my_realloc implementation into the same file as the other memory allocation primitives.
16 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
Bug#34043: Server loops excessively in _checkchunk() when safemalloc is enabled Essentially, the problem is that safemalloc is excruciatingly slow as it checks all allocated blocks for overrun at each memory management primitive, yielding a almost exponential slowdown for the memory management functions (malloc, realloc, free). The overrun check basically consists of verifying some bytes of a block for certain magic keys, which catches some simple forms of overrun. Another minor problem is violation of aliasing rules and that its own internal list of blocks is prone to corruption. Another issue with safemalloc is rather the maintenance cost as the tool has a significant impact on the server code. Given the magnitude of memory debuggers available nowadays, especially those that are provided with the platform malloc implementation, maintenance of a in-house and largely obsolete memory debugger becomes a burden that is not worth the effort due to its slowness and lack of support for detecting more common forms of heap corruption. Since there are third-party tools that can provide the same functionality at a lower or comparable performance cost, the solution is to simply remove safemalloc. Third-party tools can provide the same functionality at a lower or comparable performance cost. The removal of safemalloc also allows a simplification of the malloc wrappers, removing quite a bit of kludge: redefinition of my_malloc, my_free and the removal of the unused second argument of my_free. Since free() always check whether the supplied pointer is null, redudant checks are also removed. Also, this patch adds unit testing for my_malloc and moves my_realloc implementation into the same file as the other memory allocation primitives.
16 years ago
Bug#34043: Server loops excessively in _checkchunk() when safemalloc is enabled Essentially, the problem is that safemalloc is excruciatingly slow as it checks all allocated blocks for overrun at each memory management primitive, yielding a almost exponential slowdown for the memory management functions (malloc, realloc, free). The overrun check basically consists of verifying some bytes of a block for certain magic keys, which catches some simple forms of overrun. Another minor problem is violation of aliasing rules and that its own internal list of blocks is prone to corruption. Another issue with safemalloc is rather the maintenance cost as the tool has a significant impact on the server code. Given the magnitude of memory debuggers available nowadays, especially those that are provided with the platform malloc implementation, maintenance of a in-house and largely obsolete memory debugger becomes a burden that is not worth the effort due to its slowness and lack of support for detecting more common forms of heap corruption. Since there are third-party tools that can provide the same functionality at a lower or comparable performance cost, the solution is to simply remove safemalloc. Third-party tools can provide the same functionality at a lower or comparable performance cost. The removal of safemalloc also allows a simplification of the malloc wrappers, removing quite a bit of kludge: redefinition of my_malloc, my_free and the removal of the unused second argument of my_free. Since free() always check whether the supplied pointer is null, redudant checks are also removed. Also, this patch adds unit testing for my_malloc and moves my_realloc implementation into the same file as the other memory allocation primitives.
16 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
WL#3817: Simplify string / memory area types and make things more consistent (first part) The following type conversions was done: - Changed byte to uchar - Changed gptr to uchar* - Change my_string to char * - Change my_size_t to size_t - Change size_s to size_t Removed declaration of byte, gptr, my_string, my_size_t and size_s. Following function parameter changes was done: - All string functions in mysys/strings was changed to use size_t instead of uint for string lengths. - All read()/write() functions changed to use size_t (including vio). - All protocoll functions changed to use size_t instead of uint - Functions that used a pointer to a string length was changed to use size_t* - Changed malloc(), free() and related functions from using gptr to use void * as this requires fewer casts in the code and is more in line with how the standard functions work. - Added extra length argument to dirname_part() to return the length of the created string. - Changed (at least) following functions to take uchar* as argument: - db_dump() - my_net_write() - net_write_command() - net_store_data() - DBUG_DUMP() - decimal2bin() & bin2decimal() - Changed my_compress() and my_uncompress() to use size_t. Changed one argument to my_uncompress() from a pointer to a value as we only return one value (makes function easier to use). - Changed type of 'pack_data' argument to packfrm() to avoid casts. - Changed in readfrm() and writefrom(), ha_discover and handler::discover() the type for argument 'frmdata' to uchar** to avoid casts. - Changed most Field functions to use uchar* instead of char* (reduced a lot of casts). - Changed field->val_xxx(xxx, new_ptr) to take const pointers. Other changes: - Removed a lot of not needed casts - Added a few new cast required by other changes - Added some cast to my_multi_malloc() arguments for safety (as string lengths needs to be uint, not size_t). - Fixed all calls to hash-get-key functions to use size_t*. (Needed to be done explicitely as this conflict was often hided by casting the function to hash_get_key). - Changed some buffers to memory regions to uchar* to avoid casts. - Changed some string lengths from uint to size_t. - Changed field->ptr to be uchar* instead of char*. This allowed us to get rid of a lot of casts. - Some changes from true -> TRUE, false -> FALSE, unsigned char -> uchar - Include zlib.h in some files as we needed declaration of crc32() - Changed MY_FILE_ERROR to be (size_t) -1. - Changed many variables to hold the result of my_read() / my_write() to be size_t. This was needed to properly detect errors (which are returned as (size_t) -1). - Removed some very old VMS code - Changed packfrm()/unpackfrm() to not be depending on uint size (portability fix) - Removed windows specific code to restore cursor position as this causes slowdown on windows and we should not mix read() and pread() calls anyway as this is not thread safe. Updated function comment to reflect this. Changed function that depended on original behavior of my_pwrite() to itself restore the cursor position (one such case). - Added some missing checking of return value of malloc(). - Changed definition of MOD_PAD_CHAR_TO_FULL_LENGTH to avoid 'long' overflow. - Changed type of table_def::m_size from my_size_t to ulong to reflect that m_size is the number of elements in the array, not a string/memory length. - Moved THD::max_row_length() to table.cc (as it's not depending on THD). Inlined max_row_length_blob() into this function. - More function comments - Fixed some compiler warnings when compiled without partitions. - Removed setting of LEX_STRING() arguments in declaration (portability fix). - Some trivial indentation/variable name changes. - Some trivial code simplifications: - Replaced some calls to alloc_root + memcpy to use strmake_root()/strdup_root(). - Changed some calls from memdup() to strmake() (Safety fix) - Simpler loops in client-simple.c
19 years ago
26 years ago
26 years ago
WL#3817: Simplify string / memory area types and make things more consistent (first part) The following type conversions was done: - Changed byte to uchar - Changed gptr to uchar* - Change my_string to char * - Change my_size_t to size_t - Change size_s to size_t Removed declaration of byte, gptr, my_string, my_size_t and size_s. Following function parameter changes was done: - All string functions in mysys/strings was changed to use size_t instead of uint for string lengths. - All read()/write() functions changed to use size_t (including vio). - All protocoll functions changed to use size_t instead of uint - Functions that used a pointer to a string length was changed to use size_t* - Changed malloc(), free() and related functions from using gptr to use void * as this requires fewer casts in the code and is more in line with how the standard functions work. - Added extra length argument to dirname_part() to return the length of the created string. - Changed (at least) following functions to take uchar* as argument: - db_dump() - my_net_write() - net_write_command() - net_store_data() - DBUG_DUMP() - decimal2bin() & bin2decimal() - Changed my_compress() and my_uncompress() to use size_t. Changed one argument to my_uncompress() from a pointer to a value as we only return one value (makes function easier to use). - Changed type of 'pack_data' argument to packfrm() to avoid casts. - Changed in readfrm() and writefrom(), ha_discover and handler::discover() the type for argument 'frmdata' to uchar** to avoid casts. - Changed most Field functions to use uchar* instead of char* (reduced a lot of casts). - Changed field->val_xxx(xxx, new_ptr) to take const pointers. Other changes: - Removed a lot of not needed casts - Added a few new cast required by other changes - Added some cast to my_multi_malloc() arguments for safety (as string lengths needs to be uint, not size_t). - Fixed all calls to hash-get-key functions to use size_t*. (Needed to be done explicitely as this conflict was often hided by casting the function to hash_get_key). - Changed some buffers to memory regions to uchar* to avoid casts. - Changed some string lengths from uint to size_t. - Changed field->ptr to be uchar* instead of char*. This allowed us to get rid of a lot of casts. - Some changes from true -> TRUE, false -> FALSE, unsigned char -> uchar - Include zlib.h in some files as we needed declaration of crc32() - Changed MY_FILE_ERROR to be (size_t) -1. - Changed many variables to hold the result of my_read() / my_write() to be size_t. This was needed to properly detect errors (which are returned as (size_t) -1). - Removed some very old VMS code - Changed packfrm()/unpackfrm() to not be depending on uint size (portability fix) - Removed windows specific code to restore cursor position as this causes slowdown on windows and we should not mix read() and pread() calls anyway as this is not thread safe. Updated function comment to reflect this. Changed function that depended on original behavior of my_pwrite() to itself restore the cursor position (one such case). - Added some missing checking of return value of malloc(). - Changed definition of MOD_PAD_CHAR_TO_FULL_LENGTH to avoid 'long' overflow. - Changed type of table_def::m_size from my_size_t to ulong to reflect that m_size is the number of elements in the array, not a string/memory length. - Moved THD::max_row_length() to table.cc (as it's not depending on THD). Inlined max_row_length_blob() into this function. - More function comments - Fixed some compiler warnings when compiled without partitions. - Removed setting of LEX_STRING() arguments in declaration (portability fix). - Some trivial indentation/variable name changes. - Some trivial code simplifications: - Replaced some calls to alloc_root + memcpy to use strmake_root()/strdup_root(). - Changed some calls from memdup() to strmake() (Safety fix) - Simpler loops in client-simple.c
19 years ago
26 years ago
26 years ago
WL#3817: Simplify string / memory area types and make things more consistent (first part) The following type conversions was done: - Changed byte to uchar - Changed gptr to uchar* - Change my_string to char * - Change my_size_t to size_t - Change size_s to size_t Removed declaration of byte, gptr, my_string, my_size_t and size_s. Following function parameter changes was done: - All string functions in mysys/strings was changed to use size_t instead of uint for string lengths. - All read()/write() functions changed to use size_t (including vio). - All protocoll functions changed to use size_t instead of uint - Functions that used a pointer to a string length was changed to use size_t* - Changed malloc(), free() and related functions from using gptr to use void * as this requires fewer casts in the code and is more in line with how the standard functions work. - Added extra length argument to dirname_part() to return the length of the created string. - Changed (at least) following functions to take uchar* as argument: - db_dump() - my_net_write() - net_write_command() - net_store_data() - DBUG_DUMP() - decimal2bin() & bin2decimal() - Changed my_compress() and my_uncompress() to use size_t. Changed one argument to my_uncompress() from a pointer to a value as we only return one value (makes function easier to use). - Changed type of 'pack_data' argument to packfrm() to avoid casts. - Changed in readfrm() and writefrom(), ha_discover and handler::discover() the type for argument 'frmdata' to uchar** to avoid casts. - Changed most Field functions to use uchar* instead of char* (reduced a lot of casts). - Changed field->val_xxx(xxx, new_ptr) to take const pointers. Other changes: - Removed a lot of not needed casts - Added a few new cast required by other changes - Added some cast to my_multi_malloc() arguments for safety (as string lengths needs to be uint, not size_t). - Fixed all calls to hash-get-key functions to use size_t*. (Needed to be done explicitely as this conflict was often hided by casting the function to hash_get_key). - Changed some buffers to memory regions to uchar* to avoid casts. - Changed some string lengths from uint to size_t. - Changed field->ptr to be uchar* instead of char*. This allowed us to get rid of a lot of casts. - Some changes from true -> TRUE, false -> FALSE, unsigned char -> uchar - Include zlib.h in some files as we needed declaration of crc32() - Changed MY_FILE_ERROR to be (size_t) -1. - Changed many variables to hold the result of my_read() / my_write() to be size_t. This was needed to properly detect errors (which are returned as (size_t) -1). - Removed some very old VMS code - Changed packfrm()/unpackfrm() to not be depending on uint size (portability fix) - Removed windows specific code to restore cursor position as this causes slowdown on windows and we should not mix read() and pread() calls anyway as this is not thread safe. Updated function comment to reflect this. Changed function that depended on original behavior of my_pwrite() to itself restore the cursor position (one such case). - Added some missing checking of return value of malloc(). - Changed definition of MOD_PAD_CHAR_TO_FULL_LENGTH to avoid 'long' overflow. - Changed type of table_def::m_size from my_size_t to ulong to reflect that m_size is the number of elements in the array, not a string/memory length. - Moved THD::max_row_length() to table.cc (as it's not depending on THD). Inlined max_row_length_blob() into this function. - More function comments - Fixed some compiler warnings when compiled without partitions. - Removed setting of LEX_STRING() arguments in declaration (portability fix). - Some trivial indentation/variable name changes. - Some trivial code simplifications: - Replaced some calls to alloc_root + memcpy to use strmake_root()/strdup_root(). - Changed some calls from memdup() to strmake() (Safety fix) - Simpler loops in client-simple.c
19 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
WL#3817: Simplify string / memory area types and make things more consistent (first part) The following type conversions was done: - Changed byte to uchar - Changed gptr to uchar* - Change my_string to char * - Change my_size_t to size_t - Change size_s to size_t Removed declaration of byte, gptr, my_string, my_size_t and size_s. Following function parameter changes was done: - All string functions in mysys/strings was changed to use size_t instead of uint for string lengths. - All read()/write() functions changed to use size_t (including vio). - All protocoll functions changed to use size_t instead of uint - Functions that used a pointer to a string length was changed to use size_t* - Changed malloc(), free() and related functions from using gptr to use void * as this requires fewer casts in the code and is more in line with how the standard functions work. - Added extra length argument to dirname_part() to return the length of the created string. - Changed (at least) following functions to take uchar* as argument: - db_dump() - my_net_write() - net_write_command() - net_store_data() - DBUG_DUMP() - decimal2bin() & bin2decimal() - Changed my_compress() and my_uncompress() to use size_t. Changed one argument to my_uncompress() from a pointer to a value as we only return one value (makes function easier to use). - Changed type of 'pack_data' argument to packfrm() to avoid casts. - Changed in readfrm() and writefrom(), ha_discover and handler::discover() the type for argument 'frmdata' to uchar** to avoid casts. - Changed most Field functions to use uchar* instead of char* (reduced a lot of casts). - Changed field->val_xxx(xxx, new_ptr) to take const pointers. Other changes: - Removed a lot of not needed casts - Added a few new cast required by other changes - Added some cast to my_multi_malloc() arguments for safety (as string lengths needs to be uint, not size_t). - Fixed all calls to hash-get-key functions to use size_t*. (Needed to be done explicitely as this conflict was often hided by casting the function to hash_get_key). - Changed some buffers to memory regions to uchar* to avoid casts. - Changed some string lengths from uint to size_t. - Changed field->ptr to be uchar* instead of char*. This allowed us to get rid of a lot of casts. - Some changes from true -> TRUE, false -> FALSE, unsigned char -> uchar - Include zlib.h in some files as we needed declaration of crc32() - Changed MY_FILE_ERROR to be (size_t) -1. - Changed many variables to hold the result of my_read() / my_write() to be size_t. This was needed to properly detect errors (which are returned as (size_t) -1). - Removed some very old VMS code - Changed packfrm()/unpackfrm() to not be depending on uint size (portability fix) - Removed windows specific code to restore cursor position as this causes slowdown on windows and we should not mix read() and pread() calls anyway as this is not thread safe. Updated function comment to reflect this. Changed function that depended on original behavior of my_pwrite() to itself restore the cursor position (one such case). - Added some missing checking of return value of malloc(). - Changed definition of MOD_PAD_CHAR_TO_FULL_LENGTH to avoid 'long' overflow. - Changed type of table_def::m_size from my_size_t to ulong to reflect that m_size is the number of elements in the array, not a string/memory length. - Moved THD::max_row_length() to table.cc (as it's not depending on THD). Inlined max_row_length_blob() into this function. - More function comments - Fixed some compiler warnings when compiled without partitions. - Removed setting of LEX_STRING() arguments in declaration (portability fix). - Some trivial indentation/variable name changes. - Some trivial code simplifications: - Replaced some calls to alloc_root + memcpy to use strmake_root()/strdup_root(). - Changed some calls from memdup() to strmake() (Safety fix) - Simpler loops in client-simple.c
19 years ago
26 years ago
WL#3817: Simplify string / memory area types and make things more consistent (first part) The following type conversions was done: - Changed byte to uchar - Changed gptr to uchar* - Change my_string to char * - Change my_size_t to size_t - Change size_s to size_t Removed declaration of byte, gptr, my_string, my_size_t and size_s. Following function parameter changes was done: - All string functions in mysys/strings was changed to use size_t instead of uint for string lengths. - All read()/write() functions changed to use size_t (including vio). - All protocoll functions changed to use size_t instead of uint - Functions that used a pointer to a string length was changed to use size_t* - Changed malloc(), free() and related functions from using gptr to use void * as this requires fewer casts in the code and is more in line with how the standard functions work. - Added extra length argument to dirname_part() to return the length of the created string. - Changed (at least) following functions to take uchar* as argument: - db_dump() - my_net_write() - net_write_command() - net_store_data() - DBUG_DUMP() - decimal2bin() & bin2decimal() - Changed my_compress() and my_uncompress() to use size_t. Changed one argument to my_uncompress() from a pointer to a value as we only return one value (makes function easier to use). - Changed type of 'pack_data' argument to packfrm() to avoid casts. - Changed in readfrm() and writefrom(), ha_discover and handler::discover() the type for argument 'frmdata' to uchar** to avoid casts. - Changed most Field functions to use uchar* instead of char* (reduced a lot of casts). - Changed field->val_xxx(xxx, new_ptr) to take const pointers. Other changes: - Removed a lot of not needed casts - Added a few new cast required by other changes - Added some cast to my_multi_malloc() arguments for safety (as string lengths needs to be uint, not size_t). - Fixed all calls to hash-get-key functions to use size_t*. (Needed to be done explicitely as this conflict was often hided by casting the function to hash_get_key). - Changed some buffers to memory regions to uchar* to avoid casts. - Changed some string lengths from uint to size_t. - Changed field->ptr to be uchar* instead of char*. This allowed us to get rid of a lot of casts. - Some changes from true -> TRUE, false -> FALSE, unsigned char -> uchar - Include zlib.h in some files as we needed declaration of crc32() - Changed MY_FILE_ERROR to be (size_t) -1. - Changed many variables to hold the result of my_read() / my_write() to be size_t. This was needed to properly detect errors (which are returned as (size_t) -1). - Removed some very old VMS code - Changed packfrm()/unpackfrm() to not be depending on uint size (portability fix) - Removed windows specific code to restore cursor position as this causes slowdown on windows and we should not mix read() and pread() calls anyway as this is not thread safe. Updated function comment to reflect this. Changed function that depended on original behavior of my_pwrite() to itself restore the cursor position (one such case). - Added some missing checking of return value of malloc(). - Changed definition of MOD_PAD_CHAR_TO_FULL_LENGTH to avoid 'long' overflow. - Changed type of table_def::m_size from my_size_t to ulong to reflect that m_size is the number of elements in the array, not a string/memory length. - Moved THD::max_row_length() to table.cc (as it's not depending on THD). Inlined max_row_length_blob() into this function. - More function comments - Fixed some compiler warnings when compiled without partitions. - Removed setting of LEX_STRING() arguments in declaration (portability fix). - Some trivial indentation/variable name changes. - Some trivial code simplifications: - Replaced some calls to alloc_root + memcpy to use strmake_root()/strdup_root(). - Changed some calls from memdup() to strmake() (Safety fix) - Simpler loops in client-simple.c
19 years ago
WL#3817: Simplify string / memory area types and make things more consistent (first part) The following type conversions was done: - Changed byte to uchar - Changed gptr to uchar* - Change my_string to char * - Change my_size_t to size_t - Change size_s to size_t Removed declaration of byte, gptr, my_string, my_size_t and size_s. Following function parameter changes was done: - All string functions in mysys/strings was changed to use size_t instead of uint for string lengths. - All read()/write() functions changed to use size_t (including vio). - All protocoll functions changed to use size_t instead of uint - Functions that used a pointer to a string length was changed to use size_t* - Changed malloc(), free() and related functions from using gptr to use void * as this requires fewer casts in the code and is more in line with how the standard functions work. - Added extra length argument to dirname_part() to return the length of the created string. - Changed (at least) following functions to take uchar* as argument: - db_dump() - my_net_write() - net_write_command() - net_store_data() - DBUG_DUMP() - decimal2bin() & bin2decimal() - Changed my_compress() and my_uncompress() to use size_t. Changed one argument to my_uncompress() from a pointer to a value as we only return one value (makes function easier to use). - Changed type of 'pack_data' argument to packfrm() to avoid casts. - Changed in readfrm() and writefrom(), ha_discover and handler::discover() the type for argument 'frmdata' to uchar** to avoid casts. - Changed most Field functions to use uchar* instead of char* (reduced a lot of casts). - Changed field->val_xxx(xxx, new_ptr) to take const pointers. Other changes: - Removed a lot of not needed casts - Added a few new cast required by other changes - Added some cast to my_multi_malloc() arguments for safety (as string lengths needs to be uint, not size_t). - Fixed all calls to hash-get-key functions to use size_t*. (Needed to be done explicitely as this conflict was often hided by casting the function to hash_get_key). - Changed some buffers to memory regions to uchar* to avoid casts. - Changed some string lengths from uint to size_t. - Changed field->ptr to be uchar* instead of char*. This allowed us to get rid of a lot of casts. - Some changes from true -> TRUE, false -> FALSE, unsigned char -> uchar - Include zlib.h in some files as we needed declaration of crc32() - Changed MY_FILE_ERROR to be (size_t) -1. - Changed many variables to hold the result of my_read() / my_write() to be size_t. This was needed to properly detect errors (which are returned as (size_t) -1). - Removed some very old VMS code - Changed packfrm()/unpackfrm() to not be depending on uint size (portability fix) - Removed windows specific code to restore cursor position as this causes slowdown on windows and we should not mix read() and pread() calls anyway as this is not thread safe. Updated function comment to reflect this. Changed function that depended on original behavior of my_pwrite() to itself restore the cursor position (one such case). - Added some missing checking of return value of malloc(). - Changed definition of MOD_PAD_CHAR_TO_FULL_LENGTH to avoid 'long' overflow. - Changed type of table_def::m_size from my_size_t to ulong to reflect that m_size is the number of elements in the array, not a string/memory length. - Moved THD::max_row_length() to table.cc (as it's not depending on THD). Inlined max_row_length_blob() into this function. - More function comments - Fixed some compiler warnings when compiled without partitions. - Removed setting of LEX_STRING() arguments in declaration (portability fix). - Some trivial indentation/variable name changes. - Some trivial code simplifications: - Replaced some calls to alloc_root + memcpy to use strmake_root()/strdup_root(). - Changed some calls from memdup() to strmake() (Safety fix) - Simpler loops in client-simple.c
19 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
22 years ago
26 years ago
26 years ago
WL#3817: Simplify string / memory area types and make things more consistent (first part) The following type conversions was done: - Changed byte to uchar - Changed gptr to uchar* - Change my_string to char * - Change my_size_t to size_t - Change size_s to size_t Removed declaration of byte, gptr, my_string, my_size_t and size_s. Following function parameter changes was done: - All string functions in mysys/strings was changed to use size_t instead of uint for string lengths. - All read()/write() functions changed to use size_t (including vio). - All protocoll functions changed to use size_t instead of uint - Functions that used a pointer to a string length was changed to use size_t* - Changed malloc(), free() and related functions from using gptr to use void * as this requires fewer casts in the code and is more in line with how the standard functions work. - Added extra length argument to dirname_part() to return the length of the created string. - Changed (at least) following functions to take uchar* as argument: - db_dump() - my_net_write() - net_write_command() - net_store_data() - DBUG_DUMP() - decimal2bin() & bin2decimal() - Changed my_compress() and my_uncompress() to use size_t. Changed one argument to my_uncompress() from a pointer to a value as we only return one value (makes function easier to use). - Changed type of 'pack_data' argument to packfrm() to avoid casts. - Changed in readfrm() and writefrom(), ha_discover and handler::discover() the type for argument 'frmdata' to uchar** to avoid casts. - Changed most Field functions to use uchar* instead of char* (reduced a lot of casts). - Changed field->val_xxx(xxx, new_ptr) to take const pointers. Other changes: - Removed a lot of not needed casts - Added a few new cast required by other changes - Added some cast to my_multi_malloc() arguments for safety (as string lengths needs to be uint, not size_t). - Fixed all calls to hash-get-key functions to use size_t*. (Needed to be done explicitely as this conflict was often hided by casting the function to hash_get_key). - Changed some buffers to memory regions to uchar* to avoid casts. - Changed some string lengths from uint to size_t. - Changed field->ptr to be uchar* instead of char*. This allowed us to get rid of a lot of casts. - Some changes from true -> TRUE, false -> FALSE, unsigned char -> uchar - Include zlib.h in some files as we needed declaration of crc32() - Changed MY_FILE_ERROR to be (size_t) -1. - Changed many variables to hold the result of my_read() / my_write() to be size_t. This was needed to properly detect errors (which are returned as (size_t) -1). - Removed some very old VMS code - Changed packfrm()/unpackfrm() to not be depending on uint size (portability fix) - Removed windows specific code to restore cursor position as this causes slowdown on windows and we should not mix read() and pread() calls anyway as this is not thread safe. Updated function comment to reflect this. Changed function that depended on original behavior of my_pwrite() to itself restore the cursor position (one such case). - Added some missing checking of return value of malloc(). - Changed definition of MOD_PAD_CHAR_TO_FULL_LENGTH to avoid 'long' overflow. - Changed type of table_def::m_size from my_size_t to ulong to reflect that m_size is the number of elements in the array, not a string/memory length. - Moved THD::max_row_length() to table.cc (as it's not depending on THD). Inlined max_row_length_blob() into this function. - More function comments - Fixed some compiler warnings when compiled without partitions. - Removed setting of LEX_STRING() arguments in declaration (portability fix). - Some trivial indentation/variable name changes. - Some trivial code simplifications: - Replaced some calls to alloc_root + memcpy to use strmake_root()/strdup_root(). - Changed some calls from memdup() to strmake() (Safety fix) - Simpler loops in client-simple.c
19 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
Bug#34043: Server loops excessively in _checkchunk() when safemalloc is enabled Essentially, the problem is that safemalloc is excruciatingly slow as it checks all allocated blocks for overrun at each memory management primitive, yielding a almost exponential slowdown for the memory management functions (malloc, realloc, free). The overrun check basically consists of verifying some bytes of a block for certain magic keys, which catches some simple forms of overrun. Another minor problem is violation of aliasing rules and that its own internal list of blocks is prone to corruption. Another issue with safemalloc is rather the maintenance cost as the tool has a significant impact on the server code. Given the magnitude of memory debuggers available nowadays, especially those that are provided with the platform malloc implementation, maintenance of a in-house and largely obsolete memory debugger becomes a burden that is not worth the effort due to its slowness and lack of support for detecting more common forms of heap corruption. Since there are third-party tools that can provide the same functionality at a lower or comparable performance cost, the solution is to simply remove safemalloc. Third-party tools can provide the same functionality at a lower or comparable performance cost. The removal of safemalloc also allows a simplification of the malloc wrappers, removing quite a bit of kludge: redefinition of my_malloc, my_free and the removal of the unused second argument of my_free. Since free() always check whether the supplied pointer is null, redudant checks are also removed. Also, this patch adds unit testing for my_malloc and moves my_realloc implementation into the same file as the other memory allocation primitives.
16 years ago
26 years ago
26 years ago
Fixed compiler warnings Fixed compile-pentium64 scripts Fixed wrong estimate of update_with_key_prefix in sql-bench Merge bk-internal.mysql.com:/home/bk/mysql-5.1 into mysql.com:/home/my/mysql-5.1 Fixed unsafe define of uint4korr() Fixed that --extern works with mysql-test-run.pl Small trivial cleanups This also fixes a bug in counting number of rows that are updated when we have many simultanous queries Move all connection handling and command exectuion main loop from sql_parse.cc to sql_connection.cc Split handle_one_connection() into reusable sub functions. Split create_new_thread() into reusable sub functions. Added thread_scheduler; Preliminary interface code for future thread_handling code. Use 'my_thread_id' for internal thread id's Make thr_alarm_kill() to depend on thread_id instead of thread Make thr_abort_locks_for_thread() depend on thread_id instead of thread In store_globals(), set my_thread_var->id to be thd->thread_id. Use my_thread_var->id as basis for my_thread_name() The above changes makes the connection we have between THD and threads more soft. Added a lot of DBUG_PRINT() and DBUG_ASSERT() functions Fixed compiler warnings Fixed core dumps when running with --debug Removed setting of signal masks (was never used) Made event code call pthread_exit() (portability fix) Fixed that event code doesn't call DBUG_xxx functions before my_thread_init() is called. Made handling of thread_id and thd->variables.pseudo_thread_id uniform. Removed one common 'not freed memory' warning from mysqltest Fixed a couple of usage of not initialized warnings (unlikely cases) Suppress compiler warnings from bdb and (for the moment) warnings from ndb
19 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
  1. /* Copyright (C) 2000 MySQL AB, 2008-2009 Sun Microsystems, Inc
  2. This program is free software; you can redistribute it and/or modify
  3. it under the terms of the GNU General Public License as published by
  4. the Free Software Foundation; version 2 of the License.
  5. This program is distributed in the hope that it will be useful,
  6. but WITHOUT ANY WARRANTY; without even the implied warranty of
  7. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  8. GNU General Public License for more details.
  9. You should have received a copy of the GNU General Public License
  10. along with this program; if not, write to the Free Software
  11. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
  12. /**
  13. @file
  14. These functions handle keyblock cacheing for ISAM and MyISAM tables.
  15. One cache can handle many files.
  16. It must contain buffers of the same blocksize.
  17. init_key_cache() should be used to init cache handler.
  18. The free list (free_block_list) is a stack like structure.
  19. When a block is freed by free_block(), it is pushed onto the stack.
  20. When a new block is required it is first tried to pop one from the stack.
  21. If the stack is empty, it is tried to get a never-used block from the pool.
  22. If this is empty too, then a block is taken from the LRU ring, flushing it
  23. to disk, if neccessary. This is handled in find_key_block().
  24. With the new free list, the blocks can have three temperatures:
  25. hot, warm and cold (which is free). This is remembered in the block header
  26. by the enum BLOCK_TEMPERATURE temperature variable. Remembering the
  27. temperature is neccessary to correctly count the number of warm blocks,
  28. which is required to decide when blocks are allowed to become hot. Whenever
  29. a block is inserted to another (sub-)chain, we take the old and new
  30. temperature into account to decide if we got one more or less warm block.
  31. blocks_unused is the sum of never used blocks in the pool and of currently
  32. free blocks. blocks_used is the number of blocks fetched from the pool and
  33. as such gives the maximum number of in-use blocks at any time.
  34. */
  35. /*
  36. Key Cache Locking
  37. =================
  38. All key cache locking is done with a single mutex per key cache:
  39. keycache->cache_lock. This mutex is locked almost all the time
  40. when executing code in this file (mf_keycache.c).
  41. However it is released for I/O and some copy operations.
  42. The cache_lock is also released when waiting for some event. Waiting
  43. and signalling is done via condition variables. In most cases the
  44. thread waits on its thread->suspend condition variable. Every thread
  45. has a my_thread_var structure, which contains this variable and a
  46. '*next' and '**prev' pointer. These pointers are used to insert the
  47. thread into a wait queue.
  48. A thread can wait for one block and thus be in one wait queue at a
  49. time only.
  50. Before starting to wait on its condition variable with
  51. mysql_cond_wait(), the thread enters itself to a specific wait queue
  52. with link_into_queue() (double linked with '*next' + '**prev') or
  53. wait_on_queue() (single linked with '*next').
  54. Another thread, when releasing a resource, looks up the waiting thread
  55. in the related wait queue. It sends a signal with
  56. mysql_cond_signal() to the waiting thread.
  57. NOTE: Depending on the particular wait situation, either the sending
  58. thread removes the waiting thread from the wait queue with
  59. unlink_from_queue() or release_whole_queue() respectively, or the waiting
  60. thread removes itself.
  61. There is one exception from this locking scheme when one thread wants
  62. to reuse a block for some other address. This works by first marking
  63. the block reserved (status= BLOCK_IN_SWITCH) and then waiting for all
  64. threads that are reading the block to finish. Each block has a
  65. reference to a condition variable (condvar). It holds a reference to
  66. the thread->suspend condition variable for the waiting thread (if such
  67. a thread exists). When that thread is signaled, the reference is
  68. cleared. The number of readers of a block is registered in
  69. block->hash_link->requests. See wait_for_readers() / remove_reader()
  70. for details. This is similar to the above, but it clearly means that
  71. only one thread can wait for a particular block. There is no queue in
  72. this case. Strangely enough block->convar is used for waiting for the
  73. assigned hash_link only. More precisely it is used to wait for all
  74. requests to be unregistered from the assigned hash_link.
  75. The resize_queue serves two purposes:
  76. 1. Threads that want to do a resize wait there if in_resize is set.
  77. This is not used in the server. The server refuses a second resize
  78. request if one is already active. keycache->in_init is used for the
  79. synchronization. See set_var.cc.
  80. 2. Threads that want to access blocks during resize wait here during
  81. the re-initialization phase.
  82. When the resize is done, all threads on the queue are signalled.
  83. Hypothetical resizers can compete for resizing, and read/write
  84. requests will restart to request blocks from the freshly resized
  85. cache. If the cache has been resized too small, it is disabled and
  86. 'can_be_used' is false. In this case read/write requests bypass the
  87. cache. Since they increment and decrement 'cnt_for_resize_op', the
  88. next resizer can wait on the queue 'waiting_for_resize_cnt' until all
  89. I/O finished.
  90. */
  91. #include "mysys_priv.h"
  92. #include "mysys_err.h"
  93. #include <keycache.h>
  94. #include "my_static.h"
  95. #include <m_string.h>
  96. #include <my_bit.h>
  97. #include <errno.h>
  98. #include <stdarg.h>
  99. #include "probes_mysql.h"
  100. /*
  101. Some compilation flags have been added specifically for this module
  102. to control the following:
  103. - not to let a thread to yield the control when reading directly
  104. from key cache, which might improve performance in many cases;
  105. to enable this add:
  106. #define SERIALIZED_READ_FROM_CACHE
  107. - to set an upper bound for number of threads simultaneously
  108. using the key cache; this setting helps to determine an optimal
  109. size for hash table and improve performance when the number of
  110. blocks in the key cache much less than the number of threads
  111. accessing it;
  112. to set this number equal to <N> add
  113. #define MAX_THREADS <N>
  114. - to substitute calls of mysql_cond_wait for calls of
  115. mysql_cond_timedwait (wait with timeout set up);
  116. this setting should be used only when you want to trap a deadlock
  117. situation, which theoretically should not happen;
  118. to set timeout equal to <T> seconds add
  119. #define KEYCACHE_TIMEOUT <T>
  120. - to enable the module traps and to send debug information from
  121. key cache module to a special debug log add:
  122. #define KEYCACHE_DEBUG
  123. the name of this debug log file <LOG NAME> can be set through:
  124. #define KEYCACHE_DEBUG_LOG <LOG NAME>
  125. if the name is not defined, it's set by default;
  126. if the KEYCACHE_DEBUG flag is not set up and we are in a debug
  127. mode, i.e. when ! defined(DBUG_OFF), the debug information from the
  128. module is sent to the regular debug log.
  129. Example of the settings:
  130. #define SERIALIZED_READ_FROM_CACHE
  131. #define MAX_THREADS 100
  132. #define KEYCACHE_TIMEOUT 1
  133. #define KEYCACHE_DEBUG
  134. #define KEYCACHE_DEBUG_LOG "my_key_cache_debug.log"
  135. */
  136. #define STRUCT_PTR(TYPE, MEMBER, a) \
  137. (TYPE *) ((char *) (a) - offsetof(TYPE, MEMBER))
  138. /* types of condition variables */
  139. #define COND_FOR_REQUESTED 0
  140. #define COND_FOR_SAVED 1
  141. #define COND_FOR_READERS 2
  142. typedef mysql_cond_t KEYCACHE_CONDVAR;
  143. /* descriptor of the page in the key cache block buffer */
  144. struct st_keycache_page
  145. {
  146. int file; /* file to which the page belongs to */
  147. my_off_t filepos; /* position of the page in the file */
  148. };
  149. /* element in the chain of a hash table bucket */
  150. struct st_hash_link
  151. {
  152. struct st_hash_link *next, **prev; /* to connect links in the same bucket */
  153. struct st_block_link *block; /* reference to the block for the page: */
  154. File file; /* from such a file */
  155. my_off_t diskpos; /* with such an offset */
  156. uint requests; /* number of requests for the page */
  157. };
  158. /* simple states of a block */
  159. #define BLOCK_ERROR 1 /* an error occured when performing file i/o */
  160. #define BLOCK_READ 2 /* file block is in the block buffer */
  161. #define BLOCK_IN_SWITCH 4 /* block is preparing to read new page */
  162. #define BLOCK_REASSIGNED 8 /* blk does not accept requests for old page */
  163. #define BLOCK_IN_FLUSH 16 /* block is selected for flush */
  164. #define BLOCK_CHANGED 32 /* block buffer contains a dirty page */
  165. #define BLOCK_IN_USE 64 /* block is not free */
  166. #define BLOCK_IN_EVICTION 128 /* block is selected for eviction */
  167. #define BLOCK_IN_FLUSHWRITE 256 /* block is in write to file */
  168. #define BLOCK_FOR_UPDATE 512 /* block is selected for buffer modification */
  169. /* page status, returned by find_key_block */
  170. #define PAGE_READ 0
  171. #define PAGE_TO_BE_READ 1
  172. #define PAGE_WAIT_TO_BE_READ 2
  173. /* block temperature determines in which (sub-)chain the block currently is */
  174. enum BLOCK_TEMPERATURE { BLOCK_COLD /*free*/ , BLOCK_WARM , BLOCK_HOT };
  175. /* key cache block */
  176. struct st_block_link
  177. {
  178. struct st_block_link
  179. *next_used, **prev_used; /* to connect links in the LRU chain (ring) */
  180. struct st_block_link
  181. *next_changed, **prev_changed; /* for lists of file dirty/clean blocks */
  182. struct st_hash_link *hash_link; /* backward ptr to referring hash_link */
  183. KEYCACHE_WQUEUE wqueue[2]; /* queues on waiting requests for new/old pages */
  184. uint requests; /* number of requests for the block */
  185. uchar *buffer; /* buffer for the block page */
  186. uint offset; /* beginning of modified data in the buffer */
  187. uint length; /* end of data in the buffer */
  188. uint status; /* state of the block */
  189. enum BLOCK_TEMPERATURE temperature; /* block temperature: cold, warm, hot */
  190. uint hits_left; /* number of hits left until promotion */
  191. ulonglong last_hit_time; /* timestamp of the last hit */
  192. KEYCACHE_CONDVAR *condvar; /* condition variable for 'no readers' event */
  193. };
  194. KEY_CACHE dflt_key_cache_var;
  195. KEY_CACHE *dflt_key_cache= &dflt_key_cache_var;
  196. #define FLUSH_CACHE 2000 /* sort this many blocks at once */
  197. static int flush_all_key_blocks(KEY_CACHE *keycache);
  198. #ifdef THREAD
  199. static void wait_on_queue(KEYCACHE_WQUEUE *wqueue,
  200. mysql_mutex_t *mutex);
  201. static void release_whole_queue(KEYCACHE_WQUEUE *wqueue);
  202. #else
  203. #define wait_on_queue(wqueue, mutex) do {} while (0)
  204. #define release_whole_queue(wqueue) do {} while (0)
  205. #endif
  206. static void free_block(KEY_CACHE *keycache, BLOCK_LINK *block);
  207. #if !defined(DBUG_OFF)
  208. static void test_key_cache(KEY_CACHE *keycache,
  209. const char *where, my_bool lock);
  210. #endif
  211. #define KEYCACHE_HASH(f, pos) \
  212. (((ulong) ((pos) / keycache->key_cache_block_size) + \
  213. (ulong) (f)) & (keycache->hash_entries-1))
  214. #define FILE_HASH(f) ((uint) (f) & (CHANGED_BLOCKS_HASH-1))
  215. #define DEFAULT_KEYCACHE_DEBUG_LOG "keycache_debug.log"
  216. #if defined(KEYCACHE_DEBUG) && ! defined(KEYCACHE_DEBUG_LOG)
  217. #define KEYCACHE_DEBUG_LOG DEFAULT_KEYCACHE_DEBUG_LOG
  218. #endif
  219. #if defined(KEYCACHE_DEBUG_LOG)
  220. static FILE *keycache_debug_log=NULL;
  221. static void keycache_debug_print(const char *fmt,...);
  222. #define KEYCACHE_DEBUG_OPEN \
  223. if (!keycache_debug_log) \
  224. { \
  225. keycache_debug_log= fopen(KEYCACHE_DEBUG_LOG, "w"); \
  226. (void) setvbuf(keycache_debug_log, NULL, _IOLBF, BUFSIZ); \
  227. }
  228. #define KEYCACHE_DEBUG_CLOSE \
  229. if (keycache_debug_log) \
  230. { \
  231. fclose(keycache_debug_log); \
  232. keycache_debug_log= 0; \
  233. }
  234. #else
  235. #define KEYCACHE_DEBUG_OPEN
  236. #define KEYCACHE_DEBUG_CLOSE
  237. #endif /* defined(KEYCACHE_DEBUG_LOG) */
  238. #if defined(KEYCACHE_DEBUG_LOG) && defined(KEYCACHE_DEBUG)
  239. #define KEYCACHE_DBUG_PRINT(l, m) \
  240. { if (keycache_debug_log) fprintf(keycache_debug_log, "%s: ", l); \
  241. keycache_debug_print m; }
  242. #define KEYCACHE_DBUG_ASSERT(a) \
  243. { if (! (a) && keycache_debug_log) fclose(keycache_debug_log); \
  244. assert(a); }
  245. #else
  246. #define KEYCACHE_DBUG_PRINT(l, m) DBUG_PRINT(l, m)
  247. #define KEYCACHE_DBUG_ASSERT(a) DBUG_ASSERT(a)
  248. #endif /* defined(KEYCACHE_DEBUG_LOG) && defined(KEYCACHE_DEBUG) */
  249. #if defined(KEYCACHE_DEBUG) || !defined(DBUG_OFF)
  250. #ifdef THREAD
  251. static long keycache_thread_id;
  252. #define KEYCACHE_THREAD_TRACE(l) \
  253. KEYCACHE_DBUG_PRINT(l,("|thread %ld",keycache_thread_id))
  254. #define KEYCACHE_THREAD_TRACE_BEGIN(l) \
  255. { struct st_my_thread_var *thread_var= my_thread_var; \
  256. keycache_thread_id= thread_var->id; \
  257. KEYCACHE_DBUG_PRINT(l,("[thread %ld",keycache_thread_id)) }
  258. #define KEYCACHE_THREAD_TRACE_END(l) \
  259. KEYCACHE_DBUG_PRINT(l,("]thread %ld",keycache_thread_id))
  260. #else /* THREAD */
  261. #define KEYCACHE_THREAD_TRACE(l) KEYCACHE_DBUG_PRINT(l,(""))
  262. #define KEYCACHE_THREAD_TRACE_BEGIN(l) KEYCACHE_DBUG_PRINT(l,(""))
  263. #define KEYCACHE_THREAD_TRACE_END(l) KEYCACHE_DBUG_PRINT(l,(""))
  264. #endif /* THREAD */
  265. #else
  266. #define KEYCACHE_THREAD_TRACE_BEGIN(l)
  267. #define KEYCACHE_THREAD_TRACE_END(l)
  268. #define KEYCACHE_THREAD_TRACE(l)
  269. #endif /* defined(KEYCACHE_DEBUG) || !defined(DBUG_OFF) */
  270. #define BLOCK_NUMBER(b) \
  271. ((uint) (((char*)(b)-(char *) keycache->block_root)/sizeof(BLOCK_LINK)))
  272. #define HASH_LINK_NUMBER(h) \
  273. ((uint) (((char*)(h)-(char *) keycache->hash_link_root)/sizeof(HASH_LINK)))
  274. #if (defined(KEYCACHE_TIMEOUT) && !defined(__WIN__)) || defined(KEYCACHE_DEBUG)
  275. static int keycache_pthread_cond_wait(mysql_cond_t *cond,
  276. mysql_mutex_t *mutex);
  277. #else
  278. #define keycache_pthread_cond_wait(C, M) mysql_cond_wait(C, M)
  279. #endif
  280. #if defined(KEYCACHE_DEBUG)
  281. static int keycache_pthread_mutex_lock(mysql_mutex_t *mutex);
  282. static void keycache_pthread_mutex_unlock(mysql_mutex_t *mutex);
  283. static int keycache_pthread_cond_signal(mysql_cond_t *cond);
  284. #else
  285. #define keycache_pthread_mutex_lock(M) mysql_mutex_lock(M)
  286. #define keycache_pthread_mutex_unlock(M) mysql_mutex_unlock(M)
  287. #define keycache_pthread_cond_signal(C) mysql_cond_signal(C)
  288. #endif /* defined(KEYCACHE_DEBUG) */
  289. #if !defined(DBUG_OFF)
  290. #if defined(inline)
  291. #undef inline
  292. #endif
  293. #define inline /* disabled inline for easier debugging */
  294. static int fail_block(BLOCK_LINK *block);
  295. static int fail_hlink(HASH_LINK *hlink);
  296. static int cache_empty(KEY_CACHE *keycache);
  297. #endif
  298. static inline uint next_power(uint value)
  299. {
  300. return (uint) my_round_up_to_next_power((uint32) value) << 1;
  301. }
  302. /*
  303. Initialize a key cache
  304. SYNOPSIS
  305. init_key_cache()
  306. keycache pointer to a key cache data structure
  307. key_cache_block_size size of blocks to keep cached data
  308. use_mem total memory to use for the key cache
  309. division_limit division limit (may be zero)
  310. age_threshold age threshold (may be zero)
  311. RETURN VALUE
  312. number of blocks in the key cache, if successful,
  313. 0 - otherwise.
  314. NOTES.
  315. if keycache->key_cache_inited != 0 we assume that the key cache
  316. is already initialized. This is for now used by myisamchk, but shouldn't
  317. be something that a program should rely on!
  318. It's assumed that no two threads call this function simultaneously
  319. referring to the same key cache handle.
  320. */
  321. int init_key_cache(KEY_CACHE *keycache, uint key_cache_block_size,
  322. size_t use_mem, uint division_limit,
  323. uint age_threshold)
  324. {
  325. ulong blocks, hash_links;
  326. size_t length;
  327. int error;
  328. DBUG_ENTER("init_key_cache");
  329. DBUG_ASSERT(key_cache_block_size >= 512);
  330. KEYCACHE_DEBUG_OPEN;
  331. if (keycache->key_cache_inited && keycache->disk_blocks > 0)
  332. {
  333. DBUG_PRINT("warning",("key cache already in use"));
  334. DBUG_RETURN(0);
  335. }
  336. keycache->global_cache_w_requests= keycache->global_cache_r_requests= 0;
  337. keycache->global_cache_read= keycache->global_cache_write= 0;
  338. keycache->disk_blocks= -1;
  339. if (! keycache->key_cache_inited)
  340. {
  341. keycache->key_cache_inited= 1;
  342. /*
  343. Initialize these variables once only.
  344. Their value must survive re-initialization during resizing.
  345. */
  346. keycache->in_resize= 0;
  347. keycache->resize_in_flush= 0;
  348. keycache->cnt_for_resize_op= 0;
  349. keycache->waiting_for_resize_cnt.last_thread= NULL;
  350. keycache->in_init= 0;
  351. mysql_mutex_init(key_KEY_CACHE_cache_lock,
  352. &keycache->cache_lock, MY_MUTEX_INIT_FAST);
  353. keycache->resize_queue.last_thread= NULL;
  354. }
  355. keycache->key_cache_mem_size= use_mem;
  356. keycache->key_cache_block_size= key_cache_block_size;
  357. DBUG_PRINT("info", ("key_cache_block_size: %u",
  358. key_cache_block_size));
  359. blocks= (ulong) (use_mem / (sizeof(BLOCK_LINK) + 2 * sizeof(HASH_LINK) +
  360. sizeof(HASH_LINK*) * 5/4 + key_cache_block_size));
  361. /* It doesn't make sense to have too few blocks (less than 8) */
  362. if (blocks >= 8)
  363. {
  364. for ( ; ; )
  365. {
  366. /* Set my_hash_entries to the next bigger 2 power */
  367. if ((keycache->hash_entries= next_power(blocks)) < blocks * 5/4)
  368. keycache->hash_entries<<= 1;
  369. hash_links= 2 * blocks;
  370. #if defined(MAX_THREADS)
  371. if (hash_links < MAX_THREADS + blocks - 1)
  372. hash_links= MAX_THREADS + blocks - 1;
  373. #endif
  374. while ((length= (ALIGN_SIZE(blocks * sizeof(BLOCK_LINK)) +
  375. ALIGN_SIZE(hash_links * sizeof(HASH_LINK)) +
  376. ALIGN_SIZE(sizeof(HASH_LINK*) *
  377. keycache->hash_entries))) +
  378. ((size_t) blocks * keycache->key_cache_block_size) > use_mem)
  379. blocks--;
  380. /* Allocate memory for cache page buffers */
  381. if ((keycache->block_mem=
  382. my_large_malloc((size_t) blocks * keycache->key_cache_block_size,
  383. MYF(0))))
  384. {
  385. /*
  386. Allocate memory for blocks, hash_links and hash entries;
  387. For each block 2 hash links are allocated
  388. */
  389. if ((keycache->block_root= (BLOCK_LINK*) my_malloc(length,
  390. MYF(0))))
  391. break;
  392. my_large_free(keycache->block_mem);
  393. keycache->block_mem= 0;
  394. }
  395. if (blocks < 8)
  396. {
  397. my_errno= ENOMEM;
  398. my_error(EE_OUTOFMEMORY, MYF(0), blocks * keycache->key_cache_block_size);
  399. goto err;
  400. }
  401. blocks= blocks / 4*3;
  402. }
  403. keycache->blocks_unused= blocks;
  404. keycache->disk_blocks= (int) blocks;
  405. keycache->hash_links= hash_links;
  406. keycache->hash_root= (HASH_LINK**) ((char*) keycache->block_root +
  407. ALIGN_SIZE(blocks*sizeof(BLOCK_LINK)));
  408. keycache->hash_link_root= (HASH_LINK*) ((char*) keycache->hash_root +
  409. ALIGN_SIZE((sizeof(HASH_LINK*) *
  410. keycache->hash_entries)));
  411. bzero((uchar*) keycache->block_root,
  412. keycache->disk_blocks * sizeof(BLOCK_LINK));
  413. bzero((uchar*) keycache->hash_root,
  414. keycache->hash_entries * sizeof(HASH_LINK*));
  415. bzero((uchar*) keycache->hash_link_root,
  416. keycache->hash_links * sizeof(HASH_LINK));
  417. keycache->hash_links_used= 0;
  418. keycache->free_hash_list= NULL;
  419. keycache->blocks_used= keycache->blocks_changed= 0;
  420. keycache->global_blocks_changed= 0;
  421. keycache->blocks_available=0; /* For debugging */
  422. /* The LRU chain is empty after initialization */
  423. keycache->used_last= NULL;
  424. keycache->used_ins= NULL;
  425. keycache->free_block_list= NULL;
  426. keycache->keycache_time= 0;
  427. keycache->warm_blocks= 0;
  428. keycache->min_warm_blocks= (division_limit ?
  429. blocks * division_limit / 100 + 1 :
  430. blocks);
  431. keycache->age_threshold= (age_threshold ?
  432. blocks * age_threshold / 100 :
  433. blocks);
  434. keycache->can_be_used= 1;
  435. keycache->waiting_for_hash_link.last_thread= NULL;
  436. keycache->waiting_for_block.last_thread= NULL;
  437. DBUG_PRINT("exit",
  438. ("disk_blocks: %d block_root: 0x%lx hash_entries: %d\
  439. hash_root: 0x%lx hash_links: %d hash_link_root: 0x%lx",
  440. keycache->disk_blocks, (long) keycache->block_root,
  441. keycache->hash_entries, (long) keycache->hash_root,
  442. keycache->hash_links, (long) keycache->hash_link_root));
  443. bzero((uchar*) keycache->changed_blocks,
  444. sizeof(keycache->changed_blocks[0]) * CHANGED_BLOCKS_HASH);
  445. bzero((uchar*) keycache->file_blocks,
  446. sizeof(keycache->file_blocks[0]) * CHANGED_BLOCKS_HASH);
  447. }
  448. else
  449. {
  450. /* key_buffer_size is specified too small. Disable the cache. */
  451. keycache->can_be_used= 0;
  452. }
  453. keycache->blocks= keycache->disk_blocks > 0 ? keycache->disk_blocks : 0;
  454. DBUG_RETURN((int) keycache->disk_blocks);
  455. err:
  456. error= my_errno;
  457. keycache->disk_blocks= 0;
  458. keycache->blocks= 0;
  459. if (keycache->block_mem)
  460. {
  461. my_large_free((uchar*) keycache->block_mem);
  462. keycache->block_mem= NULL;
  463. }
  464. if (keycache->block_root)
  465. {
  466. my_free(keycache->block_root);
  467. keycache->block_root= NULL;
  468. }
  469. my_errno= error;
  470. keycache->can_be_used= 0;
  471. DBUG_RETURN(0);
  472. }
  473. /*
  474. Resize a key cache
  475. SYNOPSIS
  476. resize_key_cache()
  477. keycache pointer to a key cache data structure
  478. key_cache_block_size size of blocks to keep cached data
  479. use_mem total memory to use for the new key cache
  480. division_limit new division limit (if not zero)
  481. age_threshold new age threshold (if not zero)
  482. RETURN VALUE
  483. number of blocks in the key cache, if successful,
  484. 0 - otherwise.
  485. NOTES.
  486. The function first compares the memory size and the block size parameters
  487. with the key cache values.
  488. If they differ the function free the the memory allocated for the
  489. old key cache blocks by calling the end_key_cache function and
  490. then rebuilds the key cache with new blocks by calling
  491. init_key_cache.
  492. The function starts the operation only when all other threads
  493. performing operations with the key cache let her to proceed
  494. (when cnt_for_resize=0).
  495. */
  496. int resize_key_cache(KEY_CACHE *keycache, uint key_cache_block_size,
  497. size_t use_mem, uint division_limit,
  498. uint age_threshold)
  499. {
  500. int blocks;
  501. DBUG_ENTER("resize_key_cache");
  502. if (!keycache->key_cache_inited)
  503. DBUG_RETURN(keycache->disk_blocks);
  504. if(key_cache_block_size == keycache->key_cache_block_size &&
  505. use_mem == keycache->key_cache_mem_size)
  506. {
  507. change_key_cache_param(keycache, division_limit, age_threshold);
  508. DBUG_RETURN(keycache->disk_blocks);
  509. }
  510. keycache_pthread_mutex_lock(&keycache->cache_lock);
  511. #ifdef THREAD
  512. /*
  513. We may need to wait for another thread which is doing a resize
  514. already. This cannot happen in the MySQL server though. It allows
  515. one resizer only. In set_var.cc keycache->in_init is used to block
  516. multiple attempts.
  517. */
  518. while (keycache->in_resize)
  519. {
  520. /* purecov: begin inspected */
  521. wait_on_queue(&keycache->resize_queue, &keycache->cache_lock);
  522. /* purecov: end */
  523. }
  524. #endif
  525. /*
  526. Mark the operation in progress. This blocks other threads from doing
  527. a resize in parallel. It prohibits new blocks to enter the cache.
  528. Read/write requests can bypass the cache during the flush phase.
  529. */
  530. keycache->in_resize= 1;
  531. /* Need to flush only if keycache is enabled. */
  532. if (keycache->can_be_used)
  533. {
  534. /* Start the flush phase. */
  535. keycache->resize_in_flush= 1;
  536. if (flush_all_key_blocks(keycache))
  537. {
  538. /* TODO: if this happens, we should write a warning in the log file ! */
  539. keycache->resize_in_flush= 0;
  540. blocks= 0;
  541. keycache->can_be_used= 0;
  542. goto finish;
  543. }
  544. DBUG_ASSERT(cache_empty(keycache));
  545. /* End the flush phase. */
  546. keycache->resize_in_flush= 0;
  547. }
  548. #ifdef THREAD
  549. /*
  550. Some direct read/write operations (bypassing the cache) may still be
  551. unfinished. Wait until they are done. If the key cache can be used,
  552. direct I/O is done in increments of key_cache_block_size. That is,
  553. every block is checked if it is in the cache. We need to wait for
  554. pending I/O before re-initializing the cache, because we may change
  555. the block size. Otherwise they could check for blocks at file
  556. positions where the new block division has none. We do also want to
  557. wait for I/O done when (if) the cache was disabled. It must not
  558. run in parallel with normal cache operation.
  559. */
  560. while (keycache->cnt_for_resize_op)
  561. wait_on_queue(&keycache->waiting_for_resize_cnt, &keycache->cache_lock);
  562. #else
  563. KEYCACHE_DBUG_ASSERT(keycache->cnt_for_resize_op == 0);
  564. #endif
  565. /*
  566. Free old cache structures, allocate new structures, and initialize
  567. them. Note that the cache_lock mutex and the resize_queue are left
  568. untouched. We do not lose the cache_lock and will release it only at
  569. the end of this function.
  570. */
  571. end_key_cache(keycache, 0); /* Don't free mutex */
  572. /* The following will work even if use_mem is 0 */
  573. blocks= init_key_cache(keycache, key_cache_block_size, use_mem,
  574. division_limit, age_threshold);
  575. finish:
  576. /*
  577. Mark the resize finished. This allows other threads to start a
  578. resize or to request new cache blocks.
  579. */
  580. keycache->in_resize= 0;
  581. /* Signal waiting threads. */
  582. release_whole_queue(&keycache->resize_queue);
  583. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  584. DBUG_RETURN(blocks);
  585. }
  586. /*
  587. Increment counter blocking resize key cache operation
  588. */
  589. static inline void inc_counter_for_resize_op(KEY_CACHE *keycache)
  590. {
  591. keycache->cnt_for_resize_op++;
  592. }
  593. /*
  594. Decrement counter blocking resize key cache operation;
  595. Signal the operation to proceed when counter becomes equal zero
  596. */
  597. static inline void dec_counter_for_resize_op(KEY_CACHE *keycache)
  598. {
  599. if (!--keycache->cnt_for_resize_op)
  600. release_whole_queue(&keycache->waiting_for_resize_cnt);
  601. }
  602. /*
  603. Change the key cache parameters
  604. SYNOPSIS
  605. change_key_cache_param()
  606. keycache pointer to a key cache data structure
  607. division_limit new division limit (if not zero)
  608. age_threshold new age threshold (if not zero)
  609. RETURN VALUE
  610. none
  611. NOTES.
  612. Presently the function resets the key cache parameters
  613. concerning midpoint insertion strategy - division_limit and
  614. age_threshold.
  615. */
  616. void change_key_cache_param(KEY_CACHE *keycache, uint division_limit,
  617. uint age_threshold)
  618. {
  619. DBUG_ENTER("change_key_cache_param");
  620. keycache_pthread_mutex_lock(&keycache->cache_lock);
  621. if (division_limit)
  622. keycache->min_warm_blocks= (keycache->disk_blocks *
  623. division_limit / 100 + 1);
  624. if (age_threshold)
  625. keycache->age_threshold= (keycache->disk_blocks *
  626. age_threshold / 100);
  627. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  628. DBUG_VOID_RETURN;
  629. }
  630. /*
  631. Remove key_cache from memory
  632. SYNOPSIS
  633. end_key_cache()
  634. keycache key cache handle
  635. cleanup Complete free (Free also mutex for key cache)
  636. RETURN VALUE
  637. none
  638. */
  639. void end_key_cache(KEY_CACHE *keycache, my_bool cleanup)
  640. {
  641. DBUG_ENTER("end_key_cache");
  642. DBUG_PRINT("enter", ("key_cache: 0x%lx", (long) keycache));
  643. if (!keycache->key_cache_inited)
  644. DBUG_VOID_RETURN;
  645. if (keycache->disk_blocks > 0)
  646. {
  647. if (keycache->block_mem)
  648. {
  649. my_large_free((uchar*) keycache->block_mem);
  650. keycache->block_mem= NULL;
  651. my_free(keycache->block_root);
  652. keycache->block_root= NULL;
  653. }
  654. keycache->disk_blocks= -1;
  655. /* Reset blocks_changed to be safe if flush_all_key_blocks is called */
  656. keycache->blocks_changed= 0;
  657. }
  658. DBUG_PRINT("status", ("used: %lu changed: %lu w_requests: %lu "
  659. "writes: %lu r_requests: %lu reads: %lu",
  660. keycache->blocks_used, keycache->global_blocks_changed,
  661. (ulong) keycache->global_cache_w_requests,
  662. (ulong) keycache->global_cache_write,
  663. (ulong) keycache->global_cache_r_requests,
  664. (ulong) keycache->global_cache_read));
  665. /*
  666. Reset these values to be able to detect a disabled key cache.
  667. See Bug#44068 (RESTORE can disable the MyISAM Key Cache).
  668. */
  669. keycache->blocks_used= 0;
  670. keycache->blocks_unused= 0;
  671. if (cleanup)
  672. {
  673. mysql_mutex_destroy(&keycache->cache_lock);
  674. keycache->key_cache_inited= keycache->can_be_used= 0;
  675. KEYCACHE_DEBUG_CLOSE;
  676. }
  677. DBUG_VOID_RETURN;
  678. } /* end_key_cache */
  679. #ifdef THREAD
  680. /*
  681. Link a thread into double-linked queue of waiting threads.
  682. SYNOPSIS
  683. link_into_queue()
  684. wqueue pointer to the queue structure
  685. thread pointer to the thread to be added to the queue
  686. RETURN VALUE
  687. none
  688. NOTES.
  689. Queue is represented by a circular list of the thread structures
  690. The list is double-linked of the type (**prev,*next), accessed by
  691. a pointer to the last element.
  692. */
  693. static void link_into_queue(KEYCACHE_WQUEUE *wqueue,
  694. struct st_my_thread_var *thread)
  695. {
  696. struct st_my_thread_var *last;
  697. DBUG_ASSERT(!thread->next && !thread->prev);
  698. if (! (last= wqueue->last_thread))
  699. {
  700. /* Queue is empty */
  701. thread->next= thread;
  702. thread->prev= &thread->next;
  703. }
  704. else
  705. {
  706. thread->prev= last->next->prev;
  707. last->next->prev= &thread->next;
  708. thread->next= last->next;
  709. last->next= thread;
  710. }
  711. wqueue->last_thread= thread;
  712. }
  713. /*
  714. Unlink a thread from double-linked queue of waiting threads
  715. SYNOPSIS
  716. unlink_from_queue()
  717. wqueue pointer to the queue structure
  718. thread pointer to the thread to be removed from the queue
  719. RETURN VALUE
  720. none
  721. NOTES.
  722. See NOTES for link_into_queue
  723. */
  724. static void unlink_from_queue(KEYCACHE_WQUEUE *wqueue,
  725. struct st_my_thread_var *thread)
  726. {
  727. KEYCACHE_DBUG_PRINT("unlink_from_queue", ("thread %ld", thread->id));
  728. DBUG_ASSERT(thread->next && thread->prev);
  729. if (thread->next == thread)
  730. /* The queue contains only one member */
  731. wqueue->last_thread= NULL;
  732. else
  733. {
  734. thread->next->prev= thread->prev;
  735. *thread->prev=thread->next;
  736. if (wqueue->last_thread == thread)
  737. wqueue->last_thread= STRUCT_PTR(struct st_my_thread_var, next,
  738. thread->prev);
  739. }
  740. thread->next= NULL;
  741. #if !defined(DBUG_OFF)
  742. /*
  743. This makes it easier to see it's not in a chain during debugging.
  744. And some DBUG_ASSERT() rely on it.
  745. */
  746. thread->prev= NULL;
  747. #endif
  748. }
  749. /*
  750. Add a thread to single-linked queue of waiting threads
  751. SYNOPSIS
  752. wait_on_queue()
  753. wqueue Pointer to the queue structure.
  754. mutex Cache_lock to acquire after awake.
  755. RETURN VALUE
  756. none
  757. NOTES.
  758. Queue is represented by a circular list of the thread structures
  759. The list is single-linked of the type (*next), accessed by a pointer
  760. to the last element.
  761. The function protects against stray signals by verifying that the
  762. current thread is unlinked from the queue when awaking. However,
  763. since several threads can wait for the same event, it might be
  764. necessary for the caller of the function to check again if the
  765. condition for awake is indeed matched.
  766. */
  767. static void wait_on_queue(KEYCACHE_WQUEUE *wqueue,
  768. mysql_mutex_t *mutex)
  769. {
  770. struct st_my_thread_var *last;
  771. struct st_my_thread_var *thread= my_thread_var;
  772. /* Add to queue. */
  773. DBUG_ASSERT(!thread->next);
  774. DBUG_ASSERT(!thread->prev); /* Not required, but must be true anyway. */
  775. if (! (last= wqueue->last_thread))
  776. thread->next= thread;
  777. else
  778. {
  779. thread->next= last->next;
  780. last->next= thread;
  781. }
  782. wqueue->last_thread= thread;
  783. /*
  784. Wait until thread is removed from queue by the signalling thread.
  785. The loop protects against stray signals.
  786. */
  787. do
  788. {
  789. KEYCACHE_DBUG_PRINT("wait", ("suspend thread %ld", thread->id));
  790. keycache_pthread_cond_wait(&thread->suspend, mutex);
  791. }
  792. while (thread->next);
  793. }
  794. /*
  795. Remove all threads from queue signaling them to proceed
  796. SYNOPSIS
  797. release_whole_queue()
  798. wqueue pointer to the queue structure
  799. RETURN VALUE
  800. none
  801. NOTES.
  802. See notes for wait_on_queue().
  803. When removed from the queue each thread is signaled via condition
  804. variable thread->suspend.
  805. */
  806. static void release_whole_queue(KEYCACHE_WQUEUE *wqueue)
  807. {
  808. struct st_my_thread_var *last;
  809. struct st_my_thread_var *next;
  810. struct st_my_thread_var *thread;
  811. /* Queue may be empty. */
  812. if (!(last= wqueue->last_thread))
  813. return;
  814. next= last->next;
  815. do
  816. {
  817. thread=next;
  818. KEYCACHE_DBUG_PRINT("release_whole_queue: signal",
  819. ("thread %ld", thread->id));
  820. /* Signal the thread. */
  821. keycache_pthread_cond_signal(&thread->suspend);
  822. /* Take thread from queue. */
  823. next=thread->next;
  824. thread->next= NULL;
  825. }
  826. while (thread != last);
  827. /* Now queue is definitely empty. */
  828. wqueue->last_thread= NULL;
  829. }
  830. #endif /* THREAD */
  831. /*
  832. Unlink a block from the chain of dirty/clean blocks
  833. */
  834. static inline void unlink_changed(BLOCK_LINK *block)
  835. {
  836. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  837. if (block->next_changed)
  838. block->next_changed->prev_changed= block->prev_changed;
  839. *block->prev_changed= block->next_changed;
  840. #if !defined(DBUG_OFF)
  841. /*
  842. This makes it easier to see it's not in a chain during debugging.
  843. And some DBUG_ASSERT() rely on it.
  844. */
  845. block->next_changed= NULL;
  846. block->prev_changed= NULL;
  847. #endif
  848. }
  849. /*
  850. Link a block into the chain of dirty/clean blocks
  851. */
  852. static inline void link_changed(BLOCK_LINK *block, BLOCK_LINK **phead)
  853. {
  854. DBUG_ASSERT(!block->next_changed);
  855. DBUG_ASSERT(!block->prev_changed);
  856. block->prev_changed= phead;
  857. if ((block->next_changed= *phead))
  858. (*phead)->prev_changed= &block->next_changed;
  859. *phead= block;
  860. }
  861. /*
  862. Link a block in a chain of clean blocks of a file.
  863. SYNOPSIS
  864. link_to_file_list()
  865. keycache Key cache handle
  866. block Block to relink
  867. file File to be linked to
  868. unlink If to unlink first
  869. DESCRIPTION
  870. Unlink a block from whichever chain it is linked in, if it's
  871. asked for, and link it to the chain of clean blocks of the
  872. specified file.
  873. NOTE
  874. Please do never set/clear BLOCK_CHANGED outside of
  875. link_to_file_list() or link_to_changed_list().
  876. You would risk to damage correct counting of changed blocks
  877. and to find blocks in the wrong hash.
  878. RETURN
  879. void
  880. */
  881. static void link_to_file_list(KEY_CACHE *keycache,
  882. BLOCK_LINK *block, int file,
  883. my_bool unlink_block)
  884. {
  885. DBUG_ASSERT(block->status & BLOCK_IN_USE);
  886. DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
  887. DBUG_ASSERT(block->hash_link->file == file);
  888. if (unlink_block)
  889. unlink_changed(block);
  890. link_changed(block, &keycache->file_blocks[FILE_HASH(file)]);
  891. if (block->status & BLOCK_CHANGED)
  892. {
  893. block->status&= ~BLOCK_CHANGED;
  894. keycache->blocks_changed--;
  895. keycache->global_blocks_changed--;
  896. }
  897. }
  898. /*
  899. Re-link a block from the clean chain to the dirty chain of a file.
  900. SYNOPSIS
  901. link_to_changed_list()
  902. keycache key cache handle
  903. block block to relink
  904. DESCRIPTION
  905. Unlink a block from the chain of clean blocks of a file
  906. and link it to the chain of dirty blocks of the same file.
  907. NOTE
  908. Please do never set/clear BLOCK_CHANGED outside of
  909. link_to_file_list() or link_to_changed_list().
  910. You would risk to damage correct counting of changed blocks
  911. and to find blocks in the wrong hash.
  912. RETURN
  913. void
  914. */
  915. static void link_to_changed_list(KEY_CACHE *keycache,
  916. BLOCK_LINK *block)
  917. {
  918. DBUG_ASSERT(block->status & BLOCK_IN_USE);
  919. DBUG_ASSERT(!(block->status & BLOCK_CHANGED));
  920. DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
  921. unlink_changed(block);
  922. link_changed(block,
  923. &keycache->changed_blocks[FILE_HASH(block->hash_link->file)]);
  924. block->status|=BLOCK_CHANGED;
  925. keycache->blocks_changed++;
  926. keycache->global_blocks_changed++;
  927. }
  928. /*
  929. Link a block to the LRU chain at the beginning or at the end of
  930. one of two parts.
  931. SYNOPSIS
  932. link_block()
  933. keycache pointer to a key cache data structure
  934. block pointer to the block to link to the LRU chain
  935. hot <-> to link the block into the hot subchain
  936. at_end <-> to link the block at the end of the subchain
  937. RETURN VALUE
  938. none
  939. NOTES.
  940. The LRU ring is represented by a circular list of block structures.
  941. The list is double-linked of the type (**prev,*next) type.
  942. The LRU ring is divided into two parts - hot and warm.
  943. There are two pointers to access the last blocks of these two
  944. parts. The beginning of the warm part follows right after the
  945. end of the hot part.
  946. Only blocks of the warm part can be used for eviction.
  947. The first block from the beginning of this subchain is always
  948. taken for eviction (keycache->last_used->next)
  949. LRU chain: +------+ H O T +------+
  950. +----| end |----...<----| beg |----+
  951. | +------+last +------+ |
  952. v<-link in latest hot (new end) |
  953. | link in latest warm (new end)->^
  954. | +------+ W A R M +------+ |
  955. +----| beg |---->...----| end |----+
  956. +------+ +------+ins
  957. first for eviction
  958. It is also possible that the block is selected for eviction and thus
  959. not linked in the LRU ring.
  960. */
  961. static void link_block(KEY_CACHE *keycache, BLOCK_LINK *block, my_bool hot,
  962. my_bool at_end)
  963. {
  964. BLOCK_LINK *ins;
  965. BLOCK_LINK **pins;
  966. DBUG_ASSERT((block->status & ~BLOCK_CHANGED) == (BLOCK_READ | BLOCK_IN_USE));
  967. DBUG_ASSERT(block->hash_link); /*backptr to block NULL from free_block()*/
  968. DBUG_ASSERT(!block->requests);
  969. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  970. DBUG_ASSERT(!block->next_used);
  971. DBUG_ASSERT(!block->prev_used);
  972. #ifdef THREAD
  973. if (!hot && keycache->waiting_for_block.last_thread)
  974. {
  975. /* Signal that in the LRU warm sub-chain an available block has appeared */
  976. struct st_my_thread_var *last_thread=
  977. keycache->waiting_for_block.last_thread;
  978. struct st_my_thread_var *first_thread= last_thread->next;
  979. struct st_my_thread_var *next_thread= first_thread;
  980. HASH_LINK *hash_link= (HASH_LINK *) first_thread->opt_info;
  981. struct st_my_thread_var *thread;
  982. do
  983. {
  984. thread= next_thread;
  985. next_thread= thread->next;
  986. /*
  987. We notify about the event all threads that ask
  988. for the same page as the first thread in the queue
  989. */
  990. if ((HASH_LINK *) thread->opt_info == hash_link)
  991. {
  992. KEYCACHE_DBUG_PRINT("link_block: signal", ("thread %ld", thread->id));
  993. keycache_pthread_cond_signal(&thread->suspend);
  994. unlink_from_queue(&keycache->waiting_for_block, thread);
  995. block->requests++;
  996. }
  997. }
  998. while (thread != last_thread);
  999. hash_link->block= block;
  1000. /*
  1001. NOTE: We assigned the block to the hash_link and signalled the
  1002. requesting thread(s). But it is possible that other threads runs
  1003. first. These threads see the hash_link assigned to a block which
  1004. is assigned to another hash_link and not marked BLOCK_IN_SWITCH.
  1005. This can be a problem for functions that do not select the block
  1006. via its hash_link: flush and free. They do only see a block which
  1007. is in a "normal" state and don't know that it will be evicted soon.
  1008. We cannot set BLOCK_IN_SWITCH here because only one of the
  1009. requesting threads must handle the eviction. All others must wait
  1010. for it to complete. If we set the flag here, the threads would not
  1011. know who is in charge of the eviction. Without the flag, the first
  1012. thread takes the stick and sets the flag.
  1013. But we need to note in the block that is has been selected for
  1014. eviction. It must not be freed. The evicting thread will not
  1015. expect the block in the free list. Before freeing we could also
  1016. check if block->requests > 1. But I think including another flag
  1017. in the check of block->status is slightly more efficient and
  1018. probably easier to read.
  1019. */
  1020. block->status|= BLOCK_IN_EVICTION;
  1021. KEYCACHE_THREAD_TRACE("link_block: after signaling");
  1022. #if defined(KEYCACHE_DEBUG)
  1023. KEYCACHE_DBUG_PRINT("link_block",
  1024. ("linked,unlinked block %u status=%x #requests=%u #available=%u",
  1025. BLOCK_NUMBER(block), block->status,
  1026. block->requests, keycache->blocks_available));
  1027. #endif
  1028. return;
  1029. }
  1030. #else /* THREAD */
  1031. KEYCACHE_DBUG_ASSERT(! (!hot && keycache->waiting_for_block.last_thread));
  1032. /* Condition not transformed using DeMorgan, to keep the text identical */
  1033. #endif /* THREAD */
  1034. pins= hot ? &keycache->used_ins : &keycache->used_last;
  1035. ins= *pins;
  1036. if (ins)
  1037. {
  1038. ins->next_used->prev_used= &block->next_used;
  1039. block->next_used= ins->next_used;
  1040. block->prev_used= &ins->next_used;
  1041. ins->next_used= block;
  1042. if (at_end)
  1043. *pins= block;
  1044. }
  1045. else
  1046. {
  1047. /* The LRU ring is empty. Let the block point to itself. */
  1048. keycache->used_last= keycache->used_ins= block->next_used= block;
  1049. block->prev_used= &block->next_used;
  1050. }
  1051. KEYCACHE_THREAD_TRACE("link_block");
  1052. #if defined(KEYCACHE_DEBUG)
  1053. keycache->blocks_available++;
  1054. KEYCACHE_DBUG_PRINT("link_block",
  1055. ("linked block %u:%1u status=%x #requests=%u #available=%u",
  1056. BLOCK_NUMBER(block), at_end, block->status,
  1057. block->requests, keycache->blocks_available));
  1058. KEYCACHE_DBUG_ASSERT((ulong) keycache->blocks_available <=
  1059. keycache->blocks_used);
  1060. #endif
  1061. }
  1062. /*
  1063. Unlink a block from the LRU chain
  1064. SYNOPSIS
  1065. unlink_block()
  1066. keycache pointer to a key cache data structure
  1067. block pointer to the block to unlink from the LRU chain
  1068. RETURN VALUE
  1069. none
  1070. NOTES.
  1071. See NOTES for link_block
  1072. */
  1073. static void unlink_block(KEY_CACHE *keycache, BLOCK_LINK *block)
  1074. {
  1075. DBUG_ASSERT((block->status & ~BLOCK_CHANGED) == (BLOCK_READ | BLOCK_IN_USE));
  1076. DBUG_ASSERT(block->hash_link); /*backptr to block NULL from free_block()*/
  1077. DBUG_ASSERT(!block->requests);
  1078. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  1079. DBUG_ASSERT(block->next_used && block->prev_used &&
  1080. (block->next_used->prev_used == &block->next_used) &&
  1081. (*block->prev_used == block));
  1082. if (block->next_used == block)
  1083. /* The list contains only one member */
  1084. keycache->used_last= keycache->used_ins= NULL;
  1085. else
  1086. {
  1087. block->next_used->prev_used= block->prev_used;
  1088. *block->prev_used= block->next_used;
  1089. if (keycache->used_last == block)
  1090. keycache->used_last= STRUCT_PTR(BLOCK_LINK, next_used, block->prev_used);
  1091. if (keycache->used_ins == block)
  1092. keycache->used_ins=STRUCT_PTR(BLOCK_LINK, next_used, block->prev_used);
  1093. }
  1094. block->next_used= NULL;
  1095. #if !defined(DBUG_OFF)
  1096. /*
  1097. This makes it easier to see it's not in a chain during debugging.
  1098. And some DBUG_ASSERT() rely on it.
  1099. */
  1100. block->prev_used= NULL;
  1101. #endif
  1102. KEYCACHE_THREAD_TRACE("unlink_block");
  1103. #if defined(KEYCACHE_DEBUG)
  1104. KEYCACHE_DBUG_ASSERT(keycache->blocks_available != 0);
  1105. keycache->blocks_available--;
  1106. KEYCACHE_DBUG_PRINT("unlink_block",
  1107. ("unlinked block %u status=%x #requests=%u #available=%u",
  1108. BLOCK_NUMBER(block), block->status,
  1109. block->requests, keycache->blocks_available));
  1110. #endif
  1111. }
  1112. /*
  1113. Register requests for a block.
  1114. SYNOPSIS
  1115. reg_requests()
  1116. keycache Pointer to a key cache data structure.
  1117. block Pointer to the block to register a request on.
  1118. count Number of requests. Always 1.
  1119. NOTE
  1120. The first request unlinks the block from the LRU ring. This means
  1121. that it is protected against eveiction.
  1122. RETURN
  1123. void
  1124. */
  1125. static void reg_requests(KEY_CACHE *keycache, BLOCK_LINK *block, int count)
  1126. {
  1127. DBUG_ASSERT(block->status & BLOCK_IN_USE);
  1128. DBUG_ASSERT(block->hash_link);
  1129. if (!block->requests)
  1130. unlink_block(keycache, block);
  1131. block->requests+=count;
  1132. }
  1133. /*
  1134. Unregister request for a block
  1135. linking it to the LRU chain if it's the last request
  1136. SYNOPSIS
  1137. unreg_request()
  1138. keycache pointer to a key cache data structure
  1139. block pointer to the block to link to the LRU chain
  1140. at_end <-> to link the block at the end of the LRU chain
  1141. RETURN VALUE
  1142. none
  1143. NOTES.
  1144. Every linking to the LRU ring decrements by one a special block
  1145. counter (if it's positive). If the at_end parameter is TRUE the block is
  1146. added either at the end of warm sub-chain or at the end of hot sub-chain.
  1147. It is added to the hot subchain if its counter is zero and number of
  1148. blocks in warm sub-chain is not less than some low limit (determined by
  1149. the division_limit parameter). Otherwise the block is added to the warm
  1150. sub-chain. If the at_end parameter is FALSE the block is always added
  1151. at beginning of the warm sub-chain.
  1152. Thus a warm block can be promoted to the hot sub-chain when its counter
  1153. becomes zero for the first time.
  1154. At the same time the block at the very beginning of the hot subchain
  1155. might be moved to the beginning of the warm subchain if it stays untouched
  1156. for a too long time (this time is determined by parameter age_threshold).
  1157. It is also possible that the block is selected for eviction and thus
  1158. not linked in the LRU ring.
  1159. */
  1160. static void unreg_request(KEY_CACHE *keycache,
  1161. BLOCK_LINK *block, int at_end)
  1162. {
  1163. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  1164. DBUG_ASSERT(block->hash_link); /*backptr to block NULL from free_block()*/
  1165. DBUG_ASSERT(block->requests);
  1166. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  1167. DBUG_ASSERT(!block->next_used);
  1168. DBUG_ASSERT(!block->prev_used);
  1169. /*
  1170. Unregister the request, but do not link erroneous blocks into the
  1171. LRU ring.
  1172. */
  1173. if (!--block->requests && !(block->status & BLOCK_ERROR))
  1174. {
  1175. my_bool hot;
  1176. if (block->hits_left)
  1177. block->hits_left--;
  1178. hot= !block->hits_left && at_end &&
  1179. keycache->warm_blocks > keycache->min_warm_blocks;
  1180. if (hot)
  1181. {
  1182. if (block->temperature == BLOCK_WARM)
  1183. keycache->warm_blocks--;
  1184. block->temperature= BLOCK_HOT;
  1185. KEYCACHE_DBUG_PRINT("unreg_request", ("#warm_blocks: %lu",
  1186. keycache->warm_blocks));
  1187. }
  1188. link_block(keycache, block, hot, (my_bool)at_end);
  1189. block->last_hit_time= keycache->keycache_time;
  1190. keycache->keycache_time++;
  1191. /*
  1192. At this place, the block might be in the LRU ring or not. If an
  1193. evicter was waiting for a block, it was selected for eviction and
  1194. not linked in the LRU ring.
  1195. */
  1196. /*
  1197. Check if we should link a hot block to the warm block sub-chain.
  1198. It is possible that we select the same block as above. But it can
  1199. also be another block. In any case a block from the LRU ring is
  1200. selected. In other words it works even if the above block was
  1201. selected for eviction and not linked in the LRU ring. Since this
  1202. happens only if the LRU ring is empty, the block selected below
  1203. would be NULL and the rest of the function skipped.
  1204. */
  1205. block= keycache->used_ins;
  1206. if (block && keycache->keycache_time - block->last_hit_time >
  1207. keycache->age_threshold)
  1208. {
  1209. unlink_block(keycache, block);
  1210. link_block(keycache, block, 0, 0);
  1211. if (block->temperature != BLOCK_WARM)
  1212. {
  1213. keycache->warm_blocks++;
  1214. block->temperature= BLOCK_WARM;
  1215. }
  1216. KEYCACHE_DBUG_PRINT("unreg_request", ("#warm_blocks: %lu",
  1217. keycache->warm_blocks));
  1218. }
  1219. }
  1220. }
  1221. /*
  1222. Remove a reader of the page in block
  1223. */
  1224. static void remove_reader(BLOCK_LINK *block)
  1225. {
  1226. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  1227. DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
  1228. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  1229. DBUG_ASSERT(!block->next_used);
  1230. DBUG_ASSERT(!block->prev_used);
  1231. DBUG_ASSERT(block->hash_link->requests);
  1232. #ifdef THREAD
  1233. if (! --block->hash_link->requests && block->condvar)
  1234. keycache_pthread_cond_signal(block->condvar);
  1235. #else
  1236. --block->hash_link->requests;
  1237. #endif
  1238. }
  1239. /*
  1240. Wait until the last reader of the page in block
  1241. signals on its termination
  1242. */
  1243. static void wait_for_readers(KEY_CACHE *keycache,
  1244. BLOCK_LINK *block)
  1245. {
  1246. #ifdef THREAD
  1247. struct st_my_thread_var *thread= my_thread_var;
  1248. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  1249. DBUG_ASSERT(!(block->status & (BLOCK_IN_FLUSH | BLOCK_CHANGED)));
  1250. DBUG_ASSERT(block->hash_link);
  1251. DBUG_ASSERT(block->hash_link->block == block);
  1252. /* Linked in file_blocks or changed_blocks hash. */
  1253. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  1254. /* Not linked in LRU ring. */
  1255. DBUG_ASSERT(!block->next_used);
  1256. DBUG_ASSERT(!block->prev_used);
  1257. while (block->hash_link->requests)
  1258. {
  1259. KEYCACHE_DBUG_PRINT("wait_for_readers: wait",
  1260. ("suspend thread %ld block %u",
  1261. thread->id, BLOCK_NUMBER(block)));
  1262. /* There must be no other waiter. We have no queue here. */
  1263. DBUG_ASSERT(!block->condvar);
  1264. block->condvar= &thread->suspend;
  1265. keycache_pthread_cond_wait(&thread->suspend, &keycache->cache_lock);
  1266. block->condvar= NULL;
  1267. }
  1268. #else
  1269. KEYCACHE_DBUG_ASSERT(block->hash_link->requests == 0);
  1270. #endif
  1271. }
  1272. /*
  1273. Add a hash link to a bucket in the hash_table
  1274. */
  1275. static inline void link_hash(HASH_LINK **start, HASH_LINK *hash_link)
  1276. {
  1277. if (*start)
  1278. (*start)->prev= &hash_link->next;
  1279. hash_link->next= *start;
  1280. hash_link->prev= start;
  1281. *start= hash_link;
  1282. }
  1283. /*
  1284. Remove a hash link from the hash table
  1285. */
  1286. static void unlink_hash(KEY_CACHE *keycache, HASH_LINK *hash_link)
  1287. {
  1288. KEYCACHE_DBUG_PRINT("unlink_hash", ("fd: %u pos_ %lu #requests=%u",
  1289. (uint) hash_link->file,(ulong) hash_link->diskpos, hash_link->requests));
  1290. KEYCACHE_DBUG_ASSERT(hash_link->requests == 0);
  1291. if ((*hash_link->prev= hash_link->next))
  1292. hash_link->next->prev= hash_link->prev;
  1293. hash_link->block= NULL;
  1294. #ifdef THREAD
  1295. if (keycache->waiting_for_hash_link.last_thread)
  1296. {
  1297. /* Signal that a free hash link has appeared */
  1298. struct st_my_thread_var *last_thread=
  1299. keycache->waiting_for_hash_link.last_thread;
  1300. struct st_my_thread_var *first_thread= last_thread->next;
  1301. struct st_my_thread_var *next_thread= first_thread;
  1302. KEYCACHE_PAGE *first_page= (KEYCACHE_PAGE *) (first_thread->opt_info);
  1303. struct st_my_thread_var *thread;
  1304. hash_link->file= first_page->file;
  1305. hash_link->diskpos= first_page->filepos;
  1306. do
  1307. {
  1308. KEYCACHE_PAGE *page;
  1309. thread= next_thread;
  1310. page= (KEYCACHE_PAGE *) thread->opt_info;
  1311. next_thread= thread->next;
  1312. /*
  1313. We notify about the event all threads that ask
  1314. for the same page as the first thread in the queue
  1315. */
  1316. if (page->file == hash_link->file && page->filepos == hash_link->diskpos)
  1317. {
  1318. KEYCACHE_DBUG_PRINT("unlink_hash: signal", ("thread %ld", thread->id));
  1319. keycache_pthread_cond_signal(&thread->suspend);
  1320. unlink_from_queue(&keycache->waiting_for_hash_link, thread);
  1321. }
  1322. }
  1323. while (thread != last_thread);
  1324. link_hash(&keycache->hash_root[KEYCACHE_HASH(hash_link->file,
  1325. hash_link->diskpos)],
  1326. hash_link);
  1327. return;
  1328. }
  1329. #else /* THREAD */
  1330. KEYCACHE_DBUG_ASSERT(! (keycache->waiting_for_hash_link.last_thread));
  1331. #endif /* THREAD */
  1332. hash_link->next= keycache->free_hash_list;
  1333. keycache->free_hash_list= hash_link;
  1334. }
  1335. /*
  1336. Get the hash link for a page
  1337. */
  1338. static HASH_LINK *get_hash_link(KEY_CACHE *keycache,
  1339. int file, my_off_t filepos)
  1340. {
  1341. reg1 HASH_LINK *hash_link, **start;
  1342. #if defined(KEYCACHE_DEBUG)
  1343. int cnt;
  1344. #endif
  1345. KEYCACHE_DBUG_PRINT("get_hash_link", ("fd: %u pos: %lu",
  1346. (uint) file,(ulong) filepos));
  1347. restart:
  1348. /*
  1349. Find the bucket in the hash table for the pair (file, filepos);
  1350. start contains the head of the bucket list,
  1351. hash_link points to the first member of the list
  1352. */
  1353. hash_link= *(start= &keycache->hash_root[KEYCACHE_HASH(file, filepos)]);
  1354. #if defined(KEYCACHE_DEBUG)
  1355. cnt= 0;
  1356. #endif
  1357. /* Look for an element for the pair (file, filepos) in the bucket chain */
  1358. while (hash_link &&
  1359. (hash_link->diskpos != filepos || hash_link->file != file))
  1360. {
  1361. hash_link= hash_link->next;
  1362. #if defined(KEYCACHE_DEBUG)
  1363. cnt++;
  1364. if (! (cnt <= keycache->hash_links_used))
  1365. {
  1366. int i;
  1367. for (i=0, hash_link= *start ;
  1368. i < cnt ; i++, hash_link= hash_link->next)
  1369. {
  1370. KEYCACHE_DBUG_PRINT("get_hash_link", ("fd: %u pos: %lu",
  1371. (uint) hash_link->file,(ulong) hash_link->diskpos));
  1372. }
  1373. }
  1374. KEYCACHE_DBUG_ASSERT(cnt <= keycache->hash_links_used);
  1375. #endif
  1376. }
  1377. if (! hash_link)
  1378. {
  1379. /* There is no hash link in the hash table for the pair (file, filepos) */
  1380. if (keycache->free_hash_list)
  1381. {
  1382. hash_link= keycache->free_hash_list;
  1383. keycache->free_hash_list= hash_link->next;
  1384. }
  1385. else if (keycache->hash_links_used < keycache->hash_links)
  1386. {
  1387. hash_link= &keycache->hash_link_root[keycache->hash_links_used++];
  1388. }
  1389. else
  1390. {
  1391. #ifdef THREAD
  1392. /* Wait for a free hash link */
  1393. struct st_my_thread_var *thread= my_thread_var;
  1394. KEYCACHE_PAGE page;
  1395. KEYCACHE_DBUG_PRINT("get_hash_link", ("waiting"));
  1396. page.file= file;
  1397. page.filepos= filepos;
  1398. thread->opt_info= (void *) &page;
  1399. link_into_queue(&keycache->waiting_for_hash_link, thread);
  1400. KEYCACHE_DBUG_PRINT("get_hash_link: wait",
  1401. ("suspend thread %ld", thread->id));
  1402. keycache_pthread_cond_wait(&thread->suspend,
  1403. &keycache->cache_lock);
  1404. thread->opt_info= NULL;
  1405. #else
  1406. KEYCACHE_DBUG_ASSERT(0);
  1407. #endif
  1408. goto restart;
  1409. }
  1410. hash_link->file= file;
  1411. hash_link->diskpos= filepos;
  1412. link_hash(start, hash_link);
  1413. }
  1414. /* Register the request for the page */
  1415. hash_link->requests++;
  1416. return hash_link;
  1417. }
  1418. /*
  1419. Get a block for the file page requested by a keycache read/write operation;
  1420. If the page is not in the cache return a free block, if there is none
  1421. return the lru block after saving its buffer if the page is dirty.
  1422. SYNOPSIS
  1423. find_key_block()
  1424. keycache pointer to a key cache data structure
  1425. file handler for the file to read page from
  1426. filepos position of the page in the file
  1427. init_hits_left how initialize the block counter for the page
  1428. wrmode <-> get for writing
  1429. page_st out {PAGE_READ,PAGE_TO_BE_READ,PAGE_WAIT_TO_BE_READ}
  1430. RETURN VALUE
  1431. Pointer to the found block if successful, 0 - otherwise
  1432. NOTES.
  1433. For the page from file positioned at filepos the function checks whether
  1434. the page is in the key cache specified by the first parameter.
  1435. If this is the case it immediately returns the block.
  1436. If not, the function first chooses a block for this page. If there is
  1437. no not used blocks in the key cache yet, the function takes the block
  1438. at the very beginning of the warm sub-chain. It saves the page in that
  1439. block if it's dirty before returning the pointer to it.
  1440. The function returns in the page_st parameter the following values:
  1441. PAGE_READ - if page already in the block,
  1442. PAGE_TO_BE_READ - if it is to be read yet by the current thread
  1443. WAIT_TO_BE_READ - if it is to be read by another thread
  1444. If an error occurs THE BLOCK_ERROR bit is set in the block status.
  1445. It might happen that there are no blocks in LRU chain (in warm part) -
  1446. all blocks are unlinked for some read/write operations. Then the function
  1447. waits until first of this operations links any block back.
  1448. */
  1449. static BLOCK_LINK *find_key_block(KEY_CACHE *keycache,
  1450. File file, my_off_t filepos,
  1451. int init_hits_left,
  1452. int wrmode, int *page_st)
  1453. {
  1454. HASH_LINK *hash_link;
  1455. BLOCK_LINK *block;
  1456. int error= 0;
  1457. int page_status;
  1458. DBUG_ENTER("find_key_block");
  1459. KEYCACHE_THREAD_TRACE("find_key_block:begin");
  1460. DBUG_PRINT("enter", ("fd: %d pos: %lu wrmode: %d",
  1461. file, (ulong) filepos, wrmode));
  1462. KEYCACHE_DBUG_PRINT("find_key_block", ("fd: %d pos: %lu wrmode: %d",
  1463. file, (ulong) filepos,
  1464. wrmode));
  1465. #if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
  1466. DBUG_EXECUTE("check_keycache2",
  1467. test_key_cache(keycache, "start of find_key_block", 0););
  1468. #endif
  1469. restart:
  1470. /*
  1471. If the flush phase of a resize operation fails, the cache is left
  1472. unusable. This will be detected only after "goto restart".
  1473. */
  1474. if (!keycache->can_be_used)
  1475. DBUG_RETURN(0);
  1476. /*
  1477. Find the hash_link for the requested file block (file, filepos). We
  1478. do always get a hash_link here. It has registered our request so
  1479. that no other thread can use it for another file block until we
  1480. release the request (which is done by remove_reader() usually). The
  1481. hash_link can have a block assigned to it or not. If there is a
  1482. block, it may be assigned to this hash_link or not. In cases where a
  1483. block is evicted from the cache, it is taken from the LRU ring and
  1484. referenced by the new hash_link. But the block can still be assigned
  1485. to its old hash_link for some time if it needs to be flushed first,
  1486. or if there are other threads still reading it.
  1487. Summary:
  1488. hash_link is always returned.
  1489. hash_link->block can be:
  1490. - NULL or
  1491. - not assigned to this hash_link or
  1492. - assigned to this hash_link. If assigned, the block can have
  1493. - invalid data (when freshly assigned) or
  1494. - valid data. Valid data can be
  1495. - changed over the file contents (dirty) or
  1496. - not changed (clean).
  1497. */
  1498. hash_link= get_hash_link(keycache, file, filepos);
  1499. DBUG_ASSERT((hash_link->file == file) && (hash_link->diskpos == filepos));
  1500. page_status= -1;
  1501. if ((block= hash_link->block) &&
  1502. block->hash_link == hash_link && (block->status & BLOCK_READ))
  1503. {
  1504. /* Assigned block with valid (changed or unchanged) contents. */
  1505. page_status= PAGE_READ;
  1506. }
  1507. /*
  1508. else (page_status == -1)
  1509. - block == NULL or
  1510. - block not assigned to this hash_link or
  1511. - block assigned but not yet read from file (invalid data).
  1512. */
  1513. #ifdef THREAD
  1514. if (keycache->in_resize)
  1515. {
  1516. /* This is a request during a resize operation */
  1517. if (!block)
  1518. {
  1519. struct st_my_thread_var *thread;
  1520. /*
  1521. The file block is not in the cache. We don't need it in the
  1522. cache: we are going to read or write directly to file. Cancel
  1523. the request. We can simply decrement hash_link->requests because
  1524. we did not release cache_lock since increasing it. So no other
  1525. thread can wait for our request to become released.
  1526. */
  1527. if (hash_link->requests == 1)
  1528. {
  1529. /*
  1530. We are the only one to request this hash_link (this file/pos).
  1531. Free the hash_link.
  1532. */
  1533. hash_link->requests--;
  1534. unlink_hash(keycache, hash_link);
  1535. DBUG_RETURN(0);
  1536. }
  1537. /*
  1538. More requests on the hash_link. Someone tries to evict a block
  1539. for this hash_link (could have started before resizing started).
  1540. This means that the LRU ring is empty. Otherwise a block could
  1541. be assigned immediately. Behave like a thread that wants to
  1542. evict a block for this file/pos. Add to the queue of threads
  1543. waiting for a block. Wait until there is one assigned.
  1544. Refresh the request on the hash-link so that it cannot be reused
  1545. for another file/pos.
  1546. */
  1547. thread= my_thread_var;
  1548. thread->opt_info= (void *) hash_link;
  1549. link_into_queue(&keycache->waiting_for_block, thread);
  1550. do
  1551. {
  1552. KEYCACHE_DBUG_PRINT("find_key_block: wait",
  1553. ("suspend thread %ld", thread->id));
  1554. keycache_pthread_cond_wait(&thread->suspend,
  1555. &keycache->cache_lock);
  1556. } while (thread->next);
  1557. thread->opt_info= NULL;
  1558. /*
  1559. A block should now be assigned to the hash_link. But it may
  1560. still need to be evicted. Anyway, we should re-check the
  1561. situation. page_status must be set correctly.
  1562. */
  1563. hash_link->requests--;
  1564. goto restart;
  1565. } /* end of if (!block) */
  1566. /*
  1567. There is a block for this file/pos in the cache. Register a
  1568. request on it. This unlinks it from the LRU ring (if it is there)
  1569. and hence protects it against eviction (if not already in
  1570. eviction). We need this for returning the block to the caller, for
  1571. calling remove_reader() (for debugging purposes), and for calling
  1572. free_block(). The only case where we don't need the request is if
  1573. the block is in eviction. In that case we have to unregister the
  1574. request later.
  1575. */
  1576. reg_requests(keycache, block, 1);
  1577. if (page_status != PAGE_READ)
  1578. {
  1579. /*
  1580. - block not assigned to this hash_link or
  1581. - block assigned but not yet read from file (invalid data).
  1582. This must be a block in eviction. It will be read soon. We need
  1583. to wait here until this happened. Otherwise the caller could
  1584. access a wrong block or a block which is in read. While waiting
  1585. we cannot lose hash_link nor block. We have registered a request
  1586. on the hash_link. Everything can happen to the block but changes
  1587. in the hash_link -> block relationship. In other words:
  1588. everything can happen to the block but free or another completed
  1589. eviction.
  1590. Note that we bahave like a secondary requestor here. We just
  1591. cannot return with PAGE_WAIT_TO_BE_READ. This would work for
  1592. read requests and writes on dirty blocks that are not in flush
  1593. only. Waiting here on COND_FOR_REQUESTED works in all
  1594. situations.
  1595. */
  1596. DBUG_ASSERT(((block->hash_link != hash_link) &&
  1597. (block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH))) ||
  1598. ((block->hash_link == hash_link) &&
  1599. !(block->status & BLOCK_READ)));
  1600. wait_on_queue(&block->wqueue[COND_FOR_REQUESTED], &keycache->cache_lock);
  1601. /*
  1602. Here we can trust that the block has been assigned to this
  1603. hash_link (block->hash_link == hash_link) and read into the
  1604. buffer (BLOCK_READ). The worst things possible here are that the
  1605. block is in free (BLOCK_REASSIGNED). But the block is still
  1606. assigned to the hash_link. The freeing thread waits until we
  1607. release our request on the hash_link. The block must not be
  1608. again in eviction because we registered an request on it before
  1609. starting to wait.
  1610. */
  1611. DBUG_ASSERT(block->hash_link == hash_link);
  1612. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  1613. DBUG_ASSERT(!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH)));
  1614. }
  1615. /*
  1616. The block is in the cache. Assigned to the hash_link. Valid data.
  1617. Note that in case of page_st == PAGE_READ, the block can be marked
  1618. for eviction. In any case it can be marked for freeing.
  1619. */
  1620. if (!wrmode)
  1621. {
  1622. /* A reader can just read the block. */
  1623. *page_st= PAGE_READ;
  1624. DBUG_ASSERT((hash_link->file == file) &&
  1625. (hash_link->diskpos == filepos) &&
  1626. (block->hash_link == hash_link));
  1627. DBUG_RETURN(block);
  1628. }
  1629. /*
  1630. This is a writer. No two writers for the same block can exist.
  1631. This must be assured by locks outside of the key cache.
  1632. */
  1633. DBUG_ASSERT(!(block->status & BLOCK_FOR_UPDATE) || fail_block(block));
  1634. while (block->status & BLOCK_IN_FLUSH)
  1635. {
  1636. /*
  1637. Wait until the block is flushed to file. Do not release the
  1638. request on the hash_link yet to prevent that the block is freed
  1639. or reassigned while we wait. While we wait, several things can
  1640. happen to the block, including another flush. But the block
  1641. cannot be reassigned to another hash_link until we release our
  1642. request on it. But it can be marked BLOCK_REASSIGNED from free
  1643. or eviction, while they wait for us to release the hash_link.
  1644. */
  1645. wait_on_queue(&block->wqueue[COND_FOR_SAVED], &keycache->cache_lock);
  1646. /*
  1647. If the flush phase failed, the resize could have finished while
  1648. we waited here.
  1649. */
  1650. if (!keycache->in_resize)
  1651. {
  1652. remove_reader(block);
  1653. unreg_request(keycache, block, 1);
  1654. goto restart;
  1655. }
  1656. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  1657. DBUG_ASSERT(!(block->status & BLOCK_FOR_UPDATE) || fail_block(block));
  1658. DBUG_ASSERT(block->hash_link == hash_link);
  1659. }
  1660. if (block->status & BLOCK_CHANGED)
  1661. {
  1662. /*
  1663. We want to write a block with changed contents. If the cache
  1664. block size is bigger than the callers block size (e.g. MyISAM),
  1665. the caller may replace part of the block only. Changes of the
  1666. other part of the block must be preserved. Since the block has
  1667. not yet been selected for flush, we can still add our changes.
  1668. */
  1669. *page_st= PAGE_READ;
  1670. DBUG_ASSERT((hash_link->file == file) &&
  1671. (hash_link->diskpos == filepos) &&
  1672. (block->hash_link == hash_link));
  1673. DBUG_RETURN(block);
  1674. }
  1675. /*
  1676. This is a write request for a clean block. We do not want to have
  1677. new dirty blocks in the cache while resizing. We will free the
  1678. block and write directly to file. If the block is in eviction or
  1679. in free, we just let it go.
  1680. Unregister from the hash_link. This must be done before freeing
  1681. the block. And it must be done if not freeing the block. Because
  1682. we could have waited above, we need to call remove_reader(). Other
  1683. threads could wait for us to release our request on the hash_link.
  1684. */
  1685. remove_reader(block);
  1686. /* If the block is not in eviction and not in free, we can free it. */
  1687. if (!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
  1688. BLOCK_REASSIGNED)))
  1689. {
  1690. /*
  1691. Free block as we are going to write directly to file.
  1692. Although we have an exlusive lock for the updated key part,
  1693. the control can be yielded by the current thread as we might
  1694. have unfinished readers of other key parts in the block
  1695. buffer. Still we are guaranteed not to have any readers
  1696. of the key part we are writing into until the block is
  1697. removed from the cache as we set the BLOCK_REASSIGNED
  1698. flag (see the code below that handles reading requests).
  1699. */
  1700. free_block(keycache, block);
  1701. }
  1702. else
  1703. {
  1704. /*
  1705. The block will be evicted/freed soon. Don't touch it in any way.
  1706. Unregister the request that we registered above.
  1707. */
  1708. unreg_request(keycache, block, 1);
  1709. /*
  1710. The block is still assigned to the hash_link (the file/pos that
  1711. we are going to write to). Wait until the eviction/free is
  1712. complete. Otherwise the direct write could complete before all
  1713. readers are done with the block. So they could read outdated
  1714. data.
  1715. Since we released our request on the hash_link, it can be reused
  1716. for another file/pos. Hence we cannot just check for
  1717. block->hash_link == hash_link. As long as the resize is
  1718. proceeding the block cannot be reassigned to the same file/pos
  1719. again. So we can terminate the loop when the block is no longer
  1720. assigned to this file/pos.
  1721. */
  1722. do
  1723. {
  1724. wait_on_queue(&block->wqueue[COND_FOR_SAVED],
  1725. &keycache->cache_lock);
  1726. /*
  1727. If the flush phase failed, the resize could have finished
  1728. while we waited here.
  1729. */
  1730. if (!keycache->in_resize)
  1731. goto restart;
  1732. } while (block->hash_link &&
  1733. (block->hash_link->file == file) &&
  1734. (block->hash_link->diskpos == filepos));
  1735. }
  1736. DBUG_RETURN(0);
  1737. }
  1738. #else /* THREAD */
  1739. DBUG_ASSERT(!keycache->in_resize);
  1740. #endif
  1741. if (page_status == PAGE_READ &&
  1742. (block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
  1743. BLOCK_REASSIGNED)))
  1744. {
  1745. /*
  1746. This is a request for a block to be removed from cache. The block
  1747. is assigned to this hash_link and contains valid data, but is
  1748. marked for eviction or to be freed. Possible reasons why it has
  1749. not yet been evicted/freed can be a flush before reassignment
  1750. (BLOCK_IN_SWITCH), readers of the block have not finished yet
  1751. (BLOCK_REASSIGNED), or the evicting thread did not yet awake after
  1752. the block has been selected for it (BLOCK_IN_EVICTION).
  1753. */
  1754. KEYCACHE_DBUG_PRINT("find_key_block",
  1755. ("request for old page in block %u "
  1756. "wrmode: %d block->status: %d",
  1757. BLOCK_NUMBER(block), wrmode, block->status));
  1758. /*
  1759. Only reading requests can proceed until the old dirty page is flushed,
  1760. all others are to be suspended, then resubmitted
  1761. */
  1762. if (!wrmode && !(block->status & BLOCK_REASSIGNED))
  1763. {
  1764. /*
  1765. This is a read request and the block not yet reassigned. We can
  1766. register our request and proceed. This unlinks the block from
  1767. the LRU ring and protects it against eviction.
  1768. */
  1769. reg_requests(keycache, block, 1);
  1770. }
  1771. else
  1772. {
  1773. /*
  1774. Either this is a write request for a block that is in eviction
  1775. or in free. We must not use it any more. Instead we must evict
  1776. another block. But we cannot do this before the eviction/free is
  1777. done. Otherwise we would find the same hash_link + block again
  1778. and again.
  1779. Or this is a read request for a block in eviction/free that does
  1780. not require a flush, but waits for readers to finish with the
  1781. block. We do not read this block to let the eviction/free happen
  1782. as soon as possible. Again we must wait so that we don't find
  1783. the same hash_link + block again and again.
  1784. */
  1785. DBUG_ASSERT(hash_link->requests);
  1786. hash_link->requests--;
  1787. KEYCACHE_DBUG_PRINT("find_key_block",
  1788. ("request waiting for old page to be saved"));
  1789. wait_on_queue(&block->wqueue[COND_FOR_SAVED], &keycache->cache_lock);
  1790. KEYCACHE_DBUG_PRINT("find_key_block",
  1791. ("request for old page resubmitted"));
  1792. /*
  1793. The block is no longer assigned to this hash_link.
  1794. Get another one.
  1795. */
  1796. goto restart;
  1797. }
  1798. }
  1799. else
  1800. {
  1801. /*
  1802. This is a request for a new block or for a block not to be removed.
  1803. Either
  1804. - block == NULL or
  1805. - block not assigned to this hash_link or
  1806. - block assigned but not yet read from file,
  1807. or
  1808. - block assigned with valid (changed or unchanged) data and
  1809. - it will not be reassigned/freed.
  1810. */
  1811. if (! block)
  1812. {
  1813. /* No block is assigned to the hash_link yet. */
  1814. if (keycache->blocks_unused)
  1815. {
  1816. if (keycache->free_block_list)
  1817. {
  1818. /* There is a block in the free list. */
  1819. block= keycache->free_block_list;
  1820. keycache->free_block_list= block->next_used;
  1821. block->next_used= NULL;
  1822. }
  1823. else
  1824. {
  1825. size_t block_mem_offset;
  1826. /* There are some never used blocks, take first of them */
  1827. DBUG_ASSERT(keycache->blocks_used <
  1828. (ulong) keycache->disk_blocks);
  1829. block= &keycache->block_root[keycache->blocks_used];
  1830. block_mem_offset=
  1831. ((size_t) keycache->blocks_used) * keycache->key_cache_block_size;
  1832. block->buffer= ADD_TO_PTR(keycache->block_mem,
  1833. block_mem_offset,
  1834. uchar*);
  1835. keycache->blocks_used++;
  1836. DBUG_ASSERT(!block->next_used);
  1837. }
  1838. DBUG_ASSERT(!block->prev_used);
  1839. DBUG_ASSERT(!block->next_changed);
  1840. DBUG_ASSERT(!block->prev_changed);
  1841. DBUG_ASSERT(!block->hash_link);
  1842. DBUG_ASSERT(!block->status);
  1843. DBUG_ASSERT(!block->requests);
  1844. keycache->blocks_unused--;
  1845. block->status= BLOCK_IN_USE;
  1846. block->length= 0;
  1847. block->offset= keycache->key_cache_block_size;
  1848. block->requests= 1;
  1849. block->temperature= BLOCK_COLD;
  1850. block->hits_left= init_hits_left;
  1851. block->last_hit_time= 0;
  1852. block->hash_link= hash_link;
  1853. hash_link->block= block;
  1854. link_to_file_list(keycache, block, file, 0);
  1855. page_status= PAGE_TO_BE_READ;
  1856. KEYCACHE_DBUG_PRINT("find_key_block",
  1857. ("got free or never used block %u",
  1858. BLOCK_NUMBER(block)));
  1859. }
  1860. else
  1861. {
  1862. /*
  1863. There are no free blocks and no never used blocks, use a block
  1864. from the LRU ring.
  1865. */
  1866. #ifdef THREAD
  1867. if (! keycache->used_last)
  1868. {
  1869. /*
  1870. The LRU ring is empty. Wait until a new block is added to
  1871. it. Several threads might wait here for the same hash_link,
  1872. all of them must get the same block. While waiting for a
  1873. block, after a block is selected for this hash_link, other
  1874. threads can run first before this one awakes. During this
  1875. time interval other threads find this hash_link pointing to
  1876. the block, which is still assigned to another hash_link. In
  1877. this case the block is not marked BLOCK_IN_SWITCH yet, but
  1878. it is marked BLOCK_IN_EVICTION.
  1879. */
  1880. struct st_my_thread_var *thread= my_thread_var;
  1881. thread->opt_info= (void *) hash_link;
  1882. link_into_queue(&keycache->waiting_for_block, thread);
  1883. do
  1884. {
  1885. KEYCACHE_DBUG_PRINT("find_key_block: wait",
  1886. ("suspend thread %ld", thread->id));
  1887. keycache_pthread_cond_wait(&thread->suspend,
  1888. &keycache->cache_lock);
  1889. }
  1890. while (thread->next);
  1891. thread->opt_info= NULL;
  1892. /* Assert that block has a request registered. */
  1893. DBUG_ASSERT(hash_link->block->requests);
  1894. /* Assert that block is not in LRU ring. */
  1895. DBUG_ASSERT(!hash_link->block->next_used);
  1896. DBUG_ASSERT(!hash_link->block->prev_used);
  1897. }
  1898. #else
  1899. KEYCACHE_DBUG_ASSERT(keycache->used_last);
  1900. #endif
  1901. /*
  1902. If we waited above, hash_link->block has been assigned by
  1903. link_block(). Otherwise it is still NULL. In the latter case
  1904. we need to grab a block from the LRU ring ourselves.
  1905. */
  1906. block= hash_link->block;
  1907. if (! block)
  1908. {
  1909. /* Select the last block from the LRU ring. */
  1910. block= keycache->used_last->next_used;
  1911. block->hits_left= init_hits_left;
  1912. block->last_hit_time= 0;
  1913. hash_link->block= block;
  1914. /*
  1915. Register a request on the block. This unlinks it from the
  1916. LRU ring and protects it against eviction.
  1917. */
  1918. DBUG_ASSERT(!block->requests);
  1919. reg_requests(keycache, block,1);
  1920. /*
  1921. We do not need to set block->status|= BLOCK_IN_EVICTION here
  1922. because we will set block->status|= BLOCK_IN_SWITCH
  1923. immediately without releasing the lock in between. This does
  1924. also support debugging. When looking at the block, one can
  1925. see if the block has been selected by link_block() after the
  1926. LRU ring was empty, or if it was grabbed directly from the
  1927. LRU ring in this branch.
  1928. */
  1929. }
  1930. /*
  1931. If we had to wait above, there is a small chance that another
  1932. thread grabbed this block for the same file block already. But
  1933. in most cases the first condition is true.
  1934. */
  1935. if (block->hash_link != hash_link &&
  1936. ! (block->status & BLOCK_IN_SWITCH) )
  1937. {
  1938. /* this is a primary request for a new page */
  1939. block->status|= BLOCK_IN_SWITCH;
  1940. KEYCACHE_DBUG_PRINT("find_key_block",
  1941. ("got block %u for new page", BLOCK_NUMBER(block)));
  1942. if (block->status & BLOCK_CHANGED)
  1943. {
  1944. /* The block contains a dirty page - push it out of the cache */
  1945. KEYCACHE_DBUG_PRINT("find_key_block", ("block is dirty"));
  1946. if (block->status & BLOCK_IN_FLUSH)
  1947. {
  1948. /*
  1949. The block is marked for flush. If we do not wait here,
  1950. it could happen that we write the block, reassign it to
  1951. another file block, then, before the new owner can read
  1952. the new file block, the flusher writes the cache block
  1953. (which still has the old contents) to the new file block!
  1954. */
  1955. wait_on_queue(&block->wqueue[COND_FOR_SAVED],
  1956. &keycache->cache_lock);
  1957. /*
  1958. The block is marked BLOCK_IN_SWITCH. It should be left
  1959. alone except for reading. No free, no write.
  1960. */
  1961. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  1962. DBUG_ASSERT(!(block->status & (BLOCK_REASSIGNED |
  1963. BLOCK_CHANGED |
  1964. BLOCK_FOR_UPDATE)));
  1965. }
  1966. else
  1967. {
  1968. block->status|= BLOCK_IN_FLUSH | BLOCK_IN_FLUSHWRITE;
  1969. /*
  1970. BLOCK_IN_EVICTION may be true or not. Other flags must
  1971. have a fixed value.
  1972. */
  1973. DBUG_ASSERT((block->status & ~BLOCK_IN_EVICTION) ==
  1974. (BLOCK_READ | BLOCK_IN_SWITCH |
  1975. BLOCK_IN_FLUSH | BLOCK_IN_FLUSHWRITE |
  1976. BLOCK_CHANGED | BLOCK_IN_USE));
  1977. DBUG_ASSERT(block->hash_link);
  1978. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  1979. /*
  1980. The call is thread safe because only the current
  1981. thread might change the block->hash_link value
  1982. */
  1983. error= my_pwrite(block->hash_link->file,
  1984. block->buffer + block->offset,
  1985. block->length - block->offset,
  1986. block->hash_link->diskpos + block->offset,
  1987. MYF(MY_NABP | MY_WAIT_IF_FULL));
  1988. keycache_pthread_mutex_lock(&keycache->cache_lock);
  1989. /* Block status must not have changed. */
  1990. DBUG_ASSERT((block->status & ~BLOCK_IN_EVICTION) ==
  1991. (BLOCK_READ | BLOCK_IN_SWITCH |
  1992. BLOCK_IN_FLUSH | BLOCK_IN_FLUSHWRITE |
  1993. BLOCK_CHANGED | BLOCK_IN_USE) || fail_block(block));
  1994. keycache->global_cache_write++;
  1995. }
  1996. }
  1997. block->status|= BLOCK_REASSIGNED;
  1998. /*
  1999. The block comes from the LRU ring. It must have a hash_link
  2000. assigned.
  2001. */
  2002. DBUG_ASSERT(block->hash_link);
  2003. if (block->hash_link)
  2004. {
  2005. /*
  2006. All pending requests for this page must be resubmitted.
  2007. This must be done before waiting for readers. They could
  2008. wait for the flush to complete. And we must also do it
  2009. after the wait. Flushers might try to free the block while
  2010. we wait. They would wait until the reassignment is
  2011. complete. Also the block status must reflect the correct
  2012. situation: The block is not changed nor in flush any more.
  2013. Note that we must not change the BLOCK_CHANGED flag
  2014. outside of link_to_file_list() so that it is always in the
  2015. correct queue and the *blocks_changed counters are
  2016. correct.
  2017. */
  2018. block->status&= ~(BLOCK_IN_FLUSH | BLOCK_IN_FLUSHWRITE);
  2019. link_to_file_list(keycache, block, block->hash_link->file, 1);
  2020. release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
  2021. /*
  2022. The block is still assigned to its old hash_link.
  2023. Wait until all pending read requests
  2024. for this page are executed
  2025. (we could have avoided this waiting, if we had read
  2026. a page in the cache in a sweep, without yielding control)
  2027. */
  2028. wait_for_readers(keycache, block);
  2029. DBUG_ASSERT(block->hash_link && block->hash_link->block == block &&
  2030. block->prev_changed);
  2031. /* The reader must not have been a writer. */
  2032. DBUG_ASSERT(!(block->status & BLOCK_CHANGED));
  2033. /* Wake flushers that might have found the block in between. */
  2034. release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
  2035. /* Remove the hash link for the old file block from the hash. */
  2036. unlink_hash(keycache, block->hash_link);
  2037. /*
  2038. For sanity checks link_to_file_list() asserts that block
  2039. and hash_link refer to each other. Hence we need to assign
  2040. the hash_link first, but then we would not know if it was
  2041. linked before. Hence we would not know if to unlink it. So
  2042. unlink it here and call link_to_file_list(..., FALSE).
  2043. */
  2044. unlink_changed(block);
  2045. }
  2046. block->status= error ? BLOCK_ERROR : BLOCK_IN_USE ;
  2047. block->length= 0;
  2048. block->offset= keycache->key_cache_block_size;
  2049. block->hash_link= hash_link;
  2050. link_to_file_list(keycache, block, file, 0);
  2051. page_status= PAGE_TO_BE_READ;
  2052. KEYCACHE_DBUG_ASSERT(block->hash_link->block == block);
  2053. KEYCACHE_DBUG_ASSERT(hash_link->block->hash_link == hash_link);
  2054. }
  2055. else
  2056. {
  2057. /*
  2058. Either (block->hash_link == hash_link),
  2059. or (block->status & BLOCK_IN_SWITCH).
  2060. This is for secondary requests for a new file block only.
  2061. Either it is already assigned to the new hash_link meanwhile
  2062. (if we had to wait due to empty LRU), or it is already in
  2063. eviction by another thread. Since this block has been
  2064. grabbed from the LRU ring and attached to this hash_link,
  2065. another thread cannot grab the same block from the LRU ring
  2066. anymore. If the block is in eviction already, it must become
  2067. attached to the same hash_link and as such destined for the
  2068. same file block.
  2069. */
  2070. KEYCACHE_DBUG_PRINT("find_key_block",
  2071. ("block->hash_link: %p hash_link: %p "
  2072. "block->status: %u", block->hash_link,
  2073. hash_link, block->status ));
  2074. page_status= (((block->hash_link == hash_link) &&
  2075. (block->status & BLOCK_READ)) ?
  2076. PAGE_READ : PAGE_WAIT_TO_BE_READ);
  2077. }
  2078. }
  2079. }
  2080. else
  2081. {
  2082. /*
  2083. Block is not NULL. This hash_link points to a block.
  2084. Either
  2085. - block not assigned to this hash_link (yet) or
  2086. - block assigned but not yet read from file,
  2087. or
  2088. - block assigned with valid (changed or unchanged) data and
  2089. - it will not be reassigned/freed.
  2090. The first condition means hash_link points to a block in
  2091. eviction. This is not necessarily marked by BLOCK_IN_SWITCH yet.
  2092. But then it is marked BLOCK_IN_EVICTION. See the NOTE in
  2093. link_block(). In both cases it is destined for this hash_link
  2094. and its file block address. When this hash_link got its block
  2095. address, the block was removed from the LRU ring and cannot be
  2096. selected for eviction (for another hash_link) again.
  2097. Register a request on the block. This is another protection
  2098. against eviction.
  2099. */
  2100. DBUG_ASSERT(((block->hash_link != hash_link) &&
  2101. (block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH))) ||
  2102. ((block->hash_link == hash_link) &&
  2103. !(block->status & BLOCK_READ)) ||
  2104. ((block->status & BLOCK_READ) &&
  2105. !(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH))));
  2106. reg_requests(keycache, block, 1);
  2107. KEYCACHE_DBUG_PRINT("find_key_block",
  2108. ("block->hash_link: %p hash_link: %p "
  2109. "block->status: %u", block->hash_link,
  2110. hash_link, block->status ));
  2111. page_status= (((block->hash_link == hash_link) &&
  2112. (block->status & BLOCK_READ)) ?
  2113. PAGE_READ : PAGE_WAIT_TO_BE_READ);
  2114. }
  2115. }
  2116. KEYCACHE_DBUG_ASSERT(page_status != -1);
  2117. /* Same assert basically, but be very sure. */
  2118. KEYCACHE_DBUG_ASSERT(block);
  2119. /* Assert that block has a request and is not in LRU ring. */
  2120. DBUG_ASSERT(block->requests);
  2121. DBUG_ASSERT(!block->next_used);
  2122. DBUG_ASSERT(!block->prev_used);
  2123. /* Assert that we return the correct block. */
  2124. DBUG_ASSERT((page_status == PAGE_WAIT_TO_BE_READ) ||
  2125. ((block->hash_link->file == file) &&
  2126. (block->hash_link->diskpos == filepos)));
  2127. *page_st=page_status;
  2128. KEYCACHE_DBUG_PRINT("find_key_block",
  2129. ("fd: %d pos: %lu block->status: %u page_status: %d",
  2130. file, (ulong) filepos, block->status,
  2131. page_status));
  2132. #if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
  2133. DBUG_EXECUTE("check_keycache2",
  2134. test_key_cache(keycache, "end of find_key_block",0););
  2135. #endif
  2136. KEYCACHE_THREAD_TRACE("find_key_block:end");
  2137. DBUG_RETURN(block);
  2138. }
  2139. /*
  2140. Read into a key cache block buffer from disk.
  2141. SYNOPSIS
  2142. read_block()
  2143. keycache pointer to a key cache data structure
  2144. block block to which buffer the data is to be read
  2145. read_length size of data to be read
  2146. min_length at least so much data must be read
  2147. primary <-> the current thread will read the data
  2148. RETURN VALUE
  2149. None
  2150. NOTES.
  2151. The function either reads a page data from file to the block buffer,
  2152. or waits until another thread reads it. What page to read is determined
  2153. by a block parameter - reference to a hash link for this page.
  2154. If an error occurs THE BLOCK_ERROR bit is set in the block status.
  2155. We do not report error when the size of successfully read
  2156. portion is less than read_length, but not less than min_length.
  2157. */
  2158. static void read_block(KEY_CACHE *keycache,
  2159. BLOCK_LINK *block, uint read_length,
  2160. uint min_length, my_bool primary)
  2161. {
  2162. size_t got_length;
  2163. /* On entry cache_lock is locked */
  2164. KEYCACHE_THREAD_TRACE("read_block");
  2165. if (primary)
  2166. {
  2167. /*
  2168. This code is executed only by threads that submitted primary
  2169. requests. Until block->status contains BLOCK_READ, all other
  2170. request for the block become secondary requests. For a primary
  2171. request the block must be properly initialized.
  2172. */
  2173. DBUG_ASSERT(((block->status & ~BLOCK_FOR_UPDATE) == BLOCK_IN_USE) ||
  2174. fail_block(block));
  2175. DBUG_ASSERT((block->length == 0) || fail_block(block));
  2176. DBUG_ASSERT((block->offset == keycache->key_cache_block_size) ||
  2177. fail_block(block));
  2178. DBUG_ASSERT((block->requests > 0) || fail_block(block));
  2179. KEYCACHE_DBUG_PRINT("read_block",
  2180. ("page to be read by primary request"));
  2181. keycache->global_cache_read++;
  2182. /* Page is not in buffer yet, is to be read from disk */
  2183. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  2184. /*
  2185. Here other threads may step in and register as secondary readers.
  2186. They will register in block->wqueue[COND_FOR_REQUESTED].
  2187. */
  2188. got_length= my_pread(block->hash_link->file, block->buffer,
  2189. read_length, block->hash_link->diskpos, MYF(0));
  2190. keycache_pthread_mutex_lock(&keycache->cache_lock);
  2191. /*
  2192. The block can now have been marked for free (in case of
  2193. FLUSH_RELEASE). Otherwise the state must be unchanged.
  2194. */
  2195. DBUG_ASSERT(((block->status & ~(BLOCK_REASSIGNED |
  2196. BLOCK_FOR_UPDATE)) == BLOCK_IN_USE) ||
  2197. fail_block(block));
  2198. DBUG_ASSERT((block->length == 0) || fail_block(block));
  2199. DBUG_ASSERT((block->offset == keycache->key_cache_block_size) ||
  2200. fail_block(block));
  2201. DBUG_ASSERT((block->requests > 0) || fail_block(block));
  2202. if (got_length < min_length)
  2203. block->status|= BLOCK_ERROR;
  2204. else
  2205. {
  2206. block->status|= BLOCK_READ;
  2207. block->length= got_length;
  2208. /*
  2209. Do not set block->offset here. If this block is marked
  2210. BLOCK_CHANGED later, we want to flush only the modified part. So
  2211. only a writer may set block->offset down from
  2212. keycache->key_cache_block_size.
  2213. */
  2214. }
  2215. KEYCACHE_DBUG_PRINT("read_block",
  2216. ("primary request: new page in cache"));
  2217. /* Signal that all pending requests for this page now can be processed */
  2218. release_whole_queue(&block->wqueue[COND_FOR_REQUESTED]);
  2219. }
  2220. else
  2221. {
  2222. /*
  2223. This code is executed only by threads that submitted secondary
  2224. requests. At this point it could happen that the cache block is
  2225. not yet assigned to the hash_link for the requested file block.
  2226. But at awake from the wait this should be the case. Unfortunately
  2227. we cannot assert this here because we do not know the hash_link
  2228. for the requested file block nor the file and position. So we have
  2229. to assert this in the caller.
  2230. */
  2231. KEYCACHE_DBUG_PRINT("read_block",
  2232. ("secondary request waiting for new page to be read"));
  2233. wait_on_queue(&block->wqueue[COND_FOR_REQUESTED], &keycache->cache_lock);
  2234. KEYCACHE_DBUG_PRINT("read_block",
  2235. ("secondary request: new page in cache"));
  2236. }
  2237. }
  2238. /*
  2239. Read a block of data from a cached file into a buffer;
  2240. SYNOPSIS
  2241. key_cache_read()
  2242. keycache pointer to a key cache data structure
  2243. file handler for the file for the block of data to be read
  2244. filepos position of the block of data in the file
  2245. level determines the weight of the data
  2246. buff buffer to where the data must be placed
  2247. length length of the buffer
  2248. block_length length of the block in the key cache buffer
  2249. return_buffer return pointer to the key cache buffer with the data
  2250. RETURN VALUE
  2251. Returns address from where the data is placed if sucessful, 0 - otherwise.
  2252. NOTES.
  2253. The function ensures that a block of data of size length from file
  2254. positioned at filepos is in the buffers for some key cache blocks.
  2255. Then the function either copies the data into the buffer buff, or,
  2256. if return_buffer is TRUE, it just returns the pointer to the key cache
  2257. buffer with the data.
  2258. Filepos must be a multiple of 'block_length', but it doesn't
  2259. have to be a multiple of key_cache_block_size;
  2260. */
  2261. uchar *key_cache_read(KEY_CACHE *keycache,
  2262. File file, my_off_t filepos, int level,
  2263. uchar *buff, uint length,
  2264. uint block_length __attribute__((unused)),
  2265. int return_buffer __attribute__((unused)))
  2266. {
  2267. my_bool locked_and_incremented= FALSE;
  2268. int error=0;
  2269. uchar *start= buff;
  2270. DBUG_ENTER("key_cache_read");
  2271. DBUG_PRINT("enter", ("fd: %u pos: %lu length: %u",
  2272. (uint) file, (ulong) filepos, length));
  2273. if (keycache->key_cache_inited)
  2274. {
  2275. /* Key cache is used */
  2276. reg1 BLOCK_LINK *block;
  2277. uint read_length;
  2278. uint offset;
  2279. int page_st;
  2280. if (MYSQL_KEYCACHE_READ_START_ENABLED())
  2281. {
  2282. MYSQL_KEYCACHE_READ_START(my_filename(file), length,
  2283. (ulong) (keycache->blocks_used *
  2284. keycache->key_cache_block_size),
  2285. (ulong) (keycache->blocks_unused *
  2286. keycache->key_cache_block_size));
  2287. }
  2288. /*
  2289. When the key cache is once initialized, we use the cache_lock to
  2290. reliably distinguish the cases of normal operation, resizing, and
  2291. disabled cache. We always increment and decrement
  2292. 'cnt_for_resize_op' so that a resizer can wait for pending I/O.
  2293. */
  2294. keycache_pthread_mutex_lock(&keycache->cache_lock);
  2295. /*
  2296. Cache resizing has two phases: Flushing and re-initializing. In
  2297. the flush phase read requests are allowed to bypass the cache for
  2298. blocks not in the cache. find_key_block() returns NULL in this
  2299. case.
  2300. After the flush phase new I/O requests must wait until the
  2301. re-initialization is done. The re-initialization can be done only
  2302. if no I/O request is in progress. The reason is that
  2303. key_cache_block_size can change. With enabled cache, I/O is done
  2304. in chunks of key_cache_block_size. Every chunk tries to use a
  2305. cache block first. If the block size changes in the middle, a
  2306. block could be missed and old data could be read.
  2307. */
  2308. while (keycache->in_resize && !keycache->resize_in_flush)
  2309. wait_on_queue(&keycache->resize_queue, &keycache->cache_lock);
  2310. /* Register the I/O for the next resize. */
  2311. inc_counter_for_resize_op(keycache);
  2312. locked_and_incremented= TRUE;
  2313. /* Requested data may not always be aligned to cache blocks. */
  2314. offset= (uint) (filepos % keycache->key_cache_block_size);
  2315. /* Read data in key_cache_block_size increments */
  2316. do
  2317. {
  2318. /* Cache could be disabled in a later iteration. */
  2319. if (!keycache->can_be_used)
  2320. {
  2321. KEYCACHE_DBUG_PRINT("key_cache_read", ("keycache cannot be used"));
  2322. goto no_key_cache;
  2323. }
  2324. /* Start reading at the beginning of the cache block. */
  2325. filepos-= offset;
  2326. /* Do not read beyond the end of the cache block. */
  2327. read_length= length;
  2328. set_if_smaller(read_length, keycache->key_cache_block_size-offset);
  2329. KEYCACHE_DBUG_ASSERT(read_length > 0);
  2330. #ifndef THREAD
  2331. if (block_length > keycache->key_cache_block_size || offset)
  2332. return_buffer=0;
  2333. #endif
  2334. /* Request the cache block that matches file/pos. */
  2335. keycache->global_cache_r_requests++;
  2336. MYSQL_KEYCACHE_READ_BLOCK(keycache->key_cache_block_size);
  2337. block=find_key_block(keycache, file, filepos, level, 0, &page_st);
  2338. if (!block)
  2339. {
  2340. /*
  2341. This happens only for requests submitted during key cache
  2342. resize. The block is not in the cache and shall not go in.
  2343. Read directly from file.
  2344. */
  2345. keycache->global_cache_read++;
  2346. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  2347. error= (my_pread(file, (uchar*) buff, read_length,
  2348. filepos + offset, MYF(MY_NABP)) != 0);
  2349. keycache_pthread_mutex_lock(&keycache->cache_lock);
  2350. goto next_block;
  2351. }
  2352. if (!(block->status & BLOCK_ERROR))
  2353. {
  2354. if (page_st != PAGE_READ)
  2355. {
  2356. MYSQL_KEYCACHE_READ_MISS();
  2357. /* The requested page is to be read into the block buffer */
  2358. read_block(keycache, block,
  2359. keycache->key_cache_block_size, read_length+offset,
  2360. (my_bool)(page_st == PAGE_TO_BE_READ));
  2361. /*
  2362. A secondary request must now have the block assigned to the
  2363. requested file block. It does not hurt to check it for
  2364. primary requests too.
  2365. */
  2366. DBUG_ASSERT(keycache->can_be_used);
  2367. DBUG_ASSERT(block->hash_link->file == file);
  2368. DBUG_ASSERT(block->hash_link->diskpos == filepos);
  2369. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  2370. }
  2371. else if (block->length < read_length + offset)
  2372. {
  2373. /*
  2374. Impossible if nothing goes wrong:
  2375. this could only happen if we are using a file with
  2376. small key blocks and are trying to read outside the file
  2377. */
  2378. my_errno= -1;
  2379. block->status|= BLOCK_ERROR;
  2380. }
  2381. else
  2382. {
  2383. MYSQL_KEYCACHE_READ_HIT();
  2384. }
  2385. }
  2386. /* block status may have added BLOCK_ERROR in the above 'if'. */
  2387. if (!(block->status & BLOCK_ERROR))
  2388. {
  2389. #ifndef THREAD
  2390. if (! return_buffer)
  2391. #endif
  2392. {
  2393. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  2394. #if !defined(SERIALIZED_READ_FROM_CACHE)
  2395. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  2396. #endif
  2397. /* Copy data from the cache buffer */
  2398. if (!(read_length & 511))
  2399. bmove512(buff, block->buffer+offset, read_length);
  2400. else
  2401. memcpy(buff, block->buffer+offset, (size_t) read_length);
  2402. #if !defined(SERIALIZED_READ_FROM_CACHE)
  2403. keycache_pthread_mutex_lock(&keycache->cache_lock);
  2404. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  2405. #endif
  2406. }
  2407. }
  2408. remove_reader(block);
  2409. /* Error injection for coverage testing. */
  2410. DBUG_EXECUTE_IF("key_cache_read_block_error",
  2411. block->status|= BLOCK_ERROR;);
  2412. /* Do not link erroneous blocks into the LRU ring, but free them. */
  2413. if (!(block->status & BLOCK_ERROR))
  2414. {
  2415. /*
  2416. Link the block into the LRU ring if it's the last submitted
  2417. request for the block. This enables eviction for the block.
  2418. */
  2419. unreg_request(keycache, block, 1);
  2420. }
  2421. else
  2422. {
  2423. free_block(keycache, block);
  2424. error= 1;
  2425. break;
  2426. }
  2427. #ifndef THREAD
  2428. /* This is only true if we where able to read everything in one block */
  2429. if (return_buffer)
  2430. {
  2431. if (MYSQL_KEYCACHE_READ_DONE_ENABLED())
  2432. {
  2433. MYSQL_KEYCACHE_READ_DONE((ulong) (keycache->blocks_used *
  2434. keycache->key_cache_block_size),
  2435. (ulong) (keycache->blocks_unused *
  2436. keycache->key_cache_block_size));
  2437. }
  2438. DBUG_RETURN(block->buffer);
  2439. }
  2440. #endif
  2441. next_block:
  2442. buff+= read_length;
  2443. filepos+= read_length+offset;
  2444. offset= 0;
  2445. } while ((length-= read_length));
  2446. if (MYSQL_KEYCACHE_READ_DONE_ENABLED())
  2447. {
  2448. MYSQL_KEYCACHE_READ_DONE((ulong) (keycache->blocks_used *
  2449. keycache->key_cache_block_size),
  2450. (ulong) (keycache->blocks_unused *
  2451. keycache->key_cache_block_size));
  2452. }
  2453. goto end;
  2454. }
  2455. KEYCACHE_DBUG_PRINT("key_cache_read", ("keycache not initialized"));
  2456. no_key_cache:
  2457. /* Key cache is not used */
  2458. keycache->global_cache_r_requests++;
  2459. keycache->global_cache_read++;
  2460. if (locked_and_incremented)
  2461. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  2462. if (my_pread(file, (uchar*) buff, length, filepos, MYF(MY_NABP)))
  2463. error= 1;
  2464. if (locked_and_incremented)
  2465. keycache_pthread_mutex_lock(&keycache->cache_lock);
  2466. end:
  2467. if (locked_and_incremented)
  2468. {
  2469. dec_counter_for_resize_op(keycache);
  2470. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  2471. }
  2472. DBUG_PRINT("exit", ("error: %d", error ));
  2473. DBUG_RETURN(error ? (uchar*) 0 : start);
  2474. }
  2475. /*
  2476. Insert a block of file data from a buffer into key cache
  2477. SYNOPSIS
  2478. key_cache_insert()
  2479. keycache pointer to a key cache data structure
  2480. file handler for the file to insert data from
  2481. filepos position of the block of data in the file to insert
  2482. level determines the weight of the data
  2483. buff buffer to read data from
  2484. length length of the data in the buffer
  2485. NOTES
  2486. This is used by MyISAM to move all blocks from a index file to the key
  2487. cache
  2488. RETURN VALUE
  2489. 0 if a success, 1 - otherwise.
  2490. */
  2491. int key_cache_insert(KEY_CACHE *keycache,
  2492. File file, my_off_t filepos, int level,
  2493. uchar *buff, uint length)
  2494. {
  2495. int error= 0;
  2496. DBUG_ENTER("key_cache_insert");
  2497. DBUG_PRINT("enter", ("fd: %u pos: %lu length: %u",
  2498. (uint) file,(ulong) filepos, length));
  2499. if (keycache->key_cache_inited)
  2500. {
  2501. /* Key cache is used */
  2502. reg1 BLOCK_LINK *block;
  2503. uint read_length;
  2504. uint offset;
  2505. int page_st;
  2506. my_bool locked_and_incremented= FALSE;
  2507. /*
  2508. When the keycache is once initialized, we use the cache_lock to
  2509. reliably distinguish the cases of normal operation, resizing, and
  2510. disabled cache. We always increment and decrement
  2511. 'cnt_for_resize_op' so that a resizer can wait for pending I/O.
  2512. */
  2513. keycache_pthread_mutex_lock(&keycache->cache_lock);
  2514. /*
  2515. We do not load index data into a disabled cache nor into an
  2516. ongoing resize.
  2517. */
  2518. if (!keycache->can_be_used || keycache->in_resize)
  2519. goto no_key_cache;
  2520. /* Register the pseudo I/O for the next resize. */
  2521. inc_counter_for_resize_op(keycache);
  2522. locked_and_incremented= TRUE;
  2523. /* Loaded data may not always be aligned to cache blocks. */
  2524. offset= (uint) (filepos % keycache->key_cache_block_size);
  2525. /* Load data in key_cache_block_size increments. */
  2526. do
  2527. {
  2528. /* Cache could be disabled or resizing in a later iteration. */
  2529. if (!keycache->can_be_used || keycache->in_resize)
  2530. goto no_key_cache;
  2531. /* Start loading at the beginning of the cache block. */
  2532. filepos-= offset;
  2533. /* Do not load beyond the end of the cache block. */
  2534. read_length= length;
  2535. set_if_smaller(read_length, keycache->key_cache_block_size-offset);
  2536. KEYCACHE_DBUG_ASSERT(read_length > 0);
  2537. /* The block has been read by the caller already. */
  2538. keycache->global_cache_read++;
  2539. /* Request the cache block that matches file/pos. */
  2540. keycache->global_cache_r_requests++;
  2541. block= find_key_block(keycache, file, filepos, level, 0, &page_st);
  2542. if (!block)
  2543. {
  2544. /*
  2545. This happens only for requests submitted during key cache
  2546. resize. The block is not in the cache and shall not go in.
  2547. Stop loading index data.
  2548. */
  2549. goto no_key_cache;
  2550. }
  2551. if (!(block->status & BLOCK_ERROR))
  2552. {
  2553. if ((page_st == PAGE_WAIT_TO_BE_READ) ||
  2554. ((page_st == PAGE_TO_BE_READ) &&
  2555. (offset || (read_length < keycache->key_cache_block_size))))
  2556. {
  2557. /*
  2558. Either
  2559. this is a secondary request for a block to be read into the
  2560. cache. The block is in eviction. It is not yet assigned to
  2561. the requested file block (It does not point to the right
  2562. hash_link). So we cannot call remove_reader() on the block.
  2563. And we cannot access the hash_link directly here. We need to
  2564. wait until the assignment is complete. read_block() executes
  2565. the correct wait when called with primary == FALSE.
  2566. Or
  2567. this is a primary request for a block to be read into the
  2568. cache and the supplied data does not fill the whole block.
  2569. This function is called on behalf of a LOAD INDEX INTO CACHE
  2570. statement, which is a read-only task and allows other
  2571. readers. It is possible that a parallel running reader tries
  2572. to access this block. If it needs more data than has been
  2573. supplied here, it would report an error. To be sure that we
  2574. have all data in the block that is available in the file, we
  2575. read the block ourselves.
  2576. Though reading again what the caller did read already is an
  2577. expensive operation, we need to do this for correctness.
  2578. */
  2579. read_block(keycache, block, keycache->key_cache_block_size,
  2580. read_length + offset, (page_st == PAGE_TO_BE_READ));
  2581. /*
  2582. A secondary request must now have the block assigned to the
  2583. requested file block. It does not hurt to check it for
  2584. primary requests too.
  2585. */
  2586. DBUG_ASSERT(keycache->can_be_used);
  2587. DBUG_ASSERT(block->hash_link->file == file);
  2588. DBUG_ASSERT(block->hash_link->diskpos == filepos);
  2589. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  2590. }
  2591. else if (page_st == PAGE_TO_BE_READ)
  2592. {
  2593. /*
  2594. This is a new block in the cache. If we come here, we have
  2595. data for the whole block.
  2596. */
  2597. DBUG_ASSERT(block->hash_link->requests);
  2598. DBUG_ASSERT(block->status & BLOCK_IN_USE);
  2599. DBUG_ASSERT((page_st == PAGE_TO_BE_READ) ||
  2600. (block->status & BLOCK_READ));
  2601. #if !defined(SERIALIZED_READ_FROM_CACHE)
  2602. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  2603. /*
  2604. Here other threads may step in and register as secondary readers.
  2605. They will register in block->wqueue[COND_FOR_REQUESTED].
  2606. */
  2607. #endif
  2608. /* Copy data from buff */
  2609. if (!(read_length & 511))
  2610. bmove512(block->buffer+offset, buff, read_length);
  2611. else
  2612. memcpy(block->buffer+offset, buff, (size_t) read_length);
  2613. #if !defined(SERIALIZED_READ_FROM_CACHE)
  2614. keycache_pthread_mutex_lock(&keycache->cache_lock);
  2615. DBUG_ASSERT(block->status & BLOCK_IN_USE);
  2616. DBUG_ASSERT((page_st == PAGE_TO_BE_READ) ||
  2617. (block->status & BLOCK_READ));
  2618. #endif
  2619. /*
  2620. After the data is in the buffer, we can declare the block
  2621. valid. Now other threads do not need to register as
  2622. secondary readers any more. They can immediately access the
  2623. block.
  2624. */
  2625. block->status|= BLOCK_READ;
  2626. block->length= read_length+offset;
  2627. /*
  2628. Do not set block->offset here. If this block is marked
  2629. BLOCK_CHANGED later, we want to flush only the modified part. So
  2630. only a writer may set block->offset down from
  2631. keycache->key_cache_block_size.
  2632. */
  2633. KEYCACHE_DBUG_PRINT("key_cache_insert",
  2634. ("primary request: new page in cache"));
  2635. /* Signal all pending requests. */
  2636. release_whole_queue(&block->wqueue[COND_FOR_REQUESTED]);
  2637. }
  2638. else
  2639. {
  2640. /*
  2641. page_st == PAGE_READ. The block is in the buffer. All data
  2642. must already be present. Blocks are always read with all
  2643. data available on file. Assert that the block does not have
  2644. less contents than the preloader supplies. If the caller has
  2645. data beyond block->length, it means that a file write has
  2646. been done while this block was in cache and not extended
  2647. with the new data. If the condition is met, we can simply
  2648. ignore the block.
  2649. */
  2650. DBUG_ASSERT((page_st == PAGE_READ) &&
  2651. (read_length + offset <= block->length));
  2652. }
  2653. /*
  2654. A secondary request must now have the block assigned to the
  2655. requested file block. It does not hurt to check it for primary
  2656. requests too.
  2657. */
  2658. DBUG_ASSERT(block->hash_link->file == file);
  2659. DBUG_ASSERT(block->hash_link->diskpos == filepos);
  2660. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  2661. } /* end of if (!(block->status & BLOCK_ERROR)) */
  2662. remove_reader(block);
  2663. /* Error injection for coverage testing. */
  2664. DBUG_EXECUTE_IF("key_cache_insert_block_error",
  2665. block->status|= BLOCK_ERROR; errno=EIO;);
  2666. /* Do not link erroneous blocks into the LRU ring, but free them. */
  2667. if (!(block->status & BLOCK_ERROR))
  2668. {
  2669. /*
  2670. Link the block into the LRU ring if it's the last submitted
  2671. request for the block. This enables eviction for the block.
  2672. */
  2673. unreg_request(keycache, block, 1);
  2674. }
  2675. else
  2676. {
  2677. free_block(keycache, block);
  2678. error= 1;
  2679. break;
  2680. }
  2681. buff+= read_length;
  2682. filepos+= read_length+offset;
  2683. offset= 0;
  2684. } while ((length-= read_length));
  2685. no_key_cache:
  2686. if (locked_and_incremented)
  2687. dec_counter_for_resize_op(keycache);
  2688. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  2689. }
  2690. DBUG_RETURN(error);
  2691. }
  2692. /*
  2693. Write a buffer into a cached file.
  2694. SYNOPSIS
  2695. key_cache_write()
  2696. keycache pointer to a key cache data structure
  2697. file handler for the file to write data to
  2698. filepos position in the file to write data to
  2699. level determines the weight of the data
  2700. buff buffer with the data
  2701. length length of the buffer
  2702. dont_write if is 0 then all dirty pages involved in writing
  2703. should have been flushed from key cache
  2704. RETURN VALUE
  2705. 0 if a success, 1 - otherwise.
  2706. NOTES.
  2707. The function copies the data of size length from buff into buffers
  2708. for key cache blocks that are assigned to contain the portion of
  2709. the file starting with position filepos.
  2710. It ensures that this data is flushed to the file if dont_write is FALSE.
  2711. Filepos must be a multiple of 'block_length', but it doesn't
  2712. have to be a multiple of key_cache_block_size;
  2713. dont_write is always TRUE in the server (info->lock_type is never F_UNLCK).
  2714. */
  2715. int key_cache_write(KEY_CACHE *keycache,
  2716. File file, my_off_t filepos, int level,
  2717. uchar *buff, uint length,
  2718. uint block_length __attribute__((unused)),
  2719. int dont_write)
  2720. {
  2721. my_bool locked_and_incremented= FALSE;
  2722. int error=0;
  2723. DBUG_ENTER("key_cache_write");
  2724. DBUG_PRINT("enter",
  2725. ("fd: %u pos: %lu length: %u block_length: %u"
  2726. " key_block_length: %u",
  2727. (uint) file, (ulong) filepos, length, block_length,
  2728. keycache ? keycache->key_cache_block_size : 0));
  2729. if (!dont_write)
  2730. {
  2731. /* purecov: begin inspected */
  2732. /* Not used in the server. */
  2733. /* Force writing from buff into disk. */
  2734. keycache->global_cache_w_requests++;
  2735. keycache->global_cache_write++;
  2736. if (my_pwrite(file, buff, length, filepos, MYF(MY_NABP | MY_WAIT_IF_FULL)))
  2737. DBUG_RETURN(1);
  2738. /* purecov: end */
  2739. }
  2740. #if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
  2741. DBUG_EXECUTE("check_keycache",
  2742. test_key_cache(keycache, "start of key_cache_write", 1););
  2743. #endif
  2744. if (keycache->key_cache_inited)
  2745. {
  2746. /* Key cache is used */
  2747. reg1 BLOCK_LINK *block;
  2748. uint read_length;
  2749. uint offset;
  2750. int page_st;
  2751. if (MYSQL_KEYCACHE_WRITE_START_ENABLED())
  2752. {
  2753. MYSQL_KEYCACHE_WRITE_START(my_filename(file), length,
  2754. (ulong) (keycache->blocks_used *
  2755. keycache->key_cache_block_size),
  2756. (ulong) (keycache->blocks_unused *
  2757. keycache->key_cache_block_size));
  2758. }
  2759. /*
  2760. When the key cache is once initialized, we use the cache_lock to
  2761. reliably distinguish the cases of normal operation, resizing, and
  2762. disabled cache. We always increment and decrement
  2763. 'cnt_for_resize_op' so that a resizer can wait for pending I/O.
  2764. */
  2765. keycache_pthread_mutex_lock(&keycache->cache_lock);
  2766. /*
  2767. Cache resizing has two phases: Flushing and re-initializing. In
  2768. the flush phase write requests can modify dirty blocks that are
  2769. not yet in flush. Otherwise they are allowed to bypass the cache.
  2770. find_key_block() returns NULL in both cases (clean blocks and
  2771. non-cached blocks).
  2772. After the flush phase new I/O requests must wait until the
  2773. re-initialization is done. The re-initialization can be done only
  2774. if no I/O request is in progress. The reason is that
  2775. key_cache_block_size can change. With enabled cache I/O is done in
  2776. chunks of key_cache_block_size. Every chunk tries to use a cache
  2777. block first. If the block size changes in the middle, a block
  2778. could be missed and data could be written below a cached block.
  2779. */
  2780. while (keycache->in_resize && !keycache->resize_in_flush)
  2781. wait_on_queue(&keycache->resize_queue, &keycache->cache_lock);
  2782. /* Register the I/O for the next resize. */
  2783. inc_counter_for_resize_op(keycache);
  2784. locked_and_incremented= TRUE;
  2785. /* Requested data may not always be aligned to cache blocks. */
  2786. offset= (uint) (filepos % keycache->key_cache_block_size);
  2787. /* Write data in key_cache_block_size increments. */
  2788. do
  2789. {
  2790. /* Cache could be disabled in a later iteration. */
  2791. if (!keycache->can_be_used)
  2792. goto no_key_cache;
  2793. MYSQL_KEYCACHE_WRITE_BLOCK(keycache->key_cache_block_size);
  2794. /* Start writing at the beginning of the cache block. */
  2795. filepos-= offset;
  2796. /* Do not write beyond the end of the cache block. */
  2797. read_length= length;
  2798. set_if_smaller(read_length, keycache->key_cache_block_size-offset);
  2799. KEYCACHE_DBUG_ASSERT(read_length > 0);
  2800. /* Request the cache block that matches file/pos. */
  2801. keycache->global_cache_w_requests++;
  2802. block= find_key_block(keycache, file, filepos, level, 1, &page_st);
  2803. if (!block)
  2804. {
  2805. /*
  2806. This happens only for requests submitted during key cache
  2807. resize. The block is not in the cache and shall not go in.
  2808. Write directly to file.
  2809. */
  2810. if (dont_write)
  2811. {
  2812. /* Used in the server. */
  2813. keycache->global_cache_write++;
  2814. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  2815. if (my_pwrite(file, (uchar*) buff, read_length, filepos + offset,
  2816. MYF(MY_NABP | MY_WAIT_IF_FULL)))
  2817. error=1;
  2818. keycache_pthread_mutex_lock(&keycache->cache_lock);
  2819. }
  2820. goto next_block;
  2821. }
  2822. /*
  2823. Prevent block from flushing and from being selected for to be
  2824. freed. This must be set when we release the cache_lock.
  2825. However, we must not set the status of the block before it is
  2826. assigned to this file/pos.
  2827. */
  2828. if (page_st != PAGE_WAIT_TO_BE_READ)
  2829. block->status|= BLOCK_FOR_UPDATE;
  2830. /*
  2831. We must read the file block first if it is not yet in the cache
  2832. and we do not replace all of its contents.
  2833. In cases where the cache block is big enough to contain (parts
  2834. of) index blocks of different indexes, our request can be
  2835. secondary (PAGE_WAIT_TO_BE_READ). In this case another thread is
  2836. reading the file block. If the read completes after us, it
  2837. overwrites our new contents with the old contents. So we have to
  2838. wait for the other thread to complete the read of this block.
  2839. read_block() takes care for the wait.
  2840. */
  2841. if (!(block->status & BLOCK_ERROR) &&
  2842. ((page_st == PAGE_TO_BE_READ &&
  2843. (offset || read_length < keycache->key_cache_block_size)) ||
  2844. (page_st == PAGE_WAIT_TO_BE_READ)))
  2845. {
  2846. read_block(keycache, block,
  2847. offset + read_length >= keycache->key_cache_block_size?
  2848. offset : keycache->key_cache_block_size,
  2849. offset, (page_st == PAGE_TO_BE_READ));
  2850. DBUG_ASSERT(keycache->can_be_used);
  2851. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  2852. /*
  2853. Prevent block from flushing and from being selected for to be
  2854. freed. This must be set when we release the cache_lock.
  2855. Here we set it in case we could not set it above.
  2856. */
  2857. block->status|= BLOCK_FOR_UPDATE;
  2858. }
  2859. /*
  2860. The block should always be assigned to the requested file block
  2861. here. It need not be BLOCK_READ when overwriting the whole block.
  2862. */
  2863. DBUG_ASSERT(block->hash_link->file == file);
  2864. DBUG_ASSERT(block->hash_link->diskpos == filepos);
  2865. DBUG_ASSERT(block->status & BLOCK_IN_USE);
  2866. DBUG_ASSERT((page_st == PAGE_TO_BE_READ) || (block->status & BLOCK_READ));
  2867. /*
  2868. The block to be written must not be marked BLOCK_REASSIGNED.
  2869. Otherwise it could be freed in dirty state or reused without
  2870. another flush during eviction. It must also not be in flush.
  2871. Otherwise the old contens may have been flushed already and
  2872. the flusher could clear BLOCK_CHANGED without flushing the
  2873. new changes again.
  2874. */
  2875. DBUG_ASSERT(!(block->status & BLOCK_REASSIGNED));
  2876. while (block->status & BLOCK_IN_FLUSHWRITE)
  2877. {
  2878. /*
  2879. Another thread is flushing the block. It was dirty already.
  2880. Wait until the block is flushed to file. Otherwise we could
  2881. modify the buffer contents just while it is written to file.
  2882. An unpredictable file block contents would be the result.
  2883. While we wait, several things can happen to the block,
  2884. including another flush. But the block cannot be reassigned to
  2885. another hash_link until we release our request on it.
  2886. */
  2887. wait_on_queue(&block->wqueue[COND_FOR_SAVED], &keycache->cache_lock);
  2888. DBUG_ASSERT(keycache->can_be_used);
  2889. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  2890. /* Still must not be marked for free. */
  2891. DBUG_ASSERT(!(block->status & BLOCK_REASSIGNED));
  2892. DBUG_ASSERT(block->hash_link && (block->hash_link->block == block));
  2893. }
  2894. /*
  2895. We could perhaps release the cache_lock during access of the
  2896. data like in the other functions. Locks outside of the key cache
  2897. assure that readers and a writer do not access the same range of
  2898. data. Parallel accesses should happen only if the cache block
  2899. contains multiple index block(fragment)s. So different parts of
  2900. the buffer would be read/written. An attempt to flush during
  2901. memcpy() is prevented with BLOCK_FOR_UPDATE.
  2902. */
  2903. if (!(block->status & BLOCK_ERROR))
  2904. {
  2905. #if !defined(SERIALIZED_READ_FROM_CACHE)
  2906. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  2907. #endif
  2908. if (!(read_length & 511))
  2909. bmove512(block->buffer+offset, buff, read_length);
  2910. else
  2911. memcpy(block->buffer+offset, buff, (size_t) read_length);
  2912. #if !defined(SERIALIZED_READ_FROM_CACHE)
  2913. keycache_pthread_mutex_lock(&keycache->cache_lock);
  2914. #endif
  2915. }
  2916. if (!dont_write)
  2917. {
  2918. /* Not used in the server. buff has been written to disk at start. */
  2919. if ((block->status & BLOCK_CHANGED) &&
  2920. (!offset && read_length >= keycache->key_cache_block_size))
  2921. link_to_file_list(keycache, block, block->hash_link->file, 1);
  2922. }
  2923. else if (! (block->status & BLOCK_CHANGED))
  2924. link_to_changed_list(keycache, block);
  2925. block->status|=BLOCK_READ;
  2926. /*
  2927. Allow block to be selected for to be freed. Since it is marked
  2928. BLOCK_CHANGED too, it won't be selected for to be freed without
  2929. a flush.
  2930. */
  2931. block->status&= ~BLOCK_FOR_UPDATE;
  2932. set_if_smaller(block->offset, offset);
  2933. set_if_bigger(block->length, read_length+offset);
  2934. /* Threads may be waiting for the changes to be complete. */
  2935. release_whole_queue(&block->wqueue[COND_FOR_REQUESTED]);
  2936. /*
  2937. If only a part of the cache block is to be replaced, and the
  2938. rest has been read from file, then the cache lock has been
  2939. released for I/O and it could be possible that another thread
  2940. wants to evict or free the block and waits for it to be
  2941. released. So we must not just decrement hash_link->requests, but
  2942. also wake a waiting thread.
  2943. */
  2944. remove_reader(block);
  2945. /* Error injection for coverage testing. */
  2946. DBUG_EXECUTE_IF("key_cache_write_block_error",
  2947. block->status|= BLOCK_ERROR;);
  2948. /* Do not link erroneous blocks into the LRU ring, but free them. */
  2949. if (!(block->status & BLOCK_ERROR))
  2950. {
  2951. /*
  2952. Link the block into the LRU ring if it's the last submitted
  2953. request for the block. This enables eviction for the block.
  2954. */
  2955. unreg_request(keycache, block, 1);
  2956. }
  2957. else
  2958. {
  2959. /* Pretend a "clean" block to avoid complications. */
  2960. block->status&= ~(BLOCK_CHANGED);
  2961. free_block(keycache, block);
  2962. error= 1;
  2963. break;
  2964. }
  2965. next_block:
  2966. buff+= read_length;
  2967. filepos+= read_length+offset;
  2968. offset= 0;
  2969. } while ((length-= read_length));
  2970. goto end;
  2971. }
  2972. no_key_cache:
  2973. /* Key cache is not used */
  2974. if (dont_write)
  2975. {
  2976. /* Used in the server. */
  2977. keycache->global_cache_w_requests++;
  2978. keycache->global_cache_write++;
  2979. if (locked_and_incremented)
  2980. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  2981. if (my_pwrite(file, (uchar*) buff, length, filepos,
  2982. MYF(MY_NABP | MY_WAIT_IF_FULL)))
  2983. error=1;
  2984. if (locked_and_incremented)
  2985. keycache_pthread_mutex_lock(&keycache->cache_lock);
  2986. }
  2987. end:
  2988. if (locked_and_incremented)
  2989. {
  2990. dec_counter_for_resize_op(keycache);
  2991. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  2992. }
  2993. if (MYSQL_KEYCACHE_WRITE_DONE_ENABLED())
  2994. {
  2995. MYSQL_KEYCACHE_WRITE_DONE((ulong) (keycache->blocks_used *
  2996. keycache->key_cache_block_size),
  2997. (ulong) (keycache->blocks_unused *
  2998. keycache->key_cache_block_size));
  2999. }
  3000. #if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
  3001. DBUG_EXECUTE("exec",
  3002. test_key_cache(keycache, "end of key_cache_write", 1););
  3003. #endif
  3004. DBUG_RETURN(error);
  3005. }
  3006. /*
  3007. Free block.
  3008. SYNOPSIS
  3009. free_block()
  3010. keycache Pointer to a key cache data structure
  3011. block Pointer to the block to free
  3012. DESCRIPTION
  3013. Remove reference to block from hash table.
  3014. Remove block from the chain of clean blocks.
  3015. Add block to the free list.
  3016. NOTE
  3017. Block must not be free (status == 0).
  3018. Block must not be in free_block_list.
  3019. Block must not be in the LRU ring.
  3020. Block must not be in eviction (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH).
  3021. Block must not be in free (BLOCK_REASSIGNED).
  3022. Block must not be in flush (BLOCK_IN_FLUSH).
  3023. Block must not be dirty (BLOCK_CHANGED).
  3024. Block must not be in changed_blocks (dirty) hash.
  3025. Block must be in file_blocks (clean) hash.
  3026. Block must refer to a hash_link.
  3027. Block must have a request registered on it.
  3028. */
  3029. static void free_block(KEY_CACHE *keycache, BLOCK_LINK *block)
  3030. {
  3031. KEYCACHE_THREAD_TRACE("free block");
  3032. KEYCACHE_DBUG_PRINT("free_block",
  3033. ("block %u to be freed, hash_link %p status: %u",
  3034. BLOCK_NUMBER(block), block->hash_link,
  3035. block->status));
  3036. /*
  3037. Assert that the block is not free already. And that it is in a clean
  3038. state. Note that the block might just be assigned to a hash_link and
  3039. not yet read (BLOCK_READ may not be set here). In this case a reader
  3040. is registered in the hash_link and free_block() will wait for it
  3041. below.
  3042. */
  3043. DBUG_ASSERT((block->status & BLOCK_IN_USE) &&
  3044. !(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
  3045. BLOCK_REASSIGNED | BLOCK_IN_FLUSH |
  3046. BLOCK_CHANGED | BLOCK_FOR_UPDATE)));
  3047. /* Assert that the block is in a file_blocks chain. */
  3048. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  3049. /* Assert that the block is not in the LRU ring. */
  3050. DBUG_ASSERT(!block->next_used && !block->prev_used);
  3051. /*
  3052. IMHO the below condition (if()) makes no sense. I can't see how it
  3053. could be possible that free_block() is entered with a NULL hash_link
  3054. pointer. The only place where it can become NULL is in free_block()
  3055. (or before its first use ever, but for those blocks free_block() is
  3056. not called). I don't remove the conditional as it cannot harm, but
  3057. place an DBUG_ASSERT to confirm my hypothesis. Eventually the
  3058. condition (if()) can be removed.
  3059. */
  3060. DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
  3061. if (block->hash_link)
  3062. {
  3063. /*
  3064. While waiting for readers to finish, new readers might request the
  3065. block. But since we set block->status|= BLOCK_REASSIGNED, they
  3066. will wait on block->wqueue[COND_FOR_SAVED]. They must be signalled
  3067. later.
  3068. */
  3069. block->status|= BLOCK_REASSIGNED;
  3070. wait_for_readers(keycache, block);
  3071. /*
  3072. The block must not have been freed by another thread. Repeat some
  3073. checks. An additional requirement is that it must be read now
  3074. (BLOCK_READ).
  3075. */
  3076. DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
  3077. DBUG_ASSERT((block->status & (BLOCK_READ | BLOCK_IN_USE |
  3078. BLOCK_REASSIGNED)) &&
  3079. !(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
  3080. BLOCK_IN_FLUSH | BLOCK_CHANGED |
  3081. BLOCK_FOR_UPDATE)));
  3082. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  3083. DBUG_ASSERT(!block->prev_used);
  3084. /*
  3085. Unset BLOCK_REASSIGNED again. If we hand the block to an evicting
  3086. thread (through unreg_request() below), other threads must not see
  3087. this flag. They could become confused.
  3088. */
  3089. block->status&= ~BLOCK_REASSIGNED;
  3090. /*
  3091. Do not release the hash_link until the block is off all lists.
  3092. At least not if we hand it over for eviction in unreg_request().
  3093. */
  3094. }
  3095. /*
  3096. Unregister the block request and link the block into the LRU ring.
  3097. This enables eviction for the block. If the LRU ring was empty and
  3098. threads are waiting for a block, then the block wil be handed over
  3099. for eviction immediately. Otherwise we will unlink it from the LRU
  3100. ring again, without releasing the lock in between. So decrementing
  3101. the request counter and updating statistics are the only relevant
  3102. operation in this case. Assert that there are no other requests
  3103. registered.
  3104. */
  3105. DBUG_ASSERT(block->requests == 1);
  3106. unreg_request(keycache, block, 0);
  3107. /*
  3108. Note that even without releasing the cache lock it is possible that
  3109. the block is immediately selected for eviction by link_block() and
  3110. thus not added to the LRU ring. In this case we must not touch the
  3111. block any more.
  3112. */
  3113. if (block->status & BLOCK_IN_EVICTION)
  3114. return;
  3115. /* Error blocks are not put into the LRU ring. */
  3116. if (!(block->status & BLOCK_ERROR))
  3117. {
  3118. /* Here the block must be in the LRU ring. Unlink it again. */
  3119. DBUG_ASSERT(block->next_used && block->prev_used &&
  3120. *block->prev_used == block);
  3121. unlink_block(keycache, block);
  3122. }
  3123. if (block->temperature == BLOCK_WARM)
  3124. keycache->warm_blocks--;
  3125. block->temperature= BLOCK_COLD;
  3126. /* Remove from file_blocks hash. */
  3127. unlink_changed(block);
  3128. /* Remove reference to block from hash table. */
  3129. unlink_hash(keycache, block->hash_link);
  3130. block->hash_link= NULL;
  3131. block->status= 0;
  3132. block->length= 0;
  3133. block->offset= keycache->key_cache_block_size;
  3134. KEYCACHE_THREAD_TRACE("free block");
  3135. KEYCACHE_DBUG_PRINT("free_block", ("block is freed"));
  3136. /* Enforced by unlink_changed(), but just to be sure. */
  3137. DBUG_ASSERT(!block->next_changed && !block->prev_changed);
  3138. /* Enforced by unlink_block(): not in LRU ring nor in free_block_list. */
  3139. DBUG_ASSERT(!block->next_used && !block->prev_used);
  3140. /* Insert the free block in the free list. */
  3141. block->next_used= keycache->free_block_list;
  3142. keycache->free_block_list= block;
  3143. /* Keep track of the number of currently unused blocks. */
  3144. keycache->blocks_unused++;
  3145. /* All pending requests for this page must be resubmitted. */
  3146. release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
  3147. }
  3148. static int cmp_sec_link(BLOCK_LINK **a, BLOCK_LINK **b)
  3149. {
  3150. return (((*a)->hash_link->diskpos < (*b)->hash_link->diskpos) ? -1 :
  3151. ((*a)->hash_link->diskpos > (*b)->hash_link->diskpos) ? 1 : 0);
  3152. }
  3153. /*
  3154. Flush a portion of changed blocks to disk,
  3155. free used blocks if requested
  3156. */
  3157. static int flush_cached_blocks(KEY_CACHE *keycache,
  3158. File file, BLOCK_LINK **cache,
  3159. BLOCK_LINK **end,
  3160. enum flush_type type)
  3161. {
  3162. int error;
  3163. int last_errno= 0;
  3164. uint count= (uint) (end-cache);
  3165. /* Don't lock the cache during the flush */
  3166. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  3167. /*
  3168. As all blocks referred in 'cache' are marked by BLOCK_IN_FLUSH
  3169. we are guarunteed no thread will change them
  3170. */
  3171. my_qsort((uchar*) cache, count, sizeof(*cache), (qsort_cmp) cmp_sec_link);
  3172. keycache_pthread_mutex_lock(&keycache->cache_lock);
  3173. /*
  3174. Note: Do not break the loop. We have registered a request on every
  3175. block in 'cache'. These must be unregistered by free_block() or
  3176. unreg_request().
  3177. */
  3178. for ( ; cache != end ; cache++)
  3179. {
  3180. BLOCK_LINK *block= *cache;
  3181. KEYCACHE_DBUG_PRINT("flush_cached_blocks",
  3182. ("block %u to be flushed", BLOCK_NUMBER(block)));
  3183. /*
  3184. If the block contents is going to be changed, we abandon the flush
  3185. for this block. flush_key_blocks_int() will restart its search and
  3186. handle the block properly.
  3187. */
  3188. if (!(block->status & BLOCK_FOR_UPDATE))
  3189. {
  3190. /* Blocks coming here must have a certain status. */
  3191. DBUG_ASSERT(block->hash_link);
  3192. DBUG_ASSERT(block->hash_link->block == block);
  3193. DBUG_ASSERT(block->hash_link->file == file);
  3194. DBUG_ASSERT((block->status & ~BLOCK_IN_EVICTION) ==
  3195. (BLOCK_READ | BLOCK_IN_FLUSH | BLOCK_CHANGED | BLOCK_IN_USE));
  3196. block->status|= BLOCK_IN_FLUSHWRITE;
  3197. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  3198. error= my_pwrite(file, block->buffer+block->offset,
  3199. block->length - block->offset,
  3200. block->hash_link->diskpos+ block->offset,
  3201. MYF(MY_NABP | MY_WAIT_IF_FULL));
  3202. keycache_pthread_mutex_lock(&keycache->cache_lock);
  3203. keycache->global_cache_write++;
  3204. if (error)
  3205. {
  3206. block->status|= BLOCK_ERROR;
  3207. if (!last_errno)
  3208. last_errno= errno ? errno : -1;
  3209. }
  3210. block->status&= ~BLOCK_IN_FLUSHWRITE;
  3211. /* Block must not have changed status except BLOCK_FOR_UPDATE. */
  3212. DBUG_ASSERT(block->hash_link);
  3213. DBUG_ASSERT(block->hash_link->block == block);
  3214. DBUG_ASSERT(block->hash_link->file == file);
  3215. DBUG_ASSERT((block->status & ~(BLOCK_FOR_UPDATE | BLOCK_IN_EVICTION)) ==
  3216. (BLOCK_READ | BLOCK_IN_FLUSH | BLOCK_CHANGED | BLOCK_IN_USE));
  3217. /*
  3218. Set correct status and link in right queue for free or later use.
  3219. free_block() must not see BLOCK_CHANGED and it may need to wait
  3220. for readers of the block. These should not see the block in the
  3221. wrong hash. If not freeing the block, we need to have it in the
  3222. right queue anyway.
  3223. */
  3224. link_to_file_list(keycache, block, file, 1);
  3225. }
  3226. block->status&= ~BLOCK_IN_FLUSH;
  3227. /*
  3228. Let to proceed for possible waiting requests to write to the block page.
  3229. It might happen only during an operation to resize the key cache.
  3230. */
  3231. release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
  3232. /* type will never be FLUSH_IGNORE_CHANGED here */
  3233. if (!(type == FLUSH_KEEP || type == FLUSH_FORCE_WRITE) &&
  3234. !(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
  3235. BLOCK_FOR_UPDATE)))
  3236. {
  3237. /*
  3238. Note that a request has been registered against the block in
  3239. flush_key_blocks_int().
  3240. */
  3241. free_block(keycache, block);
  3242. }
  3243. else
  3244. {
  3245. /*
  3246. Link the block into the LRU ring if it's the last submitted
  3247. request for the block. This enables eviction for the block.
  3248. Note that a request has been registered against the block in
  3249. flush_key_blocks_int().
  3250. */
  3251. unreg_request(keycache, block, 1);
  3252. }
  3253. } /* end of for ( ; cache != end ; cache++) */
  3254. return last_errno;
  3255. }
  3256. /*
  3257. Flush all key blocks for a file to disk, but don't do any mutex locks.
  3258. SYNOPSIS
  3259. flush_key_blocks_int()
  3260. keycache pointer to a key cache data structure
  3261. file handler for the file to flush to
  3262. flush_type type of the flush
  3263. NOTES
  3264. This function doesn't do any mutex locks because it needs to be called both
  3265. from flush_key_blocks and flush_all_key_blocks (the later one does the
  3266. mutex lock in the resize_key_cache() function).
  3267. We do only care about changed blocks that exist when the function is
  3268. entered. We do not guarantee that all changed blocks of the file are
  3269. flushed if more blocks change while this function is running.
  3270. RETURN
  3271. 0 ok
  3272. 1 error
  3273. */
  3274. static int flush_key_blocks_int(KEY_CACHE *keycache,
  3275. File file, enum flush_type type)
  3276. {
  3277. BLOCK_LINK *cache_buff[FLUSH_CACHE],**cache;
  3278. int last_errno= 0;
  3279. int last_errcnt= 0;
  3280. DBUG_ENTER("flush_key_blocks_int");
  3281. DBUG_PRINT("enter",("file: %d blocks_used: %lu blocks_changed: %lu",
  3282. file, keycache->blocks_used, keycache->blocks_changed));
  3283. #if !defined(DBUG_OFF) && defined(EXTRA_DEBUG)
  3284. DBUG_EXECUTE("check_keycache",
  3285. test_key_cache(keycache, "start of flush_key_blocks", 0););
  3286. #endif
  3287. cache= cache_buff;
  3288. if (keycache->disk_blocks > 0 &&
  3289. (!my_disable_flush_key_blocks || type != FLUSH_KEEP))
  3290. {
  3291. /* Key cache exists and flush is not disabled */
  3292. int error= 0;
  3293. uint count= FLUSH_CACHE;
  3294. BLOCK_LINK **pos,**end;
  3295. BLOCK_LINK *first_in_switch= NULL;
  3296. BLOCK_LINK *last_in_flush;
  3297. BLOCK_LINK *last_for_update;
  3298. BLOCK_LINK *block, *next;
  3299. #if defined(KEYCACHE_DEBUG)
  3300. uint cnt=0;
  3301. #endif
  3302. if (type != FLUSH_IGNORE_CHANGED)
  3303. {
  3304. /*
  3305. Count how many key blocks we have to cache to be able
  3306. to flush all dirty pages with minimum seek moves
  3307. */
  3308. count= 0;
  3309. for (block= keycache->changed_blocks[FILE_HASH(file)] ;
  3310. block ;
  3311. block= block->next_changed)
  3312. {
  3313. if ((block->hash_link->file == file) &&
  3314. !(block->status & BLOCK_IN_FLUSH))
  3315. {
  3316. count++;
  3317. KEYCACHE_DBUG_ASSERT(count<= keycache->blocks_used);
  3318. }
  3319. }
  3320. /*
  3321. Allocate a new buffer only if its bigger than the one we have.
  3322. Assure that we always have some entries for the case that new
  3323. changed blocks appear while we need to wait for something.
  3324. */
  3325. if ((count > FLUSH_CACHE) &&
  3326. !(cache= (BLOCK_LINK**) my_malloc(sizeof(BLOCK_LINK*)*count,
  3327. MYF(0))))
  3328. cache= cache_buff;
  3329. /*
  3330. After a restart there could be more changed blocks than now.
  3331. So we should not let count become smaller than the fixed buffer.
  3332. */
  3333. if (cache == cache_buff)
  3334. count= FLUSH_CACHE;
  3335. }
  3336. /* Retrieve the blocks and write them to a buffer to be flushed */
  3337. restart:
  3338. last_in_flush= NULL;
  3339. last_for_update= NULL;
  3340. end= (pos= cache)+count;
  3341. for (block= keycache->changed_blocks[FILE_HASH(file)] ;
  3342. block ;
  3343. block= next)
  3344. {
  3345. #if defined(KEYCACHE_DEBUG)
  3346. cnt++;
  3347. KEYCACHE_DBUG_ASSERT(cnt <= keycache->blocks_used);
  3348. #endif
  3349. next= block->next_changed;
  3350. if (block->hash_link->file == file)
  3351. {
  3352. if (!(block->status & (BLOCK_IN_FLUSH | BLOCK_FOR_UPDATE)))
  3353. {
  3354. /*
  3355. Note: The special handling of BLOCK_IN_SWITCH is obsolete
  3356. since we set BLOCK_IN_FLUSH if the eviction includes a
  3357. flush. It can be removed in a later version.
  3358. */
  3359. if (!(block->status & BLOCK_IN_SWITCH))
  3360. {
  3361. /*
  3362. We care only for the blocks for which flushing was not
  3363. initiated by another thread and which are not in eviction.
  3364. Registering a request on the block unlinks it from the LRU
  3365. ring and protects against eviction.
  3366. */
  3367. reg_requests(keycache, block, 1);
  3368. if (type != FLUSH_IGNORE_CHANGED)
  3369. {
  3370. /* It's not a temporary file */
  3371. if (pos == end)
  3372. {
  3373. /*
  3374. This should happen relatively seldom. Remove the
  3375. request because we won't do anything with the block
  3376. but restart and pick it again in the next iteration.
  3377. */
  3378. unreg_request(keycache, block, 0);
  3379. /*
  3380. This happens only if there is not enough
  3381. memory for the big block
  3382. */
  3383. if ((error= flush_cached_blocks(keycache, file, cache,
  3384. end,type)))
  3385. {
  3386. /* Do not loop infinitely trying to flush in vain. */
  3387. if ((last_errno == error) && (++last_errcnt > 5))
  3388. goto err;
  3389. last_errno= error;
  3390. }
  3391. /*
  3392. Restart the scan as some other thread might have changed
  3393. the changed blocks chain: the blocks that were in switch
  3394. state before the flush started have to be excluded
  3395. */
  3396. goto restart;
  3397. }
  3398. /*
  3399. Mark the block with BLOCK_IN_FLUSH in order not to let
  3400. other threads to use it for new pages and interfere with
  3401. our sequence of flushing dirty file pages. We must not
  3402. set this flag before actually putting the block on the
  3403. write burst array called 'cache'.
  3404. */
  3405. block->status|= BLOCK_IN_FLUSH;
  3406. /* Add block to the array for a write burst. */
  3407. *pos++= block;
  3408. }
  3409. else
  3410. {
  3411. /* It's a temporary file */
  3412. DBUG_ASSERT(!(block->status & BLOCK_REASSIGNED));
  3413. /*
  3414. free_block() must not be called with BLOCK_CHANGED. Note
  3415. that we must not change the BLOCK_CHANGED flag outside of
  3416. link_to_file_list() so that it is always in the correct
  3417. queue and the *blocks_changed counters are correct.
  3418. */
  3419. link_to_file_list(keycache, block, file, 1);
  3420. if (!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH)))
  3421. {
  3422. /* A request has been registered against the block above. */
  3423. free_block(keycache, block);
  3424. }
  3425. else
  3426. {
  3427. /*
  3428. Link the block into the LRU ring if it's the last
  3429. submitted request for the block. This enables eviction
  3430. for the block. A request has been registered against
  3431. the block above.
  3432. */
  3433. unreg_request(keycache, block, 1);
  3434. }
  3435. }
  3436. }
  3437. else
  3438. {
  3439. /*
  3440. Link the block into a list of blocks 'in switch'.
  3441. WARNING: Here we introduce a place where a changed block
  3442. is not in the changed_blocks hash! This is acceptable for
  3443. a BLOCK_IN_SWITCH. Never try this for another situation.
  3444. Other parts of the key cache code rely on changed blocks
  3445. being in the changed_blocks hash.
  3446. */
  3447. unlink_changed(block);
  3448. link_changed(block, &first_in_switch);
  3449. }
  3450. }
  3451. else if (type != FLUSH_KEEP)
  3452. {
  3453. /*
  3454. During the normal flush at end of statement (FLUSH_KEEP) we
  3455. do not need to ensure that blocks in flush or update by
  3456. other threads are flushed. They will be flushed by them
  3457. later. In all other cases we must assure that we do not have
  3458. any changed block of this file in the cache when this
  3459. function returns.
  3460. */
  3461. if (block->status & BLOCK_IN_FLUSH)
  3462. {
  3463. /* Remember the last block found to be in flush. */
  3464. last_in_flush= block;
  3465. }
  3466. else
  3467. {
  3468. /* Remember the last block found to be selected for update. */
  3469. last_for_update= block;
  3470. }
  3471. }
  3472. }
  3473. }
  3474. if (pos != cache)
  3475. {
  3476. if ((error= flush_cached_blocks(keycache, file, cache, pos, type)))
  3477. {
  3478. /* Do not loop inifnitely trying to flush in vain. */
  3479. if ((last_errno == error) && (++last_errcnt > 5))
  3480. goto err;
  3481. last_errno= error;
  3482. }
  3483. /*
  3484. Do not restart here during the normal flush at end of statement
  3485. (FLUSH_KEEP). We have now flushed at least all blocks that were
  3486. changed when entering this function. In all other cases we must
  3487. assure that we do not have any changed block of this file in the
  3488. cache when this function returns.
  3489. */
  3490. if (type != FLUSH_KEEP)
  3491. goto restart;
  3492. }
  3493. if (last_in_flush)
  3494. {
  3495. /*
  3496. There are no blocks to be flushed by this thread, but blocks in
  3497. flush by other threads. Wait until one of the blocks is flushed.
  3498. Re-check the condition for last_in_flush. We may have unlocked
  3499. the cache_lock in flush_cached_blocks(). The state of the block
  3500. could have changed.
  3501. */
  3502. if (last_in_flush->status & BLOCK_IN_FLUSH)
  3503. wait_on_queue(&last_in_flush->wqueue[COND_FOR_SAVED],
  3504. &keycache->cache_lock);
  3505. /* Be sure not to lose a block. They may be flushed in random order. */
  3506. goto restart;
  3507. }
  3508. if (last_for_update)
  3509. {
  3510. /*
  3511. There are no blocks to be flushed by this thread, but blocks for
  3512. update by other threads. Wait until one of the blocks is updated.
  3513. Re-check the condition for last_for_update. We may have unlocked
  3514. the cache_lock in flush_cached_blocks(). The state of the block
  3515. could have changed.
  3516. */
  3517. if (last_for_update->status & BLOCK_FOR_UPDATE)
  3518. wait_on_queue(&last_for_update->wqueue[COND_FOR_REQUESTED],
  3519. &keycache->cache_lock);
  3520. /* The block is now changed. Flush it. */
  3521. goto restart;
  3522. }
  3523. /*
  3524. Wait until the list of blocks in switch is empty. The threads that
  3525. are switching these blocks will relink them to clean file chains
  3526. while we wait and thus empty the 'first_in_switch' chain.
  3527. */
  3528. while (first_in_switch)
  3529. {
  3530. #if defined(KEYCACHE_DEBUG)
  3531. cnt= 0;
  3532. #endif
  3533. wait_on_queue(&first_in_switch->wqueue[COND_FOR_SAVED],
  3534. &keycache->cache_lock);
  3535. #if defined(KEYCACHE_DEBUG)
  3536. cnt++;
  3537. KEYCACHE_DBUG_ASSERT(cnt <= keycache->blocks_used);
  3538. #endif
  3539. /*
  3540. Do not restart here. We have flushed all blocks that were
  3541. changed when entering this function and were not marked for
  3542. eviction. Other threads have now flushed all remaining blocks in
  3543. the course of their eviction.
  3544. */
  3545. }
  3546. if (! (type == FLUSH_KEEP || type == FLUSH_FORCE_WRITE))
  3547. {
  3548. BLOCK_LINK *last_for_update= NULL;
  3549. BLOCK_LINK *last_in_switch= NULL;
  3550. uint total_found= 0;
  3551. uint found;
  3552. /*
  3553. Finally free all clean blocks for this file.
  3554. During resize this may be run by two threads in parallel.
  3555. */
  3556. do
  3557. {
  3558. found= 0;
  3559. for (block= keycache->file_blocks[FILE_HASH(file)] ;
  3560. block ;
  3561. block= next)
  3562. {
  3563. /* Remember the next block. After freeing we cannot get at it. */
  3564. next= block->next_changed;
  3565. /* Changed blocks cannot appear in the file_blocks hash. */
  3566. DBUG_ASSERT(!(block->status & BLOCK_CHANGED));
  3567. if (block->hash_link->file == file)
  3568. {
  3569. /* We must skip blocks that will be changed. */
  3570. if (block->status & BLOCK_FOR_UPDATE)
  3571. {
  3572. last_for_update= block;
  3573. continue;
  3574. }
  3575. /*
  3576. We must not free blocks in eviction (BLOCK_IN_EVICTION |
  3577. BLOCK_IN_SWITCH) or blocks intended to be freed
  3578. (BLOCK_REASSIGNED).
  3579. */
  3580. if (!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
  3581. BLOCK_REASSIGNED)))
  3582. {
  3583. struct st_hash_link *next_hash_link;
  3584. my_off_t next_diskpos;
  3585. File next_file;
  3586. uint next_status;
  3587. uint hash_requests;
  3588. total_found++;
  3589. found++;
  3590. KEYCACHE_DBUG_ASSERT(found <= keycache->blocks_used);
  3591. /*
  3592. Register a request. This unlinks the block from the LRU
  3593. ring and protects it against eviction. This is required
  3594. by free_block().
  3595. */
  3596. reg_requests(keycache, block, 1);
  3597. /*
  3598. free_block() may need to wait for readers of the block.
  3599. This is the moment where the other thread can move the
  3600. 'next' block from the chain. free_block() needs to wait
  3601. if there are requests for the block pending.
  3602. */
  3603. if (next && (hash_requests= block->hash_link->requests))
  3604. {
  3605. /* Copy values from the 'next' block and its hash_link. */
  3606. next_status= next->status;
  3607. next_hash_link= next->hash_link;
  3608. next_diskpos= next_hash_link->diskpos;
  3609. next_file= next_hash_link->file;
  3610. DBUG_ASSERT(next == next_hash_link->block);
  3611. }
  3612. free_block(keycache, block);
  3613. /*
  3614. If we had to wait and the state of the 'next' block
  3615. changed, break the inner loop. 'next' may no longer be
  3616. part of the current chain.
  3617. We do not want to break the loop after every free_block(),
  3618. not even only after waits. The chain might be quite long
  3619. and contain blocks for many files. Traversing it again and
  3620. again to find more blocks for this file could become quite
  3621. inefficient.
  3622. */
  3623. if (next && hash_requests &&
  3624. ((next_status != next->status) ||
  3625. (next_hash_link != next->hash_link) ||
  3626. (next_file != next_hash_link->file) ||
  3627. (next_diskpos != next_hash_link->diskpos) ||
  3628. (next != next_hash_link->block)))
  3629. break;
  3630. }
  3631. else
  3632. {
  3633. last_in_switch= block;
  3634. }
  3635. }
  3636. } /* end for block in file_blocks */
  3637. } while (found);
  3638. /*
  3639. If any clean block has been found, we may have waited for it to
  3640. become free. In this case it could be possible that another clean
  3641. block became dirty. This is possible if the write request existed
  3642. before the flush started (BLOCK_FOR_UPDATE). Re-check the hashes.
  3643. */
  3644. if (total_found)
  3645. goto restart;
  3646. /*
  3647. To avoid an infinite loop, wait until one of the blocks marked
  3648. for update is updated.
  3649. */
  3650. if (last_for_update)
  3651. {
  3652. /* We did not wait. Block must not have changed status. */
  3653. DBUG_ASSERT(last_for_update->status & BLOCK_FOR_UPDATE);
  3654. wait_on_queue(&last_for_update->wqueue[COND_FOR_REQUESTED],
  3655. &keycache->cache_lock);
  3656. goto restart;
  3657. }
  3658. /*
  3659. To avoid an infinite loop wait until one of the blocks marked
  3660. for eviction is switched.
  3661. */
  3662. if (last_in_switch)
  3663. {
  3664. /* We did not wait. Block must not have changed status. */
  3665. DBUG_ASSERT(last_in_switch->status & (BLOCK_IN_EVICTION |
  3666. BLOCK_IN_SWITCH |
  3667. BLOCK_REASSIGNED));
  3668. wait_on_queue(&last_in_switch->wqueue[COND_FOR_SAVED],
  3669. &keycache->cache_lock);
  3670. goto restart;
  3671. }
  3672. } /* if (! (type == FLUSH_KEEP || type == FLUSH_FORCE_WRITE)) */
  3673. } /* if (keycache->disk_blocks > 0 */
  3674. #ifndef DBUG_OFF
  3675. DBUG_EXECUTE("check_keycache",
  3676. test_key_cache(keycache, "end of flush_key_blocks", 0););
  3677. #endif
  3678. err:
  3679. if (cache != cache_buff)
  3680. my_free(cache);
  3681. if (last_errno)
  3682. errno=last_errno; /* Return first error */
  3683. DBUG_RETURN(last_errno != 0);
  3684. }
  3685. /*
  3686. Flush all blocks for a file to disk
  3687. SYNOPSIS
  3688. flush_key_blocks()
  3689. keycache pointer to a key cache data structure
  3690. file handler for the file to flush to
  3691. flush_type type of the flush
  3692. RETURN
  3693. 0 ok
  3694. 1 error
  3695. */
  3696. int flush_key_blocks(KEY_CACHE *keycache,
  3697. File file, enum flush_type type)
  3698. {
  3699. int res= 0;
  3700. DBUG_ENTER("flush_key_blocks");
  3701. DBUG_PRINT("enter", ("keycache: 0x%lx", (long) keycache));
  3702. if (!keycache->key_cache_inited)
  3703. DBUG_RETURN(0);
  3704. keycache_pthread_mutex_lock(&keycache->cache_lock);
  3705. /* While waiting for lock, keycache could have been ended. */
  3706. if (keycache->disk_blocks > 0)
  3707. {
  3708. inc_counter_for_resize_op(keycache);
  3709. res= flush_key_blocks_int(keycache, file, type);
  3710. dec_counter_for_resize_op(keycache);
  3711. }
  3712. keycache_pthread_mutex_unlock(&keycache->cache_lock);
  3713. DBUG_RETURN(res);
  3714. }
  3715. /*
  3716. Flush all blocks in the key cache to disk.
  3717. SYNOPSIS
  3718. flush_all_key_blocks()
  3719. keycache pointer to key cache root structure
  3720. DESCRIPTION
  3721. Flushing of the whole key cache is done in two phases.
  3722. 1. Flush all changed blocks, waiting for them if necessary. Loop
  3723. until there is no changed block left in the cache.
  3724. 2. Free all clean blocks. Normally this means free all blocks. The
  3725. changed blocks were flushed in phase 1 and became clean. However we
  3726. may need to wait for blocks that are read by other threads. While we
  3727. wait, a clean block could become changed if that operation started
  3728. before the resize operation started. To be safe we must restart at
  3729. phase 1.
  3730. When we can run through the changed_blocks and file_blocks hashes
  3731. without finding a block any more, then we are done.
  3732. Note that we hold keycache->cache_lock all the time unless we need
  3733. to wait for something.
  3734. RETURN
  3735. 0 OK
  3736. != 0 Error
  3737. */
  3738. static int flush_all_key_blocks(KEY_CACHE *keycache)
  3739. {
  3740. BLOCK_LINK *block;
  3741. uint total_found;
  3742. uint found;
  3743. uint idx;
  3744. DBUG_ENTER("flush_all_key_blocks");
  3745. do
  3746. {
  3747. mysql_mutex_assert_owner(&keycache->cache_lock);
  3748. total_found= 0;
  3749. /*
  3750. Phase1: Flush all changed blocks, waiting for them if necessary.
  3751. Loop until there is no changed block left in the cache.
  3752. */
  3753. do
  3754. {
  3755. found= 0;
  3756. /* Step over the whole changed_blocks hash array. */
  3757. for (idx= 0; idx < CHANGED_BLOCKS_HASH; idx++)
  3758. {
  3759. /*
  3760. If an array element is non-empty, use the first block from its
  3761. chain to find a file for flush. All changed blocks for this
  3762. file are flushed. So the same block will not appear at this
  3763. place again with the next iteration. New writes for blocks are
  3764. not accepted during the flush. If multiple files share the
  3765. same hash bucket, one of them will be flushed per iteration
  3766. of the outer loop of phase 1.
  3767. */
  3768. if ((block= keycache->changed_blocks[idx]))
  3769. {
  3770. found++;
  3771. /*
  3772. Flush dirty blocks but do not free them yet. They can be used
  3773. for reading until all other blocks are flushed too.
  3774. */
  3775. if (flush_key_blocks_int(keycache, block->hash_link->file,
  3776. FLUSH_FORCE_WRITE))
  3777. DBUG_RETURN(1);
  3778. }
  3779. }
  3780. } while (found);
  3781. /*
  3782. Phase 2: Free all clean blocks. Normally this means free all
  3783. blocks. The changed blocks were flushed in phase 1 and became
  3784. clean. However we may need to wait for blocks that are read by
  3785. other threads. While we wait, a clean block could become changed
  3786. if that operation started before the resize operation started. To
  3787. be safe we must restart at phase 1.
  3788. */
  3789. do
  3790. {
  3791. found= 0;
  3792. /* Step over the whole file_blocks hash array. */
  3793. for (idx= 0; idx < CHANGED_BLOCKS_HASH; idx++)
  3794. {
  3795. /*
  3796. If an array element is non-empty, use the first block from its
  3797. chain to find a file for flush. All blocks for this file are
  3798. freed. So the same block will not appear at this place again
  3799. with the next iteration. If multiple files share the
  3800. same hash bucket, one of them will be flushed per iteration
  3801. of the outer loop of phase 2.
  3802. */
  3803. if ((block= keycache->file_blocks[idx]))
  3804. {
  3805. total_found++;
  3806. found++;
  3807. if (flush_key_blocks_int(keycache, block->hash_link->file,
  3808. FLUSH_RELEASE))
  3809. DBUG_RETURN(1);
  3810. }
  3811. }
  3812. } while (found);
  3813. /*
  3814. If any clean block has been found, we may have waited for it to
  3815. become free. In this case it could be possible that another clean
  3816. block became dirty. This is possible if the write request existed
  3817. before the resize started (BLOCK_FOR_UPDATE). Re-check the hashes.
  3818. */
  3819. } while (total_found);
  3820. #ifndef DBUG_OFF
  3821. /* Now there should not exist any block any more. */
  3822. for (idx= 0; idx < CHANGED_BLOCKS_HASH; idx++)
  3823. {
  3824. DBUG_ASSERT(!keycache->changed_blocks[idx]);
  3825. DBUG_ASSERT(!keycache->file_blocks[idx]);
  3826. }
  3827. #endif
  3828. DBUG_RETURN(0);
  3829. }
  3830. /*
  3831. Reset the counters of a key cache.
  3832. SYNOPSIS
  3833. reset_key_cache_counters()
  3834. name the name of a key cache
  3835. key_cache pointer to the key kache to be reset
  3836. DESCRIPTION
  3837. This procedure is used by process_key_caches() to reset the counters of all
  3838. currently used key caches, both the default one and the named ones.
  3839. RETURN
  3840. 0 on success (always because it can't fail)
  3841. */
  3842. int reset_key_cache_counters(const char *name __attribute__((unused)),
  3843. KEY_CACHE *key_cache)
  3844. {
  3845. DBUG_ENTER("reset_key_cache_counters");
  3846. if (!key_cache->key_cache_inited)
  3847. {
  3848. DBUG_PRINT("info", ("Key cache %s not initialized.", name));
  3849. DBUG_RETURN(0);
  3850. }
  3851. DBUG_PRINT("info", ("Resetting counters for key cache %s.", name));
  3852. key_cache->global_blocks_changed= 0; /* Key_blocks_not_flushed */
  3853. key_cache->global_cache_r_requests= 0; /* Key_read_requests */
  3854. key_cache->global_cache_read= 0; /* Key_reads */
  3855. key_cache->global_cache_w_requests= 0; /* Key_write_requests */
  3856. key_cache->global_cache_write= 0; /* Key_writes */
  3857. DBUG_RETURN(0);
  3858. }
  3859. #ifndef DBUG_OFF
  3860. /*
  3861. Test if disk-cache is ok
  3862. */
  3863. static void test_key_cache(KEY_CACHE *keycache __attribute__((unused)),
  3864. const char *where __attribute__((unused)),
  3865. my_bool lock __attribute__((unused)))
  3866. {
  3867. /* TODO */
  3868. }
  3869. #endif
  3870. #if defined(KEYCACHE_TIMEOUT)
  3871. #define KEYCACHE_DUMP_FILE "keycache_dump.txt"
  3872. #define MAX_QUEUE_LEN 100
  3873. static void keycache_dump(KEY_CACHE *keycache)
  3874. {
  3875. FILE *keycache_dump_file=fopen(KEYCACHE_DUMP_FILE, "w");
  3876. struct st_my_thread_var *last;
  3877. struct st_my_thread_var *thread;
  3878. BLOCK_LINK *block;
  3879. HASH_LINK *hash_link;
  3880. KEYCACHE_PAGE *page;
  3881. uint i;
  3882. fprintf(keycache_dump_file, "thread:%u\n", thread->id);
  3883. i=0;
  3884. thread=last=waiting_for_hash_link.last_thread;
  3885. fprintf(keycache_dump_file, "queue of threads waiting for hash link\n");
  3886. if (thread)
  3887. do
  3888. {
  3889. thread=thread->next;
  3890. page= (KEYCACHE_PAGE *) thread->opt_info;
  3891. fprintf(keycache_dump_file,
  3892. "thread:%u, (file,filepos)=(%u,%lu)\n",
  3893. thread->id,(uint) page->file,(ulong) page->filepos);
  3894. if (++i == MAX_QUEUE_LEN)
  3895. break;
  3896. }
  3897. while (thread != last);
  3898. i=0;
  3899. thread=last=waiting_for_block.last_thread;
  3900. fprintf(keycache_dump_file, "queue of threads waiting for block\n");
  3901. if (thread)
  3902. do
  3903. {
  3904. thread=thread->next;
  3905. hash_link= (HASH_LINK *) thread->opt_info;
  3906. fprintf(keycache_dump_file,
  3907. "thread:%u hash_link:%u (file,filepos)=(%u,%lu)\n",
  3908. thread->id, (uint) HASH_LINK_NUMBER(hash_link),
  3909. (uint) hash_link->file,(ulong) hash_link->diskpos);
  3910. if (++i == MAX_QUEUE_LEN)
  3911. break;
  3912. }
  3913. while (thread != last);
  3914. for (i=0 ; i< keycache->blocks_used ; i++)
  3915. {
  3916. int j;
  3917. block= &keycache->block_root[i];
  3918. hash_link= block->hash_link;
  3919. fprintf(keycache_dump_file,
  3920. "block:%u hash_link:%d status:%x #requests=%u waiting_for_readers:%d\n",
  3921. i, (int) (hash_link ? HASH_LINK_NUMBER(hash_link) : -1),
  3922. block->status, block->requests, block->condvar ? 1 : 0);
  3923. for (j=0 ; j < 2; j++)
  3924. {
  3925. KEYCACHE_WQUEUE *wqueue=&block->wqueue[j];
  3926. thread= last= wqueue->last_thread;
  3927. fprintf(keycache_dump_file, "queue #%d\n", j);
  3928. if (thread)
  3929. {
  3930. do
  3931. {
  3932. thread=thread->next;
  3933. fprintf(keycache_dump_file,
  3934. "thread:%u\n", thread->id);
  3935. if (++i == MAX_QUEUE_LEN)
  3936. break;
  3937. }
  3938. while (thread != last);
  3939. }
  3940. }
  3941. }
  3942. fprintf(keycache_dump_file, "LRU chain:");
  3943. block= keycache= used_last;
  3944. if (block)
  3945. {
  3946. do
  3947. {
  3948. block= block->next_used;
  3949. fprintf(keycache_dump_file,
  3950. "block:%u, ", BLOCK_NUMBER(block));
  3951. }
  3952. while (block != keycache->used_last);
  3953. }
  3954. fprintf(keycache_dump_file, "\n");
  3955. fclose(keycache_dump_file);
  3956. }
  3957. #endif /* defined(KEYCACHE_TIMEOUT) */
  3958. #if defined(KEYCACHE_TIMEOUT) && !defined(__WIN__)
  3959. static int keycache_pthread_cond_wait(mysql_cond_t *cond,
  3960. mysql_mutex_t *mutex)
  3961. {
  3962. int rc;
  3963. struct timeval now; /* time when we started waiting */
  3964. struct timespec timeout; /* timeout value for the wait function */
  3965. struct timezone tz;
  3966. #if defined(KEYCACHE_DEBUG)
  3967. int cnt=0;
  3968. #endif
  3969. /* Get current time */
  3970. gettimeofday(&now, &tz);
  3971. /* Prepare timeout value */
  3972. timeout.tv_sec= now.tv_sec + KEYCACHE_TIMEOUT;
  3973. /*
  3974. timeval uses microseconds.
  3975. timespec uses nanoseconds.
  3976. 1 nanosecond = 1000 micro seconds
  3977. */
  3978. timeout.tv_nsec= now.tv_usec * 1000;
  3979. KEYCACHE_THREAD_TRACE_END("started waiting");
  3980. #if defined(KEYCACHE_DEBUG)
  3981. cnt++;
  3982. if (cnt % 100 == 0)
  3983. fprintf(keycache_debug_log, "waiting...\n");
  3984. fflush(keycache_debug_log);
  3985. #endif
  3986. rc= mysql_cond_timedwait(cond, mutex, &timeout);
  3987. KEYCACHE_THREAD_TRACE_BEGIN("finished waiting");
  3988. if (rc == ETIMEDOUT || rc == ETIME)
  3989. {
  3990. #if defined(KEYCACHE_DEBUG)
  3991. fprintf(keycache_debug_log,"aborted by keycache timeout\n");
  3992. fclose(keycache_debug_log);
  3993. abort();
  3994. #endif
  3995. keycache_dump();
  3996. }
  3997. #if defined(KEYCACHE_DEBUG)
  3998. KEYCACHE_DBUG_ASSERT(rc != ETIMEDOUT);
  3999. #else
  4000. assert(rc != ETIMEDOUT);
  4001. #endif
  4002. return rc;
  4003. }
  4004. #else
  4005. #if defined(KEYCACHE_DEBUG)
  4006. static int keycache_pthread_cond_wait(mysql_cond_t *cond,
  4007. mysql_mutex_t *mutex)
  4008. {
  4009. int rc;
  4010. KEYCACHE_THREAD_TRACE_END("started waiting");
  4011. rc= mysql_cond_wait(cond, mutex);
  4012. KEYCACHE_THREAD_TRACE_BEGIN("finished waiting");
  4013. return rc;
  4014. }
  4015. #endif
  4016. #endif /* defined(KEYCACHE_TIMEOUT) && !defined(__WIN__) */
  4017. #if defined(KEYCACHE_DEBUG)
  4018. static int keycache_pthread_mutex_lock(mysql_mutex_t *mutex)
  4019. {
  4020. int rc;
  4021. rc= mysql_mutex_lock(mutex);
  4022. KEYCACHE_THREAD_TRACE_BEGIN("");
  4023. return rc;
  4024. }
  4025. static void keycache_pthread_mutex_unlock(mysql_mutex_t *mutex)
  4026. {
  4027. KEYCACHE_THREAD_TRACE_END("");
  4028. mysql_mutex_unlock(mutex);
  4029. }
  4030. static int keycache_pthread_cond_signal(mysql_cond_t *cond)
  4031. {
  4032. int rc;
  4033. KEYCACHE_THREAD_TRACE("signal");
  4034. rc= mysql_cond_signal(cond);
  4035. return rc;
  4036. }
  4037. #if defined(KEYCACHE_DEBUG_LOG)
  4038. static void keycache_debug_print(const char * fmt,...)
  4039. {
  4040. va_list args;
  4041. va_start(args,fmt);
  4042. if (keycache_debug_log)
  4043. {
  4044. (void) vfprintf(keycache_debug_log, fmt, args);
  4045. (void) fputc('\n',keycache_debug_log);
  4046. }
  4047. va_end(args);
  4048. }
  4049. #endif /* defined(KEYCACHE_DEBUG_LOG) */
  4050. #if defined(KEYCACHE_DEBUG_LOG)
  4051. void keycache_debug_log_close(void)
  4052. {
  4053. if (keycache_debug_log)
  4054. fclose(keycache_debug_log);
  4055. }
  4056. #endif /* defined(KEYCACHE_DEBUG_LOG) */
  4057. #endif /* defined(KEYCACHE_DEBUG) */
  4058. #if !defined(DBUG_OFF)
  4059. #define F_B_PRT(_f_, _v_) DBUG_PRINT("assert_fail", (_f_, _v_))
  4060. static int fail_block(BLOCK_LINK *block)
  4061. {
  4062. F_B_PRT("block->next_used: %lx\n", (ulong) block->next_used);
  4063. F_B_PRT("block->prev_used: %lx\n", (ulong) block->prev_used);
  4064. F_B_PRT("block->next_changed: %lx\n", (ulong) block->next_changed);
  4065. F_B_PRT("block->prev_changed: %lx\n", (ulong) block->prev_changed);
  4066. F_B_PRT("block->hash_link: %lx\n", (ulong) block->hash_link);
  4067. F_B_PRT("block->status: %u\n", block->status);
  4068. F_B_PRT("block->length: %u\n", block->length);
  4069. F_B_PRT("block->offset: %u\n", block->offset);
  4070. F_B_PRT("block->requests: %u\n", block->requests);
  4071. F_B_PRT("block->temperature: %u\n", block->temperature);
  4072. return 0; /* Let the assert fail. */
  4073. }
  4074. static int fail_hlink(HASH_LINK *hlink)
  4075. {
  4076. F_B_PRT("hlink->next: %lx\n", (ulong) hlink->next);
  4077. F_B_PRT("hlink->prev: %lx\n", (ulong) hlink->prev);
  4078. F_B_PRT("hlink->block: %lx\n", (ulong) hlink->block);
  4079. F_B_PRT("hlink->diskpos: %lu\n", (ulong) hlink->diskpos);
  4080. F_B_PRT("hlink->file: %d\n", hlink->file);
  4081. return 0; /* Let the assert fail. */
  4082. }
  4083. static int cache_empty(KEY_CACHE *keycache)
  4084. {
  4085. int errcnt= 0;
  4086. int idx;
  4087. if (keycache->disk_blocks <= 0)
  4088. return 1;
  4089. for (idx= 0; idx < keycache->disk_blocks; idx++)
  4090. {
  4091. BLOCK_LINK *block= keycache->block_root + idx;
  4092. if (block->status || block->requests || block->hash_link)
  4093. {
  4094. fprintf(stderr, "block index: %u\n", idx);
  4095. fail_block(block);
  4096. errcnt++;
  4097. }
  4098. }
  4099. for (idx= 0; idx < keycache->hash_links; idx++)
  4100. {
  4101. HASH_LINK *hash_link= keycache->hash_link_root + idx;
  4102. if (hash_link->requests || hash_link->block)
  4103. {
  4104. fprintf(stderr, "hash_link index: %u\n", idx);
  4105. fail_hlink(hash_link);
  4106. errcnt++;
  4107. }
  4108. }
  4109. if (errcnt)
  4110. {
  4111. fprintf(stderr, "blocks: %d used: %lu\n",
  4112. keycache->disk_blocks, keycache->blocks_used);
  4113. fprintf(stderr, "hash_links: %d used: %d\n",
  4114. keycache->hash_links, keycache->hash_links_used);
  4115. fprintf(stderr, "\n");
  4116. }
  4117. return !errcnt;
  4118. }
  4119. #endif