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