xref: /vim-8.2.3635/src/memfile.c (revision 2bf24176)
1 /* vi:set ts=8 sts=4 sw=4:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * memfile.c: Contains the functions for handling blocks of memory which can
12  * be stored in a file. This is the implementation of a sort of virtual memory.
13  *
14  * A memfile consists of a sequence of blocks. The blocks numbered from 0
15  * upwards have been assigned a place in the actual file. The block number
16  * is equal to the page number in the file. The
17  * blocks with negative numbers are currently in memory only. They can be
18  * assigned a place in the file when too much memory is being used. At that
19  * moment they get a new, positive, number. A list is used for translation of
20  * negative to positive numbers.
21  *
22  * The size of a block is a multiple of a page size, normally the page size of
23  * the device the file is on. Most blocks are 1 page long. A Block of multiple
24  * pages is used for a line that does not fit in a single page.
25  *
26  * Each block can be in memory and/or in a file. The block stays in memory
27  * as long as it is locked. If it is no longer locked it can be swapped out to
28  * the file. It is only written to the file if it has been changed.
29  *
30  * Under normal operation the file is created when opening the memory file and
31  * deleted when closing the memory file. Only with recovery an existing memory
32  * file is opened.
33  */
34 
35 #include "vim.h"
36 
37 /*
38  * Some systems have the page size in statfs.f_bsize, some in stat.st_blksize
39  */
40 #ifdef HAVE_ST_BLKSIZE
41 # define STATFS stat
42 # define F_BSIZE st_blksize
43 # define fstatfs(fd, buf, len, nul) mch_fstat((fd), (buf))
44 #else
45 # ifdef HAVE_SYS_STATFS_H
46 #  include <sys/statfs.h>
47 #  define STATFS statfs
48 #  define F_BSIZE f_bsize
49 #  ifdef __MINT__		/* do we still need this? */
50 #   define fstatfs(fd, buf, len, nul) mch_fstat((fd), (buf))
51 #  endif
52 # endif
53 #endif
54 
55 /*
56  * for Amiga Dos 2.0x we use Flush
57  */
58 #ifdef AMIGA
59 # ifdef FEAT_ARP
60 extern int dos2;			/* this is in os_amiga.c */
61 # endif
62 # ifdef SASC
63 #  include <proto/dos.h>
64 #  include <ios1.h>			/* for chkufb() */
65 # endif
66 #endif
67 
68 #define MEMFILE_PAGE_SIZE 4096		/* default page size */
69 
70 static long_u	total_mem_used = 0;	/* total memory used for memfiles */
71 
72 static void mf_ins_hash __ARGS((memfile_T *, bhdr_T *));
73 static void mf_rem_hash __ARGS((memfile_T *, bhdr_T *));
74 static bhdr_T *mf_find_hash __ARGS((memfile_T *, blocknr_T));
75 static void mf_ins_used __ARGS((memfile_T *, bhdr_T *));
76 static void mf_rem_used __ARGS((memfile_T *, bhdr_T *));
77 static bhdr_T *mf_release __ARGS((memfile_T *, int));
78 static bhdr_T *mf_alloc_bhdr __ARGS((memfile_T *, int));
79 static void mf_free_bhdr __ARGS((bhdr_T *));
80 static void mf_ins_free __ARGS((memfile_T *, bhdr_T *));
81 static bhdr_T *mf_rem_free __ARGS((memfile_T *));
82 static int  mf_read __ARGS((memfile_T *, bhdr_T *));
83 static int  mf_write __ARGS((memfile_T *, bhdr_T *));
84 static int  mf_write_block __ARGS((memfile_T *mfp, bhdr_T *hp, off_t offset, unsigned size));
85 static int  mf_trans_add __ARGS((memfile_T *, bhdr_T *));
86 static void mf_do_open __ARGS((memfile_T *, char_u *, int));
87 static void mf_hash_init __ARGS((mf_hashtab_T *));
88 static void mf_hash_free __ARGS((mf_hashtab_T *));
89 static void mf_hash_free_all __ARGS((mf_hashtab_T *));
90 static mf_hashitem_T *mf_hash_find __ARGS((mf_hashtab_T *, blocknr_T));
91 static void mf_hash_add_item __ARGS((mf_hashtab_T *, mf_hashitem_T *));
92 static void mf_hash_rem_item __ARGS((mf_hashtab_T *, mf_hashitem_T *));
93 static int mf_hash_grow __ARGS((mf_hashtab_T *));
94 
95 /*
96  * The functions for using a memfile:
97  *
98  * mf_open()	    open a new or existing memfile
99  * mf_open_file()   open a swap file for an existing memfile
100  * mf_close()	    close (and delete) a memfile
101  * mf_new()	    create a new block in a memfile and lock it
102  * mf_get()	    get an existing block and lock it
103  * mf_put()	    unlock a block, may be marked for writing
104  * mf_free()	    remove a block
105  * mf_sync()	    sync changed parts of memfile to disk
106  * mf_release_all() release as much memory as possible
107  * mf_trans_del()   may translate negative to positive block number
108  * mf_fullname()    make file name full path (use before first :cd)
109  */
110 
111 /*
112  * Open an existing or new memory block file.
113  *
114  *  fname:	name of file to use (NULL means no file at all)
115  *		Note: fname must have been allocated, it is not copied!
116  *			If opening the file fails, fname is freed.
117  *  flags:	flags for open() call
118  *
119  *  If fname != NULL and file cannot be opened, fail.
120  *
121  * return value: identifier for this memory block file.
122  */
123     memfile_T *
124 mf_open(fname, flags)
125     char_u	*fname;
126     int		flags;
127 {
128     memfile_T		*mfp;
129     off_t		size;
130 #if defined(STATFS) && defined(UNIX) && !defined(__QNX__) && !defined(__minix)
131 # define USE_FSTATFS
132     struct STATFS	stf;
133 #endif
134 
135     if ((mfp = (memfile_T *)alloc((unsigned)sizeof(memfile_T))) == NULL)
136 	return NULL;
137 
138     if (fname == NULL)	    /* no file for this memfile, use memory only */
139     {
140 	mfp->mf_fname = NULL;
141 	mfp->mf_ffname = NULL;
142 	mfp->mf_fd = -1;
143     }
144     else
145     {
146 	mf_do_open(mfp, fname, flags);	/* try to open the file */
147 
148 	/* if the file cannot be opened, return here */
149 	if (mfp->mf_fd < 0)
150 	{
151 	    vim_free(mfp);
152 	    return NULL;
153 	}
154     }
155 
156     mfp->mf_free_first = NULL;		/* free list is empty */
157     mfp->mf_used_first = NULL;		/* used list is empty */
158     mfp->mf_used_last = NULL;
159     mfp->mf_dirty = FALSE;
160     mfp->mf_used_count = 0;
161     mf_hash_init(&mfp->mf_hash);
162     mf_hash_init(&mfp->mf_trans);
163     mfp->mf_page_size = MEMFILE_PAGE_SIZE;
164 #ifdef FEAT_CRYPT
165     mfp->mf_old_key = NULL;
166 #endif
167 
168 #ifdef USE_FSTATFS
169     /*
170      * Try to set the page size equal to the block size of the device.
171      * Speeds up I/O a lot.
172      * When recovering, the actual block size will be retrieved from block 0
173      * in ml_recover().  The size used here may be wrong, therefore
174      * mf_blocknr_max must be rounded up.
175      */
176     if (mfp->mf_fd >= 0
177 	    && fstatfs(mfp->mf_fd, &stf, sizeof(struct statfs), 0) == 0
178 	    && stf.F_BSIZE >= MIN_SWAP_PAGE_SIZE
179 	    && stf.F_BSIZE <= MAX_SWAP_PAGE_SIZE)
180 	mfp->mf_page_size = stf.F_BSIZE;
181 #endif
182 
183     if (mfp->mf_fd < 0 || (flags & (O_TRUNC|O_EXCL))
184 		      || (size = lseek(mfp->mf_fd, (off_t)0L, SEEK_END)) <= 0)
185 	mfp->mf_blocknr_max = 0;	/* no file or empty file */
186     else
187 	mfp->mf_blocknr_max = (blocknr_T)((size + mfp->mf_page_size - 1)
188 							 / mfp->mf_page_size);
189     mfp->mf_blocknr_min = -1;
190     mfp->mf_neg_count = 0;
191     mfp->mf_infile_count = mfp->mf_blocknr_max;
192 
193     /*
194      * Compute maximum number of pages ('maxmem' is in Kbyte):
195      *	'mammem' * 1Kbyte / page-size-in-bytes.
196      * Avoid overflow by first reducing page size as much as possible.
197      */
198     {
199 	int	    shift = 10;
200 	unsigned    page_size = mfp->mf_page_size;
201 
202 	while (shift > 0 && (page_size & 1) == 0)
203 	{
204 	    page_size = page_size >> 1;
205 	    --shift;
206 	}
207 	mfp->mf_used_count_max = (p_mm << shift) / page_size;
208 	if (mfp->mf_used_count_max < 10)
209 	    mfp->mf_used_count_max = 10;
210     }
211 
212     return mfp;
213 }
214 
215 /*
216  * Open a file for an existing memfile.  Used when updatecount set from 0 to
217  * some value.
218  * If the file already exists, this fails.
219  * "fname" is the name of file to use (NULL means no file at all)
220  * Note: "fname" must have been allocated, it is not copied!  If opening the
221  * file fails, "fname" is freed.
222  *
223  * return value: FAIL if file could not be opened, OK otherwise
224  */
225     int
226 mf_open_file(mfp, fname)
227     memfile_T	*mfp;
228     char_u	*fname;
229 {
230     mf_do_open(mfp, fname, O_RDWR|O_CREAT|O_EXCL); /* try to open the file */
231 
232     if (mfp->mf_fd < 0)
233 	return FAIL;
234 
235     mfp->mf_dirty = TRUE;
236     return OK;
237 }
238 
239 /*
240  * Close a memory file and delete the associated file if 'del_file' is TRUE.
241  */
242     void
243 mf_close(mfp, del_file)
244     memfile_T	*mfp;
245     int		del_file;
246 {
247     bhdr_T	*hp, *nextp;
248 
249     if (mfp == NULL)		    /* safety check */
250 	return;
251     if (mfp->mf_fd >= 0)
252     {
253 	if (close(mfp->mf_fd) < 0)
254 	    EMSG(_(e_swapclose));
255     }
256     if (del_file && mfp->mf_fname != NULL)
257 	mch_remove(mfp->mf_fname);
258 					    /* free entries in used list */
259     for (hp = mfp->mf_used_first; hp != NULL; hp = nextp)
260     {
261 	total_mem_used -= hp->bh_page_count * mfp->mf_page_size;
262 	nextp = hp->bh_next;
263 	mf_free_bhdr(hp);
264     }
265     while (mfp->mf_free_first != NULL)	    /* free entries in free list */
266 	vim_free(mf_rem_free(mfp));
267     mf_hash_free(&mfp->mf_hash);
268     mf_hash_free_all(&mfp->mf_trans);	    /* free hashtable and its items */
269     vim_free(mfp->mf_fname);
270     vim_free(mfp->mf_ffname);
271     vim_free(mfp);
272 }
273 
274 /*
275  * Close the swap file for a memfile.  Used when 'swapfile' is reset.
276  */
277     void
278 mf_close_file(buf, getlines)
279     buf_T	*buf;
280     int		getlines;	/* get all lines into memory? */
281 {
282     memfile_T	*mfp;
283     linenr_T	lnum;
284 
285     mfp = buf->b_ml.ml_mfp;
286     if (mfp == NULL || mfp->mf_fd < 0)		/* nothing to close */
287 	return;
288 
289     if (getlines)
290     {
291 	/* get all blocks in memory by accessing all lines (clumsy!) */
292 	mf_dont_release = TRUE;
293 	for (lnum = 1; lnum <= buf->b_ml.ml_line_count; ++lnum)
294 	    (void)ml_get_buf(buf, lnum, FALSE);
295 	mf_dont_release = FALSE;
296 	/* TODO: should check if all blocks are really in core */
297     }
298 
299     if (close(mfp->mf_fd) < 0)			/* close the file */
300 	EMSG(_(e_swapclose));
301     mfp->mf_fd = -1;
302 
303     if (mfp->mf_fname != NULL)
304     {
305 	mch_remove(mfp->mf_fname);		/* delete the swap file */
306 	vim_free(mfp->mf_fname);
307 	vim_free(mfp->mf_ffname);
308 	mfp->mf_fname = NULL;
309 	mfp->mf_ffname = NULL;
310     }
311 }
312 
313 /*
314  * Set new size for a memfile.  Used when block 0 of a swapfile has been read
315  * and the size it indicates differs from what was guessed.
316  */
317     void
318 mf_new_page_size(mfp, new_size)
319     memfile_T	*mfp;
320     unsigned	new_size;
321 {
322     /* Correct the memory used for block 0 to the new size, because it will be
323      * freed with that size later on. */
324     total_mem_used += new_size - mfp->mf_page_size;
325     mfp->mf_page_size = new_size;
326 }
327 
328 /*
329  * get a new block
330  *
331  *   negative: TRUE if negative block number desired (data block)
332  */
333     bhdr_T *
334 mf_new(mfp, negative, page_count)
335     memfile_T	*mfp;
336     int		negative;
337     int		page_count;
338 {
339     bhdr_T	*hp;	/* new bhdr_T */
340     bhdr_T	*freep;	/* first block in free list */
341     char_u	*p;
342 
343     /*
344      * If we reached the maximum size for the used memory blocks, release one
345      * If a bhdr_T is returned, use it and adjust the page_count if necessary.
346      */
347     hp = mf_release(mfp, page_count);
348 
349 /*
350  * Decide on the number to use:
351  * If there is a free block, use its number.
352  * Otherwise use mf_block_min for a negative number, mf_block_max for
353  * a positive number.
354  */
355     freep = mfp->mf_free_first;
356     if (!negative && freep != NULL && freep->bh_page_count >= page_count)
357     {
358 	/*
359 	 * If the block in the free list has more pages, take only the number
360 	 * of pages needed and allocate a new bhdr_T with data
361 	 *
362 	 * If the number of pages matches and mf_release() did not return a
363 	 * bhdr_T, use the bhdr_T from the free list and allocate the data
364 	 *
365 	 * If the number of pages matches and mf_release() returned a bhdr_T,
366 	 * just use the number and free the bhdr_T from the free list
367 	 */
368 	if (freep->bh_page_count > page_count)
369 	{
370 	    if (hp == NULL && (hp = mf_alloc_bhdr(mfp, page_count)) == NULL)
371 		return NULL;
372 	    hp->bh_bnum = freep->bh_bnum;
373 	    freep->bh_bnum += page_count;
374 	    freep->bh_page_count -= page_count;
375 	}
376 	else if (hp == NULL)	    /* need to allocate memory for this block */
377 	{
378 	    if ((p = (char_u *)alloc(mfp->mf_page_size * page_count)) == NULL)
379 		return NULL;
380 	    hp = mf_rem_free(mfp);
381 	    hp->bh_data = p;
382 	}
383 	else		    /* use the number, remove entry from free list */
384 	{
385 	    freep = mf_rem_free(mfp);
386 	    hp->bh_bnum = freep->bh_bnum;
387 	    vim_free(freep);
388 	}
389     }
390     else	/* get a new number */
391     {
392 	if (hp == NULL && (hp = mf_alloc_bhdr(mfp, page_count)) == NULL)
393 	    return NULL;
394 	if (negative)
395 	{
396 	    hp->bh_bnum = mfp->mf_blocknr_min--;
397 	    mfp->mf_neg_count++;
398 	}
399 	else
400 	{
401 	    hp->bh_bnum = mfp->mf_blocknr_max;
402 	    mfp->mf_blocknr_max += page_count;
403 	}
404     }
405     hp->bh_flags = BH_LOCKED | BH_DIRTY;	/* new block is always dirty */
406     mfp->mf_dirty = TRUE;
407     hp->bh_page_count = page_count;
408     mf_ins_used(mfp, hp);
409     mf_ins_hash(mfp, hp);
410 
411     /*
412      * Init the data to all zero, to avoid reading uninitialized data.
413      * This also avoids that the passwd file ends up in the swap file!
414      */
415     (void)vim_memset((char *)(hp->bh_data), 0,
416 				      (size_t)mfp->mf_page_size * page_count);
417 
418     return hp;
419 }
420 
421 /*
422  * Get existing block "nr" with "page_count" pages.
423  *
424  * Note: The caller should first check a negative nr with mf_trans_del()
425  */
426     bhdr_T *
427 mf_get(mfp, nr, page_count)
428     memfile_T	*mfp;
429     blocknr_T	nr;
430     int		page_count;
431 {
432     bhdr_T    *hp;
433 						/* doesn't exist */
434     if (nr >= mfp->mf_blocknr_max || nr <= mfp->mf_blocknr_min)
435 	return NULL;
436 
437     /*
438      * see if it is in the cache
439      */
440     hp = mf_find_hash(mfp, nr);
441     if (hp == NULL)	/* not in the hash list */
442     {
443 	if (nr < 0 || nr >= mfp->mf_infile_count)   /* can't be in the file */
444 	    return NULL;
445 
446 	/* could check here if the block is in the free list */
447 
448 	/*
449 	 * Check if we need to flush an existing block.
450 	 * If so, use that block.
451 	 * If not, allocate a new block.
452 	 */
453 	hp = mf_release(mfp, page_count);
454 	if (hp == NULL && (hp = mf_alloc_bhdr(mfp, page_count)) == NULL)
455 	    return NULL;
456 
457 	hp->bh_bnum = nr;
458 	hp->bh_flags = 0;
459 	hp->bh_page_count = page_count;
460 	if (mf_read(mfp, hp) == FAIL)	    /* cannot read the block! */
461 	{
462 	    mf_free_bhdr(hp);
463 	    return NULL;
464 	}
465     }
466     else
467     {
468 	mf_rem_used(mfp, hp);	/* remove from list, insert in front below */
469 	mf_rem_hash(mfp, hp);
470     }
471 
472     hp->bh_flags |= BH_LOCKED;
473     mf_ins_used(mfp, hp);	/* put in front of used list */
474     mf_ins_hash(mfp, hp);	/* put in front of hash list */
475 
476     return hp;
477 }
478 
479 /*
480  * release the block *hp
481  *
482  *   dirty: Block must be written to file later
483  *   infile: Block should be in file (needed for recovery)
484  *
485  *  no return value, function cannot fail
486  */
487     void
488 mf_put(mfp, hp, dirty, infile)
489     memfile_T	*mfp;
490     bhdr_T	*hp;
491     int		dirty;
492     int		infile;
493 {
494     int		flags;
495 
496     flags = hp->bh_flags;
497 
498     if ((flags & BH_LOCKED) == 0)
499 	EMSG(_("E293: block was not locked"));
500     flags &= ~BH_LOCKED;
501     if (dirty)
502     {
503 	flags |= BH_DIRTY;
504 	mfp->mf_dirty = TRUE;
505     }
506     hp->bh_flags = flags;
507     if (infile)
508 	mf_trans_add(mfp, hp);	    /* may translate negative in positive nr */
509 }
510 
511 /*
512  * block *hp is no longer in used, may put it in the free list of memfile *mfp
513  */
514     void
515 mf_free(mfp, hp)
516     memfile_T	*mfp;
517     bhdr_T	*hp;
518 {
519     vim_free(hp->bh_data);	/* free the memory */
520     mf_rem_hash(mfp, hp);	/* get *hp out of the hash list */
521     mf_rem_used(mfp, hp);	/* get *hp out of the used list */
522     if (hp->bh_bnum < 0)
523     {
524 	vim_free(hp);		/* don't want negative numbers in free list */
525 	mfp->mf_neg_count--;
526     }
527     else
528 	mf_ins_free(mfp, hp);	/* put *hp in the free list */
529 }
530 
531 #if defined(__MORPHOS__) && defined(__libnix__)
532 /* function is missing in MorphOS libnix version */
533 extern unsigned long *__stdfiledes;
534 
535     static unsigned long
536 fdtofh(int filedescriptor)
537 {
538     return __stdfiledes[filedescriptor];
539 }
540 #endif
541 
542 /*
543  * Sync the memory file *mfp to disk.
544  * Flags:
545  *  MFS_ALL	If not given, blocks with negative numbers are not synced,
546  *		even when they are dirty!
547  *  MFS_STOP	Stop syncing when a character becomes available, but sync at
548  *		least one block.
549  *  MFS_FLUSH	Make sure buffers are flushed to disk, so they will survive a
550  *		system crash.
551  *  MFS_ZERO	Only write block 0.
552  *
553  * Return FAIL for failure, OK otherwise
554  */
555     int
556 mf_sync(mfp, flags)
557     memfile_T	*mfp;
558     int		flags;
559 {
560     int		status;
561     bhdr_T	*hp;
562 #if defined(SYNC_DUP_CLOSE) && !defined(MSDOS)
563     int		fd;
564 #endif
565     int		got_int_save = got_int;
566 
567     if (mfp->mf_fd < 0)	    /* there is no file, nothing to do */
568     {
569 	mfp->mf_dirty = FALSE;
570 	return FAIL;
571     }
572 
573     /* Only a CTRL-C while writing will break us here, not one typed
574      * previously. */
575     got_int = FALSE;
576 
577     /*
578      * sync from last to first (may reduce the probability of an inconsistent
579      * file) If a write fails, it is very likely caused by a full filesystem.
580      * Then we only try to write blocks within the existing file. If that also
581      * fails then we give up.
582      */
583     status = OK;
584     for (hp = mfp->mf_used_last; hp != NULL; hp = hp->bh_prev)
585 	if (((flags & MFS_ALL) || hp->bh_bnum >= 0)
586 		&& (hp->bh_flags & BH_DIRTY)
587 		&& (status == OK || (hp->bh_bnum >= 0
588 		    && hp->bh_bnum < mfp->mf_infile_count)))
589 	{
590 	    if ((flags & MFS_ZERO) && hp->bh_bnum != 0)
591 		continue;
592 	    if (mf_write(mfp, hp) == FAIL)
593 	    {
594 		if (status == FAIL)	/* double error: quit syncing */
595 		    break;
596 		status = FAIL;
597 	    }
598 	    if (flags & MFS_STOP)
599 	    {
600 		/* Stop when char available now. */
601 		if (ui_char_avail())
602 		    break;
603 	    }
604 	    else
605 		ui_breakcheck();
606 	    if (got_int)
607 		break;
608 	}
609 
610     /*
611      * If the whole list is flushed, the memfile is not dirty anymore.
612      * In case of an error this flag is also set, to avoid trying all the time.
613      */
614     if (hp == NULL || status == FAIL)
615 	mfp->mf_dirty = FALSE;
616 
617     if ((flags & MFS_FLUSH) && *p_sws != NUL)
618     {
619 #if defined(UNIX)
620 # ifdef HAVE_FSYNC
621 	/*
622 	 * most Unixes have the very useful fsync() function, just what we need.
623 	 * However, with OS/2 and EMX it is also available, but there are
624 	 * reports of bad problems with it (a bug in HPFS.IFS).
625 	 * So we disable use of it here in case someone tries to be smart
626 	 * and changes os_os2_cfg.h... (even though there is no __EMX__ test
627 	 * in the #if, as __EMX__ does not have sync(); we hope for a timely
628 	 * sync from the system itself).
629 	 */
630 #  if defined(__EMX__)
631    error "Don't use fsync with EMX! Read emxdoc.doc or emxfix01.doc for info."
632 #  endif
633 	if (STRCMP(p_sws, "fsync") == 0)
634 	{
635 	    if (fsync(mfp->mf_fd))
636 		status = FAIL;
637 	}
638 	else
639 # endif
640 	    /* OpenNT is strictly POSIX (Benzinger) */
641 	    /* Tandem/Himalaya NSK-OSS doesn't have sync() */
642 	    /* No sync() on Stratus VOS */
643 # if defined(__OPENNT) || defined(__TANDEM) || defined(__VOS__)
644 	    fflush(NULL);
645 # else
646 	    sync();
647 # endif
648 #endif
649 #ifdef VMS
650 	if (STRCMP(p_sws, "fsync") == 0)
651 	{
652 	    if (fsync(mfp->mf_fd))
653 		status = FAIL;
654 	}
655 #endif
656 #ifdef MSDOS
657 	if (_dos_commit(mfp->mf_fd))
658 	    status = FAIL;
659 #else
660 # ifdef SYNC_DUP_CLOSE
661 	/*
662 	 * Win32 is a bit more work: Duplicate the file handle and close it.
663 	 * This should flush the file to disk.
664 	 */
665 	if ((fd = dup(mfp->mf_fd)) >= 0)
666 	    close(fd);
667 # endif
668 #endif
669 #ifdef AMIGA
670 # if defined(__AROS__) || defined(__amigaos4__)
671 	if (fsync(mfp->mf_fd) != 0)
672 	    status = FAIL;
673 # else
674 	/*
675 	 * Flush() only exists for AmigaDos 2.0.
676 	 * For 1.3 it should be done with close() + open(), but then the risk
677 	 * is that the open() may fail and lose the file....
678 	 */
679 #  ifdef FEAT_ARP
680 	if (dos2)
681 #  endif
682 #  ifdef SASC
683 	{
684 	    struct UFB *fp = chkufb(mfp->mf_fd);
685 
686 	    if (fp != NULL)
687 		Flush(fp->ufbfh);
688 	}
689 #  else
690 #   if defined(_DCC) || defined(__GNUC__) || defined(__MORPHOS__)
691 	{
692 #    if defined(__GNUC__) && !defined(__MORPHOS__) && defined(__libnix__)
693 	    /* Have function (in libnix at least),
694 	     * but ain't got no prototype anywhere. */
695 	    extern unsigned long fdtofh(int filedescriptor);
696 #    endif
697 #    if !defined(__libnix__)
698 	    fflush(NULL);
699 #    else
700 	    BPTR fh = (BPTR)fdtofh(mfp->mf_fd);
701 
702 	    if (fh != 0)
703 		Flush(fh);
704 #    endif
705 	}
706 #   else /* assume Manx */
707 	    Flush(_devtab[mfp->mf_fd].fd);
708 #   endif
709 #  endif
710 # endif
711 #endif /* AMIGA */
712     }
713 
714     got_int |= got_int_save;
715 
716     return status;
717 }
718 
719 /*
720  * For all blocks in memory file *mfp that have a positive block number set
721  * the dirty flag.  These are blocks that need to be written to a newly
722  * created swapfile.
723  */
724     void
725 mf_set_dirty(mfp)
726     memfile_T	*mfp;
727 {
728     bhdr_T	*hp;
729 
730     for (hp = mfp->mf_used_last; hp != NULL; hp = hp->bh_prev)
731 	if (hp->bh_bnum > 0)
732 	    hp->bh_flags |= BH_DIRTY;
733     mfp->mf_dirty = TRUE;
734 }
735 
736 /*
737  * insert block *hp in front of hashlist of memfile *mfp
738  */
739     static void
740 mf_ins_hash(mfp, hp)
741     memfile_T	*mfp;
742     bhdr_T	*hp;
743 {
744     mf_hash_add_item(&mfp->mf_hash, (mf_hashitem_T *)hp);
745 }
746 
747 /*
748  * remove block *hp from hashlist of memfile list *mfp
749  */
750     static void
751 mf_rem_hash(mfp, hp)
752     memfile_T	*mfp;
753     bhdr_T	*hp;
754 {
755     mf_hash_rem_item(&mfp->mf_hash, (mf_hashitem_T *)hp);
756 }
757 
758 /*
759  * look in hash lists of memfile *mfp for block header with number 'nr'
760  */
761     static bhdr_T *
762 mf_find_hash(mfp, nr)
763     memfile_T	*mfp;
764     blocknr_T	nr;
765 {
766     return (bhdr_T *)mf_hash_find(&mfp->mf_hash, nr);
767 }
768 
769 /*
770  * insert block *hp in front of used list of memfile *mfp
771  */
772     static void
773 mf_ins_used(mfp, hp)
774     memfile_T	*mfp;
775     bhdr_T	*hp;
776 {
777     hp->bh_next = mfp->mf_used_first;
778     mfp->mf_used_first = hp;
779     hp->bh_prev = NULL;
780     if (hp->bh_next == NULL)	    /* list was empty, adjust last pointer */
781 	mfp->mf_used_last = hp;
782     else
783 	hp->bh_next->bh_prev = hp;
784     mfp->mf_used_count += hp->bh_page_count;
785     total_mem_used += hp->bh_page_count * mfp->mf_page_size;
786 }
787 
788 /*
789  * remove block *hp from used list of memfile *mfp
790  */
791     static void
792 mf_rem_used(mfp, hp)
793     memfile_T	*mfp;
794     bhdr_T	*hp;
795 {
796     if (hp->bh_next == NULL)	    /* last block in used list */
797 	mfp->mf_used_last = hp->bh_prev;
798     else
799 	hp->bh_next->bh_prev = hp->bh_prev;
800     if (hp->bh_prev == NULL)	    /* first block in used list */
801 	mfp->mf_used_first = hp->bh_next;
802     else
803 	hp->bh_prev->bh_next = hp->bh_next;
804     mfp->mf_used_count -= hp->bh_page_count;
805     total_mem_used -= hp->bh_page_count * mfp->mf_page_size;
806 }
807 
808 /*
809  * Release the least recently used block from the used list if the number
810  * of used memory blocks gets to big.
811  *
812  * Return the block header to the caller, including the memory block, so
813  * it can be re-used. Make sure the page_count is right.
814  *
815  * Returns NULL if no block is released.
816  */
817     static bhdr_T *
818 mf_release(mfp, page_count)
819     memfile_T	*mfp;
820     int		page_count;
821 {
822     bhdr_T	*hp;
823     int		need_release;
824     buf_T	*buf;
825 
826     /* don't release while in mf_close_file() */
827     if (mf_dont_release)
828 	return NULL;
829 
830     /*
831      * Need to release a block if the number of blocks for this memfile is
832      * higher than the maximum or total memory used is over 'maxmemtot'
833      */
834     need_release = ((mfp->mf_used_count >= mfp->mf_used_count_max)
835 				  || (total_mem_used >> 10) >= (long_u)p_mmt);
836 
837     /*
838      * Try to create a swap file if the amount of memory used is getting too
839      * high.
840      */
841     if (mfp->mf_fd < 0 && need_release && p_uc)
842     {
843 	/* find for which buffer this memfile is */
844 	for (buf = firstbuf; buf != NULL; buf = buf->b_next)
845 	    if (buf->b_ml.ml_mfp == mfp)
846 		break;
847 	if (buf != NULL && buf->b_may_swap)
848 	    ml_open_file(buf);
849     }
850 
851     /*
852      * don't release a block if
853      *	there is no file for this memfile
854      * or
855      *	the number of blocks for this memfile is lower than the maximum
856      *	  and
857      *	total memory used is not up to 'maxmemtot'
858      */
859     if (mfp->mf_fd < 0 || !need_release)
860 	return NULL;
861 
862     for (hp = mfp->mf_used_last; hp != NULL; hp = hp->bh_prev)
863 	if (!(hp->bh_flags & BH_LOCKED))
864 	    break;
865     if (hp == NULL)	/* not a single one that can be released */
866 	return NULL;
867 
868     /*
869      * If the block is dirty, write it.
870      * If the write fails we don't free it.
871      */
872     if ((hp->bh_flags & BH_DIRTY) && mf_write(mfp, hp) == FAIL)
873 	return NULL;
874 
875     mf_rem_used(mfp, hp);
876     mf_rem_hash(mfp, hp);
877 
878     /*
879      * If a bhdr_T is returned, make sure that the page_count of bh_data is
880      * right
881      */
882     if (hp->bh_page_count != page_count)
883     {
884 	vim_free(hp->bh_data);
885 	if ((hp->bh_data = alloc(mfp->mf_page_size * page_count)) == NULL)
886 	{
887 	    vim_free(hp);
888 	    return NULL;
889 	}
890 	hp->bh_page_count = page_count;
891     }
892     return hp;
893 }
894 
895 /*
896  * release as many blocks as possible
897  * Used in case of out of memory
898  *
899  * return TRUE if any memory was released
900  */
901     int
902 mf_release_all()
903 {
904     buf_T	*buf;
905     memfile_T	*mfp;
906     bhdr_T	*hp;
907     int		retval = FALSE;
908 
909     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
910     {
911 	mfp = buf->b_ml.ml_mfp;
912 	if (mfp != NULL)
913 	{
914 	    /* If no swap file yet, may open one */
915 	    if (mfp->mf_fd < 0 && buf->b_may_swap)
916 		ml_open_file(buf);
917 
918 	    /* only if there is a swapfile */
919 	    if (mfp->mf_fd >= 0)
920 	    {
921 		for (hp = mfp->mf_used_last; hp != NULL; )
922 		{
923 		    if (!(hp->bh_flags & BH_LOCKED)
924 			    && (!(hp->bh_flags & BH_DIRTY)
925 				|| mf_write(mfp, hp) != FAIL))
926 		    {
927 			mf_rem_used(mfp, hp);
928 			mf_rem_hash(mfp, hp);
929 			mf_free_bhdr(hp);
930 			hp = mfp->mf_used_last;	/* re-start, list was changed */
931 			retval = TRUE;
932 		    }
933 		    else
934 			hp = hp->bh_prev;
935 		}
936 	    }
937 	}
938     }
939     return retval;
940 }
941 
942 /*
943  * Allocate a block header and a block of memory for it
944  */
945     static bhdr_T *
946 mf_alloc_bhdr(mfp, page_count)
947     memfile_T	*mfp;
948     int		page_count;
949 {
950     bhdr_T	*hp;
951 
952     if ((hp = (bhdr_T *)alloc((unsigned)sizeof(bhdr_T))) != NULL)
953     {
954 	if ((hp->bh_data = (char_u *)alloc(mfp->mf_page_size * page_count))
955 								      == NULL)
956 	{
957 	    vim_free(hp);	    /* not enough memory */
958 	    return NULL;
959 	}
960 	hp->bh_page_count = page_count;
961     }
962     return hp;
963 }
964 
965 /*
966  * Free a block header and the block of memory for it
967  */
968     static void
969 mf_free_bhdr(hp)
970     bhdr_T	*hp;
971 {
972     vim_free(hp->bh_data);
973     vim_free(hp);
974 }
975 
976 /*
977  * insert entry *hp in the free list
978  */
979     static void
980 mf_ins_free(mfp, hp)
981     memfile_T	*mfp;
982     bhdr_T	*hp;
983 {
984     hp->bh_next = mfp->mf_free_first;
985     mfp->mf_free_first = hp;
986 }
987 
988 /*
989  * remove the first entry from the free list and return a pointer to it
990  * Note: caller must check that mfp->mf_free_first is not NULL!
991  */
992     static bhdr_T *
993 mf_rem_free(mfp)
994     memfile_T	*mfp;
995 {
996     bhdr_T	*hp;
997 
998     hp = mfp->mf_free_first;
999     mfp->mf_free_first = hp->bh_next;
1000     return hp;
1001 }
1002 
1003 /*
1004  * read a block from disk
1005  *
1006  * Return FAIL for failure, OK otherwise
1007  */
1008     static int
1009 mf_read(mfp, hp)
1010     memfile_T	*mfp;
1011     bhdr_T	*hp;
1012 {
1013     off_t	offset;
1014     unsigned	page_size;
1015     unsigned	size;
1016 
1017     if (mfp->mf_fd < 0)	    /* there is no file, can't read */
1018 	return FAIL;
1019 
1020     page_size = mfp->mf_page_size;
1021     offset = (off_t)page_size * hp->bh_bnum;
1022     size = page_size * hp->bh_page_count;
1023     if (lseek(mfp->mf_fd, offset, SEEK_SET) != offset)
1024     {
1025 	PERROR(_("E294: Seek error in swap file read"));
1026 	return FAIL;
1027     }
1028     if ((unsigned)read_eintr(mfp->mf_fd, hp->bh_data, size) != size)
1029     {
1030 	PERROR(_("E295: Read error in swap file"));
1031 	return FAIL;
1032     }
1033 
1034 #ifdef FEAT_CRYPT
1035     /* Decrypt if 'key' is set and this is a data block. And when changing the
1036      * key. */
1037     if (*mfp->mf_buffer->b_p_key != NUL || mfp->mf_old_key != NULL)
1038 	ml_decrypt_data(mfp, hp->bh_data, offset, size);
1039 #endif
1040 
1041     return OK;
1042 }
1043 
1044 /*
1045  * write a block to disk
1046  *
1047  * Return FAIL for failure, OK otherwise
1048  */
1049     static int
1050 mf_write(mfp, hp)
1051     memfile_T	*mfp;
1052     bhdr_T	*hp;
1053 {
1054     off_t	offset;	    /* offset in the file */
1055     blocknr_T	nr;	    /* block nr which is being written */
1056     bhdr_T	*hp2;
1057     unsigned	page_size;  /* number of bytes in a page */
1058     unsigned	page_count; /* number of pages written */
1059     unsigned	size;	    /* number of bytes written */
1060 
1061     if (mfp->mf_fd < 0)	    /* there is no file, can't write */
1062 	return FAIL;
1063 
1064     if (hp->bh_bnum < 0)	/* must assign file block number */
1065 	if (mf_trans_add(mfp, hp) == FAIL)
1066 	    return FAIL;
1067 
1068     page_size = mfp->mf_page_size;
1069 
1070     /*
1071      * We don't want gaps in the file. Write the blocks in front of *hp
1072      * to extend the file.
1073      * If block 'mf_infile_count' is not in the hash list, it has been
1074      * freed. Fill the space in the file with data from the current block.
1075      */
1076     for (;;)
1077     {
1078 	nr = hp->bh_bnum;
1079 	if (nr > mfp->mf_infile_count)		/* beyond end of file */
1080 	{
1081 	    nr = mfp->mf_infile_count;
1082 	    hp2 = mf_find_hash(mfp, nr);	/* NULL caught below */
1083 	}
1084 	else
1085 	    hp2 = hp;
1086 
1087 	offset = (off_t)page_size * nr;
1088 	if (lseek(mfp->mf_fd, offset, SEEK_SET) != offset)
1089 	{
1090 	    PERROR(_("E296: Seek error in swap file write"));
1091 	    return FAIL;
1092 	}
1093 	if (hp2 == NULL)	    /* freed block, fill with dummy data */
1094 	    page_count = 1;
1095 	else
1096 	    page_count = hp2->bh_page_count;
1097 	size = page_size * page_count;
1098 	if (mf_write_block(mfp, hp2 == NULL ? hp : hp2, offset, size) == FAIL)
1099 	{
1100 	    /*
1101 	     * Avoid repeating the error message, this mostly happens when the
1102 	     * disk is full. We give the message again only after a successful
1103 	     * write or when hitting a key. We keep on trying, in case some
1104 	     * space becomes available.
1105 	     */
1106 	    if (!did_swapwrite_msg)
1107 		EMSG(_("E297: Write error in swap file"));
1108 	    did_swapwrite_msg = TRUE;
1109 	    return FAIL;
1110 	}
1111 	did_swapwrite_msg = FALSE;
1112 	if (hp2 != NULL)		    /* written a non-dummy block */
1113 	    hp2->bh_flags &= ~BH_DIRTY;
1114 					    /* appended to the file */
1115 	if (nr + (blocknr_T)page_count > mfp->mf_infile_count)
1116 	    mfp->mf_infile_count = nr + page_count;
1117 	if (nr == hp->bh_bnum)		    /* written the desired block */
1118 	    break;
1119     }
1120     return OK;
1121 }
1122 
1123 /*
1124  * Write block "hp" with data size "size" to file "mfp->mf_fd".
1125  * Takes care of encryption.
1126  * Return FAIL or OK.
1127  */
1128     static int
1129 mf_write_block(mfp, hp, offset, size)
1130     memfile_T	*mfp;
1131     bhdr_T	*hp;
1132     off_t	offset UNUSED;
1133     unsigned	size;
1134 {
1135     char_u	*data = hp->bh_data;
1136     int		result = OK;
1137 
1138 #ifdef FEAT_CRYPT
1139     /* Encrypt if 'key' is set and this is a data block. */
1140     if (*mfp->mf_buffer->b_p_key != NUL)
1141     {
1142 	data = ml_encrypt_data(mfp, data, offset, size);
1143 	if (data == NULL)
1144 	    return FAIL;
1145     }
1146 #endif
1147 
1148     if ((unsigned)write_eintr(mfp->mf_fd, data, size) != size)
1149 	result = FAIL;
1150 
1151 #ifdef FEAT_CRYPT
1152     if (data != hp->bh_data)
1153 	vim_free(data);
1154 #endif
1155 
1156     return result;
1157 }
1158 
1159 /*
1160  * Make block number for *hp positive and add it to the translation list
1161  *
1162  * Return FAIL for failure, OK otherwise
1163  */
1164     static int
1165 mf_trans_add(mfp, hp)
1166     memfile_T	*mfp;
1167     bhdr_T	*hp;
1168 {
1169     bhdr_T	*freep;
1170     blocknr_T	new_bnum;
1171     NR_TRANS	*np;
1172     int		page_count;
1173 
1174     if (hp->bh_bnum >= 0)		    /* it's already positive */
1175 	return OK;
1176 
1177     if ((np = (NR_TRANS *)alloc((unsigned)sizeof(NR_TRANS))) == NULL)
1178 	return FAIL;
1179 
1180 /*
1181  * Get a new number for the block.
1182  * If the first item in the free list has sufficient pages, use its number
1183  * Otherwise use mf_blocknr_max.
1184  */
1185     freep = mfp->mf_free_first;
1186     page_count = hp->bh_page_count;
1187     if (freep != NULL && freep->bh_page_count >= page_count)
1188     {
1189 	new_bnum = freep->bh_bnum;
1190 	/*
1191 	 * If the page count of the free block was larger, reduce it.
1192 	 * If the page count matches, remove the block from the free list
1193 	 */
1194 	if (freep->bh_page_count > page_count)
1195 	{
1196 	    freep->bh_bnum += page_count;
1197 	    freep->bh_page_count -= page_count;
1198 	}
1199 	else
1200 	{
1201 	    freep = mf_rem_free(mfp);
1202 	    vim_free(freep);
1203 	}
1204     }
1205     else
1206     {
1207 	new_bnum = mfp->mf_blocknr_max;
1208 	mfp->mf_blocknr_max += page_count;
1209     }
1210 
1211     np->nt_old_bnum = hp->bh_bnum;	    /* adjust number */
1212     np->nt_new_bnum = new_bnum;
1213 
1214     mf_rem_hash(mfp, hp);		    /* remove from old hash list */
1215     hp->bh_bnum = new_bnum;
1216     mf_ins_hash(mfp, hp);		    /* insert in new hash list */
1217 
1218     /* Insert "np" into "mf_trans" hashtable with key "np->nt_old_bnum" */
1219     mf_hash_add_item(&mfp->mf_trans, (mf_hashitem_T *)np);
1220 
1221     return OK;
1222 }
1223 
1224 /*
1225  * Lookup a translation from the trans lists and delete the entry.
1226  *
1227  * Return the positive new number when found, the old number when not found
1228  */
1229     blocknr_T
1230 mf_trans_del(mfp, old_nr)
1231     memfile_T	*mfp;
1232     blocknr_T	old_nr;
1233 {
1234     NR_TRANS	*np;
1235     blocknr_T	new_bnum;
1236 
1237     np = (NR_TRANS *)mf_hash_find(&mfp->mf_trans, old_nr);
1238 
1239     if (np == NULL)		/* not found */
1240 	return old_nr;
1241 
1242     mfp->mf_neg_count--;
1243     new_bnum = np->nt_new_bnum;
1244 
1245     /* remove entry from the trans list */
1246     mf_hash_rem_item(&mfp->mf_trans, (mf_hashitem_T *)np);
1247 
1248     vim_free(np);
1249 
1250     return new_bnum;
1251 }
1252 
1253 /*
1254  * Set mfp->mf_ffname according to mfp->mf_fname and some other things.
1255  * Only called when creating or renaming the swapfile.	Either way it's a new
1256  * name so we must work out the full path name.
1257  */
1258     void
1259 mf_set_ffname(mfp)
1260     memfile_T	*mfp;
1261 {
1262     mfp->mf_ffname = FullName_save(mfp->mf_fname, FALSE);
1263 }
1264 
1265 /*
1266  * Make the name of the file used for the memfile a full path.
1267  * Used before doing a :cd
1268  */
1269     void
1270 mf_fullname(mfp)
1271     memfile_T	*mfp;
1272 {
1273     if (mfp != NULL && mfp->mf_fname != NULL && mfp->mf_ffname != NULL)
1274     {
1275 	vim_free(mfp->mf_fname);
1276 	mfp->mf_fname = mfp->mf_ffname;
1277 	mfp->mf_ffname = NULL;
1278     }
1279 }
1280 
1281 /*
1282  * return TRUE if there are any translations pending for 'mfp'
1283  */
1284     int
1285 mf_need_trans(mfp)
1286     memfile_T	*mfp;
1287 {
1288     return (mfp->mf_fname != NULL && mfp->mf_neg_count > 0);
1289 }
1290 
1291 /*
1292  * Open a swap file for a memfile.
1293  * The "fname" must be in allocated memory, and is consumed (also when an
1294  * error occurs).
1295  */
1296     static void
1297 mf_do_open(mfp, fname, flags)
1298     memfile_T	*mfp;
1299     char_u	*fname;
1300     int		flags;		/* flags for open() */
1301 {
1302 #ifdef HAVE_LSTAT
1303     struct stat sb;
1304 #endif
1305 
1306     mfp->mf_fname = fname;
1307 
1308     /*
1309      * Get the full path name before the open, because this is
1310      * not possible after the open on the Amiga.
1311      * fname cannot be NameBuff, because it must have been allocated.
1312      */
1313     mf_set_ffname(mfp);
1314 #if defined(MSDOS) || defined(MSWIN)
1315     /*
1316      * A ":!cd e:xxx" may change the directory without us knowing, use the
1317      * full pathname always.  Careful: This frees fname!
1318      */
1319     mf_fullname(mfp);
1320 #endif
1321 
1322 #ifdef HAVE_LSTAT
1323     /*
1324      * Extra security check: When creating a swap file it really shouldn't
1325      * exist yet.  If there is a symbolic link, this is most likely an attack.
1326      */
1327     if ((flags & O_CREAT) && mch_lstat((char *)mfp->mf_fname, &sb) >= 0)
1328     {
1329 	mfp->mf_fd = -1;
1330 	EMSG(_("E300: Swap file already exists (symlink attack?)"));
1331     }
1332     else
1333 #endif
1334     {
1335 	/*
1336 	 * try to open the file
1337 	 */
1338 	flags |= O_EXTRA | O_NOFOLLOW;
1339 #ifdef WIN32
1340 	/* Prevent handle inheritance that cause problems with Cscope
1341 	 * (swap file may not be deleted if cscope connection was open after
1342 	 * the file) */
1343 	flags |= O_NOINHERIT;
1344 #endif
1345 	mfp->mf_fd = mch_open_rw((char *)mfp->mf_fname, flags);
1346     }
1347 
1348     /*
1349      * If the file cannot be opened, use memory only
1350      */
1351     if (mfp->mf_fd < 0)
1352     {
1353 	vim_free(mfp->mf_fname);
1354 	vim_free(mfp->mf_ffname);
1355 	mfp->mf_fname = NULL;
1356 	mfp->mf_ffname = NULL;
1357     }
1358     else
1359     {
1360 #ifdef HAVE_FD_CLOEXEC
1361 	int fdflags = fcntl(mfp->mf_fd, F_GETFD);
1362 	if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
1363 	    fcntl(mfp->mf_fd, F_SETFD, fdflags | FD_CLOEXEC);
1364 #endif
1365 #if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
1366 	mch_copy_sec(fname, mfp->mf_fname);
1367 #endif
1368 	mch_hide(mfp->mf_fname);    /* try setting the 'hidden' flag */
1369     }
1370 }
1371 
1372 /*
1373  * Implementation of mf_hashtab_T follows.
1374  */
1375 
1376 /*
1377  * The number of buckets in the hashtable is increased by a factor of
1378  * MHT_GROWTH_FACTOR when the average number of items per bucket
1379  * exceeds 2 ^ MHT_LOG_LOAD_FACTOR.
1380  */
1381 #define MHT_LOG_LOAD_FACTOR 6
1382 #define MHT_GROWTH_FACTOR   2   /* must be a power of two */
1383 
1384 /*
1385  * Initialize an empty hash table.
1386  */
1387     static void
1388 mf_hash_init(mht)
1389     mf_hashtab_T *mht;
1390 {
1391     vim_memset(mht, 0, sizeof(mf_hashtab_T));
1392     mht->mht_buckets = mht->mht_small_buckets;
1393     mht->mht_mask = MHT_INIT_SIZE - 1;
1394 }
1395 
1396 /*
1397  * Free the array of a hash table.  Does not free the items it contains!
1398  * The hash table must not be used again without another mf_hash_init() call.
1399  */
1400     static void
1401 mf_hash_free(mht)
1402     mf_hashtab_T *mht;
1403 {
1404     if (mht->mht_buckets != mht->mht_small_buckets)
1405 	vim_free(mht->mht_buckets);
1406 }
1407 
1408 /*
1409  * Free the array of a hash table and all the items it contains.
1410  */
1411     static void
1412 mf_hash_free_all(mht)
1413     mf_hashtab_T    *mht;
1414 {
1415     long_u	    idx;
1416     mf_hashitem_T   *mhi;
1417     mf_hashitem_T   *next;
1418 
1419     for (idx = 0; idx <= mht->mht_mask; idx++)
1420 	for (mhi = mht->mht_buckets[idx]; mhi != NULL; mhi = next)
1421 	{
1422 	    next = mhi->mhi_next;
1423 	    vim_free(mhi);
1424 	}
1425 
1426     mf_hash_free(mht);
1427 }
1428 
1429 /*
1430  * Find "key" in hashtable "mht".
1431  * Returns a pointer to a mf_hashitem_T or NULL if the item was not found.
1432  */
1433     static mf_hashitem_T *
1434 mf_hash_find(mht, key)
1435     mf_hashtab_T    *mht;
1436     blocknr_T	    key;
1437 {
1438     mf_hashitem_T   *mhi;
1439 
1440     mhi = mht->mht_buckets[key & mht->mht_mask];
1441     while (mhi != NULL && mhi->mhi_key != key)
1442 	mhi = mhi->mhi_next;
1443 
1444     return mhi;
1445 }
1446 
1447 /*
1448  * Add item "mhi" to hashtable "mht".
1449  * "mhi" must not be NULL.
1450  */
1451     static void
1452 mf_hash_add_item(mht, mhi)
1453     mf_hashtab_T    *mht;
1454     mf_hashitem_T   *mhi;
1455 {
1456     long_u	    idx;
1457 
1458     idx = mhi->mhi_key & mht->mht_mask;
1459     mhi->mhi_next = mht->mht_buckets[idx];
1460     mhi->mhi_prev = NULL;
1461     if (mhi->mhi_next != NULL)
1462 	mhi->mhi_next->mhi_prev = mhi;
1463     mht->mht_buckets[idx] = mhi;
1464 
1465     mht->mht_count++;
1466 
1467     /*
1468      * Grow hashtable when we have more thank 2^MHT_LOG_LOAD_FACTOR
1469      * items per bucket on average
1470      */
1471     if (mht->mht_fixed == 0
1472 	&& (mht->mht_count >> MHT_LOG_LOAD_FACTOR) > mht->mht_mask)
1473     {
1474 	if (mf_hash_grow(mht) == FAIL)
1475 	{
1476 	    /* stop trying to grow after first failure to allocate memory */
1477 	    mht->mht_fixed = 1;
1478 	}
1479     }
1480 }
1481 
1482 /*
1483  * Remove item "mhi" from hashtable "mht".
1484  * "mhi" must not be NULL and must have been inserted into "mht".
1485  */
1486     static void
1487 mf_hash_rem_item(mht, mhi)
1488     mf_hashtab_T    *mht;
1489     mf_hashitem_T   *mhi;
1490 {
1491     if (mhi->mhi_prev == NULL)
1492 	mht->mht_buckets[mhi->mhi_key & mht->mht_mask] = mhi->mhi_next;
1493     else
1494 	mhi->mhi_prev->mhi_next = mhi->mhi_next;
1495 
1496     if (mhi->mhi_next != NULL)
1497 	mhi->mhi_next->mhi_prev = mhi->mhi_prev;
1498 
1499     mht->mht_count--;
1500 
1501     /* We could shrink the table here, but it typically takes little memory,
1502      * so why bother?  */
1503 }
1504 
1505 /*
1506  * Increase number of buckets in the hashtable by MHT_GROWTH_FACTOR and
1507  * rehash items.
1508  * Returns FAIL when out of memory.
1509  */
1510     static int
1511 mf_hash_grow(mht)
1512     mf_hashtab_T    *mht;
1513 {
1514     long_u	    i, j;
1515     int		    shift;
1516     mf_hashitem_T   *mhi;
1517     mf_hashitem_T   *tails[MHT_GROWTH_FACTOR];
1518     mf_hashitem_T   **buckets;
1519     size_t	    size;
1520 
1521     size = (mht->mht_mask + 1) * MHT_GROWTH_FACTOR * sizeof(void *);
1522     buckets = (mf_hashitem_T **)lalloc_clear(size, FALSE);
1523     if (buckets == NULL)
1524 	return FAIL;
1525 
1526     shift = 0;
1527     while ((mht->mht_mask >> shift) != 0)
1528 	shift++;
1529 
1530     for (i = 0; i <= mht->mht_mask; i++)
1531     {
1532 	/*
1533 	 * Traverse the items in the i-th original bucket and move them into
1534 	 * MHT_GROWTH_FACTOR new buckets, preserving their relative order
1535 	 * within each new bucket.  Preserving the order is important because
1536 	 * mf_get() tries to keep most recently used items at the front of
1537 	 * each bucket.
1538 	 *
1539 	 * Here we strongly rely on the fact the hashes are computed modulo
1540 	 * a power of two.
1541 	 */
1542 
1543 	vim_memset(tails, 0, sizeof(tails));
1544 
1545 	for (mhi = mht->mht_buckets[i]; mhi != NULL; mhi = mhi->mhi_next)
1546 	{
1547 	    j = (mhi->mhi_key >> shift) & (MHT_GROWTH_FACTOR - 1);
1548 	    if (tails[j] == NULL)
1549 	    {
1550 		buckets[i + (j << shift)] = mhi;
1551 		tails[j] = mhi;
1552 		mhi->mhi_prev = NULL;
1553 	    }
1554 	    else
1555 	    {
1556 		tails[j]->mhi_next = mhi;
1557 		mhi->mhi_prev = tails[j];
1558 		tails[j] = mhi;
1559 	    }
1560 	}
1561 
1562 	for (j = 0; j < MHT_GROWTH_FACTOR; j++)
1563 	    if (tails[j] != NULL)
1564 		tails[j]->mhi_next = NULL;
1565     }
1566 
1567     if (mht->mht_buckets != mht->mht_small_buckets)
1568 	vim_free(mht->mht_buckets);
1569 
1570     mht->mht_buckets = buckets;
1571     mht->mht_mask = (mht->mht_mask + 1) * MHT_GROWTH_FACTOR - 1;
1572 
1573     return OK;
1574 }
1575