xref: /openbmc/qemu/hw/usb/dev-serial.c (revision ed5abf46)
1 /*
2  * FTDI FT232BM Device emulation
3  *
4  * Copyright (c) 2006 CodeSourcery.
5  * Copyright (c) 2008 Samuel Thibault <samuel.thibault@ens-lyon.org>
6  * Written by Paul Brook, reused for FTDI by Samuel Thibault
7  *
8  * This code is licensed under the LGPL.
9  */
10 
11 #include "qemu/osdep.h"
12 #include "qapi/error.h"
13 #include "qemu/cutils.h"
14 #include "qemu/error-report.h"
15 #include "qemu/module.h"
16 #include "hw/qdev-properties.h"
17 #include "hw/usb.h"
18 #include "migration/vmstate.h"
19 #include "desc.h"
20 #include "chardev/char-serial.h"
21 #include "chardev/char-fe.h"
22 
23 //#define DEBUG_Serial
24 
25 #ifdef DEBUG_Serial
26 #define DPRINTF(fmt, ...) \
27 do { printf("usb-serial: " fmt , ## __VA_ARGS__); } while (0)
28 #else
29 #define DPRINTF(fmt, ...) do {} while(0)
30 #endif
31 
32 #define RECV_BUF 384
33 
34 /* Commands */
35 #define FTDI_RESET		0
36 #define FTDI_SET_MDM_CTRL	1
37 #define FTDI_SET_FLOW_CTRL	2
38 #define FTDI_SET_BAUD		3
39 #define FTDI_SET_DATA		4
40 #define FTDI_GET_MDM_ST		5
41 #define FTDI_SET_EVENT_CHR	6
42 #define FTDI_SET_ERROR_CHR	7
43 #define FTDI_SET_LATENCY	9
44 #define FTDI_GET_LATENCY	10
45 
46 #define DeviceOutVendor	((USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_DEVICE)<<8)
47 #define DeviceInVendor	((USB_DIR_IN |USB_TYPE_VENDOR|USB_RECIP_DEVICE)<<8)
48 
49 /* RESET */
50 
51 #define FTDI_RESET_SIO	0
52 #define FTDI_RESET_RX	1
53 #define FTDI_RESET_TX	2
54 
55 /* SET_MDM_CTRL */
56 
57 #define FTDI_DTR	1
58 #define FTDI_SET_DTR	(FTDI_DTR << 8)
59 #define FTDI_RTS	2
60 #define FTDI_SET_RTS	(FTDI_RTS << 8)
61 
62 /* SET_FLOW_CTRL */
63 
64 #define FTDI_RTS_CTS_HS		1
65 #define FTDI_DTR_DSR_HS		2
66 #define FTDI_XON_XOFF_HS	4
67 
68 /* SET_DATA */
69 
70 #define FTDI_PARITY	(0x7 << 8)
71 #define FTDI_ODD	(0x1 << 8)
72 #define FTDI_EVEN	(0x2 << 8)
73 #define FTDI_MARK	(0x3 << 8)
74 #define FTDI_SPACE	(0x4 << 8)
75 
76 #define FTDI_STOP	(0x3 << 11)
77 #define FTDI_STOP1	(0x0 << 11)
78 #define FTDI_STOP15	(0x1 << 11)
79 #define FTDI_STOP2	(0x2 << 11)
80 
81 /* GET_MDM_ST */
82 /* TODO: should be sent every 40ms */
83 #define FTDI_CTS  (1<<4)        // CTS line status
84 #define FTDI_DSR  (1<<5)        // DSR line status
85 #define FTDI_RI   (1<<6)        // RI line status
86 #define FTDI_RLSD (1<<7)        // Receive Line Signal Detect
87 
88 /* Status */
89 
90 #define FTDI_DR   (1<<0)        // Data Ready
91 #define FTDI_OE   (1<<1)        // Overrun Err
92 #define FTDI_PE   (1<<2)        // Parity Err
93 #define FTDI_FE   (1<<3)        // Framing Err
94 #define FTDI_BI   (1<<4)        // Break Interrupt
95 #define FTDI_THRE (1<<5)        // Transmitter Holding Register
96 #define FTDI_TEMT (1<<6)        // Transmitter Empty
97 #define FTDI_FIFO (1<<7)        // Error in FIFO
98 
99 typedef struct {
100     USBDevice dev;
101     USBEndpoint *intr;
102     uint8_t recv_buf[RECV_BUF];
103     uint16_t recv_ptr;
104     uint16_t recv_used;
105     uint8_t event_chr;
106     uint8_t error_chr;
107     uint8_t event_trigger;
108     QEMUSerialSetParams params;
109     int latency;        /* ms */
110     CharBackend cs;
111 } USBSerialState;
112 
113 #define TYPE_USB_SERIAL "usb-serial-dev"
114 #define USB_SERIAL_DEV(obj) OBJECT_CHECK(USBSerialState, (obj), TYPE_USB_SERIAL)
115 
116 enum {
117     STR_MANUFACTURER = 1,
118     STR_PRODUCT_SERIAL,
119     STR_PRODUCT_BRAILLE,
120     STR_SERIALNUMBER,
121 };
122 
123 static const USBDescStrings desc_strings = {
124     [STR_MANUFACTURER]    = "QEMU",
125     [STR_PRODUCT_SERIAL]  = "QEMU USB SERIAL",
126     [STR_PRODUCT_BRAILLE] = "QEMU USB BAUM BRAILLE",
127     [STR_SERIALNUMBER]    = "1",
128 };
129 
130 static const USBDescIface desc_iface0 = {
131     .bInterfaceNumber              = 0,
132     .bNumEndpoints                 = 2,
133     .bInterfaceClass               = 0xff,
134     .bInterfaceSubClass            = 0xff,
135     .bInterfaceProtocol            = 0xff,
136     .eps = (USBDescEndpoint[]) {
137         {
138             .bEndpointAddress      = USB_DIR_IN | 0x01,
139             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
140             .wMaxPacketSize        = 64,
141         },{
142             .bEndpointAddress      = USB_DIR_OUT | 0x02,
143             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
144             .wMaxPacketSize        = 64,
145         },
146     }
147 };
148 
149 static const USBDescDevice desc_device = {
150     .bcdUSB                        = 0x0200,
151     .bMaxPacketSize0               = 8,
152     .bNumConfigurations            = 1,
153     .confs = (USBDescConfig[]) {
154         {
155             .bNumInterfaces        = 1,
156             .bConfigurationValue   = 1,
157             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_WAKEUP,
158             .bMaxPower             = 50,
159             .nif = 1,
160             .ifs = &desc_iface0,
161         },
162     },
163 };
164 
165 static const USBDesc desc_serial = {
166     .id = {
167         .idVendor          = 0x0403,
168         .idProduct         = 0x6001,
169         .bcdDevice         = 0x0400,
170         .iManufacturer     = STR_MANUFACTURER,
171         .iProduct          = STR_PRODUCT_SERIAL,
172         .iSerialNumber     = STR_SERIALNUMBER,
173     },
174     .full = &desc_device,
175     .str  = desc_strings,
176 };
177 
178 static const USBDesc desc_braille = {
179     .id = {
180         .idVendor          = 0x0403,
181         .idProduct         = 0xfe72,
182         .bcdDevice         = 0x0400,
183         .iManufacturer     = STR_MANUFACTURER,
184         .iProduct          = STR_PRODUCT_BRAILLE,
185         .iSerialNumber     = STR_SERIALNUMBER,
186     },
187     .full = &desc_device,
188     .str  = desc_strings,
189 };
190 
191 static void usb_serial_reset(USBSerialState *s)
192 {
193     /* TODO: Set flow control to none */
194     s->event_chr = 0x0d;
195     s->event_trigger = 0;
196     s->recv_ptr = 0;
197     s->recv_used = 0;
198     /* TODO: purge in char driver */
199 }
200 
201 static void usb_serial_handle_reset(USBDevice *dev)
202 {
203     USBSerialState *s = (USBSerialState *)dev;
204 
205     DPRINTF("Reset\n");
206 
207     usb_serial_reset(s);
208     /* TODO: Reset char device, send BREAK? */
209 }
210 
211 static uint8_t usb_get_modem_lines(USBSerialState *s)
212 {
213     int flags;
214     uint8_t ret;
215 
216     if (qemu_chr_fe_ioctl(&s->cs,
217                           CHR_IOCTL_SERIAL_GET_TIOCM, &flags) == -ENOTSUP) {
218         return FTDI_CTS|FTDI_DSR|FTDI_RLSD;
219     }
220 
221     ret = 0;
222     if (flags & CHR_TIOCM_CTS)
223         ret |= FTDI_CTS;
224     if (flags & CHR_TIOCM_DSR)
225         ret |= FTDI_DSR;
226     if (flags & CHR_TIOCM_RI)
227         ret |= FTDI_RI;
228     if (flags & CHR_TIOCM_CAR)
229         ret |= FTDI_RLSD;
230 
231     return ret;
232 }
233 
234 static void usb_serial_handle_control(USBDevice *dev, USBPacket *p,
235                int request, int value, int index, int length, uint8_t *data)
236 {
237     USBSerialState *s = (USBSerialState *)dev;
238     int ret;
239 
240     DPRINTF("got control %x, value %x\n",request, value);
241     ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
242     if (ret >= 0) {
243         return;
244     }
245 
246     switch (request) {
247     case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
248         break;
249 
250         /* Class specific requests.  */
251     case DeviceOutVendor | FTDI_RESET:
252         switch (value) {
253         case FTDI_RESET_SIO:
254             usb_serial_reset(s);
255             break;
256         case FTDI_RESET_RX:
257             s->recv_ptr = 0;
258             s->recv_used = 0;
259             /* TODO: purge from char device */
260             break;
261         case FTDI_RESET_TX:
262             /* TODO: purge from char device */
263             break;
264         }
265         break;
266     case DeviceOutVendor | FTDI_SET_MDM_CTRL:
267     {
268         static int flags;
269         qemu_chr_fe_ioctl(&s->cs, CHR_IOCTL_SERIAL_GET_TIOCM, &flags);
270         if (value & FTDI_SET_RTS) {
271             if (value & FTDI_RTS)
272                 flags |= CHR_TIOCM_RTS;
273             else
274                 flags &= ~CHR_TIOCM_RTS;
275         }
276         if (value & FTDI_SET_DTR) {
277             if (value & FTDI_DTR)
278                 flags |= CHR_TIOCM_DTR;
279             else
280                 flags &= ~CHR_TIOCM_DTR;
281         }
282         qemu_chr_fe_ioctl(&s->cs, CHR_IOCTL_SERIAL_SET_TIOCM, &flags);
283         break;
284     }
285     case DeviceOutVendor | FTDI_SET_FLOW_CTRL:
286         /* TODO: ioctl */
287         break;
288     case DeviceOutVendor | FTDI_SET_BAUD: {
289         static const int subdivisors8[8] = { 0, 4, 2, 1, 3, 5, 6, 7 };
290         int subdivisor8 = subdivisors8[((value & 0xc000) >> 14)
291                                      | ((index & 1) << 2)];
292         int divisor = value & 0x3fff;
293 
294         /* chip special cases */
295         if (divisor == 1 && subdivisor8 == 0)
296             subdivisor8 = 4;
297         if (divisor == 0 && subdivisor8 == 0)
298             divisor = 1;
299 
300         s->params.speed = (48000000 / 2) / (8 * divisor + subdivisor8);
301         qemu_chr_fe_ioctl(&s->cs, CHR_IOCTL_SERIAL_SET_PARAMS, &s->params);
302         break;
303     }
304     case DeviceOutVendor | FTDI_SET_DATA:
305         switch (value & FTDI_PARITY) {
306             case 0:
307                 s->params.parity = 'N';
308                 break;
309             case FTDI_ODD:
310                 s->params.parity = 'O';
311                 break;
312             case FTDI_EVEN:
313                 s->params.parity = 'E';
314                 break;
315             default:
316                 DPRINTF("unsupported parity %d\n", value & FTDI_PARITY);
317                 goto fail;
318         }
319         switch (value & FTDI_STOP) {
320             case FTDI_STOP1:
321                 s->params.stop_bits = 1;
322                 break;
323             case FTDI_STOP2:
324                 s->params.stop_bits = 2;
325                 break;
326             default:
327                 DPRINTF("unsupported stop bits %d\n", value & FTDI_STOP);
328                 goto fail;
329         }
330         qemu_chr_fe_ioctl(&s->cs, CHR_IOCTL_SERIAL_SET_PARAMS, &s->params);
331         /* TODO: TX ON/OFF */
332         break;
333     case DeviceInVendor | FTDI_GET_MDM_ST:
334         data[0] = usb_get_modem_lines(s) | 1;
335         data[1] = 0;
336         p->actual_length = 2;
337         break;
338     case DeviceOutVendor | FTDI_SET_EVENT_CHR:
339         /* TODO: handle it */
340         s->event_chr = value;
341         break;
342     case DeviceOutVendor | FTDI_SET_ERROR_CHR:
343         /* TODO: handle it */
344         s->error_chr = value;
345         break;
346     case DeviceOutVendor | FTDI_SET_LATENCY:
347         s->latency = value;
348         break;
349     case DeviceInVendor | FTDI_GET_LATENCY:
350         data[0] = s->latency;
351         p->actual_length = 1;
352         break;
353     default:
354     fail:
355         DPRINTF("got unsupported/bogus control %x, value %x\n", request, value);
356         p->status = USB_RET_STALL;
357         break;
358     }
359 }
360 
361 static void usb_serial_handle_data(USBDevice *dev, USBPacket *p)
362 {
363     USBSerialState *s = (USBSerialState *)dev;
364     uint8_t devep = p->ep->nr;
365     struct iovec *iov;
366     uint8_t header[2];
367     int i, first_len, len;
368 
369     switch (p->pid) {
370     case USB_TOKEN_OUT:
371         if (devep != 2)
372             goto fail;
373         for (i = 0; i < p->iov.niov; i++) {
374             iov = p->iov.iov + i;
375             /* XXX this blocks entire thread. Rewrite to use
376              * qemu_chr_fe_write and background I/O callbacks */
377             qemu_chr_fe_write_all(&s->cs, iov->iov_base, iov->iov_len);
378         }
379         p->actual_length = p->iov.size;
380         break;
381 
382     case USB_TOKEN_IN:
383         if (devep != 1)
384             goto fail;
385         first_len = RECV_BUF - s->recv_ptr;
386         len = p->iov.size;
387         if (len <= 2) {
388             p->status = USB_RET_NAK;
389             break;
390         }
391         header[0] = usb_get_modem_lines(s) | 1;
392         /* We do not have the uart details */
393         /* handle serial break */
394         if (s->event_trigger && s->event_trigger & FTDI_BI) {
395             s->event_trigger &= ~FTDI_BI;
396             header[1] = FTDI_BI;
397             usb_packet_copy(p, header, 2);
398             break;
399         } else {
400             header[1] = 0;
401         }
402         len -= 2;
403         if (len > s->recv_used)
404             len = s->recv_used;
405         if (!len) {
406             p->status = USB_RET_NAK;
407             break;
408         }
409         if (first_len > len)
410             first_len = len;
411         usb_packet_copy(p, header, 2);
412         usb_packet_copy(p, s->recv_buf + s->recv_ptr, first_len);
413         if (len > first_len)
414             usb_packet_copy(p, s->recv_buf, len - first_len);
415         s->recv_used -= len;
416         s->recv_ptr = (s->recv_ptr + len) % RECV_BUF;
417         break;
418 
419     default:
420         DPRINTF("Bad token\n");
421     fail:
422         p->status = USB_RET_STALL;
423         break;
424     }
425 }
426 
427 static int usb_serial_can_read(void *opaque)
428 {
429     USBSerialState *s = opaque;
430 
431     if (!s->dev.attached) {
432         return 0;
433     }
434     return RECV_BUF - s->recv_used;
435 }
436 
437 static void usb_serial_read(void *opaque, const uint8_t *buf, int size)
438 {
439     USBSerialState *s = opaque;
440     int first_size, start;
441 
442     /* room in the buffer? */
443     if (size > (RECV_BUF - s->recv_used))
444         size = RECV_BUF - s->recv_used;
445 
446     start = s->recv_ptr + s->recv_used;
447     if (start < RECV_BUF) {
448         /* copy data to end of buffer */
449         first_size = RECV_BUF - start;
450         if (first_size > size)
451             first_size = size;
452 
453         memcpy(s->recv_buf + start, buf, first_size);
454 
455         /* wrap around to front if needed */
456         if (size > first_size)
457             memcpy(s->recv_buf, buf + first_size, size - first_size);
458     } else {
459         start -= RECV_BUF;
460         memcpy(s->recv_buf + start, buf, size);
461     }
462     s->recv_used += size;
463 
464     usb_wakeup(s->intr, 0);
465 }
466 
467 static void usb_serial_event(void *opaque, QEMUChrEvent event)
468 {
469     USBSerialState *s = opaque;
470 
471     switch (event) {
472         case CHR_EVENT_BREAK:
473             s->event_trigger |= FTDI_BI;
474             break;
475         case CHR_EVENT_OPENED:
476             if (!s->dev.attached) {
477                 usb_device_attach(&s->dev, &error_abort);
478             }
479             break;
480         case CHR_EVENT_CLOSED:
481             if (s->dev.attached) {
482                 usb_device_detach(&s->dev);
483             }
484             break;
485         case CHR_EVENT_MUX_IN:
486         case CHR_EVENT_MUX_OUT:
487             /* Ignore */
488             break;
489     }
490 }
491 
492 static void usb_serial_realize(USBDevice *dev, Error **errp)
493 {
494     USBSerialState *s = USB_SERIAL_DEV(dev);
495     Error *local_err = NULL;
496 
497     usb_desc_create_serial(dev);
498     usb_desc_init(dev);
499     dev->auto_attach = 0;
500 
501     if (!qemu_chr_fe_backend_connected(&s->cs)) {
502         error_setg(errp, "Property chardev is required");
503         return;
504     }
505 
506     usb_check_attach(dev, &local_err);
507     if (local_err) {
508         error_propagate(errp, local_err);
509         return;
510     }
511 
512     qemu_chr_fe_set_handlers(&s->cs, usb_serial_can_read, usb_serial_read,
513                              usb_serial_event, NULL, s, NULL, true);
514     usb_serial_handle_reset(dev);
515 
516     if (qemu_chr_fe_backend_open(&s->cs) && !dev->attached) {
517         usb_device_attach(dev, &error_abort);
518     }
519     s->intr = usb_ep_get(dev, USB_TOKEN_IN, 1);
520 }
521 
522 static USBDevice *usb_braille_init(USBBus *bus, const char *unused)
523 {
524     USBDevice *dev;
525     Chardev *cdrv;
526 
527     cdrv = qemu_chr_new("braille", "braille", NULL);
528     if (!cdrv)
529         return NULL;
530 
531     dev = usb_create(bus, "usb-braille");
532     qdev_prop_set_chr(&dev->qdev, "chardev", cdrv);
533     return dev;
534 }
535 
536 static const VMStateDescription vmstate_usb_serial = {
537     .name = "usb-serial",
538     .unmigratable = 1,
539 };
540 
541 static Property serial_properties[] = {
542     DEFINE_PROP_CHR("chardev", USBSerialState, cs),
543     DEFINE_PROP_END_OF_LIST(),
544 };
545 
546 static void usb_serial_dev_class_init(ObjectClass *klass, void *data)
547 {
548     DeviceClass *dc = DEVICE_CLASS(klass);
549     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
550 
551     uc->realize        = usb_serial_realize;
552     uc->handle_reset   = usb_serial_handle_reset;
553     uc->handle_control = usb_serial_handle_control;
554     uc->handle_data    = usb_serial_handle_data;
555     dc->vmsd = &vmstate_usb_serial;
556     set_bit(DEVICE_CATEGORY_INPUT, dc->categories);
557 }
558 
559 static const TypeInfo usb_serial_dev_type_info = {
560     .name = TYPE_USB_SERIAL,
561     .parent = TYPE_USB_DEVICE,
562     .instance_size = sizeof(USBSerialState),
563     .abstract = true,
564     .class_init = usb_serial_dev_class_init,
565 };
566 
567 static void usb_serial_class_initfn(ObjectClass *klass, void *data)
568 {
569     DeviceClass *dc = DEVICE_CLASS(klass);
570     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
571 
572     uc->product_desc   = "QEMU USB Serial";
573     uc->usb_desc       = &desc_serial;
574     device_class_set_props(dc, serial_properties);
575 }
576 
577 static const TypeInfo serial_info = {
578     .name          = "usb-serial",
579     .parent        = TYPE_USB_SERIAL,
580     .class_init    = usb_serial_class_initfn,
581 };
582 
583 static Property braille_properties[] = {
584     DEFINE_PROP_CHR("chardev", USBSerialState, cs),
585     DEFINE_PROP_END_OF_LIST(),
586 };
587 
588 static void usb_braille_class_initfn(ObjectClass *klass, void *data)
589 {
590     DeviceClass *dc = DEVICE_CLASS(klass);
591     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
592 
593     uc->product_desc   = "QEMU USB Braille";
594     uc->usb_desc       = &desc_braille;
595     device_class_set_props(dc, braille_properties);
596 }
597 
598 static const TypeInfo braille_info = {
599     .name          = "usb-braille",
600     .parent        = TYPE_USB_SERIAL,
601     .class_init    = usb_braille_class_initfn,
602 };
603 
604 static void usb_serial_register_types(void)
605 {
606     type_register_static(&usb_serial_dev_type_info);
607     type_register_static(&serial_info);
608     type_register_static(&braille_info);
609     usb_legacy_register("usb-braille", "braille", usb_braille_init);
610 }
611 
612 type_init(usb_serial_register_types)
613