library.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <disklabel.h>
  6. #include "library.h"
  7. int read_disklabel(int fd,struct disklabel *d) {
  8. if(lseek(fd,LABELOFFSET,SEEK_SET)<0) {
  9. return -1;
  10. }
  11. if(read(fd,d,sizeof(*d))!=sizeof(*d)) {
  12. return -1;
  13. }
  14. if(d->d_magic!=DISKLABELMAGIC || d->d_magic2!=DISKLABELMAGIC) {
  15. fprintf(stderr,"Existing disk label is corrupt\n");
  16. return -1;
  17. }
  18. return 0;
  19. }
  20. int dosumlabel(int fd,struct disklabel *d) {
  21. u_int64_t buf[128];
  22. int x;
  23. u_int64_t sum=0;
  24. if(lseek(fd,0,SEEK_SET)<0) {
  25. return -1;
  26. }
  27. if(read(fd,buf,64*sizeof(u_int64_t))!=(64*sizeof(u_int64_t))) {
  28. return -1;
  29. }
  30. memcpy(&buf[LABELOFFSET/sizeof(u_int64_t)],d,sizeof(*d));
  31. for(x=0;x<63;x++) {
  32. sum+=buf[x];
  33. }
  34. if(lseek(fd,63*sizeof(u_int64_t),SEEK_SET)<0) {
  35. return -1;
  36. }
  37. if(write(fd,&sum,sizeof(sum))!=sizeof(sum)) {
  38. return -1;
  39. }
  40. return 0;
  41. }
  42. static int does_overlap(int a1,int a2,int b1,int b2) {
  43. if(a1>b1 && a1<b2) {
  44. return 1;
  45. }
  46. if(a2>b1 && a2<b2) {
  47. return 1;
  48. }
  49. if(b1>a1 && b1<a2) {
  50. return 1;
  51. }
  52. if(b2>a1 && b2<a2) {
  53. return 1;
  54. }
  55. return 0;
  56. }
  57. /*
  58. returns the number of the partition overlapping with the area
  59. from offset to endplace, while ignoring partitions in the bitset ignore.
  60. */
  61. int overlaplabel(struct disklabel *d,int offset,int endplace,unsigned force) {
  62. int x;
  63. for(x=0;x<d->d_npartitions;x++) {
  64. if((force & (1U << x)) == 0) {
  65. int part_offset=d->d_partitions[x].p_offset;
  66. int part_end=d->d_partitions[x].p_offset+d->d_partitions[x].p_size;
  67. if(part_end>0 && does_overlap(part_offset,part_end,offset,endplace))
  68. return x;
  69. }
  70. }
  71. return -1;
  72. }