mem.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. /* Cache memory handling.
  2. Copyright (C) 2004-2026 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published
  6. by the Free Software Foundation; version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, see <https://www.gnu.org/licenses/>. */
  14. #include <assert.h>
  15. #include <errno.h>
  16. #include <error.h>
  17. #include <fcntl.h>
  18. #include <inttypes.h>
  19. #include <libintl.h>
  20. #include <limits.h>
  21. #include <obstack.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <unistd.h>
  25. #include <sys/mman.h>
  26. #include <sys/param.h>
  27. #include "dbg_log.h"
  28. #include "nscd.h"
  29. static int
  30. sort_he (const void *p1, const void *p2)
  31. {
  32. struct hashentry *h1 = *(struct hashentry **) p1;
  33. struct hashentry *h2 = *(struct hashentry **) p2;
  34. if (h1 < h2)
  35. return -1;
  36. if (h1 > h2)
  37. return 1;
  38. return 0;
  39. }
  40. static int
  41. sort_he_data (const void *p1, const void *p2)
  42. {
  43. struct hashentry *h1 = *(struct hashentry **) p1;
  44. struct hashentry *h2 = *(struct hashentry **) p2;
  45. if (h1->packet < h2->packet)
  46. return -1;
  47. if (h1->packet > h2->packet)
  48. return 1;
  49. return 0;
  50. }
  51. /* Basic definitions for the bitmap implementation. Only BITMAP_T
  52. needs to be changed to choose a different word size. */
  53. #define BITMAP_T uint8_t
  54. #define BITS (CHAR_BIT * sizeof (BITMAP_T))
  55. #define ALLBITS ((((BITMAP_T) 1) << BITS) - 1)
  56. #define HIGHBIT (((BITMAP_T) 1) << (BITS - 1))
  57. static void
  58. markrange (BITMAP_T *mark, ref_t start, size_t len)
  59. {
  60. /* Adjust parameters for block alignment. */
  61. assert ((start & BLOCK_ALIGN_M1) == 0);
  62. start /= BLOCK_ALIGN;
  63. len = (len + BLOCK_ALIGN_M1) / BLOCK_ALIGN;
  64. size_t elem = start / BITS;
  65. if (start % BITS != 0)
  66. {
  67. if (start % BITS + len <= BITS)
  68. {
  69. /* All fits in the partial byte. */
  70. mark[elem] |= (ALLBITS >> (BITS - len)) << (start % BITS);
  71. return;
  72. }
  73. mark[elem++] |= ALLBITS << (start % BITS);
  74. len -= BITS - (start % BITS);
  75. }
  76. while (len >= BITS)
  77. {
  78. mark[elem++] = ALLBITS;
  79. len -= BITS;
  80. }
  81. if (len > 0)
  82. mark[elem] |= ALLBITS >> (BITS - len);
  83. }
  84. void
  85. gc (struct database_dyn *db)
  86. {
  87. /* We need write access. */
  88. pthread_rwlock_wrlock (&db->lock);
  89. /* And the memory handling lock. */
  90. pthread_mutex_lock (&db->memlock);
  91. /* We need an array representing the data area. All memory
  92. allocation is BLOCK_ALIGN aligned so this is the level at which
  93. we have to look at the memory. We use a mark and sweep algorithm
  94. where the marks are placed in this array. */
  95. assert (db->head->first_free % BLOCK_ALIGN == 0);
  96. BITMAP_T *mark;
  97. bool mark_use_malloc;
  98. /* In prune_cache we are also using a dynamically allocated array.
  99. If the array in the caller is too large we have malloc'ed it. */
  100. size_t stack_used = sizeof (bool) * db->head->module;
  101. if (__glibc_unlikely (stack_used > MAX_STACK_USE))
  102. stack_used = 0;
  103. size_t nmark = (db->head->first_free / BLOCK_ALIGN + BITS - 1) / BITS;
  104. size_t memory_needed = nmark * sizeof (BITMAP_T);
  105. if (__glibc_likely (stack_used + memory_needed <= MAX_STACK_USE))
  106. {
  107. mark = (BITMAP_T *) alloca_account (memory_needed, stack_used);
  108. mark_use_malloc = false;
  109. memset (mark, '\0', memory_needed);
  110. }
  111. else
  112. {
  113. mark = (BITMAP_T *) xcalloc (1, memory_needed);
  114. mark_use_malloc = true;
  115. }
  116. /* Create an array which can hold pointer to all the entries in hash
  117. entries. */
  118. memory_needed = 2 * db->head->nentries * sizeof (struct hashentry *);
  119. struct hashentry **he;
  120. struct hashentry **he_data;
  121. bool he_use_malloc;
  122. if (__glibc_likely (stack_used + memory_needed <= MAX_STACK_USE))
  123. {
  124. he = alloca_account (memory_needed, stack_used);
  125. he_use_malloc = false;
  126. }
  127. else
  128. {
  129. he = xmalloc (memory_needed);
  130. he_use_malloc = true;
  131. }
  132. he_data = &he[db->head->nentries];
  133. size_t cnt = 0;
  134. for (size_t idx = 0; idx < db->head->module; ++idx)
  135. {
  136. ref_t *prevp = &db->head->array[idx];
  137. ref_t run = *prevp;
  138. while (run != ENDREF)
  139. {
  140. assert (cnt < db->head->nentries);
  141. he[cnt] = (struct hashentry *) (db->data + run);
  142. he[cnt]->prevp = prevp;
  143. prevp = &he[cnt]->next;
  144. /* This is the hash entry itself. */
  145. markrange (mark, run, sizeof (struct hashentry));
  146. /* Add the information for the data itself. We do this
  147. only for the one special entry marked with FIRST. */
  148. if (he[cnt]->first)
  149. {
  150. struct datahead *dh
  151. = (struct datahead *) (db->data + he[cnt]->packet);
  152. markrange (mark, he[cnt]->packet, dh->allocsize);
  153. }
  154. run = he[cnt]->next;
  155. ++cnt;
  156. }
  157. }
  158. assert (cnt == db->head->nentries);
  159. /* Sort the entries by the addresses of the referenced data. All
  160. the entries pointing to the same DATAHEAD object will have the
  161. same key. Stability of the sorting is unimportant. */
  162. memcpy (he_data, he, cnt * sizeof (struct hashentry *));
  163. qsort (he_data, cnt, sizeof (struct hashentry *), sort_he_data);
  164. /* Sort the entries by their address. */
  165. qsort (he, cnt, sizeof (struct hashentry *), sort_he);
  166. #define obstack_chunk_alloc xmalloc
  167. #define obstack_chunk_free free
  168. struct obstack ob;
  169. obstack_init (&ob);
  170. /* Determine the highest used address. */
  171. size_t high = nmark;
  172. while (high > 0 && mark[high - 1] == 0)
  173. --high;
  174. /* No memory used. */
  175. if (high == 0)
  176. {
  177. db->head->first_free = 0;
  178. goto out;
  179. }
  180. /* Determine the highest offset. */
  181. BITMAP_T mask = HIGHBIT;
  182. while ((mark[high - 1] & mask) == 0)
  183. mask >>= 1;
  184. /* Now we can iterate over the MARK array and find bits which are not
  185. set. These represent memory which can be recovered. */
  186. size_t byte = 0;
  187. /* Find the first gap. */
  188. while (byte < high && mark[byte] == ALLBITS)
  189. ++byte;
  190. if (byte == high
  191. || (byte == high - 1 && (mark[byte] & ~(mask | (mask - 1))) == 0))
  192. /* No gap. */
  193. goto out;
  194. mask = 1;
  195. cnt = 0;
  196. while ((mark[byte] & mask) != 0)
  197. {
  198. ++cnt;
  199. mask <<= 1;
  200. }
  201. ref_t off_free = (byte * BITS + cnt) * BLOCK_ALIGN;
  202. assert (off_free <= db->head->first_free);
  203. struct hashentry **next_hash = he;
  204. struct hashentry **next_data = he_data;
  205. /* Skip over the hash entries in the first block which does not get
  206. moved. */
  207. while (next_hash < &he[db->head->nentries]
  208. && *next_hash < (struct hashentry *) (db->data + off_free))
  209. ++next_hash;
  210. while (next_data < &he_data[db->head->nentries]
  211. && (*next_data)->packet < off_free)
  212. ++next_data;
  213. /* Now we start modifying the data. Make sure all readers of the
  214. data are aware of this and temporarily don't use the data. */
  215. atomic_fetch_add_relaxed (&db->head->gc_cycle, 1);
  216. assert ((db->head->gc_cycle & 1) == 1);
  217. /* We do not perform the move operations right away since the
  218. he_data array is not sorted by the address of the data. */
  219. struct moveinfo
  220. {
  221. void *from;
  222. void *to;
  223. size_t size;
  224. struct moveinfo *next;
  225. } *moves = NULL;
  226. while (byte < high)
  227. {
  228. /* Search for the next filled block. BYTE is the index of the
  229. entry in MARK, MASK is the bit, and CNT is the bit number.
  230. OFF_FILLED is the corresponding offset. */
  231. if ((mark[byte] & ~(mask - 1)) == 0)
  232. {
  233. /* No other bit set in the same element of MARK. Search in the
  234. following memory. */
  235. do
  236. ++byte;
  237. while (byte < high && mark[byte] == 0);
  238. if (byte == high)
  239. /* That was it. */
  240. break;
  241. mask = 1;
  242. cnt = 0;
  243. }
  244. /* Find the exact bit. */
  245. while ((mark[byte] & mask) == 0)
  246. {
  247. ++cnt;
  248. mask <<= 1;
  249. }
  250. ref_t off_alloc = (byte * BITS + cnt) * BLOCK_ALIGN;
  251. assert (off_alloc <= db->head->first_free);
  252. /* Find the end of the used area. */
  253. if ((mark[byte] & ~(mask - 1)) == (BITMAP_T) ~(mask - 1))
  254. {
  255. /* All other bits set. Search the next bytes in MARK. */
  256. do
  257. ++byte;
  258. while (byte < high && mark[byte] == ALLBITS);
  259. mask = 1;
  260. cnt = 0;
  261. }
  262. if (byte < high)
  263. {
  264. /* Find the exact bit. */
  265. while ((mark[byte] & mask) != 0)
  266. {
  267. ++cnt;
  268. mask <<= 1;
  269. }
  270. }
  271. ref_t off_allocend = (byte * BITS + cnt) * BLOCK_ALIGN;
  272. assert (off_allocend <= db->head->first_free);
  273. /* Now we know that we can copy the area from OFF_ALLOC to
  274. OFF_ALLOCEND (not included) to the memory starting at
  275. OFF_FREE. First fix up all the entries for the
  276. displacement. */
  277. ref_t disp = off_alloc - off_free;
  278. struct moveinfo *new_move;
  279. if (__builtin_expect (stack_used + sizeof (*new_move) <= MAX_STACK_USE,
  280. 1))
  281. new_move = alloca_account (sizeof (*new_move), stack_used);
  282. else
  283. new_move = obstack_alloc (&ob, sizeof (*new_move));
  284. new_move->from = db->data + off_alloc;
  285. new_move->to = db->data + off_free;
  286. new_move->size = off_allocend - off_alloc;
  287. /* Create a circular list to be always able to append at the end. */
  288. if (moves == NULL)
  289. moves = new_move->next = new_move;
  290. else
  291. {
  292. new_move->next = moves->next;
  293. moves = moves->next = new_move;
  294. }
  295. /* The following loop will prepare to move this much data. */
  296. off_free += off_allocend - off_alloc;
  297. while (off_alloc < off_allocend)
  298. {
  299. /* Determine whether the next entry is for a hash entry or
  300. the data. */
  301. if ((struct hashentry *) (db->data + off_alloc) == *next_hash)
  302. {
  303. /* Just correct the forward reference. */
  304. *(*next_hash++)->prevp -= disp;
  305. off_alloc += ((sizeof (struct hashentry) + BLOCK_ALIGN_M1)
  306. & ~BLOCK_ALIGN_M1);
  307. }
  308. else
  309. {
  310. assert (next_data < &he_data[db->head->nentries]);
  311. assert ((*next_data)->packet == off_alloc);
  312. struct datahead *dh = (struct datahead *) (db->data + off_alloc);
  313. do
  314. {
  315. assert ((*next_data)->key >= (*next_data)->packet);
  316. assert ((*next_data)->key + (*next_data)->len
  317. <= (*next_data)->packet + dh->allocsize);
  318. (*next_data)->packet -= disp;
  319. (*next_data)->key -= disp;
  320. ++next_data;
  321. }
  322. while (next_data < &he_data[db->head->nentries]
  323. && (*next_data)->packet == off_alloc);
  324. off_alloc += (dh->allocsize + BLOCK_ALIGN_M1) & ~BLOCK_ALIGN_M1;
  325. }
  326. }
  327. assert (off_alloc == off_allocend);
  328. assert (off_alloc <= db->head->first_free);
  329. if (off_alloc == db->head->first_free)
  330. /* We are done, that was the last block. */
  331. break;
  332. }
  333. assert (next_hash == &he[db->head->nentries]);
  334. assert (next_data == &he_data[db->head->nentries]);
  335. /* Now perform the actual moves. */
  336. if (moves != NULL)
  337. {
  338. struct moveinfo *runp = moves->next;
  339. do
  340. {
  341. assert ((char *) runp->to >= db->data);
  342. assert ((char *) runp->to + runp->size
  343. <= db->data + db->head->first_free);
  344. assert ((char *) runp->from >= db->data);
  345. assert ((char *) runp->from + runp->size
  346. <= db->data + db->head->first_free);
  347. /* The regions may overlap. */
  348. memmove (runp->to, runp->from, runp->size);
  349. runp = runp->next;
  350. }
  351. while (runp != moves->next);
  352. if (__glibc_unlikely (debug_level >= 3))
  353. dbg_log (_("freed %zu bytes in %s cache"),
  354. (size_t) (db->head->first_free
  355. - ((char *) moves->to + moves->size - db->data)),
  356. dbnames[db - dbs]);
  357. /* The byte past the end of the last copied block is the next
  358. available byte. */
  359. db->head->first_free = (char *) moves->to + moves->size - db->data;
  360. /* Consistency check. */
  361. if (__glibc_unlikely (debug_level >= 3))
  362. {
  363. for (size_t idx = 0; idx < db->head->module; ++idx)
  364. {
  365. ref_t run = db->head->array[idx];
  366. size_t cnt = 0;
  367. while (run != ENDREF)
  368. {
  369. if (run + sizeof (struct hashentry) > db->head->first_free)
  370. {
  371. dbg_log ("entry %zu in hash bucket %zu out of bounds: "
  372. "%" PRIu32 "+%zu > %zu\n",
  373. cnt, idx, run, sizeof (struct hashentry),
  374. (size_t) db->head->first_free);
  375. break;
  376. }
  377. struct hashentry *he = (struct hashentry *) (db->data + run);
  378. if (he->key + he->len > db->head->first_free)
  379. dbg_log ("key of entry %zu in hash bucket %zu out of "
  380. "bounds: %" PRIu32 "+%zu > %zu\n",
  381. cnt, idx, he->key, (size_t) he->len,
  382. (size_t) db->head->first_free);
  383. if (he->packet + sizeof (struct datahead)
  384. > db->head->first_free)
  385. dbg_log ("packet of entry %zu in hash bucket %zu out of "
  386. "bounds: %" PRIu32 "+%zu > %zu\n",
  387. cnt, idx, he->packet, sizeof (struct datahead),
  388. (size_t) db->head->first_free);
  389. else
  390. {
  391. struct datahead *dh = (struct datahead *) (db->data
  392. + he->packet);
  393. if (he->packet + dh->allocsize
  394. > db->head->first_free)
  395. dbg_log ("full key of entry %zu in hash bucket %zu "
  396. "out of bounds: %" PRIu32 "+%zu > %zu",
  397. cnt, idx, he->packet, (size_t) dh->allocsize,
  398. (size_t) db->head->first_free);
  399. }
  400. run = he->next;
  401. ++cnt;
  402. }
  403. }
  404. }
  405. }
  406. /* Make sure the data on disk is updated. */
  407. if (db->persistent)
  408. msync (db->head, db->data + db->head->first_free - (char *) db->head,
  409. MS_ASYNC);
  410. /* Now we are done modifying the data. */
  411. atomic_fetch_add_relaxed (&db->head->gc_cycle, 1);
  412. assert ((db->head->gc_cycle & 1) == 0);
  413. /* We are done. */
  414. out:
  415. pthread_mutex_unlock (&db->memlock);
  416. pthread_rwlock_unlock (&db->lock);
  417. if (he_use_malloc)
  418. free (he);
  419. if (mark_use_malloc)
  420. free (mark);
  421. obstack_free (&ob, NULL);
  422. }
  423. void *
  424. mempool_alloc (struct database_dyn *db, size_t len, int data_alloc)
  425. {
  426. /* Make sure LEN is a multiple of our maximum alignment so we can
  427. keep track of used memory is multiples of this alignment value. */
  428. if ((len & BLOCK_ALIGN_M1) != 0)
  429. len += BLOCK_ALIGN - (len & BLOCK_ALIGN_M1);
  430. if (data_alloc)
  431. pthread_rwlock_rdlock (&db->lock);
  432. pthread_mutex_lock (&db->memlock);
  433. assert ((db->head->first_free & BLOCK_ALIGN_M1) == 0);
  434. bool tried_resize = false;
  435. void *res;
  436. retry:
  437. res = db->data + db->head->first_free;
  438. if (__glibc_unlikely (db->head->first_free + len > db->head->data_size))
  439. {
  440. if (! tried_resize)
  441. {
  442. /* Try to resize the database. Grow size of 1/8th. */
  443. size_t oldtotal = (sizeof (struct database_pers_head)
  444. + roundup (db->head->module * sizeof (ref_t),
  445. ALIGN)
  446. + db->head->data_size);
  447. size_t new_data_size = (db->head->data_size
  448. + MAX (2 * len, db->head->data_size / 8));
  449. size_t newtotal = (sizeof (struct database_pers_head)
  450. + roundup (db->head->module * sizeof (ref_t), ALIGN)
  451. + new_data_size);
  452. if (newtotal > db->max_db_size)
  453. {
  454. new_data_size -= newtotal - db->max_db_size;
  455. newtotal = db->max_db_size;
  456. }
  457. if (db->mmap_used && newtotal > oldtotal
  458. /* We only have to adjust the file size. The new pages
  459. become magically available. */
  460. && TEMP_FAILURE_RETRY_VAL (posix_fallocate (db->wr_fd, oldtotal,
  461. newtotal
  462. - oldtotal)) == 0)
  463. {
  464. db->head->data_size = new_data_size;
  465. tried_resize = true;
  466. goto retry;
  467. }
  468. }
  469. if (data_alloc)
  470. pthread_rwlock_unlock (&db->lock);
  471. if (! db->last_alloc_failed)
  472. {
  473. dbg_log (_("no more memory for database '%s'"), dbnames[db - dbs]);
  474. db->last_alloc_failed = true;
  475. }
  476. ++db->head->addfailed;
  477. /* No luck. */
  478. res = NULL;
  479. }
  480. else
  481. {
  482. db->head->first_free += len;
  483. db->last_alloc_failed = false;
  484. }
  485. pthread_mutex_unlock (&db->memlock);
  486. return res;
  487. }