├── .gitignore
├── LICENSE
├── Makefile
├── Makefile.common
├── PKGBUILD
├── README.md
├── blkio.c
├── blkio.h
├── ctypes.h
├── kv.c
├── kv.h
├── lib.c
├── lib.h
├── remixdb.h
├── remixdb.strip
├── sotest.c
├── sst.c
├── sst.h
├── wh.c
├── wh.h
├── xdb.c
├── xdb.h
├── xdb.py
├── xdbcow.sh
├── xdbdemo.c
├── xdbexit.c
└── xdbtest.c
/.gitignore:
--------------------------------------------------------------------------------
1 | *.out
2 | *.so
3 | *.o
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile
2 | # rules (always with .out)
3 | # SRC-X.out += abc # extra source: abc.c
4 | # MOD-X.out += abc # extra module: abc.c abc.h
5 | # ASM-X.out += abc # extra assembly: abc.S
6 | # DEP-X.out += abc # extra dependency: abc
7 | # FLG-X.out += -finline # extra flags
8 | # LIB-X.out += abc # extra -labc options
9 |
10 | # X.out : xyz.h xyz.c # for extra dependences that are to be compiled/linked.
11 |
12 | # X => X.out
13 | TARGETS += xdbdemo xdbtest xdbexit
14 | # X => X.c only
15 | SOURCES +=
16 | SOURCES += $(EXTRASRC)
17 | # X => X.S only
18 | ASSMBLY +=
19 | ASSMBLY += $(EXTRAASM)
20 | # X => X.c X.h
21 | MODULES += lib kv wh blkio sst xdb
22 | MODULES += $(EXTRAMOD)
23 | # X => X.h
24 | HEADERS += ctypes
25 | HEADERS += $(EXTRAHDR)
26 |
27 | # EXTERNSRC/EXTERNDEP do not belong to this repo.
28 | # extern-src will be linked
29 | EXTERNSRC +=
30 | # extern-dep will not be linked
31 | EXTERNDEP +=
32 |
33 | FLG +=
34 | LIB += m
35 |
36 |
37 | #### all
38 | .PHONY : all
39 | all : bin libremixdb.so sotest.out
40 |
41 | libremixdb.so : Makefile Makefile.common lib.h kv.h wh.h blkio.h sst.h xdb.h lib.c kv.c wh.c blkio.c sst.c xdb.c
42 | $(eval ALLFLG := $(CSTD) $(EXTRA) $(FLG) -shared -fPIC)
43 | $(eval ALLLIB := $(addprefix -l,$(LIB) $(LIB-$@)))
44 | $(CCC) $(ALLFLG) -o $@ lib.c kv.c wh.c blkio.c sst.c xdb.c $(ALLLIB)
45 | strip --strip-all --discard-all @remixdb.strip $@
46 |
47 | sotest.out : sotest.c Makefile Makefile.common libremixdb.so remixdb.h
48 | $(eval ALLFLG := $(CSTD) $(EXTRA) $(FLG))
49 | $(CCC) $(ALLFLG) -o $@ $< -L . -lremixdb
50 | @echo "$(shell $(TPUT) setaf 4)Now run $ LD_LIBRARY_PATH=. ./sotest.out$(shell $(TPUT) sgr0)"
51 |
52 | .PHONY : install
53 | install : libremixdb.so remixdb.h
54 | install -D --mode=0755 libremixdb.so $(PREFIX)/lib/libremixdb.so
55 | install -D --mode=0644 remixdb.h $(PREFIX)/usr/include/remixdb.h
56 |
57 | # append common rules (have to do it here)
58 | include Makefile.common
59 |
--------------------------------------------------------------------------------
/Makefile.common:
--------------------------------------------------------------------------------
1 | #usage: include Makefile.common at the end of your Makefile
2 |
3 | # no builtin rules/vars (CC, CXX, etc. are still defined but will be empty)
4 | MAKEFLAGS += -r -R
5 |
6 | HDR = $(addsuffix .h,$(MODULES) $(HEADERS))
7 | SRC = $(addsuffix .c,$(MODULES) $(SOURCES))
8 | ASM = $(addsuffix .S,$(ASSMBLY))
9 | OBJ = $(addsuffix .o,$(MODULES) $(SOURCES) $(ASSEMBLY))
10 | DEP = Makefile.common Makefile $(HDR) $(EXTERNDEP) $(EXTERNSRC)
11 | BIN = $(addsuffix .out,$(TARGETS))
12 | DIS = $(addsuffix .dis,$(TARGETS))
13 |
14 | # clang:
15 | # EXTRA="-Rpass=loop-vectorize" # IDs loops that were successfully V-ed
16 | # EXTRA="-Rpass-missed=loop-vectorize" # IDs loops that failed V
17 | # EXTRA="-Rpass-analysis=loop-vectorize" # IDs the statements that caused V to fail
18 | # EXTRA="-Rpass=\ *" # remarks for all passes
19 | # other passes: https://llvm.org/docs/Passes.html
20 |
21 | O ?= rg
22 |
23 | # predefined OPT: make O={rg,r,0g,3g,p,0s,3s,cov,mc,hc,wn,stk}
24 | ifeq ($O,rg) # make O=rg
25 | OPT ?= -DNDEBUG -g3 -O3 -flto -fno-stack-protector
26 | else ifeq ($O,r) # make O=r (for release)
27 | OPT ?= -DNDEBUG -O3 -flto -fno-stack-protector
28 | else ifeq ($O,ns) # make O=ns (no signal handlers)
29 | OPT ?= -DNDEBUG -O3 -flto -fno-stack-protector -DNOSIGNAL
30 | else ifeq ($O,0g) # make O=0g
31 | OPT ?= -g3 -O0 -fno-inline
32 | else ifeq ($O,2g) # make O=2g
33 | OPT ?= -g3 -O2
34 | else ifeq ($O,3g) # make O=3g
35 | OPT ?= -g3 -O3 -flto -fno-inline
36 | else ifeq ($O,p) # make O=p (profiling: rg+noinline)
37 | OPT ?= -DNDEBUG -g3 -O3 -flto -fno-stack-protector -fno-inline
38 | else ifeq ($O,0s) # make O=0s (address sanitizer)
39 | OPT ?= -g3 -O0 -fno-inline -fsanitize=address -fno-omit-frame-pointer -DHEAPCHECKING
40 | else ifeq ($O,3s) # make O=3s (address sanitizer)
41 | OPT ?= -g3 -O3 -fno-inline -fsanitize=address -fno-omit-frame-pointer -DHEAPCHECKING
42 | else ifeq ($O,t) # make O=0t (thread sanitizer)
43 | OPT ?= -g3 -O1 -fno-inline -fsanitize=thread -fno-stack-protector
44 | else ifeq ($O,cov) # make O=cov (for gcov)
45 | OPT ?= -g3 -DNDEBUG -O0 --coverage
46 | CCC = gcc
47 | else ifeq ($O,mc) # make O=mc (for valgrind memcheck)
48 | OPT ?= -g3 -O1 -fno-inline -DHEAPCHECKING
49 | ARCH ?= broadwell
50 | else ifeq ($O,hc) # make O=hc (for gperftools heapcheck)
51 | OPT ?= -g3 -O1 -fno-inline
52 | LIB += tcmalloc
53 | else ifeq ($O,wn) # more warning
54 | OPT ?= -g3 -O3 -Wvla -Wformat=2 -Wconversion -Wstrict-prototypes -Wmissing-prototypes
55 | else ifeq ($O,stk) # check stack usage with gcc
56 | OPT ?= -g3 -O3 -DNDEBUG -fstack-usage
57 | CCC = gcc
58 | endif
59 |
60 | # malloc: g:glibc, t:tcmalloc, j:jemalloc
61 | M ?= g
62 |
63 | ifeq ($M,t)
64 | LIB += tcmalloc
65 | FLG += -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-free
66 | else ifeq ($M,j)
67 | LIB += jemalloc
68 | endif
69 |
70 | UNAME_S := $(shell uname -s)
71 | ifeq ($(UNAME_S),Linux)
72 | CHECK_S := -D__linux__
73 | LIB += rt
74 | else ifeq ($(UNAME_S),FreeBSD)
75 | CHECK_S := -D__FreeBSD__
76 | FLG += -I/usr/local/include -L/usr/local/lib
77 | LIB += rt
78 | LIB += execinfo
79 | TPUT := /usr/local/bin/tput
80 | else ifeq ($(UNAME_S),Darwin)
81 | CHECK_S := -D__APPLE__ -D__MACH__
82 | # do nothing
83 | else
84 | $(error "Supported Platforms: Linux, FreeBSD, Darwin")
85 | endif
86 | TPUT ?= tput
87 |
88 | CCC ?= clang
89 | CSTD = -std=gnu18
90 | XCC ?= clang++
91 | XSTD = -std=gnu++17
92 |
93 | UNAME_M := $(shell uname -m)
94 | ifeq ($(UNAME_M),aarch64) # "native" does not work for clang@aarch64
95 | CHECK_M := -D__aarch64__
96 | ARCH ?= armv8-a+crc
97 | else ifeq ($(UNAME_M),arm64) # "native" does not work for clang@aarch64
98 | CHECK_M := -D__aarch64__
99 | ARCH ?= armv8-a+crc
100 | else ifeq ($(UNAME_M),x86_64)
101 | CHECK_M := -D__x86_64__
102 | ARCH ?= native
103 | else ifeq ($(UNAME_M),amd64) # freebsd
104 | CHECK_M := -D__x86_64__
105 | ARCH ?= native
106 | else
107 | $(error "Supported Platforms: aarch64, x86_64")
108 | endif
109 |
110 | TUNE ?= native
111 |
112 | NBI += memcpy memmove memcmp
113 |
114 | # minimal requirement on x86_64: -march=nehalem
115 | # minimal requirement on aarch64: -march=armv8-a+crc
116 | FLG += -march=$(ARCH) -mtune=$(TUNE)
117 | FLG += -pthread -Wall -Wextra -Wshadow #-Weverything
118 | FLG += $(addprefix -fno-builtin-,$(NBI))
119 | FLG += $(OPT)
120 |
121 | ifneq ($(shell $(CCC) --version 2>/dev/null | grep clang),)
122 | FLG += -ferror-limit=3
123 | CCCTYPE := clang
124 | else ifneq ($(shell $(CCC) --version 2>/dev/null | grep gcc),)
125 | FLG += -fmax-errors=3
126 | FLG += -Wno-unknown-pragmas
127 | CCCTYPE := gcc
128 | else
129 | $(error "Supported Compilers: clang, gcc")
130 | endif
131 |
132 | ifeq ($(CCCTYPE),clang)
133 | CCINST = /usr/lib/clang/$(shell $(CCC) --version 2>/dev/null | awk '/^clang/ { print $$3 }')
134 | CCINC = $(CCINST)/include
135 | else ifeq ($(CCCTYPE),gcc)
136 | CCINST = /usr/lib/gcc/$(shell $(CCC) -dumpmachine)/$(shell $(CCC) -dumpversion)
137 | CCINC = $(CCINST)/include $(CCINST)/include-fixed
138 | endif
139 | CCINC = /usr/include /usr/local/include
140 |
141 | ifneq ($(shell find $(CCINC) -name backtrace-supported.h 2>/dev/null),)
142 | LIB += backtrace
143 | FLG += -DBACKTRACE
144 | endif
145 |
146 | ifneq ($(shell find $(CCINC) -name liburing.h 2>/dev/null),)
147 | LIB += uring
148 | FLG += -DLIBURING
149 | endif
150 |
151 |
152 | uniq = $(if $1,$(firstword $1) $(call uniq,$(filter-out $(firstword $1),$1)))
153 | magentatxt := $(shell $(TPUT) setaf 5)
154 | greentxt := $(shell $(TPUT) setaf 2)
155 | bluetxt := $(shell $(TPUT) setaf 4)
156 | normaltxt := $(shell $(TPUT) sgr0)
157 |
158 | .PHONY : bin dis def clean cleanx check tags
159 |
160 | bin : $(BIN)
161 | dis : $(DIS) bin
162 | .DEFAULT_GOAL = bin
163 | .SECONDEXPANSION:
164 |
165 | ifeq ($(J),o)
166 | # DANGER. Don't use unless it works!
167 | # build from .o files but target-specific flags are missing in %.o : %.x
168 | %.out : %.o $(OBJ) $$(addsuffix .o,$$(SRC-$$@) $$(MOD-$$@) $$(ASM-$$@))
169 | $(eval ALLFLG := $(CSTD) $(EXTRA) $(FLG) $(FLG-$*) $(FLG-$*.o) $(FLG-$@) -rdynamic)
170 | $(eval ALLLIB := $(addprefix -l,$(LIB) $(LIB-$@)))
171 | $(CCC) $(ALLFLG) -o $@ $^ $(ALLLIB)
172 | #
173 | else # default: all-in-one command
174 | %.out : %.c $(SRC) $(ASM) $(DEP) $$(DEP-$$@) $$(addsuffix .c,$$(SRC-$$@) $$(MOD-$$@)) $$(addsuffix .h,$$(HDR-$$@) $$(MOD-$$@)) $$(addsuffix .S,$$(ASM-$$@))
175 | $(eval ALLSRC := $(SRC) $(addsuffix .c,$(SRC-$@) $(MOD-$@)) $(ASM) $(addsuffix .S,$(ASM-$@)))
176 | $(eval UNIQSRC := $(call uniq,$(ALLSRC)))
177 | $(eval ALLFLG := $(CSTD) $(EXTRA) $(FLG) $(FLG-$@) -rdynamic)
178 | $(eval ALLLIB := $(addprefix -l,$(LIB) $(LIB-$@)))
179 | @printf '$(bluetxt)$@$(magentatxt) <= $(greentxt)$< $(UNIQSRC)$(normaltxt)\n'
180 | $(CCC) $(ALLFLG) -o $@ $< $(UNIQSRC) $(ALLLIB)
181 | #
182 | endif
183 |
184 |
185 | %.dis : %.out
186 | objdump -SlwtC $< 1>$@ 2>/dev/null
187 |
188 | %.o : %.cc $(DEP) $$(DEP-$$@) $$(addsuffix .h,$$(HDR-$$@) $$(MOD-$$@))
189 | $(XCC) $(XSTD) $(EXTRA) $(FLG) $(FLG-$*) $(FLG-$@) -o $@ -c $<
190 |
191 | %.o : %.c $(DEP) $$(DEP-$$@) $$(addsuffix .h,$$(HDR-$$@) $$(MOD-$$@))
192 | $(CCC) $(CSTD) $(EXTRA) $(FLG) $(FLG-$*) $(FLG-$@) -o $@ -c $<
193 |
194 | %.o : %.S $(DEP) $$(DEP-$$@) $$(addsuffix .h,$$(HDR-$$@) $$(MOD-$$@))
195 | $(CCC) $(CSTD) $(EXTRA) $(FLG) $(FLG-$*) $(FLG-$@) -o $@ -c $<
196 |
197 | %.s : %.c $(DEP) $$(DEP-$$@) $$(addsuffix .h,$$(HDR-$$@) $$(MOD-$$@))
198 | $(CCC) $(CSTD) $(EXTRA) $(FLG) $(FLG-$*) $(FLG-$*.o) -S -o $@ -c $<
199 |
200 | def :
201 | $(CCC) $(FLG) -dM -E -
2 |
3 | pkgname=remixdb
4 | pkgver=0.1
5 | pkgrel=1
6 | pkgdesc="RemixDB Embedded Key-Value Store"
7 | arch=('x86_64')
8 | url="https://github.com/wuxb45/remixdb"
9 | license=('GPL3.0')
10 | depends=('glibc' 'liburing')
11 | provides=('libremixdb.so')
12 | source=("git+https://github.com/wuxb45/remixdb")
13 | sha512sums=('SKIP')
14 | validpgpkeys=('SKIP')
15 |
16 | build() {
17 | cd "$pkgname"
18 | make O=r libremixdb.so
19 | }
20 |
21 | package() {
22 | cd "$pkgname"
23 | make PREFIX="$pkgdir" install
24 | }
25 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # REMIX and RemixDB
2 |
3 | The REMIX data structure was introduced in paper ["REMIX: Efficient Range Query for LSM-trees", FAST'21](https://www.usenix.org/conference/fast21/presentation/zhong).
4 |
5 | This repository maintains a reference implementation of the REMIX index data structure,
6 | as well as a thread-safe embedded key-value store implementation, namely RemixDB.
7 | It compiles on recent Linux/FreeBSD/MacOS and supports x86\_64 and AArch64 CPUs.
8 |
9 | This code repository is being actively maintained and contains optimizations beyong the original RemixDB implementation.
10 |
11 | # News
12 |
13 | * An experimental Python API is available in `xdb.py`. See the end of `xdb.py` for examples.
14 |
15 | * RemixDB now provides `xdb_merge` for atomic read-modify-write operations.
16 |
17 | * Two optimizations have been added to boost compaction and point query performance (see below).
18 |
19 | # Optimizations
20 |
21 | ## Optimization 1: Minimizing REMIX (Re-)Building Cost
22 |
23 | This implementation employs an optimization to minimize the REMIX building cost.
24 | This optimization improves the throughput by 2x (0.96MOPS vs. 0.50MOPS) in a random-write experiment, compared to the implementation described in the REMIX paper.
25 | Configuration: klen=16; vlen=120; 2.02 billion KVs; 256GB valid KV data; single-threaded loading in random order; no compression.
26 |
27 | When creating a new table file, RemixDB can create a copy of all the keys in the table.
28 | Specificially, it encodes all the keys (without values) in sorted order using prefix compression, which creates a *Compressed Keys Block* (*CKB*).
29 | The CKB is stored at the end of the table file.
30 | This feature can be freely turned on and off. There is no compatibility issue when tables with and without the CKB are used together.
31 |
32 | When creating a new REMIX, the building process will check if every input table contains a CKB.
33 | If true, the process will build the new REMIX using these CKBs. It also leverages the existing REMIX to avoid unncecssary key comparisons.
34 | In this way, the new REMIX will be created by reading the old REMIX and the CKBs, without accessing the key-value data blocks of the table files.
35 |
36 | In a running system the old REMIX structures are usually cache-resident.
37 | The CKBs are only used for REMIX building, which are read into memory in batch, and discarded once the building is finished.
38 |
39 | A CKB is often much smaller than the original key-value data block, unless the system manages huge keys with small values.
40 | Suppose the average CKB size is 10% of the average key-value data block size,
41 | this optimization trades 10% more write I/O and storage space usage for a 90% reduction of read I/O during REMIX building.
42 |
43 | `remixdb_open` opens/creates a remixdb with the optimization turned on. Each newly created sstable will have the CKB.
44 | You should use `remixdb_open` unless it's absolutely necessary to save a little bit disk space.
45 | `remixdb_open_compact` opens a remixdb with the optimization turned off. Each newly created sstable will not contain a CKB.
46 | A store created by one of these functions can be safely opened by the other function.
47 |
48 | ## Optimization 2: Improving Point Query with Hash Tags
49 |
50 | A point query in the original RemixDB performs binary search in a segment, which takes about five key comparisons and can cost multiple I/Os.
51 | The current implementation provides a new option, named `tags` (the last argument of `remixdb_open`).
52 |
53 | With this option enabled, every new REMIX will store an array of 8-bit hash tags. Each tag corresponds to a key managed by the REMIX.
54 | A point query (GET/PROBE) will first locate the target segment as usual.
55 | Then it will check the tags to find candidate keys for full-key matching without using binary search in the segment.
56 | With 8-bit tags and at most 32 keys in a segment, a point query takes about 1.06 key comparisons if the key is found,
57 | and about 0.12 key comparisons if the key does not exist.
58 |
59 | TODO: the tags can also be used to speed up iterator seeks with existing keys.
60 |
61 | # Limitations of the Current Implementation
62 |
63 | * *KV size*: The maximum key+value size is capped at 65500 bytes.
64 | This roughly corresponds to the 64KB block size limit.
65 | TODO: store huge KV pairs in a separate file and store the file address of the KV pair in RemixDB.
66 |
67 | # Configuration and Tuning
68 |
69 | ## CPU affinity
70 | RemixDB employs background threads to perform asynchronous compaction.
71 | When possible (on Linux or FreeBSD), these threads are pinned on specific cores for efficiency.
72 | To avoid interferences with the foreground threads, it is necessary to separate the cores used by different threads.
73 | By default, RemixDB pins 4 compaction threads on the last four cores of the current process's affinity list.
74 | For example, on a machine with two 10-core processors, cores 0,2,4,...,16,18 belong to numa node 0,
75 | and the rest cores belong to numa node 1.
76 | The default behavior is to use the cores from 16 to 19, which is a suboptimal setup.
77 | To avoid the performance penalty, one should use `numactl` to specify the cpu affinity.
78 |
79 | ```
80 | $ numactl -C 0,2,4,6,8 ./xdbdemo.out # compaction threads on 2,4,6,8
81 |
82 | $ numactl -C 0,2,4,6,8,10,12,14 ./xdbtest.out 256 256 18 18 100 # user threads on 0,2,4,6; compaction threads on 8,10,12,14
83 | ```
84 |
85 | The worker threads affinity can also be explicitly specified using `xdb_open`.
86 |
87 | ## Maximum number of open files
88 | The current implementation keeps every table file open at run time.
89 | This requires a large `nofile` in `/etc/security/limits.conf`.
90 | For example, add `* - nofile 100000` to `limits.conf`, reboot/relogin, and double-check with `ulimit -n`.
91 |
92 | ## Maximum Table File Size
93 | `MSSTZ_NBLKS` (sst.c) controls the maximum number of 4KB blocks in an SST file. The default number is 20400.
94 | The maximum value is 65520 (256MB data blocks, plus metadata).
95 |
96 | ## Hugepages
97 |
98 | Configuring huge pages can effectively improve RemixDB's performance.
99 | Usually a few hundred 2MB hugepages would be sufficient for memory allocation in MemTables.
100 | The block cache automatically detects and uses 1GB huge pages when available (otherwise, fall back to 2MB pages, and then 4KB pages).
101 | 4x 1GB huge pages should be configured if you set cache size to 4GB.
102 |
103 | # Getting Started
104 |
105 | RemixDB by default uses `liburing` (`io_uring`) and thus requires a Linux kernel >= 5.1.
106 | It also works with POSIX AIO on all the supported platforms but the performance can be negatively affected.
107 |
108 | `clang` is the default compiler. It usually produces faster code than GCC. To use GCC:
109 |
110 | $ make CCC=gcc
111 |
112 | `jemalloc` is highly recommended. If jemalloc is available and you prefer to use it, use `M=j` with `make`:
113 |
114 | $ make M=j
115 |
116 | Similarly, `tcmalloc` can be linked with `M=t`.
117 |
118 | The `xdbdemo.c` contains sample code that uses the `remixdb_*` functions.
119 | These functions present a clean programming interface without using special data types or structures.
120 |
121 | ## xdbdemo
122 | To compile and run the demo code:
123 |
124 | $ make M=j xdbdemo.out
125 | $ ./xdbdemo.out
126 |
127 | ## xdbtest
128 |
129 | `xdbtest` is a stress test program that uses the `remixdb_*` functions.
130 | It trys to use all the available cores on the affinity list, which can lead to mediocre performance.
131 | You should use numactl to specify what cores are available for the tester threads.
132 | Suppose you have eight cores (0...7) in total, the best practice is to let the testers to run on the first four cores and assign the last four cores to the compaction threads. The following examples use this configuration.
133 |
134 | Run with a 4GB block cache, 4GB MemTables, and a dataset with 32 million KVs (2^25), performing 1 million updates in each round (2^20):
135 |
136 | $ make M=j xdbtest.out
137 | $ numactl -N 0 ./xdbtest.out /tmp/xdbtest 4096 4096 25 20 100
138 |
139 | To run with smaller memory footprint (a 256MB block cache, 256MB Memtables, and 1 million KVs):
140 |
141 | $ numactl -N 0 ./xdbtest.out /tmp/xdbtest 256 256 20 20 100
142 |
143 | This setup consumes up to 850MB memory (RSS) and 1.8GB space in /tmp/xdbtest.
144 |
145 | A first run of xdbtest.out should always show stale=0.
146 | If you run it again without deleting `/tmp/xdbtest`,
147 | it will show non-zero stale numbers at the beginning but it will quickly drop and eventually reach zero.
148 |
149 | ## xdbexit
150 |
151 | `xdbexit` is a simple program testing crash-recovery.
152 | It inserts some new keys and calls `remixdb_sync()` to make all buffered data persist in the WAL.
153 | Then it immediately calls `exit()` without doing any clean-up.
154 | Run it repeatedly. In each run it should show that all the previously inserted KVs are found.
155 |
156 | Run with a small footprint:
157 |
158 | $ for i in $(seq 1 30); do ./xdbexit.out ./dbdir 256 256; done
159 |
160 | Run with in a regular-sized setup:
161 |
162 | $ for i in $(seq 1 30); do ./xdbexit.out ./dbdir 4096 4096; done
163 |
164 | ## libremixdb.so
165 |
166 | To use remixdb as a shared library, run `make libremixdb.so` and `make install`.
167 | A PKGBUILD (for Archlinux's pacman) is included as an example packaging script.
168 |
--------------------------------------------------------------------------------
/blkio.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016--2021 Wu, Xingbo
3 | *
4 | * All rights reserved. No warranty, explicit or implicit, provided.
5 | */
6 | #define _GNU_SOURCE
7 |
8 | // include {{{
9 | #include "lib.h"
10 | #include "ctypes.h"
11 | #include
12 | #include
13 | #include
14 | #include "blkio.h"
15 |
16 | // }}} include
17 |
18 | // wring {{{
19 | // wring is NOT thread-safe
20 | struct wring {
21 | void * mem;
22 | void * head;
23 | size_t memsz;
24 | u32 iosz;
25 | int fd;
26 | #if defined(LIBURING)
27 | u32 batch; // submit when pending >= batch
28 | u32 nring; // number of pending + submitted
29 | u32 pending; // number of unsubmitted sqes
30 | bool fixed_file; // use this fd for write (0 for registered file)
31 | bool fixed_mem; // use write_fixed()
32 | bool padding[2];
33 | struct io_uring uring;
34 | #else
35 | u32 off_mask;
36 | u32 off_submit;
37 | u32 off_finish; // nothing to finish if == submit
38 | u32 reserved;
39 | struct {
40 | struct aiocb aiocb;
41 | void * data;
42 | } aring[0];
43 | #endif // LIBURING
44 | };
45 |
46 | struct wring *
47 | wring_create(const int fd, const u32 iosz, const u32 depth0)
48 | {
49 | debug_assert(depth0);
50 | #if defined(LIBURING)
51 | const u32 depth = depth0 < 64 ? bits_p2_up_u32(depth0) : 64;
52 | struct wring * const wring = calloc(1, sizeof(*wring));
53 | #else // POSIX AIO
54 | const u32 depth = depth0 < 8 ? bits_p2_up_u32(depth0) : 8;
55 | struct wring * const wring = calloc(1, sizeof(*wring) + (sizeof(wring->aring[0]) * depth));
56 | #endif // LIBURING
57 | const u64 iosz_64 = iosz; // memsz can be larger
58 |
59 | if (!wring)
60 | return NULL;
61 | const size_t memsz = bits_round_up(iosz_64 * depth, 21); // a multiple of 2MB
62 | // 2MB buffer (initialized to zero by mmap)
63 | u8 * const mem = pages_alloc_best(memsz, false, &wring->memsz);
64 | if (!mem) {
65 | free(wring);
66 | return NULL;
67 | }
68 | // link all
69 | for (u64 i = 0; i < depth-1; i++)
70 | *(u64 *)(mem + (iosz_64 * i)) = (u64)(mem + (iosz_64 * (i+1)));
71 | wring->mem = mem;
72 | wring->head = mem;
73 | wring->iosz = iosz;
74 | wring->fd = fd;
75 | #if defined(LIBURING)
76 | wring->batch = depth >> 2; // 1/4
77 | struct io_uring_params p = {};
78 | // uncomment to use sqpoll (must use root or sys_admin)
79 | //p.flags = IORING_SETUP_SQPOLL | IORING_SETUP_SQ_AFF;
80 | //p.sq_thread_cpu = 2;
81 | if (io_uring_queue_init_params(depth << 1, &wring->uring, &p)) {
82 | pages_unmap(wring->mem, wring->memsz);
83 | free(wring);
84 | return NULL;
85 | }
86 |
87 | // register memory and file
88 | struct iovec vecs = {mem, wring->memsz};
89 | // enable memlock in /etc/security/limits.conf
90 | wring->fixed_mem = io_uring_register_buffers(&wring->uring, &vecs, 1) == 0;
91 | // this usually works
92 | wring->fixed_file = io_uring_register_files(&wring->uring, &fd, 1) == 0;
93 |
94 | #else
95 | wring->off_mask = depth - 1;
96 | #endif // LIBURING
97 | return wring;
98 | }
99 |
100 | void
101 | wring_update_fd(struct wring * const wring, const int fd)
102 | {
103 | wring->fd = fd;
104 | #if defined(LIBURING)
105 | if (wring->fixed_file) {
106 | const int r = io_uring_register_files_update(&wring->uring, 0, &wring->fd, 1);
107 | if (r != 1)
108 | wring->fixed_file = false;
109 | }
110 | #endif // LIBURING
111 | }
112 |
113 | void
114 | wring_destroy(struct wring * const wring)
115 | {
116 | wring_flush(wring);
117 |
118 | #if defined(LIBURING)
119 | io_uring_queue_exit(&wring->uring);
120 | #endif // LIBURING
121 |
122 | pages_unmap(wring->mem, wring->memsz);
123 | free(wring);
124 | }
125 |
126 | static void *
127 | wring_wait(struct wring * const wring)
128 | {
129 | #if defined(LIBURING)
130 | debug_assert(wring->nring);
131 | struct io_uring_cqe * cqe = NULL;
132 | // wait and directly return buffer
133 | int ret = io_uring_wait_cqe(&wring->uring, &cqe);
134 | if (ret)
135 | debug_die();
136 | if (cqe->res < 0)
137 | debug_die();
138 |
139 | void * const ptr = io_uring_cqe_get_data(cqe);
140 | io_uring_cqe_seen(&wring->uring, cqe);
141 | wring->nring--;
142 | #else // AIO
143 | debug_assert(wring->off_submit != wring->off_finish);
144 | const u32 i = wring->off_finish & wring->off_mask;
145 | struct aiocb * const cb = &(wring->aring[i].aiocb);
146 | do {
147 | const int r = aio_error(cb);
148 | if (r == 0)
149 | break;
150 | else if (r != EINPROGRESS)
151 | debug_die_perror();
152 | cpu_pause();
153 | } while (true);
154 | const ssize_t ret = aio_return(cb);
155 | if (ret != (ssize_t)cb->aio_nbytes)
156 | debug_die();
157 | void * const ptr = wring->aring[i].data;
158 | wring->off_finish++;
159 | #endif // LIBURING
160 | return ptr;
161 | }
162 |
163 | static void *
164 | wring_wait_buf(struct wring * const wring)
165 | {
166 | do {
167 | void * const buf = wring_wait(wring);
168 | if (buf)
169 | return buf;
170 | } while (true);
171 | }
172 |
173 | void *
174 | wring_acquire(struct wring * const wring)
175 | {
176 | if (wring->head == NULL)
177 | return wring_wait_buf(wring);
178 | // use the free list
179 | void * const ptr = wring->head;
180 | debug_assert(ptr);
181 | wring->head = (void *)(*(u64*)ptr);
182 | return ptr;
183 | }
184 |
185 | static void
186 | wring_finish(struct wring * const wring)
187 | {
188 | void * const ptr = wring_wait(wring);
189 | if (ptr) { // may return NULL for fsync
190 | *(u64*)ptr = (u64)(wring->head);
191 | wring->head = ptr;
192 | }
193 | }
194 |
195 | #if defined(LIBURING)
196 | static void
197 | wring_submit(struct wring * const wring)
198 | {
199 | const int n = io_uring_submit(&wring->uring);
200 | if (unlikely(n < 0))
201 | debug_die();
202 | debug_assert(n > 0 && (u32)n <= wring->pending);
203 | wring->pending -= (u32)n;
204 | }
205 | #else
206 | static void
207 | wring_wait_slot(struct wring * const wring)
208 | {
209 | // test if the ring is already full
210 | if ((wring->off_finish + wring->off_mask) == wring->off_submit)
211 | wring_finish(wring);
212 | }
213 | #endif // LIBURING
214 |
215 | // write a 4kB page
216 | void
217 | wring_write_partial(struct wring * const wring, const off_t off,
218 | void * const buf, const size_t buf_off, const u32 size)
219 | {
220 | debug_assert((buf_off + size) <= wring->iosz);
221 | u8 * const wbuf = ((u8 *)buf) + buf_off;
222 | #if defined(LIBURING)
223 | struct io_uring_sqe * const sqe = io_uring_get_sqe(&wring->uring);
224 | debug_assert(sqe);
225 |
226 | const int fd = wring->fixed_file ? 0 : wring->fd;
227 | if (wring->fixed_mem) {
228 | io_uring_prep_write_fixed(sqe, fd, wbuf, size, off, 0);
229 | } else {
230 | io_uring_prep_write(sqe, fd, wbuf, size, off);
231 | }
232 |
233 | if (wring->fixed_file)
234 | io_uring_sqe_set_flags(sqe, IOSQE_FIXED_FILE);
235 |
236 | io_uring_sqe_set_data(sqe, buf);
237 |
238 | wring->pending++;
239 | wring->nring++;
240 | if (wring->pending >= wring->batch)
241 | wring_submit(wring);
242 | #else // AIO
243 | wring_wait_slot(wring);
244 | const u32 i = wring->off_submit & wring->off_mask;
245 | struct aiocb * const cb = &wring->aring[i].aiocb;
246 | cb->aio_fildes = wring->fd;
247 | cb->aio_buf = wbuf;
248 | cb->aio_nbytes = size;
249 | cb->aio_offset = off;
250 | wring->aring[i].data = buf;
251 | const int r = aio_write(cb);
252 | if (r != 0)
253 | debug_die_perror();
254 |
255 | wring->off_submit++;
256 | #endif // LIBURING
257 | }
258 |
259 | inline void
260 | wring_write(struct wring * const wring, const off_t off, void * const buf)
261 | {
262 | wring_write_partial(wring, off, buf, 0, wring->iosz);
263 | }
264 |
265 | static bool
266 | wring_empty(struct wring * const wring)
267 | {
268 | #if defined(LIBURING)
269 | return wring->nring == 0;
270 | #else
271 | return wring->off_submit == wring->off_finish;
272 | #endif // LIBURING
273 | }
274 |
275 | void
276 | wring_flush(struct wring * const wring)
277 | {
278 | #if defined(LIBURING)
279 | while (wring->pending)
280 | wring_submit(wring);
281 | #endif // LIBURING
282 | while (!wring_empty(wring))
283 | wring_finish(wring);
284 | }
285 |
286 | void
287 | wring_fsync(struct wring * const wring)
288 | {
289 | #if defined(LIBURING)
290 | struct io_uring_sqe * const sqe = io_uring_get_sqe(&wring->uring);
291 | io_uring_prep_fsync(sqe, wring->fd, IORING_FSYNC_DATASYNC);
292 | io_uring_sqe_set_data(sqe, NULL);
293 | wring->pending++;
294 | wring->nring++;
295 | wring_submit(wring); // just submit
296 | #else
297 | wring_wait_slot(wring);
298 | const u32 i = wring->off_submit & wring->off_mask;
299 | struct aiocb * const cb = &wring->aring[i].aiocb;
300 | cb->aio_fildes = wring->fd;
301 | cb->aio_buf = NULL;
302 | cb->aio_nbytes = 0;
303 | wring->aring[i].data = NULL;
304 | #if defined(__FreeBSD__)
305 | const int flags = O_SYNC;
306 | #else
307 | const int flags = O_DSYNC;
308 | #endif
309 | const int r = aio_fsync(flags, cb);
310 | if (r != 0)
311 | debug_die_perror();
312 |
313 | wring->off_submit++;
314 | #endif // LIBURING
315 | }
316 | // }}} wring
317 |
318 | // coq {{{
319 |
320 | // struct {{{
321 | #define COQ_NR ((128u))
322 | #define COQ_MASK ((COQ_NR - 1u))
323 | #define COQ_MAX ((COQ_MASK))
324 |
325 | static_assert((COQ_NR & COQ_MASK) == 0, "COQ_NR");
326 |
327 | // the wait queue
328 | struct cowqe {
329 | cowq_func func;
330 | void * priv;
331 | };
332 |
333 | struct coht {
334 | au32 head; // consume the head
335 | au32 tail; // append to the tail
336 | };
337 |
338 | struct coq {
339 | struct coht rqht;
340 | struct coht wqht;
341 |
342 | struct co * rq[COQ_NR];
343 | struct cowqe wq[COQ_NR];
344 | #if defined(LIBURING)
345 | struct io_uring uring[0]; // optional uring at the end
346 | #endif // LIBURING
347 | };
348 | // }}} struct
349 |
350 | // helpers {{{
351 | static inline u32
352 | coht_nr(struct coht * const ht)
353 | {
354 | const u32 nr = ht->tail - ht->head;
355 | debug_assert(nr < COQ_NR);
356 | return nr;
357 | }
358 |
359 | static inline bool
360 | coht_full(struct coht * const ht)
361 | {
362 | return coht_nr(ht) == COQ_MAX;
363 | }
364 |
365 | static inline bool
366 | coht_empty(struct coht * const ht)
367 | {
368 | return coht_nr(ht) == 0;
369 | }
370 |
371 | static inline u32
372 | coht_enqueue(struct coht * const ht)
373 | {
374 | debug_assert(!coht_full(ht));
375 |
376 | const u32 i = ht->tail & COQ_MASK;
377 | ht->tail++;
378 | cpu_cfence();
379 | return i;
380 | }
381 |
382 | static inline u32
383 | coht_dequeue(struct coht * const ht)
384 | {
385 | debug_assert(!coht_empty(ht));
386 | const u32 i = ht->head & COQ_MASK;
387 | ht->head++;
388 | cpu_cfence();
389 | return i;
390 | }
391 |
392 | static inline u32
393 | corq_nr(struct coq * const q)
394 | {
395 | return coht_nr(&(q->rqht));
396 | }
397 |
398 | static inline u32
399 | cowq_nr(struct coq * const q)
400 | {
401 | return coht_nr(&(q->wqht));
402 | }
403 |
404 | static inline bool
405 | corq_full(struct coq * const q)
406 | {
407 | return coht_full(&(q->rqht));
408 | }
409 |
410 | static inline bool
411 | cowq_full(struct coq * const q)
412 | {
413 | return coht_full(&(q->wqht));
414 | }
415 |
416 | static inline bool
417 | corq_empty(struct coq * const q)
418 | {
419 | return coht_empty(&(q->rqht));
420 | }
421 |
422 | static inline bool
423 | cowq_empty(struct coq * const q)
424 | {
425 | return coht_empty(&(q->wqht));
426 | }
427 | // }}} helpers
428 |
429 | // coq {{{
430 | struct coq *
431 | coq_create(void)
432 | {
433 | struct coq * const q = calloc(1, sizeof(*q));
434 | return q;
435 | }
436 |
437 | void
438 | coq_destroy(struct coq * const coq)
439 | {
440 | free(coq);
441 | }
442 |
443 | struct coq *
444 | coq_create_auto(const u32 depth)
445 | {
446 | #if defined(LIBURING)
447 | return coq_uring_create_pair(depth);
448 | #else
449 | (void)depth;
450 | return coq_create();
451 | #endif // LIBURING
452 | }
453 |
454 | void
455 | coq_destroy_auto(struct coq * const coq)
456 | {
457 | #if defined(LIBURING)
458 | coq_uring_destroy_pair(coq);
459 | #else
460 | coq_destroy(coq);
461 | #endif // LIBURING
462 | }
463 |
464 | // return the position in the queue
465 | u32
466 | corq_enqueue(struct coq * const q, struct co * const co)
467 | {
468 | if (corq_full(q))
469 | return UINT32_MAX;
470 |
471 | const u32 i = coht_enqueue(&(q->rqht));
472 | q->rq[i] = co;
473 | return i;
474 | }
475 |
476 | // return the position in the queue
477 | // the func should do clean up for the target coroutine
478 | u32
479 | cowq_enqueue(struct coq * const q, cowq_func func, void * const priv)
480 | {
481 | if (cowq_full(q))
482 | return UINT32_MAX;
483 |
484 | const u32 i = coht_enqueue(&(q->wqht));
485 | q->wq[i].func = func;
486 | q->wq[i].priv = priv;
487 | return i;
488 | }
489 |
490 | static void
491 | corq_process(struct coq * const q)
492 | {
493 | if (corq_empty(q))
494 | return;
495 |
496 | const u32 i = coht_dequeue(&(q->rqht));
497 | struct co * const co = q->rq[i];
498 | co_enter(co, 0);
499 | if (!co_valid(co))
500 | co_destroy(co);
501 | }
502 |
503 | static void
504 | cowq_process(struct coq * const q)
505 | {
506 | do {
507 | const u32 i = coht_dequeue(&q->wqht);
508 | cowq_func func = q->wq[i].func;
509 | if (func) { // skip empty entries
510 | func(q->wq[i].priv);
511 | return;
512 | }
513 | } while (cowq_nr(q));
514 | }
515 |
516 | void
517 | cowq_remove(struct coq * const q, const u32 i)
518 | {
519 | q->wq[i].func = NULL;
520 | }
521 |
522 | // will not give control to wq workers
523 | void
524 | coq_yield(struct coq * const q)
525 | {
526 | corq_enqueue(q, co_self());
527 | co_back(0);
528 | }
529 |
530 | static bool
531 | coq_process_idle(void * const priv)
532 | {
533 | struct co * const co = (typeof(co))priv;
534 | co_enter(co, 0);
535 | if (!co_valid(co))
536 | co_destroy(co);
537 | return true;
538 | }
539 |
540 | // resume after all the wq workers have run
541 | void
542 | coq_idle(struct coq * const q)
543 | {
544 | cowq_enqueue(q, coq_process_idle, co_self());
545 | co_back(0);
546 | }
547 |
548 | void
549 | coq_run(struct coq * const q)
550 | {
551 | while (!(corq_empty(q) && cowq_empty(q))) {
552 |
553 | // flush the run-queue
554 | while (corq_nr(q))
555 | corq_process(q);
556 |
557 | // process work-completion as long as the run-queue is empty
558 | while (cowq_nr(q) && corq_empty(q))
559 | cowq_process(q);
560 | }
561 | }
562 |
563 | static __thread struct coq * coq_curr = NULL;
564 |
565 | inline void
566 | coq_install(struct coq * const q)
567 | {
568 | if (coq_curr)
569 | debug_die();
570 | coq_curr = q;
571 | }
572 |
573 | inline void
574 | coq_uninstall(void)
575 | {
576 | if (coq_curr == NULL)
577 | debug_die();
578 | coq_curr = NULL;
579 | }
580 |
581 | inline struct coq *
582 | coq_current(void)
583 | {
584 | return coq_curr;
585 | }
586 | // }}} coq
587 |
588 | // aio {{{
589 | static bool
590 | cowq_process_aio(void * const priv)
591 | {
592 | struct co * const co = (typeof(co))priv;
593 | debug_assert(co);
594 | co_enter(co, 0);
595 | if (!co_valid(co))
596 | co_destroy(co);
597 | return true;
598 | }
599 |
600 | static ssize_t
601 | coq_wait_aio(struct coq * const q, struct aiocb * const cb, struct co * const self)
602 | {
603 | do {
604 | cowq_enqueue(q, cowq_process_aio, (void *)self);
605 | co_back(0);
606 | const int r = aio_error(cb);
607 | if (r != EINPROGRESS)
608 | return aio_return(cb);
609 | } while (true);
610 | }
611 |
612 | ssize_t
613 | coq_pread_aio(struct coq * const q, const int fd, void * const buf, const size_t count, const off_t offset)
614 | {
615 | struct co * const self = co_self();
616 | if (!self)
617 | return pread(fd, buf, count, offset);
618 |
619 | struct aiocb cb = { .aio_fildes = fd, .aio_buf = buf, .aio_nbytes = count, .aio_offset = offset};
620 | const int r = aio_read(&cb);
621 | if (unlikely(r))
622 | return -1;
623 |
624 | return coq_wait_aio(q, &cb, self);
625 | }
626 |
627 | ssize_t
628 | coq_pwrite_aio(struct coq * const q, const int fd, const void * const buf, const size_t count, const off_t offset)
629 | {
630 | struct co * const self = co_self();
631 | if (!self)
632 | return pwrite(fd, buf, count, offset);
633 |
634 | struct aiocb cb = { .aio_fildes = fd, .aio_buf = (void *)buf, .aio_nbytes = count, .aio_offset = offset};
635 | const int r = aio_write(&cb);
636 | if (unlikely(r))
637 | return -1;
638 |
639 | return coq_wait_aio(q, &cb, self);
640 | }
641 | // }}} aio
642 |
643 | // io_uring {{{
644 | #if defined(LIBURING)
645 | static inline bool
646 | coq_uring_init(struct io_uring * const ring, const u32 depth)
647 | {
648 | struct io_uring_params p = {};
649 | return 0 == io_uring_queue_init_params(depth, ring, &p);
650 | }
651 |
652 | struct io_uring *
653 | coq_uring_create(const u32 depth)
654 | {
655 | struct io_uring * const ring = malloc(sizeof(*ring));
656 | if (coq_uring_init(ring, depth)) {
657 | return ring;
658 | } else {
659 | free(ring);
660 | return NULL;
661 | }
662 | }
663 |
664 | // returns a coq plus a uring at the end
665 | struct coq *
666 | coq_uring_create_pair(const u32 depth)
667 | {
668 | struct coq * const coq = calloc(1, sizeof(struct coq) + sizeof(struct io_uring));
669 | if (coq_uring_init(coq->uring, depth)) {
670 | return coq;
671 | } else {
672 | free(coq);
673 | return NULL;
674 | }
675 | }
676 |
677 | void
678 | coq_uring_destroy(struct io_uring * const ring)
679 | {
680 | io_uring_queue_exit(ring);
681 | free(ring);
682 | }
683 |
684 | void
685 | coq_uring_destroy_pair(struct coq * const coq)
686 | {
687 | io_uring_queue_exit(coq->uring);
688 | coq_destroy(coq);
689 | }
690 |
691 | static bool
692 | cowq_process_uring(void * const priv)
693 | {
694 | struct io_uring * const ring = (typeof(ring))priv;
695 | struct io_uring_cqe * cqe = NULL;
696 | int ret = io_uring_wait_cqe(ring, &cqe);
697 |
698 | if (ret)
699 | return false;
700 |
701 | struct co * const co = (typeof(co))io_uring_cqe_get_data(cqe);
702 | debug_assert(co);
703 | co_enter(co, (u64)cqe);
704 | if (!co_valid(co))
705 | co_destroy(co);
706 | return true;
707 | }
708 |
709 | ssize_t
710 | coq_pread_uring(struct coq * const q, struct io_uring * const ring0,
711 | const int fd, void * const buf, const size_t count, const off_t offset)
712 | {
713 | struct co * const self = co_self();
714 | if (!self)
715 | return pread(fd, buf, count, offset);
716 |
717 | struct io_uring * const ring = ring0 ? ring0 : q->uring;
718 | struct io_uring_sqe * const sqe = io_uring_get_sqe(ring);
719 | if (sqe == NULL)
720 | return -1;
721 |
722 | struct iovec vec = {.iov_base = buf, .iov_len = count};
723 | io_uring_prep_readv(sqe, fd, &vec, 1, offset);
724 | io_uring_sqe_set_data(sqe, self);
725 | io_uring_submit(ring);
726 |
727 | // prepare callback
728 | cowq_enqueue(q, cowq_process_uring, (void *)ring);
729 |
730 | // yield
731 | struct io_uring_cqe * const cqe = (typeof(cqe))co_back(0);
732 | debug_assert(cqe);
733 | const ssize_t ret = cqe->res;
734 | io_uring_cqe_seen(ring, cqe);
735 | return ret;
736 | }
737 |
738 | ssize_t
739 | coq_pwrite_uring(struct coq * const q, struct io_uring * const ring0,
740 | const int fd, const void * const buf, const size_t count, const off_t offset)
741 | {
742 | struct co * const self = co_self();
743 | if (!self)
744 | return pwrite(fd, buf, count, offset);
745 |
746 | struct io_uring * const ring = ring0 ? ring0 : q->uring;
747 | struct io_uring_sqe * const sqe = io_uring_get_sqe(ring);
748 | if (sqe == NULL)
749 | return -1;
750 |
751 | struct iovec vec = {.iov_base = (void *)buf, .iov_len = count};
752 | io_uring_prep_writev(sqe, fd, &vec, 1, offset);
753 | io_uring_sqe_set_data(sqe, self);
754 | io_uring_submit(ring);
755 |
756 | // prepare callback
757 | cowq_enqueue(q, cowq_process_uring, (void *)ring);
758 |
759 | // yield
760 | struct io_uring_cqe * const cqe = (typeof(cqe))co_back(0);
761 | debug_assert(cqe);
762 | const ssize_t ret = cqe->res;
763 | io_uring_cqe_seen(ring, cqe);
764 | return ret;
765 | }
766 | #endif // LIBURING
767 | // }}} io_uring
768 |
769 | // }}} coq
770 |
771 | // rcache {{{
772 | // read-only cache
773 | #define RCACHE_NWAY ((16u))
774 | #define RCACHE_VSHIFT128 ((2))
775 | #define RCACHE_VSHIFT256 ((3))
776 | #define RCACHE_VSHIFT512 ((4))
777 | #define RCACHE_VWAY128 ((RCACHE_NWAY >> RCACHE_VSHIFT128))
778 | #define RCACHE_VWAY256 ((RCACHE_NWAY >> RCACHE_VSHIFT256))
779 | #define RCACHE_VWAY512 ((RCACHE_NWAY >> RCACHE_VSHIFT512))
780 | #define RCACHE_MASK ((RCACHE_NWAY - 1))
781 | #define RCACHE_MAXHIST ((UINT8_MAX - 1))
782 | struct rcache_group {
783 | u8 hist[RCACHE_NWAY]; // 1x16=16B
784 | spinlock lock; // 4B
785 | au32 valid_bits; // 4B
786 | au32 write_bits; // 4B
787 | au32 dirty_bits; // 4B
788 | au16 refcnt[RCACHE_NWAY]; // 2x16=32B
789 | union {
790 | u32 tag[RCACHE_NWAY]; // 4x16=64B: high x-bit is fd; low y-bit is page-number (256MB max)
791 | m128 tagv128[RCACHE_VWAY128];
792 | #if defined(__AVX2__)
793 | m256 tagv256[RCACHE_VWAY256];
794 | #endif
795 | #if defined(__AVX512F__)
796 | m512 tagv512[RCACHE_VWAY512];
797 | #endif
798 | };
799 | };
800 |
801 | static_assert((sizeof(struct rcache_group) % 64) == 0, "rcache_group size");
802 |
803 | struct rcache {
804 | u8 * mem;
805 | struct rcache_group * groups;
806 | u32 group_mask;
807 | u32 nr_groups;
808 | u32 fd_shift;
809 | u32 pno_mask;
810 | u64 memsize;
811 | u64 gmemsize;
812 | struct bitmap * close_bm;
813 | };
814 |
815 | struct rcache *
816 | rcache_create(const u64 size_mb, const u32 fd_bits)
817 | {
818 | debug_assert(size_mb && fd_bits);
819 | const u64 cachesz = bits_p2_up_u64(size_mb) << 20;
820 | const u64 npages = cachesz / PGSZ;
821 | const u64 ngroups = npages / (u64)RCACHE_NWAY;
822 | if (ngroups > UINT32_MAX)
823 | return NULL;
824 | struct rcache * const c = calloc(1, sizeof(*c));
825 | if (!c)
826 | return NULL;
827 | c->mem = pages_alloc_best(cachesz, true, &c->memsize); // can use 1GB huge page
828 | if (!c->mem) {
829 | free(c);
830 | return NULL;
831 | }
832 | c->groups = pages_alloc_best(ngroups * sizeof(struct rcache_group), false, &c->gmemsize);
833 | if (!c->groups) {
834 | pages_unmap(c->mem, c->memsize);
835 | free(c);
836 | return NULL;
837 | }
838 | c->group_mask = (u32)ngroups - 1;
839 | c->nr_groups = (u32)ngroups;
840 |
841 | c->fd_shift = 32 - fd_bits;
842 | c->pno_mask = (1u << c->fd_shift) - 1u;
843 |
844 | c->close_bm = bitmap_create(1lu << fd_bits);
845 | debug_assert(c->close_bm);
846 |
847 | for (u64 i = 0; i < ngroups; i++)
848 | spinlock_init(&(c->groups[i].lock));
849 |
850 | return c;
851 | }
852 |
853 | void
854 | rcache_destroy(struct rcache * const c)
855 | {
856 | free(c->close_bm);
857 | pages_unmap(c->mem, c->memsize);
858 | pages_unmap(c->groups, c->gmemsize);
859 | free(c);
860 | }
861 |
862 | static inline void
863 | rcache_read(int fd, void *pg, u32 pno)
864 | {
865 | struct coq * const coq = coq_current();
866 | if (coq) {
867 | #if defined(LIBURING)
868 | if (coq_pread_uring(coq, NULL, fd, pg, PGSZ, PGSZ * pno) != PGSZ)
869 | debug_die();
870 | #else
871 | if (coq_pread_aio(coq, fd, pg, PGSZ, PGSZ * pno) != PGSZ)
872 | debug_die();
873 | #endif // LIBURING
874 | } else { // regular pread
875 | if (pread(fd, pg, PGSZ, PGSZ * pno) != PGSZ)
876 | debug_die();
877 | }
878 | }
879 |
880 | static inline int
881 | rcache_tag_to_fd(struct rcache * const c, const u32 tag)
882 | {
883 | return (int)(tag >> c->fd_shift);
884 | }
885 |
886 | static inline u32
887 | rcache_tag(struct rcache * const c, const int fd, const u32 pno)
888 | {
889 | debug_assert(fd > 0); // please don't use stdin
890 | debug_assert((u32)__builtin_clz((u32)fd) >= c->fd_shift);
891 | debug_assert(pno <= c->pno_mask);
892 |
893 | const u32 tag = (((u32)fd) << c->fd_shift) | pno;
894 | return tag;
895 | }
896 |
897 | static inline u32
898 | rcache_hash(const u32 tag)
899 | {
900 | return crc32c_u32(0x0D15EA5Eu, tag);
901 | }
902 |
903 | static inline u8 *
904 | rcache_page(struct rcache * const c, const u32 gid, const u32 i)
905 | {
906 | return c->mem + (PGSZ * (gid * RCACHE_NWAY + i));
907 | }
908 |
909 | // thread-unsafe
910 | void
911 | rcache_close_lazy(struct rcache * const c, const int fd)
912 | {
913 | debug_assert(bitmap_test(c->close_bm, (u64)fd) == false);
914 | bitmap_set1(c->close_bm, (u64)fd);
915 | }
916 |
917 | // thread-unsafe
918 | u64
919 | rcache_close_flush(struct rcache * const c)
920 | {
921 | struct bitmap * const bm = c->close_bm;
922 | const u64 count = bitmap_count(bm);
923 | if (count == 0)
924 | return 0;
925 |
926 | for (u32 i = 0; i < c->nr_groups; i++) {
927 | struct rcache_group * const g = &(c->groups[i]);
928 | spinlock_lock(&(g->lock));
929 | for (u32 j = 0; j < RCACHE_NWAY; j++) {
930 | const int fd = rcache_tag_to_fd(c, g->tag[j]);
931 | if (bitmap_test(bm, (u64)fd)) {
932 | g->tag[j] = 0;
933 | g->hist[j] = 0;
934 | debug_assert(g->refcnt[j] == 0);
935 | }
936 | }
937 | spinlock_unlock(&(g->lock));
938 | }
939 | while (bitmap_count(bm)) {
940 | const u64 bit = bitmap_first(bm);
941 | close((int)bit);
942 | bitmap_set0(bm, bit);
943 | }
944 | return count;
945 | }
946 |
947 | // invalidate cache and close(fd)
948 | void
949 | rcache_close(struct rcache * const c, const int fd)
950 | {
951 | for (u32 i = 0; i < c->nr_groups; i++) {
952 | struct rcache_group * const g = &(c->groups[i]);
953 | spinlock_lock(&(g->lock));
954 | for (u32 j = 0; j < RCACHE_NWAY; j++) {
955 | if (rcache_tag_to_fd(c, g->tag[j]) == fd) {
956 | g->tag[j] = 0;
957 | g->hist[j] = 0;
958 | debug_assert(g->refcnt[j] == 0);
959 | }
960 | }
961 | spinlock_unlock(&(g->lock));
962 | }
963 | close(fd);
964 | }
965 |
966 | static inline void
967 | rcache_pause(void)
968 | {
969 | struct coq * const coq = coq_current();
970 | if (coq)
971 | coq_idle(coq);
972 | else
973 | cpu_pause();
974 | }
975 |
976 | // lock has been acquired
977 | // read-only; return a page that has zero reference
978 | static u32
979 | rcache_search_victim(struct rcache_group * const g, const u32 i0)
980 | {
981 | // search unused page
982 | #pragma nounroll
983 | do {
984 | u32 imin = i0;
985 | u16 cmin = UINT16_MAX;
986 | u8 hmin = UINT8_MAX;
987 | #pragma nounroll
988 | for (u32 k = 0; k < RCACHE_NWAY; k++) {
989 | const u32 i = (k + i0) & RCACHE_MASK;
990 | if (g->hist[i] < hmin && atomic_load_explicit(&(g->refcnt[i]), MO_CONSUME) == 0) {
991 | // refcnt is 0 but we may still have a better choice
992 | imin = i;
993 | cmin = 0;
994 | hmin = g->hist[i];
995 | }
996 | }
997 | if (cmin == 0) // found a victim
998 | return imin;
999 |
1000 | rcache_pause();
1001 | } while (true);
1002 | }
1003 |
1004 | static void *
1005 | rcache_hit_i(struct rcache * const c, const u32 gid, struct rcache_group * const g, const u32 i)
1006 | {
1007 | const u8 hist0 = g->hist[i];
1008 | if (hist0 < RCACHE_MAXHIST)
1009 | g->hist[i] = hist0 + 1;
1010 | atomic_fetch_add_explicit(&(g->refcnt[i]), 1, MO_ACQUIRE);
1011 | spinlock_unlock(&(g->lock));
1012 | // wait if invalid
1013 | const u32 vbit = 1u << i;
1014 | while ((atomic_load_explicit(&(g->valid_bits), MO_CONSUME) & vbit) == 0)
1015 | rcache_pause();
1016 | return rcache_page(c, gid, i);
1017 | }
1018 |
1019 | static void *
1020 | rcache_hit(struct rcache * const c, const u32 tag, const u32 gid, struct rcache_group * const g)
1021 | {
1022 | #if defined(__x86_64__)
1023 | #if defined(__AVX512F__)
1024 | const m512 tmpv = _mm512_set1_epi32((s32)tag);
1025 | for (u32 v = 0; v < RCACHE_VWAY512; v++) {
1026 | const u32 m = (u32)_mm512_cmpeq_epu32_mask(tmpv, g->tagv512[v]);
1027 | if (m) {
1028 | const u32 i = (v << RCACHE_VSHIFT512) + ((u32)__builtin_ctz(m));
1029 | return rcache_hit_i(c, gid, g, i);
1030 | }
1031 | }
1032 | #elif defined(__AVX2__)
1033 | const m256 tmpv = _mm256_set1_epi32((s32)tag);
1034 | for (u32 v = 0; v < RCACHE_VWAY256; v++) {
1035 | const u32 m = (u32)_mm256_movemask_epi8(_mm256_cmpeq_epi32(tmpv, g->tagv256[v]));
1036 | if (m) {
1037 | const u32 i = (v << RCACHE_VSHIFT256) + ((u32)__builtin_ctz(m) >> 2);
1038 | return rcache_hit_i(c, gid, g, i);
1039 | }
1040 | }
1041 | #else // SSE4.2
1042 | const m128 tmpv = _mm_set1_epi32((s32)tag);
1043 | for (u32 v = 0; v < RCACHE_VWAY128; v++) {
1044 | const u32 m = (u32)_mm_movemask_epi8(_mm_cmpeq_epi32(tmpv, g->tagv128[v]));
1045 | if (m) {
1046 | const u32 i = (v << RCACHE_VSHIFT128) + ((u32)__builtin_ctz(m) >> 2);
1047 | return rcache_hit_i(c, gid, g, i);
1048 | }
1049 | }
1050 | #endif // __AVX512F__
1051 | #else // TODO: AArch64 SIMD
1052 | const u32 i0 = tag & RCACHE_MASK;
1053 | for (u32 k = 0; k < RCACHE_NWAY; k++) {
1054 | const u32 i = (k + i0) & RCACHE_MASK;
1055 | if (g->tag[i] == tag) // hit
1056 | return rcache_hit_i(c, gid, g, i);
1057 | }
1058 | #endif // __x86_64__
1059 | // still locked
1060 | return NULL;
1061 | }
1062 |
1063 | static __thread u64 rcache_stat_reads = 0;
1064 | void *
1065 | rcache_acquire(struct rcache * const c, const int fd, const u32 pno)
1066 | {
1067 | const u32 tag = rcache_tag(c, fd, pno);
1068 | const u32 gid = rcache_hash(tag) & c->group_mask;
1069 | struct rcache_group * const g = &(c->groups[gid]);
1070 |
1071 | spinlock_lock(&(g->lock));
1072 | void * const ret1 = rcache_hit(c, tag, gid, g);
1073 | if (ret1)
1074 | return ret1;
1075 |
1076 | const u32 iv = rcache_search_victim(g, tag & RCACHE_MASK);
1077 | debug_assert(g->refcnt[iv] == 0);
1078 |
1079 | void * const pg = rcache_page(c, gid, iv);
1080 | atomic_store_explicit(&(g->refcnt[iv]), 1, MO_RELAXED);
1081 | g->tag[iv] = tag;
1082 | g->hist[iv] = 0;
1083 | const u32 vbit = 1u << iv;
1084 | atomic_fetch_and_explicit(&(g->valid_bits), ~vbit, MO_ACQUIRE); // clear bit
1085 | spinlock_unlock(&(g->lock));
1086 | // perform I/O after releasing the lock
1087 | rcache_read(fd, pg, pno); // must succeed
1088 | rcache_stat_reads++;
1089 | atomic_fetch_or_explicit(&(g->valid_bits), vbit, MO_RELEASE); // clear bit
1090 | return pg;
1091 | }
1092 |
1093 | void
1094 | rcache_retain(struct rcache * const c, const void * const buf)
1095 | {
1096 | const u64 tmp = (((u64)buf) - ((u64)c->mem)) / PGSZ;
1097 | const u32 gid = (u32)(tmp / RCACHE_NWAY);
1098 | const u32 i = tmp & RCACHE_MASK;
1099 |
1100 | struct rcache_group * const g = &(c->groups[gid]);
1101 | debug_assert(g->refcnt[i]);
1102 | atomic_fetch_add_explicit(&(g->refcnt[i]), 1, MO_ACQUIRE);
1103 | }
1104 |
1105 | void
1106 | rcache_release(struct rcache * const c, const void * const buf)
1107 | {
1108 | const u64 tmp = (((u64)buf) - ((u64)c->mem)) / PGSZ;
1109 | const u32 gid = (u32)(tmp / RCACHE_NWAY);
1110 | const u32 i = tmp & RCACHE_MASK;
1111 |
1112 | struct rcache_group * const g = &(c->groups[gid]);
1113 | debug_assert(g->refcnt[i]);
1114 | atomic_fetch_sub_explicit(&(g->refcnt[i]), 1, MO_RELEASE);
1115 | }
1116 |
1117 | inline void
1118 | rcache_thread_stat_reset(void)
1119 | {
1120 | rcache_stat_reads = 0;
1121 | }
1122 |
1123 | inline u64
1124 | rcache_thread_stat_reads(void)
1125 | {
1126 | return rcache_stat_reads;
1127 | }
1128 | // }}} rcache
1129 |
1130 | // vim:fdm=marker
1131 |
--------------------------------------------------------------------------------
/blkio.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016--2021 Wu, Xingbo
3 | *
4 | * All rights reserved. No warranty, explicit or implicit, provided.
5 | */
6 | #pragma once
7 |
8 | #include "lib.h"
9 | #if defined(LIBURING)
10 | #include
11 | #endif // LIBURING
12 |
13 | #ifdef __cplusplus
14 | extern "C" {
15 | #endif
16 |
17 | // wring {{{
18 | struct wring;
19 |
20 | // iosz: fixed write size; must be a multiple of PGSZ
21 | extern struct wring *
22 | wring_create(const int fd, const u32 iosz, const u32 depth);
23 |
24 | extern void
25 | wring_update_fd(struct wring * const wring, const int fd);
26 |
27 | extern void
28 | wring_destroy(struct wring * const wring);
29 |
30 | extern void *
31 | wring_acquire(struct wring * const wring);
32 |
33 | // write part of the buf
34 | extern void
35 | wring_write_partial(struct wring * const wring, const off_t off,
36 | void * const buf, const size_t buf_off, const u32 size);
37 |
38 | extern void
39 | wring_write(struct wring * const wring, const off_t off, void * const buf);
40 |
41 | // flush the queue and wait for completion
42 | extern void
43 | wring_flush(struct wring * const wring);
44 |
45 | // send an fsync but does not wait for completion
46 | extern void
47 | wring_fsync(struct wring * const wring);
48 | // }}} wring
49 |
50 | // coq {{{
51 |
52 | struct coq;
53 | typedef bool (*cowq_func) (void * priv);
54 |
55 | extern struct coq *
56 | coq_create(void);
57 |
58 | extern void
59 | coq_destroy(struct coq * const coq);
60 |
61 | // prefer io_uring on Linux; fall back to POSIX AIO
62 | extern struct coq *
63 | coq_create_auto(const u32 depth);
64 |
65 | extern void
66 | coq_destroy_auto(struct coq * const coq);
67 |
68 | extern u32
69 | corq_enqueue(struct coq * const q, struct co * const co);
70 |
71 | extern u32
72 | cowq_enqueue(struct coq * const q, cowq_func exec, void * const priv);
73 |
74 | extern void
75 | cowq_remove(struct coq * const q, const u32 i);
76 |
77 | extern void
78 | coq_yield(struct coq * const q);
79 |
80 | extern void
81 | coq_idle(struct coq * const q);
82 |
83 | extern void
84 | coq_run(struct coq * const q);
85 |
86 | extern void
87 | coq_install(struct coq * const q);
88 |
89 | extern void
90 | coq_uninstall(void);
91 |
92 | extern struct coq *
93 | coq_current(void);
94 |
95 | extern ssize_t
96 | coq_pread_aio(struct coq * const q, const int fd, void * const buf, const size_t count, const off_t offset);
97 |
98 | extern ssize_t
99 | coq_pwrite_aio(struct coq * const q, const int fd, const void * const buf, const size_t count, const off_t offset);
100 |
101 | #if defined(LIBURING)
102 | // io_uring-specific
103 | extern struct io_uring *
104 | coq_uring_create(const u32 depth);
105 |
106 | // use ring==NULL in pread_uring and pwrite_uring
107 | extern struct coq *
108 | coq_uring_create_pair(const u32 depth);
109 |
110 | extern void
111 | coq_uring_destroy(struct io_uring * const ring);
112 |
113 | extern void
114 | coq_uring_destroy_pair(struct coq * const coq);
115 |
116 | extern ssize_t
117 | coq_pread_uring(struct coq * const q, struct io_uring * const ring,
118 | const int fd, void * const buf, const size_t count, const off_t offset);
119 |
120 | extern ssize_t
121 | coq_pwrite_uring(struct coq * const q, struct io_uring * const ring,
122 | const int fd, const void * const buf, const size_t count, const off_t offset);
123 | #endif // LIBURING
124 | // }}} coq
125 |
126 | // rcache {{{
127 | extern struct rcache *
128 | rcache_create(const u64 size_mb, const u32 fd_bits);
129 |
130 | extern void
131 | rcache_destroy(struct rcache * const c);
132 |
133 | extern void
134 | rcache_close_lazy(struct rcache * const c, const int fd);
135 |
136 | extern u64
137 | rcache_close_flush(struct rcache * const c);
138 |
139 | extern void
140 | rcache_close(struct rcache * const c, const int fd);
141 |
142 | extern void *
143 | rcache_acquire(struct rcache * const c, const int fd, const u32 pageid);
144 |
145 | extern void
146 | rcache_retain(struct rcache * const c, const void * const buf);
147 |
148 | extern void
149 | rcache_release(struct rcache * const c, const void * const buf);
150 |
151 | extern void
152 | rcache_thread_stat_reset(void);
153 |
154 | extern u64
155 | rcache_thread_stat_reads(void);
156 | // }}} rcache
157 |
158 | #ifdef __cplusplus
159 | }
160 | #endif
161 | // vim:fdm=marker
162 |
--------------------------------------------------------------------------------
/ctypes.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016--2021 Wu, Xingbo
3 | *
4 | * All rights reserved. No warranty, explicit or implicit, provided.
5 | */
6 | #pragma once
7 |
8 | // C types only; C++ source code don't use this
9 |
10 | #include
11 | #include
12 |
13 | /* C11 atomic types */
14 | typedef atomic_bool abool;
15 |
16 | typedef atomic_uchar au8;
17 | typedef atomic_ushort au16;
18 | typedef atomic_uint au32;
19 | typedef atomic_ulong au64;
20 | static_assert(sizeof(au8) == 1, "sizeof(au8)");
21 | static_assert(sizeof(au16) == 2, "sizeof(au16)");
22 | static_assert(sizeof(au32) == 4, "sizeof(au32)");
23 | static_assert(sizeof(au64) == 8, "sizeof(au64)");
24 |
25 | typedef atomic_char as8;
26 | typedef atomic_short as16;
27 | typedef atomic_int as32;
28 | typedef atomic_long as64;
29 | static_assert(sizeof(as8) == 1, "sizeof(as8)");
30 | static_assert(sizeof(as16) == 2, "sizeof(as16)");
31 | static_assert(sizeof(as32) == 4, "sizeof(as32)");
32 | static_assert(sizeof(as64) == 8, "sizeof(as64)");
33 |
34 | // shorten long names
35 | #define MO_RELAXED memory_order_relaxed
36 | #define MO_CONSUME memory_order_consume
37 | #define MO_ACQUIRE memory_order_acquire
38 | #define MO_RELEASE memory_order_release
39 | #define MO_ACQ_REL memory_order_acq_rel
40 | #define MO_SEQ_CST memory_order_seq_cst
41 |
--------------------------------------------------------------------------------
/kv.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016--2021 Wu, Xingbo
3 | *
4 | * All rights reserved. No warranty, explicit or implicit, provided.
5 | */
6 | #pragma once
7 |
8 | #ifdef __cplusplus
9 | extern "C" {
10 | #endif
11 |
12 | // crc32c {{{
13 | #define KV_CRC32C_SEED ((0xDEADBEEFu))
14 |
15 | extern u32
16 | kv_crc32c(const void * const ptr, u32 len);
17 |
18 | extern u64
19 | kv_crc32c_extend(const u32 crc32c);
20 | // }}} crc32c
21 |
22 | // kv {{{
23 |
24 | // struct {{{
25 | /*
26 | * Some internal union names can be ignored:
27 | * struct kv {
28 | * u32 klen;
29 | * u32 vlen;
30 | * u64 hash;
31 | * u8 kv[];
32 | * };
33 | */
34 | struct kv {
35 | union { // the first u64
36 | u64 kvlen;
37 | struct {
38 | u32 klen;
39 | union { u32 vlen; u32 refcnt; };
40 | };
41 | };
42 | union {
43 | u64 hash; // hashvalue of the key
44 | u64 priv; // can hide a value here if hash is not used
45 | void * privptr;
46 | struct { u32 hashlo; u32 hashhi; }; // little endian
47 | struct { u32 privlo; u32 privhi; };
48 | };
49 | u8 kv[0]; // len(kv) == klen + vlen
50 | } __attribute__((packed));
51 |
52 | struct kref {
53 | u32 len;
54 | union { u32 hash32; u32 priv; };
55 | const u8 * ptr;
56 | } __attribute__((packed));
57 |
58 | struct kvref {
59 | const u8 * kptr; // read-only
60 | const u8 * vptr; // read-only
61 | struct kv hdr; // hdr.kv[] is invalid
62 | };
63 | // }}} struct
64 |
65 | // kv {{{
66 | typedef int (*kv_kv_cmp_func)(const struct kv *, const struct kv *);
67 |
68 | extern size_t
69 | kv_size(const struct kv * const kv);
70 |
71 | extern size_t
72 | kv_size_align(const struct kv * const kv, const u64 align);
73 |
74 | extern size_t
75 | key_size(const struct kv * const key);
76 |
77 | extern size_t
78 | key_size_align(const struct kv * const key, const u64 align);
79 |
80 | extern void
81 | kv_update_hash(struct kv * const kv);
82 |
83 | extern void
84 | kv_refill_value(struct kv * const kv, const void * const value, const u32 vlen);
85 |
86 | extern void
87 | kv_refill(struct kv * const kv, const void * const key, const u32 klen,
88 | const void * const value, const u32 vlen);
89 |
90 | extern void
91 | kv_refill_str(struct kv * const kv, const char * const key,
92 | const void * const value, const u32 vlen);
93 |
94 | extern void
95 | kv_refill_str_str(struct kv * const kv, const char * const key,
96 | const char * const value);
97 |
98 | // the u64 key is filled in big-endian byte order
99 | extern void
100 | kv_refill_u64(struct kv * const kv, const u64 key, const void * const value, const u32 vlen);
101 |
102 | extern void
103 | kv_refill_hex32(struct kv * const kv, const u32 hex, const void * const value, const u32 vlen);
104 |
105 | extern void
106 | kv_refill_hex64(struct kv * const kv, const u64 hex, const void * const value, const u32 vlen);
107 |
108 | extern void
109 | kv_refill_hex64_klen(struct kv * const kv, const u64 hex, const u32 klen,
110 | const void * const value, const u32 vlen);
111 |
112 | extern void
113 | kv_refill_kref(struct kv * const kv, const struct kref * const kref);
114 |
115 | extern void
116 | kv_refill_kref_v(struct kv * const kv, const struct kref * const kref,
117 | const void * const value, const u32 vlen);
118 |
119 | extern struct kref
120 | kv_kref(const struct kv * const key);
121 |
122 | extern struct kv *
123 | kv_create(const void * const key, const u32 klen, const void * const value, const u32 vlen);
124 |
125 | extern struct kv *
126 | kv_create_str(const char * const key, const void * const value, const u32 vlen);
127 |
128 | extern struct kv *
129 | kv_create_str_str(const char * const key, const char * const value);
130 |
131 | extern struct kv *
132 | kv_create_kref(const struct kref * const kref, const void * const value, const u32 vlen);
133 |
134 | // a static kv with klen == 0
135 | extern const struct kv *
136 | kv_null(void);
137 |
138 | extern struct kv *
139 | kv_dup(const struct kv * const kv);
140 |
141 | extern struct kv *
142 | kv_dup_key(const struct kv * const kv);
143 |
144 | extern struct kv *
145 | kv_dup2(const struct kv * const from, struct kv * const to);
146 |
147 | extern struct kv *
148 | kv_dup2_key(const struct kv * const from, struct kv * const to);
149 |
150 | extern struct kv *
151 | kv_dup2_key_prefix(const struct kv * const from, struct kv * const to, const u32 plen);
152 |
153 | extern bool
154 | kv_match(const struct kv * const key1, const struct kv * const key2);
155 |
156 | extern bool
157 | kv_match_hash(const struct kv * const key1, const struct kv * const key2);
158 |
159 | extern bool
160 | kv_match_full(const struct kv * const kv1, const struct kv * const kv2);
161 |
162 | extern bool
163 | kv_match_kv128(const struct kv * const sk, const u8 * const kv128);
164 |
165 | extern int
166 | kv_compare(const struct kv * const kv1, const struct kv * const kv2);
167 |
168 | extern int
169 | kv_k128_compare(const struct kv * const sk, const u8 * const k128);
170 |
171 | extern int
172 | kv_kv128_compare(const struct kv * const sk, const u8 * const kv128);
173 |
174 | extern void
175 | kv_qsort(struct kv ** const kvs, const size_t nr);
176 |
177 | extern u32
178 | kv_key_lcp(const struct kv * const key1, const struct kv * const key2);
179 |
180 | extern u32
181 | kv_key_lcp_skip(const struct kv * const key1, const struct kv * const key2, const u32 lcp0);
182 |
183 | extern void
184 | kv_psort(struct kv ** const kvs, const u64 nr, const u64 tlo, const u64 thi);
185 |
186 | extern void *
187 | kv_vptr(struct kv * const kv);
188 |
189 | extern void *
190 | kv_kptr(struct kv * const kv);
191 |
192 | extern const void *
193 | kv_vptr_c(const struct kv * const kv);
194 |
195 | extern const void *
196 | kv_kptr_c(const struct kv * const kv);
197 |
198 | extern void
199 | kv_print(const struct kv * const kv, const char * const cmd, FILE * const out);
200 | // }}} kv
201 |
202 | // mm {{{
203 | typedef struct kv * (* kvmap_mm_in_func)(struct kv * kv, void * priv);
204 | typedef struct kv * (* kvmap_mm_out_func)(struct kv * kv, struct kv * out);
205 | typedef void (* kvmap_mm_free_func)(struct kv * kv, void * priv);
206 |
207 | // manage internal kv data of kvmap
208 | struct kvmap_mm {
209 | // to create a private copy of "kv"
210 | // see put() functions
211 | kvmap_mm_in_func in;
212 | // to duplicate a private copy of "kv" to "out"
213 | // see get() and iter_peek() functions
214 | kvmap_mm_out_func out;
215 | // to free a kv
216 | // see del() and put() functions
217 | kvmap_mm_free_func free;
218 | void * priv;
219 | };
220 |
221 | extern struct kv *
222 | kvmap_mm_in_noop(struct kv * const kv, void * const priv);
223 |
224 | extern struct kv *
225 | kvmap_mm_out_noop(struct kv * const kv, struct kv * const out);
226 |
227 | extern void
228 | kvmap_mm_free_noop(struct kv * const kv, void * const priv);
229 |
230 | extern struct kv *
231 | kvmap_mm_in_dup(struct kv * const kv, void * const priv);
232 |
233 | extern struct kv *
234 | kvmap_mm_out_dup(struct kv * const kv, struct kv * const out);
235 |
236 | extern void
237 | kvmap_mm_free_free(struct kv * const kv, void * const priv);
238 |
239 | // the default mm
240 | extern const struct kvmap_mm kvmap_mm_dup; // in:Dup, out:Dup, free:Free
241 | extern const struct kvmap_mm kvmap_mm_ndf; // in:Noop, out:Dup, free:Free
242 | // }}} mm
243 |
244 | // ref {{{
245 | typedef int (*kref_kv_cmp_func)(const struct kref *, const struct kv *);
246 |
247 | // ptr and len only
248 | extern void
249 | kref_ref_raw(struct kref * const kref, const u8 * const ptr, const u32 len);
250 |
251 | // this calculates hash32
252 | extern void
253 | kref_ref_hash32(struct kref * const kref, const u8 * const ptr, const u32 len);
254 |
255 | extern void
256 | kref_update_hash32(struct kref * const kref);
257 |
258 | extern void
259 | kref_ref_kv(struct kref * const kref, const struct kv * const kv);
260 |
261 | extern void
262 | kref_ref_kv_hash32(struct kref * const kref, const struct kv * const kv);
263 |
264 | extern bool
265 | kref_match(const struct kref * const k1, const struct kref * const k2);
266 |
267 | extern bool
268 | kref_kv_match(const struct kref * const kref, const struct kv * const k);
269 |
270 | extern int
271 | kref_compare(const struct kref * const kref1, const struct kref * const kref2);
272 |
273 | extern int
274 | kref_kv_compare(const struct kref * const kref, const struct kv * const k);
275 |
276 | extern u32
277 | kref_lcp(const struct kref * const k1, const struct kref * const k2);
278 |
279 | extern u32
280 | kref_kv_lcp(const struct kref * const kref, const struct kv * const kv);
281 |
282 | extern int
283 | kref_k128_compare(const struct kref * const sk, const u8 * const k128);
284 |
285 | extern int
286 | kref_kv128_compare(const struct kref * const sk, const u8 * const kv128);
287 |
288 | extern const struct kref *
289 | kref_null(void);
290 |
291 | extern void
292 | kvref_ref_kv(struct kvref * const ref, struct kv * const kv);
293 |
294 | extern struct kv *
295 | kvref_dup2_kv(struct kvref * const ref, struct kv * const to);
296 |
297 | extern struct kv *
298 | kvref_dup2_key(struct kvref * const ref, struct kv * const to);
299 |
300 | extern int
301 | kvref_kv_compare(const struct kvref * const ref, const struct kv * const kv);
302 | // }}} ref
303 |
304 | // kv128 {{{
305 | extern size_t
306 | kv128_estimate_kv(const struct kv * const kv);
307 |
308 | extern u8 *
309 | kv128_encode_kv(const struct kv * const kv, u8 * const out, size_t * const pesize);
310 |
311 | extern struct kv *
312 | kv128_decode_kv(const u8 * const ptr, struct kv * const out, size_t * const pesize);
313 |
314 | extern size_t
315 | kv128_size(const u8 * const ptr);
316 | // }}} kv128
317 |
318 | // }}} kv
319 |
320 | // kvmap {{{
321 |
322 | // kvmap_api {{{
323 | typedef void (* kv_inp_func)(struct kv * const curr, void * const priv);
324 |
325 | // the merge function should:
326 | // 1: return NULL if the origin kv is not changed at all
327 | // 2: return kv0 if updates has been applied in-place
328 | // 3: return a different kv if the original kv must be replaced
329 | // In an in-memory kvmap, 2==1 and no further action is needed
330 | // In a persistent kv store with a memtable, 2 will need an insertion if kv0 is not from the memtable
331 | typedef struct kv * (* kv_merge_func)(struct kv * const kv0, void * const priv);
332 |
333 | struct kvmap_api {
334 | // feature bits
335 | bool hashkey; // true: caller needs to provide correct hash in kv/kref
336 | bool ordered; // true: has iter_seek
337 | bool threadsafe; // true: support thread_safe access
338 | bool readonly; // true: no put() and del()
339 | bool irefsafe; // true: iter's kref/kvref can be safely accessed after iter_seek/iter_skip/iter_park
340 | bool unique; // provide unique keys, especially for iterators
341 | bool refpark; // ref has park() and resume()
342 | bool async; // XXX for testing KVell
343 |
344 | // put (aka put/upsert): return true on success; false on error
345 | // mm.in() controls how things move into the kvmap; the default mm make a copy with malloc()
346 | // mm.free() controls how old kv get disposed when replaced
347 | bool (* put) (void * const ref, struct kv * const kv);
348 | // get: search and return a kv if found, or NULL if not
349 | // with the default mm: malloc() if out == NULL; otherwise, use out as buffer
350 | // with custom kvmap_mm: mm.out() controls buffer; use with caution
351 | // caller should use the returned ptr even if out is provided
352 | struct kv * (* get) (void * const ref, const struct kref * const key, struct kv * const out);
353 | // probe: return true on found, false on not found
354 | bool (* probe) (void * const ref, const struct kref * const key);
355 | // del: return true on something deleted, false on not found
356 | // mm.free() controls how old kv get disposed when replaced
357 | bool (* del) (void * const ref, const struct kref * const key);
358 | // inp: inplace operation if key exists; otherwise return false; uf() is always executed even with NULL key
359 | // inpr/inpw acquires r/w locks respectively.
360 | // Note that in inpw() you can only change the value.
361 | bool (* inpr) (void * const ref, const struct kref * const key, kv_inp_func uf, void * const priv);
362 | bool (* inpw) (void * const ref, const struct kref * const key, kv_inp_func uf, void * const priv);
363 | // merge: put+callback on old/new keys; another name: read-modify-write
364 | // return true if successfull; return false on error
365 | bool (* merge) (void * const ref, const struct kref * const key, kv_merge_func uf, void * const priv);
366 | // delete-range: delete all keys from start (inclusive) to end (exclusive)
367 | u64 (* delr) (void * const ref, const struct kref * const start, const struct kref * const end);
368 | // make everything persist; for persistent maps only
369 | void (* sync) (void * const ref);
370 |
371 | // general guidelines for thread-safe iters:
372 | // - it is assumed that the key under the cursor is locked/freezed/immutable
373 | // - once created one must call iter_seek to make it valid
374 | // - the ownership of ref is given to the iter so ref should not be used until iter_destroy
375 | // - creating and use more than one iter based on a ref can cause deadlocks
376 | void * (* iter_create) (void * const ref);
377 | // move the cursor to the first key >= search-key;
378 | void (* iter_seek) (void * const iter, const struct kref * const key);
379 | // check if the cursor points to a valid key
380 | bool (* iter_valid) (void * const iter);
381 | // return the current key; copy to out if (out != NULL)
382 | // mm.out() controls copy-out
383 | struct kv * (* iter_peek) (void * const iter, struct kv * const out);
384 | // similar to peek but does not copy; return false if iter is invalid
385 | bool (* iter_kref) (void * const iter, struct kref * const kref);
386 | // similar to iter_kref but also provide the value
387 | bool (* iter_kvref) (void * const iter, struct kvref * const kvref);
388 | // iter_retain makes kref or kvref of the current iter remain valid until released
389 | // the returned opaque pointer should be provided when releasing the hold
390 | u64 (* iter_retain) (void * const iter);
391 | void (* iter_release) (void * const iter, const u64 opaque);
392 | // skip one element
393 | void (* iter_skip1) (void * const iter);
394 | // skip nr elements
395 | void (* iter_skip) (void * const iter, const u32 nr);
396 | // iter_next == iter_peek + iter_skip1
397 | struct kv * (* iter_next) (void * const iter, struct kv * const out);
398 | // perform inplace opeation if the current key is valid; return false if no current key
399 | // the uf() is always executed even with NULL key
400 | bool (* iter_inp) (void * const iter, kv_inp_func uf, void * const priv);
401 | // invalidate the iter to release any resources or locks
402 | // afterward, must call seek() again before accessing data
403 | void (* iter_park) (void * const iter);
404 | // destroy iter
405 | void (* iter_destroy) (void * const iter);
406 |
407 | // misc:
408 | // create refs for maps if required; always use use kvmap_ref() and kvmap_unref()
409 | // if there are ref/unref functions, ref-ptr should be used as map for all kv operations
410 | void * (* ref) (void * map);
411 | // return the original map
412 | void * (* unref) (void * ref);
413 | // pause access without unref; must call resume later before access index again
414 | void (* park) (void * ref);
415 | // resume access of ref; must be paired with a park()
416 | void (* resume) (void * ref);
417 |
418 | // UNSAFE functions:
419 | // empty the map
420 | void (* clean) (void * map);
421 | // erase everything
422 | void (* destroy) (void * map);
423 | // for debugging
424 | void (* fprint) (void * map, FILE * const out);
425 | };
426 |
427 | // registry
428 | struct kvmap_api_reg {
429 | int nargs; // number of arguments after name
430 | const char * name;
431 | const char * args_msg; // see ...helper_message
432 | // multiple apis may share one create function
433 | // arguments: name (e.g., "rdb"), mm (usually NULL), the remaining args
434 | void * (*create)(const char *, const struct kvmap_mm *, char **);
435 | const struct kvmap_api * api;
436 | };
437 |
438 | // call this function to register a kvmap_api
439 | extern void
440 | kvmap_api_register(const int nargs, const char * const name, const char * const args_msg,
441 | void * (*create)(const char *, const struct kvmap_mm *, char **), const struct kvmap_api * const api);
442 |
443 | extern void
444 | kvmap_api_helper_message(void);
445 |
446 | extern int
447 | kvmap_api_helper(int argc, char ** const argv, const struct kvmap_mm * const mm,
448 | const struct kvmap_api ** const api_out, void ** const map_out);
449 | // }}} kvmap_api
450 |
451 | // helpers {{{
452 | extern void
453 | kvmap_inp_steal_kv(struct kv * const kv, void * const priv);
454 |
455 | extern void *
456 | kvmap_ref(const struct kvmap_api * const api, void * const map);
457 |
458 | extern void *
459 | kvmap_unref(const struct kvmap_api * const api, void * const ref);
460 |
461 | extern struct kv *
462 | kvmap_kv_get(const struct kvmap_api * const api, void * const ref,
463 | const struct kv * const key, struct kv * const out);
464 |
465 | extern bool
466 | kvmap_kv_probe(const struct kvmap_api * const api, void * const ref,
467 | const struct kv * const key);
468 |
469 | extern bool
470 | kvmap_kv_put(const struct kvmap_api * const api, void * const ref,
471 | struct kv * const kv);
472 |
473 | extern bool
474 | kvmap_kv_del(const struct kvmap_api * const api, void * const ref,
475 | const struct kv * const key);
476 |
477 | extern bool
478 | kvmap_kv_inpr(const struct kvmap_api * const api, void * const ref,
479 | const struct kv * const key, kv_inp_func uf, void * const priv);
480 |
481 | extern bool
482 | kvmap_kv_inpw(const struct kvmap_api * const api, void * const ref,
483 | const struct kv * const key, kv_inp_func uf, void * const priv);
484 |
485 | extern bool
486 | kvmap_kv_merge(const struct kvmap_api * const api, void * const ref,
487 | const struct kv * const key, kv_merge_func uf, void * const priv);
488 |
489 | extern u64
490 | kvmap_kv_delr(const struct kvmap_api * const api, void * const ref,
491 | const struct kv * const start, const struct kv * const end);
492 |
493 | extern void
494 | kvmap_kv_iter_seek(const struct kvmap_api * const api, void * const iter,
495 | const struct kv * const key);
496 |
497 | extern struct kv *
498 | kvmap_raw_get(const struct kvmap_api * const api, void * const ref,
499 | const u32 len, const u8 * const ptr, struct kv * const out);
500 |
501 | extern bool
502 | kvmap_raw_probe(const struct kvmap_api * const api, void * const ref,
503 | const u32 len, const u8 * const ptr);
504 |
505 | extern bool
506 | kvmap_raw_del(const struct kvmap_api * const api, void * const ref,
507 | const u32 len, const u8 * const ptr);
508 |
509 | extern bool
510 | kvmap_raw_inpr(const struct kvmap_api * const api, void * const ref,
511 | const u32 len, const u8 * const ptr, kv_inp_func uf, void * const priv);
512 |
513 | extern bool
514 | kvmap_raw_inpw(const struct kvmap_api * const api, void * const ref,
515 | const u32 len, const u8 * const ptr, kv_inp_func uf, void * const priv);
516 |
517 | extern void
518 | kvmap_raw_iter_seek(const struct kvmap_api * const api, void * const iter,
519 | const u32 len, const u8 * const ptr);
520 |
521 | extern u64
522 | kvmap_dump_keys(const struct kvmap_api * const api, void * const map, const int fd);
523 | // }}} helpers
524 |
525 | // }}} kvmap
526 |
527 | // miter {{{
528 | // general-purpose merging iterator
529 | // api functions:
530 | // REQUIRED:
531 | // - iter_create
532 | // - iter_seek
533 | // - iter_peek
534 | // - iter_skip
535 | // - iter_destroy
536 | // - iter_kref
537 | // - iter_kvref
538 | // OPTIONAL (api-specific):
539 | // - ref/unref
540 | // - iter_park
541 | // - resume/park (need also set api->refpark)
542 | // OPTIONAL (performance):
543 | // - api->unique (faster miter_skip_unique)
544 | // - iter_retain/iter_release (less memcpy)
545 |
546 | struct miter;
547 |
548 | extern struct miter *
549 | miter_create(void);
550 |
551 | // caller owns the ref and the iter; miter will not destroy them
552 | // using the iter or the ref with an active miter can lead to undefined behavior
553 | extern bool
554 | miter_add_iter(struct miter * const miter, const struct kvmap_api * const api, void * const ref, void * const iter);
555 |
556 | // caller owns the ref; miter will create and destroy the iter
557 | // using the underlying ref with an active miter can lead to undefined behavior
558 | extern void *
559 | miter_add_ref(struct miter * const miter, const struct kvmap_api * const api, void * const ref);
560 |
561 | // miter will take a ref of the map, create an iter, and clean up everything
562 | // be careful of using another ref/iter in the same thread
563 | extern void *
564 | miter_add(struct miter * const miter, const struct kvmap_api * const api, void * const map);
565 |
566 | extern u32
567 | miter_rank(struct miter * const miter);
568 |
569 | extern void
570 | miter_seek(struct miter * const miter, const struct kref * const key);
571 |
572 | extern void
573 | miter_kv_seek(struct miter * const miter, const struct kv * const key);
574 |
575 | extern bool
576 | miter_valid(struct miter * const miter);
577 |
578 | extern struct kv *
579 | miter_peek(struct miter * const miter, struct kv * const out);
580 |
581 | extern bool
582 | miter_kref(struct miter * const miter, struct kref * const kref);
583 |
584 | extern bool
585 | miter_kvref(struct miter * const miter, struct kvref * const kvref);
586 |
587 | extern void
588 | miter_skip1(struct miter * const miter);
589 |
590 | extern void
591 | miter_skip(struct miter * const miter, const u32 nr);
592 |
593 | extern struct kv *
594 | miter_next(struct miter * const miter, struct kv * const out);
595 |
596 | extern void
597 | miter_skip_unique(struct miter * const miter);
598 |
599 | extern struct kv *
600 | miter_next_unique(struct miter * const miter, struct kv * const out);
601 |
602 | extern void
603 | miter_park(struct miter * const miter);
604 |
605 | extern void
606 | miter_clean(struct miter * const miter);
607 |
608 | extern void
609 | miter_destroy(struct miter * const miter);
610 | // }}} miter
611 |
612 | #ifdef __cplusplus
613 | }
614 | #endif
615 | // vim:fdm=marker
616 |
--------------------------------------------------------------------------------
/lib.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016--2021 Wu, Xingbo
3 | *
4 | * All rights reserved. No warranty, explicit or implicit, provided.
5 | */
6 | #pragma once
7 |
8 | // includes {{{
9 | // C headers
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include
15 | #include
16 | #include
17 | #include
18 | #include
19 |
20 | // POSIX headers
21 | #include
22 | #include
23 | #include
24 |
25 | // Linux headers
26 | #include
27 | #include
28 | #include
29 | #include
30 |
31 | // SIMD
32 | #if defined(__x86_64__)
33 | #include
34 | #elif defined(__aarch64__)
35 | #include
36 | #include
37 | #endif
38 | // }}} includes
39 |
40 | #ifdef __cplusplus
41 | extern "C" {
42 | #endif
43 |
44 | // types {{{
45 | typedef char s8;
46 | typedef short s16;
47 | typedef int s32;
48 | typedef long s64;
49 | typedef __int128_t s128;
50 | static_assert(sizeof(s8) == 1, "sizeof(s8)");
51 | static_assert(sizeof(s16) == 2, "sizeof(s16)");
52 | static_assert(sizeof(s32) == 4, "sizeof(s32)");
53 | static_assert(sizeof(s64) == 8, "sizeof(s64)");
54 | static_assert(sizeof(s128) == 16, "sizeof(s128)");
55 |
56 | typedef unsigned char u8;
57 | typedef unsigned short u16;
58 | typedef unsigned int u32;
59 | typedef unsigned long u64;
60 | typedef __uint128_t u128;
61 | static_assert(sizeof(u8) == 1, "sizeof(u8)");
62 | static_assert(sizeof(u16) == 2, "sizeof(u16)");
63 | static_assert(sizeof(u32) == 4, "sizeof(u32)");
64 | static_assert(sizeof(u64) == 8, "sizeof(u64)");
65 | static_assert(sizeof(u128) == 16, "sizeof(u128)");
66 |
67 | #if defined(__x86_64__)
68 | typedef __m128i m128;
69 | #if defined(__AVX2__)
70 | typedef __m256i m256;
71 | #endif // __AVX2__
72 | #if defined(__AVX512F__)
73 | typedef __m512i m512;
74 | #endif // __AVX512F__
75 | #elif defined(__aarch64__)
76 | typedef uint8x16_t m128;
77 | #else
78 | #error Need x86_64 or AArch64.
79 | #endif
80 | // }}} types
81 |
82 | // defs {{{
83 | #define likely(____x____) __builtin_expect(____x____, 1)
84 | #define unlikely(____x____) __builtin_expect(____x____, 0)
85 |
86 | // ansi colors
87 | // 3X:fg; 4X:bg; 9X:light fg; 10X:light bg;
88 | // X can be one of the following colors:
89 | // 0:black; 1:red; 2:green; 3:yellow;
90 | // 4:blue; 5:magenta; 6:cyan; 7:white;
91 | #define TERMCLR(____code____) "\x1b[" #____code____ "m"
92 | // }}} defs
93 |
94 | // const {{{
95 | #define PGSZ ((4096lu))
96 | // }}} const
97 |
98 | // math {{{
99 | extern u64
100 | mhash64(const u64 v);
101 |
102 | extern u32
103 | mhash32(const u32 v);
104 |
105 | extern u64
106 | gcd64(u64 a, u64 b);
107 | // }}} math
108 |
109 | // random {{{
110 | extern u64
111 | random_u64(void);
112 |
113 | extern void
114 | srandom_u64(const u64 seed);
115 |
116 | extern double
117 | random_double(void);
118 | // }}} random
119 |
120 | // timing {{{
121 | extern u64
122 | time_nsec(void);
123 |
124 | extern double
125 | time_sec(void);
126 |
127 | extern u64
128 | time_diff_nsec(const u64 last);
129 |
130 | extern double
131 | time_diff_sec(const double last);
132 |
133 | extern void
134 | time_stamp(char * str, const size_t size);
135 |
136 | extern void
137 | time_stamp2(char * str, const size_t size);
138 | // }}} timing
139 |
140 | // cpucache {{{
141 | extern void
142 | cpu_pause(void);
143 |
144 | extern void
145 | cpu_mfence(void);
146 |
147 | extern void
148 | cpu_cfence(void);
149 |
150 | extern void
151 | cpu_prefetch0(const void * const ptr);
152 |
153 | extern void
154 | cpu_prefetch1(const void * const ptr);
155 |
156 | extern void
157 | cpu_prefetch2(const void * const ptr);
158 |
159 | extern void
160 | cpu_prefetch3(const void * const ptr);
161 |
162 | extern void
163 | cpu_prefetchw(const void * const ptr);
164 | // }}} cpucache
165 |
166 | // crc32c {{{
167 | extern u32
168 | crc32c_u8(const u32 crc, const u8 v);
169 |
170 | extern u32
171 | crc32c_u16(const u32 crc, const u16 v);
172 |
173 | extern u32
174 | crc32c_u32(const u32 crc, const u32 v);
175 |
176 | extern u32
177 | crc32c_u64(const u32 crc, const u64 v);
178 |
179 | // 1 <= nr <= 3
180 | extern u32
181 | crc32c_inc_123(const u8 * buf, u32 nr, u32 crc);
182 |
183 | // nr % 4 == 0
184 | extern u32
185 | crc32c_inc_x4(const u8 * buf, u32 nr, u32 crc);
186 |
187 | extern u32
188 | crc32c_inc(const u8 * buf, u32 nr, u32 crc);
189 | // }}} crc32c
190 |
191 | // debug {{{
192 | extern void
193 | debug_break(void);
194 |
195 | extern void
196 | debug_backtrace(void);
197 |
198 | extern void
199 | watch_u64_usr1(u64 * const ptr);
200 |
201 | #ifndef NDEBUG
202 | extern void
203 | debug_assert(const bool v);
204 | #else
205 | #define debug_assert(expr) ((void)0)
206 | #endif
207 |
208 | __attribute__((noreturn))
209 | extern void
210 | debug_die(void);
211 |
212 | __attribute__((noreturn))
213 | extern void
214 | debug_die_perror(void);
215 |
216 | extern void
217 | debug_dump_maps(FILE * const out);
218 |
219 | extern bool
220 | debug_perf_switch(void);
221 | // }}} debug
222 |
223 | // mm {{{
224 | #ifdef ALLOCFAIL
225 | extern bool
226 | alloc_fail(void);
227 | #endif
228 |
229 | extern void *
230 | xalloc(const size_t align, const size_t size);
231 |
232 | extern void *
233 | yalloc(const size_t size);
234 |
235 | extern void **
236 | malloc_2d(const size_t nr, const size_t size);
237 |
238 | extern void **
239 | calloc_2d(const size_t nr, const size_t size);
240 |
241 | extern void
242 | pages_unmap(void * const ptr, const size_t size);
243 |
244 | extern void
245 | pages_lock(void * const ptr, const size_t size);
246 |
247 | /* hugepages */
248 | // force posix allocators: -DVALGRIND_MEMCHECK
249 | extern void *
250 | pages_alloc_4kb(const size_t nr_4kb);
251 |
252 | extern void *
253 | pages_alloc_2mb(const size_t nr_2mb);
254 |
255 | extern void *
256 | pages_alloc_1gb(const size_t nr_1gb);
257 |
258 | extern void *
259 | pages_alloc_best(const size_t size, const bool try_1gb, u64 * const size_out);
260 | // }}} mm
261 |
262 | // process/thread {{{
263 | extern void
264 | thread_get_name(const pthread_t pt, char * const name, const size_t len);
265 |
266 | extern void
267 | thread_set_name(const pthread_t pt, const char * const name);
268 |
269 | extern long
270 | process_get_rss(void);
271 |
272 | extern u32
273 | process_affinity_count(void);
274 |
275 | extern u32
276 | process_getaffinity_list(const u32 max, u32 * const cores);
277 |
278 | extern void
279 | thread_setaffinity_list(const u32 nr, const u32 * const list);
280 |
281 | extern void
282 | thread_pin(const u32 cpu);
283 |
284 | extern u64
285 | process_cpu_time_usec(void);
286 |
287 | // if args == true, argx is void **
288 | // if args == false, argx is void *
289 | extern u64
290 | thread_fork_join(u32 nr, void *(*func) (void *), const bool args, void * const argx);
291 |
292 | extern int
293 | thread_create_at(const u32 cpu, pthread_t * const thread, void *(*start_routine) (void *), void * const arg);
294 | // }}} process/thread
295 |
296 | // locking {{{
297 | typedef union {
298 | u32 opaque;
299 | } spinlock;
300 |
301 | extern void
302 | spinlock_init(spinlock * const lock);
303 |
304 | extern void
305 | spinlock_lock(spinlock * const lock);
306 |
307 | extern bool
308 | spinlock_trylock(spinlock * const lock);
309 |
310 | extern void
311 | spinlock_unlock(spinlock * const lock);
312 |
313 | typedef union {
314 | u32 opaque;
315 | } rwlock;
316 |
317 | extern void
318 | rwlock_init(rwlock * const lock);
319 |
320 | extern bool
321 | rwlock_trylock_read(rwlock * const lock);
322 |
323 | // low-priority reader-lock; use with trylock_write_hp
324 | extern bool
325 | rwlock_trylock_read_lp(rwlock * const lock);
326 |
327 | extern bool
328 | rwlock_trylock_read_nr(rwlock * const lock, u16 nr);
329 |
330 | extern void
331 | rwlock_lock_read(rwlock * const lock);
332 |
333 | extern void
334 | rwlock_unlock_read(rwlock * const lock);
335 |
336 | extern bool
337 | rwlock_trylock_write(rwlock * const lock);
338 |
339 | extern bool
340 | rwlock_trylock_write_nr(rwlock * const lock, u16 nr);
341 |
342 | extern void
343 | rwlock_lock_write(rwlock * const lock);
344 |
345 | // writer has higher priority; new readers are blocked
346 | extern bool
347 | rwlock_trylock_write_hp(rwlock * const lock);
348 |
349 | extern bool
350 | rwlock_trylock_write_hp_nr(rwlock * const lock, u16 nr);
351 |
352 | extern void
353 | rwlock_lock_write_hp(rwlock * const lock);
354 |
355 | extern void
356 | rwlock_unlock_write(rwlock * const lock);
357 |
358 | extern void
359 | rwlock_write_to_read(rwlock * const lock);
360 |
361 | typedef union {
362 | u64 opqaue[8];
363 | } mutex;
364 |
365 | extern void
366 | mutex_init(mutex * const lock);
367 |
368 | extern void
369 | mutex_lock(mutex * const lock);
370 |
371 | extern bool
372 | mutex_trylock(mutex * const lock);
373 |
374 | extern void
375 | mutex_unlock(mutex * const lock);
376 |
377 | extern void
378 | mutex_deinit(mutex * const lock);
379 | // }}} locking
380 |
381 | // coroutine {{{
382 | extern u64 co_switch_stack(u64 * const saversp, const u64 newrsp, const u64 retval);
383 |
384 | struct co;
385 |
386 | extern struct co *
387 | co_create(const u64 stacksize, void * func, void * priv, u64 * const host);
388 |
389 | extern void
390 | co_reuse(struct co * const co, void * func, void * priv, u64 * const host);
391 |
392 | extern struct co *
393 | co_fork(void * func, void * priv);
394 |
395 | extern void *
396 | co_priv(void);
397 |
398 | extern u64
399 | co_enter(struct co * const to, const u64 retval);
400 |
401 | extern u64
402 | co_switch_to(struct co * const to, const u64 retval);
403 |
404 | extern u64
405 | co_back(const u64 retval);
406 |
407 | extern void
408 | co_exit(const u64 retval);
409 |
410 | extern bool
411 | co_valid(struct co * const co);
412 |
413 | extern struct co *
414 | co_self(void);
415 |
416 | extern void
417 | co_destroy(struct co * const co);
418 |
419 | struct corr;
420 |
421 | extern struct corr *
422 | corr_create(const u64 stacksize, void * func, void * priv, u64 * const host);
423 |
424 | extern struct corr *
425 | corr_link(const u64 stacksize, void * func, void * priv, struct corr * const prev);
426 |
427 | extern void
428 | corr_reuse(struct corr * const co, void * func, void * priv, u64 * const host);
429 |
430 | extern void
431 | corr_relink(struct corr * const co, void * func, void * priv, struct corr * const prev);
432 |
433 | extern void
434 | corr_enter(struct corr * const co);
435 |
436 | extern void
437 | corr_yield(void);
438 |
439 | extern void
440 | corr_exit(void);
441 |
442 | extern void
443 | corr_destroy(struct corr * const co);
444 | // }}} coroutine
445 |
446 | // bits {{{
447 | extern u32
448 | bits_reverse_u32(const u32 v);
449 |
450 | extern u64
451 | bits_reverse_u64(const u64 v);
452 |
453 | extern u64
454 | bits_rotl_u64(const u64 v, const u8 n);
455 |
456 | extern u64
457 | bits_rotr_u64(const u64 v, const u8 n);
458 |
459 | extern u32
460 | bits_rotl_u32(const u32 v, const u8 n);
461 |
462 | extern u32
463 | bits_rotr_u32(const u32 v, const u8 n);
464 |
465 | extern u64
466 | bits_p2_up_u64(const u64 v);
467 |
468 | extern u32
469 | bits_p2_up_u32(const u32 v);
470 |
471 | extern u64
472 | bits_p2_down_u64(const u64 v);
473 |
474 | extern u32
475 | bits_p2_down_u32(const u32 v);
476 |
477 | extern u64
478 | bits_round_up(const u64 v, const u8 power);
479 |
480 | extern u64
481 | bits_round_up_a(const u64 v, const u64 a);
482 |
483 | extern u64
484 | bits_round_down(const u64 v, const u8 power);
485 |
486 | extern u64
487 | bits_round_down_a(const u64 v, const u64 a);
488 | // }}} bits
489 |
490 | // simd {{{
491 | extern u32
492 | m128_movemask_u8(const m128 v);
493 |
494 | // extern u32
495 | //m128_movemask_u16(const m128 v);
496 | //
497 | // extern u32
498 | //m128_movemask_u32(const m128 v);
499 | // }}} simd
500 |
501 | // vi128 {{{
502 | extern u32
503 | vi128_estimate_u32(const u32 v);
504 |
505 | extern u8 *
506 | vi128_encode_u32(u8 * dst, u32 v);
507 |
508 | extern const u8 *
509 | vi128_decode_u32(const u8 * src, u32 * const out);
510 |
511 | extern u32
512 | vi128_estimate_u64(const u64 v);
513 |
514 | extern u8 *
515 | vi128_encode_u64(u8 * dst, u64 v);
516 |
517 | extern const u8 *
518 | vi128_decode_u64(const u8 * src, u64 * const out);
519 | // }}} vi128
520 |
521 | // misc {{{
522 | // TODO: only works on little endian?
523 | struct entry13 { // what a beautiful name
524 | union {
525 | u16 e1;
526 | struct { // easy for debugging
527 | u64 e1_64:16;
528 | u64 e3:48;
529 | };
530 | u64 v64;
531 | void * ptr;
532 | };
533 | };
534 |
535 | static_assert(sizeof(struct entry13) == 8, "sizeof(entry13) != 8");
536 |
537 | // directly access read .e1 and .e3
538 | // directly write .e1
539 | // use entry13_update() to update the entire entry
540 |
541 | extern struct entry13
542 | entry13(const u16 e1, const u64 e3);
543 |
544 | extern void
545 | entry13_update_e3(struct entry13 * const e, const u64 e3);
546 |
547 | extern void *
548 | u64_to_ptr(const u64 v);
549 |
550 | extern u64
551 | ptr_to_u64(const void * const ptr);
552 |
553 | extern size_t
554 | m_usable_size(void * const ptr);
555 |
556 | extern size_t
557 | fdsize(const int fd);
558 |
559 | extern u32
560 | memlcp(const u8 * const p1, const u8 * const p2, const u32 max);
561 |
562 | __attribute__ ((format (printf, 2, 3)))
563 | extern void
564 | logger_printf(const int fd, const char * const fmt, ...);
565 | // }}} misc
566 |
567 | // bitmap {{{
568 | struct bitmap;
569 |
570 | extern struct bitmap *
571 | bitmap_create(const u64 nbits);
572 |
573 | extern void
574 | bitmap_init(struct bitmap * const bm, const u64 nbits);
575 |
576 | extern bool
577 | bitmap_test(const struct bitmap * const bm, const u64 idx);
578 |
579 | extern bool
580 | bitmap_test_all1(struct bitmap * const bm);
581 |
582 | extern bool
583 | bitmap_test_all0(struct bitmap * const bm);
584 |
585 | extern void
586 | bitmap_set1(struct bitmap * const bm, const u64 idx);
587 |
588 | extern void
589 | bitmap_set0(struct bitmap * const bm, const u64 idx);
590 |
591 | extern void
592 | bitmap_set1_safe64(struct bitmap * const bm, const u64 idx);
593 |
594 | extern void
595 | bitmap_set0_safe64(struct bitmap * const bm, const u64 idx);
596 |
597 | extern u64
598 | bitmap_count(struct bitmap * const bm);
599 |
600 | extern u64
601 | bitmap_first(struct bitmap * const bm);
602 |
603 | extern void
604 | bitmap_set_all1(struct bitmap * const bm);
605 |
606 | extern void
607 | bitmap_set_all0(struct bitmap * const bm);
608 | // }}} bitmap
609 |
610 | // slab {{{
611 | struct slab;
612 |
613 | extern struct slab *
614 | slab_create(const u64 obj_size, const u64 blk_size);
615 |
616 | extern bool
617 | slab_reserve_unsafe(struct slab * const slab, const u64 nr);
618 |
619 | extern void *
620 | slab_alloc_unsafe(struct slab * const slab);
621 |
622 | extern void *
623 | slab_alloc_safe(struct slab * const slab);
624 |
625 | extern void
626 | slab_free_unsafe(struct slab * const slab, void * const ptr);
627 |
628 | extern void
629 | slab_free_safe(struct slab * const slab, void * const ptr);
630 |
631 | extern void
632 | slab_free_all(struct slab * const slab);
633 |
634 | extern u64
635 | slab_get_nalloc(struct slab * const slab);
636 |
637 | extern void
638 | slab_destroy(struct slab * const slab);
639 | // }}} slab
640 |
641 | // qsort {{{
642 | extern int
643 | compare_u16(const void * const p1, const void * const p2);
644 |
645 | extern void
646 | qsort_u16(u16 * const array, const size_t nr);
647 |
648 | extern u16 *
649 | bsearch_u16(const u16 v, const u16 * const array, const size_t nr);
650 |
651 | extern void
652 | shuffle_u16(u16 * const array, const u64 nr);
653 |
654 | extern int
655 | compare_u32(const void * const p1, const void * const p2);
656 |
657 | extern void
658 | qsort_u32(u32 * const array, const size_t nr);
659 |
660 | extern u32 *
661 | bsearch_u32(const u32 v, const u32 * const array, const size_t nr);
662 |
663 | extern void
664 | shuffle_u32(u32 * const array, const u64 nr);
665 |
666 | extern int
667 | compare_u64(const void * const p1, const void * const p2);
668 |
669 | extern void
670 | qsort_u64(u64 * const array, const size_t nr);
671 |
672 | extern u64 *
673 | bsearch_u64(const u64 v, const u64 * const array, const size_t nr);
674 |
675 | extern void
676 | shuffle_u64(u64 * const array, const u64 nr);
677 |
678 | extern int
679 | compare_double(const void * const p1, const void * const p2);
680 |
681 | extern void
682 | qsort_double(double * const array, const size_t nr);
683 |
684 | extern void
685 | qsort_u64_sample(const u64 * const array0, const u64 nr, const u64 res, FILE * const out);
686 |
687 | extern void
688 | qsort_double_sample(const double * const array0, const u64 nr, const u64 res, FILE * const out);
689 | // }}} qsort
690 |
691 | // xlog {{{
692 | struct xlog;
693 |
694 | extern struct xlog *
695 | xlog_create(const u64 nr_init, const u64 unit_size);
696 |
697 | extern void
698 | xlog_append(struct xlog * const xlog, const void * const rec);
699 |
700 | extern void
701 | xlog_append_cycle(struct xlog * const xlog, const void * const rec);
702 |
703 | extern void
704 | xlog_reset(struct xlog * const xlog);
705 |
706 | extern u64
707 | xlog_read(struct xlog * const xlog, void * const buf, const u64 nr_max);
708 |
709 | extern void
710 | xlog_dump(struct xlog * const xlog, FILE * const out);
711 |
712 | extern void
713 | xlog_destroy(struct xlog * const xlog);
714 |
715 | struct xlog_iter;
716 |
717 | extern struct xlog_iter *
718 | xlog_iter_create(const struct xlog * const xlog);
719 |
720 | extern bool
721 | xlog_iter_next(struct xlog_iter * const iter, void * const out);
722 | // free iter after use
723 | // }}} xlog
724 |
725 | // string {{{
726 | // XXX strdec_ and strhex_ functions does not append the trailing '\0' to the output string
727 | // size of out should be >= 10
728 | extern void
729 | strdec_32(void * const out, const u32 v);
730 |
731 | // size of out should be >= 20
732 | extern void
733 | strdec_64(void * const out, const u64 v);
734 |
735 | // size of out should be >= 8
736 | extern void
737 | strhex_32(void * const out, const u32 v);
738 |
739 | // size of out should be >= 16
740 | extern void
741 | strhex_64(void * const out, const u64 v);
742 |
743 | extern u64
744 | a2u64(const void * const str);
745 |
746 | extern u32
747 | a2u32(const void * const str);
748 |
749 | extern s64
750 | a2s64(const void * const str);
751 |
752 | extern s32
753 | a2s32(const void * const str);
754 |
755 | extern void
756 | str_print_hex(FILE * const out, const void * const data, const u32 len);
757 |
758 | extern void
759 | str_print_dec(FILE * const out, const void * const data, const u32 len);
760 |
761 | // user should free returned ptr (and nothing else) after use
762 | extern char **
763 | strtoks(const char * const str, const char * const delim);
764 |
765 | extern u32
766 | strtoks_count(const char * const * const toks);
767 | // }}} string
768 |
769 | // qsbr {{{
770 | // QSBR vs EBR (Quiescent-State vs Epoch Based Reclaimation)
771 | // QSBR: readers just use qsbr_update -> qsbr_update -> ... repeatedly
772 | // EBR: readers use qsbr_update -> qsbr_park -> qsbr_resume -> qsbr_update -> ...
773 | // The advantage of EBR is qsbr_park can happen much earlier than the next qsbr_update
774 | // The disadvantage is the extra cost, a pair of park/resume is used in every iteration
775 | struct qsbr;
776 | struct qsbr_ref {
777 | #ifdef QSBR_DEBUG
778 | u64 debug[16];
779 | #endif
780 | u64 opaque[3];
781 | };
782 |
783 | extern struct qsbr *
784 | qsbr_create(void);
785 |
786 | // every READER accessing the shared data must first register itself with the qsbr
787 | extern bool
788 | qsbr_register(struct qsbr * const q, struct qsbr_ref * const qref);
789 |
790 | extern void
791 | qsbr_unregister(struct qsbr * const q, struct qsbr_ref * const qref);
792 |
793 | // For READER: mark the beginning of critical section; like rcu_read_lock()
794 | extern void
795 | qsbr_update(struct qsbr_ref * const qref, const u64 v);
796 |
797 | // temporarily stop access the shared data to avoid blocking writers
798 | // READER can use qsbr_park (like rcu_read_unlock()) in conjunction with qsbr_update
799 | // qsbr_park is roughly equivalent to qsbr_unregister, but faster
800 | extern void
801 | qsbr_park(struct qsbr_ref * const qref);
802 |
803 | // undo the effect of qsbr_park; must use it between qsbr_park and qsbr_update
804 | // qsbr_resume is roughly equivalent to qsbr_register, but faster
805 | extern void
806 | qsbr_resume(struct qsbr_ref * const qref);
807 |
808 | // WRITER: wait until all the readers have announced v=target with qsbr_update
809 | extern void
810 | qsbr_wait(struct qsbr * const q, const u64 target);
811 |
812 | extern void
813 | qsbr_destroy(struct qsbr * const q);
814 | // }}} qsbr
815 |
816 | #ifdef __cplusplus
817 | }
818 | #endif
819 | // vim:fdm=marker
820 |
--------------------------------------------------------------------------------
/remixdb.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016--2021 Wu, Xingbo
3 | *
4 | * All rights reserved. No warranty, explicit or implicit, provided.
5 | */
6 | #pragma once
7 |
8 | #include
9 | #include
10 |
11 | #ifdef __cplusplus
12 | extern "C" {
13 | #endif
14 |
15 | struct xdb;
16 | struct xdb_ref;
17 | struct xdb_iter;
18 |
19 | extern struct xdb *
20 | remixdb_open(const char * const dir, const size_t cache_size_mb, const size_t mt_size_mb);
21 |
22 | extern struct xdb *
23 | remixdb_open_compact(const char * const dir, const size_t cache_size_mb, const size_t mt_size_mb);
24 |
25 | extern struct xdb_ref *
26 | remixdb_ref(struct xdb * const xdb);
27 |
28 | extern void
29 | remixdb_unref(struct xdb_ref * const ref);
30 |
31 | extern void
32 | remixdb_close(struct xdb * const xdb);
33 |
34 | extern bool
35 | remixdb_set(struct xdb_ref * const ref, const void * const kbuf, const uint32_t klen,
36 | const void * const vbuf, const uint32_t vlen);
37 |
38 | extern bool
39 | remixdb_del(struct xdb_ref * const ref, const void * const kbuf, const uint32_t klen);
40 |
41 | extern bool
42 | remixdb_probe(struct xdb_ref * const ref, const void * const kbuf, const uint32_t klen);
43 |
44 | extern bool
45 | remixdb_get(struct xdb_ref * const ref, const void * const kbuf, const uint32_t klen,
46 | void * const vbuf_out, uint32_t * const vlen_out);
47 |
48 | extern void
49 | remixdb_sync(struct xdb_ref * const ref);
50 |
51 | extern struct xdb_iter *
52 | remixdb_iter_create(struct xdb_ref * const ref);
53 |
54 | extern void
55 | remixdb_iter_seek(struct xdb_iter * const iter, const void * const kbuf, const uint32_t klen);
56 |
57 | extern bool
58 | remixdb_iter_valid(struct xdb_iter * const iter);
59 |
60 | extern bool
61 | remixdb_iter_peek(struct xdb_iter * const iter,
62 | void * const kbuf_out, uint32_t * const klen_out,
63 | void * const vbuf_out, uint32_t * const vlen_out);
64 |
65 | extern void
66 | remixdb_iter_skip(struct xdb_iter * const iter, const uint32_t nr);
67 |
68 | extern void
69 | remixdb_iter_park(struct xdb_iter * const iter);
70 |
71 | extern void
72 | remixdb_iter_destroy(struct xdb_iter * const iter);
73 |
74 | #ifdef __cplusplus
75 | }
76 | #endif
77 | // vim:fdm=marker
78 |
--------------------------------------------------------------------------------
/remixdb.strip:
--------------------------------------------------------------------------------
1 | -K remixdb_open
2 | -K remixdb_open_compact
3 | -K remixdb_close
4 | -K remixdb_ref
5 | -K remixdb_unref
6 | -K remixdb_put
7 | -K remixdb_del
8 | -K remixdb_get
9 | -K remixdb_probe
10 | -K remixdb_sync
11 | -K remixdb_iter_create
12 | -K remixdb_iter_destroy
13 | -K remixdb_iter_valid
14 | -K remixdb_iter_seek
15 | -K remixdb_iter_park
16 | -K remixdb_iter_peek
17 | -K remixdb_iter_skip
18 |
--------------------------------------------------------------------------------
/sotest.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2021 Wu, Xingbo
3 | *
4 | * All rights reserved. No warranty, explicit or implicit, provided.
5 | */
6 | #include
7 | #include
8 |
9 | #include "remixdb.h"
10 |
11 | int
12 | main(int argc, char ** argv)
13 | {
14 | (void)argc;
15 | (void)argv;
16 | struct xdb * const xdb = remixdb_open("/tmp/xdbdemo", 256, 256); // blockcache=256MB, MemTable=256MB
17 | struct xdb_ref * const ref = remixdb_ref(xdb);
18 |
19 | bool r;
20 |
21 | r = remixdb_set(ref, "remix", 5, "easy", 4);
22 | printf("remixdb_set remix easy %c\n", r?'T':'F');
23 |
24 | r = remixdb_set(ref, "time_travel", 11, "impossible", 10);
25 | printf("remixdb_set time_travel impossible %c\n", r?'T':'F');
26 |
27 | r = remixdb_del(ref, "time_travel", 11);
28 | printf("remixdb_del time_travel %c\n", r?'T':'F');
29 |
30 | r = remixdb_probe(ref, "time_travel", 11);
31 | printf("remixdb_probe time_travel %c\n", r?'T':'F');
32 |
33 | uint32_t klen_out = 0;
34 | char kbuf_out[8] = {};
35 | uint32_t vlen_out = 0;
36 | char vbuf_out[8] = {};
37 | r = remixdb_get(ref, "remix", 5, vbuf_out, &vlen_out);
38 | printf("remixdb_get remix %c %u %.*s\n", r?'T':'F', vlen_out, vlen_out, vbuf_out);
39 |
40 | // prepare a few keys for range ops
41 | r = remixdb_set(ref, "00", 2, "0_value", 7);
42 | r = remixdb_set(ref, "11", 2, "1_value", 7);
43 | r = remixdb_set(ref, "22", 2, "2_value", 7);
44 |
45 | struct xdb_iter * const iter = remixdb_iter_create(ref);
46 |
47 | remixdb_iter_seek(iter, NULL, 0); // seek to the head
48 | printf("remixdb_iter_seek \"\"\n");
49 | while (remixdb_iter_valid(iter)) {
50 | r = remixdb_iter_peek(iter, kbuf_out, &klen_out, vbuf_out, &vlen_out);
51 | if (r) {
52 | printf("remixdb_iter_peek klen=%u key=%.*s vlen=%u value=%.*s\n",
53 | klen_out, klen_out, kbuf_out, vlen_out, vlen_out, vbuf_out);
54 | } else {
55 | printf("ERROR!\n");
56 | }
57 | remixdb_iter_skip(iter, 1);
58 | }
59 |
60 | // call iter_park if you will go idle but want to use the iter later
61 | // don't need to call iter_park if you're actively using iter
62 | remixdb_iter_park(iter);
63 | usleep(10);
64 |
65 | remixdb_iter_seek(iter, "0", 1);
66 | printf("remixdb_iter_seek \"0\"\n");
67 | // this time we don't want to copy the value
68 | r = remixdb_iter_peek(iter, kbuf_out, &klen_out, NULL, NULL);
69 | if (r){
70 | printf("remixdb_iter_peek klen=%u key=%.*s\n", klen_out, klen_out, kbuf_out);
71 | } else {
72 | printf("ERROR: iter_peek failed\n");
73 | }
74 |
75 | remixdb_iter_destroy(iter);
76 | // there must be no active iter when calling unref()
77 | remixdb_unref(ref);
78 |
79 | // unsafe operations: should have released all references
80 | remixdb_close(xdb); // destroy also calls clean interally
81 | return 0;
82 | }
83 |
--------------------------------------------------------------------------------
/sst.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016--2021 Wu, Xingbo
3 | *
4 | * All rights reserved. No warranty, explicit or implicit, provided.
5 | */
6 | #pragma once
7 |
8 | #include "blkio.h"
9 |
10 | #ifdef __cplusplus
11 | extern "C" {
12 | #endif
13 |
14 | #define SST_VLEN_TS ((0x10000u)) // tomb stone
15 | #define SST_VLEN_MASK ((0xffffu)) // real vlen == vlen & 0xffff
16 |
17 | // kv {{{
18 | extern size_t
19 | sst_kv_vi128_estimate(const struct kv * const kv);
20 |
21 | extern u8 *
22 | sst_kv_vi128_encode(u8 * ptr, const struct kv * const kv);
23 |
24 | extern size_t
25 | sst_kv_size(const struct kv * const kv);
26 |
27 | extern struct kv *
28 | sst_kvref_dup2_kv(struct kvref * const kvref, struct kv * const out);
29 | // }}} kv
30 |
31 | // mm {{{
32 |
33 | extern struct kv *
34 | kvmap_mm_in_ts(struct kv * const kv, void * const priv);
35 |
36 | extern struct kv *
37 | kvmap_mm_out_ts(struct kv * const kv, struct kv * const out);
38 |
39 | extern const struct kvmap_mm kvmap_mm_ts;
40 | // }}} mm
41 |
42 | // sst {{{
43 | struct sst;
44 |
45 | extern struct sst *
46 | sst_open(const char * const dirname, const u64 seq, const u32 way);
47 |
48 | extern const struct sst_meta *
49 | sst_meta(struct sst * const sst);
50 |
51 | extern void
52 | sst_rcache(struct sst * const sst, struct rcache * const rc);
53 |
54 | extern struct kv *
55 | sst_get(struct sst * const map, const struct kref * const key, struct kv * const out);
56 |
57 | extern bool
58 | sst_probe(struct sst* const map, const struct kref * const key);
59 |
60 | extern struct kv *
61 | sst_first_key(struct sst * const map, struct kv * const out);
62 |
63 | extern struct kv *
64 | sst_last_key(struct sst * const map, struct kv * const out);
65 |
66 | extern void
67 | sst_destroy(struct sst * const map);
68 |
69 | extern void
70 | sst_dump(struct sst * const sst, const char * const fn);
71 |
72 | extern void
73 | sst_fprint(struct sst * const map, FILE * const out);
74 |
75 | struct sst_iter;
76 |
77 | extern struct sst_iter *
78 | sst_iter_create(struct sst * const sst);
79 |
80 | extern bool
81 | sst_iter_ts(struct sst_iter * const iter);
82 |
83 | extern void
84 | sst_iter_seek(struct sst_iter * const iter, const struct kref * const key);
85 |
86 | extern void
87 | sst_iter_seek_null(struct sst_iter * const iter);
88 |
89 | extern bool
90 | sst_iter_valid(struct sst_iter * const iter);
91 |
92 | extern struct kv *
93 | sst_iter_peek(struct sst_iter * const iter, struct kv * const out);
94 |
95 | extern bool
96 | sst_iter_kref(struct sst_iter * const iter, struct kref * const kref);
97 |
98 | extern bool
99 | sst_iter_kvref(struct sst_iter * const iter, struct kvref * const kvref);
100 |
101 | extern u64
102 | sst_iter_retain(struct sst_iter * const iter);
103 |
104 | extern void
105 | sst_iter_release(struct sst_iter * const iter, const u64 opaque);
106 |
107 | extern void
108 | sst_iter_skip1(struct sst_iter * const iter);
109 |
110 | extern void
111 | sst_iter_skip(struct sst_iter * const iter, const u32 nr);
112 |
113 | extern struct kv *
114 | sst_iter_next(struct sst_iter * const iter, struct kv * const out);
115 |
116 | extern void
117 | sst_iter_park(struct sst_iter * const iter);
118 |
119 | u64
120 | sst_iter_retain(struct sst_iter * const iter);
121 |
122 | void
123 | sst_iter_release(struct sst_iter * const iter, const u64 opaque);
124 |
125 | extern void
126 | sst_iter_destroy(struct sst_iter * const iter);
127 | // }}} sst
128 |
129 | // build-sst {{{
130 | // api contains sorted keys and supports iter_next().
131 | // all keys in the map_api will be added to the sstable.
132 | extern u64
133 | sst_build(const char * const dirname, struct miter * const miter,
134 | const u64 seq, const u32 way, const u32 maxblkid0, const bool del, const bool ckeys,
135 | const struct kv * const k0, const struct kv * const kz);
136 | // }}} build-sst
137 |
138 | // msstx {{{
139 | // msst (multi-sst)
140 | struct msst;
141 | struct msstx_iter;
142 |
143 | // msstx
144 | extern struct msst *
145 | msstx_open(const char * const dirname, const u64 seq, const u32 nway);
146 |
147 | extern void
148 | msst_rcache(struct msst * const msst, struct rcache * const rc);
149 |
150 | extern void
151 | msstx_destroy(struct msst * const msst);
152 |
153 | extern struct msstx_iter *
154 | msstx_iter_create(struct msst * const msst);
155 |
156 | extern struct kv *
157 | msstx_get(struct msst * const msst, const struct kref * const key, struct kv * const out);
158 |
159 | extern bool
160 | msstx_probe(struct msst * const msst, const struct kref * const key);
161 |
162 | extern bool
163 | msstx_iter_valid(struct msstx_iter * const iter);
164 |
165 | extern void
166 | msstx_iter_seek(struct msstx_iter * const iter, const struct kref * const key);
167 |
168 | extern void
169 | msstx_iter_seek_null(struct msstx_iter * const iter);
170 |
171 | extern struct kv *
172 | msstx_iter_peek(struct msstx_iter * const iter, struct kv * const out);
173 |
174 | extern bool
175 | msstx_iter_kref(struct msstx_iter * const iter, struct kref * const kref);
176 |
177 | extern bool
178 | msstx_iter_kvref(struct msstx_iter * const iter, struct kvref * const kvref);
179 |
180 | extern u64
181 | msstx_iter_retain(struct msstx_iter * const iter);
182 |
183 | extern void
184 | msstx_iter_release(struct msstx_iter * const iter, const u64 opaque);
185 |
186 | extern void
187 | msstx_iter_skip1(struct msstx_iter * const iter);
188 |
189 | extern void
190 | msstx_iter_skip(struct msstx_iter * const iter, const u32 nr);
191 |
192 | extern struct kv *
193 | msstx_iter_next(struct msstx_iter * const iter, struct kv * const out);
194 |
195 | extern void
196 | msstx_iter_park(struct msstx_iter * const iter);
197 |
198 | extern void
199 | msstx_iter_destroy(struct msstx_iter * const iter);
200 | // }}} msstx
201 |
202 | // ssty {{{
203 | struct ssty;
204 |
205 | extern struct ssty *
206 | ssty_open(const char * const dirname, const u64 seq, const u32 nway);
207 |
208 | extern void
209 | ssty_destroy(struct ssty * const ssty);
210 |
211 | extern void
212 | ssty_fprint(struct ssty * const ssty, FILE * const fout);
213 | // }}} ssty
214 |
215 | // mssty {{{
216 | struct mssty_ref;
217 | struct mssty_iter;
218 |
219 | extern bool
220 | mssty_open_y(const char * const dirname, struct msst * const msst);
221 |
222 | extern struct msst *
223 | mssty_open(const char * const dirname, const u64 seq, const u32 nway);
224 |
225 | extern void
226 | mssty_destroy(struct msst * const msst);
227 |
228 | extern void
229 | mssty_fprint(struct msst * const msst, FILE * const fout);
230 |
231 | extern struct mssty_ref *
232 | mssty_ref(struct msst * const msst);
233 |
234 | extern struct msst *
235 | mssty_unref(struct mssty_ref * const ref);
236 |
237 | extern struct mssty_iter *
238 | mssty_iter_create(struct mssty_ref * const ref);
239 |
240 | extern bool
241 | mssty_iter_valid(struct mssty_iter * const iter);
242 |
243 | extern void
244 | mssty_iter_seek(struct mssty_iter * const iter, const struct kref * const key);
245 |
246 | extern void
247 | mssty_iter_seek_null(struct mssty_iter * const iter);
248 |
249 | extern void
250 | mssty_iter_seek_near(struct mssty_iter * const iter, const struct kref * const key, const bool bsearch_keys);
251 |
252 | extern struct kv *
253 | mssty_iter_peek(struct mssty_iter * const iter, struct kv * const out);
254 |
255 | extern bool
256 | mssty_iter_kref(struct mssty_iter * const iter, struct kref * const kref);
257 |
258 | extern bool
259 | mssty_iter_kvref(struct mssty_iter * const iter, struct kvref * const kvref);
260 |
261 | extern u64
262 | mssty_iter_retain(struct mssty_iter * const iter);
263 |
264 | extern void
265 | mssty_iter_release(struct mssty_iter * const iter, const u64 opaque);
266 |
267 | extern void
268 | mssty_iter_skip1(struct mssty_iter * const iter);
269 |
270 | extern void
271 | mssty_iter_skip(struct mssty_iter * const iter, const u32 nr);
272 |
273 | extern struct kv *
274 | mssty_iter_next(struct mssty_iter * const iter, struct kv * const out);
275 |
276 | extern void
277 | mssty_iter_park(struct mssty_iter * const iter);
278 |
279 | extern void
280 | mssty_iter_destroy(struct mssty_iter * const iter);
281 |
282 | // ts iter: ignore a key if its newest version is a tombstone
283 | extern bool
284 | mssty_iter_ts(struct mssty_iter * const iter);
285 |
286 | extern void
287 | mssty_iter_seek_ts(struct mssty_iter * const iter, const struct kref * const key);
288 |
289 | extern void
290 | mssty_iter_skip1_ts(struct mssty_iter * const iter);
291 |
292 | extern void
293 | mssty_iter_skip_ts(struct mssty_iter * const iter, const u32 nr);
294 |
295 | extern struct kv *
296 | mssty_iter_next_ts(struct mssty_iter * const iter, struct kv * const out);
297 |
298 | // dup iter: return all versions, including old keys and tombstones
299 | extern struct kv *
300 | mssty_iter_peek_dup(struct mssty_iter * const iter, struct kv * const out);
301 |
302 | extern void
303 | mssty_iter_skip1_dup(struct mssty_iter * const iter);
304 |
305 | extern void
306 | mssty_iter_skip_dup(struct mssty_iter * const iter, const u32 nr);
307 |
308 | extern struct kv *
309 | mssty_iter_next_dup(struct mssty_iter * const iter, struct kv * const out);
310 |
311 | extern bool
312 | mssty_iter_kref_dup(struct mssty_iter * const iter, struct kref * const kref);
313 |
314 | extern bool
315 | mssty_iter_kvref_dup(struct mssty_iter * const iter, struct kvref * const kvref);
316 |
317 | // mssty_get can return tombstone
318 | extern struct kv *
319 | mssty_get(struct mssty_ref * const ref, const struct kref * const key, struct kv * const out);
320 |
321 | // mssty_probe can return tombstone
322 | extern bool
323 | mssty_probe(struct mssty_ref * const ref, const struct kref * const key);
324 |
325 | // return NULL for tomestone
326 | extern struct kv *
327 | mssty_get_ts(struct mssty_ref * const ref, const struct kref * const key, struct kv * const out);
328 |
329 | // return false for tomestone
330 | extern bool
331 | mssty_probe_ts(struct mssty_ref * const ref, const struct kref * const key);
332 |
333 | extern bool
334 | mssty_get_value_ts(struct mssty_ref * const ref, const struct kref * const key,
335 | void * const vbuf_out, u32 * const vlen_out);
336 |
337 | extern struct kv *
338 | mssty_first(struct msst * const msst, struct kv * const out);
339 |
340 | extern struct kv *
341 | mssty_last(struct msst * const msst, struct kv * const out);
342 |
343 | extern void
344 | mssty_dump(struct msst * const msst, const char * const fn);
345 | // }}} mssty
346 |
347 | // build-ssty {{{
348 | // build extended metadata based on a set of sstables.
349 | // y0 and way0 are optional for speeding up the sorting
350 | extern u32
351 | ssty_build(const char * const dirname, struct msst * const msst,
352 | const u64 seq, const u32 way, struct msst * const y0, const u32 way0, const bool tags);
353 | // }}} build-ssty
354 |
355 | // msstv {{{
356 | struct msstv;
357 | struct msstv_iter;
358 | struct msstv_ref;
359 |
360 | extern struct msstv *
361 | msstv_create(const u64 nslots, const u64 version);
362 |
363 | extern void
364 | msstv_append(struct msstv * const v, struct msst * const msst, const struct kv * const anchor);
365 |
366 | extern void
367 | msstv_rcache(struct msstv * const v, struct rcache * const rc);
368 |
369 | extern void
370 | msstv_destroy(struct msstv * const v);
371 |
372 | extern struct msstv *
373 | msstv_open(const char * const dirname, const char * const filename);
374 |
375 | extern struct msstv *
376 | msstv_open_version(const char * const dirname, const u64 version);
377 |
378 | extern struct msstv_ref *
379 | msstv_ref(struct msstv * const v);
380 |
381 | extern struct msstv *
382 | msstv_unref(struct msstv_ref * const ref);
383 |
384 | extern struct kv *
385 | msstv_get(struct msstv_ref * const ref, const struct kref * const key, struct kv * const out);
386 |
387 | extern bool
388 | msstv_probe(struct msstv_ref * const ref, const struct kref * const key);
389 |
390 | // return NULL for tomestone
391 | extern struct kv *
392 | msstv_get_ts(struct msstv_ref * const ref, const struct kref * const key, struct kv * const out);
393 |
394 | // return false for tomestone
395 | extern bool
396 | msstv_probe_ts(struct msstv_ref * const ref, const struct kref * const key);
397 |
398 | extern bool
399 | msstv_get_value_ts(struct msstv_ref * const ref, const struct kref * const key,
400 | void * const vbuf_out, u32 * const vlen_out);
401 |
402 | extern struct msstv_iter *
403 | msstv_iter_create(struct msstv_ref * const ref);
404 |
405 | extern bool
406 | msstv_iter_valid(struct msstv_iter * const vi);
407 |
408 | extern void
409 | msstv_iter_seek(struct msstv_iter * const vi, const struct kref * const key);
410 |
411 | extern struct kv *
412 | msstv_iter_peek(struct msstv_iter * const vi, struct kv * const out);
413 |
414 | extern bool
415 | msstv_iter_kref(struct msstv_iter * const vi, struct kref * const kref);
416 |
417 | extern bool
418 | msstv_iter_kvref(struct msstv_iter * const vi, struct kvref * const kvref);
419 |
420 | extern u64
421 | msstv_iter_retain(struct msstv_iter * const vi);
422 |
423 | extern void
424 | msstv_iter_release(struct msstv_iter * const vi, const u64 opaque);
425 |
426 | extern void
427 | msstv_iter_skip1(struct msstv_iter * const vi);
428 |
429 | extern void
430 | msstv_iter_skip(struct msstv_iter * const vi, const u32 nr);
431 |
432 | extern struct kv *
433 | msstv_iter_next(struct msstv_iter * const vi, struct kv * const out);
434 |
435 | extern void
436 | msstv_iter_park(struct msstv_iter * const vi);
437 |
438 | extern bool
439 | msstv_iter_ts(struct msstv_iter * const vi);
440 |
441 | extern void
442 | msstv_iter_seek_ts(struct msstv_iter * const vi, const struct kref * const key);
443 |
444 | extern void
445 | msstv_iter_skip1_ts(struct msstv_iter * const vi);
446 |
447 | extern void
448 | msstv_iter_skip_ts(struct msstv_iter * const vi, const u32 nr);
449 |
450 | extern struct kv *
451 | msstv_iter_next_ts(struct msstv_iter * const vi, struct kv * const out);
452 |
453 | extern void
454 | msstv_fprint(struct msstv * const v, FILE * const out);
455 |
456 | extern void
457 | msstv_iter_destroy(struct msstv_iter * const vi);
458 |
459 | // UNSAFE!
460 | // return the anchors of msstv terminated with NULL
461 | // the returned pointer should be freed after use
462 | // must use when holding a msstv
463 | // anchor->vlen: 0: accepted; 1: rejected
464 | extern struct kv **
465 | msstv_anchors(struct msstv * const v);
466 | // }}} msstv
467 |
468 | // msstz {{{
469 | struct msstz;
470 |
471 | extern struct msstz *
472 | msstz_open(const char * const dirname, const u64 cache_size_mb, const bool ckeys, const bool tags);
473 |
474 | extern void
475 | msstz_destroy(struct msstz * const z);
476 |
477 | extern int
478 | msstz_logfd(struct msstz * const z);
479 |
480 | // return number of bytes written since opened
481 | extern u64
482 | msstz_stat_writes(struct msstz * const z);
483 |
484 | extern u64
485 | msstz_stat_reads(struct msstz * const z);
486 |
487 | // default is 0
488 | extern void
489 | msstz_set_minsz(struct msstz * const z, const u64 minsz);
490 |
491 | extern u64
492 | msstz_version(struct msstz * const z);
493 |
494 | extern struct msstv *
495 | msstz_getv(struct msstz * const z);
496 |
497 | extern void
498 | msstz_putv(struct msstz * const z, struct msstv * const v);
499 |
500 | typedef void (*msstz_range_cb)(void * priv, const bool accepted, const struct kv * k0, const struct kv * kz);
501 |
502 | extern void
503 | msstz_comp(struct msstz * const z, const struct kvmap_api * const api1, void * const map1,
504 | const u32 nr_workers, const u32 co_per_worker, const u64 max_reject);
505 | // }}} msstz
506 |
507 | // api {{{
508 | extern const struct kvmap_api kvmap_api_sst;
509 | extern const struct kvmap_api kvmap_api_msstx;
510 | extern const struct kvmap_api kvmap_api_mssty;
511 | extern const struct kvmap_api kvmap_api_mssty_ts;
512 | extern const struct kvmap_api kvmap_api_msstv;
513 | extern const struct kvmap_api kvmap_api_msstv_ts;
514 | // }}} api
515 |
516 | #ifdef __cplusplus
517 | }
518 | #endif
519 | // vim:fdm=marker
520 |
--------------------------------------------------------------------------------
/wh.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016--2021 Wu, Xingbo
3 | *
4 | * All rights reserved. No warranty, explicit or implicit, provided.
5 | */
6 | #pragma once
7 |
8 | #ifdef __cplusplus
9 | extern "C" {
10 | #endif
11 |
12 | struct wormhole;
13 | struct wormref;
14 |
15 | // wormhole {{{
16 | // the wh created by wormhole_create() can work with all of safe/unsafe operations.
17 | extern struct wormhole *
18 | wormhole_create(const struct kvmap_mm * const mm);
19 |
20 | // the wh created by whunsafe_create() can only work with the unsafe operations.
21 | extern struct wormhole *
22 | whunsafe_create(const struct kvmap_mm * const mm);
23 |
24 | extern struct kv *
25 | wormhole_get(struct wormref * const ref, const struct kref * const key, struct kv * const out);
26 |
27 | extern bool
28 | wormhole_probe(struct wormref * const ref, const struct kref * const key);
29 |
30 | extern bool
31 | wormhole_put(struct wormref * const ref, struct kv * const kv);
32 |
33 | extern bool
34 | wormhole_merge(struct wormref * const ref, const struct kref * const kref,
35 | kv_merge_func uf, void * const priv);
36 |
37 | extern bool
38 | wormhole_inpr(struct wormref * const ref, const struct kref * const key,
39 | kv_inp_func uf, void * const priv);
40 |
41 | extern bool
42 | wormhole_inpw(struct wormref * const ref, const struct kref * const key,
43 | kv_inp_func uf, void * const priv);
44 |
45 | extern bool
46 | wormhole_del(struct wormref * const ref, const struct kref * const key);
47 |
48 | extern u64
49 | wormhole_delr(struct wormref * const ref, const struct kref * const start,
50 | const struct kref * const end);
51 |
52 | extern struct wormhole_iter *
53 | wormhole_iter_create(struct wormref * const ref);
54 |
55 | extern void
56 | wormhole_iter_seek(struct wormhole_iter * const iter, const struct kref * const key);
57 |
58 | extern bool
59 | wormhole_iter_valid(struct wormhole_iter * const iter);
60 |
61 | extern struct kv *
62 | wormhole_iter_peek(struct wormhole_iter * const iter, struct kv * const out);
63 |
64 | extern bool
65 | wormhole_iter_kref(struct wormhole_iter * const iter, struct kref * const kref);
66 |
67 | extern bool
68 | wormhole_iter_kvref(struct wormhole_iter * const iter, struct kvref * const kvref);
69 |
70 | extern void
71 | wormhole_iter_skip1(struct wormhole_iter * const iter);
72 |
73 | extern void
74 | wormhole_iter_skip(struct wormhole_iter * const iter, const u32 nr);
75 |
76 | extern struct kv *
77 | wormhole_iter_next(struct wormhole_iter * const iter, struct kv * const out);
78 |
79 | extern bool
80 | wormhole_iter_inp(struct wormhole_iter * const iter, kv_inp_func uf, void * const priv);
81 |
82 | extern void
83 | wormhole_iter_park(struct wormhole_iter * const iter);
84 |
85 | extern void
86 | wormhole_iter_destroy(struct wormhole_iter * const iter);
87 |
88 | extern struct wormref *
89 | wormhole_ref(struct wormhole * const map);
90 |
91 | extern struct wormhole *
92 | wormhole_unref(struct wormref * const ref);
93 |
94 | extern void
95 | wormhole_park(struct wormref * const ref);
96 |
97 | extern void
98 | wormhole_resume(struct wormref * const ref);
99 |
100 | extern void
101 | wormhole_refresh_qstate(struct wormref * const ref);
102 |
103 | // clean with more threads
104 | extern void
105 | wormhole_clean_th(struct wormhole * const map, const u32 nr_threads);
106 |
107 | extern void
108 | wormhole_clean(struct wormhole * const map);
109 |
110 | extern void
111 | wormhole_destroy(struct wormhole * const map);
112 |
113 | // safe API (no need to refresh qstate)
114 |
115 | extern struct kv *
116 | whsafe_get(struct wormref * const ref, const struct kref * const key, struct kv * const out);
117 |
118 | extern bool
119 | whsafe_probe(struct wormref * const ref, const struct kref * const key);
120 |
121 | extern bool
122 | whsafe_put(struct wormref * const ref, struct kv * const kv);
123 |
124 | extern bool
125 | whsafe_merge(struct wormref * const ref, const struct kref * const kref,
126 | kv_merge_func uf, void * const priv);
127 |
128 | extern bool
129 | whsafe_inpr(struct wormref * const ref, const struct kref * const key,
130 | kv_inp_func uf, void * const priv);
131 |
132 | extern bool
133 | whsafe_inpw(struct wormref * const ref, const struct kref * const key,
134 | kv_inp_func uf, void * const priv);
135 |
136 | extern bool
137 | whsafe_del(struct wormref * const ref, const struct kref * const key);
138 |
139 | extern u64
140 | whsafe_delr(struct wormref * const ref, const struct kref * const start,
141 | const struct kref * const end);
142 |
143 | // use wormhole_iter_create
144 | extern void
145 | whsafe_iter_seek(struct wormhole_iter * const iter, const struct kref * const key);
146 |
147 | extern struct kv *
148 | whsafe_iter_peek(struct wormhole_iter * const iter, struct kv * const out);
149 |
150 | // use wormhole_iter_valid
151 | // use wormhole_iter_peek
152 | // use wormhole_iter_kref
153 | // use wormhole_iter_kvref
154 | // use wormhole_iter_skip1
155 | // use wormhole_iter_skip
156 | // use wormhole_iter_next
157 | // use wormhole_iter_inp
158 |
159 | extern void
160 | whsafe_iter_park(struct wormhole_iter * const iter);
161 |
162 | extern void
163 | whsafe_iter_destroy(struct wormhole_iter * const iter);
164 |
165 | extern struct wormref *
166 | whsafe_ref(struct wormhole * const map);
167 |
168 | // use wormhole_unref
169 |
170 | // unsafe API
171 |
172 | extern struct kv *
173 | whunsafe_get(struct wormhole * const map, const struct kref * const key, struct kv * const out);
174 |
175 | extern bool
176 | whunsafe_probe(struct wormhole * const map, const struct kref * const key);
177 |
178 | extern bool
179 | whunsafe_put(struct wormhole * const map, struct kv * const kv);
180 |
181 | extern bool
182 | whunsafe_merge(struct wormhole * const map, const struct kref * const kref,
183 | kv_merge_func uf, void * const priv);
184 |
185 | extern bool
186 | whunsafe_inp(struct wormhole * const map, const struct kref * const key,
187 | kv_inp_func uf, void * const priv);
188 |
189 | extern bool
190 | whunsafe_del(struct wormhole * const map, const struct kref * const key);
191 |
192 | extern u64
193 | whunsafe_delr(struct wormhole * const map, const struct kref * const start,
194 | const struct kref * const end);
195 |
196 | extern struct wormhole_iter *
197 | whunsafe_iter_create(struct wormhole * const map);
198 |
199 | extern void
200 | whunsafe_iter_seek(struct wormhole_iter * const iter, const struct kref * const key);
201 |
202 | // unsafe iter_valid: use wormhole_iter_valid
203 | // unsafe iter_peek: use wormhole_iter_peek
204 | // unsafe iter_kref: use wormhole_iter_kref
205 |
206 | extern void
207 | whunsafe_iter_skip1(struct wormhole_iter * const iter);
208 |
209 | extern void
210 | whunsafe_iter_skip(struct wormhole_iter * const iter, const u32 nr);
211 |
212 | extern struct kv *
213 | whunsafe_iter_next(struct wormhole_iter * const iter, struct kv * const out);
214 |
215 | // unsafe iter_inp: use wormhole_iter_inp
216 |
217 | extern void
218 | whunsafe_iter_destroy(struct wormhole_iter * const iter);
219 |
220 | extern void
221 | wormhole_fprint(struct wormhole * const map, FILE * const out);
222 |
223 | extern const struct kvmap_api kvmap_api_wormhole;
224 | extern const struct kvmap_api kvmap_api_whsafe;
225 | extern const struct kvmap_api kvmap_api_whunsafe;
226 | // }}} wormhole
227 |
228 | #ifdef __cplusplus
229 | }
230 | #endif
231 | // vim:fdm=marker
232 |
--------------------------------------------------------------------------------
/xdb.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016--2021 Wu, Xingbo
3 | *
4 | * All rights reserved. No warranty, explicit or implicit, provided.
5 | */
6 | #pragma once
7 |
8 | #include "lib.h"
9 | #include "kv.h"
10 |
11 | #ifdef __cplusplus
12 | extern "C" {
13 | #endif
14 |
15 | struct xdb;
16 | struct xdb_ref;
17 | struct xdb_iter;
18 |
19 | // xdb {{{
20 | extern struct xdb *
21 | xdb_open(const char * const dir, const size_t cache_size_mb, const size_t mt_size_mb, const size_t wal_size_mb,
22 | const bool ckeys, const bool tags, const u32 nr_workers, const u32 co_per_worker, const char * const worker_cores);
23 |
24 | extern void
25 | xdb_close(struct xdb * const xdb);
26 |
27 | // kvmap_api
28 | extern struct xdb_ref *
29 | xdb_ref(struct xdb * const xdb);
30 |
31 | extern struct xdb*
32 | xdb_unref(struct xdb_ref * const ref);
33 |
34 | extern struct kv *
35 | xdb_get(struct xdb_ref * const ref, const struct kref * const kref, struct kv * const out);
36 |
37 | extern bool
38 | xdb_probe(struct xdb_ref * const ref, const struct kref * const kref);
39 |
40 | extern bool
41 | xdb_put(struct xdb_ref * const ref, const struct kv * const kv);
42 |
43 | extern bool
44 | xdb_del(struct xdb_ref * const ref, const struct kref * const kref);
45 |
46 | extern void
47 | xdb_sync(struct xdb_ref * const ref);
48 |
49 | // AKA Atomic Read-Modify-Write
50 | // A merge can fail without doing anything due to allocate failures
51 | // uf() can be invoked multiple times due to abort and retry (these are not errors)
52 | // The last invocation will take the actual effect if it is successful
53 | // The returned kvs will be ignored except for the last one (returned by the last call to uf)
54 | // Memory allocated by uf must be freed by the caller after xdb_merge has returned
55 | // The uf can perform in-place update if kv0 is not NULL (just return kv0 from uf())
56 | // An in-place update may still cause an memtable insertion if kv0 was not from the memtable (loaded from a partition)
57 | extern bool
58 | xdb_merge(struct xdb_ref * const ref, const struct kref * const kref, kv_merge_func uf, void * const priv);
59 |
60 | // iter
61 | extern struct xdb_iter *
62 | xdb_iter_create(struct xdb_ref * const ref);
63 |
64 | extern void
65 | xdb_iter_park(struct xdb_iter * const iter);
66 |
67 | extern void
68 | xdb_iter_seek(struct xdb_iter * const iter, const struct kref * const key);
69 |
70 | extern bool
71 | xdb_iter_valid(struct xdb_iter * const iter);
72 |
73 | extern struct kv *
74 | xdb_iter_peek(struct xdb_iter * const iter, struct kv * const out);
75 |
76 | extern bool
77 | xdb_iter_kref(struct xdb_iter * const iter, struct kref * const kref);
78 |
79 | extern bool
80 | xdb_iter_kvref(struct xdb_iter * const iter, struct kvref * const kvref);
81 |
82 | extern void
83 | xdb_iter_skip1(struct xdb_iter * const iter);
84 |
85 | extern void
86 | xdb_iter_skip(struct xdb_iter * const iter, u32 n);
87 |
88 | extern struct kv*
89 | xdb_iter_next(struct xdb_iter * const iter, struct kv * const out);
90 |
91 | extern void
92 | xdb_iter_destroy(struct xdb_iter * const iter);
93 |
94 | extern const struct kvmap_api kvmap_api_xdb;
95 | // }}} xdb
96 |
97 | // remixdb {{{
98 | extern struct xdb *
99 | remixdb_open(const char * const dir, const size_t cache_size_mb, const size_t mt_size_mb, const bool tags);
100 |
101 | extern struct xdb *
102 | remixdb_open_compact(const char * const dir, const size_t cache_size_mb, const size_t mt_size_mb);
103 |
104 | extern struct xdb_ref *
105 | remixdb_ref(struct xdb * const xdb);
106 |
107 | extern void
108 | remixdb_unref(struct xdb_ref * const ref);
109 |
110 | extern void
111 | remixdb_close(struct xdb * const xdb);
112 |
113 | extern bool
114 | remixdb_put(struct xdb_ref * const ref, const void * const kbuf, const u32 klen,
115 | const void * const vbuf, const u32 vlen);
116 |
117 | extern bool
118 | remixdb_del(struct xdb_ref * const ref, const void * const kbuf, const u32 klen);
119 |
120 | extern bool
121 | remixdb_probe(struct xdb_ref * const ref, const void * const kbuf, const u32 klen);
122 |
123 | extern bool
124 | remixdb_get(struct xdb_ref * const ref, const void * const kbuf, const u32 klen,
125 | void * const vbuf_out, u32 * const vlen_out);
126 |
127 | extern void
128 | remixdb_sync(struct xdb_ref * const ref);
129 |
130 | extern struct xdb_iter *
131 | remixdb_iter_create(struct xdb_ref * const ref);
132 |
133 | extern void
134 | remixdb_iter_seek(struct xdb_iter * const iter, const void * const kbuf, const u32 klen);
135 |
136 | extern bool
137 | remixdb_iter_valid(struct xdb_iter * const iter);
138 |
139 | extern bool
140 | remixdb_iter_peek(struct xdb_iter * const iter,
141 | void * const kbuf_out, u32 * const klen_out,
142 | void * const vbuf_out, u32 * const vlen_out);
143 |
144 | extern void
145 | remixdb_iter_skip1(struct xdb_iter * const iter);
146 |
147 | extern void
148 | remixdb_iter_skip(struct xdb_iter * const iter, const u32 nr);
149 |
150 | extern void
151 | remixdb_iter_park(struct xdb_iter * const iter);
152 |
153 | extern void
154 | remixdb_iter_destroy(struct xdb_iter * const iter);
155 | // }}} remixdb
156 |
157 | #ifdef __cplusplus
158 | }
159 | #endif
160 | // vim:fdm=marker
161 |
--------------------------------------------------------------------------------
/xdb.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | #
4 | # Copyright (c) 2016--2021 Wu, Xingbo
5 | #
6 | # All rights reserved. No warranty, explicit or implicit, provided.
7 | #
8 |
9 | import msgpack
10 | from ctypes import * # CDLL and c_xxx types
11 |
12 | # libxdb {{{
13 | # Change this path when necessary
14 | libxdb = CDLL("./libremixdb.so")
15 |
16 | # open
17 | # dir, cachesz, mtsz, tags -> xdbptr
18 | libxdb.remixdb_open.argtypes = [c_char_p, c_uint, c_uint, c_bool]
19 | libxdb.remixdb_open.restype = c_void_p
20 |
21 | # close (no return value)
22 | libxdb.remixdb_close.argtypes = [c_void_p]
23 |
24 | # ref
25 | libxdb.remixdb_ref.argtypes = [c_void_p]
26 | libxdb.remixdb_ref.restype = c_void_p
27 |
28 | # unref
29 | libxdb.remixdb_unref.argtypes = [c_void_p]
30 |
31 | # put
32 | # xdbptr, keyptr, keylen, vptr, vlen -> bool
33 | libxdb.remixdb_put.argtypes = [c_void_p, c_char_p, c_uint, c_char_p, c_uint]
34 | libxdb.remixdb_put.restype = c_bool
35 |
36 | # get
37 | # xdbptr, keyptr, keylen, vptr_out, vlen_out -> bool
38 | libxdb.remixdb_get.argtypes = [c_void_p, c_char_p, c_uint, c_char_p, c_void_p]
39 | libxdb.remixdb_get.restype = c_bool
40 |
41 | # probe
42 | libxdb.remixdb_probe.argtypes = [c_void_p, c_char_p, c_uint]
43 | libxdb.remixdb_probe.restype = c_bool
44 |
45 | # del
46 | libxdb.remixdb_del.argtypes = [c_void_p, c_char_p, c_uint]
47 | libxdb.remixdb_del.restype = c_bool
48 |
49 | # sync
50 | libxdb.remixdb_sync.argtypes = [c_void_p]
51 |
52 | # iter_create
53 | libxdb.remixdb_iter_create.argtypes = [c_void_p]
54 | libxdb.remixdb_iter_create.restype = c_void_p
55 |
56 | # iter_seek
57 | libxdb.remixdb_iter_seek.argtypes = [c_void_p, c_char_p, c_uint]
58 |
59 | # iter_valid
60 | libxdb.remixdb_iter_valid.argtypes = [c_void_p]
61 | libxdb.remixdb_iter_valid.restype = c_bool
62 |
63 | # iter_skip1
64 | libxdb.remixdb_iter_skip1.argtypes = [c_void_p]
65 |
66 | # iter_skip
67 | libxdb.remixdb_iter_skip.argtypes = [c_void_p, c_uint]
68 |
69 | # iter_peek
70 | libxdb.remixdb_iter_peek.argtypes = [c_void_p, c_char_p, c_void_p, c_char_p, c_void_p]
71 | libxdb.remixdb_iter_peek.restype = c_bool
72 |
73 | # iter_destroy
74 | libxdb.remixdb_iter_destroy.argtypes = [c_void_p]
75 | # }}} libxdb
76 |
77 | # class {{{
78 | class Xdb:
79 | def __init__(self, dirname, cachesz=256, mtsz=256, tags=True):
80 | self.xdbptr = libxdb.remixdb_open(dirname.encode('ascii'), c_uint(cachesz), c_uint(mtsz), c_bool(tags))
81 |
82 | # user must call explicitly
83 | def close(self):
84 | libxdb.remixdb_close(self.xdbptr)
85 |
86 | def ref(self):
87 | return XdbRef(self.xdbptr)
88 |
89 | class XdbRef:
90 | # use xdb.ref()
91 | def __init__(self, xdbptr):
92 | self.refptr = libxdb.remixdb_ref(xdbptr)
93 | self.vbuf = create_string_buffer(65500)
94 |
95 | # user must call explicitly
96 | def unref(self):
97 | libxdb.remixdb_unref(self.refptr)
98 |
99 | def iter(self):
100 | return XdbIter(self.refptr)
101 |
102 | # key: python string; value: any (hierarchical) python object
103 | def put(self, key, value):
104 | binkey = key.encode()
105 | binvalue = msgpack.packb(value)
106 | print(key, msgpack.unpackb(binvalue), len(binvalue))
107 |
108 | return libxdb.remixdb_put(self.refptr, binkey, c_uint(len(binkey)), binvalue, c_uint(len(binvalue)))
109 |
110 |
111 | # return the value as a python object
112 | def get(self, key):
113 | binkey = key.encode()
114 | vlen = c_uint()
115 | ret = libxdb.remixdb_get(self.refptr, binkey, len(binkey), self.vbuf, byref(vlen))
116 | if ret:
117 | #vbuf[vlen.value] = b'\x00'
118 | return msgpack.unpackb(self.vbuf.value)
119 | else:
120 | return None
121 |
122 | def delete(self, key):
123 | binkey = key.encode()
124 | return libxdb.remixdb_del(self.refptr, binkey, c_uint(len(binkey)))
125 |
126 | def probe(self, key):
127 | binkey = key.encode()
128 | return libxdb.remixdb_probe(self.refptr, binkey, c_uint(len(binkey)))
129 |
130 | def sync(self):
131 | return libxdb.remixdb_sync(self.refptr)
132 |
133 | class XdbIter:
134 | def __init__(self, refptr):
135 | self.iptr = libxdb.remixdb_iter_create(refptr)
136 | self.kbuf = create_string_buffer(65500)
137 | self.vbuf = create_string_buffer(65500)
138 |
139 | # user must call explicitly
140 | def destroy(self):
141 | libxdb.remixdb_iter_destroy(self.iptr)
142 |
143 | def seek(self, key):
144 | if key is None:
145 | libxdb.remixdb_iter_seek(self.iptr, None, c_uint(0))
146 | else:
147 | binkey = key.encode()
148 | libxdb.remixdb_iter_seek(self.iptr, binkey, c_uint(len(binkey)))
149 |
150 | def valid(self):
151 | return libxdb.remixdb_iter_valid(self.iptr)
152 |
153 | def skip1(self):
154 | libxdb.remixdb_iter_skip1(self.iptr)
155 |
156 | def skip(self, nr):
157 | libxdb.remixdb_iter_skip(self.iptr, c_uint(nr))
158 |
159 | # return (key, value) pair or None
160 | def peek(self):
161 | klen = c_uint()
162 | vlen = c_uint()
163 | if libxdb.remixdb_iter_peek(self.iptr, self.kbuf, byref(klen), self.vbuf, byref(vlen)):
164 | self.kbuf[klen.value] = b'\x00'
165 | #vbuf[vlen.value] = b'\x00'
166 | return (self.kbuf.value.decode(), klen.value, msgpack.unpackb(self.vbuf.value), vlen.value)
167 | else:
168 | return None
169 |
170 | # }}} class
171 |
172 | # examples
173 | xdb1 = Xdb("/tmp/pyxdb") # change this path when necessary
174 | ref1 = xdb1.ref() # take a ref for kv operations
175 |
176 | ref1.put("Hello", "pyxdb")
177 | ref1.put("key1", "value1")
178 | ref1.put("key2", "value2")
179 | ref1.put("key3", {"xxx":"valuex", "yyy":"valuey"})
180 | ref1.delete("key2")
181 |
182 | rget = ref1.get("Hello")
183 | print(rget)
184 |
185 | # don't use ref when iterating
186 | iter1 = ref1.iter()
187 | iter1.seek(None)
188 | while iter1.valid():
189 | r = iter1.peek()
190 | print(r)
191 | iter1.skip1()
192 |
193 | iter1.destroy() # must destroy all iters before unref
194 |
195 | ref1.sync()
196 | ref1.unref() # must unref all refs before close()
197 | xdb1.close()
198 |
199 | # vim:fdm=marker
200 |
--------------------------------------------------------------------------------
/xdbcow.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # This script performs a naive COW copy of an xdb directory
4 | # orig and dest must be in the same file system that supports hard links
5 | # The table files will be duplicated using hard links without copying
6 | # the WAL files are really copied because they are mutable
7 |
8 | if [[ $# -lt 2 ]]; then
9 | echo "usage: "
10 | exit 0
11 | fi
12 |
13 | orig=${1} dest=${2}
14 |
15 | if [[ ! -d ${orig} || ! -h ${orig}/HEAD ]]; then
16 | echo "${orig}/HEAD is not a symbolic link"
17 | exit 0
18 | fi
19 |
20 | if [[ -d ${dest} ]]; then
21 | echo "${dest} already exists; must use a non-existing path"
22 | exit 0
23 | fi
24 |
25 | mkdir -p ${dest}
26 | if [[ ! -d ${dest} ]]; then
27 | echo "creating ${dest} failed"
28 | exit 0
29 | fi
30 |
31 | # hardlinks for immutable files
32 | cp -l ${orig}/*.sstx ${orig}/*.ssty ${orig}/*.ver ${dest}/
33 |
34 | # duplicate softlinks HEAD and HEAD1 (pointing to a *.ver)
35 | cp -a ${orig}/HEAD ${dest}/HEAD
36 | cp -a ${orig}/HEAD1 ${dest}/HEAD1
37 |
38 | # really copy wals
39 | cp ${orig}/wal1 ${orig}/wal2 ${dest}/
40 |
--------------------------------------------------------------------------------
/xdbdemo.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2021 Wu, Xingbo
3 | *
4 | * All rights reserved. No warranty, explicit or implicit, provided.
5 | */
6 | #define _GNU_SOURCE
7 |
8 | #include
9 |
10 | #include "lib.h"
11 | #include "kv.h"
12 | #include "xdb.h"
13 |
14 | int
15 | main(int argc, char ** argv)
16 | {
17 | (void)argc;
18 | (void)argv;
19 | // Use a small config for demo
20 | // In a moderate setup the recommended numbers are 4096 for both
21 | struct xdb * const xdb = remixdb_open("./xdbdemo", 256, 256, true); // blockcache=256MB, MemTable=256MB, use_tags=true
22 |
23 | // A ref is required to perform the following DB operations.
24 | // A thread should maintain a ref and keep using it.
25 | // Different threads should use different refs.
26 | struct xdb_ref * const ref = remixdb_ref(xdb);
27 |
28 | bool r;
29 |
30 | r = remixdb_put(ref, "remix", 5, "easy", 4);
31 | printf("remixdb_put remix easy %c\n", r?'T':'F');
32 |
33 | r = remixdb_put(ref, "time_travel", 11, "impossible", 10);
34 | printf("remixdb_put time_travel impossible %c\n", r?'T':'F');
35 |
36 | r = remixdb_del(ref, "time_travel", 11);
37 | printf("remixdb_del time_travel %c\n", r?'T':'F');
38 |
39 | r = remixdb_probe(ref, "time_travel", 11);
40 | printf("remixdb_probe time_travel %c\n", r?'T':'F');
41 |
42 | u32 klen_out = 0;
43 | char kbuf_out[8] = {};
44 | u32 vlen_out = 0;
45 | char vbuf_out[8] = {};
46 | r = remixdb_get(ref, "remix", 5, vbuf_out, &vlen_out);
47 | printf("remixdb_get remix %c %u %.*s\n", r?'T':'F', vlen_out, vlen_out, vbuf_out);
48 |
49 | // prepare a few keys for range ops
50 | remixdb_put(ref, "00", 2, "0_value", 7);
51 | remixdb_put(ref, "11", 2, "1_value", 7);
52 | remixdb_put(ref, "22", 2, "2_value", 7);
53 |
54 | // Make all the data persistent in the log.
55 | // Performing sync is expensive.
56 | remixdb_sync(ref);
57 |
58 | // range operations
59 | struct xdb_iter * const iter = remixdb_iter_create(ref);
60 |
61 | printf("remixdb_iter_seek \"\" (zero-length string)\n");
62 | remixdb_iter_seek(iter, NULL, 0); // seek to the first key
63 | // You can actually insert an zero-size key to the store. (0 <= klen, klen+vlen <= 65500)
64 |
65 | while (remixdb_iter_valid(iter)) { // check whether the iter points to a valid KV pair
66 | r = remixdb_iter_peek(iter, kbuf_out, &klen_out, vbuf_out, &vlen_out);
67 | if (r) {
68 | printf("remixdb_iter_peek klen=%u key=%.*s vlen=%u value=%.*s\n",
69 | klen_out, klen_out, kbuf_out, vlen_out, vlen_out, vbuf_out);
70 | } else {
71 | printf("ERROR!\n");
72 | }
73 | remixdb_iter_skip1(iter);
74 | }
75 |
76 | // This is OPTIONAL!
77 | // an iter can hold some (reader) locks.
78 | // Other (writer) threads can be blocked by active iters.
79 | // call iter_park to release those resources when you need to go idle
80 | // don't need to call iter_park if you're actively using the iter
81 | remixdb_iter_park(iter);
82 | usleep(10);
83 |
84 | // after calling iter_park, you must perform a seek() to proceed with other operations.
85 | printf("remixdb_iter_seek \"0\" (key_length=1)\n");
86 | remixdb_iter_seek(iter, "0", 1);
87 | // this time we don't want to copy the value
88 | r = remixdb_iter_peek(iter, kbuf_out, &klen_out, NULL, NULL);
89 | if (r){
90 | printf("remixdb_iter_peek klen=%u key=%.*s\n", klen_out, klen_out, kbuf_out);
91 | } else {
92 | printf("ERROR: iter_peek failed\n");
93 | }
94 |
95 | remixdb_iter_destroy(iter);
96 | // there must be no active iters when we call unref()
97 | remixdb_unref(ref);
98 |
99 | // close is not thread-safe
100 | // other threads must have released their references when you call close()
101 | remixdb_close(xdb);
102 | return 0;
103 | }
104 |
--------------------------------------------------------------------------------
/xdbexit.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016--2021 Wu, Xingbo
3 | *
4 | * All rights reserved. No warranty, explicit or implicit, provided.
5 | */
6 | #define _GNU_SOURCE
7 |
8 | #include "lib.h"
9 | #include "kv.h"
10 | #include "sst.h"
11 | #include "xdb.h"
12 |
13 | int
14 | main(int argc, char** argv)
15 | {
16 | if (argc < 4) {
17 | printf("Usage: \n");
18 | return 0;
19 | }
20 |
21 | struct xdb * const xdb = remixdb_open(argv[1], a2u64(argv[2]), a2u64(argv[3]), true);
22 | if (!xdb) {
23 | fprintf(stderr, "xdb_open failed\n");
24 | return 0;
25 | }
26 | struct xdb_ref * const ref = remixdb_ref(xdb);
27 |
28 | struct xdb_iter * const iter = remixdb_iter_create(ref);
29 | u64 kid = 0;
30 | remixdb_iter_seek(iter, "", 0);
31 | remixdb_iter_skip(iter, 1000);
32 | u8 key[20];
33 | u8 keycmp[20];
34 | u32 klen = 0;
35 | while (remixdb_iter_valid(iter)) {
36 | kid += 1000;
37 | remixdb_iter_peek(iter, key, &klen, NULL, NULL);
38 | strdec_64(keycmp, kid);
39 | if (memcmp(key, keycmp, 20)) {
40 | printf("key mismatch at %lu; delete %s and restart the loop\n", kid, argv[1]);
41 | exit(0);
42 | }
43 | remixdb_iter_skip(iter, 1000);
44 | }
45 |
46 | u64 count = kid;
47 | remixdb_iter_seek(iter, "", 0);
48 | remixdb_iter_skip(iter, kid);
49 | while (remixdb_iter_valid(iter)) {
50 | remixdb_iter_peek(iter, key, &klen, NULL, NULL);
51 | remixdb_iter_skip1(iter);
52 | strdec_64(keycmp, count);
53 | count++;
54 | if (memcmp(key, keycmp, 20)) {
55 | printf("key mismatch at %lu; delete %s and restart loop again\n", count, argv[1]);
56 | exit(0);
57 | }
58 | }
59 | printf("found %lu keys, last %.20s OK\n", count, key);
60 | remixdb_iter_destroy(iter);
61 |
62 | u8 value[1024];
63 | memset(value, 0x11, 1024);
64 | #define NEW ((100000))
65 | for (u64 i = 0; i < NEW; i++) {
66 | strdec_64(key, count + i);
67 | remixdb_put(ref, key, 20, value, 1024);
68 | }
69 | printf("insert [%lu, %lu]; now exit()\n", count, count + NEW - 1);
70 | remixdb_sync(ref);
71 | exit(0);
72 | return 0;
73 | }
74 |
--------------------------------------------------------------------------------
/xdbtest.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016--2021 Wu, Xingbo
3 | *
4 | * All rights reserved. No warranty, explicit or implicit, provided.
5 | */
6 | #define _GNU_SOURCE
7 |
8 | #include "ctypes.h"
9 | #include "lib.h"
10 | #include "kv.h"
11 | #include "sst.h"
12 | #include "xdb.h"
13 |
14 | struct xdb * xdb;
15 | static u64 nkeys = 0;
16 | static u64 nupdate = 0;
17 | static u64 min_stale = 0;
18 | static u8 * magics = NULL;
19 | u32 nths_update = 0;
20 | u32 nths_getscan = 0;
21 |
22 | au64 all_seq;
23 | au64 all_stale;
24 | au64 all_found;
25 |
26 | static void *
27 | update_worker(void * const ptr)
28 | {
29 | (void)ptr;
30 | srandom_u64(time_nsec());
31 | const u64 seq = atomic_fetch_add(&all_seq, 1);
32 | const u64 range = nkeys / nths_update;
33 | const u64 mask = range - 1;
34 | const u64 base = seq * range;
35 | struct xdb_ref * const ref = remixdb_ref(xdb);
36 | u8 ktmp[16];
37 | u8 * const vtmp = calloc(1, 1lu << 16);
38 | memset(vtmp, (int)random_u64(), 1lu << 16);
39 |
40 | //printf("random update [%lu, %lu]\n", base, base+mask);
41 | // set/del
42 | for (u64 i = 0; i < nupdate; i++) {
43 | const u64 r = random_u64();
44 | const u64 k = base + ((r >> 8) & mask);
45 | const u8 v = r & 0xff;
46 | vtmp[0] = v;
47 | magics[k] = v;
48 | strhex_64(ktmp, k);
49 |
50 | if (v == 0) { // delete
51 | remixdb_del(ref, ktmp, 16);
52 | } else { // update
53 | const u32 vlen = ((i & 0x3fffu) != 0x1357u) ? (((u32)r & 0xf0) + 100) : ((((u32)r & 0xf0) << 6) + 4200);
54 | remixdb_put(ref, ktmp, 16, vtmp, vlen);
55 | }
56 | }
57 |
58 | remixdb_unref(ref);
59 | free(vtmp);
60 | return NULL;
61 | }
62 |
63 | static void *
64 | getscan_worker(void * const ptr)
65 | {
66 | (void)ptr;
67 | const u64 seq = atomic_fetch_add(&all_seq, 1);
68 | const u64 unit = nkeys / nths_getscan + 1;
69 | const u64 min = unit * seq;
70 | const u64 max0 = min + unit;
71 | const u64 max = nkeys < max0 ? nkeys : max0;
72 |
73 | struct xdb_ref * const ref = remixdb_ref(xdb);
74 |
75 | u8 ktmp[16];
76 | u8 * const out = calloc(1, 1lu << 16);
77 | u32 vlen_out = 0;
78 |
79 | // get seq
80 | u64 stale = 0;
81 | for (u64 i = min; i < max; i++) {
82 | strhex_64(ktmp, i);
83 | const bool r = remixdb_get(ref, ktmp, 16, out, &vlen_out);
84 | if ((r ? out[0] : 0) != magics[i])
85 | stale++;
86 | }
87 |
88 | u32 klen_out;
89 | u8 kend[16];
90 | strhex_64(ktmp, min);
91 | strhex_64(kend, max);
92 | struct xdb_iter * const iter = remixdb_iter_create(ref);
93 | remixdb_iter_seek(iter, ktmp, 16);
94 | memset(ktmp, 0, 16);
95 |
96 | // scan
97 | u64 found = 0;
98 | while (remixdb_iter_valid(iter)) {
99 | remixdb_iter_peek(iter, ktmp, &klen_out, NULL, NULL);
100 | debug_assert(klen_out == 16);
101 | if (memcmp(ktmp, kend, 16) < 0) {
102 | found++;
103 | remixdb_iter_skip1(iter);
104 | } else {
105 | break;
106 | }
107 | }
108 |
109 | //printf("get [%lu, %lu] stale %lu found %lu\n", min, max-1, stale, found);
110 | atomic_fetch_add(&all_stale, stale);
111 | atomic_fetch_add(&all_found, found);
112 |
113 | remixdb_iter_destroy(iter);
114 | remixdb_unref(ref);
115 | free(out);
116 | return NULL;
117 | }
118 |
119 | int
120 | main(int argc, char** argv)
121 | {
122 | if (argc < 6) {
123 | printf("Usage: []\n");
124 | printf(" WAL size = *2\n");
125 | return 0;
126 | }
127 |
128 | const u32 ncores = process_affinity_count();
129 | if (ncores < 5) {
130 | fprintf(stderr, "Need at least five cores on the cpu affinity list\n");
131 | exit(0);
132 | }
133 |
134 | const u64 cachesz = a2u64(argv[2]);
135 | const u64 mtsz = a2u64(argv[3]);
136 | const u64 dpower = a2u64(argv[4]);
137 | const u64 upower = a2u64(argv[5]);
138 |
139 | xdb = remixdb_open(argv[1], cachesz, mtsz, true);
140 | if (!xdb) {
141 | fprintf(stderr, "xdb_open failed\n");
142 | return 0;
143 | }
144 |
145 | nkeys = 1lu << dpower;
146 | if (nkeys < 1024)
147 | nkeys = 1024;
148 | nupdate = 1lu << upower;
149 |
150 | min_stale = nkeys;
151 | magics = calloc(nkeys, 1);
152 | nths_getscan = ncores - 4;
153 | nths_update = ncores - 4;
154 |
155 | while (__builtin_popcount(nths_update) > 1)
156 | nths_update--;
157 | printf("write threads %u check threads %u\n", nths_update, nths_getscan);
158 |
159 | debug_assert(magics);
160 | const u32 ne = (argc < 7) ? 1000000 : a2u32(argv[6]);
161 |
162 | for (u32 e = 0; e < ne; e++) {
163 | all_seq = 0;
164 | const u64 dt = thread_fork_join(nths_update, update_worker, false, NULL);
165 | if ((e & 0x3u) == 0x3u) { // close/open every 4 epochs
166 | remixdb_close(xdb);
167 | // turn on/off ckeys alternatively, very stressful.
168 | xdb = (e & 4) ? remixdb_open(argv[1], cachesz, mtsz, (e & 8) != 0) : remixdb_open_compact(argv[1], cachesz, mtsz);
169 | if (xdb) {
170 | printf("reopen remixdb ok\n");
171 | } else {
172 | printf("reopen failed\n");
173 | exit(0);
174 | }
175 | }
176 | all_stale = 0;
177 | all_found = 0;
178 | all_seq = 0;
179 | (void)thread_fork_join(nths_getscan, getscan_worker, false, NULL);
180 |
181 | char ts[64];
182 | time_stamp(ts, sizeof(ts));
183 | const u64 nr = nupdate * nths_update;
184 | printf("[%4u] %s put/del nr %lu mops %.3lf keyrange %lu keycount %lu stale %lu\n",
185 | e, ts, nr, (double)nr / (double)dt * 1e3, nkeys, all_found, all_stale);
186 |
187 | if (all_stale > min_stale)
188 | debug_die();
189 | min_stale = all_stale;
190 | }
191 | free(magics);
192 | remixdb_close(xdb);
193 | return 0;
194 | }
195 |
--------------------------------------------------------------------------------