fd.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Copyright (C) 2001 - 2007 Jeff Dike (jdike@{linux.intel,addtoit}.com)
  3. * Licensed under the GPL
  4. */
  5. #include <stddef.h>
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #include <errno.h>
  9. #include <termios.h>
  10. #include <unistd.h>
  11. #include "chan_user.h"
  12. #include "um_malloc.h"
  13. #include "user.h"
  14. #include "os.h"
  15. #include "kern_constants.h"
  16. struct fd_chan {
  17. int fd;
  18. int raw;
  19. struct termios tt;
  20. char str[sizeof("1234567890\0")];
  21. };
  22. static void *fd_init(char *str, int device, const struct chan_opts *opts)
  23. {
  24. struct fd_chan *data;
  25. char *end;
  26. int n;
  27. if (*str != ':') {
  28. printk(UM_KERN_ERR "fd_init : channel type 'fd' must specify a "
  29. "file descriptor\n");
  30. return NULL;
  31. }
  32. str++;
  33. n = strtoul(str, &end, 0);
  34. if ((*end != '\0') || (end == str)) {
  35. printk(UM_KERN_ERR "fd_init : couldn't parse file descriptor "
  36. "'%s'\n", str);
  37. return NULL;
  38. }
  39. data = kmalloc(sizeof(*data), UM_GFP_KERNEL);
  40. if(data == NULL)
  41. return NULL;
  42. *data = ((struct fd_chan) { .fd = n,
  43. .raw = opts->raw });
  44. return data;
  45. }
  46. static int fd_open(int input, int output, int primary, void *d, char **dev_out)
  47. {
  48. struct fd_chan *data = d;
  49. int err;
  50. if (data->raw && isatty(data->fd)) {
  51. CATCH_EINTR(err = tcgetattr(data->fd, &data->tt));
  52. if (err)
  53. return err;
  54. err = raw(data->fd);
  55. if (err)
  56. return err;
  57. }
  58. sprintf(data->str, "%d", data->fd);
  59. *dev_out = data->str;
  60. return data->fd;
  61. }
  62. static void fd_close(int fd, void *d)
  63. {
  64. struct fd_chan *data = d;
  65. int err;
  66. if (!data->raw || !isatty(fd))
  67. return;
  68. CATCH_EINTR(err = tcsetattr(fd, TCSAFLUSH, &data->tt));
  69. if (err)
  70. printk(UM_KERN_ERR "Failed to restore terminal state - "
  71. "errno = %d\n", -err);
  72. data->raw = 0;
  73. }
  74. const struct chan_ops fd_ops = {
  75. .type = "fd",
  76. .init = fd_init,
  77. .open = fd_open,
  78. .close = fd_close,
  79. .read = generic_read,
  80. .write = generic_write,
  81. .console_write = generic_console_write,
  82. .window_size = generic_window_size,
  83. .free = generic_free,
  84. .winch = 1,
  85. };