blob: 4e6eb65361c7aca6e2f3b92fc343a91ef00fbb58 [file] [log] [blame]
Bill Richardsonf1372d92010-06-11 09:15:55 -07001// Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "cgpt.h"
6
7#include <getopt.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11#include <uuid/uuid.h>
12
13#include "cgptlib_internal.h"
14
15static void Usage(void)
16{
17 printf("\nUsage: %s create [OPTIONS] DRIVE\n\n"
18 "Create or reset an empty GPT.\n\n"
19 "Options:\n"
20 " -z Zero the sectors of the GPT table and entries\n"
21 "\n", progname);
22}
23
24int cmd_create(int argc, char *argv[]) {
25 struct drive drive;
26 int zap = 0;
27
28 int c;
29 int errorcnt = 0;
30
31 opterr = 0; // quiet, you
32 while ((c=getopt(argc, argv, ":hz")) != -1)
33 {
34 switch (c)
35 {
36 case 'z':
37 zap = 1;
38 break;
39
40 case 'h':
41 Usage();
42 return CGPT_OK;
43 case '?':
44 Error("unrecognized option: -%c\n", optopt);
45 errorcnt++;
46 break;
47 case ':':
48 Error("missing argument to -%c\n", optopt);
49 errorcnt++;
50 break;
51 default:
52 errorcnt++;
53 break;
54 }
55 }
56 if (errorcnt)
57 {
58 Usage();
59 return CGPT_FAILED;
60 }
61
62 if (optind >= argc) {
63 Usage();
64 return CGPT_FAILED;
65 }
66
67 if (CGPT_OK != DriveOpen(argv[optind], &drive))
68 return CGPT_FAILED;
69
70 // Erase the data
71 memset(drive.gpt.primary_header, 0,
72 drive.gpt.sector_bytes * GPT_HEADER_SECTOR);
73 memset(drive.gpt.secondary_header, 0,
74 drive.gpt.sector_bytes * GPT_HEADER_SECTOR);
75 memset(drive.gpt.primary_entries, 0,
76 drive.gpt.sector_bytes * GPT_ENTRIES_SECTORS);
77 memset(drive.gpt.secondary_entries, 0,
78 drive.gpt.sector_bytes * GPT_ENTRIES_SECTORS);
79
80 drive.gpt.modified |= (GPT_MODIFIED_HEADER1 | GPT_MODIFIED_ENTRIES1 |
81 GPT_MODIFIED_HEADER2 | GPT_MODIFIED_ENTRIES2);
82
83 // Initialize a blank set
84 if (!zap)
85 {
86 GptHeader *h = (GptHeader *)drive.gpt.primary_header;
87 memcpy(h->signature, GPT_HEADER_SIGNATURE, GPT_HEADER_SIGNATURE_SIZE);
88 h->revision = GPT_HEADER_REVISION;
89 h->size = sizeof(GptHeader);
90 h->my_lba = 1;
91 h->first_usable_lba = 1 + 1 + GPT_ENTRIES_SECTORS;
92 h->last_usable_lba = drive.gpt.drive_sectors - 1 - GPT_ENTRIES_SECTORS - 1;
93 uuid_generate((uint8_t *)&h->disk_uuid);
94 h->entries_lba = 2;
95 h->number_of_entries = 128;
96 h->size_of_entry = sizeof(GptEntry);
97
98 // Copy to secondary
99 RepairHeader(&drive.gpt, MASK_PRIMARY);
100
101 UpdateCrc(&drive.gpt);
102 }
103
104 // Write it all out
105 return DriveClose(&drive, 1);
106}