Get the memory status from the point of view of the maxmemory directive: * if the memory used is under the maxmemory setting then C_OK is returned. * Otherwise, if we are over the memory limit, the function returns * C_ERR. * * The function may return additional info via reference, only if the * pointers to the respective arguments is not NULL. Certain fields are * populated only when C_ERR
| 372 | * (Populated both for C_ERR and C_OK) |
| 373 | */ |
| 374 | int getMaxmemoryState(size_t *total, size_t *logical, size_t *tofree, float *level) { |
| 375 | size_t mem_reported, mem_used, mem_tofree; |
| 376 | |
| 377 | /* Check if we are over the memory usage limit. If we are not, no need |
| 378 | * to subtract the slaves output buffers. We can just return ASAP. */ |
| 379 | mem_reported = zmalloc_used_memory(); |
| 380 | if (total) *total = mem_reported; |
| 381 | |
| 382 | /* We may return ASAP if there is no need to compute the level. */ |
| 383 | int return_ok_asap = !server.maxmemory || mem_reported <= server.maxmemory; |
| 384 | if (return_ok_asap && !level) return C_OK; |
| 385 | |
| 386 | /* Remove the size of slaves output buffers and AOF buffer from the |
| 387 | * count of used memory. */ |
| 388 | mem_used = mem_reported; |
| 389 | size_t overhead = freeMemoryGetNotCountedMemory(); |
| 390 | mem_used = (mem_used > overhead) ? mem_used-overhead : 0; |
| 391 | |
| 392 | /* Compute the ratio of memory usage. */ |
| 393 | if (level) { |
| 394 | if (!server.maxmemory) { |
| 395 | *level = 0; |
| 396 | } else { |
| 397 | *level = (float)mem_used / (float)server.maxmemory; |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | if (return_ok_asap) return C_OK; |
| 402 | |
| 403 | /* Check if we are still over the memory limit. */ |
| 404 | if (mem_used <= server.maxmemory) return C_OK; |
| 405 | |
| 406 | /* Compute how much memory we need to free. */ |
| 407 | mem_tofree = mem_used - server.maxmemory; |
| 408 | |
| 409 | if (logical) *logical = mem_used; |
| 410 | if (tofree) *tofree = mem_tofree; |
| 411 | |
| 412 | return C_ERR; |
| 413 | } |
| 414 | |
| 415 | /* Return 1 if used memory is more than maxmemory after allocating more memory, |
| 416 | * return 0 if not. Redis may reject user's requests or evict some keys if used |
no test coverage detected