newfs_udf.c revision 1.4 1 /* $NetBSD: newfs_udf.c,v 1.4 2008/07/26 20:20:56 reinoud Exp $ */
2
3 /*
4 * Copyright (c) 2006, 2008 Reinoud Zandijk
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 *
27 */
28
29 /*
30 * TODO
31 * - implement meta data partition formatting.
32 * - implement support for a read-only companion partition?
33 */
34
35 #define _EXPOSE_MMC
36 #if 0
37 # define DEBUG
38 #endif
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <dirent.h>
43 #include <inttypes.h>
44 #include <stdint.h>
45 #include <string.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <unistd.h>
49 #include <util.h>
50 #include <fattr.h>
51 #include <time.h>
52 #include <assert.h>
53 #include <err.h>
54
55 #include <sys/ioctl.h>
56 #include <sys/stat.h>
57 #include <sys/types.h>
58 #include <sys/cdio.h>
59 #include <sys/disklabel.h>
60 #include <sys/dkio.h>
61 #include <sys/param.h>
62 #include <sys/queue.h>
63
64 #include <fs/udf/ecma167-udf.h>
65 #include <fs/udf/udf_mount.h>
66 #include "udf_create.h"
67
68 /* general settings */
69 #define UDF_512_TRACK 0 /* NOT recommended */
70 #define UDF_META_PERC 20 /* picked */
71
72
73 /* prototypes */
74 int newfs_udf(int argc, char **argv);
75 static void usage(void) __attribute__((__noreturn__));
76
77 int udf_derive_format(int req_en, int req_dis, int force);
78 int udf_proces_names(void);
79 int udf_do_newfs(void);
80
81 /* Identifying myself */
82 #define APP_NAME "*NetBSD newfs"
83 #define APP_VERSION_MAIN 0
84 #define APP_VERSION_SUB 3
85 #define IMPL_NAME "*NetBSD userland UDF"
86
87
88 /* global variables describing disc and format requests */
89 int fd; /* device: file descriptor */
90 char *dev; /* device: name */
91 struct mmc_discinfo mmc_discinfo; /* device: disc info */
92
93 char *format_str; /* format: string representation */
94 int format_flags; /* format: attribute flags */
95 int media_accesstype; /* derived from current mmc cap */
96 int check_surface; /* for rewritables */
97
98 int wrtrack_skew;
99 int meta_perc = UDF_META_PERC;
100 float meta_fract = (float) UDF_META_PERC / 100.0;
101
102
103 /* shared structure between udf_create.c users */
104 struct udf_create_context context;
105 struct udf_disclayout layout;
106
107
108 /* queue for temporary storage of sectors to be written out */
109 struct wrsect {
110 uint32_t sectornr;
111 uint8_t *sector_data;
112 TAILQ_ENTRY(wrsect) next;
113 };
114
115 /* write queue and track blocking skew */
116 TAILQ_HEAD(wrsect_list, wrsect) write_queue;
117
118
119 /* --------------------------------------------------------------------- */
120
121 /*
122 * write queue implementation
123 */
124
125 static int
126 udf_write_sector(void *sector, uint32_t location)
127 {
128 struct wrsect *pos, *seekpos;
129
130
131 /* search location */
132 TAILQ_FOREACH_REVERSE(seekpos, &write_queue, wrsect_list, next) {
133 if (seekpos->sectornr <= location)
134 break;
135 }
136 if ((seekpos == NULL) || (seekpos->sectornr != location)) {
137 pos = calloc(1, sizeof(struct wrsect));
138 if (pos == NULL)
139 return ENOMEM;
140 /* allocate space for copy of sector data */
141 pos->sector_data = calloc(1, context.sector_size);
142 if (pos->sector_data == NULL)
143 return ENOMEM;
144 pos->sectornr = location;
145
146 if (seekpos) {
147 TAILQ_INSERT_AFTER(&write_queue, seekpos, pos, next);
148 } else {
149 TAILQ_INSERT_HEAD(&write_queue, pos, next);
150 }
151 } else {
152 pos = seekpos;
153 }
154 memcpy(pos->sector_data, sector, context.sector_size);
155
156 return 0;
157 }
158
159
160 /*
161 * Now all write requests are queued in the TAILQ, write them out to the
162 * disc/file image. Special care needs to be taken for devices that are only
163 * strict overwritable i.e. only in packet size chunks
164 *
165 * XXX support for growing vnd?
166 */
167
168 static int
169 writeout_write_queue(void)
170 {
171 struct wrsect *pos;
172 uint64_t offset;
173 uint32_t line_len, line_offset;
174 uint32_t line_start, new_line_start, relpos;
175 uint32_t blockingnr;
176 uint8_t *linebuf, *adr;
177
178 blockingnr = layout.blockingnr;
179 line_len = blockingnr * context.sector_size;
180 line_offset = wrtrack_skew * context.sector_size;
181
182 linebuf = malloc(line_len);
183 if (linebuf == NULL)
184 return ENOMEM;
185
186 pos = TAILQ_FIRST(&write_queue);
187 bzero(linebuf, line_len);
188
189 /*
190 * Always writing out in whole lines now; this is slightly wastefull
191 * on logical overwrite volumes but it reduces complexity and the loss
192 * is near zero compared to disc size.
193 */
194 line_start = (pos->sectornr - wrtrack_skew) / blockingnr;
195 TAILQ_FOREACH(pos, &write_queue, next) {
196 new_line_start = (pos->sectornr - wrtrack_skew) / blockingnr;
197 if (new_line_start != line_start) {
198 /* write out */
199 offset = (uint64_t) line_start * line_len + line_offset;
200 #ifdef DEBUG
201 printf("WRITEOUT %08"PRIu64" + %02d -- "
202 "[%08"PRIu64"..%08"PRIu64"]\n",
203 offset / context.sector_size, blockingnr,
204 offset / context.sector_size,
205 offset / context.sector_size + blockingnr-1);
206 #endif
207 if (pwrite(fd, linebuf, line_len, offset) < 0) {
208 perror("Writing failed");
209 return errno;
210 }
211 line_start = new_line_start;
212 bzero(linebuf, line_len);
213 }
214
215 relpos = (pos->sectornr - wrtrack_skew) % blockingnr;
216 adr = linebuf + relpos * context.sector_size;
217 memcpy(adr, pos->sector_data, context.sector_size);
218 }
219 /* writeout last chunk */
220 offset = (uint64_t) line_start * line_len + line_offset;
221 #ifdef DEBUG
222 printf("WRITEOUT %08"PRIu64" + %02d -- [%08"PRIu64"..%08"PRIu64"]\n",
223 offset / context.sector_size, blockingnr,
224 offset / context.sector_size,
225 offset / context.sector_size + blockingnr-1);
226 #endif
227 if (pwrite(fd, linebuf, line_len, offset) < 0) {
228 perror("Writing failed");
229 return errno;
230 }
231
232 /* success */
233 return 0;
234 }
235
236 /* --------------------------------------------------------------------- */
237
238 /*
239 * mmc_discinfo and mmc_trackinfo readers modified from origional in udf main
240 * code in sys/fs/udf/
241 */
242
243 #ifdef DEBUG
244 static void
245 udf_dump_discinfo(struct mmc_discinfo *di)
246 {
247 char bits[128];
248
249 printf("Device/media info :\n");
250 printf("\tMMC profile 0x%02x\n", di->mmc_profile);
251 printf("\tderived class %d\n", di->mmc_class);
252 printf("\tsector size %d\n", di->sector_size);
253 printf("\tdisc state %d\n", di->disc_state);
254 printf("\tlast ses state %d\n", di->last_session_state);
255 printf("\tbg format state %d\n", di->bg_format_state);
256 printf("\tfrst track %d\n", di->first_track);
257 printf("\tfst on last ses %d\n", di->first_track_last_session);
258 printf("\tlst on last ses %d\n", di->last_track_last_session);
259 printf("\tlink block penalty %d\n", di->link_block_penalty);
260 snprintb(bits, sizeof(bits), MMC_DFLAGS_FLAGBITS, (uint64_t) di->disc_flags);
261 printf("\tdisc flags %s\n", bits);
262 printf("\tdisc id %x\n", di->disc_id);
263 printf("\tdisc barcode %"PRIx64"\n", di->disc_barcode);
264
265 printf("\tnum sessions %d\n", di->num_sessions);
266 printf("\tnum tracks %d\n", di->num_tracks);
267
268 snprintb(bits, sizeof(bits), MMC_CAP_FLAGBITS, di->mmc_cur);
269 printf("\tcapabilities cur %s\n", bits);
270 snprintb(bits, sizeof(bits), MMC_CAP_FLAGBITS, di->mmc_cap);
271 printf("\tcapabilities cap %s\n", bits);
272 printf("\n");
273 printf("\tlast_possible_lba %d\n", di->last_possible_lba);
274 printf("\n");
275 }
276 #else
277 #define udf_dump_discinfo(a);
278 #endif
279
280 /* --------------------------------------------------------------------- */
281
282 static int
283 udf_update_discinfo(struct mmc_discinfo *di)
284 {
285 struct disklabel disklab;
286 struct partition *dp;
287 struct stat st;
288 int partnr, error;
289
290 memset(di, 0, sizeof(struct mmc_discinfo));
291
292 /* check if we're on a MMC capable device, i.e. CD/DVD */
293 error = ioctl(fd, MMCGETDISCINFO, di);
294 if (error == 0)
295 return 0;
296
297 /*
298 * disc partition support; note we can't use DIOCGPART in userland so
299 * get disc label and use the stat info to get the partition number.
300 */
301 if (ioctl(fd, DIOCGDINFO, &disklab) == -1) {
302 /* failed to get disclabel! */
303 perror("disklabel");
304 return errno;
305 }
306
307 /* get disk partition it refers to */
308 fstat(fd, &st);
309 partnr = DISKPART(st.st_rdev);
310 dp = &disklab.d_partitions[partnr];
311
312 /* set up a disc info profile for partitions */
313 di->mmc_profile = 0x01; /* disc type */
314 di->mmc_class = MMC_CLASS_DISC;
315 di->disc_state = MMC_STATE_CLOSED;
316 di->last_session_state = MMC_STATE_CLOSED;
317 di->bg_format_state = MMC_BGFSTATE_COMPLETED;
318 di->link_block_penalty = 0;
319
320 di->mmc_cur = MMC_CAP_RECORDABLE | MMC_CAP_REWRITABLE |
321 MMC_CAP_ZEROLINKBLK | MMC_CAP_HW_DEFECTFREE;
322 di->mmc_cap = di->mmc_cur;
323 di->disc_flags = MMC_DFLAGS_UNRESTRICTED;
324
325 /* TODO problem with last_possible_lba on resizable VND; request */
326 if (dp->p_size == 0) {
327 perror("faulty disklabel partition returned, check label\n");
328 return EIO;
329 }
330 di->last_possible_lba = dp->p_size - 1;
331 di->sector_size = disklab.d_secsize;
332
333 di->num_sessions = 1;
334 di->num_tracks = 1;
335
336 di->first_track = 1;
337 di->first_track_last_session = di->last_track_last_session = 1;
338
339 return 0;
340 }
341
342
343 static int
344 udf_update_trackinfo(struct mmc_discinfo *di, struct mmc_trackinfo *ti)
345 {
346 int error, class;
347
348 class = di->mmc_class;
349 if (class != MMC_CLASS_DISC) {
350 /* tracknr specified in struct ti */
351 error = ioctl(fd, MMCGETTRACKINFO, ti);
352 return error;
353 }
354
355 /* discs partition support */
356 if (ti->tracknr != 1)
357 return EIO;
358
359 /* create fake ti (TODO check for resized vnds) */
360 ti->sessionnr = 1;
361
362 ti->track_mode = 0; /* XXX */
363 ti->data_mode = 0; /* XXX */
364 ti->flags = MMC_TRACKINFO_LRA_VALID | MMC_TRACKINFO_NWA_VALID;
365
366 ti->track_start = 0;
367 ti->packet_size = 1;
368
369 /* TODO support for resizable vnd */
370 ti->track_size = di->last_possible_lba;
371 ti->next_writable = di->last_possible_lba;
372 ti->last_recorded = ti->next_writable;
373 ti->free_blocks = 0;
374
375 return 0;
376 }
377
378
379 static int
380 udf_setup_writeparams(struct mmc_discinfo *di)
381 {
382 struct mmc_writeparams mmc_writeparams;
383 int error;
384
385 if (di->mmc_class == MMC_CLASS_DISC)
386 return 0;
387
388 /*
389 * only CD burning normally needs setting up, but other disc types
390 * might need other settings to be made. The MMC framework will set up
391 * the nessisary recording parameters according to the disc
392 * characteristics read in. Modifications can be made in the discinfo
393 * structure passed to change the nature of the disc.
394 */
395 memset(&mmc_writeparams, 0, sizeof(struct mmc_writeparams));
396 mmc_writeparams.mmc_class = di->mmc_class;
397 mmc_writeparams.mmc_cur = di->mmc_cur;
398
399 /*
400 * UDF dictates first track to determine track mode for the whole
401 * disc. [UDF 1.50/6.10.1.1, UDF 1.50/6.10.2.1]
402 * To prevent problems with a `reserved' track in front we start with
403 * the 2nd track and if that is not valid, go for the 1st.
404 */
405 mmc_writeparams.tracknr = 2;
406 mmc_writeparams.data_mode = MMC_DATAMODE_DEFAULT; /* XA disc */
407 mmc_writeparams.track_mode = MMC_TRACKMODE_DEFAULT; /* data */
408
409 error = ioctl(fd, MMCSETUPWRITEPARAMS, &mmc_writeparams);
410 if (error) {
411 mmc_writeparams.tracknr = 1;
412 error = ioctl(fd, MMCSETUPWRITEPARAMS, &mmc_writeparams);
413 }
414 return error;
415 }
416
417
418 static void
419 udf_synchronise_caches(void)
420 {
421 struct mmc_op mmc_op;
422
423 bzero(&mmc_op, sizeof(struct mmc_op));
424 mmc_op.operation = MMC_OP_SYNCHRONISECACHE;
425
426 /* this device might not know this ioct, so just be ignorant */
427 (void) ioctl(fd, MMCOP, &mmc_op);
428 }
429
430 /* --------------------------------------------------------------------- */
431
432 static int
433 udf_write_dscr_phys(union dscrptr *dscr, uint32_t location,
434 uint32_t sects)
435 {
436 uint32_t phys;
437 uint8_t *bpos;
438 int error, cnt;
439
440 dscr->tag.tag_loc = udf_rw32(location);
441 (void) udf_validate_tag_and_crc_sums(dscr);
442
443 for (cnt = 0; cnt < sects; cnt++) {
444 bpos = (uint8_t *) dscr;
445 bpos += context.sector_size * cnt;
446
447 phys = location + cnt;
448 error = udf_write_sector(bpos, phys);
449 if (error)
450 return error;
451 }
452 return 0;
453 }
454
455
456 static int
457 udf_write_dscr_virt(union dscrptr *dscr, uint32_t location, uint32_t vpart,
458 uint32_t sects)
459 {
460 struct file_entry *fe;
461 struct extfile_entry *efe;
462 struct extattrhdr_desc *extattrhdr;
463 uint32_t phys;
464 uint8_t *bpos;
465 int error, cnt;
466
467 extattrhdr = NULL;
468 if (udf_rw16(dscr->tag.id) == TAGID_FENTRY) {
469 fe = (struct file_entry *) dscr;
470 if (udf_rw32(fe->l_ea) > 0)
471 extattrhdr = (struct extattrhdr_desc *) fe->data;
472 }
473 if (udf_rw16(dscr->tag.id) == TAGID_EXTFENTRY) {
474 efe = (struct extfile_entry *) dscr;
475 if (udf_rw32(efe->l_ea) > 0)
476 extattrhdr = (struct extattrhdr_desc *) efe->data;
477 }
478 if (extattrhdr) {
479 extattrhdr->tag.tag_loc = udf_rw32(location);
480 udf_validate_tag_and_crc_sums((union dscrptr *) extattrhdr);
481 }
482
483 dscr->tag.tag_loc = udf_rw32(location);
484 udf_validate_tag_and_crc_sums(dscr);
485
486 for (cnt = 0; cnt < sects; cnt++) {
487 bpos = (uint8_t *) dscr;
488 bpos += context.sector_size * cnt;
489
490 /* NOTE linear mapping assumed in the ranges used */
491 phys = context.vtop_offset[vpart] + location + cnt;
492
493 error = udf_write_sector(bpos, phys);
494 if (error)
495 return error;
496 }
497 return 0;
498 }
499
500 /* --------------------------------------------------------------------- */
501
502 /*
503 * udf_derive_format derives the format_flags from the disc's mmc_discinfo.
504 * The resulting flags uniquely define a disc format. Note there are at least
505 * 7 distinct format types defined in UDF.
506 */
507
508 #define UDF_VERSION(a) \
509 (((a) == 0x100) || ((a) == 0x102) || ((a) == 0x150) || ((a) == 0x200) || \
510 ((a) == 0x201) || ((a) == 0x250) || ((a) == 0x260))
511
512 int
513 udf_derive_format(int req_enable, int req_disable, int force)
514 {
515 /* disc writability, formatted, appendable */
516 if ((mmc_discinfo.mmc_cur & MMC_CAP_RECORDABLE) == 0) {
517 (void)printf("Can't newfs readonly device\n");
518 return EROFS;
519 }
520 if (mmc_discinfo.mmc_cur & MMC_CAP_SEQUENTIAL) {
521 /* sequentials need sessions appended */
522 if (mmc_discinfo.disc_state == MMC_STATE_CLOSED) {
523 (void)printf("Can't append session to a closed disc\n");
524 return EROFS;
525 }
526 if ((mmc_discinfo.disc_state != MMC_STATE_EMPTY) && !force) {
527 (void)printf("Disc not empty! Use -F to force "
528 "initialisation\n");
529 return EROFS;
530 }
531 } else {
532 /* check if disc (being) formatted or has been started on */
533 if (mmc_discinfo.disc_state == MMC_STATE_EMPTY) {
534 (void)printf("Disc is not formatted\n");
535 return EROFS;
536 }
537 }
538
539 /* determine UDF format */
540 format_flags = 0;
541 if (mmc_discinfo.mmc_cur & MMC_CAP_REWRITABLE) {
542 /* all rewritable media */
543 format_flags |= FORMAT_REWRITABLE;
544 if (context.min_udf >= 0x0250) {
545 /* standard dictates meta as default */
546 format_flags |= FORMAT_META;
547 }
548
549 if ((mmc_discinfo.mmc_cur & MMC_CAP_HW_DEFECTFREE) == 0) {
550 /* sparables for defect management */
551 if (context.min_udf >= 0x150)
552 format_flags |= FORMAT_SPARABLE;
553 }
554 } else {
555 /* all once recordable media */
556 format_flags |= FORMAT_WRITEONCE;
557 if (mmc_discinfo.mmc_cur & MMC_CAP_SEQUENTIAL) {
558 format_flags |= FORMAT_SEQUENTIAL;
559
560 if (mmc_discinfo.mmc_cur & MMC_CAP_PSEUDOOVERWRITE) {
561 /* logical overwritable */
562 format_flags |= FORMAT_LOW;
563 } else {
564 /* have to use VAT for overwriting */
565 format_flags |= FORMAT_VAT;
566 }
567 } else {
568 /* rare WORM devices, but BluRay has one, strat4096 */
569 format_flags |= FORMAT_WORM;
570 }
571 }
572
573 /* enable/disable requests */
574 if (req_disable & FORMAT_META) {
575 format_flags &= ~FORMAT_META;
576 req_disable &= ~FORMAT_META;
577 }
578 if (req_disable || req_enable) {
579 (void)printf("Internal error\n");
580 (void)printf("\tunrecognised enable/disable req.\n");
581 return EIO;
582 }
583 if ((format_flags && FORMAT_VAT) && UDF_512_TRACK)
584 format_flags |= FORMAT_TRACK512;
585
586 /* determine partition/media access type */
587 media_accesstype = UDF_ACCESSTYPE_NOT_SPECIFIED;
588 if (mmc_discinfo.mmc_cur & MMC_CAP_REWRITABLE) {
589 media_accesstype = UDF_ACCESSTYPE_OVERWRITABLE;
590 if (mmc_discinfo.mmc_cur & MMC_CAP_ERASABLE)
591 media_accesstype = UDF_ACCESSTYPE_REWRITEABLE;
592 } else {
593 /* all once recordable media */
594 media_accesstype = UDF_ACCESSTYPE_WRITE_ONCE;
595 }
596 if (mmc_discinfo.mmc_cur & MMC_CAP_PSEUDOOVERWRITE)
597 media_accesstype = UDF_ACCESSTYPE_PSEUDO_OVERWITE;
598
599 /* adjust minimum version limits */
600 if (format_flags & FORMAT_VAT)
601 context.min_udf = MAX(context.min_udf, 0x0150);
602 if (format_flags & FORMAT_SPARABLE)
603 context.min_udf = MAX(context.min_udf, 0x0150);
604 if (format_flags & FORMAT_META)
605 context.min_udf = MAX(context.min_udf, 0x0250);
606 if (format_flags & FORMAT_LOW)
607 context.min_udf = MAX(context.min_udf, 0x0260);
608
609 /* adjust maximum version limits not to tease or break things */
610 if (!(format_flags & FORMAT_META) && (context.max_udf > 0x200))
611 context.max_udf = 0x201;
612
613 if ((format_flags & (FORMAT_VAT | FORMAT_SPARABLE)) == 0)
614 if (context.max_udf <= 0x150)
615 context.min_udf = 0x102;
616
617 /* limit Ecma 167 descriptor if possible/needed */
618 context.dscrver = 3;
619 if ((context.min_udf < 0x200) || (context.max_udf < 0x200)) {
620 context.dscrver = 2;
621 context.max_udf = 0x150; /* last version < 0x200 */
622 }
623
624 /* is it possible ? */
625 if (context.min_udf > context.max_udf) {
626 (void)printf("Initialisation prohibited by specified maximum "
627 "UDF version 0x%04x. Minimum version required 0x%04x\n",
628 context.max_udf, context.min_udf);
629 return EPERM;
630 }
631
632 if (!UDF_VERSION(context.min_udf) || !UDF_VERSION(context.max_udf)) {
633 printf("Choose UDF version numbers from "
634 "0x102, 0x150, 0x200, 0x201, 0x250 and 0x260\n");
635 printf("Default version is 0x201\n");
636 return EPERM;
637 }
638
639 return 0;
640 }
641
642 #undef UDF_VERSION
643
644
645 /* --------------------------------------------------------------------- */
646
647 int
648 udf_proces_names(void)
649 {
650 uint32_t primary_nr;
651 uint64_t volset_nr;
652
653 if (context.logvol_name == NULL)
654 context.logvol_name = strdup("anonymous");
655 if (context.primary_name == NULL) {
656 if (mmc_discinfo.disc_flags & MMC_DFLAGS_DISCIDVALID) {
657 primary_nr = mmc_discinfo.disc_id;
658 } else {
659 primary_nr = (uint32_t) random();
660 }
661 context.primary_name = calloc(32, 1);
662 sprintf(context.primary_name, "%08"PRIx32, primary_nr);
663 }
664 if (context.volset_name == NULL) {
665 if (mmc_discinfo.disc_flags & MMC_DFLAGS_BARCODEVALID) {
666 volset_nr = mmc_discinfo.disc_barcode;
667 } else {
668 volset_nr = (uint32_t) random();
669 volset_nr |= ((uint64_t) random()) << 32;
670 }
671 context.volset_name = calloc(128,1);
672 sprintf(context.volset_name, "%016"PRIx64, volset_nr);
673 }
674 if (context.fileset_name == NULL)
675 context.fileset_name = strdup("anonymous");
676
677 /* check passed/created identifiers */
678 if (strlen(context.logvol_name) > 128) {
679 (void)printf("Logical volume name too long\n");
680 return EINVAL;
681 }
682 if (strlen(context.primary_name) > 32) {
683 (void)printf("Primary volume name too long\n");
684 return EINVAL;
685 }
686 if (strlen(context.volset_name) > 128) {
687 (void)printf("Volume set name too long\n");
688 return EINVAL;
689 }
690 if (strlen(context.fileset_name) > 32) {
691 (void)printf("Fileset name too long\n");
692 return EINVAL;
693 }
694
695 /* signal all OK */
696 return 0;
697 }
698
699 /* --------------------------------------------------------------------- */
700
701 static int
702 udf_prepare_disc(void)
703 {
704 struct mmc_trackinfo ti;
705 struct mmc_op op;
706 int tracknr, error;
707
708 /* If the last track is damaged, repair it */
709 ti.tracknr = mmc_discinfo.last_track_last_session;
710 error = udf_update_trackinfo(&mmc_discinfo, &ti);
711 if (error)
712 return error;
713
714 if (ti.flags & MMC_TRACKINFO_DAMAGED) {
715 /*
716 * Need to repair last track before anything can be done.
717 * this is an optional command, so ignore its error but report
718 * warning.
719 */
720 memset(&op, 0, sizeof(op));
721 op.operation = MMC_OP_REPAIRTRACK;
722 op.mmc_profile = mmc_discinfo.mmc_profile;
723 op.tracknr = ti.tracknr;
724 error = ioctl(fd, MMCOP, &op);
725
726 if (error)
727 (void)printf("Drive can't explicitly repair last "
728 "damaged track, but it might autorepair\n");
729 }
730 /* last track (if any) might not be damaged now, operations are ok now */
731
732 /* setup write parameters from discinfo */
733 error = udf_setup_writeparams(&mmc_discinfo);
734 if (error)
735 return error;
736
737 /* if the drive is not sequential, we're done */
738 if ((mmc_discinfo.mmc_cur & MMC_CAP_SEQUENTIAL) == 0)
739 return 0;
740
741 #ifdef notyet
742 /* if last track is not the reserved but an empty track, unreserve it */
743 if (ti.flags & MMC_TRACKINFO_BLANK) {
744 if (ti.flags & MMC_TRACKINFO_RESERVED == 0) {
745 memset(&op, 0, sizeof(op));
746 op.operation = MMC_OP_UNRESERVETRACK;
747 op.mmc_profile = mmc_discinfo.mmc_profile;
748 op.tracknr = ti.tracknr;
749 error = ioctl(fd, MMCOP, &op);
750 if (error)
751 return error;
752
753 /* update discinfo since it changed by the operation */
754 error = udf_update_discinfo(&mmc_discinfo);
755 if (error)
756 return error;
757 }
758 }
759 #endif
760
761 /* close the last session if its still open */
762 if (mmc_discinfo.last_session_state == MMC_STATE_INCOMPLETE) {
763 printf("Closing last open session if present\n");
764 /* close all associated tracks */
765 tracknr = mmc_discinfo.first_track_last_session;
766 while (tracknr <= mmc_discinfo.last_track_last_session) {
767 ti.tracknr = tracknr;
768 error = udf_update_trackinfo(&mmc_discinfo, &ti);
769 if (error)
770 return error;
771 printf("\tClosing open track %d\n", tracknr);
772 memset(&op, 0, sizeof(op));
773 op.operation = MMC_OP_CLOSETRACK;
774 op.mmc_profile = mmc_discinfo.mmc_profile;
775 op.tracknr = tracknr;
776 error = ioctl(fd, MMCOP, &op);
777 if (error)
778 return error;
779 tracknr ++;
780 }
781 printf("Closing session\n");
782 memset(&op, 0, sizeof(op));
783 op.operation = MMC_OP_CLOSESESSION;
784 op.mmc_profile = mmc_discinfo.mmc_profile;
785 op.sessionnr = mmc_discinfo.num_sessions;
786 error = ioctl(fd, MMCOP, &op);
787 if (error)
788 return error;
789
790 /* update discinfo since it changed by the operations */
791 error = udf_update_discinfo(&mmc_discinfo);
792 if (error)
793 return error;
794 }
795
796 if (format_flags & FORMAT_TRACK512) {
797 /* get last track again */
798 ti.tracknr = mmc_discinfo.last_track_last_session;
799 error = udf_update_trackinfo(&mmc_discinfo, &ti);
800 if (error)
801 return error;
802
803 /* Split up the space at 512 for iso cd9660 hooking */
804 memset(&op, 0, sizeof(op));
805 op.operation = MMC_OP_RESERVETRACK_NWA; /* UPTO nwa */
806 op.mmc_profile = mmc_discinfo.mmc_profile;
807 op.extent = 512; /* size */
808 error = ioctl(fd, MMCOP, &op);
809 if (error)
810 return error;
811 }
812
813 return 0;
814 }
815
816 /* --------------------------------------------------------------------- */
817
818 static int
819 udf_surface_check(void)
820 {
821 uint32_t loc, block_bytes;
822 uint32_t sector_size, blockingnr;
823 uint8_t *buffer;
824 int error, num_errors;
825 int bpos;
826
827 sector_size = context.sector_size;
828 blockingnr = layout.blockingnr;
829
830 block_bytes = layout.blockingnr * sector_size;
831 if ((buffer = malloc(block_bytes)) == NULL)
832 return ENOMEM;
833
834 /* set all one to not kill Flash memory? */
835 for (bpos = 0; bpos < block_bytes; bpos++)
836 buffer[bpos] = 0x00;
837
838 printf("\nChecking disc surface : phase 1 - writing\n");
839 num_errors = 0;
840 loc = layout.first_lba;
841 while (loc <= layout.last_lba) {
842 /* write blockingnr sectors */
843 error = pwrite(fd, buffer, block_bytes, loc*sector_size);
844 printf(" %08d + %d (%02d %%)\r", loc, blockingnr,
845 (int)((100.0 * loc)/layout.last_lba));
846 fflush(stdout);
847 if (error == -1) {
848 /* block is bad */
849 printf("BAD block at %08d + %d \n",
850 loc, layout.blockingnr);
851 if ((error = udf_register_bad_block(loc)))
852 return error;
853 num_errors ++;
854 }
855 loc += layout.blockingnr;
856 }
857
858 printf("\nChecking disc surface : phase 2 - reading\n");
859 num_errors = 0;
860 loc = layout.first_lba;
861 while (loc <= layout.last_lba) {
862 /* read blockingnr sectors */
863 error = pread(fd, buffer, block_bytes, loc*sector_size);
864 printf(" %08d + %d (%02d %%)\r", loc, blockingnr,
865 (int)((100.0 * loc)/layout.last_lba));
866 fflush(stdout);
867 if (error == -1) {
868 /* block is bad */
869 printf("BAD block at %08d + %d \n",
870 loc, layout.blockingnr);
871 if ((error = udf_register_bad_block(loc)))
872 return error;
873 num_errors ++;
874 }
875 loc += layout.blockingnr;
876 }
877 printf("Scan complete : %d bad blocks found\n", num_errors);
878 free(buffer);
879
880 return 0;
881 }
882
883 /* --------------------------------------------------------------------- */
884
885 static int
886 udf_write_iso9660_vrs(void)
887 {
888 struct vrs_desc *iso9660_vrs_desc;
889 uint32_t pos;
890 int error, cnt, dpos;
891
892 /* create ISO/Ecma-167 identification descriptors */
893 if ((iso9660_vrs_desc = calloc(1, context.sector_size)) == NULL)
894 return ENOMEM;
895
896 /*
897 * All UDF formats should have their ISO/Ecma-167 descriptors written
898 * except when not possible due to track reservation in the case of
899 * VAT
900 */
901 if ((format_flags & FORMAT_TRACK512) == 0) {
902 dpos = (2048 + context.sector_size - 1) / context.sector_size;
903
904 /* wipe at least 6 times 2048 byte `sectors' */
905 for (cnt = 0; cnt < 6 *dpos; cnt++) {
906 pos = layout.iso9660_vrs + cnt;
907 if ((error = udf_write_sector(iso9660_vrs_desc, pos)))
908 return error;
909 }
910
911 /* common VRS fields in all written out ISO descriptors */
912 iso9660_vrs_desc->struct_type = 0;
913 iso9660_vrs_desc->version = 1;
914 pos = layout.iso9660_vrs;
915
916 /* BEA01, NSR[23], TEA01 */
917 memcpy(iso9660_vrs_desc->identifier, "BEA01", 5);
918 if ((error = udf_write_sector(iso9660_vrs_desc, pos)))
919 return error;
920 pos += dpos;
921
922 if (context.dscrver == 2)
923 memcpy(iso9660_vrs_desc->identifier, "NSR02", 5);
924 else
925 memcpy(iso9660_vrs_desc->identifier, "NSR03", 5);
926 ;
927 if ((error = udf_write_sector(iso9660_vrs_desc, pos)))
928 return error;
929 pos += dpos;
930
931 memcpy(iso9660_vrs_desc->identifier, "TEA01", 5);
932 if ((error = udf_write_sector(iso9660_vrs_desc, pos)))
933 return error;
934 }
935
936 /* return success */
937 return 0;
938 }
939
940
941 /* --------------------------------------------------------------------- */
942
943 /*
944 * Main function that creates and writes out disc contents based on the
945 * format_flags's that uniquely define the type of disc to create.
946 */
947
948 int
949 udf_do_newfs(void)
950 {
951 union dscrptr *zero_dscr;
952 union dscrptr *terminator_dscr;
953 union dscrptr *root_dscr;
954 union dscrptr *vat_dscr;
955 union dscrptr *dscr;
956 struct mmc_trackinfo ti;
957 uint32_t sparable_blocks;
958 uint32_t sector_size, blockingnr;
959 uint32_t cnt, loc, len;
960 int sectcopy;
961 int error, integrity_type;
962 int data_part, metadata_part;
963
964 /* init */
965 sector_size = mmc_discinfo.sector_size;
966
967 /* determine span/size */
968 ti.tracknr = mmc_discinfo.first_track_last_session;
969 error = udf_update_trackinfo(&mmc_discinfo, &ti);
970 if (error)
971 return error;
972
973 if (mmc_discinfo.sector_size < context.sector_size) {
974 fprintf(stderr, "Impossible to format: sectorsize too small\n");
975 return EIO;
976 }
977 context.sector_size = sector_size;
978
979 /* determine blockingnr */
980 blockingnr = ti.packet_size;
981 if (blockingnr <= 1) {
982 /* paranoia on blockingnr */
983 switch (mmc_discinfo.mmc_profile) {
984 case 0x09 : /* CD-R */
985 case 0x0a : /* CD-RW */
986 blockingnr = 32; /* UDF requirement */
987 break;
988 case 0x11 : /* DVD-R (DL) */
989 case 0x1b : /* DVD+R */
990 case 0x2b : /* DVD+R Dual layer */
991 case 0x13 : /* DVD-RW restricted overwrite */
992 case 0x14 : /* DVD-RW sequential */
993 blockingnr = 16; /* SCSI definition */
994 break;
995 case 0x41 : /* BD-R Sequential recording (SRM) */
996 case 0x51 : /* HD DVD-R */
997 blockingnr = 32; /* SCSI definition */
998 break;
999 default:
1000 break;
1001 }
1002
1003 }
1004 if (blockingnr <= 0) {
1005 printf("Can't fixup blockingnumber for device "
1006 "type %d\n", mmc_discinfo.mmc_profile);
1007
1008 printf("Device is not returning valid blocking"
1009 " number and media type is unknown.\n");
1010
1011 return EINVAL;
1012 }
1013
1014 /* setup sector writeout queue's */
1015 TAILQ_INIT(&write_queue);
1016 wrtrack_skew = ti.track_start % blockingnr;
1017
1018 if (mmc_discinfo.mmc_class == MMC_CLASS_CD) {
1019 /* not too much for CD-RW, still 20Mb */
1020 sparable_blocks = 32;
1021 } else {
1022 /* take a value for DVD*RW mainly, BD is `defect free' */
1023 sparable_blocks = 512;
1024 }
1025
1026 /* get layout */
1027 error = udf_calculate_disc_layout(format_flags, context.min_udf,
1028 wrtrack_skew,
1029 ti.track_start, mmc_discinfo.last_possible_lba,
1030 sector_size, blockingnr, sparable_blocks,
1031 meta_fract);
1032
1033 /* cache partition for we need it often */
1034 data_part = context.data_part;
1035 metadata_part = context.metadata_part;
1036
1037 /* Create sparing table descriptor if applicable */
1038 if (format_flags & FORMAT_SPARABLE) {
1039 if ((error = udf_create_sparing_tabled()))
1040 return error;
1041
1042 if (check_surface) {
1043 if ((error = udf_surface_check()))
1044 return error;
1045 }
1046 }
1047
1048 /* Create a generic terminator descriptor */
1049 terminator_dscr = calloc(1, sector_size);
1050 if (terminator_dscr == NULL)
1051 return ENOMEM;
1052 udf_create_terminator(terminator_dscr, 0);
1053
1054 /*
1055 * Start with wipeout of VRS1 upto start of partition. This allows
1056 * formatting for sequentials with the track reservation and it
1057 * cleans old rubbish on rewritables. For sequentuals without the
1058 * track reservation all is wiped from track start.
1059 */
1060 if ((zero_dscr = calloc(1, context.sector_size)) == NULL)
1061 return ENOMEM;
1062
1063 loc = (format_flags & FORMAT_TRACK512) ? layout.vds1 : ti.track_start;
1064 for (; loc < layout.part_start_lba; loc++) {
1065 if ((error = udf_write_sector(zero_dscr, loc)))
1066 return error;
1067 }
1068
1069 /* Create anchors */
1070 for (cnt = 0; cnt < 3; cnt++) {
1071 if ((error = udf_create_anchor(cnt)))
1072 return error;
1073 }
1074
1075 /*
1076 * Create the two Volume Descriptor Sets (VDS) each containing the
1077 * following descriptors : primary volume, partition space,
1078 * unallocated space, logical volume, implementation use and the
1079 * terminator
1080 */
1081
1082 /* start of volume recognision sequence building */
1083 context.vds_seq = 0;
1084
1085 /* Create primary volume descriptor */
1086 if ((error = udf_create_primaryd()))
1087 return error;
1088
1089 /* Create partition descriptor */
1090 if ((error = udf_create_partitiond(context.data_part, media_accesstype)))
1091 return error;
1092
1093 /* Create unallocated space descriptor */
1094 if ((error = udf_create_unalloc_spaced()))
1095 return error;
1096
1097 /* Create logical volume descriptor */
1098 if ((error = udf_create_logical_dscr(format_flags)))
1099 return error;
1100
1101 /* Create implementation use descriptor */
1102 /* TODO input of fields 1,2,3 and passing them */
1103 if ((error = udf_create_impvold(NULL, NULL, NULL)))
1104 return error;
1105
1106 /* write out what we've created so far */
1107
1108 /* writeout iso9660 vrs */
1109 if ((error = udf_write_iso9660_vrs()))
1110 return error;
1111
1112 /* Writeout anchors */
1113 for (cnt = 0; cnt < 3; cnt++) {
1114 dscr = (union dscrptr *) context.anchors[cnt];
1115 loc = layout.anchors[cnt];
1116 if ((error = udf_write_dscr_phys(dscr, loc, 1)))
1117 return error;
1118
1119 /* sequential media has only one anchor */
1120 if (format_flags & FORMAT_SEQUENTIAL)
1121 break;
1122 }
1123
1124 /* write out main and secondary VRS */
1125 for (sectcopy = 1; sectcopy <= 2; sectcopy++) {
1126 loc = (sectcopy == 1) ? layout.vds1 : layout.vds2;
1127
1128 /* primary volume descriptor */
1129 dscr = (union dscrptr *) context.primary_vol;
1130 error = udf_write_dscr_phys(dscr, loc, 1);
1131 if (error)
1132 return error;
1133 loc++;
1134
1135 /* partition descriptor(s) */
1136 for (cnt = 0; cnt < UDF_PARTITIONS; cnt++) {
1137 dscr = (union dscrptr *) context.partitions[cnt];
1138 if (dscr) {
1139 error = udf_write_dscr_phys(dscr, loc, 1);
1140 if (error)
1141 return error;
1142 loc++;
1143 }
1144 }
1145
1146 /* unallocated space descriptor */
1147 dscr = (union dscrptr *) context.unallocated;
1148 error = udf_write_dscr_phys(dscr, loc, 1);
1149 if (error)
1150 return error;
1151 loc++;
1152
1153 /* logical volume descriptor */
1154 dscr = (union dscrptr *) context.logical_vol;
1155 error = udf_write_dscr_phys(dscr, loc, 1);
1156 if (error)
1157 return error;
1158 loc++;
1159
1160 /* implementation use descriptor */
1161 dscr = (union dscrptr *) context.implementation;
1162 error = udf_write_dscr_phys(dscr, loc, 1);
1163 if (error)
1164 return error;
1165 loc++;
1166
1167 /* terminator descriptor */
1168 error = udf_write_dscr_phys(terminator_dscr, loc, 1);
1169 if (error)
1170 return error;
1171 loc++;
1172 }
1173
1174 /* writeout the two sparable table descriptors (if needed) */
1175 if (format_flags & FORMAT_SPARABLE) {
1176 for (sectcopy = 1; sectcopy <= 2; sectcopy++) {
1177 loc = (sectcopy == 1) ? layout.spt_1 : layout.spt_2;
1178 dscr = (union dscrptr *) context.sparing_table;
1179 len = layout.sparing_table_dscr_lbas;
1180
1181 /* writeout */
1182 error = udf_write_dscr_phys(dscr, loc, len);
1183 if (error)
1184 return error;
1185 }
1186 }
1187
1188 /*
1189 * Create unallocated space bitmap descriptor. Sequential recorded
1190 * media report their own free/used space; no free/used space tables
1191 * should be recorded for these.
1192 */
1193 if ((format_flags & FORMAT_SEQUENTIAL) == 0) {
1194 error = udf_create_space_bitmap(
1195 layout.alloc_bitmap_dscr_size,
1196 layout.part_size_lba,
1197 &context.part_unalloc_bits[data_part]);
1198 if (error)
1199 return error;
1200 /* TODO: freed space bitmap if applicable */
1201
1202 /* mark space allocated for the unallocated space bitmap */
1203 udf_mark_allocated(layout.unalloc_space, data_part,
1204 layout.alloc_bitmap_dscr_size);
1205 }
1206
1207 /*
1208 * Create metadata partition file entries and allocate and init their
1209 * space and free space maps.
1210 */
1211 if (format_flags & FORMAT_META) {
1212 error = udf_create_space_bitmap(
1213 layout.meta_bitmap_dscr_size,
1214 layout.meta_part_size_lba,
1215 &context.part_unalloc_bits[metadata_part]);
1216 if (error)
1217 return error;
1218
1219 error = udf_create_meta_files();
1220 if (error)
1221 return error;
1222
1223 /* mark space allocated for meta partition and its bitmap */
1224 udf_mark_allocated(layout.meta_file, data_part, 1);
1225 udf_mark_allocated(layout.meta_mirror, data_part, 1);
1226 udf_mark_allocated(layout.meta_bitmap, data_part, 1);
1227 udf_mark_allocated(layout.meta_part_start_lba, data_part,
1228 layout.meta_part_size_lba);
1229
1230 /* mark space allocated for the unallocated space bitmap */
1231 udf_mark_allocated(layout.meta_bitmap_space, data_part,
1232 layout.meta_bitmap_dscr_size);
1233 }
1234
1235 /* create logical volume integrity descriptor */
1236 context.num_files = 0;
1237 context.num_directories = 0;
1238 integrity_type = UDF_INTEGRITY_OPEN;
1239 if ((error = udf_create_lvintd(integrity_type)))
1240 return error;
1241
1242 /* create FSD */
1243 if ((error = udf_create_fsd()))
1244 return error;
1245 udf_mark_allocated(layout.fsd, metadata_part, 1);
1246
1247 /* create root directory */
1248 assert(context.unique_id == 0x10);
1249 context.unique_id = 0;
1250 if ((error = udf_create_new_rootdir(&root_dscr)))
1251 return error;
1252 udf_mark_allocated(layout.rootdir, metadata_part, 1);
1253
1254 /* writeout FSD + rootdir */
1255 dscr = (union dscrptr *) context.fileset_desc;
1256 error = udf_write_dscr_virt(dscr, layout.fsd, metadata_part, 1);
1257 if (error)
1258 return error;
1259
1260 error = udf_write_dscr_virt(root_dscr, layout.rootdir, metadata_part, 1);
1261 if (error)
1262 return error;
1263
1264 /* writeout initial open integrity sequence + terminator */
1265 loc = layout.lvis;
1266 dscr = (union dscrptr *) context.logvol_integrity;
1267 error = udf_write_dscr_phys(dscr, loc, 1);
1268 if (error)
1269 return error;
1270 loc++;
1271 error = udf_write_dscr_phys(terminator_dscr, loc, 1);
1272 if (error)
1273 return error;
1274
1275
1276 /* XXX the place to add more files */
1277
1278
1279 if ((format_flags & FORMAT_SEQUENTIAL) == 0) {
1280 /* update lvint and mark it closed */
1281 udf_update_lvintd(UDF_INTEGRITY_CLOSED);
1282
1283 /* overwrite initial terminator */
1284 loc = layout.lvis+1;
1285 dscr = (union dscrptr *) context.logvol_integrity;
1286 error = udf_write_dscr_phys(dscr, loc, 1);
1287 if (error)
1288 return error;
1289 loc++;
1290
1291 /* mark end of integrity desciptor sequence again */
1292 error = udf_write_dscr_phys(terminator_dscr, loc, 1);
1293 if (error)
1294 return error;
1295 }
1296
1297 /* write out unallocated space bitmap on non sequential media */
1298 if ((format_flags & FORMAT_SEQUENTIAL) == 0) {
1299 /* writeout unallocated space bitmap */
1300 loc = layout.unalloc_space;
1301 dscr = (union dscrptr *) (context.part_unalloc_bits[data_part]);
1302 len = layout.alloc_bitmap_dscr_size;
1303 error = udf_write_dscr_virt(dscr, loc, data_part, len);
1304 if (error)
1305 return error;
1306 }
1307
1308 if (format_flags & FORMAT_META) {
1309 loc = layout.meta_file;
1310 dscr = (union dscrptr *) context.meta_file;
1311 error = udf_write_dscr_virt(dscr, loc, data_part, 1);
1312 if (error)
1313 return error;
1314
1315 loc = layout.meta_mirror;
1316 dscr = (union dscrptr *) context.meta_mirror;
1317 error = udf_write_dscr_virt(dscr, loc, data_part, 1);
1318 if (error)
1319 return error;
1320
1321 loc = layout.meta_bitmap;
1322 dscr = (union dscrptr *) context.meta_bitmap;
1323 error = udf_write_dscr_virt(dscr, loc, data_part, 1);
1324 if (error)
1325 return error;
1326
1327 /* writeout unallocated space bitmap */
1328 loc = layout.meta_bitmap_space;
1329 dscr = (union dscrptr *) (context.part_unalloc_bits[metadata_part]);
1330 len = layout.meta_bitmap_dscr_size;
1331 error = udf_write_dscr_virt(dscr, loc, data_part, len);
1332 if (error)
1333 return error;
1334 }
1335
1336 /* create a VAT and account for FSD+root */
1337 vat_dscr = NULL;
1338 if (format_flags & FORMAT_VAT) {
1339 /* update lvint to reflect the newest values (no writeout) */
1340 udf_update_lvintd(UDF_INTEGRITY_CLOSED);
1341
1342 error = udf_create_new_VAT(&vat_dscr);
1343 if (error)
1344 return error;
1345
1346 loc = layout.vat;
1347 error = udf_write_dscr_virt(vat_dscr, loc, metadata_part, 1);
1348 if (error)
1349 return error;
1350 }
1351
1352 /* write out sectors */
1353 if ((error = writeout_write_queue()))
1354 return error;
1355
1356 /* done */
1357 return 0;
1358 }
1359
1360 /* --------------------------------------------------------------------- */
1361
1362 /* version can be specified as 0xabc or a.bc */
1363 static int
1364 parse_udfversion(const char *pos, uint32_t *version) {
1365 int hex = 0;
1366 char c1, c2, c3, c4;
1367
1368 *version = 0;
1369 if (*pos == '0') {
1370 pos++;
1371 /* expect hex format */
1372 hex = 1;
1373 if (*pos++ != 'x')
1374 return 1;
1375 }
1376
1377 c1 = *pos++;
1378 if (c1 < '0' || c1 > '9')
1379 return 1;
1380 c1 -= '0';
1381
1382 c2 = *pos++;
1383 if (!hex) {
1384 if (c2 != '.')
1385 return 1;
1386 c2 = *pos++;
1387 }
1388 if (c2 < '0' || c2 > '9')
1389 return 1;
1390 c2 -= '0';
1391
1392 c3 = *pos++;
1393 if (c3 < '0' || c3 > '9')
1394 return 1;
1395 c3 -= '0';
1396
1397 c4 = *pos++;
1398 if (c4 != 0)
1399 return 1;
1400
1401 *version = c1 * 0x100 + c2 * 0x10 + c3;
1402 return 0;
1403 }
1404
1405
1406 static int
1407 a_udf_version(const char *s, const char *id_type)
1408 {
1409 uint32_t version;
1410
1411 if (parse_udfversion(s, &version))
1412 errx(1, "unknown %s id %s; specify as hex or float", id_type, s);
1413 return version;
1414 }
1415
1416 /* --------------------------------------------------------------------- */
1417
1418 static void
1419 usage(void)
1420 {
1421 (void)fprintf(stderr, "Usage: %s [-cFM] [-L loglabel] "
1422 "[-P discid] [-S setlabel] [-s size] [-p perc] "
1423 "[-t gmtoff] [-v min_udf] [-V max_udf] special\n", getprogname());
1424 exit(EXIT_FAILURE);
1425 }
1426
1427
1428 int
1429 main(int argc, char **argv)
1430 {
1431 struct tm *tm;
1432 struct stat st;
1433 time_t now;
1434 char scrap[255];
1435 int ch, req_enable, req_disable, force;
1436 int error;
1437
1438 setprogname(argv[0]);
1439
1440 /* initialise */
1441 format_str = strdup("");
1442 req_enable = req_disable = 0;
1443 format_flags = FORMAT_INVALID;
1444 force = 0;
1445 check_surface = 0;
1446
1447 srandom((unsigned long) time(NULL));
1448 udf_init_create_context();
1449 context.app_name = APP_NAME;
1450 context.impl_name = IMPL_NAME;
1451 context.app_version_main = APP_VERSION_MAIN;
1452 context.app_version_sub = APP_VERSION_SUB;
1453
1454 /* minimum and maximum UDF versions we advise */
1455 context.min_udf = 0x201;
1456 context.max_udf = 0x201;
1457
1458 /* use user's time zone as default */
1459 (void)time(&now);
1460 tm = localtime(&now);
1461 context.gmtoff = tm->tm_gmtoff;
1462
1463 /* process options */
1464 while ((ch = getopt(argc, argv, "cFL:Mp:P:s:S:t:v:V:")) != -1) {
1465 switch (ch) {
1466 case 'c' :
1467 check_surface = 1;
1468 break;
1469 case 'F' :
1470 force = 1;
1471 break;
1472 case 'L' :
1473 if (context.logvol_name) free(context.logvol_name);
1474 context.logvol_name = strdup(optarg);
1475 break;
1476 case 'M' :
1477 req_disable |= FORMAT_META;
1478 break;
1479 case 'p' :
1480 meta_perc = a_num(optarg, "meta_perc");
1481 /* limit to `sensible` values */
1482 meta_perc = MIN(meta_perc, 99);
1483 meta_perc = MAX(meta_perc, 1);
1484 meta_fract = (float) meta_perc/100.0;
1485 break;
1486 case 'v' :
1487 context.min_udf = a_udf_version(optarg, "min_udf");
1488 if (context.min_udf > context.max_udf)
1489 context.max_udf = context.min_udf;
1490 break;
1491 case 'V' :
1492 context.max_udf = a_udf_version(optarg, "max_udf");
1493 if (context.min_udf > context.max_udf)
1494 context.min_udf = context.max_udf;
1495 break;
1496 case 'P' :
1497 context.primary_name = strdup(optarg);
1498 break;
1499 case 's' :
1500 /* TODO size argument; recordable emulation */
1501 break;
1502 case 'S' :
1503 if (context.volset_name) free(context.volset_name);
1504 context.volset_name = strdup(optarg);
1505 break;
1506 case 't' :
1507 /* time zone overide */
1508 context.gmtoff = a_num(optarg, "gmtoff");
1509 break;
1510 default :
1511 usage();
1512 /* NOTREACHED */
1513 }
1514 }
1515
1516 if (optind + 1 != argc)
1517 usage();
1518
1519 /* get device and directory specifier */
1520 dev = argv[optind];
1521
1522 /* open device */
1523 if ((fd = open(dev, O_RDWR, 0)) == -1) {
1524 perror("can't open device");
1525 return EXIT_FAILURE;
1526 }
1527
1528 /* stat the device */
1529 if (fstat(fd, &st) != 0) {
1530 perror("can't stat the device");
1531 close(fd);
1532 return EXIT_FAILURE;
1533 }
1534
1535 /* Formatting can only be done on raw devices */
1536 if (!S_ISCHR(st.st_mode)) {
1537 printf("%s is not a raw device\n", dev);
1538 close(fd);
1539 return EXIT_FAILURE;
1540 }
1541
1542 /* just in case something went wrong, synchronise the drive's cache */
1543 udf_synchronise_caches();
1544
1545 /* get disc information */
1546 error = udf_update_discinfo(&mmc_discinfo);
1547 if (error) {
1548 perror("can't retrieve discinfo");
1549 close(fd);
1550 return EXIT_FAILURE;
1551 }
1552
1553 /* derive disc identifiers when not specified and check given */
1554 error = udf_proces_names();
1555 if (error) {
1556 /* error message has been printed */
1557 close(fd);
1558 return EXIT_FAILURE;
1559 }
1560
1561 /* derive newfs disc format from disc profile */
1562 error = udf_derive_format(req_enable, req_disable, force);
1563 if (error) {
1564 /* error message has been printed */
1565 close(fd);
1566 return EXIT_FAILURE;
1567 }
1568
1569 udf_dump_discinfo(&mmc_discinfo);
1570 printf("Formatting disc compatible with UDF version %x to %x\n\n",
1571 context.min_udf, context.max_udf);
1572 (void)snprintb(scrap, sizeof(scrap), FORMAT_FLAGBITS,
1573 (uint64_t) format_flags);
1574 printf("UDF properties %s\n", scrap);
1575 printf("Volume set `%s'\n", context.volset_name);
1576 printf("Primary volume `%s`\n", context.primary_name);
1577 printf("Logical volume `%s`\n", context.logvol_name);
1578 if (format_flags & FORMAT_META)
1579 printf("Metadata percentage %d %%\n", meta_perc);
1580 printf("\n");
1581
1582 /* prepare disc if nessisary (recordables mainly) */
1583 error = udf_prepare_disc();
1584 if (error) {
1585 perror("preparing disc failed");
1586 close(fd);
1587 return EXIT_FAILURE;
1588 };
1589
1590 /* set up administration */
1591 error = udf_do_newfs();
1592
1593 /* in any case, synchronise the drive's cache to prevent lockups */
1594 udf_synchronise_caches();
1595
1596 close(fd);
1597 if (error)
1598 return EXIT_FAILURE;
1599
1600 return EXIT_SUCCESS;
1601 }
1602
1603 /* --------------------------------------------------------------------- */
1604
1605