From 33f7bfa351c4edc9e2420afd5d503bb90046d90a Mon Sep 17 00:00:00 2001 From: David Date: Tue, 14 Mar 2017 21:01:44 +0800 Subject: [PATCH 01/15] ARM: Fix off-by-one interrupt stack allocation (revert missed change in up_initialize.c) --- arch/arm/src/common/up_initialize.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/arm/src/common/up_initialize.c b/arch/arm/src/common/up_initialize.c index ff11e45170d..5182598246a 100644 --- a/arch/arm/src/common/up_initialize.c +++ b/arch/arm/src/common/up_initialize.c @@ -100,7 +100,7 @@ static void up_calibratedelay(void) * ****************************************************************************/ -#if defined(CONFIG_STACK_COLORATION) && CONFIG_ARCH_INTERRUPTSTACK > 7 +#if defined(CONFIG_STACK_COLORATION) && CONFIG_ARCH_INTERRUPTSTACK > 3 static inline void up_color_intstack(void) { uint32_t *ptr = (uint32_t *)&g_intstackalloc; From 55fb9645a7212aaa1661d8c03c84c8951a8644c4 Mon Sep 17 00:00:00 2001 From: David Sidrane Date: Wed, 15 Mar 2017 07:42:55 -1000 Subject: [PATCH 02/15] Guard from pend_reprios overlow --- sched/wqueue/kwork_inherit.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/sched/wqueue/kwork_inherit.c b/sched/wqueue/kwork_inherit.c index b6d98c7b406..a960480bd05 100644 --- a/sched/wqueue/kwork_inherit.c +++ b/sched/wqueue/kwork_inherit.c @@ -110,6 +110,11 @@ static void lpwork_boostworker(pid_t wpid, uint8_t reqprio) wtcb->pend_reprios[wtcb->npend_reprio] = wtcb->sched_priority; wtcb->npend_reprio++; } + else + { + serr("ERROR: CONFIG_SEM_NNESTPRIO exceeded\n"); + DEBUGASSERT(wtcb->npend_reprio < CONFIG_SEM_NNESTPRIO); + } } /* Raise the priority of the worker. This cannot cause a context @@ -129,8 +134,16 @@ static void lpwork_boostworker(pid_t wpid, uint8_t reqprio) * saved priority and not to the base priority. */ - wtcb->pend_reprios[wtcb->npend_reprio] = reqprio; - wtcb->npend_reprio++; + if (wtcb->npend_reprio < CONFIG_SEM_NNESTPRIO) + { + wtcb->pend_reprios[wtcb->npend_reprio] = reqprio; + wtcb->npend_reprio++; + } + else + { + serr("ERROR: CONFIG_SEM_NNESTPRIO exceeded\n"); + DEBUGASSERT(wtcb->npend_reprio < CONFIG_SEM_NNESTPRIO); + } } } #else From 57a1360c847734ce54a87b3f43dc79bc36896f47 Mon Sep 17 00:00:00 2001 From: Gregory Nutt Date: Wed, 15 Mar 2017 14:30:24 -0600 Subject: [PATCH 03/15] Add option to enable wireless debug output. --- Kconfig | 32 +++++++++++++++++++ drivers/wireless/nrf24l01.c | 52 +++++++++++++++---------------- include/debug.h | 44 ++++++++++++++++++++++++++ include/nuttx/wireless/nrf24l01.h | 17 +--------- 4 files changed, 103 insertions(+), 42 deletions(-) diff --git a/Kconfig b/Kconfig index 4d7949d4e31..bbff98b262b 100644 --- a/Kconfig +++ b/Kconfig @@ -732,6 +732,38 @@ config DEBUG_NET_INFO endif # DEBUG_NET +config DEBUG_WIRELESS + bool "Wireless Debug Features" + default n + depends on WIRELESS | DRIVERS_WIRELESS + ---help--- + Enable DEBUG_WIRELESS debug features. + +if DEBUG_WIRELESS + +config DEBUG_WIRELESS_ERROR + bool "Wireless Error Output" + default n + depends on DEBUG_ERROR + ---help--- + Enable wireless error output to SYSLOG. + +config DEBUG_WIRELESS_WARN + bool "Wireless Warnings Output" + default n + depends on DEBUG_WARN + ---help--- + Enable wireless warning output to SYSLOG. + +config DEBUG_WIRELESS_INFO + bool "Wireless Informational Output" + default n + depends on DEBUG_INFO + ---help--- + Enable wireless informational output to SYSLOG. + +endif # DEBUG_WIRELESS + config DEBUG_SCHED bool "Scheduler Debug Features" default n diff --git a/drivers/wireless/nrf24l01.c b/drivers/wireless/nrf24l01.c index c3ed88d17a7..ae0d29b483c 100644 --- a/drivers/wireless/nrf24l01.c +++ b/drivers/wireless/nrf24l01.c @@ -221,7 +221,7 @@ static uint8_t fifoget(struct nrf24l01_dev_s *dev, FAR uint8_t *buffer, static void nrf24l01_worker(FAR void *arg); #endif -#ifdef NRF24L01_DEBUG +#ifdef CONFIG_DEBUG_WIRELESS static void binarycvt(char *deststr, const uint8_t *srcbin, size_t srclen) #endif @@ -595,7 +595,7 @@ static int nrf24l01_irqhandler(int irq, FAR void *context, FAR void *arg) { FAR struct nrf24l01_dev_s *dev = (FAR struct nrf24l01_dev_s *)arg; - winfo("*IRQ*\n"); + wlinfo("*IRQ*\n"); #ifdef CONFIG_WL_NRF24L01_RXSUPPORT /* If RX is enabled we delegate the actual work to bottom-half handler */ @@ -667,7 +667,7 @@ static void nrf24l01_worker(FAR void *arg) bool has_data = false; #endif - winfo("RX_DR is set!\n"); + wlinfo("RX_DR is set!\n"); /* Read and store all received payloads */ @@ -686,7 +686,7 @@ static void nrf24l01_worker(FAR void *arg) pipeno = (status & NRF24L01_RX_P_NO_MASK) >> NRF24L01_RX_P_NO_SHIFT; if (pipeno >= NRF24L01_PIPE_COUNT) /* 6=invalid 7=fifo empty */ { - werr("invalid pipe rx: %d\n", (int)pipeno); + wlerr("invalid pipe rx: %d\n", (int)pipeno); nrf24l01_flush_rx(dev); break; } @@ -703,7 +703,7 @@ static void nrf24l01_worker(FAR void *arg) if (pktlen > NRF24L01_MAX_PAYLOAD_LEN) /* bad length */ { - werr("invalid length in rx: %d\n", (int)pktlen); + wlerr("invalid length in rx: %d\n", (int)pktlen); nrf24l01_flush_rx(dev); break; } @@ -720,8 +720,8 @@ static void nrf24l01_worker(FAR void *arg) status = nrf24l01_readreg(dev, NRF24L01_FIFO_STATUS, &fifo_status, 1); - winfo("FIFO_STATUS=%02x\n", fifo_status); - winfo("STATUS=%02x\n", status); + wlinfo("FIFO_STATUS=%02x\n", fifo_status); + wlinfo("STATUS=%02x\n", status); } while ((fifo_status & NRF24L01_RX_EMPTY) == 0); @@ -730,7 +730,7 @@ static void nrf24l01_worker(FAR void *arg) { dev->pfd->revents |= POLLIN; /* Data available for input */ - winfo("Wake up polled fd\n"); + wlinfo("Wake up polled fd\n"); sem_post(dev->pfd->sem); } #endif @@ -758,7 +758,7 @@ static void nrf24l01_worker(FAR void *arg) } else { - werr("invalid length in rx: %d\n", (int)pktlen); + wlerr("invalid length in rx: %d\n", (int)pktlen); } } @@ -874,7 +874,7 @@ static int dosend(FAR struct nrf24l01_dev_s *dev, FAR const uint8_t *data, if (result < 0) { - werr("wait for irq failed\n"); + wlerr("wait for irq failed\n"); nrf24l01_flush_tx(dev); goto out; } @@ -888,11 +888,11 @@ static int dosend(FAR struct nrf24l01_dev_s *dev, FAR const uint8_t *data, dev->lastxmitcount = (obsvalue & NRF24L01_ARC_CNT_MASK) >> NRF24L01_ARC_CNT_SHIFT; - winfo("Transmission OK (lastxmitcount=%d)\n", dev->lastxmitcount); + wlinfo("Transmission OK (lastxmitcount=%d)\n", dev->lastxmitcount); } else if (status & NRF24L01_MAX_RT) { - winfo("MAX_RT! (lastxmitcount=%d)\n", dev->lastxmitcount); + wlinfo("MAX_RT! (lastxmitcount=%d)\n", dev->lastxmitcount); result = -ECOMM; dev->lastxmitcount = NRF24L01_XMIT_MAXRT; @@ -906,7 +906,7 @@ static int dosend(FAR struct nrf24l01_dev_s *dev, FAR const uint8_t *data, { /* Unexpected... */ - werr("ERROR: No TX_DS nor MAX_RT bit set in STATUS reg!\n"); + wlerr("ERROR: No TX_DS nor MAX_RT bit set in STATUS reg!\n"); result = -EIO; } @@ -930,7 +930,7 @@ out: * Name: binarycvt ****************************************************************************/ -#ifdef NRF24L01_DEBUG +#ifdef CONFIG_DEBUG_WIRELESS static void binarycvt(char *deststr, const uint8_t *srcbin, size_t srclen) { int i = 0; @@ -958,7 +958,7 @@ static int nrf24l01_open(FAR struct file *filep) FAR struct nrf24l01_dev_s *dev; int result; - winfo("Opening nRF24L01 dev\n"); + wlinfo("Opening nRF24L01 dev\n"); DEBUGASSERT(filep); inode = filep->f_inode; @@ -1004,7 +1004,7 @@ static int nrf24l01_close(FAR struct file *filep) FAR struct inode *inode; FAR struct nrf24l01_dev_s *dev; - winfo("Closing nRF24L01 dev\n"); + wlinfo("Closing nRF24L01 dev\n"); DEBUGASSERT(filep); inode = filep->f_inode; @@ -1103,7 +1103,7 @@ static int nrf24l01_ioctl(FAR struct file *filep, int cmd, unsigned long arg) FAR struct nrf24l01_dev_s *dev; int result = OK; - winfo("cmd: %d arg: %ld\n", cmd, arg); + wlinfo("cmd: %d arg: %ld\n", cmd, arg); DEBUGASSERT(filep); inode = filep->f_inode; @@ -1347,7 +1347,7 @@ static int nrf24l01_poll(FAR struct file *filep, FAR struct pollfd *fds, FAR struct nrf24l01_dev_s *dev; int result = OK; - winfo("setup: %d\n", (int)setup); + wlinfo("setup: %d\n", (int)setup); DEBUGASSERT(filep && fds); inode = filep->f_inode; @@ -1501,12 +1501,12 @@ int nrf24l01_register(FAR struct spi_dev_s *spi, /* Register the device as an input device */ - winfo("Registering " DEV_NAME "\n"); + wlinfo("Registering " DEV_NAME "\n"); result = register_driver(DEV_NAME, &nrf24l01_fops, 0666, dev); if (result < 0) { - werr("ERROR: register_driver() failed: %d\n", result); + wlerr("ERROR: register_driver() failed: %d\n", result); nrf24l01_unregister(dev); } @@ -1990,7 +1990,7 @@ int nrf24l01_sendto(FAR struct nrf24l01_dev_s *dev, FAR const uint8_t *data, if ((dev->en_aa & 1) && (memcmp(destaddr, dev->pipe0addr, dev->addrlen))) { - winfo("Change pipe #0 addr to dest addr\n"); + wlinfo("Change pipe #0 addr to dest addr\n"); nrf24l01_writereg(dev, NRF24L01_RX_ADDR_P0, destaddr, NRF24L01_MAX_ADDR_LEN); pipeaddrchg = true; @@ -2004,7 +2004,7 @@ int nrf24l01_sendto(FAR struct nrf24l01_dev_s *dev, FAR const uint8_t *data, nrf24l01_writereg(dev, NRF24L01_RX_ADDR_P0, dev->pipe0addr, NRF24L01_MAX_ADDR_LEN); - winfo("Pipe #0 default addr restored\n"); + wlinfo("Pipe #0 default addr restored\n"); } nrf24l01_unlock(dev->spi); @@ -2045,7 +2045,7 @@ ssize_t nrf24l01_recv(struct nrf24l01_dev_s *dev, uint8_t *buffer, * Name: nrf24l01_dumpregs ****************************************************************************/ -#ifdef NRF24L01_DEBUG +#ifdef CONFIG_DEBUG_WIRELESS void nrf24l01_dumpregs(struct nrf24l01_dev_s *dev) { uint8_t addr[NRF24L01_MAX_ADDR_LEN]; @@ -2097,17 +2097,17 @@ void nrf24l01_dumpregs(struct nrf24l01_dev_s *dev) syslog(LOG_INFO, "FEATURE: %02x\n", nrf24l01_readregbyte(dev, NRF24L01_FEATURE)); } -#endif /* NRF24L01_DEBUG */ +#endif /* CONFIG_DEBUG_WIRELESS */ /**************************************************************************** * Name: nrf24l01_dumprxfifo ****************************************************************************/ -#if defined(NRF24L01_DEBUG) && defined(CONFIG_WL_NRF24L01_RXSUPPORT) +#if defined(CONFIG_DEBUG_WIRELESS) && defined(CONFIG_WL_NRF24L01_RXSUPPORT) void nrf24l01_dumprxfifo(struct nrf24l01_dev_s *dev) { syslog(LOG_INFO, "bytes count: %d\n", dev->fifo_len); syslog(LOG_INFO, "next read: %d, next write: %d\n", dev->nxt_read, dev-> nxt_write); } -#endif /* NRF24L01_DEBUG && CONFIG_WL_NRF24L01_RXSUPPORT */ +#endif /* CONFIG_DEBUG_WIRELESS && CONFIG_WL_NRF24L01_RXSUPPORT */ diff --git a/include/debug.h b/include/debug.h index 0bde25605be..64352dad34c 100644 --- a/include/debug.h +++ b/include/debug.h @@ -233,6 +233,24 @@ # define ninfo(x...) #endif +#ifdef CONFIG_DEBUG_WIRELESS_ERROR +# define wlerr(format, ...) _err(format, ##__VA_ARGS__) +#else +# define wlerr(x...) +#endif + +#ifdef CONFIG_DEBUG_WIRELESS_WARN +# define wlwarn(format, ...) _warn(format, ##__VA_ARGS__) +#else +# define wlwarn(x...) +#endif + +#ifdef CONFIG_DEBUG_WIRELESS_INFO +# define wlinfo(format, ...) _info(format, ##__VA_ARGS__) +#else +# define wlinfo(x...) +#endif + #ifdef CONFIG_DEBUG_FS_ERROR # define ferr(format, ...) _err(format, ##__VA_ARGS__) #else @@ -777,6 +795,24 @@ # define ninfo (void) #endif +#ifdef CONFIG_DEBUG_WIRELESS_ERROR +# define wlerr _err +#else +# define wlerr (void) +#endif + +#ifdef CONFIG_DEBUG_WIRELESS_WARN +# define wlwarn _warn +#else +# define wlwarn (void) +#endif + +#ifdef CONFIG_DEBUG_WIRELESS_INFO +# define wlinfo _info +#else +# define wlinfo (void) +#endif + #ifdef CONFIG_DEBUG_FS_ERROR # define ferr _err #else @@ -1267,6 +1303,14 @@ # define ninfodumpbuffer(m,b,n) #endif +#ifdef CONFIG_DEBUG_WIRELESS +# define wlerrdumpbuffer(m,b,n) errdumpbuffer(m,b,n) +# define wlinfodumpbuffer(m,b,n) infodumpbuffer(m,b,n) +#else +# define wlerrdumpbuffer(m,b,n) +# define wlinfodumpbuffer(m,b,n) +#endif + #ifdef CONFIG_DEBUG_FS # define ferrdumpbuffer(m,b,n) errdumpbuffer(m,b,n) # define finfodumpbuffer(m,b,n) infodumpbuffer(m,b,n) diff --git a/include/nuttx/wireless/nrf24l01.h b/include/nuttx/wireless/nrf24l01.h index 76ac27d0df7..610b3c36821 100644 --- a/include/nuttx/wireless/nrf24l01.h +++ b/include/nuttx/wireless/nrf24l01.h @@ -64,8 +64,6 @@ #define NRF24L01_DYN_LENGTH 33 /* Specific length value to use to enable dynamic packet length */ #define NRF24L01_XMIT_MAXRT 255 /* Specific value returned by Number of available pipes */ -/* #define NRF24L01_DEBUG 1 */ - /* IOCTL commands */ #define NRF24L01IOC_SETRETRCFG _WLIOC(NRF24L01_FIRST+0) /* arg: Pointer to nrf24l01_retrcfg_t structure */ @@ -88,16 +86,6 @@ #define NRF24L01IOC_SETTXADDR WLIOC_SETADDR #define NRF24L01IOC_GETTXADDR WLIOC_GETADDR -/* NRF24L01 debug */ - -#ifdef NRF24L01_DEBUG -# define werr(format, ...) _err(format, ##__VA_ARGS__) -# define winfo(format, ...) _info(format, ##__VA_ARGS__) -#else -# define werr(x...) -# define winfo(x...) -#endif - /**************************************************************************** * Public Data Types ****************************************************************************/ @@ -505,12 +493,9 @@ ssize_t nrf24l01_recv(struct nrf24l01_dev_s *dev, uint8_t *buffer, #endif -#ifdef NRF24L01_DEBUG - +#ifdef CONFIG_DEBUG_WIRELESS void nrf24l01_dumpregs(FAR struct nrf24l01_dev_s *dev); - void nrf24l01_dumprxfifo(FAR struct nrf24l01_dev_s *dev); - #endif #undef EXTERN From 255673b9d097bdfa417a2c51c1eaaec019fcb78f Mon Sep 17 00:00:00 2001 From: Gregory Nutt Date: Wed, 15 Mar 2017 15:16:16 -0600 Subject: [PATCH 04/15] Fix a typo introduced in Kconfig with last commit --- Kconfig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Kconfig b/Kconfig index bbff98b262b..1116ba6ccc5 100644 --- a/Kconfig +++ b/Kconfig @@ -735,7 +735,7 @@ endif # DEBUG_NET config DEBUG_WIRELESS bool "Wireless Debug Features" default n - depends on WIRELESS | DRIVERS_WIRELESS + depends on WIRELESS || DRIVERS_WIRELESS ---help--- Enable DEBUG_WIRELESS debug features. From f9c22461c45234ef628c902fdc50b93b05a0db77 Mon Sep 17 00:00:00 2001 From: Gregory Nutt Date: Wed, 15 Mar 2017 16:38:09 -0600 Subject: [PATCH 05/15] include/nuttx/fs/ioctl.h: Fix IOCTL numbering --- include/nuttx/fs/ioctl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/nuttx/fs/ioctl.h b/include/nuttx/fs/ioctl.h index c5d25cd2120..5582ccd0fee 100644 --- a/include/nuttx/fs/ioctl.h +++ b/include/nuttx/fs/ioctl.h @@ -85,7 +85,7 @@ #define _I2CBASE (0x2000) /* I2C driver commands */ #define _SPIBASE (0x2100) /* SPI driver commands */ #define _GPIOBASE (0x2200) /* GPIO driver commands */ -#define _CLIOCBASE (0x1200) /* Contactless modules ioctl commands */ +#define _CLIOCBASE (0x2300) /* Contactless modules ioctl commands */ /* boardctl() commands share the same number space */ From 3cc2a4f7c9bb495da6c59f373f8d0e7672e4ee13 Mon Sep 17 00:00:00 2001 From: David Sidrane Date: Wed, 15 Mar 2017 14:02:55 -1000 Subject: [PATCH 06/15] sem_holder: Fixes improper restoration of base_priority in the case of CONFIG_SEM_PREALLOCHOLDERS=0 The call to sem_restorebaseprio_task context switches in the sem_foreachholder(sem, sem_restoreholderprioB, stcb); call prior to releasing the holder. So the running task is left as a holder as is the started task. Leaving both slots filled Thus failing to perforem the boost/or restoration on the correct tcb. This PR fixes this by releasing the running task slot prior to reprioritization that can lead to the context switch. To faclitate this, the interface to sem_restorebaseprio needed to take the tcb from the holder prior to the holder being freed. In the failure case where sched_verifytcb fails it added the overhead of looking up the holder. There is also the adfitinal thunking on the foreach to get from holer to holder->tcb. An alternate approach could be to leve the interface the same and allocate a holder on the stack of sem_restoreholderprioB copy the sem's holder to it, free it as is done in this pr and and then pass that address sem_restoreholderprio as the holder. It could then get the holder's tcb but we would keep the same sem_findholder in sched_verifytcb. --- sched/semaphore/sem_holder.c | 71 +++++++++++++++++++++++++++--------- 1 file changed, 53 insertions(+), 18 deletions(-) diff --git a/sched/semaphore/sem_holder.c b/sched/semaphore/sem_holder.c index eaf443342db..bca4b4429bf 100644 --- a/sched/semaphore/sem_holder.c +++ b/sched/semaphore/sem_holder.c @@ -235,6 +235,24 @@ static inline void sem_freeholder(sem_t *sem, FAR struct semholder_s *pholder) #endif } +/**************************************************************************** + * Name: sem_findandfreeholder + ****************************************************************************/ + +static inline void sem_findandfreeholder(sem_t *sem, FAR struct tcb_s *htcb) +{ + FAR struct semholder_s *pholder = sem_findholder(sem, htcb); + + /* When no more counts are held, remove the holder from the list. The + * count was decremented in sem_releaseholder. + */ + + if (pholder != NULL && pholder->counts <= 0) + { + sem_freeholder(sem, pholder); + } +} + /**************************************************************************** * Name: sem_foreachholder ****************************************************************************/ @@ -460,10 +478,10 @@ static int sem_dumpholder(FAR struct semholder_s *pholder, FAR sem_t *sem, * Name: sem_restoreholderprio ****************************************************************************/ -static int sem_restoreholderprio(FAR struct semholder_s *pholder, +static int sem_restoreholderprio(FAR struct tcb_s *htcb, FAR sem_t *sem, FAR void *arg) { - FAR struct tcb_s *htcb = (FAR struct tcb_s *)pholder->htcb; + FAR struct semholder_s *pholder = 0; #if CONFIG_SEM_NNESTPRIO > 0 FAR struct tcb_s *stcb = (FAR struct tcb_s *)arg; int rpriority; @@ -481,7 +499,11 @@ static int sem_restoreholderprio(FAR struct semholder_s *pholder, { serr("ERROR: TCB 0x%08x is a stale handle, counts lost\n", htcb); DEBUGASSERT(!sched_verifytcb(htcb)); - sem_freeholder(sem, pholder); + pholder = sem_findholder(sem, htcb); + if (pholder != NULL) + { + sem_freeholder(sem, pholder); + } } /* Was the priority of the holder thread boosted? If so, then drop its @@ -600,6 +622,20 @@ static int sem_restoreholderprio(FAR struct semholder_s *pholder, return 0; } +/**************************************************************************** + * Name: sem_restoreholderprioall + * + * Description: + * Reprioritize all holders + * + ****************************************************************************/ + +static int sem_restoreholderprioall(FAR struct semholder_s *pholder, + FAR sem_t *sem, FAR void *arg) +{ + return sem_restoreholderprio(pholder->htcb, sem, arg); +} + /**************************************************************************** * Name: sem_restoreholderprioA * @@ -614,7 +650,7 @@ static int sem_restoreholderprioA(FAR struct semholder_s *pholder, FAR struct tcb_s *rtcb = this_task(); if (pholder->htcb != rtcb) { - return sem_restoreholderprio(pholder, sem, arg); + return sem_restoreholderprio(pholder->htcb, sem, arg); } return 0; @@ -632,9 +668,18 @@ static int sem_restoreholderprioB(FAR struct semholder_s *pholder, FAR sem_t *sem, FAR void *arg) { FAR struct tcb_s *rtcb = this_task(); + if (pholder->htcb == rtcb) { - (void)sem_restoreholderprio(pholder, sem, arg); + + /* The running task has given up a count on the semaphore + * Release the holder if all counts have been given up. + * before reprioritizing causes a context switch. + */ + + sem_findandfreeholder(sem, rtcb); + + (void)sem_restoreholderprio(rtcb, sem, arg); return 1; } @@ -687,7 +732,7 @@ static inline void sem_restorebaseprio_irq(FAR struct tcb_s *stcb, { /* Drop the priority of all holder threads */ - (void)sem_foreachholder(sem, sem_restoreholderprio, stcb); + (void)sem_foreachholder(sem, sem_restoreholderprioall, stcb); } /* If there are no tasks waiting for available counts, then all holders @@ -781,18 +826,8 @@ static inline void sem_restorebaseprio_task(FAR struct tcb_s *stcb, * counts, then we need to remove it from the list of holders. */ - pholder = sem_findholder(sem, rtcb); - if (pholder != NULL) - { - /* When no more counts are held, remove the holder from the list. The - * count was decremented in sem_releaseholder. - */ + sem_findandfreeholder(sem, rtcb); - if (pholder->counts <= 0) - { - sem_freeholder(sem, pholder); - } - } } /**************************************************************************** @@ -1097,7 +1132,7 @@ void sem_canceled(FAR struct tcb_s *stcb, FAR sem_t *sem) /* Adjust the priority of every holder as necessary */ - (void)sem_foreachholder(sem, sem_restoreholderprio, stcb); + (void)sem_foreachholder(sem, sem_restoreholderprioall, stcb); } #endif From 08e92abb0ba744927ed0b32294859b0f47726f82 Mon Sep 17 00:00:00 2001 From: David Cabecinhas Date: Thu, 16 Mar 2017 19:13:39 +0800 Subject: [PATCH 07/15] ARM: Remove redundant interrupt stack coloring --- arch/arm/src/a1x/a1x_irq.c | 10 ---------- arch/arm/src/efm32/efm32_irq.c | 10 ---------- arch/arm/src/imx6/imx_irq.c | 10 ---------- arch/arm/src/sam34/sam_irq.c | 10 ---------- arch/arm/src/sama5/sam_irq.c | 10 ---------- arch/arm/src/samv7/sam_irq.c | 10 ---------- arch/arm/src/stm32/stm32_irq.c | 10 ---------- arch/arm/src/stm32f7/stm32_irq.c | 10 ---------- arch/arm/src/stm32l4/stm32l4_irq.c | 10 ---------- arch/arm/src/tms570/tms570_irq.c | 8 -------- 10 files changed, 98 deletions(-) diff --git a/arch/arm/src/a1x/a1x_irq.c b/arch/arm/src/a1x/a1x_irq.c index ecabb5ff4d6..21c074d83ca 100644 --- a/arch/arm/src/a1x/a1x_irq.c +++ b/arch/arm/src/a1x/a1x_irq.c @@ -159,16 +159,6 @@ void up_irqinitialize(void) (void)getreg32(A1X_INTC_IRQ_PEND(i)); /* Reading status clears pending interrupts */ } - /* Colorize the interrupt stack for debug purposes */ - -#if defined(CONFIG_STACK_COLORATION) && CONFIG_ARCH_INTERRUPTSTACK > 3 - { - size_t intstack_size = (CONFIG_ARCH_INTERRUPTSTACK & ~3); - up_stack_color((FAR void *)((uintptr_t)&g_intstackbase - intstack_size), - intstack_size); - } -#endif - /* Set the interrupt base address to zero. We do not use the vectored * interrupts. */ diff --git a/arch/arm/src/efm32/efm32_irq.c b/arch/arm/src/efm32/efm32_irq.c index 859860d0725..254d196f125 100644 --- a/arch/arm/src/efm32/efm32_irq.c +++ b/arch/arm/src/efm32/efm32_irq.c @@ -319,16 +319,6 @@ void up_irqinitialize(void) putreg32(0xffffffff, NVIC_IRQ_CLEAR(i)); } -#if defined(CONFIG_STACK_COLORATION) && CONFIG_ARCH_INTERRUPTSTACK > 3 - /* Colorize the interrupt stack for debug purposes */ - - { - size_t intstack_size = (CONFIG_ARCH_INTERRUPTSTACK & ~3); - up_stack_color((FAR void *)((uintptr_t)&g_intstackbase - intstack_size), - intstack_size); - } -#endif - /* Make sure that we are using the correct vector table. The default * vector address is 0x0000:0000 but if we are executing code that is * positioned in SRAM or in external FLASH, then we may need to reset diff --git a/arch/arm/src/imx6/imx_irq.c b/arch/arm/src/imx6/imx_irq.c index b15a9a4e6dd..d5248ef40f1 100644 --- a/arch/arm/src/imx6/imx_irq.c +++ b/arch/arm/src/imx6/imx_irq.c @@ -93,16 +93,6 @@ void up_irqinitialize(void) * access to the GIC. */ - /* Colorize the interrupt stack for debug purposes */ - -#if defined(CONFIG_STACK_COLORATION) && CONFIG_ARCH_INTERRUPTSTACK > 3 - { - size_t intstack_size = (CONFIG_ARCH_INTERRUPTSTACK & ~3); - up_stack_color((FAR void *)((uintptr_t)&g_intstackbase - intstack_size), - intstack_size); - } -#endif - /* Initialize the Generic Interrupt Controller (GIC) for CPU0 */ arm_gic0_initialize(); /* Initialization unique to CPU0 */ diff --git a/arch/arm/src/sam34/sam_irq.c b/arch/arm/src/sam34/sam_irq.c index eb6b1747059..24d08cff921 100644 --- a/arch/arm/src/sam34/sam_irq.c +++ b/arch/arm/src/sam34/sam_irq.c @@ -385,16 +385,6 @@ void up_irqinitialize(void) putreg32(0, regaddr); } - /* Colorize the interrupt stack for debug purposes */ - -#if defined(CONFIG_STACK_COLORATION) && CONFIG_ARCH_INTERRUPTSTACK > 3 - { - size_t intstack_size = (CONFIG_ARCH_INTERRUPTSTACK & ~3); - up_stack_color((FAR void *)((uintptr_t)&g_intstackbase - intstack_size), - intstack_size); - } -#endif - /* Make sure that we are using the correct vector table. The default * vector address is 0x0000:0000 but if we are executing code that is * positioned in SRAM or in external FLASH, then we may need to reset diff --git a/arch/arm/src/sama5/sam_irq.c b/arch/arm/src/sama5/sam_irq.c index c8cf1f5cd54..fd4dfd8c5cc 100644 --- a/arch/arm/src/sama5/sam_irq.c +++ b/arch/arm/src/sama5/sam_irq.c @@ -431,16 +431,6 @@ void up_irqinitialize(void) * access to the AIC. */ - /* Colorize the interrupt stack for debug purposes */ - -#if defined(CONFIG_STACK_COLORATION) && CONFIG_ARCH_INTERRUPTSTACK > 3 - { - size_t intstack_size = (CONFIG_ARCH_INTERRUPTSTACK & ~3); - up_stack_color((FAR void *)((uintptr_t)&g_intstackbase - intstack_size), - intstack_size); - } -#endif - /* Redirect all interrupts to the AIC if so configured */ sam_aic_redirection(); diff --git a/arch/arm/src/samv7/sam_irq.c b/arch/arm/src/samv7/sam_irq.c index f2e44893298..15910d24d6f 100644 --- a/arch/arm/src/samv7/sam_irq.c +++ b/arch/arm/src/samv7/sam_irq.c @@ -381,16 +381,6 @@ void up_irqinitialize(void) putreg32(0, regaddr); } - /* Colorize the interrupt stack for debug purposes */ - -#if defined(CONFIG_STACK_COLORATION) && CONFIG_ARCH_INTERRUPTSTACK > 3 - { - size_t intstack_size = (CONFIG_ARCH_INTERRUPTSTACK & ~3); - up_stack_color((FAR void *)((uintptr_t)&g_intstackbase - intstack_size), - intstack_size); - } -#endif - /* Make sure that we are using the correct vector table. The default * vector address is 0x0000:0000 but if we are executing code that is * positioned in SRAM or in external FLASH, then we may need to reset diff --git a/arch/arm/src/stm32/stm32_irq.c b/arch/arm/src/stm32/stm32_irq.c index 051c9829794..2a51836a52a 100644 --- a/arch/arm/src/stm32/stm32_irq.c +++ b/arch/arm/src/stm32/stm32_irq.c @@ -310,16 +310,6 @@ void up_irqinitialize(void) putreg32(0xffffffff, NVIC_IRQ_CLEAR(i)); } - /* Colorize the interrupt stack for debug purposes */ - -#if defined(CONFIG_STACK_COLORATION) && CONFIG_ARCH_INTERRUPTSTACK > 3 - { - size_t intstack_size = (CONFIG_ARCH_INTERRUPTSTACK & ~3); - up_stack_color((FAR void *)((uintptr_t)&g_intstackbase - intstack_size), - intstack_size); - } -#endif - /* The standard location for the vector table is at the beginning of FLASH * at address 0x0800:0000. If we are using the STMicro DFU bootloader, then * the vector table will be offset to a different location in FLASH and we diff --git a/arch/arm/src/stm32f7/stm32_irq.c b/arch/arm/src/stm32f7/stm32_irq.c index b2407501036..fc6a207854a 100644 --- a/arch/arm/src/stm32f7/stm32_irq.c +++ b/arch/arm/src/stm32f7/stm32_irq.c @@ -415,16 +415,6 @@ void up_irqinitialize(void) putreg32(0, regaddr); } - /* Colorize the interrupt stack for debug purposes */ - -#if defined(CONFIG_STACK_COLORATION) && CONFIG_ARCH_INTERRUPTSTACK > 3 - { - size_t intstack_size = (CONFIG_ARCH_INTERRUPTSTACK & ~3); - up_stack_color((FAR void *)((uintptr_t)&g_intstackbase - intstack_size), - intstack_size); - } -#endif - /* Make sure that we are using the correct vector table. The default * vector address is 0x0000:0000 but if we are executing code that is * positioned in SRAM or in external FLASH, then we may need to reset diff --git a/arch/arm/src/stm32l4/stm32l4_irq.c b/arch/arm/src/stm32l4/stm32l4_irq.c index 7a0ed88bd37..4b401d88301 100644 --- a/arch/arm/src/stm32l4/stm32l4_irq.c +++ b/arch/arm/src/stm32l4/stm32l4_irq.c @@ -304,16 +304,6 @@ void up_irqinitialize(void) putreg32(0xffffffff, NVIC_IRQ_CLEAR(i)); } - /* Colorize the interrupt stack for debug purposes */ - -#if defined(CONFIG_STACK_COLORATION) && CONFIG_ARCH_INTERRUPTSTACK > 3 - { - size_t intstack_size = (CONFIG_ARCH_INTERRUPTSTACK & ~3); - up_stack_color((FAR void *)((uintptr_t)&g_intstackbase - intstack_size), - intstack_size); - } -#endif - /* The standard location for the vector table is at the beginning of FLASH * at address 0x0800:0000. If we are using the STMicro DFU bootloader, then * the vector table will be offset to a different location in FLASH and we diff --git a/arch/arm/src/tms570/tms570_irq.c b/arch/arm/src/tms570/tms570_irq.c index 99032611997..11d606d637e 100644 --- a/arch/arm/src/tms570/tms570_irq.c +++ b/arch/arm/src/tms570/tms570_irq.c @@ -115,14 +115,6 @@ void up_irqinitialize(void) FAR uintptr_t *vimram; int i; - /* Colorize the interrupt stack for debug purposes */ - -#if defined(CONFIG_STACK_COLORATION) && CONFIG_ARCH_INTERRUPTSTACK > 3 - size_t intstack_size = (CONFIG_ARCH_INTERRUPTSTACK & ~3); - up_stack_color((FAR void *)((uintptr_t)&g_intstackbase - intstack_size), - intstack_size); -#endif - /* Initialize VIM RAM vectors. These vectors are not used in the current * interrupt handler logic. */ From 4b65817e99cbdf04fefad883eca0e7c8a9add63c Mon Sep 17 00:00:00 2001 From: David Cabecinhas Date: Thu, 16 Mar 2017 19:58:50 +0800 Subject: [PATCH 08/15] ARM: Set EABI stack alignment for all ARM architectures (remove OABI code) --- arch/arm/src/common/up_createstack.c | 23 ++++++----------------- arch/arm/src/common/up_stackframe.c | 17 +++-------------- arch/arm/src/common/up_usestack.c | 23 ++++++----------------- arch/arm/src/common/up_vfork.c | 17 +++-------------- 4 files changed, 18 insertions(+), 62 deletions(-) diff --git a/arch/arm/src/common/up_createstack.c b/arch/arm/src/common/up_createstack.c index 70d83a83a58..4503e15532e 100644 --- a/arch/arm/src/common/up_createstack.c +++ b/arch/arm/src/common/up_createstack.c @@ -66,22 +66,11 @@ # define HAVE_KERNEL_HEAP 1 #endif -/* ARM requires at least a 4-byte stack alignment. For use with EABI and - * floating point, the stack must be aligned to 8-byte addresses. +/* For use with EABI and floating point, the stack must be aligned to 8-byte + * addresses. */ -#ifndef CONFIG_STACK_ALIGNMENT - -/* The symbol __ARM_EABI__ is defined by GCC if EABI is being used. If you - * are not using GCC, make sure that CONFIG_STACK_ALIGNMENT is set correctly! - */ - -# ifdef __ARM_EABI__ -# define CONFIG_STACK_ALIGNMENT 8 -# else -# define CONFIG_STACK_ALIGNMENT 4 -# endif -#endif +#define CONFIG_STACK_ALIGNMENT 8 /* Stack alignment macros */ @@ -233,9 +222,9 @@ int up_create_stack(FAR struct tcb_s *tcb, size_t stack_size, uint8_t ttype) top_of_stack = (uint32_t)tcb->stack_alloc_ptr + stack_size - 4; - /* The ARM stack must be aligned; 4 byte alignment for OABI and - * 8-byte alignment for EABI. If necessary top_of_stack must be - * rounded down to the next boundary + /* The ARM stack must be aligned to 8-byte alignment for EABI. + * If necessary top_of_stack must be rounded down to the next + * boundary */ top_of_stack = STACK_ALIGN_DOWN(top_of_stack); diff --git a/arch/arm/src/common/up_stackframe.c b/arch/arm/src/common/up_stackframe.c index b5712b2a291..dace2e9239f 100644 --- a/arch/arm/src/common/up_stackframe.c +++ b/arch/arm/src/common/up_stackframe.c @@ -53,22 +53,11 @@ * Pre-processor Macros ****************************************************************************/ -/* ARM requires at least a 4-byte stack alignment. For use with EABI and - * floating point, the stack must be aligned to 8-byte addresses. +/* For use with EABI and floating point, the stack must be aligned to 8-byte + * addresses. */ -#ifndef CONFIG_STACK_ALIGNMENT - -/* The symbol __ARM_EABI__ is defined by GCC if EABI is being used. If you - * are not using GCC, make sure that CONFIG_STACK_ALIGNMENT is set correctly! - */ - -# ifdef __ARM_EABI__ -# define CONFIG_STACK_ALIGNMENT 8 -# else -# define CONFIG_STACK_ALIGNMENT 4 -# endif -#endif +#define CONFIG_STACK_ALIGNMENT 8 /* Stack alignment macros */ diff --git a/arch/arm/src/common/up_usestack.c b/arch/arm/src/common/up_usestack.c index 887387976ae..f8072a66d4e 100644 --- a/arch/arm/src/common/up_usestack.c +++ b/arch/arm/src/common/up_usestack.c @@ -56,22 +56,11 @@ * Pre-processor Macros ****************************************************************************/ -/* ARM requires at least a 4-byte stack alignment. For use with EABI and - * floating point, the stack must be aligned to 8-byte addresses. +/* For use with EABI and floating point, the stack must be aligned to 8-byte + * addresses. */ -#ifndef CONFIG_STACK_ALIGNMENT - -/* The symbol __ARM_EABI__ is defined by GCC if EABI is being used. If you - * are not using GCC, make sure that CONFIG_STACK_ALIGNMENT is set correctly! - */ - -# ifdef __ARM_EABI__ -# define CONFIG_STACK_ALIGNMENT 8 -# else -# define CONFIG_STACK_ALIGNMENT 4 -# endif -#endif +#define CONFIG_STACK_ALIGNMENT 8 /* Stack alignment macros */ @@ -143,9 +132,9 @@ int up_use_stack(struct tcb_s *tcb, void *stack, size_t stack_size) top_of_stack = (uint32_t)tcb->stack_alloc_ptr + stack_size - 4; - /* The ARM stack must be aligned; 4 byte alignment for OABI and 8-byte - * alignment for EABI. If necessary top_of_stack must be rounded down - * to the next boundary + /* The ARM stack must be aligned to 8-byte alignment for EABI. + * If necessary top_of_stack must be rounded down to the next + * boundary */ top_of_stack = STACK_ALIGN_DOWN(top_of_stack); diff --git a/arch/arm/src/common/up_vfork.c b/arch/arm/src/common/up_vfork.c index e655ab15b43..5a69e310e38 100644 --- a/arch/arm/src/common/up_vfork.c +++ b/arch/arm/src/common/up_vfork.c @@ -56,22 +56,11 @@ * Pre-processor Definitions ****************************************************************************/ -/* ARM requires at least a 4-byte stack alignment. For use with EABI and - * floating point, the stack must be aligned to 8-byte addresses. +/* For use with EABI and floating point, the stack must be aligned to 8-byte + * addresses. */ -#ifndef CONFIG_STACK_ALIGNMENT - -/* The symbol __ARM_EABI__ is defined by GCC if EABI is being used. If you - * are not using GCC, make sure that CONFIG_STACK_ALIGNMENT is set correctly! - */ - -# ifdef __ARM_EABI__ -# define CONFIG_STACK_ALIGNMENT 8 -# else -# define CONFIG_STACK_ALIGNMENT 4 -# endif -#endif +#define CONFIG_STACK_ALIGNMENT 8 /**************************************************************************** * Public Functions From 1280c915648cf1f74969130b8dccc896effd2547 Mon Sep 17 00:00:00 2001 From: no1wudi <757509347@qq.com> Date: Thu, 16 Mar 2017 23:04:52 +0800 Subject: [PATCH 09/15] fixed descritpions of NUC100/120 --- arch/arm/Kconfig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/arm/Kconfig b/arch/arm/Kconfig index fd44dcff077..9be59af0009 100644 --- a/arch/arm/Kconfig +++ b/arch/arm/Kconfig @@ -156,7 +156,7 @@ config ARCH_CHIP_NUC1XX select ARCH_CORTEXM0 select ARCH_HAVE_CMNVECTOR ---help--- - NPX LPC43XX architectures (ARM Cortex-M4). + Nuvoton NUC100/120 architectures (ARM Cortex-M0). config ARCH_CHIP_SAMA5 bool "Atmel SAMA5" From c3ccfab720bb0d0e922c2243e9c183d9e3b76dc9 Mon Sep 17 00:00:00 2001 From: Alan Carvalho de Assis Date: Thu, 16 Mar 2017 11:40:03 -0600 Subject: [PATCH 10/15] Fix mksyscall host binary name --- syscall/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/syscall/Makefile b/syscall/Makefile index 14c0c4dea50..94fa8cdfdb9 100644 --- a/syscall/Makefile +++ b/syscall/Makefile @@ -39,7 +39,7 @@ DELIM ?= $(strip /) include proxies$(DELIM)Make.defs include stubs$(DELIM)Make.defs -MKSYSCALL = "$(TOPDIR)$(DELIM)tools$(DELIM)mksyscall$(EXEEXT)" +MKSYSCALL = "$(TOPDIR)$(DELIM)tools$(DELIM)mksyscall$(HOSTEXEEXT)" CSVFILE = "$(TOPDIR)$(DELIM)syscall$(DELIM)syscall.csv" STUB_SRCS += syscall_funclookup.c syscall_stublookup.c syscall_nparms.c From 7601a27cee348f70bebcac95e8e8372fe0651bbf Mon Sep 17 00:00:00 2001 From: David Sidrane Date: Thu, 16 Mar 2017 14:16:18 -1000 Subject: [PATCH 11/15] sem_holder:The logic for the list version is unchanged --- sched/semaphore/sem_holder.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/sched/semaphore/sem_holder.c b/sched/semaphore/sem_holder.c index bca4b4429bf..bc5c186e6bf 100644 --- a/sched/semaphore/sem_holder.c +++ b/sched/semaphore/sem_holder.c @@ -672,13 +672,17 @@ static int sem_restoreholderprioB(FAR struct semholder_s *pholder, if (pholder->htcb == rtcb) { - /* The running task has given up a count on the semaphore - * Release the holder if all counts have been given up. - * before reprioritizing causes a context switch. + /* The running task has given up a count on the semaphore */ + +#if CONFIG_SEM_PREALLOCHOLDERS == 0 + /* In the case where there are only 2 holders. This step + * is necessary to insure we have space. Release the holder + * if all counts have been given up. before reprioritizing + * causes a context switch. */ sem_findandfreeholder(sem, rtcb); - +#endif (void)sem_restoreholderprio(rtcb, sem, arg); return 1; } From ac0d957f26a8214835df6cfcd0bfcd89d6ce863e Mon Sep 17 00:00:00 2001 From: Jussi Kivilinna Date: Fri, 17 Mar 2017 17:32:44 -0600 Subject: [PATCH 12/15] libc: printf: fix precision for string formatting. Fixes use of format precision to truncate input string. --- libc/stdio/lib_libvsprintf.c | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/libc/stdio/lib_libvsprintf.c b/libc/stdio/lib_libvsprintf.c index 894f0404538..1a3501c704a 100644 --- a/libc/stdio/lib_libvsprintf.c +++ b/libc/stdio/lib_libvsprintf.c @@ -1171,9 +1171,7 @@ int lib_vsprintf(FAR struct lib_outstream_s *obj, FAR const IPTR char *src, FAR char *ptmp; #ifndef CONFIG_NOPRINTF_FIELDWIDTH int width; -#ifdef CONFIG_LIBC_FLOATINGPOINT int trunc; -#endif uint8_t fmt; #endif uint8_t flags; @@ -1215,9 +1213,7 @@ int lib_vsprintf(FAR struct lib_outstream_s *obj, FAR const IPTR char *src, #ifndef CONFIG_NOPRINTF_FIELDWIDTH fmt = FMT_RJUST; width = 0; -#ifdef CONFIG_LIBC_FLOATINGPOINT trunc = 0; -#endif #endif /* Process each format qualifier. */ @@ -1265,10 +1261,8 @@ int lib_vsprintf(FAR struct lib_outstream_s *obj, FAR const IPTR char *src, int value = va_arg(ap, int); if (IS_HASDOT(flags)) { -#ifdef CONFIG_LIBC_FLOATINGPOINT trunc = value; SET_HASASTERISKTRUNC(flags); -#endif } else { @@ -1307,9 +1301,7 @@ int lib_vsprintf(FAR struct lib_outstream_s *obj, FAR const IPTR char *src, if (IS_HASDOT(flags)) { -#ifdef CONFIG_LIBC_FLOATINGPOINT trunc = n; -#endif } else { @@ -1361,6 +1353,7 @@ int lib_vsprintf(FAR struct lib_outstream_s *obj, FAR const IPTR char *src, { #ifndef CONFIG_NOPRINTF_FIELDWIDTH int swidth; + int left; #endif /* Get the string to output */ @@ -1375,13 +1368,21 @@ int lib_vsprintf(FAR struct lib_outstream_s *obj, FAR const IPTR char *src, */ #ifndef CONFIG_NOPRINTF_FIELDWIDTH - swidth = strlen(ptmp); + swidth = (IS_HASDOT(flags) && trunc >= 0) + ? strnlen(ptmp, trunc) : strlen(ptmp); prejustify(obj, fmt, 0, width, swidth); + left = swidth; #endif /* Concatenate the string into the output */ while (*ptmp) { +#ifndef CONFIG_NOPRINTF_FIELDWIDTH + if (left-- <= 0) + { + break; + } +#endif obj->put(obj, *ptmp); ptmp++; } From acec5e3199e13e2d772e3340b2f73a0bf424c5d9 Mon Sep 17 00:00:00 2001 From: Jussi Kivilinna Date: Fri, 17 Mar 2017 17:34:56 -0600 Subject: [PATCH 13/15] vsnprintf(): If size is zero, then vsnprintf() should return the size of the required buffer without writing anything. This is same fix that was done for snprintf in 2014 by commit 59846a8fe928abb389e3776ebdbb52022da45be3. --- libc/stdio/lib_vsnprintf.c | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/libc/stdio/lib_vsnprintf.c b/libc/stdio/lib_vsnprintf.c index d25fc0d2d53..40f7dffc502 100644 --- a/libc/stdio/lib_vsnprintf.c +++ b/libc/stdio/lib_vsnprintf.c @@ -55,17 +55,38 @@ int vsnprintf(FAR char *buf, size_t size, FAR const IPTR char *format, va_list ap) { - struct lib_memoutstream_s memoutstream; - int n; + union + { + struct lib_outstream_s nulloutstream; + struct lib_memoutstream_s memoutstream; + } u; - /* Initialize a memory stream to write to the buffer */ + FAR struct lib_outstream_s *stream; + int n; - lib_memoutstream((FAR struct lib_memoutstream_s *)&memoutstream, - buf, size); + /* "If the value of [size] is zero on a call to vsnprintf(), nothing shall + * be written, the number of bytes that would have been written had [size] + * been sufficiently large excluding the terminating null shall be returned, + * and [buf] may be a null pointer." -- opengroup.org + */ + + if (size > 0) + { + /* Initialize a memory stream to write to the buffer */ + + lib_memoutstream(&u.memoutstream, buf, size); + stream = &u.memoutstream.public; + } + else + { + /* Use a null stream to get the size of the buffer */ + + lib_nulloutstream(&u.nulloutstream); + stream = &u.nulloutstream; + } /* Then let lib_vsprintf do the real work */ - n = lib_vsprintf((FAR struct lib_outstream_s *)&memoutstream.public, - format, ap); + n = lib_vsprintf(stream, format, ap); return n; } From 0a95536b850ce4a8513989ab9c6b088e84a122a3 Mon Sep 17 00:00:00 2001 From: Brian Webb Date: Fri, 17 Mar 2017 20:35:49 -0700 Subject: [PATCH 14/15] Adds driver support for the XBox One controller. Currently only the latest version (XBox One X) controller works. The older XBox One controllers do not enumerate correctly. --- configs/stm32f4discovery/src/stm32_usb.c | 13 +- drivers/usbhost/Kconfig | 32 + drivers/usbhost/Make.defs | 4 + drivers/usbhost/usbhost_xboxcontroller.c | 2195 ++++++++++++++++++++++ include/nuttx/input/xbox-controller.h | 88 + include/nuttx/usb/usbhost.h | 21 + 6 files changed, 2352 insertions(+), 1 deletion(-) create mode 100644 drivers/usbhost/usbhost_xboxcontroller.c create mode 100644 include/nuttx/input/xbox-controller.h diff --git a/configs/stm32f4discovery/src/stm32_usb.c b/configs/stm32f4discovery/src/stm32_usb.c index c929c1bfe2c..f0d2e161705 100644 --- a/configs/stm32f4discovery/src/stm32_usb.c +++ b/configs/stm32f4discovery/src/stm32_usb.c @@ -167,7 +167,8 @@ int stm32_usbhost_initialize(void) { int pid; #if defined(CONFIG_USBHOST_HUB) || defined(CONFIG_USBHOST_MSC) || \ - defined(CONFIG_USBHOST_HIDKBD) || defined(CONFIG_USBHOST_HIDMOUSE) + defined(CONFIG_USBHOST_HIDKBD) || defined(CONFIG_USBHOST_HIDMOUSE) || \ + defined(CONFIG_USBHOST_XBOXCONTROLLER) int ret; #endif @@ -227,6 +228,16 @@ int stm32_usbhost_initialize(void) } #endif +#ifdef CONFIG_USBHOST_XBOXCONTROLLER + /* Initialize the HID mouse class */ + + ret = usbhost_xboxcontroller_init(); + if (ret != OK) + { + uerr("ERROR: Failed to register the XBox Controller class\n"); + } +#endif + /* Then get an instance of the USB host interface */ uinfo("Initialize USB host\n"); diff --git a/drivers/usbhost/Kconfig b/drivers/usbhost/Kconfig index 334e393f51c..5e49aa7b864 100644 --- a/drivers/usbhost/Kconfig +++ b/drivers/usbhost/Kconfig @@ -521,6 +521,38 @@ config RTL8187_PID endif # USBHOST_RTL8187 +config USBHOST_XBOXCONTROLLER + bool "Xbox Controller Support" + default n + depends on !INT_DISABLE + select INPUT + ---help--- + Enable support for the Xbox Controller driver. + +if USBHOST_XBOXCONTROLLER + +config XBOXCONTROLLER_DEFPRIO + int "Polling Thread Priority" + default 50 + ---help--- + Priority of the polling thread. Default: 50. + +config XBOXCONTROLLER_STACKSIZE + int "Polling thread stack size" + default 1024 + ---help--- + Stack size for polling thread. Default: 1024 + +config XBOXCONTROLLER_NPOLLWAITERS + int "Max Number of Waiters for Poll Event" + default 2 + depends on !DISABLE_POLL + ---help--- + If the poll() method is enabled, this defines the maximum number + of threads that can be waiting for mouse events. Default: 2. + +endif # USBHOST_XBOXCONTROLLER + config USBHOST_TRACE bool "Enable USB HCD tracing for debug" default n diff --git a/drivers/usbhost/Make.defs b/drivers/usbhost/Make.defs index fd28be8766f..105156aee36 100644 --- a/drivers/usbhost/Make.defs +++ b/drivers/usbhost/Make.defs @@ -66,6 +66,10 @@ ifeq ($(CONFIG_USBHOST_HIDMOUSE),y) CSRCS += usbhost_hidmouse.c endif +ifeq ($(CONFIG_USBHOST_XBOXCONTROLLER),y) +CSRCS += usbhost_xboxcontroller.c +endif + # HCD debug/trace logic ifeq ($(CONFIG_USBHOST_TRACE),y) diff --git a/drivers/usbhost/usbhost_xboxcontroller.c b/drivers/usbhost/usbhost_xboxcontroller.c new file mode 100644 index 00000000000..fd12efee975 --- /dev/null +++ b/drivers/usbhost/usbhost_xboxcontroller.c @@ -0,0 +1,2195 @@ +/**************************************************************************** + * drivers/usbhost/usbhost_xboxcontroller.c + * + * Copyright (C) 2016 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/* Configuration ************************************************************/ + +#ifndef CONFIG_SCHED_WORKQUEUE +# warning "Worker thread support is required (CONFIG_SCHED_WORKQUEUE)" +#endif + +#ifndef CONFIG_XBOXCONTROLLER_DEFPRIO +# define CONFIG_XBOXCONTROLLER_DEFPRIO 50 +#endif + +#ifndef CONFIG_XBOXCONTROLLER_STACKSIZE +# define CONFIG_XBOXCONTROLLER_STACKSIZE 1024 +#endif + +#ifndef CONFIG_XBOXCONTROLLER_NPOLLWAITERS +# define CONFIG_XBOXCONTROLLER_NPOLLWAITERS 2 +#endif + +/* Driver support ***********************************************************/ +/* This format is used to construct the /dev/xbox[n] device driver path. It + * defined here so that it will be used consistently in all places. + */ + +#define DEV_FORMAT "/dev/xbox%c" +#define DEV_NAMELEN 11 + +/* Used in usbhost_cfgdesc() */ + +#define USBHOST_IFFOUND 0x01 +#define USBHOST_EPINFOUND 0x02 /* Required interrupt IN EP descriptor found */ +#define USBHOST_EPOUTFOUND 0x04 /* Required interrupt OUT EP descriptor found */ +#define USBHOST_ALLFOUND 0x07 + +#define USBHOST_MAX_CREFS 0x7fff + +/* Received message types */ + +#define USBHOST_WAITING_CONNECTION 0x02 +#define USBHOST_GUIDE_BUTTON_STATUS 0x07 +#define USBHOST_BUTTON_DATA 0x20 + +/* Button definitions */ + +#define XBOX_BUTTON_GUIDE_INDEX 4 +#define XBOX_BUTTON_SYNC_INDEX 4 +#define XBOX_BUTTON_SYNC_MASK (1 << 0) +#define XBOX_BUTTON_START_INDEX 4 +#define XBOX_BUTTON_START_MASK (1 << 2) +#define XBOX_BUTTON_BACK_INDEX 4 +#define XBOX_BUTTON_BACK_MASK (1 << 3) +#define XBOX_BUTTON_A_INDEX 4 +#define XBOX_BUTTON_A_MASK (1 << 4) +#define XBOX_BUTTON_B_INDEX 4 +#define XBOX_BUTTON_B_MASK (1 << 5) +#define XBOX_BUTTON_X_INDEX 4 +#define XBOX_BUTTON_X_MASK (1 << 6) +#define XBOX_BUTTON_Y_INDEX 4 +#define XBOX_BUTTON_Y_MASK (1 << 7) +#define XBOX_BUTTON_DPAD_UP_INDEX 5 +#define XBOX_BUTTON_DPAD_UP_MASK (1 << 0) +#define XBOX_BUTTON_DPAD_DOWN_INDEX 5 +#define XBOX_BUTTON_DPAD_DOWN_MASK (1 << 1) +#define XBOX_BUTTON_DPAD_LEFT_INDEX 5 +#define XBOX_BUTTON_DPAD_LEFT_MASK (1 << 2) +#define XBOX_BUTTON_DPAD_RIGHT_INDEX 5 +#define XBOX_BUTTON_DPAD_RIGHT_MASK (1 << 3) +#define XBOX_BUTTON_BUMPER_LEFT_INDEX 5 +#define XBOX_BUTTON_BUMPER_LEFT_MASK (1 << 4) +#define XBOX_BUTTON_BUMPER_RIGHT_INDEX 5 +#define XBOX_BUTTON_BUMPER_RIGHT_MASK (1 << 5) +#define XBOX_BUTTON_STICK_LEFT_INDEX 5 +#define XBOX_BUTTON_STICK_LEFT_MASK (1 << 6) +#define XBOX_BUTTON_STICK_RIGHT_INDEX 5 +#define XBOX_BUTTON_STICK_RIGHT_MASK (1 << 7) +#define XBOX_BUTTON_TRIGGER_LEFT 3 +#define XBOX_BUTTON_TRIGGER_RIGHT 4 +#define XBOX_BUTTON_STICK_LEFT_X 5 +#define XBOX_BUTTON_STICK_LEFT_Y 6 +#define XBOX_BUTTON_STICK_RIGHT_X 7 +#define XBOX_BUTTON_STICK_RIGHT_Y 8 +#define XBOX_BUTTON_SET(buffer, index, mask) ((((buffer)[(index)] & (mask)) != 0) ? true : false); + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +/* This structure contains the internal, private state of the USB host class + * driver. + */ + +struct usbhost_state_s +{ + /* This is the externally visible portion of the state */ + + struct usbhost_class_s usbclass; + + /* The remainder of the fields are provide to the class driver */ + + char devchar; /* Character identifying the /dev/xbox[n] device */ + volatile bool disconnected; /* TRUE: Device has been disconnected */ + volatile bool polling; /* TRUE: Poll thread is running */ + volatile bool open; /* TRUE: The controller device is open */ + volatile bool valid; /* TRUE: New sample data is available */ + volatile bool initialized; /* TRUE: The initialization packet has been sent */ + uint8_t ifno; /* Interface number */ + uint8_t nwaiters; /* Number of threads waiting for controller data */ + sem_t waitsem; /* Used to wait for controller data */ + int16_t crefs; /* Reference count on the driver instance */ + sem_t exclsem; /* Used to maintain mutual exclusive access */ + struct work_s work; /* For interacting with the worker thread */ + FAR uint8_t *tbuffer; /* The allocated transfer buffer */ + FAR uint8_t obuffer[20]; /* The fixed output transfer buffer */ + size_t tbuflen; /* Size of the allocated transfer buffer */ + usbhost_ep_t epin; /* IN endpoint */ + usbhost_ep_t epout; /* OUT endpoint */ + pid_t pollpid; /* PID of the poll task */ + size_t out_seq_num; /* The sequence number for outgoing packets */ + struct xbox_controller_buttonstate_s rpt; /* The latest report out of the controller. */ +}; + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +/* Semaphores */ + +static void usbhost_takesem(sem_t *sem); +#define usbhost_givesem(s) sem_post(s); + +/* Memory allocation services */ + +static inline FAR struct usbhost_state_s *usbhost_allocclass(void); +static inline void usbhost_freeclass(FAR struct usbhost_state_s *usbclass); + +/* Device name management */ + +static int usbhost_allocdevno(FAR struct usbhost_state_s *priv); +static void usbhost_freedevno(FAR struct usbhost_state_s *priv); +static inline void usbhost_mkdevname(FAR struct usbhost_state_s *priv, + FAR char *devname); + +/* Worker thread actions */ + +static void usbhost_destroy(FAR void *arg); +static void usbhost_notify(FAR struct usbhost_state_s *priv); +static int usbhost_xboxcontroller_poll(int argc, char *argv[]); + +/* Helpers for usbhost_connect() */ + +static inline int usbhost_cfgdesc(FAR struct usbhost_state_s *priv, + FAR const uint8_t *configdesc, + int desclen); +static inline int usbhost_devinit(FAR struct usbhost_state_s *priv); + +/* (Little Endian) Data helpers */ + +static inline uint16_t usbhost_getle16(const uint8_t *val); +static inline void usbhost_putle16(uint8_t *dest, uint16_t val); +static inline uint32_t usbhost_getle32(const uint8_t *val); +#if 0 /* Not used */ +static void usbhost_putle32(uint8_t *dest, uint32_t val); +#endif + +/* Transfer descriptor memory management */ + +static inline int usbhost_talloc(FAR struct usbhost_state_s *priv); +static inline int usbhost_tfree(FAR struct usbhost_state_s *priv); + +/* struct usbhost_registry_s methods */ + +static struct usbhost_class_s *usbhost_create(FAR struct usbhost_hubport_s *hport, + FAR const struct usbhost_id_s *id); + +/* struct usbhost_class_s methods */ + +static int usbhost_connect(FAR struct usbhost_class_s *usbclass, + FAR const uint8_t *configdesc, int desclen); +static int usbhost_disconnected(FAR struct usbhost_class_s *usbclass); + +/* Driver methods. We export the controller as a standard character driver */ + +static int usbhost_open(FAR struct file *filep); +static int usbhost_close(FAR struct file *filep); +static ssize_t usbhost_read(FAR struct file *filep, + FAR char *buffer, size_t len); +static ssize_t usbhost_write(FAR struct file *filep, + FAR const char *buffer, size_t len); +static int usbhost_ioctl(FAR struct file* filep, int cmd, unsigned long arg); +#ifndef CONFIG_DISABLE_POLL +static int usbhost_poll(FAR struct file *filep, FAR struct pollfd *fds, + bool setup); +#endif + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/* This structure provides the registry entry ID information that will be + * used to associate the USB class driver to a connected USB device. + */ + +static const const struct usbhost_id_s g_xboxcontroller_id[] = +{ + /* XBox One classic controller */ + { + USB_CLASS_VENDOR_SPEC, /* base -- Must be one of the USB_CLASS_* definitions in usb.h */ + 0x0047, /* subclass -- depends on the device */ + 0x00d0, /* proto -- depends on the device */ + 0x045E, /* vid */ + 0x02DD /* pid */ + }, + /* XBox One S controller */ + { + USB_CLASS_VENDOR_SPEC, /* base -- Must be one of the USB_CLASS_* definitions in usb.h */ + 0x0047, /* subclass -- depends on the device */ + 0x00d0, /* proto -- depends on the device */ + 0x045E, /* vid */ + 0x02EA /* pid */ + } +}; + +/* This is the USB host storage class's registry entry */ + +static struct usbhost_registry_s g_xboxcontroller = +{ + NULL, /* flink */ + usbhost_create, /* create */ + 2, /* nids */ + g_xboxcontroller_id /* id[] */ +}; + +/* The configuration information for the block file device. */ + +static const struct file_operations g_xboxcontroller_fops = +{ + usbhost_open, /* open */ + usbhost_close, /* close */ + usbhost_read, /* read */ + usbhost_write, /* write */ + 0, /* seek */ + usbhost_ioctl /* ioctl */ +#ifndef CONFIG_DISABLE_POLL + , usbhost_poll /* poll */ +#endif +}; + +/* This is a bitmap that is used to allocate device names /dev/xboxa-z. */ + +static uint32_t g_devinuse; + +/* The following are used to managed the class creation operation */ + +static sem_t g_exclsem; /* For mutually exclusive thread creation */ +static sem_t g_syncsem; /* Thread data passing interlock */ +static struct usbhost_state_s *g_priv; /* Data passed to thread */ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: usbhost_takesem + * + * Description: + * This is just a wrapper to handle the annoying behavior of semaphore + * waits that return due to the receipt of a signal. + * + ****************************************************************************/ + +static void usbhost_takesem(sem_t *sem) +{ + /* Take the semaphore (perhaps waiting) */ + + while (sem_wait(sem) != 0) + { + /* The only case that an error should occur here is if the wait was + * awakened by a signal. + */ + + ASSERT(errno == EINTR); + } +} + +/**************************************************************************** + * Name: usbhost_allocclass + * + * Description: + * This is really part of the logic that implements the create() method + * of struct usbhost_registry_s. This function allocates memory for one + * new class instance. + * + * Input Parameters: + * None + * + * Returned Values: + * On success, this function will return a non-NULL instance of struct + * usbhost_class_s. NULL is returned on failure; this function will + * will fail only if there are insufficient resources to create another + * USB host class instance. + * + ****************************************************************************/ + +static inline FAR struct usbhost_state_s *usbhost_allocclass(void) +{ + FAR struct usbhost_state_s *priv; + + DEBUGASSERT(!up_interrupt_context()); + priv = (FAR struct usbhost_state_s *)kmm_malloc(sizeof(struct usbhost_state_s)); + uinfo("Allocated: %p\n", priv); + return priv; +} + +/**************************************************************************** + * Name: usbhost_freeclass + * + * Description: + * Free a class instance previously allocated by usbhost_allocclass(). + * + * Input Parameters: + * usbclass - A reference to the class instance to be freed. + * + * Returned Values: + * None + * + ****************************************************************************/ + +static inline void usbhost_freeclass(FAR struct usbhost_state_s *usbclass) +{ + DEBUGASSERT(usbclass != NULL); + + /* Free the class instance (perhaps calling sched_kmm_free() in case we are + * executing from an interrupt handler. + */ + + uinfo("Freeing: %p\n", usbclass); + kmm_free(usbclass); +} + +/**************************************************************************** + * Name: Device name management + * + * Description: + * Some tiny functions to coordinate management of device names. + * + ****************************************************************************/ + +static int usbhost_allocdevno(FAR struct usbhost_state_s *priv) +{ + irqstate_t flags; + int devno; + + flags = enter_critical_section(); + for (devno = 0; devno < 26; devno++) + { + uint32_t bitno = 1 << devno; + if ((g_devinuse & bitno) == 0) + { + g_devinuse |= bitno; + priv->devchar = 'a' + devno; + leave_critical_section(flags); + return OK; + } + } + + leave_critical_section(flags); + return -EMFILE; +} + +static void usbhost_freedevno(FAR struct usbhost_state_s *priv) +{ + int devno = 'a' - priv->devchar; + + if (devno >= 0 && devno < 26) + { + irqstate_t flags = enter_critical_section(); + g_devinuse &= ~(1 << devno); + leave_critical_section(flags); + } +} + +static inline void usbhost_mkdevname(FAR struct usbhost_state_s *priv, + FAR char *devname) +{ + (void)snprintf(devname, DEV_NAMELEN, DEV_FORMAT, priv->devchar); +} + +/**************************************************************************** + * Name: usbhost_destroy + * + * Description: + * The USB device has been disconnected and the reference count on the USB + * host class instance has gone to 1.. Time to destroy the USB host class + * instance. + * + * Input Parameters: + * arg - A reference to the class instance to be destroyed. + * + * Returned Values: + * None + * + ****************************************************************************/ + +static void usbhost_destroy(FAR void *arg) +{ + FAR struct usbhost_state_s *priv = (FAR struct usbhost_state_s *)arg; + FAR struct usbhost_hubport_s *hport; + char devname[DEV_NAMELEN]; + + DEBUGASSERT(priv != NULL && priv->usbclass.hport != NULL); + uinfo("crefs: %d\n", priv->crefs); + + hport = priv->usbclass.hport; + + DEBUGASSERT(hport->drvr); + + uinfo("crefs: %d\n", priv->crefs); + + /* Unregister the driver */ + + uinfo("Unregister driver\n"); + usbhost_mkdevname(priv, devname); + (void)unregister_driver(devname); + + /* Release the device name used by this connection */ + + usbhost_freedevno(priv); + + /* Free the interrupt endpoints */ + + if (priv->epin) + { + DRVR_EPFREE(hport->drvr, priv->epin); + } + + /* Free any transfer buffers */ + + usbhost_tfree(priv); + + /* Destroy the semaphores */ + + sem_destroy(&priv->exclsem); + sem_destroy(&priv->waitsem); + + /* Disconnect the USB host device */ + + DRVR_DISCONNECT(hport->drvr, hport); + + /* Free the function address assigned to this device */ + + usbhost_devaddr_destroy(hport, hport->funcaddr); + hport->funcaddr = 0; + + /* And free the class instance. */ + + usbhost_freeclass(priv); +} + +/**************************************************************************** + * Name: usbhost_notify + * + * Description: + * Wake any threads waiting for controller data + * + * Input Paramters: + * priv - A reference to the controller state structure. + * + * Returned Value: + * None + * + ****************************************************************************/ + +static void usbhost_notify(FAR struct usbhost_state_s *priv) +{ +#ifndef CONFIG_DISABLE_POLL + int i; +#endif + + /* If there are threads waiting for read data, then signal one of them + * that the read data is available. + */ + + if (priv->nwaiters > 0) + { + sem_post(&priv->waitsem); + } + + /* If there are threads waiting on poll() for controller data to become available, + * then wake them up now. NOTE: we wake up all waiting threads because we + * do not know that they are going to do. If they all try to read the data, + * then some make end up blocking after all. + */ + +#ifndef CONFIG_DISABLE_POLL + for (i = 0; i < CONFIG_XBOXCONTROLLER_NPOLLWAITERS; i++) + { + struct pollfd *fds = priv->fds[i]; + if (fds) + { + fds->revents |= POLLIN; + iinfo("Report events: %02x\n", fds->revents); + sem_post(fds->sem); + } + } +#endif +} + +/**************************************************************************** + * Name: usbhost_xboxcontroller_poll + * + * Description: + * Periodically check for new controller data. + * + * Input Parameters: + * arg - A reference to the class instance to be destroyed. + * + * Returned Values: + * None + * + ****************************************************************************/ + +static int usbhost_xboxcontroller_poll(int argc, char *argv[]) +{ + FAR struct usbhost_state_s *priv; + FAR struct usbhost_hubport_s *hport; + irqstate_t flags; +#if defined(CONFIG_DEBUG_USB) && defined(CONFIG_DEBUG_INFO) + unsigned int npolls = 0; +#endif + unsigned int nerrors = 0; + ssize_t nbytes; + int ret = OK; + + /* Synchronize with the start-up logic. Get the private instance, re-start + * the start-up logic, and wait a bit to make sure that all of the class + * creation logic has a chance to run to completion. + * + * NOTE: that the reference count is *not* incremented here. When the driver + * structure was created, it was created with a reference count of one. This + * thread is responsible for that count. The count will be decrement when + * this thread exits. + */ + + priv = g_priv; + DEBUGASSERT(priv != NULL && priv->usbclass.hport != NULL); + hport = priv->usbclass.hport; + + priv->polling = true; + usbhost_givesem(&g_syncsem); + sleep(1); + + /* Loop here until the device is disconnected */ + + uinfo("Entering poll loop\n"); + + while (!priv->disconnected) + { + /* Read the next ccontroller report. We will stall here until the + * controller sends data. + */ + + nbytes = DRVR_TRANSFER(hport->drvr, priv->epin, + priv->tbuffer, priv->tbuflen); + + /* Check for errors -- Bail if an excessive number of consecutive + * errors are encountered. + */ + + if (nbytes < 0) + { + /* If DRVR_TRANSFER() returns EAGAIN, that simply means that + * the devices was not ready and has NAK'ed the transfer. That + * should not be treated as an error (unless it persists for a + * long time). + */ + + if (nbytes != -EAGAIN) + { + + uerr("ERROR: DRVR_TRANSFER returned: %d/%u\n", + (int)nbytes, nerrors); + + if (++nerrors > 200) + { + uerr(" Too many errors... aborting: %d\n", nerrors); + ret = (int)nbytes; + break; + } + } + } + + /* The report was received correctly. */ + + else + { + + /* Success, reset the error counter */ + + nerrors = 0; + + /* The type of message is in the first byte */ + switch (priv->tbuffer[0]) + { + + case USBHOST_WAITING_CONNECTION: + + /* Send the initialization message when we received the + * the first waiting connection message. + */ + + if (!priv->initialized) { + + /* Get exclusive access to the controller state data */ + + usbhost_takesem(&priv->exclsem); + + priv->tbuffer[0] = 0x05; + priv->tbuffer[1] = 0x20; + priv->tbuffer[2] = priv->out_seq_num++; + priv->tbuffer[3] = 0x01; + priv->tbuffer[4] = 0x00; + nbytes = DRVR_TRANSFER(hport->drvr, priv->epout, + priv->tbuffer, 5); + priv->initialized = true; + + /* Release our lock on the state structure */ + + usbhost_givesem(&priv->exclsem); + } + + break; + + case USBHOST_GUIDE_BUTTON_STATUS: + + /* Get exclusive access to the controller state data */ + + usbhost_takesem(&priv->exclsem); + + /* Read the data out of the controller report. */ + + priv->rpt.guide = (priv->tbuffer[XBOX_BUTTON_GUIDE_INDEX] != 0) ? true : false; + + priv->valid = true; + + /* The One X controller requires an ACK of the guide button status message. */ + + if (priv->tbuffer[1] == 0x30) + { + + static const uint8_t guide_button_report_ack[] = { + 0x01, 0x20, 0x00, 0x09, 0x00, 0x07, 0x20, 0x02, + 0x00, 0x00, 0x00, 0x00, 0x00 + }; + + /* Remember the input packet sequence number. */ + + uint8_t seq_num = priv->tbuffer[2]; + + /* Copy the ACK packet into the transfer buffer. */ + + memcpy(priv->tbuffer, guide_button_report_ack, sizeof(guide_button_report_ack)); + + /* Ensure the sequence number is the same as the input packet. */ + + priv->tbuffer[2] = seq_num; + + /* Perform the transfer. */ + + nbytes = DRVR_TRANSFER(hport->drvr, priv->epout, + priv->tbuffer, sizeof(guide_button_report_ack)); + } + + /* Notify any waiters that new controller data is available */ + + usbhost_notify(priv); + + /* Release our lock on the state structure */ + + usbhost_givesem(&priv->exclsem); + + break; + + case USBHOST_BUTTON_DATA: + + /* Ignore the controller data if no task has opened the driver. */ + + if (priv->open) + { + /* Get exclusive access to the controller state data */ + + usbhost_takesem(&priv->exclsem); + + /* Read the data out of the controller report. */ + + priv->rpt.sync = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_SYNC_INDEX, XBOX_BUTTON_SYNC_MASK); + priv->rpt.start = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_START_INDEX, XBOX_BUTTON_START_MASK); + priv->rpt.back = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_BACK_INDEX, XBOX_BUTTON_BACK_MASK); + priv->rpt.a = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_A_INDEX, XBOX_BUTTON_A_MASK); + priv->rpt.b = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_B_INDEX, XBOX_BUTTON_B_MASK); + priv->rpt.x = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_X_INDEX, XBOX_BUTTON_X_MASK); + priv->rpt.y = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_Y_INDEX, XBOX_BUTTON_Y_MASK); + priv->rpt.dpad_up = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_DPAD_UP_INDEX, XBOX_BUTTON_DPAD_UP_MASK); + priv->rpt.dpad_down = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_DPAD_DOWN_INDEX, XBOX_BUTTON_DPAD_DOWN_MASK); + priv->rpt.dpad_left = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_DPAD_LEFT_INDEX, XBOX_BUTTON_DPAD_LEFT_MASK); + priv->rpt.dpad_right = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_DPAD_RIGHT_INDEX, XBOX_BUTTON_DPAD_RIGHT_MASK); + priv->rpt.bumper_left = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_BUMPER_LEFT_INDEX, XBOX_BUTTON_BUMPER_LEFT_MASK); + priv->rpt.bumper_right = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_BUMPER_RIGHT_INDEX, XBOX_BUTTON_BUMPER_RIGHT_MASK); + priv->rpt.stick_click_left = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_STICK_LEFT_INDEX, XBOX_BUTTON_STICK_LEFT_MASK); + priv->rpt.stick_click_right = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_STICK_RIGHT_INDEX, XBOX_BUTTON_STICK_RIGHT_MASK); + priv->rpt.trigger_left = ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_TRIGGER_LEFT]; + priv->rpt.trigger_right = ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_TRIGGER_RIGHT]; + priv->rpt.stick_left_x = ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_STICK_LEFT_X]; + priv->rpt.stick_left_y = ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_STICK_LEFT_Y]; + priv->rpt.stick_right_x = ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_STICK_RIGHT_X]; + priv->rpt.stick_right_y = ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_STICK_RIGHT_Y]; + + priv->valid = true; + + /* Notify any waiters that new controller data is available */ + + usbhost_notify(priv); + + /* Release our lock on the state structure */ + + usbhost_givesem(&priv->exclsem); + } + + break; + + default: + + uinfo("Received messge type: %x\n", priv->tbuffer[0]); + + } + + } + + /* If USB debug is on, then provide some periodic indication that + * polling is still happening. + */ + +#if defined(CONFIG_DEBUG_USB) && defined(CONFIG_DEBUG_INFO) + npolls++; + if ((npolls & 31) == 0) + { + uinfo("Still polling: %d\n", npolls); + } +#endif + } + + /* We get here when the driver is removed.. or when too many errors have + * been encountered. + * + * Make sure that we have exclusive access to the private data structure. + * There may now be other tasks with the character driver open and actively + * trying to interact with the class driver. + */ + + usbhost_takesem(&priv->exclsem); + + /* Indicate that we are no longer running and decrement the reference + * count held by this thread. If there are no other users of the class, + * we can destroy it now. Otherwise, we have to wait until the all + * of the file descriptors are closed. + */ + + uinfo("Controller removed, polling halted\n"); + + flags = enter_critical_section(); + priv->polling = false; + + /* Decrement the reference count held by this thread. */ + + DEBUGASSERT(priv->crefs > 0); + priv->crefs--; + + /* There are two possibilities: + * 1) The reference count is greater than zero. This means that there + * are still open references to the controller driver. In this case + * we need to wait until usbhost_close() is called and all of the + * open driver references are decremented. Then usbhost_destroy() can + * be called from usbhost_close(). + * 2) The reference count is now zero. This means that there are no + * further open references and we can call usbhost_destroy() now. + */ + + if (priv->crefs < 1) + { + /* Unregister the driver and destroy the instance (while we hold + * the semaphore!) + */ + + usbhost_destroy(priv); + } + else + { + /* No, we will destroy the driver instance when it is final open + * reference is closed + */ + + usbhost_givesem(&priv->exclsem); + } + + leave_critical_section(flags); + return ret; +} + +/**************************************************************************** + * Name: usbhost_sample + * + * Description: + * Check if new controller data is available + * + * Input Parameters: + * priv - controller state instance + * sample - The location to return the sample data + * + ****************************************************************************/ + +static int usbhost_sample(FAR struct usbhost_state_s *priv, + FAR struct xbox_controller_buttonstate_s *sample) +{ + irqstate_t flags; + int ret = -EAGAIN; + + /* Interrupts me be disabled when this is called to (1) prevent posting + * of semaphores from interrupt handlers, and (2) to prevent sampled data + * from changing until it has been reported. + */ + + flags = enter_critical_section(); + + /* Is there new mouse data available? */ + + if (priv->valid) + { + /* Return a copy of the sampled data. */ + + memcpy(sample, &priv->rpt, sizeof(struct xbox_controller_buttonstate_s)); + + /* The sample has been reported and is no longer valid */ + + priv->valid = false; + ret = OK; + } + + leave_critical_section(flags); + return ret; +} + +/**************************************************************************** + * Name: usbhost_waitsample + * + * Description: + * Wait for the next valid controller sample + * + * Input Parameters: + * priv - controller state instance + * sample - The location to return the sample data + * + ****************************************************************************/ + +static int usbhost_waitsample(FAR struct usbhost_state_s *priv, + FAR struct xbox_controller_buttonstate_s *sample) +{ + irqstate_t flags; + int ret; + + /* Interrupts me be disabled when this is called to (1) prevent posting + * of semaphores from interrupt handlers, and (2) to prevent sampled data + * from changing until it has been reported. + * + * In addition, we will also disable pre-emption to prevent other threads + * from getting control while we muck with the semaphores. + */ + + sched_lock(); + flags = enter_critical_section(); + + /* Now release the semaphore that manages mutually exclusive access to + * the device structure. This may cause other tasks to become ready to + * run, but they cannot run yet because pre-emption is disabled. + */ + + sem_post(&priv->exclsem); + + /* Try to get the a sample... if we cannot, then wait on the semaphore + * that is posted when new sample data is available. + */ + + while (usbhost_sample(priv, sample) < 0) + { + /* Wait for a change in the HIDMOUSE state */ + + iinfo("Waiting..\n"); + priv->nwaiters++; + ret = sem_wait(&priv->waitsem); + priv->nwaiters--; + + if (ret < 0) + { + /* If we are awakened by a signal, then we need to return + * the failure now. + */ + + ierr("ERROR: sem_wait: %d\n", errno); + DEBUGASSERT(errno == EINTR); + ret = -EINTR; + goto errout; + } + + /* Did the controller become disconnected while we were waiting */ + + if (priv->disconnected) + { + ret = -ENODEV; + goto errout; + } + } + + iinfo("Sampled\n"); + + /* Re-acquire the semaphore that manages mutually exclusive access to + * the device structure. We may have to wait here. But we have our sample. + * Interrupts and pre-emption will be re-enabled while we wait. + */ + + ret = sem_wait(&priv->exclsem); + +errout: + /* Then re-enable interrupts. We might get interrupt here and there + * could be a new sample. But no new threads will run because we still + * have pre-emption disabled. + */ + + leave_critical_section(flags); + + /* Restore pre-emption. We might get suspended here but that is okay + * because we already have our sample. Note: this means that if there + * were two threads reading from the HIDMOUSE for some reason, the data + * might be read out of order. + */ + + sched_unlock(); + return ret; +} + +/**************************************************************************** + * Name: usbhost_cfgdesc + * + * Description: + * This function implements the connect() method of struct + * usbhost_class_s. This method is a callback into the class + * implementation. It is used to provide the device's configuration + * descriptor to the class so that the class may initialize properly + * + * Input Parameters: + * priv - The USB host class instance. + * configdesc - A pointer to a uint8_t buffer container the configuration + * descriptor. + * desclen - The length in bytes of the configuration descriptor. + * + * Returned Values: + * On success, zero (OK) is returned. On a failure, a negated errno value is + * returned indicating the nature of the failure + * + * Assumptions: + * This function will *not* be called from an interrupt handler. + * + ****************************************************************************/ + +static inline int usbhost_cfgdesc(FAR struct usbhost_state_s *priv, + FAR const uint8_t *configdesc, int desclen) +{ + FAR struct usbhost_hubport_s *hport; + FAR struct usb_cfgdesc_s *cfgdesc; + FAR struct usb_desc_s *desc; + FAR struct usbhost_epdesc_s epindesc; + FAR struct usbhost_epdesc_s epoutdesc; + int remaining; + uint8_t found = 0; + bool done = false; + int ret; + + DEBUGASSERT(priv != NULL && priv->usbclass.hport && + configdesc != NULL && desclen >= sizeof(struct usb_cfgdesc_s)); + hport = priv->usbclass.hport; + + /* Keep the compiler from complaining about uninitialized variables */ + + memset(&epindesc, 0, sizeof(struct usbhost_epdesc_s)); + memset(&epoutdesc, 0, sizeof(struct usbhost_epdesc_s)); + + /* Verify that we were passed a configuration descriptor */ + + cfgdesc = (FAR struct usb_cfgdesc_s *)configdesc; + if (cfgdesc->type != USB_DESC_TYPE_CONFIG) + { + return -EINVAL; + } + + /* Get the total length of the configuration descriptor (little endian). + * It might be a good check to get the number of interfaces here too. + */ + + remaining = (int)usbhost_getle16(cfgdesc->totallen); + + /* Skip to the next entry descriptor */ + + configdesc += cfgdesc->len; + remaining -= cfgdesc->len; + + /* Loop where there are more dscriptors to examine */ + + while (remaining >= sizeof(struct usb_desc_s) && !done) + { + /* What is the next descriptor? */ + + desc = (FAR struct usb_desc_s *)configdesc; + switch (desc->type) + { + /* Interface descriptor. We really should get the number of endpoints + * from this descriptor too. + */ + + case USB_DESC_TYPE_INTERFACE: + { + uinfo("Interface descriptor\n"); + DEBUGASSERT(remaining >= USB_SIZEOF_IFDESC); + + /* Did we already find what we needed from a preceding interface? */ + + if ((found & USBHOST_ALLFOUND) == USBHOST_ALLFOUND) + { + /* Yes.. then break out of the loop and use the preceding + * interface. + */ + + done = true; + } + else + { + /* Otherwise, discard any endpoints previously found */ + + found = USBHOST_IFFOUND; + } + } + break; + + /* Endpoint descriptor. Here, we expect two bulk endpoints, an IN + * and an OUT. + */ + + case USB_DESC_TYPE_ENDPOINT: + { + FAR struct usb_epdesc_s *epdesc = (FAR struct usb_epdesc_s *)configdesc; + + uinfo("Endpoint descriptor\n"); + DEBUGASSERT(remaining >= USB_SIZEOF_EPDESC); + + /* Check for a interrupt endpoint. */ + + if ((epdesc->attr & USB_EP_ATTR_XFERTYPE_MASK) == USB_EP_ATTR_XFER_INT) + { + /* Yes.. it is a interrupt endpoint. IN or OUT? */ + + if (USB_ISEPOUT(epdesc->addr)) + { + /* It is an OUT interrupt endpoint. There should be only one + * interrupt OUT endpoint. + */ + + if ((found & USBHOST_EPOUTFOUND) != 0) + { + /* Oops.. more than one endpoint. We don't know + * what to do with this. + */ + + return -EINVAL; + } + found |= USBHOST_EPOUTFOUND; + + /* Save the bulk OUT endpoint information */ + + epoutdesc.hport = hport; + epoutdesc.addr = epdesc->addr & USB_EP_ADDR_NUMBER_MASK; + epoutdesc.in = false; + epoutdesc.xfrtype = USB_EP_ATTR_XFER_INT; + epoutdesc.interval = epdesc->interval; + epoutdesc.mxpacketsize = usbhost_getle16(epdesc->mxpacketsize); + uerr("Interrupt OUT EP addr:%d mxpacketsize:%d\n", + epoutdesc.addr, epoutdesc.mxpacketsize); + } + else + { + /* It is an IN interrupt endpoint. There should be only one + * interrupt IN endpoint. + */ + + if ((found & USBHOST_EPINFOUND) != 0) + { + /* Oops.. more than one endpoint. We don't know + * what to do with this. + */ + + return -EINVAL; + } + + found |= USBHOST_EPINFOUND; + + /* Save the bulk IN endpoint information */ + + epindesc.hport = hport; + epindesc.addr = epdesc->addr & USB_EP_ADDR_NUMBER_MASK; + epindesc.in = true; + epindesc.xfrtype = USB_EP_ATTR_XFER_INT; + epindesc.interval = epdesc->interval; + epindesc.mxpacketsize = usbhost_getle16(epdesc->mxpacketsize); + uerr("Interrupt IN EP addr:%d mxpacketsize:%d\n", + epindesc.addr, epindesc.mxpacketsize); + } + } + } + break; + + /* Other descriptors are just ignored for now */ + + default: + break; + } + + /* If we found everything we need with this interface, then break out + * of the loop early. + */ + + if (found == USBHOST_ALLFOUND) + { + done=true; + } + + /* Increment the address of the next descriptor */ + + configdesc += desc->len; + remaining -= desc->len; + } + + /* Sanity checking... did we find all of things that we need? */ + + if (found != USBHOST_ALLFOUND) + { + uerr("ERROR: Found IF:%s BIN:%s EPOUT:%s\n", + (found & USBHOST_IFFOUND) != 0 ? "YES" : "NO", + (found & USBHOST_EPINFOUND) != 0 ? "YES" : "NO", + (found & USBHOST_EPOUTFOUND) != 0 ? "YES" : "NO"); + return -EINVAL; + } + + /* We are good... Allocate the endpoints */ + + ret = DRVR_EPALLOC(hport->drvr, &epoutdesc, &priv->epout); + if (ret < 0) + { + uerr("ERROR: Failed to allocate Interrupt OUT endpoint\n"); + return ret; + } + + ret = DRVR_EPALLOC(hport->drvr, &epindesc, &priv->epin); + if (ret < 0) + { + uerr("ERROR: Failed to allocate Interrupt IN endpoint\n"); + (void)DRVR_EPFREE(hport->drvr, priv->epout); + return ret; + } + + uinfo("Endpoints allocated\n"); + return OK; +} + +/**************************************************************************** + * Name: usbhost_devinit + * + * Description: + * The USB device has been successfully connected. This completes the + * initialization operations. It is first called after the + * configuration descriptor has been received. + * + * This function is called from the connect() method. This function always + * executes on the thread of the caller of connect(). + * + * Input Parameters: + * priv - A reference to the class instance. + * + * Returned Values: + * None + * + ****************************************************************************/ + +static inline int usbhost_devinit(FAR struct usbhost_state_s *priv) +{ + char devname[DEV_NAMELEN]; + int ret = OK; + + /* Set aside a transfer buffer for exclusive use by the class driver */ + + ret = usbhost_talloc(priv); + if (ret < 0) + { + uerr("ERROR: Failed to allocate transfer buffer\n"); + return ret; + } + + /* Increment the reference count. This will prevent usbhost_destroy() from + * being called asynchronously if the device is removed. + */ + + priv->crefs++; + DEBUGASSERT(priv->crefs == 2); + + /* Start a worker task to poll the USB device. It would be nice to used the + * the NuttX worker thread to do this, but this task needs to wait for events + * and activities on the worker thread should not involve significant waiting. + * Having a dedicated thread is more efficient in this sense, but requires more + * memory resources, primarily for the dedicated stack (CONFIG_XBOXCONTROLLER_STACKSIZE). + */ + + /* The inputs to a task started by kernel_thread() are very awkward for this + * purpose. They are really designed for command line tasks (argc/argv). So + * the following is kludge pass binary data when the controller poll task + * is started. + * + * First, make sure we have exclusive access to g_priv (what is the likelihood + * of this being used? About zero, but we protect it anyway). + */ + + usbhost_takesem(&g_exclsem); + g_priv = priv; + + uinfo("Starting thread\n"); + priv->pollpid = kernel_thread("xbox", CONFIG_XBOXCONTROLLER_DEFPRIO, + CONFIG_XBOXCONTROLLER_STACKSIZE, + (main_t)usbhost_xboxcontroller_poll, (FAR char * const *)NULL); + if (priv->pollpid == ERROR) + { + /* Failed to started the poll thread... probably due to memory resources */ + + usbhost_givesem(&g_exclsem); + ret = -ENOMEM; + goto errout; + } + + /* Now wait for the poll task to get properly initialized */ + + usbhost_takesem(&g_syncsem); + usbhost_givesem(&g_exclsem); + + /* Configure the device */ + + /* Register the driver */ + + uinfo("Register block driver\n"); + usbhost_mkdevname(priv, devname); + ret = register_driver(devname, &g_xboxcontroller_fops, 0666, priv); + + /* Check if we successfully initialized. We now have to be concerned + * about asynchronous modification of crefs because the block + * driver has been registerd. + */ + +errout: + usbhost_takesem(&priv->exclsem); + priv->crefs--; + usbhost_givesem(&priv->exclsem); + return ret; +} + +/**************************************************************************** + * Name: usbhost_getle16 + * + * Description: + * Get a (possibly unaligned) 16-bit little endian value. + * + * Input Parameters: + * val - A pointer to the first byte of the little endian value. + * + * Returned Values: + * A uint16_t representing the whole 16-bit integer value + * + ****************************************************************************/ + +static inline uint16_t usbhost_getle16(const uint8_t *val) +{ + return (uint16_t)val[1] << 8 | (uint16_t)val[0]; +} + +/**************************************************************************** + * Name: usbhost_putle16 + * + * Description: + * Put a (possibly unaligned) 16-bit little endian value. + * + * Input Parameters: + * dest - A pointer to the first byte to save the little endian value. + * val - The 16-bit value to be saved. + * + * Returned Values: + * None + * + ****************************************************************************/ + +static void usbhost_putle16(uint8_t *dest, uint16_t val) +{ + dest[0] = val & 0xff; /* Little endian means LS byte first in byte stream */ + dest[1] = val >> 8; +} + +/**************************************************************************** + * Name: usbhost_getle32 + * + * Description: + * Get a (possibly unaligned) 32-bit little endian value. + * + * Input Parameters: + * dest - A pointer to the first byte to save the big endian value. + * val - The 32-bit value to be saved. + * + * Returned Values: + * None + * + ****************************************************************************/ + +static inline uint32_t usbhost_getle32(const uint8_t *val) +{ + /* Little endian means LS halfword first in byte stream */ + + return (uint32_t)usbhost_getle16(&val[2]) << 16 | (uint32_t)usbhost_getle16(val); +} + +/**************************************************************************** + * Name: usbhost_putle32 + * + * Description: + * Put a (possibly unaligned) 32-bit little endian value. + * + * Input Parameters: + * dest - A pointer to the first byte to save the little endian value. + * val - The 32-bit value to be saved. + * + * Returned Values: + * None + * + ****************************************************************************/ + +#if 0 /* Not used */ +static void usbhost_putle32(uint8_t *dest, uint32_t val) +{ + /* Little endian means LS halfword first in byte stream */ + + usbhost_putle16(dest, (uint16_t)(val & 0xffff)); + usbhost_putle16(dest+2, (uint16_t)(val >> 16)); +} +#endif + +/**************************************************************************** + * Name: usbhost_talloc + * + * Description: + * Allocate transfer buffer memory. + * + * Input Parameters: + * priv - A reference to the class instance. + * + * Returned Values: + * On sucess, zero (OK) is returned. On failure, an negated errno value + * is returned to indicate the nature of the failure. + * + ****************************************************************************/ + +static inline int usbhost_talloc(FAR struct usbhost_state_s *priv) +{ + FAR struct usbhost_hubport_s *hport; + + DEBUGASSERT(priv != NULL && priv->usbclass.hport != NULL && + priv->tbuffer == NULL); + hport = priv->usbclass.hport; + + return DRVR_ALLOC(hport->drvr, &priv->tbuffer, &priv->tbuflen); +} + +/**************************************************************************** + * Name: usbhost_tfree + * + * Description: + * Free transfer buffer memory. + * + * Input Parameters: + * priv - A reference to the class instance. + * + * Returned Values: + * On sucess, zero (OK) is returned. On failure, an negated errno value + * is returned to indicate the nature of the failure. + * + ****************************************************************************/ + +static inline int usbhost_tfree(FAR struct usbhost_state_s *priv) +{ + FAR struct usbhost_hubport_s *hport; + int result = OK; + + DEBUGASSERT(priv != NULL && priv->usbclass.hport != NULL); + + if (priv->tbuffer) + { + hport = priv->usbclass.hport; + result = DRVR_FREE(hport->drvr, priv->tbuffer); + priv->tbuffer = NULL; + priv->tbuflen = 0; + } + + return result; +} + +/**************************************************************************** + * struct usbhost_registry_s methods + ****************************************************************************/ + +/**************************************************************************** + * Name: usbhost_create + * + * Description: + * This function implements the create() method of struct usbhost_registry_s. + * The create() method is a callback into the class implementation. It is + * used to (1) create a new instance of the USB host class state and to (2) + * bind a USB host driver "session" to the class instance. Use of this + * create() method will support environments where there may be multiple + * USB ports and multiple USB devices simultaneously connected. + * + * Input Parameters: + * hport - The hub hat manages the new class instance. + * id - In the case where the device supports multiple base classes, + * subclasses, or protocols, this specifies which to configure for. + * + * Returned Values: + * On success, this function will return a non-NULL instance of struct + * usbhost_class_s that can be used by the USB host driver to communicate + * with the USB host class. NULL is returned on failure; this function + * will fail only if the hport input parameter is NULL or if there are + * insufficient resources to create another USB host class instance. + * + ****************************************************************************/ + +static FAR struct usbhost_class_s *usbhost_create(FAR struct usbhost_hubport_s *hport, + FAR const struct usbhost_id_s *id) +{ + FAR struct usbhost_state_s *priv; + + /* Allocate a USB host class instance */ + + priv = usbhost_allocclass(); + if (priv) + { + /* Initialize the allocated storage class instance */ + + memset(priv, 0, sizeof(struct usbhost_state_s)); + + /* Assign a device number to this class instance */ + + if (usbhost_allocdevno(priv) == OK) + { + /* Initialize class method function pointers */ + + priv->usbclass.hport = hport; + priv->usbclass.connect = usbhost_connect; + priv->usbclass.disconnected = usbhost_disconnected; + + /* The initial reference count is 1... One reference is held by the driver */ + + priv->crefs = 1; + + /* Initialize semaphores (this works okay in the interrupt context) */ + + sem_init(&priv->exclsem, 0, 1); + sem_init(&priv->waitsem, 0, 0); + + /* The waitsem semaphore is used for signaling and, hence, should + * not have priority inheritance enabled. + */ + + sem_setprotocol(&priv->waitsem, SEM_PRIO_NONE); + + /* Return the instance of the USB class driver */ + + return &priv->usbclass; + } + } + + /* An error occurred. Free the allocation and return NULL on all failures */ + + if (priv) + { + usbhost_freeclass(priv); + } + return NULL; +} + +/**************************************************************************** + * struct usbhost_class_s methods + ****************************************************************************/ +/**************************************************************************** + * Name: usbhost_connect + * + * Description: + * This function implements the connect() method of struct + * usbhost_class_s. This method is a callback into the class + * implementation. It is used to provide the device's configuration + * descriptor to the class so that the class may initialize properly + * + * Input Parameters: + * usbclass - The USB host class entry previously obtained from a call to + * create(). + * configdesc - A pointer to a uint8_t buffer container the configuration + * descriptor. + * desclen - The length in bytes of the configuration descriptor. + * + * Returned Values: + * On success, zero (OK) is returned. On a failure, a negated errno value is + * returned indicating the nature of the failure + * + * NOTE that the class instance remains valid upon return with a failure. It is + * the responsibility of the higher level enumeration logic to call + * CLASS_DISCONNECTED to free up the class driver resources. + * + * Assumptions: + * - This function will *not* be called from an interrupt handler. + * - If this function returns an error, the USB host controller driver + * must call to DISCONNECTED method to recover from the error + * + ****************************************************************************/ + +static int usbhost_connect(FAR struct usbhost_class_s *usbclass, + FAR const uint8_t *configdesc, int desclen) +{ + FAR struct usbhost_state_s *priv = (FAR struct usbhost_state_s *)usbclass; + int ret; + + DEBUGASSERT(priv != NULL && + configdesc != NULL && + desclen >= sizeof(struct usb_cfgdesc_s)); + + /* Parse the configuration descriptor to get the endpoints */ + + ret = usbhost_cfgdesc(priv, configdesc, desclen); + if (ret < 0) + { + uerr("ERROR: usbhost_cfgdesc() failed: %d\n", ret); + } + else + { + /* Now configure the device and register the NuttX driver */ + + ret = usbhost_devinit(priv); + if (ret < 0) + { + uerr("ERROR: usbhost_devinit() failed: %d\n", ret); + } + } + + return ret; +} + +/**************************************************************************** + * Name: usbhost_disconnected + * + * Description: + * This function implements the disconnected() method of struct + * usbhost_class_s. This method is a callback into the class + * implementation. It is used to inform the class that the USB device has + * been disconnected. + * + * Input Parameters: + * usbclass - The USB host class entry previously obtained from a call to + * create(). + * + * Returned Values: + * On success, zero (OK) is returned. On a failure, a negated errno value + * is returned indicating the nature of the failure + * + * Assumptions: + * This function may be called from an interrupt handler. + * + ****************************************************************************/ + +static int usbhost_disconnected(struct usbhost_class_s *usbclass) +{ + FAR struct usbhost_state_s *priv = (FAR struct usbhost_state_s *)usbclass; + int i; + + DEBUGASSERT(priv != NULL); + + /* Set an indication to any users of the device that the device is no + * longer available. + */ + + priv->disconnected = true; + uinfo("Disconnected\n"); + + /* Are there a thread(s) waiting for controller data that will never come? */ + + for (i = 0; i < priv->nwaiters; i++) + { + /* Yes.. wake them up */ + + usbhost_givesem(&priv->waitsem); + } + + /* Possibilities: + * + * - Failure occurred before the controller poll task was started successfully. + * In this case, the disconnection will have to be handled on the worker + * task. + * - Failure occurred after the controller poll task was started successfully. In + * this case, the disconnection can be performed on the mouse poll thread. + */ + + if (priv->polling) + { + /* The polling task is still alive. Signal the mouse polling task. + * When that task wakes up, it will decrement the reference count and, + * perhaps, destroy the class instance. Then it will exit. + */ + + (void)kill(priv->pollpid, SIGALRM); + } + else + { + /* In the case where the failure occurs before the polling task was + * started. Now what? We are probably executing from an interrupt + * handler here. We will use the worker thread. This is kind of + * wasteful and begs for a re-design. + */ + + DEBUGASSERT(priv->work.worker == NULL); + (void)work_queue(HPWORK, &priv->work, usbhost_destroy, priv, 0); + } + + return OK; +} + +/**************************************************************************** + * Character driver methods + ****************************************************************************/ +/**************************************************************************** + * Name: usbhost_open + * + * Description: + * Standard character driver open method. + * + ****************************************************************************/ + +static int usbhost_open(FAR struct file *filep) +{ + FAR struct inode *inode; + FAR struct usbhost_state_s *priv; + irqstate_t flags; + int ret; + + uinfo("Entry\n"); + DEBUGASSERT(filep && filep->f_inode); + inode = filep->f_inode; + priv = inode->i_private; + + /* Make sure that we have exclusive access to the private data structure */ + + DEBUGASSERT(priv && priv->crefs > 0 && priv->crefs < USBHOST_MAX_CREFS); + usbhost_takesem(&priv->exclsem); + + /* Check if the controller device is still connected. We need to disable + * interrupts momentarily to assure that there are no asynchronous disconnect + * events. + */ + + flags = enter_critical_section(); + if (priv->disconnected) + { + /* No... the driver is no longer bound to the class. That means that + * the USB storage device is no longer connected. Refuse any further + * attempts to open the driver. + */ + + ret = -ENODEV; + } + else + { + /* Was the driver previously open? We need to perform special + * initialization on the first time that the driver is opened. + */ + + if (!priv->open) + { + /* Set the thresholding values so that the first button press + * will be reported. + */ + +#ifdef NEVER + priv->xlast = INVALID_POSITION_B16; + priv->ylast = INVALID_POSITION_B16; +#ifdef CONFIG_MOUSE_WHEEL + priv->wlast = INVALID_POSITION_B16; +#endif + /* Set the reported position to the center of the range */ + + priv->xaccum = (HIDMOUSE_XMAX_B16 >> 1); + priv->yaccum = (HIDMOUSE_YMAX_B16 >> 1); +#endif + } + + /* Otherwise, just increment the reference count on the driver */ + + priv->crefs++; + priv->open = true; + ret = OK; + } + + leave_critical_section(flags); + + usbhost_givesem(&priv->exclsem); + return ret; +} + +/**************************************************************************** + * Name: usbhost_close + * + * Description: + * Standard character driver close method. + * + ****************************************************************************/ + +static int usbhost_close(FAR struct file *filep) +{ + FAR struct inode *inode; + FAR struct usbhost_state_s *priv; + irqstate_t flags; + + uinfo("Entry\n"); + DEBUGASSERT(filep && filep->f_inode); + inode = filep->f_inode; + priv = inode->i_private; + + /* Decrement the reference count on the driver */ + + DEBUGASSERT(priv->crefs >= 1); + usbhost_takesem(&priv->exclsem); + + /* We need to disable interrupts momentarily to assure that there are no + * asynchronous poll or disconnect events. + */ + + flags = enter_critical_section(); + priv->crefs--; + + /* Check if the USB controller device is still connected. If the device is + * no longer connected, then unregister the driver and free the driver + * class instance. + */ + + if (priv->disconnected) + { + /* If the reference count is one or less then there are two + * possibilities: + * + * 1) It might be zero meaning that the polling thread has already + * exited and decremented its count. + * 2) If might be one meaning either that (a) the polling thread is still + * running and still holds a count, or (b) the polling thread has exited, + * but there is still an outstanding open reference. + */ + + if (priv->crefs == 0 || (priv->crefs == 1 && priv->polling)) + { + /* Yes.. In either case, then the driver is no longer open */ + + priv->open = false; + + /* Check if the USB keyboard device is still connected. */ + + if (priv->crefs == 0) + { + /* The polling thread is no longer running */ + + DEBUGASSERT(!priv->polling); + + /* If the device is no longer connected, unregister the driver + * and free the driver class instance. + */ + + usbhost_destroy(priv); + + /* Skip giving the semaphore... it is no longer valid */ + + leave_critical_section(flags); + return OK; + } + else /* if (priv->crefs == 1) */ + { + /* The polling thread is still running. Signal it so that it + * will wake up and call usbhost_destroy(). The particular + * signal that we use does not matter in this case. + */ + + (void)kill(priv->pollpid, SIGALRM); + } + } + } + + usbhost_givesem(&priv->exclsem); + leave_critical_section(flags); + return OK; +} + +/**************************************************************************** + * Name: usbhost_read + * + * Description: + * Standard character driver read method. + * + ****************************************************************************/ + +static ssize_t usbhost_read(FAR struct file *filep, FAR char *buffer, size_t len) +{ + FAR struct inode *inode; + FAR struct usbhost_state_s *priv; + FAR struct xbox_controller_buttonstate_s sample; + int ret; + + DEBUGASSERT(filep && filep->f_inode && buffer); + inode = filep->f_inode; + priv = inode->i_private; + + /* Make sure that we have exclusive access to the private data structure */ + + DEBUGASSERT(priv && priv->crefs > 0 && priv->crefs < USBHOST_MAX_CREFS); + usbhost_takesem(&priv->exclsem); + + /* Check if the controller is still connected. We need to disable interrupts + * momentarily to assure that there are no asynchronous disconnect events. + */ + + if (priv->disconnected) + { + /* No... the driver is no longer bound to the class. That means that + * the USB controller is no longer connected. Refuse any further attempts + * to access the driver. + */ + + ret = -ENODEV; + goto errout; + } + + /* Try to read sample data. */ + + ret = usbhost_sample(priv, &sample); + if (ret < 0) + { + /* Sample data is not available now. We would ave to wait to get + * receive sample data. If the user has specified the O_NONBLOCK + * option, then just return an error. + */ + + if (filep->f_oflags & O_NONBLOCK) + { + /* Yes.. then return a failure */ + + ret = -EAGAIN; + goto errout; + } + + /* Wait for sample data */ + + ret = usbhost_waitsample(priv, &sample); + ret = 0; + if (ret < 0) + { + /* We might have been awakened by a signal */ + + ierr("ERROR: usbhost_waitsample: %d\n", ret); + goto errout; + } + } + + /* We now have sampled controller data that we can report to the caller. */ + + memcpy(buffer, &sample, sizeof(struct xbox_controller_buttonstate_s)); + + ret = sizeof(struct xbox_controller_buttonstate_s); + +errout: + usbhost_givesem(&priv->exclsem); + iinfo("Returning: %d\n", ret); + return (ssize_t)ret; +} + +/**************************************************************************** + * Name: usbhost_write + * + * Description: + * Standard character driver write method. + * + ****************************************************************************/ + +static ssize_t usbhost_write(FAR struct file *filep, FAR const char *buffer, + size_t len) +{ + + /* Not implemented. */ + + return -ENOSYS; +} + +/**************************************************************************** + * Name: usbhost_ioctl + * + * Description: + * Standard character driver ioctl method. + * + ****************************************************************************/ + +static int usbhost_ioctl(FAR struct file* filep, int cmd, unsigned long arg) +{ + FAR struct inode *inode; + FAR struct usbhost_state_s *priv; + int ret = 0; + int nbytes; + FAR struct usbhost_hubport_s *hport; + static uint8_t rumble_cmd[] = { + 0x09, 0x00, 0x00, 0x09, 0x00, 0x0f, 0x00, + 0x00, 0x00, 0x00, 0xff, 0x00, 0xff + }; + + uinfo("Entered\n"); + DEBUGASSERT(filep && filep->f_inode && buffer); + inode = filep->f_inode; + priv = inode->i_private; + hport = priv->usbclass.hport; + + /* Check if the controller is still connected. We need to disable interrupts + * momentarily to assure that there are no asynchronous disconnect events. + */ + + if (priv->disconnected) + { + /* No... the driver is no longer bound to the class. That means that + * the USB controller is no longer connected. Refuse any further attempts + * to access the driver. + */ + + ret = -ENODEV; + goto errout; + } + + /* Determine which IOCTL command to execute. */ + switch (cmd) + { + + case XBOX_CONTROLLER_IOCTL_RUMBLE: + + /* The least significant byte is the weak actuator strength. + * The second byte is the strong actuator strength. + */ + + memcpy(priv->obuffer, rumble_cmd, sizeof(rumble_cmd)); + priv->obuffer[2] = priv->out_seq_num++; + priv->obuffer[8] = (arg >> 1) & 0xff; // Strong (left actuator) + priv->obuffer[9] = arg & 0xff; // Weak (right actuator) + + /* Perform the transfer. */ + + nbytes = DRVR_TRANSFER(hport->drvr, priv->epout, + priv->obuffer, sizeof(rumble_cmd)); + + /* Did we encounter an error? */ + + if (nbytes < 0) + { + ret = nbytes; + } + + break; + + default: + + ret = -EINVAL; + goto errout; + } + +errout: + iinfo("Returning: %d\n", ret); + return ret; +} + +/**************************************************************************** + * Name: usbhost_poll + * + * Description: + * Standard character driver poll method. + * + ****************************************************************************/ + +#ifndef CONFIG_DISABLE_POLL +static int usbhost_poll(FAR struct file *filep, FAR struct pollfd *fds, + bool setup) +{ + FAR struct inode *inode; + FAR struct usbhost_state_s *priv; + int ret = OK; + int i; + + DEBUGASSERT(filep && filep->f_inode && fds); + inode = filep->f_inode; + priv = inode->i_private; + + /* Make sure that we have exclusive access to the private data structure */ + + DEBUGASSERT(priv); + usbhost_takesem(&priv->exclsem); + + /* Check if the controller is still connected. We need to disable interrupts + * momentarily to assure that there are no asynchronous disconnect events. + */ + + if (priv->disconnected) + { + /* No... the driver is no longer bound to the class. That means that + * the USB controller is no longer connected. Refuse any further attempts + * to access the driver. + */ + + ret = -ENODEV; + } + else if (setup) + { + /* This is a request to set up the poll. Find an available slot for + * the poll structure reference + */ + + for (i = 0; i < CONFIG_XBOXCONTROLLER_NPOLLWAITERS; i++) + { + /* Find an available slot */ + + if (!priv->fds[i]) + { + /* Bind the poll structure and this slot */ + + priv->fds[i] = fds; + fds->priv = &priv->fds[i]; + break; + } + } + + if (i >= CONFIG_XBOXCONTROLLER_NPOLLWAITERS) + { + fds->priv = NULL; + ret = -EBUSY; + goto errout; + } + + /* Should we immediately notify on any of the requested events? Notify + * the POLLIN event if there is buffered controller data. + */ + + if (priv->valid) + { + usbhost_pollnotify(priv); + } + } + else + { + /* This is a request to tear down the poll. */ + + struct pollfd **slot = (struct pollfd **)fds->priv; + DEBUGASSERT(slot); + + /* Remove all memory of the poll setup */ + + *slot = NULL; + fds->priv = NULL; + } + +errout: + sem_post(&priv->exclsem); + return ret; +} +#endif + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: usbhost_xboxcontroller_init + * + * Description: + * Initialize the USB class driver. This function should be called + * be platform-specific code in order to initialize and register support + * for the USB host class device. + * + * Input Parameters: + * None + * + * Returned Values: + * On success this function will return zero (OK); A negated errno value + * will be returned on failure. + * + ****************************************************************************/ + +int usbhost_xboxcontroller_init(void) +{ + + /* Perform any one-time initialization of the class implementation */ + + sem_init(&g_exclsem, 0, 1); + sem_init(&g_syncsem, 0, 0); + + /* The g_syncsem semaphore is used for signaling and, hence, should not + * have priority inheritance enabled. + */ + + sem_setprotocol(&g_syncsem, SEM_PRIO_NONE); + + /* Advertise our availability to support (certain) devices */ + + return usbhost_registerclass(&g_xboxcontroller); +} diff --git a/include/nuttx/input/xbox-controller.h b/include/nuttx/input/xbox-controller.h new file mode 100644 index 00000000000..b4e0262740e --- /dev/null +++ b/include/nuttx/input/xbox-controller.h @@ -0,0 +1,88 @@ +/************************************************************************************ + * include/nuttx/input/xbox-controller.h + * + * Copyright (C) 2016 Brian Webb. + * Author: Brian Webb + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ************************************************************************************/ + +#ifndef __INCLUDE_NUTTX_INPUT_XBOX_CONTROLLER_H +#define __INCLUDE_NUTTX_INPUT_XBOX_CONTROLLER_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/**************************************************************************** + * Public Types + ****************************************************************************/ + +/* This type defines the button data report from the controller. */ + +struct xbox_controller_buttonstate_s +{ + bool guide : 1; + bool sync : 1; + bool start : 1; + bool back : 1; + bool a : 1; + bool b : 1; + bool x : 1; + bool y : 1; + bool dpad_up : 1; + bool dpad_down : 1; + bool dpad_left : 1; + bool dpad_right : 1; + bool bumper_left : 1; + bool bumper_right : 1; + bool stick_click_left : 1; + bool stick_click_right : 1; + int16_t stick_left_x; + int16_t stick_left_y; + int16_t stick_right_x; + int16_t stick_right_y; + int16_t trigger_left; + int16_t trigger_right; +}; + +/* The supported IOCTL commands. */ + +enum +{ + XBOX_CONTROLLER_IOCTL_RUMBLE +} xbox_controller_iotcl_cmds; + +#ifdef __cplusplus +} +#endif + +#endif /* __INCLUDE_NUTTX_INPUT_XBOX_CONTROLLER_H */ + diff --git a/include/nuttx/usb/usbhost.h b/include/nuttx/usb/usbhost.h index 587917701cd..6b6b495954a 100644 --- a/include/nuttx/usb/usbhost.h +++ b/include/nuttx/usb/usbhost.h @@ -1084,6 +1084,27 @@ int usbhost_kbdinit(void); int usbhost_mouse_init(void); #endif +#ifdef CONFIG_USBHOST_XBOXCONTROLLER +/**************************************************************************** + * Name: usbhost_xboxcontroller_init + * + * Description: + * Initialize the USB XBox controller driver. This function + * should be called be platform-specific code in order to initialize and + * register support for the USB XBox controller. + * + * Input Parameters: + * None + * + * Returned Values: + * On success this function will return zero (OK); A negated errno value + * will be returned on failure. + * + ****************************************************************************/ + +int usbhost_xboxcontroller_init(void); +#endif + /**************************************************************************** * Name: usbhost_wlaninit * From 175f8960cfc20a00c8882be8bb04807d47adaee0 Mon Sep 17 00:00:00 2001 From: Gregory Nutt Date: Sat, 18 Mar 2017 06:47:34 -0600 Subject: [PATCH 15/15] Cosmetic changes from review of last PR --- drivers/usbhost/usbhost_xboxcontroller.c | 295 +++++++++++++---------- 1 file changed, 164 insertions(+), 131 deletions(-) diff --git a/drivers/usbhost/usbhost_xboxcontroller.c b/drivers/usbhost/usbhost_xboxcontroller.c index fd12efee975..6fcf49d6a88 100644 --- a/drivers/usbhost/usbhost_xboxcontroller.c +++ b/drivers/usbhost/usbhost_xboxcontroller.c @@ -2,7 +2,8 @@ * drivers/usbhost/usbhost_xboxcontroller.c * * Copyright (C) 2016 Gregory Nutt. All rights reserved. - * Author: Gregory Nutt + * Authors: Gregory Nutt + * Brian Webb * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -143,7 +144,8 @@ #define XBOX_BUTTON_STICK_LEFT_Y 6 #define XBOX_BUTTON_STICK_RIGHT_X 7 #define XBOX_BUTTON_STICK_RIGHT_Y 8 -#define XBOX_BUTTON_SET(buffer, index, mask) ((((buffer)[(index)] & (mask)) != 0) ? true : false); +#define XBOX_BUTTON_SET(buffer, index, mask) \ + ((((buffer)[(index)] & (mask)) != 0) ? true : false); /**************************************************************************** * Private Types @@ -291,7 +293,7 @@ static struct usbhost_registry_s g_xboxcontroller = NULL, /* flink */ usbhost_create, /* create */ 2, /* nids */ - g_xboxcontroller_id /* id[] */ + g_xboxcontroller_id /* id[] */ }; /* The configuration information for the block file device. */ @@ -342,7 +344,7 @@ static void usbhost_takesem(sem_t *sem) * awakened by a signal. */ - ASSERT(errno == EINTR); + DEBUGASSERT(errno == EINTR); } } @@ -558,7 +560,7 @@ static void usbhost_notify(FAR struct usbhost_state_s *priv) #ifndef CONFIG_DISABLE_POLL for (i = 0; i < CONFIG_XBOXCONTROLLER_NPOLLWAITERS; i++) { - struct pollfd *fds = priv->fds[i]; + FAR struct pollfd *fds = priv->fds[i]; if (fds) { fds->revents |= POLLIN; @@ -640,16 +642,15 @@ static int usbhost_xboxcontroller_poll(int argc, char *argv[]) if (nbytes != -EAGAIN) { - - uerr("ERROR: DRVR_TRANSFER returned: %d/%u\n", - (int)nbytes, nerrors); - + uerr("ERROR: DRVR_TRANSFER returned: %d/%u\n", + (int)nbytes, nerrors); + if (++nerrors > 200) { uerr(" Too many errors... aborting: %d\n", nerrors); ret = (int)nbytes; break; - } + } } } @@ -657,146 +658,176 @@ static int usbhost_xboxcontroller_poll(int argc, char *argv[]) else { - /* Success, reset the error counter */ - nerrors = 0; - - /* The type of message is in the first byte */ - switch (priv->tbuffer[0]) - { + nerrors = 0; - case USBHOST_WAITING_CONNECTION: - - /* Send the initialization message when we received the - * the first waiting connection message. - */ - - if (!priv->initialized) { + /* The type of message is in the first byte */ - /* Get exclusive access to the controller state data */ + switch (priv->tbuffer[0]) + { + case USBHOST_WAITING_CONNECTION: + /* Send the initialization message when we received the + * the first waiting connection message. + */ - usbhost_takesem(&priv->exclsem); + if (!priv->initialized) + { + /* Get exclusive access to the controller state data */ - priv->tbuffer[0] = 0x05; - priv->tbuffer[1] = 0x20; - priv->tbuffer[2] = priv->out_seq_num++; - priv->tbuffer[3] = 0x01; - priv->tbuffer[4] = 0x00; - nbytes = DRVR_TRANSFER(hport->drvr, priv->epout, - priv->tbuffer, 5); - priv->initialized = true; - - /* Release our lock on the state structure */ + usbhost_takesem(&priv->exclsem); - usbhost_givesem(&priv->exclsem); - } + priv->tbuffer[0] = 0x05; + priv->tbuffer[1] = 0x20; + priv->tbuffer[2] = priv->out_seq_num++; + priv->tbuffer[3] = 0x01; + priv->tbuffer[4] = 0x00; + nbytes = DRVR_TRANSFER(hport->drvr, priv->epout, + priv->tbuffer, 5); + priv->initialized = true; - break; - - case USBHOST_GUIDE_BUTTON_STATUS: + /* Release our lock on the state structure */ - /* Get exclusive access to the controller state data */ + usbhost_givesem(&priv->exclsem); + } - usbhost_takesem(&priv->exclsem); + break; - /* Read the data out of the controller report. */ + case USBHOST_GUIDE_BUTTON_STATUS: + /* Get exclusive access to the controller state data */ - priv->rpt.guide = (priv->tbuffer[XBOX_BUTTON_GUIDE_INDEX] != 0) ? true : false; - - priv->valid = true; + usbhost_takesem(&priv->exclsem); - /* The One X controller requires an ACK of the guide button status message. */ + /* Read the data out of the controller report. */ - if (priv->tbuffer[1] == 0x30) - { - - static const uint8_t guide_button_report_ack[] = { - 0x01, 0x20, 0x00, 0x09, 0x00, 0x07, 0x20, 0x02, - 0x00, 0x00, 0x00, 0x00, 0x00 - }; + priv->rpt.guide = (priv->tbuffer[XBOX_BUTTON_GUIDE_INDEX] != 0) ? true : false; + priv->valid = true; - /* Remember the input packet sequence number. */ - - uint8_t seq_num = priv->tbuffer[2]; + /* The One X controller requires an ACK of the guide button status + * message. + */ - /* Copy the ACK packet into the transfer buffer. */ - - memcpy(priv->tbuffer, guide_button_report_ack, sizeof(guide_button_report_ack)); + if (priv->tbuffer[1] == 0x30) + { + static const uint8_t guide_button_report_ack[] = + { + 0x01, 0x20, 0x00, 0x09, 0x00, 0x07, 0x20, 0x02, + 0x00, 0x00, 0x00, 0x00, 0x00 + }; - /* Ensure the sequence number is the same as the input packet. */ - - priv->tbuffer[2] = seq_num; + /* Remember the input packet sequence number. */ - /* Perform the transfer. */ - - nbytes = DRVR_TRANSFER(hport->drvr, priv->epout, - priv->tbuffer, sizeof(guide_button_report_ack)); - } - - /* Notify any waiters that new controller data is available */ + uint8_t seq_num = priv->tbuffer[2]; - usbhost_notify(priv); + /* Copy the ACK packet into the transfer buffer. */ - /* Release our lock on the state structure */ + memcpy(priv->tbuffer, guide_button_report_ack, + sizeof(guide_button_report_ack)); - usbhost_givesem(&priv->exclsem); + /* Ensure the sequence number is the same as the input packet. */ - break; - - case USBHOST_BUTTON_DATA: + priv->tbuffer[2] = seq_num; - /* Ignore the controller data if no task has opened the driver. */ + /* Perform the transfer. */ - if (priv->open) - { - /* Get exclusive access to the controller state data */ + nbytes = DRVR_TRANSFER(hport->drvr, priv->epout, priv->tbuffer, + sizeof(guide_button_report_ack)); + } - usbhost_takesem(&priv->exclsem); + /* Notify any waiters that new controller data is available */ - /* Read the data out of the controller report. */ + usbhost_notify(priv); - priv->rpt.sync = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_SYNC_INDEX, XBOX_BUTTON_SYNC_MASK); - priv->rpt.start = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_START_INDEX, XBOX_BUTTON_START_MASK); - priv->rpt.back = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_BACK_INDEX, XBOX_BUTTON_BACK_MASK); - priv->rpt.a = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_A_INDEX, XBOX_BUTTON_A_MASK); - priv->rpt.b = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_B_INDEX, XBOX_BUTTON_B_MASK); - priv->rpt.x = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_X_INDEX, XBOX_BUTTON_X_MASK); - priv->rpt.y = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_Y_INDEX, XBOX_BUTTON_Y_MASK); - priv->rpt.dpad_up = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_DPAD_UP_INDEX, XBOX_BUTTON_DPAD_UP_MASK); - priv->rpt.dpad_down = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_DPAD_DOWN_INDEX, XBOX_BUTTON_DPAD_DOWN_MASK); - priv->rpt.dpad_left = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_DPAD_LEFT_INDEX, XBOX_BUTTON_DPAD_LEFT_MASK); - priv->rpt.dpad_right = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_DPAD_RIGHT_INDEX, XBOX_BUTTON_DPAD_RIGHT_MASK); - priv->rpt.bumper_left = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_BUMPER_LEFT_INDEX, XBOX_BUTTON_BUMPER_LEFT_MASK); - priv->rpt.bumper_right = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_BUMPER_RIGHT_INDEX, XBOX_BUTTON_BUMPER_RIGHT_MASK); - priv->rpt.stick_click_left = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_STICK_LEFT_INDEX, XBOX_BUTTON_STICK_LEFT_MASK); - priv->rpt.stick_click_right = XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_STICK_RIGHT_INDEX, XBOX_BUTTON_STICK_RIGHT_MASK); - priv->rpt.trigger_left = ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_TRIGGER_LEFT]; - priv->rpt.trigger_right = ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_TRIGGER_RIGHT]; - priv->rpt.stick_left_x = ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_STICK_LEFT_X]; - priv->rpt.stick_left_y = ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_STICK_LEFT_Y]; - priv->rpt.stick_right_x = ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_STICK_RIGHT_X]; - priv->rpt.stick_right_y = ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_STICK_RIGHT_Y]; - - priv->valid = true; + /* Release our lock on the state structure */ - /* Notify any waiters that new controller data is available */ + usbhost_givesem(&priv->exclsem); - usbhost_notify(priv); + break; - /* Release our lock on the state structure */ + case USBHOST_BUTTON_DATA: + /* Ignore the controller data if no task has opened the driver. */ - usbhost_givesem(&priv->exclsem); - } + if (priv->open) + { + /* Get exclusive access to the controller state data */ - break; + usbhost_takesem(&priv->exclsem); - default: - - uinfo("Received messge type: %x\n", priv->tbuffer[0]); - - } - + /* Read the data out of the controller report. */ + + priv->rpt.sync = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_SYNC_INDEX, + XBOX_BUTTON_SYNC_MASK); + priv->rpt.start = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_START_INDEX, + XBOX_BUTTON_START_MASK); + priv->rpt.back = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_BACK_INDEX, + XBOX_BUTTON_BACK_MASK); + priv->rpt.a = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_A_INDEX, + XBOX_BUTTON_A_MASK); + priv->rpt.b = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_B_INDEX, + XBOX_BUTTON_B_MASK); + priv->rpt.x = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_X_INDEX, + XBOX_BUTTON_X_MASK); + priv->rpt.y = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_Y_INDEX, + XBOX_BUTTON_Y_MASK); + priv->rpt.dpad_up = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_DPAD_UP_INDEX, + XBOX_BUTTON_DPAD_UP_MASK); + priv->rpt.dpad_down = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_DPAD_DOWN_INDEX, + XBOX_BUTTON_DPAD_DOWN_MASK); + priv->rpt.dpad_left = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_DPAD_LEFT_INDEX, + XBOX_BUTTON_DPAD_LEFT_MASK); + priv->rpt.dpad_right = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_DPAD_RIGHT_INDEX, + XBOX_BUTTON_DPAD_RIGHT_MASK); + priv->rpt.bumper_left = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_BUMPER_LEFT_INDEX, + XBOX_BUTTON_BUMPER_LEFT_MASK); + priv->rpt.bumper_right = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_BUMPER_RIGHT_INDEX, XBOX_BUTTON_BUMPER_RIGHT_MASK); + priv->rpt.stick_click_left = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_STICK_LEFT_INDEX, + XBOX_BUTTON_STICK_LEFT_MASK); + priv->rpt.stick_click_right = + XBOX_BUTTON_SET(priv->tbuffer, XBOX_BUTTON_STICK_RIGHT_INDEX, + XBOX_BUTTON_STICK_RIGHT_MASK); + priv->rpt.trigger_left = + ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_TRIGGER_LEFT]; + priv->rpt.trigger_right = + ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_TRIGGER_RIGHT]; + priv->rpt.stick_left_x = + ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_STICK_LEFT_X]; + priv->rpt.stick_left_y = + ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_STICK_LEFT_Y]; + priv->rpt.stick_right_x = + ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_STICK_RIGHT_X]; + priv->rpt.stick_right_y = + ((int16_t*)(priv->tbuffer))[XBOX_BUTTON_STICK_RIGHT_Y]; + + priv->valid = true; + + /* Notify any waiters that new controller data is available */ + + usbhost_notify(priv); + + /* Release our lock on the state structure */ + + usbhost_givesem(&priv->exclsem); + } + + break; + + default: + uinfo("Received messge type: %x\n", priv->tbuffer[0]); + } } /* If USB debug is on, then provide some periodic indication that @@ -925,7 +956,7 @@ static int usbhost_sample(FAR struct usbhost_state_s *priv, ****************************************************************************/ static int usbhost_waitsample(FAR struct usbhost_state_s *priv, - FAR struct xbox_controller_buttonstate_s *sample) + FAR struct xbox_controller_buttonstate_s *sample) { irqstate_t flags; int ret; @@ -1142,6 +1173,7 @@ static inline int usbhost_cfgdesc(FAR struct usbhost_state_s *priv, return -EINVAL; } + found |= USBHOST_EPOUTFOUND; /* Save the bulk OUT endpoint information */ @@ -1199,7 +1231,7 @@ static inline int usbhost_cfgdesc(FAR struct usbhost_state_s *priv, if (found == USBHOST_ALLFOUND) { - done=true; + done = true; } /* Increment the address of the next descriptor */ @@ -1563,6 +1595,7 @@ static FAR struct usbhost_class_s *usbhost_create(FAR struct usbhost_hubport_s * { usbhost_freeclass(priv); } + return NULL; } @@ -1785,7 +1818,6 @@ static int usbhost_open(FAR struct file *filep) } leave_critical_section(flags); - usbhost_givesem(&priv->exclsem); return ret; } @@ -1838,7 +1870,7 @@ static int usbhost_close(FAR struct file *filep) * but there is still an outstanding open reference. */ - if (priv->crefs == 0 || (priv->crefs == 1 && priv->polling)) + if (priv->crefs == 0 || (priv->crefs == 1 && priv->polling)) { /* Yes.. In either case, then the driver is no longer open */ @@ -1973,9 +2005,8 @@ errout: static ssize_t usbhost_write(FAR struct file *filep, FAR const char *buffer, size_t len) { - /* Not implemented. */ - + return -ENOSYS; } @@ -1994,7 +2025,8 @@ static int usbhost_ioctl(FAR struct file* filep, int cmd, unsigned long arg) int ret = 0; int nbytes; FAR struct usbhost_hubport_s *hport; - static uint8_t rumble_cmd[] = { + static uint8_t rumble_cmd[] = + { 0x09, 0x00, 0x00, 0x09, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff }; @@ -2021,6 +2053,7 @@ static int usbhost_ioctl(FAR struct file* filep, int cmd, unsigned long arg) } /* Determine which IOCTL command to execute. */ + switch (cmd) { @@ -2034,18 +2067,18 @@ static int usbhost_ioctl(FAR struct file* filep, int cmd, unsigned long arg) priv->obuffer[2] = priv->out_seq_num++; priv->obuffer[8] = (arg >> 1) & 0xff; // Strong (left actuator) priv->obuffer[9] = arg & 0xff; // Weak (right actuator) - + /* Perform the transfer. */ - + nbytes = DRVR_TRANSFER(hport->drvr, priv->epout, - priv->obuffer, sizeof(rumble_cmd)); + priv->obuffer, sizeof(rumble_cmd)); /* Did we encounter an error? */ if (nbytes < 0) - { - ret = nbytes; - } + { + ret = nbytes; + } break; @@ -2054,7 +2087,7 @@ static int usbhost_ioctl(FAR struct file* filep, int cmd, unsigned long arg) ret = -EINVAL; goto errout; } - + errout: iinfo("Returning: %d\n", ret); return ret;