From 60b30c036397cb5627fa374bb930794b225daa29 Mon Sep 17 00:00:00 2001 From: Jack Humbert Date: Fri, 7 Jul 2017 11:55:23 -0400 Subject: Squashed 'lib/lufa/' content from commit 385d40300 git-subtree-dir: lib/lufa git-subtree-split: 385d4030035dbaf41591309dbde47653bd03841b --- Projects/Webserver/Lib/DHCPClientApp.c | 208 ++ Projects/Webserver/Lib/DHCPClientApp.h | 69 + Projects/Webserver/Lib/DHCPCommon.c | 103 + Projects/Webserver/Lib/DHCPCommon.h | 159 ++ Projects/Webserver/Lib/DHCPServerApp.c | 265 ++ Projects/Webserver/Lib/DHCPServerApp.h | 64 + Projects/Webserver/Lib/DataflashManager.c | 534 ++++ Projects/Webserver/Lib/DataflashManager.h | 87 + Projects/Webserver/Lib/FATFs/00readme.txt | 135 + Projects/Webserver/Lib/FATFs/diskio.c | 65 + Projects/Webserver/Lib/FATFs/diskio.h | 52 + Projects/Webserver/Lib/FATFs/ff.c | 4139 +++++++++++++++++++++++++++++ Projects/Webserver/Lib/FATFs/ff.h | 337 +++ Projects/Webserver/Lib/FATFs/ffconf.h | 190 ++ Projects/Webserver/Lib/FATFs/integer.h | 38 + Projects/Webserver/Lib/HTTPServerApp.c | 284 ++ Projects/Webserver/Lib/HTTPServerApp.h | 84 + Projects/Webserver/Lib/SCSI.c | 344 +++ Projects/Webserver/Lib/SCSI.h | 87 + Projects/Webserver/Lib/TELNETServerApp.c | 163 ++ Projects/Webserver/Lib/TELNETServerApp.h | 71 + Projects/Webserver/Lib/uIPManagement.c | 298 +++ Projects/Webserver/Lib/uIPManagement.h | 69 + Projects/Webserver/Lib/uip/clock.c | 37 + Projects/Webserver/Lib/uip/clock.h | 13 + Projects/Webserver/Lib/uip/timer.c | 128 + Projects/Webserver/Lib/uip/timer.h | 87 + Projects/Webserver/Lib/uip/uip-split.c | 151 ++ Projects/Webserver/Lib/uip/uip-split.h | 104 + Projects/Webserver/Lib/uip/uip.c | 1941 ++++++++++++++ Projects/Webserver/Lib/uip/uip.h | 2130 +++++++++++++++ Projects/Webserver/Lib/uip/uip_arp.c | 432 +++ Projects/Webserver/Lib/uip/uip_arp.h | 146 + Projects/Webserver/Lib/uip/uipopt.h | 740 ++++++ 34 files changed, 13754 insertions(+) create mode 100644 Projects/Webserver/Lib/DHCPClientApp.c create mode 100644 Projects/Webserver/Lib/DHCPClientApp.h create mode 100644 Projects/Webserver/Lib/DHCPCommon.c create mode 100644 Projects/Webserver/Lib/DHCPCommon.h create mode 100644 Projects/Webserver/Lib/DHCPServerApp.c create mode 100644 Projects/Webserver/Lib/DHCPServerApp.h create mode 100644 Projects/Webserver/Lib/DataflashManager.c create mode 100644 Projects/Webserver/Lib/DataflashManager.h create mode 100644 Projects/Webserver/Lib/FATFs/00readme.txt create mode 100644 Projects/Webserver/Lib/FATFs/diskio.c create mode 100644 Projects/Webserver/Lib/FATFs/diskio.h create mode 100644 Projects/Webserver/Lib/FATFs/ff.c create mode 100644 Projects/Webserver/Lib/FATFs/ff.h create mode 100644 Projects/Webserver/Lib/FATFs/ffconf.h create mode 100644 Projects/Webserver/Lib/FATFs/integer.h create mode 100644 Projects/Webserver/Lib/HTTPServerApp.c create mode 100644 Projects/Webserver/Lib/HTTPServerApp.h create mode 100644 Projects/Webserver/Lib/SCSI.c create mode 100644 Projects/Webserver/Lib/SCSI.h create mode 100644 Projects/Webserver/Lib/TELNETServerApp.c create mode 100644 Projects/Webserver/Lib/TELNETServerApp.h create mode 100644 Projects/Webserver/Lib/uIPManagement.c create mode 100644 Projects/Webserver/Lib/uIPManagement.h create mode 100644 Projects/Webserver/Lib/uip/clock.c create mode 100644 Projects/Webserver/Lib/uip/clock.h create mode 100644 Projects/Webserver/Lib/uip/timer.c create mode 100644 Projects/Webserver/Lib/uip/timer.h create mode 100644 Projects/Webserver/Lib/uip/uip-split.c create mode 100644 Projects/Webserver/Lib/uip/uip-split.h create mode 100644 Projects/Webserver/Lib/uip/uip.c create mode 100644 Projects/Webserver/Lib/uip/uip.h create mode 100644 Projects/Webserver/Lib/uip/uip_arp.c create mode 100644 Projects/Webserver/Lib/uip/uip_arp.h create mode 100644 Projects/Webserver/Lib/uip/uipopt.h (limited to 'Projects/Webserver/Lib') diff --git a/Projects/Webserver/Lib/DHCPClientApp.c b/Projects/Webserver/Lib/DHCPClientApp.c new file mode 100644 index 0000000000..760718127e --- /dev/null +++ b/Projects/Webserver/Lib/DHCPClientApp.c @@ -0,0 +1,208 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2017. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2017 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaims all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ + +/** \file + * + * DHCP Client Application. When connected to the uIP stack, this will retrieve IP configuration settings from the + * DHCP server on the network. + */ + +#define INCLUDE_FROM_DHCPCLIENTAPP_C +#include "DHCPClientApp.h" + +#if defined(ENABLE_DHCP_CLIENT) || defined(__DOXYGEN__) + +/** Initialization function for the DHCP client. */ +void DHCPClientApp_Init(void) +{ + /* Create a new UDP connection to the DHCP server port for the DHCP solicitation */ + struct uip_udp_conn* Connection = uip_udp_new(&uip_broadcast_addr, HTONS(DHCP_SERVER_PORT)); + + /* If the connection was successfully created, bind it to the local DHCP client port */ + if (Connection != NULL) + { + uip_udp_appstate_t* const AppState = &Connection->appstate; + uip_udp_bind(Connection, HTONS(DHCP_CLIENT_PORT)); + + /* Set the initial client state */ + AppState->DHCPClient.CurrentState = DHCP_STATE_SendDiscover; + + /* Set timeout period to half a second for a DHCP server to respond */ + timer_set(&AppState->DHCPClient.Timeout, CLOCK_SECOND / 2); + } +} + +/** uIP stack application callback for the DHCP client. This function must be called each time the TCP/IP stack + * needs a UDP packet to be processed. + */ +void DHCPClientApp_Callback(void) +{ + uip_udp_appstate_t* const AppState = &uip_udp_conn->appstate; + DHCP_Header_t* const AppData = (DHCP_Header_t*)uip_appdata; + uint16_t AppDataSize = 0; + + switch (AppState->DHCPClient.CurrentState) + { + case DHCP_STATE_SendDiscover: + /* Clear all DHCP settings, reset client IP address */ + memset(&AppState->DHCPClient.DHCPOffer_Data, 0x00, sizeof(AppState->DHCPClient.DHCPOffer_Data)); + uip_sethostaddr((uip_ipaddr_t*)&AppState->DHCPClient.DHCPOffer_Data.AllocatedIP); + + /* Fill out the DHCP response header */ + AppDataSize += DHCPClientApp_FillDHCPHeader(AppData, DHCP_DISCOVER, AppState); + + /* Add the required DHCP options list to the packet */ + uint8_t RequiredOptionList[] = {DHCP_OPTION_SUBNET_MASK, DHCP_OPTION_ROUTER, DHCP_OPTION_DNS_SERVER}; + AppDataSize += DHCPCommon_SetOption(AppData->Options, DHCP_OPTION_REQ_LIST, sizeof(RequiredOptionList), + RequiredOptionList); + + /* Send the DHCP DISCOVER packet */ + uip_udp_send(AppDataSize); + + /* Reset the timeout timer, progress to next state */ + timer_reset(&AppState->DHCPClient.Timeout); + AppState->DHCPClient.CurrentState = DHCP_STATE_WaitForOffer; + + break; + case DHCP_STATE_WaitForOffer: + if (!(uip_newdata())) + { + /* Check if the DHCP timeout period has expired while waiting for a response */ + if (timer_expired(&AppState->DHCPClient.Timeout)) + AppState->DHCPClient.CurrentState = DHCP_STATE_SendDiscover; + + break; + } + + uint8_t OfferResponse_MessageType; + if ((AppData->TransactionID == DHCP_TRANSACTION_ID) && + DHCPCommon_GetOption(AppData->Options, DHCP_OPTION_MSG_TYPE, &OfferResponse_MessageType) && + (OfferResponse_MessageType == DHCP_OFFER)) + { + /* Received a DHCP offer for an IP address, copy over values for later request */ + memcpy(&AppState->DHCPClient.DHCPOffer_Data.AllocatedIP, &AppData->YourIP, sizeof(uip_ipaddr_t)); + DHCPCommon_GetOption(AppData->Options, DHCP_OPTION_SUBNET_MASK, &AppState->DHCPClient.DHCPOffer_Data.Netmask); + DHCPCommon_GetOption(AppData->Options, DHCP_OPTION_ROUTER, &AppState->DHCPClient.DHCPOffer_Data.GatewayIP); + DHCPCommon_GetOption(AppData->Options, DHCP_OPTION_SERVER_ID, &AppState->DHCPClient.DHCPOffer_Data.ServerIP); + + timer_reset(&AppState->DHCPClient.Timeout); + AppState->DHCPClient.CurrentState = DHCP_STATE_SendRequest; + } + + break; + case DHCP_STATE_SendRequest: + /* Fill out the DHCP response header */ + AppDataSize += DHCPClientApp_FillDHCPHeader(AppData, DHCP_REQUEST, AppState); + + /* Add the DHCP REQUESTED IP ADDRESS option to the packet */ + AppDataSize += DHCPCommon_SetOption(AppData->Options, DHCP_OPTION_REQ_IPADDR, sizeof(uip_ipaddr_t), + &AppState->DHCPClient.DHCPOffer_Data.AllocatedIP); + + /* Add the DHCP SERVER IP ADDRESS option to the packet */ + AppDataSize += DHCPCommon_SetOption(AppData->Options, DHCP_OPTION_SERVER_ID, sizeof(uip_ipaddr_t), + &AppState->DHCPClient.DHCPOffer_Data.ServerIP); + + /* Send the DHCP REQUEST packet */ + uip_udp_send(AppDataSize); + + /* Reset the timeout timer, progress to next state */ + timer_reset(&AppState->DHCPClient.Timeout); + AppState->DHCPClient.CurrentState = DHCP_STATE_WaitForACK; + + break; + case DHCP_STATE_WaitForACK: + if (!(uip_newdata())) + { + /* Check if the DHCP timeout period has expired while waiting for a response */ + if (timer_expired(&AppState->DHCPClient.Timeout)) + AppState->DHCPClient.CurrentState = DHCP_STATE_SendDiscover; + + break; + } + + uint8_t RequestResponse_MessageType; + if ((AppData->TransactionID == DHCP_TRANSACTION_ID) && + DHCPCommon_GetOption(AppData->Options, DHCP_OPTION_MSG_TYPE, &RequestResponse_MessageType) && + (RequestResponse_MessageType == DHCP_ACK)) + { + /* Set the new network parameters from the DHCP server */ + uip_sethostaddr((uip_ipaddr_t*)&AppState->DHCPClient.DHCPOffer_Data.AllocatedIP); + uip_setnetmask((uip_ipaddr_t*)&AppState->DHCPClient.DHCPOffer_Data.Netmask); + uip_setdraddr((uip_ipaddr_t*)&AppState->DHCPClient.DHCPOffer_Data.GatewayIP); + + AppState->DHCPClient.CurrentState = DHCP_STATE_AddressLeased; + } + + break; + } +} + +/** Fills the DHCP packet response with the appropriate BOOTP header for DHCP. This fills out all the required + * fields, leaving only the additional DHCP options to be added to the packet before it is sent to the DHCP server. + * + * \param[out] DHCPHeader Location in the packet buffer where the BOOTP header should be written to + * \param[in] DHCPMessageType DHCP Message type, such as DHCP_DISCOVER + * \param[in] AppState Application state of the current UDP connection + * + * \return Size in bytes of the created DHCP packet + */ +static uint16_t DHCPClientApp_FillDHCPHeader(DHCP_Header_t* const DHCPHeader, + const uint8_t DHCPMessageType, + uip_udp_appstate_t* const AppState) +{ + /* Erase existing packet data so that we start will all 0x00 DHCP header data */ + memset(DHCPHeader, 0, sizeof(DHCP_Header_t)); + + /* Fill out the DHCP packet header */ + DHCPHeader->Operation = DHCP_OP_BOOTREQUEST; + DHCPHeader->HardwareType = DHCP_HTYPE_ETHERNET; + DHCPHeader->HardwareAddressLength = sizeof(MACAddress); + DHCPHeader->Hops = 0; + DHCPHeader->TransactionID = DHCP_TRANSACTION_ID; + DHCPHeader->ElapsedSeconds = 0; + DHCPHeader->Flags = HTONS(BOOTP_BROADCAST); + memcpy(&DHCPHeader->ClientIP, &uip_hostaddr, sizeof(uip_ipaddr_t)); + memcpy(&DHCPHeader->YourIP, &AppState->DHCPClient.DHCPOffer_Data.AllocatedIP, sizeof(uip_ipaddr_t)); + memcpy(&DHCPHeader->NextServerIP, &AppState->DHCPClient.DHCPOffer_Data.ServerIP, sizeof(uip_ipaddr_t)); + memcpy(&DHCPHeader->ClientHardwareAddress, &MACAddress, sizeof(struct uip_eth_addr)); + DHCPHeader->Cookie = DHCP_MAGIC_COOKIE; + + /* Add a DHCP message type and terminator options to the start of the DHCP options field */ + DHCPHeader->Options[0] = DHCP_OPTION_MSG_TYPE; + DHCPHeader->Options[1] = 1; + DHCPHeader->Options[2] = DHCPMessageType; + DHCPHeader->Options[3] = DHCP_OPTION_END; + + /* Calculate the total number of bytes added to the outgoing packet */ + return (sizeof(DHCP_Header_t) + 4); +} + +#endif + diff --git a/Projects/Webserver/Lib/DHCPClientApp.h b/Projects/Webserver/Lib/DHCPClientApp.h new file mode 100644 index 0000000000..0aec00331c --- /dev/null +++ b/Projects/Webserver/Lib/DHCPClientApp.h @@ -0,0 +1,69 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2017. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2017 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaims all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ + +/** \file + * + * Header file for DHCPClientApp.c. + */ + +#ifndef _DHCPCLIENT_APP_H_ +#define _DHCPCLIENT_APP_H_ + + /* Includes: */ + #include + + #include + + #include "Config/AppConfig.h" + #include "../Webserver.h" + #include "DHCPCommon.h" + + /* Enums: */ + /** States for each DHCP connection to a DHCP client. */ + enum DHCP_Client_States_t + { + DHCP_STATE_SendDiscover, /**< Send DISCOVER packet to retrieve DHCP lease offers */ + DHCP_STATE_WaitForOffer, /**< Waiting for OFFER packet giving available DHCP leases */ + DHCP_STATE_SendRequest, /**< Send REQUEST packet to request a DHCP lease */ + DHCP_STATE_WaitForACK, /**< Wait for ACK packet to complete the DHCP lease */ + DHCP_STATE_AddressLeased, /**< DHCP address has been leased from a DHCP server */ + }; + + /* Function Prototypes: */ + void DHCPClientApp_Init(void); + void DHCPClientApp_Callback(void); + + #if defined(INCLUDE_FROM_DHCPCLIENTAPP_C) + static uint16_t DHCPClientApp_FillDHCPHeader(DHCP_Header_t* const DHCPHeader, + const uint8_t DHCPMessageType, + uip_udp_appstate_t* const AppState); + #endif +#endif + diff --git a/Projects/Webserver/Lib/DHCPCommon.c b/Projects/Webserver/Lib/DHCPCommon.c new file mode 100644 index 0000000000..6d80f65cae --- /dev/null +++ b/Projects/Webserver/Lib/DHCPCommon.c @@ -0,0 +1,103 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2017. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2017 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaims all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ + +/** \file + * + * Common DHCP routines to manage DHCP packet data. + */ + +#include "DHCPCommon.h" + +#if defined(ENABLE_DHCP_CLIENT) || defined(ENABLE_DHCP_SERVER) || defined(__DOXYGEN__) + +/** Sets the given DHCP option in the DHCP packet's option list. This automatically moves the + * end of options terminator past the new option in the options list. + * + * \param[in,out] DHCPOptionList Pointer to the start of the DHCP packet's options list + * \param[in] Option DHCP option to add to the list + * \param[in] DataLen Size in bytes of the option data to add + * \param[in] OptionData Buffer where the option's data is to be sourced from + * + * \return Number of bytes added to the DHCP packet + */ +uint8_t DHCPCommon_SetOption(uint8_t* DHCPOptionList, + const uint8_t Option, + const uint8_t DataLen, + void* const OptionData) +{ + /* Skip through the DHCP options list until the terminator option is found */ + while (*DHCPOptionList != DHCP_OPTION_END) + DHCPOptionList += (DHCPOptionList[1] + 2); + + /* Overwrite the existing terminator with the new option, add a new terminator at the end of the list */ + DHCPOptionList[0] = Option; + DHCPOptionList[1] = DataLen; + memcpy(&DHCPOptionList[2], OptionData, DataLen); + DHCPOptionList[2 + DataLen] = DHCP_OPTION_END; + + /* Calculate the total number of bytes added to the outgoing packet */ + return (2 + DataLen); +} + +/** Retrieves the given option's data (if present) from the DHCP packet's options list. + * + * \param[in,out] DHCPOptionList Pointer to the start of the DHCP packet's options list + * \param[in] Option DHCP option to retrieve to the list + * \param[out] Destination Buffer where the option's data is to be written to if found + * + * \return Boolean \c true if the option was found in the DHCP packet's options list, \c false otherwise + */ +bool DHCPCommon_GetOption(const uint8_t* DHCPOptionList, + const uint8_t Option, + void* const Destination) +{ + /* Look through the incoming DHCP packet's options list for the requested option */ + while (*DHCPOptionList != DHCP_OPTION_END) + { + /* Check if the current DHCP option in the packet is the one requested */ + if (DHCPOptionList[0] == Option) + { + /* Copy request option's data to the destination buffer */ + memcpy(Destination, &DHCPOptionList[2], DHCPOptionList[1]); + + /* Indicate that the requested option data was successfully retrieved */ + return true; + } + + /* Skip to next DHCP option in the options list */ + DHCPOptionList += (DHCPOptionList[1] + 2); + } + + /* Requested option not found in the incoming packet's DHCP options list */ + return false; +} + +#endif + diff --git a/Projects/Webserver/Lib/DHCPCommon.h b/Projects/Webserver/Lib/DHCPCommon.h new file mode 100644 index 0000000000..8f54c16717 --- /dev/null +++ b/Projects/Webserver/Lib/DHCPCommon.h @@ -0,0 +1,159 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2017. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2017 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaims all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ + +/** \file + * + * Header file for common DHCP defines. + */ + +#ifndef _DHCP_COMMON_H_ +#define _DHCP_COMMON_H_ + + /* Includes: */ + #include + #include + #include + + #include "Config/AppConfig.h" + + #include + + /* Macros: */ + /** UDP listen port for a BOOTP server. */ + #define DHCP_SERVER_PORT 67 + + /** UDP listen port for a BOOTP client. */ + #define DHCP_CLIENT_PORT 68 + + /** BOOTP message type for a BOOTP REQUEST message. */ + #define DHCP_OP_BOOTREQUEST 0x01 + + /** BOOTP message type for a BOOTP REPLY message. */ + #define DHCP_OP_BOOTREPLY 0x02 + + /** BOOTP flag for a BOOTP broadcast message. */ + #define BOOTP_BROADCAST 0x8000 + + /** Magic DHCP cookie for a BOOTP message to identify it as a DHCP message. */ + #define DHCP_MAGIC_COOKIE 0x63538263 + + /** Unique transaction ID used to identify DHCP responses to the client. */ + #define DHCP_TRANSACTION_ID 0x13245466 + + /** DHCP message type for a DISCOVER message. */ + #define DHCP_DISCOVER 1 + + /** DHCP message type for an OFFER message. */ + #define DHCP_OFFER 2 + + /** DHCP message type for a REQUEST message. */ + #define DHCP_REQUEST 3 + + /** DHCP message type for a DECLINE message. */ + #define DHCP_DECLINE 4 + + /** DHCP message type for an ACK message. */ + #define DHCP_ACK 5 + + /** DHCP message type for a NAK message. */ + #define DHCP_NAK 6 + + /** DHCP message type for a RELEASE message. */ + #define DHCP_RELEASE 7 + + /** DHCP medium type for standard Ethernet. */ + #define DHCP_HTYPE_ETHERNET 1 + + /** DHCP message option for the network subnet mask. */ + #define DHCP_OPTION_SUBNET_MASK 1 + + /** DHCP message option for the network gateway IP. */ + #define DHCP_OPTION_ROUTER 3 + + /** DHCP message option for the network DNS server. */ + #define DHCP_OPTION_DNS_SERVER 6 + + /** DHCP message option for the requested client IP address. */ + #define DHCP_OPTION_REQ_IPADDR 50 + + /** DHCP message option for the IP address lease time. */ + #define DHCP_OPTION_LEASE_TIME 51 + + /** DHCP message option for the DHCP message type. */ + #define DHCP_OPTION_MSG_TYPE 53 + + /** DHCP message option for the DHCP server IP. */ + #define DHCP_OPTION_SERVER_ID 54 + + /** DHCP message option for the list of required options from the server. */ + #define DHCP_OPTION_REQ_LIST 55 + + /** DHCP message option for the options list terminator. */ + #define DHCP_OPTION_END 255 + + /* Type Defines: */ + /** Type define for a DHCP packet inside an Ethernet frame. */ + typedef struct + { + uint8_t Operation; /**< DHCP operation, either DHCP_OP_BOOTREQUEST or DHCP_OP_BOOTREPLY */ + uint8_t HardwareType; /**< Hardware carrier type constant */ + uint8_t HardwareAddressLength; /**< Length in bytes of a hardware (MAC) address on the network */ + uint8_t Hops; /**< Number of hops required to reach the server, unused */ + + uint32_t TransactionID; /**< Unique ID of the DHCP packet, for positive matching between sent and received packets */ + + uint16_t ElapsedSeconds; /**< Elapsed seconds since the request was made */ + uint16_t Flags; /**< BOOTP packet flags */ + + uip_ipaddr_t ClientIP; /**< Client IP address, if already leased an IP */ + uip_ipaddr_t YourIP; /**< Client IP address */ + uip_ipaddr_t NextServerIP; /**< Legacy BOOTP protocol field, unused for DHCP */ + uip_ipaddr_t RelayAgentIP; /**< Legacy BOOTP protocol field, unused for DHCP */ + + uint8_t ClientHardwareAddress[16]; /**< Hardware (MAC) address of the client making a request to the DHCP server */ + uint8_t ServerHostnameString[64]; /**< Legacy BOOTP protocol field, unused for DHCP */ + uint8_t BootFileName[128]; /**< Legacy BOOTP protocol field, unused for DHCP */ + + uint32_t Cookie; /**< Magic BOOTP protocol cookie to indicate a valid packet */ + + uint8_t Options[]; /**< DHCP message options */ + } DHCP_Header_t; + + /* Function Prototypes: */ + uint8_t DHCPCommon_SetOption(uint8_t* DHCPOptionList, + const uint8_t Option, + const uint8_t DataLen, + void* const OptionData); + bool DHCPCommon_GetOption(const uint8_t* DHCPOptionList, + const uint8_t Option, + void* const Destination); + +#endif + diff --git a/Projects/Webserver/Lib/DHCPServerApp.c b/Projects/Webserver/Lib/DHCPServerApp.c new file mode 100644 index 0000000000..fea54ddb0e --- /dev/null +++ b/Projects/Webserver/Lib/DHCPServerApp.c @@ -0,0 +1,265 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2017. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2017 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaims all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ + +/** \file + * + * DHCP Server Application. When connected to the uIP stack, this will send IP configuration settings to a + * DHCP client on the network. + */ + +#define INCLUDE_FROM_DHCPSERVERAPP_C +#include "DHCPServerApp.h" + +#if defined(ENABLE_DHCP_SERVER) || defined(__DOXYGEN__) + +struct uip_conn* BroadcastConnection; + +uint8_t LeasedIPs[255 / 8]; + +/** Initialization function for the DHCP server. */ +void DHCPServerApp_Init(void) +{ + /* Listen on port 67 for DHCP server connections from hosts */ + uip_listen(HTONS(DHCP_SERVER_PORT)); + + /* Create a new UDP connection to the DHCP server port for the DHCP solicitation */ + struct uip_udp_conn* BroadcastConnection = uip_udp_new(&uip_broadcast_addr, HTONS(DHCP_CLIENT_PORT)); + + /* If the connection was successfully created, bind it to the local DHCP client port */ + if (BroadcastConnection != NULL) + uip_udp_bind(BroadcastConnection, HTONS(DHCP_SERVER_PORT)); + + /* Set all IP addresses as unleased */ + memset(LeasedIPs, 0x00, sizeof(LeasedIPs)); +} + +/** uIP stack application callback for the DHCP server. This function must be called each time the TCP/IP stack + * needs a UDP packet to be processed. + */ +void DHCPServerApp_Callback(void) +{ + DHCP_Header_t* const AppData = (DHCP_Header_t*)uip_appdata; + uint16_t AppDataSize = 0; + + /* Only process when new data arrives - don't retransmit lost packets */ + if (uip_newdata()) + { + /* Get the DHCP message type (if present), otherwise early-abort */ + uint8_t DHCPMessageType; + if (!(DHCPCommon_GetOption(AppData->Options, DHCP_OPTION_MSG_TYPE, &DHCPMessageType))) + return; + + uip_ipaddr_t Netmask, GatewayIPAddress, PreferredClientIP; + struct uip_eth_addr RemoteMACAddress; + uint32_t TransactionID; + + /* Get configured network mask, gateway IP and extract out DHCP transaction ID and remote IP */ + uip_getnetmask(&Netmask); + uip_getdraddr(&GatewayIPAddress); + memcpy(&RemoteMACAddress, &AppData->ClientHardwareAddress, sizeof(struct uip_eth_addr)); + TransactionID = AppData->TransactionID; + + /* Try to extract out the client's preferred IP address if it is indicated in the packet */ + if (!(DHCPCommon_GetOption(AppData->Options, DHCP_OPTION_REQ_IPADDR, &PreferredClientIP))) + memcpy(&PreferredClientIP, &uip_all_zeroes_addr, sizeof(uip_ipaddr_t)); + + switch (DHCPMessageType) + { + case DHCP_DISCOVER: + /* If no preference was made or the preferred IP is already taken, find a new address */ + if (DHCPServerApp_CheckIfIPLeased(&PreferredClientIP)) + DHCPServerApp_GetUnleasedIP(&PreferredClientIP); + + /* Create a new DHCP OFFER packet with the offered IP address */ + AppDataSize += DHCPServerApp_FillDHCPHeader(AppData, DHCP_OFFER, &RemoteMACAddress, &PreferredClientIP, TransactionID); + + /* Add network mask and router information to the list of DHCP OFFER packet options */ + AppDataSize += DHCPCommon_SetOption(AppData->Options, DHCP_OPTION_SUBNET_MASK, + sizeof(uip_ipaddr_t), &Netmask); + AppDataSize += DHCPCommon_SetOption(AppData->Options, DHCP_OPTION_ROUTER, + sizeof(uip_ipaddr_t), &GatewayIPAddress); + + /* Send the DHCP OFFER packet */ + uip_poll_conn(BroadcastConnection); + memcpy(&uip_udp_conn->ripaddr, &uip_broadcast_addr, sizeof(uip_ipaddr_t)); + uip_udp_send(AppDataSize); + + break; + case DHCP_REQUEST: + /* Check to see if the requested IP address has already been leased to a client */ + if (!(DHCPServerApp_CheckIfIPLeased(&PreferredClientIP))) + { + /* Create a new DHCP ACK packet to accept the IP address lease */ + AppDataSize += DHCPServerApp_FillDHCPHeader(AppData, DHCP_ACK, &RemoteMACAddress, &PreferredClientIP, TransactionID); + + /* Add network mask and router information to the list of DHCP ACK packet options */ + AppDataSize += DHCPCommon_SetOption(AppData->Options, DHCP_OPTION_SUBNET_MASK, + sizeof(uip_ipaddr_t), &Netmask); + AppDataSize += DHCPCommon_SetOption(AppData->Options, DHCP_OPTION_ROUTER, + sizeof(uip_ipaddr_t), &GatewayIPAddress); + + /* Mark the requested IP as leased to a client */ + DHCPServerApp_LeaseIP(&PreferredClientIP); + } + else + { + /* Create a new DHCP NAK packet to reject the requested allocation */ + AppDataSize += DHCPServerApp_FillDHCPHeader(AppData, DHCP_NAK, &RemoteMACAddress, &uip_all_zeroes_addr, TransactionID); + } + + /* Send the DHCP ACK or NAK packet */ + uip_poll_conn(BroadcastConnection); + memcpy(&uip_udp_conn->ripaddr, &uip_broadcast_addr, sizeof(uip_ipaddr_t)); + uip_udp_send(AppDataSize); + + break; + case DHCP_RELEASE: + /* Mark the IP address as released in the allocation table */ + DHCPServerApp_UnleaseIP(&uip_udp_conn->ripaddr); + break; + } + } +} + +/** Fills the DHCP packet response with the appropriate BOOTP header for DHCP. This fills out all the required + * fields, leaving only the additional DHCP options to be added to the packet before it is sent to the DHCP client. + * + * \param[out] DHCPHeader Location in the packet buffer where the BOOTP header should be written to + * \param[in] DHCPMessageType DHCP Message type, such as DHCP_DISCOVER + * \param[in] ClientHardwareAddress Client MAC address the created transaction should be directed to + * \param[in] PreferredClientIP Preferred IP that should be given to the client if it is unallocated + * \param[in] TransactionID Transaction ID the created transaction should be associated with + * + * \return Size in bytes of the created DHCP packet + */ +static uint16_t DHCPServerApp_FillDHCPHeader(DHCP_Header_t* const DHCPHeader, + const uint8_t DHCPMessageType, + const struct uip_eth_addr* const ClientHardwareAddress, + const uip_ipaddr_t* const PreferredClientIP, + const uint32_t TransactionID) +{ + /* Erase existing packet data so that we start will all 0x00 DHCP header data */ + memset(DHCPHeader, 0, sizeof(DHCP_Header_t)); + + DHCPHeader->Operation = DHCPMessageType; + DHCPHeader->HardwareType = DHCP_HTYPE_ETHERNET; + DHCPHeader->HardwareAddressLength = sizeof(MACAddress); + DHCPHeader->Hops = 0; + DHCPHeader->TransactionID = TransactionID; + DHCPHeader->ElapsedSeconds = 0; + DHCPHeader->Flags = 0; + memcpy(&DHCPHeader->NextServerIP, &uip_hostaddr, sizeof(uip_ipaddr_t)); + memcpy(&DHCPHeader->YourIP, PreferredClientIP, sizeof(uip_ipaddr_t)); + memcpy(&DHCPHeader->ClientHardwareAddress, ClientHardwareAddress, sizeof(struct uip_eth_addr)); + DHCPHeader->Cookie = DHCP_MAGIC_COOKIE; + + /* Add a DHCP message type and terminator options to the start of the DHCP options field */ + DHCPHeader->Options[0] = DHCP_OPTION_MSG_TYPE; + DHCPHeader->Options[1] = 1; + DHCPHeader->Options[2] = DHCPMessageType; + DHCPHeader->Options[3] = DHCP_OPTION_END; + + /* Calculate the total number of bytes added to the outgoing packet */ + return (sizeof(DHCP_Header_t) + 4); +} + +/** Checks to see if the nominated IP address has already been allocated to a client. + * + * \param[in] IPAddress IP Address whose lease status should be checked + * + * \pre The IP address must be within the same /24 subnet as the virtual webserver. + * + * \return Boolean \c true if the IP has already been leased to a client, \c false otherwise. + */ +static bool DHCPServerApp_CheckIfIPLeased(const uip_ipaddr_t* const IPAddress) +{ + uint8_t Byte = (IPAddress->u8[3] / 8); + uint8_t Mask = (1 << (IPAddress->u8[3] % 8)); + + /* Make sure that the requested IP address isn't already leased to the virtual server or another client */ + if (IPAddress->u8[3] && !(IPAddress->u8[3] == uip_hostaddr.u8[3]) && !(LeasedIPs[Byte] & Mask)) + return false; + else + return true; +} + +/** Retrieves the next unleased IP in the IP address pool. + * + * \param[out] NewIPAddress Location where the generated IP Address should be stored + */ +static void DHCPServerApp_GetUnleasedIP(uip_ipaddr_t* const NewIPAddress) +{ + uip_ipaddr_copy(NewIPAddress, &uip_hostaddr); + + /** Look through the current subnet, skipping the broadcast and zero IP addresses */ + for (uint8_t IP = 1; IP < 254; IP++) + { + /* Update new IP address to lease with the current IP address to test */ + NewIPAddress->u8[3] = IP; + + /* If we've found an unleased IP, abort with the updated IP stored for the called */ + if (!(DHCPServerApp_CheckIfIPLeased(NewIPAddress))) + return; + } +} + +/** Marks the given IP Address as leased in the address pool, so that it will not be + * allocated to another client unless it is first released. + * + * \param[in] IPAddress IP Address to mark as leased + * + * \pre The IP address must be within the same /24 subnet as the virtual webserver. + */ +static void DHCPServerApp_LeaseIP(const uip_ipaddr_t* const IPAddress) +{ + uint8_t Byte = (IPAddress->u8[3] / 8); + uint8_t Mask = (1 << (IPAddress->u8[3] % 8)); + + /* Mark the IP address as leased in the allocation table */ + LeasedIPs[Byte] |= Mask; +} + +/** Marks the given IP Address as not leased in the address pool, so that it can be + * allocated to another client upon request. + * + * \param[in] IPAddress IP Address to mark as not leased + * + * \pre The IP address must be within the same /24 subnet as the virtual webserver. + */ +static void DHCPServerApp_UnleaseIP(const uip_ipaddr_t* const IPAddress) +{ + uint8_t Byte = (IPAddress->u8[3] / 8); + uint8_t Mask = (1 << (IPAddress->u8[3] % 8)); + + /* Mark the IP address as unleased in the allocation table */ + LeasedIPs[Byte] &= ~Mask; +} +#endif + diff --git a/Projects/Webserver/Lib/DHCPServerApp.h b/Projects/Webserver/Lib/DHCPServerApp.h new file mode 100644 index 0000000000..a9dae7bf3a --- /dev/null +++ b/Projects/Webserver/Lib/DHCPServerApp.h @@ -0,0 +1,64 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2017. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2017 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaims all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ + +/** \file + * + * Header file for DHCPServerApp.c. + */ + +#ifndef _DHCPSERVER_APP_H_ +#define _DHCPSERVER_APP_H_ + + /* Includes: */ + #include + + #include + + #include "Config/AppConfig.h" + #include "../Webserver.h" + #include "DHCPCommon.h" + + /* Function Prototypes: */ + void DHCPServerApp_Init(void); + void DHCPServerApp_Callback(void); + + #if defined(INCLUDE_FROM_DHCPSERVERAPP_C) + static uint16_t DHCPServerApp_FillDHCPHeader(DHCP_Header_t* const DHCPHeader, + const uint8_t DHCPMessageType, + const struct uip_eth_addr* const ClientHardwareAddress, + const uip_ipaddr_t* const PreferredClientIP, + const uint32_t TransactionID); + static bool DHCPServerApp_CheckIfIPLeased(const uip_ipaddr_t* const IPAddress); + static void DHCPServerApp_GetUnleasedIP(uip_ipaddr_t* const NewIPAddress); + static void DHCPServerApp_LeaseIP(const uip_ipaddr_t* const IPAddress); + static void DHCPServerApp_UnleaseIP(const uip_ipaddr_t* const IPAddress); + #endif +#endif + diff --git a/Projects/Webserver/Lib/DataflashManager.c b/Projects/Webserver/Lib/DataflashManager.c new file mode 100644 index 0000000000..b1111ce39b --- /dev/null +++ b/Projects/Webserver/Lib/DataflashManager.c @@ -0,0 +1,534 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2017. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2017 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaims all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ + +/** \file + * + * Functions to manage the physical Dataflash media, including reading and writing of + * blocks of data. These functions are called by the SCSI layer when data must be stored + * or retrieved to/from the physical storage media. If a different media is used (such + * as a SD card or EEPROM), functions similar to these will need to be generated. + */ + +#define INCLUDE_FROM_DATAFLASHMANAGER_C +#include "DataflashManager.h" + +/** Writes blocks (OS blocks, not Dataflash pages) to the storage medium, the board Dataflash IC(s), from + * the pre-selected data OUT endpoint. This routine reads in OS sized blocks from the endpoint and writes + * them to the Dataflash in Dataflash page sized blocks. + * + * \param[in] MSInterfaceInfo Pointer to a structure containing a Mass Storage Class configuration and state + * \param[in] BlockAddress Data block starting address for the write sequence + * \param[in] TotalBlocks Number of blocks of data to write + */ +void DataflashManager_WriteBlocks(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo, + const uint32_t BlockAddress, + uint16_t TotalBlocks) +{ + uint16_t CurrDFPage = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE); + uint16_t CurrDFPageByte = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE); + uint8_t CurrDFPageByteDiv16 = (CurrDFPageByte >> 4); + bool UsingSecondBuffer = false; + + /* Select the correct starting Dataflash IC for the block requested */ + Dataflash_SelectChipFromPage(CurrDFPage); + +#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE) + /* Copy selected dataflash's current page contents to the Dataflash buffer */ + Dataflash_SendByte(DF_CMD_MAINMEMTOBUFF1); + Dataflash_SendAddressBytes(CurrDFPage, 0); + Dataflash_WaitWhileBusy(); +#endif + + /* Send the Dataflash buffer write command */ + Dataflash_SendByte(DF_CMD_BUFF1WRITE); + Dataflash_SendAddressBytes(0, CurrDFPageByte); + + /* Wait until endpoint is ready before continuing */ + if (Endpoint_WaitUntilReady()) + return; + + while (TotalBlocks) + { + uint8_t BytesInBlockDiv16 = 0; + + /* Write an endpoint packet sized data block to the Dataflash */ + while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4)) + { + /* Check if the endpoint is currently empty */ + if (!(Endpoint_IsReadWriteAllowed())) + { + /* Clear the current endpoint bank */ + Endpoint_ClearOUT(); + + /* Wait until the host has sent another packet */ + if (Endpoint_WaitUntilReady()) + return; + } + + /* Check if end of Dataflash page reached */ + if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4)) + { + /* Write the Dataflash buffer contents back to the Dataflash page */ + Dataflash_WaitWhileBusy(); + Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE); + Dataflash_SendAddressBytes(CurrDFPage, 0); + + /* Reset the Dataflash buffer counter, increment the page counter */ + CurrDFPageByteDiv16 = 0; + CurrDFPage++; + + /* Once all the Dataflash ICs have had their first buffers filled, switch buffers to maintain throughput */ + if (Dataflash_GetSelectedChip() == DATAFLASH_CHIP_MASK(DATAFLASH_TOTALCHIPS)) + UsingSecondBuffer = !(UsingSecondBuffer); + + /* Select the next Dataflash chip based on the new Dataflash page index */ + Dataflash_SelectChipFromPage(CurrDFPage); + +#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE) + /* If less than one Dataflash page remaining, copy over the existing page to preserve trailing data */ + if ((TotalBlocks * (VIRTUAL_MEMORY_BLOCK_SIZE >> 4)) < (DATAFLASH_PAGE_SIZE >> 4)) + { + /* Copy selected dataflash's current page contents to the Dataflash buffer */ + Dataflash_WaitWhileBusy(); + Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_MAINMEMTOBUFF2 : DF_CMD_MAINMEMTOBUFF1); + Dataflash_SendAddressBytes(CurrDFPage, 0); + Dataflash_WaitWhileBusy(); + } +#endif + + /* Send the Dataflash buffer write command */ + Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2WRITE : DF_CMD_BUFF1WRITE); + Dataflash_SendAddressBytes(0, 0); + } + + /* Write one 16-byte chunk of data to the Dataflash */ + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + Dataflash_SendByte(Endpoint_Read_8()); + + /* Increment the Dataflash page 16 byte block counter */ + CurrDFPageByteDiv16++; + + /* Increment the block 16 byte block counter */ + BytesInBlockDiv16++; + + /* Check if the current command is being aborted by the host */ + if (MSInterfaceInfo->State.IsMassStoreReset) + return; + } + + /* Decrement the blocks remaining counter */ + TotalBlocks--; + } + + /* Write the Dataflash buffer contents back to the Dataflash page */ + Dataflash_WaitWhileBusy(); + Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE); + Dataflash_SendAddressBytes(CurrDFPage, 0x00); + Dataflash_WaitWhileBusy(); + + /* If the endpoint is empty, clear it ready for the next packet from the host */ + if (!(Endpoint_IsReadWriteAllowed())) + Endpoint_ClearOUT(); + + /* Deselect all Dataflash chips */ + Dataflash_DeselectChip(); +} + +/** Reads blocks (OS blocks, not Dataflash pages) from the storage medium, the board Dataflash IC(s), into + * the pre-selected data IN endpoint. This routine reads in Dataflash page sized blocks from the Dataflash + * and writes them in OS sized blocks to the endpoint. + * + * \param[in] MSInterfaceInfo Pointer to a structure containing a Mass Storage Class configuration and state + * \param[in] BlockAddress Data block starting address for the read sequence + * \param[in] TotalBlocks Number of blocks of data to read + */ +void DataflashManager_ReadBlocks(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo, + const uint32_t BlockAddress, + uint16_t TotalBlocks) +{ + uint16_t CurrDFPage = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE); + uint16_t CurrDFPageByte = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE); + uint8_t CurrDFPageByteDiv16 = (CurrDFPageByte >> 4); + + /* Select the correct starting Dataflash IC for the block requested */ + Dataflash_SelectChipFromPage(CurrDFPage); + + /* Send the Dataflash main memory page read command */ + Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD); + Dataflash_SendAddressBytes(CurrDFPage, CurrDFPageByte); + Dataflash_SendByte(0x00); + Dataflash_SendByte(0x00); + Dataflash_SendByte(0x00); + Dataflash_SendByte(0x00); + + /* Wait until endpoint is ready before continuing */ + if (Endpoint_WaitUntilReady()) + return; + + while (TotalBlocks) + { + uint8_t BytesInBlockDiv16 = 0; + + /* Read an endpoint packet sized data block from the Dataflash */ + while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4)) + { + /* Check if the endpoint is currently full */ + if (!(Endpoint_IsReadWriteAllowed())) + { + /* Clear the endpoint bank to send its contents to the host */ + Endpoint_ClearIN(); + + /* Wait until the endpoint is ready for more data */ + if (Endpoint_WaitUntilReady()) + return; + } + + /* Check if end of Dataflash page reached */ + if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4)) + { + /* Reset the Dataflash buffer counter, increment the page counter */ + CurrDFPageByteDiv16 = 0; + CurrDFPage++; + + /* Select the next Dataflash chip based on the new Dataflash page index */ + Dataflash_SelectChipFromPage(CurrDFPage); + + /* Send the Dataflash main memory page read command */ + Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD); + Dataflash_SendAddressBytes(CurrDFPage, 0); + Dataflash_SendByte(0x00); + Dataflash_SendByte(0x00); + Dataflash_SendByte(0x00); + Dataflash_SendByte(0x00); + } + + /* Read one 16-byte chunk of data from the Dataflash */ + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + Endpoint_Write_8(Dataflash_ReceiveByte()); + + /* Increment the Dataflash page 16 byte block counter */ + CurrDFPageByteDiv16++; + + /* Increment the block 16 byte block counter */ + BytesInBlockDiv16++; + + /* Check if the current command is being aborted by the host */ + if (MSInterfaceInfo->State.IsMassStoreReset) + return; + } + + /* Decrement the blocks remaining counter */ + TotalBlocks--; + } + + /* If the endpoint is full, send its contents to the host */ + if (!(Endpoint_IsReadWriteAllowed())) + Endpoint_ClearIN(); + + /* Deselect all Dataflash chips */ + Dataflash_DeselectChip(); +} + +/** Writes blocks (OS blocks, not Dataflash pages) to the storage medium, the board Dataflash IC(s), from + * the given RAM buffer. This routine reads in OS sized blocks from the buffer and writes them to the + * Dataflash in Dataflash page sized blocks. This can be linked to FAT libraries to write files to the + * Dataflash. + * + * \param[in] BlockAddress Data block starting address for the write sequence + * \param[in] TotalBlocks Number of blocks of data to write + * \param[in] BufferPtr Pointer to the data source RAM buffer + */ +void DataflashManager_WriteBlocks_RAM(const uint32_t BlockAddress, + uint16_t TotalBlocks, + const uint8_t* BufferPtr) +{ + uint16_t CurrDFPage = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE); + uint16_t CurrDFPageByte = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE); + uint8_t CurrDFPageByteDiv16 = (CurrDFPageByte >> 4); + bool UsingSecondBuffer = false; + + /* Select the correct starting Dataflash IC for the block requested */ + Dataflash_SelectChipFromPage(CurrDFPage); + +#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE) + /* Copy selected dataflash's current page contents to the Dataflash buffer */ + Dataflash_SendByte(DF_CMD_MAINMEMTOBUFF1); + Dataflash_SendAddressBytes(CurrDFPage, 0); + Dataflash_WaitWhileBusy(); +#endif + + /* Send the Dataflash buffer write command */ + Dataflash_SendByte(DF_CMD_BUFF1WRITE); + Dataflash_SendAddressBytes(0, CurrDFPageByte); + + while (TotalBlocks) + { + uint8_t BytesInBlockDiv16 = 0; + + /* Write an endpoint packet sized data block to the Dataflash */ + while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4)) + { + /* Check if end of Dataflash page reached */ + if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4)) + { + /* Write the Dataflash buffer contents back to the Dataflash page */ + Dataflash_WaitWhileBusy(); + Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE); + Dataflash_SendAddressBytes(CurrDFPage, 0); + + /* Reset the Dataflash buffer counter, increment the page counter */ + CurrDFPageByteDiv16 = 0; + CurrDFPage++; + + /* Once all the Dataflash ICs have had their first buffers filled, switch buffers to maintain throughput */ + if (Dataflash_GetSelectedChip() == DATAFLASH_CHIP_MASK(DATAFLASH_TOTALCHIPS)) + UsingSecondBuffer = !(UsingSecondBuffer); + + /* Select the next Dataflash chip based on the new Dataflash page index */ + Dataflash_SelectChipFromPage(CurrDFPage); + +#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE) + /* If less than one Dataflash page remaining, copy over the existing page to preserve trailing data */ + if ((TotalBlocks * (VIRTUAL_MEMORY_BLOCK_SIZE >> 4)) < (DATAFLASH_PAGE_SIZE >> 4)) + { + /* Copy selected dataflash's current page contents to the Dataflash buffer */ + Dataflash_WaitWhileBusy(); + Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_MAINMEMTOBUFF2 : DF_CMD_MAINMEMTOBUFF1); + Dataflash_SendAddressBytes(CurrDFPage, 0); + Dataflash_WaitWhileBusy(); + } +#endif + + /* Send the Dataflash buffer write command */ + Dataflash_ToggleSelectedChipCS(); + Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2WRITE : DF_CMD_BUFF1WRITE); + Dataflash_SendAddressBytes(0, 0); + } + + /* Write one 16-byte chunk of data to the Dataflash */ + for (uint8_t ByteNum = 0; ByteNum < 16; ByteNum++) + Dataflash_SendByte(*(BufferPtr++)); + + /* Increment the Dataflash page 16 byte block counter */ + CurrDFPageByteDiv16++; + + /* Increment the block 16 byte block counter */ + BytesInBlockDiv16++; + } + + /* Decrement the blocks remaining counter */ + TotalBlocks--; + } + + /* Write the Dataflash buffer contents back to the Dataflash page */ + Dataflash_WaitWhileBusy(); + Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE); + Dataflash_SendAddressBytes(CurrDFPage, 0x00); + Dataflash_WaitWhileBusy(); + + /* Deselect all Dataflash chips */ + Dataflash_DeselectChip(); +} + +/** Reads blocks (OS blocks, not Dataflash pages) from the storage medium, the board Dataflash IC(s), into + * the preallocated RAM buffer. This routine reads in Dataflash page sized blocks from the Dataflash + * and writes them in OS sized blocks to the given buffer. This can be linked to FAT libraries to read + * the files stored on the Dataflash. + * + * \param[in] BlockAddress Data block starting address for the read sequence + * \param[in] TotalBlocks Number of blocks of data to read + * \param[out] BufferPtr Pointer to the data destination RAM buffer + */ +void DataflashManager_ReadBlocks_RAM(const uint32_t BlockAddress, + uint16_t TotalBlocks, + uint8_t* BufferPtr) +{ + uint16_t CurrDFPage = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE); + uint16_t CurrDFPageByte = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE); + uint8_t CurrDFPageByteDiv16 = (CurrDFPageByte >> 4); + + /* Select the correct starting Dataflash IC for the block requested */ + Dataflash_SelectChipFromPage(CurrDFPage); + + /* Send the Dataflash main memory page read command */ + Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD); + Dataflash_SendAddressBytes(CurrDFPage, CurrDFPageByte); + Dataflash_SendByte(0x00); + Dataflash_SendByte(0x00); + Dataflash_SendByte(0x00); + Dataflash_SendByte(0x00); + + while (TotalBlocks) + { + uint8_t BytesInBlockDiv16 = 0; + + /* Read an endpoint packet sized data block from the Dataflash */ + while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4)) + { + /* Check if end of Dataflash page reached */ + if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4)) + { + /* Reset the Dataflash buffer counter, increment the page counter */ + CurrDFPageByteDiv16 = 0; + CurrDFPage++; + + /* Select the next Dataflash chip based on the new Dataflash page index */ + Dataflash_SelectChipFromPage(CurrDFPage); + + /* Send the Dataflash main memory page read command */ + Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD); + Dataflash_SendAddressBytes(CurrDFPage, 0); + Dataflash_SendByte(0x00); + Dataflash_SendByte(0x00); + Dataflash_SendByte(0x00); + Dataflash_SendByte(0x00); + } + + /* Read one 16-byte chunk of data from the Dataflash */ + for (uint8_t ByteNum = 0; ByteNum < 16; ByteNum++) + *(BufferPtr++) = Dataflash_ReceiveByte(); + + /* Increment the Dataflash page 16 byte block counter */ + CurrDFPageByteDiv16++; + + /* Increment the block 16 byte block counter */ + BytesInBlockDiv16++; + } + + /* Decrement the blocks remaining counter */ + TotalBlocks--; + } + + /* Deselect all Dataflash chips */ + Dataflash_DeselectChip(); +} + +/** Disables the Dataflash memory write protection bits on the board Dataflash ICs, if enabled. */ +void DataflashManager_ResetDataflashProtections(void) +{ + /* Select first Dataflash chip, send the read status register command */ + Dataflash_SelectChip(DATAFLASH_CHIP1); + Dataflash_SendByte(DF_CMD_GETSTATUS); + + /* Check if sector protection is enabled */ + if (Dataflash_ReceiveByte() & DF_STATUS_SECTORPROTECTION_ON) + { + Dataflash_ToggleSelectedChipCS(); + + /* Send the commands to disable sector protection */ + Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[0]); + Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[1]); + Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[2]); + Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[3]); + } + + /* Select second Dataflash chip (if present on selected board), send read status register command */ + #if (DATAFLASH_TOTALCHIPS == 2) + Dataflash_SelectChip(DATAFLASH_CHIP2); + Dataflash_SendByte(DF_CMD_GETSTATUS); + + /* Check if sector protection is enabled */ + if (Dataflash_ReceiveByte() & DF_STATUS_SECTORPROTECTION_ON) + { + Dataflash_ToggleSelectedChipCS(); + + /* Send the commands to disable sector protection */ + Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[0]); + Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[1]); + Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[2]); + Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[3]); + } + #endif + + /* Deselect current Dataflash chip */ + Dataflash_DeselectChip(); +} + +/** Performs a simple test on the attached Dataflash IC(s) to ensure that they are working. + * + * \return Boolean \c true if all media chips are working, \c false otherwise + */ +bool DataflashManager_CheckDataflashOperation(void) +{ + uint8_t ReturnByte; + + /* Test first Dataflash IC is present and responding to commands */ + Dataflash_SelectChip(DATAFLASH_CHIP1); + Dataflash_SendByte(DF_CMD_READMANUFACTURERDEVICEINFO); + ReturnByte = Dataflash_ReceiveByte(); + Dataflash_DeselectChip(); + + /* If returned data is invalid, fail the command */ + if (ReturnByte != DF_MANUFACTURER_ATMEL) + return false; + + #if (DATAFLASH_TOTALCHIPS == 2) + /* Test second Dataflash IC is present and responding to commands */ + Dataflash_SelectChip(DATAFLASH_CHIP2); + Dataflash_SendByte(DF_CMD_READMANUFACTURERDEVICEINFO); + ReturnByte = Dataflash_ReceiveByte(); + Dataflash_DeselectChip(); + + /* If returned data is invalid, fail the command */ + if (ReturnByte != DF_MANUFACTURER_ATMEL) + return false; + #endif + + return true; +} + diff --git a/Projects/Webserver/Lib/DataflashManager.h b/Projects/Webserver/Lib/DataflashManager.h new file mode 100644 index 0000000000..367fbac8c4 --- /dev/null +++ b/Projects/Webserver/Lib/DataflashManager.h @@ -0,0 +1,87 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2017. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2017 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaims all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ + +/** \file + * + * Header file for DataflashManager.c. + */ + +#ifndef _DATAFLASH_MANAGER_H_ +#define _DATAFLASH_MANAGER_H_ + + /* Includes: */ + #include + + #include "../Descriptors.h" + + #include + #include + #include + + /* Preprocessor Checks: */ + #if (DATAFLASH_PAGE_SIZE % 16) + #error Dataflash page size must be a multiple of 16 bytes. + #endif + + /* Defines: */ + /** Total number of bytes of the storage medium, comprised of one or more Dataflash ICs. */ + #define VIRTUAL_MEMORY_BYTES ((uint32_t)DATAFLASH_PAGES * DATAFLASH_PAGE_SIZE * DATAFLASH_TOTALCHIPS) + + /** Block size of the device. This is kept at 512 to remain compatible with the OS despite the underlying + * storage media (Dataflash) using a different native block size. Do not change this value. + */ + #define VIRTUAL_MEMORY_BLOCK_SIZE 512 + + /** Total number of blocks of the virtual memory for reporting to the host as the device's total capacity. Do not + * change this value; change VIRTUAL_MEMORY_BYTES instead to alter the media size. + */ + #define VIRTUAL_MEMORY_BLOCKS (VIRTUAL_MEMORY_BYTES / VIRTUAL_MEMORY_BLOCK_SIZE) + + /** Indicates if the disk is write protected or not. */ + #define DISK_READ_ONLY false + + /* Function Prototypes: */ + void DataflashManager_WriteBlocks(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo, + const uint32_t BlockAddress, + uint16_t TotalBlocks); + void DataflashManager_ReadBlocks(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo, + const uint32_t BlockAddress, + uint16_t TotalBlocks); + void DataflashManager_WriteBlocks_RAM(const uint32_t BlockAddress, + uint16_t TotalBlocks, + const uint8_t* BufferPtr) ATTR_NON_NULL_PTR_ARG(3); + void DataflashManager_ReadBlocks_RAM(const uint32_t BlockAddress, + uint16_t TotalBlocks, + uint8_t* BufferPtr) ATTR_NON_NULL_PTR_ARG(3); + void DataflashManager_ResetDataflashProtections(void); + bool DataflashManager_CheckDataflashOperation(void); + +#endif + diff --git a/Projects/Webserver/Lib/FATFs/00readme.txt b/Projects/Webserver/Lib/FATFs/00readme.txt new file mode 100644 index 0000000000..80d8843d13 --- /dev/null +++