summaryrefslogtreecommitdiffstats
path: root/util.c
blob: 81fa18141af2382c4c64f4c0a36f02e8d2d969a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "util.h"

const char *program;

void *xmalloc(size_t len)
{
  void *p = malloc(len);

  if (!p) {
    perror(program);
    exit(1);
  }

  return p;
}

struct disk *allocate_disk(const struct diskfmt *fmt)
{
  struct disk *disk = xmalloc(sizeof(struct disk));
  size_t size = fmt->sectors << 8;
  int i, starter;
  int secperclust = 1 << fmt->cluster_shift;
  unsigned char *p;

  memset(disk, 0, sizeof *disk);

  disk->fmt = fmt;
  disk->image = xmalloc(size);
  disk->bitmap = disk->image + (fmt->syssec << 8);
  disk->mfd.disk = disk;
  disk->mfd.bitmap = disk->bitmap;
  disk->mfd.dirsec = disk->image + (fmt->dirsec[0] << 8);
  disk->mfd.block = 0;		/* This is the MFD */

  /* Post-formatting content? */
  memset(disk->image, 0x40, size);

  /* Create empty bitmap */
  memset(disk->bitmap, 0, 256);
  for (i = fmt->sectors >> fmt->cluster_shift; i < 239*8; i++)
    mark_used(disk, i);		/* Mark nonexistent clusters busy */

  /* 239..254 is the MFD bitmap */
  disk->bitmap[239] = 0x01;	/* Reserved entry */

  /* This is claimed in a message found on ABC-klubben MSG */
  disk->bitmap[0xff] = fmt->cluster_shift;

  /* Mark the first 16/32 sectors used */
  starter = (fmt->syssec + 2 + fmt->dirsecs + secperclust - 1)
    >> fmt->cluster_shift;
  for (i = 0; i < starter; i++)
    mark_used(disk, i);

  /* Copy bitmap to backup empty bitmap (= bad block map) */
  memcpy(disk->bitmap + 256, disk->bitmap, 256);

  /* Create MFD directory sectors */
  p = disk->mfd.dirsec + (fmt->dirsec[0] << 8);
  memset(p, 0x00, 16);		/* Reserved entry */
  memset(p+16, 0xff, (fmt->dirsecs << 8) - 16);

  return disk;
}