File: qfits_memory.c

package info (click to toggle)
qfits 6.2.0-8
  • links: PTS
  • area: main
  • in suites: bullseye, buster, jessie, jessie-kfreebsd, sid, stretch
  • size: 2,976 kB
  • ctags: 1,019
  • sloc: ansic: 11,631; sh: 8,330; makefile: 131
file content (1484 lines) | stat: -rw-r--r-- 51,107 bytes parent folder | download | duplicates (2)
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
/* $Id: qfits_memory.c,v 1.4 2006/08/24 15:01:56 yjung Exp $
 *
 * This file is part of the ESO QFITS Library
 * Copyright (C) 2001-2004 European Southern Observatory
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * $Author: yjung $
 * $Date: 2006/08/24 15:01:56 $
 * $Revision: 1.4 $
 * $Name: qfits-6_2_0 $
 */

/*-----------------------------------------------------------------------------
                                Includes
 -----------------------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/resource.h>

/*-----------------------------------------------------------------------------
                                Defines
 -----------------------------------------------------------------------------*/

/*
  This symbol sets the debug level for the memory module. Debug levels are 
  defined as follows:

  0   no debugging.
  1   add tracing for memory leaks and diagnostics in qfits_memory_status 
  2   add lots of debug messages
*/
#ifndef QFITS_MEMORY_DEBUG
#define QFITS_MEMORY_DEBUG       0
#endif

/*
  This symbol defines the level of usage of the memory module. 

  0   Use the memory system calls.
  1   Use the memory system calls, but exit if they are not succesfull
  2   Fully use the memory functions
*/
#ifndef QFITS_MEMORY_MODE
#define QFITS_MEMORY_MODE        2
#endif

/* Initial number of entries in memory table */
/* If this number is big, the size of the memory table can become
   problematic.
 */
#ifndef QFITS_MEMORY_MAXPTRS
#define QFITS_MEMORY_MAXPTRS     200003
#endif

/* Identify true RAM memory */
#define MEMTYPE_RAM         'R'
/* Identify swap memory */
#define MEMTYPE_SWAP        'S'
/* Identify memory-mapped file */
#define MEMTYPE_MMAP        'M'

/* Minimal page size in bytes */
#define MEMPAGESZ           2048

/* Size of temporary dir name */
#define TMPDIRNAMESZ        1024

/* Size of temporary file names */
#define TMPFILENAMESZ       1024

/* Size of source file names */
#define SRCFILENAMESZ       64

/* Size of mapped file names */
#define MAPFILENAMESZ       256

/*-----------------------------------------------------------------------------
                                Macros
 -----------------------------------------------------------------------------*/

/* Debug */
#if (QFITS_MEMORY_DEBUG>=2)
#define qfits_mem_debug( code ) { code }
#else
#define qfits_mem_debug( code )
#endif

/* A very simple hash */
#define PTR_HASH(ptr) (((unsigned long int) ptr) % QFITS_MEMORY_MAXPTRS)

/*-----------------------------------------------------------------------------
                        Private variables
 -----------------------------------------------------------------------------*/

/* Initialization flag */
static int  qfits_memory_initialized=0 ;

/* Path to temporary directory */
static char qfits_memory_tmpdirname[TMPDIRNAMESZ] = "." ;

/*----------------------------------------------------------------------------*/
/*
  This table holds a list pointer cells (all the ones allocated so far).
  It is strictly internal to this source file.
 */
/*----------------------------------------------------------------------------*/
static struct {
    /* Number of active cells */
    int                 ncells ;
    /* Total allocated memory in bytes */
    size_t              alloc_total ;
    /* Total allocated RAM in bytes */
    size_t              alloc_ram ;
    /* Total allocated VM in bytes */
    size_t              alloc_swap ;
    /* Peak allocation ever seen for diagnostics */
    size_t              alloc_max ;
    /* Peak number of pointers ever seen for diagnostics */
    int                 max_cells ;

    /* Current number of swap files */
    int                 nswapfiles ;
    /* Registration counter for swap files */
    int                 file_reg ;

    /* Current number of memory-mapped files */
    int                 n_mm_files ;
    /* Current number of mappings derived from files */
    int                 n_mm_mappings ;

#ifdef __linux__
    /* Page size in bytes (Linux only) */
    int                 pagesize ;
    /* Value found for RLIMIT_DATA (Linux only) */
    int                 rlimit_data ;
#endif
} qfits_memory_table ;

/* Various infos about the pointers */
/* List of pointers (outside of cells for efficiency reason) */
static void *   qfits_memory_p_val[QFITS_MEMORY_MAXPTRS] ;
/* Pointed size in bytes */
static size_t   qfits_memory_p_size[QFITS_MEMORY_MAXPTRS] ;
#if (QFITS_MEMORY_DEBUG>=1)
/* Name of the source file where the alloc was requested */
static char *   qfits_memory_p_filename[QFITS_MEMORY_MAXPTRS] ;
/* Line number where the alloc was requested */
static int      qfits_memory_p_lineno[QFITS_MEMORY_MAXPTRS] ;
#endif
/* Memory type: RAM, swap, or mapped file */
static char     qfits_memory_p_memtype[QFITS_MEMORY_MAXPTRS] ;
/* Swap memory only */
/* Swap file ID */
static int      qfits_memory_p_swapfileid[QFITS_MEMORY_MAXPTRS] ;
/* Swap file descriptor */
static int      qfits_memory_p_swapfd[QFITS_MEMORY_MAXPTRS] ;
/* Mapped files only */
/* Name of mapped file */
static char     qfits_memory_p_mm_filename[QFITS_MEMORY_MAXPTRS][MAPFILENAMESZ];
/* Hash of mapped file name for quick search */
static unsigned qfits_memory_p_mm_hash[QFITS_MEMORY_MAXPTRS] ;
/* Reference counter for this pointer */
static int      qfits_memory_p_mm_refcount[QFITS_MEMORY_MAXPTRS] ;

/*-----------------------------------------------------------------------------
                    Private function prototypes 
 -----------------------------------------------------------------------------*/

static unsigned qfits_memory_hash(char *) ;
static void qfits_memory_init(void) ;
static void qfits_memory_cleanup(void);
static int qfits_memory_addcell(void*, size_t, const char*, int, char, int, 
        int, char*) ;
static int qfits_memory_remcell(int) ;
static void qfits_memory_dumpcell(int, FILE*) ;
static char * qfits_memory_tmpfilename(int) ;
static char * strdup_(const char * str) ;
void qfits_memory_status_(const char *, int) ;

/*----------------------------------------------------------------------------*/
/**
 * @defgroup    qfits_memory     POSIX-compatible extended memory handling
 *
 * qfits_memory is a small and efficient module offering memory extension 
 * capabitilies to ANSI C programs running on POSIX-compliant systems. It
 * offers several useful features such as memory leak detection, protection for 
 * free on NULL or unallocated pointers, and virtually unlimited memory space.
 * qfits_memory requires the @c mmap() system call to be implemented in the 
 * local C library to function. This module has been tested on a number of 
 * current Unix * flavours and is reported to work fine.
 * The current limitation is the limited number of pointers it can handle at
 * the same time.
 */
/*----------------------------------------------------------------------------*/
/**@{*/

/*-----------------------------------------------------------------------------
                            Function codes
 -----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------*/
/**
  @brief    Allocate memory.
  @param    size        Size (in bytes) to allocate.
  @param    filename    Name of the file where the alloc took place.
  @param    lineno      Line number in the file.
  @return   1 newly allocated pointer.

  This function is a replacement call for malloc. It should never be called
  directly but through a macro instead, as:

  @code
  qfits_memory_malloc(size, __FILE__, __LINE__)
  @endcode
 */
/*----------------------------------------------------------------------------*/
void * qfits_memory_malloc(
        size_t          size, 
        const char  *   filename, 
        int             lineno)
{
    void    *   ptr ;
    char    *   fname ;
    int         swapfileid ;
    int         swapfd ;
    char        wbuf[MEMPAGESZ] ;
    int         nbufs ;
    int         memtype ;
    int         i ;
    int         pos ;
#ifdef __linux__
    int         p ;
#endif

    /* If QFITS_MEMORY_MODE is 0 or 1, do not use the qfits_memory model  */
    if (QFITS_MEMORY_MODE == 0) return malloc(size);
    else if (QFITS_MEMORY_MODE == 1) {
        ptr = malloc(size);
        if (ptr == NULL) exit(1) ;
        else return ptr ;
    }
    
    /* Initialize table if needed */
    if (qfits_memory_initialized==0) {
        qfits_memory_init() ;
        qfits_memory_initialized++ ;
    }

    /* Protect the call */
    if (size==0) {
        qfits_mem_debug(
            fprintf(stderr, "qfits_mem: malloc called with 0 size - %s (%d)\n",
                    filename, lineno);
        );
        return NULL ;
    }

    /* Try to allocate in memory */
#ifdef __linux__
    /* Linux does not honor the RLIMIT_DATA limit.
     * The only way to limit the amount of memory taken by
     * a process is to set RLIMIT_AS, which unfortunately also
     * limits down the maximal amount of memory addressable with
     * mmap() calls, making on-the-fly swap space creation useless
     * in this module. To avoid this, the RLIMIT_DATA value
     * is honored here with this test.
     */
    ptr = NULL ;
    if (qfits_memory_table.rlimit_data<1) {
        /* No limit set on RLIMIT_DATA: proceed with malloc */
        ptr = malloc(size);
    } else if (qfits_memory_table.alloc_total+size <= 
            (size_t)qfits_memory_table.rlimit_data) {
        /* Next allocation will still be within limits: proceed */
        ptr = malloc(size);
    }
#else
    ptr = malloc(size);
#endif
    if (ptr==NULL) {
        /* No more RAM available: try to allocate private swap */
        qfits_mem_debug(
            fprintf(stderr, "qfits_mem: hit a NULL pointer -- swapping\n");
        );

        /* Create swap file with rights: rw-rw-rw- */
        swapfileid = ++ qfits_memory_table.file_reg ;
        fname = qfits_memory_tmpfilename(swapfileid);
        swapfd = open(fname, O_RDWR | O_CREAT, 0666);
        if (swapfd==-1) {
            fprintf(stderr, "qfits_mem: cannot create swap file\n");
            exit(-1);
        }
        fchmod(swapfd, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);

        /* Compute number of passes to insert buffer */
        nbufs = size / MEMPAGESZ ;
        if (size % MEMPAGESZ != 0) nbufs ++ ;

        /* Dump empty buffers into file */
        memset(wbuf, 0, MEMPAGESZ);
        for (i=0 ; i<nbufs ; i++) {
            if (write(swapfd, wbuf, MEMPAGESZ)==-1) {
                perror("write");
                fprintf(stderr,
                        "qfits_mem: fatal error: cannot create swapfile\n");
                close(swapfd);
                remove(fname);
                exit(-1);
            }
        }

        /* mmap() the swap file */
        ptr = (void*)mmap(0,
                          nbufs * MEMPAGESZ,
                          PROT_READ | PROT_WRITE,
                          MAP_PRIVATE,
                          swapfd,
                          0);
        if ((char*)ptr == (char*)-1) {
            perror("mmap");
            fprintf(stderr,
                    "qfits_mem: fatal error: mmap failed for swap file\n");
            close(swapfd);
            remove(fname);
            exit(-1);
        }

        qfits_mem_debug(
            fprintf(stderr, "qfits_mem: swap [%s] created for %ld bytes\n", 
                fname, (long)size);
        );

        memtype = MEMTYPE_SWAP ;
        qfits_memory_table.alloc_swap += size ;
        qfits_memory_table.nswapfiles ++ ;
    } else {
        /* Memory allocation succeeded */
#ifdef __linux__
        /*
         * On Linux, the returned pointer might not be honored later.
         * To make sure the returned memory is actually usable, it has to
         * be touched. The following will touch one byte every 'pagesize'
         * bytes to make sure all blocks are visited and properly allocated
         * by the OS.
         */
        qfits_mem_debug(
            fprintf(stderr, "qfits_mem: touching memory (Linux)\n");
        );
        for (p=0 ; p<(int)size ; p+=qfits_memory_table.pagesize) 
            ((char*)ptr)[p] = 0;
#endif
        swapfd = -1 ;
        swapfileid = -1 ;
        memtype = MEMTYPE_RAM ;
        qfits_memory_table.alloc_ram   += size ;
    }
    
    /* Print out message in debug mode */
    qfits_mem_debug(
        fprintf(stderr, "qfits_mem: %p alloc(%ld) in %s (%d)\n",
            ptr, (long)size, filename, lineno) ;
    );

    /* Add cell into general table */
    pos = qfits_memory_addcell(  ptr,
                            size,
                            filename,
                            lineno,
                            memtype,
                            swapfileid,
                            swapfd,
                            NULL);
    /* Adjust size */
    qfits_memory_table.alloc_total += size ;
    /* Remember biggest allocated block */
    if (qfits_memory_table.alloc_total > qfits_memory_table.alloc_max)
        qfits_memory_table.alloc_max = qfits_memory_table.alloc_total ;

    /* Insert memory stamp */
    return (void*)ptr ;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Allocate memory.
  @param    nmemb       Number of elements to allocate.
  @param    size        Size (in bytes) of each element.
  @param    filename    Name of the file where the alloc took place.
  @param    lineno      Line number in the file.
  @return   1 newly allocated pointer.

  This function is a replacement call for calloc. It should never be called
  directly but through a macro instead, as:

  @code
  qfits_memory_calloc(nmemb, size, __FILE__, __LINE__)
  @endcode
 */
/*----------------------------------------------------------------------------*/
void * qfits_memory_calloc(
        size_t          nmemb, 
        size_t          size, 
        const char  *   filename, 
        int             lineno)
{
    void    *   ptr ;

    /* If QFITS_MEMORY_MODE is 0 or 1, do not use the qfits_memory model  */
    if (QFITS_MEMORY_MODE == 0) return calloc(nmemb, size) ;
    else if (QFITS_MEMORY_MODE == 1) {
        ptr = calloc(nmemb, size) ;
        if (ptr == NULL) exit(1) ;
        else return ptr ;
    }
    
    ptr = qfits_memory_malloc(nmemb * size, filename, lineno) ;
    return memset(ptr, 0, nmemb * size) ;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Map a file's contents to memory as a char pointer.
  @param    name        Name of the file to map
  @param    offs        Offset to the first mapped byte in file.
  @param    size        Returned size of the mapped file in bytes.
  @param    srcname     Name of the source file making the call.
  @param    srclin      Line # where the call was made.
  @return   A pointer to char, to be freed using qfits_memory_free().

  This function takes in input the name of a file. It tries to map the file 
  into memory and if it succeeds, returns the file's contents as a char pointer.
  It also modifies the input size variable to be the size of the mapped file in
  bytes. This function is normally never directly called but through the 
  falloc() macro.

  The offset indicates the starting point for the mapping, i.e. if you are not 
  interested in mapping the whole file but only from a given place.

  The returned pointer ptr must be deallocated with qfits_memory_fdealloc(ptr)
 */
/*----------------------------------------------------------------------------*/
char * qfits_memory_falloc(
        char        *   name,
        size_t          offs,
        size_t      *   size,
        const char  *   srcname,
        int             srclin)
{
    unsigned        mm_hash ;
    char        *   ptr ;
    struct stat     sta ;
    int             fd ;
    int             nptrs ;
    int             i ;

    /* If QFITS_MEMORY_MODE is 0 or 1, do not use the qfits_memory model  */
    if ((QFITS_MEMORY_MODE == 0) || (QFITS_MEMORY_MODE == 1)) {

        if (size!=NULL) *size = 0 ;

        /* Check file's existence and compute its size */
        if (stat(name, &sta)==-1) {
            qfits_mem_debug(
                fprintf(stderr, "qfits_mem: cannot stat file %s - %s (%d)\n",
                        name, srcname, srclin);
            );
            if (QFITS_MEMORY_MODE == 0) return NULL ;
            else exit(1) ;
        }
        /* Check offset request does not go past end of file */
        if (offs>=(size_t)sta.st_size) {
            qfits_mem_debug(
                fprintf(stderr,
                    "qfits_mem: falloc offsets larger than file size");
            );
            if (QFITS_MEMORY_MODE == 0) return NULL ;
            else exit(1) ;
        }

        /* Open file */
        if ((fd=open(name, O_RDONLY))==-1) {
            qfits_mem_debug(
                fprintf(stderr, "qfits_mem: cannot open file %s - %s (%d)\n",
                        name, srcname, srclin);
            );
            if (QFITS_MEMORY_MODE == 0) return NULL ;
            else exit(1) ;
        }

        /* Memory-map input file */
        ptr = (char*)mmap(0, sta.st_size, 
                PROT_READ | PROT_WRITE, MAP_PRIVATE,fd,0);
        
        /* Close file */
        close(fd);
        if (ptr == (char*)-1 || ptr==NULL) {
            qfits_mem_debug(
                perror("mmap");
                fprintf(stderr, "qfits_mem: falloc cannot mmap file %s", name);
            );
            if (QFITS_MEMORY_MODE == 0) return NULL ;
            else exit(1) ;
        }

        qfits_mem_debug(
            fprintf(stderr,
                    "qfits_mem: falloc mmap succeeded for [%s] - %s (%d)\n",
                    name, srcname, srclin);
        );

        if (size!=NULL) (*size) = sta.st_size ;
        
        return ptr + offs ;
    }

    /* Protect the call */
    if (size!=NULL) *size = 0 ;

    /* Initialize table if needed */
    if (qfits_memory_initialized==0) {
        qfits_memory_init() ;
        qfits_memory_initialized++ ;
    }

    if (qfits_memory_table.ncells>0) {
        /* Check if file has already been mapped */
        /* Compute hash for this name */
        mm_hash = qfits_memory_hash(name);
        /* Loop over all memory cells */
        nptrs=0 ;
        for (i=0 ; i<QFITS_MEMORY_MAXPTRS ; i++) {
            if (qfits_memory_p_val[i]!=NULL)
                nptrs++ ;
            if ((qfits_memory_p_val[i]!=NULL) &&
                (qfits_memory_p_mm_filename[i] != NULL) &&
                (qfits_memory_p_mm_hash[i] == mm_hash)) {
                if (!strncmp(qfits_memory_p_mm_filename[i], name,
                             MAPFILENAMESZ)) {
                    /* File already mapped */
                    /* Check offset consistency wrt file size */
                    if (offs >= qfits_memory_p_size[i]) {
                        qfits_mem_debug(
                            fprintf(stderr,
                                "qfits_mem: falloc offset larger than file sz");
                        );
                        return NULL ;
                    }
                    /* Increase reference counter */
                    qfits_memory_p_mm_refcount[i] ++ ;
                    qfits_mem_debug(
                        fprintf(stderr,
                                "qfits_mem: incref on %s (%d mappings)\n",
                                name,
                                qfits_memory_p_mm_refcount[i]);
                    );
                    /* Increase number of mappings */
                    qfits_memory_table.n_mm_mappings ++ ;
                    /* Build up return pointer */
                    ptr = (char*)qfits_memory_p_val[i] + offs ;
                    /* Available size is filesize minus offset */
                    if (size!=NULL) {
                        *size = qfits_memory_p_size[i] - offs ;
                    }
                    /* Return constructed pointer as void * */
                    return (void*)ptr ;
                }
            }
            if (nptrs>=qfits_memory_table.ncells) break ;
        }
    }

    /* First mapping attempt for this file */
    /* Check file's existence and compute its size */
    if (stat(name, &sta)==-1) {
        qfits_mem_debug(
            fprintf(stderr, "qfits_mem: cannot stat file %s - %s (%d)\n",
                    name, srcname, srclin);
        );
        return NULL ;
    }
    /* Check offset request does not go past end of file */
    if (offs>=(size_t)sta.st_size) {
        qfits_mem_debug(
            fprintf(stderr,
                "qfits_mem: falloc offsets larger than file size");
        );
        return NULL ;
    }

    /* Open file */
    if ((fd=open(name, O_RDONLY))==-1) {
        qfits_mem_debug(
            fprintf(stderr, "qfits_mem: cannot open file %s - %s (%d)\n",
                    name, srcname, srclin);
        );
        return NULL ;
    }

    /* Memory-map input file */
    ptr = (char*)mmap(0, sta.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE,fd,0);
    
    /* Close file */
    close(fd);
    if (ptr == (char*)-1 || ptr==NULL) {
        qfits_mem_debug(
            perror("mmap");
            fprintf(stderr, "qfits_mem: falloc cannot mmap file %s", name);
        );
        return NULL ;
    }

    qfits_memory_table.n_mm_files ++ ;
    qfits_memory_table.n_mm_mappings ++ ;
    qfits_mem_debug(
        fprintf(stderr,
                "qfits_mem: falloc mmap succeeded for [%s] - %s (%d)\n",
                name, srcname, srclin);
    );

    /* Add cell into general table */
    (void) qfits_memory_addcell((void*)ptr, sta.st_size, srcname, srclin, 
                           MEMTYPE_MMAP, -1, -1, name) ;

    if (size!=NULL) (*size) = sta.st_size ;
    
    return ptr + offs ;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Free memory that has been allocated with falloc
  @param    ptr         Pointer to free.
  @param    offs        Offset to the first mapped byte in file.
  @param    size        size to unmap
  @param    filename    Name of the file where the dealloc took place.
  @param    lineno      Line number in the file.
  @return   void
 */
/*----------------------------------------------------------------------------*/
void qfits_memory_fdealloc(
        void        *   ptr, 
        size_t          offs,
        size_t          size, 
        const char  *   filename, 
        int             lineno)
{
    int     i ;
    int     pos ;
    char *  swapname ;
    int     nptrs ;
    int     ii;

    /* Do nothing for a NULL pointer */
    if (ptr==NULL) {
        /* Output a warning */
        fprintf(stderr, "qfits_mem: free requested on NULL ptr -- %s (%d)\n",
                filename, lineno);
        return ;
    }
    
    /* If QFITS_MEMORY_MODE is 0 or 1, do not use the qfits_memory model  */
    if ((QFITS_MEMORY_MODE == 0) || (QFITS_MEMORY_MODE == 1)) {
        munmap((char*)(ptr)-offs, size) ;
        return ;
    }
    
    /* Locate pointer in main table */
    nptrs = 0 ;
    pos = -1 ;
    i = PTR_HASH(ptr);
    for (ii=0 ; ii<QFITS_MEMORY_MAXPTRS ; ii++) {
        if (++i == QFITS_MEMORY_MAXPTRS) i = 0;
        if (qfits_memory_p_val[i] == NULL) continue ;
        nptrs++ ;
        if (qfits_memory_p_val[i] == ptr) {
            pos=i ;
            break ;
        }
        if (qfits_memory_p_memtype[i]==MEMTYPE_MMAP) {
            if (((char*)qfits_memory_p_val[i]<=(char*)ptr) &&
                (((char*)qfits_memory_p_val[i] + 
                  qfits_memory_p_size[i]) >= (char*)ptr)) {
                pos = i ;
                break ;
            }
        }
        if (nptrs>=qfits_memory_table.ncells) break ;
    }
    if (pos==-1) {
        fprintf(stderr,
                "qfits_mem: %s (%d) free req. on unallocated pointer (%p)\n",
                filename, lineno, ptr);
        /* Pointer sent to system's free() function, maybe it should not? */
        free(ptr);
        return ;
    }

    /* Deallocate pointer */
    switch (qfits_memory_p_memtype[pos]) {
        case MEMTYPE_RAM:
            /* --- RAM pointer */
            /* Free normal memory pointer */
            free(ptr);
            qfits_memory_table.alloc_ram -= qfits_memory_p_size[pos] ;
            break ;
        case MEMTYPE_SWAP:
            /* --- SWAP pointer */
            swapname = qfits_memory_tmpfilename(qfits_memory_p_swapfileid[pos]);
            qfits_mem_debug(
                    fprintf(stderr, "qfits_mem: deallocating swap file [%s]\n", 
                        swapname);
            );
            /* Munmap file */
            if (munmap(ptr, qfits_memory_p_size[pos])!=0) {
                qfits_mem_debug( perror("munmap"); );
            }
            /* Close swap file */
            if (close(qfits_memory_p_swapfd[pos])==-1) {
                qfits_mem_debug( perror("close"); );
            }
            /* Remove swap file */
            if (remove(swapname)!=0) {
                qfits_mem_debug( perror("remove"); );
            }
            qfits_memory_table.alloc_swap -= qfits_memory_p_size[pos] ;
            qfits_memory_table.nswapfiles -- ;
            break ;
        case MEMTYPE_MMAP:
            /* --- MEMORY-MAPPED pointer */
            /* Decrease reference count */
            qfits_memory_p_mm_refcount[pos] -- ;
            /* Decrease total number of mappings */
            qfits_memory_table.n_mm_mappings -- ;
            /* Non-null ref count means the file stays mapped */
            if (qfits_memory_p_mm_refcount[pos]>0) {
                qfits_mem_debug(
                    fprintf(stderr, "qfits_mem: decref on %s (%d mappings)\n",
                            qfits_memory_p_mm_filename[pos],
                            qfits_memory_p_mm_refcount[pos]);
                );
                return ;
            }
            /* Ref count reached zero: unmap the file */
            qfits_mem_debug(
                    fprintf(stderr,
                        "qfits_mem: unmapping file %s\n",
                        qfits_memory_p_mm_filename[pos]);
            );
            munmap((char*)qfits_memory_p_val[pos],
                    qfits_memory_p_size[pos]);
            /* Decrease total number of mapped files */
            qfits_memory_table.n_mm_files -- ;
            break ;
        default:
            qfits_mem_debug(
                    fprintf(stderr, "qfits_mem: unknown memory cell type???");
            );
            break ;
    }

    if (qfits_memory_p_memtype[pos]!=MEMTYPE_MMAP) {
        /* Adjust allocated totals */
        qfits_memory_table.alloc_total -= qfits_memory_p_size[pos] ;

        /* Print out message in debug mode */
        qfits_mem_debug(
            fprintf(stderr, "qfits_mem: free(%p) %ld bytes in %s (%d)\n",
                    ptr,
                    (long)qfits_memory_p_size[pos],
                    filename,
                    lineno);
        );
    }
    /* Remove cell from main table */
    qfits_memory_remcell(pos) ;
    return ;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Free memory.
  @param    ptr         Pointer to free.
  @param    filename    Name of the file where the dealloc took place.
  @param    lineno      Line number in the file.
  @return   void

  Free the memory associated to a given pointer. Prints out a warning on stderr
  if the requested pointer is NULL or cannot be found in the extended memory 
  table.
 */
/*----------------------------------------------------------------------------*/
void qfits_memory_free(
        void        *   ptr, 
        const char  *   filename, 
        int             lineno)
{
    int     i ;
    int     pos ;
    char *  swapname ;
    int     nptrs ;
    int     ii;

    /* If QFITS_MEMORY_MODE is 0 or 1, do not use the qfits_memory model  */
    if ((QFITS_MEMORY_MODE == 0) || (QFITS_MEMORY_MODE == 1)) {
        free(ptr);
        return ;
    }
    
    /* Do nothing for a NULL pointer */
    if (ptr==NULL) {
        /* Output a warning */
        fprintf(stderr, "qfits_mem: free requested on NULL ptr -- %s (%d)\n",
                filename, lineno);
        return ;
    }

    /* Locate pointer in main table */
    nptrs = 0 ;
    pos = -1 ;
    i = PTR_HASH(ptr);
    for (ii=0 ; ii<QFITS_MEMORY_MAXPTRS ; ii++) {
        if (++i == QFITS_MEMORY_MAXPTRS) i = 0;
        if (qfits_memory_p_val[i] == NULL) continue ;
        nptrs++ ;
        if (qfits_memory_p_val[i] == ptr) {
            pos=i ;
            break ;
        }
        if (qfits_memory_p_memtype[i]==MEMTYPE_MMAP) {
            if (((char*)qfits_memory_p_val[i]<=(char*)ptr) &&
                (((char*)qfits_memory_p_val[i] + 
                  qfits_memory_p_size[i]) >= (char*)ptr)) {
                pos = i ;
                break ;
            }
        }
        if (nptrs>=qfits_memory_table.ncells) break ;
    }
    if (pos==-1) {
        fprintf(stderr,
                "qfits_mem: %s (%d) free requested on unallocated ptr (%p)\n",
                filename, lineno, ptr);
        /* Pointer sent to system's free() function, maybe it should not? */
        free(ptr);
        return ;
    }

    /* Deallocate pointer */
    switch (qfits_memory_p_memtype[pos]) {
        case MEMTYPE_RAM:
            /* --- RAM pointer */
            /* Free normal memory pointer */
            free(ptr);
            qfits_memory_table.alloc_ram -= qfits_memory_p_size[pos] ;
            break ;
        case MEMTYPE_SWAP:
            /* --- SWAP pointer */
            swapname = qfits_memory_tmpfilename(qfits_memory_p_swapfileid[pos]);
            qfits_mem_debug(
                    fprintf(stderr, "qfits_mem: deallocating swap file [%s]\n", 
                        swapname);
            );
            /* Munmap file */
            if (munmap(ptr, qfits_memory_p_size[pos])!=0) {
                qfits_mem_debug( perror("munmap"); );
            }
            /* Close swap file */
            if (close(qfits_memory_p_swapfd[pos])==-1) {
                qfits_mem_debug( perror("close"); );
            }
            /* Remove swap file */
            if (remove(swapname)!=0) {
                qfits_mem_debug( perror("remove"); );
            }
            qfits_memory_table.alloc_swap -= qfits_memory_p_size[pos] ;
            qfits_memory_table.nswapfiles -- ;
            break ;
        case MEMTYPE_MMAP:
            /* --- MEMORY-MAPPED pointer */
            /* Decrease reference count */
            qfits_memory_p_mm_refcount[pos] -- ;
            /* Decrease total number of mappings */
            qfits_memory_table.n_mm_mappings -- ;
            /* Non-null ref count means the file stays mapped */
            if (qfits_memory_p_mm_refcount[pos]>0) {
                qfits_mem_debug(
                    fprintf(stderr, "qfits_mem: decref on %s (%d mappings)\n",
                            qfits_memory_p_mm_filename[pos],
                            qfits_memory_p_mm_refcount[pos]);
                );
                return ;
            }
            /* Ref count reached zero: unmap the file */
            qfits_mem_debug(
                    fprintf(stderr,
                        "qfits_mem: unmapping file %s\n",
                        qfits_memory_p_mm_filename[pos]);
            );
            munmap((char*)qfits_memory_p_val[pos],
                    qfits_memory_p_size[pos]);
            /* Decrease total number of mapped files */
            qfits_memory_table.n_mm_files -- ;
            break ;
        default:
            qfits_mem_debug(
                    fprintf(stderr, "qfits_mem: unknown memory cell type???");
            );
            break ;
    }

    if (qfits_memory_p_memtype[pos]!=MEMTYPE_MMAP) {
        /* Adjust allocated totals */
        qfits_memory_table.alloc_total -= qfits_memory_p_size[pos] ;

        /* Print out message in debug mode */
        qfits_mem_debug(
            fprintf(stderr, "qfits_mem: free(%p) %ld bytes in %s (%d)\n",
                    ptr,
                    (long)qfits_memory_p_size[pos],
                    filename,
                    lineno);
        );
    }
    /* Remove cell from main table */
    qfits_memory_remcell(pos) ;
    return ;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Re-Allocate memory.
  @param    ptr         Pointer to free.
  @param    size        Size (in bytes) to allocate.
  @param    filename    Name of the file where the alloc took place.
  @param    lineno      Line number in the file.
  @return   1 newly allocated pointer.

  This function is a replacement call for realloc. It should never be called
  directly but through a macro instead, as:

  @code
  qfits_memory_realloc(nmemb, size, __FILE__, __LINE__)
  @endcode
 */
/*----------------------------------------------------------------------------*/
void * qfits_memory_realloc(
        void        *   ptr, 
        size_t          size, 
        const char  *   filename, 
        int             lineno)
{
    void    *   ptr2 ;
    size_t      small_sz ;
    size_t      ptr_sz ;
    int         pos = -1 ;
    int         i ;
    
    /* If QFITS_MEMORY_MODE is 0 or 1, do not use the qfits_memory model  */
    if (QFITS_MEMORY_MODE == 0) return realloc(ptr, size) ;
    else if (QFITS_MEMORY_MODE == 1) {
        ptr2 = realloc(ptr, size) ;
        if (ptr2 == NULL) exit(1) ;
        else return ptr2 ;
    }

    if (ptr == NULL) return qfits_memory_malloc(size, filename, lineno) ;

    /* Get the pointer size */
    for (i=0 ; i<QFITS_MEMORY_MAXPTRS ; i++) {
        if (qfits_memory_p_val[i] == NULL) continue ;
        if (qfits_memory_p_val[i] == ptr) {
            pos = i ;
            break ;
        }
    }
    if (pos==-1) {
        fprintf(stderr,
            "qfits_mem: %s (%d) realloc requested on unallocated ptr (%p)\n",
            filename, lineno, ptr);
        /* Pointer sent to system's realloc() function, maybe it should not? */
        return realloc(ptr, size) ;
    }
    ptr_sz = qfits_memory_p_size[pos] ;
    
    /* Compute the smaller size */
    small_sz = size < ptr_sz ? size : ptr_sz ;
    
    /* Allocate the new pointer */
    ptr2 = qfits_memory_malloc(size, filename, lineno) ;
    
    /* Copy the common data */
    memcpy(ptr2, ptr, small_sz) ;

    /* Free the passed ptr */
    qfits_memory_free(ptr, filename, lineno) ;
    
    /* Return  */
    return ptr2 ;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Duplicate a string using calloc.
  @param    s       String to duplicate.
  @param    filename    Name of the file where the call took place.
  @param    lineno      Line number in the file.
  @return   1 newly allocated character string.

  This function calls in turn calloc to perform the allocation. It should
  never be called directly but only through a macro, like:

  @code
  qfits_memory_strdup(s, __FILE__, __LINE__)
  @endcode

  This function calls qfits_memory_malloc() to do the allocation.
 */
/*----------------------------------------------------------------------------*/
char * qfits_memory_strdup(
        const char  *   s, 
        const char  *   filename, 
        int             lineno)
{
    char    *   t ;
    
    /* If QFITS_MEMORY_MODE is 0 or 1, do not use the qfits_memory model  */
    if (QFITS_MEMORY_MODE == 0) return strdup_(s) ;
    else if (QFITS_MEMORY_MODE == 1) {
        t = strdup_(s) ;
        if (t == NULL) exit(1) ;
        else return t ;
    }

    if (s==NULL) return NULL ;
    t = qfits_memory_malloc(1+strlen(s), filename, lineno);
    return strcpy(t, s);
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Display memory status information.
  @return   void

  This function is meant for debugging purposes, but it is recommended to
  call it at the end of every executable making use of the extended memory
  features. 
 */
/*----------------------------------------------------------------------------*/
void qfits_memory_status(void)
{
    int     i ;

    /* If QFITS_MEMORY_MODE is 0 or 1, do not use the qfits_memory model  */
    if ((QFITS_MEMORY_MODE == 0) || (QFITS_MEMORY_MODE == 1)) return ;
    
#if (QFITS_MEMORY_DEBUG>=1)
    fprintf(stderr, "#----- memory diagnostics -----\n") ;

    fprintf(stderr,
            "#- Peak memory usage\n"
            "ALL_maxalloc_kb     %ld\n"
            "ALL_maxpointers     %d\n",
            (long)(qfits_memory_table.alloc_max/1024),
            qfits_memory_table.max_cells);
    fprintf(stderr,
            "#- Local implementation\n"
            "TAB_ptrs            %d\n"
            "TAB_size            %u bytes\n",
            QFITS_MEMORY_MAXPTRS,
            (unsigned)sizeof(qfits_memory_table));
#ifdef __linux__
    fprintf(stderr,
            "#- Linux specific\n"
            "LINUX_pagesize      %d bytes\n"
            "LINUX_RLIMIT_DATA   %d kb\n",
            qfits_memory_table.pagesize,
            qfits_memory_table.rlimit_data);
#endif
#endif

    if (qfits_memory_table.ncells<1) return ;
    fprintf(stderr, "#----- memory diagnostics -----\n") ;

    fprintf(stderr,
            "#- ALL status\n"
            "ALL_npointers       %d\n"
            "ALL_size            %ld\n"
            "ALL_maxalloc_kb     %ld\n"
            "ALL_maxpointers     %d\n",
            qfits_memory_table.ncells,
            (long)qfits_memory_table.alloc_total,
            (long)(qfits_memory_table.alloc_max/1024),
            qfits_memory_table.max_cells);

    if (qfits_memory_table.alloc_ram > 0) {
        fprintf(stderr, 
                "#- RAM status\n"
                "RAM_alloc           %ld\n",
                (long)qfits_memory_table.alloc_ram);
    }
    if (qfits_memory_table.alloc_swap > 0) {
        fprintf(stderr,
                "#- SWP status\n"
                "SWP_alloc           %ld\n"
                "SWP_files           %d\n",
                (long)qfits_memory_table.alloc_swap,
                qfits_memory_table.nswapfiles);
    }

    if (qfits_memory_table.n_mm_files>0) {
        fprintf(stderr,
                "#- MAP status\n"
                "MAP_files           %d\n"
                "MAP_mappings        %d\n",
                qfits_memory_table.n_mm_files,
                qfits_memory_table.n_mm_mappings);
    }

    fprintf(stderr, "#- pointer details\n");
    for (i=0 ; i<QFITS_MEMORY_MAXPTRS; i++) {
        qfits_memory_dumpcell(i, stderr);
    }
    return ;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Tell if there is still some memory allocated
  @return   1 if the memory table is tempty, 0 if no, 
            -1 if the memory model is off
 */
/*----------------------------------------------------------------------------*/
int qfits_memory_is_empty(void)
{
    if ((QFITS_MEMORY_MODE == 0) || (QFITS_MEMORY_MODE == 1)) return -1 ;
    if (qfits_memory_table.ncells<1) return 1 ;
    else return 0 ;
}

/**@}*/

/*
 * posted to comp.sys.next.programmer:
 * 
 *   
 * From: moser@ifor.math.ethz.ch (Dominik Moser,CLV A4,2 40 19,720 49 89)
 * Subject: Re: Compile problems (pgp 2.6.3i)
 * Date: 10 Jul 1996 06:50:42 GMT
 * Organization: Swiss Federal Institute of Technology (ETHZ)
 * References: <4rrhvj$6fr@bagan.srce.hr>
 * Message-ID: <4rvjs2$6oh@elna.ethz.ch>
 * 
 * Most systems don't have this (yet)
 
 */
static char * strdup_(const char * str)
{
    char    *   p ;

    if ((p = malloc(strlen(str)+1)) == NULL)
    return((char *) NULL);

    (void) strcpy(p, str);

    return(p);
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Hash a string to an unsigned value.
  @param    key     String to hash
  @return   1 unsigned value as a hash for the given string.
  
  This hash function has been taken from an Article in Dr Dobbs Journal. This 
  is normally a collision-free function, distributing keys evenly. The key is 
  stored anyway in the struct so that collision can be avoided by comparing the
  key itself in last resort.
 */
/*----------------------------------------------------------------------------*/
static unsigned qfits_memory_hash(char * key)
{
    int         len ;
    unsigned    hash ;
    int         i ;

    len = strlen(key);
    for (hash=0, i=0 ; i<len ; i++) {
        hash += (unsigned)key[i] ;
        hash += (hash<<10);
        hash ^= (hash>>6) ;
    }
    hash += (hash <<3);
    hash ^= (hash >>11);
    hash += (hash <<15);
    return hash ;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Initialize extended memory features.
  @return   void

  This function is implicitly called by the first malloc() or calloc() or 
  strdup_() execution. It allocates a minimal number of memory cells into
  the global extended memory table. It also install atexit routines the first 
  time it is called, and increases the number of possible descriptors to the 
  maximum.
 */
/*----------------------------------------------------------------------------*/
static void qfits_memory_init(void)
{
    struct rlimit rlim ;

    qfits_mem_debug(
        fprintf(stderr,
                "qfits_mem: initializing main table size=%d ptrs (%ld bytes)\n",
                QFITS_MEMORY_MAXPTRS,
                (long)sizeof(qfits_memory_table));
    );
    /* Initialize memory table */
    memset(&qfits_memory_table, 0, sizeof(qfits_memory_table));

    /* Install cleanup routine at exit */
    atexit(qfits_memory_cleanup);
        
    /* Increase number of descriptors to maximum */
    getrlimit(RLIMIT_NOFILE, &rlim) ;
    qfits_mem_debug(
        fprintf(stderr, "qfits_mem: increasing from %ld to %ld file handles\n",
                (long)rlim.rlim_cur,
                (long)rlim.rlim_max);
    );
    rlim.rlim_cur = rlim.rlim_max ;
    setrlimit(RLIMIT_NOFILE, &rlim) ;

#ifdef __linux__
    /* Get RLIMIT_DATA on Linux */
    getrlimit(RLIMIT_DATA, &rlim);
    qfits_memory_table.rlimit_data = rlim.rlim_cur ;
    qfits_mem_debug(
        fprintf(stderr, "qfits_mem: got RLIMIT_DATA=%d\n",
                qfits_memory_table.rlimit_data);
    );
    /* Get page size on Linux */
    qfits_memory_table.pagesize = getpagesize();

#endif
    return ;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Removes all swap files.
  @return   void

  This routine will delete all swap files from the temporary area.
 */
/*----------------------------------------------------------------------------*/
static void qfits_memory_cleanup(void)
{
    int     reg ;

    if (qfits_memory_table.file_reg>0) {
        qfits_mem_debug(
            fprintf(stderr, "qfits_mem: cleaning up swap files... ");
        );
        /*
         * Call remove() on all possible VM files. If the file exists, it
         * is effectively removed. It it does not, ignore the error.
         * This is not the cleanest way of doing it, but this function is
         * meant to be called also in cases of emergency (e.g. segfault),
         * so it should not rely on a correct memory table.
         */
        for (reg=0 ; reg<qfits_memory_table.file_reg ; reg++) {
            remove(qfits_memory_tmpfilename(reg+1));
        }
        qfits_mem_debug(
            fprintf(stderr, "qfits_mem: done cleaning swap files\n");
        );
    }
    return ;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Add allocation cell to qfits_memory_table.
  @param    pointer         Pointer value.
  @param    size            Pointer size.
  @param    filename        Name of the C source file where alloc was done.
  @param    lineno          Line # where the allocation took place.
  @param    memtype         Memory type: RAM or SWAP.
  @param    swapfileid      Associated swap file ID (if any).
  @param    swapfd          Associated swap file descriptor (if any).
  @param    mm_filename     Mapped file name (if any)
  @return   the index in the qfits_memory_table of the added cell

  Add a memory cell in the xtended memory table to register that a new 
  allocation took place. 
  This call is not protected against illegal parameter values, so make sure 
  the passed values are correct!
 */
/*----------------------------------------------------------------------------*/
static int qfits_memory_addcell(
        void        *   pointer,
        size_t          size,
        const char  *   filename,
        int             lineno,
        char            memtype,
        int             swapfileid,
        int             swapfd,
        char        *   mm_filename)
{
    int pos, ii ;
    
    /* Check there is still some space left */
    if (qfits_memory_table.ncells >= QFITS_MEMORY_MAXPTRS) {
        fprintf(stderr, "fatal qfits_memory error: reached max pointers (%d)\n",
                QFITS_MEMORY_MAXPTRS);
        exit(-1);
    }
    /* Find an available slot */
    pos = PTR_HASH(pointer);
    for (ii = 0 ; ii<QFITS_MEMORY_MAXPTRS ; ii++) {
        if (++pos == QFITS_MEMORY_MAXPTRS) pos = 0;
        if (qfits_memory_p_val[pos] == NULL) break ;
    }
    qfits_mem_debug(
            fprintf(stderr, "qfits_mem: freecell found at pos %d\n", pos);
            );
    
    /* Store information */
    qfits_memory_p_val[pos] = pointer ;
    qfits_memory_p_size[pos] = size ;

    /* Filename and line number */
#if (QFITS_MEMORY_DEBUG>=1)
    qfits_memory_p_filename[pos] = filename ;
    qfits_memory_p_lineno[pos] = lineno ;
#endif
    
    qfits_memory_p_memtype[pos] = memtype ;
    qfits_memory_p_swapfileid[pos] = swapfileid ;
    qfits_memory_p_swapfd[pos] = swapfd ;
    
    if (mm_filename!=NULL) {
        strncpy(qfits_memory_p_mm_filename[pos], mm_filename,MAPFILENAMESZ);
        qfits_memory_p_mm_hash[pos] = qfits_memory_hash(mm_filename);
        qfits_memory_p_mm_refcount[pos] = 1 ;
    } else {
        qfits_memory_p_mm_filename[pos][0] = 0 ;
        qfits_memory_p_mm_hash[pos] = 0 ;
        qfits_memory_p_mm_refcount[pos] = 0 ;
    }
    qfits_memory_table.ncells ++ ;
    if (qfits_memory_table.ncells > qfits_memory_table.max_cells)
        qfits_memory_table.max_cells = qfits_memory_table.ncells ;
    return pos ;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Remove a memory cell from the xtended memory table.
  @param    pos     Position of the pointer in the table.
  @return   int 0 if Ok, -1 if error occurred.

  Remove the specified cell in qfits_memory_table. 
  This call is not protected against illegal parameter values, so make sure 
  the passed values are correct!
 */
/*----------------------------------------------------------------------------*/
static int qfits_memory_remcell(int pos)
{
    qfits_mem_debug(
        fprintf(stderr, "qfits_mem: removing cell from pos %d (cached)\n", pos);
    );
    /* Set pointer to NULL */
    qfits_memory_p_val[pos] = NULL ;
    /* Decrement number of allocated pointers */
    qfits_memory_table.ncells -- ;
    return 0 ;
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Dump a memory cell to an open file pointer.
  @param    cell    Cell to dump.
  @param    out     Open file pointer to dump to.
  @return   void

  This function is meant for debugging purposes only. It takes in input a
  pointer to a memory cell and dumps it to the requested file pointer (it
  is Ok to provide stdout or stderr as file pointers). If the passed
  position is invalid or the table pointer is NULL, this function returns
  immediately.
 */
/*----------------------------------------------------------------------------*/
static void qfits_memory_dumpcell(
        int         pos, 
        FILE    *   out)
{
    if (pos<0 || pos>=QFITS_MEMORY_MAXPTRS) return ;
    if (qfits_memory_p_val[pos]==NULL) return ;

    if (qfits_memory_p_memtype[pos] == MEMTYPE_MMAP) {
#if (QFITS_MEMORY_DEBUG>=1)
        fprintf(out,
            "M(%p) - %s (%d) maps [%s] for %ld bytes",
            qfits_memory_p_val[pos],
            qfits_memory_p_filename[pos],
            qfits_memory_p_lineno[pos],
            qfits_memory_p_mm_filename[pos],
            (long)qfits_memory_p_size[pos]);
#else
        fprintf(out,
            "M(%p) maps [%s] for %ld bytes",
            qfits_memory_p_val[pos],
            qfits_memory_p_mm_filename[pos],
            (long)qfits_memory_p_size[pos]);
#endif
    } else {
#if (QFITS_MEMORY_DEBUG>=1)
        fprintf(out, "%c(%p) - %s (%d) for %ld bytes",
            qfits_memory_p_memtype[pos],
            qfits_memory_p_val[pos],
            qfits_memory_p_filename[pos],
            qfits_memory_p_lineno[pos],
            (long)qfits_memory_p_size[pos]);
#else
        fprintf(out, "%c(%p) for %ld bytes",
            qfits_memory_p_memtype[pos],
            qfits_memory_p_val[pos],
            (long)qfits_memory_p_size[pos]);
#endif
    }
    if (qfits_memory_p_memtype[pos]==MEMTYPE_SWAP) {
        fprintf(out, " swf[%s][%d]",
                qfits_memory_tmpfilename(qfits_memory_p_swapfileid[pos]),
                qfits_memory_p_swapfd[pos]);
    }
    fprintf(out, "\n");
}

/*----------------------------------------------------------------------------*/
/**
  @brief    Compute filename associated to a temporary file ID.
  @param    reg     Registration number of temporary file name.
  @return   pointer to statically allocated char string.

  This function computes the valid file name associated to a temporary file
  ID. It computes the result, stores it in an internal static string and
  returns a pointer to it.
 */
/*----------------------------------------------------------------------------*/
static char * qfits_memory_tmpfilename(int reg)
{
    static char qfits_mem_tmpfilename[TMPFILENAMESZ] ;
    /* Create file name using tmp directory as a base */
    sprintf(qfits_mem_tmpfilename, "%s/vmswap_%05ld_%05x", 
            qfits_memory_tmpdirname, (long)getpid(), reg) ;
    return qfits_mem_tmpfilename ;
}