xfarray.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * Copyright (C) 2021-2023 Oracle. All Rights Reserved.
  4. * Author: Darrick J. Wong <djwong@kernel.org>
  5. */
  6. #include "xfs_platform.h"
  7. #include "xfs_fs.h"
  8. #include "xfs_shared.h"
  9. #include "xfs_format.h"
  10. #include "scrub/scrub.h"
  11. #include "scrub/xfile.h"
  12. #include "scrub/xfarray.h"
  13. #include "scrub/trace.h"
  14. /*
  15. * Large Arrays of Fixed-Size Records
  16. * ==================================
  17. *
  18. * This memory array uses an xfile (which itself is a shmem file) to store
  19. * large numbers of fixed-size records in memory that can be paged out. This
  20. * puts less stress on the memory reclaim algorithms during an online repair
  21. * because we don't have to pin so much memory. However, array access is less
  22. * direct than would be in a regular memory array. Access to the array is
  23. * performed via indexed load and store methods, and an append method is
  24. * provided for convenience. Array elements can be unset, which sets them to
  25. * all zeroes. Unset entries are skipped during iteration, though direct loads
  26. * will return a zeroed buffer. Callers are responsible for concurrency
  27. * control.
  28. */
  29. /*
  30. * Pointer to scratch space. Because we can't access the xfile data directly,
  31. * we allocate a small amount of memory on the end of the xfarray structure to
  32. * buffer array items when we need space to store values temporarily.
  33. */
  34. static inline void *xfarray_scratch(struct xfarray *array)
  35. {
  36. return (array + 1);
  37. }
  38. /* Compute array index given an xfile offset. */
  39. static xfarray_idx_t
  40. xfarray_idx(
  41. struct xfarray *array,
  42. loff_t pos)
  43. {
  44. if (array->obj_size_log >= 0)
  45. return (xfarray_idx_t)pos >> array->obj_size_log;
  46. return div_u64((xfarray_idx_t)pos, array->obj_size);
  47. }
  48. /* Compute xfile offset of array element. */
  49. static inline loff_t xfarray_pos(struct xfarray *array, xfarray_idx_t idx)
  50. {
  51. if (array->obj_size_log >= 0)
  52. return idx << array->obj_size_log;
  53. return idx * array->obj_size;
  54. }
  55. /*
  56. * Initialize a big memory array. Array records cannot be larger than a
  57. * page, and the array cannot span more bytes than the page cache supports.
  58. * If @required_capacity is nonzero, the maximum array size will be set to this
  59. * quantity and the array creation will fail if the underlying storage cannot
  60. * support that many records.
  61. */
  62. int
  63. xfarray_create(
  64. const char *description,
  65. unsigned long long required_capacity,
  66. size_t obj_size,
  67. struct xfarray **arrayp)
  68. {
  69. struct xfarray *array;
  70. struct xfile *xfile;
  71. int error;
  72. ASSERT(obj_size < PAGE_SIZE);
  73. error = xfile_create(description, 0, &xfile);
  74. if (error)
  75. return error;
  76. error = -ENOMEM;
  77. array = kzalloc(sizeof(struct xfarray) + obj_size, XCHK_GFP_FLAGS);
  78. if (!array)
  79. goto out_xfile;
  80. array->xfile = xfile;
  81. array->obj_size = obj_size;
  82. if (is_power_of_2(obj_size))
  83. array->obj_size_log = ilog2(obj_size);
  84. else
  85. array->obj_size_log = -1;
  86. array->max_nr = xfarray_idx(array, MAX_LFS_FILESIZE);
  87. trace_xfarray_create(array, required_capacity);
  88. if (required_capacity > 0) {
  89. if (array->max_nr < required_capacity) {
  90. error = -ENOMEM;
  91. goto out_xfarray;
  92. }
  93. array->max_nr = required_capacity;
  94. }
  95. *arrayp = array;
  96. return 0;
  97. out_xfarray:
  98. kfree(array);
  99. out_xfile:
  100. xfile_destroy(xfile);
  101. return error;
  102. }
  103. /* Destroy the array. */
  104. void
  105. xfarray_destroy(
  106. struct xfarray *array)
  107. {
  108. xfile_destroy(array->xfile);
  109. kfree(array);
  110. }
  111. /* Load an element from the array. */
  112. int
  113. xfarray_load(
  114. struct xfarray *array,
  115. xfarray_idx_t idx,
  116. void *ptr)
  117. {
  118. if (idx >= array->nr)
  119. return -ENODATA;
  120. return xfile_load(array->xfile, ptr, array->obj_size,
  121. xfarray_pos(array, idx));
  122. }
  123. /* Is this array element potentially unset? */
  124. static inline bool
  125. xfarray_is_unset(
  126. struct xfarray *array,
  127. loff_t pos)
  128. {
  129. void *temp = xfarray_scratch(array);
  130. int error;
  131. if (array->unset_slots == 0)
  132. return false;
  133. error = xfile_load(array->xfile, temp, array->obj_size, pos);
  134. if (!error && xfarray_element_is_null(array, temp))
  135. return true;
  136. return false;
  137. }
  138. /*
  139. * Unset an array element. If @idx is the last element in the array, the
  140. * array will be truncated. Otherwise, the entry will be zeroed.
  141. */
  142. int
  143. xfarray_unset(
  144. struct xfarray *array,
  145. xfarray_idx_t idx)
  146. {
  147. void *temp = xfarray_scratch(array);
  148. loff_t pos = xfarray_pos(array, idx);
  149. int error;
  150. if (idx >= array->nr)
  151. return -ENODATA;
  152. if (idx == array->nr - 1) {
  153. array->nr--;
  154. return 0;
  155. }
  156. if (xfarray_is_unset(array, pos))
  157. return 0;
  158. memset(temp, 0, array->obj_size);
  159. error = xfile_store(array->xfile, temp, array->obj_size, pos);
  160. if (error)
  161. return error;
  162. array->unset_slots++;
  163. return 0;
  164. }
  165. /*
  166. * Store an element in the array. The element must not be completely zeroed,
  167. * because those are considered unset sparse elements.
  168. */
  169. int
  170. xfarray_store(
  171. struct xfarray *array,
  172. xfarray_idx_t idx,
  173. const void *ptr)
  174. {
  175. int ret;
  176. if (idx >= array->max_nr)
  177. return -EFBIG;
  178. ASSERT(!xfarray_element_is_null(array, ptr));
  179. ret = xfile_store(array->xfile, ptr, array->obj_size,
  180. xfarray_pos(array, idx));
  181. if (ret)
  182. return ret;
  183. array->nr = max(array->nr, idx + 1);
  184. return 0;
  185. }
  186. /* Is this array element NULL? */
  187. bool
  188. xfarray_element_is_null(
  189. struct xfarray *array,
  190. const void *ptr)
  191. {
  192. return !memchr_inv(ptr, 0, array->obj_size);
  193. }
  194. /*
  195. * Store an element anywhere in the array that is unset. If there are no
  196. * unset slots, append the element to the array.
  197. */
  198. int
  199. xfarray_store_anywhere(
  200. struct xfarray *array,
  201. const void *ptr)
  202. {
  203. void *temp = xfarray_scratch(array);
  204. loff_t endpos = xfarray_pos(array, array->nr);
  205. loff_t pos;
  206. int error;
  207. /* Find an unset slot to put it in. */
  208. for (pos = 0;
  209. pos < endpos && array->unset_slots > 0;
  210. pos += array->obj_size) {
  211. error = xfile_load(array->xfile, temp, array->obj_size,
  212. pos);
  213. if (error || !xfarray_element_is_null(array, temp))
  214. continue;
  215. error = xfile_store(array->xfile, ptr, array->obj_size,
  216. pos);
  217. if (error)
  218. return error;
  219. array->unset_slots--;
  220. return 0;
  221. }
  222. /* No unset slots found; attach it on the end. */
  223. array->unset_slots = 0;
  224. return xfarray_append(array, ptr);
  225. }
  226. /* Return length of array. */
  227. uint64_t
  228. xfarray_length(
  229. struct xfarray *array)
  230. {
  231. return array->nr;
  232. }
  233. /*
  234. * Decide which array item we're going to read as part of an _iter_get.
  235. * @cur is the array index, and @pos is the file offset of that array index in
  236. * the backing xfile. Returns ENODATA if we reach the end of the records.
  237. *
  238. * Reading from a hole in a sparse xfile causes page instantiation, so for
  239. * iterating a (possibly sparse) array we need to figure out if the cursor is
  240. * pointing at a totally uninitialized hole and move the cursor up if
  241. * necessary.
  242. */
  243. static inline int
  244. xfarray_find_data(
  245. struct xfarray *array,
  246. xfarray_idx_t *cur,
  247. loff_t *pos)
  248. {
  249. unsigned int pgoff = offset_in_page(*pos);
  250. loff_t end_pos = *pos + array->obj_size - 1;
  251. loff_t new_pos;
  252. /*
  253. * If the current array record is not adjacent to a page boundary, we
  254. * are in the middle of the page. We do not need to move the cursor.
  255. */
  256. if (pgoff != 0 && pgoff + array->obj_size - 1 < PAGE_SIZE)
  257. return 0;
  258. /*
  259. * Call SEEK_DATA on the last byte in the record we're about to read.
  260. * If the record ends at (or crosses) the end of a page then we know
  261. * that the first byte of the record is backed by pages and don't need
  262. * to query it. If instead the record begins at the start of the page
  263. * then we know that querying the last byte is just as good as querying
  264. * the first byte, since records cannot be larger than a page.
  265. *
  266. * If the call returns the same file offset, we know this record is
  267. * backed by real pages. We do not need to move the cursor.
  268. */
  269. new_pos = xfile_seek_data(array->xfile, end_pos);
  270. if (new_pos == -ENXIO)
  271. return -ENODATA;
  272. if (new_pos < 0)
  273. return new_pos;
  274. if (new_pos == end_pos)
  275. return 0;
  276. /*
  277. * Otherwise, SEEK_DATA told us how far up to move the file pointer to
  278. * find more data. Move the array index to the first record past the
  279. * byte offset we were given.
  280. */
  281. new_pos = roundup_64(new_pos, array->obj_size);
  282. *cur = xfarray_idx(array, new_pos);
  283. *pos = xfarray_pos(array, *cur);
  284. return 0;
  285. }
  286. /*
  287. * Starting at *idx, fetch the next non-null array entry and advance the index
  288. * to set up the next _load_next call. Returns ENODATA if we reach the end of
  289. * the array. Callers must set @*idx to XFARRAY_CURSOR_INIT before the first
  290. * call to this function.
  291. */
  292. int
  293. xfarray_load_next(
  294. struct xfarray *array,
  295. xfarray_idx_t *idx,
  296. void *rec)
  297. {
  298. xfarray_idx_t cur = *idx;
  299. loff_t pos = xfarray_pos(array, cur);
  300. int error;
  301. do {
  302. if (cur >= array->nr)
  303. return -ENODATA;
  304. /*
  305. * Ask the backing store for the location of next possible
  306. * written record, then retrieve that record.
  307. */
  308. error = xfarray_find_data(array, &cur, &pos);
  309. if (error)
  310. return error;
  311. error = xfarray_load(array, cur, rec);
  312. if (error)
  313. return error;
  314. cur++;
  315. pos += array->obj_size;
  316. } while (xfarray_element_is_null(array, rec));
  317. *idx = cur;
  318. return 0;
  319. }
  320. /* Sorting functions */
  321. #ifdef DEBUG
  322. # define xfarray_sort_bump_loads(si) do { (si)->loads++; } while (0)
  323. # define xfarray_sort_bump_stores(si) do { (si)->stores++; } while (0)
  324. # define xfarray_sort_bump_compares(si) do { (si)->compares++; } while (0)
  325. # define xfarray_sort_bump_heapsorts(si) do { (si)->heapsorts++; } while (0)
  326. #else
  327. # define xfarray_sort_bump_loads(si)
  328. # define xfarray_sort_bump_stores(si)
  329. # define xfarray_sort_bump_compares(si)
  330. # define xfarray_sort_bump_heapsorts(si)
  331. #endif /* DEBUG */
  332. /* Load an array element for sorting. */
  333. static inline int
  334. xfarray_sort_load(
  335. struct xfarray_sortinfo *si,
  336. xfarray_idx_t idx,
  337. void *ptr)
  338. {
  339. xfarray_sort_bump_loads(si);
  340. return xfarray_load(si->array, idx, ptr);
  341. }
  342. /* Store an array element for sorting. */
  343. static inline int
  344. xfarray_sort_store(
  345. struct xfarray_sortinfo *si,
  346. xfarray_idx_t idx,
  347. void *ptr)
  348. {
  349. xfarray_sort_bump_stores(si);
  350. return xfarray_store(si->array, idx, ptr);
  351. }
  352. /* Compare an array element for sorting. */
  353. static inline int
  354. xfarray_sort_cmp(
  355. struct xfarray_sortinfo *si,
  356. const void *a,
  357. const void *b)
  358. {
  359. xfarray_sort_bump_compares(si);
  360. return si->cmp_fn(a, b);
  361. }
  362. /* Return a pointer to the low index stack for quicksort partitioning. */
  363. static inline xfarray_idx_t *xfarray_sortinfo_lo(struct xfarray_sortinfo *si)
  364. {
  365. return (xfarray_idx_t *)(si + 1);
  366. }
  367. /* Return a pointer to the high index stack for quicksort partitioning. */
  368. static inline xfarray_idx_t *xfarray_sortinfo_hi(struct xfarray_sortinfo *si)
  369. {
  370. return xfarray_sortinfo_lo(si) + si->max_stack_depth;
  371. }
  372. /* Size of each element in the quicksort pivot array. */
  373. static inline size_t
  374. xfarray_pivot_rec_sz(
  375. struct xfarray *array)
  376. {
  377. return round_up(array->obj_size, 8) + sizeof(xfarray_idx_t);
  378. }
  379. /* Allocate memory to handle the sort. */
  380. static inline int
  381. xfarray_sortinfo_alloc(
  382. struct xfarray *array,
  383. xfarray_cmp_fn cmp_fn,
  384. unsigned int flags,
  385. struct xfarray_sortinfo **infop)
  386. {
  387. struct xfarray_sortinfo *si;
  388. size_t nr_bytes = sizeof(struct xfarray_sortinfo);
  389. size_t pivot_rec_sz = xfarray_pivot_rec_sz(array);
  390. int max_stack_depth;
  391. /*
  392. * The median-of-nine pivot algorithm doesn't work if a subset has
  393. * fewer than 9 items. Make sure the in-memory sort will always take
  394. * over for subsets where this wouldn't be the case.
  395. */
  396. BUILD_BUG_ON(XFARRAY_QSORT_PIVOT_NR >= XFARRAY_ISORT_NR);
  397. /*
  398. * Tail-call recursion during the partitioning phase means that
  399. * quicksort will never recurse more than log2(nr) times. We need one
  400. * extra level of stack to hold the initial parameters. In-memory
  401. * sort will always take care of the last few levels of recursion for
  402. * us, so we can reduce the stack depth by that much.
  403. */
  404. max_stack_depth = ilog2(array->nr) + 1 - (XFARRAY_ISORT_SHIFT - 1);
  405. if (max_stack_depth < 1)
  406. max_stack_depth = 1;
  407. /* Each level of quicksort uses a lo and a hi index */
  408. nr_bytes += max_stack_depth * sizeof(xfarray_idx_t) * 2;
  409. /* Scratchpad for in-memory sort, or finding the pivot */
  410. nr_bytes += max_t(size_t,
  411. (XFARRAY_QSORT_PIVOT_NR + 1) * pivot_rec_sz,
  412. XFARRAY_ISORT_NR * array->obj_size);
  413. si = kvzalloc(nr_bytes, XCHK_GFP_FLAGS);
  414. if (!si)
  415. return -ENOMEM;
  416. si->array = array;
  417. si->cmp_fn = cmp_fn;
  418. si->flags = flags;
  419. si->max_stack_depth = max_stack_depth;
  420. si->max_stack_used = 1;
  421. xfarray_sortinfo_lo(si)[0] = 0;
  422. xfarray_sortinfo_hi(si)[0] = array->nr - 1;
  423. si->relax = INIT_XCHK_RELAX;
  424. if (flags & XFARRAY_SORT_KILLABLE)
  425. si->relax.interruptible = false;
  426. trace_xfarray_sort(si, nr_bytes);
  427. *infop = si;
  428. return 0;
  429. }
  430. /* Should this sort be terminated by a fatal signal? */
  431. static inline bool
  432. xfarray_sort_terminated(
  433. struct xfarray_sortinfo *si,
  434. int *error)
  435. {
  436. /*
  437. * If preemption is disabled, we need to yield to the scheduler every
  438. * few seconds so that we don't run afoul of the soft lockup watchdog
  439. * or RCU stall detector.
  440. */
  441. if (xchk_maybe_relax(&si->relax)) {
  442. if (*error == 0)
  443. *error = -EINTR;
  444. return true;
  445. }
  446. return false;
  447. }
  448. /* Do we want an in-memory sort? */
  449. static inline bool
  450. xfarray_want_isort(
  451. struct xfarray_sortinfo *si,
  452. xfarray_idx_t start,
  453. xfarray_idx_t end)
  454. {
  455. /*
  456. * For array subsets that fit in the scratchpad, it's much faster to
  457. * use the kernel's heapsort than quicksort's stack machine.
  458. */
  459. return (end - start) < XFARRAY_ISORT_NR;
  460. }
  461. /* Return the scratch space within the sortinfo structure. */
  462. static inline void *xfarray_sortinfo_isort_scratch(struct xfarray_sortinfo *si)
  463. {
  464. return xfarray_sortinfo_hi(si) + si->max_stack_depth;
  465. }
  466. /*
  467. * Sort a small number of array records using scratchpad memory. The records
  468. * need not be contiguous in the xfile's memory pages.
  469. */
  470. STATIC int
  471. xfarray_isort(
  472. struct xfarray_sortinfo *si,
  473. xfarray_idx_t lo,
  474. xfarray_idx_t hi)
  475. {
  476. void *scratch = xfarray_sortinfo_isort_scratch(si);
  477. loff_t lo_pos = xfarray_pos(si->array, lo);
  478. loff_t len = xfarray_pos(si->array, hi - lo + 1);
  479. int error;
  480. trace_xfarray_isort(si, lo, hi);
  481. xfarray_sort_bump_loads(si);
  482. error = xfile_load(si->array->xfile, scratch, len, lo_pos);
  483. if (error)
  484. return error;
  485. xfarray_sort_bump_heapsorts(si);
  486. sort(scratch, hi - lo + 1, si->array->obj_size, si->cmp_fn, NULL);
  487. xfarray_sort_bump_stores(si);
  488. return xfile_store(si->array->xfile, scratch, len, lo_pos);
  489. }
  490. /*
  491. * Sort the records from lo to hi (inclusive) if they are all backed by the
  492. * same memory folio. Returns 1 if it sorted, 0 if it did not, or a negative
  493. * errno.
  494. */
  495. STATIC int
  496. xfarray_foliosort(
  497. struct xfarray_sortinfo *si,
  498. xfarray_idx_t lo,
  499. xfarray_idx_t hi)
  500. {
  501. struct folio *folio;
  502. void *startp;
  503. loff_t lo_pos = xfarray_pos(si->array, lo);
  504. uint64_t len = xfarray_pos(si->array, hi - lo + 1);
  505. /* No single folio could back this many records. */
  506. if (len > XFILE_MAX_FOLIO_SIZE)
  507. return 0;
  508. xfarray_sort_bump_loads(si);
  509. folio = xfile_get_folio(si->array->xfile, lo_pos, len, XFILE_ALLOC);
  510. if (IS_ERR(folio))
  511. return PTR_ERR(folio);
  512. if (!folio)
  513. return 0;
  514. trace_xfarray_foliosort(si, lo, hi);
  515. xfarray_sort_bump_heapsorts(si);
  516. startp = folio_address(folio) + offset_in_folio(folio, lo_pos);
  517. sort(startp, hi - lo + 1, si->array->obj_size, si->cmp_fn, NULL);
  518. xfarray_sort_bump_stores(si);
  519. xfile_put_folio(si->array->xfile, folio);
  520. return 1;
  521. }
  522. /* Return a pointer to the xfarray pivot record within the sortinfo struct. */
  523. static inline void *xfarray_sortinfo_pivot(struct xfarray_sortinfo *si)
  524. {
  525. return xfarray_sortinfo_hi(si) + si->max_stack_depth;
  526. }
  527. /* Return a pointer to the start of the pivot array. */
  528. static inline void *
  529. xfarray_sortinfo_pivot_array(
  530. struct xfarray_sortinfo *si)
  531. {
  532. return xfarray_sortinfo_pivot(si) + si->array->obj_size;
  533. }
  534. /* The xfarray record is stored at the start of each pivot array element. */
  535. static inline void *
  536. xfarray_pivot_array_rec(
  537. void *pa,
  538. size_t pa_recsz,
  539. unsigned int pa_idx)
  540. {
  541. return pa + (pa_recsz * pa_idx);
  542. }
  543. /* The xfarray index is stored at the end of each pivot array element. */
  544. static inline xfarray_idx_t *
  545. xfarray_pivot_array_idx(
  546. void *pa,
  547. size_t pa_recsz,
  548. unsigned int pa_idx)
  549. {
  550. return xfarray_pivot_array_rec(pa, pa_recsz, pa_idx + 1) -
  551. sizeof(xfarray_idx_t);
  552. }
  553. /*
  554. * Find a pivot value for quicksort partitioning, swap it with a[lo], and save
  555. * the cached pivot record for the next step.
  556. *
  557. * Load evenly-spaced records within the given range into memory, sort them,
  558. * and choose the pivot from the median record. Using multiple points will
  559. * improve the quality of the pivot selection, and hopefully avoid the worst
  560. * quicksort behavior, since our array values are nearly always evenly sorted.
  561. */
  562. STATIC int
  563. xfarray_qsort_pivot(
  564. struct xfarray_sortinfo *si,
  565. xfarray_idx_t lo,
  566. xfarray_idx_t hi)
  567. {
  568. void *pivot = xfarray_sortinfo_pivot(si);
  569. void *parray = xfarray_sortinfo_pivot_array(si);
  570. void *recp;
  571. xfarray_idx_t *idxp;
  572. xfarray_idx_t step = (hi - lo) / (XFARRAY_QSORT_PIVOT_NR - 1);
  573. size_t pivot_rec_sz = xfarray_pivot_rec_sz(si->array);
  574. int i, j;
  575. int error;
  576. ASSERT(step > 0);
  577. /*
  578. * Load the xfarray indexes of the records we intend to sample into the
  579. * pivot array.
  580. */
  581. idxp = xfarray_pivot_array_idx(parray, pivot_rec_sz, 0);
  582. *idxp = lo;
  583. for (i = 1; i < XFARRAY_QSORT_PIVOT_NR - 1; i++) {
  584. idxp = xfarray_pivot_array_idx(parray, pivot_rec_sz, i);
  585. *idxp = lo + (i * step);
  586. }
  587. idxp = xfarray_pivot_array_idx(parray, pivot_rec_sz,
  588. XFARRAY_QSORT_PIVOT_NR - 1);
  589. *idxp = hi;
  590. /* Load the selected xfarray records into the pivot array. */
  591. for (i = 0; i < XFARRAY_QSORT_PIVOT_NR; i++) {
  592. xfarray_idx_t idx;
  593. recp = xfarray_pivot_array_rec(parray, pivot_rec_sz, i);
  594. idxp = xfarray_pivot_array_idx(parray, pivot_rec_sz, i);
  595. /* No unset records; load directly into the array. */
  596. if (likely(si->array->unset_slots == 0)) {
  597. error = xfarray_sort_load(si, *idxp, recp);
  598. if (error)
  599. return error;
  600. continue;
  601. }
  602. /*
  603. * Load non-null records into the scratchpad without changing
  604. * the xfarray_idx_t in the pivot array.
  605. */
  606. idx = *idxp;
  607. xfarray_sort_bump_loads(si);
  608. error = xfarray_load_next(si->array, &idx, recp);
  609. if (error)
  610. return error;
  611. }
  612. xfarray_sort_bump_heapsorts(si);
  613. sort(parray, XFARRAY_QSORT_PIVOT_NR, pivot_rec_sz, si->cmp_fn, NULL);
  614. /*
  615. * We sorted the pivot array records (which includes the xfarray
  616. * indices) in xfarray record order. The median element of the pivot
  617. * array contains the xfarray record that we will use as the pivot.
  618. * Copy that xfarray record to the designated space.
  619. */
  620. recp = xfarray_pivot_array_rec(parray, pivot_rec_sz,
  621. XFARRAY_QSORT_PIVOT_NR / 2);
  622. memcpy(pivot, recp, si->array->obj_size);
  623. /* If the pivot record we chose was already in a[lo] then we're done. */
  624. idxp = xfarray_pivot_array_idx(parray, pivot_rec_sz,
  625. XFARRAY_QSORT_PIVOT_NR / 2);
  626. if (*idxp == lo)
  627. return 0;
  628. /*
  629. * Find the cached copy of a[lo] in the pivot array so that we can swap
  630. * a[lo] and a[pivot].
  631. */
  632. for (i = 0, j = -1; i < XFARRAY_QSORT_PIVOT_NR; i++) {
  633. idxp = xfarray_pivot_array_idx(parray, pivot_rec_sz, i);
  634. if (*idxp == lo)
  635. j = i;
  636. }
  637. if (j < 0) {
  638. ASSERT(j >= 0);
  639. return -EFSCORRUPTED;
  640. }
  641. /* Swap a[lo] and a[pivot]. */
  642. error = xfarray_sort_store(si, lo, pivot);
  643. if (error)
  644. return error;
  645. recp = xfarray_pivot_array_rec(parray, pivot_rec_sz, j);
  646. idxp = xfarray_pivot_array_idx(parray, pivot_rec_sz,
  647. XFARRAY_QSORT_PIVOT_NR / 2);
  648. return xfarray_sort_store(si, *idxp, recp);
  649. }
  650. /*
  651. * Set up the pointers for the next iteration. We push onto the stack all of
  652. * the unsorted values between a[lo + 1] and a[end[i]], and we tweak the
  653. * current stack frame to point to the unsorted values between a[beg[i]] and
  654. * a[lo] so that those values will be sorted when we pop the stack.
  655. */
  656. static inline int
  657. xfarray_qsort_push(
  658. struct xfarray_sortinfo *si,
  659. xfarray_idx_t *si_lo,
  660. xfarray_idx_t *si_hi,
  661. xfarray_idx_t lo,
  662. xfarray_idx_t hi)
  663. {
  664. /* Check for stack overflows */
  665. if (si->stack_depth >= si->max_stack_depth - 1) {
  666. ASSERT(si->stack_depth < si->max_stack_depth - 1);
  667. return -EFSCORRUPTED;
  668. }
  669. si->max_stack_used = max_t(uint8_t, si->max_stack_used,
  670. si->stack_depth + 2);
  671. si_lo[si->stack_depth + 1] = lo + 1;
  672. si_hi[si->stack_depth + 1] = si_hi[si->stack_depth];
  673. si_hi[si->stack_depth++] = lo - 1;
  674. /*
  675. * Always start with the smaller of the two partitions to keep the
  676. * amount of recursion in check.
  677. */
  678. if (si_hi[si->stack_depth] - si_lo[si->stack_depth] >
  679. si_hi[si->stack_depth - 1] - si_lo[si->stack_depth - 1]) {
  680. swap(si_lo[si->stack_depth], si_lo[si->stack_depth - 1]);
  681. swap(si_hi[si->stack_depth], si_hi[si->stack_depth - 1]);
  682. }
  683. return 0;
  684. }
  685. static inline void
  686. xfarray_sort_scan_done(
  687. struct xfarray_sortinfo *si)
  688. {
  689. if (si->folio)
  690. xfile_put_folio(si->array->xfile, si->folio);
  691. si->folio = NULL;
  692. }
  693. /*
  694. * Cache the folio backing the start of the given array element. If the array
  695. * element is contained entirely within the folio, return a pointer to the
  696. * cached folio. Otherwise, load the element into the scratchpad and return a
  697. * pointer to the scratchpad.
  698. */
  699. static inline int
  700. xfarray_sort_scan(
  701. struct xfarray_sortinfo *si,
  702. xfarray_idx_t idx,
  703. void **ptrp)
  704. {
  705. loff_t idx_pos = xfarray_pos(si->array, idx);
  706. int error = 0;
  707. if (xfarray_sort_terminated(si, &error))
  708. return error;
  709. trace_xfarray_sort_scan(si, idx);
  710. /* If the cached folio doesn't cover this index, release it. */
  711. if (si->folio &&
  712. (idx < si->first_folio_idx || idx > si->last_folio_idx))
  713. xfarray_sort_scan_done(si);
  714. /* Grab the first folio that backs this array element. */
  715. if (!si->folio) {
  716. struct folio *folio;
  717. loff_t next_pos;
  718. folio = xfile_get_folio(si->array->xfile, idx_pos,
  719. si->array->obj_size, XFILE_ALLOC);
  720. if (IS_ERR(folio))
  721. return PTR_ERR(folio);
  722. si->folio = folio;
  723. si->first_folio_idx = xfarray_idx(si->array,
  724. folio_pos(si->folio) + si->array->obj_size - 1);
  725. next_pos = folio_next_pos(si->folio);
  726. si->last_folio_idx = xfarray_idx(si->array, next_pos - 1);
  727. if (xfarray_pos(si->array, si->last_folio_idx + 1) > next_pos)
  728. si->last_folio_idx--;
  729. trace_xfarray_sort_scan(si, idx);
  730. }
  731. /*
  732. * If this folio still doesn't cover the desired element, it must cross
  733. * a folio boundary. Read into the scratchpad and we're done.
  734. */
  735. if (idx < si->first_folio_idx || idx > si->last_folio_idx) {
  736. void *temp = xfarray_scratch(si->array);
  737. error = xfile_load(si->array->xfile, temp, si->array->obj_size,
  738. idx_pos);
  739. if (error)
  740. return error;
  741. *ptrp = temp;
  742. return 0;
  743. }
  744. /* Otherwise return a pointer to the array element in the folio. */
  745. *ptrp = folio_address(si->folio) + offset_in_folio(si->folio, idx_pos);
  746. return 0;
  747. }
  748. /*
  749. * Sort the array elements via quicksort. This implementation incorporates
  750. * four optimizations discussed in Sedgewick:
  751. *
  752. * 1. Use an explicit stack of array indices to store the next array partition
  753. * to sort. This helps us to avoid recursion in the call stack, which is
  754. * particularly expensive in the kernel.
  755. *
  756. * 2. For arrays with records in arbitrary or user-controlled order, choose the
  757. * pivot element using a median-of-nine decision tree. This reduces the
  758. * probability of selecting a bad pivot value which causes worst case
  759. * behavior (i.e. partition sizes of 1).
  760. *
  761. * 3. The smaller of the two sub-partitions is pushed onto the stack to start
  762. * the next level of recursion, and the larger sub-partition replaces the
  763. * current stack frame. This guarantees that we won't need more than
  764. * log2(nr) stack space.
  765. *
  766. * 4. For small sets, load the records into the scratchpad and run heapsort on
  767. * them because that is very fast. In the author's experience, this yields
  768. * a ~10% reduction in runtime.
  769. *
  770. * If a small set is contained entirely within a single xfile memory page,
  771. * map the page directly and run heap sort directly on the xfile page
  772. * instead of using the load/store interface. This halves the runtime.
  773. *
  774. * 5. This optimization is specific to the implementation. When converging lo
  775. * and hi after selecting a pivot, we will try to retain the xfile memory
  776. * page between load calls, which reduces run time by 50%.
  777. */
  778. /*
  779. * Due to the use of signed indices, we can only support up to 2^63 records.
  780. * Files can only grow to 2^63 bytes, so this is not much of a limitation.
  781. */
  782. #define QSORT_MAX_RECS (1ULL << 63)
  783. int
  784. xfarray_sort(
  785. struct xfarray *array,
  786. xfarray_cmp_fn cmp_fn,
  787. unsigned int flags)
  788. {
  789. struct xfarray_sortinfo *si;
  790. xfarray_idx_t *si_lo, *si_hi;
  791. void *pivot;
  792. void *scratch = xfarray_scratch(array);
  793. xfarray_idx_t lo, hi;
  794. int error = 0;
  795. if (array->nr < 2)
  796. return 0;
  797. if (array->nr >= QSORT_MAX_RECS)
  798. return -E2BIG;
  799. error = xfarray_sortinfo_alloc(array, cmp_fn, flags, &si);
  800. if (error)
  801. return error;
  802. si_lo = xfarray_sortinfo_lo(si);
  803. si_hi = xfarray_sortinfo_hi(si);
  804. pivot = xfarray_sortinfo_pivot(si);
  805. while (si->stack_depth >= 0) {
  806. int ret;
  807. lo = si_lo[si->stack_depth];
  808. hi = si_hi[si->stack_depth];
  809. trace_xfarray_qsort(si, lo, hi);
  810. /* Nothing left in this partition to sort; pop stack. */
  811. if (lo >= hi) {
  812. si->stack_depth--;
  813. continue;
  814. }
  815. /*
  816. * If directly mapping the folio and sorting can solve our
  817. * problems, we're done.
  818. */
  819. ret = xfarray_foliosort(si, lo, hi);
  820. if (ret < 0)
  821. goto out_free;
  822. if (ret == 1) {
  823. si->stack_depth--;
  824. continue;
  825. }
  826. /* If insertion sort can solve our problems, we're done. */
  827. if (xfarray_want_isort(si, lo, hi)) {
  828. error = xfarray_isort(si, lo, hi);
  829. if (error)
  830. goto out_free;
  831. si->stack_depth--;
  832. continue;
  833. }
  834. /* Pick a pivot, move it to a[lo] and stash it. */
  835. error = xfarray_qsort_pivot(si, lo, hi);
  836. if (error)
  837. goto out_free;
  838. /*
  839. * Rearrange a[lo..hi] such that everything smaller than the
  840. * pivot is on the left side of the range and everything larger
  841. * than the pivot is on the right side of the range.
  842. */
  843. while (lo < hi) {
  844. void *p;
  845. /*
  846. * Decrement hi until it finds an a[hi] less than the
  847. * pivot value.
  848. */
  849. error = xfarray_sort_scan(si, hi, &p);
  850. if (error)
  851. goto out_free;
  852. while (xfarray_sort_cmp(si, p, pivot) >= 0 && lo < hi) {
  853. hi--;
  854. error = xfarray_sort_scan(si, hi, &p);
  855. if (error)
  856. goto out_free;
  857. }
  858. if (p != scratch)
  859. memcpy(scratch, p, si->array->obj_size);
  860. xfarray_sort_scan_done(si);
  861. if (xfarray_sort_terminated(si, &error))
  862. goto out_free;
  863. /* Copy that item (a[hi]) to a[lo]. */
  864. if (lo < hi) {
  865. error = xfarray_sort_store(si, lo++, scratch);
  866. if (error)
  867. goto out_free;
  868. }
  869. /*
  870. * Increment lo until it finds an a[lo] greater than
  871. * the pivot value.
  872. */
  873. error = xfarray_sort_scan(si, lo, &p);
  874. if (error)
  875. goto out_free;
  876. while (xfarray_sort_cmp(si, p, pivot) <= 0 && lo < hi) {
  877. lo++;
  878. error = xfarray_sort_scan(si, lo, &p);
  879. if (error)
  880. goto out_free;
  881. }
  882. if (p != scratch)
  883. memcpy(scratch, p, si->array->obj_size);
  884. xfarray_sort_scan_done(si);
  885. if (xfarray_sort_terminated(si, &error))
  886. goto out_free;
  887. /* Copy that item (a[lo]) to a[hi]. */
  888. if (lo < hi) {
  889. error = xfarray_sort_store(si, hi--, scratch);
  890. if (error)
  891. goto out_free;
  892. }
  893. if (xfarray_sort_terminated(si, &error))
  894. goto out_free;
  895. }
  896. /*
  897. * Put our pivot value in the correct place at a[lo]. All
  898. * values between a[beg[i]] and a[lo - 1] should be less than
  899. * the pivot; and all values between a[lo + 1] and a[end[i]-1]
  900. * should be greater than the pivot.
  901. */
  902. error = xfarray_sort_store(si, lo, pivot);
  903. if (error)
  904. goto out_free;
  905. /* Set up the stack frame to process the two partitions. */
  906. error = xfarray_qsort_push(si, si_lo, si_hi, lo, hi);
  907. if (error)
  908. goto out_free;
  909. if (xfarray_sort_terminated(si, &error))
  910. goto out_free;
  911. }
  912. out_free:
  913. trace_xfarray_sort_stats(si, error);
  914. xfarray_sort_scan_done(si);
  915. kvfree(si);
  916. return error;
  917. }
  918. /* How many bytes is this array consuming? */
  919. unsigned long long
  920. xfarray_bytes(
  921. struct xfarray *array)
  922. {
  923. return xfile_bytes(array->xfile);
  924. }
  925. /* Empty the entire array. */
  926. void
  927. xfarray_truncate(
  928. struct xfarray *array)
  929. {
  930. xfile_discard(array->xfile, 0, MAX_LFS_FILESIZE);
  931. array->nr = 0;
  932. }