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