]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/block.c
- In block.c call dvd_write_part() to write last part rather
[bacula/bacula] / bacula / src / stored / block.c
1 /*
2  *
3  *   block.c -- tape block handling functions
4  *
5  *              Kern Sibbald, March MMI
6  *                 added BB02 format October MMII
7  *
8  *   Version $Id$
9  *
10  */
11 /*
12    Copyright (C) 2001-2005 Kern Sibbald
13
14    This program is free software; you can redistribute it and/or
15    modify it under the terms of the GNU General Public License
16    version 2 as amended with additional clauses defined in the
17    file LICENSE in the main source directory.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
22    the file LICENSE for additional details.
23
24  */
25
26
27 #include "bacula.h"
28 #include "stored.h"
29
30 extern int debug_level;
31 static bool terminate_writing_volume(DCR *dcr);
32 static bool do_new_file_bookkeeping(DCR *dcr);
33 static bool do_dvd_size_checks(DCR *dcr);
34 static void reread_last_block(DCR *dcr);
35
36 /*
37  * Dump the block header, then walk through
38  * the block printing out the record headers.
39  */
40 void dump_block(DEV_BLOCK *b, const char *msg)
41 {
42    ser_declare;
43    char *p;
44    char Id[BLKHDR_ID_LENGTH+1];
45    uint32_t CheckSum, BlockCheckSum;
46    uint32_t block_len;
47    uint32_t BlockNumber;
48    uint32_t VolSessionId, VolSessionTime, data_len;
49    int32_t  FileIndex;
50    int32_t  Stream;
51    int bhl, rhl;
52
53    unser_begin(b->buf, BLKHDR1_LENGTH);
54    unser_uint32(CheckSum);
55    unser_uint32(block_len);
56    unser_uint32(BlockNumber);
57    unser_bytes(Id, BLKHDR_ID_LENGTH);
58    ASSERT(unser_length(b->buf) == BLKHDR1_LENGTH);
59    Id[BLKHDR_ID_LENGTH] = 0;
60    if (Id[3] == '2') {
61       unser_uint32(VolSessionId);
62       unser_uint32(VolSessionTime);
63       bhl = BLKHDR2_LENGTH;
64       rhl = RECHDR2_LENGTH;
65    } else {
66       VolSessionId = VolSessionTime = 0;
67       bhl = BLKHDR1_LENGTH;
68       rhl = RECHDR1_LENGTH;
69    }
70
71    if (block_len > 100000) {
72       Dmsg3(20, "Dump block %s 0x%x blocksize too big %u\n", msg, b, block_len);
73       return;
74    }
75
76    BlockCheckSum = bcrc32((uint8_t *)b->buf+BLKHDR_CS_LENGTH,
77                          block_len-BLKHDR_CS_LENGTH);
78    Pmsg6(000, _("Dump block %s %x: size=%d BlkNum=%d\n"
79 "               Hdrcksum=%x cksum=%x\n"),
80       msg, b, block_len, BlockNumber, CheckSum, BlockCheckSum);
81    p = b->buf + bhl;
82    while (p < (b->buf + block_len+WRITE_RECHDR_LENGTH)) {
83       unser_begin(p, WRITE_RECHDR_LENGTH);
84       if (rhl == RECHDR1_LENGTH) {
85          unser_uint32(VolSessionId);
86          unser_uint32(VolSessionTime);
87       }
88       unser_int32(FileIndex);
89       unser_int32(Stream);
90       unser_uint32(data_len);
91       Pmsg6(000, _("   Rec: VId=%u VT=%u FI=%s Strm=%s len=%d p=%x\n"),
92            VolSessionId, VolSessionTime, FI_to_ascii(FileIndex),
93            stream_to_ascii(Stream, FileIndex), data_len, p);
94       p += data_len + rhl;
95   }
96 }
97
98 /*
99  * Create a new block structure.
100  * We pass device so that the block can inherit the
101  * min and max block sizes.
102  */
103 DEV_BLOCK *new_block(DEVICE *dev)
104 {
105    DEV_BLOCK *block = (DEV_BLOCK *)get_memory(sizeof(DEV_BLOCK));
106
107    memset(block, 0, sizeof(DEV_BLOCK));
108
109    /* If the user has specified a max_block_size, use it as the default */
110    if (dev->max_block_size == 0) {
111       block->buf_len = DEFAULT_BLOCK_SIZE;
112    } else {
113       block->buf_len = dev->max_block_size;
114    }
115    block->dev = dev;
116    block->block_len = block->buf_len;  /* default block size */
117    block->buf = get_memory(block->buf_len);
118    empty_block(block);
119    block->BlockVer = BLOCK_VER;       /* default write version */
120    Dmsg1(650, "Returning new block=%x\n", block);
121    return block;
122 }
123
124
125 /*
126  * Duplicate an existing block (eblock)
127  */
128 DEV_BLOCK *dup_block(DEV_BLOCK *eblock)
129 {
130    DEV_BLOCK *block = (DEV_BLOCK *)get_memory(sizeof(DEV_BLOCK));
131    int buf_len = sizeof_pool_memory(eblock->buf);
132
133    memcpy(block, eblock, sizeof(DEV_BLOCK));
134    block->buf = get_memory(buf_len);
135    memcpy(block->buf, eblock->buf, buf_len);
136    return block;
137 }
138
139
140 /*
141  * Only the first block checksum error was reported.
142  *   If there are more, report it now.
143  */
144 void print_block_read_errors(JCR *jcr, DEV_BLOCK *block)
145 {
146    if (block->read_errors > 1) {
147       Jmsg(jcr, M_ERROR, 0, _("%d block read errors not printed.\n"),
148          block->read_errors);
149    }
150 }
151
152 /*
153  * Free block
154  */
155 void free_block(DEV_BLOCK *block)
156 {
157    Dmsg1(999, "free_block buffer %x\n", block->buf);
158    free_memory(block->buf);
159    Dmsg1(999, "free_block block %x\n", block);
160    free_memory((POOLMEM *)block);
161 }
162
163 /* Empty the block -- for writing */
164 void empty_block(DEV_BLOCK *block)
165 {
166    block->binbuf = WRITE_BLKHDR_LENGTH;
167    block->bufp = block->buf + block->binbuf;
168    block->read_len = 0;
169    block->write_failed = false;
170    block->block_read = false;
171    block->FirstIndex = block->LastIndex = 0;
172 }
173
174 /*
175  * Create block header just before write. The space
176  * in the buffer should have already been reserved by
177  * init_block.
178  */
179 void ser_block_header(DEV_BLOCK *block)
180 {
181    ser_declare;
182    uint32_t CheckSum = 0;
183    uint32_t block_len = block->binbuf;
184
185    Dmsg1(1390, "ser_block_header: block_len=%d\n", block_len);
186    ser_begin(block->buf, BLKHDR2_LENGTH);
187    ser_uint32(CheckSum);
188    ser_uint32(block_len);
189    ser_uint32(block->BlockNumber);
190    ser_bytes(WRITE_BLKHDR_ID, BLKHDR_ID_LENGTH);
191    if (BLOCK_VER >= 2) {
192       ser_uint32(block->VolSessionId);
193       ser_uint32(block->VolSessionTime);
194    }
195
196    /* Checksum whole block except for the checksum */
197    CheckSum = bcrc32((uint8_t *)block->buf+BLKHDR_CS_LENGTH,
198                  block_len-BLKHDR_CS_LENGTH);
199    Dmsg1(1390, "ser_bloc_header: checksum=%x\n", CheckSum);
200    ser_begin(block->buf, BLKHDR2_LENGTH);
201    ser_uint32(CheckSum);              /* now add checksum to block header */
202 }
203
204 /*
205  * Unserialize the block header for reading block.
206  *  This includes setting all the buffer pointers correctly.
207  *
208  *  Returns: false on failure (not a block)
209  *           true  on success
210  */
211 static bool unser_block_header(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
212 {
213    ser_declare;
214    char Id[BLKHDR_ID_LENGTH+1];
215    uint32_t CheckSum, BlockCheckSum;
216    uint32_t block_len;
217    uint32_t block_end;
218    uint32_t BlockNumber;
219    int bhl;
220
221    unser_begin(block->buf, BLKHDR_LENGTH);
222    unser_uint32(CheckSum);
223    unser_uint32(block_len);
224    unser_uint32(BlockNumber);
225    unser_bytes(Id, BLKHDR_ID_LENGTH);
226    ASSERT(unser_length(block->buf) == BLKHDR1_LENGTH);
227
228    Id[BLKHDR_ID_LENGTH] = 0;
229    if (Id[3] == '1') {
230       bhl = BLKHDR1_LENGTH;
231       block->BlockVer = 1;
232       block->bufp = block->buf + bhl;
233       if (strncmp(Id, BLKHDR1_ID, BLKHDR_ID_LENGTH) != 0) {
234          dev->dev_errno = EIO;
235          Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Wanted ID: \"%s\", got \"%s\". Buffer discarded.\n"),
236             dev->file, dev->block_num, BLKHDR1_ID, Id);
237          if (block->read_errors == 0 || verbose >= 2) {
238             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
239          }
240          block->read_errors++;
241          return false;
242       }
243    } else if (Id[3] == '2') {
244       unser_uint32(block->VolSessionId);
245       unser_uint32(block->VolSessionTime);
246       bhl = BLKHDR2_LENGTH;
247       block->BlockVer = 2;
248       block->bufp = block->buf + bhl;
249       if (strncmp(Id, BLKHDR2_ID, BLKHDR_ID_LENGTH) != 0) {
250          dev->dev_errno = EIO;
251          Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Wanted ID: \"%s\", got \"%s\". Buffer discarded.\n"),
252             dev->file, dev->block_num, BLKHDR2_ID, Id);
253          if (block->read_errors == 0 || verbose >= 2) {
254             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
255          }
256          block->read_errors++;
257          return false;
258       }
259    } else {
260       dev->dev_errno = EIO;
261       Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Wanted ID: \"%s\", got \"%s\". Buffer discarded.\n"),
262           dev->file, dev->block_num, BLKHDR2_ID, Id);
263       if (block->read_errors == 0 || verbose >= 2) {
264          Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
265       }
266       block->read_errors++;
267       unser_uint32(block->VolSessionId);
268       unser_uint32(block->VolSessionTime);
269       return false;
270    }
271
272    /* Sanity check */
273    if (block_len > MAX_BLOCK_LENGTH) {
274       dev->dev_errno = EIO;
275       Mmsg3(dev->errmsg,  _("Volume data error at %u:%u! Block length %u is insane (too large), probably due to a bad archive.\n"),
276          dev->file, dev->block_num, block_len);
277       if (block->read_errors == 0 || verbose >= 2) {
278          Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
279       }
280       block->read_errors++;
281       return false;
282    }
283
284    Dmsg1(390, "unser_block_header block_len=%d\n", block_len);
285    /* Find end of block or end of buffer whichever is smaller */
286    if (block_len > block->read_len) {
287       block_end = block->read_len;
288    } else {
289       block_end = block_len;
290    }
291    block->binbuf = block_end - bhl;
292    block->block_len = block_len;
293    block->BlockNumber = BlockNumber;
294    Dmsg3(390, "Read binbuf = %d %d block_len=%d\n", block->binbuf,
295       bhl, block_len);
296    if (block_len <= block->read_len) {
297       BlockCheckSum = bcrc32((uint8_t *)block->buf+BLKHDR_CS_LENGTH,
298                          block_len-BLKHDR_CS_LENGTH);
299       if (BlockCheckSum != CheckSum) {
300          dev->dev_errno = EIO;
301          Mmsg6(dev->errmsg, _("Volume data error at %u:%u!\n" 
302             "Block checksum mismatch in block=%u len=%d: calc=%x blk=%x\n"),
303             dev->file, dev->block_num, (unsigned)BlockNumber, 
304             block_len, BlockCheckSum, CheckSum);
305          if (block->read_errors == 0 || verbose >= 2) {
306             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
307          }
308          block->read_errors++;
309          if (!forge_on) {
310             return false;
311          }
312       }
313    }
314    return true;
315 }
316
317 /*
318  * Write a block to the device, with locking and unlocking
319  *
320  * Returns: true  on success
321  *        : false on failure
322  *
323  */
324 bool write_block_to_device(DCR *dcr)
325 {
326    bool stat = true;
327    DEVICE *dev = dcr->dev;
328    JCR *jcr = dcr->jcr;
329
330    if (dcr->spooling) {
331       stat = write_block_to_spool_file(dcr);
332       return stat;
333    }
334
335    if (!dcr->dev_locked) {
336       lock_device(dev);
337    }
338
339    /*
340     * If a new volume has been mounted since our last write
341     *   Create a JobMedia record for the previous volume written,
342     *   and set new parameters to write this volume
343     * The same applies for if we are in a new file.
344     */
345    if (dcr->NewVol || dcr->NewFile) {
346       if (job_canceled(jcr)) {
347          stat = false;
348          goto bail_out;
349       }
350       /* Create a jobmedia record for this job */
351       if (!dir_create_jobmedia_record(dcr)) {
352          dev->dev_errno = EIO;
353          Jmsg(jcr, M_FATAL, 0, _("Could not create JobMedia record for Volume=\"%s\" Job=%s\n"),
354             dcr->VolCatInfo.VolCatName, jcr->Job);
355          set_new_volume_parameters(dcr);
356          stat = false;
357          goto bail_out;
358       }
359       if (dcr->NewVol) {
360          /* Note, setting a new volume also handles any pending new file */
361          set_new_volume_parameters(dcr);
362          dcr->NewFile = false;        /* this handled for new file too */
363       } else {
364          set_new_file_parameters(dcr);
365       }
366    }
367
368    if (!write_block_to_dev(dcr)) {
369        if (job_canceled(jcr) || jcr->JobType == JT_SYSTEM) {
370           stat = false;
371        } else {
372           stat = fixup_device_block_write_error(dcr);
373        }
374    }
375
376 bail_out:
377    if (!dcr->dev_locked) {
378       unlock_device(dev);
379    }
380    return stat;
381 }
382
383 /*
384  * Write a block to the device
385  *
386  *  Returns: true  on success or EOT
387  *           false on hard error
388  */
389 bool write_block_to_dev(DCR *dcr)
390 {
391    ssize_t stat = 0;
392    uint32_t wlen;                     /* length to write */
393    int hit_max1, hit_max2;
394    bool ok = true;
395    DEVICE *dev = dcr->dev;
396    JCR *jcr = dcr->jcr;
397    DEV_BLOCK *block = dcr->block;
398
399 #ifdef NO_TAPE_WRITE_TEST
400    empty_block(block);
401    return true;
402 #endif
403    ASSERT(block->binbuf == ((uint32_t) (block->bufp - block->buf)));
404
405    /* dump_block(block, "before write"); */
406    if (dev->at_weot()) {
407       Dmsg0(100, "return write_block_to_dev with ST_WEOT\n");
408       dev->dev_errno = ENOSPC;
409       Jmsg(jcr, M_FATAL, 0,  _("Cannot write block. Device at EOM.\n"));
410       return false;
411    }
412    if (!dev->can_append()) {
413       dev->dev_errno = EIO;
414       Jmsg(jcr, M_FATAL, 0, _("Attempt to write on read-only Volume.\n"));
415       return false;
416    }
417    wlen = block->binbuf;
418    if (wlen <= WRITE_BLKHDR_LENGTH) {  /* Does block have data in it? */
419       Dmsg0(100, "return write_block_to_dev no data to write\n");
420       return true;
421    }
422    /*
423     * Clear to the end of the buffer if it is not full,
424     *  and on tape devices, apply min and fixed blocking.
425     */
426    if (wlen != block->buf_len) {
427       uint32_t blen;                  /* current buffer length */
428
429       Dmsg2(200, "binbuf=%d buf_len=%d\n", block->binbuf, block->buf_len);
430       blen = wlen;
431
432       /* Adjust write size to min/max for tapes only */
433       if (dev->is_tape()) {
434          /* check for fixed block size */
435          if (dev->min_block_size == dev->max_block_size) {
436             wlen = block->buf_len;    /* fixed block size already rounded */
437          /* Check for min block size */
438          } else if (wlen < dev->min_block_size) {
439             wlen =  ((dev->min_block_size + TAPE_BSIZE - 1) / TAPE_BSIZE) * TAPE_BSIZE;
440          /* Ensure size is rounded */
441          } else {
442             wlen = ((wlen + TAPE_BSIZE - 1) / TAPE_BSIZE) * TAPE_BSIZE;
443          }
444       }
445       if (wlen-blen > 0) {
446          memset(block->bufp, 0, wlen-blen); /* clear garbage */
447       }
448    }
449
450    ser_block_header(block);
451
452    /* Limit maximum Volume size to value specified by user */
453    hit_max1 = (dev->max_volume_size > 0) &&
454        ((dev->VolCatInfo.VolCatBytes + block->binbuf)) >= dev->max_volume_size;
455    hit_max2 = (dev->VolCatInfo.VolCatMaxBytes > 0) &&
456        ((dev->VolCatInfo.VolCatBytes + block->binbuf)) >= dev->VolCatInfo.VolCatMaxBytes;
457    if (hit_max1 || hit_max2) {
458       char ed1[50];
459       uint64_t max_cap;
460       Dmsg0(10, "==== Output bytes Triggered medium max capacity.\n");
461       if (hit_max1) {
462          max_cap = dev->max_volume_size;
463       } else {
464          max_cap = dev->VolCatInfo.VolCatMaxBytes;
465       }
466       Jmsg(jcr, M_INFO, 0, _("User defined maximum volume capacity %s exceeded on device %s.\n"),
467             edit_uint64_with_commas(max_cap, ed1),  dev->print_name());
468       terminate_writing_volume(dcr);
469       reread_last_block(dcr);   /* DEBUG */
470       dev->dev_errno = ENOSPC;
471       return false;
472    }
473
474    /* Limit maximum File size on volume to user specified value */
475    if ((dev->max_file_size > 0) &&
476        (dev->file_size+block->binbuf) >= dev->max_file_size) {
477       dev->file_size = 0;             /* reset file size */
478
479       if (weof_dev(dev, 1) != 0) {            /* write eof */
480          Dmsg0(190, "WEOF error in max file size.\n");
481          Jmsg(jcr, M_FATAL, 0, _("Unable to write EOF. ERR=%s\n"), 
482             strerror_dev(dev));
483          terminate_writing_volume(dcr);
484          dev->dev_errno = ENOSPC;
485          return false;
486       }
487       if (!write_ansi_ibm_labels(dcr, ANSI_EOF_LABEL, dev->VolHdr.VolumeName)) {
488          return false;
489       }
490
491       if (!do_new_file_bookkeeping(dcr)) {
492          /* Error message already sent */
493          return false;
494       }
495    }
496    
497    if (!do_dvd_size_checks(dcr)) {
498       /* Error message already sent */
499       return false;
500    }
501
502    dev->VolCatInfo.VolCatWrites++;
503    Dmsg1(1300, "Write block of %u bytes\n", wlen);
504 #ifdef DEBUG_BLOCK_ZEROING
505    uint32_t *bp = (uint32_t *)block->buf;
506    if (bp[0] == 0 && bp[1] == 0 && bp[2] == 0 && block->buf[12] == 0) {
507       Jmsg0(jcr, M_ABORT, 0, _("Write block header zeroed.\n"));
508    }
509 #endif
510
511    /*
512     * Do write here
513     */ 
514    stat = write(dev->fd, block->buf, (size_t)wlen);
515
516 #ifdef DEBUG_BLOCK_ZEROING
517    if (bp[0] == 0 && bp[1] == 0 && bp[2] == 0 && block->buf[12] == 0) {
518       Jmsg0(jcr, M_ABORT, 0, _("Write block header zeroed.\n"));
519    }
520 #endif
521
522    if (stat != (ssize_t)wlen) {
523       /* Some devices simply report EIO when the volume is full.
524        * With a little more thought we may be able to check
525        * capacity and distinguish real errors and EOT
526        * conditions.  In any case, we probably want to
527        * simulate an End of Medium.
528        */
529       if (stat == -1) {
530          berrno be;
531          clrerror_dev(dev, -1);
532          if (dev->dev_errno == 0) {
533             dev->dev_errno = ENOSPC;        /* out of space */
534          }
535          if (dev->dev_errno != ENOSPC) {
536             Jmsg4(jcr, M_ERROR, 0, _("Write error at %u:%u on device %s. ERR=%s.\n"),
537                dev->file, dev->block_num, dev->print_name(), be.strerror());
538          }
539       } else {
540         dev->dev_errno = ENOSPC;            /* out of space */
541       }
542       if (dev->dev_errno == ENOSPC) {
543          Jmsg(jcr, M_INFO, 0, _("End of Volume \"%s\" at %u:%u on device %s. Write of %u bytes got %d.\n"),
544             dev->VolCatInfo.VolCatName,
545             dev->file, dev->block_num, dev->print_name(), wlen, stat);
546       }
547       Dmsg7(100, "=== Write error. fd=%d size=%u rtn=%d dev_blk=%d blk_blk=%d errno=%d: ERR=%s\n",
548          dev->fd, wlen, stat, dev->block_num, block->BlockNumber, 
549          dev->dev_errno, strerror(dev->dev_errno));
550
551       ok = terminate_writing_volume(dcr);
552       if (!ok && !forge_on) {
553          return false;
554       }
555       if (ok) {
556          reread_last_block(dcr);
557       }
558       return false;
559    }
560
561    /* We successfully wrote the block, now do housekeeping */
562
563    dev->VolCatInfo.VolCatBytes += block->binbuf;
564    dev->VolCatInfo.VolCatBlocks++;
565    dev->EndBlock = dev->block_num;
566    dev->EndFile  = dev->file;
567    dev->block_num++;
568    block->BlockNumber++;
569
570    /* Update dcr values */
571    if (dev->is_tape()) {
572       dcr->EndBlock = dev->EndBlock;
573       dcr->EndFile  = dev->EndFile;
574    } else {
575       /* Save address of block just written */
576       uint64_t addr = dev->file_addr + wlen - 1;
577       dcr->EndBlock = (uint32_t)addr;
578       dcr->EndFile = (uint32_t)(addr >> 32);
579       dev->block_num = dcr->EndBlock;
580       dev->file = dcr->EndFile;
581    }
582    if (dcr->VolFirstIndex == 0 && block->FirstIndex > 0) {
583       dcr->VolFirstIndex = block->FirstIndex;
584    }
585    if (block->LastIndex > 0) {
586       dcr->VolLastIndex = block->LastIndex;
587    }
588    dcr->WroteVol = true;
589    dev->file_addr += wlen;            /* update file address */
590    dev->file_size += wlen;
591    dev->part_size += wlen;
592
593    Dmsg2(1300, "write_block: wrote block %d bytes=%d\n", dev->block_num, wlen);
594    empty_block(block);
595    return true;
596 }
597
598 static void reread_last_block(DCR *dcr)
599 {
600 #define CHECK_LAST_BLOCK
601 #ifdef  CHECK_LAST_BLOCK
602    bool ok = true;
603    DEVICE *dev = dcr->dev;
604    JCR *jcr = dcr->jcr;
605    DEV_BLOCK *block = dcr->block;
606    /*
607     * If the device is a tape and it supports backspace record,
608     *   we backspace over one or two eof marks depending on
609     *   how many we just wrote, then over the last record,
610     *   then re-read it and verify that the block number is
611     *   correct.
612     */
613    if (dev->is_tape() && dev_cap(dev, CAP_BSR)) {
614       /* Now back up over what we wrote and read the last block */
615       if (!bsf_dev(dev, 1)) {
616          berrno be;
617          ok = false;
618          Jmsg(jcr, M_ERROR, 0, _("Backspace file at EOT failed. ERR=%s\n"), 
619               be.strerror(dev->dev_errno));
620       }
621       if (ok && dev_cap(dev, CAP_TWOEOF) && !bsf_dev(dev, 1)) {
622          berrno be;
623          ok = false;
624          Jmsg(jcr, M_ERROR, 0, _("Backspace file at EOT failed. ERR=%s\n"), 
625               be.strerror(dev->dev_errno));
626       }
627       /* Backspace over record */
628       if (ok && !bsr_dev(dev, 1)) {
629          berrno be;
630          ok = false;
631          Jmsg(jcr, M_ERROR, 0, _("Backspace record at EOT failed. ERR=%s\n"), 
632               be.strerror(dev->dev_errno));
633          /*
634           *  On FreeBSD systems, if the user got here, it is likely that his/her
635           *    tape drive is "frozen".  The correct thing to do is a
636           *    rewind(), but if we do that, higher levels in cleaning up, will
637           *    most likely write the EOS record over the beginning of the
638           *    tape.  The rewind *is* done later in mount.c when another
639           *    tape is requested. Note, the clrerror_dev() call in bsr_dev()
640           *    calls ioctl(MTCERRSTAT), which *should* fix the problem.
641           */
642       }
643       if (ok) {
644          DEV_BLOCK *lblock = new_block(dev);
645          /* Note, this can destroy dev->errmsg */
646          dcr->block = lblock;
647          if (!read_block_from_dev(dcr, NO_BLOCK_NUMBER_CHECK)) {
648             Jmsg(jcr, M_ERROR, 0, _("Re-read last block at EOT failed. ERR=%s"), 
649                  dev->errmsg);
650          } else {
651             if (lblock->BlockNumber+1 == block->BlockNumber) {
652                Jmsg(jcr, M_INFO, 0, _("Re-read of last block succeeded.\n"));
653             } else {
654                Jmsg(jcr, M_ERROR, 0, _(
655 "Re-read of last block failed. Last block=%u Current block=%u.\n"),
656                     lblock->BlockNumber, block->BlockNumber);
657             }
658          }
659          free_block(lblock);
660          dcr->block = block;
661       }
662    }
663 #endif
664 }
665
666 static bool terminate_writing_volume(DCR *dcr)
667 {
668    DEVICE *dev = dcr->dev;
669    bool ok = true;
670
671    /* Create a JobMedia record to indicated end of tape */
672    dev->VolCatInfo.VolCatFiles = dev->file;
673    if (!dir_create_jobmedia_record(dcr)) {
674       Dmsg0(190, "Error from create JobMedia\n");
675       dev->dev_errno = EIO;
676        Jmsg(dcr->jcr, M_FATAL, 0, _("Could not create JobMedia record for Volume=\"%s\" Job=%s\n"),
677             dcr->VolCatInfo.VolCatName, dcr->jcr->Job);
678        ok = false;
679        goto bail_out;
680    }
681    dcr->block->write_failed = true;
682    if (weof_dev(dev, 1) != 0) {         /* end the tape */
683       dev->VolCatInfo.VolCatErrors++;
684       Jmsg(dcr->jcr, M_ERROR, 0, _("Error writing final EOF to tape. This tape may not be readable.\n"
685            "%s"), dev->errmsg);
686       ok = false;
687       Dmsg0(100, "WEOF error.\n");
688    }
689    if (ok) {
690       ok = write_ansi_ibm_labels(dcr, ANSI_EOV_LABEL, dev->VolHdr.VolumeName);
691    }
692    bstrncpy(dev->VolCatInfo.VolCatStatus, "Full", sizeof(dev->VolCatInfo.VolCatStatus));
693    dev->VolCatInfo.VolCatFiles = dev->file;   /* set number of files */
694    dev->VolCatInfo.VolCatJobs++;              /* increment number of jobs */
695    
696    if (dev->is_dvd()) {
697       dvd_write_part(dcr);                 /* write last part */
698    }
699    
700    if (!dir_update_volume_info(dcr, false)) {
701       ok = false;
702    }
703    Dmsg1(100, "dir_update_volume_info terminate writing -- %s\n", ok?"OK":"ERROR");
704
705    /*
706     * Walk through all attached dcrs setting flag to call
707     * set_new_file_parameters() when that dcr is next used.
708     */
709    DCR *mdcr;
710    foreach_dlist(mdcr, dev->attached_dcrs) {
711       if (mdcr->jcr->JobId == 0) {
712          continue;
713       }
714       mdcr->NewFile = true;        /* set reminder to do set_new_file_params */
715    }
716    /* Set new file/block parameters for current dcr */
717    set_new_file_parameters(dcr);
718
719    if (ok && dev_cap(dev, CAP_TWOEOF) && weof_dev(dev, 1) != 0) {  /* end the tape */
720       dev->VolCatInfo.VolCatErrors++;
721       /* This may not be fatal since we already wrote an EOF */
722       Jmsg(dcr->jcr, M_ERROR, 0, "%s", dev->errmsg);
723    }
724 bail_out:
725    dev->set_ateot();                  /* no more writing this tape */
726    Dmsg1(100, "Leave terminate_writing_volume -- %s\n", ok?"OK":"ERROR");
727    return ok;
728 }
729
730 /*
731  * Do bookkeeping when a new file is created on a Volume. This is
732  *  also done for disk files to generate the jobmedia records for
733  *  quick seeking.
734  */
735 static bool do_new_file_bookkeeping(DCR *dcr) 
736 {
737    DEVICE *dev = dcr->dev;
738    JCR *jcr = dcr->jcr;
739
740    /* Create a JobMedia record so restore can seek */
741    if (!dir_create_jobmedia_record(dcr)) {
742       Dmsg0(190, "Error from create_job_media.\n");
743       dev->dev_errno = EIO;
744        Jmsg(jcr, M_FATAL, 0, _("Could not create JobMedia record for Volume=\"%s\" Job=%s\n"),
745             dcr->VolCatInfo.VolCatName, jcr->Job);
746        terminate_writing_volume(dcr);
747        dev->dev_errno = EIO;
748        return false;
749    }
750    dev->VolCatInfo.VolCatFiles = dev->file;
751    if (!dir_update_volume_info(dcr, false)) {
752       Dmsg0(190, "Error from update_vol_info.\n");
753       terminate_writing_volume(dcr);
754       dev->dev_errno = EIO;
755       return false;
756    }
757    Dmsg0(100, "dir_update_volume_info max file size -- OK\n");
758
759    /*
760     * Walk through all attached dcrs setting flag to call
761     * set_new_file_parameters() when that dcr is next used.
762     */
763    DCR *mdcr;
764    foreach_dlist(mdcr, dev->attached_dcrs) {
765       if (mdcr->jcr->JobId == 0) {
766          continue;
767       }
768       mdcr->NewFile = true;        /* set reminder to do set_new_file_params */
769    }
770    /* Set new file/block parameters for current dcr */
771    set_new_file_parameters(dcr);
772    return true;
773 }
774
775 /*
776  * Do all checks for DVD sizes during writing.
777  */
778 static bool do_dvd_size_checks(DCR *dcr) 
779 {
780    DEVICE *dev = dcr->dev;
781    JCR *jcr = dcr->jcr;
782    DEV_BLOCK *block = dcr->block;
783
784    /* Limit maximum part size to value specified by user 
785     * (not applicable to tapes/fifos)   
786     */
787    if (!(dev->is_tape() || dev->is_fifo()) && dev->max_part_size > 0 &&
788         (dev->part_size + block->binbuf) >= dev->max_part_size) {
789       if (dev->part < dev->num_parts) {
790          Jmsg3(dcr->jcr, M_FATAL, 0, _("Error while writing, current part number"
791                " is less than the total number of parts (%d/%d, device=%s)\n"),
792                dev->part, dev->num_parts, dev->print_name());
793          dev->dev_errno = EIO;
794          return false;
795       }
796       
797       if (dvd_open_next_part(dcr) < 0) {
798          Jmsg2(dcr->jcr, M_FATAL, 0, _("Unable to open device next part %s: ERR=%s\n"),
799                 dev->print_name(), strerror_dev(dev));
800          dev->dev_errno = EIO;
801          return false;
802       }
803       
804       dev->VolCatInfo.VolCatParts = dev->num_parts;
805             
806       if (!dir_update_volume_info(dcr, false)) {
807          Dmsg0(190, "Error from update_vol_info.\n");
808          dev->dev_errno = EIO;
809          return false;
810       }
811    }
812    
813    if (dev->free_space_errno < 0) { /* Error while getting free space */
814       char ed1[50], ed2[50];
815       Dmsg1(10, "Cannot get free space on the device ERR=%s.\n", dev->errmsg);
816       Jmsg(jcr, M_FATAL, 0, _("End of Volume \"%s\" at %u:%u on device %s "
817          "(part_size=%s, free_space=%s, free_space_errno=%d, errmsg=%s).\n"),
818            dev->VolCatInfo.VolCatName,
819            dev->file, dev->block_num, dev->print_name(),
820            edit_uint64_with_commas(dev->part_size, ed1), edit_uint64_with_commas(dev->free_space, ed2),
821            dev->free_space_errno, dev->errmsg);
822       dev->dev_errno = -dev->free_space_errno;
823       return false;
824    }
825    
826    if ((dev->free_space_errno > 0 && (dev->part_size + block->binbuf) >= dev->free_space)) {
827       char ed1[50], ed2[50];
828       Dmsg0(10, "==== Just enough free space on the device to write the current part...\n");
829       Jmsg(jcr, M_INFO, 0, _("End of Volume \"%s\" at %u:%u on device %s "
830          "(part_size=%s, free_space=%s, free_space_errno=%d).\n"),
831             dev->VolCatInfo.VolCatName,
832             dev->file, dev->block_num, dev->print_name(),
833             edit_uint64_with_commas(dev->part_size, ed1), edit_uint64_with_commas(dev->free_space, ed2),
834             dev->free_space_errno);
835       terminate_writing_volume(dcr);
836       dev->dev_errno = ENOSPC;
837       return false;
838    }   
839    return true;
840 }
841
842
843 /*
844  * Read block with locking
845  *
846  */
847 bool read_block_from_device(DCR *dcr, bool check_block_numbers)
848 {
849    bool ok;
850    DEVICE *dev = dcr->dev;
851    Dmsg0(200, "Enter read_block_from_device\n");
852    lock_device(dev);
853    ok = read_block_from_dev(dcr, check_block_numbers);
854    unlock_device(dev);
855    Dmsg0(200, "Leave read_block_from_device\n");
856    return ok;
857 }
858
859 /*
860  * Read the next block into the block structure and unserialize
861  *  the block header.  For a file, the block may be partially
862  *  or completely in the current buffer.
863  */
864 bool read_block_from_dev(DCR *dcr, bool check_block_numbers)
865 {
866    ssize_t stat;
867    int looping;
868    uint32_t BlockNumber;
869    int retry;
870    JCR *jcr = dcr->jcr;
871    DEVICE *dev = dcr->dev;
872    DEV_BLOCK *block = dcr->block;
873    
874    if (dev->at_eot()) {
875       return false;
876    }
877    looping = 0;
878    Dmsg1(200, "Full read() in read_block_from_device() len=%d\n",
879          block->buf_len);
880 reread:
881    if (looping > 1) {
882       dev->dev_errno = EIO;
883       Mmsg1(dev->errmsg, _("Block buffer size looping problem on device %s\n"),
884          dev->print_name());
885       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
886       block->read_len = 0;
887       return false;
888    }
889    
890    /*Dmsg1(100, "dev->file_size=%u\n",(unsigned int)dev->file_size);
891    Dmsg1(100, "dev->file_addr=%u\n",(unsigned int)dev->file_addr);
892    Dmsg1(100, "lseek=%u\n",(unsigned int)lseek(dev->fd, 0, SEEK_CUR));
893    Dmsg1(100, "dev->part_start=%u\n",(unsigned int)dev->part_start);
894    Dmsg1(100, "dev->file_addr-dev->part_start=%u\n",(unsigned int)dev->file_addr-dev->part_start);
895    Dmsg1(100, "dev->file_size-dev->part_start=%u\n",(unsigned int)dev->file_size-dev->part_start);
896    Dmsg1(100, "dev->part_size=%u\n", (unsigned int)dev->part_size);
897    Dmsg1(100, "dev->part=%u\n", (unsigned int)dev->part);
898    Dmsg1(100, "dev->num_parts=%u\n", (unsigned int)dev->num_parts);
899    Dmsg1(100, "dev->VolCatInfo.VolCatParts=%u\n", (unsigned int)dev->VolCatInfo.VolCatParts);
900    Dmsg3(100, "Tests : %d %d %d\n", (dev->VolCatInfo.VolCatParts > 0), 
901          ((dev->file_addr-dev->part_start) == dev->part_size), 
902          (dev->part <= dev->VolCatInfo.VolCatParts));*/
903    /* Check for part file end */
904    if ((dev->num_parts > 0) &&
905         ((dev->file_addr-dev->part_start) == dev->part_size) && 
906         (dev->part < dev->num_parts)) {
907       if (dvd_open_next_part(dcr) < 0) {
908          Jmsg2(dcr->jcr, M_FATAL, 0, _("Unable to open device next part %s: ERR=%s\n"),
909                dev->print_name(), strerror_dev(dev));
910          dev->dev_errno = EIO;
911          return false;
912       }
913    }
914    
915    retry = 0;
916    do {
917 //    uint32_t *bp = (uint32_t *)block->buf;
918 //    Pmsg3(000, "Read %p %u at %llu\n", block->buf, block->buf_len, lseek(dev->fd, 0, SEEK_CUR));
919
920       stat = read(dev->fd, block->buf, (size_t)block->buf_len);
921
922 //    Pmsg8(000, "stat=%d Csum=%u blen=%u bnum=%u %c%c%c%c\n",stat, bp[0],bp[1],bp[2],
923 //      block->buf[12],block->buf[13],block->buf[14],block->buf[15]);
924
925       if (retry == 1) {
926          dev->VolCatInfo.VolCatErrors++;
927       }
928    } while (stat == -1 && (errno == EINTR || errno == EIO) && retry++ < 11);
929    if (stat < 0) {
930       berrno be;
931       clrerror_dev(dev, -1);
932       Dmsg1(200, "Read device got: ERR=%s\n", be.strerror());
933       block->read_len = 0;
934       Mmsg4(dev->errmsg, _("Read error at file:blk %u:%u on device %s. ERR=%s.\n"),
935          dev->file, dev->block_num, dev->print_name(), be.strerror());
936       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
937       if (dev->at_eof()) {        /* EOF just seen? */
938          dev->set_eot();          /* yes, error => EOT */
939       }
940       return false;
941    }
942    Dmsg3(200, "Read device got %d bytes at %u:%u\n", stat,
943       dev->file, dev->block_num);
944    if (stat == 0) {             /* Got EOF ! */
945       dev->block_num = 0;
946       block->read_len = 0;
947       Mmsg3(dev->errmsg, _("Read zero bytes at %u:%u on device %s.\n"),
948          dev->file, dev->block_num, dev->print_name());
949       if (dev->at_eof()) {       /* EOF already read? */
950          dev->set_eot();         /* yes, 2 EOFs => EOT */
951          return 0;
952       }
953       dev->set_ateof();
954       return false;             /* return eof */
955    }
956    /* Continue here for successful read */
957    block->read_len = stat;      /* save length read */
958    if (block->read_len < BLKHDR2_LENGTH) {
959       dev->dev_errno = EIO;
960       Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Very short block of %d bytes on device %s discarded.\n"),
961          dev->file, dev->block_num, block->read_len, dev->print_name());
962       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
963       dev->set_short_block();   
964       block->read_len = block->binbuf = 0;
965       return false;             /* return error */
966    }
967
968    BlockNumber = block->BlockNumber + 1;
969    if (!unser_block_header(jcr, dev, block)) {
970       if (forge_on) {
971          dev->file_addr += block->read_len;
972          dev->file_size += block->read_len;
973          goto reread;
974       }
975       return false;
976    }
977
978    /*
979     * If the block is bigger than the buffer, we reposition for
980     *  re-reading the block, allocate a buffer of the correct size,
981     *  and go re-read.
982     */
983    if (block->block_len > block->buf_len) {
984       dev->dev_errno = EIO;
985       Mmsg2(dev->errmsg,  _("Block length %u is greater than buffer %u. Attempting recovery.\n"),
986          block->block_len, block->buf_len);
987       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
988       Pmsg1(000, "%s", dev->errmsg);
989       /* Attempt to reposition to re-read the block */
990       if (dev->is_tape()) {
991          Dmsg0(200, "BSR for reread; block too big for buffer.\n");
992          if (!bsr_dev(dev, 1)) {
993             Jmsg(jcr, M_ERROR, 0, "%s", strerror_dev(dev));
994             block->read_len = 0;
995             return false;
996          }
997       } else {
998          Dmsg0(200, "Seek to beginning of block for reread.\n");
999          off_t pos = lseek_dev(dev, (off_t)0, SEEK_CUR); /* get curr pos */
1000          pos -= block->read_len;
1001          lseek_dev(dev, pos, SEEK_SET);
1002          dev->file_addr = pos;
1003       }
1004       Mmsg1(dev->errmsg, _("Setting block buffer size to %u bytes.\n"), block->block_len);
1005       Jmsg(jcr, M_INFO, 0, "%s", dev->errmsg);
1006       Pmsg1(000, "%s", dev->errmsg);
1007       /* Set new block length */
1008       dev->max_block_size = block->block_len;
1009       block->buf_len = block->block_len;
1010       free_memory(block->buf);
1011       block->buf = get_memory(block->buf_len);
1012       empty_block(block);
1013       looping++;
1014       goto reread;                    /* re-read block with correct block size */
1015    }
1016
1017    if (block->block_len > block->read_len) {
1018       dev->dev_errno = EIO;
1019       Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Short block of %d bytes on device %s discarded.\n"),
1020          dev->file, dev->block_num, block->read_len, dev->print_name());
1021       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
1022       dev->set_short_block();
1023       block->read_len = block->binbuf = 0;
1024       return false;             /* return error */
1025    }
1026
1027    dev->clear_short_block();
1028    dev->clear_eof();
1029    dev->VolCatInfo.VolCatReads++;
1030    dev->VolCatInfo.VolCatRBytes += block->read_len;
1031
1032    dev->VolCatInfo.VolCatBytes += block->block_len;
1033    dev->VolCatInfo.VolCatBlocks++;
1034    dev->EndBlock = dev->block_num;
1035    dev->EndFile  = dev->file;
1036    dev->block_num++;
1037
1038    /* Update dcr values */
1039    if (dev->is_tape()) {
1040       dcr->EndBlock = dev->EndBlock;
1041       dcr->EndFile  = dev->EndFile;
1042    } else {
1043       uint64_t addr = dev->file_addr + block->read_len - 1;
1044       dcr->EndBlock = (uint32_t)addr;
1045       dcr->EndFile = (uint32_t)(addr >> 32);
1046       dev->block_num = dcr->EndBlock;
1047       dev->file = dcr->EndFile;
1048    }
1049    dev->file_addr += block->read_len;
1050    dev->file_size += block->read_len;
1051
1052    /*
1053     * If we read a short block on disk,
1054     * seek to beginning of next block. This saves us
1055     * from shuffling blocks around in the buffer. Take a
1056     * look at this from an efficiency stand point later, but
1057     * it should only happen once at the end of each job.
1058     *
1059     * I've been lseek()ing negative relative to SEEK_CUR for 30
1060     *   years now. However, it seems that with the new off_t definition,
1061     *   it is not possible to seek negative amounts, so we use two
1062     *   lseek(). One to get the position, then the second to do an
1063     *   absolute positioning -- so much for efficiency.  KES Sep 02.
1064     */
1065    Dmsg0(200, "At end of read block\n");
1066    if (block->read_len > block->block_len && !dev->is_tape()) {
1067       char ed1[50];
1068       off_t pos = lseek_dev(dev, (off_t)0, SEEK_CUR); /* get curr pos */
1069       pos -= (block->read_len - block->block_len);
1070       lseek_dev(dev, pos, SEEK_SET);
1071       Dmsg3(200, "Did lseek pos=%s blk_size=%d rdlen=%d\n", 
1072          edit_uint64(pos, ed1), block->block_len,
1073             block->read_len);
1074       dev->file_addr = pos;
1075       dev->file_size = pos;
1076    }
1077    Dmsg2(200, "Exit read_block read_len=%d block_len=%d\n",
1078       block->read_len, block->block_len);
1079    block->block_read = true;
1080    return true;
1081 }