/* * QEMU graphical console * * Copyright (c) 2004 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "vl.h" #define DEFAULT_BACKSCROLL 512 #define MAX_CONSOLES 12 #define RGBA(r, g, b, a) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b)) #define RGB(r, g, b) RGBA(r, g, b, 0xff) typedef struct TextCell { uint8_t ch; uint8_t bgcol:4; uint8_t fgcol:4; } TextCell; #define MAX_ESC_PARAMS 3 enum TTYState { TTY_STATE_NORM, TTY_STATE_ESC, TTY_STATE_CSI, }; struct TextConsole { int text_console; /* true if text console */ DisplayState *ds; int g_width, g_height; int width; int height; int total_height; int backscroll_height; int fgcol; int bgcol; int x, y; int y_displayed; int y_base; TextCell *cells; enum TTYState state; int esc_params[MAX_ESC_PARAMS]; int nb_esc_params; /* kbd read handler */ IOReadHandler *fd_read; void *fd_opaque; }; static TextConsole *active_console; static TextConsole *consoles[MAX_CONSOLES]; static int nb_consoles = 0; /* convert a RGBA color to a color index usable in graphic primitives */ static unsigned int vga_get_color(DisplayState *ds, unsigned int rgba) { unsigned int r, g, b, color; switch(ds->depth) { #if 0 case 8: r = (rgba >> 16) & 0xff; g = (rgba >> 8) & 0xff; b = (rgba) & 0xff; color = (rgb_to_index[r] * 6 * 6) + (rgb_to_index[g] * 6) + (rgb_to_index[b]); break; #endif case 15: r = (rgba >> 16) & 0xff; g = (rgba >> 8) & 0xff; b = (rgba) & 0xff; color = ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3); break; case 16: r = (rgba >> 16) & 0xff; g = (rgba >> 8) & 0xff; b = (rgba) & 0xff; color = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3); break; case 32: default: color = rgba; break; } return color; } static void vga_fill_rect (DisplayState *ds, int posx, int posy, int width, int height, uint32_t color) { uint8_t *d, *d1; int x, y, bpp; bpp = (ds->depth + 7) >> 3; d1 = ds->data + ds->linesize * posy + bpp * posx; for (y = 0; y < height; y++) { d = d1; switch(bpp) { case 1: for (x = 0; x < width; x++) { *((uint8_t *)d) = color; d++; } break; case 2: for (x = 0; x < width; x++) { *((uint16_t *)d) = color; d += 2; } break; case 4: for (x = 0; x < width; x++) { *((uint32_t *)d) = color; d += 4; } break; } d1 += ds->linesize; } } /* copy from (xs, ys) to (xd, yd) a rectangle of size (w, h) */ static void vga_bitblt(DisplayState *ds, int xs, int ys, int xd, int yd, int w, int h) { const uint8_t *s; uint8_t *d; int wb, y, bpp; bpp = (ds->depth + 7) >> 3; wb = w * bpp; if (yd <= ys) { s = ds->data + ds->linesize * ys + bpp * xs; d = ds->data + ds->linesize * yd + bpp * xd; for (y = 0; y < h; y++) { memmove(d, s, wb); d += ds->linesize; s += ds->linesize; } } else { s = ds->data + ds->linesize * (ys + h - 1) + bpp * xs; d = ds->data + ds->linesize * (yd + h - 1) + bpp * xd; for (y = 0; y < h; y++) { memmove(d, s, wb); d -= ds->linesize; s -= ds->linesize; } } } /***********************************************************/ /* basic char display */ #define FONT_HEIGHT 16 #define FONT_WIDTH 8 #include "vgafont.h" #define cbswap_32(__x) \ ((uint32_t)( \ (((uint32_t)(__x) & (uint32_t)0x000000ffUL) << 24) | \ (((uint32_t)(__x) & (uint32_t)0x0000ff00UL) << 8) | \ (((uint32_t)(__x) & (uint32_t)0x00ff0000UL) >> 8) | \ (((uint32_t)(__x) & (uint32_t)0xff000000UL) >> 24) )) #ifdef WORDS_BIGENDIAN #define PAT(x) x #else #define PAT(x) cbswap_32(x) #endif static const uint32_t dmask16[16] = { PAT(0x00000000), PAT(0x000000ff), PAT(0x0000ff00), PAT(0x0000ffff), PAT(0x00ff0000), PAT(0x00ff00ff), PAT(0x00ffff00), PAT(0x00ffffff), PAT(0xff000000), PAT(0xff0000ff), PAT(0xff00ff00), PAT(0xff00ffff), PAT(0xffff0000), PAT(0xffff00ff), PAT(0xffffff00), PAT(0xffffffff), }; static const uint32_t dmask4[4] = { PAT(0x00000000), PAT(0x0000ffff), PAT(0xffff0000), PAT(0xffffffff), }; static uint32_t color_table[8]; static const uint32_t color_table_rgb[8] = { RGB(0x00, 0x00, 0x00), RGB(0xff, 0x00, 0x00), RGB(0x00, 0xff, 0x00), RGB(0xff, 0xff, 0x00), RGB(0x00, 0x00, 0xff), RGB(0xff, 0x00, 0xff), RGB(0x00, 0xff, 0xff), RGB(0xff, 0xff, 0xff), }; static inline unsigned int col_expand(DisplayState *ds, unsigned int col) { switch(ds->depth) { case 8: col |= col << 8; col |= col << 16; break; case 15: case 16: col |= col << 16; break; default: break; } return col; } static void vga_putcharxy(DisplayState *ds, int x, int y, int ch, unsigned int fgcol, unsigned int bgcol) { uint8_t *d; const uint8_t *font_ptr; unsigned int font_data, linesize, xorcol, bpp; int i; bpp = (ds->depth + 7) >> 3; d = ds->data + ds->linesize * y * FONT_HEIGHT + bpp * x * FONT_WIDTH; linesize = ds->linesize; font_ptr = vgafont16 + FONT_HEIGHT * ch; xorcol = bgcol ^ fgcol; switch(ds->depth) { case 8: for(i = 0; i < FONT_HEIGHT; i++) { font_data = *font_ptr++; ((uint32_t *)d)[0] = (dmask16[(font_data >> 4)] & xorcol) ^ bgcol; ((uint32_t *)d)[1] = (dmask16[(font_data >> 0) & 0xf] & xorcol) ^ bgcol; d += linesize; } break; case 16: case 15: for(i = 0; i < FONT_HEIGHT; i++) { font_data = *font_ptr++; ((uint32_t *)d)[0] = (dmask4[(font_data >> 6)] & xorcol) ^ bgcol; ((uint32_t *)d)[1] = (dmask4[(font_data >> 4) & 3] & xorcol) ^ bgcol; ((uint32_t *)d)[2] = (dmask4[(font_data >> 2) & 3] & xorcol) ^ bgcol; ((uint32_t *)d)[3] = (dmask4[(font_data >> 0) & 3] & xorcol) ^ bgcol; d += linesize; } break; case 32: for(i = 0; i < FONT_HEIGHT; i++) { font_data = *font_ptr++; ((uint32_t *)d)[0] = (-((font_data >> 7)) & xorcol) ^ bgcol; ((uint32_t *)d)[1] = (-((font_data >> 6) & 1) & xorcol) ^ bgcol; ((uint32_t *)d)[2] = (-((font_data >> 5) & 1) & xorcol) ^ bgcol; ((uint32_t *)d)[3] = (-((font_data >> 4) & 1) & xorcol) ^ bgcol; ((uint32_t *)d)[4] = (-((font_data >> 3) & 1) & xorcol) ^ bgcol; ((uint32_t *)d)[5] = (-((font_data >> 2) & 1) & xorcol) ^ bgcol; ((uint32_t *)d)[6] = (-((font_data >> 1) & 1) & xorcol) ^ bgcol; ((uint32_t *)d)[7] = (-((font_data >> 0) & 1) & xorcol) ^ bgcol; d += linesize; } break; } } static void text_console_resize(TextConsole *s) { TextCell *cells, *c, *c1; int w1, x, y, last_width; last_width = s->width; s->width = s->g_width / FONT_WIDTH; s->height = s->g_height / FONT_HEIGHT; w1 = last_width; if (s->width < w1) w1 = s->width; cells = qemu_malloc(s->width * s->total_height * sizeof(TextCell)); for(y = 0; y < s->total_height; y++) { c = &cells[y * s->width]; if (w1 > 0) { c1 = &s->cells[y * last_width]; for(x = 0; x < w1; x++) { *c++ = *c1++; } } for(x = w1; x < s->width; x++) { c->ch = ' '; c->fgcol = 7; c->bgcol = 0; c++; } } qemu_free(s->cells); s->cells = cells; } static void update_xy(TextConsole *s, int x, int y) { TextCell *c; int y1, y2; if (s == active_console) { y1 = (s->y_base + y) % s->total_height; y2 = y1 - s->y_displayed; if (y2 < 0) y2 += s->total_height; if (y2 < s->height) { c = &s->cells[y1 * s->width + x]; vga_putcharxy(s->ds, x, y2, c->ch, color_table[c->fgcol], color_table[c->bgcol]); dpy_update(s->ds, x * FONT_WIDTH, y2 * FONT_HEIGHT, FONT_WIDTH, FONT_HEIGHT); } } } static void console_show_cursor(TextConsole *s, int show) { TextCell *c; int y, y1; if (s == active_console) { y1 = (s->y_base + s->y) % s->total_height; y = y1 - s->y_displayed; if (y < 0) y += s->total_height; if (y < s->height) { c = &s->cells[y1 * s->width + s->x]; if (show) { vga_putcharxy(s->ds, s->x, y, c->ch, color_table[0], color_table[7]); } else { vga_putcharxy(s->ds, s->x, y, c->ch, color_table[c->fgcol], color_table[c->bgcol]); } dpy_update(s->ds, s->x * FONT_WIDTH, y * FONT_HEIGHT, FONT_WIDTH, FONT_HEIGHT); } } } static void console_refresh(TextConsole *s) { TextCell *c; int x, y, y1; if (s != active_console) return; vga_fill_rect(s->ds, 0, 0, s->ds->width, s->ds->height, color_table[0]); y1 = s->y_displayed; for(y = 0; y < s->height; y++) { c = s->cells + y1 * s->width; for(x = 0; x < s->width; x++) { vga_putcharxy(s->ds, x, y, c->ch, color_table[c->fgcol], color_table[c->bgcol]); c++; } if (++y1 == s->total_height) y1 = 0; } dpy_update(s->ds, 0, 0, s->ds->width, s->ds->height); console_show_cursor(s, 1); } static void console_scroll(int ydelta) { TextConsole *s; int i, y1; s = active_console; if (!s || !s->text_console) return; if (ydelta > 0) { for(i = 0; i < ydelta; i++) { if (s->y_displayed == s->y_base) break; if (++s->y_displayed == s->total_height) s->y_displayed = 0; } } else { ydelta = -ydelta; i = s->backscroll_height; if (i > s->total_height - s->height) i = s->total_height - s->height; y1 = s->y_base - i; if (y1 < 0) y1 += s->total_height; for(i = 0; i < ydelta; i++) { if (s->y_displayed == y1) break; if (--s->y_displayed < 0) s->y_displayed = s->total_height - 1; } } console_refresh(s); } static void console_put_lf(TextConsole *s) { TextCell *c; int x, y1; s->x = 0; s->y++; if (s->y >= s->height) { s->y = s->height - 1; if (s->y_displayed == s->y_base) { if (++s->y_displayed == s->total_height) s->y_displayed = 0; } if (++s->y_base == s->total_height) s->y_base = 0; if (s->backscroll_height < s->total_height) s->backscroll_height++; y1 = (s->y_base + s->height - 1) % s->total_height; c = &s->cells[y1 * s->width]; for(x = 0; x < s->width; x++) { c->ch = ' '; c->fgcol = s->fgcol; c->bgcol = s->bgcol; c++; } if (s == active_console && s->y_displayed == s->y_base) { vga_bitblt(s->ds, 0, FONT_HEIGHT, 0, 0, s->width * FONT_WIDTH, (s->height - 1) * FONT_HEIGHT); vga_fill_rect(s->ds, 0, (s->height - 1) * FONT_HEIGHT, s->width * FONT_WIDTH, FONT_HEIGHT, color_table[s->bgcol]); dpy_update(s->ds, 0, 0, s->width * FONT_WIDTH, s->height * FONT_HEIGHT); } } } static void console_putchar(TextConsole *s, int ch) { TextCell *c; int y1, i, x; switch(s->state) { case TTY_STATE_NORM: switch(ch) { case '\r': s->x = 0; break; case '\n': console_put_lf(s); break; case 27: s->state = TTY_STATE_ESC; break; default: y1 = (s->y_base + s->y) % s->total_height; c = &s->cells[y1 * s->width + s->x]; c->ch = ch; c->fgcol = s->fgcol; c->bgcol = s->bgcol; update_xy(s, s->x, s->y); s->x++; if (s->x >= s->width) console_put_lf(s); break; } break; case TTY_STATE_ESC: if (ch == '[') { for(i=0;iesc_params[i] = 0; s->nb_esc_params = 0; s->state = TTY_STATE_CSI; } else { s->state = TTY_STATE_NORM; } break; case TTY_STATE_CSI: if (ch >= '0' && ch <= '9') { if (s->nb_esc_params < MAX_ESC_PARAMS) { s->esc_params[s->nb_esc_params] = s->esc_params[s->nb_esc_params] * 10 + ch - '0'; } } else { s->nb_esc_params++; if (ch == ';') break; s->state = TTY_STATE_NORM; switch(ch) { case 'D': if (s->x > 0) s->x--; break; case 'C': if (s->x < (s->width - 1)) s->x++; break; case 'K': /* clear to eol */ y1 = (s->y_base + s->y) % s->total_height; for(x = s->x; x < s->width; x++) { c = &s->cells[y1 * s->width + x]; c->ch = ' '; c->fgcol = s->fgcol; c->bgcol = s->bgcol; c++; update_xy(s, x, s->y); } break; default: break; } break; } } } void console_select(unsigned int index) { TextConsole *s; if (index >= MAX_CONSOLES) return; s = consoles[index]; if (s) { active_console = s; if (s->text_console) { if (s->g_width != s->ds->width || s->g_height != s->ds->height) { s->g_width = s->ds->width; s->g_height = s->ds->height; text_console_resize(s); } console_refresh(s); } } } static int console_puts(CharDriverState *chr, const uint8_t *buf, int len) { TextConsole *s = chr->opaque; int i; console_show_cursor(s, 0); for(i = 0; i < len; i++) { console_putchar(s, buf[i]); } console_show_cursor(s, 1); return len; } static void console_chr_add_read_handler(CharDriverState *chr, IOCanRWHandler *fd_can_read, IOReadHandler *fd_read, void *opaque) { TextConsole *s = chr->opaque; s->fd_read = fd_read; s->fd_opaque = opaque; } static void console_send_event(CharDriverState *chr, int event) { TextConsole *s = chr->opaque; int i; if (event == CHR_EVENT_FOCUS) { for(i = 0; i < nb_consoles; i++) { if (consoles[i] == s) { console_select(i); break; } } } } /* called when an ascii key is pressed */ void kbd_put_keysym(int keysym) { TextConsole *s; uint8_t buf[16], *q; int c; s = active_console; if (!s || !s->text_console) return; switch(keysym) { case QEMU_KEY_CTRL_UP: console_scroll(-1); break; case QEMU_KEY_CTRL_DOWN: console_scroll(1); break; case QEMU_KEY_CTRL_PAGEUP: console_scroll(-10); break; case QEMU_KEY_CTRL_PAGEDOWN: console_scroll(10); break; default: if (s->fd_read) { /* convert the QEMU keysym to VT100 key string */ q = buf; if (keysym >= 0xe100 && keysym <= 0xe11f) { *q++ = '\033'; *q++ = '['; c = keysym - 0xe100; if (c >= 10) *q++ = '0' + (c / 10); *q++ = '0' + (c % 10); *q++ = '~'; } else if (keysym >= 0xe120 && keysym <= 0xe17f) { *q++ = '\033'; *q++ = '['; *q++ = keysym & 0xff; } else { *q++ = keysym; } s->fd_read(s->fd_opaque, buf, q - buf); } break; } } TextConsole *graphic_console_init(DisplayState *ds) { TextConsole *s; if (nb_consoles >= MAX_CONSOLES) return NULL; s = qemu_mallocz(sizeof(TextConsole)); if (!s) { return NULL; } if (!active_console) active_console = s; s->ds = ds; consoles[nb_consoles++] = s; return s; } int is_active_console(TextConsole *s) { return s == active_console; } CharDriverState *text_console_init(DisplayState *ds) { CharDriverState *chr; TextConsole *s; int i; static int color_inited; chr = qemu_mallocz(sizeof(CharDriverState)); if (!chr) return NULL; s = graphic_console_init(ds); if (!s) { free(chr); return NULL; } s->text_console = 1; chr->opaque = s; chr->chr_write = console_puts; chr->chr_add_read_handler = console_chr_add_read_handler; chr->chr_send_event = console_send_event; if (!color_inited) { color_inited = 1; for(i = 0; i < 8; i++) { color_table[i] = col_expand(s->ds, vga_get_color(s->ds, color_table_rgb[i])); } } s->y_displayed = 0; s->y_base = 0; s->total_height = DEFAULT_BACKSCROLL; s->x = 0; s->y = 0; s->fgcol = 7; s->bgcol = 0; s->g_width = s->ds->width; s->g_height = s->ds->height; text_console_resize(s); return chr; } ' href='#n493'>493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
/*
    ChibiOS - Copyright (C) 2006..2018 Giovanni Di Sirio

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

/**
 * @file    hal_usb.c
 * @brief   USB Driver code.
 *
 * @addtogroup USB
 * @{
 */

#include <string.h>

#include "hal.h"

#if (HAL_USE_USB == TRUE) || defined(__DOXYGEN__)

/*===========================================================================*/
/* Driver local definitions.                                                 */
/*===========================================================================*/

/*===========================================================================*/
/* Driver exported variables.                                                */
/*===========================================================================*/

/*===========================================================================*/
/* Driver local variables and types.                                         */
/*===========================================================================*/

static const uint8_t zero_status[] = {0x00, 0x00};
static const uint8_t active_status[] ={0x00, 0x00};
static const uint8_t halted_status[] = {0x01, 0x00};

/*===========================================================================*/
/* Driver local functions.                                                   */
/*===========================================================================*/

static uint16_t get_hword(uint8_t *p) {
  uint16_t hw;

  hw  = (uint16_t)*p++;
  hw |= (uint16_t)*p << 8U;
  return hw;
}

/**
 * @brief  SET ADDRESS transaction callback.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 */
static void set_address(USBDriver *usbp) {

  usbp->address = usbp->setup[2];
  usb_lld_set_address(usbp);
  _usb_isr_invoke_event_cb(usbp, USB_EVENT_ADDRESS);
  usbp->state = USB_SELECTED;
}

/**
 * @brief   Standard requests handler.
 * @details This is the standard requests default handler, most standard
 *          requests are handled here, the user can override the standard
 *          handling using the @p requests_hook_cb hook in the
 *          @p USBConfig structure.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 * @return              The request handling exit code.
 * @retval false        Request not recognized by the handler or error.
 * @retval true         Request handled.
 */
static bool default_handler(USBDriver *usbp) {
  const USBDescriptor *dp;

  /* Decoding the request.*/
  switch ((((uint32_t)usbp->setup[0] & (USB_RTYPE_RECIPIENT_MASK |
                                        USB_RTYPE_TYPE_MASK)) |
           ((uint32_t)usbp->setup[1] << 8U))) {
  case (uint32_t)USB_RTYPE_RECIPIENT_DEVICE | ((uint32_t)USB_REQ_GET_STATUS << 8):
    /* Just returns the current status word.*/
    usbSetupTransfer(usbp, (uint8_t *)&usbp->status, 2, NULL);
    return true;
  case (uint32_t)USB_RTYPE_RECIPIENT_DEVICE | ((uint32_t)USB_REQ_CLEAR_FEATURE << 8):
    /* Only the DEVICE_REMOTE_WAKEUP is handled here, any other feature
       number is handled as an error.*/
    if (usbp->setup[2] == USB_FEATURE_DEVICE_REMOTE_WAKEUP) {
      usbp->status &= ~2U;
      usbSetupTransfer(usbp, NULL, 0, NULL);
      return true;
    }
    return false;
  case (uint32_t)USB_RTYPE_RECIPIENT_DEVICE | ((uint32_t)USB_REQ_SET_FEATURE << 8):
    /* Only the DEVICE_REMOTE_WAKEUP is handled here, any other feature
       number is handled as an error.*/
    if (usbp->setup[2] == USB_FEATURE_DEVICE_REMOTE_WAKEUP) {
      usbp->status |= 2U;
      usbSetupTransfer(usbp, NULL, 0, NULL);
      return true;
    }
    return false;
  case (uint32_t)USB_RTYPE_RECIPIENT_DEVICE | ((uint32_t)USB_REQ_SET_ADDRESS << 8):
    /* The SET_ADDRESS handling can be performed here or postponed after
       the status packed depending on the USB_SET_ADDRESS_MODE low
       driver setting.*/
#if USB_SET_ADDRESS_MODE == USB_EARLY_SET_ADDRESS
    if ((usbp->setup[0] == USB_RTYPE_RECIPIENT_DEVICE) &&
        (usbp->setup[1] == USB_REQ_SET_ADDRESS)) {
      set_address(usbp);
    }
    usbSetupTransfer(usbp, NULL, 0, NULL);
#else
    usbSetupTransfer(usbp, NULL, 0, set_address);
#endif
    return true;
  case (uint32_t)USB_RTYPE_RECIPIENT_DEVICE | ((uint32_t)USB_REQ_GET_DESCRIPTOR << 8):
  case (uint32_t)USB_RTYPE_RECIPIENT_INTERFACE | ((uint32_t)USB_REQ_GET_DESCRIPTOR << 8):
    /* Handling descriptor requests from the host.*/
    dp = usbp->config->get_descriptor_cb(usbp, usbp->setup[3],
                                         usbp->setup[2],
                                         get_hword(&usbp->setup[4]));
    if (dp == NULL) {
      return false;
    }
    /*lint -save -e9005 [11.8] Removing const is fine.*/
    usbSetupTransfer(usbp, (uint8_t *)dp->ud_string, dp->ud_size, NULL);
    /*lint -restore*/
    return true;
  case (uint32_t)USB_RTYPE_RECIPIENT_DEVICE | ((uint32_t)USB_REQ_GET_CONFIGURATION << 8):
    /* Returning the last selected configuration.*/
    usbSetupTransfer(usbp, &usbp->configuration, 1, NULL);
    return true;
  case (uint32_t)USB_RTYPE_RECIPIENT_DEVICE | ((uint32_t)USB_REQ_SET_CONFIGURATION << 8):
#if defined(USB_SET_CONFIGURATION_OLD_BEHAVIOR)
    /* Handling configuration selection from the host only if it is different
       from the current configuration.*/
    if (usbp->configuration != usbp->setup[2])
#endif
    {
      /* If the USB device is already active then we have to perform the clear
         procedure on the current configuration.*/
      if (usbp->state == USB_ACTIVE) {
        /* Current configuration cleared.*/
        osalSysLockFromISR ();
        usbDisableEndpointsI(usbp);
        osalSysUnlockFromISR ();
        usbp->configuration = 0U;
        usbp->state = USB_SELECTED;
        _usb_isr_invoke_event_cb(usbp, USB_EVENT_UNCONFIGURED);
      }
      if (usbp->setup[2] != 0U) {
        /* New configuration.*/
        usbp->configuration = usbp->setup[2];
        usbp->state = USB_ACTIVE;
        _usb_isr_invoke_event_cb(usbp, USB_EVENT_CONFIGURED);
      }
    }
    usbSetupTransfer(usbp, NULL, 0, NULL);
    return true;
  case (uint32_t)USB_RTYPE_RECIPIENT_INTERFACE | ((uint32_t)USB_REQ_GET_STATUS << 8):
  case (uint32_t)USB_RTYPE_RECIPIENT_ENDPOINT | ((uint32_t)USB_REQ_SYNCH_FRAME << 8):
    /* Just sending two zero bytes, the application can change the behavior
       using a hook..*/
    /*lint -save -e9005 [11.8] Removing const is fine.*/
    usbSetupTransfer(usbp, (uint8_t *)zero_status, 2, NULL);
    /*lint -restore*/
    return true;
  case (uint32_t)USB_RTYPE_RECIPIENT_ENDPOINT | ((uint32_t)USB_REQ_GET_STATUS << 8):
    /* Sending the EP status.*/
    if ((usbp->setup[4] & 0x80U) != 0U) {
      switch (usb_lld_get_status_in(usbp, usbp->setup[4] & 0x0FU)) {
      case EP_STATUS_STALLED:
        /*lint -save -e9005 [11.8] Removing const is fine.*/
        usbSetupTransfer(usbp, (uint8_t *)halted_status, 2, NULL);
        /*lint -restore*/
        return true;
      case EP_STATUS_ACTIVE:
        /*lint -save -e9005 [11.8] Removing const is fine.*/
        usbSetupTransfer(usbp, (uint8_t *)active_status, 2, NULL);
        /*lint -restore*/
        return true;
      case EP_STATUS_DISABLED:
      default:
        return false;
      }
    }
    else {
      switch (usb_lld_get_status_out(usbp, usbp->setup[4] & 0x0FU)) {
      case EP_STATUS_STALLED:
        /*lint -save -e9005 [11.8] Removing const is fine.*/
        usbSetupTransfer(usbp, (uint8_t *)halted_status, 2, NULL);
        /*lint -restore*/
        return true;
      case EP_STATUS_ACTIVE:
        /*lint -save -e9005 [11.8] Removing const is fine.*/
        usbSetupTransfer(usbp, (uint8_t *)active_status, 2, NULL);
        /*lint -restore*/
        return true;
      case EP_STATUS_DISABLED:
      default:
        return false;
      }
    }
  case (uint32_t)USB_RTYPE_RECIPIENT_ENDPOINT | ((uint32_t)USB_REQ_CLEAR_FEATURE << 8):
    /* Only ENDPOINT_HALT is handled as feature.*/
    if (usbp->setup[2] != USB_FEATURE_ENDPOINT_HALT) {
      return false;
    }
    /* Clearing the EP status, not valid for EP0, it is ignored in that case.*/
    if ((usbp->setup[4] & 0x0FU) != 0U) {
      if ((usbp->setup[4] & 0x80U) != 0U) {
        usb_lld_clear_in(usbp, usbp->setup[4] & 0x0FU);
      }
      else {
        usb_lld_clear_out(usbp, usbp->setup[4] & 0x0FU);
      }
    }
    usbSetupTransfer(usbp, NULL, 0, NULL);
    return true;
  case (uint32_t)USB_RTYPE_RECIPIENT_ENDPOINT | ((uint32_t)USB_REQ_SET_FEATURE << 8):
    /* Only ENDPOINT_HALT is handled as feature.*/
    if (usbp->setup[2] != USB_FEATURE_ENDPOINT_HALT) {
      return false;
    }
    /* Stalling the EP, not valid for EP0, it is ignored in that case.*/
    if ((usbp->setup[4] & 0x0FU) != 0U) {
      if ((usbp->setup[4] & 0x80U) != 0U) {
        usb_lld_stall_in(usbp, usbp->setup[4] & 0x0FU);
      }
      else {
        usb_lld_stall_out(usbp, usbp->setup[4] & 0x0FU);
      }
    }
    usbSetupTransfer(usbp, NULL, 0, NULL);
    return true;
  case (uint32_t)USB_RTYPE_RECIPIENT_DEVICE | ((uint32_t)USB_REQ_SET_DESCRIPTOR << 8):
  case (uint32_t)USB_RTYPE_RECIPIENT_INTERFACE | ((uint32_t)USB_REQ_CLEAR_FEATURE << 8):
  case (uint32_t)USB_RTYPE_RECIPIENT_INTERFACE | ((uint32_t)USB_REQ_SET_FEATURE << 8):
  case (uint32_t)USB_RTYPE_RECIPIENT_INTERFACE | ((uint32_t)USB_REQ_GET_INTERFACE << 8):
  case (uint32_t)USB_RTYPE_RECIPIENT_INTERFACE | ((uint32_t)USB_REQ_SET_INTERFACE << 8):
    /* All the above requests are not handled here, if you need them then
       use the hook mechanism and provide handling.*/
  default:
    return false;
  }
}

/*===========================================================================*/
/* Driver exported functions.                                                */
/*===========================================================================*/

/**
 * @brief   USB Driver initialization.
 * @note    This function is implicitly invoked by @p halInit(), there is
 *          no need to explicitly initialize the driver.
 *
 * @init
 */
void usbInit(void) {

  usb_lld_init();
}

/**
 * @brief   Initializes the standard part of a @p USBDriver structure.
 *
 * @param[out] usbp     pointer to the @p USBDriver object
 *
 * @init
 */
void usbObjectInit(USBDriver *usbp) {
  unsigned i;

  usbp->state        = USB_STOP;
  usbp->config       = NULL;
  for (i = 0; i < (unsigned)USB_MAX_ENDPOINTS; i++) {
    usbp->in_params[i]  = NULL;
    usbp->out_params[i] = NULL;
  }
  usbp->transmitting = 0;
  usbp->receiving    = 0;
}

/**
 * @brief   Configures and activates the USB peripheral.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 * @param[in] config    pointer to the @p USBConfig object
 *
 * @api
 */
void usbStart(USBDriver *usbp, const USBConfig *config) {
  unsigned i;

  osalDbgCheck((usbp != NULL) && (config != NULL));

  osalSysLock();
  osalDbgAssert((usbp->state == USB_STOP) || (usbp->state == USB_READY),
                "invalid state");
  usbp->config = config;
  for (i = 0; i <= (unsigned)USB_MAX_ENDPOINTS; i++) {
    usbp->epc[i] = NULL;
  }
  usb_lld_start(usbp);
  usbp->state = USB_READY;
  osalSysUnlock();
}

/**
 * @brief   Deactivates the USB peripheral.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 *
 * @api
 */
void usbStop(USBDriver *usbp) {
  unsigned i;

  osalDbgCheck(usbp != NULL);

  osalSysLock();

  osalDbgAssert((usbp->state == USB_STOP) || (usbp->state == USB_READY) ||
                (usbp->state == USB_SELECTED) || (usbp->state == USB_ACTIVE) ||
                (usbp->state == USB_SUSPENDED),
                "invalid state");

  usb_lld_stop(usbp);
  usbp->config = NULL;
  usbp->state  = USB_STOP;

  /* Resetting all ongoing synchronous operations.*/
  for (i = 0; i <= (unsigned)USB_MAX_ENDPOINTS; i++) {
#if USB_USE_WAIT == TRUE
    if (usbp->epc[i] != NULL) {
      if (usbp->epc[i]->in_state != NULL) {
        osalThreadResumeI(&usbp->epc[i]->in_state->thread, MSG_RESET);
      }
      if (usbp->epc[i]->out_state != NULL) {
        osalThreadResumeI(&usbp->epc[i]->out_state->thread, MSG_RESET);
      }
    }
#endif
    usbp->epc[i] = NULL;
  }
  osalOsRescheduleS();

  osalSysUnlock();
}

/**
 * @brief   Enables an endpoint.
 * @details This function enables an endpoint, both IN and/or OUT directions
 *          depending on the configuration structure.
 * @note    This function must be invoked in response of a SET_CONFIGURATION
 *          or SET_INTERFACE message.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 * @param[in] ep        endpoint number
 * @param[in] epcp      the endpoint configuration
 *
 * @iclass
 */
void usbInitEndpointI(USBDriver *usbp, usbep_t ep,
                      const USBEndpointConfig *epcp) {

  osalDbgCheckClassI();
  osalDbgCheck((usbp != NULL) && (epcp != NULL));
  osalDbgAssert(usbp->state == USB_ACTIVE,
                "invalid state");
  osalDbgAssert(usbp->epc[ep] == NULL, "already initialized");

  /* Logically enabling the endpoint in the USBDriver structure.*/
  usbp->epc[ep] = epcp;

  /* Clearing the state structures, custom fields as well.*/
  if (epcp->in_state != NULL) {
    memset(epcp->in_state, 0, sizeof(USBInEndpointState));
  }
  if (epcp->out_state != NULL) {
    memset(epcp->out_state, 0, sizeof(USBOutEndpointState));
  }

  /* Low level endpoint activation.*/
  usb_lld_init_endpoint(usbp, ep);
}

/**
 * @brief   Disables all the active endpoints.
 * @details This function disables all the active endpoints except the
 *          endpoint zero.
 * @note    This function must be invoked in response of a SET_CONFIGURATION
 *          message with configuration number zero.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 *
 * @iclass
 */
void usbDisableEndpointsI(USBDriver *usbp) {
  unsigned i;

  osalDbgCheckClassI();
  osalDbgCheck(usbp != NULL);
  osalDbgAssert(usbp->state == USB_ACTIVE, "invalid state");

  usbp->transmitting &= 1U;
  usbp->receiving    &= 1U;

  for (i = 1; i <= (unsigned)USB_MAX_ENDPOINTS; i++) {
#if USB_USE_WAIT == TRUE
    /* Signaling the event to threads waiting on endpoints.*/
    if (usbp->epc[i] != NULL) {
      if (usbp->epc[i]->in_state != NULL) {
        osalThreadResumeI(&usbp->epc[i]->in_state->thread, MSG_RESET);
      }
      if (usbp->epc[i]->out_state != NULL) {
        osalThreadResumeI(&usbp->epc[i]->out_state->thread, MSG_RESET);
      }
    }
#endif
    usbp->epc[i] = NULL;
  }

  /* Low level endpoints deactivation.*/
  usb_lld_disable_endpoints(usbp);
}

/**
 * @brief   Starts a receive transaction on an OUT endpoint.
 * @note    This function is meant to be called from ISR context outside
 *          critical zones because there is a potentially slow operation
 *          inside.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 * @param[in] ep        endpoint number
 * @param[out] buf      buffer where to copy the received data
 * @param[in] n         transaction size. It is recommended a multiple of
 *                      the packet size because the excess is discarded.
 *
 * @iclass
 */
void usbStartReceiveI(USBDriver *usbp, usbep_t ep,
                      uint8_t *buf, size_t n) {
  USBOutEndpointState *osp;

  osalDbgCheckClassI();
  osalDbgCheck((usbp != NULL) && (ep <= (usbep_t)USB_MAX_ENDPOINTS));
  osalDbgAssert(!usbGetReceiveStatusI(usbp, ep), "already receiving");

  /* Marking the endpoint as active.*/
  usbp->receiving |= (uint16_t)((unsigned)1U << (unsigned)ep);

  /* Setting up the transfer.*/
  /*lint -save -e661 [18.1] pclint is confused by the check on ep.*/
  osp = usbp->epc[ep]->out_state;
  /*lint -restore*/
  osp->rxbuf  = buf;
  osp->rxsize = n;
  osp->rxcnt  = 0;
#if USB_USE_WAIT == TRUE
  osp->thread = NULL;
#endif

  /* Starting transfer.*/
  usb_lld_start_out(usbp, ep);
}

/**
 * @brief   Starts a transmit transaction on an IN endpoint.
 * @note    This function is meant to be called from ISR context outside
 *          critical zones because there is a potentially slow operation
 *          inside.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 * @param[in] ep        endpoint number
 * @param[in] buf       buffer where to fetch the data to be transmitted
 * @param[in] n         transaction size
 *
 * @iclass
 */
void usbStartTransmitI(USBDriver *usbp, usbep_t ep,
                       const uint8_t *buf, size_t n) {
  USBInEndpointState *isp;

  osalDbgCheckClassI();
  osalDbgCheck((usbp != NULL) && (ep <= (usbep_t)USB_MAX_ENDPOINTS));
  osalDbgAssert(!usbGetTransmitStatusI(usbp, ep), "already transmitting");

  /* Marking the endpoint as active.*/
  usbp->transmitting |= (uint16_t)((unsigned)1U << (unsigned)ep);

  /* Setting up the transfer.*/
  /*lint -save -e661 [18.1] pclint is confused by the check on ep.*/
  isp = usbp->epc[ep]->in_state;
  /*lint -restore*/
  isp->txbuf  = buf;
  isp->txsize = n;
  isp->txcnt  = 0;
#if USB_USE_WAIT == TRUE
  isp->thread = NULL;
#endif

  /* Starting transfer.*/
  usb_lld_start_in(usbp, ep);
}

#if (USB_USE_WAIT == TRUE) || defined(__DOXYGEN__)
/**
 * @brief   Performs a receive transaction on an OUT endpoint.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 * @param[in] ep        endpoint number
 * @param[out] buf      buffer where to copy the received data
 * @param[in] n         transaction size. It is recommended a multiple of
 *                      the packet size because the excess is discarded.
 *
 * @return              The received effective data size, it can be less than
 *                      the amount specified.
 * @retval MSG_RESET    driver not in @p USB_ACTIVE state or the operation
 *                      has been aborted by an USB reset or a transition to
 *                      the @p USB_SUSPENDED state.
 *
 * @api
 */
msg_t usbReceive(USBDriver *usbp, usbep_t ep, uint8_t *buf, size_t n) {
  msg_t msg;

  osalSysLock();

  if (usbGetDriverStateI(usbp) != USB_ACTIVE) {
    osalSysUnlock();
    return MSG_RESET;
  }

  usbStartReceiveI(usbp, ep, buf, n);
  msg = osalThreadSuspendS(&usbp->epc[ep]->out_state->thread);
  osalSysUnlock();

  return msg;
}

/**
 * @brief   Performs a transmit transaction on an IN endpoint.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 * @param[in] ep        endpoint number
 * @param[in] buf       buffer where to fetch the data to be transmitted
 * @param[in] n         transaction size
 *
 * @return              The operation status.
 * @retval MSG_OK       operation performed successfully.
 * @retval MSG_RESET    driver not in @p USB_ACTIVE state or the operation
 *                      has been aborted by an USB reset or a transition to
 *                      the @p USB_SUSPENDED state.
 *
 * @api
 */
msg_t usbTransmit(USBDriver *usbp, usbep_t ep, const uint8_t *buf, size_t n) {
  msg_t msg;

  osalSysLock();

  if (usbGetDriverStateI(usbp) != USB_ACTIVE) {
    osalSysUnlock();
    return MSG_RESET;
  }

  usbStartTransmitI(usbp, ep, buf, n);
  msg = osalThreadSuspendS(&usbp->epc[ep]->in_state->thread);
  osalSysUnlock();

  return msg;
}
#endif /* USB_USE_WAIT == TRUE */

/**
 * @brief   Stalls an OUT endpoint.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 * @param[in] ep        endpoint number
 *
 * @return              The operation status.
 * @retval false        Endpoint stalled.
 * @retval true         Endpoint busy, not stalled.
 *
 * @iclass
 */
bool usbStallReceiveI(USBDriver *usbp, usbep_t ep) {

  osalDbgCheckClassI();
  osalDbgCheck(usbp != NULL);

  if (usbGetReceiveStatusI(usbp, ep)) {
    return true;
  }

  usb_lld_stall_out(usbp, ep);
  return false;
}

/**
 * @brief   Stalls an IN endpoint.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 * @param[in] ep        endpoint number
 *
 * @return              The operation status.
 * @retval false        Endpoint stalled.
 * @retval true         Endpoint busy, not stalled.
 *
 * @iclass
 */
bool usbStallTransmitI(USBDriver *usbp, usbep_t ep) {

  osalDbgCheckClassI();
  osalDbgCheck(usbp != NULL);

  if (usbGetTransmitStatusI(usbp, ep)) {
    return true;
  }

  usb_lld_stall_in(usbp, ep);
  return false;
}

/**
 * @brief   Host wake-up procedure.
 * @note    It is silently ignored if the USB device is not in the
 *          @p USB_SUSPENDED state.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 *
 * @api
 */
void usbWakeupHost(USBDriver *usbp) {

  if (usbp->state == USB_SUSPENDED) {
    /* Starting host wakeup procedure.*/
    usb_lld_wakeup_host(usbp);
  }
}

/**
 * @brief   USB reset routine.
 * @details This function must be invoked when an USB bus reset condition is
 *          detected.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 *
 * @notapi
 */
void _usb_reset(USBDriver *usbp) {
  unsigned i;

  /* State transition.*/
  usbp->state         = USB_READY;

  /* Resetting internal state.*/
  usbp->status        = 0;
  usbp->address       = 0;
  usbp->configuration = 0;
  usbp->transmitting  = 0;
  usbp->receiving     = 0;

  /* Invalidates all endpoints into the USBDriver structure.*/
  for (i = 0; i <= (unsigned)USB_MAX_ENDPOINTS; i++) {
#if USB_USE_WAIT == TRUE
    /* Signaling the event to threads waiting on endpoints.*/
    if (usbp->epc[i] != NULL) {
      osalSysLockFromISR();
      if (usbp->epc[i]->in_state != NULL) {
        osalThreadResumeI(&usbp->epc[i]->in_state->thread, MSG_RESET);
      }
      if (usbp->epc[i]->out_state != NULL) {
        osalThreadResumeI(&usbp->epc[i]->out_state->thread, MSG_RESET);
      }
      osalSysUnlockFromISR();
    }
#endif
    usbp->epc[i] = NULL;
  }

  /* EP0 state machine initialization.*/
  usbp->ep0state = USB_EP0_STP_WAITING;

  /* Low level reset.*/
  usb_lld_reset(usbp);

  /* Notification of reset event.*/
  _usb_isr_invoke_event_cb(usbp, USB_EVENT_RESET);
}

/**
 * @brief   USB suspend routine.
 * @details This function must be invoked when an USB bus suspend condition is
 *          detected.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 *
 * @notapi
 */
void _usb_suspend(USBDriver *usbp) {
  /* No state change, suspend always returns to previous state. */

  /* State transition.*/
  usbp->saved_state = usbp->state;
  usbp->state       = USB_SUSPENDED;

  /* Notification of suspend event.*/
  _usb_isr_invoke_event_cb(usbp, USB_EVENT_SUSPEND);

  /* Signaling the event to threads waiting on endpoints.*/
#if USB_USE_WAIT == TRUE
  {
    unsigned i;

    for (i = 0; i <= (unsigned)USB_MAX_ENDPOINTS; i++) {
      if (usbp->epc[i] != NULL) {
        osalSysLockFromISR();
        if (usbp->epc[i]->in_state != NULL) {
          osalThreadResumeI(&usbp->epc[i]->in_state->thread, MSG_RESET);
        }
        if (usbp->epc[i]->out_state != NULL) {
          osalThreadResumeI(&usbp->epc[i]->out_state->thread, MSG_RESET);
        }
        osalSysUnlockFromISR();
      }
    }
  }
#endif
}

/**
 * @brief   USB wake-up routine.
 * @details This function must be invoked when an USB bus wake-up condition is
 *          detected.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 *
 * @notapi
 */
void _usb_wakeup(USBDriver *usbp) {

  /* State transition, returning to the previous state.*/
  usbp->state = usbp->saved_state;

  /* Notification of suspend event.*/
  _usb_isr_invoke_event_cb(usbp, USB_EVENT_WAKEUP);
}

/**
 * @brief   Default EP0 SETUP callback.
 * @details This function is used by the low level driver as default handler
 *          for EP0 SETUP events.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 * @param[in] ep        endpoint number, always zero
 *
 * @notapi
 */
void _usb_ep0setup(USBDriver *usbp, usbep_t ep) {
  size_t max;

  /* Is the EP0 state machine in the correct state for handling setup
     packets?*/
  if (usbp->ep0state != USB_EP0_STP_WAITING) {
    /* This is unexpected could require handling with a warning event.*/
    /* TODO: handling here.*/

    /* Resetting the EP0 state machine and going ahead.*/
    usbp->ep0state = USB_EP0_STP_WAITING;
  }

  /* Reading the setup data into the driver buffer.*/
  usbReadSetup(usbp, ep, usbp->setup);

  /* First verify if the application has an handler installed for this
     request.*/
  /*lint -save -e9007 [13.5] No side effects, it is intentional.*/
  if ((usbp->config->requests_hook_cb == NULL) ||
      !(usbp->config->requests_hook_cb(usbp))) {
  /*lint -restore*/
    /* Invoking the default handler, if this fails then stalls the
       endpoint zero as error.*/
    /*lint -save -e9007 [13.5] No side effects, it is intentional.*/
    if (((usbp->setup[0] & USB_RTYPE_TYPE_MASK) != USB_RTYPE_TYPE_STD) ||
        !default_handler(usbp)) {
    /*lint -restore*/
      /* Error response, the state machine goes into an error state, the low
         level layer will have to reset it to USB_EP0_WAITING_SETUP after
         receiving a SETUP packet.*/
      usb_lld_stall_in(usbp, 0);
      usb_lld_stall_out(usbp, 0);
      _usb_isr_invoke_event_cb(usbp, USB_EVENT_STALLED);
      usbp->ep0state = USB_EP0_ERROR;
      return;
    }
  }
#if (USB_SET_ADDRESS_ACK_HANDLING == USB_SET_ADDRESS_ACK_HW)
  if (usbp->setup[1] == USB_REQ_SET_ADDRESS) {
    /* Zero-length packet sent by hardware */
    return;
  }
#endif
  /* Transfer preparation. The request handler must have populated
     correctly the fields ep0next, ep0n and ep0endcb using the macro
     usbSetupTransfer().*/
  max = (size_t)get_hword(&usbp->setup[6]);
  /* The transfer size cannot exceed the specified amount.*/
  if (usbp->ep0n > max) {
    usbp->ep0n = max;
  }
  if ((usbp->setup[0] & USB_RTYPE_DIR_MASK) == USB_RTYPE_DIR_DEV2HOST) {
    /* IN phase.*/
    if (usbp->ep0n != 0U) {
      /* Starts the transmit phase.*/
      usbp->ep0state = USB_EP0_IN_TX;
      osalSysLockFromISR();
      usbStartTransmitI(usbp, 0, usbp->ep0next, usbp->ep0n);
      osalSysUnlockFromISR();
    }
    else {
      /* No transmission phase, directly receiving the zero sized status
         packet.*/
      usbp->ep0state = USB_EP0_OUT_WAITING_STS;
#if (USB_EP0_STATUS_STAGE == USB_EP0_STATUS_STAGE_SW)
      osalSysLockFromISR();
      usbStartReceiveI(usbp, 0, NULL, 0);
      osalSysUnlockFromISR();
#else
      usb_lld_end_setup(usbp, ep);
#endif
    }
  }
  else {
    /* OUT phase.*/
    if (usbp->ep0n != 0U) {
      /* Starts the receive phase.*/
      usbp->ep0state = USB_EP0_OUT_RX;
      osalSysLockFromISR();
      usbStartReceiveI(usbp, 0, (uint8_t *)usbp->ep0next, usbp->ep0n);
      osalSysUnlockFromISR();
    }
    else {
      /* No receive phase, directly sending the zero sized status
         packet.*/
      usbp->ep0state = USB_EP0_IN_SENDING_STS;
#if (USB_EP0_STATUS_STAGE == USB_EP0_STATUS_STAGE_SW)
      osalSysLockFromISR();
      usbStartTransmitI(usbp, 0, NULL, 0);
      osalSysUnlockFromISR();
#else
      usb_lld_end_setup(usbp, ep);
#endif
    }
  }
}

/**
 * @brief   Default EP0 IN callback.
 * @details This function is used by the low level driver as default handler
 *          for EP0 IN events.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 * @param[in] ep        endpoint number, always zero
 *
 * @notapi
 */
void _usb_ep0in(USBDriver *usbp, usbep_t ep) {
  size_t max;

  (void)ep;
  switch (usbp->ep0state) {
  case USB_EP0_IN_TX:
    max = (size_t)get_hword(&usbp->setup[6]);
    /* If the transmitted size is less than the requested size and it is a
       multiple of the maximum packet size then a zero size packet must be
       transmitted.*/
    if ((usbp->ep0n < max) &&
        ((usbp->ep0n % usbp->epc[0]->in_maxsize) == 0U)) {
      osalSysLockFromISR();
      usbStartTransmitI(usbp, 0, NULL, 0);
      osalSysUnlockFromISR();
      usbp->ep0state = USB_EP0_IN_WAITING_TX0;
      return;
    }
    /* Falls through.*/
  case USB_EP0_IN_WAITING_TX0:
    /* Transmit phase over, receiving the zero sized status packet.*/
    usbp->ep0state = USB_EP0_OUT_WAITING_STS;
#if (USB_EP0_STATUS_STAGE == USB_EP0_STATUS_STAGE_SW)
    osalSysLockFromISR();
    usbStartReceiveI(usbp, 0, NULL, 0);
    osalSysUnlockFromISR();
#else
    usb_lld_end_setup(usbp, ep);
#endif
    return;
  case USB_EP0_IN_SENDING_STS:
    /* Status packet sent, invoking the callback if defined.*/
    if (usbp->ep0endcb != NULL) {
      usbp->ep0endcb(usbp);
    }
    usbp->ep0state = USB_EP0_STP_WAITING;
    return;
  case USB_EP0_STP_WAITING:
  case USB_EP0_OUT_WAITING_STS:
  case USB_EP0_OUT_RX:
    /* All the above are invalid states in the IN phase.*/
    osalDbgAssert(false, "EP0 state machine error");
    /* Falls through.*/
  case USB_EP0_ERROR:
    /* Error response, the state machine goes into an error state, the low
       level layer will have to reset it to USB_EP0_WAITING_SETUP after
       receiving a SETUP packet.*/
    usb_lld_stall_in(usbp, 0);
    usb_lld_stall_out(usbp, 0);
    _usb_isr_invoke_event_cb(usbp, USB_EVENT_STALLED);
    usbp->ep0state = USB_EP0_ERROR;
    return;
  default:
    osalDbgAssert(false, "EP0 state machine invalid state");
  }
}

/**
 * @brief   Default EP0 OUT callback.
 * @details This function is used by the low level driver as default handler
 *          for EP0 OUT events.
 *
 * @param[in] usbp      pointer to the @p USBDriver object
 * @param[in] ep        endpoint number, always zero
 *
 * @notapi
 */
void _usb_ep0out(USBDriver *usbp, usbep_t ep) {

  (void)ep;
  switch (usbp->ep0state) {
  case USB_EP0_OUT_RX:
    /* Receive phase over, sending the zero sized status packet.*/
    usbp->ep0state = USB_EP0_IN_SENDING_STS;
#if (USB_EP0_STATUS_STAGE == USB_EP0_STATUS_STAGE_SW)
    osalSysLockFromISR();
    usbStartTransmitI(usbp, 0, NULL, 0);
    osalSysUnlockFromISR();
#else
    usb_lld_end_setup(usbp, ep);
#endif
    return;
  case USB_EP0_OUT_WAITING_STS:
    /* Status packet received, it must be zero sized, invoking the callback
       if defined.*/
#if (USB_EP0_STATUS_STAGE == USB_EP0_STATUS_STAGE_SW)
    if (usbGetReceiveTransactionSizeX(usbp, 0) != 0U) {
      break;
    }
#endif
    if (usbp->ep0endcb != NULL) {
      usbp->ep0endcb(usbp);
    }
    usbp->ep0state = USB_EP0_STP_WAITING;
    return;
  case USB_EP0_STP_WAITING:
  case USB_EP0_IN_TX:
  case USB_EP0_IN_WAITING_TX0:
  case USB_EP0_IN_SENDING_STS:
    /* All the above are invalid states in the IN phase.*/
    osalDbgAssert(false, "EP0 state machine error");
    /* Falls through.*/
  case USB_EP0_ERROR:
    /* Error response, the state machine goes into an error state, the low
       level layer will have to reset it to USB_EP0_WAITING_SETUP after
       receiving a SETUP packet.*/
    usb_lld_stall_in(usbp, 0);
    usb_lld_stall_out(usbp, 0);
    _usb_isr_invoke_event_cb(usbp, USB_EVENT_STALLED);
    usbp->ep0state = USB_EP0_ERROR;
    return;
  default:
    osalDbgAssert(false, "EP0 state machine invalid state");
  }
}

#endif /* HAL_USE_USB == TRUE */

/** @} */