xref: /openbmc/qemu/hw/usb/dev-serial.c (revision f7160f32)
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 (512 - (2 * 8))
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] = FTDI_THRE | FTDI_TEMT;
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_token_in(USBSerialState *s, USBPacket *p)
362 {
363     const int max_packet_size = desc_iface0.eps[0].wMaxPacketSize;
364     int packet_len;
365     uint8_t header[2];
366 
367     packet_len = p->iov.size;
368     if (packet_len <= 2) {
369         p->status = USB_RET_NAK;
370         return;
371     }
372 
373     header[0] = usb_get_modem_lines(s) | 1;
374     /* We do not have the uart details */
375     /* handle serial break */
376     if (s->event_trigger && s->event_trigger & FTDI_BI) {
377         s->event_trigger &= ~FTDI_BI;
378         header[1] = FTDI_BI;
379         usb_packet_copy(p, header, 2);
380         return;
381     } else {
382         header[1] = 0;
383     }
384 
385     if (!s->recv_used) {
386         p->status = USB_RET_NAK;
387         return;
388     }
389 
390     while (s->recv_used && packet_len > 2) {
391         int first_len, len;
392 
393         len = MIN(packet_len, max_packet_size);
394         len -= 2;
395         if (len > s->recv_used) {
396             len = s->recv_used;
397         }
398 
399         first_len = RECV_BUF - s->recv_ptr;
400         if (first_len > len) {
401             first_len = len;
402         }
403         usb_packet_copy(p, header, 2);
404         usb_packet_copy(p, s->recv_buf + s->recv_ptr, first_len);
405         if (len > first_len) {
406             usb_packet_copy(p, s->recv_buf, len - first_len);
407         }
408         s->recv_used -= len;
409         s->recv_ptr = (s->recv_ptr + len) % RECV_BUF;
410         packet_len -= len + 2;
411     }
412 
413     return;
414 }
415 
416 static void usb_serial_handle_data(USBDevice *dev, USBPacket *p)
417 {
418     USBSerialState *s = (USBSerialState *)dev;
419     uint8_t devep = p->ep->nr;
420     struct iovec *iov;
421     int i;
422 
423     switch (p->pid) {
424     case USB_TOKEN_OUT:
425         if (devep != 2)
426             goto fail;
427         for (i = 0; i < p->iov.niov; i++) {
428             iov = p->iov.iov + i;
429             /* XXX this blocks entire thread. Rewrite to use
430              * qemu_chr_fe_write and background I/O callbacks */
431             qemu_chr_fe_write_all(&s->cs, iov->iov_base, iov->iov_len);
432         }
433         p->actual_length = p->iov.size;
434         break;
435 
436     case USB_TOKEN_IN:
437         if (devep != 1)
438             goto fail;
439         usb_serial_token_in(s, p);
440         break;
441 
442     default:
443         DPRINTF("Bad token\n");
444     fail:
445         p->status = USB_RET_STALL;
446         break;
447     }
448 }
449 
450 static int usb_serial_can_read(void *opaque)
451 {
452     USBSerialState *s = opaque;
453 
454     if (!s->dev.attached) {
455         return 0;
456     }
457     return RECV_BUF - s->recv_used;
458 }
459 
460 static void usb_serial_read(void *opaque, const uint8_t *buf, int size)
461 {
462     USBSerialState *s = opaque;
463     int first_size, start;
464 
465     /* room in the buffer? */
466     if (size > (RECV_BUF - s->recv_used))
467         size = RECV_BUF - s->recv_used;
468 
469     start = s->recv_ptr + s->recv_used;
470     if (start < RECV_BUF) {
471         /* copy data to end of buffer */
472         first_size = RECV_BUF - start;
473         if (first_size > size)
474             first_size = size;
475 
476         memcpy(s->recv_buf + start, buf, first_size);
477 
478         /* wrap around to front if needed */
479         if (size > first_size)
480             memcpy(s->recv_buf, buf + first_size, size - first_size);
481     } else {
482         start -= RECV_BUF;
483         memcpy(s->recv_buf + start, buf, size);
484     }
485     s->recv_used += size;
486 
487     usb_wakeup(s->intr, 0);
488 }
489 
490 static void usb_serial_event(void *opaque, QEMUChrEvent event)
491 {
492     USBSerialState *s = opaque;
493 
494     switch (event) {
495         case CHR_EVENT_BREAK:
496             s->event_trigger |= FTDI_BI;
497             break;
498         case CHR_EVENT_OPENED:
499             if (!s->dev.attached) {
500                 usb_device_attach(&s->dev, &error_abort);
501             }
502             break;
503         case CHR_EVENT_CLOSED:
504             if (s->dev.attached) {
505                 usb_device_detach(&s->dev);
506             }
507             break;
508         case CHR_EVENT_MUX_IN:
509         case CHR_EVENT_MUX_OUT:
510             /* Ignore */
511             break;
512     }
513 }
514 
515 static void usb_serial_realize(USBDevice *dev, Error **errp)
516 {
517     USBSerialState *s = USB_SERIAL_DEV(dev);
518     Error *local_err = NULL;
519 
520     usb_desc_create_serial(dev);
521     usb_desc_init(dev);
522     dev->auto_attach = 0;
523 
524     if (!qemu_chr_fe_backend_connected(&s->cs)) {
525         error_setg(errp, "Property chardev is required");
526         return;
527     }
528 
529     usb_check_attach(dev, &local_err);
530     if (local_err) {
531         error_propagate(errp, local_err);
532         return;
533     }
534 
535     qemu_chr_fe_set_handlers(&s->cs, usb_serial_can_read, usb_serial_read,
536                              usb_serial_event, NULL, s, NULL, true);
537     usb_serial_handle_reset(dev);
538 
539     if (qemu_chr_fe_backend_open(&s->cs) && !dev->attached) {
540         usb_device_attach(dev, &error_abort);
541     }
542     s->intr = usb_ep_get(dev, USB_TOKEN_IN, 1);
543 }
544 
545 static USBDevice *usb_braille_init(const char *unused)
546 {
547     USBDevice *dev;
548     Chardev *cdrv;
549 
550     cdrv = qemu_chr_new("braille", "braille", NULL);
551     if (!cdrv)
552         return NULL;
553 
554     dev = usb_new("usb-braille");
555     qdev_prop_set_chr(&dev->qdev, "chardev", cdrv);
556     return dev;
557 }
558 
559 static const VMStateDescription vmstate_usb_serial = {
560     .name = "usb-serial",
561     .unmigratable = 1,
562 };
563 
564 static Property serial_properties[] = {
565     DEFINE_PROP_CHR("chardev", USBSerialState, cs),
566     DEFINE_PROP_END_OF_LIST(),
567 };
568 
569 static void usb_serial_dev_class_init(ObjectClass *klass, void *data)
570 {
571     DeviceClass *dc = DEVICE_CLASS(klass);
572     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
573 
574     uc->realize        = usb_serial_realize;
575     uc->handle_reset   = usb_serial_handle_reset;
576     uc->handle_control = usb_serial_handle_control;
577     uc->handle_data    = usb_serial_handle_data;
578     dc->vmsd = &vmstate_usb_serial;
579     set_bit(DEVICE_CATEGORY_INPUT, dc->categories);
580 }
581 
582 static const TypeInfo usb_serial_dev_type_info = {
583     .name = TYPE_USB_SERIAL,
584     .parent = TYPE_USB_DEVICE,
585     .instance_size = sizeof(USBSerialState),
586     .abstract = true,
587     .class_init = usb_serial_dev_class_init,
588 };
589 
590 static void usb_serial_class_initfn(ObjectClass *klass, void *data)
591 {
592     DeviceClass *dc = DEVICE_CLASS(klass);
593     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
594 
595     uc->product_desc   = "QEMU USB Serial";
596     uc->usb_desc       = &desc_serial;
597     device_class_set_props(dc, serial_properties);
598 }
599 
600 static const TypeInfo serial_info = {
601     .name          = "usb-serial",
602     .parent        = TYPE_USB_SERIAL,
603     .class_init    = usb_serial_class_initfn,
604 };
605 
606 static Property braille_properties[] = {
607     DEFINE_PROP_CHR("chardev", USBSerialState, cs),
608     DEFINE_PROP_END_OF_LIST(),
609 };
610 
611 static void usb_braille_class_initfn(ObjectClass *klass, void *data)
612 {
613     DeviceClass *dc = DEVICE_CLASS(klass);
614     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
615 
616     uc->product_desc   = "QEMU USB Braille";
617     uc->usb_desc       = &desc_braille;
618     device_class_set_props(dc, braille_properties);
619 }
620 
621 static const TypeInfo braille_info = {
622     .name          = "usb-braille",
623     .parent        = TYPE_USB_SERIAL,
624     .class_init    = usb_braille_class_initfn,
625 };
626 
627 static void usb_serial_register_types(void)
628 {
629     type_register_static(&usb_serial_dev_type_info);
630     type_register_static(&serial_info);
631     type_register_static(&braille_info);
632     usb_legacy_register("usb-braille", "braille", usb_braille_init);
633 }
634 
635 type_init(usb_serial_register_types)
636