nsec.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include <u.h>
  2. #include <libc.h>
  3. static uvlong order = 0x0001020304050607ULL;
  4. static void
  5. be2vlong(vlong *to, uchar *f)
  6. {
  7. uchar *t, *o;
  8. int i;
  9. t = (uchar*)to;
  10. o = (uchar*)&order;
  11. for(i = 0; i < 8; i++)
  12. t[o[i]] = f[i];
  13. }
  14. /*
  15. * After a fork with fd's copied, both fd's are pointing to
  16. * the same Chan structure. Since the offset is kept in the Chan
  17. * structure, the seek's and read's in the two processes can
  18. * compete at moving the offset around. Hence the retry loop.
  19. *
  20. * Since the bintime version doesn't need a seek, it doesn't
  21. * have the loop.
  22. */
  23. vlong
  24. nsec(void)
  25. {
  26. char b[12+1];
  27. static int f = -1;
  28. static int usebintime;
  29. int retries;
  30. vlong t;
  31. if(f < 0){
  32. usebintime = 1;
  33. f = open("/dev/bintime", OREAD|OCEXEC);
  34. if(f < 0){
  35. usebintime = 0;
  36. f = open("/dev/nsec", OREAD|OCEXEC);
  37. if(f < 0)
  38. return 0;
  39. }
  40. }
  41. if(usebintime){
  42. if(read(f, b, sizeof(uvlong)) < 0)
  43. goto error;
  44. be2vlong(&t, (uchar*)b);
  45. return t;
  46. } else {
  47. for(retries = 0; retries < 100; retries++){
  48. if(seek(f, 0, 0) >= 0 && read(f, b, sizeof(b)-1) >= 0){
  49. b[sizeof(b)-1] = 0;
  50. return strtoll(b, 0, 0);
  51. }
  52. }
  53. }
  54. error:
  55. close(f);
  56. f = -1;
  57. return 0;
  58. }