usbstring.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // SPDX-License-Identifier: LGPL-2.1+
  2. /*
  3. * Copyright (C) 2003 David Brownell
  4. *
  5. * Ported to U-Boot by: Thomas Smits <ts.smits@gmail.com> and
  6. * Remy Bohmer <linux@bohmer.net>
  7. */
  8. #include <common.h>
  9. #include <linux/errno.h>
  10. #include <linux/usb/ch9.h>
  11. #include <linux/usb/gadget.h>
  12. #include <linux/utf.h>
  13. /**
  14. * usb_gadget_get_string - fill out a string descriptor
  15. * @table: of c strings encoded using UTF-8
  16. * @id: string id, from low byte of wValue in get string descriptor
  17. * @buf: at least 256 bytes
  18. *
  19. * Finds the UTF-8 string matching the ID, and converts it into a
  20. * string descriptor in utf16-le.
  21. * Returns length of descriptor (always even) or negative errno
  22. *
  23. * If your driver needs stings in multiple languages, you'll probably
  24. * "switch (wIndex) { ... }" in your ep0 string descriptor logic,
  25. * using this routine after choosing which set of UTF-8 strings to use.
  26. * Note that US-ASCII is a strict subset of UTF-8; any string bytes with
  27. * the eighth bit set will be multibyte UTF-8 characters, not ISO-8859/1
  28. * characters (which are also widely used in C strings).
  29. */
  30. int
  31. usb_gadget_get_string(struct usb_gadget_strings *table, int id, u8 *buf)
  32. {
  33. struct usb_string *s;
  34. int len;
  35. if (!table)
  36. return -EINVAL;
  37. /* descriptor 0 has the language id */
  38. if (id == 0) {
  39. buf[0] = 4;
  40. buf[1] = USB_DT_STRING;
  41. buf[2] = (u8) table->language;
  42. buf[3] = (u8) (table->language >> 8);
  43. return 4;
  44. }
  45. for (s = table->strings; s && s->s; s++)
  46. if (s->id == id)
  47. break;
  48. /* unrecognized: stall. */
  49. if (!s || !s->s)
  50. return -EINVAL;
  51. /* string descriptors have length, tag, then UTF16-LE text */
  52. len = min((size_t) 126, strlen(s->s));
  53. memset(buf + 2, 0, 2 * len); /* zero all the bytes */
  54. len = utf8_to_utf16le(s->s, (__le16 *)&buf[2], len);
  55. if (len < 0)
  56. return -EINVAL;
  57. buf[0] = (len + 1) * 2;
  58. buf[1] = USB_DT_STRING;
  59. return buf[0];
  60. }