newfs_udf.c revision 1.15 1 /* $NetBSD: newfs_udf.c,v 1.15 2013/08/05 14:11:30 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 #include "udf_write.h"
69 #include "newfs_udf.h"
70
71 /* prototypes */
72 int newfs_udf(int argc, char **argv);
73 static void usage(void) __attribute__((__noreturn__));
74
75
76 /* queue for temporary storage of sectors to be written out */
77 struct wrsect {
78 uint32_t sectornr;
79 uint8_t *sector_data;
80 TAILQ_ENTRY(wrsect) next;
81 };
82
83 /* write queue and track blocking skew */
84 TAILQ_HEAD(wrsect_list, wrsect) write_queue;
85
86
87 /* global variables describing disc and format requests */
88 int fd; /* device: file descriptor */
89 char *dev; /* device: name */
90 struct mmc_discinfo mmc_discinfo; /* device: disc info */
91
92 char *format_str; /* format: string representation */
93 int format_flags; /* format: attribute flags */
94 int media_accesstype; /* derived from current mmc cap */
95 int check_surface; /* for rewritables */
96 int imagefile_secsize; /* for files */
97 int emul_packetsize; /* for discs and files */
98
99 int wrtrack_skew;
100 int meta_perc = UDF_META_PERC;
101 float meta_fract = (float) UDF_META_PERC / 100.0;
102
103
104 /* --------------------------------------------------------------------- */
105
106 /*
107 * write queue implementation
108 */
109
110 int
111 udf_write_sector(void *sector, uint32_t location)
112 {
113 struct wrsect *pos, *seekpos;
114
115
116 /* search location */
117 TAILQ_FOREACH_REVERSE(seekpos, &write_queue, wrsect_list, next) {
118 if (seekpos->sectornr <= location)
119 break;
120 }
121 if ((seekpos == NULL) || (seekpos->sectornr != location)) {
122 pos = calloc(1, sizeof(struct wrsect));
123 if (pos == NULL)
124 return ENOMEM;
125 /* allocate space for copy of sector data */
126 pos->sector_data = calloc(1, context.sector_size);
127 if (pos->sector_data == NULL)
128 return ENOMEM;
129 pos->sectornr = location;
130
131 if (seekpos) {
132 TAILQ_INSERT_AFTER(&write_queue, seekpos, pos, next);
133 } else {
134 TAILQ_INSERT_HEAD(&write_queue, pos, next);
135 }
136 } else {
137 pos = seekpos;
138 }
139 memcpy(pos->sector_data, sector, context.sector_size);
140
141 return 0;
142 }
143
144
145 /*
146 * Now all write requests are queued in the TAILQ, write them out to the
147 * disc/file image. Special care needs to be taken for devices that are only
148 * strict overwritable i.e. only in packet size chunks
149 *
150 * XXX support for growing vnd?
151 */
152
153 int
154 writeout_write_queue(void)
155 {
156 struct wrsect *pos;
157 uint64_t offset;
158 uint32_t line_len, line_offset;
159 uint32_t line_start, new_line_start, relpos;
160 uint32_t blockingnr;
161 uint8_t *linebuf, *adr;
162
163 blockingnr = layout.blockingnr;
164 line_len = blockingnr * context.sector_size;
165 line_offset = wrtrack_skew * context.sector_size;
166
167 linebuf = malloc(line_len);
168 if (linebuf == NULL)
169 return ENOMEM;
170
171 pos = TAILQ_FIRST(&write_queue);
172 bzero(linebuf, line_len);
173
174 /*
175 * Always writing out in whole lines now; this is slightly wastefull
176 * on logical overwrite volumes but it reduces complexity and the loss
177 * is near zero compared to disc size.
178 */
179 line_start = (pos->sectornr - wrtrack_skew) / blockingnr;
180 TAILQ_FOREACH(pos, &write_queue, next) {
181 new_line_start = (pos->sectornr - wrtrack_skew) / blockingnr;
182 if (new_line_start != line_start) {
183 /* write out */
184 offset = (uint64_t) line_start * line_len + line_offset;
185 #ifdef DEBUG
186 printf("WRITEOUT %08"PRIu64" + %02d -- "
187 "[%08"PRIu64"..%08"PRIu64"]\n",
188 offset / context.sector_size, blockingnr,
189 offset / context.sector_size,
190 offset / context.sector_size + blockingnr-1);
191 #endif
192 if (pwrite(fd, linebuf, line_len, offset) < 0) {
193 perror("Writing failed");
194 return errno;
195 }
196 line_start = new_line_start;
197 bzero(linebuf, line_len);
198 }
199
200 relpos = (pos->sectornr - wrtrack_skew) % blockingnr;
201 adr = linebuf + relpos * context.sector_size;
202 memcpy(adr, pos->sector_data, context.sector_size);
203 }
204 /* writeout last chunk */
205 offset = (uint64_t) line_start * line_len + line_offset;
206 #ifdef DEBUG
207 printf("WRITEOUT %08"PRIu64" + %02d -- [%08"PRIu64"..%08"PRIu64"]\n",
208 offset / context.sector_size, blockingnr,
209 offset / context.sector_size,
210 offset / context.sector_size + blockingnr-1);
211 #endif
212 if (pwrite(fd, linebuf, line_len, offset) < 0) {
213 perror("Writing failed");
214 return errno;
215 }
216
217 /* success */
218 return 0;
219 }
220
221 /* --------------------------------------------------------------------- */
222
223 /*
224 * mmc_discinfo and mmc_trackinfo readers modified from origional in udf main
225 * code in sys/fs/udf/
226 */
227
228 #ifdef DEBUG
229 static void
230 udf_dump_discinfo(struct mmc_discinfo *di)
231 {
232 char bits[128];
233
234 printf("Device/media info :\n");
235 printf("\tMMC profile 0x%02x\n", di->mmc_profile);
236 printf("\tderived class %d\n", di->mmc_class);
237 printf("\tsector size %d\n", di->sector_size);
238 printf("\tdisc state %d\n", di->disc_state);
239 printf("\tlast ses state %d\n", di->last_session_state);
240 printf("\tbg format state %d\n", di->bg_format_state);
241 printf("\tfrst track %d\n", di->first_track);
242 printf("\tfst on last ses %d\n", di->first_track_last_session);
243 printf("\tlst on last ses %d\n", di->last_track_last_session);
244 printf("\tlink block penalty %d\n", di->link_block_penalty);
245 snprintb(bits, sizeof(bits), MMC_DFLAGS_FLAGBITS, (uint64_t) di->disc_flags);
246 printf("\tdisc flags %s\n", bits);
247 printf("\tdisc id %x\n", di->disc_id);
248 printf("\tdisc barcode %"PRIx64"\n", di->disc_barcode);
249
250 printf("\tnum sessions %d\n", di->num_sessions);
251 printf("\tnum tracks %d\n", di->num_tracks);
252
253 snprintb(bits, sizeof(bits), MMC_CAP_FLAGBITS, di->mmc_cur);
254 printf("\tcapabilities cur %s\n", bits);
255 snprintb(bits, sizeof(bits), MMC_CAP_FLAGBITS, di->mmc_cap);
256 printf("\tcapabilities cap %s\n", bits);
257 printf("\n");
258 printf("\tlast_possible_lba %d\n", di->last_possible_lba);
259 printf("\n");
260 }
261 #else
262 #define udf_dump_discinfo(a);
263 #endif
264
265 /* --------------------------------------------------------------------- */
266
267 static int
268 udf_update_discinfo(struct mmc_discinfo *di)
269 {
270 struct stat st;
271 struct disklabel disklab;
272 struct partition *dp;
273 off_t size, sectors, secsize;
274 int partnr, error;
275
276 memset(di, 0, sizeof(struct mmc_discinfo));
277
278 /* check if we're on a MMC capable device, i.e. CD/DVD */
279 error = ioctl(fd, MMCGETDISCINFO, di);
280 if (error == 0)
281 return 0;
282
283 /* (re)fstat the file */
284 fstat(fd, &st);
285
286 if (S_ISREG(st.st_mode)) {
287 /* file support; we pick the minimum sector size allowed */
288 size = st.st_size;
289 secsize = imagefile_secsize;
290 sectors = size / secsize;
291 } else {
292 /*
293 * disc partition support; note we can't use DIOCGPART in
294 * userland so get disc label and use the stat info to get the
295 * partition number.
296 */
297 if (ioctl(fd, DIOCGDINFO, &disklab) == -1) {
298 /* failed to get disclabel! */
299 perror("disklabel");
300 return errno;
301 }
302
303 /* get disk partition it refers to */
304 fstat(fd, &st);
305 partnr = DISKPART(st.st_rdev);
306 dp = &disklab.d_partitions[partnr];
307
308 /* TODO problem with last_possible_lba on resizable VND */
309 if (dp->p_size == 0) {
310 perror("faulty disklabel partition returned, "
311 "check label\n");
312 return EIO;
313 }
314
315 sectors = dp->p_size;
316 secsize = disklab.d_secsize;
317 }
318
319 /* set up a disc info profile for partitions */
320 di->mmc_profile = 0x01; /* disc type */
321 di->mmc_class = MMC_CLASS_DISC;
322 di->disc_state = MMC_STATE_CLOSED;
323 di->last_session_state = MMC_STATE_CLOSED;
324 di->bg_format_state = MMC_BGFSTATE_COMPLETED;
325 di->link_block_penalty = 0;
326
327 di->mmc_cur = MMC_CAP_RECORDABLE | MMC_CAP_REWRITABLE |
328 MMC_CAP_ZEROLINKBLK | MMC_CAP_HW_DEFECTFREE;
329 di->mmc_cap = di->mmc_cur;
330 di->disc_flags = MMC_DFLAGS_UNRESTRICTED;
331
332 di->last_possible_lba = sectors - 1;
333 di->sector_size = secsize;
334
335 di->num_sessions = 1;
336 di->num_tracks = 1;
337
338 di->first_track = 1;
339 di->first_track_last_session = di->last_track_last_session = 1;
340
341 return 0;
342 }
343
344
345 int
346 udf_update_trackinfo(struct mmc_discinfo *di, struct mmc_trackinfo *ti)
347 {
348 int error, class;
349
350 class = di->mmc_class;
351 if (class != MMC_CLASS_DISC) {
352 /* tracknr specified in struct ti */
353 error = ioctl(fd, MMCGETTRACKINFO, ti);
354 return error;
355 }
356
357 /* discs partition support */
358 if (ti->tracknr != 1)
359 return EIO;
360
361 /* create fake ti (TODO check for resized vnds) */
362 ti->sessionnr = 1;
363
364 ti->track_mode = 0; /* XXX */
365 ti->data_mode = 0; /* XXX */
366 ti->flags = MMC_TRACKINFO_LRA_VALID | MMC_TRACKINFO_NWA_VALID;
367
368 ti->track_start = 0;
369 ti->packet_size = emul_packetsize;
370
371 /* TODO support for resizable vnd */
372 ti->track_size = di->last_possible_lba;
373 ti->next_writable = di->last_possible_lba;
374 ti->last_recorded = ti->next_writable;
375 ti->free_blocks = 0;
376
377 return 0;
378 }
379
380
381 static int
382 udf_setup_writeparams(struct mmc_discinfo *di)
383 {
384 struct mmc_writeparams mmc_writeparams;
385 int error;
386
387 if (di->mmc_class == MMC_CLASS_DISC)
388 return 0;
389
390 /*
391 * only CD burning normally needs setting up, but other disc types
392 * might need other settings to be made. The MMC framework will set up
393 * the nessisary recording parameters according to the disc
394 * characteristics read in. Modifications can be made in the discinfo
395 * structure passed to change the nature of the disc.
396 */
397 memset(&mmc_writeparams, 0, sizeof(struct mmc_writeparams));
398 mmc_writeparams.mmc_class = di->mmc_class;
399 mmc_writeparams.mmc_cur = di->mmc_cur;
400
401 /*
402 * UDF dictates first track to determine track mode for the whole
403 * disc. [UDF 1.50/6.10.1.1, UDF 1.50/6.10.2.1]
404 * To prevent problems with a `reserved' track in front we start with
405 * the 2nd track and if that is not valid, go for the 1st.
406 */
407 mmc_writeparams.tracknr = 2;
408 mmc_writeparams.data_mode = MMC_DATAMODE_DEFAULT; /* XA disc */
409 mmc_writeparams.track_mode = MMC_TRACKMODE_DEFAULT; /* data */
410
411 error = ioctl(fd, MMCSETUPWRITEPARAMS, &mmc_writeparams);
412 if (error) {
413 mmc_writeparams.tracknr = 1;
414 error = ioctl(fd, MMCSETUPWRITEPARAMS, &mmc_writeparams);
415 }
416 return error;
417 }
418
419
420 static void
421 udf_synchronise_caches(void)
422 {
423 struct mmc_op mmc_op;
424
425 bzero(&mmc_op, sizeof(struct mmc_op));
426 mmc_op.operation = MMC_OP_SYNCHRONISECACHE;
427
428 /* this device might not know this ioct, so just be ignorant */
429 (void) ioctl(fd, MMCOP, &mmc_op);
430 }
431
432 /* --------------------------------------------------------------------- */
433
434 static int
435 udf_prepare_disc(void)
436 {
437 struct mmc_trackinfo ti;
438 struct mmc_op op;
439 int tracknr, error;
440
441 /* If the last track is damaged, repair it */
442 ti.tracknr = mmc_discinfo.last_track_last_session;
443 error = udf_update_trackinfo(&mmc_discinfo, &ti);
444 if (error)
445 return error;
446
447 if (ti.flags & MMC_TRACKINFO_DAMAGED) {
448 /*
449 * Need to repair last track before anything can be done.
450 * this is an optional command, so ignore its error but report
451 * warning.
452 */
453 memset(&op, 0, sizeof(op));
454 op.operation = MMC_OP_REPAIRTRACK;
455 op.mmc_profile = mmc_discinfo.mmc_profile;
456 op.tracknr = ti.tracknr;
457 error = ioctl(fd, MMCOP, &op);
458
459 if (error)
460 (void)printf("Drive can't explicitly repair last "
461 "damaged track, but it might autorepair\n");
462 }
463 /* last track (if any) might not be damaged now, operations are ok now */
464
465 /* setup write parameters from discinfo */
466 error = udf_setup_writeparams(&mmc_discinfo);
467 if (error)
468 return error;
469
470 /* if the drive is not sequential, we're done */
471 if ((mmc_discinfo.mmc_cur & MMC_CAP_SEQUENTIAL) == 0)
472 return 0;
473
474 #ifdef notyet
475 /* if last track is not the reserved but an empty track, unreserve it */
476 if (ti.flags & MMC_TRACKINFO_BLANK) {
477 if (ti.flags & MMC_TRACKINFO_RESERVED == 0) {
478 memset(&op, 0, sizeof(op));
479 op.operation = MMC_OP_UNRESERVETRACK;
480 op.mmc_profile = mmc_discinfo.mmc_profile;
481 op.tracknr = ti.tracknr;
482 error = ioctl(fd, MMCOP, &op);
483 if (error)
484 return error;
485
486 /* update discinfo since it changed by the operation */
487 error = udf_update_discinfo(&mmc_discinfo);
488 if (error)
489 return error;
490 }
491 }
492 #endif
493
494 /* close the last session if its still open */
495 if (mmc_discinfo.last_session_state == MMC_STATE_INCOMPLETE) {
496 printf("Closing last open session if present\n");
497 /* close all associated tracks */
498 tracknr = mmc_discinfo.first_track_last_session;
499 while (tracknr <= mmc_discinfo.last_track_last_session) {
500 ti.tracknr = tracknr;
501 error = udf_update_trackinfo(&mmc_discinfo, &ti);
502 if (error)
503 return error;
504 printf("\tClosing open track %d\n", tracknr);
505 memset(&op, 0, sizeof(op));
506 op.operation = MMC_OP_CLOSETRACK;
507 op.mmc_profile = mmc_discinfo.mmc_profile;
508 op.tracknr = tracknr;
509 error = ioctl(fd, MMCOP, &op);
510 if (error)
511 return error;
512 tracknr ++;
513 }
514 printf("Closing session\n");
515 memset(&op, 0, sizeof(op));
516 op.operation = MMC_OP_CLOSESESSION;
517 op.mmc_profile = mmc_discinfo.mmc_profile;
518 op.sessionnr = mmc_discinfo.num_sessions;
519 error = ioctl(fd, MMCOP, &op);
520 if (error)
521 return error;
522
523 /* update discinfo since it changed by the operations */
524 error = udf_update_discinfo(&mmc_discinfo);
525 if (error)
526 return error;
527 }
528
529 if (format_flags & FORMAT_TRACK512) {
530 /* get last track again */
531 ti.tracknr = mmc_discinfo.last_track_last_session;
532 error = udf_update_trackinfo(&mmc_discinfo, &ti);
533 if (error)
534 return error;
535
536 /* Split up the space at 512 for iso cd9660 hooking */
537 memset(&op, 0, sizeof(op));
538 op.operation = MMC_OP_RESERVETRACK_NWA; /* UPTO nwa */
539 op.mmc_profile = mmc_discinfo.mmc_profile;
540 op.extent = 512; /* size */
541 error = ioctl(fd, MMCOP, &op);
542 if (error)
543 return error;
544 }
545
546 return 0;
547 }
548
549 /* --------------------------------------------------------------------- */
550
551 int
552 udf_surface_check(void)
553 {
554 uint32_t loc, block_bytes;
555 uint32_t sector_size, blockingnr, bpos;
556 uint8_t *buffer;
557 int error, num_errors;
558
559 sector_size = context.sector_size;
560 blockingnr = layout.blockingnr;
561
562 block_bytes = layout.blockingnr * sector_size;
563 if ((buffer = malloc(block_bytes)) == NULL)
564 return ENOMEM;
565
566 /* set all one to not kill Flash memory? */
567 for (bpos = 0; bpos < block_bytes; bpos++)
568 buffer[bpos] = 0x00;
569
570 printf("\nChecking disc surface : phase 1 - writing\n");
571 num_errors = 0;
572 loc = layout.first_lba;
573 while (loc <= layout.last_lba) {
574 /* write blockingnr sectors */
575 error = pwrite(fd, buffer, block_bytes, loc*sector_size);
576 printf(" %08d + %d (%02d %%)\r", loc, blockingnr,
577 (int)((100.0 * loc)/layout.last_lba));
578 fflush(stdout);
579 if (error == -1) {
580 /* block is bad */
581 printf("BAD block at %08d + %d \n",
582 loc, layout.blockingnr);
583 if ((error = udf_register_bad_block(loc))) {
584 free(buffer);
585 return error;
586 }
587 num_errors ++;
588 }
589 loc += layout.blockingnr;
590 }
591
592 printf("\nChecking disc surface : phase 2 - reading\n");
593 num_errors = 0;
594 loc = layout.first_lba;
595 while (loc <= layout.last_lba) {
596 /* read blockingnr sectors */
597 error = pread(fd, buffer, block_bytes, loc*sector_size);
598 printf(" %08d + %d (%02d %%)\r", loc, blockingnr,
599 (int)((100.0 * loc)/layout.last_lba));
600 fflush(stdout);
601 if (error == -1) {
602 /* block is bad */
603 printf("BAD block at %08d + %d \n",
604 loc, layout.blockingnr);
605 if ((error = udf_register_bad_block(loc))) {
606 free(buffer);
607 return error;
608 }
609 num_errors ++;
610 }
611 loc += layout.blockingnr;
612 }
613 printf("Scan complete : %d bad blocks found\n", num_errors);
614 free(buffer);
615
616 return 0;
617 }
618
619
620 /* --------------------------------------------------------------------- */
621
622 static int
623 udf_do_newfs(void)
624 {
625 int error;
626
627 error = udf_do_newfs_prefix();
628 if (error)
629 return error;
630 error = udf_do_rootdir();
631 if (error)
632 return error;
633 error = udf_do_newfs_postfix();
634
635 return error;
636 }
637
638 /* --------------------------------------------------------------------- */
639
640
641 /* version can be specified as 0xabc or a.bc */
642 static int
643 parse_udfversion(const char *pos, uint32_t *version) {
644 int hex = 0;
645 char c1, c2, c3, c4;
646
647 *version = 0;
648 if (*pos == '0') {
649 pos++;
650 /* expect hex format */
651 hex = 1;
652 if (*pos++ != 'x')
653 return 1;
654 }
655
656 c1 = *pos++;
657 if (c1 < '0' || c1 > '9')
658 return 1;
659 c1 -= '0';
660
661 c2 = *pos++;
662 if (!hex) {
663 if (c2 != '.')
664 return 1;
665 c2 = *pos++;
666 }
667 if (c2 < '0' || c2 > '9')
668 return 1;
669 c2 -= '0';
670
671 c3 = *pos++;
672 if (c3 < '0' || c3 > '9')
673 return 1;
674 c3 -= '0';
675
676 c4 = *pos++;
677 if (c4 != 0)
678 return 1;
679
680 *version = c1 * 0x100 + c2 * 0x10 + c3;
681 return 0;
682 }
683
684
685 static int
686 a_udf_version(const char *s, const char *id_type)
687 {
688 uint32_t version;
689
690 if (parse_udfversion(s, &version))
691 errx(1, "unknown %s id %s; specify as hex or float", id_type, s);
692 return version;
693 }
694
695 /* --------------------------------------------------------------------- */
696
697 static void
698 usage(void)
699 {
700 (void)fprintf(stderr, "Usage: %s [-cFM] [-L loglabel] "
701 "[-P discid] [-S sectorsize] [-s size] [-p perc] "
702 "[-t gmtoff] [-v min_udf] [-V max_udf] special\n", getprogname());
703 exit(EXIT_FAILURE);
704 }
705
706
707 int
708 main(int argc, char **argv)
709 {
710 struct tm *tm;
711 struct stat st;
712 time_t now;
713 off_t setsize;
714 char scrap[255], *colon;
715 int ch, req_enable, req_disable, force;
716 int error;
717
718 setprogname(argv[0]);
719
720 /* initialise */
721 format_str = strdup("");
722 req_enable = req_disable = 0;
723 format_flags = FORMAT_INVALID;
724 force = 0;
725 check_surface = 0;
726 setsize = 0;
727 imagefile_secsize = 512; /* minimum allowed sector size */
728 emul_packetsize = 32; /* reasonable default */
729
730 srandom((unsigned long) time(NULL));
731 udf_init_create_context();
732 context.app_name = APP_NAME;
733 context.impl_name = IMPL_NAME;
734 context.app_version_main = APP_VERSION_MAIN;
735 context.app_version_sub = APP_VERSION_SUB;
736
737 /* minimum and maximum UDF versions we advise */
738 context.min_udf = 0x201;
739 context.max_udf = 0x201;
740
741 /* use user's time zone as default */
742 (void)time(&now);
743 tm = localtime(&now);
744 context.gmtoff = tm->tm_gmtoff;
745
746 /* process options */
747 while ((ch = getopt(argc, argv, "cFL:Mp:P:s:S:B:t:v:V:")) != -1) {
748 switch (ch) {
749 case 'c' :
750 check_surface = 1;
751 break;
752 case 'F' :
753 force = 1;
754 break;
755 case 'L' :
756 if (context.logvol_name) free(context.logvol_name);
757 context.logvol_name = strdup(optarg);
758 break;
759 case 'M' :
760 req_disable |= FORMAT_META;
761 break;
762 case 'p' :
763 meta_perc = a_num(optarg, "meta_perc");
764 /* limit to `sensible` values */
765 meta_perc = MIN(meta_perc, 99);
766 meta_perc = MAX(meta_perc, 1);
767 meta_fract = (float) meta_perc/100.0;
768 break;
769 case 'v' :
770 context.min_udf = a_udf_version(optarg, "min_udf");
771 if (context.min_udf > context.max_udf)
772 context.max_udf = context.min_udf;
773 break;
774 case 'V' :
775 context.max_udf = a_udf_version(optarg, "max_udf");
776 if (context.min_udf > context.max_udf)
777 context.min_udf = context.max_udf;
778 break;
779 case 'P' :
780 /* check if there is a ':' in the name */
781 if ((colon = strstr(optarg, ":"))) {
782 if (context.volset_name)
783 free(context.volset_name);
784 *colon = 0;
785 context.volset_name = strdup(optarg);
786 optarg = colon+1;
787 }
788 if (context.primary_name)
789 free(context.primary_name);
790 if ((strstr(optarg, ":"))) {
791 perror("primary name can't have ':' in its name");
792 return EXIT_FAILURE;
793 }
794 context.primary_name = strdup(optarg);
795 break;
796 case 's' :
797 /* support for files, set file size */
798 /* XXX support for formatting recordables on vnd/file? */
799 if (dehumanize_number(optarg, &setsize) < 0) {
800 perror("can't parse size argument");
801 return EXIT_FAILURE;
802 }
803 setsize = MAX(0, setsize);
804 break;
805 case 'S' :
806 imagefile_secsize = a_num(optarg, "secsize");
807 imagefile_secsize = MAX(512, imagefile_secsize);
808 break;
809 case 'B' :
810 emul_packetsize = a_num(optarg,
811 "blockingnr, packetsize");
812 emul_packetsize = MAX(emul_packetsize, 1);
813 emul_packetsize = MIN(emul_packetsize, 32);
814 break;
815 case 't' :
816 /* time zone overide */
817 context.gmtoff = a_num(optarg, "gmtoff");
818 break;
819 default :
820 usage();
821 /* NOTREACHED */
822 }
823 }
824
825 if (optind + 1 != argc)
826 usage();
827
828 /* get device and directory specifier */
829 dev = argv[optind];
830
831 /* open device */
832 if ((fd = open(dev, O_RDWR, 0)) == -1) {
833 /* check if we need to create a file */
834 fd = open(dev, O_RDONLY, 0);
835 if (fd > 0) {
836 perror("device is there but can't be opened for read/write");
837 return EXIT_FAILURE;
838 }
839 if (!force) {
840 perror("can't open device");
841 return EXIT_FAILURE;
842 }
843 if (setsize == 0) {
844 perror("need to create image file but no size specified");
845 return EXIT_FAILURE;
846 }
847 /* need to create a file */
848 fd = open(dev, O_RDWR | O_CREAT | O_TRUNC, 0777);
849 if (fd == -1) {
850 perror("can't create image file");
851 return EXIT_FAILURE;
852 }
853 }
854
855 /* stat the device */
856 if (fstat(fd, &st) != 0) {
857 perror("can't stat the device");
858 close(fd);
859 return EXIT_FAILURE;
860 }
861
862 if (S_ISREG(st.st_mode)) {
863 if (setsize == 0)
864 setsize = st.st_size;
865 /* sanitise arguments */
866 imagefile_secsize &= ~511;
867 setsize &= ~(imagefile_secsize-1);
868
869 if (ftruncate(fd, setsize)) {
870 perror("can't resize file");
871 return EXIT_FAILURE;
872 }
873 }
874
875 /* formatting can only be done on raw devices */
876 if (!S_ISREG(st.st_mode) && !S_ISCHR(st.st_mode)) {
877 printf("%s is not a raw device\n", dev);
878 close(fd);
879 return EXIT_FAILURE;
880 }
881
882 /* just in case something went wrong, synchronise the drive's cache */
883 udf_synchronise_caches();
884
885 /* get 'disc' information */
886 error = udf_update_discinfo(&mmc_discinfo);
887 if (error) {
888 perror("can't retrieve discinfo");
889 close(fd);
890 return EXIT_FAILURE;
891 }
892
893 /* derive disc identifiers when not specified and check given */
894 error = udf_proces_names();
895 if (error) {
896 /* error message has been printed */
897 close(fd);
898 return EXIT_FAILURE;
899 }
900
901 /* derive newfs disc format from disc profile */
902 error = udf_derive_format(req_enable, req_disable, force);
903 if (error) {
904 /* error message has been printed */
905 close(fd);
906 return EXIT_FAILURE;
907 }
908
909 udf_dump_discinfo(&mmc_discinfo);
910 printf("Formatting disc compatible with UDF version %x to %x\n\n",
911 context.min_udf, context.max_udf);
912 (void)snprintb(scrap, sizeof(scrap), FORMAT_FLAGBITS,
913 (uint64_t) format_flags);
914 printf("UDF properties %s\n", scrap);
915 printf("Volume set `%s'\n", context.volset_name);
916 printf("Primary volume `%s`\n", context.primary_name);
917 printf("Logical volume `%s`\n", context.logvol_name);
918 if (format_flags & FORMAT_META)
919 printf("Metadata percentage %d %%\n", meta_perc);
920 printf("\n");
921
922 /* prepare disc if nessisary (recordables mainly) */
923 error = udf_prepare_disc();
924 if (error) {
925 perror("preparing disc failed");
926 close(fd);
927 return EXIT_FAILURE;
928 };
929
930 /* setup sector writeout queue's */
931 TAILQ_INIT(&write_queue);
932
933 /* perform the newfs itself */
934 error = udf_do_newfs();
935 if (!error) {
936 /* write out sectors */
937 error = writeout_write_queue();
938 }
939
940 /* in any case, synchronise the drive's cache to prevent lockups */
941 udf_synchronise_caches();
942
943 close(fd);
944 if (error)
945 return EXIT_FAILURE;
946
947 return EXIT_SUCCESS;
948 }
949
950 /* --------------------------------------------------------------------- */
951
952