usbstring.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (C) 2003 David Brownell
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU Lesser General Public License as published
  6. * by the Free Software Foundation; either version 2.1 of the License, or
  7. * (at your option) any later version.
  8. */
  9. #include <linux/errno.h>
  10. #include <linux/kernel.h>
  11. #include <linux/module.h>
  12. #include <linux/list.h>
  13. #include <linux/string.h>
  14. #include <linux/device.h>
  15. #include <linux/init.h>
  16. #include <linux/nls.h>
  17. #include <linux/usb/ch9.h>
  18. #include <linux/usb/gadget.h>
  19. /**
  20. * usb_gadget_get_string - fill out a string descriptor
  21. * @table: of c strings encoded using UTF-8
  22. * @id: string id, from low byte of wValue in get string descriptor
  23. * @buf: at least 256 bytes, must be 16-bit aligned
  24. *
  25. * Finds the UTF-8 string matching the ID, and converts it into a
  26. * string descriptor in utf16-le.
  27. * Returns length of descriptor (always even) or negative errno
  28. *
  29. * If your driver needs stings in multiple languages, you'll probably
  30. * "switch (wIndex) { ... }" in your ep0 string descriptor logic,
  31. * using this routine after choosing which set of UTF-8 strings to use.
  32. * Note that US-ASCII is a strict subset of UTF-8; any string bytes with
  33. * the eighth bit set will be multibyte UTF-8 characters, not ISO-8859/1
  34. * characters (which are also widely used in C strings).
  35. */
  36. int
  37. usb_gadget_get_string (struct usb_gadget_strings *table, int id, u8 *buf)
  38. {
  39. struct usb_string *s;
  40. int len;
  41. /* descriptor 0 has the language id */
  42. if (id == 0) {
  43. buf [0] = 4;
  44. buf [1] = USB_DT_STRING;
  45. buf [2] = (u8) table->language;
  46. buf [3] = (u8) (table->language >> 8);
  47. return 4;
  48. }
  49. for (s = table->strings; s && s->s; s++)
  50. if (s->id == id)
  51. break;
  52. /* unrecognized: stall. */
  53. if (!s || !s->s)
  54. return -EINVAL;
  55. /* string descriptors have length, tag, then UTF16-LE text */
  56. len = min ((size_t) 126, strlen (s->s));
  57. len = utf8s_to_utf16s(s->s, len, UTF16_LITTLE_ENDIAN,
  58. (wchar_t *) &buf[2], 126);
  59. if (len < 0)
  60. return -EINVAL;
  61. buf [0] = (len + 1) * 2;
  62. buf [1] = USB_DT_STRING;
  63. return buf [0];
  64. }
  65. EXPORT_SYMBOL_GPL(usb_gadget_get_string);