summaryrefslogtreecommitdiff
path: root/winhelp.h
blob: d0c81d562ba18859a4471ab3851caa820c2e9ff2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
/*
 * winhelp.h   header file for winhelp.c
 */

typedef struct WHLP_tag *WHLP;

typedef struct WHLP_TOPIC_tag *WHLP_TOPIC;

/*
 * Initialise a new WHlp context and begin accumulating data in it.
 */
WHLP whlp_new(void);

/*
 * Close a WHlp context and write out the help file it has created.
 */
void whlp_close(WHLP h, char *filename);

/*
 * Abandon and free a WHlp context without writing out anything.
 */
void whlp_abandon(WHLP h);

/*
 * Specify the title and copyright notice of a help file. Also
 * specify Help macros to be run on loading.
 */
void whlp_title(WHLP h, char *title);
void whlp_copyright(WHLP h, char *copyright);
void whlp_start_macro(WHLP h, char *macro);

/*
 * Register a help topic. Irritatingly, due to weird phase-order
 * issues with the whole file format, you have to register all your
 * topics _before_ actually outputting your text. This seems likely
 * to require two passes over the source document.
 * 
 * If you want to specify a particular context string (for
 * reference from other programs, to provide context-sensitive
 * help), you can supply it here. Otherwise, just pass NULL and a
 * nondescript one will be allocated automatically.
 *
 * If you specify two context strings which clash under the Windows
 * help file hash algorithm, this function will return NULL and
 * provide a pointer to the other context string that this one
 * clashed with, and you must tell your user to fix the clash.
 * Sadly this is the only way to do it; despite HLP files having a
 * perfectly good method of mapping arbitrary strings to things,
 * they didn't see fit to use that method for help contexts, so
 * instead they hash the context names and expect the hashes to be
 * unique. Sigh.
 * 
 * On success (i.e. in any circumstance other than a hash clash), a
 * valid WHLP_TOPIC is returned for later use.
 */
WHLP_TOPIC whlp_register_topic(WHLP h, char *context_name, char **clash);

/*
 * Link two topics together in a browse sequence. Automatically
 * takes care of the forward and reverse links.
 */
void whlp_browse_link(WHLP h, WHLP_TOPIC before, WHLP_TOPIC after);

/*
 * After calling whlp_register_topic for all topics, you should
 * call this, which will sort out all loose ends and allocate
 * context names for all anonymous topics. Then you can start
 * writing actual text.
 */
void whlp_prepare(WHLP h);

/*
 * Create a link from an index term to a topic.
 */
void whlp_index_term(WHLP h, char *index, WHLP_TOPIC topic);

/*
 * Call this if you need the id of a topic and you don't already
 * know it (for example, if whlp_prepare has allocated it
 * anonymously for you). You might need this, for example, in
 * creating macros for button-bar bindings.
 * 
 * The string returned will be freed when the WHLP context is
 * closed. You should not free it yourself.
 * 
 * Do not call this before calling whlp_prepare().
 */
char *whlp_topic_id(WHLP_TOPIC topic);

/*
 * Call this to specify which help topic will be the first one
 * displayed when the help file is loaded.
 */
void whlp_primary_topic(WHLP h, WHLP_TOPIC topic);

/*
 * Call this when about to begin writing out the text for a topic.
 * 
 * Any additional arguments are Help macros, terminated with a
 * NULL. So the minimum call sequence is
 * 
 *   whlp_begin_topic(helpfile, mytopic, "Title", NULL);
 */
void whlp_begin_topic(WHLP h, WHLP_TOPIC topic, char *title, ...);

/*
 * Call this to set up a font descriptor. You supply the font name,
 * the font size (in half-points), the graphic rendition flags
 * (bold, italic etc), and the general font family (for Windows to
 * select a fallback font if yours is unavailable). You can also
 * specify a foreground colour for the text (but unfortunately not
 * a background).
 * 
 * Font descriptors are identified in whlp_set_font() by small
 * integers, which are allocated from 0 upwards in the order you
 * call whlp_create_font(). For your convenience,
 * whlp_create_font() returns the integer allocated to each font
 * descriptor you create, but you could work this out just as
 * easily yourself by counting.
 */
enum {
    WHLP_FONT_BOLD = 1,
    WHLP_FONT_ITALIC = 2,
    WHLP_FONT_UNDERLINE = 4,
    WHLP_FONT_STRIKEOUT = 8,
    WHLP_FONT_DOUBLEUND = 16,
    WHLP_FONT_SMALLCAPS = 32
};
enum {
    WHLP_FONTFAM_FIXED = 1,
    WHLP_FONTFAM_SERIF = 2,
    WHLP_FONTFAM_SANS = 3,
    WHLP_FONTFAM_SCRIPT = 4,
    WHLP_FONTFAM_DECOR = 5
};
int whlp_create_font(WHLP h, char *font, int family, int halfpoints,
		     int rendition, int r, int g, int b);

/*
 * Routines to output paragraphs and actual text (at last).
 * 
 * You should start by calling whlp_para_attr() to set any
 * paragraph attributes that differ from the standard settings.
 * Next call whlp_begin_para() to start the paragraph. Then call
 * the various in-paragraph functions until you have output the
 * whole paragraph, and finally call whlp_end_para() to finish it
 * off.
 */
enum {
    WHLP_PARA_SPACEABOVE=1, WHLP_PARA_SPACEBELOW, WHLP_PARA_SPACELINES,
    WHLP_PARA_LEFTINDENT, WHLP_PARA_RIGHTINDENT, WHLP_PARA_FIRSTLINEINDENT,
    WHLP_PARA_ALIGNMENT
};
enum {
    WHLP_ALIGN_LEFT, WHLP_ALIGN_RIGHT, WHLP_ALIGN_CENTRE
};
enum {
    WHLP_PARA_SCROLL, WHLP_PARA_NONSCROLL
};
void whlp_para_attr(WHLP h, int attr_id, int attr_param);
void whlp_set_tabstop(WHLP h, int tabstop, int alignment);
void whlp_begin_para(WHLP h, int para_type);
void whlp_end_para(WHLP h);
void whlp_set_font(WHLP h, int font_id);
void whlp_text(WHLP h, char *text);
void whlp_start_hyperlink(WHLP h, WHLP_TOPIC target);
void whlp_end_hyperlink(WHLP h);
void whlp_tab(WHLP h);
href='#n589'>589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * Copyright (C) 2007 Nicolas Pennequin
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/
#include "config.h"
#include <string.h>
#include "strlcpy.h"
#include "system.h"
#include "storage.h"
#include "thread.h"
#include "kernel.h"
#include "panic.h"
#include "debug.h"
#include "file.h"
#include "appevents.h"
#include "metadata.h"
#include "bmp.h"
#ifdef HAVE_ALBUMART
#include "albumart.h"
#include "jpeg_load.h"
#include "playback.h"
#endif
#include "buffering.h"

/* Define LOGF_ENABLE to enable logf output in this file */
/* #define LOGF_ENABLE */
#include "logf.h"

/* macros to enable logf for queues
   logging on SYS_TIMEOUT can be disabled */
#ifdef SIMULATOR
/* Define this for logf output of all queuing except SYS_TIMEOUT */
#define BUFFERING_LOGQUEUES
/* Define this to logf SYS_TIMEOUT messages */
/* #define BUFFERING_LOGQUEUES_SYS_TIMEOUT */
#endif

#ifdef BUFFERING_LOGQUEUES
#define LOGFQUEUE logf
#else
#define LOGFQUEUE(...)
#endif

#ifdef BUFFERING_LOGQUEUES_SYS_TIMEOUT
#define LOGFQUEUE_SYS_TIMEOUT logf
#else
#define LOGFQUEUE_SYS_TIMEOUT(...)
#endif

#define GUARD_BUFSIZE   (32*1024)

/* amount of data to read in one read() call */
#define BUFFERING_DEFAULT_FILECHUNK      (1024*32)

#define BUF_HANDLE_MASK                  0x7FFFFFFF

enum handle_flags
{
    H_CANWRAP   = 0x1,   /* Handle data may wrap in buffer */
    H_ALLOCALL  = 0x2,   /* All data must be allocated up front */
    H_FIXEDDATA = 0x4,   /* Data is fixed in position */
};

struct memory_handle {
    int     id;             /* A unique ID for the handle */
    enum data_type type;    /* Type of data buffered with this handle */
    uint8_t flags;          /* Handle property flags */
    int8_t  pinned;         /* Count of pinnings */
    int8_t  signaled;       /* Stop any attempt at waiting to get the data */
    char    path[MAX_PATH]; /* Path if data originated in a file */
    int     fd;             /* File descriptor to path (-1 if closed) */
    size_t  data;           /* Start index of the handle's data buffer */
    size_t  ridx;           /* Read pointer, relative to the main buffer */
    size_t  widx;           /* Write pointer, relative to the main buffer */
    ssize_t filesize;       /* File total length */
    off_t   start;          /* Offset at which we started reading the file */
    off_t   pos;            /* Read position in file */
    off_t volatile end;     /* Offset at which we stopped reading the file */
    struct memory_handle *next;
};

struct buf_message_data
{
    int handle_id;
    intptr_t data;
};

static char *buffer;
static char *guard_buffer;

static size_t buffer_len;

/* Configuration */
static size_t conf_watermark = 0; /* Level to trigger filebuf fill */
static size_t high_watermark = 0; /* High watermark for rebuffer */

/* current memory handle in the linked list. NULL when the list is empty. */
static struct memory_handle *cur_handle;
/* first memory handle in the linked list. NULL when the list is empty. */
static struct memory_handle *first_handle;

static int num_handles;  /* number of handles in the list */

static int base_handle_id;

/* Main lock for adding / removing handles */
static struct mutex llist_mutex SHAREDBSS_ATTR;

/* Handle cache (makes find_handle faster).
   This is global so that move_handle and rm_handle can invalidate it. */
static struct memory_handle *cached_handle = NULL;

static struct data_counters
{
    size_t remaining;   /* Amount of data needing to be buffered */
    size_t buffered;    /* Amount of data currently in the buffer */
    size_t useful;      /* Amount of data still useful to the user */
} data_counters;


/* Messages available to communicate with the buffering thread */
enum
{
    Q_BUFFER_HANDLE = 1, /* Request buffering of a handle, this should not be
                            used in a low buffer situation. */
    Q_REBUFFER_HANDLE,   /* Request reset and rebuffering of a handle at a new
                            file starting position. */
    Q_CLOSE_HANDLE,      /* Request closing a handle */

    /* Configuration: */
    Q_START_FILL,        /* Request that the buffering thread initiate a buffer
                            fill at its earliest convenience */
    Q_HANDLE_ADDED,      /* Inform the buffering thread that a handle was added,
                            (which means the disk is spinning) */
};

/* Buffering thread */
static void buffering_thread(void);
static long buffering_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)];
static const char buffering_thread_name[] = "buffering";
static unsigned int buffering_thread_id = 0;
static struct event_queue buffering_queue SHAREDBSS_ATTR;
static struct queue_sender_list buffering_queue_sender_list SHAREDBSS_ATTR;

static void close_fd(int *fd_p)
{
    int fd = *fd_p;
    if (fd >= 0) {
        close(fd);
        *fd_p = -1;
    }
}

/* Ring buffer helper functions */
static inline void * ringbuf_ptr(uintptr_t p)
{
    return buffer + p;
}

static inline uintptr_t ringbuf_offset(const void *ptr)
{
    return (uintptr_t)(ptr - (void *)buffer);
}

/* Buffer pointer (p) plus value (v), wrapped if necessary */
static inline uintptr_t ringbuf_add(uintptr_t p, size_t v)
{
    uintptr_t res = p + v;
    if (res >= buffer_len)
        res -= buffer_len; /* wrap if necssary */
    return res;
}

/* Buffer pointer (p) minus value (v), wrapped if necessary */
static inline uintptr_t ringbuf_sub(uintptr_t p, size_t v)
{
    uintptr_t res = p;
    if (p < v)
        res += buffer_len; /* wrap */

    return res - v;
}

/* How far value (v) plus buffer pointer (p1) will cross buffer pointer (p2) */
static inline ssize_t ringbuf_add_cross(uintptr_t p1, size_t v, uintptr_t p2)
{
    ssize_t res = p1 + v - p2;
    if (p1 >= p2) /* wrap if necessary */
        res -= buffer_len;

    return res;
}

/* Real buffer watermark */
#define BUF_WATERMARK MIN(conf_watermark, high_watermark)

/*
LINKED LIST MANAGEMENT
======================

add_handle  : Add a handle to the list
rm_handle   : Remove a handle from the list
find_handle : Get a handle pointer from an ID
move_handle : Move a handle in the buffer (with or without its data)

These functions only handle the linked list structure. They don't touch the
contents of the struct memory_handle headers.

The first and current (== last) handle are kept track of.
A new handle is added at to the end and becomes the current one.

num_handles = N
first_handle -> h0 -> h1 -> h2 -> ... hN-1 -> NULL
                                      ^
cur_handle   -------------------------+
*/

static int next_handle_id(void)
{
    static int cur_handle_id = 0;

    /* Wrap signed int is safe and 0 doesn't happen */
    int next_hid = (cur_handle_id + 1) & BUF_HANDLE_MASK;
    if (next_hid == 0)
        next_hid = 1;

    cur_handle_id = next_hid;

    return next_hid;
}

/* adds the handle to the linked list */
static void link_cur_handle(struct memory_handle *h)
{
    h->next = NULL;

    if (first_handle)
        cur_handle->next = h;
    else
        first_handle = h; /* the first one */

    cur_handle = h;
    num_handles++;
}

/* Add a new handle to the linked list and return it. It will have become the
   new current handle.
   flags contains information on how this may be allocated
   data_size must contain the size of what will be in the handle.
   widx_out points to variable to receive first available byte of data area
   returns a valid memory handle if all conditions for allocation are met.
           NULL if there memory_handle itself cannot be allocated or if the
           data_size cannot be allocated and alloc_all is set. */
static struct memory_handle *
add_handle(unsigned int flags, size_t data_size, size_t *data_out)
{
    /* Gives each handle a unique id */
    if (num_handles >= BUF_MAX_HANDLES)
        return NULL;

    size_t ridx = 0, widx = 0;
    off_t cur_total = 0;

    if (first_handle) {
        /* Buffer is not empty */
        ridx = ringbuf_offset(first_handle);
        widx = cur_handle->data;
        cur_total = cur_handle->filesize - cur_handle->start;
    }

    if (cur_total > 0) {
        /* the current handle hasn't finished buffering. We can only add
           a new one if there is already enough free space to finish
           the buffering. */
        if (ringbuf_add_cross(widx, cur_total, ridx) >= 0) {
            /* Not enough space to finish allocation */
            return NULL;
        } else {
            /* Apply all the needed reserve */
            widx = ringbuf_add(widx, cur_total);
        }
    }

    /* Align to pointer size up */
    size_t adjust = ALIGN_UP(widx, sizeof(intptr_t)) - widx;
    size_t index = ringbuf_add(widx, adjust);
    size_t len = data_size + sizeof(struct memory_handle);

    /* First, will the handle wrap? */
    /* If the handle would wrap, move to the beginning of the buffer,
     * or if the data must not but would wrap, move it to the beginning */
    if (index + sizeof(struct memory_handle) > buffer_len ||
        (!(flags & H_CANWRAP) && index + len > buffer_len)) {
        index = 0;
    }

    /* How far we shifted index to align things, must be < buffer_len */
    size_t shift = ringbuf_sub(index, widx);

    /* How much space are we short in the actual ring buffer? */
    ssize_t overlap = ringbuf_add_cross(widx, shift + len, ridx);
    if (overlap >= 0 &&
        ((flags & H_ALLOCALL) || (size_t)overlap >= data_size)) {
        /* Not enough space for required allocations */
        return NULL;
    }

    /* There is enough space for the required data, initialize the struct */
    struct memory_handle *h = ringbuf_ptr(index);

    h->id       = next_handle_id();
    h->flags    = flags;
    h->pinned   = 0; /* Can be moved */
    h->signaled = 0; /* Data can be waited for */

    /* Return the start of the data area */
    *data_out = ringbuf_add(index, sizeof (struct memory_handle));

    return h;
}

/* Delete a given memory handle from the linked list
   and return true for success. Nothing is actually erased from memory. */
static bool rm_handle(const struct memory_handle *h)
{
    if (h == NULL)
        return true;

    struct memory_handle *m = first_handle;
    struct memory_handle *c = cur_handle;

    if (h == m) {
        m = m->next;
        first_handle = m;
        if (!m) {
            /* h was the first and last handle: the buffer is now empty */
            cur_handle = NULL;
        }
    } else {
        /* Find the previous handle */
        while (m && m->next != h) {
            m = m->next;
        }
        if (m && m->next == h) {
            m->next = h->next;
            if (h == c)
                cur_handle = m;
        } else {
            /* If we don't find ourselves, this is a seriously incoherent
               state with a corrupted list and severe action is needed! */
            panicf("rm_handle fail: %d", h->id);
            return false;
        }
    }

    /* Invalidate the cache to prevent it from keeping the old location of h */
    if (h == cached_handle)
        cached_handle = NULL;

    num_handles--;
    return true;
}

/* Return a pointer to the memory handle of given ID.
   NULL if the handle wasn't found */
static struct memory_handle *find_handle(int handle_id)
{
    if (handle_id < 0 || !first_handle)
        return NULL;

    /* Simple caching because most of the time the requested handle
       will either be the same as the last, or the one after the last */
    struct memory_handle *cached = cached_handle;
    if (cached) {
        if (cached->id == handle_id) {
            return cached;
        } else {
            cached = cached->next;
            if (cached && cached->id == handle_id) {
                cached_handle = cached;
                return cached;
            }
        }
    }

    struct memory_handle *m = first_handle;
    while (m && m->id != handle_id) {
        m = m->next;
    }

    /* This condition can only be reached with !m or m->id == handle_id */
    if (m)
        cached_handle = m;

    return m;
}

/* Move a memory handle and data_size of its data delta bytes along the buffer.
   delta maximum bytes available to move the handle.  If the move is performed
         it is set to the actual distance moved.
   data_size is the amount of data to move along with the struct.
   returns true if the move is successful and false if the handle is NULL,
           the  move would be less than the size of a memory_handle after
           correcting for wraps or if the handle is not found in the linked
           list for adjustment.  This function has no side effects if false
           is returned. */
static bool move_handle(struct memory_handle **h, size_t *delta,
                        size_t data_size)