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