blob: 4617a95bd0a7a8968fc5417110503fb2a951021c [file] [log] [blame]
Tom Rini10e47792018-05-06 17:58:06 -04001// SPDX-License-Identifier: LGPL-2.1+
Remy Bohmerdf063442009-07-29 18:18:43 +02002/*
3 * Copyright (C) 2003 David Brownell
4 *
Bin Meng75574052016-02-05 19:30:11 -08005 * Ported to U-Boot by: Thomas Smits <ts.smits@gmail.com> and
Remy Bohmerdf063442009-07-29 18:18:43 +02006 * Remy Bohmer <linux@bohmer.net>
7 */
8
Masahiro Yamada56a931c2016-09-21 11:28:55 +09009#include <linux/errno.h>
Remy Bohmerdf063442009-07-29 18:18:43 +020010#include <linux/usb/ch9.h>
11#include <linux/usb/gadget.h>
Li June787da42021-01-25 21:43:47 +080012#include <linux/utf.h>
Remy Bohmerdf063442009-07-29 18:18:43 +020013
14/**
15 * usb_gadget_get_string - fill out a string descriptor
16 * @table: of c strings encoded using UTF-8
17 * @id: string id, from low byte of wValue in get string descriptor
18 * @buf: at least 256 bytes
19 *
20 * Finds the UTF-8 string matching the ID, and converts it into a
21 * string descriptor in utf16-le.
22 * Returns length of descriptor (always even) or negative errno
23 *
24 * If your driver needs stings in multiple languages, you'll probably
25 * "switch (wIndex) { ... }" in your ep0 string descriptor logic,
26 * using this routine after choosing which set of UTF-8 strings to use.
27 * Note that US-ASCII is a strict subset of UTF-8; any string bytes with
28 * the eighth bit set will be multibyte UTF-8 characters, not ISO-8859/1
29 * characters (which are also widely used in C strings).
30 */
31int
Vitaly Kuzmichev49ed8052010-09-13 18:37:11 +040032usb_gadget_get_string(struct usb_gadget_strings *table, int id, u8 *buf)
Remy Bohmerdf063442009-07-29 18:18:43 +020033{
34 struct usb_string *s;
35 int len;
36
Rob Herringef60fda2014-04-18 08:54:28 -050037 if (!table)
38 return -EINVAL;
39
Remy Bohmerdf063442009-07-29 18:18:43 +020040 /* descriptor 0 has the language id */
41 if (id == 0) {
Vitaly Kuzmichev49ed8052010-09-13 18:37:11 +040042 buf[0] = 4;
43 buf[1] = USB_DT_STRING;
44 buf[2] = (u8) table->language;
45 buf[3] = (u8) (table->language >> 8);
Remy Bohmerdf063442009-07-29 18:18:43 +020046 return 4;
47 }
48 for (s = table->strings; s && s->s; s++)
49 if (s->id == id)
50 break;
51
52 /* unrecognized: stall. */
53 if (!s || !s->s)
54 return -EINVAL;
55
56 /* string descriptors have length, tag, then UTF16-LE text */
Vitaly Kuzmichev49ed8052010-09-13 18:37:11 +040057 len = min((size_t) 126, strlen(s->s));
58 memset(buf + 2, 0, 2 * len); /* zero all the bytes */
Remy Bohmerdf063442009-07-29 18:18:43 +020059 len = utf8_to_utf16le(s->s, (__le16 *)&buf[2], len);
60 if (len < 0)
61 return -EINVAL;
Vitaly Kuzmichev49ed8052010-09-13 18:37:11 +040062 buf[0] = (len + 1) * 2;
63 buf[1] = USB_DT_STRING;
64 return buf[0];
Remy Bohmerdf063442009-07-29 18:18:43 +020065}