File: cache.c

package info (click to toggle)
zapping 0.10~cvs6-2
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 9,856 kB
  • ctags: 11,841
  • sloc: ansic: 111,154; asm: 11,770; sh: 9,812; xml: 2,742; makefile: 1,283; perl: 488
file content (1761 lines) | stat: -rw-r--r-- 37,355 bytes parent folder | download | duplicates (6)
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
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
/*
 *  libzvbi - Teletext cache
 *
 *  Copyright (C) 2001, 2002, 2003, 2004 Michael H. Schimek
 *
 *  Based on code from AleVT 1.5.1
 *  Copyright (C) 1998, 1999 Edgar Toernig <froese@gmx.de>
 *
 *  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 program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "../site_def.h"

#include <stdlib.h>		/* malloc() */
#include "event-priv.h"
#include "cache-priv.h"

#ifndef CACHE_DEBUG
#  define CACHE_DEBUG 0
#endif

#ifndef CACHE_STATUS
#  define CACHE_STATUS 0
#endif

#ifndef CACHE_CONSISTENCY
#  define CACHE_CONSISTENCY 0
#endif

/** @internal */
struct _vbi3_cache {
	/**
	 * Teletext pages by pgno, most recently used at
	 * head of list. Uses cache_page.hash_node.
	 */
	list			hash[HASH_SIZE];

	/** Total number of pages cached, for statistics. */
	unsigned int		n_pages;

	unsigned int		ref_count;

	/**
	 * Teletext pages to be replaced when out of memory, oldest at
	 * head of list, uses cache_page.pri_node.
	 */
	list			priority;

	/** Referenced Teletext pages, uses cache_page.pri_node. */
	list			referenced;

	/**
	 * Memory used by all pages except referenced and zombies. (May
	 * deadlock if all pages are referenced and the caller releases
	 * only when receiving new pages.)
	 */
	unsigned long		memory_used;
	unsigned long		memory_limit;

	/** Cached networks, most recently used at head of list. */
	list			networks;

	/** Number of networks in cache except referenced and zombies. */
	unsigned int		n_networks;
	unsigned int		network_limit;

	_vbi3_event_handler_list handlers;
};

static void
delete_all_pages		(vbi3_cache *		ca,
				 cache_network *	cn);

static const char *
cache_priority_name		(cache_priority		pri)
{
	switch (pri) {

#undef CASE
#define CASE(pri) case CACHE_PRI_ ## pri : return #pri ;

	CASE (ZOMBIE)
	CASE (NORMAL)
	CASE (SPECIAL)

	default:
		assert (0);
		return NULL;
	}
}

static void
cache_network_dump		(const cache_network *	cn,
				 FILE *			fp)
{
	fprintf (fp, "network ref=%u referenced=%u zombie=%u",
		 cn->ref_count,
		 cn->n_referenced_pages,
		 cn->zombie);
}

/* Removes Teletext page from network statistics. */ 
static void
cache_network_remove_page	(cache_network *	cn,
				 cache_page *		cp)
{
	page_stat *ps;

	if (CACHE_CONSISTENCY)
		assert (cn == cp->network);

	cp->network = NULL;

	--cn->n_pages;

	ps = cache_network_page_stat (cn, cp->pgno);

	--ps->n_subpages;
}

/* Adds Teletext page to network statistics. */
static void
cache_network_add_page		(cache_network *	cn,
				 cache_page *		cp)
{
	page_stat *ps;

	if (cn->zombie) {
		assert (NULL != cn->cache);

		++cn->cache->n_networks;
		cn->zombie = FALSE;
	}

	cp->network = cn;

	++cn->n_pages;

	/* Consistency check: page number range 0x100 ... 0x8FF
	   including hex pages, and we store at most subpages
	   0x00 ... 0x79. */
	if (CACHE_CONSISTENCY)
		assert (cn->n_pages <= 0x800 * 80);

	if (cn->n_pages > cn->max_pages)
		cn->max_pages = cn->n_pages;

	ps = cache_network_page_stat (cn, cp->pgno);

	++ps->n_subpages;

	if (ps->n_subpages > ps->max_subpages)
		ps->max_subpages = ps->n_subpages;

	/* See above. */
	if (CACHE_CONSISTENCY)
		assert (ps->n_subpages <= 80);

	/* Subno must be 0 (no subpages),
	   0x0 ... 0xF (system pages),
	   0x01 ... 0x79 bcd (regular subpages),
	   0x0000 ... 0x2359 bcd (clock pages).

	   Note clock pages replace any page with same pgno, unless they
	   have no page_type and subno is 0x0000 ... 0x0059. So we store
	   at most 60 clock subpages. */
	if (CACHE_CONSISTENCY) {
		assert (cp->subno >= 0);

		if (cp->subno >= 0x10) {
			assert (vbi3_is_bcd (cp->subno));

			if (cp->subno >= 0x0100) {
				assert (cp->subno <= 0x2359);
				assert ((cp->subno & 0xFF) <= 0x59);
			} else {
				assert (cp->subno <= 0x79);
			}
		}
	}

	if (0 == ps->subno_min /* none yet */
	    || cp->subno < ps->subno_min)
		ps->subno_min = cp->subno;

	if (cp->subno > ps->subno_max)
		ps->subno_max = cp->subno;
}

static void
delete_network			(vbi3_cache *		ca,
				 cache_network *	cn)
{
	if (CACHE_CONSISTENCY) {
		assert (ca == cn->cache);
		assert (is_member (&ca->networks, &cn->node));
	}

	if (CACHE_DEBUG) {
		fputs ("Delete ", stderr);
		cache_network_dump (cn, stderr);
		fputc ('\n', stderr);
	}

	if (cn->n_pages > 0) {
		/* Delete all unreferenced pages. */
		delete_all_pages (ca, cn);
	}

	/* Zombies don't count. */
	if (!cn->zombie)
		--ca->n_networks;

	if (ca->handlers.event_mask & VBI3_EVENT_REMOVE_NETWORK) {
		vbi3_event e;

		e.type		= VBI3_EVENT_REMOVE_NETWORK;
		e.network	= &cn->network;
		e.timestamp	= 0;

		_vbi3_event_handler_list_send (&ca->handlers, &e);
	}

	if (cn->ref_count > 0
	    || cn->n_referenced_pages > 0) {
		cn->zombie = TRUE;
		return;
	}

	unlink_node (&cn->node);

	vbi3_network_destroy (&cn->network);

#ifndef ZAPPING8
	vbi3_program_info_destroy (&cn->program_info);
	vbi3_aspect_ratio_destroy (&cn->aspect_ratio);

	{
		vbi3_pid_channel ch;

		for (ch = 0; ch < N_ELEMENTS (cn->program_id); ++ch)
			vbi3_program_id_destroy (&cn->program_id[ch]);
	}

#endif
	cache_network_destroy_caption (cn);
	cache_network_destroy_teletext (cn);

	CLEAR (*cn);

	vbi3_cache_free (cn);
}

/**
 * @internal
 * @param ca Cache allocated with vbi3_cache_new().
 *
 * Deletes all cache contents. Referenced networks and Teletext pages
 * are marked for deletion when unreferenced.
 */
static void
vbi3_cache_purge			(vbi3_cache *		ca)
{
	cache_network *cn, *cn1;

	assert (NULL != ca);

	FOR_ALL_NODES (cn, cn1, &ca->networks, node) {
		delete_network (ca, cn);
	}
}

static void
delete_surplus_networks		(vbi3_cache *		ca)
{
	cache_network *cn, *cn1;

	/* Remove last recently used networks first. */
	FOR_ALL_NODES_REVERSE (cn, cn1, &ca->networks, node) {
		if (cn->ref_count > 0
		    || cn->n_referenced_pages > 0)
			continue;

		if (cn->zombie
		    || vbi3_network_is_anonymous (&cn->network)
		    || ca->n_networks > ca->network_limit)
			delete_network (ca, cn);
	}
}

/**
 * @internal
 * @param ca Cache allocated with vbi3_cache_new().
 * @param limit Number of networks.
 *
 * Limits the number of networks cached. The default is 1
 * as in libzvbi 0.2. Currently each network takes about 16 KB
 * additional to the vbi3_cache_set_memory_limit().
 *
 * When the number is smaller than the current number of networks
 * cached this function attempts to delete the data of the last
 * recently requested stations.
 */
void
vbi3_cache_set_network_limit	(vbi3_cache *		ca,
				 unsigned int		limit)
{
	assert (NULL != ca);

	ca->network_limit = SATURATE (limit, 1, 3000);

	delete_surplus_networks (ca);
}

static cache_network *
network_by_id			(vbi3_cache *		ca,
				 const vbi3_network *	nk)
{
	cache_network *cn, *cn1;

	/* Shortcut if this is one of our pointers (e.g. event->network). */
	FOR_ALL_NODES (cn, cn1, &ca->networks, node)
		if (&cn->network == nk)
			goto found;

	if (nk->user_data) {
		FOR_ALL_NODES (cn, cn1, &ca->networks, node)
			if (cn->network.user_data == nk->user_data)
				goto found2;

		/* Perhaps no user_data has been assigned to this
		   network yet. Try to find it by CNI or call_sign. */
	}

	if (nk->cni_vps) {
		FOR_ALL_NODES (cn, cn1, &ca->networks, node)
			if (cn->network.cni_vps == nk->cni_vps)
				goto found3;

		/* Perhaps we did not receive nk->cni_vps yet but
		   another CNI or call_sign. */
	}

	if (nk->cni_8301)
		FOR_ALL_NODES (cn, cn1, &ca->networks, node)
			if (cn->network.cni_8301 == nk->cni_8301)
				goto found3;

	if (nk->cni_8302)
		FOR_ALL_NODES (cn, cn1, &ca->networks, node)
			if (cn->network.cni_8302 == nk->cni_8302)
				goto found3;

	if (nk->call_sign[0])
		FOR_ALL_NODES (cn, cn1, &ca->networks, node)
			if (0 == strcmp (cn->network.call_sign, nk->call_sign))
				goto found3;

	return NULL;

	/* All given IDs must match unless the ID is not stored yet. */

 found3:
	if (nk->user_data && cn->network.user_data)
		return NULL;

 found2:
	if (nk->cni_vps && cn->network.cni_vps
	    && cn->network.cni_vps != nk->cni_vps)
		return NULL;

	if (nk->cni_8301 && cn->network.cni_8301
	    && cn->network.cni_8301 != nk->cni_8301)
		return NULL;

	if (nk->cni_8302 && cn->network.cni_8302
	    && cn->network.cni_8302 != nk->cni_8302)
		return NULL;

	if (nk->call_sign[0] && cn->network.call_sign[0]
	    && 0 != strcmp (cn->network.call_sign, nk->call_sign))
		return NULL;

 found:
	/* Find faster next time, delete last. */
	add_head (&ca->networks, unlink_node (&cn->node));

	return cn;
}

static cache_network *
recycle_network			(vbi3_cache *		ca)
{
	cache_network *cn, *cn1;

	/* We absorb the last recently used cache_network
	   without references. */

	FOR_ALL_NODES_REVERSE (cn, cn1, &ca->networks, node) {
		if (0 == cn->ref_count
		    && 0 == cn->n_referenced_pages) {
			goto found;
		}
	}

	return NULL;

 found:
	if (cn->n_pages > 0)
		delete_all_pages (ca, cn);

	unlink_node (&cn->node);

	cn->ref_count = 0;

	cn->zombie = FALSE;

	vbi3_network_destroy (&cn->network);

	cn->confirm_cni_vps = 0;
	cn->confirm_cni_8301 = 0;
	cn->confirm_cni_8302 = 0;

#ifndef ZAPPING8
	vbi3_program_info_destroy (&cn->program_info);
	vbi3_aspect_ratio_destroy (&cn->aspect_ratio);

	{
		vbi3_pid_channel ch;

		for (ch = 0; ch < N_ELEMENTS (cn->program_id); ++ch)
			vbi3_program_id_destroy (&cn->program_id[ch]);
	}
#endif

	cn->n_pages = 0;
	cn->max_pages = 0;

	cn->n_referenced_pages = 0;

	cache_network_destroy_caption (cn);
	cache_network_destroy_teletext (cn);

	return cn;
}

static cache_network *
add_network			(vbi3_cache *		ca,
				 const vbi3_network *	nk,
				 vbi3_videostd_set	videostd_set)
{
	cache_network *cn;

#ifdef ZAPPING8
	videostd_set = videostd_set; /* unused, no warning */
#endif

	if (nk && (cn = network_by_id (ca, nk))) {
		/* Note does not merge nk. */
		return cn;
	}

	if (ca->n_networks < ca->network_limit
	    || NULL == (cn = recycle_network (ca))) {
		if (!(cn = vbi3_cache_malloc (sizeof (*cn)))) {
			if (CACHE_DEBUG)
				fprintf (stderr, "%s: out of memory\n",
					 __FUNCTION__);
			return NULL;
		}

		CLEAR (*cn);

		++ca->n_networks;
	}

	add_head (&ca->networks, &cn->node);

	cn->cache = ca;

	if (nk)
		vbi3_network_copy (&cn->network, nk);

#ifndef ZAPPING8
	vbi3_program_info_init (&cn->program_info);
	vbi3_aspect_ratio_init (&cn->aspect_ratio, videostd_set);

	for (ch = 0; ch < N_ELEMENTS (cn->program_id); ++ch)
		vbi3_program_id_init (&cn->program_id[ch], ch);
#endif
	cache_network_init_caption (cn);
	cache_network_init_teletext (cn);

	return cn;
}

/**
 */
void
vbi3_ttx_page_stat_destroy	(vbi3_ttx_page_stat *	ps)
{
	assert (NULL != ps);

	CLEAR (*ps);
}

/**
 */
void
vbi3_ttx_page_stat_init		(vbi3_ttx_page_stat *	ps)
{
	assert (NULL != ps);

	CLEAR (*ps);

	ps->page_type = VBI3_UNKNOWN_PAGE;
}

/**
 * @internal
 */
void
cache_network_get_ttx_page_stat	(const cache_network *	cn,
				 vbi3_ttx_page_stat *	ps,
				 vbi3_pgno		pgno)
{
	const page_stat *ps1;

	assert (NULL != ps);

	ps1 = cache_network_const_page_stat (cn, pgno);

	if (VBI3_NORMAL_PAGE == (vbi3_page_type) ps1->page_type) {
		unsigned int flags;

		flags = ps1->flags & (C5_NEWSFLASH |
				      C6_SUBTITLE |
				      C7_SUPPRESS_HEADER);

		if ((C5_NEWSFLASH | C7_SUPPRESS_HEADER) == flags)
			ps->page_type = VBI3_NEWSFLASH_PAGE;
		else if ((C6_SUBTITLE | C7_SUPPRESS_HEADER) == flags)
			ps->page_type = VBI3_SUBTITLE_PAGE;
		else
			ps->page_type = VBI3_NORMAL_PAGE;
	} else {
		ps->page_type = (vbi3_page_type) ps1->page_type;
	}

	if (0xFF == ps1->charset_code) {
		/* Unknown. */
		ps->character_set = NULL;
	} else {
		ps->character_set = vbi3_character_set_from_code
			((vbi3_charset_code) ps1->charset_code);
	}

	if (ps1->subcode <= 9)
		ps->subpages	= ps1->subcode; /* common */
	else if (SUBCODE_UNKNOWN == ps1->subcode)
		ps->subpages	= 0;
	else if (SUBCODE_MULTI_PAGE == ps1->subcode)
		ps->subpages	= 2; /* two or more */
	else if (ps1->subcode >= 0x80)
		ps->subpages	= 0; /* non-standard (clock etc) */
	else
		ps->subpages	= vbi3_bcd2bin (ps1->subcode);

	ps->subno_min	= (vbi3_subno) ps1->subno_min;
	ps->subno_max	= (vbi3_subno) ps1->subno_max;
}

/**
 */
vbi3_bool
vbi3_cache_get_ttx_page_stat	(vbi3_cache *		ca,
				 vbi3_ttx_page_stat *	ps,
				 const vbi3_network *	nk,
				 vbi3_pgno		pgno)
{
	cache_network *cn;

	assert (NULL != ca);
	assert (NULL != ps);
	assert (NULL != nk);

	if (pgno < 0x100 || pgno > 0x8FF)
		return FALSE;

	if (!(cn = _vbi3_cache_get_network (ca, nk)))
		return FALSE;

	cache_network_get_ttx_page_stat	(cn, ps, pgno);

	cache_network_unref (cn);

	return TRUE;
}

/**
 * DOCUMENT ME
 */
vbi3_network *
vbi3_cache_get_networks		(vbi3_cache *		ca,
				 unsigned int *		n_elements)
{
	vbi3_network *nk;
	cache_network *cn, *cn1;
	unsigned long size;
	unsigned int i;

	assert (NULL != ca);
	assert (NULL != n_elements);

	*n_elements = 0;

	if (0 == ca->n_networks)
		return NULL;

	/* Not ca->n_networks because we list zombies too. */
	size = (list_length (&ca->networks) + 1) * sizeof (*nk);

	if (!(nk = vbi3_malloc (size))) {
		error ("Out of memory (%lu bytes)", size);
		return NULL;
	}

	i = 0;

	FOR_ALL_NODES (cn, cn1, &ca->networks, node) {
		if (vbi3_network_is_anonymous (&cn->network))
			continue;

		if (!(vbi3_network_copy (nk + i, &cn->network))) {
			vbi3_network_array_delete (nk, i);
			return NULL;
		}

		++i;
	}

	CLEAR (nk[i]);

	*n_elements = i;

	return nk;
}

/**
 * @internal
 * @param cn cache_network obtained with _vbi3_cache_add_cache_network()
 *   or _vbi3_cache_get_cache_network(), can be @c NULL.
 *
 * Releases a network reference.
 */
void
cache_network_unref		(cache_network *	cn)
{
	vbi3_cache *ca;

	if (NULL == cn)
		return;

	assert (NULL != cn->cache);

	ca = cn->cache;

	if (CACHE_CONSISTENCY)
		assert (is_member (&ca->networks, &cn->node));

	if (0 == cn->ref_count) {
		debug ("Unreferenced network %p", (void *) cn);
		return;
	} else if (1 == cn->ref_count) {
		cn->ref_count = 0;

		delete_surplus_networks (ca);
	} else {
		--cn->ref_count;
	}
}

/**
 * @internal
 * @param cn
 *
 * Duplicates a network reference.
 *
 * @returns
 * @a cn, never fails.
 */
cache_network *
cache_network_ref		(cache_network *	cn)
{
	assert (NULL != cn);

	++cn->ref_count;

	return cn;
}

/**
 * @internal
 * @param ca Cache allocated with vbi3_cache_new().
 * @param nk Identifies the network by cni_8301, cni_8302, cni_vps,
 *   call_sign or user_data, whichever is non-zero.
 *
 * Finds a network in the cache.
 *
 * @returns
 * Pointer to a cache_network structure, @c NULL on error.  You must call
 * _vbi3_cache_network_unref() when this reference is no longer
 * needed.
 */
cache_network *
_vbi3_cache_get_network		(vbi3_cache *		ca,
				 const vbi3_network *	nk)
{
	cache_network *cn;

	assert (NULL != ca);
	assert (NULL != nk);

	if ((cn = network_by_id (ca, nk))) {
		if (cn->zombie) {
			++ca->n_networks;
			cn->zombie = FALSE;
		}

		++cn->ref_count;
	}

	return cn;
}

/**
 * @internal
 * @param ca Cache allocated with vbi3_cache_new().
 * @param nk Create network with this cni_8301, cni_8302, cni_vps,
 *   call_sign or temp_id, whichever is non-zero. Can be @c NULL
 *   to add an anonymous network.
 *
 * Adds a network to the cache.
 *
 * @returns
 * Pointer to a new cache_network structure, an already existing
 * structure or @c NULL on error.  You must call
 * _vbi3_cache_network_unref() when this reference is no
 * longer needed.
 */
cache_network *
_vbi3_cache_add_network		(vbi3_cache *		ca,
				 const vbi3_network *	nk,
				 vbi3_videostd_set	videostd_set)
{
	cache_network *cn;

	assert (NULL != ca);

	if ((cn = add_network (ca, nk, videostd_set))) {
		++cn->ref_count;
	}

	return cn;
}

/** internal */
void
cache_page_dump			(const cache_page *	cp,
				 FILE *			fp)
{
	const cache_network *cn;

	fprintf (fp, "page %x.%x ", cp->pgno, cp->subno);

	if ((cn = cp->network)) {
		const page_stat *ps;

		ps = cache_network_const_page_stat (cn, cp->pgno);

		fprintf (fp, "%s/L%u/S%04x subp=%u/%u (%u-%u) ",
			 vbi3_page_type_name (ps->page_type),
			 ps->charset_code,
			 ps->subcode,
			 ps->n_subpages,
			 ps->max_subpages,
			 ps->subno_min,
			 ps->subno_max);
	}

	fprintf (stderr, "ref=%u %s",
		 cp->ref_count, cache_priority_name (cp->priority));
}

/**
 * @internal
 * @param cp Teletext page.
 * 
 * @returns
 * Storage size required for the raw Teletext page,
 * depending on its function and the data union member used.
 */
unsigned int
cache_page_size			(const cache_page *	cp)
{
	const unsigned int header_size = sizeof (*cp) - sizeof (cp->data);

	switch (cp->function) {
	case PAGE_FUNCTION_UNKNOWN:
	case PAGE_FUNCTION_LOP:
		if (cp->x28_designations & 0x13)
			return header_size + sizeof (cp->data.ext_lop);
		else if (cp->x26_designations)
			return header_size + sizeof (cp->data.enh_lop);
		else
			return header_size + sizeof (cp->data.lop);

	case PAGE_FUNCTION_GPOP:
	case PAGE_FUNCTION_POP:
		return header_size + sizeof (cp->data.pop);

	case PAGE_FUNCTION_GDRCS:
	case PAGE_FUNCTION_DRCS:
		return header_size + sizeof (cp->data.drcs);

	case PAGE_FUNCTION_AIT:
		return header_size + sizeof (cp->data.ait);

	default:
		return sizeof (*cp);
	}
}

/** internal */
vbi3_bool
cache_page_copy			(cache_page *		dst,
				 const cache_page *	src)
{
	if (dst == src)
		return TRUE;

	assert (NULL != dst);

	if (src) {
		memcpy (dst, src, cache_page_size (src));

		dst->network = NULL; /* not cached */
	} else {
		CLEAR (*dst);
	}

	return TRUE;
}

vbi3_inline unsigned int
hash				(vbi3_pgno		pgno)
{
	return pgno % HASH_SIZE;
}

static vbi3_bool
page_in_cache			(const vbi3_cache *	ca,
				 const cache_page *	cp)
{
	const list *hash_list;
	const list *pri_list;

	if (CACHE_PRI_ZOMBIE == cp->priority) {
		/* Note cp->ref_count may be zero if the page is
		   about to be deleted. */
		return is_member (&ca->referenced, &cp->pri_node);
	}

	hash_list = &ca->hash[hash (cp->pgno)];

	if (cp->ref_count > 0)
		pri_list = &ca->referenced;
	else
		pri_list = &ca->priority;

	return (is_member (hash_list, &cp->hash_node)
		&& is_member (pri_list, &cp->pri_node));
}

static void
delete_page			(vbi3_cache *		ca,
				 cache_page *		cp)
{
	if (CACHE_CONSISTENCY) {
		assert (NULL != cp->network);
		assert (ca == cp->network->cache);
		assert (page_in_cache (ca, cp));
	}

	if (cp->ref_count > 0) {
		if (CACHE_PRI_ZOMBIE != cp->priority) {
			/* Remove from cache, mark for deletion.
			   cp->pri_node remains on ca->referenced. */

			unlink_node (&cp->hash_node);

			cp->priority = CACHE_PRI_ZOMBIE;
		}

		return;
	}

	if (CACHE_DEBUG) {
		fputs ("Delete ", stderr);
		cache_page_dump (cp, stderr);
		fputc (' ', stderr);
		cache_network_dump (cp->network, stderr);
		fputc ('\n', stderr);
	}

	if (CACHE_PRI_ZOMBIE != cp->priority) {
		/* Referenced and zombie pages don't count. */ 
		ca->memory_used -= cache_page_size (cp);

		unlink_node (&cp->hash_node);
	}

	unlink_node (&cp->pri_node);

	cache_network_remove_page (cp->network, cp);

	vbi3_cache_free (cp);

	--ca->n_pages;
}

static void
delete_all_pages		(vbi3_cache *		ca,
				 cache_network *	cn)
{
	cache_page *cp, *cp1;

	if (CACHE_CONSISTENCY && NULL != cn) {
		assert (ca == cn->cache);
		assert (is_member (&ca->networks, &cn->node));
	}

	FOR_ALL_NODES (cp, cp1, &ca->priority, pri_node)
		if (!cn || cp->network == cn)
			delete_page (ca, cp);
}

static void
delete_surplus_pages		(vbi3_cache *		ca)
{
	cache_priority pri;
	cache_page *cp, *cp1;

	for (pri = CACHE_PRI_NORMAL; pri <= CACHE_PRI_SPECIAL; ++pri) {
		FOR_ALL_NODES (cp, cp1, &ca->priority, pri_node) {
			if (ca->memory_used <= ca->memory_limit)
				return;
			else if (cp->priority == pri
				 && 0 == cp->network->ref_count)
				delete_page (ca, cp);
		}
	}

	for (pri = CACHE_PRI_NORMAL; pri <= CACHE_PRI_SPECIAL; ++pri) {
		FOR_ALL_NODES (cp, cp1, &ca->priority, pri_node) {
			if (ca->memory_used <= ca->memory_limit)
				return;
			else if (cp->priority == pri)
				delete_page (ca, cp);
		}
	}
}

/**
 * @param ca Cache allocated with vbi3_cache_new().
 * @param limit Amount of memory in bytes.
 *
 * Limits the amount of memory used by the Teletext page cache. Reasonable
 * values range from 16 KB to 1 GB, default is 1 GB as in libzvbi 0.2.
 * The number of pages transmitted by networks varies. Expect on the order
 * of one megabyte for a complete set.
 * 
 * When the cache is too small to contain all pages of a network,
 * newly received pages will replace older pages. Pages of the
 * current network, or which have been recently requested, or will
 * likely be requested in the future, or take longer to reload
 * are last deleted.
 *
 * When @a limit is smaller than the amount of memory currently
 * used, this function attempts to delete an appropriate number of
 * pages.
 */
void
vbi3_cache_set_memory_limit	(vbi3_cache *		ca,
				 unsigned long		limit)
{
	assert (NULL != ca);

	ca->memory_limit = SATURATE (limit, 1 << 10, 1 << 30);

	delete_surplus_pages (ca);
}

static cache_page *
page_by_pgno			(vbi3_cache *		ca,
				 const cache_network *	cn,
				 vbi3_pgno		pgno,
				 vbi3_subno		subno,
				 vbi3_subno		subno_mask)
{
	list *hash_list;
	cache_page *cp, *cp1;

	if (CACHE_CONSISTENCY) {
		assert (ca == cn->cache);
		assert (is_member (&ca->networks, &cn->node));
	}

	hash_list = ca->hash + hash (pgno);

	FOR_ALL_NODES (cp, cp1, hash_list, hash_node) {
		if (CACHE_DEBUG > 1) {
			fputs ("Try ", stderr);
			cache_page_dump (cp, stderr);
			fputc ('\n', stderr);
		}

		if (cp->pgno == pgno
		    && (cp->subno & subno_mask) == subno
		    && (!cn || cp->network == cn)) {
			/* Find faster next time. */
			add_head (hash_list, unlink_node (&cp->hash_node));
			return cp;
		}
	}

	return NULL;
}

/**
 * @internal
 * @param cp
 *
 * Unreferences a page returned by vbi3_cache_put_cache_page(),
 * vbi3_cache_get_cache_page(), or vbi3_page_new_cache_page_ref().
 * @a cp can be @c NULL.
 */
void
cache_page_unref		(cache_page *		cp)
{
	vbi3_cache *ca;

	if (NULL == cp)
		return;

	assert (NULL != cp->network);
	assert (NULL != cp->network->cache);

	ca = cp->network->cache;

	if (CACHE_CONSISTENCY)
		assert (page_in_cache (ca, cp));

	if (0 == cp->ref_count) {
		debug ("Unreferenced page %p", (void *) cp);
		return;
	}

	if (CACHE_DEBUG) {
		fputs ("Unref ", stderr);
		_vbi3_cache_dump (ca, stderr);
		fputc (' ', stderr);
		cache_page_dump (cp, stderr);
	}

	if (1 == cp->ref_count) {
		cache_network *cn;

		cp->ref_count = 0;

		cn = cp->network;

		switch (cp->priority) {
		case CACHE_PRI_ZOMBIE:
			delete_page (ca, cp);
			break;

		default:
			if (CACHE_DEBUG) {
				fputc (' ', stderr);
				cache_network_dump (cn, stderr);
			}

			add_tail (&ca->priority, unlink_node (&cp->pri_node));

			ca->memory_used += cache_page_size (cp);

			break;
		}

		--cn->n_referenced_pages;

		if (cn->zombie
		    && 0 == cn->n_referenced_pages
		    && 0 == cn->ref_count)
			delete_network (ca, cn);

		if (ca->memory_used > ca->memory_limit)
			delete_surplus_pages (ca);
	} else {
		--cp->ref_count;
	}

	if (CACHE_DEBUG)
		fputc ('\n', stderr);
}

/**
 * @internal
 * @param cp
 *
 * Duplicates a page reference.
 *
 * @returns
 * @a cp, never fails.
 */
cache_page *
cache_page_ref			(cache_page *		cp)
{
	assert (NULL != cp);

	if (CACHE_DEBUG) {
		fputs ("Ref ", stderr);
		cache_page_dump (cp, stderr);
	}

	if (0 == cp->ref_count) {
		vbi3_cache *ca;
		cache_network *cn;

		cn = cp->network;
		ca = cn->cache;

		if (CACHE_DEBUG) {
			fputc (' ', stderr);
			cache_network_dump (cn, stderr);
		}

		if (cn->zombie) {
			++ca->n_networks;
			cn->zombie = FALSE;
		}

		++cn->n_referenced_pages;

		ca->memory_used -= cache_page_size (cp);

		add_tail (&ca->referenced, unlink_node (&cp->pri_node));
	}

	if (CACHE_DEBUG)
		fputc ('\n', stderr);

	++cp->ref_count;

	return cp;
}

/**
 * @internal
 *
 * Gets a page from the cache. When @a subno is @c VBI3_ANY_SUBNO, the most
 * recently received subpage of that page is returned.
 * 
 * The reference counter of the page is incremented, you must call
 * cache_page_unref() to unreference the page.
 * 
 * @return 
 * cache_page pointer, NULL when the requested page is not cached.
 */
cache_page *
_vbi3_cache_get_page		(vbi3_cache *		ca,
				 cache_network *	cn,
				 vbi3_pgno		pgno,
				 vbi3_subno		subno,
				 vbi3_subno		subno_mask)
{
	cache_page *cp;

	assert (NULL != ca);
	assert (NULL != cn);

	assert (ca == cn->cache);

	if (CACHE_CONSISTENCY)
		assert (is_member (&ca->networks, &cn->node));

	if (pgno < 0x100 || pgno > 0x8FF) {
		debug ("pgno 0x%x out of bounds", pgno);
		return NULL;
	}

	if (CACHE_DEBUG) {
		fprintf (stderr, "Get %x.%x/%x ", pgno, subno, subno_mask);
		_vbi3_cache_dump (ca, stderr);
		fputc (' ', stderr);
		cache_network_dump (cn, stderr);
		fputc ('\n', stderr);
	}

	if (VBI3_ANY_SUBNO == subno)
		subno_mask = 0;

	if (!(cp = page_by_pgno (ca, cn, pgno, subno, subno_mask)))
		goto failure;

	if (CACHE_DEBUG) {
		fputs ("Found ", stderr);
		cache_page_dump (cp, stderr);
		fputc ('\n', stderr);
	}

	return cache_page_ref (cp);

 failure:
	return NULL;
}

/**
 * @internal
 * For vbi3_search.
 */
int
_vbi3_cache_foreach_page	(vbi3_cache *		ca,
				 cache_network *	cn,
				 vbi3_pgno		pgno,
				 vbi3_subno		subno,
				 int			dir,
				 _vbi3_cache_foreach_cb *callback,
				 void *			user_data)
{
	cache_page *cp;
	page_stat *ps;
	vbi3_bool wrapped;

	assert (NULL != ca);
	assert (NULL != cn);
	assert (NULL != callback);

	if (0 == cn->n_pages)
		return 0;

	if ((cp = _vbi3_cache_get_page (ca, cn, pgno, subno, -1))) {
		subno = cp->subno;
	} else if (VBI3_ANY_SUBNO == subno) {
		cp = NULL;
		subno = 0;
	}

	ps = cache_network_page_stat (cn, pgno);

	wrapped = FALSE;

	for (;;) {
		if (cp) {
			int r;

			r = callback (cp, wrapped, user_data);

			cache_page_unref (cp);
			cp = NULL;

			if (0 != r)
				return r;
		}

		subno += dir;

		while (0 == ps->n_subpages
		       || subno < ps->subno_min
		       || subno > ps->subno_max) {
			if (dir < 0) {
				--pgno;
				--ps;

				if (pgno < 0x100) {
					pgno = 0x8FF;
					ps = cache_network_page_stat(cn, pgno);
					wrapped = TRUE;
				}

				subno = ps->subno_max;
			} else {
				++pgno;
				++ps;

				if (pgno > 0x8FF) {
					pgno = 0x100;
					ps = cache_network_page_stat(cn, pgno);
					wrapped = TRUE;
				}

				subno = ps->subno_min;
			}
		}

		cp = _vbi3_cache_get_page (ca, cn, pgno, subno, -1);
	}
}

/**
 * @internal
 * @param ca Cache.
 * @param cn Network this page belongs to.
 * @param cp Teletext page to store in the cache.
 *
 * Puts a copy of @a cp in the cache.
 * 
 * @returns
 * cache_page pointer (in the cache, not @a cp), NULL on failure
 * (out of memory). You must unref the returned page if no longer needed.
 */
cache_page *
_vbi3_cache_put_page		(vbi3_cache *		ca,
				 cache_network *	cn,
				 const cache_page *	cp)
{
	cache_page *death_row[20];
	unsigned int death_count;
	cache_page *old_cp;
	long memory_available;	/* NB can be < 0 */
	long memory_needed;
	cache_priority pri;
	cache_page *new_cp;

	assert (NULL != ca);
	assert (NULL != cn);
	assert (NULL != cp);

	assert (ca == cn->cache);

	memory_needed = cache_page_size (cp);
	memory_available = ca->memory_limit - ca->memory_used;

	if (CACHE_CONSISTENCY)
		assert (is_member (&ca->networks, &cn->node));

	if (CACHE_DEBUG) {
		fprintf (stderr, "Put %x.%x ", cp->pgno, cp->subno);
		_vbi3_cache_dump (ca, stderr);
		fputc (' ', stderr);
		cache_network_dump (cn, stderr);
		fputc (' ', stderr);
	}

	death_count = 0;

	{
		const page_stat *ps;
		vbi3_subno subno_mask;

		/* EN 300 706, A.1, E.2: Pages with subno > 0x79 do not really
		   have subpages. In this case we use subno_mask zero,
		   replacing any previously received subpage. XXX doesn't
		   work for clock pages without page_type between 00:00
		   and 00:59. */

		ps = cache_network_const_page_stat (cn, cp->pgno);

		if (VBI3_NONSTD_SUBPAGES == (vbi3_page_type) ps->page_type)
			subno_mask = 0;
		else
			subno_mask = - ((unsigned int) cp->subno <= 0x79);

		old_cp = page_by_pgno (ca, cn,
				       cp->pgno,
				       cp->subno & subno_mask,
				       subno_mask);
	}

	if (old_cp) {
		if (CACHE_DEBUG) {
			fputs ("is cached ", stderr);
			cache_page_dump (old_cp, stderr);
			fputc (' ', stderr);
		}

		if (old_cp->ref_count > 0) {
			/* This page is still in use. We remove it from
			   the cache and mark for deletion when unref'd.
			   old_cp->pri_node remains on ca->referenced. */
			unlink_node (&old_cp->hash_node);

			old_cp->priority = CACHE_PRI_ZOMBIE;
			old_cp = NULL;
		} else {
			/* Got our first replacement candidate. */
			death_row[death_count++] = old_cp;
			memory_available += cache_page_size (old_cp);
		}
	}

	if (memory_available >= memory_needed)
		goto replace;

	/* Find more pages to replace until we have enough memory. */

	for (pri = CACHE_PRI_NORMAL; pri <= CACHE_PRI_SPECIAL; ++pri) {
		cache_page *cp, *cp1;

		FOR_ALL_NODES (cp, cp1, &ca->priority, pri_node) {
			if (memory_available >= memory_needed)
				goto replace;

			if (pri != cp->priority
			    || cp->network->ref_count > 0
			    || cp == old_cp)
				continue;

			assert (death_count < N_ELEMENTS (death_row));

			death_row[death_count++] = cp;
			memory_available += cache_page_size (cp);
		}
	}

	for (pri = CACHE_PRI_NORMAL; pri <= CACHE_PRI_SPECIAL; ++pri) {
		cache_page *cp, *cp1;

		FOR_ALL_NODES (cp, cp1, &ca->priority, pri_node) {
			if (memory_available >= memory_needed)
				goto replace;

			if (pri != cp->priority
			    || cp == old_cp)
				continue;

			assert (death_count < N_ELEMENTS (death_row));

			death_row[death_count++] = cp;
			memory_available += cache_page_size (cp);
		}
	}

	if (CACHE_DEBUG) {
		fprintf (stderr, "need %lu bytes but only %lu available ",
			 memory_needed, memory_available);
	}

	goto failure;

 replace:
	if (memory_available == memory_needed
	    && 1 == death_count) {
		/* Usually we can replace a single page of same size. */

		new_cp = death_row[0];

		if (CACHE_DEBUG) {
			fputs ("reusing ", stderr);
			cache_page_dump (new_cp, stderr);
			fputc (' ', stderr);
		}

		unlink_node (&new_cp->pri_node);
		unlink_node (&new_cp->hash_node);

		cache_network_remove_page (new_cp->network, new_cp);

		ca->memory_used -= memory_needed;
	} else {
		unsigned int i;

		if (!(new_cp = vbi3_cache_malloc ((size_t) memory_needed))) {
			if (CACHE_DEBUG)
				fputs ("out of memory ", stderr);

			goto failure;
		}

		for (i = 0; i < death_count; ++i)
			delete_page (ca, death_row[i]);

		++ca->n_pages;
	}

	add_head (ca->hash + hash (cp->pgno), &new_cp->hash_node);

	/* 100, 200, 300, ... magazine start page. */
	if (0x00 == (cp->pgno & 0xFF))
		new_cp->priority = CACHE_PRI_SPECIAL;
	/* 111, 222, 333, ... magic page number. */
	else if ((cp->pgno >> 4) == (cp->pgno & 0xFF))
		new_cp->priority = CACHE_PRI_SPECIAL;
	/* Something we may not want in cache, much less all subpages. */
	else if (PAGE_FUNCTION_UNKNOWN == cp->function)
		new_cp->priority = CACHE_PRI_NORMAL;
	/* POP, GPOP, DRCS, GDRCS */
	else if (PAGE_FUNCTION_LOP != cp->function)
		new_cp->priority = CACHE_PRI_SPECIAL;
	/* Regular subpage, not clock, not rotating ads etc. */
	else if (cp->subno > 0x00 && cp->subno < 0x79)
		new_cp->priority = CACHE_PRI_SPECIAL;
	else
		new_cp->priority = CACHE_PRI_NORMAL;

	new_cp->function		= cp->function;

	new_cp->pgno			= cp->pgno;
	new_cp->subno			= cp->subno;

	new_cp->national		= cp->national;

	new_cp->flags			= cp->flags;

	new_cp->lop_packets		= cp->lop_packets;
	new_cp->x26_designations	= cp->x26_designations;
	new_cp->x27_designations	= cp->x27_designations;
	new_cp->x28_designations	= cp->x28_designations;

	memcpy (&new_cp->data, &cp->data,
		memory_needed - (sizeof (*new_cp) - sizeof (new_cp->data)));

	new_cp->ref_count = 1;
	ca->memory_used += 0; /* see _vbi3_cache_get_page() */

	++cn->n_referenced_pages;

	add_tail (&ca->referenced, &new_cp->pri_node);

	cache_network_add_page (cn, new_cp);

	if (CACHE_DEBUG) {
		fputc ('\n', stderr);
	}

	if (CACHE_STATUS) {
		fprintf (stderr, "cache status:\n");
		_vbi3_cache_dump (ca, stderr);
		fputc ('\n', stderr);
		cache_page_dump (new_cp, stderr);
		fputc ('\n', stderr);
		cache_network_dump (new_cp->network, stderr);
		fputc ('\n', stderr);
	}

	return new_cp;

 failure:
	if (CACHE_DEBUG) {
		fputc ('\n', stderr);
	}

	return NULL;
}

/** @internal */
void
_vbi3_cache_dump		(const vbi3_cache *	ca,
				 FILE *			fp)
{
	fprintf (fp, "cache ref=%u pages=%u mem=%lu/%lu KiB networks=%u/%u",
		 ca->ref_count,
		 ca->n_pages,
		 (ca->memory_used + 1023) >> 10,
		 (ca->memory_limit + 1023) >> 10,
		 ca->n_networks,
		 ca->network_limit);
}

/**
 * @param ca Cache allocated with vbi3_cache_new().
 * @param callback Function to be called on events.
 * @param user_data User pointer passed through to the @a callback function.
 * 
 * Removes an event handler from the cache, if a handler with
 * this @a callback and @a user_data has been registered. You can
 * safely call this function from a handler removing itself or another
 * handler.
 */
void
vbi3_cache_remove_event_handler	(vbi3_cache *		ca,
				 vbi3_event_cb *	callback,
				 void *			user_data)
{
	assert (NULL != ca);

	_vbi3_event_handler_list_remove_by_callback
		(&ca->handlers, callback, user_data);
}

/**
 * @param ca Cache allocated with vbi3_cache_new().
 * @param event_mask Set of events (@c VBI3_EVENT_) the handler is waiting
 *   for, can be -1 for all and 0 for none.
 * @param callback Function to be called on events.
 * @param user_data User pointer passed through to the @a callback function.
 * 
 * Adds a new event handler to the cache. When the @a callback
 * with @a user_data is already registered the function merely changes the
 * set of events it will receive in the future. When the @a event_mask is
 * empty the function does nothing or removes an already registered event
 * handler. You can safely call this function from an event handler.
 *
 * Any number of handlers can be added, also different handlers for the
 * same event which will be called in registration order.
 *
 * Currently the following events are supported:
 * @c VBI3_EVENT_REMOVE_NETWORK.
 *
 * @returns
 * @c FALSE of failure (out of memory).
 */
vbi3_bool
vbi3_cache_add_event_handler	(vbi3_cache *		ca,
				 vbi3_event_mask	event_mask,
				 vbi3_event_cb *	callback,
				 void *			user_data)
{
	assert (NULL != ca);

	event_mask &= VBI3_EVENT_REMOVE_NETWORK;

	if (0 == event_mask)
		return TRUE;

	return (NULL != _vbi3_event_handler_list_add
		(&ca->handlers, event_mask, callback, user_data));
}

/**
 * @param ca Cache allocated with vbi3_cache_new(), can be @c NULL.
 *
 * Frees all resources associated with the cache, regardless of
 * any remaining references to it.
 */
void
vbi3_cache_delete		(vbi3_cache *		ca)
{
	unsigned int i;

	if (NULL == ca)
		return;

	vbi3_cache_purge (ca);

	if (!is_empty (&ca->referenced)) {
		debug ("Some cached pages still referenced, memory leaks");
	}

	if (!is_empty (&ca->networks)) {
		debug ("Some cached networks still referenced, memory leaks");
	}

	_vbi3_event_handler_list_destroy (&ca->handlers);

	list_destroy (&ca->networks);
	list_destroy (&ca->priority);
	list_destroy (&ca->referenced);

	for (i = 0; i < N_ELEMENTS (ca->hash); ++i)
		list_destroy (ca->hash + i);

	CLEAR (*ca);

	vbi3_free (ca);
}

/**
 * @param ca Cache allocated with vbi3_cache_new(), can be @c NULL.
 *
 * Releases a cache reference. When this is the last reference
 * the function calls vbi3_cache_delete().
 */
void
vbi3_cache_unref			(vbi3_cache *		ca)
{
	if (NULL == ca)
		return;

	if (1 == ca->ref_count) {
		vbi3_cache_delete (ca);
	} else {
		--ca->ref_count;
	}
}

/**
 * @param ca Cache allocated with vbi3_cache_new().
 *
 * Creates a new reference to the cache.
 *
 * @returns
 * @a ca. You must call vbi3_cache_unref() when the reference is
 * no longer needed.
 */
vbi3_cache *
vbi3_cache_ref			(vbi3_cache *		ca)
{
	assert (NULL != ca);

	++ca->ref_count;

	return ca;
}

/**
 * Allocates a new cache for VBI decoders.
 *
 * A cache is a shared object with a reference counter. To create
 * a new reference call vbi3_cache_ref().
 *
 * @returns
 * Pointer to newly allocated cache which must be freed with
 * vbi3_cache_unref() or vbi3_cache_delete() when done. @c NULL on
 * failure (out of memory).
 */
vbi3_cache *
vbi3_cache_new			(void)
{
	vbi3_cache *ca;
	unsigned int i;

	if (!(ca = vbi3_malloc (sizeof (*ca)))) {
		error ("Out of memory (%u bytes)", sizeof (*ca));
		return NULL;
	}

	CLEAR (*ca);

	for (i = 0; i < N_ELEMENTS (ca->hash); ++i)
		list_init (ca->hash + i);

	list_init (&ca->referenced);
	list_init (&ca->priority);
	list_init (&ca->networks);

	ca->memory_limit = 1 << 30;
	ca->network_limit = 1;

	ca->ref_count = 1;

	if (!_vbi3_event_handler_list_init (&ca->handlers)) {
		vbi3_cache_delete (ca);
		ca = NULL;
	}

	return ca;
}