Imported Upstream version 2.5.1
[debian/amanda] / tape-src / tapetype.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 1991-1998 University of Maryland at College Park
4  * All Rights Reserved.
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and its
7  * documentation for any purpose is hereby granted without fee, provided that
8  * the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of U.M. not be used in advertising or
11  * publicity pertaining to distribution of the software without specific,
12  * written prior permission.  U.M. makes no representations about the
13  * suitability of this software for any purpose.  It is provided "as is"
14  * without express or implied warranty.
15  *
16  * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
18  * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
20  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  *
23  * Author: James da Silva, Systems Design and Analysis Group
24  *                         Computer Science Department
25  *                         University of Maryland at College Park
26  */
27 /*
28  * $Id: tapetype.c,v 1.27 2006/08/24 01:57:16 paddy_s Exp $
29  *
30  * tests a tape in a given tape unit and prints a tapetype entry for
31  * it.  */
32 #include "amanda.h"
33
34 #include "tapeio.h"
35
36 #define NBLOCKS 32                      /* number of random blocks */
37
38 extern int optind;
39
40 static char *sProgName;
41 static char *tapedev;
42 static int fd;
43
44 static size_t blockkb = 32;
45 static size_t blocksize;
46
47 static char *randombytes = (char *) NULL;
48
49 #if USE_RAND
50 /* If the C library does not define random(), try to use rand() by
51    defining USE_RAND, but then make sure you are not using hardware
52    compression, because the low-order bits of rand() may not be that
53    random... :-( */
54 #define random() rand()
55 #define srandom(seed) srand(seed)
56 #endif
57
58 static char *getrandombytes(void);
59 static int writeblock(int fd);
60 static off_t writeblocks(int fd, off_t nblks);
61 static void allocrandombytes(void);
62 static void do_pass0(off_t size, time_t *seconds, int dorewind);
63 static void do_pass(off_t size, off_t *blocks, off_t *files, time_t *seconds);
64 static void help(void);
65 static void initnotrandombytes(void);
66 static void initrandombytes(void);
67 static void show_progress(off_t *blocks, off_t *files);
68 static void usage(void);
69
70 int main(int argc, char **argv);
71
72 static void
73 allocrandombytes(void)
74 {
75   size_t i;
76   size_t j;
77   size_t page_size;
78   char   *p;
79
80   if (randombytes == (char *)NULL) {
81 #if defined(HAVE_GETPAGESIZE)
82     page_size = (size_t)getpagesize();
83 #else
84     page_size = (size_t)1024;
85 #endif
86     j = (NBLOCKS * blocksize) + page_size;      /* buffer space plus one page */
87     j = am_round(j, page_size);                 /* even number of pages */
88     p = (char *)alloc(j);
89     i = (size_t)(p - (char *)0) & (page_size - 1);/* page boundary offset */
90     if(i != 0) {
91       randombytes = p + (page_size - i);        /* round up to page boundary */
92     } else {
93       randombytes = p;                          /* alloc already on boundary */
94     }
95   }
96 }
97
98 static void
99 initnotrandombytes(void)
100 {
101   unsigned long i;
102   unsigned long j;
103   char *p;
104
105   allocrandombytes();
106   j = NBLOCKS * blocksize;
107   p = randombytes;
108   for(i=0; i < j; ++i) {
109     *p++ = (char) (i % 256);
110   }
111 }
112
113 static void
114 initrandombytes(void)
115 {
116   unsigned long i, j;
117   char *p;
118
119   allocrandombytes();
120   j = NBLOCKS * blocksize;
121   p = randombytes;
122   for(i=0; i < j; ++i) {
123     *p++ = (char)random();
124   }
125 }
126
127 static char *
128 getrandombytes(void)
129 {
130   static unsigned long counter = 0;
131
132   return randombytes + ((counter++ % NBLOCKS) * blocksize);
133 }
134
135 static int short_write;
136
137 static int
138 writeblock(
139     int         fd)
140 {
141   ssize_t w;
142
143   if ((w = tapefd_write(fd, getrandombytes(), blocksize)) == (ssize_t)blocksize) {
144     return 1;
145   }
146   if (w >= 0) {
147     short_write = 1;
148   } else {
149     short_write = 0;
150   }
151   return 0;
152 }
153
154
155 /* returns number of blocks actually written */
156 static off_t
157 writeblocks(
158     int         fd,
159     off_t       nblks)
160 {
161   off_t blks = (off_t)0;
162
163   while (blks < nblks) {
164     if (! writeblock(fd)) {
165       return (off_t)0;
166     }
167     blks += (off_t)1;
168   }
169
170   return blks;
171 }
172
173
174 static void
175 usage(void)
176 {
177   fputs("usage: ", stderr);
178   fputs(sProgName, stderr);
179   fputs(" [-h]", stderr);
180   fputs(" [-c]", stderr);
181   fputs(" [-o]", stderr);
182   fputs(" [-b blocksize]", stderr);
183   fputs(" -e estsize", stderr);
184   fputs(" [-f tapedev]", stderr);
185   fputs(" [-t typename]", stderr);
186   fputc('\n', stderr);
187 }
188
189 static void
190 help(void)
191 {
192   usage();
193   fputs("-h                     display this message\n"
194         "-c                     run hardware compression detection test only\n"
195         "-o                     overwrite amanda tape\n"
196         "-b blocksize           record block size (default: 32k)\n"
197         "-e estsize             estimated tape size (No default!)\n"
198         "-f tapedev             tape device name (default: $TAPE)\n"
199         "-t typename            tapetype name (default: unknown-tapetype)\n"
200         "\n"
201         "Note: disable hardware compression when running this program.\n",
202         stderr);
203 }
204
205
206 int do_tty;
207
208 static void
209 show_progress(
210     off_t *     blocks,
211     off_t *     files)
212 {
213   fprintf(stderr, "wrote " OFF_T_FMT " " SIZE_T_FMT "Kb block%s in " OFF_T_FMT " file%s",
214           (OFF_T_FMT_TYPE)*blocks,
215           (SIZE_T_FMT_TYPE)blockkb, (*blocks == (off_t)1) ? "" : "s",
216           (OFF_T_FMT_TYPE)*files, (*files == (off_t)1) ? "" : "s");
217 }
218
219
220 static void
221 do_pass(
222     off_t       size,
223     off_t *     blocks,
224     off_t *     files,
225     time_t *    seconds)
226 {
227   off_t blks;
228   time_t start, end;
229   int save_errno;
230
231   if (tapefd_rewind(fd) == -1) {
232     fprintf(stderr, "%s: could not rewind %s: %s\n",
233             sProgName, tapedev, strerror(errno));
234     exit(1);
235   }
236
237   time(&start);
238
239   while(1) {
240
241     if ((blks = writeblocks(fd, size)) <= (off_t)0 || tapefd_weof(fd, (off_t)1) != 0)
242       break;
243     *blocks += blks;
244     *files += (off_t)1;
245     if(do_tty) {
246       putc('\r', stderr);
247       show_progress(blocks, files);
248     }
249   }
250   save_errno = errno;
251
252   time(&end);
253
254   if (*blocks == (off_t)0) {
255     fprintf(stderr, "%s: could not write any data in this pass: %s\n",
256             sProgName, short_write ? "short write" : strerror(save_errno));
257     exit(1);
258   }
259
260   if(end <= start) {
261     /*
262      * Just in case time warped backward or the device is really, really
263      * fast (e.g. /dev/null testing).
264      */
265     *seconds = 1;
266   } else {
267     *seconds = end - start;
268   }
269   if(do_tty) {
270     putc('\r', stderr);
271   }
272   show_progress(blocks, files);
273   fprintf(stderr, " in " TIME_T_FMT " second%s (%s)\n",
274           (TIME_T_FMT_TYPE)*seconds, (*seconds == 1) ? "" : "s",
275           short_write ? "short write" : strerror(save_errno));
276 }
277
278
279 static void
280 do_pass0(
281     off_t       size,
282     time_t *    seconds,
283     int         dorewind)
284 {
285   off_t blks;
286   time_t start, end;
287   int save_errno;
288
289   if (dorewind  &&  tapefd_rewind(fd) == -1) {
290     fprintf(stderr, "%s: could not rewind %s: %s\n",
291             sProgName, tapedev, strerror(errno));
292     exit(1);
293   }
294
295   time(&start);
296
297   blks = writeblocks(fd, size);
298   tapefd_weof(fd, (off_t)1);
299
300   save_errno = errno;
301
302   time(&end);
303
304   if (blks <= (off_t)0) {
305     fprintf(stderr, "%s: could not write any data in this pass: %s\n",
306             sProgName, short_write ? "short write" : strerror(save_errno));
307     exit(1);
308   }
309
310   if(end <= start) {
311     /*
312      * Just in case time warped backward or the device is really, really
313      * fast (e.g. /dev/null testing).
314      */
315     *seconds = 1;
316   } else {
317     *seconds = end - start;
318   }
319 }
320
321
322 int
323 main(
324     int         argc,
325     char **     argv)
326 {
327   off_t pass1blocks = (off_t)0;
328   off_t pass2blocks = (off_t)0;
329   time_t pass1time;
330   time_t pass2time;
331   time_t timediff;
332   off_t pass1files = (off_t)0;
333   off_t pass2files = (off_t)0;
334   off_t estsize;
335   off_t pass0size;
336   off_t pass1size;
337   off_t pass2size;
338   off_t blockdiff;
339   off_t filediff;
340   size_t filemark;
341   unsigned long speed;
342   off_t size;
343   char *sizeunits;
344   int ch;
345   char *suffix = NULL;
346   char *typename;
347   time_t now;
348   int hwcompr = 0;
349   int comprtstonly = 0;
350   int overwrite_label = 0;
351   int is_labeled = 0;
352   char *result;
353   char *datestamp = NULL;
354   char *label = NULL;
355
356
357   if ((sProgName = strrchr(*argv, '/')) == NULL) {
358     sProgName = *argv;
359   } else {
360     sProgName++;
361   }
362
363   /* Don't die when child closes pipe */
364   signal(SIGPIPE, SIG_IGN);
365
366   estsize = (off_t)0;
367   tapedev = getenv("TAPE");
368   typename = "unknown-tapetype";
369
370   while ((ch = getopt(argc, argv, "b:e:f:t:hco")) != EOF) {
371     switch (ch) {
372     case 'b':
373       blockkb = (size_t)strtol(optarg, &suffix, 0);
374       if (!(*suffix == '\0' || *suffix == 'k' || *suffix == 'K')) {
375         if (*suffix == 'm' || *suffix == 'M') {
376           blockkb *= 1024;
377         } else if (*suffix == 'g' || *suffix == 'G') {
378           blockkb *= (1024 * 1024);
379         } else {
380           fprintf(stderr, "%s: unknown size suffix \'%c\'\n",
381                   sProgName, *suffix);
382           return 1;
383         }
384       }
385       break;
386     case 'e':
387       estsize = OFF_T_STRTOL(optarg, &suffix, 0);
388       if (!(*suffix == '\0' || *suffix == 'k' || *suffix == 'K')) {
389         if (*suffix == 'm' || *suffix == 'M') {
390           estsize *= (off_t)1024;
391         } else if (*suffix == 'g' || *suffix == 'G') {
392           estsize *= (off_t)(1024 * 1024);
393         } else {
394           fprintf(stderr, "%s: unknown size suffix \'%c\'\n",
395                   sProgName, *suffix);
396           return 1;
397         }
398       }
399       break;
400
401     case 'f':
402       tapedev = stralloc(optarg);
403       break;
404
405     case 't':
406       typename = stralloc(optarg);
407       break;
408
409     case 'c':
410       comprtstonly = 1;
411       break;
412
413     case 'h':
414       help();
415       return 1;
416
417     case 'o':
418       overwrite_label=1;
419       break;
420
421     default:
422       fprintf(stderr, "%s: unknown option \'%c\'\n", sProgName, ch);
423       /*FALLTHROUGH*/
424
425     case '?':
426       usage();
427       return 1;
428     }
429   }
430   blocksize = blockkb * 1024;
431
432   if (tapedev == NULL) {
433     fprintf(stderr, "%s: No tapedev specified\n", sProgName);
434     usage();
435     return 1;
436   }
437   if (optind < argc) {
438     usage();
439     return 1;
440   }
441
442   if (estsize == 0) {
443     if (comprtstonly) {
444       estsize = (off_t)(1024 * 1024);           /* assume 1 GByte for now */
445     } else {
446       fprintf(stderr, "%s: please specify estimated tape capacity (e.g. '-e 4g')\n", sProgName);
447       usage();
448       return 1;
449     }
450   }
451
452
453 /* verifier tape */
454
455
456   fd = tape_open(tapedev, O_RDONLY, 0);
457   if (fd == -1) {
458     fprintf(stderr, "%s: could not open %s: %s\n",
459             sProgName, tapedev, strerror(errno));
460     return 1;
461   }
462
463   if((result = tapefd_rdlabel(fd, &datestamp, &label)) == NULL) {
464     is_labeled = 1;
465   }
466   else if (strcmp(result,"not an amanda tape") == 0) {
467     is_labeled = 2;
468   }
469
470   if(tapefd_rewind(fd) == -1) {
471     fprintf(stderr, "%s: could not rewind %s: %s\n",
472             sProgName, tapedev, strerror(errno));
473     tapefd_close(fd);
474     return 1;
475   }
476
477   tapefd_close(fd);
478
479   if(is_labeled == 1 && overwrite_label == 0) {
480     fprintf(stderr, "%s: The tape is an amanda tape, use -o to overwrite the tape\n",
481             sProgName);
482     return 1;
483   }
484   else if(is_labeled == 2 && overwrite_label == 0) {
485     fprintf(stderr, "%s: The tape is already used, use -o to overwrite the tape\n",
486             sProgName);
487     return 1;
488   }
489
490   fd = tape_open(tapedev, O_RDWR, 0);
491   if (fd == -1) {
492     fprintf(stderr, "%s: could not open %s: %s\n",
493             sProgName, tapedev, strerror(errno));
494     return 1;
495   }
496
497   do_tty = isatty(fileno(stderr));
498
499   /*
500    * Estimate pass: write twice a small file, once with compressable
501    * data and once with uncompressable data.
502    * The theory is that if the drive is in hardware compression mode
503    * we notice a significant difference in writing speed between the two
504    * (at least if we can provide data as fast the tape streams).
505    */
506
507   initnotrandombytes();
508
509   fprintf(stderr, "Estimate phase 1...");
510   pass0size = (off_t)(8 * 1024 / blockkb);
511   pass1time = 0;
512   pass2time = 0;
513   /*
514    * To get accurate results, we should write enough data
515    * so that rewind/start/stop time is small compared to
516    * the total time; let's take 10%.
517    * The timer has a 1 sec granularity, so the test
518    * should take at least 10 seconds to measure a
519    * difference with 10% accuracy; let's take 25 seconds.
520    */ 
521   while (pass1time < 25 || ((100*(pass2time-pass1time)/pass2time) >= 10) ) {
522     if (pass1time != 0) {
523       time_t t = pass1time;
524       do {
525           pass0size *= (off_t)2;
526           t *= 2;
527       } while (t < 25);
528     }
529     /*
530      * first a dummy pass to rewind, stop, start and
531      * get drive streaming, then do the real timing
532      */
533     do_pass0(pass0size, &pass2time, 1);
534     do_pass0(pass0size, &pass1time, 0);
535     if (pass0size >= (off_t)(10 * 1024 * 1024)) {
536       fprintf(stderr,
537         "\rTape device is too fast to detect hardware compression...\n");
538       break;    /* avoid loops if tape is superfast or broken */
539     }
540   }
541   fprintf(stderr,
542         "\rWriting " OFF_T_FMT " Mbyte   compresseable data:  "
543         TIME_T_FMT " sec\n",
544         (OFF_T_FMT_TYPE)((off_t)blockkb * pass0size / (off_t)1024),
545         (TIME_T_FMT_TYPE)pass1time);
546
547   /*
548    * now generate uncompressable data and try again
549    */
550   time(&now);
551   srandom((unsigned)now);
552   initrandombytes();
553
554   fprintf(stderr, "Estimate phase 2...");
555   do_pass0(pass0size, &pass2time, 1);   /* rewind and get drive streaming */
556   do_pass0(pass0size, &pass2time, 0);
557   fprintf(stderr, "\rWriting " OFF_T_FMT
558         " Mbyte uncompresseable data:  " TIME_T_FMT " sec\n",
559         (OFF_T_FMT_TYPE)((off_t)blockkb * pass0size / (off_t)1024),
560         (TIME_T_FMT_TYPE)pass2time);
561
562   /*
563    * Compute the time difference between writing the compressable and
564    * uncompressable data.  If it differs more than 20%, then warn
565    * user that the tape drive has probably hardware compression enabled.
566    */
567   if (pass1time > pass2time) {
568     /*
569      * Strange!  I would expect writing compresseable data to be
570      * much faster (or about equal, if hardware compression is disabled)
571      */
572     timediff = 0;
573   } else {
574     timediff = pass2time - pass1time;
575   }
576   if (((100 * timediff) / pass2time) >= 20) {   /* 20% faster? */
577     fprintf(stderr, "WARNING: Tape drive has hardware compression enabled\n");
578     hwcompr = 1;
579   }
580
581   /*
582    * Inform about estimated time needed to run the remaining of this program
583    */
584   fprintf(stderr, "Estimated time to write 2 * %lu Mbyte: ", (unsigned long) (estsize / (off_t)1024));
585   pass1time = (time_t)(2.0 * (double)pass2time * (double)estsize /
586                 (1.0 * (double)pass0size * (double)blockkb));
587         /* avoid overflow and underflow by doing math in floating point */
588   fprintf(stderr, TIME_T_FMT " sec = ",
589           (TIME_T_FMT_TYPE)pass1time);
590   fprintf(stderr, TIME_T_FMT " h " TIME_T_FMT " min\n",
591           (TIME_T_FMT_TYPE)(pass1time/(time_t)3600),
592           (TIME_T_FMT_TYPE)((pass1time%(time_t)3600) / (time_t)60));
593
594   if (comprtstonly) {
595         exit(hwcompr);
596   }
597
598
599   /*
600    * Do pass 1 -- write files that are 1% of the estimated size until error.
601    */
602   pass1size = (off_t)(((double)estsize * 0.01) / (double)blockkb); /* 1% of estimate */
603   if(pass1size <= (off_t)0) {
604     pass1size = (off_t)2;                               /* strange end case */
605   }
606   do_pass(pass1size, &pass1blocks, &pass1files, &pass1time);
607
608   /*
609    * Do pass 2 -- write smaller files until error.
610    */
611   pass2size = pass1size / (off_t)2;
612   do_pass(pass2size, &pass2blocks, &pass2files, &pass2time);
613
614   /*
615    * Compute the size of a filemark as the difference in data written
616    * between pass 1 and pass 2 divided by the difference in number of
617    * file marks written between pass 1 and pass 2.  Note that we have
618    * to be careful in case size_t is unsigned (i.e. do not subtract
619    * things and then check for less than zero).
620    */
621   if (pass1blocks <= pass2blocks) {
622     /*
623      * If tape marks take up space, there should be fewer blocks in pass
624      * 2 than in pass 1 since we wrote twice as many tape marks.  But
625      * odd things happen, so make sure the result does not go negative.
626      */
627     blockdiff = (off_t)0;
628   } else {
629     blockdiff = pass1blocks - pass2blocks;
630   }
631   if (pass2files <= pass1files) {
632     /*
633      * This should not happen, but just in case ...
634      */
635     filediff = (off_t)1;
636   } else {
637     filediff = pass2files - pass1files;
638   }
639   filemark = (size_t)((blockdiff * (off_t)blockkb) / filediff);
640
641   /*
642    * Compute the length as the average of the two pass sizes including
643    * tape marks.
644    */
645   size = ((pass1blocks * (off_t)blockkb + (off_t)filemark * pass1files)
646            + (pass2blocks * (off_t)blockkb + (off_t)filemark * pass2files))
647            / (off_t)2;
648   if (size >= (off_t)(1024 * 1024 * 1000)) {
649     size /= (off_t)(1024 * 1024);
650     sizeunits = "gbytes";
651   } else if (size >= (off_t)(1024 * 1000)) {
652     size /= (off_t)1024;
653     sizeunits = "mbytes";
654   } else {
655     sizeunits = "kbytes";
656   }
657
658   /*
659    * Compute the speed as the average of the two passes.
660    */
661   speed = (unsigned long)((((double)pass1blocks
662            * (double)blockkb / (double)pass1time)
663            + ((double)pass2blocks * (double)blockkb / (double)pass2time)) / 2.0);
664
665   /*
666    * Dump the tapetype.
667    */
668   printf("define tapetype %s {\n", typename);
669   printf("    comment \"just produced by tapetype prog (hardware compression %s)\"\n",
670         hwcompr ? "on" : "off");
671   printf("    length " OFF_T_FMT " %s\n", (OFF_T_FMT_TYPE)size, sizeunits);
672   printf("    filemark " SIZE_T_FMT " kbytes\n", (SIZE_T_FMT_TYPE)filemark);
673   printf("    speed %lu kps\n", speed);
674   printf("}\n");
675
676   if (tapefd_rewind(fd) == -1) {
677     fprintf(stderr, "%s: could not rewind %s: %s\n",
678             sProgName, tapedev, strerror(errno));
679     return 1;
680   }
681
682   if (tapefd_close(fd) == -1) {
683     fprintf(stderr, "%s: could not close %s: %s\n",
684             sProgName, tapedev, strerror(errno));
685     return 1;
686   }
687
688   return 0;
689 }