blob: 4bbf7b8ca3b26fb7159ea1262e51d293a4248dc5 [file] [log] [blame]
Yi Kong39bbd962022-01-09 19:41:38 +08001/* Copyright 2021 Alain Knaff.
2 * This file is part of mtools.
3 *
4 * Mtools is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * Mtools is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with Mtools. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "sysincludes.h"
19#include "llong.h"
20#include "device.h"
21
22int check_if_sectors_fit(uint32_t tot_sectors,
23 mt_off_t maxBytes,
24 uint32_t sectorSize,
25 char *errmsg)
26{
27 if(!maxBytes)
28 return 0; /* Maxbytes = 0 => no checking */
29 if(tot_sectors > (smt_off_t) maxBytes / (smt_off_t) sectorSize) {
30 sprintf(errmsg,
31 "%d sectors too large for this platform\n",
32 tot_sectors);
33 return -1;
34 }
35 return 0;
36}
37
38/*
39 * Calculate number of total sectors on device if needed, and check that
40 * they fit into
41 */
42int chs_to_totsectors(struct device *dev, char *errmsg)
43{
44 uint32_t sect_per_track, tot_sectors;
45
46 if(dev->tot_sectors)
47 return 0;
48
49 if(!dev->heads || !dev->sectors || !dev->tracks)
50 return 0; /* not fully specified => we cannot do
51 anything anyways */
52
53 /* Cannot overflow as both dev->heads and dev->sectors are 16
54 * bit quantities, whose product will be put into a 32 bit
55 * field */
56 sect_per_track = dev->heads * dev->sectors;
57
58 if(dev->tracks > UINT32_MAX / sect_per_track) {
59 /* Would not fit in 32 bits */
60
61 if(errmsg)
62 sprintf(errmsg,
63 "Number of sectors larger than 2^32\n");
64 return -1;
65 }
66
67 tot_sectors = dev->tracks * sect_per_track;
68 if(tot_sectors > dev->hidden % sect_per_track)
69 tot_sectors -= dev->hidden % sect_per_track;
70 dev->tot_sectors = tot_sectors;
71 return 0;
72}