answer stringlengths 15 1.25M |
|---|
/** @file ai_order.cpp Implementation of AIOrder. */
#include "../../stdafx.h"
#include "ai_order.hpp"
#include "ai_vehicle.hpp"
#include "../ai_instance.hpp"
#include "../../debug.h"
#include "../../vehicle_base.h"
#include "../../roadstop_base.h"
#include "../../depot_base.h"
#include "../../station_base.h"
#include "../../waypoint_base.h"
/**
* Gets the order type given a tile
* @param t the tile to get the order from
* @return the order type, or OT_END when there is no order
*/
static OrderType GetOrderTypeByTile(TileIndex t)
{
if (!::IsValidTile(t)) return OT_END;
switch (::GetTileType(t)) {
default: break;
case MP_STATION:
if (IsBuoy(t) || IsRailWaypoint(t)) return OT_GOTO_WAYPOINT;
if (IsHangar(t)) return OT_GOTO_DEPOT;
return OT_GOTO_STATION;
case MP_WATER: if (::IsShipDepot(t)) return OT_GOTO_DEPOT; break;
case MP_ROAD: if (::GetRoadTileType(t) == ROAD_TILE_DEPOT) return OT_GOTO_DEPOT; break;
case MP_RAILWAY:
if (IsRailDepot(t)) return OT_GOTO_DEPOT;
break;
}
return OT_END;
}
/* static */ bool AIOrder::IsValidVehicleOrder(VehicleID vehicle_id, OrderPosition order_position)
{
return AIVehicle::IsValidVehicle(vehicle_id) && order_position >= 0 && (order_position < ::Vehicle::Get(vehicle_id)->GetNumManualOrders() || order_position == ORDER_CURRENT);
}
/**
* Get the current order the vehicle is executing. If the current order is in
* the order list, return the order from the orderlist. If the current order
* was a manual order, return the current order.
*/
static const Order *ResolveOrder(VehicleID vehicle_id, AIOrder::OrderPosition order_position)
{
const Vehicle *v = ::Vehicle::Get(vehicle_id);
if (order_position == AIOrder::ORDER_CURRENT) {
const Order *order = &v->current_order;
if (order->GetType() == OT_GOTO_DEPOT && !(order->GetDepotOrderType() & <API key>)) return order;
order_position = AIOrder::<API key>(vehicle_id, order_position);
if (order_position == AIOrder::ORDER_INVALID) return NULL;
}
const Order *order = v->orders.list->GetFirstOrder();
while (order->GetType() == OT_AUTOMATIC) order = order->next;
while (order_position > 0) {
order_position = (AIOrder::OrderPosition)(order_position - 1);
order = order->next;
while (order->GetType() == OT_AUTOMATIC) order = order->next;
}
return order;
}
/* static */ bool AIOrder::IsGotoStationOrder(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return false;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
return order != NULL && order->GetType() == OT_GOTO_STATION;
}
/* static */ bool AIOrder::IsGotoDepotOrder(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return false;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
return order != NULL && order->GetType() == OT_GOTO_DEPOT;
}
/* static */ bool AIOrder::IsGotoWaypointOrder(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return false;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
return order != NULL && order->GetType() == OT_GOTO_WAYPOINT;
}
/* static */ bool AIOrder::IsConditionalOrder(VehicleID vehicle_id, OrderPosition order_position)
{
if (order_position == ORDER_CURRENT) return false;
if (!IsValidVehicleOrder(vehicle_id, order_position)) return false;
const Order *order = Vehicle::Get(vehicle_id)->GetOrder(order_position);
return order->GetType() == OT_CONDITIONAL;
}
/* static */ bool AIOrder::IsVoidOrder(VehicleID vehicle_id, OrderPosition order_position)
{
if (order_position == ORDER_CURRENT) return false;
if (!IsValidVehicleOrder(vehicle_id, order_position)) return false;
const Order *order = Vehicle::Get(vehicle_id)->GetOrder(order_position);
return order->GetType() == OT_DUMMY;
}
/* static */ bool AIOrder::<API key>(VehicleID vehicle_id)
{
if (AIVehicle::IsValidVehicle(vehicle_id)) return false;
if (GetOrderCount(vehicle_id) == 0) return false;
const Order *order = &::Vehicle::Get(vehicle_id)->current_order;
if (order->GetType() != OT_GOTO_DEPOT) return true;
return (order->GetDepotOrderType() & <API key>) != 0;
}
/* static */ AIOrder::OrderPosition AIOrder::<API key>(VehicleID vehicle_id, OrderPosition order_position)
{
if (!AIVehicle::IsValidVehicle(vehicle_id)) return ORDER_INVALID;
if (order_position == ORDER_CURRENT) {
int cur_order_pos = ::Vehicle::Get(vehicle_id)-><API key>;
const Order *order = ::Vehicle::Get(vehicle_id)->GetOrder(0);
if (order == NULL) return ORDER_INVALID;
int <API key> = 0;
for (int i = 0; i < cur_order_pos; i++) {
if (order->GetType() == OT_AUTOMATIC) <API key>++;
order = order->next;
}
return (AIOrder::OrderPosition)(cur_order_pos - <API key>);
}
return (order_position >= 0 && order_position < ::Vehicle::Get(vehicle_id)->GetNumManualOrders()) ? order_position : ORDER_INVALID;
}
/* static */ bool AIOrder::AreOrderFlagsValid(TileIndex destination, AIOrderFlags order_flags)
{
OrderType ot = (order_flags & <API key>) ? OT_GOTO_DEPOT : ::GetOrderTypeByTile(destination);
switch (ot) {
case OT_GOTO_STATION:
return (order_flags & ~(AIOF_NON_STOP_FLAGS | AIOF_UNLOAD_FLAGS | AIOF_LOAD_FLAGS)) == 0 &&
/* Test the different mutual exclusive flags. */
((order_flags & AIOF_TRANSFER) == 0 || (order_flags & AIOF_UNLOAD) == 0) &&
((order_flags & AIOF_TRANSFER) == 0 || (order_flags & AIOF_NO_UNLOAD) == 0) &&
((order_flags & AIOF_UNLOAD) == 0 || (order_flags & AIOF_NO_UNLOAD) == 0) &&
((order_flags & AIOF_UNLOAD) == 0 || (order_flags & AIOF_NO_UNLOAD) == 0) &&
((order_flags & AIOF_NO_UNLOAD) == 0 || (order_flags & AIOF_NO_LOAD) == 0) &&
((order_flags & AIOF_FULL_LOAD_ANY) == 0 || (order_flags & AIOF_NO_LOAD) == 0);
case OT_GOTO_DEPOT:
return (order_flags & ~(AIOF_NON_STOP_FLAGS | AIOF_DEPOT_FLAGS)) == 0 &&
((order_flags & <API key>) == 0 || (order_flags & AIOF_STOP_IN_DEPOT) == 0);
case OT_GOTO_WAYPOINT: return (order_flags & ~(AIOF_NON_STOP_FLAGS)) == 0;
default: return false;
}
}
/* static */ bool AIOrder::<API key>(OrderCondition condition, CompareFunction compare)
{
switch (condition) {
case OC_LOAD_PERCENTAGE:
case OC_RELIABILITY:
case OC_MAX_SPEED:
case OC_AGE:
return compare >= CF_EQUALS && compare <= CF_MORE_EQUALS;
case OC_REQUIRES_SERVICE:
return compare == CF_IS_TRUE || compare == CF_IS_FALSE;
case OC_UNCONDITIONALLY:
return true;
default: return false;
}
}
/* static */ int32 AIOrder::GetOrderCount(VehicleID vehicle_id)
{
return AIVehicle::IsValidVehicle(vehicle_id) ? ::Vehicle::Get(vehicle_id)->GetNumOrders() : -1;
}
/* static */ TileIndex AIOrder::GetOrderDestination(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return INVALID_TILE;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
if (order == NULL || order->GetType() == OT_CONDITIONAL) return INVALID_TILE;
const Vehicle *v = ::Vehicle::Get(vehicle_id);
switch (order->GetType()) {
case OT_GOTO_DEPOT: {
/* We don't know where the nearest depot is... (yet) */
if (order->GetDepotActionType() & <API key>) return INVALID_TILE;
if (v->type != VEH_AIRCRAFT) return ::Depot::Get(order->GetDestination())->xy;
/* Aircraft's hangars are referenced by StationID, not DepotID */
const Station *st = ::Station::Get(order->GetDestination());
if (!st->airport.HasHangar()) return INVALID_TILE;
return st->airport.GetHangarTile(0);
}
case OT_GOTO_STATION: {
const Station *st = ::Station::Get(order->GetDestination());
if (st->train_station.tile != INVALID_TILE) {
TILE_AREA_LOOP(t, st->train_station) {
if (st-><API key>(t)) return t;
}
} else if (st->dock_tile != INVALID_TILE) {
return st->dock_tile;
} else if (st->bus_stops != NULL) {
return st->bus_stops->xy;
} else if (st->truck_stops != NULL) {
return st->truck_stops->xy;
} else if (st->airport.tile != INVALID_TILE) {
TILE_AREA_LOOP(tile, st->airport) {
if (st-><API key>(tile) && !::IsHangar(tile)) return tile;
}
}
return INVALID_TILE;
}
case OT_GOTO_WAYPOINT: {
const Waypoint *wp = ::Waypoint::Get(order->GetDestination());
if (wp->train_station.tile != INVALID_TILE) {
TILE_AREA_LOOP(t, wp->train_station) {
if (wp-><API key>(t)) return t;
}
}
/* If the waypoint has no rail waypoint tiles, it must have a buoy */
return wp->xy;
}
default: return INVALID_TILE;
}
}
/* static */ AIOrder::AIOrderFlags AIOrder::GetOrderFlags(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return AIOF_INVALID;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
if (order == NULL || order->GetType() == OT_CONDITIONAL || order->GetType() == OT_DUMMY) return AIOF_INVALID;
AIOrderFlags order_flags = AIOF_NONE;
order_flags |= (AIOrderFlags)order->GetNonStopType();
switch (order->GetType()) {
case OT_GOTO_DEPOT:
if (order->GetDepotOrderType() & ODTFB_SERVICE) order_flags |= <API key>;
if (order->GetDepotActionType() & ODATFB_HALT) order_flags |= AIOF_STOP_IN_DEPOT;
if (order->GetDepotActionType() & <API key>) order_flags |= <API key>;
break;
case OT_GOTO_STATION:
order_flags |= (AIOrderFlags)(order->GetLoadType() << 5);
order_flags |= (AIOrderFlags)(order->GetUnloadType() << 2);
break;
default: break;
}
return order_flags;
}
/* static */ AIOrder::OrderPosition AIOrder::GetOrderJumpTo(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return ORDER_INVALID;
if (order_position == ORDER_CURRENT || !IsConditionalOrder(vehicle_id, order_position)) return ORDER_INVALID;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
return (OrderPosition)order-><API key>();
}
/* static */ AIOrder::OrderCondition AIOrder::GetOrderCondition(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return OC_INVALID;
if (order_position == ORDER_CURRENT || !IsConditionalOrder(vehicle_id, order_position)) return OC_INVALID;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
return (OrderCondition)order-><API key>();
}
/* static */ AIOrder::CompareFunction AIOrder::<API key>(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return CF_INVALID;
if (order_position == ORDER_CURRENT || !IsConditionalOrder(vehicle_id, order_position)) return CF_INVALID;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
return (CompareFunction)order-><API key>();
}
/* static */ int32 AIOrder::<API key>(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return -1;
if (order_position == ORDER_CURRENT || !IsConditionalOrder(vehicle_id, order_position)) return -1;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
int32 value = order->GetConditionValue();
if (order-><API key>() == OCV_MAX_SPEED) value = value * 16 / 10;
return value;
}
/* static */ AIOrder::StopLocation AIOrder::GetStopLocation(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return <API key>;
if (AIVehicle::GetVehicleType(vehicle_id) != AIVehicle::VT_RAIL) return <API key>;
if (!IsGotoStationOrder(vehicle_id, order_position)) return <API key>;
const Order *order = ::ResolveOrder(vehicle_id, order_position);
return (AIOrder::StopLocation)order->GetStopLocation();
}
/* static */ bool AIOrder::SetOrderJumpTo(VehicleID vehicle_id, OrderPosition order_position, OrderPosition jump_to)
{
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position));
EnforcePrecondition(false, order_position != ORDER_CURRENT && IsConditionalOrder(vehicle_id, order_position));
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, jump_to) && jump_to != ORDER_CURRENT);
return AIObject::DoCommand(0, vehicle_id | (order_position << 20), <API key> | (jump_to << 4), CMD_MODIFY_ORDER);
}
/* static */ bool AIOrder::SetOrderCondition(VehicleID vehicle_id, OrderPosition order_position, OrderCondition condition)
{
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position));
EnforcePrecondition(false, order_position != ORDER_CURRENT && IsConditionalOrder(vehicle_id, order_position));
EnforcePrecondition(false, condition >= OC_LOAD_PERCENTAGE && condition <= OC_UNCONDITIONALLY);
return AIObject::DoCommand(0, vehicle_id | (order_position << 20), MOF_COND_VARIABLE | (condition << 4), CMD_MODIFY_ORDER);
}
/* static */ bool AIOrder::<API key>(VehicleID vehicle_id, OrderPosition order_position, CompareFunction compare)
{
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position));
EnforcePrecondition(false, order_position != ORDER_CURRENT && IsConditionalOrder(vehicle_id, order_position));
EnforcePrecondition(false, compare >= CF_EQUALS && compare <= CF_IS_FALSE);
return AIObject::DoCommand(0, vehicle_id | (order_position << 20), MOF_COND_COMPARATOR | (compare << 4), CMD_MODIFY_ORDER);
}
/* static */ bool AIOrder::<API key>(VehicleID vehicle_id, OrderPosition order_position, int32 value)
{
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position));
EnforcePrecondition(false, order_position != ORDER_CURRENT && IsConditionalOrder(vehicle_id, order_position));
EnforcePrecondition(false, value >= 0 && value < 2048);
if (GetOrderCondition(vehicle_id, order_position) == OC_MAX_SPEED) value = value * 10 / 16;
return AIObject::DoCommand(0, vehicle_id | (order_position << 20), MOF_COND_VALUE | (value << 4), CMD_MODIFY_ORDER);
}
/* static */ bool AIOrder::SetStopLocation(VehicleID vehicle_id, OrderPosition order_position, StopLocation stop_location)
{
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position));
EnforcePrecondition(false, AIVehicle::GetVehicleType(vehicle_id) == AIVehicle::VT_RAIL);
EnforcePrecondition(false, IsGotoStationOrder(vehicle_id, order_position));
EnforcePrecondition(false, stop_location >= STOPLOCATION_NEAR && stop_location <= STOPLOCATION_FAR);
uint32 p1 = vehicle_id | (order_position << 20);
uint32 p2 = MOF_STOP_LOCATION | (stop_location << 4);
return AIObject::DoCommand(0, p1, p2, CMD_MODIFY_ORDER);
}
/* static */ bool AIOrder::AppendOrder(VehicleID vehicle_id, TileIndex destination, AIOrderFlags order_flags)
{
EnforcePrecondition(false, AIVehicle::IsValidVehicle(vehicle_id));
EnforcePrecondition(false, AreOrderFlagsValid(destination, order_flags));
return InsertOrder(vehicle_id, (AIOrder::OrderPosition)::Vehicle::Get(vehicle_id)->GetNumOrders(), destination, order_flags);
}
/* static */ bool AIOrder::<API key>(VehicleID vehicle_id, OrderPosition jump_to)
{
EnforcePrecondition(false, AIVehicle::IsValidVehicle(vehicle_id));
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, jump_to));
return <API key>(vehicle_id, (AIOrder::OrderPosition)::Vehicle::Get(vehicle_id)->GetNumOrders(), jump_to);
}
/* static */ bool AIOrder::InsertOrder(VehicleID vehicle_id, OrderPosition order_position, TileIndex destination, AIOrder::AIOrderFlags order_flags)
{
/* IsValidVehicleOrder is not good enough because it does not allow appending. */
if (order_position == ORDER_CURRENT) order_position = AIOrder::<API key>(vehicle_id, order_position);
EnforcePrecondition(false, AIVehicle::IsValidVehicle(vehicle_id));
EnforcePrecondition(false, order_position >= 0 && order_position <= ::Vehicle::Get(vehicle_id)->GetNumOrders());
EnforcePrecondition(false, AreOrderFlagsValid(destination, order_flags));
Order order;
OrderType ot = (order_flags & <API key>) ? OT_GOTO_DEPOT : ::GetOrderTypeByTile(destination);
switch (ot) {
case OT_GOTO_DEPOT: {
OrderDepotTypeFlags odtf = (OrderDepotTypeFlags)(<API key> | ((order_flags & <API key>) ? ODTFB_SERVICE : 0));
<API key> odaf = (<API key>)(ODATF_SERVICE_ONLY | ((order_flags & AIOF_STOP_IN_DEPOT) ? ODATFB_HALT : 0));
if (order_flags & <API key>) odaf |= <API key>;
OrderNonStopFlags onsf = (OrderNonStopFlags)((order_flags & <API key>) ? <API key> : <API key>);
if (order_flags & <API key>) {
order.MakeGoToDepot(0, odtf, onsf, odaf);
} else {
/* Check explicitly if the order is to a station (for aircraft) or
* to a depot (other vehicle types). */
if (::Vehicle::Get(vehicle_id)->type == VEH_AIRCRAFT) {
if (!::IsTileType(destination, MP_STATION)) return false;
order.MakeGoToDepot(::GetStationIndex(destination), odtf, onsf, odaf);
} else {
if (::IsTileType(destination, MP_STATION)) return false;
order.MakeGoToDepot(::GetDepotIndex(destination), odtf, onsf, odaf);
}
}
break;
}
case OT_GOTO_STATION:
order.MakeGoToStation(::GetStationIndex(destination));
order.SetLoadType((OrderLoadFlags)GB(order_flags, 5, 3));
order.SetUnloadType((OrderUnloadFlags)GB(order_flags, 2, 3));
order.SetStopLocation(<API key>);
break;
case OT_GOTO_WAYPOINT:
order.MakeGoToWaypoint(::GetStationIndex(destination));
break;
default:
return false;
}
order.SetNonStopType((OrderNonStopFlags)GB(order_flags, 0, 2));
return AIObject::DoCommand(0, vehicle_id | (order_position << 20), order.Pack(), CMD_INSERT_ORDER);
}
/* static */ bool AIOrder::<API key>(VehicleID vehicle_id, OrderPosition order_position, OrderPosition jump_to)
{
/* IsValidVehicleOrder is not good enough because it does not allow appending. */
if (order_position == ORDER_CURRENT) order_position = AIOrder::<API key>(vehicle_id, order_position);
EnforcePrecondition(false, AIVehicle::IsValidVehicle(vehicle_id));
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, jump_to));
Order order;
order.MakeConditional(jump_to);
return AIObject::DoCommand(0, vehicle_id | (order_position << 20), order.Pack(), CMD_INSERT_ORDER);
}
/* static */ bool AIOrder::RemoveOrder(VehicleID vehicle_id, OrderPosition order_position)
{
order_position = AIOrder::<API key>(vehicle_id, order_position);
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position));
return AIObject::DoCommand(0, vehicle_id, order_position, CMD_DELETE_ORDER);
}
/* static */ bool AIOrder::SkipToOrder(VehicleID vehicle_id, OrderPosition next_order)
{
next_order = AIOrder::<API key>(vehicle_id, next_order);
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, next_order));
return AIObject::DoCommand(0, vehicle_id, next_order, CMD_SKIP_TO_ORDER);
}
/**
* Callback handler as SetOrderFlags possibly needs multiple DoCommand calls
* to be able to set all order flags correctly. As we need to wait till the
* command has completed before we know the next bits to change we need to
* call the function multiple times. Each time it'll reduce the difference
* between the wanted and the current order.
* @param instance The AI we are doing the callback for.
*/
static void <API key>(class AIInstance *instance)
{
AIObject::SetLastCommandRes(AIOrder::_SetOrderFlags());
AIInstance::DoCommandReturn(instance);
}
/* static */ bool AIOrder::_SetOrderFlags()
{
/* Make sure we don't go into an infinite loop */
int retry = AIObject::GetCallbackVariable(3) - 1;
if (retry < 0) {
DEBUG(ai, 0, "Possible infinite loop in SetOrderFlags() detected");
return false;
}
AIObject::SetCallbackVariable(3, retry);
VehicleID vehicle_id = (VehicleID)AIObject::GetCallbackVariable(0);
OrderPosition order_position = (OrderPosition)AIObject::GetCallbackVariable(1);
AIOrderFlags order_flags = (AIOrderFlags)AIObject::GetCallbackVariable(2);
order_position = AIOrder::<API key>(vehicle_id, order_position);
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position));
EnforcePrecondition(false, AreOrderFlagsValid(GetOrderDestination(vehicle_id, order_position), order_flags));
const Order *order = ::ResolveOrder(vehicle_id, order_position);
AIOrderFlags current = GetOrderFlags(vehicle_id, order_position);
EnforcePrecondition(false, (order_flags & <API key>) == (current & <API key>));
if ((current & AIOF_NON_STOP_FLAGS) != (order_flags & AIOF_NON_STOP_FLAGS)) {
return AIObject::DoCommand(0, vehicle_id | (order_position << 20), (order_flags & AIOF_NON_STOP_FLAGS) << 4 | MOF_NON_STOP, CMD_MODIFY_ORDER, NULL, &<API key>);
}
switch (order->GetType()) {
case OT_GOTO_DEPOT:
if ((current & AIOF_DEPOT_FLAGS) != (order_flags & AIOF_DEPOT_FLAGS)) {
uint data = DA_ALWAYS_GO;
if (order_flags & <API key>) data = DA_SERVICE;
if (order_flags & AIOF_STOP_IN_DEPOT) data = DA_STOP;
return AIObject::DoCommand(0, vehicle_id | (order_position << 20), (data << 4) | MOF_DEPOT_ACTION, CMD_MODIFY_ORDER, NULL, &<API key>);
}
break;
case OT_GOTO_STATION:
if ((current & AIOF_UNLOAD_FLAGS) != (order_flags & AIOF_UNLOAD_FLAGS)) {
return AIObject::DoCommand(0, vehicle_id | (order_position << 20), (order_flags & AIOF_UNLOAD_FLAGS) << 2 | MOF_UNLOAD, CMD_MODIFY_ORDER, NULL, &<API key>);
}
if ((current & AIOF_LOAD_FLAGS) != (order_flags & AIOF_LOAD_FLAGS)) {
return AIObject::DoCommand(0, vehicle_id | (order_position << 20), (order_flags & AIOF_LOAD_FLAGS) >> 1 | MOF_LOAD, CMD_MODIFY_ORDER, NULL, &<API key>);
}
break;
default: break;
}
assert(GetOrderFlags(vehicle_id, order_position) == order_flags);
return true;
}
/* static */ bool AIOrder::SetOrderFlags(VehicleID vehicle_id, OrderPosition order_position, AIOrder::AIOrderFlags order_flags)
{
AIObject::SetCallbackVariable(0, vehicle_id);
AIObject::SetCallbackVariable(1, order_position);
AIObject::SetCallbackVariable(2, order_flags);
/* In case another client(s) change orders at the same time we could
* end in an infinite loop. This stops that from happening ever. */
AIObject::SetCallbackVariable(3, 8);
return AIOrder::_SetOrderFlags();
}
/* static */ bool AIOrder::MoveOrder(VehicleID vehicle_id, OrderPosition order_position_move, OrderPosition <API key>)
{
order_position_move = AIOrder::<API key>(vehicle_id, order_position_move);
<API key> = AIOrder::<API key>(vehicle_id, <API key>);
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position_move));
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, <API key>));
return AIObject::DoCommand(0, vehicle_id, order_position_move | (<API key> << 16), CMD_MOVE_ORDER);
}
/* static */ bool AIOrder::CopyOrders(VehicleID vehicle_id, VehicleID main_vehicle_id)
{
EnforcePrecondition(false, AIVehicle::IsValidVehicle(vehicle_id));
EnforcePrecondition(false, AIVehicle::IsValidVehicle(main_vehicle_id));
return AIObject::DoCommand(0, vehicle_id | CO_COPY << 30, main_vehicle_id, CMD_CLONE_ORDER);
}
/* static */ bool AIOrder::ShareOrders(VehicleID vehicle_id, VehicleID main_vehicle_id)
{
EnforcePrecondition(false, AIVehicle::IsValidVehicle(vehicle_id));
EnforcePrecondition(false, AIVehicle::IsValidVehicle(main_vehicle_id));
return AIObject::DoCommand(0, vehicle_id | CO_SHARE << 30, main_vehicle_id, CMD_CLONE_ORDER);
}
/* static */ bool AIOrder::UnshareOrders(VehicleID vehicle_id)
{
EnforcePrecondition(false, AIVehicle::IsValidVehicle(vehicle_id));
return AIObject::DoCommand(0, vehicle_id | CO_UNSHARE << 30, 0, CMD_CLONE_ORDER);
} |
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "imp.h"
#include <helper/binarybuffer.h>
#include <target/algorithm.h>
#include <target/armv7m.h>
/* Regarding performance:
*
* Short story - it might be best to leave the performance at
* current levels.
*
* You may see a jump in speed if you change to using
* 32bit words for the block programming.
*
* Its a shame you cannot use the double word as its
* even faster - but you require external VPP for that mode.
*
* Having said all that 16bit writes give us the widest vdd
* operating range, so may be worth adding a note to that effect.
*
*/
/* Erase time can be as high as 1000ms, 10x this and it's toast... */
#define FLASH_ERASE_TIMEOUT 10000
#define FLASH_WRITE_TIMEOUT 5
#define STM32_FLASH_BASE 0x40023c00
#define STM32_FLASH_ACR 0x40023c00
#define STM32_FLASH_KEYR 0x40023c04
#define STM32_FLASH_OPTKEYR 0x40023c08
#define STM32_FLASH_SR 0x40023c0C
#define STM32_FLASH_CR 0x40023c10
#define STM32_FLASH_OPTCR 0x40023c14
#define STM32_FLASH_OPTCR1 0x40023c18
/* FLASH_CR register bits */
#define FLASH_PG (1 << 0)
#define FLASH_SER (1 << 1)
#define FLASH_MER (1 << 2)
#define FLASH_MER1 (1 << 15)
#define FLASH_STRT (1 << 16)
#define FLASH_PSIZE_8 (0 << 8)
#define FLASH_PSIZE_16 (1 << 8)
#define FLASH_PSIZE_32 (2 << 8)
#define FLASH_PSIZE_64 (3 << 8)
#define FLASH_SNB(a) ((a) << 3)
#define FLASH_LOCK (1 << 31)
/* FLASH_SR register bits */
#define FLASH_BSY (1 << 16)
#define FLASH_PGSERR (1 << 7) /* Programming sequence error */
#define FLASH_PGPERR (1 << 6) /* Programming parallelism error */
#define FLASH_PGAERR (1 << 5) /* Programming alignment error */
#define FLASH_WRPERR (1 << 4) /* Write protection error */
#define FLASH_OPERR (1 << 1) /* Operation error */
#define FLASH_ERROR (FLASH_PGSERR | FLASH_PGPERR | FLASH_PGAERR | FLASH_WRPERR | FLASH_OPERR)
/* STM32_FLASH_OPTCR register bits */
#define OPT_LOCK (1 << 0)
#define OPT_START (1 << 1)
/* STM32_FLASH_OBR bit definitions (reading) */
#define OPT_ERROR 0
#define OPT_READOUT 1
#define OPT_RDWDGSW 2
#define OPT_RDRSTSTOP 3
#define OPT_RDRSTSTDBY 4
#define OPT_BFB2 5 /* dual flash bank only */
/* register unlock keys */
#define KEY1 0x45670123
#define KEY2 0xCDEF89AB
/* option register unlock key */
#define OPTKEY1 0x08192A3B
#define OPTKEY2 0x4C5D6E7F
struct stm32x_options {
uint8_t RDP;
uint8_t user_options;
uint32_t protection;
};
struct stm32x_flash_bank {
struct stm32x_options option_bytes;
int probed;
bool has_large_mem; /* stm32f42x/stm32f43x family */
uint32_t user_bank_size;
};
/* flash bank stm32x <base> <size> 0 0 <target#>
*/
<API key>(<API key>)
{
struct stm32x_flash_bank *stm32x_info;
if (CMD_ARGC < 6)
return <API key>;
stm32x_info = malloc(sizeof(struct stm32x_flash_bank));
bank->driver_priv = stm32x_info;
stm32x_info->probed = 0;
stm32x_info->user_bank_size = bank->size;
return ERROR_OK;
}
static inline int <API key>(struct flash_bank *bank, uint32_t reg)
{
return reg;
}
static inline int <API key>(struct flash_bank *bank, uint32_t *status)
{
struct target *target = bank->target;
return target_read_u32(target, <API key>(bank, STM32_FLASH_SR), status);
}
static int <API key>(struct flash_bank *bank, int timeout)
{
struct target *target = bank->target;
uint32_t status;
int retval = ERROR_OK;
/* wait for busy to clear */
for (;;) {
retval = <API key>(bank, &status);
if (retval != ERROR_OK)
return retval;
LOG_DEBUG("status: 0x%" PRIx32 "", status);
if ((status & FLASH_BSY) == 0)
break;
if (timeout
LOG_ERROR("timed out waiting for flash");
return ERROR_FAIL;
}
alive_sleep(1);
}
if (status & FLASH_WRPERR) {
LOG_ERROR("stm32x device protected");
retval = ERROR_FAIL;
}
/* Clear but report errors */
if (status & FLASH_ERROR) {
/* If this operation fails, we ignore it and report the original
* retval
*/
target_write_u32(target, <API key>(bank, STM32_FLASH_SR),
status & FLASH_ERROR);
}
return retval;
}
static int stm32x_unlock_reg(struct target *target)
{
uint32_t ctrl;
/* first check if not already unlocked
* otherwise writing on STM32_FLASH_KEYR will fail
*/
int retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
if (retval != ERROR_OK)
return retval;
if ((ctrl & FLASH_LOCK) == 0)
return ERROR_OK;
/* unlock flash registers */
retval = target_write_u32(target, STM32_FLASH_KEYR, KEY1);
if (retval != ERROR_OK)
return retval;
retval = target_write_u32(target, STM32_FLASH_KEYR, KEY2);
if (retval != ERROR_OK)
return retval;
retval = target_read_u32(target, STM32_FLASH_CR, &ctrl);
if (retval != ERROR_OK)
return retval;
if (ctrl & FLASH_LOCK) {
LOG_ERROR("flash not unlocked STM32_FLASH_CR: %x", ctrl);
return <API key>;
}
return ERROR_OK;
}
static int <API key>(struct target *target)
{
uint32_t ctrl;
int retval = target_read_u32(target, STM32_FLASH_OPTCR, &ctrl);
if (retval != ERROR_OK)
return retval;
if ((ctrl & OPT_LOCK) == 0)
return ERROR_OK;
/* unlock option registers */
retval = target_write_u32(target, STM32_FLASH_OPTKEYR, OPTKEY1);
if (retval != ERROR_OK)
return retval;
retval = target_write_u32(target, STM32_FLASH_OPTKEYR, OPTKEY2);
if (retval != ERROR_OK)
return retval;
retval = target_read_u32(target, STM32_FLASH_OPTCR, &ctrl);
if (retval != ERROR_OK)
return retval;
if (ctrl & OPT_LOCK) {
LOG_ERROR("options not unlocked STM32_FLASH_OPTCR: %x", ctrl);
return <API key>;
}
return ERROR_OK;
}
static int stm32x_read_options(struct flash_bank *bank)
{
uint32_t optiondata;
struct stm32x_flash_bank *stm32x_info = NULL;
struct target *target = bank->target;
stm32x_info = bank->driver_priv;
/* read current option bytes */
int retval = target_read_u32(target, STM32_FLASH_OPTCR, &optiondata);
if (retval != ERROR_OK)
return retval;
stm32x_info->option_bytes.user_options = optiondata & 0xec;
stm32x_info->option_bytes.RDP = (optiondata >> 8) & 0xff;
stm32x_info->option_bytes.protection = (optiondata >> 16) & 0xfff;
if (stm32x_info->has_large_mem) {
retval = target_read_u32(target, STM32_FLASH_OPTCR1, &optiondata);
if (retval != ERROR_OK)
return retval;
/* append protection bits */
stm32x_info->option_bytes.protection |= (optiondata >> 4) & 0x00fff000;
}
if (stm32x_info->option_bytes.RDP != 0xAA)
LOG_INFO("Device Security Bit Set");
return ERROR_OK;
}
static int <API key>(struct flash_bank *bank)
{
struct stm32x_flash_bank *stm32x_info = NULL;
struct target *target = bank->target;
uint32_t optiondata;
stm32x_info = bank->driver_priv;
int retval = <API key>(target);
if (retval != ERROR_OK)
return retval;
/* rebuild option data */
optiondata = stm32x_info->option_bytes.user_options;
buf_set_u32(&optiondata, 8, 8, stm32x_info->option_bytes.RDP);
buf_set_u32(&optiondata, 16, 12, stm32x_info->option_bytes.protection);
/* program options */
retval = target_write_u32(target, STM32_FLASH_OPTCR, optiondata);
if (retval != ERROR_OK)
return retval;
if (stm32x_info->has_large_mem) {
uint32_t optiondata2 = 0;
buf_set_u32(&optiondata2, 16, 12, stm32x_info->option_bytes.protection >> 12);
retval = target_write_u32(target, STM32_FLASH_OPTCR1, optiondata2);
if (retval != ERROR_OK)
return retval;
}
/* start programming cycle */
retval = target_write_u32(target, STM32_FLASH_OPTCR, optiondata | OPT_START);
if (retval != ERROR_OK)
return retval;
/* wait for completion */
retval = <API key>(bank, FLASH_ERASE_TIMEOUT);
if (retval != ERROR_OK)
return retval;
/* relock registers */
retval = target_write_u32(target, STM32_FLASH_OPTCR, OPT_LOCK);
if (retval != ERROR_OK)
return retval;
return ERROR_OK;
}
static int <API key>(struct flash_bank *bank)
{
struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
/* read write protection settings */
int retval = stm32x_read_options(bank);
if (retval != ERROR_OK) {
LOG_DEBUG("unable to read option bytes");
return retval;
}
for (int i = 0; i < bank->num_sectors; i++) {
if (stm32x_info->option_bytes.protection & (1 << i))
bank->sectors[i].is_protected = 0;
else
bank->sectors[i].is_protected = 1;
}
return ERROR_OK;
}
static int stm32x_erase(struct flash_bank *bank, int first, int last)
{
struct target *target = bank->target;
int i;
if (bank->target->state != TARGET_HALTED) {
LOG_ERROR("Target not halted");
return <API key>;
}
int retval;
retval = stm32x_unlock_reg(target);
if (retval != ERROR_OK)
return retval;
/*
Sector Erase
To erase a sector, follow the procedure below:
1. Check that no Flash memory operation is ongoing by checking the BSY bit in the
FLASH_SR register
2. Set the SER bit and select the sector (out of the 12 sectors in the main memory block)
you wish to erase (SNB) in the FLASH_CR register
3. Set the STRT bit in the FLASH_CR register
4. Wait for the BSY bit to be cleared
*/
for (i = first; i <= last; i++) {
retval = target_write_u32(target,
<API key>(bank, STM32_FLASH_CR), FLASH_SER | FLASH_SNB(i) | FLASH_STRT);
if (retval != ERROR_OK)
return retval;
retval = <API key>(bank, FLASH_ERASE_TIMEOUT);
if (retval != ERROR_OK)
return retval;
bank->sectors[i].is_erased = 1;
}
retval = target_write_u32(target, <API key>(bank, STM32_FLASH_CR), FLASH_LOCK);
if (retval != ERROR_OK)
return retval;
return ERROR_OK;
}
static int stm32x_protect(struct flash_bank *bank, int set, int first, int last)
{
struct target *target = bank->target;
struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
if (target->state != TARGET_HALTED) {
LOG_ERROR("Target not halted");
return <API key>;
}
/* read protection settings */
int retval = stm32x_read_options(bank);
if (retval != ERROR_OK) {
LOG_DEBUG("unable to read option bytes");
return retval;
}
for (int i = first; i <= last; i++) {
if (set)
stm32x_info->option_bytes.protection &= ~(1 << i);
else
stm32x_info->option_bytes.protection |= (1 << i);
}
retval = <API key>(bank);
if (retval != ERROR_OK)
return retval;
return ERROR_OK;
}
static int stm32x_write_block(struct flash_bank *bank, uint8_t *buffer,
uint32_t offset, uint32_t count)
{
struct target *target = bank->target;
uint32_t buffer_size = 16384;
struct working_area *write_algorithm;
struct working_area *source;
uint32_t address = bank->base + offset;
struct reg_param reg_params[5];
struct armv7m_algorithm armv7m_info;
int retval = ERROR_OK;
/* see contrib/loaders/flash/stm32f2x.S for src */
static const uint8_t <API key>[] = {
/* wait_fifo: */
0xD0, 0xF8, 0x00, 0x80, /* ldr r8, [r0, #0] */
0xB8, 0xF1, 0x00, 0x0F, /* cmp r8, #0 */
0x1A, 0xD0, /* beq exit */
0x47, 0x68, /* ldr r7, [r0, #4] */
0x47, 0x45, /* cmp r7, r8 */
0xF7, 0xD0, /* beq wait_fifo */
0xDF, 0xF8, 0x30, 0x60, /* ldr r6, STM32_PROG16 */
0x26, 0x61, /* str r6, [r4, #<API key>] */
0x37, 0xF8, 0x02, 0x6B, /* ldrh r6, [r7], #0x02 */
0x22, 0xF8, 0x02, 0x6B, /* strh r6, [r2], #0x02 */
/* busy: */
0xE6, 0x68, /* ldr r6, [r4, #<API key>] */
0x16, 0xF4, 0x80, 0x3F, /* tst r6, #0x10000 */
0xFB, 0xD1, /* bne busy */
0x16, 0xF0, 0xF0, 0x0F, /* tst r6, #0xf0 */
0x07, 0xD1, /* bne error */
0x8F, 0x42, /* cmp r7, r1 */
0x28, 0xBF, /* it cs */
0x00, 0xF1, 0x08, 0x07, /* addcs r7, r0, #8 */
0x47, 0x60, /* str r7, [r0, #4] */
0x01, 0x3B, /* subs r3, r3, #1 */
0x13, 0xB1, /* cbz r3, exit */
0xE1, 0xE7, /* b wait_fifo */
/* error: */
0x00, 0x21, /* movs r1, #0 */
0x41, 0x60, /* str r1, [r0, #4] */
/* exit: */
0x30, 0x46, /* mov r0, r6 */
0x00, 0xBE, /* bkpt #0x00 */
/* <STM32_PROG16>: */
0x01, 0x01, 0x00, 0x00, /* .word 0x00000101 */
};
if (<API key>(target, sizeof(<API key>),
&write_algorithm) != ERROR_OK) {
LOG_WARNING("no working area available, can't do block memory writes");
return <API key>;
};
retval = target_write_buffer(target, write_algorithm->address,
sizeof(<API key>),
(uint8_t *)<API key>);
if (retval != ERROR_OK)
return retval;
/* memory buffer */
while (<API key>(target, buffer_size, &source) != ERROR_OK) {
buffer_size /= 2;
if (buffer_size <= 256) {
/* we already allocated the writing code, but failed to get a
* buffer, free the algorithm */
<API key>(target, write_algorithm);
LOG_WARNING("no large enough working area available, can't do block memory writes");
return <API key>;
}
};
armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
armv7m_info.core_mode = ARM_MODE_THREAD;
init_reg_param(®_params[0], "r0", 32, PARAM_IN_OUT); /* buffer start, status (out) */
init_reg_param(®_params[1], "r1", 32, PARAM_OUT); /* buffer end */
init_reg_param(®_params[2], "r2", 32, PARAM_OUT); /* target address */
init_reg_param(®_params[3], "r3", 32, PARAM_OUT); /* count (halfword-16bit) */
init_reg_param(®_params[4], "r4", 32, PARAM_OUT); /* flash base */
buf_set_u32(reg_params[0].value, 0, 32, source->address);
buf_set_u32(reg_params[1].value, 0, 32, source->address + source->size);
buf_set_u32(reg_params[2].value, 0, 32, address);
buf_set_u32(reg_params[3].value, 0, 32, count);
buf_set_u32(reg_params[4].value, 0, 32, STM32_FLASH_BASE);
retval = <API key>(target, buffer, count, 2,
0, NULL,
5, reg_params,
source->address, source->size,
write_algorithm->address, 0,
&armv7m_info);
if (retval == <API key>) {
LOG_ERROR("error executing stm32x flash write algorithm");
uint32_t error = buf_get_u32(reg_params[0].value, 0, 32) & FLASH_ERROR;
if (error & FLASH_WRPERR)
LOG_ERROR("flash memory write protected");
if (error != 0) {
LOG_ERROR("flash write failed = %08x", error);
/* Clear but report errors */
target_write_u32(target, STM32_FLASH_SR, error);
retval = ERROR_FAIL;
}
}
<API key>(target, source);
<API key>(target, write_algorithm);
destroy_reg_param(®_params[0]);
destroy_reg_param(®_params[1]);
destroy_reg_param(®_params[2]);
destroy_reg_param(®_params[3]);
destroy_reg_param(®_params[4]);
return retval;
}
static int stm32x_write(struct flash_bank *bank, uint8_t *buffer,
uint32_t offset, uint32_t count)
{
struct target *target = bank->target;
uint32_t words_remaining = (count / 2);
uint32_t bytes_remaining = (count & 0x00000001);
uint32_t address = bank->base + offset;
uint32_t bytes_written = 0;
int retval;
if (bank->target->state != TARGET_HALTED) {
LOG_ERROR("Target not halted");
return <API key>;
}
if (offset & 0x1) {
LOG_WARNING("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
return <API key>;
}
retval = stm32x_unlock_reg(target);
if (retval != ERROR_OK)
return retval;
/* multiple half words (2-byte) to be programmed? */
if (words_remaining > 0) {
/* try using a block write */
retval = stm32x_write_block(bank, buffer, offset, words_remaining);
if (retval != ERROR_OK) {
if (retval == <API key>) {
/* if block write failed (no sufficient working area),
* we use normal (slow) single dword accesses */
LOG_WARNING("couldn't use block writes, falling back to single memory accesses");
}
} else {
buffer += words_remaining * 2;
address += words_remaining * 2;
words_remaining = 0;
}
}
if ((retval != ERROR_OK) && (retval != <API key>))
return retval;
while (words_remaining > 0) {
uint16_t value;
memcpy(&value, buffer + bytes_written, sizeof(uint16_t));
retval = target_write_u32(target, <API key>(bank, STM32_FLASH_CR),
FLASH_PG | FLASH_PSIZE_16);
if (retval != ERROR_OK)
return retval;
retval = target_write_u16(target, address, value);
if (retval != ERROR_OK)
return retval;
retval = <API key>(bank, FLASH_WRITE_TIMEOUT);
if (retval != ERROR_OK)
return retval;
bytes_written += 2;
words_remaining
address += 2;
}
if (bytes_remaining) {
retval = target_write_u32(target, <API key>(bank, STM32_FLASH_CR),
FLASH_PG | FLASH_PSIZE_8);
if (retval != ERROR_OK)
return retval;
retval = target_write_u8(target, address, buffer[bytes_written]);
if (retval != ERROR_OK)
return retval;
retval = <API key>(bank, FLASH_WRITE_TIMEOUT);
if (retval != ERROR_OK)
return retval;
}
return target_write_u32(target, STM32_FLASH_CR, FLASH_LOCK);
}
static void setup_sector(struct flash_bank *bank, int start, int num, int size)
{
for (int i = start; i < (start + num) ; i++) {
assert(i < bank->num_sectors);
bank->sectors[i].offset = bank->size;
bank->sectors[i].size = size;
bank->size += bank->sectors[i].size;
}
}
static int <API key>(struct flash_bank *bank, uint32_t *device_id)
{
/* this checks for a stm32f4x errata issue where a
* stm32f2x DBGMCU_IDCODE is incorrectly returned.
* If the issue is detected target is forced to stm32f4x Rev A.
* Only effects Rev A silicon */
struct target *target = bank->target;
uint32_t cpuid;
/* read stm32 device id register */
int retval = target_read_u32(target, 0xE0042000, device_id);
if (retval != ERROR_OK)
return retval;
if ((*device_id & 0xfff) == 0x411) {
/* read CPUID reg to check core type */
retval = target_read_u32(target, 0xE000ED00, &cpuid);
if (retval != ERROR_OK)
return retval;
/* check for cortex_m4 */
if (((cpuid >> 4) & 0xFFF) == 0xC24) {
*device_id &= ~((0xFFFF << 16) | 0xfff);
*device_id |= (0x1000 << 16) | 0x413;
LOG_INFO("stm32f4x errata detected - fixing incorrect MCU_IDCODE");
}
}
return retval;
}
static int stm32x_probe(struct flash_bank *bank)
{
struct target *target = bank->target;
struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
int i;
uint16_t flash_size_in_kb;
uint16_t <API key>;
uint32_t device_id;
uint32_t base_address = 0x08000000;
stm32x_info->probed = 0;
stm32x_info->has_large_mem = false;
/* read stm32 device id register */
int retval = <API key>(bank, &device_id);
if (retval != ERROR_OK)
return retval;
LOG_INFO("device id = 0x%08" PRIx32 "", device_id);
/* set max flash size depending on family */
switch (device_id & 0xfff) {
case 0x411:
case 0x413:
<API key> = 1024;
break;
case 0x419:
<API key> = 2048;
stm32x_info->has_large_mem = true;
break;
default:
LOG_WARNING("Cannot identify target as a STM32 family.");
return ERROR_FAIL;
}
/* get flash size from target. */
retval = target_read_u16(target, 0x1FFF7A22, &flash_size_in_kb);
/* failed reading flash size or flash size invalid (early silicon),
* default to max target family */
if (retval != ERROR_OK || flash_size_in_kb == 0xffff || flash_size_in_kb == 0) {
LOG_WARNING("STM32 flash size failed, probe inaccurate - assuming %dk flash",
<API key>);
flash_size_in_kb = <API key>;
}
/* if the user sets the size manually then ignore the probed value
* this allows us to work around devices that have a invalid flash size register value */
if (stm32x_info->user_bank_size) {
LOG_INFO("ignoring flash probed value, using configured bank size");
flash_size_in_kb = stm32x_info->user_bank_size / 1024;
}
LOG_INFO("flash size = %dkbytes", flash_size_in_kb);
/* did we assign flash size? */
assert(flash_size_in_kb != 0xffff);
/* calculate numbers of pages */
int num_pages = (flash_size_in_kb / 128) + 4;
/* check for larger 2048 bytes devices */
if (stm32x_info->has_large_mem)
num_pages += 4;
/* check that calculation result makes sense */
assert(num_pages > 0);
if (bank->sectors) {
free(bank->sectors);
bank->sectors = NULL;
}
bank->base = base_address;
bank->num_sectors = num_pages;
bank->sectors = malloc(sizeof(struct flash_sector) * num_pages);
bank->size = 0;
/* fixed memory */
setup_sector(bank, 0, 4, 16 * 1024);
setup_sector(bank, 4, 1, 64 * 1024);
/* dynamic memory */
setup_sector(bank, 4 + 1, MIN(12, num_pages) - 5, 128 * 1024);
if (stm32x_info->has_large_mem) {
/* fixed memory for larger devices */
setup_sector(bank, 12, 4, 16 * 1024);
setup_sector(bank, 16, 1, 64 * 1024);
/* dynamic memory for larger devices */
setup_sector(bank, 16 + 1, num_pages - 5 - 12, 128 * 1024);
}
for (i = 0; i < num_pages; i++) {
bank->sectors[i].is_erased = -1;
bank->sectors[i].is_protected = 0;
}
stm32x_info->probed = 1;
return ERROR_OK;
}
static int stm32x_auto_probe(struct flash_bank *bank)
{
struct stm32x_flash_bank *stm32x_info = bank->driver_priv;
if (stm32x_info->probed)
return ERROR_OK;
return stm32x_probe(bank);
}
static int get_stm32x_info(struct flash_bank *bank, char *buf, int buf_size)
{
uint32_t dbgmcu_idcode;
/* read stm32 device id register */
int retval = <API key>(bank, &dbgmcu_idcode);
if (retval != ERROR_OK)
return retval;
uint16_t device_id = dbgmcu_idcode & 0xfff;
uint16_t rev_id = dbgmcu_idcode >> 16;
const char *device_str;
const char *rev_str = NULL;
switch (device_id) {
case 0x411:
device_str = "STM32F2xx";
switch (rev_id) {
case 0x1000:
rev_str = "A";
break;
case 0x2000:
rev_str = "B";
break;
case 0x1001:
rev_str = "Z";
break;
case 0x2001:
rev_str = "Y";
break;
case 0x2003:
rev_str = "X";
break;
}
break;
case 0x413:
case 0x419:
device_str = "STM32F4xx";
switch (rev_id) {
case 0x1000:
rev_str = "A";
break;
case 0x1001:
rev_str = "Z";
break;
}
break;
default:
snprintf(buf, buf_size, "Cannot identify target as a STM32F2/4\n");
return ERROR_FAIL;
}
if (rev_str != NULL)
snprintf(buf, buf_size, "%s - Rev: %s", device_str, rev_str);
else
snprintf(buf, buf_size, "%s - Rev: unknown (0x%04x)", device_str, rev_id);
return ERROR_OK;
}
COMMAND_HANDLER(<API key>)
{
struct target *target = NULL;
struct stm32x_flash_bank *stm32x_info = NULL;
if (CMD_ARGC < 1)
return <API key>;
struct flash_bank *bank;
int retval = <API key>(<API key>, 0, &bank);
if (ERROR_OK != retval)
return retval;
stm32x_info = bank->driver_priv;
target = bank->target;
if (target->state != TARGET_HALTED) {
LOG_ERROR("Target not halted");
return <API key>;
}
if (stm32x_read_options(bank) != ERROR_OK) {
command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
return ERROR_OK;
}
/* set readout protection */
stm32x_info->option_bytes.RDP = 0;
if (<API key>(bank) != ERROR_OK) {
command_print(CMD_CTX, "%s failed to lock device", bank->driver->name);
return ERROR_OK;
}
command_print(CMD_CTX, "%s locked", bank->driver->name);
return ERROR_OK;
}
COMMAND_HANDLER(<API key>)
{
struct target *target = NULL;
struct stm32x_flash_bank *stm32x_info = NULL;
if (CMD_ARGC < 1)
return <API key>;
struct flash_bank *bank;
int retval = <API key>(<API key>, 0, &bank);
if (ERROR_OK != retval)
return retval;
stm32x_info = bank->driver_priv;
target = bank->target;
if (target->state != TARGET_HALTED) {
LOG_ERROR("Target not halted");
return <API key>;
}
if (stm32x_read_options(bank) != ERROR_OK) {
command_print(CMD_CTX, "%s failed to read options", bank->driver->name);
return ERROR_OK;
}
/* clear readout protection and complementary option bytes
* this will also force a device unlock if set */
stm32x_info->option_bytes.RDP = 0xAA;
if (<API key>(bank) != ERROR_OK) {
command_print(CMD_CTX, "%s failed to unlock device", bank->driver->name);
return ERROR_OK;
}
command_print(CMD_CTX, "%s unlocked.\n"
"INFO: a reset or power cycle is required "
"for the new settings to take effect.", bank->driver->name);
return ERROR_OK;
}
static int stm32x_mass_erase(struct flash_bank *bank)
{
int retval;
struct target *target = bank->target;
struct stm32x_flash_bank *stm32x_info = NULL;
if (target->state != TARGET_HALTED) {
LOG_ERROR("Target not halted");
return <API key>;
}
stm32x_info = bank->driver_priv;
retval = stm32x_unlock_reg(target);
if (retval != ERROR_OK)
return retval;
/* mass erase flash memory */
if (stm32x_info->has_large_mem)
retval = target_write_u32(target, <API key>(bank, STM32_FLASH_CR), FLASH_MER | FLASH_MER1);
else
retval = target_write_u32(target, <API key>(bank, STM32_FLASH_CR), FLASH_MER);
if (retval != ERROR_OK)
return retval;
retval = target_write_u32(target, <API key>(bank, STM32_FLASH_CR),
FLASH_MER | FLASH_STRT);
if (retval != ERROR_OK)
return retval;
retval = <API key>(bank, 30000);
if (retval != ERROR_OK)
return retval;
retval = target_write_u32(target, <API key>(bank, STM32_FLASH_CR), FLASH_LOCK);
if (retval != ERROR_OK)
return retval;
return ERROR_OK;
}
COMMAND_HANDLER(<API key>)
{
int i;
if (CMD_ARGC < 1) {
command_print(CMD_CTX, "stm32x mass_erase <bank>");
return <API key>;
}
struct flash_bank *bank;
int retval = <API key>(<API key>, 0, &bank);
if (ERROR_OK != retval)
return retval;
retval = stm32x_mass_erase(bank);
if (retval == ERROR_OK) {
/* set all sectors as erased */
for (i = 0; i < bank->num_sectors; i++)
bank->sectors[i].is_erased = 1;
command_print(CMD_CTX, "stm32x mass erase complete");
} else {
command_print(CMD_CTX, "stm32x mass erase failed");
}
return retval;
}
static const struct <API key> <API key>[] = {
{
.name = "lock",
.handler = <API key>,
.mode = COMMAND_EXEC,
.usage = "bank_id",
.help = "Lock entire flash device.",
},
{
.name = "unlock",
.handler = <API key>,
.mode = COMMAND_EXEC,
.usage = "bank_id",
.help = "Unlock entire protected flash device.",
},
{
.name = "mass_erase",
.handler = <API key>,
.mode = COMMAND_EXEC,
.usage = "bank_id",
.help = "Erase entire flash device.",
},
<API key>
};
static const struct <API key> <API key>[] = {
{
.name = "stm32f2x",
.mode = COMMAND_ANY,
.help = "stm32f2x flash command group",
.usage = "",
.chain = <API key>,
},
<API key>
};
struct flash_driver stm32f2x_flash = {
.name = "stm32f2x",
.commands = <API key>,
.flash_bank_command = <API key>,
.erase = stm32x_erase,
.protect = stm32x_protect,
.write = stm32x_write,
.read = default_flash_read,
.probe = stm32x_probe,
.auto_probe = stm32x_auto_probe,
.erase_check = <API key>,
.protect_check = <API key>,
.info = get_stm32x_info,
}; |
#!/bin/bash
# TrinityX
# This program is free software; you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# details.
display_var TRIX_CTRL_HOSTNAME
echo_info 'Configuring postfix'
postconf -e "myhostname = $(hostname)"
postconf -e "inet_interfaces = all"
echo_info 'Enabling and starting postfix'
systemctl enable postfix
systemctl restart postfix |
#controls {
padding-left: 1em;
} |
#ifdef WAF_BUILD
#include "gtk2ardour-config.h"
#endif
#include <cstdlib>
#include <cmath>
#include <gtkmm2ext/gtk_ui.h>
#include "ardour/route_group.h"
#include "editor.h"
#include "keyboard.h"
#include "marker.h"
#include "time_axis_view.h"
#include "prompter.h"
#include "gui_thread.h"
#include "editor_group_tabs.h"
#include "route_group_dialog.h"
#include "route_time_axis.h"
#include "editor_routes.h"
#include "editor_route_groups.h"
#include "ardour/route.h"
#include "ardour/session.h"
#include "i18n.h"
using namespace std;
using namespace ARDOUR;
using namespace PBD;
using namespace Gtk;
using Gtkmm2ext::Keyboard;
EditorRouteGroups::EditorRouteGroups (Editor* e)
: EditorComponent (e)
, <API key> (_("No Selection = All Tracks"))
, _in_row_change (false)
, _in_rebuild (false)
{
_model = ListStore::create (_columns);
_display.set_model (_model);
int const columns = 10;
_display.append_column (_("Name"), _columns.text);
_display.append_column (_("G"), _columns.gain);
_display.append_column (_("Rel"), _columns.gain_relative);
_display.append_column (_("M"), _columns.mute);
_display.append_column (_("S"), _columns.solo);
_display.append_column (_("Rec"), _columns.record);
_display.append_column (_("Sel"), _columns.select);
_display.append_column (_("E"), _columns.edits);
_display.append_column (_("A"), _columns.active_state);
_display.append_column (_("Show"), _columns.is_visible);
for (int i = 0; i < columns; ++i) {
_display.get_column (i)->set_data (X_("colnum"), GUINT_TO_POINTER(i));
}
_display.get_column (0)->set_expand (true);
for (int i = 1; i < columns; ++i) {
_display.get_column (i)->set_expand (false);
}
_display.set_headers_visible (true);
/* name is directly editable */
CellRendererText* name_cell = dynamic_cast<CellRendererText*>(_display.<API key> (0));
name_cell->property_editable() = true;
name_cell->signal_edited().connect (sigc::mem_fun (*this, &EditorRouteGroups::name_edit));
/* use checkbox for the active + visible columns */
for (int i = 1; i < columns; ++i) {
CellRendererToggle* active_cell = dynamic_cast <CellRendererToggle*> (_display.<API key> (i));
active_cell-><API key>() = true;
active_cell->property_radio() = false;
}
_model->signal_row_changed().connect (sigc::mem_fun (*this, &EditorRouteGroups::row_change));
/* What signal would you guess was emitted when the rows of your treeview are reordered
by a drag and drop? <API key>? That would be far too easy.
No, signal_row_deleted().
*/
_model->signal_row_deleted().connect (sigc::mem_fun (*this, &EditorRouteGroups::row_deleted));
_display.set_name ("EditGroupList");
_display.get_selection()->set_mode (SELECTION_SINGLE);
_display.set_headers_visible (true);
_display.set_reorderable (true);
_display.set_rules_hint (true);
_display.set_size_request (75, -1);
_scroller.add (_display);
_scroller.set_policy (POLICY_AUTOMATIC, POLICY_AUTOMATIC);
_display.<API key>().connect (sigc::mem_fun(*this, &EditorRouteGroups::button_press_event), false);
HBox* button_box = manage (new HBox());
button_box->set_homogeneous (true);
Button* add_button = manage (new Button ());
Button* remove_button = manage (new Button ());
Widget* w;
w = manage (new Image (Stock::ADD, ICON_SIZE_BUTTON));
w->show();
add_button->add (*w);
w = manage (new Image (Stock::REMOVE, ICON_SIZE_BUTTON));
w->show();
remove_button->add (*w);
add_button->signal_clicked().connect (sigc::hide_return (sigc::mem_fun (*this, &EditorRouteGroups::<API key>)));
remove_button->signal_clicked().connect (sigc::mem_fun (*this, &EditorRouteGroups::remove_selected));
button_box->pack_start (*add_button);
button_box->pack_start (*remove_button);
<API key>.show ();
_display_packer.pack_start (_scroller, true, true);
_display_packer.pack_start (<API key>, false, false);
_display_packer.pack_start (*button_box, false, false);
<API key>.signal_toggled().connect (sigc::mem_fun (*this, &EditorRouteGroups::all_group_toggled));
}
void
EditorRouteGroups::remove_selected ()
{
Glib::RefPtr<TreeSelection> selection = _display.get_selection();
TreeView::Selection::ListHandle_Path rows = selection->get_selected_rows ();
if (rows.empty()) {
return;
}
TreeView::Selection::ListHandle_Path::iterator i = rows.begin();
TreeIter iter;
/* selection mode is single, so rows.begin() is it */
if ((iter = _model->get_iter (*i))) {
RouteGroup* rg = (*iter)[_columns.routegroup];
if (rg) {
_session->remove_route_group (*rg);
}
}
}
void
EditorRouteGroups::button_clicked ()
{
<API key> ();
}
gint
EditorRouteGroups::button_press_event (GdkEventButton* ev)
{
TreeModel::Path path;
TreeIter iter;
RouteGroup* group = 0;
TreeViewColumn* column;
int cellx;
int celly;
bool const p = _display.get_path_at_pos ((int)ev->x, (int)ev->y, path, column, cellx, celly);
if (p) {
iter = _model->get_iter (path);
}
if (iter) {
group = (*iter)[_columns.routegroup];
}
if (Keyboard::<API key> (ev)) {
_editor->_group_tabs->get_menu(group)->popup (1, ev->time);
return true;
}
if (!p) {
return 1;
}
switch (GPOINTER_TO_UINT (column->get_data (X_("colnum")))) {
case 0:
if (Keyboard::is_edit_event (ev)) {
if ((iter = _model->get_iter (path))) {
if ((group = (*iter)[_columns.routegroup]) != 0) {
#ifdef GTKOSX
_display.queue_draw();
#endif
return true;
}
}
}
break;
case 1:
if ((iter = _model->get_iter (path))) {
bool gain = (*iter)[_columns.gain];
(*iter)[_columns.gain] = !gain;
#ifdef GTKOSX
_display.queue_draw();
#endif
return true;
}
break;
case 2:
if ((iter = _model->get_iter (path))) {
bool gain_relative = (*iter)[_columns.gain_relative];
(*iter)[_columns.gain_relative] = !gain_relative;
#ifdef GTKOSX
_display.queue_draw();
#endif
return true;
}
break;
case 3:
if ((iter = _model->get_iter (path))) {
bool mute = (*iter)[_columns.mute];
(*iter)[_columns.mute] = !mute;
#ifdef GTKOSX
_display.queue_draw();
#endif
return true;
}
break;
case 4:
if ((iter = _model->get_iter (path))) {
bool solo = (*iter)[_columns.solo];
(*iter)[_columns.solo] = !solo;
#ifdef GTKOSX
_display.queue_draw();
#endif
return true;
}
break;
case 5:
if ((iter = _model->get_iter (path))) {
bool record = (*iter)[_columns.record];
(*iter)[_columns.record] = !record;
#ifdef GTKOSX
_display.queue_draw();
#endif
return true;
}
break;
case 6:
if ((iter = _model->get_iter (path))) {
bool select = (*iter)[_columns.select];
(*iter)[_columns.select] = !select;
#ifdef GTKOSX
_display.queue_draw();
#endif
return true;
}
break;
case 7:
if ((iter = _model->get_iter (path))) {
bool edits = (*iter)[_columns.edits];
(*iter)[_columns.edits] = !edits;
#ifdef GTKOSX
_display.queue_draw();
#endif
return true;
}
break;
case 8:
if ((iter = _model->get_iter (path))) {
bool active_state = (*iter)[_columns.active_state];
(*iter)[_columns.active_state] = !active_state;
#ifdef GTKOSX
_display.queue_draw();
#endif
return true;
}
break;
case 9:
if ((iter = _model->get_iter (path))) {
bool is_visible = (*iter)[_columns.is_visible];
(*iter)[_columns.is_visible] = !is_visible;
#ifdef GTKOSX
_display.queue_draw();
#endif
return true;
}
break;
default:
break;
}
return false;
}
void
EditorRouteGroups::row_change (const Gtk::TreeModel::Path&, const Gtk::TreeModel::iterator& iter)
{
RouteGroup* group;
if (_in_row_change) {
return;
}
if ((group = (*iter)[_columns.routegroup]) == 0) {
return;
}
PropertyList plist;
plist.add (Properties::name, string ((*iter)[_columns.text]));
bool val = (*iter)[_columns.gain];
plist.add (Properties::gain, val);
val = (*iter)[_columns.gain_relative];
plist.add (Properties::relative, val);
val = (*iter)[_columns.mute];
plist.add (Properties::mute, val);
val = (*iter)[_columns.solo];
plist.add (Properties::solo, val);
val = (*iter)[_columns.record];
plist.add (Properties::recenable, val);
val = (*iter)[_columns.select];
plist.add (Properties::select, val);
val = (*iter)[_columns.edits];
plist.add (Properties::edit, val);
val = (*iter)[_columns.active_state];
plist.add (Properties::route_active, val);
group->set_hidden (!(*iter)[_columns.is_visible], this);
group->apply_changes (plist);
}
void
EditorRouteGroups::add (RouteGroup* group)
{
ENSURE_GUI_THREAD (*this, &EditorRouteGroups::add, group)
bool focus = false;
TreeModel::Row row = *(_model->append());
row[_columns.gain] = group->is_gain ();
row[_columns.gain_relative] = group->is_relative ();
row[_columns.mute] = group->is_mute ();
row[_columns.solo] = group->is_solo ();
row[_columns.record] = group->is_recenable();
row[_columns.select] = group->is_select ();
row[_columns.edits] = group->is_edit ();
row[_columns.active_state] = group->is_route_active ();
row[_columns.is_visible] = !group->is_hidden();
_in_row_change = true;
row[_columns.routegroup] = group;
if (!group->name().empty()) {
row[_columns.text] = group->name();
} else {
row[_columns.text] = _("unnamed");
focus = true;
}
group->PropertyChanged.connect (<API key>, MISSING_INVALIDATOR, ui_bind (&EditorRouteGroups::property_changed, this, group, _1), gui_context());
if (focus) {
TreeViewColumn* col = _display.get_column (0);
CellRendererText* name_cell = dynamic_cast<CellRendererText*>(_display.<API key> (0));
_display.set_cursor (_model->get_path (row), *col, *name_cell, true);
}
_in_row_change = false;
_editor->_group_tabs->set_dirty ();
}
void
EditorRouteGroups::groups_changed ()
{
ENSURE_GUI_THREAD (*this, &EditorRouteGroups::groups_changed);
_in_rebuild = true;
/* just rebuild the while thing */
_model->clear ();
if (_session) {
_session->foreach_route_group (sigc::mem_fun (*this, &EditorRouteGroups::add));
}
_in_rebuild = false;
}
void
EditorRouteGroups::property_changed (RouteGroup* group, const PropertyChange& change)
{
_in_row_change = true;
Gtk::TreeModel::Children children = _model->children();
for(Gtk::TreeModel::Children::iterator iter = children.begin(); iter != children.end(); ++iter) {
if (group == (*iter)[_columns.routegroup]) {
(*iter)[_columns.text] = group->name();
(*iter)[_columns.gain] = group->is_gain ();
(*iter)[_columns.gain_relative] = group->is_relative ();
(*iter)[_columns.mute] = group->is_mute ();
(*iter)[_columns.solo] = group->is_solo ();
(*iter)[_columns.record] = group->is_recenable ();
(*iter)[_columns.select] = group->is_select ();
(*iter)[_columns.edits] = group->is_edit ();
(*iter)[_columns.active_state] = group->is_route_active ();
(*iter)[_columns.is_visible] = !group->is_hidden();
}
}
_in_row_change = false;
if (change.contains (Properties::name) || change.contains (Properties::active)) {
_editor->_group_tabs->set_dirty ();
}
for (TrackViewList::const_iterator i = _editor->get_track_views().begin(); i != _editor->get_track_views().end(); ++i) {
if ((*i)->route_group() == group) {
if (group->is_hidden ()) {
_editor-><API key> (*i);
} else {
_editor->_routes-><API key> (**i);
}
}
}
}
void
EditorRouteGroups::name_edit (const std::string& path, const std::string& new_text)
{
RouteGroup* group;
TreeIter iter;
if ((iter = _model->get_iter (path))) {
if ((group = (*iter)[_columns.routegroup]) == 0) {
return;
}
if (new_text != group->name()) {
group->set_name (new_text);
}
}
}
void
EditorRouteGroups::clear ()
{
_display.set_model (Glib::RefPtr<Gtk::TreeStore> (0));
_model->clear ();
_display.set_model (_model);
}
void
EditorRouteGroups::set_session (Session* s)
{
SessionHandlePtr::set_session (s);
if (_session) {
RouteGroup& arg (_session->all_route_group());
arg.PropertyChanged.connect (<API key>, MISSING_INVALIDATOR, ui_bind (&EditorRouteGroups::all_group_changed, this, _1), gui_context());
_session->route_group_added.connect (<API key>, MISSING_INVALIDATOR, ui_bind (&EditorRouteGroups::add, this, _1), gui_context());
_session->route_group_removed.connect (
<API key>, MISSING_INVALIDATOR, boost::bind (&EditorRouteGroups::groups_changed, this), gui_context()
);
_session-><API key>.connect (
<API key>, MISSING_INVALIDATOR, boost::bind (&EditorRouteGroups::groups_changed, this), gui_context()
);
}
PBD::PropertyChange pc;
pc.add (Properties::select);
pc.add (Properties::active);
all_group_changed (pc);
groups_changed ();
}
void
EditorRouteGroups::<API key> ()
{
RouteList rl;
return _editor->_group_tabs-><API key> (rl);
}
void
EditorRouteGroups::all_group_toggled ()
{
if (_session) {
_session->all_route_group().set_select (<API key>.get_active());
}
}
void
EditorRouteGroups::all_group_changed (const PropertyChange&)
{
if (_session) {
RouteGroup& arg (_session->all_route_group());
<API key>.set_active (arg.is_active() && arg.is_select());
} else {
<API key>.set_active (false);
}
}
/** Called when a model row is deleted, but also when the model is
* reordered by a user drag-and-drop; the latter is what we are
* interested in here.
*/
void
EditorRouteGroups::row_deleted (Gtk::TreeModel::Path const &)
{
if (_in_rebuild) {
/* We need to ignore this in cases where we're not doing a drag-and-drop
re-order.
*/
return;
}
/* Re-write the session's route group list so that the new order is preserved */
list<RouteGroup*> new_list;
Gtk::TreeModel::Children children = _model->children();
for (Gtk::TreeModel::Children::iterator i = children.begin(); i != children.end(); ++i) {
new_list.push_back ((*i)[_columns.routegroup]);
}
_session-><API key> (new_list);
} |
#ifndef _I915_REG_H_
#define _I915_REG_H_
#define _PIPE(pipe, a, b) ((a) + (pipe)*((b)-(a)))
#define _MASKED_BIT_ENABLE(a) (((a) << 16) | (a))
/*
* The Bridge device's PCI config space has information about the
* fb aperture size and the amount of pre-reserved memory.
* This is all handled in the intel-gtt.ko module. i915.ko only
* cares about the vga bit for the vga rbiter.
*/
#define INTEL_GMCH_CTRL 0x52
#define <API key> (1 << 1)
/* PCI config space */
#define HPLLCC 0xc0 /* 855 only */
#define <API key> (0xf << 0)
#define GC_CLOCK_133_200 (0 << 0)
#define GC_CLOCK_100_200 (1 << 0)
#define GC_CLOCK_100_133 (2 << 0)
#define GC_CLOCK_166_250 (3 << 0)
#define GCFGC2 0xda
#define GCFGC 0xf0 /* 915+ only */
#define <API key> (1 << 7)
#define <API key> (0 << 4)
#define <API key> (4 << 4)
#define <API key> (7 << 4)
#define <API key> (0xf << 0)
#define <API key> (8 << 0)
#define <API key> (9 << 0)
#define <API key> (0xb << 0)
#define <API key> (0xc << 0)
#define <API key> (0xf << 0)
#define <API key> (2 << 0)
#define <API key> (3 << 0)
#define <API key> (4 << 0)
#define <API key> (5 << 0)
#define <API key> (7 << 0)
#define <API key> (0 << 0)
#define <API key> (1 << 0)
#define <API key> (3 << 0)
#define <API key> (5 << 0)
#define <API key> (7 << 0)
#define <API key> (0 << 0)
#define <API key> (1 << 0)
#define <API key> (4 << 0)
#define LBB 0xf4
/* Graphics reset regs */
#define I965_GDRST 0xc0 /* PCI config register */
#define ILK_GDSR 0x2ca4 /* MCHBAR offset */
#define GRDOM_FULL (0<<2)
#define GRDOM_RENDER (1<<2)
#define GRDOM_MEDIA (3<<2)
#define GEN6_GDRST 0x941c
#define GEN6_GRDOM_FULL (1 << 0)
#define GEN6_GRDOM_RENDER (1 << 1)
#define GEN6_GRDOM_MEDIA (1 << 2)
#define GEN6_GRDOM_BLT (1 << 3)
/* VGA stuff */
#define VGA_ST01_MDA 0x3ba
#define VGA_ST01_CGA 0x3da
#define VGA_MSR_WRITE 0x3c2
#define VGA_MSR_READ 0x3cc
#define VGA_MSR_MEM_EN (1<<1)
#define VGA_MSR_CGA_MODE (1<<0)
#define VGA_SR_INDEX 0x3c4
#define VGA_SR_DATA 0x3c5
#define VGA_AR_INDEX 0x3c0
#define VGA_AR_VID_EN (1<<5)
#define VGA_AR_DATA_WRITE 0x3c0
#define VGA_AR_DATA_READ 0x3c1
#define VGA_GR_INDEX 0x3ce
#define VGA_GR_DATA 0x3cf
/* GR05 */
#define <API key> 3
#define <API key> 1
/* GR06 */
#define <API key> 0xc
#define <API key> 2
#define <API key> 0
#define <API key> 1
#define <API key> 2
#define <API key> 3
#define VGA_DACMASK 0x3c6
#define VGA_DACRX 0x3c7
#define VGA_DACWX 0x3c8
#define VGA_DACDATA 0x3c9
#define VGA_CR_INDEX_MDA 0x3b4
#define VGA_CR_DATA_MDA 0x3b5
#define VGA_CR_INDEX_CGA 0x3d4
#define VGA_CR_DATA_CGA 0x3d5
/*
* Memory interface instructions used by the kernel
*/
#define MI_INSTR(opcode, flags) (((opcode) << 23) | (flags))
#define MI_NOOP MI_INSTR(0, 0)
#define MI_USER_INTERRUPT MI_INSTR(0x02, 0)
#define MI_WAIT_FOR_EVENT MI_INSTR(0x03, 0)
#define <API key> (1<<16)
#define <API key> (1<<6)
#define <API key> (1<<2)
#define <API key> (1<<1)
#define MI_FLUSH MI_INSTR(0x04, 0)
#define MI_READ_FLUSH (1 << 0)
#define MI_EXE_FLUSH (1 << 1)
#define MI_NO_WRITE_FLUSH (1 << 2)
#define MI_SCENE_COUNT (1 << 3) /* just increment scene count */
#define MI_END_SCENE (1 << 4) /* flush binner and incr scene count */
#define MI_INVALIDATE_ISP (1 << 5) /* invalidate indirect state pointers */
#define MI_BATCH_BUFFER_END MI_INSTR(0x0a, 0)
#define MI_SUSPEND_FLUSH MI_INSTR(0x0b, 0)
#define MI_SUSPEND_FLUSH_EN (1<<0)
#define MI_REPORT_HEAD MI_INSTR(0x07, 0)
#define MI_OVERLAY_FLIP MI_INSTR(0x11,0)
#define MI_OVERLAY_CONTINUE (0x0<<21)
#define MI_OVERLAY_ON (0x1<<21)
#define MI_OVERLAY_OFF (0x2<<21)
#define <API key> MI_INSTR(0x12, 0)
#define MI_DISPLAY_FLIP MI_INSTR(0x14, 2)
#define <API key> MI_INSTR(0x14, 1)
#define <API key>(n) ((n) << 20)
#define MI_SET_CONTEXT MI_INSTR(0x18, 0)
#define MI_MM_SPACE_GTT (1<<8)
#define <API key> (0<<8)
#define <API key> (1<<3)
#define <API key> (1<<2)
#define MI_FORCE_RESTORE (1<<1)
#define MI_RESTORE_INHIBIT (1<<0)
#define MI_STORE_DWORD_IMM MI_INSTR(0x20, 1)
#define MI_MEM_VIRTUAL (1 << 22) /* 965+ only */
#define <API key> MI_INSTR(0x21, 1)
#define <API key> 2
/* Official intel docs are somewhat sloppy concerning <API key>:
* - Always issue a MI_NOOP _before_ the <API key> - otherwise hw
* simply ignores the register load under certain conditions.
* - One can actually load arbitrary many arbitrary registers: Simply issue x
* address/value pairs. Don't overdue it, though, x <= 2^4 must hold!
*/
#define <API key>(x) MI_INSTR(0x22, 2*x-1)
#define MI_FLUSH_DW MI_INSTR(0x26, 1) /* for GEN6 */
#define MI_INVALIDATE_TLB (1<<18)
#define MI_INVALIDATE_BSD (1<<7)
#define MI_BATCH_BUFFER MI_INSTR(0x30, 1)
#define MI_BATCH_NON_SECURE (1)
#define <API key> (1<<8)
#define <API key> MI_INSTR(0x31, 0)
#define MI_SEMAPHORE_MBOX MI_INSTR(0x16, 1) /* gen6+ */
#define <API key> (1<<22)
#define MI_SEMAPHORE_UPDATE (1<<21)
#define <API key> (1<<20)
#define <API key> (1<<18)
/*
* 3D instructions used by the kernel
*/
#define GFX_INSTR(opcode, flags) ((0x3 << 29) | ((opcode) << 24) | (flags))
#define GFX_OP_RASTER_RULES ((0x3<<29)|(0x7<<24))
#define GFX_OP_SCISSOR ((0x3<<29)|(0x1c<<24)|(0x10<<19))
#define SC_UPDATE_SCISSOR (0x1<<1)
#define SC_ENABLE_MASK (0x1<<0)
#define SC_ENABLE (0x1<<0)
#define <API key> ((0x3<<29)|(0x1d<<24)|(0x7<<16))
#define GFX_OP_SCISSOR_INFO ((0x3<<29)|(0x1d<<24)|(0x81<<16)|(0x1))
#define SCI_YMIN_MASK (0xffff<<16)
#define SCI_XMIN_MASK (0xffff<<0)
#define SCI_YMAX_MASK (0xffff<<16)
#define SCI_XMAX_MASK (0xffff<<0)
#define <API key> ((0x3<<29)|(0x1c<<24)|(0x10<<19))
#define GFX_OP_SCISSOR_RECT ((0x3<<29)|(0x1d<<24)|(0x81<<16)|1)
#define GFX_OP_COLOR_FACTOR ((0x3<<29)|(0x1d<<24)|(0x1<<16)|0x0)
#define GFX_OP_STIPPLE ((0x3<<29)|(0x1d<<24)|(0x83<<16))
#define GFX_OP_MAP_INFO ((0x3<<29)|(0x1d<<24)|0x4)
#define <API key> ((0x3<<29)|(0x1d<<24)|(0x85<<16)|0x0)
#define <API key> ((0x3<<29)|(0x1d<<24)|(0x8e<<16)|1)
#define <API key> ((0x3<<29)|(0x1d<<24)|(0x80<<16)|(0x3))
#define <API key> ((0x7900<<16)|0x2)
#define SRC_COPY_BLT_CMD ((2<<29)|(0x43<<22)|4)
#define XY_SRC_COPY_BLT_CMD ((2<<29)|(0x53<<22)|6)
#define <API key> ((2<<29)|(0x71<<22)|5)
#define <API key> (1<<21)
#define <API key> (1<<20)
#define BLT_DEPTH_8 (0<<24)
#define BLT_DEPTH_16_565 (1<<24)
#define BLT_DEPTH_16_1555 (2<<24)
#define BLT_DEPTH_32 (3<<24)
#define BLT_ROP_GXCOPY (0xcc<<16)
#define <API key> (1<<15) /* 965+ only */
#define <API key> (1<<11) /* 965+ only */
#define <API key> ((0x0<<29)|(0x14<<23)|2)
#define ASYNC_FLIP (1<<22)
#define DISPLAY_PLANE_A (0<<20)
#define DISPLAY_PLANE_B (1<<20)
#define GFX_OP_PIPE_CONTROL ((0x3<<29)|(0x3<<27)|(0x2<<24)|2)
#define <API key> (1<<14)
#define <API key> (1<<13)
#define <API key> (1<<12)
#define <API key> (1<<11) /* MBZ on Ironlake */
#define <API key> (1<<10) /* GM45+ only */
#define <API key> (1<<9)
#define PIPE_CONTROL_NOTIFY (1<<8)
#define <API key> (1<<2) /* in addr dword */
#define <API key> (1<<1) /* in addr word, Ironlake+ only */
/*
* Reset registers
*/
#define DEBUG_RESET_I830 0x6070
#define DEBUG_RESET_FULL (1<<7)
#define DEBUG_RESET_RENDER (1<<8)
#define DEBUG_RESET_DISPLAY (1<<9)
/*
* Fence registers
*/
#define FENCE_REG_830_0 0x2000
#define FENCE_REG_945_8 0x3000
#define <API key> 0x07f80000
#define <API key> 12
#define <API key>(size) ((ffs((size) >> 19) - 1) << 8)
#define <API key> 4
#define <API key> (1<<0)
#define <API key> 4
#define <API key> 6
#define <API key> (1<<8)
#define <API key> 0x0ff00000
#define <API key>(size) ((ffs((size) >> 20) - 1) << 8)
#define FENCE_REG_965_0 0x03000
#define <API key> 2
#define <API key> 1
#define <API key> (1<<0)
#define <API key> 0x0400
#define <API key> 0x100000
#define <API key> 32
/*
* Instruction and interrupt control regs
*/
#define PGTBL_ER 0x02024
#define RENDER_RING_BASE 0x02000
#define BSD_RING_BASE 0x04000
#define GEN6_BSD_RING_BASE 0x12000
#define BLT_RING_BASE 0x22000
#define RING_TAIL(base) ((base)+0x30)
#define RING_HEAD(base) ((base)+0x34)
#define RING_START(base) ((base)+0x38)
#define RING_CTL(base) ((base)+0x3c)
#define RING_SYNC_0(base) ((base)+0x40)
#define RING_SYNC_1(base) ((base)+0x44)
#define RING_MAX_IDLE(base) ((base)+0x54)
#define RING_HWS_PGA(base) ((base)+0x80)
#define RING_HWS_PGA_GEN6(base) ((base)+0x2080)
#define RENDER_HWS_PGA_GEN7 (0x04080)
#define BSD_HWS_PGA_GEN7 (0x04180)
#define BLT_HWS_PGA_GEN7 (0x04280)
#define RING_ACTHD(base) ((base)+0x74)
#define RING_NOPID(base) ((base)+0x94)
#define RING_IMR(base) ((base)+0xa8)
#define TAIL_ADDR 0x001FFFF8
#define HEAD_WRAP_COUNT 0xFFE00000
#define HEAD_WRAP_ONE 0x00200000
#define HEAD_ADDR 0x001FFFFC
#define RING_NR_PAGES 0x001FF000
#define RING_REPORT_MASK 0x00000006
#define RING_REPORT_64K 0x00000002
#define RING_REPORT_128K 0x00000004
#define RING_NO_REPORT 0x00000000
#define RING_VALID_MASK 0x00000001
#define RING_VALID 0x00000001
#define RING_INVALID 0x00000000
#define RING_WAIT_I8XX (1<<0) /* gen2, PRBx_HEAD */
#define RING_WAIT (1<<11) /* gen3+, PRBx_CTL */
#define RING_WAIT_SEMAPHORE (1<<10) /* gen6+ */
#if 0
#define PRB0_TAIL 0x02030
#define PRB0_HEAD 0x02034
#define PRB0_START 0x02038
#define PRB0_CTL 0x0203c
#define PRB1_TAIL 0x02040 /* 915+ only */
#define PRB1_HEAD 0x02044 /* 915+ only */
#define PRB1_START 0x02048 /* 915+ only */
#define PRB1_CTL 0x0204c /* 915+ only */
#endif
#define IPEIR_I965 0x02064
#define IPEHR_I965 0x02068
#define INSTDONE_I965 0x0206c
#define INSTPS 0x02070 /* 965+ only */
#define INSTDONE1 0x0207c /* 965+ only */
#define ACTHD_I965 0x02074
#define HWS_PGA 0x02080
#define HWS_ADDRESS_MASK 0xfffff000
#define <API key> 4
#define PWRCTXA 0x2088 /* 965GM+ only */
#define PWRCTX_EN (1<<0)
#define IPEIR 0x02088
#define IPEHR 0x0208c
#define INSTDONE 0x02090
#define NOPID 0x02094
#define HWSTAM 0x02098
#define VCS_INSTDONE 0x1206C
#define VCS_IPEIR 0x12064
#define VCS_IPEHR 0x12068
#define VCS_ACTHD 0x12074
#define BCS_INSTDONE 0x2206C
#define BCS_IPEIR 0x22064
#define BCS_IPEHR 0x22068
#define BCS_ACTHD 0x22074
#define ERROR_GEN6 0x040a0
/* GM45+ chicken bits -- debug workaround bits that may be required
* for various sorts of correct behavior. The top 16 bits of each are
* the enables for writing to the corresponding low bit.
*/
#define _3D_CHICKEN 0x02084
#define <API key> (1 << 10)
#define _3D_CHICKEN2 0x0208c
/* Disables pipelining of read flushes past the SF-WIZ interface.
* Required on all Ironlake steppings according to the B-Spec, but the
* particular danger of not doing so is not specified.
*/
# define <API key> (1 << 14)
#define _3D_CHICKEN3 0x02090
#define MI_MODE 0x0209c
# define VS_TIMER_DISPATCH (1 << 6)
# define MI_FLUSH_ENABLE (1 << 11)
#define GFX_MODE 0x02520
#define GFX_RUN_LIST_ENABLE (1<<15)
#define <API key> (1<<13)
#define <API key> (1<<12)
#define GFX_REPLAY_MODE (1<<11)
#define <API key> (1<<10)
#define GFX_PPGTT_ENABLE (1<<9)
#define SCPD0 0x0209c /* 915+ only */
#define IER 0x020a0
#define IIR 0x020a4
#define IMR 0x020a8
#define ISR 0x020ac
#define <API key> (1<<18)
#define <API key> (1<<17)
#define <API key> (1<<15)
#define <API key> (1<<14) /* p-state */
#define <API key> (1<<13)
#define <API key> (1<<12)
#define <API key> (1<<11)
#define <API key> (1<<10)
#define <API key> (1<<9)
#define <API key> (1<<8)
#define <API key> (1<<7)
#define <API key> (1<<6)
#define <API key> (1<<5)
#define <API key> (1<<4)
#define <API key> (1<<2)
#define I915_USER_INTERRUPT (1<<1)
#define I915_ASLE_INTERRUPT (1<<0)
#define <API key> (1<<25)
#define EIR 0x020b0
#define EMR 0x020b4
#define ESR 0x020b8
#define <API key> (1<<5)
#define GM45_ERROR_MEM_PRIV (1<<4)
#define <API key> (1<<4)
#define GM45_ERROR_CP_PRIV (1<<3)
#define <API key> (1<<1)
#define <API key> (1<<0)
#define INSTPM 0x020c0
#define INSTPM_SELF_EN (1<<12) /* 915GM only */
#define INSTPM_AGPBUSY_DIS (1<<11) /* gen3: when disabled, pending interrupts
will not assert AGPBUSY# and will only
be delivered when out of C3. */
#define ACTHD 0x020c8
#define FW_BLC 0x020d8
#define FW_BLC2 0x020dc
#define FW_BLC_SELF 0x020e0 /* 915+ only */
#define FW_BLC_SELF_EN_MASK (1<<31)
#define <API key> (1<<16) /* 945 only */
#define FW_BLC_SELF_EN (1<<15) /* 945 only */
#define MM_BURST_LENGTH 0x00700000
#define MM_FIFO_WATERMARK 0x0001F000
#define LM_BURST_LENGTH 0x00000700
#define LM_FIFO_WATERMARK 0x0000001F
#define MI_ARB_STATE 0x020e4 /* 915+ only */
#define MI_ARB_MASK_SHIFT 16 /* shift for enable bits */
/* Make render/texture TLB fetches lower priorty than associated data
* fetches. This is not turned on by default
*/
#define <API key> (1 << 15)
/* Isoch request wait on GTT enable (Display A/B/C streams).
* Make isoch requests stall on the TLB update. May cause
* display underruns (test mode only)
*/
#define <API key> (1 << 14)
/* Block grant count for isoch requests when block count is
* set to a finite value.
*/
#define <API key> (3 << 12)
#define <API key> (0 << 12) /* for 3 display planes */
#define <API key> (1 << 12) /* for 2 display planes */
#define <API key> (2 << 12) /* for 1 display plane */
#define <API key> (3 << 12) /* don't use */
/* Enable render writes to complete in C2/C3/C4 power states.
* If this isn't enabled, render writes are prevented in low
* power states. That seems bad to me.
*/
#define <API key> (1 << 11)
/* This acknowledges an async flip immediately instead
* of waiting for 2TLB fetches.
*/
#define <API key> (1 << 10)
/* Enables non-sequential data reads through arbiter
*/
#define <API key> (1 << 9)
/* Disable FSB snooping of cacheable write cycles from binner/render
* command stream
*/
#define <API key> (1 << 8)
/* Arbiter time slice for non-isoch streams */
#define <API key> (7 << 5)
#define MI_ARB_TIME_SLICE_1 (0 << 5)
#define MI_ARB_TIME_SLICE_2 (1 << 5)
#define MI_ARB_TIME_SLICE_4 (2 << 5)
#define MI_ARB_TIME_SLICE_6 (3 << 5)
#define MI_ARB_TIME_SLICE_8 (4 << 5)
#define <API key> (5 << 5)
#define <API key> (6 << 5)
#define <API key> (7 << 5)
/* Low priority grace period page size */
#define <API key> (0 << 4) /* default */
#define <API key> (1 << 4)
/* Disable display A/B trickle feed */
#define <API key> (1 << 2)
/* Set display plane priority */
#define <API key> (0 << 0) /* display A > display B */
#define <API key> (1 << 0) /* display B > display A */
#define CACHE_MODE_0 0x02120 /* 915+ only */
#define CM0_MASK_SHIFT 16
#define CM0_IZ_OPT_DISABLE (1<<6)
#define CM0_ZR_OPT_DISABLE (1<<5)
#define <API key> (1<<4)
#define <API key> (1<<3)
#define <API key> (1<<1)
#define <API key> (1<<0)
#define BB_ADDR 0x02140 /* 8 bytes */
#define GFX_FLSH_CNTL 0x02170 /* 915+ only */
#define ECOSKPD 0x021d0
#define ECO_GATING_CX_ONLY (1<<3)
#define ECO_FLIP_DONE (1<<0)
/* GEN6 interrupt control */
#define GEN6_RENDER_HWSTAM 0x2098
#define GEN6_RENDER_IMR 0x20a8
#define <API key> (1 << 8)
#define <API key> (1 << 7)
#define <API key> (1 << 6)
#define <API key> (1 << 5)
#define <API key> (1 << 4)
#define <API key> (1 << 3)
#define <API key> (1 << 2)
#define <API key> (1 << 1)
#define <API key> (1 << 0)
#define GEN6_BLITTER_HWSTAM 0x22098
#define GEN6_BLITTER_IMR 0x220a8
#define <API key> (1 << 26)
#define <API key> (1 << 25)
#define <API key> (1 << 24)
#define <API key> (1 << 22)
#define <API key> 0x221d0
#define <API key> 16
#define <API key> (1<<3)
#define <API key> 0x12050
#define <API key> (1 << 16)
#define <API key> (1 << 0)
#define <API key> 0
#define <API key> (1 << 3)
#define GEN6_BSD_HWSTAM 0x12098
#define GEN6_BSD_IMR 0x120a8
#define <API key> (1 << 12)
#define GEN6_BSD_RNCID 0x12198
/*
* Framebuffer compression (915+ only)
*/
#define FBC_CFB_BASE 0x03200 /* 4k page aligned */
#define FBC_LL_BASE 0x03204 /* 4k page aligned */
#define FBC_CONTROL 0x03208
#define FBC_CTL_EN (1<<31)
#define FBC_CTL_PERIODIC (1<<30)
#define <API key> (16)
#define <API key> (1<<14)
#define FBC_CTL_C3_IDLE (1<<13)
#define <API key> (5)
#define FBC_CTL_FENCENO (1<<0)
#define FBC_COMMAND 0x0320c
#define FBC_CMD_COMPRESS (1<<0)
#define FBC_STATUS 0x03210
#define <API key> (1<<31)
#define FBC_STAT_COMPRESSED (1<<30)
#define FBC_STAT_MODIFIED (1<<29)
#define <API key> (1<<0)
#define FBC_CONTROL2 0x03214
#define FBC_CTL_FENCE_DBL (0<<4)
#define FBC_CTL_IDLE_IMM (0<<2)
#define FBC_CTL_IDLE_FULL (1<<2)
#define FBC_CTL_IDLE_LINE (2<<2)
#define FBC_CTL_IDLE_DEBUG (3<<2)
#define FBC_CTL_CPU_FENCE (1<<1)
#define FBC_CTL_PLANEA (0<<0)
#define FBC_CTL_PLANEB (1<<0)
#define FBC_FENCE_OFF 0x0321b
#define FBC_TAG 0x03300
#define FBC_LL_SIZE (1536)
/* Framebuffer compression for GM45+ */
#define DPFC_CB_BASE 0x3200
#define DPFC_CONTROL 0x3208
#define DPFC_CTL_EN (1<<31)
#define DPFC_CTL_PLANEA (0<<30)
#define DPFC_CTL_PLANEB (1<<30)
#define DPFC_CTL_FENCE_EN (1<<29)
#define DPFC_SR_EN (1<<10)
#define DPFC_CTL_LIMIT_1X (0<<6)
#define DPFC_CTL_LIMIT_2X (1<<6)
#define DPFC_CTL_LIMIT_4X (2<<6)
#define DPFC_RECOMP_CTL 0x320c
#define <API key> (1<<27)
#define <API key> (16)
#define <API key> (0x07ff0000)
#define <API key> (0)
#define <API key> (0x0000003f)
#define DPFC_STATUS 0x3210
#define <API key> (16)
#define DPFC_INVAL_SEG_MASK (0x07ff0000)
#define DPFC_COMP_SEG_SHIFT (0)
#define DPFC_COMP_SEG_MASK (0x000003ff)
#define DPFC_STATUS2 0x3214
#define DPFC_FENCE_YOFF 0x3218
#define DPFC_CHICKEN 0x3224
#define DPFC_HT_MODIFY (1<<31)
/* Framebuffer compression for Ironlake */
#define ILK_DPFC_CB_BASE 0x43200
#define ILK_DPFC_CONTROL 0x43208
/* The bit 28-8 is reserved */
#define DPFC_RESERVED (0x1FFFFF00)
#define ILK_DPFC_RECOMP_CTL 0x4320c
#define ILK_DPFC_STATUS 0x43210
#define ILK_DPFC_FENCE_YOFF 0x43218
#define ILK_DPFC_CHICKEN 0x43224
#define ILK_FBC_RT_BASE 0x2128
#define ILK_FBC_RT_VALID (1<<0)
#define <API key> 0x42000
#define ILK_FBCQ_DIS (1<<22)
#define ILK_PABSTRETCH_DIS (1<<21)
/*
* Framebuffer compression for Sandybridge
*
* The following two registers are of type GTTMMADR
*/
#define SNB_DPFC_CTL_SA 0x100100
#define <API key> (1<<29)
#define <API key> 0x100104
/*
* GPIO regs
*/
#define GPIOA 0x5010
#define GPIOB 0x5014
#define GPIOC 0x5018
#define GPIOD 0x501c
#define GPIOE 0x5020
#define GPIOF 0x5024
#define GPIOG 0x5028
#define GPIOH 0x502c
# define GPIO_CLOCK_DIR_MASK (1 << 0)
# define GPIO_CLOCK_DIR_IN (0 << 1)
# define GPIO_CLOCK_DIR_OUT (1 << 1)
# define GPIO_CLOCK_VAL_MASK (1 << 2)
# define GPIO_CLOCK_VAL_OUT (1 << 3)
# define GPIO_CLOCK_VAL_IN (1 << 4)
# define <API key> (1 << 5)
# define GPIO_DATA_DIR_MASK (1 << 8)
# define GPIO_DATA_DIR_IN (0 << 9)
# define GPIO_DATA_DIR_OUT (1 << 9)
# define GPIO_DATA_VAL_MASK (1 << 10)
# define GPIO_DATA_VAL_OUT (1 << 11)
# define GPIO_DATA_VAL_IN (1 << 12)
# define <API key> (1 << 13)
#define GMBUS0 0x5100 /* clock/port select */
#define GMBUS_RATE_100KHZ (0<<8)
#define GMBUS_RATE_50KHZ (1<<8)
#define GMBUS_RATE_400KHZ (2<<8) /* reserved on Pineview */
#define GMBUS_RATE_1MHZ (3<<8) /* reserved on Pineview */
#define GMBUS_HOLD_EXT (1<<7) /* 300ns hold time, rsvd on Pineview */
#define GMBUS_PORT_DISABLED 0
#define GMBUS_PORT_SSC 1
#define GMBUS_PORT_VGADDC 2
#define GMBUS_PORT_PANEL 3
#define GMBUS_PORT_DPC 4 /* HDMIC */
#define GMBUS_PORT_DPB 5 /* SDVO, HDMIB */
/* 6 reserved */
#define GMBUS_PORT_DPD 7 /* HDMID */
#define GMBUS_NUM_PORTS 8
#define GMBUS1 0x5104 /* command/status */
#define GMBUS_SW_CLR_INT (1<<31)
#define GMBUS_SW_RDY (1<<30)
#define GMBUS_ENT (1<<29) /* enable timeout */
#define GMBUS_CYCLE_NONE (0<<25)
#define GMBUS_CYCLE_WAIT (1<<25)
#define GMBUS_CYCLE_INDEX (2<<25)
#define GMBUS_CYCLE_STOP (4<<25)
#define <API key> 16
#define <API key> 8
#define <API key> 1
#define GMBUS_SLAVE_READ (1<<0)
#define GMBUS_SLAVE_WRITE (0<<0)
#define GMBUS2 0x5108 /* status */
#define GMBUS_INUSE (1<<15)
#define GMBUS_HW_WAIT_PHASE (1<<14)
#define GMBUS_STALL_TIMEOUT (1<<13)
#define GMBUS_INT (1<<12)
#define GMBUS_HW_RDY (1<<11)
#define GMBUS_SATOER (1<<10)
#define GMBUS_ACTIVE (1<<9)
#define GMBUS3 0x510c /* data buffer bytes 3-0 */
#define GMBUS4 0x5110 /* interrupt mask (Pineview+) */
#define <API key> (1<<4)
#define GMBUS_NAK_EN (1<<3)
#define GMBUS_IDLE_EN (1<<2)
#define GMBUS_HW_WAIT_EN (1<<1)
#define GMBUS_HW_RDY_EN (1<<0)
#define GMBUS5 0x5120 /* byte index */
#define <API key> (1<<31)
/*
* Clock control & power management
*/
#define VGA0 0x6000
#define VGA1 0x6004
#define VGA_PD 0x6010
#define VGA0_PD_P2_DIV_4 (1 << 7)
#define VGA0_PD_P1_DIV_2 (1 << 5)
#define VGA0_PD_P1_SHIFT 0
#define VGA0_PD_P1_MASK (0x1f << 0)
#define VGA1_PD_P2_DIV_4 (1 << 15)
#define VGA1_PD_P1_DIV_2 (1 << 13)
#define VGA1_PD_P1_SHIFT 8
#define VGA1_PD_P1_MASK (0x1f << 8)
#define _DPLL_A 0x06014
#define _DPLL_B 0x06018
#define DPLL(pipe) _PIPE(pipe, _DPLL_A, _DPLL_B)
#define DPLL_VCO_ENABLE (1 << 31)
#define DPLL_DVO_HIGH_SPEED (1 << 30)
#define <API key> (1 << 29)
#define DPLL_VGA_MODE_DIS (1 << 28)
#define <API key> (1 << 26) /* i915 */
#define DPLLB_MODE_LVDS (2 << 26) /* i915 */
#define DPLL_MODE_MASK (3 << 26)
#define <API key> (0 << 24) /* i915 */
#define <API key> (1 << 24) /* i915 */
#define <API key> (0 << 24) /* i915 */
#define <API key> (1 << 24) /* i915 */
#define <API key> 0x03000000 /* i915 */
#define <API key> 0x00ff0000 /* i915 */
#define <API key> 0x00ff8000 /* Pineview */
#define SRX_INDEX 0x3c4
#define SRX_DATA 0x3c5
#define SR01 1
#define SR01_SCREEN_OFF (1<<5)
#define PPCR 0x61204
#define PPCR_ON (1<<0)
#define DVOB 0x61140
#define DVOB_ON (1<<31)
#define DVOC 0x61160
#define DVOC_ON (1<<31)
#define LVDS 0x61180
#define LVDS_ON (1<<31)
/* Scratch pad debug 0 reg:
*/
#define <API key> 0x001f0000
/*
* The i830 generation, in LVDS mode, defines P1 as the bit number set within
* this field (only one bit may be set).
*/
#define <API key> 0x003f0000
#define <API key> 16
#define <API key> 15
/* i830, required in DVO non-gang */
#define PLL_P2_DIVIDE_BY_4 (1 << 23)
#define <API key> (1 << 21) /* i830 */
#define <API key> (0 << 13)
#define <API key> (1 << 13) /* i830 */
#define <API key> (2 << 13) /* SDVO TVCLKIN */
#define <API key> (3 << 13)
#define PLL_REF_INPUT_MASK (3 << 13)
#define <API key> 9
/* Ironlake */
# define <API key> 9
# define <API key> (7 << 9)
# define <API key>(x) (((x)-1) << 9)
# define <API key> 0
# define <API key> 0xff
/*
* Parallel to Serial Load Pulse phase selection.
* Selects the phase for the 10X DPLL clock for the PCIe
* digital display port. The range is 4 to 13; 10 or more
* is just a flip delay. The default is 6
*/
#define <API key> (0xf << <API key>)
#define <API key> (1 << 8)
/*
* SDVO multiplier for 945G/GM. Not used on 965.
*/
#define <API key> 0x000000ff
#define <API key> 4
#define <API key> 0
#define _DPLL_A_MD 0x0601c /* 965+ only */
/*
* UDI pixel divider, controlling how many pixels are stuffed into a packet.
*
* Value is pixels minus 1. Must be set to 1 pixel for SDVO.
*/
#define <API key> 0x3f000000
#define <API key> 24
/* UDI pixel divider for VGA, same as <API key>. */
#define <API key> 0x003f0000
#define <API key> 16
/*
* SDVO/UDI pixel multiplier.
*
* SDVO requires that the bus clock rate be between 1 and 2 Ghz, and the bus
* clock rate is 10 times the DPLL clock. At low resolution/refresh rate
* modes, the bus rate would be below the limits, so SDVO allows for stuffing
* dummy bytes in the datastream at an increased clock rate, with both sides of
* the link knowing how many bytes are fill.
*
* So, for a mode with a dotclock of 65Mhz, we would want to double the clock
* rate to 130Mhz to get a bus rate of 1.30Ghz. The DPLL clock rate would be
* set to 130Mhz, and the SDVO multiplier set to 2x in this register and
* through an SDVO command.
*
* This register field has values of multiplication factor minus 1, with
* a maximum multiplier of 5 for SDVO.
*/
#define <API key> 0x00003f00
#define <API key> 8
/*
* SDVO/UDI pixel multiplier for VGA, same as <API key>.
* This best be set to the default value (3) or the CRT won't work. No,
* I don't entirely understand what this does...
*/
#define <API key> 0x0000003f
#define <API key> 0
#define _DPLL_B_MD 0x06020 /* 965+ only */
#define DPLL_MD(pipe) _PIPE(pipe, _DPLL_A_MD, _DPLL_B_MD)
#define _FPA0 0x06040
#define _FPA1 0x06044
#define _FPB0 0x06048
#define _FPB1 0x0604c
#define FP0(pipe) _PIPE(pipe, _FPA0, _FPB0)
#define FP1(pipe) _PIPE(pipe, _FPA1, _FPB1)
#define FP_N_DIV_MASK 0x003f0000
#define <API key> 0x00ff0000
#define FP_N_DIV_SHIFT 16
#define FP_M1_DIV_MASK 0x00003f00
#define FP_M1_DIV_SHIFT 8
#define FP_M2_DIV_MASK 0x0000003f
#define <API key> 0x000000ff
#define FP_M2_DIV_SHIFT 0
#define DPLL_TEST 0x606c
#define <API key> (0 << 22)
#define <API key> (1 << 22)
#define <API key> (2 << 22)
#define <API key> (3 << 22)
#define DPLLB_TEST_N_BYPASS (1 << 19)
#define DPLLB_TEST_M_BYPASS (1 << 18)
#define <API key> (1 << 16)
#define DPLLA_TEST_N_BYPASS (1 << 3)
#define DPLLA_TEST_M_BYPASS (1 << 2)
#define <API key> (1 << 0)
#define D_STATE 0x6104
#define <API key> (1<<6)
#define DSTATE_PLL_D3_OFF (1<<3)
#define <API key> (1<<1)
#define <API key> (1<<0)
#define DSPCLK_GATE_D 0x6200
# define <API key> (1 << 30) /* 965 */
# define <API key> (1 << 29) /* 965 */
# define <API key> (1 << 28) /* 965 */
# define <API key> (1 << 27) /* 965 */
# define <API key> (1 << 26) /* 965 */
# define <API key> (1 << 25) /* 965 */
# define <API key> (1 << 24) /* 965 */
# define <API key> (1 << 23) /* 915-945 */
# define <API key> (1 << 22) /* 915-945 */
# define <API key> (1 << 21) /* 915-945 */
# define <API key> (1 << 20) /* 915-945 */
# define <API key> (1 << 19) /* 915-945 */
# define <API key> (1 << 18) /* 915-945 */
# define <API key> (1 << 17) /* 915-945 */
# define <API key> (1 << 16) /* 915-945 */
# define <API key> (1 << 15) /* 915-945 */
# define <API key> (1 << 14) /* 915-945 */
# define <API key> (1 << 13) /* 915-945 */
# define <API key> (1 << 12) /* 915-945 */
# define <API key> (1 << 11)
# define <API key> (1 << 10)
# define <API key> (1 << 9)
# define <API key> (1 << 8)
# define <API key> (1 << 7) /* 915+: reserved */
# define <API key> (1 << 6) /* 830-865 */
# define <API key> (1 << 6) /* 915-945 */
# define <API key> (1 << 5)
# define <API key> (1 << 4)
/**
* This bit must be set on the 830 to prevent hangs when turning off the
* overlay scaler.
*/
# define <API key> (1 << 3)
# define <API key> (1 << 2)
# define <API key> (1 << 1)
# define <API key> (1 << 0) /* 830 */
# define <API key> (1 << 0) /* 845,865 */
#define RENCLK_GATE_D1 0x6204
# define <API key> (1 << 13) /* 945GM only */
# define <API key> (1 << 12) /* 945GM only */
# define <API key> (1 << 11)
# define <API key> (1 << 10)
# define <API key> (1 << 9)
# define <API key> (1 << 8)
# define <API key> (1 << 7)
# define <API key> (1 << 6)
# define <API key> (1 << 5)
/** This bit must be unset on 855,865 */
# define <API key> (1 << 4)
# define <API key> (1 << 3)
# define <API key> (1 << 2)
# define <API key> (1 << 1)
/** This bit must be set on 855,865. */
# define <API key> (1 << 0)
# define <API key> (1 << 16)
# define <API key> (1 << 15)
# define <API key> (1 << 14)
# define <API key> (1 << 13)
# define <API key> (1 << 12)
# define <API key> (1 << 11)
# define <API key> (1 << 10)
# define <API key> (1 << 9)
# define <API key> (1 << 8)
# define <API key> (1 << 7)
# define <API key> (1 << 6)
# define <API key> (1 << 5)
# define <API key> (1 << 4)
# define <API key> (1 << 3)
# define <API key> (1 << 2)
# define <API key> (1 << 1)
# define <API key> (1 << 0)
# define <API key> (1 << 30)
/** This bit must always be set on 965G/965GM */
# define <API key> (1 << 29)
# define <API key> (1 << 28)
# define <API key> (1 << 27)
# define <API key> (1 << 26)
# define <API key> (1 << 25)
# define <API key> (1 << 24)
/** This bit must always be set on 965G */
# define <API key> (1 << 23)
# define <API key> (1 << 22)
# define <API key> (1 << 21)
# define <API key> (1 << 20)
# define <API key> (1 << 19)
# define <API key> (1 << 17)
# define <API key> (1 << 16)
# define <API key> (1 << 15)
# define <API key> (1 << 14)
# define <API key> (1 << 13)
# define <API key> (1 << 12)
# define <API key> (1 << 11)
# define <API key> (1 << 6)
# define <API key> (1 << 5)
# define <API key> (1 << 4)
# define <API key> (1 << 3)
# define <API key> (1 << 2)
# define <API key> (1 << 1)
# define <API key> (1 << 0)
#define RENCLK_GATE_D2 0x6208
#define <API key> (1 << 9)
#define <API key> (1 << 7)
#define <API key> (1 << 6)
#define RAMCLK_GATE_D 0x6210 /* CRL only */
#define DEUC 0x6214 /* CRL only */
/*
* Palette regs
*/
#define _PALETTE_A 0x0a000
#define _PALETTE_B 0x0a800
#define PALETTE(pipe) _PIPE(pipe, _PALETTE_A, _PALETTE_B)
/* MCH MMIO space */
/*
* MCHBAR mirror.
*
* This mirrors the MCHBAR MMIO space whose location is determined by
* device 0 function 0's pci config register 0x44 or 0x48 and matches it in
* every way. It is not accessible from the CP register read instructions.
*
*/
#define MCHBAR_MIRROR_BASE 0x10000
#define <API key> 0x140000
/** 915-945 and GM965 MCH register controlling DRAM channel access */
#define DCC 0x10200
#define <API key> (0 << 0)
#define <API key> (1 << 0)
#define <API key> (2 << 0)
#define <API key> (3 << 0)
#define <API key> (1 << 10)
#define <API key> (1 << 9)
/** Pineview MCH register contains DDR3 setting */
#define CSHRDDR3CTL 0x101a8
#define CSHRDDR3CTL_DDR3 (1 << 2)
/** 965 MCH register controlling DRAM channel configuration */
#define C0DRB3 0x10206
#define C1DRB3 0x10606
/* Clocking configuration register */
#define CLKCFG 0x10c00
#define CLKCFG_FSB_400 (5 << 0) /* hrawclk 100 */
#define CLKCFG_FSB_533 (1 << 0) /* hrawclk 133 */
#define CLKCFG_FSB_667 (3 << 0) /* hrawclk 166 */
#define CLKCFG_FSB_800 (2 << 0) /* hrawclk 200 */
#define CLKCFG_FSB_1067 (6 << 0) /* hrawclk 266 */
#define CLKCFG_FSB_1333 (7 << 0) /* hrawclk 333 */
/* Note, below two are guess */
#define CLKCFG_FSB_1600 (4 << 0) /* hrawclk 400 */
#define CLKCFG_FSB_1600_ALT (0 << 0) /* hrawclk 400 */
#define CLKCFG_FSB_MASK (7 << 0)
#define CLKCFG_MEM_533 (1 << 4)
#define CLKCFG_MEM_667 (2 << 4)
#define CLKCFG_MEM_800 (3 << 4)
#define CLKCFG_MEM_MASK (7 << 4)
#define TSC1 0x11001
#define TSE (1<<0)
#define TR1 0x11006
#define TSFS 0x11020
#define TSFS_SLOPE_MASK 0x0000ff00
#define TSFS_SLOPE_SHIFT 8
#define TSFS_INTR_MASK 0x000000ff
#define CRSTANDVID 0x11100
#define PXVFREQ_BASE 0x11110 /* P[0-15]VIDFREQ (0x1114c) (Ironlake) */
#define PXVFREQ_PX_MASK 0x7f000000
#define PXVFREQ_PX_SHIFT 24
#define VIDFREQ_BASE 0x11110
#define VIDFREQ1 0x11110 /* VIDFREQ1-4 (0x1111c) (Cantiga) */
#define VIDFREQ2 0x11114
#define VIDFREQ3 0x11118
#define VIDFREQ4 0x1111c
#define VIDFREQ_P0_MASK 0x1f000000
#define VIDFREQ_P0_SHIFT 24
#define <API key> 0x00f00000
#define <API key> 20
#define <API key> 0x000f0000
#define <API key> 16
#define VIDFREQ_P1_MASK 0x00001f00
#define VIDFREQ_P1_SHIFT 8
#define <API key> 0x000000f0
#define <API key> 4
#define <API key> 0x0000000f
#define INTTOEXT_BASE_ILK 0x11300
#define INTTOEXT_BASE 0x11120 /* INTTOEXT1-8 (0x1113c) */
#define INTTOEXT_MAP3_SHIFT 24
#define INTTOEXT_MAP3_MASK (0x1f << INTTOEXT_MAP3_SHIFT)
#define INTTOEXT_MAP2_SHIFT 16
#define INTTOEXT_MAP2_MASK (0x1f << INTTOEXT_MAP2_SHIFT)
#define INTTOEXT_MAP1_SHIFT 8
#define INTTOEXT_MAP1_MASK (0x1f << INTTOEXT_MAP1_SHIFT)
#define INTTOEXT_MAP0_SHIFT 0
#define INTTOEXT_MAP0_MASK (0x1f << INTTOEXT_MAP0_SHIFT)
#define MEMSWCTL 0x11170 /* Ironlake only */
#define MEMCTL_CMD_MASK 0xe000
#define MEMCTL_CMD_SHIFT 13
#define MEMCTL_CMD_RCLK_OFF 0
#define MEMCTL_CMD_RCLK_ON 1
#define MEMCTL_CMD_CHFREQ 2
#define MEMCTL_CMD_CHVID 3
#define MEMCTL_CMD_VMMOFF 4
#define MEMCTL_CMD_VMMON 5
#define MEMCTL_CMD_STS (1<<12) /* write 1 triggers command, clears
when command complete */
#define MEMCTL_FREQ_MASK 0x0f00 /* jitter, from 0-15 */
#define MEMCTL_FREQ_SHIFT 8
#define MEMCTL_SFCAVM (1<<7)
#define MEMCTL_TGT_VID_MASK 0x007f
#define MEMIHYST 0x1117c
#define MEMINTREN 0x11180 /* 16 bits */
#define MEMINT_RSEXIT_EN (1<<8)
#define MEMINT_CX_SUPR_EN (1<<7)
#define MEMINT_CONT_BUSY_EN (1<<6)
#define MEMINT_AVG_BUSY_EN (1<<5)
#define MEMINT_EVAL_CHG_EN (1<<4)
#define MEMINT_MON_IDLE_EN (1<<3)
#define MEMINT_UP_EVAL_EN (1<<2)
#define MEMINT_DOWN_EVAL_EN (1<<1)
#define MEMINT_SW_CMD_EN (1<<0)
#define MEMINTRSTR 0x11182 /* 16 bits */
#define MEM_RSEXIT_MASK 0xc000
#define MEM_RSEXIT_SHIFT 14
#define MEM_CONT_BUSY_MASK 0x3000
#define MEM_CONT_BUSY_SHIFT 12
#define MEM_AVG_BUSY_MASK 0x0c00
#define MEM_AVG_BUSY_SHIFT 10
#define MEM_EVAL_CHG_MASK 0x0300
#define MEM_EVAL_BUSY_SHIFT 8
#define MEM_MON_IDLE_MASK 0x00c0
#define MEM_MON_IDLE_SHIFT 6
#define MEM_UP_EVAL_MASK 0x0030
#define MEM_UP_EVAL_SHIFT 4
#define MEM_DOWN_EVAL_MASK 0x000c
#define MEM_DOWN_EVAL_SHIFT 2
#define MEM_SW_CMD_MASK 0x0003
#define MEM_INT_STEER_GFX 0
#define MEM_INT_STEER_CMR 1
#define MEM_INT_STEER_SMI 2
#define MEM_INT_STEER_SCI 3
#define MEMINTRSTS 0x11184
#define MEMINT_RSEXIT (1<<7)
#define MEMINT_CONT_BUSY (1<<6)
#define MEMINT_AVG_BUSY (1<<5)
#define MEMINT_EVAL_CHG (1<<4)
#define MEMINT_MON_IDLE (1<<3)
#define MEMINT_UP_EVAL (1<<2)
#define MEMINT_DOWN_EVAL (1<<1)
#define MEMINT_SW_CMD (1<<0)
#define MEMMODECTL 0x11190
#define MEMMODE_BOOST_EN (1<<31)
#define <API key> 0x0f000000 /* jitter for boost, 0-15 */
#define <API key> 24
#define <API key> 0x00030000
#define <API key> 16
#define <API key> 0
#define <API key> 1
#define MEMMODE_HWIDLE_EN (1<<15)
#define MEMMODE_SWMODE_EN (1<<14)
#define MEMMODE_RCLK_GATE (1<<13)
#define MEMMODE_HW_UPDATE (1<<12)
#define MEMMODE_FSTART_MASK 0x00000f00 /* starting jitter, 0-15 */
#define <API key> 8
#define MEMMODE_FMAX_MASK 0x000000f0 /* max jitter, 0-15 */
#define MEMMODE_FMAX_SHIFT 4
#define MEMMODE_FMIN_MASK 0x0000000f /* min jitter, 0-15 */
#define RCBMAXAVG 0x1119c
#define MEMSWCTL2 0x1119e /* Cantiga only */
#define SWMEMCMD_RENDER_OFF (0 << 13)
#define SWMEMCMD_RENDER_ON (1 << 13)
#define SWMEMCMD_SWFREQ (2 << 13)
#define SWMEMCMD_TARVID (3 << 13)
#define SWMEMCMD_VRM_OFF (4 << 13)
#define SWMEMCMD_VRM_ON (5 << 13)
#define CMDSTS (1<<12)
#define SFCAVM (1<<11)
#define SWFREQ_MASK 0x0380 /* P0-7 */
#define SWFREQ_SHIFT 7
#define TARVID_MASK 0x001f
#define MEMSTAT_CTG 0x111a0
#define RCBMINAVG 0x111a0
#define RCUPEI 0x111b0
#define RCDNEI 0x111b4
#define RSTDBYCTL 0x111b8
#define RS1EN (1<<31)
#define RS2EN (1<<30)
#define RS3EN (1<<29)
#define D3RS3EN (1<<28) /* Display D3 imlies RS3 */
#define SWPROMORSX (1<<27) /* RSx promotion timers ignored */
#define RCWAKERW (1<<26) /* Resetwarn from PCH causes wakeup */
#define DPRSLPVREN (1<<25) /* Fast voltage ramp enable */
#define GFXTGHYST (1<<24) /* Hysteresis to allow trunk gating */
#define RCX_SW_EXIT (1<<23) /* Leave RSx and prevent re-entry */
#define RSX_STATUS_MASK (7<<20)
#define RSX_STATUS_ON (0<<20)
#define RSX_STATUS_RC1 (1<<20)
#define RSX_STATUS_RC1E (2<<20)
#define RSX_STATUS_RS1 (3<<20)
#define RSX_STATUS_RS2 (4<<20) /* aka rc6 */
#define RSX_STATUS_RSVD (5<<20) /* deep rc6 unsupported on ilk */
#define RSX_STATUS_RS3 (6<<20) /* rs3 unsupported on ilk */
#define RSX_STATUS_RSVD2 (7<<20)
#define UWRCRSXE (1<<19) /* wake counter limit prevents rsx */
#define RSCRP (1<<18) /* rs requests control on rs1/2 reqs */
#define JRSC (1<<17) /* rsx coupled to cpu c-state */
#define RS2INC0 (1<<16) /* allow rs2 in cpu c0 */
#define RS1CONTSAV_MASK (3<<14)
#define RS1CONTSAV_NO_RS1 (0<<14) /* rs1 doesn't save/restore context */
#define RS1CONTSAV_RSVD (1<<14)
#define RS1CONTSAV_SAVE_RS1 (2<<14) /* rs1 saves context */
#define RS1CONTSAV_FULL_RS1 (3<<14) /* rs1 saves and restores context */
#define NORMSLEXLAT_MASK (3<<12)
#define SLOW_RS123 (0<<12)
#define SLOW_RS23 (1<<12)
#define SLOW_RS3 (2<<12)
#define NORMAL_RS123 (3<<12)
#define RCMODE_TIMEOUT (1<<11) /* 0 is eval interval method */
#define IMPROMOEN (1<<10) /* promo is immediate or delayed until next idle interval (only for timeout method above) */
#define RCENTSYNC (1<<9) /* rs coupled to cpu c-state (3/6/7) */
#define STATELOCK (1<<7) /* locked to rs_cstate if 0 */
#define RS_CSTATE_MASK (3<<4)
#define RS_CSTATE_C367_RS1 (0<<4)
#define <API key> (1<<4)
#define RS_CSTATE_RSVD (2<<4)
#define RS_CSTATE_C367_RS2 (3<<4)
#define REDSAVES (1<<3) /* no context save if was idle during rs0 */
#define REDRESTORES (1<<2) /* no restore if was idle during rs0 */
#define VIDCTL 0x111c0
#define VIDSTS 0x111c8
#define VIDSTART 0x111cc /* 8 bits */
#define MEMSTAT_ILK 0x111f8
#define MEMSTAT_VID_MASK 0x7f00
#define MEMSTAT_VID_SHIFT 8
#define MEMSTAT_PSTATE_MASK 0x00f8
#define <API key> 3
#define MEMSTAT_MON_ACTV (1<<2)
#define <API key> 0x0003
#define <API key> 0
#define MEMSTAT_SRC_CTL_TRB 1
#define MEMSTAT_SRC_CTL_THM 2
#define <API key> 3
#define RCPREVBSYTUPAVG 0x113b8
#define RCPREVBSYTDNAVG 0x113bc
#define PMMISC 0x11214
#define MCPPCE_EN (1<<0) /* enable PM_MSG from PCH->MPC */
#define SDEW 0x1124c
#define CSIEW0 0x11250
#define CSIEW1 0x11254
#define CSIEW2 0x11258
#define PEW 0x1125c
#define DEW 0x11270
#define MCHAFE 0x112c0
#define CSIEC 0x112e0
#define DMIEC 0x112e4
#define DDREC 0x112e8
#define PEG0EC 0x112ec
#define PEG1EC 0x112f0
#define GFXEC 0x112f4
#define RPPREVBSYTUPAVG 0x113b8
#define RPPREVBSYTDNAVG 0x113bc
#define ECR 0x11600
#define ECR_GPFE (1<<31)
#define ECR_IMONE (1<<30)
#define ECR_CAP_MASK 0x0000001f /* Event range, 0-31 */
#define OGW0 0x11608
#define OGW1 0x1160c
#define EG0 0x11610
#define EG1 0x11614
#define EG2 0x11618
#define EG3 0x1161c
#define EG4 0x11620
#define EG5 0x11624
#define EG6 0x11628
#define EG7 0x1162c
#define PXW 0x11664
#define PXWL 0x11680
#define LCFUSE02 0x116c0
#define LCFUSE_HIV_MASK 0x000000ff
#define CSIPLL0 0x12c10
#define DDRMPLL1 0X12c20
#define PEG_BAND_GAP_DATA 0x14d68
#define GEN6_GT_PERF_STATUS 0x145948
#define <API key> 0x145994
#define GEN6_RP_STATE_CAP 0x145998
/*
* Logical Context regs
*/
#define CCID 0x2180
#define CCID_EN (1<<0)
/*
* Overlay regs
*/
#define OVADD 0x30000
#define DOVSTA 0x30008
#define OC_BUF (0x3<<20)
#define OGAMC5 0x30010
#define OGAMC4 0x30014
#define OGAMC3 0x30018
#define OGAMC2 0x3001c
#define OGAMC1 0x30020
#define OGAMC0 0x30024
/*
* Display engine regs
*/
/* Pipe A timing regs */
#define _HTOTAL_A 0x60000
#define _HBLANK_A 0x60004
#define _HSYNC_A 0x60008
#define _VTOTAL_A 0x6000c
#define _VBLANK_A 0x60010
#define _VSYNC_A 0x60014
#define _PIPEASRC 0x6001c
#define _BCLRPAT_A 0x60020
/* Pipe B timing regs */
#define _HTOTAL_B 0x61000
#define _HBLANK_B 0x61004
#define _HSYNC_B 0x61008
#define _VTOTAL_B 0x6100c
#define _VBLANK_B 0x61010
#define _VSYNC_B 0x61014
#define _PIPEBSRC 0x6101c
#define _BCLRPAT_B 0x61020
#define HTOTAL(pipe) _PIPE(pipe, _HTOTAL_A, _HTOTAL_B)
#define HBLANK(pipe) _PIPE(pipe, _HBLANK_A, _HBLANK_B)
#define HSYNC(pipe) _PIPE(pipe, _HSYNC_A, _HSYNC_B)
#define VTOTAL(pipe) _PIPE(pipe, _VTOTAL_A, _VTOTAL_B)
#define VBLANK(pipe) _PIPE(pipe, _VBLANK_A, _VBLANK_B)
#define VSYNC(pipe) _PIPE(pipe, _VSYNC_A, _VSYNC_B)
#define BCLRPAT(pipe) _PIPE(pipe, _BCLRPAT_A, _BCLRPAT_B)
/* VGA port control */
#define ADPA 0x61100
#define ADPA_DAC_ENABLE (1<<31)
#define ADPA_DAC_DISABLE 0
#define <API key> (1<<30)
#define ADPA_PIPE_A_SELECT 0
#define ADPA_PIPE_B_SELECT (1<<30)
#define <API key> (1<<15)
#define <API key> 0
#define <API key> (1<<11)
#define <API key> 0
#define <API key> (1<<10)
#define <API key> 0
#define <API key> (1<<4)
#define <API key> 0
#define <API key> (1<<3)
#define <API key> 0
#define ADPA_DPMS_MASK (~(3<<10))
#define ADPA_DPMS_ON (0<<10)
#define ADPA_DPMS_SUSPEND (1<<10)
#define ADPA_DPMS_STANDBY (2<<10)
#define ADPA_DPMS_OFF (3<<10)
/* Hotplug control (945+ only) */
#define PORT_HOTPLUG_EN 0x61110
#define <API key> (1 << 29)
#define DPB_HOTPLUG_INT_EN (1 << 29)
#define <API key> (1 << 28)
#define DPC_HOTPLUG_INT_EN (1 << 28)
#define <API key> (1 << 27)
#define DPD_HOTPLUG_INT_EN (1 << 27)
#define <API key> (1 << 26)
#define <API key> (1 << 25)
#define TV_HOTPLUG_INT_EN (1 << 18)
#define CRT_HOTPLUG_INT_EN (1 << 9)
#define <API key> (1 << 3)
#define <API key> (0 << 8)
/* must use period 64 on GM45 according to docs */
#define <API key> (1 << 8)
#define <API key> (0 << 7)
#define <API key> (1 << 7)
#define <API key> (0 << 5)
#define <API key> (1 << 5)
#define <API key> (2 << 5)
#define <API key> (3 << 5)
#define <API key> (3 << 5)
#define <API key> (0 << 4)
#define <API key> (1 << 4)
#define <API key> (0 << 2)
#define <API key> (1 << 2)
#define PORT_HOTPLUG_STAT 0x61114
#define <API key> (1 << 29)
#define <API key> (1 << 29)
#define <API key> (1 << 28)
#define <API key> (1 << 28)
#define <API key> (1 << 27)
#define <API key> (1 << 27)
#define <API key> (1 << 11)
#define <API key> (1 << 10)
#define <API key> (3 << 8)
#define <API key> (3 << 8)
#define <API key> (2 << 8)
#define <API key> (0 << 8)
#define <API key> (1 << 7)
#define <API key> (1 << 6)
/* SDVO port control */
#define SDVOB 0x61140
#define SDVOC 0x61160
#define SDVO_ENABLE (1 << 31)
#define SDVO_PIPE_B_SELECT (1 << 30)
#define SDVO_STALL_SELECT (1 << 29)
#define <API key> (1 << 26)
/**
* 915G/GM SDVO pixel multiplier.
*
* Programmed value is multiplier - 1, up to 5x.
*
* \sa <API key>
*/
#define <API key> (7 << 23)
#define <API key> 23
#define <API key> (15 << 19)
#define <API key> (6 << 19)
#define <API key> (1 << 18)
#define SDVOC_GANG_MODE (1 << 16)
#define SDVO_ENCODING_SDVO (0x0 << 10)
#define SDVO_ENCODING_HDMI (0x2 << 10)
/** Requird for HDMI operation */
#define <API key> (1 << 9)
#define <API key> (1 << 8)
#define SDVO_BORDER_ENABLE (1 << 7)
#define SDVO_AUDIO_ENABLE (1 << 6)
/** New with 965, default is to be set */
#define <API key> (1 << 4)
/** New with 965, default is to be set */
#define <API key> (1 << 3)
#define <API key> (1 << 3)
#define SDVO_DETECTED (1 << 2)
/* Bits to be preserved when writing */
#define SDVOB_PRESERVE_MASK ((1 << 17) | (1 << 16) | (1 << 14) | (1 << 26))
#define SDVOC_PRESERVE_MASK ((1 << 17) | (1 << 26))
/* DVO port control */
#define DVOA 0x61120
#define DVOB 0x61140
#define DVOC 0x61160
#define DVO_ENABLE (1 << 31)
#define DVO_PIPE_B_SELECT (1 << 30)
#define <API key> (0 << 28)
#define DVO_PIPE_STALL (1 << 28)
#define DVO_PIPE_STALL_TV (2 << 28)
#define DVO_PIPE_STALL_MASK (3 << 28)
#define DVO_USE_VGA_SYNC (1 << 15)
#define DVO_DATA_ORDER_I740 (0 << 14)
#define DVO_DATA_ORDER_FP (1 << 14)
#define DVO_VSYNC_DISABLE (1 << 11)
#define DVO_HSYNC_DISABLE (1 << 10)
#define DVO_VSYNC_TRISTATE (1 << 9)
#define DVO_HSYNC_TRISTATE (1 << 8)
#define DVO_BORDER_ENABLE (1 << 7)
#define DVO_DATA_ORDER_GBRG (1 << 6)
#define DVO_DATA_ORDER_RGGB (0 << 6)
#define <API key> (0 << 6)
#define <API key> (1 << 6)
#define <API key> (1 << 4)
#define <API key> (1 << 3)
#define <API key> (1 << 2)
#define <API key> (1 << 1) /* SDG only */
#define <API key> (1 << 0) /* SDG only */
#define DVO_PRESERVE_MASK (0x7<<24)
#define DVOA_SRCDIM 0x61124
#define DVOB_SRCDIM 0x61144
#define DVOC_SRCDIM 0x61164
#define <API key> 12
#define <API key> 0
/* LVDS port control */
#define LVDS 0x61180
/*
* Enables the LVDS port. This bit must be set before DPLLs are enabled, as
* the DPLL semantics change when the LVDS is assigned to that pipe.
*/
#define LVDS_PORT_EN (1 << 31)
/* Selects pipe B for LVDS data. Must be set on pre-965. */
#define LVDS_PIPEB_SELECT (1 << 30)
#define LVDS_PIPE_MASK (1 << 30)
/* LVDS dithering flag on 965/g4x platform */
#define LVDS_ENABLE_DITHER (1 << 25)
/* LVDS sync polarity flags. Set to invert (i.e. negative) */
#define LVDS_VSYNC_POLARITY (1 << 21)
#define LVDS_HSYNC_POLARITY (1 << 20)
/* Enable border for unscaled (or aspect-scaled) display */
#define LVDS_BORDER_ENABLE (1 << 15)
/*
* Enables the A0-A2 data pairs and CLKA, containing 18 bits of color data per
* pixel.
*/
#define <API key> (3 << 8)
#define <API key> (0 << 8)
#define <API key> (3 << 8)
/*
* Controls the A3 data pair, which contains the additional LSBs for 24 bit
* mode. Only enabled if <API key> also indicates it should be
* on.
*/
#define LVDS_A3_POWER_MASK (3 << 6)
#define LVDS_A3_POWER_DOWN (0 << 6)
#define LVDS_A3_POWER_UP (3 << 6)
/*
* Controls the CLKB pair. This should only be set when LVDS_B0B3_POWER_UP
* is set.
*/
#define <API key> (3 << 4)
#define <API key> (0 << 4)
#define LVDS_CLKB_POWER_UP (3 << 4)
/*
* Controls the B0-B3 data pairs. This must be set to match the DPLL p2
* setting for whether we are in dual-channel mode. The B3 pair will
* additionally only be powered up when LVDS_A3_POWER_UP is set.
*/
#define <API key> (3 << 2)
#define <API key> (0 << 2)
#define LVDS_B0B3_POWER_UP (3 << 2)
#define LVDS_PIPE_ENABLED(V, P) \
(((V) & (LVDS_PIPE_MASK | LVDS_PORT_EN)) == ((P) << 30 | LVDS_PORT_EN))
/* Video Data Island Packet control */
#define VIDEO_DIP_DATA 0x61178
#define VIDEO_DIP_CTL 0x61170
#define VIDEO_DIP_ENABLE (1 << 31)
#define VIDEO_DIP_PORT_B (1 << 29)
#define VIDEO_DIP_PORT_C (2 << 29)
#define <API key> (1 << 21)
#define <API key> (2 << 21)
#define <API key> (8 << 21)
#define <API key> (0 << 19)
#define <API key> (1 << 19)
#define <API key> (3 << 19)
#define VIDEO_DIP_FREQ_ONCE (0 << 16)
#define <API key> (1 << 16)
#define <API key> (2 << 16)
/* Panel power sequencing */
#define PP_STATUS 0x61200
#define PP_ON (1 << 31)
/*
* Indicates that all dependencies of the panel are on:
*
* - PLL enabled
* - pipe enabled
* - LVDS/DVOB/DVOC on
*/
#define PP_READY (1 << 30)
#define PP_SEQUENCE_NONE (0 << 28)
#define PP_SEQUENCE_ON (1 << 28)
#define PP_SEQUENCE_OFF (2 << 28)
#define PP_SEQUENCE_MASK 0x30000000
#define <API key> (1 << 27)
#define <API key> (1 << 3)
#define <API key> 0x0000000f
#define PP_CONTROL 0x61204
#define POWER_TARGET_ON (1 << 0)
#define PP_ON_DELAYS 0x61208
#define PP_OFF_DELAYS 0x6120c
#define PP_DIVISOR 0x61210
/* Panel fitting */
#define PFIT_CONTROL 0x61230
#define PFIT_ENABLE (1 << 31)
#define PFIT_PIPE_MASK (3 << 29)
#define PFIT_PIPE_SHIFT 29
#define VERT_INTERP_DISABLE (0 << 10)
#define <API key> (1 << 10)
#define VERT_INTERP_MASK (3 << 10)
#define VERT_AUTO_SCALE (1 << 9)
#define <API key> (0 << 6)
#define <API key> (1 << 6)
#define HORIZ_INTERP_MASK (3 << 6)
#define HORIZ_AUTO_SCALE (1 << 5)
#define <API key> (1 << 3)
#define PFIT_FILTER_FUZZY (0 << 24)
#define PFIT_SCALING_AUTO (0 << 26)
#define <API key> (1 << 26)
#define PFIT_SCALING_PILLAR (2 << 26)
#define PFIT_SCALING_LETTER (3 << 26)
#define PFIT_PGM_RATIOS 0x61234
#define <API key> 0xfff00000
#define <API key> 0x0000fff0
/* Pre-965 */
#define <API key> 20
#define <API key> 0xfff00000
#define <API key> 4
#define <API key> 0x0000fff0
/* 965+ */
#define <API key> 16
#define <API key> 0x1fff0000
#define <API key> 0
#define <API key> 0x00001fff
#define PFIT_AUTO_RATIOS 0x61238
/* Backlight control */
#define BLC_PWM_CTL 0x61254
#define <API key> (17)
#define BLC_PWM_CTL2 0x61250 /* 965+ only */
#define <API key> (1 << 30)
/*
* This is the most significant 15 bits of the number of backlight cycles in a
* complete cycle of the modulated backlight control.
*
* The actual value is this field multiplied by two.
*/
#define <API key> (0x7fff << 17)
#define BLM_LEGACY_MODE (1 << 16)
/*
* This is the number of cycles out of the backlight modulation cycle for which
* the backlight is on.
*
* This field must be no greater than the number of cycles in the complete
* backlight modulation cycle.
*/
#define <API key> (0)
#define <API key> (0xffff)
#define BLC_HIST_CTL 0x61260
/* TV port control */
#define TV_CTL 0x68000
/** Enables the TV encoder */
# define TV_ENC_ENABLE (1 << 31)
/** Sources the TV encoder input from pipe B instead of A. */
# define TV_ENC_PIPEB_SELECT (1 << 30)
/** Outputs composite video (DAC A only) */
# define <API key> (0 << 28)
/** Outputs SVideo video (DAC B/C) */
# define <API key> (1 << 28)
/** Outputs Component video (DAC A/B/C) */
# define <API key> (2 << 28)
/** Outputs Composite and SVideo (DAC A/B/C) */
# define <API key> (3 << 28)
# define TV_TRILEVEL_SYNC (1 << 21)
/** Enables slow sync generation (945GM only) */
# define TV_SLOW_SYNC (1 << 20)
/** Selects 4x oversampling for 480i and 576p */
# define TV_OVERSAMPLE_4X (0 << 18)
/** Selects 2x oversampling for 720p and 1080i */
# define TV_OVERSAMPLE_2X (1 << 18)
/** Selects no oversampling for 1080p */
# define TV_OVERSAMPLE_NONE (2 << 18)
/** Selects 8x oversampling */
# define TV_OVERSAMPLE_8X (3 << 18)
/** Selects progressive mode rather than interlaced */
# define TV_PROGRESSIVE (1 << 17)
/** Sets the colorburst to PAL mode. Required for non-M PAL modes. */
# define TV_PAL_BURST (1 << 16)
/** Field for setting delay of Y compared to C */
# define TV_YC_SKEW_MASK (7 << 12)
/** Enables a fix for 480p/576p standard definition modes on the 915GM only */
# define TV_ENC_SDP_FIX (1 << 11)
/**
* Enables a fix for the 915GM only.
*
* Not sure what it does.
*/
# define TV_ENC_C0_FIX (1 << 10)
/** Bits that must be preserved by software */
# define TV_CTL_SAVE ((1 << 11) | (3 << 9) | (7 << 6) | 0xf)
# define TV_FUSE_STATE_MASK (3 << 4)
/** Read-only state that reports all features enabled */
# define <API key> (0 << 4)
/** Read-only state that reports that Macrovision is disabled in hardware*/
# define <API key> (1 << 4)
/** Read-only state that reports that TV-out is disabled in hardware. */
# define <API key> (2 << 4)
/** Normal operation */
# define TV_TEST_MODE_NORMAL (0 << 0)
/** Encoder test pattern 1 - combo pattern */
# define <API key> (1 << 0)
/** Encoder test pattern 2 - full screen vertical 75% color bars */
# define <API key> (2 << 0)
/** Encoder test pattern 3 - full screen horizontal 75% color bars */
# define <API key> (3 << 0)
/** Encoder test pattern 4 - random noise */
# define <API key> (4 << 0)
/** Encoder test pattern 5 - linear color ramps */
# define <API key> (5 << 0)
/**
* This test mode forces the DACs to 50% of full output.
*
* This is used for load detection in combination with TVDAC_SENSE_MASK
*/
# define <API key> (7 << 0)
# define TV_TEST_MODE_MASK (7 << 0)
#define TV_DAC 0x68004
# define TV_DAC_SAVE 0x00ffff00
/**
* Reports that DAC state change logic has reported change (RO).
*
* This gets cleared when TV_DAC_STATE_EN is cleared
*/
# define TVDAC_STATE_CHG (1 << 31)
# define TVDAC_SENSE_MASK (7 << 28)
/** Reports that DAC A voltage is above the detect threshold */
# define TVDAC_A_SENSE (1 << 30)
/** Reports that DAC B voltage is above the detect threshold */
# define TVDAC_B_SENSE (1 << 29)
/** Reports that DAC C voltage is above the detect threshold */
# define TVDAC_C_SENSE (1 << 28)
/**
* Enables DAC state detection logic, for load-based TV detection.
*
* The PLL of the chosen pipe (in TV_CTL) must be running, and the encoder set
* to off, for load detection to work.
*/
# define TVDAC_STATE_CHG_EN (1 << 27)
/** Sets the DAC A sense value to high */
# define TVDAC_A_SENSE_CTL (1 << 26)
/** Sets the DAC B sense value to high */
# define TVDAC_B_SENSE_CTL (1 << 25)
/** Sets the DAC C sense value to high */
# define TVDAC_C_SENSE_CTL (1 << 24)
/** Overrides the ENC_ENABLE and DAC voltage levels */
# define DAC_CTL_OVERRIDE (1 << 7)
/** Sets the slew rate. Must be preserved in software */
# define ENC_TVDAC_SLEW_FAST (1 << 6)
# define DAC_A_1_3_V (0 << 4)
# define DAC_A_1_1_V (1 << 4)
# define DAC_A_0_7_V (2 << 4)
# define DAC_A_MASK (3 << 4)
# define DAC_B_1_3_V (0 << 2)
# define DAC_B_1_1_V (1 << 2)
# define DAC_B_0_7_V (2 << 2)
# define DAC_B_MASK (3 << 2)
# define DAC_C_1_3_V (0 << 0)
# define DAC_C_1_1_V (1 << 0)
# define DAC_C_0_7_V (2 << 0)
# define DAC_C_MASK (3 << 0)
#define TV_CSC_Y 0x68010
# define TV_RY_MASK 0x07ff0000
# define TV_RY_SHIFT 16
# define TV_GY_MASK 0x00000fff
# define TV_GY_SHIFT 0
#define TV_CSC_Y2 0x68014
# define TV_BY_MASK 0x07ff0000
# define TV_BY_SHIFT 16
/**
* Y attenuation for component video.
*
* Stored in 1.9 fixed point.
*/
# define TV_AY_MASK 0x000003ff
# define TV_AY_SHIFT 0
#define TV_CSC_U 0x68018
# define TV_RU_MASK 0x07ff0000
# define TV_RU_SHIFT 16
# define TV_GU_MASK 0x000007ff
# define TV_GU_SHIFT 0
#define TV_CSC_U2 0x6801c
# define TV_BU_MASK 0x07ff0000
# define TV_BU_SHIFT 16
/**
* U attenuation for component video.
*
* Stored in 1.9 fixed point.
*/
# define TV_AU_MASK 0x000003ff
# define TV_AU_SHIFT 0
#define TV_CSC_V 0x68020
# define TV_RV_MASK 0x0fff0000
# define TV_RV_SHIFT 16
# define TV_GV_MASK 0x000007ff
# define TV_GV_SHIFT 0
#define TV_CSC_V2 0x68024
# define TV_BV_MASK 0x07ff0000
# define TV_BV_SHIFT 16
/**
* V attenuation for component video.
*
* Stored in 1.9 fixed point.
*/
# define TV_AV_MASK 0x000007ff
# define TV_AV_SHIFT 0
#define TV_CLR_KNOBS 0x68028
/** 2s-complement brightness adjustment */
# define TV_BRIGHTNESS_MASK 0xff000000
# define TV_BRIGHTNESS_SHIFT 24
/** Contrast adjustment, as a 2.6 unsigned floating point number */
# define TV_CONTRAST_MASK 0x00ff0000
# define TV_CONTRAST_SHIFT 16
/** Saturation adjustment, as a 2.6 unsigned floating point number */
# define TV_SATURATION_MASK 0x0000ff00
# define TV_SATURATION_SHIFT 8
/** Hue adjustment, as an integer phase angle in degrees */
# define TV_HUE_MASK 0x000000ff
# define TV_HUE_SHIFT 0
#define TV_CLR_LEVEL 0x6802c
/** Controls the DAC level for black */
# define TV_BLACK_LEVEL_MASK 0x01ff0000
# define <API key> 16
/** Controls the DAC level for blanking */
# define TV_BLANK_LEVEL_MASK 0x000001ff
# define <API key> 0
#define TV_H_CTL_1 0x68030
/** Number of pixels in the hsync. */
# define TV_HSYNC_END_MASK 0x1fff0000
# define TV_HSYNC_END_SHIFT 16
/** Total number of pixels minus one in the line (display and blanking). */
# define TV_HTOTAL_MASK 0x00001fff
# define TV_HTOTAL_SHIFT 0
#define TV_H_CTL_2 0x68034
/** Enables the colorburst (needed for non-component color) */
# define TV_BURST_ENA (1 << 31)
/** Offset of the colorburst from the start of hsync, in pixels minus one. */
# define <API key> 16
# define <API key> 0x1fff0000
/** Length of the colorburst */
# define TV_HBURST_LEN_SHIFT 0
# define TV_HBURST_LEN_MASK 0x0001fff
#define TV_H_CTL_3 0x68038
/** End of hblank, measured in pixels minus one from start of hsync */
# define TV_HBLANK_END_SHIFT 16
# define TV_HBLANK_END_MASK 0x1fff0000
/** Start of hblank, measured in pixels minus one from start of hsync */
# define <API key> 0
# define <API key> 0x0001fff
#define TV_V_CTL_1 0x6803c
/** XXX */
# define TV_NBR_END_SHIFT 16
# define TV_NBR_END_MASK 0x07ff0000
/** XXX */
# define TV_VI_END_F1_SHIFT 8
# define TV_VI_END_F1_MASK 0x00003f00
/** XXX */
# define TV_VI_END_F2_SHIFT 0
# define TV_VI_END_F2_MASK 0x0000003f
#define TV_V_CTL_2 0x68040
/** Length of vsync, in half lines */
# define TV_VSYNC_LEN_MASK 0x07ff0000
# define TV_VSYNC_LEN_SHIFT 16
/** Offset of the start of vsync in field 1, measured in one less than the
* number of half lines.
*/
# define <API key> 0x00007f00
# define <API key> 8
/**
* Offset of the start of vsync in field 2, measured in one less than the
* number of half lines.
*/
# define <API key> 0x0000007f
# define <API key> 0
#define TV_V_CTL_3 0x68044
/** Enables generation of the equalization signal */
# define TV_EQUAL_ENA (1 << 31)
/** Length of vsync, in half lines */
# define TV_VEQ_LEN_MASK 0x007f0000
# define TV_VEQ_LEN_SHIFT 16
/** Offset of the start of equalization in field 1, measured in one less than
* the number of half lines.
*/
# define <API key> 0x0007f00
# define <API key> 8
/**
* Offset of the start of equalization in field 2, measured in one less than
* the number of half lines.
*/
# define <API key> 0x000007f
# define <API key> 0
#define TV_V_CTL_4 0x68048
/**
* Offset to start of vertical colorburst, measured in one less than the
* number of lines from vertical start.
*/
# define <API key> 0x003f0000
# define <API key> 16
/**
* Offset to the end of vertical colorburst, measured in one less than the
* number of lines from the start of NBR.
*/
# define <API key> 0x000000ff
# define <API key> 0
#define TV_V_CTL_5 0x6804c
/**
* Offset to start of vertical colorburst, measured in one less than the
* number of lines from vertical start.
*/
# define <API key> 0x003f0000
# define <API key> 16
/**
* Offset to the end of vertical colorburst, measured in one less than the
* number of lines from the start of NBR.
*/
# define <API key> 0x000000ff
# define <API key> 0
#define TV_V_CTL_6 0x68050
/**
* Offset to start of vertical colorburst, measured in one less than the
* number of lines from vertical start.
*/
# define <API key> 0x003f0000
# define <API key> 16
/**
* Offset to the end of vertical colorburst, measured in one less than the
* number of lines from the start of NBR.
*/
# define <API key> 0x000000ff
# define <API key> 0
#define TV_V_CTL_7 0x68054
/**
* Offset to start of vertical colorburst, measured in one less than the
* number of lines from vertical start.
*/
# define <API key> 0x003f0000
# define <API key> 16
/**
* Offset to the end of vertical colorburst, measured in one less than the
* number of lines from the start of NBR.
*/
# define <API key> 0x000000ff
# define <API key> 0
#define TV_SC_CTL_1 0x68060
/** Turns on the first subcarrier phase generation DDA */
# define TV_SC_DDA1_EN (1 << 31)
/** Turns on the first subcarrier phase generation DDA */
# define TV_SC_DDA2_EN (1 << 30)
/** Turns on the first subcarrier phase generation DDA */
# define TV_SC_DDA3_EN (1 << 29)
/** Sets the subcarrier DDA to reset frequency every other field */
# define TV_SC_RESET_EVERY_2 (0 << 24)
/** Sets the subcarrier DDA to reset frequency every fourth field */
# define TV_SC_RESET_EVERY_4 (1 << 24)
/** Sets the subcarrier DDA to reset frequency every eighth field */
# define TV_SC_RESET_EVERY_8 (2 << 24)
/** Sets the subcarrier DDA to never reset the frequency */
# define TV_SC_RESET_NEVER (3 << 24)
/** Sets the peak amplitude of the colorburst.*/
# define TV_BURST_LEVEL_MASK 0x00ff0000
# define <API key> 16
/** Sets the increment of the first subcarrier phase generation DDA */
# define TV_SCDDA1_INC_MASK 0x00000fff
# define TV_SCDDA1_INC_SHIFT 0
#define TV_SC_CTL_2 0x68064
/** Sets the rollover for the second subcarrier phase generation DDA */
# define TV_SCDDA2_SIZE_MASK 0x7fff0000
# define <API key> 16
/** Sets the increent of the second subcarrier phase generation DDA */
# define TV_SCDDA2_INC_MASK 0x00007fff
# define TV_SCDDA2_INC_SHIFT 0
#define TV_SC_CTL_3 0x68068
/** Sets the rollover for the third subcarrier phase generation DDA */
# define TV_SCDDA3_SIZE_MASK 0x7fff0000
# define <API key> 16
/** Sets the increent of the third subcarrier phase generation DDA */
# define TV_SCDDA3_INC_MASK 0x00007fff
# define TV_SCDDA3_INC_SHIFT 0
#define TV_WIN_POS 0x68070
/** X coordinate of the display from the start of horizontal active */
# define TV_XPOS_MASK 0x1fff0000
# define TV_XPOS_SHIFT 16
/** Y coordinate of the display from the start of vertical active (NBR) */
# define TV_YPOS_MASK 0x00000fff
# define TV_YPOS_SHIFT 0
#define TV_WIN_SIZE 0x68074
/** Horizontal size of the display window, measured in pixels*/
# define TV_XSIZE_MASK 0x1fff0000
# define TV_XSIZE_SHIFT 16
/**
* Vertical size of the display window, measured in pixels.
*
* Must be even for interlaced modes.
*/
# define TV_YSIZE_MASK 0x00000fff
# define TV_YSIZE_SHIFT 0
#define TV_FILTER_CTL_1 0x68080
/**
* Enables automatic scaling calculation.
*
* If set, the rest of the registers are ignored, and the calculated values can
* be read back from the register.
*/
# define TV_AUTO_SCALE (1 << 31)
/**
* Disables the vertical filter.
*
* This is required on modes more than 1024 pixels wide */
# define TV_V_FILTER_BYPASS (1 << 29)
/** Enables adaptive vertical filtering */
# define TV_VADAPT (1 << 28)
# define TV_VADAPT_MODE_MASK (3 << 26)
/** Selects the least adaptive vertical filtering mode */
# define <API key> (0 << 26)
/** Selects the moderately adaptive vertical filtering mode */
# define <API key> (1 << 26)
/** Selects the most adaptive vertical filtering mode */
# define TV_VADAPT_MODE_MOST (3 << 26)
/**
* Sets the horizontal scaling factor.
*
* This should be the fractional part of the horizontal scaling factor divided
* by the oversampling rate. TV_HSCALE should be less than 1, and set to:
*
* (src width - 1) / ((oversample * dest width) - 1)
*/
# define TV_HSCALE_FRAC_MASK 0x00003fff
# define <API key> 0
#define TV_FILTER_CTL_2 0x68084
/**
* Sets the integer part of the 3.15 fixed-point vertical scaling factor.
*
* TV_VSCALE should be (src height - 1) / ((interlace * dest height) - 1)
*/
# define TV_VSCALE_INT_MASK 0x00038000
# define TV_VSCALE_INT_SHIFT 15
/**
* Sets the fractional part of the 3.15 fixed-point vertical scaling factor.
*
* \sa TV_VSCALE_INT_MASK
*/
# define TV_VSCALE_FRAC_MASK 0x00007fff
# define <API key> 0
#define TV_FILTER_CTL_3 0x68088
/**
* Sets the integer part of the 3.15 fixed-point vertical scaling factor.
*
* TV_VSCALE should be (src height - 1) / (1/4 * (dest height - 1))
*
* For progressive modes, TV_VSCALE_IP_INT should be set to zeroes.
*/
# define <API key> 0x00038000
# define <API key> 15
/**
* Sets the fractional part of the 3.15 fixed-point vertical scaling factor.
*
* For progressive modes, TV_VSCALE_IP_INT should be set to zeroes.
*
* \sa <API key>
*/
# define <API key> 0x00007fff
# define <API key> 0
#define TV_CC_CONTROL 0x68090
# define TV_CC_ENABLE (1 << 31)
/**
* Specifies which field to send the CC data in.
*
* CC data is usually sent in field 0.
*/
# define TV_CC_FID_MASK (1 << 27)
# define TV_CC_FID_SHIFT 27
/** Sets the horizontal position of the CC data. Usually 135. */
# define TV_CC_HOFF_MASK 0x03ff0000
# define TV_CC_HOFF_SHIFT 16
/** Sets the vertical position of the CC data. Usually 21 */
# define TV_CC_LINE_MASK 0x0000003f
# define TV_CC_LINE_SHIFT 0
#define TV_CC_DATA 0x68094
# define TV_CC_RDY (1 << 31)
/** Second word of CC data to be transmitted. */
# define TV_CC_DATA_2_MASK 0x007f0000
# define TV_CC_DATA_2_SHIFT 16
/** First word of CC data to be transmitted. */
# define TV_CC_DATA_1_MASK 0x0000007f
# define TV_CC_DATA_1_SHIFT 0
#define TV_H_LUMA_0 0x68100
#define TV_H_LUMA_59 0x681ec
#define TV_H_CHROMA_0 0x68200
#define TV_H_CHROMA_59 0x682ec
#define TV_V_LUMA_0 0x68300
#define TV_V_LUMA_42 0x683a8
#define TV_V_CHROMA_0 0x68400
#define TV_V_CHROMA_42 0x684a8
/* Display Port */
#define DP_A 0x64000 /* eDP */
#define DP_B 0x64100
#define DP_C 0x64200
#define DP_D 0x64300
#define DP_PORT_EN (1 << 31)
#define DP_PIPEB_SELECT (1 << 30)
#define DP_PIPE_MASK (1 << 30)
#define DP_PIPE_ENABLED(V, P) \
(((V) & (DP_PIPE_MASK | DP_PORT_EN)) == ((P) << 30 | DP_PORT_EN))
/* Link training mode - select a suitable mode for each stage */
#define DP_LINK_TRAIN_PAT_1 (0 << 28)
#define DP_LINK_TRAIN_PAT_2 (1 << 28)
#define <API key> (2 << 28)
#define DP_LINK_TRAIN_OFF (3 << 28)
#define DP_LINK_TRAIN_MASK (3 << 28)
#define DP_LINK_TRAIN_SHIFT 28
/* CPT Link training mode */
#define <API key> (0 << 8)
#define <API key> (1 << 8)
#define <API key> (2 << 8)
#define <API key> (3 << 8)
#define <API key> (7 << 8)
#define <API key> 8
/* Signal voltages. These are mostly controlled by the other end */
#define DP_VOLTAGE_0_4 (0 << 25)
#define DP_VOLTAGE_0_6 (1 << 25)
#define DP_VOLTAGE_0_8 (2 << 25)
#define DP_VOLTAGE_1_2 (3 << 25)
#define DP_VOLTAGE_MASK (7 << 25)
#define DP_VOLTAGE_SHIFT 25
/* Signal pre-emphasis levels, like voltages, the other end tells us what
* they want
*/
#define DP_PRE_EMPHASIS_0 (0 << 22)
#define DP_PRE_EMPHASIS_3_5 (1 << 22)
#define DP_PRE_EMPHASIS_6 (2 << 22)
#define DP_PRE_EMPHASIS_9_5 (3 << 22)
#define <API key> (7 << 22)
#define <API key> 22
/* How many wires to use. I guess 3 was too hard */
#define DP_PORT_WIDTH_1 (0 << 19)
#define DP_PORT_WIDTH_2 (1 << 19)
#define DP_PORT_WIDTH_4 (3 << 19)
#define DP_PORT_WIDTH_MASK (7 << 19)
/* Mystic DPCD version 1.1 special mode */
#define DP_ENHANCED_FRAMING (1 << 18)
/* eDP */
#define DP_PLL_FREQ_270MHZ (0 << 16)
#define DP_PLL_FREQ_160MHZ (1 << 16)
#define DP_PLL_FREQ_MASK (3 << 16)
/** locked once port is enabled */
#define DP_PORT_REVERSAL (1 << 15)
/* eDP */
#define DP_PLL_ENABLE (1 << 14)
/** sends the clock on lane 15 of the PEG for debug */
#define <API key> (1 << 13)
#define <API key> (1 << 12)
#define <API key> (1 << 7)
/** limit RGB values to avoid confusing TVs */
#define <API key> (1 << 8)
/** Turn on the audio link */
#define <API key> (1 << 6)
/** vs and hs sync polarity */
#define DP_SYNC_VS_HIGH (1 << 4)
#define DP_SYNC_HS_HIGH (1 << 3)
/** A fantasy */
#define DP_DETECTED (1 << 2)
/** The aux channel provides a way to talk to the
* signal sink for DDC etc. Max packet size supported
* is 20 bytes in each direction, hence the 5 fixed
* data registers
*/
#define DPA_AUX_CH_CTL 0x64010
#define DPA_AUX_CH_DATA1 0x64014
#define DPA_AUX_CH_DATA2 0x64018
#define DPA_AUX_CH_DATA3 0x6401c
#define DPA_AUX_CH_DATA4 0x64020
#define DPA_AUX_CH_DATA5 0x64024
#define DPB_AUX_CH_CTL 0x64110
#define DPB_AUX_CH_DATA1 0x64114
#define DPB_AUX_CH_DATA2 0x64118
#define DPB_AUX_CH_DATA3 0x6411c
#define DPB_AUX_CH_DATA4 0x64120
#define DPB_AUX_CH_DATA5 0x64124
#define DPC_AUX_CH_CTL 0x64210
#define DPC_AUX_CH_DATA1 0x64214
#define DPC_AUX_CH_DATA2 0x64218
#define DPC_AUX_CH_DATA3 0x6421c
#define DPC_AUX_CH_DATA4 0x64220
#define DPC_AUX_CH_DATA5 0x64224
#define DPD_AUX_CH_CTL 0x64310
#define DPD_AUX_CH_DATA1 0x64314
#define DPD_AUX_CH_DATA2 0x64318
#define DPD_AUX_CH_DATA3 0x6431c
#define DPD_AUX_CH_DATA4 0x64320
#define DPD_AUX_CH_DATA5 0x64324
#define <API key> (1 << 31)
#define DP_AUX_CH_CTL_DONE (1 << 30)
#define <API key> (1 << 29)
#define <API key> (1 << 28)
#define <API key> (0 << 26)
#define <API key> (1 << 26)
#define <API key> (2 << 26)
#define <API key> (3 << 26)
#define <API key> (3 << 26)
#define <API key> (1 << 25)
#define <API key> (0x1f << 20)
#define <API key> 20
#define <API key> (0xf << 16)
#define <API key> 16
#define <API key> (1 << 15)
#define <API key> (1 << 14)
#define <API key> (1 << 13)
#define <API key> (1 << 12)
#define <API key> (1 << 11)
#define <API key> (0x7ff)
#define <API key> 0
/*
* Computing GMCH M and N values for the Display Port link
*
* GMCH M/N = dot clock * bytes per pixel / ls_clk * # of lanes
*
* ls_clk (we assume) is the DP link clock (1.62 or 2.7 GHz)
*
* The GMCH value is used internally
*
* bytes_per_pixel is the number of bytes coming out of the plane,
* which is after the LUTs, so we want the bytes for our color format.
* For our current usage, this is always 3, one byte for R, G and B.
*/
#define _PIPEA_GMCH_DATA_M 0x70050
#define _PIPEB_GMCH_DATA_M 0x71050
/* Transfer unit size for display port - 1, default is 0x3f (for TU size 64) */
#define <API key> (0x3f << 25)
#define <API key> 25
#define <API key> (0xffffff)
#define _PIPEA_GMCH_DATA_N 0x70054
#define _PIPEB_GMCH_DATA_N 0x71054
#define <API key> (0xffffff)
/*
* Computing Link M and N values for the Display Port link
*
* Link M / N = pixel_clock / ls_clk
*
* (the DP spec calls pixel_clock the 'strm_clk')
*
* The Link value is transmitted in the Main Stream
* Attributes and VB-ID.
*/
#define _PIPEA_DP_LINK_M 0x70060
#define _PIPEB_DP_LINK_M 0x71060
#define <API key> (0xffffff)
#define _PIPEA_DP_LINK_N 0x70064
#define _PIPEB_DP_LINK_N 0x71064
#define <API key> (0xffffff)
#define PIPE_GMCH_DATA_M(pipe) _PIPE(pipe, _PIPEA_GMCH_DATA_M, _PIPEB_GMCH_DATA_M)
#define PIPE_GMCH_DATA_N(pipe) _PIPE(pipe, _PIPEA_GMCH_DATA_N, _PIPEB_GMCH_DATA_N)
#define PIPE_DP_LINK_M(pipe) _PIPE(pipe, _PIPEA_DP_LINK_M, _PIPEB_DP_LINK_M)
#define PIPE_DP_LINK_N(pipe) _PIPE(pipe, _PIPEA_DP_LINK_N, _PIPEB_DP_LINK_N)
/* Display & cursor control */
/* Pipe A */
#define _PIPEADSL 0x70000
#define DSL_LINEMASK 0x00000fff
#define _PIPEACONF 0x70008
#define PIPECONF_ENABLE (1<<31)
#define PIPECONF_DISABLE 0
#define <API key> (1<<30)
#define <API key> (1<<30)
#define <API key> (3<<27)
#define <API key> 0
#define <API key> 0
#define <API key> (1<<25)
#define PIPECONF_PALETTE 0
#define PIPECONF_GAMMA (1<<24)
#define <API key> (1<<25)
#define <API key> (0 << 21)
#define <API key> (6 << 21)
#define <API key> (7 << 21)
#define <API key> (1<<16)
#define PIPECONF_BPP_MASK (0x000000e0)
#define PIPECONF_BPP_8 (0<<5)
#define PIPECONF_BPP_10 (1<<5)
#define PIPECONF_BPP_6 (2<<5)
#define PIPECONF_BPP_12 (3<<5)
#define PIPECONF_DITHER_EN (1<<4)
#define <API key> (0x0000000c)
#define <API key> (0<<2)
#define <API key> (1<<2)
#define <API key> (2<<2)
#define <API key> (3<<2)
#define _PIPEASTAT 0x70024
#define <API key> (1UL<<31)
#define <API key> (1UL<<29)
#define <API key> (1UL<<28)
#define <API key> (1UL<<27)
#define <API key> (1UL<<26)
#define <API key> (1UL<<25)
#define <API key> (1UL<<24)
#define <API key> (1UL<<23)
#define <API key> (1UL<<22)
#define <API key> (1UL<<21)
#define <API key> (1UL<<20)
#define <API key> (1UL<<18) /* pre-965 */
#define <API key> (1UL<<18) /* 965 or later */
#define <API key> (1UL<<17)
#define <API key> (1UL<<16)
#define <API key> (1UL<<13)
#define <API key> (1UL<<12)
#define <API key> (1UL<<11)
#define <API key> (1UL<<10)
#define <API key> (1UL<<9)
#define <API key> (1UL<<8)
#define <API key> (1UL<<7)
#define <API key> (1UL<<6)
#define <API key> (1UL<<5)
#define <API key> (1UL<<4)
#define <API key> (1UL<<2) /* pre-965 */
#define <API key> (1UL<<2) /* 965 or later */
#define <API key> (1UL<<1)
#define <API key> (1UL<<0)
#define PIPE_BPC_MASK (7 << 5) /* Ironlake */
#define PIPE_8BPC (0 << 5)
#define PIPE_10BPC (1 << 5)
#define PIPE_6BPC (2 << 5)
#define PIPE_12BPC (3 << 5)
#define PIPESRC(pipe) _PIPE(pipe, _PIPEASRC, _PIPEBSRC)
#define PIPECONF(pipe) _PIPE(pipe, _PIPEACONF, _PIPEBCONF)
#define PIPEDSL(pipe) _PIPE(pipe, _PIPEADSL, _PIPEBDSL)
#define PIPEFRAME(pipe) _PIPE(pipe, _PIPEAFRAMEHIGH, _PIPEBFRAMEHIGH)
#define PIPEFRAMEPIXEL(pipe) _PIPE(pipe, _PIPEAFRAMEPIXEL, _PIPEBFRAMEPIXEL)
#define PIPESTAT(pipe) _PIPE(pipe, _PIPEASTAT, _PIPEBSTAT)
#define DSPARB 0x70030
#define DSPARB_CSTART_MASK (0x7f << 7)
#define DSPARB_CSTART_SHIFT 7
#define DSPARB_BSTART_MASK (0x7f)
#define DSPARB_BSTART_SHIFT 0
#define DSPARB_BEND_SHIFT 9 /* on 855 */
#define DSPARB_AEND_SHIFT 0
#define DSPFW1 0x70034
#define DSPFW_SR_SHIFT 23
#define DSPFW_SR_MASK (0x1ff<<23)
#define DSPFW_CURSORB_SHIFT 16
#define DSPFW_CURSORB_MASK (0x3f<<16)
#define DSPFW_PLANEB_SHIFT 8
#define DSPFW_PLANEB_MASK (0x7f<<8)
#define DSPFW_PLANEA_MASK (0x7f)
#define DSPFW2 0x70038
#define DSPFW_CURSORA_MASK 0x00003f00
#define DSPFW_CURSORA_SHIFT 8
#define DSPFW_PLANEC_MASK (0x7f)
#define DSPFW3 0x7003c
#define DSPFW_HPLL_SR_EN (1<<31)
#define <API key> 24
#define <API key> (1<<30)
#define <API key> (0x3f<<24)
#define <API key> 16
#define <API key> (0x3f<<16)
#define DSPFW_HPLL_SR_MASK (0x1ff)
/* FIFO watermark sizes etc */
#define G4X_FIFO_LINE_SIZE 64
#define I915_FIFO_LINE_SIZE 64
#define I830_FIFO_LINE_SIZE 32
#define G4X_FIFO_SIZE 127
#define I965_FIFO_SIZE 512
#define I945_FIFO_SIZE 127
#define I915_FIFO_SIZE 95
#define I855GM_FIFO_SIZE 127 /* In cachelines */
#define I830_FIFO_SIZE 95
#define G4X_MAX_WM 0x3f
#define I915_MAX_WM 0x3f
#define <API key> 512 /* in 64byte unit */
#define <API key> 64
#define PINEVIEW_MAX_WM 0x1ff
#define PINEVIEW_DFT_WM 0x3f
#define <API key> 0
#define PINEVIEW_GUARD_WM 10
#define <API key> 64
#define <API key> 0x3f
#define <API key> 0
#define <API key> 5
#define I965_CURSOR_FIFO 64
#define I965_CURSOR_MAX_WM 32
#define I965_CURSOR_DFT_WM 8
/* define the Watermark register on Ironlake */
#define WM0_PIPEA_ILK 0x45100
#define WM0_PIPE_PLANE_MASK (0x7f<<16)
#define <API key> 16
#define <API key> (0x3f<<8)
#define <API key> 8
#define <API key> (0x1f)
#define WM0_PIPEB_ILK 0x45104
#define WM1_LP_ILK 0x45108
#define WM1_LP_SR_EN (1<<31)
#define <API key> 24
#define WM1_LP_LATENCY_MASK (0x7f<<24)
#define WM1_LP_FBC_MASK (0xf<<20)
#define WM1_LP_FBC_SHIFT 20
#define WM1_LP_SR_MASK (0x1ff<<8)
#define WM1_LP_SR_SHIFT 8
#define WM1_LP_CURSOR_MASK (0x3f)
#define WM2_LP_ILK 0x4510c
#define WM2_LP_EN (1<<31)
#define WM3_LP_ILK 0x45110
#define WM3_LP_EN (1<<31)
#define WM1S_LP_ILK 0x45120
#define WM1S_LP_EN (1<<31)
/* Memory latency timer register */
#define MLTR_ILK 0x11222
#define MLTR_WM1_SHIFT 0
#define MLTR_WM2_SHIFT 8
/* the unit of memory self-refresh latency time is 0.5us */
#define ILK_SRLT_MASK 0x3f
#define ILK_LATENCY(shift) (I915_READ(MLTR_ILK) >> (shift) & ILK_SRLT_MASK)
#define <API key>() ILK_LATENCY(MLTR_WM1_SHIFT)
#define <API key>() ILK_LATENCY(MLTR_WM2_SHIFT)
/* define the fifo size on Ironlake */
#define ILK_DISPLAY_FIFO 128
#define ILK_DISPLAY_MAXWM 64
#define ILK_DISPLAY_DFTWM 8
#define ILK_CURSOR_FIFO 32
#define ILK_CURSOR_MAXWM 16
#define ILK_CURSOR_DFTWM 8
#define ILK_DISPLAY_SR_FIFO 512
#define <API key> 0x1ff
#define <API key> 0x3f
#define ILK_CURSOR_SR_FIFO 64
#define ILK_CURSOR_MAX_SRWM 0x3f
#define ILK_CURSOR_DFT_SRWM 8
#define ILK_FIFO_LINE_SIZE 64
/* define the WM info on Sandybridge */
#define SNB_DISPLAY_FIFO 128
#define SNB_DISPLAY_MAXWM 0x7f /* bit 16:22 */
#define SNB_DISPLAY_DFTWM 8
#define SNB_CURSOR_FIFO 32
#define SNB_CURSOR_MAXWM 0x1f /* bit 4:0 */
#define SNB_CURSOR_DFTWM 8
#define SNB_DISPLAY_SR_FIFO 512
#define <API key> 0x1ff /* bit 16:8 */
#define <API key> 0x3f
#define SNB_CURSOR_SR_FIFO 64
#define SNB_CURSOR_MAX_SRWM 0x3f /* bit 5:0 */
#define SNB_CURSOR_DFT_SRWM 8
#define SNB_FBC_MAX_SRWM 0xf /* bit 23:20 */
#define SNB_FIFO_LINE_SIZE 64
/* the address where we get all kinds of latency value */
#define SSKPD 0x5d10
#define SSKPD_WM_MASK 0x3f
#define SSKPD_WM0_SHIFT 0
#define SSKPD_WM1_SHIFT 8
#define SSKPD_WM2_SHIFT 16
#define SSKPD_WM3_SHIFT 24
#define SNB_LATENCY(shift) (I915_READ(<API key> + SSKPD) >> (shift) & SSKPD_WM_MASK)
#define <API key>() SNB_LATENCY(SSKPD_WM0_SHIFT)
#define <API key>() SNB_LATENCY(SSKPD_WM1_SHIFT)
#define <API key>() SNB_LATENCY(SSKPD_WM2_SHIFT)
#define <API key>() SNB_LATENCY(SSKPD_WM3_SHIFT)
/*
* The two pipe frame counter registers are not synchronized, so
* reading a stable value is somewhat tricky. The following code
* should work:
*
* do {
* high1 = ((INREG(PIPEAFRAMEHIGH) & <API key>) >>
* <API key>;
* low1 = ((INREG(PIPEAFRAMEPIXEL) & PIPE_FRAME_LOW_MASK) >>
* <API key>);
* high2 = ((INREG(PIPEAFRAMEHIGH) & <API key>) >>
* <API key>);
* } while (high1 != high2);
* frame = (high1 << 8) | low1;
*/
#define _PIPEAFRAMEHIGH 0x70040
#define <API key> 0x0000ffff
#define <API key> 0
#define _PIPEAFRAMEPIXEL 0x70044
#define PIPE_FRAME_LOW_MASK 0xff000000
#define <API key> 24
#define PIPE_PIXEL_MASK 0x00ffffff
#define PIPE_PIXEL_SHIFT 0
/* GM45+ just has to be different */
#define <API key> 0x70040
#define <API key> 0x70044
#define PIPE_FRMCOUNT_GM45(pipe) _PIPE(pipe, <API key>, <API key>)
/* Cursor A & B regs */
#define _CURACNTR 0x70080
/* Old style CUR*CNTR flags (desktop 8xx) */
#define CURSOR_ENABLE 0x80000000
#define CURSOR_GAMMA_ENABLE 0x40000000
#define CURSOR_STRIDE_MASK 0x30000000
#define CURSOR_FORMAT_SHIFT 24
#define CURSOR_FORMAT_MASK (0x07 << CURSOR_FORMAT_SHIFT)
#define CURSOR_FORMAT_2C (0x00 << CURSOR_FORMAT_SHIFT)
#define CURSOR_FORMAT_3C (0x01 << CURSOR_FORMAT_SHIFT)
#define CURSOR_FORMAT_4C (0x02 << CURSOR_FORMAT_SHIFT)
#define CURSOR_FORMAT_ARGB (0x04 << CURSOR_FORMAT_SHIFT)
#define CURSOR_FORMAT_XRGB (0x05 << CURSOR_FORMAT_SHIFT)
/* New style CUR*CNTR flags */
#define CURSOR_MODE 0x27
#define CURSOR_MODE_DISABLE 0x00
#define <API key> 0x07
#define <API key> ((1 << 5) | <API key>)
#define MCURSOR_PIPE_SELECT (1 << 28)
#define MCURSOR_PIPE_A 0x00
#define MCURSOR_PIPE_B (1 << 28)
#define <API key> (1 << 26)
#define _CURABASE 0x70084
#define _CURAPOS 0x70088
#define CURSOR_POS_MASK 0x007FF
#define CURSOR_POS_SIGN 0x8000
#define CURSOR_X_SHIFT 0
#define CURSOR_Y_SHIFT 16
#define CURSIZE 0x700a0
#define _CURBCNTR 0x700c0
#define _CURBBASE 0x700c4
#define _CURBPOS 0x700c8
#define _CURBCNTR_IVB 0x71080
#define _CURBBASE_IVB 0x71084
#define _CURBPOS_IVB 0x71088
#define CURCNTR(pipe) _PIPE(pipe, _CURACNTR, _CURBCNTR)
#define CURBASE(pipe) _PIPE(pipe, _CURABASE, _CURBBASE)
#define CURPOS(pipe) _PIPE(pipe, _CURAPOS, _CURBPOS)
#define CURCNTR_IVB(pipe) _PIPE(pipe, _CURACNTR, _CURBCNTR_IVB)
#define CURBASE_IVB(pipe) _PIPE(pipe, _CURABASE, _CURBBASE_IVB)
#define CURPOS_IVB(pipe) _PIPE(pipe, _CURAPOS, _CURBPOS_IVB)
/* Display A control */
#define _DSPACNTR 0x70180
#define <API key> (1<<31)
#define <API key> 0
#define <API key> (1<<30)
#define <API key> 0
#define <API key> (0xf<<26)
#define DISPPLANE_8BPP (0x2<<26)
#define DISPPLANE_15_16BPP (0x4<<26)
#define DISPPLANE_16BPP (0x5<<26)
#define <API key> (0x6<<26)
#define DISPPLANE_32BPP (0x7<<26)
#define <API key> (0xa<<26)
#define <API key> (1<<25)
#define <API key> 0
#define <API key> 24
#define <API key> (3<<<API key>)
#define <API key> 0
#define <API key> (1<<<API key>)
#define <API key> (1<<22)
#define <API key> 0
#define <API key> (1<<20)
#define <API key> 0
#define <API key> 0
#define <API key> (1<<18)
#define <API key> (1<<14) /* Ironlake */
#define DISPPLANE_TILED (1<<10)
#define _DSPAADDR 0x70184
#define _DSPASTRIDE 0x70188
#define _DSPAPOS 0x7018C /* reserved */
#define _DSPASIZE 0x70190
#define _DSPASURF 0x7019C /* 965+ only */
#define _DSPATILEOFF 0x701A4 /* 965+ only */
#define DSPCNTR(plane) _PIPE(plane, _DSPACNTR, _DSPBCNTR)
#define DSPADDR(plane) _PIPE(plane, _DSPAADDR, _DSPBADDR)
#define DSPSTRIDE(plane) _PIPE(plane, _DSPASTRIDE, _DSPBSTRIDE)
#define DSPPOS(plane) _PIPE(plane, _DSPAPOS, _DSPBPOS)
#define DSPSIZE(plane) _PIPE(plane, _DSPASIZE, _DSPBSIZE)
#define DSPSURF(plane) _PIPE(plane, _DSPASURF, _DSPBSURF)
#define DSPTILEOFF(plane) _PIPE(plane, _DSPATILEOFF, _DSPBTILEOFF)
/* VBIOS flags */
#define SWF00 0x71410
#define SWF01 0x71414
#define SWF02 0x71418
#define SWF03 0x7141c
#define SWF04 0x71420
#define SWF05 0x71424
#define SWF06 0x71428
#define SWF10 0x70410
#define SWF11 0x70414
#define SWF14 0x71420
#define SWF30 0x72414
#define SWF31 0x72418
#define SWF32 0x7241c
/* Pipe B */
#define _PIPEBDSL 0x71000
#define _PIPEBCONF 0x71008
#define _PIPEBSTAT 0x71024
#define _PIPEBFRAMEHIGH 0x71040
#define _PIPEBFRAMEPIXEL 0x71044
#define <API key> 0x71040
#define <API key> 0x71044
/* Display B control */
#define _DSPBCNTR 0x71180
#define <API key> (1<<15)
#define <API key> 0
#define <API key> 0
#define <API key> (1)
#define _DSPBADDR 0x71184
#define _DSPBSTRIDE 0x71188
#define _DSPBPOS 0x7118C
#define _DSPBSIZE 0x71190
#define _DSPBSURF 0x7119C
#define _DSPBTILEOFF 0x711A4
/* VBIOS regs */
#define VGACNTRL 0x71400
# define VGA_DISP_DISABLE (1 << 31)
# define VGA_2X_MODE (1 << 30)
# define VGA_PIPE_B_SELECT (1 << 29)
/* Ironlake */
#define CPU_VGACNTRL 0x41000
#define <API key> 0x44030
#define <API key> (1 << 4)
#define <API key> (0 << 2)
#define <API key> (1 << 2)
#define <API key> (2 << 2)
#define <API key> (3 << 2)
#define <API key> (0 << 0)
#define <API key> (1 << 1)
#define <API key> (1 << 0)
/* refresh rate hardware control */
#define RR_HW_CTL 0x45300
#define <API key> 0xff
#define <API key> 0xff00
#define FDI_PLL_BIOS_0 0x46000
#define <API key> 0xff
#define FDI_PLL_BIOS_1 0x46004
#define FDI_PLL_BIOS_2 0x46008
#define <API key> 0x4600c
#define <API key> 0x46010
#define <API key> 0x46014
#define PCH_DSPCLK_GATE_D 0x42020
# define <API key> (1 << 9)
# define <API key> (1 << 8)
# define <API key> (1 << 7)
# define <API key> (1 << 5)
#define PCH_3DCGDIS0 0x46020
# define <API key> (1 << 18)
# define <API key> (1 << 1)
#define PCH_3DCGDIS1 0x46024
# define <API key> (1 << 11)
#define FDI_PLL_FREQ_CTL 0x46030
#define <API key> (1<<24)
#define <API key> 0xfff00
#define <API key> 0xff
#define _PIPEA_DATA_M1 0x60030
#define TU_SIZE(x) (((x)-1) << 25) /* default size 64 */
#define TU_SIZE_MASK 0x7e000000
#define PIPE_DATA_M1_OFFSET 0
#define _PIPEA_DATA_N1 0x60034
#define PIPE_DATA_N1_OFFSET 0
#define _PIPEA_DATA_M2 0x60038
#define PIPE_DATA_M2_OFFSET 0
#define _PIPEA_DATA_N2 0x6003c
#define PIPE_DATA_N2_OFFSET 0
#define _PIPEA_LINK_M1 0x60040
#define PIPE_LINK_M1_OFFSET 0
#define _PIPEA_LINK_N1 0x60044
#define PIPE_LINK_N1_OFFSET 0
#define _PIPEA_LINK_M2 0x60048
#define PIPE_LINK_M2_OFFSET 0
#define _PIPEA_LINK_N2 0x6004c
#define PIPE_LINK_N2_OFFSET 0
/* PIPEB timing regs are same start from 0x61000 */
#define _PIPEB_DATA_M1 0x61030
#define _PIPEB_DATA_N1 0x61034
#define _PIPEB_DATA_M2 0x61038
#define _PIPEB_DATA_N2 0x6103c
#define _PIPEB_LINK_M1 0x61040
#define _PIPEB_LINK_N1 0x61044
#define _PIPEB_LINK_M2 0x61048
#define _PIPEB_LINK_N2 0x6104c
#define PIPE_DATA_M1(pipe) _PIPE(pipe, _PIPEA_DATA_M1, _PIPEB_DATA_M1)
#define PIPE_DATA_N1(pipe) _PIPE(pipe, _PIPEA_DATA_N1, _PIPEB_DATA_N1)
#define PIPE_DATA_M2(pipe) _PIPE(pipe, _PIPEA_DATA_M2, _PIPEB_DATA_M2)
#define PIPE_DATA_N2(pipe) _PIPE(pipe, _PIPEA_DATA_N2, _PIPEB_DATA_N2)
#define PIPE_LINK_M1(pipe) _PIPE(pipe, _PIPEA_LINK_M1, _PIPEB_LINK_M1)
#define PIPE_LINK_N1(pipe) _PIPE(pipe, _PIPEA_LINK_N1, _PIPEB_LINK_N1)
#define PIPE_LINK_M2(pipe) _PIPE(pipe, _PIPEA_LINK_M2, _PIPEB_LINK_M2)
#define PIPE_LINK_N2(pipe) _PIPE(pipe, _PIPEA_LINK_N2, _PIPEB_LINK_N2)
/* CPU panel fitter */
/* IVB+ has 3 fitters, 0 is 7x5 capable, the other two only 3x3 */
#define _PFA_CTL_1 0x68080
#define _PFB_CTL_1 0x68880
#define PF_ENABLE (1<<31)
#define PF_FILTER_MASK (3<<23)
#define <API key> (0<<23)
#define PF_FILTER_MED_3x3 (1<<23)
#define <API key> (2<<23)
#define <API key> (3<<23)
#define _PFA_WIN_SZ 0x68074
#define _PFB_WIN_SZ 0x68874
#define _PFA_WIN_POS 0x68070
#define _PFB_WIN_POS 0x68870
#define _PFA_VSCALE 0x68084
#define _PFB_VSCALE 0x68884
#define _PFA_HSCALE 0x68090
#define _PFB_HSCALE 0x68890
#define PF_CTL(pipe) _PIPE(pipe, _PFA_CTL_1, _PFB_CTL_1)
#define PF_WIN_SZ(pipe) _PIPE(pipe, _PFA_WIN_SZ, _PFB_WIN_SZ)
#define PF_WIN_POS(pipe) _PIPE(pipe, _PFA_WIN_POS, _PFB_WIN_POS)
#define PF_VSCALE(pipe) _PIPE(pipe, _PFA_VSCALE, _PFB_VSCALE)
#define PF_HSCALE(pipe) _PIPE(pipe, _PFA_HSCALE, _PFB_HSCALE)
/* legacy palette */
#define _LGC_PALETTE_A 0x4a000
#define _LGC_PALETTE_B 0x4a800
#define LGC_PALETTE(pipe) _PIPE(pipe, _LGC_PALETTE_A, _LGC_PALETTE_B)
/* interrupts */
#define <API key> (1 << 31)
#define <API key> (1 << 29)
#define <API key> (1 << 28)
#define DE_PLANEB_FLIP_DONE (1 << 27)
#define DE_PLANEA_FLIP_DONE (1 << 26)
#define DE_PCU_EVENT (1 << 25)
#define DE_GTT_FAULT (1 << 24)
#define DE_POISON (1 << 23)
#define DE_PERFORM_COUNTER (1 << 22)
#define DE_PCH_EVENT (1 << 21)
#define DE_AUX_CHANNEL_A (1 << 20)
#define DE_DP_A_HOTPLUG (1 << 19)
#define DE_GSE (1 << 18)
#define DE_PIPEB_VBLANK (1 << 15)
#define DE_PIPEB_EVEN_FIELD (1 << 14)
#define DE_PIPEB_ODD_FIELD (1 << 13)
#define <API key> (1 << 12)
#define DE_PIPEB_VSYNC (1 << 11)
#define <API key> (1 << 8)
#define DE_PIPEA_VBLANK (1 << 7)
#define DE_PIPEA_EVEN_FIELD (1 << 6)
#define DE_PIPEA_ODD_FIELD (1 << 5)
#define <API key> (1 << 4)
#define DE_PIPEA_VSYNC (1 << 3)
#define <API key> (1 << 0)
/* More Ivybridge lolz */
#define DE_ERR_DEBUG_IVB (1<<30)
#define DE_GSE_IVB (1<<29)
#define DE_PCH_EVENT_IVB (1<<28)
#define DE_DP_A_HOTPLUG_IVB (1<<27)
#define <API key> (1<<26)
#define <API key> (1<<9)
#define <API key> (1<<4)
#define <API key> (1<<8)
#define <API key> (1<<3)
#define DE_PIPEB_VBLANK_IVB (1<<5)
#define DE_PIPEA_VBLANK_IVB (1<<0)
#define DEISR 0x44000
#define DEIMR 0x44004
#define DEIIR 0x44008
#define DEIER 0x4400c
/* GT interrupt */
#define GT_PIPE_NOTIFY (1 << 4)
#define GT_SYNC_STATUS (1 << 2)
#define GT_USER_INTERRUPT (1 << 0)
#define <API key> (1 << 5)
#define <API key> (1 << 12)
#define <API key> (1 << 22)
#define GTISR 0x44010
#define GTIMR 0x44014
#define GTIIR 0x44018
#define GTIER 0x4401c
#define <API key> 0x42004
/* Required on all Ironlake and Sandybridge according to the B-Spec. */
#define <API key> (1 << 25)
#define ILK_DPARB_GATE (1<<22)
#define ILK_VSDPFD_FULL (1<<21)
#define <API key> 0x42014
#define <API key> (1<<31)
#define <API key> (1<<30)
#define <API key> (1<<29)
#define ILK_HDCP_DISABLE (1<<25)
#define ILK_eDP_A_DISABLE (1<<24)
#define ILK_DESKTOP (1<<23)
#define ILK_DSPCLK_GATE 0x42020
#define <API key> (1<<28)
#define ILK_DPARB_CLK_GATE (1<<5)
#define ILK_DPFD_CLK_GATE (1<<7)
/* According to spec this bit 7/8/9 of 0x42020 should be set to enable FBC */
#define ILK_CLK_FBC (1<<7)
#define ILK_DPFC_DIS1 (1<<8)
#define ILK_DPFC_DIS2 (1<<9)
#define DISP_ARB_CTL 0x45000
#define <API key> (1<<13)
#define DISP_FBC_WM_DIS (1<<15)
/* GEN7 chicken */
#define <API key> 0x7010
# define <API key> ((1<<10) | (1<<26))
#define GEN7_L3CNTLREG1 0xB01C
#define <API key> 0x3C4FFF8C
#define <API key> 0xB030
#define <API key> 0x20000000
/* <API key> */
#define <API key> 0x9030
#define <API key> (1<<11)
/* PCH */
/* south display engine interrupt */
#define SDE_AUDIO_POWER_D (1 << 27)
#define SDE_AUDIO_POWER_C (1 << 26)
#define SDE_AUDIO_POWER_B (1 << 25)
#define <API key> (25)
#define <API key> (7 << <API key>)
#define SDE_GMBUS (1 << 24)
#define <API key> (1 << 23)
#define <API key> (1 << 22)
#define SDE_AUDIO_HDCP_MASK (3 << 22)
#define SDE_AUDIO_TRANSB (1 << 21)
#define SDE_AUDIO_TRANSA (1 << 20)
#define <API key> (3 << 20)
#define SDE_POISON (1 << 19)
/* 18 reserved */
#define SDE_FDI_RXB (1 << 17)
#define SDE_FDI_RXA (1 << 16)
#define SDE_FDI_MASK (3 << 16)
#define SDE_AUXD (1 << 15)
#define SDE_AUXC (1 << 14)
#define SDE_AUXB (1 << 13)
#define SDE_AUX_MASK (7 << 13)
/* 12 reserved */
#define SDE_CRT_HOTPLUG (1 << 11)
#define SDE_PORTD_HOTPLUG (1 << 10)
#define SDE_PORTC_HOTPLUG (1 << 9)
#define SDE_PORTB_HOTPLUG (1 << 8)
#define SDE_SDVOB_HOTPLUG (1 << 6)
#define SDE_HOTPLUG_MASK (0xf << 8)
#define SDE_TRANSB_CRC_DONE (1 << 5)
#define SDE_TRANSB_CRC_ERR (1 << 4)
#define <API key> (1 << 3)
#define SDE_TRANSA_CRC_DONE (1 << 2)
#define SDE_TRANSA_CRC_ERR (1 << 1)
#define <API key> (1 << 0)
#define SDE_TRANS_MASK (0x3f)
/* CPT */
#define SDE_CRT_HOTPLUG_CPT (1 << 19)
#define <API key> (1 << 23)
#define <API key> (1 << 22)
#define <API key> (1 << 21)
#define <API key> (SDE_CRT_HOTPLUG_CPT | \
<API key> | \
<API key> | \
<API key>)
#define SDEISR 0xc4000
#define SDEIMR 0xc4004
#define SDEIIR 0xc4008
#define SDEIER 0xc400c
/* digital port hotplug */
#define PCH_PORT_HOTPLUG 0xc4030
#define <API key> (1 << 20)
#define <API key> (0)
#define <API key> (1 << 18)
#define <API key> (2 << 18)
#define <API key> (3 << 18)
#define <API key> (0)
#define <API key> (1 << 16)
#define <API key> (1 << 17)
#define <API key> (1 << 12)
#define <API key> (0)
#define <API key> (1 << 10)
#define <API key> (2 << 10)
#define <API key> (3 << 10)
#define <API key> (0)
#define <API key> (1 << 8)
#define <API key> (1 << 9)
#define <API key> (1 << 4)
#define <API key> (0)
#define <API key> (1 << 2)
#define <API key> (2 << 2)
#define <API key> (3 << 2)
#define <API key> (0)
#define <API key> (1 << 0)
#define <API key> (1 << 1)
#define PCH_GPIOA 0xc5010
#define PCH_GPIOB 0xc5014
#define PCH_GPIOC 0xc5018
#define PCH_GPIOD 0xc501c
#define PCH_GPIOE 0xc5020
#define PCH_GPIOF 0xc5024
#define PCH_GMBUS0 0xc5100
#define PCH_GMBUS1 0xc5104
#define PCH_GMBUS2 0xc5108
#define PCH_GMBUS3 0xc510c
#define PCH_GMBUS4 0xc5110
#define PCH_GMBUS5 0xc5120
#define _PCH_DPLL_A 0xc6014
#define _PCH_DPLL_B 0xc6018
#define PCH_DPLL(pipe) _PIPE(pipe, _PCH_DPLL_A, _PCH_DPLL_B)
#define _PCH_FPA0 0xc6040
#define FP_CB_TUNE (0x3<<22)
#define _PCH_FPA1 0xc6044
#define _PCH_FPB0 0xc6048
#define _PCH_FPB1 0xc604c
#define PCH_FP0(pipe) _PIPE(pipe, _PCH_FPA0, _PCH_FPB0)
#define PCH_FP1(pipe) _PIPE(pipe, _PCH_FPA1, _PCH_FPB1)
#define PCH_DPLL_TEST 0xc606c
#define PCH_DREF_CONTROL 0xC6200
#define DREF_CONTROL_MASK 0x7fc3
#define <API key> (0<<13)
#define <API key> (2<<13)
#define <API key> (3<<13)
#define <API key> (3<<13)
#define <API key> (0<<11)
#define <API key> (2<<11)
#define <API key> (3<<11)
#define <API key> (0<<9)
#define <API key> (1<<9)
#define <API key> (2<<9)
#define <API key> (3<<9)
#define <API key> (0<<7)
#define <API key> (2<<7)
#define <API key> (3<<7)
#define <API key> (0<<6)
#define <API key> (1<<6)
#define DREF_SSC1_DISABLE (0<<1)
#define DREF_SSC1_ENABLE (1<<1)
#define DREF_SSC4_DISABLE (0)
#define DREF_SSC4_ENABLE (1)
#define PCH_RAWCLK_FREQ 0xc6204
#define FDL_TP1_TIMER_SHIFT 12
#define FDL_TP1_TIMER_MASK (3<<12)
#define FDL_TP2_TIMER_SHIFT 10
#define FDL_TP2_TIMER_MASK (3<<10)
#define RAWCLK_FREQ_MASK 0x3ff
#define PCH_DPLL_TMR_CFG 0xc6208
#define PCH_SSC4_PARMS 0xc6210
#define PCH_SSC4_AUX_PARMS 0xc6214
#define PCH_DPLL_SEL 0xc7000
#define TRANSA_DPLL_ENABLE (1<<3)
#define TRANSA_DPLLB_SEL (1<<0)
#define TRANSA_DPLLA_SEL 0
#define TRANSB_DPLL_ENABLE (1<<7)
#define TRANSB_DPLLB_SEL (1<<4)
#define TRANSB_DPLLA_SEL (0)
#define TRANSC_DPLL_ENABLE (1<<11)
#define TRANSC_DPLLB_SEL (1<<8)
#define TRANSC_DPLLA_SEL (0)
/* transcoder */
#define _TRANS_HTOTAL_A 0xe0000
#define TRANS_HTOTAL_SHIFT 16
#define TRANS_HACTIVE_SHIFT 0
#define _TRANS_HBLANK_A 0xe0004
#define <API key> 16
#define <API key> 0
#define _TRANS_HSYNC_A 0xe0008
#define <API key> 16
#define <API key> 0
#define _TRANS_VTOTAL_A 0xe000c
#define TRANS_VTOTAL_SHIFT 16
#define TRANS_VACTIVE_SHIFT 0
#define _TRANS_VBLANK_A 0xe0010
#define <API key> 16
#define <API key> 0
#define _TRANS_VSYNC_A 0xe0014
#define <API key> 16
#define <API key> 0
#define _TRANSA_DATA_M1 0xe0030
#define _TRANSA_DATA_N1 0xe0034
#define _TRANSA_DATA_M2 0xe0038
#define _TRANSA_DATA_N2 0xe003c
#define _TRANSA_DP_LINK_M1 0xe0040
#define _TRANSA_DP_LINK_N1 0xe0044
#define _TRANSA_DP_LINK_M2 0xe0048
#define _TRANSA_DP_LINK_N2 0xe004c
#define _TRANS_HTOTAL_B 0xe1000
#define _TRANS_HBLANK_B 0xe1004
#define _TRANS_HSYNC_B 0xe1008
#define _TRANS_VTOTAL_B 0xe100c
#define _TRANS_VBLANK_B 0xe1010
#define _TRANS_VSYNC_B 0xe1014
#define TRANS_HTOTAL(pipe) _PIPE(pipe, _TRANS_HTOTAL_A, _TRANS_HTOTAL_B)
#define TRANS_HBLANK(pipe) _PIPE(pipe, _TRANS_HBLANK_A, _TRANS_HBLANK_B)
#define TRANS_HSYNC(pipe) _PIPE(pipe, _TRANS_HSYNC_A, _TRANS_HSYNC_B)
#define TRANS_VTOTAL(pipe) _PIPE(pipe, _TRANS_VTOTAL_A, _TRANS_VTOTAL_B)
#define TRANS_VBLANK(pipe) _PIPE(pipe, _TRANS_VBLANK_A, _TRANS_VBLANK_B)
#define TRANS_VSYNC(pipe) _PIPE(pipe, _TRANS_VSYNC_A, _TRANS_VSYNC_B)
#define _TRANSB_DATA_M1 0xe1030
#define _TRANSB_DATA_N1 0xe1034
#define _TRANSB_DATA_M2 0xe1038
#define _TRANSB_DATA_N2 0xe103c
#define _TRANSB_DP_LINK_M1 0xe1040
#define _TRANSB_DP_LINK_N1 0xe1044
#define _TRANSB_DP_LINK_M2 0xe1048
#define _TRANSB_DP_LINK_N2 0xe104c
#define TRANSDATA_M1(pipe) _PIPE(pipe, _TRANSA_DATA_M1, _TRANSB_DATA_M1)
#define TRANSDATA_N1(pipe) _PIPE(pipe, _TRANSA_DATA_N1, _TRANSB_DATA_N1)
#define TRANSDATA_M2(pipe) _PIPE(pipe, _TRANSA_DATA_M2, _TRANSB_DATA_M2)
#define TRANSDATA_N2(pipe) _PIPE(pipe, _TRANSA_DATA_N2, _TRANSB_DATA_N2)
#define TRANSDPLINK_M1(pipe) _PIPE(pipe, _TRANSA_DP_LINK_M1, _TRANSB_DP_LINK_M1)
#define TRANSDPLINK_N1(pipe) _PIPE(pipe, _TRANSA_DP_LINK_N1, _TRANSB_DP_LINK_N1)
#define TRANSDPLINK_M2(pipe) _PIPE(pipe, _TRANSA_DP_LINK_M2, _TRANSB_DP_LINK_M2)
#define TRANSDPLINK_N2(pipe) _PIPE(pipe, _TRANSA_DP_LINK_N2, _TRANSB_DP_LINK_N2)
#define _TRANSACONF 0xf0008
#define _TRANSBCONF 0xf1008
#define TRANSCONF(plane) _PIPE(plane, _TRANSACONF, _TRANSBCONF)
#define TRANS_DISABLE (0<<31)
#define TRANS_ENABLE (1<<31)
#define TRANS_STATE_MASK (1<<30)
#define TRANS_STATE_DISABLE (0<<30)
#define TRANS_STATE_ENABLE (1<<30)
#define <API key> (0<<27)
#define <API key> (1<<27)
#define <API key> (2<<27)
#define <API key> (3<<27)
#define TRANS_DP_AUDIO_ONLY (1<<26)
#define <API key> (0<<26)
#define TRANS_PROGRESSIVE (0<<21)
#define TRANS_8BPC (0<<5)
#define TRANS_10BPC (1<<5)
#define TRANS_6BPC (2<<5)
#define TRANS_12BPC (3<<5)
#define SOUTH_CHICKEN2 0xc2004
#define <API key> (1<<0)
#define _FDI_RXA_CHICKEN 0xc200c
#define _FDI_RXB_CHICKEN 0xc2010
#define <API key> (1<<1)
#define <API key> (1<<0)
#define FDI_RX_CHICKEN(pipe) _PIPE(pipe, _FDI_RXA_CHICKEN, _FDI_RXB_CHICKEN)
#define SOUTH_DSPCLK_GATE_D 0xc2020
#define <API key> (1<<29)
/* CPU: FDI_TX */
#define _FDI_TXA_CTL 0x60100
#define _FDI_TXB_CTL 0x61100
#define FDI_TX_CTL(pipe) _PIPE(pipe, _FDI_TXA_CTL, _FDI_TXB_CTL)
#define FDI_TX_DISABLE (0<<31)
#define FDI_TX_ENABLE (1<<31)
#define <API key> (0<<28)
#define <API key> (1<<28)
#define <API key> (2<<28)
#define FDI_LINK_TRAIN_NONE (3<<28)
#define <API key> (0<<25)
#define <API key> (1<<25)
#define <API key> (2<<25)
#define <API key> (3<<25)
#define <API key> (0<<22)
#define <API key> (1<<22)
#define <API key> (2<<22)
#define <API key> (3<<22)
/* ILK always use 400mV 0dB for voltage swing and pre-emphasis level.
SNB has different settings. */
/* SNB A-stepping */
#define <API key> (0x38<<22)
#define <API key> (0x02<<22)
#define <API key> (0x01<<22)
#define <API key> (0x0<<22)
/* SNB B-stepping */
#define <API key> (0x0<<22)
#define <API key> (0x3a<<22)
#define <API key> (0x39<<22)
#define <API key> (0x38<<22)
#define <API key> (0x3f<<22)
#define <API key> (0<<19)
#define <API key> (1<<19)
#define <API key> (2<<19)
#define <API key> (3<<19)
#define <API key> (1<<18)
/* Ironlake: hardwired to 1 */
#define FDI_TX_PLL_ENABLE (1<<14)
/* Ivybridge has different bits for lolz */
#define <API key> (0<<8)
#define <API key> (1<<8)
#define <API key> (2<<8)
#define <API key> (3<<8)
/* both Tx and Rx */
#define FDI_COMPOSITE_SYNC (1<<11)
#define FDI_LINK_TRAIN_AUTO (1<<10)
#define <API key> (0<<7)
#define <API key> (1<<7)
/* FDI_RX, FDI_X is hard-wired to Transcoder_X */
#define _FDI_RXA_CTL 0xf000c
#define _FDI_RXB_CTL 0xf100c
#define FDI_RX_CTL(pipe) _PIPE(pipe, _FDI_RXA_CTL, _FDI_RXB_CTL)
#define FDI_RX_ENABLE (1<<31)
/* train, dp width same as FDI_TX */
#define FDI_FS_ERRC_ENABLE (1<<27)
#define FDI_FE_ERRC_ENABLE (1<<26)
#define <API key> (7<<19)
#define FDI_8BPC (0<<16)
#define FDI_10BPC (1<<16)
#define FDI_6BPC (2<<16)
#define FDI_12BPC (3<<16)
#define <API key> (1<<15)
#define <API key> (1<<14)
#define FDI_RX_PLL_ENABLE (1<<13)
#define <API key> (1<<11)
#define <API key> (1<<10)
#define <API key> (1<<9)
#define <API key> (1<<8)
#define <API key> (1<<6)
#define FDI_PCDCLK (1<<4)
/* CPT */
#define FDI_AUTO_TRAINING (1<<10)
#define <API key> (0<<8)
#define <API key> (1<<8)
#define <API key> (2<<8)
#define <API key> (3<<8)
#define <API key> (3<<8)
#define _FDI_RXA_MISC 0xf0010
#define _FDI_RXB_MISC 0xf1010
#define _FDI_RXA_TUSIZE1 0xf0030
#define _FDI_RXA_TUSIZE2 0xf0038
#define _FDI_RXB_TUSIZE1 0xf1030
#define _FDI_RXB_TUSIZE2 0xf1038
#define FDI_RX_MISC(pipe) _PIPE(pipe, _FDI_RXA_MISC, _FDI_RXB_MISC)
#define FDI_RX_TUSIZE1(pipe) _PIPE(pipe, _FDI_RXA_TUSIZE1, _FDI_RXB_TUSIZE1)
#define FDI_RX_TUSIZE2(pipe) _PIPE(pipe, _FDI_RXA_TUSIZE2, _FDI_RXB_TUSIZE2)
/* FDI_RX interrupt register format */
#define <API key> (1<<10)
#define FDI_RX_SYMBOL_LOCK (1<<9) /* train 2 */
#define FDI_RX_BIT_LOCK (1<<8) /* train 1 */
#define <API key> (1<<7)
#define FDI_RX_FS_CODE_ERR (1<<6)
#define FDI_RX_FE_CODE_ERR (1<<5)
#define <API key> (1<<4)
#define <API key> (1<<3)
#define <API key> (1<<2)
#define <API key> (1<<1)
#define <API key> (1<<0)
#define _FDI_RXA_IIR 0xf0014
#define _FDI_RXA_IMR 0xf0018
#define _FDI_RXB_IIR 0xf1014
#define _FDI_RXB_IMR 0xf1018
#define FDI_RX_IIR(pipe) _PIPE(pipe, _FDI_RXA_IIR, _FDI_RXB_IIR)
#define FDI_RX_IMR(pipe) _PIPE(pipe, _FDI_RXA_IMR, _FDI_RXB_IMR)
#define FDI_PLL_CTL_1 0xfe000
#define FDI_PLL_CTL_2 0xfe004
/* CRT */
#define PCH_ADPA 0xe1100
#define <API key> (1<<30)
#define ADPA_TRANS_A_SELECT 0
#define ADPA_TRANS_B_SELECT (1<<30)
#define <API key> 0x03ff0000 /* bit 25-16 */
#define <API key> (0<<24)
#define <API key> (3<<24)
#define <API key> (3<<24)
#define <API key> (2<<24)
#define <API key> (1<<23)
#define <API key> (0<<22)
#define <API key> (1<<22)
#define <API key> (0<<21)
#define <API key> (1<<21)
#define <API key> (0<<20)
#define <API key> (1<<20)
#define <API key> (0<<18)
#define <API key> (1<<18)
#define <API key> (2<<18)
#define <API key> (3<<18)
#define <API key> (0<<17)
#define <API key> (1<<17)
#define <API key> (1<<16)
#define ADPA_PIPE_ENABLED(V, P) \
(((V) & (<API key> | ADPA_DAC_ENABLE)) == ((P) << 30 | ADPA_DAC_ENABLE))
/* or SDVOB */
#define HDMIB 0xe1140
#define PORT_ENABLE (1 << 31)
#define TRANSCODER_A (0)
#define TRANSCODER_B (1 << 30)
#define TRANSCODER_MASK (1 << 30)
#define COLOR_FORMAT_8bpc (0)
#define COLOR_FORMAT_12bpc (3 << 26)
#define <API key> (1 << 23)
#define SDVO_ENCODING (0)
#define TMDS_ENCODING (2 << 10)
#define <API key> (1 << 9)
/* CPT */
#define HDMI_MODE_SELECT (1 << 9)
#define DVI_MODE_SELECT (0)
#define SDVOB_BORDER_ENABLE (1 << 7)
#define AUDIO_ENABLE (1 << 6)
#define VSYNC_ACTIVE_HIGH (1 << 4)
#define HSYNC_ACTIVE_HIGH (1 << 3)
#define PORT_DETECTED (1 << 2)
#define HDMI_PIPE_ENABLED(V, P) \
(((V) & (TRANSCODER_MASK | PORT_ENABLE)) == ((P) << 30 | PORT_ENABLE))
/* PCH SDVOB multiplex with HDMIB */
#define PCH_SDVOB HDMIB
#define HDMIC 0xe1150
#define HDMID 0xe1160
#define PCH_LVDS 0xe1180
#define LVDS_DETECTED (1 << 1)
#define BLC_PWM_CPU_CTL2 0x48250
#define PWM_ENABLE (1 << 31)
#define PWM_PIPE_A (0 << 29)
#define PWM_PIPE_B (1 << 29)
#define BLC_PWM_CPU_CTL 0x48254
#define BLC_PWM_PCH_CTL1 0xc8250
#define PWM_PCH_ENABLE (1 << 31)
#define <API key> (1 << 29)
#define <API key> (0 << 29)
#define <API key> (1 << 28)
#define <API key> (0 << 28)
#define BLC_PWM_PCH_CTL2 0xc8254
#define PCH_PP_STATUS 0xc7200
#define PCH_PP_CONTROL 0xc7204
#define PANEL_UNLOCK_REGS (0xabcd << 16)
#define EDP_FORCE_VDD (1 << 3)
#define EDP_BLC_ENABLE (1 << 2)
#define PANEL_POWER_RESET (1 << 1)
#define PANEL_POWER_OFF (0 << 0)
#define PANEL_POWER_ON (1 << 0)
#define PCH_PP_ON_DELAYS 0xc7208
#define EDP_PANEL (1 << 30)
#define PCH_PP_OFF_DELAYS 0xc720c
#define PCH_PP_DIVISOR 0xc7210
#define PCH_DP_B 0xe4100
#define PCH_DPB_AUX_CH_CTL 0xe4110
#define <API key> 0xe4114
#define <API key> 0xe4118
#define <API key> 0xe411c
#define <API key> 0xe4120
#define <API key> 0xe4124
#define PCH_DP_C 0xe4200
#define PCH_DPC_AUX_CH_CTL 0xe4210
#define <API key> 0xe4214
#define <API key> 0xe4218
#define <API key> 0xe421c
#define <API key> 0xe4220
#define <API key> 0xe4224
#define PCH_DP_D 0xe4300
#define PCH_DPD_AUX_CH_CTL 0xe4310
#define <API key> 0xe4314
#define <API key> 0xe4318
#define <API key> 0xe431c
#define <API key> 0xe4320
#define <API key> 0xe4324
/* CPT */
#define <API key> 0
#define <API key> (1<<29)
#define <API key> (2<<29)
#define PORT_TRANS_SEL_MASK (3<<29)
#define TRANS_DP_CTL_A 0xe0300
#define TRANS_DP_CTL_B 0xe1300
#define TRANS_DP_CTL_C 0xe2300
#define TRANS_DP_CTL(pipe) (TRANS_DP_CTL_A + (pipe) * 0x01000)
#define <API key> (1<<31)
#define TRANS_DP_PORT_SEL_B (0<<29)
#define TRANS_DP_PORT_SEL_C (1<<29)
#define TRANS_DP_PORT_SEL_D (2<<29)
#define <API key> (3<<29)
#define <API key> (3<<29)
#define TRANS_DP_AUDIO_ONLY (1<<26)
#define <API key> (1<<18)
#define TRANS_DP_8BPC (0<<9)
#define TRANS_DP_10BPC (1<<9)
#define TRANS_DP_6BPC (2<<9)
#define TRANS_DP_12BPC (3<<9)
#define TRANS_DP_BPC_MASK (3<<9)
#define <API key> (1<<4)
#define <API key> 0
#define <API key> (1<<3)
#define <API key> 0
#define TRANS_DP_SYNC_MASK (3<<3)
/* SNB eDP training params */
/* SNB A-stepping */
#define <API key> (0x38<<22)
#define <API key> (0x02<<22)
#define <API key> (0x01<<22)
#define <API key> (0x0<<22)
/* SNB B-stepping */
#define <API key> (0x0<<22)
#define <API key> (0x1<<22)
#define <API key> (0x3a<<22)
#define <API key> (0x39<<22)
#define <API key> (0x38<<22)
#define <API key> (0x3f<<22)
#define FORCEWAKE 0xA18C
#define FORCEWAKE_ACK 0x130090
#define <API key> 0x120008
#define GEN6_UCGCTL2 0x9404
# define <API key> (1 << 13)
# define <API key> (1 << 12)
# define <API key> (1 << 11)
#define GEN6_RPNSWREQ 0xA008
#define GEN6_TURBO_DISABLE (1<<31)
#define GEN6_FREQUENCY(x) ((x)<<25)
#define GEN6_OFFSET(x) ((x)<<19)
#define <API key> (0<<15)
#define GEN6_RC_VIDEO_FREQ 0xA00C
#define GEN6_RC_CONTROL 0xA090
#define <API key> (1<<16)
#define <API key> (1<<17)
#define <API key> (1<<18)
#define <API key> (1<<20)
#define <API key> (1<<22)
#define GEN6_RC_CTL_EI_MODE(x) ((x)<<27)
#define <API key> (1<<31)
#define <API key> 0xA010
#define <API key> 0xA014
#define GEN6_RPSTAT1 0xA01C
#define GEN6_CAGF_SHIFT 8
#define GEN6_CAGF_MASK (0x7f << GEN6_CAGF_SHIFT)
#define GEN6_RP_CONTROL 0xA024
#define GEN6_RP_MEDIA_TURBO (1<<11)
#define <API key> (1<<9)
#define <API key> (1<<8)
#define GEN6_RP_ENABLE (1<<7)
#define GEN6_RP_UP_IDLE_MIN (0x1<<3)
#define GEN6_RP_UP_BUSY_AVG (0x2<<3)
#define <API key> (0x4<<3)
#define <API key> (0x1<<0)
#define <API key> 0xA02C
#define <API key> 0xA030
#define GEN6_RP_CUR_UP_EI 0xA050
#define GEN6_CURICONT_MASK 0xffffff
#define GEN6_RP_CUR_UP 0xA054
#define <API key> 0xffffff
#define GEN6_RP_PREV_UP 0xA058
#define GEN6_RP_CUR_DOWN_EI 0xA05C
#define GEN6_CURIAVG_MASK 0xffffff
#define GEN6_RP_CUR_DOWN 0xA060
#define GEN6_RP_PREV_DOWN 0xA064
#define GEN6_RP_UP_EI 0xA068
#define GEN6_RP_DOWN_EI 0xA06C
#define <API key> 0xA070
#define GEN6_RC_STATE 0xA094
#define <API key> 0xA098
#define <API key> 0xA09C
#define <API key> 0xA0A0
#define <API key> 0xA0A8
#define <API key> 0xA0AC
#define GEN6_RC_SLEEP 0xA0B0
#define GEN6_RC1e_THRESHOLD 0xA0B4
#define GEN6_RC6_THRESHOLD 0xA0B8
#define GEN6_RC6p_THRESHOLD 0xA0BC
#define <API key> 0xA0C0
#define GEN6_PMINTRMSK 0xA168
#define GEN6_PMISR 0x44020
#define GEN6_PMIMR 0x44024 /* rps_lock */
#define GEN6_PMIIR 0x44028
#define GEN6_PMIER 0x4402C
#define GEN6_PM_MBOX_EVENT (1<<25)
#define <API key> (1<<24)
#define <API key> (1<<6)
#define <API key> (1<<5)
#define <API key> (1<<4)
#define <API key> (1<<2)
#define <API key> (1<<1)
#define <API key> (<API key> | \
<API key> | \
<API key>)
#define GEN6_PCODE_MAILBOX 0x138124
#define GEN6_PCODE_READY (1<<31)
#define GEN6_READ_OC_PARAMS 0xc
#define <API key> 0x9
#define GEN6_PCODE_DATA 0x138128
#endif /* _I915_REG_H_ */ |
import {AjxCallback} from "../../ajax/boot/AjxCallback";
import {DwtKeyMapMgr} from "../../ajax/dwt/keyboard/DwtKeyMapMgr";
import {DwtToolBarButton} from "../../ajax/dwt/widgets/DwtToolBar";
import {AjxSoapDoc} from "../../ajax/soap/AjxSoapDoc";
import {ZmCsfeResult} from "../../zimbra/csfe/ZmCsfeResult";
import {ZmController} from "../share/controller/ZmController";
import {ZmAppChooser} from "../share/view/ZmAppChooser";
import {ZmToolBar} from "../share/view/ZmToolBar";
import {ZmApp} from "./ZmApp";
import {ZmAppViewMgr} from "./ZmAppViewMgr";
import {<API key>} from "./ZmRequestMgr";
export class ZmZimbraMail extends ZmController {
public static unloadHackCallback(): void {}
private mRequestResponse: ZmCsfeResult;
public sendRequest(params: <API key>): string | ZmCsfeResult {
if (
typeof params.callback !== "undefined"
&& typeof this.mRequestResponse !== "undefined"
) {
params.callback.run(this.mRequestResponse);
}
return undefined;
}
public cancelRequest(reqId: string, errorCallback?: AjxCallback, noBusyOverlay?: boolean): void {}
public getKeyMapMgr(): DwtKeyMapMgr {
return undefined;
}
// Only for tests TODO: wut?
public setRequestResponse(resp: ZmCsfeResult) {
this.mRequestResponse = resp;
}
public getNewButton(): DwtToolBarButton {
return undefined;
}
public setNewButtonProps(params: <API key>): void {}
public getAppChooser(): ZmAppChooser { return undefined; }
public addApp(app: ZmApp): void {}
public getAppViewMgr(): ZmAppViewMgr { return undefined; }
}
export interface <API key> extends <API key> {
soapDoc?: AjxSoapDoc;
jsonObj?: {[request: string]: any};
asyncMode?: boolean;
busyMsg?: string;
callback?: AjxCallback;
errorCallback?: AjxCallback;
noBusyOverlay?: boolean;
noAuthToken?: boolean;
}
export interface <API key> {
text?: string;
tooltip?: string;
icon?: string;
iconDis?: string;
defaultId?: string;
disabled?: boolean;
hidden?: boolean;
} |
package ie.ucd.srg.logica.eplatform.eventhandling;
/**
* @author Alan Morkan
*/
public class DefaultEvent extends Event{
/**
*
* @param s
* @param i
*/
//@ requires s != null;
//@ requires i > 0;
public DefaultEvent(String s, int i){
//@ assert false;
super(s,i);
}
} |
<?php
/*
Template Name: Category Temples
*/
@session_start();
global $wpdb,$post;
$prefix=$wpdb->base_prefix;
get_header();
$category_id='';
$title='';
if(isset($_REQUEST['cid']) && trim($_REQUEST['cid'])!='' && trim($_REQUEST['cid'])>0)
{
$category_id=$_REQUEST['cid'];
$category=Categorydetail($category_id);
if(count($category)>0){$title=$category[0]->category;}
}
?>
<div class="container">
<?php get_sidebar(); ?>
<div class="mid_content">
<h1><?php _e($title); ?></h1>
<div class="science_box">
<div class="all_temple1">
<?php while (have_posts()) : the_post();
the_content();
endwhile; ?>
</div>
</div>
<div class="clr"></div>
<?php
?>
<?php _e(category_temples($category_id)); ?>
</div>
<?php get_sidebar('right'); ?>
<div class="clr"></div>
</div>
<?php
get_footer(); |
<?php
/**
* Pay for order form
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
?>
<form id="order_review" method="post">
<table class="shop_table">
<thead>
<tr>
<th class="product-name"><?php _e( 'Tên sản phẩm', 'woocommerce' ); ?></th>
<th class="product-quantity"><?php _e( 'Số lượng', 'woocommerce' ); ?></th>
<th class="product-total"><?php _e( 'Tổng cộng', 'woocommerce' ); ?></th>
</tr>
</thead>
<tbody>
<?php
if ( sizeof( $order->get_items() ) > 0 ) :
foreach ( $order->get_items() as $item ) :
echo '
<tr>
<td class="product-name">' . $item['name'].'</td>
<td class="product-quantity">' . $item['qty'].'</td>
<td class="product-subtotal">' . $order-><API key>( $item ) . '</td>
</tr>';
endforeach;
endif;
?>
</tbody>
<tfoot>
<?php
if ( $totals = $order-><API key>() ) foreach ( $totals as $total ) :
?>
<tr>
<th scope="row" colspan="2"><?php echo $total['label']; ?></th>
<td class="product-total"><?php echo $total['value']; ?></td>
</tr>
<?php
endforeach;
?>
</tfoot>
</table>
<div id="payment">
<?php if ( $order->needs_payment() ) : ?>
<h3><?php _e( 'Phương thức trả', 'woocommerce' ); ?></h3>
<ul class="payment_methods methods">
<?php
if ( $available_gateways = WC()->payment_gateways-><API key>() ) {
// Chosen Method
if ( sizeof( $available_gateways ) )
current( $available_gateways )->set_current();
foreach ( $available_gateways as $gateway ) {
?>
<li class="payment_method_<?php echo $gateway->id; ?>">
<input id="payment_method_<?php echo $gateway->id; ?>" type="radio" class="input-radio" name="payment_method" value="<?php echo esc_attr( $gateway->id ); ?>" <?php checked( $gateway->chosen, true ); ?> <API key>="<?php echo esc_attr( $gateway->order_button_text ); ?>" />
<label for="payment_method_<?php echo $gateway->id; ?>"><?php echo $gateway->get_title(); ?> <?php echo $gateway->get_icon(); ?></label>
<?php
if ( $gateway->has_fields() || $gateway->get_description() ) {
echo '<div class="payment_box payment_method_' . $gateway->id . '" style="display:none;">';
$gateway->payment_fields();
echo '</div>';
}
?>
</li>
<?php
}
} else {
echo '<p>' . __( 'Sorry, it seems that there are no available payment methods for your location. Please contact us if you require assistance or wish to make alternate arrangements.', 'woocommerce' ) . '</p>';
}
?>
</ul>
<?php endif; ?>
<div class="form-row">
<?php wp_nonce_field( 'woocommerce-pay' ); ?>
<?php
$<API key> = apply_filters( '<API key>', __( 'Pay for order', 'woocommerce' ) );
echo apply_filters( '<API key>', '<input type="submit" class="button alt" id="place_order" value="' . esc_attr( $<API key> ) . '" data-value="' . esc_attr( $<API key> ) . '" />' );
?>
<input type="hidden" name="woocommerce_pay" value="1" />
</div>
</div>
</form> |
package com.caucho.vfs.memory;
import com.caucho.vfs.Vfs;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
/**
* URL memory handler.
*/
class MemoryURLConnection extends URLConnection {
MemoryURLConnection(URL url)
{
super(url);
}
public void connect()
{
}
public InputStream getInputStream()
throws IOException
{
return Vfs.lookup().lookup(url.toString()).openRead();
}
public OutputStream getOutputStream()
throws IOException
{
return Vfs.lookup().lookup(url.toString()).openWrite();
}
} |
package io.github.mzmine.modules.dataprocessing.<API key>.lipidutils;
import io.github.mzmine.modules.dataprocessing.<API key>.<API key>.<API key>;
import io.github.mzmine.modules.dataprocessing.<API key>.lipids.<API key>;
import io.github.mzmine.modules.dataprocessing.<API key>.lipids.LipidCategories;
import io.github.mzmine.modules.dataprocessing.<API key>.lipids.LipidClasses;
import io.github.mzmine.modules.dataprocessing.<API key>.lipids.LipidMainClasses;
public class LipidParsingUtils {
public static <API key> <API key>(
String <API key>) {
<API key>[] <API key> =
<API key>.class.getEnumConstants();
for (<API key> <API key> : <API key>) {
if (<API key>.name().equals(<API key>)) {
return <API key>;
}
}
return null;
}
public static <API key> <API key>(
String <API key>) {
<API key>[] <API key> = <API key>.class.getEnumConstants();
for (<API key> <API key> : <API key>) {
if (<API key>.name().equals(<API key>)) {
return <API key>;
}
}
return null;
}
public static LipidCategories <API key>(String lipidCategoryName) {
LipidCategories[] lipidCategories = LipidCategories.class.getEnumConstants();
for (LipidCategories lipidCategory : lipidCategories) {
if (lipidCategory.name().equals(lipidCategoryName)) {
return lipidCategory;
}
}
return null;
}
public static LipidMainClasses <API key>(
String lipidMainClassName) {
LipidMainClasses[] lipidMainClasses = LipidMainClasses.class.getEnumConstants();
for (LipidMainClasses lipidMainClass : lipidMainClasses) {
if (lipidMainClass.name().equals(lipidMainClassName)) {
return lipidMainClass;
}
}
return null;
}
public static LipidChainType <API key>(String lipidChainTypeName) {
LipidChainType[] lipidChainTypes = LipidChainType.class.getEnumConstants();
for (LipidChainType lipidChainType : lipidChainTypes) {
if (lipidChainType.name().equals(lipidChainTypeName)) {
return lipidChainType;
}
}
return null;
}
public static LipidClasses <API key>(String lipidClassName) {
LipidClasses[] lipidClasses = LipidClasses.class.getEnumConstants();
for (LipidClasses lipidClass : lipidClasses) {
if (lipidClass.getName().equals(lipidClassName)) {
return lipidClass;
}
}
return null;
}
} |
var _globalSpeed = null;
function initParallax() {
//duplicate and place an image tag
var _targetContainer = $(".parallax");
var _bgImg = _targetContainer.css("background-image");
//var _bgURL = _bgImg.substring(_bgImg.indexOf("(")+1,_bgImg.lastIndexOf(")"));
var _parallaxImg = "<div class='<API key>'></div>";
_targetContainer.append(_parallaxImg);
function setParallaxSize(){
var _headerOffset = $("header").css("position") === "relative" ? $("header").outerHeight() : 0;
$(".<API key>").css({
"width" : _targetContainer.outerWidth(),
"height" : _targetContainer.outerHeight() + _headerOffset,
"backgroundImage" : _bgImg
});
$(".<API key>").css("top",function(){
var _headerOffset = 0;
var _offset = $(this).offset();
var _top = _offset.top;
var _style = _top + _headerOffset;
return _style;
});
}
setParallaxSize();
_targetContainer.removeAttr("style");//remove the original
//bind to scroll
//var _speed = 0.5;
var _speed = _globalSpeed!==null ? _globalSpeed : 0.5;
function handleScroll(){
var _headerOffset = 0;
$(".<API key>").css("top", function(){
var _newPos = (-($(window).scrollTop())*_speed) + _headerOffset;
return _newPos;
});
}
$(window).scroll( handleScroll );
$(window).resize( setParallaxSize );
}
function getBackgroundPos(obj) {
var pos = obj.css("background-position");
if (pos === 'undefined' || pos === null) {
pos = [obj.css("<API key>"),obj.css("<API key>")];//i hate IE!!
} else {
pos = pos.split(" ");
}
return {
x: parseFloat(pos[0]),
xUnit: pos[0].replace(/[0-9-.]/g, ""),
y: parseFloat(pos[1]),
yUnit: pos[1].replace(/[0-9-.]/g, "")
};
}
function initPosMessage() {
$(".branding-box").each(function(){
var _this = $(this);
var _origPos,
_winWidth,
_winHeight,
//_ratio,
_contentHeight,
_imgHeight,
_speed,
_distance,
_paralax;
function handleResize(){
_origPos = getBackgroundPos(_this).y;
_winWidth = $(window).width();
_winHeight = $(window).height();
//_ratio = 505/1300;
_contentHeight = _this.height();
_imgHeight = 1.2*_contentHeight;
_distance = _imgHeight - _contentHeight;
_speed = _distance/_winHeight;
_globalSpeed = _speed;
if(_winWidth > _winHeight){
_paralax = true;
} else {
_paralax = false;
}
}
function handleScroll(){
if(_paralax === true){
//var _newPos = "center " + -(($(window).scrollTop()*_globalSpeed)) + "px";
var _newPosX = "50%";
var _newPosY = -(($(window).scrollTop()*_globalSpeed)) + "px";
_this.css({
"<API key>": _newPosX,
"<API key>": _newPosY
});
} else {
_this.css({
"<API key>": "40%",
"<API key>": "50%"
});
}
}
handleScroll();
handleResize();
$(window).scroll( handleScroll );
$(window).resize( handleResize );
});
}
function initFooter() {
var _origPos,
_winWidth,
_winHeight,
_ratio,
_contentHeight,
_imgHeight,
_speed,
_distance,
_paralax;
function handleResize(){
_origPos = getBackgroundPos($(".sub-footer")).y;
_winWidth = $(window).width();
_winHeight = $(window).height();
_ratio = 1350/1200;
_contentHeight = $("#container").height();
_imgHeight = _ratio*_winWidth;
_distance = _imgHeight - _winHeight;
_speed = _distance/_contentHeight;
if(_winWidth > _winHeight){
_paralax = true;
} else {
_paralax = false;
}
}
function handleScroll(){
if(_paralax === true){
var _newPosX = "50%";
var _newPosY = -(($(window).scrollTop()*_speed)) + "px";
$(".sub-footer").css({
"<API key>": _newPosX,
"<API key>": _newPosY
});
/*
var _newPos = "center " + -(($(window).scrollTop()*_speed)) + "px";
$(".sub-footer").css({
"background-position": _newPos
});
*/
}
}
handleScroll();
handleResize();
$(window).scroll( handleScroll );
$(window).resize( handleResize );
}
function initMobileTrigger() {
$(".nav-trigger").click(function(e) {
e.preventDefault();
$("body").toggleClass("mobile-nav-open");
});
}
function initCarousel() {
$(".carousel").each(function(index){
//set some vars
var _this = $(this);
var _items = _this.find(".carousel-item");
var _itemCount = _items.length;
var _pageCount = 1;
var _itemsPerPage = 1;
var _parentSection = _this.parent();
var _currentPage = 1;
var _wrapperWidth, _itemWidth, _itemPadding, _carouselWidth, _navDots = "";
//create a wrapper
var _carouselID = "carousel_" + index;
var _wrapper = "<div class='carousel-wrapper' id='" + _carouselID + "'></div>";
//place carousel into wrapper
_this.wrap(_wrapper);
var _setSize = function(){
_wrapperWidth = _this.parent().outerWidth();
if($(window).outerWidth() < 620){//small
_itemPadding = _wrapperWidth * 0.02;
_itemWidth = _wrapperWidth * 0.9 + _itemPadding;
_carouselWidth = _itemWidth * _itemCount;
_itemsPerPage = 1;
} else {//medium, large and ex-large
_itemPadding = _wrapperWidth * 0.02;
_itemWidth = _wrapperWidth/4 + _itemPadding/4;
_carouselWidth = _itemWidth * _itemCount;
_itemsPerPage = 4;
}
_pageCount = Math.ceil(_itemCount/_itemsPerPage);
//set carousel width and item width
_items.each(function(){
$(this).css({
"width": _itemWidth,
"paddingRight": _itemPadding
});
});
_this.width(_carouselWidth);
_this.css("left",0);
_currentPage = 1;
};
//_setSize();
function navigateItem(event){
var _arg = event.data.directive;
var _caller = event.target;
var _target;
if(event.data.swipeTarget){
_target = event.data.swipeTarget;
} else {
_target = $(_caller).attr("data-carousel");
}
var _targetObj = $("#" + _target).find(".carousel").first();
var _distance = parseInt(_itemWidth * _itemsPerPage);
var _currentPos = parseInt(_targetObj.css("left"));
var _maxScroll = _distance * (_pageCount-1);
var _index = $(_caller).attr("data-index");
var _newPos;
if(_arg === "moveNext"){
if(_currentPos > -(_maxScroll)){
_newPos = _currentPos - _distance;
_targetObj.css({
"left": _newPos
});
_currentPage += 1;
updateNavDots();
}
} else if(_arg === "movePrev"){
if(_currentPos < 0){
_newPos = _currentPos + _distance;
_targetObj.css({
"left": _newPos
});
_currentPage -= 1;
updateNavDots();
}
} else if(_arg === "jump"){
_newPos = -(_distance*_index);
_targetObj.css({
"left": _newPos
});
_currentPage = parseInt(_index) + 1;
updateNavDots();
}
}
//create the number of dots
function drawNavDots(){
$("#navDots_" + _carouselID).remove();
_navDots = "";
for (var i=0; i<_pageCount; i++){
if (i === 0) {
_navDots += "<span class='nav-dot-current' data-index='" + i + "' data-carousel='" + _carouselID + "'></span>";
} else {
_navDots += "<span data-index='" + i + "' data-carousel='" + _carouselID + "'></span>";
}
}
$("<div id='navDots_" + _carouselID + "' class='nav-dots'>" + _navDots + "</div>").appendTo(_parentSection);
$("#navDots_" + _carouselID).find("span").click({directive:"jump"},navigateItem);
}
//drawNavDots();
//create controls
$("<div id='scrollControls_" + _carouselID + "' class='scrollControls'><div class='scroll-btn-prev' data-carousel='" + _carouselID + "'><span>prev</span></div><div class='scroll-btn-next' data-carousel='" + _carouselID + "'><span>next</span></div></div>").appendTo(_parentSection);
//set swipe
var _swipeArea = $("#" + _carouselID).hammer();
_swipeArea.on("swipeleft",{directive:"moveNext",swipeTarget:_carouselID},navigateItem);
_swipeArea.on("swiperight",{directive:"movePrev",swipeTarget:_carouselID},navigateItem);
_swipeArea.on("touch", function(ev) {
ev.gesture.preventDefault();
});
//set arrow clicks
$("#scrollControls_" + _carouselID).find(".scroll-btn-prev").click({directive:"movePrev"},navigateItem);
$("#scrollControls_" + _carouselID).find(".scroll-btn-next").click({directive:"moveNext"},navigateItem);
//update the nav dots
function updateNavDots(){
$("#navDots_" + _carouselID).find("span").each(function(){
var _this = $(this);
$(this).removeClass("nav-dot-current");
if(parseInt(_this.attr("data-index")) === parseInt(_currentPage-1)){
_this.addClass("nav-dot-current");
}
});
}
$(window).resize( function(){
_setSize();
drawNavDots();
}).trigger("resize");
});
}
function initSearchToggle() {
$("#secondary-nav li.btn-search a").wrapInner("<span></span>");
$("#secondary-nav li.btn-search a").click(function(e){
e.preventDefault();
//remove the event handlers
$(document).off();
$("#primary-search").off();
if($("body").hasClass("mobile-nav-open")){
$("body").removeClass("mobile-nav-open");
setTimeout(function(){
$("body").toggleClass("search-open");
},500);
} else {
$("body").toggleClass("search-open");
if($("body").hasClass("search-open")){
$("#primary-search input:first").focus();
} else {
$("#primary-search input:first").blur();
}
}
if($(window).outerWidth() < 980){
$(document).click(function() {
$("body").removeClass("search-open");
});
$("#primary-search").click(function(e){
e.stopPropagation();//make sure it doesn't close on iteself
});
}
});
}
function initDatePicker(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd;
}
if(mm<10) {
mm='0'+mm;
}
var newdate = mm + "-" + dd + "-" + yyyy;
$("#date-picker").DatePicker({
flat: true,
date: newdate,
current: newdate,
format: "m-d-Y",
calendars: 1,
starts: 0,
prev: "",
next: "",
onChange: function(formated){
$('#date-select').val(formated);
}
});
}
function initPageLeads(){
if($(".home-icons").length) {
return false;
}
$(".page-lead:nth-child(3n+3)").attr("data-orientation","right");
$(".page-lead:nth-child(3n+2)").attr("data-orientation","center");
$(".page-lead:nth-child(3n+1)").attr("data-orientation","left");
$(".page-lead").hover(function(){
$("#page-modal-wrapper").delay(200).fadeOut(300,function(){
$(this).remove();
});
var _this = $(this);
var _title = _this.attr("data-title");
var _desc = _this.attr("data-content");
var _offset = _this.offset();
var _orientation = _this.attr("data-orientation");
//var _itemOffset = _this.offset();
var _img = _this.find("img");
var _src = _img.attr("src");
var _hoverSrc = _src.substring(0,_src.lastIndexOf("."));
var _fileExt = _src.substring(_src.lastIndexOf("."));
//console.log(_fileExt);
_img.attr("src",_hoverSrc + "-hover" + _fileExt);
var _modalContent = "<div id='page-info-modal' class='" + _orientation + "'><h3>" + _title + "</h3><p>" + _desc + "</p></div>";
$(_modalContent).prependTo("body").wrapAll("<div id='page-modal-wrapper'></div>").css({
"opacity":0,
"display":"block",
"top": (_offset.top + _this.outerHeight()) - 100
}).delay(200).animate({
"top": (_offset.top + _this.outerHeight()) - 80,
"opacity":1
},850,'easeOutExpo');
function isElementInViewport (el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.<API key>();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
var _el = $("#page-info-modal");
if ( !isElementInViewport(_el) ) {
if (typeof jQuery === "function" && _el instanceof jQuery) {
_el = _el[0];
}
// var rect = _el.<API key>();
// $("htm,body").animate({
// scrollTop: $(window).scrollTop() + Math.abs(rect.bottom - $(window).innerHeight()) + 40
// }, 550);
//console.log($(window).innerHeight);
}
}, function(){
var _this = $(this);
var _img = _this.find("img");
var _src = _img.attr("src");
var _origSrc = _src.replace("-hover","");
//console.log(_fileExt);
_img.attr("src",_origSrc);
$("#page-modal-wrapper").delay(200).fadeOut(150,function(){
$(this).remove();
});
});
}
function initFormUpload() {
$(".form-file").each(function(){
var _this = $(this);
//add a new label
var _label = $("<label for='" + _this.attr("id") + "'>Select a File (.JPG, .RTF, or .PDF)</label>");
_label.insertBefore(_this);
_label.addClass("form-control");
//hide form file initial
_this.addClass("file-upload-hide");
//add a cap image to appear as a button
function appendCap(){
var _capContent = "<div class='form-upload-cap'></div>'";
var _cap = $(_capContent);
_cap.appendTo(_label);
}
appendCap();
_this.change(function(){
_label.text(_this.val().substr(_this.val().lastIndexOf("\\")+1));
appendCap();
});
});
}
//
function initShareLinks(){
$(".share-box a").click(function(){
var _shareDir = $(this).attr("data-share");
var _softURL = window.location.href;
var _fullURL;
if(_shareDir === "twitter") {
_fullURL = encodeURI("https://twitter.com/intent/tweet?url=" + String(_softURL));
openShareWin(_fullURL);
} else if(_shareDir === "facebook"){
_fullURL = encodeURI("http:
openShareWin(_fullURL);
} else if(_shareDir === "linkedin") {
_fullURL = encodeURI("http:
openShareWin(_fullURL);
} else if(_shareDir === "googleplus") {
_fullURL = encodeURI("https://plus.google.com/share?url=" + String(_softURL));
openShareWin(_fullURL);
}
return false;
});
function openShareWin(_shareURL){
var config;
window.open(_shareURL,"Share This",config="height=440,width=520,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=no");
}
}
// jquery is ready
$(document).ready(function(){
initMobileTrigger();
initCarousel();
initSearchToggle();
initPageLeads();
initDatePicker();
initFormUpload();
initShareLinks();
initPosMessage();
initParallax();
initFooter();
$(".secondary-content select").chosen();
}); |
// Disassembler
int next; // Next instruction word value, for 2 word instructions.
AVR disassembly
// 0000 0000 0000 0000 N0P
// 0000 0001 dddd rrrr M0VW
// 0000 0010 dddd rrrr MULS
// 0000 0011 0ddd 0rrr MULSU
// 0000 0011 0ddd 1rrr FMUL
// 0000 0011 1ddd 0rrr FMULS
// 0000 0011 1ddd 1rrr FMULSU
// 0000 01rd dddd rrrr CPC
// 0000 10rd dddd rrrr SBC
// 0000 11rd dddd rrrr ADD
void Wreg(int n) {
Wc('r'); Wd(n, 1);
}
void WregPair(int n) {
Wreg(n+1); Wc(':'); Wreg(n);
}
void WSramAddr(int addr) {
if (SramSymbol[addr]) {
Ws(SramSymbol[addr]);
Ws(" ($"); Wx(addr,1); Wc(')');
} else {
Wc('$'); Wx(addr,1);
}
}
int Winst0(int i, int code) {
u8 rrrrr = ((code & 0x200) >> 5) | (code & 0xF);
u8 ddddd = (code >> 4) & 0x1F;
switch ((code>>8) & 0xF) {
case 0: Ws("nop "); return 0; break;
case 1: Ws("movw "); WregPair((code>>3) & 0x1e); Wc(','); WregPair((code<<1) & 0x1e); return 0; break;
case 2: Ws("muls "); Wreg(((code>>4) & 0xf) + 16); Wc(','); Wreg((code & 0xf) + 16); return 0; break;
case 3: Ws("mulsu/fmul/fmuls/fmulsu?"); break;
default:
switch ((code>>10) & 3) {
case 1: Ws("cpc "); break;
case 2: Ws("sbc "); break;
case 3: Ws("add "); break;
}
Wreg(ddddd); Ws(", "); Wreg(rrrrr);
break;
}
return 0;
}
int Winst8(int i, int code) {Ws("Inst 8xxx"); return 0;}
int WinstA(int i, int code) {Ws("Inst Axxx"); return 0;}
// 0001 00rd dddd rrrr CPSE
// 0001 01rd dddd rrrr CP
// 0001 10rd dddd rrrr SUB
// 0001 11rd dddd rrrr ADC
// 0010 00rd dddd rrrr AND
// 0010 01rd dddd rrrr E0R
// 0010 10rd dddd rrrr 0R
// 0010 11rd dddd rrrr M0V
void wrdddddrrrr(int code) {
int d = (code >> 4) & 0x1f;
int r = ((code >> 5) & 0x10) | (code & 0x0f);
Wreg(d); Ws(", "); Wreg(r);
}
int Winst1(int i, int code) {
switch ((code>>10) & 3) {
case 0: Ws("cpse "); break;
case 1: Ws("cp "); break;
case 2: Ws("sub "); break;
case 3: Ws("adc "); break;
}
wrdddddrrrr(code);
return 0;
}
int Winst2(int i, int code) {
int d = (code >> 4) & 0x1f;
int r = ((code >> 5) & 0x10) | (code & 0x0f);
u8 c = (code >> 10) & 3;
if (d == r && c < 2) {
switch (c) {
case 0: Ws("tst "); Wreg(d); break;
case 1: Ws("clr "); Wreg(d); break;
}
} else {
switch ((code>>10) & 3) {
case 0: Ws("and "); break;
case 1: Ws("eor "); break;
case 2: Ws("or "); break;
case 3: Ws("mov "); break;
}
wrdddddrrrr(code);
}
return 0;
}
// 0011 kkkk dddd kkkk CPI
// 0100 kkkk dddd kkkk SBCI
// 0101 kkkk dddd kkkk SUBI
// 0110 kkkk dddd kkkk ORI (aka SBR)
// 0111 kkkk dddd kkkk ANDI
int Winst3(int i, int code) {Ws("cpi "); Wreg(((code >> 4) & 0xF) + 16); Ws(", $"); Wx(((code >> 4) & 0xF0) | (code & 0x0F),1); return 0;}
int Winst4(int i, int code) {Ws("sbci "); Wreg(((code >> 4) & 0xF) + 16); Ws(", $"); Wx(((code >> 4) & 0xF0) | (code & 0x0F),1); return 0;}
int Winst5(int i, int code) {Ws("subi "); Wreg(((code >> 4) & 0xF) + 16); Ws(", $"); Wx(((code >> 4) & 0xF0) | (code & 0x0F),1); return 0;}
int Winst6(int i, int code) {Ws("ori "); Wreg(((code >> 4) & 0xF) + 16); Ws(", $"); Wx(((code >> 4) & 0xF0) | (code & 0x0F),1); return 0;}
int Winst7(int i, int code) {Ws("andi "); Wreg(((code >> 4) & 0xF) + 16); Ws(", $"); Wx(((code >> 4) & 0xF0) | (code & 0x0F),1); return 0;}
// 1000 000d dddd 0000 LD Z
// 1000 000d dddd 1000 LD Y
// 10q0 qq0d dddd 0qqq LDD Z
// 10q0 qq0d dddd 1qqq LDD Y
// 10q0 qq1d dddd 0qqq STD Z
// 10q0 qq1d dddd 1qqq STD Y
// 1001 000d dddd 0000 LDS *
// 1001 000d dddd 010+ LPM Z
// 1001 000d dddd 011+ ELPM Z
// 1001 000d dddd 11-+ LD X
// 1001 000d dddd 1111 P0P
int Winst90(int i, int code) { // 90xx and 91xx
int dst = (code >> 4) & 0x1f;
switch (code & 0xf) {
case 0x0: Ws("lds "); Wreg(dst); Ws(", $"); Wx(next,4); return 1; break;
case 0x1: Ws("ld "); Wreg(dst); Ws(", Z+"); return 0; break;
case 0x2: Ws("ld "); Wreg(dst); Ws(", -Z"); return 0; break;
case 0x4: Ws("lpm "); Wreg(dst); Ws(", Z"); return 0; break;
case 0x5: Ws("lpm "); Wreg(dst); Ws(", Z+"); return 0; break;
case 0x6: Ws("elpm "); Wreg(dst); Ws(", Z"); return 0; break;
case 0x7: Ws("elpm "); Wreg(dst); Ws(", Z+"); return 0; break;
case 0x9: Ws("ld "); Wreg(dst); Ws(", Y+"); return 0; break;
case 0xA: Ws("ld "); Wreg(dst); Ws(", -Y"); return 0; break;
case 0xC: Ws("ld "); Wreg(dst); Ws(", X"); return 0; break;
case 0xD: Ws("ld "); Wreg(dst); Ws(", X+"); return 0; break;
case 0xE: Ws("ld "); Wreg(dst); Ws(", -X"); return 0; break;
case 0xF: Ws("pop "); Wreg(dst); return 0; break;
default: Ws("??? "); return 0; break;
}
return 0;
}
// 1001 001r rrrr 0000 STS *
// 1001 001r rrrr 01xx ???
// 1001 001r rrrr 11-+ ST X
// 1001 001d dddd 1111 PUSH
int Winst92(int i, int code) { // 92xx and 93xx
int dst = (code >> 4) & 0x1f;
switch (code & 0xf) {
case 0x0: Ws("sts "); Wreg(dst); Ws(", $"); Wx(next,4); return 1; break;
case 0x1: Ws("st "); Wreg(dst); Ws(", Z+"); return 0; break;
case 0x2: Ws("st "); Wreg(dst); Ws(", -Z"); return 0; break;
case 0x9: Ws("st "); Wreg(dst); Ws(", Y+"); return 0; break;
case 0xA: Ws("st "); Wreg(dst); Ws(", -Y"); return 0; break;
case 0xC: Ws("st "); Wreg(dst); Ws(", X"); return 0; break;
case 0xD: Ws("st "); Wreg(dst); Ws(", X+"); return 0; break;
case 0xE: Ws("st "); Wreg(dst); Ws(", -X"); return 0; break;
case 0xF: Ws("push "); Wreg(dst); return 0; break;
default: Ws("??? "); return 0; break;
}
return 0;
}
int Winst94(int i, int code) { // 94xx and 95xx
if ((code & 0xE) == 8) {
if (code & 0x100) {
// 1001 0101 0000 1000 RET
// 1001 0101 0000 1001 ICALL
// 1001 0101 0001 1000 RETI
// 1001 0101 0001 1001 EICALL
// 1001 0101 1000 1000 SLEEP
// 1001 0101 1001 1000 BREAK
// 1001 0101 1010 1000 WDR
// 1001 0101 1100 1000 LPM
// 1001 0101 1101 1000 ELPM
// 1001 0101 1110 1000 SPM
// 1001 0101 1111 1000 ESPM
switch (code & 0xFF) {
case 0x08: Ws("ret "); break;
case 0x09: Ws("icall "); break;
case 0x18: Ws("reti "); break;
case 0x19: Ws("eicall"); break;
case 0x88: Ws("sleep "); break;
case 0x98: Ws("break "); break;
case 0xA8: Ws("wdr "); break;
case 0xC8: Ws("lpm "); break;
case 0xD8: Ws("elpm "); break;
case 0xE8: Ws("spm "); break;
case 0xF8: Ws("espm "); break;
}
} else {
if (code & 1) {
// 1001 0100 0000 1001 IJMP
// 1001 0100 0001 1001 EIJMP
if (code & 0x10) {Ws("eijmp ");} else {Ws("ijmp ");}
} else { // bset, blcr
// 1001 0100 0sss 1000 BSET
// 1001 0100 1sss 1000 BCLR
switch((code>>4) & 0xF) {
case 0x0: Ws("sec "); break;
case 0x1: Ws("sez "); break;
case 0x2: Ws("sen "); break;
case 0x3: Ws("sev "); break;
case 0x4: Ws("ses "); break;
case 0x5: Ws("seh "); break;
case 0x6: Ws("set "); break;
case 0x7: Ws("sei "); break;
case 0x8: Ws("clc "); break;
case 0x9: Ws("clz "); break;
case 0xA: Ws("cln "); break;
case 0xB: Ws("clv "); break;
case 0xC: Ws("cls "); break;
case 0xD: Ws("clh "); break;
case 0xE: Ws("clt "); break;
case 0xF: Ws("cli "); break;
}
}
}
} else {
if ((code & 0xC) != 0xC) {
// 1001 010d dddd 0000 COM
// 1001 010d dddd 0001 NEG
// 1001 010d dddd 0010 SWAP
// 1001 010d dddd 0011 INC
// 1001 010d dddd 0100 ???
// 1001 010d dddd 0101 ASR
// 1001 010d dddd 0110 LSR
// 1001 010d dddd 0111 ROR
// 1001 010d dddd 1010 DEC
switch (code & 0xf) {
case 0x0: Ws("com "); break;
case 0x1: Ws("neg "); break;
case 0x2: Ws("swap "); break;
case 0x3: Ws("inc "); break;
case 0x5: Ws("asr "); break;
case 0x6: Ws("lsr "); break;
case 0x7: Ws("ror "); break;
case 0xA: Ws("dec "); break;
default: Ws("??? "); break;
}
Wreg((code >> 4) & 0x1f);
} else { // jmp, call
// 1001 010k kkkk 110k kkkk kkkk kkkk kkkk JMP *
// 1001 010k kkkk 111k kkkk kkkk kkkk kkkk CALL *
Ws((code & 2) ? "call $" : "jmp $");
int addrhi = ((code >> 3) & 0x3E) | (code & 1);
Wx(((addrhi<<16)+next)*2,6); return 1;
}
}
return 0;
}
// 1001 0110 kkdd kkkk ADIW
int Winst96(int i, int code) {
int regpair = ((code >> 3) & 6) + 24;
int value = ((code >> 2) & 0x30) | (code & 0xf);
Ws("adiw "); WregPair(regpair); Ws(", $"); Wx(value,2);
return 0;
}
// 1001 0111 kkdd kkkk SBIW
int Winst97(int i, int code) {
int regpair = ((code >> 3) & 6) + 24;
int value = ((code >> 2) & 0x30) | (code & 0xf);
Ws("sbiw "); WregPair(regpair); Ws(", $"); Wx(value,2);
return 0;
}
// 1001 1000 AAAA Abbb CBI
int Winst98(int i, int code) {Ws("cbi "); WSramAddr((code >> 3) & 0x1F); Ws(", "); Wd(code & 7,1); return 0;}
// 1001 1001 AAAA Abbb SBIC
int Winst99(int i, int code) {Ws("sbic "); WSramAddr((code >> 3) & 0x1F); Ws(", "); Wd(code & 7,1); return 0;}
// 1001 1010 AAAA Abbb SBI
int Winst9A(int i, int code) {Ws("sbi "); WSramAddr((code >> 3) & 0x1F); Ws(", "); Wd(code & 7,1); return 0;}
// 1001 1011 AAAA Abbb SBIS
int Winst9B(int i, int code) {Ws("sbis "); WSramAddr((code >> 3) & 0x1F); Ws(", "); Wd(code & 7,1); return 0;}
// 1001 11rd dddd rrrr MUL
int Winst9C(int i, int code) {
u8 rrrrr = ((code & 0x200) >> 5) | (code & 0xF);
u8 ddddd = (code >> 4) & 0x1F;
Ws("mul "); Wreg(ddddd); Wc(','); Wreg(rrrrr);
return 0;
}
int Winst9(int i, int code) {
switch ((code >> 8) & 0xf) {
case 0x0:
case 0x1: return Winst90(i, code); break;
case 0x2:
case 0x3: return Winst92(i, code); break;
case 0x4:
case 0x5: return Winst94(i, code); break;
case 0x6: return Winst96(i, code); break;
case 0x7: return Winst97(i, code); break;
case 0x8: return Winst98(i, code); break;
case 0x9: return Winst99(i, code); break;
case 0xA: return Winst9A(i, code); break;
case 0xB: return Winst9B(i, code); break;
case 0xC:
case 0xD:
case 0xE:
case 0xF: return Winst9C(i, code); break; }
return 0;
}
// 1011 0AAd dddd AAAA IN
// 1011 1AAr rrrr AAAA 0UT
int WinstB(int i, int code) {
int reg = (code >> 4) & 0x1f;
int adr = ((code >> 5) & 0x30) | (code & 0xf);
if (code & 0x800) {
Ws("out "); WSramAddr(adr); Ws(", "); Wreg(reg);
} else {
Ws("in "); Wreg(reg); Ws(", "); WSramAddr(adr);
}
return 0;
}
void wRelative(int i, int delta) {
if (CodeSymbol[i + delta*2]) {Ws(CodeSymbol[i + delta*2]);}
else {Wx(i + delta*2, 4);}
Ws(" (");
if (delta >= 0) {Wc('+');}
Wd(delta, 1);
Wc(')');
}
void wRelative12(int i, int code) {
if (code & 0x0800) {
wRelative(i, ((code & 0x7ff) - 0x800) + 1);
} else {
wRelative(i, (code & 0x7ff) + 1);
}
}
// 1100 kkkk kkkk kkkk RJMP
int WinstC(int i, int code) {
Ws("rjmp ");
wRelative12(i, code);
return 0;
}
// 1101 kkkk kkkk kkkk RCALL
int WinstD(int i, int code) {
Ws("rcall ");
wRelative12(i, code);
return 0;
}
// 1110 kkkk dddd kkkk LDI
int WinstE(int i, int code) {
int reg = ((code >> 4) & 0xf) + 16;
int val = ((code >> 4) & 0xf0) | (code & 0xf);
Ws("ldi ");
Wreg(reg); Ws(", "); WSramAddr(val);
return 0;
}
void wRelative7(int i, int code) {
if (code & 0x40) {
wRelative(i, ((code & 0x3f) - 0x40) + 1);
} else {
wRelative(i, (code & 0x3f) + 1);
}
}
int WinstF(int i, int code) {
if (!(code & 0x800)) {
// 1111 00kk kkkk ksss BRBS
// 1111 01kk kkkk ksss BRBC
int s = code & 7;
int k = (code >> 3) & 0x7f;
if (code & 0x400) { // brbc
switch (s) {
case 0: Ws("brsh "); break; // aka brcc
case 1: Ws("brne "); break;
case 2: Ws("brpl "); break;
case 3: Ws("brvc "); break;
case 4: Ws("brge "); break;
case 5: Ws("brhc "); break;
case 6: Ws("brtc "); break;
case 7: Ws("brid "); break;
}
} else { // brbs
switch (s) {
case 0: Ws("brlo "); break; // aka brcs
case 1: Ws("breq "); break;
case 2: Ws("brmi "); break;
case 3: Ws("brvs "); break;
case 4: Ws("brlt "); break;
case 5: Ws("brhs "); break;
case 6: Ws("brts "); break;
case 7: Ws("brie "); break;
}
}
wRelative7(i, k);
} else if ((code & 8) == 0) {
// 1111 100d dddd 0bbb BLD
// 1111 101d dddd 0bbb BST
// 1111 110r rrrr 0bbb SBRC
// 1111 111r rrrr 0bbb SBRS
int bit = code & 7;
int reg = (code >> 4) & 0x1f;
switch ((code >> 9) & 3) {
case 0: Ws("bld "); break;
case 1: Ws("bst "); break;
case 2: Ws("sbrc "); break;
case 3: Ws("sbrs "); break;
}
Wreg(reg); Ws(", "); Wd(bit,1);
} else {
if (code != 0xffff) {Ws("???");} // Special casse - show nothing for uninitialised memory
}
return 0;
}
int Winstruction(int i, int code) {
switch (code>>12) {
case 0x0: return Winst0(i, code); break;
case 0x1: return Winst1(i, code); break;
case 0x2: return Winst2(i, code); break;
case 0x3: return Winst3(i, code); break;
case 0x4: return Winst4(i, code); break;
case 0x5: return Winst5(i, code); break;
case 0x6: return Winst6(i, code); break;
case 0x7: return Winst7(i, code); break;
case 0x8: return Winst8(i, code); break;
case 0x9: return Winst9(i, code); break;
case 0xA: return WinstA(i, code); break;
case 0xB: return WinstB(i, code); break;
case 0xC: return WinstC(i, code); break;
case 0xD: return WinstD(i, code); break;
case 0xE: return WinstE(i, code); break;
case 0xF: return WinstF(i, code); break;
}
return 0;
}
char *SkipPath(char *name) { // Return pointer to name with any leading path skipped
char *p = name;
char *start = name;
while (*p) {
if (((*p == '/') || (*p == '\\')) && *(p+1)) {start = p+1;}
p++;
}
return start;
}
int <API key>(int addr, u8 *buf) { // Returns instruction length in words
Assert((addr & 1) == 0);
if (CodeSymbol[addr]) {Wl(); Ws(CodeSymbol[addr]); Wsl(":");}
if (HasLineNumbers) {
if (FileName[addr]) {Ws(SkipPath(FileName[addr]));}
if (LineNumber[addr]) {Wc('['); Wd(LineNumber[addr],1); Wc(']');}
Wt(20);
}
Wx(addr, 4); Ws(": ");
int code = (buf[1] << 8) | buf[0];
Wx(code, 4); Ws(" "); // Instruction code
next = (buf[3] << 8) | buf[2];
if (Winstruction(addr, code)) return 4;
return 2;
} |
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <syslog.h>
#include <fcntl.h>
#include <net/if_arp.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/uio.h>
#include "libnetlink.h"
int rcvbuf = 1024 * 1024;
void rtnl_close(struct rtnl_handle *rth)
{
if (rth->fd >= 0) {
close(rth->fd);
rth->fd = -1;
}
}
int rtnl_open_byproto(struct rtnl_handle *rth, unsigned subscriptions,
int protocol)
{
socklen_t addr_len;
int sndbuf = 32768;
memset(rth, 0, sizeof(*rth));
rth->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
if (rth->fd < 0) {
perror("Cannot open netlink socket");
return -1;
}
if (setsockopt(rth->fd,SOL_SOCKET,SO_SNDBUF,&sndbuf,sizeof(sndbuf)) < 0) {
perror("SO_SNDBUF");
return -1;
}
if (setsockopt(rth->fd,SOL_SOCKET,SO_RCVBUF,&rcvbuf,sizeof(rcvbuf)) < 0) {
perror("SO_RCVBUF");
return -1;
}
memset(&rth->local, 0, sizeof(rth->local));
rth->local.nl_family = AF_NETLINK;
rth->local.nl_groups = subscriptions;
if (bind(rth->fd, (struct sockaddr*)&rth->local, sizeof(rth->local)) < 0) {
perror("Cannot bind netlink socket");
return -1;
}
addr_len = sizeof(rth->local);
if (getsockname(rth->fd, (struct sockaddr*)&rth->local, &addr_len) < 0) {
perror("Cannot getsockname");
return -1;
}
if (addr_len != sizeof(rth->local)) {
fprintf(stderr, "Wrong address length %d\n", addr_len);
return -1;
}
if (rth->local.nl_family != AF_NETLINK) {
fprintf(stderr, "Wrong address family %d\n", rth->local.nl_family);
return -1;
}
rth->seq = time(NULL);
return 0;
}
int rtnl_open(struct rtnl_handle *rth, unsigned subscriptions)
{
return rtnl_open_byproto(rth, subscriptions, NETLINK_ROUTE);
}
int <API key>(struct rtnl_handle *rth, int family, int type)
{
struct {
struct nlmsghdr nlh;
struct rtgenmsg g;
} req;
memset(&req, 0, sizeof(req));
req.nlh.nlmsg_len = sizeof(req);
req.nlh.nlmsg_type = type;
req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
req.nlh.nlmsg_pid = 0;
req.nlh.nlmsg_seq = rth->dump = ++rth->seq;
req.g.rtgen_family = family;
return send(rth->fd, (void*)&req, sizeof(req), 0);
}
int rtnl_send(struct rtnl_handle *rth, const char *buf, int len)
{
return send(rth->fd, buf, len, 0);
}
int rtnl_send_check(struct rtnl_handle *rth, const char *buf, int len)
{
struct nlmsghdr *h;
int status;
char resp[1024];
status = send(rth->fd, buf, len, 0);
if (status < 0)
return status;
/* Check for immediate errors */
status = recv(rth->fd, resp, sizeof(resp), MSG_DONTWAIT|MSG_PEEK);
if (status < 0) {
if (errno == EAGAIN)
return 0;
return -1;
}
for (h = (struct nlmsghdr *)resp; NLMSG_OK(h, status);
h = NLMSG_NEXT(h, status)) {
if (h->nlmsg_type == NLMSG_ERROR) {
struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr)))
fprintf(stderr, "ERROR truncated\n");
else
errno = -err->error;
return -1;
}
}
return 0;
}
int rtnl_dump_request(struct rtnl_handle *rth, int type, void *req, int len)
{
struct nlmsghdr nlh;
struct sockaddr_nl nladdr;
struct iovec iov[2] = {
{ .iov_base = &nlh, .iov_len = sizeof(nlh) },
{ .iov_base = req, .iov_len = len }
};
struct msghdr msg = {
.msg_name = &nladdr,
.msg_namelen = sizeof(nladdr),
.msg_iov = iov,
.msg_iovlen = 2,
};
memset(&nladdr, 0, sizeof(nladdr));
nladdr.nl_family = AF_NETLINK;
nlh.nlmsg_len = NLMSG_LENGTH(len);
nlh.nlmsg_type = type;
nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
nlh.nlmsg_pid = 0;
nlh.nlmsg_seq = rth->dump = ++rth->seq;
return sendmsg(rth->fd, &msg, 0);
}
int rtnl_dump_filter_l(struct rtnl_handle *rth,
const struct <API key> *arg)
{
struct sockaddr_nl nladdr;
struct iovec iov;
struct msghdr msg = {
.msg_name = &nladdr,
.msg_namelen = sizeof(nladdr),
.msg_iov = &iov,
.msg_iovlen = 1,
};
char buf[16384];
iov.iov_base = buf;
while (1) {
int status;
const struct <API key> *a;
int found_done = 0;
int msglen = 0;
iov.iov_len = sizeof(buf);
status = recvmsg(rth->fd, &msg, 0);
if (status < 0) {
if (errno == EINTR || errno == EAGAIN)
continue;
fprintf(stderr, "netlink receive error %s (%d)\n",
strerror(errno), errno);
return -1;
}
if (status == 0) {
fprintf(stderr, "EOF on netlink\n");
return -1;
}
for (a = arg; a->filter; a++) {
struct nlmsghdr *h = (struct nlmsghdr*)buf;
msglen = status;
while (NLMSG_OK(h, msglen)) {
int err;
if (nladdr.nl_pid != 0 ||
h->nlmsg_pid != rth->local.nl_pid ||
h->nlmsg_seq != rth->dump) {
if (a->junk) {
err = a->junk(&nladdr, h,
a->arg2);
if (err < 0)
return err;
}
goto skip_it;
}
if (h->nlmsg_type == NLMSG_DONE) {
found_done = 1;
break; /* process next filter */
}
if (h->nlmsg_type == NLMSG_ERROR) {
struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
fprintf(stderr,
"ERROR truncated\n");
} else {
errno = -err->error;
perror("RTNETLINK answers");
}
return -1;
}
err = a->filter(&nladdr, h, a->arg1);
if (err < 0)
return err;
skip_it:
h = NLMSG_NEXT(h, msglen);
}
}
if (found_done)
return 0;
if (msg.msg_flags & MSG_TRUNC) {
fprintf(stderr, "Message truncated\n");
continue;
}
if (msglen) {
fprintf(stderr, "!!!Remnant of size %d\n", msglen);
exit(1);
}
}
}
int rtnl_dump_filter(struct rtnl_handle *rth,
rtnl_filter_t filter,
void *arg1,
rtnl_filter_t junk,
void *arg2)
{
const struct <API key> a[2] = {
{ .filter = filter, .arg1 = arg1, .junk = junk, .arg2 = arg2 },
{ .filter = NULL, .arg1 = NULL, .junk = NULL, .arg2 = NULL }
};
return rtnl_dump_filter_l(rth, a);
}
int rtnl_talk(struct rtnl_handle *rtnl, struct nlmsghdr *n, pid_t peer,
unsigned groups, struct nlmsghdr *answer,
rtnl_filter_t junk,
void *jarg)
{
int status;
unsigned seq;
struct nlmsghdr *h;
struct sockaddr_nl nladdr;
struct iovec iov = {
.iov_base = (void*) n,
.iov_len = n->nlmsg_len
};
struct msghdr msg = {
.msg_name = &nladdr,
.msg_namelen = sizeof(nladdr),
.msg_iov = &iov,
.msg_iovlen = 1,
};
char buf[16384];
memset(&nladdr, 0, sizeof(nladdr));
nladdr.nl_family = AF_NETLINK;
nladdr.nl_pid = peer;
nladdr.nl_groups = groups;
n->nlmsg_seq = seq = ++rtnl->seq;
if (answer == NULL)
n->nlmsg_flags |= NLM_F_ACK;
status = sendmsg(rtnl->fd, &msg, 0);
if (status < 0) {
perror("Cannot talk to rtnetlink");
return -1;
}
memset(buf,0,sizeof(buf));
iov.iov_base = buf;
while (1) {
iov.iov_len = sizeof(buf);
status = recvmsg(rtnl->fd, &msg, 0);
if (status < 0) {
if (errno == EINTR || errno == EAGAIN)
continue;
fprintf(stderr, "netlink receive error %s (%d)\n",
strerror(errno), errno);
return -1;
}
if (status == 0) {
fprintf(stderr, "EOF on netlink\n");
return -1;
}
if (msg.msg_namelen != sizeof(nladdr)) {
fprintf(stderr, "sender address length == %d\n", msg.msg_namelen);
exit(1);
}
for (h = (struct nlmsghdr*)buf; status >= sizeof(*h); ) {
int err;
int len = h->nlmsg_len;
int l = len - sizeof(*h);
if (l<0 || len>status) {
if (msg.msg_flags & MSG_TRUNC) {
fprintf(stderr, "Truncated message\n");
return -1;
}
fprintf(stderr, "!!!malformed message: len=%d\n", len);
exit(1);
}
if (nladdr.nl_pid != peer ||
h->nlmsg_pid != rtnl->local.nl_pid ||
h->nlmsg_seq != seq) {
if (junk) {
err = junk(&nladdr, h, jarg);
if (err < 0)
return err;
}
/* Don't forget to skip that message. */
status -= NLMSG_ALIGN(len);
h = (struct nlmsghdr*)((char*)h + NLMSG_ALIGN(len));
continue;
}
if (h->nlmsg_type == NLMSG_ERROR) {
struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
if (l < sizeof(struct nlmsgerr)) {
fprintf(stderr, "ERROR truncated\n");
} else {
errno = -err->error;
if (errno == 0) {
if (answer)
memcpy(answer, h, h->nlmsg_len);
return 0;
}
perror("RTNETLINK answers");
}
return -1;
}
if (answer) {
memcpy(answer, h, h->nlmsg_len);
return 0;
}
fprintf(stderr, "Unexpected reply!!!\n");
status -= NLMSG_ALIGN(len);
h = (struct nlmsghdr*)((char*)h + NLMSG_ALIGN(len));
}
if (msg.msg_flags & MSG_TRUNC) {
fprintf(stderr, "Message truncated\n");
continue;
}
if (status) {
fprintf(stderr, "!!!Remnant of size %d\n", status);
exit(1);
}
}
}
int rtnl_listen(struct rtnl_handle *rtnl,
rtnl_filter_t handler,
void *jarg)
{
int status;
struct nlmsghdr *h;
struct sockaddr_nl nladdr;
struct iovec iov;
struct msghdr msg = {
.msg_name = &nladdr,
.msg_namelen = sizeof(nladdr),
.msg_iov = &iov,
.msg_iovlen = 1,
};
char buf[8192];
memset(&nladdr, 0, sizeof(nladdr));
nladdr.nl_family = AF_NETLINK;
nladdr.nl_pid = 0;
nladdr.nl_groups = 0;
iov.iov_base = buf;
while (1) {
iov.iov_len = sizeof(buf);
status = recvmsg(rtnl->fd, &msg, 0);
if (status < 0) {
if (errno == EINTR || errno == EAGAIN)
continue;
fprintf(stderr, "netlink receive error %s (%d)\n",
strerror(errno), errno);
if (errno == ENOBUFS)
continue;
return -1;
}
if (status == 0) {
fprintf(stderr, "EOF on netlink\n");
return -1;
}
if (msg.msg_namelen != sizeof(nladdr)) {
fprintf(stderr, "Sender address length == %d\n", msg.msg_namelen);
exit(1);
}
for (h = (struct nlmsghdr*)buf; status >= sizeof(*h); ) {
int err;
int len = h->nlmsg_len;
int l = len - sizeof(*h);
if (l<0 || len>status) {
if (msg.msg_flags & MSG_TRUNC) {
fprintf(stderr, "Truncated message\n");
return -1;
}
fprintf(stderr, "!!!malformed message: len=%d\n", len);
exit(1);
}
err = handler(&nladdr, h, jarg);
if (err < 0)
return err;
status -= NLMSG_ALIGN(len);
h = (struct nlmsghdr*)((char*)h + NLMSG_ALIGN(len));
}
if (msg.msg_flags & MSG_TRUNC) {
fprintf(stderr, "Message truncated\n");
continue;
}
if (status) {
fprintf(stderr, "!!!Remnant of size %d\n", status);
exit(1);
}
}
}
int rtnl_from_file(FILE *rtnl, rtnl_filter_t handler,
void *jarg)
{
int status;
struct sockaddr_nl nladdr;
char buf[8192];
struct nlmsghdr *h = (void*)buf;
memset(&nladdr, 0, sizeof(nladdr));
nladdr.nl_family = AF_NETLINK;
nladdr.nl_pid = 0;
nladdr.nl_groups = 0;
while (1) {
int err, len, type;
int l;
status = fread(&buf, 1, sizeof(*h), rtnl);
if (status < 0) {
if (errno == EINTR)
continue;
perror("rtnl_from_file: fread");
return -1;
}
if (status == 0)
return 0;
len = h->nlmsg_len;
type= h->nlmsg_type;
l = len - sizeof(*h);
if (l<0 || len>sizeof(buf)) {
fprintf(stderr, "!!!malformed message: len=%d @%lu\n",
len, ftell(rtnl));
return -1;
}
status = fread(NLMSG_DATA(h), 1, NLMSG_ALIGN(l), rtnl);
if (status < 0) {
perror("rtnl_from_file: fread");
return -1;
}
if (status < l) {
fprintf(stderr, "rtnl-from_file: truncated message\n");
return -1;
}
err = handler(&nladdr, h, jarg);
if (err < 0)
return err;
}
}
int addattr32(struct nlmsghdr *n, int maxlen, int type, __u32 data)
{
int len = RTA_LENGTH(4);
struct rtattr *rta;
if (NLMSG_ALIGN(n->nlmsg_len) + len > maxlen) {
fprintf(stderr,"addattr32: Error! max allowed bound %d exceeded\n",maxlen);
return -1;
}
rta = NLMSG_TAIL(n);
rta->rta_type = type;
rta->rta_len = len;
memcpy(RTA_DATA(rta), &data, 4);
n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + len;
return 0;
}
int addattr_l(struct nlmsghdr *n, int maxlen, int type, const void *data,
int alen)
{
int len = RTA_LENGTH(alen);
struct rtattr *rta;
if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len) > maxlen) {
fprintf(stderr, "addattr_l ERROR: message exceeded bound of %d\n",maxlen);
return -1;
}
rta = NLMSG_TAIL(n);
rta->rta_type = type;
rta->rta_len = len;
memcpy(RTA_DATA(rta), data, alen);
n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len);
return 0;
}
int addraw_l(struct nlmsghdr *n, int maxlen, const void *data, int len)
{
if (NLMSG_ALIGN(n->nlmsg_len) + NLMSG_ALIGN(len) > maxlen) {
fprintf(stderr, "addraw_l ERROR: message exceeded bound of %d\n",maxlen);
return -1;
}
memcpy(NLMSG_TAIL(n), data, len);
memset((void *) NLMSG_TAIL(n) + len, 0, NLMSG_ALIGN(len) - len);
n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + NLMSG_ALIGN(len);
return 0;
}
struct rtattr *addattr_nest(struct nlmsghdr *n, int maxlen, int type)
{
struct rtattr *nest = NLMSG_TAIL(n);
addattr_l(n, maxlen, type, NULL, 0);
return nest;
}
int addattr_nest_end(struct nlmsghdr *n, struct rtattr *nest)
{
nest->rta_len = (void *)NLMSG_TAIL(n) - (void *)nest;
return n->nlmsg_len;
}
struct rtattr *addattr_nest_compat(struct nlmsghdr *n, int maxlen, int type,
const void *data, int len)
{
struct rtattr *start = NLMSG_TAIL(n);
addattr_l(n, maxlen, type, data, len);
addattr_nest(n, maxlen, type);
return start;
}
int <API key>(struct nlmsghdr *n, struct rtattr *start)
{
struct rtattr *nest = (void *)start + NLMSG_ALIGN(start->rta_len);
start->rta_len = (void *)NLMSG_TAIL(n) - (void *)start;
addattr_nest_end(n, nest);
return n->nlmsg_len;
}
int rta_addattr32(struct rtattr *rta, int maxlen, int type, __u32 data)
{
int len = RTA_LENGTH(4);
struct rtattr *subrta;
if (RTA_ALIGN(rta->rta_len) + len > maxlen) {
fprintf(stderr,"rta_addattr32: Error! max allowed bound %d exceeded\n",maxlen);
return -1;
}
subrta = (struct rtattr*)(((char*)rta) + RTA_ALIGN(rta->rta_len));
subrta->rta_type = type;
subrta->rta_len = len;
memcpy(RTA_DATA(subrta), &data, 4);
rta->rta_len = NLMSG_ALIGN(rta->rta_len) + len;
return 0;
}
int rta_addattr_l(struct rtattr *rta, int maxlen, int type,
const void *data, int alen)
{
struct rtattr *subrta;
int len = RTA_LENGTH(alen);
if (RTA_ALIGN(rta->rta_len) + RTA_ALIGN(len) > maxlen) {
fprintf(stderr,"rta_addattr_l: Error! max allowed bound %d exceeded\n",maxlen);
return -1;
}
subrta = (struct rtattr*)(((char*)rta) + RTA_ALIGN(rta->rta_len));
subrta->rta_type = type;
subrta->rta_len = len;
memcpy(RTA_DATA(subrta), data, alen);
rta->rta_len = NLMSG_ALIGN(rta->rta_len) + RTA_ALIGN(len);
return 0;
}
int parse_rtattr(struct rtattr *tb[], int max, struct rtattr *rta, int len)
{
memset(tb, 0, sizeof(struct rtattr *) * (max + 1));
while (RTA_OK(rta, len)) {
if ((rta->rta_type <= max) && (!tb[rta->rta_type]))
tb[rta->rta_type] = rta;
rta = RTA_NEXT(rta,len);
}
if (len)
fprintf(stderr, "!!!Deficit %d, rta_len=%d\n", len, rta->rta_len);
return 0;
}
int <API key>(struct rtattr *tb[], int max, struct rtattr *rta, int len)
{
int i = 0;
memset(tb, 0, sizeof(struct rtattr *) * max);
while (RTA_OK(rta, len)) {
if (rta->rta_type <= max && i < max)
tb[i++] = rta;
rta = RTA_NEXT(rta,len);
}
if (len)
fprintf(stderr, "!!!Deficit %d, rta_len=%d\n", len, rta->rta_len);
return i;
}
int <API key>(struct rtattr *tb[], int max, struct rtattr *rta,
int len)
{
if (RTA_PAYLOAD(rta) < len)
return -1;
if (RTA_PAYLOAD(rta) >= RTA_ALIGN(len) + sizeof(struct rtattr)) {
rta = RTA_DATA(rta) + RTA_ALIGN(len);
return parse_rtattr_nested(tb, max, rta);
}
memset(tb, 0, sizeof(struct rtattr *) * (max + 1));
return 0;
} |
#ifndef UMLFORKJOINVITEM_H
#define UMLFORKJOINVITEM_H
#include "projectbase/shapes/PolygonElement.h"
#include "interfaces/Defs.h"
class WXDLLIMPEXP_CD umlForkJoinVItem : public uddPolygonElement
{
public:
<API key>(umlForkJoinVItem);
umlForkJoinVItem();
umlForkJoinVItem(const umlForkJoinVItem &obj);
virtual ~umlForkJoinVItem();
protected:
// protected functions
virtual void CreateHandles();
private:
// private functions
void Initialize();
};
#endif // UMLFORKJOINVITEM_H |
package edu.ucdenver.bios.powersvc.resource.test; |
#include "config.h"
#include "vm/types.h"
#include "vm/jit/s390/codegen.h"
#include "vm/jit/s390/md-abi.h"
#include "mm/memory.h"
#include "native/native.h"
#include "vm/builtin.h"
#include "vmcore/class.h"
#include "vm/exceptions.h"
#include "vmcore/field.h"
#include "vm/initialize.h"
#include "vmcore/options.h"
#include "vmcore/references.h"
#include "vm/resolve.h"
#include "vm/jit/patcher.h"
#include "vm/jit/stacktrace.h"
#include <assert.h>
#define OOPS() assert(0);
#define __PORTED__
java_objectheader *patcher_wrapper(u1 *sp, u1 *pv, u1 *ra)
{
#if 1
stackframeinfo sfi;
u1 *xpc;
java_objectheader *o;
functionptr f;
bool result;
java_objectheader *e;
/* define the patcher function */
bool (*patcher_function)(u1 *);
/* get stuff from the stack */
xpc = (u1 *) *((ptrint *) (sp + 5 * 4));
o = (java_objectheader *) *((ptrint *) (sp + 4 * 4));
f = (functionptr) *((ptrint *) (sp + 0 * 4));
xpc = xpc - 4; /* the patch position is 4 bytes before the RA */
*((ptrint *) (sp + 5 * 4)) = (ptrint) xpc;
/* store PV into the patcher function position */
*((ptrint *) (sp + 0 * 4)) = (ptrint) pv;
/* cast the passed function to a patcher function */
patcher_function = (bool (*)(u1 *)) (ptrint) f;
/* enter a monitor on the patching position */
<API key>;
/* create the stackframeinfo */
/* RA is passed as NULL, but the XPC is correct and can be used in
<API key> for
<API key>. */
<API key>(&sfi, pv, sp + (6 * 4), ra, xpc);
/* call the proper patcher function */
result = (patcher_function)(sp);
/* remove the stackframeinfo */
<API key>(&sfi);
/* check for return value and exit accordingly */
if (result == false) {
e = <API key>();
PATCHER_MONITOREXIT;
return e;
}
<API key>;
return NULL;
#else
stackframeinfo sfi;
u1 *xpc;
java_objectheader *o;
u4 mcode;
functionptr f;
bool result;
java_objectheader *e;
/* define the patcher function */
bool (*patcher_function)(u1 *);
assert(pv != NULL);
/* get stuff from the stack */
xpc = (u1 *) *((ptrint *) (sp + 5 * 4));
o = (java_objectheader *) *((ptrint *) (sp + 4 * 4));
f = (functionptr) *((ptrint *) (sp + 0 * 4));
/* Correct RA is calculated in codegen.c and stored in the patcher
stub stack. There's no need to adjust xpc. */
/* store PV into the patcher function position */
*((ptrint *) (sp + 0 * 4)) = (ptrint) pv;
/* cast the passed function to a patcher function */
patcher_function = (bool (*)(u1 *)) (ptrint) f;
/* enter a monitor on the patching position */
<API key>;
/* create the stackframeinfo */
<API key>(&sfi, pv, sp + 8 * 4, ra, xpc);
/* call the proper patcher function */
result = (patcher_function)(sp);
/* remove the stackframeinfo */
<API key>(&sfi);
/* check for return value and exit accordingly */
if (result == false) {
e = <API key>();
PATCHER_MONITOREXIT;
return e;
}
<API key>;
return NULL;
#endif
}
bool <API key>(u1 *sp)
{
u1 *ra;
u4 mcode;
unresolved_field *uf;
s4 disp;
fieldinfo *fi;
u1 *pv;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 4));
mcode = *((u4 *) (sp + 3 * 4));
uf = (unresolved_field *) *((ptrint *) (sp + 2 * 4));
disp = *((s4 *) (sp + 1 * 4));
pv = (u1 *) *((ptrint *) (sp + 0 * 4));
/* get the fieldinfo */
if (!(fi = resolve_field_eager(uf)))
return false;
/* check if the field's class is initialized */
if (!(fi->class->state & CLASS_INITIALIZED))
if (!initialize_class(fi->class))
return false;
*((ptrint *) (pv + disp)) = (ptrint) &(fi->value);
/* patch back original code */
*((u4 *) ra) = mcode;
return true;
}
bool <API key>(u1 *sp)
{
u1 *ra;
u4 mcode;
unresolved_field *uf;
fieldinfo *fi;
u1 byte;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 4));
mcode = *((u4 *) (sp + 3 * 4));
uf = (unresolved_field *) *((ptrint *) (sp + 2 * 4));
/* get the fieldinfo */
if (!(fi = resolve_field_eager(uf)))
return false;
/* patch back original code */
*((u4 *) ra) = mcode;
/* If NOPs are generated, skip them */
if (opt_shownops)
ra += PATCHER_NOPS_SKIP;
/* patch correct offset */
if (fi->type == TYPE_LNG) {
assert(N_VALID_DISP(fi->offset + 4));
/* 2 RX operations, for 2 words; each already contains a 0 or 4 offset. */
*((u4 *) ra ) |= (fi->offset + (*((u4 *) ra) & 0xF));
ra += 4;
*((u4 *) ra ) |= (fi->offset + (*((u4 *) ra) & 0xF));
} else {
assert(N_VALID_DISP(fi->offset));
/* 1 RX operation */
*((u4 *) ra) |= fi->offset;
}
return true;
}
bool <API key>(u1 *sp)
{
OOPS();
u1 *ra;
u8 mcode;
unresolved_field *uf;
fieldinfo *fi;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 8));
mcode = *((u8 *) (sp + 3 * 8));
uf = (unresolved_field *) *((ptrint *) (sp + 2 * 8));
/* get the fieldinfo */
if (!(fi = resolve_field_eager(uf)))
return false;
/* patch back original code */
*((u8 *) ra) = mcode;
/* if we show disassembly, we have to skip the nop's */
if (opt_shownops)
ra = ra + 5;
/* patch the field's offset */
if (IS_2_WORD_TYPE(fi->type) || IS_ADR_TYPE(fi->type)) {
/* handle special case when the base register is %r12 */
if (*(ra + 2) == 0x84) {
*((u4 *) (ra + 4)) = (u4) (fi->offset);
*((u4 *) (ra + 12 + 4)) = (u4) (fi->offset + 4);
}
else {
*((u4 *) (ra + 3)) = (u4) (fi->offset);
*((u4 *) (ra + 11 + 3)) = (u4) (fi->offset + 4);
}
}
else {
/* handle special case when the base register is %r12 */
if (*(ra + 2) == 0x84)
*((u4 *) (ra + 4)) = (u4) (fi->offset);
else
*((u4 *) (ra + 3)) = (u4) (fi->offset);
}
return true;
}
bool patcher_aconst(u1 *sp)
{
OOPS();
u1 *ra;
u8 mcode;
constant_classref *cr;
classinfo *c;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 8));
mcode = *((u8 *) (sp + 3 * 8));
cr = (constant_classref *) *((ptrint *) (sp + 2 * 8));
/* get the classinfo */
if (!(c = <API key>(cr)))
return false;
/* patch back original code */
*((u8 *) ra) = mcode;
/* if we show disassembly, we have to skip the nop's */
if (opt_shownops)
ra = ra + 5;
/* patch the classinfo pointer */
*((ptrint *) (ra + 2)) = (ptrint) c;
return true;
}
bool <API key>(u1 *sp)
{
OOPS();
u1 *ra;
u8 mcode;
constant_classref *cr;
classinfo *c;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 8));
mcode = *((u8 *) (sp + 3 * 8));
cr = (constant_classref *) *((ptrint *) (sp + 2 * 8));
/* get the classinfo */
if (!(c = <API key>(cr)))
return false;
/* patch back original code */
*((u8 *) ra) = mcode;
/* if we show disassembly, we have to skip the nop's */
if (opt_shownops)
ra = ra + 5;
/* patch the classinfo pointer */
*((ptrint *) (ra + 10 + 2)) = (ptrint) c;
return true;
}
bool <API key>(u1 *sp)
{
OOPS();
u1 *ra;
u8 mcode;
constant_classref *cr;
classinfo *c;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 8));
mcode = *((u8 *) (sp + 3 * 8));
cr = (constant_classref *) *((ptrint *) (sp + 2 * 8));
/* get the classinfo */
if (!(c = <API key>(cr)))
return false;
/* patch back original code */
*((u8 *) ra) = mcode;
/* if we show disassembly, we have to skip the nop's */
if (opt_shownops)
ra = ra + 5;
/* patch the classinfo pointer */
*((ptrint *) (ra + 2)) = (ptrint) c;
return true;
}
__PORTED__ bool <API key>(u1 *sp)
{
u1 *ra;
u4 mcode;
unresolved_method *um;
s4 disp;
u1 *pv;
methodinfo *m;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 4));
mcode = *((u4 *) (sp + 3 * 4));
um = (unresolved_method *) *((ptrint *) (sp + 2 * 4));
disp = *((s4 *) (sp + 1 * 4));
pv = (u1 *) *((ptrint *) (sp + 0 * 4));
/* get the fieldinfo */
if (!(m = <API key>(um)))
return false;
*((ptrint *) (pv + disp)) = (ptrint) m->stubroutine;
/* patch back original code */
*((u4 *) ra) = mcode;
/* patch stubroutine */
return true;
}
bool <API key>(u1 *sp)
{
u1 *ra;
u4 mcode;
unresolved_method *um;
methodinfo *m;
s4 off;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 4));
mcode = *((u4 *) (sp + 3 * 4));
um = (unresolved_method *) *((ptrint *) (sp + 2 * 4));
/* get the fieldinfo */
if (!(m = <API key>(um)))
return false;
/* patch back original code */
*((u4 *) ra) = mcode;
/* If NOPs are generated, skip them */
if (opt_shownops)
ra += PATCHER_NOPS_SKIP;
/* patch vftbl index */
off = (s4) (OFFSET(vftbl_t, table[0]) +
sizeof(methodptr) * m->vftblindex);
assert(N_VALID_DISP(off));
*((s4 *)(ra + 4)) |= off;
return true;
}
bool <API key>(u1 *sp)
{
u1 *ra;
u4 mcode;
unresolved_method *um;
methodinfo *m;
s4 idx, off;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 4));
mcode = *((u4 *) (sp + 3 * 4));
um = (unresolved_method *) *((ptrint *) (sp + 2 * 4));
/* get the fieldinfo */
if (!(m = <API key>(um)))
return false;
/* patch back original code */
*((u4 *) ra) = mcode;
/* If NOPs are generated, skip them */
if (opt_shownops)
ra += PATCHER_NOPS_SKIP;
/* get interfacetable index */
idx = (s4) (OFFSET(vftbl_t, interfacetable[0]) -
sizeof(methodptr) * m->class->index) +
N_DISP_MAX;
ASSERT_VALID_DISP(idx);
/* get method offset */
off =
(s4) (sizeof(methodptr) * (m - m->class->methods));
ASSERT_VALID_DISP(off);
/* patch them */
*((s4 *)(ra + 4)) |= idx;
*((s4 *)(ra + 4 + 4)) |= off;
return true;
}
__PORTED__ bool <API key>(u1 *sp)
{
constant_classref *cr;
s4 disp;
u1 *pv;
classinfo *c;
u4 mcode;
u1 *ra;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 4));
mcode = *((u4 *) (sp + 3 * 4));
cr = (constant_classref *) *((ptrint *) (sp + 2 * 4));
disp = *((s4 *) (sp + 1 * 4));
pv = (u1 *) *((ptrint *) (sp + 0 * 4));
/* get the fieldinfo */
if (!(c = <API key>(cr)))
return false;
/* patch class flags */
*((s4 *) (pv + disp)) = (s4) c->flags;
/* patch back original code */
*((u4 *) ra) = mcode;
return true;
}
__PORTED__ bool <API key>(u1 *sp)
{
constant_classref *cr;
s4 disp;
u1 *pv;
classinfo *c;
u4 mcode;
u1 *ra;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 4));
mcode = *((u4 *) (sp + 3 * 4));
cr = (constant_classref *) *((ptrint *) (sp + 2 * 4));
disp = *((s4 *) (sp + 1 * 4));
pv = (u1 *) *((ptrint *) (sp + 0 * 4));
/* get the classinfo */
if (!(c = <API key>(cr)))
return false;
/* patch the classinfo pointer */
*((ptrint *) (pv + disp)) = (ptrint) c;
/* patch back original code */
*((u4 *) ra) = mcode;
return true;
}
bool <API key>(u1 *sp)
{
constant_classref *cr;
s4 disp;
u1 *pv;
classinfo *c;
u4 mcode;
u1 *ra;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 4));
mcode = *((u4 *) (sp + 3 * 4));
cr = (constant_classref *) *((ptrint *) (sp + 2 * 4));
disp = *((s4 *) (sp + 1 * 4));
pv = (u1 *) *((ptrint *) (sp + 0 * 4));
/* get the fieldinfo */
if (!(c = <API key>(cr)))
return false;
/* patch super class' vftbl */
*((ptrint *) (pv + disp)) = (ptrint) c->vftbl;
/* patch back original code */
*((u4 *) ra) = mcode;
return true;
}
bool <API key>(u1 *sp)
{
u1 *ra;
u4 mcode;
constant_classref *cr;
classinfo *c;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 4));
mcode = *((u4 *) (sp + 3 * 4));
cr = (constant_classref *) *((ptrint *) (sp + 2 * 4));
/* get the fieldinfo */
if (!(c = <API key>(cr)))
return false;
/* patch back original code */
*((u4 *) ra) = mcode;
/* If NOPs are generated, skip them */
if (opt_shownops)
ra += PATCHER_NOPS_SKIP;
/* patch super class index */
/* From here, split your editor and open codegen.c */
switch (*(ra + 1) >> 4) {
case REG_ITMP1:
/* First M_ALD is into ITMP1 */
/* INSTANCEOF code */
*(u4 *)(ra + SZ_L + SZ_L) |= (u2)(s2)(- c->index);
*(u4 *)(ra + SZ_L + SZ_L + SZ_AHI + SZ_BRC) |=
(u2)(s2)(OFFSET(vftbl_t, interfacetable[0]) -
c->index * sizeof(methodptr*));
break;
case REG_ITMP2:
/* First M_ALD is into ITMP2 */
/* CHECKCAST code */
*(u4 *)(ra + SZ_L + SZ_L) |= (u2)(s2)(- c->index);
*(u4 *)(ra + SZ_L + SZ_L + SZ_AHI + SZ_BRC + SZ_ILL) |=
(u2)(s2)(OFFSET(vftbl_t, interfacetable[0]) -
c->index * sizeof(methodptr*));
break;
default:
assert(0);
break;
}
return true;
}
bool <API key>(u1 *sp)
{
OOPS();
u1 *ra;
u8 mcode;
constant_classref *cr;
classinfo *c;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 8));
mcode = *((u8 *) (sp + 3 * 8));
cr = (constant_classref *) *((ptrint *) (sp + 2 * 8));
/* get the fieldinfo */
if (!(c = <API key>(cr)))
return false;
/* patch back original code */
*((u8 *) ra) = mcode;
/* if we show disassembly, we have to skip the nop's */
if (opt_shownops)
ra = ra + 5;
/* patch super class' vftbl */
*((ptrint *) (ra + 2)) = (ptrint) c->vftbl;
*((ptrint *) (ra + 10 + 7 + 7 + 3 + 2)) = (ptrint) c->vftbl;
return true;
}
bool <API key>(u1 *sp)
{
OOPS();
u1 *ra;
u8 mcode;
constant_classref *cr;
classinfo *c;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 8));
mcode = *((u8 *) (sp + 3 * 8));
cr = (constant_classref *) *((ptrint *) (sp + 2 * 8));
/* get the fieldinfo */
if (!(c = <API key>(cr)))
return false;
/* patch back original code */
*((u8 *) ra) = mcode;
/* if we show disassembly, we have to skip the nop's */
if (opt_shownops)
ra = ra + 5;
/* patch super class' vftbl */
*((ptrint *) (ra + 2)) = (ptrint) c->vftbl;
return true;
}
__PORTED__ bool patcher_clinit(u1 *sp)
{
u1 *ra;
u4 mcode;
classinfo *c;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 4));
mcode = *((u4 *) (sp + 3 * 4));
c = (classinfo *) *((ptrint *) (sp + 2 * 4));
/* check if the class is initialized */
if (!(c->state & CLASS_INITIALIZED))
if (!initialize_class(c))
return false;
/* patch back original code */
*((u4 *) ra) = mcode;
return true;
}
#ifdef ENABLE_VERIFIER
__PORTED__ bool <API key>(u1 *sp)
{
u1 *ra;
u4 mcode;
unresolved_class *uc;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 4));
mcode = *((u4 *) (sp + 3 * 4));
uc = (unresolved_class *) *((ptrint *) (sp + 2 * 4));
/* resolve the class and check subtype constraints */
if (!<API key>(uc))
return false;
/* patch back original code */
*((u4 *) ra) = mcode;
return true;
}
#endif /* ENABLE_VERIFIER */
#if !defined(<API key>)
__PORTED__ bool <API key>(u1 *sp)
{
u1 *ra;
u4 mcode;
methodinfo *m;
functionptr f;
s4 disp;
u1 *pv;
/* get stuff from the stack */
ra = (u1 *) *((ptrint *) (sp + 5 * 4));
mcode = *((u4 *) (sp + 3 * 4));
disp = *((s4 *) (sp + 1 * 4));
m = (methodinfo *) *((ptrint *) (sp + 2 * 4));
pv = (u1 *) *((ptrint *) (sp + 0 * 4));
/* resolve native function */
if (!(f = <API key>(m)))
return false;
/* patch native function pointer */
*((ptrint *) (pv + disp)) = (ptrint) f;
/* patch back original code */
*((u4 *) ra) = mcode;
return true;
}
#endif /* !defined(<API key>) */ |
// <API key>: GPL-2.0-or-later
// GiiBiiAdvance - GBA/GB emulator
#include "../build_options.h"
#include "../debug_utils.h"
#include "cpu.h"
#include "gameboy.h"
#include "gb_main.h"
#include "general.h"
#include "interrupts.h"
#include "memory.h"
#include "ppu.h"
#include "video.h"
extern _GB_CONTEXT_ GameBoy;
void GB_PPUWriteLYC_DMG(int reference_clocks, int value)
{
<API key>(reference_clocks);
GameBoy.Memory.IO_Ports[LYC_REG - 0xFF00] = value;
if (GameBoy.Emulator.lcd_on)
{
GB_PPUCheckLYC();
<API key>();
GB_CPUBreakLoop();
}
}
void GB_PPUWriteLCDC_DMG(int reference_clocks, int value)
{
_GB_MEMORY_ *mem = &GameBoy.Memory;
<API key>(reference_clocks);
if ((mem->IO_Ports[LCDC_REG - 0xFF00] ^ value) & (1 << 7))
{
mem->IO_Ports[LY_REG - 0xFF00] = 0x00;
GameBoy.Emulator.CurrentScanLine = 0;
mem->IO_Ports[STAT_REG - 0xFF00] &= 0xFC;
GameBoy.Emulator.ScreenMode = 0;
if (value & (1 << 7))
{
GameBoy.Emulator.ly_clocks = 456;
GameBoy.Emulator.CurrentScanLine = 0;
GameBoy.Emulator.ScreenMode = 1;
mem->IO_Ports[STAT_REG - 0xFF00] &= 0xFC;
mem->IO_Ports[STAT_REG - 0xFF00] |= 1;
}
else
{
GameBoy.Emulator.ly_clocks = 0;
}
<API key>();
mem->IO_Ports[IF_REG - 0xFF00] &= ~I_STAT;
}
GameBoy.Emulator.lcd_on = value >> 7;
mem->IO_Ports[LCDC_REG - 0xFF00] = value;
GB_CPUBreakLoop();
}
void GB_PPUWriteSTAT_DMG(unused__ int reference_clocks, int value)
{
_GB_MEMORY_ *mem = &GameBoy.Memory;
<API key>(<API key>());
GB_CPUBreakLoop();
mem->IO_Ports[STAT_REG - 0xFF00] &= 0x07;
mem->IO_Ports[STAT_REG - 0xFF00] |= value & 0xF8;
<API key>();
// BUG
int mode_0_or_1 = (GameBoy.Emulator.ScreenMode == 0)
|| (GameBoy.Emulator.ScreenMode == 1);
if (GameBoy.Emulator.lcd_on && mode_0_or_1)
{
<API key>(I_STAT);
}
// Old code
//if ((GameBoy.Emulator.CGBEnabled == 0) && GameBoy.Emulator.lcd_on &&
// (GameBoy.Emulator.ScreenMode == 2))
// <API key>(I_STAT);
//if (value & IENABLE_OAM)
// Debug_DebugMsgArg("Wrote STAT - ENABLE OAM INT");
}
void <API key>(int increment_clocks)
{
_GB_MEMORY_ *mem = &GameBoy.Memory;
GameBoy.Emulator.ly_clocks += increment_clocks;
int done = 0;
while (done == 0)
{
switch (GameBoy.Emulator.ScreenMode)
{
case 2:
if (GameBoy.Emulator.ly_clocks >= 82)
{
GameBoy.Emulator.ScreenMode = 3;
mem->IO_Ports[STAT_REG - 0xFF00] |= 0x03;
<API key>();
}
else
{
done = 1;
}
break;
case 3:
if (GameBoy.Emulator.ly_clocks >= 252)
{
GameBoy.Emulator.DrawScanlineFn(
GameBoy.Emulator.CurrentScanLine);
GameBoy.Emulator.ScreenMode = 0;
mem->IO_Ports[STAT_REG - 0xFF00] &= 0xFC;
GameBoy.Emulator.ly_drawn = 1;
<API key>();
}
else
{
done = 1;
}
break;
case 0:
if (GameBoy.Emulator.ly_drawn == 0)
{
if (GameBoy.Emulator.ly_clocks >= 4)
{
if (GameBoy.Emulator.CurrentScanLine == 144)
{
GameBoy.Emulator.ScreenMode = 1;
mem->IO_Ports[STAT_REG - 0xFF00] &= 0xFC;
mem->IO_Ports[STAT_REG - 0xFF00] |= 0x01;
<API key>(I_VBLANK);
}
else
{
GameBoy.Emulator.ScreenMode = 2;
mem->IO_Ports[STAT_REG - 0xFF00] &= 0xFC;
mem->IO_Ports[STAT_REG - 0xFF00] |= 0x02;
GB_PPUCheckLYC();
}
<API key>();
}
else
{
done = 1;
}
}
else
{
if (GameBoy.Emulator.ly_clocks >= 456)
{
GameBoy.Emulator.ly_clocks -= 456;
GameBoy.Emulator.CurrentScanLine++;
GameBoy.Emulator.ly_drawn = 0;
mem->IO_Ports[LY_REG - 0xFF00] =
GameBoy.Emulator.CurrentScanLine;
if (GameBoy.Emulator.CurrentScanLine == 144)
{
GB_PPUCheckLYC();
<API key>();
}
}
else
{
done = 1;
}
}
break;
case 1:
if (GameBoy.Emulator.ly_clocks >= 456)
{
GameBoy.Emulator.ly_clocks -= 456;
if (GameBoy.Emulator.CurrentScanLine == 0)
{
GameBoy.Emulator.ScreenMode = 2;
mem->IO_Ports[STAT_REG - 0xFF00] &= 0xFC;
mem->IO_Ports[STAT_REG - 0xFF00] |= 0x02;
<API key>();
break;
}
GameBoy.Emulator.CurrentScanLine++;
GB_PPUCheckLYC();
if (GameBoy.Emulator.CurrentScanLine == 153)
{
// 8 clocks this scanline
GameBoy.Emulator.ly_clocks += (456 - 8);
}
else if (GameBoy.Emulator.CurrentScanLine == 154)
{
GameBoy.Emulator.CurrentScanLine = 0;
GameBoy.Emulator.FrameDrawn = 1;
// 456 - 8 cycles left of vblank...
GameBoy.Emulator.ly_clocks += 8;
}
mem->IO_Ports[LY_REG - 0xFF00] =
GameBoy.Emulator.CurrentScanLine;
GB_PPUCheckLYC();
<API key>();
}
else
{
done = 1;
}
break;
default:
done = 1;
break;
}
}
}
int <API key>(void)
{
int <API key> = 0x7FFFFFFF;
if (GameBoy.Emulator.lcd_on)
{
switch (GameBoy.Emulator.ScreenMode)
{
case 2:
<API key> = 82 - GameBoy.Emulator.ly_clocks;
break;
case 3:
<API key> = 4;
break;
case 0:
<API key> = 4;
//<API key> = 456 - GameBoy.Emulator.ly_clocks;
break;
case 1:
<API key> = 456 - GameBoy.Emulator.ly_clocks;
break;
default:
break;
}
}
return <API key>;
} |
package org.xbrlapi.data.dom.tests;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.Assert;
import org.testng.AssertJUnit;
import java.net.URI;
import org.xbrlapi.utilities.XBRLException;
/**
* Test the XML DOM XBRLAPI Store implementation.
* @author Geoffrey Shuetrim (geoff@galexy.net)
*/
public class <API key> extends BaseTestCase {
private final String STARTING_POINT = "test.data.label.links";
@BeforeMethod
protected void setUp() throws Exception {
super.setUp();
loader.discover(this.getURI(STARTING_POINT));
}
@AfterMethod
protected void tearDown() throws Exception {
super.tearDown();
}
@Test
public void <API key>() {
try {
URI documentToDelete = this.getURI(STARTING_POINT);
store.deleteDocument(documentToDelete);
AssertJUnit.assertFalse(store.getDocumentURIs().contains(documentToDelete));
} catch (XBRLException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
@Test
public void <API key>() {
try {
int initialSize = store.getDocumentURIs().size();
store.<API key>(this.getURI(STARTING_POINT));
AssertJUnit.assertFalse(store.getDocumentURIs().contains(this.getURI(STARTING_POINT)));
AssertJUnit.assertEquals(initialSize-3,store.getDocumentURIs().size());
} catch (XBRLException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
} |
// main.c
// 20150518-58
#include <stdio.h>
int main()
{
float p(int,int);
int n,x;
printf("input n & x:");
scanf("%d %d",&n,&x);
printf("n=%d,x=%d\n",n,x);
printf("p%d(%d) = %f\n",n,x,p(n,x));
return 0;
}
float p(int n,int x)
{
if(n == 0)
return(1);
else if(n == 1)
return(x);
else
return((2*n-1)*x*p((n-1),x) -(n-1)*p((n-2),x)/n);
} |
package org.n52.sos.i18n;
import org.hamcrest.Matchers;
import java.util.Locale;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.n52.iceland.i18n.I18NSerializer;
import org.n52.janmayen.i18n.MultilingualString;
/**
* TODO JavaDoc
*
* @author Christian Autermann
*/
public class I18NSerializerTest {
private static final String TEXT = "text!;\")=?§";
@Rule
public final ErrorCollector errors = new ErrorCollector();
@Test
public void testSingle() {
test(new MultilingualString().addLocalization(Locale.ENGLISH, "text"));
test(new MultilingualString()
.addLocalization(Locale.ENGLISH, TEXT));
}
@Test
public void testMultiple() {
test(new MultilingualString()
.addLocalization(Locale.ENGLISH, TEXT)
.addLocalization(Locale.CANADA_FRENCH, TEXT)
.addLocalization(Locale.TRADITIONAL_CHINESE, TEXT)
.addLocalization(Locale.GERMANY, TEXT)
.addLocalization(Locale.KOREAN, TEXT));
}
private void test(MultilingualString string) {
errors.checkThat(string, Matchers.is(Matchers.notNullValue()));
String encoded = new I18NSerializer().encode(string);
System.out.println(encoded);
errors.checkThat(encoded.isEmpty(), Matchers.is(string.isEmpty()));
MultilingualString decoded = new I18NSerializer().decode(encoded);
errors.checkThat(decoded, Matchers.is(Matchers.equalTo(string)));
}
} |
#include "proslic.h"
#include "si3226.h"
Si3226_General_Cfg <API key> = {
BO_DCDC_QCUK,
0x8720000L, /* VBATR_EXPECT */
0x3D70000L, /* VBATH_EXPECT */
0x0L, /* DCDC_FSW_VTHLO */
0x0L, /* DCDC_FSW_VHYST */
0x1300000L, /* DCDC_VREF_MIN */
0x5A00000L, /* DCDC_VREF_MIN_RING */
0x200000L, /* DCDC_FSW_NORM */
0x200000L, /* DCDC_FSW_NORM_LO */
0x200000L, /* DCDC_FSW_RING */
0x100000L, /* DCDC_FSW_RING_LO */
0xD980000L, /* DCDC_DIN_LIM */
0xC00000L, /* DCDC_VOUT_LIM */
0x0L, /* DCDC_DCFF_ENABLE */
0x500000L, /* DCDC_UVHYST */
0x600000L, /* DCDC_UVTHRESH */
0xB00000L, /* DCDC_OVTHRESH */
0x1F00000L, /* DCDC_OITHRESH */
0x100000L, /* DCDC_SWDRV_POL */
0x300000L, /* DCDC_SWFET */
0x600000L, /* DCDC_VREF_CTRL */
0x200000L, /* DCDC_RNGTYPE */
0x0L, /* DCDC_ANA_GAIN */
0x0L, /* DCDC_ANA_TOFF */
0x0L, /* DCDC_ANA_TONMIN */
0x0L, /* DCDC_ANA_TONMAX */
0x0L, /* DCDC_ANA_DSHIFT */
0x0L, /* DCDC_ANA_LPOLY */
0x7FeF000L, /* COEF_P_HVIC */
0x68D000L, /* P_TH_HVIC */
0x0, /* CM_CLAMP */
0x3F, /* AUTO */
0x0, /* DAA_CNTL */
0x7F, /* IRQEN1 */
0xFF, /* IRQEN2 */
0xFF, /* IRQEN3 */
0xFF, /* IRQEN4 */
0x0, /* ENHANCE */
0, /* DAA_ENABLE */
0x8000000L, /* SCALE_KAUDIO */
0x151EB80L, /* AC_ADC_GAIN */
};
Si3226_DTMFDec_Cfg <API key>[] = {
{0x2d40000L,0x1a660000L,0x2d40000L,0x6ba0000L,0x1dcc0000L,0x33f0000L,0xbd30000L,0x19d20000L,0x4150000L,0x188F0000L,0x4150000L,0xd970000L,0x18620000L,0xf1c0000L}
};
Si3226_GPIO_Cfg <API key> = {
0,0,0,0,0,0,0
};
Si3226_CI_Cfg Si3226_CI_Presets [] = {
{0}
};
<API key> <API key> [] = {
{0x1377080L,0},
{0x80C3180L,0}
};
Si3226_Ring_Cfg Si3226_Ring_Presets[] ={
{ /* <API key> */
0x00050000L, /* RTPER */
0x07EFD9D5L, /* RINGFR */
0x001BD493L, /* RINGAMP */
0x00000000L, /* RINGPHAS */
0x00000000L, /* RINGOF */
0x15E5200EL, /* SLOPE_RING */
0x00D16348L, /* IRING_LIM */
0x0068C6BBL, /* RTACTH */
0x0FFFFFFFL, /* RTDCTH */
0x00006000L, /* RTACDB */
0x00006000L, /* RTDCDB */
0x0064874DL, /* VOV_RING_BAT */
0x0064874DL, /* VOV_RING_GND */
0x049CE106L, /* VBATR_EXPECT */
0x80, /* RINGTALO */
0x3E, /* RINGTAHI */
0x00, /* RINGTILO */
0x7D, /* RINGTIHI */
0x01000547L, /* ADAP_RING_MIN_I */
0x00003000L, /* COUNTER_IRING_VAL */
0x00051EB8L, /* COUNTER_VTR_VAL */
0x0163063FL, /* CONST_028 */
0x019E31F4L, /* CONST_032 */
0x01F108BEL, /* CONST_036 */
0x026D4AEEL, /* CONST_046 */
0x00370000L, /* RRD_DELAY */
0x00190000L, /* RRD_DELAY2 */
0x01893740L, /* DCDC_VREF_MIN_RNG */
0x58, /* RINGCON */
0x01, /* USERSTAT */
0x024E7083L, /* VCM_RING */
0x024E7083L, /* VCM_RING_FIXED */
0x003126E8L, /* DELTA_VCM */
0x200000L, /* DCDC_RNGTYPE */
},
{ /* <API key> */
0x00050000L, /* RTPER */
0x07EFD9D5L, /* RINGFR */
0x001BD493L, /* RINGAMP */
0x00000000L, /* RINGPHAS */
0x00000000L, /* RINGOF */
0x15E5200EL, /* SLOPE_RING */
0x00D16348L, /* IRING_LIM */
0x0068C6BBL, /* RTACTH */
0x0FFFFFFFL, /* RTDCTH */
0x00006000L, /* RTACDB */
0x00006000L, /* RTDCDB */
0x0064874DL, /* VOV_RING_BAT */
0x0064874DL, /* VOV_RING_GND */
0x0565EFA2L, /* VBATR_EXPECT */
0x80, /* RINGTALO */
0x3E, /* RINGTAHI */
0x00, /* RINGTILO */
0x7D, /* RINGTIHI */
0x01000547L, /* ADAP_RING_MIN_I */
0x00003000L, /* COUNTER_IRING_VAL */
0x00051EB8L, /* COUNTER_VTR_VAL */
0x0163063FL, /* CONST_028 */
0x019E31F4L, /* CONST_032 */
0x01F108BEL, /* CONST_036 */
0x026D4AEEL, /* CONST_046 */
0x00370000L, /* RRD_DELAY */
0x00190000L, /* RRD_DELAY2 */
0x01893740L, /* DCDC_VREF_MIN_RNG */
0x58, /* RINGCON */
0x00, /* USERSTAT */
0x02B2F7D1L, /* VCM_RING */
0x02B2F7D1L, /* VCM_RING_FIXED */
0x003126E8L, /* DELTA_VCM */
0x200000L, /* DCDC_RNGTYPE */
},
{ /* <API key> */
0x00050000L, /* RTPER */
0x07EFD9D5L, /* RINGFR */
0x002203D0L, /* RINGAMP */
0x00000000L, /* RINGPHAS */
0x049A5F69L, /* RINGOF */
0x15E5200EL, /* SLOPE_RING */
0x00D16348L, /* IRING_LIM */
0x032EDF91L, /* RTACTH */
0x0038E38EL, /* RTDCTH */
0x00006000L, /* RTACDB */
0x00006000L, /* RTDCDB */
0x007ADE42L, /* VOV_RING_BAT */
0x007ADE42L, /* VOV_RING_GND */
0x08B5BA6CL, /* VBATR_EXPECT */
0x80, /* RINGTALO */
0x3E, /* RINGTAHI */
0x00, /* RINGTILO */
0x7D, /* RINGTIHI */
0x0138EA01L, /* ADAP_RING_MIN_I */
0x00003000L, /* COUNTER_IRING_VAL */
0x00051EB8L, /* COUNTER_VTR_VAL */
0x01A40BA6L, /* CONST_028 */
0x01EA0D97L, /* CONST_032 */
0x024C104FL, /* CONST_036 */
0x02DF1463L, /* CONST_046 */
0x00370000L, /* RRD_DELAY */
0x00190000L, /* RRD_DELAY2 */
0x01893740L, /* DCDC_VREF_MIN_RNG */
0x58, /* RINGCON */
0x01, /* USERSTAT */
0x045ADD36L, /* VCM_RING */
0x045ADD36L, /* VCM_FIXED_RING */
0x003126E8L, /* DELTA_VCM */
0x200000L, /* DCDC_RNGTYPE */
}
};
Si3226_DCfeed_Cfg <API key>[] = {
/* inputs: v_vlim=48.000, i_vlim=0.000, v_rfeed=42.800, i_rfeed=10.000,v_ilim=33.200, i_ilim=20.000,
vcm_oh=27.000, vov_gnd=4.000, vov_bat=4.000, r_ring=320.000
lcronhk=10.000, lcroffhk=12.000, lcrdbi=5.000, longhith=8.000, longloth=7.000, longdbi=5.000
lcrmask=80.000, lcrmask_polrev=80.000, lcrmask_state=200.000, lcrmask_linecap=200.000 */
{ /* DCFEED_48V_20MA */
0x1DDF41C9L, /* SLOPE_VLIM */
0x1EF68D5EL, /* SLOPE_RFEED */
0x40A0E0L, /* SLOPE_ILIM */
0x18AAD168L, /* SLOPE_DELTA1 */
0x1CA39FFAL, /* SLOPE_DELTA2 */
0x5A38633L, /* V_VLIM */
0x5072476L, /* V_RFEED */
0x3E67006L, /* V_ILIM */
0xFDFAB5L, /* CONST_RFEED */
0x5D0FA6L, /* CONST_ILIM */
0x2D8D96L, /* I_VLIM */
0x5B0AFBL, /* LCRONHK */
0x6D4060L, /* LCROFFHK */
0x8000L, /* LCRDBI */
0x48D595L, /* LONGHITH */
0x3FBAE2L, /* LONGLOTH */
0x8000L, /* LONGDBI */
0x120000L, /* LCRMASK */
0x80000L, /* LCRMASK_POLREV */
0x140000L, /* LCRMASK_STATE */
0x140000L, /* LCRMASK_LINECAP */
0x1BA5E35L, /* VCM_OH */
0x418937L, /* VOV_BAT */
0x418937L /* VOV_GND */
},
{ /* DCFEED_48V_25MA */
0x1D46EA04L, /* SLOPE_VLIM */
0x1EA4087EL, /* SLOPE_RFEED */
0x40A0E0L, /* SLOPE_ILIM */
0x1A224120L, /* SLOPE_DELTA1 */
0x1D4FB32EL, /* SLOPE_DELTA2 */
0x5A38633L, /* V_VLIM */
0x5072476L, /* V_RFEED */
0x3E67006L, /* V_ILIM */
0x13D7962L, /* CONST_RFEED */
0x74538FL, /* CONST_ILIM */
0x2D8D96L, /* I_VLIM */
0x5B0AFBL, /* LCRONHK */
0x6D4060L, /* LCROFFHK */
0x8000L, /* LCRDBI */
0x48D595L, /* LONGHITH */
0x3FBAE2L, /* LONGLOTH */
0x8000L, /* LONGDBI */
0x120000L, /* LCRMASK */
0x80000L, /* LCRMASK_POLREV */
0x140000L, /* LCRMASK_STATE */
0x140000L, /* LCRMASK_LINECAP */
0x1BA5E35L, /* VCM_OH */
0x418937L, /* VOV_BAT */
0x418937L /* VOV_GND */
}
};
<API key> <API key>[] ={
{ /* Si3226_600_0_0_30_0.txt - ZSYN_600_0_0 */
{0x07F46C00L,0x000E4600L,0x00008580L,0x1FFD6100L, /* TXACEQ */
0x07EF5000L,0x0013F580L,0x1FFDE000L,0x1FFCB280L}, /* RXACEQ */
{0x0027CB00L,0x1F8A8880L,0x02801180L,0x1F625C80L, /* ECFIR/ECIIR */
0x0314FB00L,0x1E6B8E80L,0x00C5FF00L,0x1FC96F00L,
0x1FFD1200L,0x00023C00L,0x0ED29D00L,0x192A9400L},
{0x00810E00L,0x1EFEBE80L,0x00803500L,0x0FF66D00L, /* ZSYNTH */
0x18099080L,0x59},
0x088E0D80L, /* TXACGAIN */
0x01456D80L, /* RXACGAIN */
0x07ABE580L,0x18541B00L,0x0757CB00L, /* RXHPF */
0, 0 /* 0dB RX, 0dB TX */
},
{ /* <API key>.txt - ZSYN_270_750_150*/
{0x071F7A80L,0x1FD01280L,0x00132700L,0x1FFEF980L, /* TXACEQ */
0x0A8AA300L,0x1B9A5500L,0x008E7F00L,0x1FD7F300L}, /* RXACEQ */
{0x0068CA00L,0x1EAE1E00L,0x0394FA00L,0x1E94AE80L, /* ECFIR/ECIIR */
0x0356D800L,0x0166CA80L,0x1EC16380L,0x01DE2780L,
0x1F852300L,0x0046BE80L,0x02F17C80L,0x1EBCD280L},
{0x028A0C00L,0x19EE4580L,0x03876100L,0x0A762700L, /* ZSYNTH */
0x1D87A380L,0x93},
0x08000000L, /* TXACGAIN */
0x0109C280L, /* RXACGAIN */
0x07BC6F00L,0x18439180L,0x0778DE00L, /* RXHPF */
0, 0 /* 0dB RX, 0dB TX */
},
{ /* <API key>.txt - ZSYN_370_620_310 */
{0x07E59E80L,0x1FD33400L,0x1FFDF800L,0x1FFD8300L, /* TXACEQ */
0x09F38000L,0x1C1C5A00L,0x1F94D700L,0x1FDE5800L}, /* RXACEQ */
{0x00234480L,0x1F9CDD00L,0x01F5D580L,0x1FF39000L, /* ECFIR/ECIIR */
0x02C17180L,0x1FBE2500L,0x00DFFE80L,0x00441A80L,
0x003BF800L,0x1FC42400L,0x0D9EB380L,0x1A514580L},
{0x003ED200L,0x1F5D6B80L,0x0063B100L,0x0F12E200L, /* ZSYNTH */
0x18EC9380L,0x8B},
0x08000000L, /* TXACGAIN */
0x0127C700L, /* RXACGAIN */
0x07B51200L,0x184AEE80L,0x076A2480L, /* RXHPF */
0, 0 /* 0dB RX, 0dB TX */
},
{ /* <API key>.txt - ZSYN_220_820_120 */
{0x06E38480L,0x1FD33B00L,0x00069780L,0x1FFCAB80L, /* TXACEQ */
0x0A78F680L,0x1BC5C880L,0x009AEA00L,0x1FD66D80L}, /* RXACEQ */
{0x00378B00L,0x1F3FCA00L,0x02B5ED00L,0x1F2B6200L, /* ECFIR/ECIIR */
0x04189080L,0x1F8A4480L,0x01113680L,0x00373100L,
0x001DAE80L,0x1FE02F00L,0x0C89C780L,0x1B689680L},
{0x02391100L,0x1A886080L,0x033E3B00L,0x0A136200L, /* ZSYNTH */
0x1DEA4180L,0x8C},
0x08000000L, /* TXACGAIN */
0x01019200L, /* RXACGAIN */
0x07BD1680L,0x1842EA00L,0x077A2D00L, /* RXHPF */
0, 0 /* 0dB RX, 0dB TX */
},
{ /* <API key>.txt - ZSYN_600_0_1000 */
{0x07F83980L,0x00056200L,0x1FFEE880L,0x1FFB1900L, /* TXACEQ */
0x08405000L,0x001DD200L,0x0003DB80L,0x00008700L}, /* RXACEQ */
{0x1FEE8700L,0x009B2B00L,0x000C9680L,0x03700100L, /* ECFIR/ECIIR */
0x1F62E400L,0x01C77400L,0x1FBBCF80L,0x0089D500L,
0x005CFF80L,0x1FA96E80L,0x0F679480L,0x18962A80L},
{0x00657C00L,0x1F2FA580L,0x006ADE00L,0x0FE12100L, /* ZSYNTH */
0x181ED080L,0x57},
0x08618D80L, /* TXACGAIN */
0x013E3400L, /* RXACGAIN */
0x0717CE80L,0x18E83200L,0x062F9C80L, /* RXHPF */
0, 0 /* 0dB RX, 0dB TX */
},
{ /* <API key>.txt - ZSYN_200_680_100 */
{0x073A7B00L,0x1FCEB400L,0x0002C680L,0x1FFD0780L, /* TXACEQ */
0x09BA8580L,0x1D2DF780L,0x006F5000L,0x1FDFE200L}, /* RXACEQ */
{0x0004B700L,0x000F9800L,0x01201200L,0x00E1D880L, /* ECFIR/ECIIR */
0x03314A00L,0x1E84A580L,0x029D2380L,0x1E6F3400L,
0x00E99200L,0x1F121100L,0x0588BC00L,0x025CAE00L},
{0x01415C00L,0x1C98C180L,0x0225A500L,0x0A138200L, /* ZSYNTH */
0x1DEA2280L,0x8E},
0x08000000L, /* TXACGAIN */
0x010DFD80L, /* RXACGAIN */
0x07BA2180L,0x1845DF00L,0x07744380L, /* RXHPF */
0, 0 /* 0dB RX, 0dB TX */
},
{ /* <API key>.txt - ZSYN_200_820_115 */
{0x06D56380L,0x1FDF1900L,0x00095A00L,0x1FFDAA80L, /* TXACEQ */
0x0A596300L,0x1C067880L,0x0095EF00L,0x1FD7AF00L}, /* RXACEQ */
{0x00687000L,0x1EAE1800L,0x03983D80L,0x1EB14B00L, /* ECFIR/ECIIR */
0x037B3E80L,0x016FC900L,0x1ED60100L,0x01B17D80L,
0x1FA20D00L,0x001CE900L,0x027D3380L,0x1DBDBA80L},
{0x00246300L,0x1E5E0580L,0x017D2300L,0x0A138100L, /* ZSYNTH */
0x1DEA2280L,0xA7},
0x08000000L, /* TXACGAIN */
0x01009500L, /* RXACGAIN */
0x07BBEE80L,0x18441200L,0x0777DD80L, /* RXHPF */
0, 0 /* 0dB RX, 0dB TX */
}
};
Si3226_FSK_Cfg Si3226_FSK_Presets[] ={
/* inputs: mark freq=1200.000, space freq2200.000, amp=0.220, baud=1200.000, startStopDis=0, interrupt depth = 0 */
{ 0x2232000L, 0x77C2000L, 0x3C0000L, 0x200000L, 0x6B60000L, 0x79C0000L,0, 0 }
};
Si3226_Tone_Cfg Si3226_Tone_Presets[] ={
/* inputs: freq1 = 350.000, amp1 = -18.000, freq2 = 440.000, amp2 = -18.000, ta1 = 0.000, ti1 = 0.000, ta2 = 0.000, ti2 = 0.000*/
{ {0x7B30000L, 0x3A000L, 0x0L, 0x0, 0x0, 0x0, 0x0}, {0x7870000L, 0x4A000L, 0x0L, 0x0, 0x0, 0x0, 0x0}, 0x66 },
/* inputs: freq1 = 480.000, amp1 = -18.000, freq2 = 620.000, amp2 = -18.000, ta1 = 0.500, ti1 = 0.500, ta2 = 0.500, ti2 = 0.500*/
{ {0x7700000L, 0x52000L, 0x0L, 0xA0, 0xF, 0xA0, 0xF}, {0x7120000L, 0x6A000L, 0x0L, 0xA0, 0xF, 0xA0, 0xF}, 0x66 },
/* inputs: freq1 = 480.000, amp1 = -18.000, freq2 = 440.000, amp2 = -18.000, ta1 = 2.000, ti1 = 4.000, ta2 = 2.000, ti2 = 4.000*/
{ {0x7700000L, 0x52000L, 0x0L, 0x80, 0x3E, 0x0, 0x7D}, {0x7870000L, 0x4A000L, 0x0L, 0x80, 0x3E, 0x0, 0x7D}, 0x66 },
/* inputs: freq1 = 480.000, amp1 = -18.000, freq2 = 620.000, amp2 = -18.000, ta1 = 0.300, ti1 = 0.200, ta2 = 0.300, ti2 = 0.200*/
{ {0x7700000L, 0x52000L, 0x0L, 0x60, 0x9, 0x40, 0x6}, {0x7120000L, 0x6A000L, 0x0L, 0x60, 0x9, 0x40, 0x6}, 0x66 },
/* inputs: freq1 = 480.000, amp1 = -18.000, freq2 = 620.000, amp2 = -18.000, ta1 = 0.200, ti1 = 0.200, ta2 = 0.200, ti2 = 0.200*/
{ {0x7700000L, 0x52000L, 0x0L, 0x40, 0x6, 0x40, 0x6}, {0x7120000L, 0x6A000L, 0x0L, 0x40, 0x6, 0x40, 0x6}, 0x66 }
};
Si3226_PCM_Cfg Si3226_PCM_Presets[] ={
/* inputs: u-law narrowband positive edge, dtx positive edge, both disabled, tx hwy = A, rx hwy = A */
{ 0x1, 0x0, 0x0, 0x0 }
}; |
$wnd.showcase.runAsyncCallback26("fLb(718,1,a7c);_.xc=function L0b(){var a,b,c;LNb(this.b,(a=new FPc,Vs(a.f,ydd,10),CPc(a,new Qzc('Without a direction estimator, the widget\\'s direction is unaffected by the value the user types in. This makes the entry of opposite-direction text confusing and inconvenient.<br><b>Try typing \"(212) 765 4321\" or \"Hi, how are you?\" into the following right-to-left TextArea (which had the direction estimator turned off):<\\/b>')),b=new uNc,zD(b.b,null),_Hc(b,(mI(),lI)),CPc(a,b),CPc(a,new Qzc('<b>The following TextArea has the default direction estimator in effect, and is thus bidi-aware. Check it by replacing the right-to-left text with some English, e.g. the sample strings above:<\\/b>')),c=new uNc,Ws((wrc(),c.hb),qfd,'\\u0643\\u0645 \\u0639\\u062F\\u062F \\u062D\\u0628\\u0627\\u062A \\u0627\\u0644\\u0631\\u0645\\u0644 \\u0641\\u064A \\u0627\\u0644\\u0634\\u0627\\u0637\\u0626?'),yD(c.b),CPc(a,c),a))};P7c(lo)(26);\n//# sourceURL=showcase-26.js\n") |
#include "src/sview/sview.h"
#define _DEBUG 0
#define ECLIPSE_RT 0
int cpus_per_node = 1;
int g_node_scaling = 1;
//static int _l_topo_color_ndx = MAKE_TOPO_1;
//static int _l_sw_color_ndx = 0;
/* These need to be in alpha order (except POS and CNT) */
enum {
SORTID_POS = POS_LOC,
SORTID_ARCH,
SORTID_BASE_WATTS,
SORTID_BOARDS,
SORTID_BOOT_TIME,
SORTID_COLOR,
SORTID_CPUS,
SORTID_CPU_LOAD,
<API key>,
SORTID_CORES,
<API key>,
SORTID_ERR_CPUS,
SORTID_FEATURES,
SORTID_GRES,
SORTID_IDLE_CPUS,
SORTID_NAME,
SORTID_NODE_ADDR,
<API key>,
SORTID_MEMORY, /* RealMemory */
SORTID_REASON,
SORTID_RACK_MP,
<API key>,
SORTID_SOCKETS,
SORTID_STATE,
SORTID_STATE_NUM,
SORTID_THREADS,
SORTID_DISK, /* TmpDisk */
SORTID_UPDATED,
SORTID_USED_CPUS,
SORTID_USED_MEMORY,
SORTID_VERSION,
SORTID_WEIGHT,
SORTID_CNT
};
typedef struct {
int node_col;
char *nodelist;
} process_node_t;
/*these are the settings to apply for the user
* on the first startup after a fresh slurm install.*/
static char *_initial_page_opts = "Name,RackMidplane,State,CPU_Count,"
"Used_CPU_Count,Error_CPU_Count,CoresPerSocket,Sockets,ThreadsPerCore,"
"Real_Memory,Tmp_Disk";
static display_data_t display_data_node[] = {
{G_TYPE_INT, SORTID_POS, NULL, FALSE, EDIT_NONE, refresh_node,
create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_NAME, "Name", FALSE, EDIT_NONE, refresh_node,
create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_COLOR, NULL, TRUE, EDIT_COLOR, refresh_node,
create_model_node, admin_edit_node},
#ifdef HAVE_BG
{G_TYPE_STRING, SORTID_RACK_MP, "RackMidplane", FALSE, EDIT_NONE,
refresh_node, create_model_node, admin_edit_node},
#else
{G_TYPE_STRING, SORTID_RACK_MP, NULL, TRUE, EDIT_NONE, refresh_node,
create_model_node, admin_edit_node},
#endif
{G_TYPE_STRING, SORTID_NODE_ADDR, "NodeAddr", FALSE, EDIT_NONE,
refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, <API key>, "NodeHostName", FALSE, EDIT_NONE,
refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_STATE, "State", FALSE, EDIT_MODEL, refresh_node,
create_model_node, admin_edit_node},
{G_TYPE_INT, SORTID_STATE_NUM, NULL, FALSE, EDIT_NONE, refresh_node,
create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_CPUS, "CPU Count", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_USED_CPUS, "Used CPU Count", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_ERR_CPUS, "Error CPU Count", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_IDLE_CPUS, "Idle CPU Count", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_INT, SORTID_BOARDS, "Boards", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_INT, SORTID_SOCKETS, "Sockets", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_INT, SORTID_CORES, "CoresPerSocket", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_INT, SORTID_THREADS, "ThreadsPerCore", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_MEMORY, "Real Memory", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_USED_MEMORY, "Used Memory", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_DISK, "Tmp Disk", FALSE, EDIT_NONE, refresh_node,
create_model_node, admin_edit_node},
{G_TYPE_INT, SORTID_WEIGHT,"Weight", FALSE, EDIT_NONE, refresh_node,
create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_CPU_LOAD, "CPU Load", FALSE, EDIT_NONE,
refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_ARCH, "Arch", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_FEATURES, "Features", FALSE,
EDIT_TEXTBOX, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_GRES, "Gres", FALSE,
EDIT_TEXTBOX, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_BOOT_TIME, "BootTime", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, <API key>, "SlurmdStartTime", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_REASON, "Reason", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_BASE_WATTS, "Lowest Joules", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, <API key>,"Consumed Joules", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, <API key>, "Current Watts", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_STRING, SORTID_VERSION, "Version", FALSE,
EDIT_NONE, refresh_node, create_model_node, admin_edit_node},
{G_TYPE_INT, SORTID_UPDATED, NULL, FALSE, EDIT_NONE, refresh_node,
create_model_node, admin_edit_node},
{G_TYPE_NONE, -1, NULL, FALSE, EDIT_NONE}
};
static display_data_t options_data_node[] = {
{G_TYPE_INT, SORTID_POS, NULL, FALSE, EDIT_NONE},
{G_TYPE_STRING, INFO_PAGE, "Full Info", TRUE, NODE_PAGE},
#ifdef HAVE_BG
{G_TYPE_STRING, NODE_PAGE, "Drain Midplane", TRUE, ADMIN_PAGE},
{G_TYPE_STRING, NODE_PAGE, "Undrain Midplane", TRUE, ADMIN_PAGE},
{G_TYPE_STRING, NODE_PAGE, "Resume Midplane", TRUE, ADMIN_PAGE},
{G_TYPE_STRING, NODE_PAGE, "Set Midplane Down",
TRUE, ADMIN_PAGE},
{G_TYPE_STRING, NODE_PAGE, "Make Midplane Idle",
TRUE, ADMIN_PAGE},
#else
{G_TYPE_STRING, NODE_PAGE, "Drain Node", TRUE, ADMIN_PAGE},
{G_TYPE_STRING, NODE_PAGE, "Undrain Node", TRUE, ADMIN_PAGE},
{G_TYPE_STRING, NODE_PAGE, "Resume Node", TRUE, ADMIN_PAGE},
{G_TYPE_STRING, NODE_PAGE, "Set Node(s) Down", TRUE, ADMIN_PAGE},
{G_TYPE_STRING, NODE_PAGE, "Make Node(s) Idle", TRUE, ADMIN_PAGE},
#endif
{G_TYPE_STRING, NODE_PAGE, "Update Features", TRUE, ADMIN_PAGE},
{G_TYPE_STRING, NODE_PAGE, "Update Gres", TRUE, ADMIN_PAGE},
{G_TYPE_STRING, JOB_PAGE, "Jobs", TRUE, NODE_PAGE},
#ifdef HAVE_BG
{G_TYPE_STRING, BLOCK_PAGE, "Blocks", TRUE, NODE_PAGE},
#else
{G_TYPE_STRING, BLOCK_PAGE, NULL, TRUE, NODE_PAGE},
#endif
{G_TYPE_STRING, PART_PAGE, "Partitions", TRUE, NODE_PAGE},
{G_TYPE_STRING, RESV_PAGE, "Reservations", TRUE, NODE_PAGE},
//{G_TYPE_STRING, SUBMIT_PAGE, "Job Submit", FALSE, NODE_PAGE},
{G_TYPE_NONE, -1, NULL, FALSE, EDIT_NONE}
};
static display_data_t *local_display_data = NULL;
static GtkTreeModel *last_model = NULL;
static void _layout_node_record(GtkTreeView *treeview,
sview_node_info_t *sview_node_info_ptr,
int update)
{
char tmp_cnt[50];
char tmp_current_watts[50];
char tmp_base_watts[50];
char tmp_consumed_energy[50];
char tmp_version[50];
char *upper = NULL, *lower = NULL;
GtkTreeIter iter;
uint16_t err_cpus = 0, alloc_cpus = 0;
uint32_t alloc_memory = 0;
node_info_t *node_ptr = sview_node_info_ptr->node_ptr;
int idle_cpus = node_ptr->cpus;
GtkTreeStore *treestore =
GTK_TREE_STORE(<API key>(treeview));
if (!treestore)
return;
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_NAME),
node_ptr->name);
if (sview_node_info_ptr->rack_mp)
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_RACK_MP),
sview_node_info_ptr->rack_mp);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_NODE_ADDR),
node_ptr->node_addr);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
<API key>),
node_ptr->node_hostname);
convert_num_unit((float)node_ptr->cpus, tmp_cnt, sizeof(tmp_cnt),
UNIT_NONE);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_CPUS),
tmp_cnt);
if (node_ptr->cpu_load == NO_VAL) {
snprintf(tmp_cnt, sizeof(tmp_cnt), "N/A");
} else {
snprintf(tmp_cnt, sizeof(tmp_cnt), "%.2f",
(node_ptr->cpu_load / 100.0));
}
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_CPU_LOAD),
tmp_cnt);
<API key>(node_ptr->select_nodeinfo,
<API key>,
<API key>,
&alloc_cpus);
if (cluster_flags & CLUSTER_FLAG_BG) {
if (!alloc_cpus
&& ((node_ptr->node_state & <API key>)
|| (node_ptr->node_state & <API key>)))
alloc_cpus = node_ptr->cpus;
else
alloc_cpus *= cpus_per_node;
}
idle_cpus -= alloc_cpus;
convert_num_unit((float)alloc_cpus, tmp_cnt,
sizeof(tmp_cnt), UNIT_NONE);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_USED_CPUS),
tmp_cnt);
<API key>(node_ptr->select_nodeinfo,
<API key>,
NODE_STATE_ERROR,
&err_cpus);
if (cluster_flags & CLUSTER_FLAG_BG)
err_cpus *= cpus_per_node;
idle_cpus -= err_cpus;
convert_num_unit((float)err_cpus, tmp_cnt, sizeof(tmp_cnt), UNIT_NONE);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_ERR_CPUS),
tmp_cnt);
convert_num_unit((float)idle_cpus, tmp_cnt, sizeof(tmp_cnt), UNIT_NONE);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_IDLE_CPUS),
tmp_cnt);
upper = node_state_string(node_ptr->node_state);
lower = str_tolower(upper);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_STATE),
lower);
xfree(lower);
convert_num_unit((float)node_ptr->boards, tmp_cnt, sizeof(tmp_cnt),
UNIT_NONE);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_BOARDS),
tmp_cnt);
convert_num_unit((float)node_ptr->sockets, tmp_cnt, sizeof(tmp_cnt),
UNIT_NONE);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_SOCKETS),
tmp_cnt);
convert_num_unit((float)node_ptr->cores, tmp_cnt, sizeof(tmp_cnt),
UNIT_NONE);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_CORES),
tmp_cnt);
convert_num_unit((float)node_ptr->threads, tmp_cnt, sizeof(tmp_cnt),
UNIT_NONE);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_THREADS),
tmp_cnt);
convert_num_unit((float)node_ptr->real_memory, tmp_cnt, sizeof(tmp_cnt),
UNIT_MEGA);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_MEMORY),
tmp_cnt);
<API key>(node_ptr->select_nodeinfo,
<API key>,
<API key>,
&alloc_memory);
snprintf(tmp_cnt, sizeof(tmp_cnt), "%uM", alloc_memory);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_USED_MEMORY),
tmp_cnt);
convert_num_unit((float)node_ptr->tmp_disk, tmp_cnt, sizeof(tmp_cnt),
UNIT_MEGA);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_DISK),
tmp_cnt);
snprintf(tmp_cnt, sizeof(tmp_cnt), "%u", node_ptr->weight);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_WEIGHT),
tmp_cnt);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_ARCH),
node_ptr->arch);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_FEATURES),
node_ptr->features);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_GRES),
node_ptr->gres);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_BOOT_TIME),
sview_node_info_ptr->boot_time);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
<API key>),
sview_node_info_ptr->slurmd_start_time);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_REASON),
sview_node_info_ptr->reason);
if (node_ptr->energy->current_watts == NO_VAL) {
snprintf(tmp_current_watts, sizeof(tmp_current_watts),
"N/A");
snprintf(tmp_base_watts, sizeof(tmp_base_watts),
"N/A");
snprintf(tmp_consumed_energy, sizeof(tmp_consumed_energy),
"N/A");
} else {
snprintf(tmp_current_watts, sizeof(tmp_current_watts),
"%u", node_ptr->energy->current_watts);
snprintf(tmp_base_watts, sizeof(tmp_base_watts),
"%u", node_ptr->energy->base_watts);
snprintf(tmp_consumed_energy, sizeof(tmp_consumed_energy),
"%u", node_ptr->energy->consumed_energy);
}
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_BASE_WATTS),
tmp_base_watts);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
<API key>),
tmp_consumed_energy);
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
<API key>),
tmp_current_watts);
if (node_ptr->version == NULL) {
snprintf(tmp_version, sizeof(tmp_version), "N/A");
} else {
snprintf(tmp_version, sizeof(tmp_version), "%s",
node_ptr->version);
}
<API key>(update, treestore, &iter,
find_col_name(display_data_node,
SORTID_VERSION),
tmp_version);
return;
}
static void _update_node_record(sview_node_info_t *sview_node_info_ptr,
GtkTreeStore *treestore)
{
uint16_t alloc_cpus = 0, err_cpus = 0, idle_cpus;
uint32_t alloc_memory;
node_info_t *node_ptr = sview_node_info_ptr->node_ptr;
char tmp_disk[20], tmp_cpus[20], tmp_err_cpus[20], tmp_idle_cpus[20];
char tmp_mem[20], tmp_used_memory[20];
char tmp_used_cpus[20], tmp_cpu_load[20];
char tmp_current_watts[50], tmp_base_watts[50], tmp_consumed_energy[50];
char tmp_version[50];
char *tmp_state_lower, *tmp_state_upper;
if (node_ptr->energy->current_watts == NO_VAL) {
snprintf(tmp_current_watts, sizeof(tmp_current_watts),
"N/A");
snprintf(tmp_base_watts, sizeof(tmp_base_watts),
"N/A");
snprintf(tmp_consumed_energy, sizeof(tmp_consumed_energy),
"N/A");
} else {
snprintf(tmp_current_watts, sizeof(tmp_current_watts),
"%u ", node_ptr->energy->current_watts);
snprintf(tmp_base_watts, sizeof(tmp_base_watts),
"%u", node_ptr->energy->base_watts);
snprintf(tmp_consumed_energy, sizeof(tmp_consumed_energy),
"%u", node_ptr->energy->consumed_energy);
}
if (node_ptr->cpu_load == NO_VAL) {
strcpy(tmp_cpu_load, "N/A");
} else {
snprintf(tmp_cpu_load, sizeof(tmp_cpu_load),
"%.2f", (node_ptr->cpu_load / 100.0));
}
convert_num_unit((float)node_ptr->cpus, tmp_cpus,
sizeof(tmp_cpus), UNIT_NONE);
<API key>(node_ptr->select_nodeinfo,
<API key>,
<API key>,
&alloc_cpus);
if (cluster_flags & CLUSTER_FLAG_BG) {
if (!alloc_cpus &&
(IS_NODE_ALLOCATED(node_ptr) ||
IS_NODE_COMPLETING(node_ptr)))
alloc_cpus = node_ptr->cpus;
else
alloc_cpus *= cpus_per_node;
}
idle_cpus = node_ptr->cpus - alloc_cpus;
convert_num_unit((float)alloc_cpus, tmp_used_cpus,
sizeof(tmp_used_cpus), UNIT_NONE);
<API key>(node_ptr->select_nodeinfo,
<API key>,
<API key>,
&alloc_memory);
snprintf(tmp_used_memory, sizeof(tmp_used_memory), "%uM", alloc_memory);
convert_num_unit((float)alloc_cpus, tmp_used_cpus,
sizeof(tmp_used_cpus), UNIT_NONE);
<API key>(node_ptr->select_nodeinfo,
<API key>,
NODE_STATE_ERROR,
&err_cpus);
if (cluster_flags & CLUSTER_FLAG_BG)
err_cpus *= cpus_per_node;
idle_cpus -= err_cpus;
convert_num_unit((float)err_cpus, tmp_err_cpus, sizeof(tmp_err_cpus),
UNIT_NONE);
convert_num_unit((float)idle_cpus, tmp_idle_cpus, sizeof(tmp_idle_cpus),
UNIT_NONE);
if (IS_NODE_DRAIN(node_ptr)) {
/* don't worry about mixed since the
* whole node is being drained. */
} else if ((alloc_cpus && err_cpus) ||
(idle_cpus && (idle_cpus != node_ptr->cpus))) {
node_ptr->node_state &= NODE_STATE_FLAGS;
node_ptr->node_state |= NODE_STATE_MIXED;
}
tmp_state_upper = node_state_string(node_ptr->node_state);
tmp_state_lower = str_tolower(tmp_state_upper);
convert_num_unit((float)node_ptr->real_memory, tmp_mem, sizeof(tmp_mem),
UNIT_MEGA);
convert_num_unit((float)node_ptr->tmp_disk, tmp_disk, sizeof(tmp_disk),
UNIT_MEGA);
if (node_ptr->version == NULL) {
snprintf(tmp_version, sizeof(tmp_version), "N/A");
} else {
snprintf(tmp_version, sizeof(tmp_version), "%s",
node_ptr->version);
}
/* Combining these records provides a slight performance improvement */
gtk_tree_store_set(treestore, &sview_node_info_ptr->iter_ptr,
SORTID_ARCH, node_ptr->arch,
SORTID_BASE_WATTS,tmp_base_watts,
SORTID_BOARDS, node_ptr->boards,
SORTID_BOOT_TIME, sview_node_info_ptr->boot_time,
SORTID_COLOR,
sview_colors[sview_node_info_ptr->pos
% sview_colors_cnt],
<API key>, tmp_consumed_energy,
SORTID_CORES, node_ptr->cores,
SORTID_CPUS, tmp_cpus,
<API key>, tmp_current_watts,
SORTID_CPU_LOAD, tmp_cpu_load,
SORTID_DISK, tmp_disk,
SORTID_ERR_CPUS, tmp_err_cpus,
SORTID_IDLE_CPUS, tmp_idle_cpus,
SORTID_FEATURES, node_ptr->features,
SORTID_GRES, node_ptr->gres,
SORTID_MEMORY, tmp_mem,
SORTID_NAME, node_ptr->name,
SORTID_NODE_ADDR, node_ptr->node_addr,
<API key>, node_ptr->node_hostname,
SORTID_RACK_MP, sview_node_info_ptr->rack_mp,
SORTID_REASON, sview_node_info_ptr->reason,
<API key>,
sview_node_info_ptr->slurmd_start_time,
SORTID_SOCKETS, node_ptr->sockets,
SORTID_STATE, tmp_state_lower,
SORTID_STATE_NUM, node_ptr->node_state,
SORTID_THREADS, node_ptr->threads,
SORTID_USED_CPUS, tmp_used_cpus,
SORTID_USED_MEMORY, tmp_used_memory,
SORTID_VERSION, tmp_version,
SORTID_WEIGHT, node_ptr->weight,
SORTID_UPDATED, 1,
-1);
xfree(tmp_state_lower);
return;
}
static void _append_node_record(sview_node_info_t *sview_node_info,
GtkTreeStore *treestore)
{
<API key>(treestore, &sview_node_info->iter_ptr, NULL);
gtk_tree_store_set(treestore, &sview_node_info->iter_ptr, SORTID_POS,
sview_node_info->pos, -1);
_update_node_record(sview_node_info, treestore);
}
static void _update_info_node(List info_list, GtkTreeView *tree_view)
{
GtkTreeModel *model = <API key>(tree_view);
char *name = NULL;
ListIterator itr = NULL;
sview_node_info_t *sview_node_info = NULL;
set_for_update(model, SORTID_UPDATED);
itr = <API key>(info_list);
while ((sview_node_info = (sview_node_info_t*) list_next(itr))) {
/* This means the tree_store changed (added new column
* or something). */
if (last_model != model)
sview_node_info->iter_set = false;
if (sview_node_info->iter_set) {
gtk_tree_model_get(model, &sview_node_info->iter_ptr,
SORTID_NAME, &name, -1);
if (strcmp(name, sview_node_info->node_name)) {
/* Bad pointer */
sview_node_info->iter_set = false;
//g_print("bad node iter pointer\n");
}
g_free(name);
}
if (sview_node_info->iter_set)
_update_node_record(sview_node_info,
GTK_TREE_STORE(model));
else {
_append_node_record(sview_node_info,
GTK_TREE_STORE(model));
sview_node_info->iter_set = true;
}
}
<API key>(itr);
/* remove all old nodes */
remove_old(model, SORTID_UPDATED);
last_model = model;
}
static void _node_info_free(sview_node_info_t *sview_node_info)
{
if (sview_node_info) {
xfree(sview_node_info->slurmd_start_time);
xfree(sview_node_info->boot_time);
xfree(sview_node_info->node_name);
xfree(sview_node_info->rack_mp);
xfree(sview_node_info->reason);
}
}
static void _node_info_list_del(void *object)
{
sview_node_info_t *sview_node_info = (sview_node_info_t *)object;
if (sview_node_info) {
_node_info_free(sview_node_info);
xfree(sview_node_info);
}
}
static void _display_info_node(List info_list, popup_info_t *popup_win)
{
specific_info_t *spec_info = popup_win->spec_info;
char *name = (char *)spec_info->search_info->gchar_data;
int found = 0;
node_info_t *node_ptr = NULL;
GtkTreeView *treeview = NULL;
int update = 0;
ListIterator itr = NULL;
sview_node_info_t *sview_node_info = NULL;
int i = -1;
if (!spec_info->search_info->gchar_data) {
goto finished;
}
need_refresh:
if (!spec_info->display_widget) {
treeview = <API key>(
popup_win->table);
spec_info->display_widget =
gtk_widget_ref(GTK_WIDGET(treeview));
} else {
treeview = GTK_TREE_VIEW(spec_info->display_widget);
update = 1;
}
itr = <API key>(info_list);
while ((sview_node_info = (sview_node_info_t*) list_next(itr))) {
node_ptr = sview_node_info->node_ptr;
i++;
if (!strcmp(node_ptr->name, name)) {
change_grid_color(popup_win->grid_button_list,
i, i, i, true, 0);
_layout_node_record(treeview, sview_node_info, update);
found = 1;
break;
}
}
<API key>(itr);
if (!found) {
if (!popup_win->not_found) {
char *temp;
GtkTreeIter iter;
GtkTreeModel *model = NULL;
if (cluster_flags & CLUSTER_FLAG_BG)
temp = "MIDPLANE NOT FOUND\n";
else
temp = "NODE NOT FOUND\n";
/* only time this will be run so no update */
model = <API key>(treeview);
<API key>(0,
GTK_TREE_STORE(model),
&iter,
temp, "");
}
popup_win->not_found = true;
} else {
if (popup_win->not_found) {
popup_win->not_found = false;
gtk_widget_destroy(spec_info->display_widget);
goto need_refresh;
}
}
gtk_widget_show(spec_info->display_widget);
finished:
return;
}
static void _selected_page(GtkMenuItem *menuitem,
display_data_t *display_data)
{
switch(display_data->extra) {
case NODE_PAGE:
popup_all_node_name(display_data->user_data, display_data->id);
break;
case ADMIN_PAGE:
admin_node_name(display_data->user_data,
NULL, display_data->name);
break;
default:
g_print("node got %d %d\n", display_data->extra,
display_data->id);
}
}
static void _process_each_node(GtkTreeModel *model, GtkTreePath *path,
GtkTreeIter *iter, gpointer userdata)
{
char *name = NULL;
process_node_t *process_node = userdata;
gtk_tree_model_get(model, iter, process_node->node_col, &name, -1);
if (process_node->nodelist)
xstrfmtcat(process_node->nodelist, ",%s", name);
else
process_node->nodelist = xstrdup(name);
g_free(name);
}
/*process_each_node ^^^*/
extern void refresh_node(GtkAction *action, gpointer user_data)
{
popup_info_t *popup_win = (popup_info_t *)user_data;
xassert(popup_win);
xassert(popup_win->spec_info);
xassert(popup_win->spec_info->title);
popup_win->force_refresh = 1;
specific_info_node(popup_win);
}
/* don't destroy the list from this function */
extern List <API key>(node_info_msg_t *node_info_ptr,
bool by_partition)
{
static List info_list = NULL;
static node_info_msg_t *last_node_info_ptr = NULL;
List last_list = NULL;
ListIterator last_list_itr = NULL;
int i = 0;
sview_node_info_t *sview_node_info_ptr = NULL;
node_info_t *node_ptr = NULL;
char user[32], time_str[32];
if (!by_partition) {
if (!node_info_ptr
|| (info_list && (node_info_ptr == last_node_info_ptr)))
goto update_color;
}
last_node_info_ptr = node_info_ptr;
if (info_list)
last_list = info_list;
info_list = list_create(_node_info_list_del);
if (!info_list) {
g_print("malloc error\n");
return NULL;
}
if (last_list)
last_list_itr = <API key>(last_list);
for (i=0; i<node_info_ptr->record_count; i++) {
char *select_reason_str = NULL;
node_ptr = &(node_info_ptr->node_array[i]);
if (!node_ptr->name || (node_ptr->name[0] == '\0'))
continue;
sview_node_info_ptr = NULL;
if (last_list_itr) {
while ((sview_node_info_ptr =
list_next(last_list_itr))) {
if (!strcmp(sview_node_info_ptr->node_name,
node_ptr->name)) {
list_remove(last_list_itr);
_node_info_free(sview_node_info_ptr);
break;
}
}
list_iterator_reset(last_list_itr);
}
/* constrain list to included partitions' nodes */
/* and there are excluded values to process */
/* and user has not requested to show hidden */
/* if (by_partition && <API key> */
/* && !<API key>.show_hidden */
/* && !<API key>(i)) */
/* continue; */
if (!sview_node_info_ptr)
sview_node_info_ptr =
xmalloc(sizeof(sview_node_info_t));
list_append(info_list, sview_node_info_ptr);
sview_node_info_ptr->node_name = xstrdup(node_ptr->name);
sview_node_info_ptr->node_ptr = node_ptr;
sview_node_info_ptr->pos = i;
<API key>(node_ptr->select_nodeinfo,
<API key>,
0, &sview_node_info_ptr->rack_mp);
if (node_ptr->reason &&
(node_ptr->reason_uid != NO_VAL) && node_ptr->reason_time) {
struct passwd *pw = NULL;
if ((pw=getpwuid(node_ptr->reason_uid)))
snprintf(user, sizeof(user), "%s", pw->pw_name);
else
snprintf(user, sizeof(user), "Unk(%u)",
node_ptr->reason_uid);
slurm_make_time_str(&node_ptr->reason_time,
time_str, sizeof(time_str));
sview_node_info_ptr->reason = xstrdup_printf(
"%s [%s@%s]", node_ptr->reason, user, time_str);
} else if (node_ptr->reason)
sview_node_info_ptr->reason = xstrdup(node_ptr->reason);
<API key>(node_ptr->select_nodeinfo,
<API key>,
0, &select_reason_str);
if (select_reason_str && select_reason_str[0]) {
if (sview_node_info_ptr->reason)
xstrfmtcat(sview_node_info_ptr->reason, "\n%s",
select_reason_str);
else {
sview_node_info_ptr->reason = select_reason_str;
select_reason_str = NULL;
}
}
xfree(select_reason_str);
if (node_ptr->boot_time) {
slurm_make_time_str(&node_ptr->boot_time,
time_str, sizeof(time_str));
sview_node_info_ptr->boot_time = xstrdup(time_str);
}
if (node_ptr->slurmd_start_time) {
slurm_make_time_str(&node_ptr->slurmd_start_time,
time_str, sizeof(time_str));
sview_node_info_ptr->slurmd_start_time =
xstrdup(time_str);
}
}
if (last_list) {
<API key>(last_list_itr);
list_destroy(last_list);
}
update_color:
return info_list;
}
extern int get_new_info_node(node_info_msg_t **info_ptr, int force)
{
node_info_msg_t *new_node_ptr = NULL;
uint16_t show_flags = 0;
int error_code = <API key>;
time_t now = time(NULL), delay;
static time_t last;
static bool changed = 0;
static uint16_t last_flags = 0;
delay = now - last;
if (delay < 2) {
/* Avoid re-loading node information within 2 secs as the data
* may still be in use. If we load new node data and free the
* old data while it it still in use, the result is likely
* invalid memory references. */
force = 0;
/* FIXME: Add an "in use" flag, copy the data, or otherwise
* permit the timely loading of new node information. */
}
if (g_node_info_ptr && !force &&
(delay < <API key>.refresh_delay)) {
if (*info_ptr != g_node_info_ptr)
error_code = SLURM_SUCCESS;
*info_ptr = g_node_info_ptr;
return error_code;
}
last = now;
//if (<API key>.show_hidden)
show_flags |= SHOW_ALL;
if (g_node_info_ptr) {
if (show_flags != last_flags)
g_node_info_ptr->last_update = 0;
error_code = slurm_load_node(g_node_info_ptr->last_update,
&new_node_ptr, show_flags);
if (error_code == SLURM_SUCCESS) {
<API key>(g_node_info_ptr);
changed = 1;
} else if (slurm_get_errno() == <API key>) {
error_code = <API key>;
new_node_ptr = g_node_info_ptr;
changed = 0;
}
} else {
new_node_ptr = NULL;
error_code = slurm_load_node((time_t) NULL, &new_node_ptr,
show_flags);
changed = 1;
}
last_flags = show_flags;
g_node_info_ptr = new_node_ptr;
if (g_node_info_ptr && (*info_ptr != g_node_info_ptr))
error_code = SLURM_SUCCESS;
if (new_node_ptr && new_node_ptr->node_array && changed) {
int i;
node_info_t *node_ptr = NULL;
uint16_t err_cpus = 0, alloc_cpus = 0;
int idle_cpus;
g_node_scaling = new_node_ptr->node_scaling;
cpus_per_node =
new_node_ptr->node_array[0].cpus / g_node_scaling;
sview_max_cpus = 0;
for (i=0; i<g_node_info_ptr->record_count; i++) {
node_ptr = &(g_node_info_ptr->node_array[i]);
if (!node_ptr->name || (node_ptr->name[0] == '\0'))
continue; /* bad node */
sview_max_cpus = MAX(sview_max_cpus, node_ptr->cpus);
idle_cpus = node_ptr->cpus;
<API key>(
node_ptr->select_nodeinfo,
<API key>,
<API key>,
&alloc_cpus);
if (cluster_flags & CLUSTER_FLAG_BG) {
if (!alloc_cpus
&& (IS_NODE_ALLOCATED(node_ptr)
|| IS_NODE_COMPLETING(node_ptr)))
alloc_cpus = node_ptr->cpus;
else
alloc_cpus *= cpus_per_node;
}
idle_cpus -= alloc_cpus;
<API key>(
node_ptr->select_nodeinfo,
<API key>,
NODE_STATE_ERROR,
&err_cpus);
if (cluster_flags & CLUSTER_FLAG_BG)
err_cpus *= cpus_per_node;
idle_cpus -= err_cpus;
if (IS_NODE_DRAIN(node_ptr)) {
/* don't worry about mixed since the
whole node is being drained. */
} else if ((alloc_cpus && err_cpus) ||
(idle_cpus &&
(idle_cpus != node_ptr->cpus))) {
node_ptr->node_state &= NODE_STATE_FLAGS;
if (err_cpus)
node_ptr->node_state |= NODE_STATE_ERROR;
node_ptr->node_state |= NODE_STATE_MIXED;
} else if (err_cpus) {
node_ptr->node_state &= NODE_STATE_FLAGS;
node_ptr->node_state |= NODE_STATE_ERROR;
}
/* if (alloc_cpus && err_cpus && !idle_cpus) { */
/* node_ptr->node_state &= NODE_STATE_FLAGS; */
/* node_ptr->node_state |= NODE_STATE_AE; */
/* } else if (alloc_cpus && err_cpus && idle_cpus) { */
/* node_ptr->node_state &= NODE_STATE_FLAGS; */
/* node_ptr->node_state |= NODE_STATE_AEI; */
/* } else if (alloc_cpus && !err_cpus && idle_cpus) { */
/* node_ptr->node_state &= NODE_STATE_FLAGS; */
/* node_ptr->node_state |= NODE_STATE_AI; */
/* } else if (!alloc_cpus && err_cpus && idle_cpus) { */
/* node_ptr->node_state &= NODE_STATE_FLAGS; */
/* node_ptr->node_state |= NODE_STATE_EI; */
}
}
*info_ptr = g_node_info_ptr;
if (!g_topo_info_msg_ptr &&
<API key>.grid_topological) {
get_topo_conf(); /* pull in topology NOW */
}
return error_code;
}
extern int <API key>(GtkDialog *dialog, const char *nodelist,
const char *old_features)
{
char tmp_char[100];
char *edit = NULL;
GtkWidget *entry = NULL;
GtkWidget *label = NULL;
update_node_msg_t *node_msg = xmalloc(sizeof(update_node_msg_t));
int response = 0;
int no_dialog = 0;
int rc = SLURM_SUCCESS;
if (_DEBUG)
g_print("<API key>:global_row_count: %d "
"node_names %s\n",
global_row_count, nodelist);
if (!dialog) {
snprintf(tmp_char, sizeof(tmp_char),
"Update Features for Node(s) %s?",
nodelist);
dialog = GTK_DIALOG(
<API key>(
tmp_char,
GTK_WINDOW(main_window),
GTK_DIALOG_MODAL
| <API key>,
NULL));
no_dialog = 1;
}
label = <API key>(dialog,
GTK_STOCK_YES, GTK_RESPONSE_OK);
<API key>(GTK_WINDOW(dialog), label);
<API key>(dialog,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
<API key>(node_msg);
node_msg->node_names = xstrdup(nodelist);
snprintf(tmp_char, sizeof(tmp_char),
"Features for Node(s) %s?", nodelist);
label = gtk_label_new(tmp_char);
gtk_box_pack_start(GTK_BOX(dialog->vbox),
label, FALSE, FALSE, 0);
entry = create_entry();
if (!entry)
goto end_it;
if (old_features)
gtk_entry_set_text(GTK_ENTRY(entry), old_features);
gtk_box_pack_start(GTK_BOX(dialog->vbox), entry, TRUE, TRUE, 0);
gtk_widget_show_all(GTK_WIDGET(dialog));
response = gtk_dialog_run(dialog);
if (response == GTK_RESPONSE_OK) {
node_msg->features =
xstrdup(gtk_entry_get_text(GTK_ENTRY(entry)));
if (!node_msg->features) {
edit = g_strdup_printf("No features given.");
display_edit_note(edit);
g_free(edit);
goto end_it;
}
if ((rc = slurm_update_node(node_msg) == SLURM_SUCCESS)) {
edit = g_strdup_printf(
"Node(s) %s updated successfully.",
nodelist);
display_edit_note(edit);
g_free(edit);
} else {
edit = g_strdup_printf(
"Problem updating node(s) %s: %s",
nodelist, slurm_strerror(rc));
display_edit_note(edit);
g_free(edit);
}
}
end_it:
<API key>(node_msg);
if (no_dialog)
gtk_widget_destroy(GTK_WIDGET(dialog));
return rc;
}
extern int update_gres_node(GtkDialog *dialog, const char *nodelist,
const char *old_gres)
{
char tmp_char[100];
char *edit = NULL;
GtkWidget *entry = NULL;
GtkWidget *label = NULL;
update_node_msg_t *node_msg = xmalloc(sizeof(update_node_msg_t));
int response = 0;
int no_dialog = 0;
int rc = SLURM_SUCCESS;
if (_DEBUG)
g_print("update_gres_node:global_row_count:"
" %d node_names %s\n",
global_row_count, nodelist);
if (!dialog) {
snprintf(tmp_char, sizeof(tmp_char),
"Update Gres for Node(s) %s?",
nodelist);
dialog = GTK_DIALOG(
<API key>(
tmp_char,
GTK_WINDOW(main_window),
GTK_DIALOG_MODAL
| <API key>,
NULL));
no_dialog = 1;
}
label = <API key>(dialog, GTK_STOCK_YES, GTK_RESPONSE_OK);
<API key>(GTK_WINDOW(dialog), label);
<API key>(dialog, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
<API key>(node_msg);
node_msg->node_names = xstrdup(nodelist);
snprintf(tmp_char, sizeof(tmp_char), "Gres for Node(s) %s?", nodelist);
label = gtk_label_new(tmp_char);
gtk_box_pack_start(GTK_BOX(dialog->vbox), label, FALSE, FALSE, 0);
entry = create_entry();
if (!entry)
goto end_it;
if (old_gres)
gtk_entry_set_text(GTK_ENTRY(entry), old_gres);
gtk_box_pack_start(GTK_BOX(dialog->vbox), entry, TRUE, TRUE, 0);
gtk_widget_show_all(GTK_WIDGET(dialog));
response = gtk_dialog_run(dialog);
if (response == GTK_RESPONSE_OK) {
node_msg->gres = xstrdup(gtk_entry_get_text(GTK_ENTRY(entry)));
if (!node_msg->gres) {
edit = g_strdup_printf("No gres given.");
display_edit_note(edit);
g_free(edit);
goto end_it;
}
if ((rc = slurm_update_node(node_msg)) == SLURM_SUCCESS) {
edit = g_strdup_printf(
"Nodes %s updated successfully.",
nodelist);
display_edit_note(edit);
g_free(edit);
} else {
edit = g_strdup_printf(
"Problem updating nodes %s: %s",
nodelist, slurm_strerror(rc));
display_edit_note(edit);
g_free(edit);
}
}
end_it:
<API key>(node_msg);
if (no_dialog)
gtk_widget_destroy(GTK_WIDGET(dialog));
return rc;
}
extern int update_state_node(GtkDialog *dialog,
const char *nodelist, const char *type)
{
uint16_t state = (uint16_t) NO_VAL;
char *upper = NULL, *lower = NULL;
int i = 0;
int rc = SLURM_SUCCESS;
char tmp_char[100];
update_node_msg_t *node_msg = xmalloc(sizeof(update_node_msg_t));
GtkWidget *label = NULL;
GtkWidget *entry = NULL;
int no_dialog = 0;
if (!dialog) {
dialog = GTK_DIALOG(
<API key>(
type,
GTK_WINDOW(main_window),
GTK_DIALOG_MODAL
| <API key>,
NULL));
no_dialog = 1;
}
label = <API key>(dialog, GTK_STOCK_YES, GTK_RESPONSE_OK);
<API key>(GTK_WINDOW(dialog), label);
<API key>(dialog, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
<API key>(node_msg);
node_msg->node_names = xstrdup(nodelist);
if (!strncasecmp("drain", type, 5)) {
snprintf(tmp_char, sizeof(tmp_char),
"Are you sure you want to drain node(s) %s?\n\n"
"Please put reason.",
nodelist);
entry = create_entry();
label = gtk_label_new(tmp_char);
state = NODE_STATE_DRAIN;
} else if (!strncasecmp("resume", type, 5)) {
snprintf(tmp_char, sizeof(tmp_char),
"Are you sure you want to resume node(s) %s?",
nodelist);
label = gtk_label_new(tmp_char);
state = NODE_RESUME;
} else if (!strncasecmp("set", type, 3)) {
snprintf(tmp_char, sizeof(tmp_char),
"Are you sure you want to down node(s) %s?\n\n"
"Please put reason.",
nodelist);
entry = create_entry();
label = gtk_label_new(tmp_char);
state = NODE_STATE_DOWN;
} else if (!strncasecmp("undrain", type, 5)) {
snprintf(tmp_char, sizeof(tmp_char),
"Are you sure you want to undrain node(s) %s?",
nodelist);
label = gtk_label_new(tmp_char);
state = NODE_STATE_UNDRAIN;
} else {
if (!strncasecmp("make", type, 4))
type = "idle";
for(i = 0; i < NODE_STATE_END; i++) {
upper = node_state_string(i);
lower = str_tolower(upper);
if (!strcmp(lower, type)) {
snprintf(tmp_char, sizeof(tmp_char),
"Are you sure you want to set "
"node(s) %s to %s?",
nodelist, lower);
label = gtk_label_new(tmp_char);
state = i;
xfree(lower);
break;
}
xfree(lower);
}
}
if (!label)
goto end_it;
node_msg->node_state = (uint16_t)state;
gtk_box_pack_start(GTK_BOX(dialog->vbox), label, FALSE, FALSE, 0);
if (entry)
gtk_box_pack_start(GTK_BOX(dialog->vbox), entry, TRUE, TRUE, 0);
gtk_widget_show_all(GTK_WIDGET(dialog));
i = gtk_dialog_run(dialog);
if (i == GTK_RESPONSE_OK) {
if (entry) {
node_msg->reason = xstrdup(
gtk_entry_get_text(GTK_ENTRY(entry)));
if (!node_msg->reason || !strlen(node_msg->reason)) {
lower = g_strdup_printf(
"You need a reason to do that.");
display_edit_note(lower);
g_free(lower);
goto end_it;
}
if (uid_from_string(getlogin(),
&node_msg->reason_uid) < 0)
node_msg->reason_uid = getuid();
}
if ((rc = slurm_update_node(node_msg)) == SLURM_SUCCESS) {
lower = g_strdup_printf(
"Nodes %s updated successfully.",
nodelist);
display_edit_note(lower);
g_free(lower);
} else {
lower = g_strdup_printf(
"Problem updating nodes %s: %s",
nodelist, slurm_strerror(rc));
display_edit_note(lower);
g_free(lower);
}
}
end_it:
<API key>(node_msg);
if (no_dialog)
gtk_widget_destroy(GTK_WIDGET(dialog));
return rc;
}
extern GtkListStore *create_model_node(int type)
{
GtkListStore *model = NULL;
GtkTreeIter iter;
char *upper = NULL, *lower = NULL;
int i=0;
last_model = NULL; /* Reformat display */
switch(type) {
case SORTID_STATE:
model = gtk_list_store_new(2, G_TYPE_STRING,
G_TYPE_INT);
<API key>(model, &iter);
gtk_list_store_set(model, &iter,
0, "drain",
1, i,
-1);
<API key>(model, &iter);
gtk_list_store_set(model, &iter,
0, "NoResp",
1, i,
-1);
<API key>(model, &iter);
gtk_list_store_set(model, &iter,
0, "resume",
1, i,
-1);
<API key>(model, &iter);
gtk_list_store_set(model, &iter,
0, "undrain",
1, i,
-1);
for(i = 0; i < NODE_STATE_END; i++) {
upper = node_state_string(i);
<API key>(model, &iter);
lower = str_tolower(upper);
gtk_list_store_set(model, &iter,
0, lower,
1, i,
-1);
xfree(lower);
}
break;
}
return model;
}
extern void admin_edit_node(GtkCellRendererText *cell,
const char *path_string,
const char *new_text,
gpointer data)
{
GtkTreeStore *treestore = GTK_TREE_STORE(data);
GtkTreePath *path = <API key>(path_string);
GtkTreeIter iter;
char *nodelist = NULL;
int column = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(cell),
"column"));
if (!new_text || !strcmp(new_text, ""))
goto no_input;
<API key>(GTK_TREE_MODEL(treestore), &iter, path);
switch(column) {
case SORTID_STATE:
gtk_tree_model_get(GTK_TREE_MODEL(treestore), &iter,
SORTID_NAME,
&nodelist, -1);
update_state_node(NULL, nodelist, new_text);
g_free(nodelist);
default:
break;
}
no_input:
gtk_tree_path_free(path);
g_mutex_unlock(sview_mutex);
}
extern void get_info_node(GtkTable *table, display_data_t *display_data)
{
int error_code = SLURM_SUCCESS;
static int view = -1;
static node_info_msg_t *node_info_ptr = NULL;
char error_char[100];
GtkWidget *label = NULL;
GtkTreeView *tree_view = NULL;
static GtkWidget *display_widget = NULL;
List info_list = NULL;
int i = 0, sort_key;
sview_node_info_t *sview_node_info_ptr = NULL;
ListIterator itr = NULL;
GtkTreePath *path = NULL;
static bool set_opts = FALSE;
if (!set_opts)
set_page_opts(NODE_PAGE, display_data_node,
SORTID_CNT, _initial_page_opts);
set_opts = TRUE;
/* reset */
if (!table && !display_data) {
if (display_widget)
gtk_widget_destroy(display_widget);
display_widget = NULL;
goto reset_curs;
}
if (display_data)
local_display_data = display_data;
if (!table) {
display_data_node->set_menu = local_display_data->set_menu;
goto reset_curs;
}
if (display_widget && toggled) {
gtk_widget_destroy(display_widget);
display_widget = NULL;
/* Since the node_info_ptr could change out from under
* us we always need to check if it is new or not.
*/
/* goto display_it; */
}
if ((error_code = get_new_info_node(&node_info_ptr, force_refresh))
== <API key>) {
if (!display_widget || view == ERROR_VIEW)
goto display_it;
} else if (error_code != SLURM_SUCCESS) {
if (view == ERROR_VIEW)
goto end_it;
view = ERROR_VIEW;
if (display_widget)
gtk_widget_destroy(display_widget);
sprintf(error_char, "slurm_load_node: %s",
slurm_strerror(slurm_get_errno()));
label = gtk_label_new(error_char);
display_widget = gtk_widget_ref(label);
<API key>(table, label, 0, 1, 0, 1);
gtk_widget_show(label);
goto end_it;
}
display_it:
info_list = <API key>(node_info_ptr, FALSE);
if (!info_list)
goto reset_curs;
i = 0;
/* set up the grid */
if (display_widget && GTK_IS_TREE_VIEW(display_widget) &&
<API key>(
<API key>(
GTK_TREE_VIEW(display_widget)))) {
GtkTreeViewColumn *focus_column = NULL;
/* highlight the correct nodes from the last selection */
<API key>(GTK_TREE_VIEW(display_widget),
&path, &focus_column);
}
if (!path) {
int array_size = node_info_ptr->record_count;
int *color_inx = xmalloc(sizeof(int) * array_size);
bool *color_set_flag = xmalloc(sizeof(bool) * array_size);
itr = <API key>(info_list);
while ((sview_node_info_ptr = list_next(itr))) {
color_set_flag[i] = true;
color_inx[i] = i;
i++;
}
<API key>(itr);
<API key>(grid_button_list, array_size,
color_inx, color_set_flag, true, 0);
xfree(color_inx);
xfree(color_set_flag);
} else {
highlight_grid(GTK_TREE_VIEW(display_widget),
SORTID_POS, (int)NO_VAL, grid_button_list);
gtk_tree_path_free(path);
}
if (view == ERROR_VIEW && display_widget) {
gtk_widget_destroy(display_widget);
display_widget = NULL;
}
if (!display_widget) {
tree_view = create_treeview(local_display_data,
&grid_button_list);
/*set multiple capability here*/
<API key>(
<API key>(tree_view),
<API key>);
display_widget = gtk_widget_ref(GTK_WIDGET(tree_view));
<API key>(GTK_TABLE(table),
GTK_WIDGET(tree_view),
0, 1, 0, 1);
/* Since this function sets the model of the tree_view to the
* treestore we don't really care about the return value
* On large clusters, sorting on the node name slows GTK down
* by a large margin. */
if (node_info_ptr->record_count > 1000)
sort_key = -1;
else
sort_key = SORTID_NAME;
create_treestore(tree_view, display_data_node,
SORTID_CNT, sort_key, SORTID_COLOR);
}
view = INFO_VIEW;
/* If the system has a large number of nodes then not all lines
* will be displayed. You can try different values for the third
* argument of <API key>() in an attempt to
* maximumize the data displayed in your environment. These are my
* results: Y=1000 good for 43 lines, Y=-1 good for 1151 lines,
* Y=64000 good for 2781 lines, Y=99000 good for 1453 lines */
/* <API key>(display_widget, -1, -1); */
_update_info_node(info_list, GTK_TREE_VIEW(display_widget));
end_it:
toggled = FALSE;
force_refresh = 1;
reset_curs:
if (main_window && main_window->window)
<API key>(main_window->window, NULL);
return;
}
extern void specific_info_node(popup_info_t *popup_win)
{
int error_code = SLURM_SUCCESS;
static node_info_msg_t *node_info_ptr = NULL;
specific_info_t *spec_info = popup_win->spec_info;
char error_char[100];
GtkWidget *label = NULL;
GtkTreeView *tree_view = NULL;
List info_list = NULL;
List send_info_list = NULL;
ListIterator itr = NULL;
sview_node_info_t *sview_node_info_ptr = NULL;
node_info_t *node_ptr = NULL;
hostlist_t hostlist = NULL;
hostlist_iterator_t host_itr = NULL;
int i = -1, sort_key;
sview_search_info_t *search_info = spec_info->search_info;
if (!spec_info->display_widget)
setup_popup_info(popup_win, display_data_node, SORTID_CNT);
if (node_info_ptr && popup_win->toggled) {
gtk_widget_destroy(spec_info->display_widget);
spec_info->display_widget = NULL;
/* Since the node_info_ptr could change out from under
* us we always need to check if it is new or not.
*/
/* goto display_it; */
}
if ((error_code = get_new_info_node(&node_info_ptr,
popup_win->force_refresh))
== <API key>) {
if (!spec_info->display_widget || spec_info->view == ERROR_VIEW)
goto display_it;
} else if (error_code != SLURM_SUCCESS) {
if (spec_info->view == ERROR_VIEW)
goto end_it;
spec_info->view = ERROR_VIEW;
if (spec_info->display_widget)
gtk_widget_destroy(spec_info->display_widget);
sprintf(error_char, "slurm_load_node: %s",
slurm_strerror(slurm_get_errno()));
label = gtk_label_new(error_char);
<API key>(popup_win->table,
label,
0, 1, 0, 1);
gtk_widget_show(label);
spec_info->display_widget = gtk_widget_ref(label);
return;
}
display_it:
info_list = <API key>(node_info_ptr, FALSE);
if (!info_list)
return;
if (spec_info->view == ERROR_VIEW && spec_info->display_widget) {
gtk_widget_destroy(spec_info->display_widget);
spec_info->display_widget = NULL;
}
if (spec_info->type != INFO_PAGE && !spec_info->display_widget) {
tree_view = create_treeview(local_display_data,
&popup_win->grid_button_list);
/*set multiple capability here*/
<API key>(
<API key>(tree_view),
<API key>);
spec_info->display_widget =
gtk_widget_ref(GTK_WIDGET(tree_view));
<API key>(popup_win->table,
GTK_WIDGET(tree_view),
0, 1, 0, 1);
/* Since this function sets the model of the tree_view to the
* treestore we don't really care about the return value
* On large clusters, sorting on the node name slows GTK down
* by a large margin. */
if (node_info_ptr->record_count > 1000)
sort_key = -1;
else
sort_key = SORTID_NAME;
create_treestore(tree_view, popup_win->display_data,
SORTID_CNT, sort_key, SORTID_COLOR);
}
<API key>(popup_win);
spec_info->view = INFO_VIEW;
if (spec_info->type == INFO_PAGE) {
_display_info_node(info_list, popup_win);
goto end_it;
}
<API key>(popup_win);
/* just linking to another list, don't free the inside, just
the list */
send_info_list = list_create(NULL);
if (search_info->gchar_data) {
hostlist = hostlist_create(search_info->gchar_data);
host_itr = <API key>(hostlist);
}
i = -1;
itr = <API key>(info_list);
while ((sview_node_info_ptr = list_next(itr))) {
int found = 0;
char *host = NULL;
i++;
node_ptr = sview_node_info_ptr->node_ptr;
switch(search_info->search_type) {
case SEARCH_NODE_STATE:
if (search_info->int_data == NO_VAL)
continue;
else if (search_info->int_data
!= node_ptr->node_state) {
if (IS_NODE_MIXED(node_ptr)) {
uint16_t alloc_cnt = 0, err_cnt = 0;
uint16_t idle_cnt = node_ptr->cpus;
<API key>(
node_ptr->select_nodeinfo,
<API key>,
<API key>,
&alloc_cnt);
<API key>(
node_ptr->select_nodeinfo,
<API key>,
NODE_STATE_ERROR,
&err_cnt);
idle_cnt -= (alloc_cnt + err_cnt);
if ((search_info->int_data
& NODE_STATE_BASE)
== <API key>) {
if (alloc_cnt)
break;
} else if ((search_info->int_data
& NODE_STATE_BASE)
== NODE_STATE_ERROR) {
if (err_cnt)
break;
} else if ((search_info->int_data
& NODE_STATE_BASE)
== NODE_STATE_IDLE) {
if (idle_cnt)
break;
}
}
continue;
}
break;
case SEARCH_NODE_NAME:
default:
if (!search_info->gchar_data)
continue;
while ((host = hostlist_next(host_itr))) {
if (!strcmp(host, node_ptr->name)) {
free(host);
found = 1;
break;
}
free(host);
}
<API key>(host_itr);
if (!found)
continue;
break;
}
list_push(send_info_list, sview_node_info_ptr);
change_grid_color(popup_win->grid_button_list,
i, i, 0, true, 0);
}
<API key>(itr);
<API key>(popup_win);
if (search_info->gchar_data) {
<API key>(host_itr);
hostlist_destroy(hostlist);
}
_update_info_node(send_info_list,
GTK_TREE_VIEW(spec_info->display_widget));
list_destroy(send_info_list);
end_it:
popup_win->toggled = 0;
popup_win->force_refresh = 0;
return;
}
extern void set_menus_node(void *arg, void *arg2, GtkTreePath *path, int type)
{
GtkTreeView *tree_view = (GtkTreeView *)arg;
popup_info_t *popup_win = (popup_info_t *)arg;
GtkMenu *menu = (GtkMenu *)arg2;
List button_list = (List)arg2;
switch(type) {
case TAB_CLICKED:
make_fields_menu(NULL, menu, display_data_node, SORTID_CNT);
break;
case ROW_CLICKED:
make_options_menu(tree_view, path, menu, options_data_node);
break;
case ROW_LEFT_CLICKED:
{
GtkTreeModel *model = <API key>(tree_view);
GtkTreeIter iter;
if (!<API key>(model, &iter, path)) {
g_error("error getting iter from model\n");
break;
}
highlight_grid(tree_view, SORTID_POS, (int)NO_VAL, button_list);
break;
}
case FULL_CLICKED:
{
GtkTreeModel *model = <API key>(tree_view);
GtkTreeIter iter;
if (!<API key>(model, &iter, path)) {
g_error("error getting iter from model\n");
break;
}
popup_all_node(model, &iter, INFO_PAGE);
break;
}
case POPUP_CLICKED:
make_fields_menu(popup_win, menu,
popup_win->display_data, SORTID_CNT);
break;
default:
g_error("UNKNOWN type %d given to set_fields\n", type);
}
}
extern void popup_all_node(GtkTreeModel *model, GtkTreeIter *iter, int id)
{
char *name = NULL;
gtk_tree_model_get(model, iter, SORTID_NAME, &name, -1);
if (_DEBUG)
g_print("popup_all_node: name = %s\n", name);
popup_all_node_name(name, id);
/* this name gets g_strdup'ed in the previous function */
g_free(name);
}
extern void popup_all_node_name(char *name, int id)
{
char title[100];
ListIterator itr = NULL;
popup_info_t *popup_win = NULL;
GError *error = NULL;
char *node;
if (cluster_flags & CLUSTER_FLAG_BG)
node = "Midplane";
else
node = "Node";
switch(id) {
case JOB_PAGE:
snprintf(title, 100, "Job(s) with %s %s", node, name);
break;
case PART_PAGE:
snprintf(title, 100, "Partition(s) with %s %s", node, name);
break;
case RESV_PAGE:
snprintf(title, 100, "Reservation(s) with %s %s", node, name);
break;
case BLOCK_PAGE:
snprintf(title, 100, "Blocks(s) with %s %s", node, name);
break;
case SUBMIT_PAGE:
snprintf(title, 100, "Submit job on %s %s", node, name);
break;
case INFO_PAGE:
snprintf(title, 100, "Full Info for %s %s", node, name);
break;
default:
g_print("%s got %d\n", node, id);
}
itr = <API key>(popup_list);
while ((popup_win = list_next(itr))) {
if (popup_win->spec_info)
if (!strcmp(popup_win->spec_info->title, title)) {
break;
}
}
<API key>(itr);
if (!popup_win) {
if (id == INFO_PAGE)
popup_win = create_popup_info(id, NODE_PAGE, title);
else
popup_win = create_popup_info(NODE_PAGE, id, title);
popup_win->spec_info->search_info->gchar_data = g_strdup(name);
if (!sview_thread_new((gpointer)popup_thr, popup_win,
FALSE, &error)) {
g_printerr ("Failed to create node popup thread: "
"%s\n",
error->message);
return;
}
} else
gtk_window_present(GTK_WINDOW(popup_win->popup));
}
extern void <API key>(char *name, GdkEventButton *event)
{
GtkMenu *menu = GTK_MENU(gtk_menu_new());
display_data_t *display_data = options_data_node;
GtkWidget *menuitem;
while (display_data++) {
if (display_data->id == -1)
break;
if (!display_data->name)
continue;
display_data->user_data = name;
menuitem = <API key>(display_data->name);
g_signal_connect(menuitem, "activate",
G_CALLBACK(_selected_page),
display_data);
<API key>(GTK_MENU_SHELL(menu), menuitem);
}
gtk_widget_show_all(GTK_WIDGET(menu));
gtk_menu_popup(menu, NULL, NULL, NULL, NULL,
event ? event->button : 0,
gdk_event_get_time((GdkEvent*)event));
}
extern void select_admin_nodes(GtkTreeModel *model,
GtkTreeIter *iter,
display_data_t *display_data,
uint32_t node_col,
GtkTreeView *treeview)
{
if (treeview) {
char *old_value = NULL;
hostlist_t hl = NULL;
process_node_t process_node;
memset(&process_node, 0, sizeof(process_node_t));
if (node_col == NO_VAL)
process_node.node_col = SORTID_NAME;
else
process_node.node_col = node_col;
<API key>(
<API key>(treeview),
_process_each_node, &process_node);
hl = hostlist_create(process_node.nodelist);
hostlist_uniq(hl);
hostlist_sort(hl);
xfree(process_node.nodelist);
process_node.nodelist = <API key>(hl);
hostlist_destroy(hl);
if (!strcasecmp("Update Features", display_data->name)) {
/* get old features */
gtk_tree_model_get(model, iter, SORTID_FEATURES,
&old_value, -1);
} else if (!strcasecmp("Update Gres", display_data->name)) {
/* get old gres */
gtk_tree_model_get(model, iter, SORTID_GRES,
&old_value, -1);
}
admin_node_name(process_node.nodelist, old_value,
display_data->name);
xfree(process_node.nodelist);
if (old_value)
g_free(old_value);
}
} /*select_admin_nodes ^^^*/
extern void admin_node_name(char *name, char *old_value, char *type)
{
GtkWidget *popup = <API key>(
type,
GTK_WINDOW(main_window),
GTK_DIALOG_MODAL | <API key>,
NULL);
<API key>(GTK_WINDOW(popup), NULL);
if (!strcasecmp("Update Features", type)
|| !strcasecmp("Update Node Features", type)
|| !strcasecmp("Update Midplane Features",
type)) { /* update features */
<API key>(GTK_DIALOG(popup), name, old_value);
} else if (!strcasecmp("Update Gres", type)) { /* update gres */
update_gres_node(GTK_DIALOG(popup), name, old_value);
} else /* something that has to deal with a node state change */
update_state_node(GTK_DIALOG(popup), name, type);
gtk_widget_destroy(popup);
return;
}
extern void cluster_change_node(void)
{
display_data_t *display_data = display_data_node;
while (display_data++) {
if (display_data->id == -1)
break;
if (cluster_flags & CLUSTER_FLAG_BG) {
switch(display_data->id) {
case SORTID_RACK_MP:
display_data->name = "RackMidplane";
break;
}
} else {
switch(display_data->id) {
case SORTID_RACK_MP:
display_data->name = NULL;
break;
}
}
}
display_data = options_data_node;
while (display_data++) {
if (display_data->id == -1)
break;
if (cluster_flags & CLUSTER_FLAG_BG) {
switch(display_data->id) {
case BLOCK_PAGE:
display_data->name = "Blocks";
break;
}
if (!display_data->name) {
} else if (!strcmp(display_data->name, "Drain Node"))
display_data->name = "Drain Midplane";
else if (!strcmp(display_data->name, "Undrain Node"))
display_data->name = "Undrain Midplane";
else if (!strcmp(display_data->name, "Resume Node"))
display_data->name = "Resume Midplane";
else if (!strcmp(display_data->name, "Put Node Down"))
display_data->name = "Put Midplane Down";
else if (!strcmp(display_data->name, "Make Node Idle"))
display_data->name =
"Make Midplane Idle";
} else {
switch(display_data->id) {
case BLOCK_PAGE:
display_data->name = NULL;
break;
}
if (!display_data->name) {
} else if (!strcmp(display_data->name,
"Drain Midplanes"))
display_data->name = "Drain Nodes";
else if (!strcmp(display_data->name,
"Undrain Midplanes"))
display_data->name = "Undrain Nodes";
else if (!strcmp(display_data->name,
"Resume Midplanes"))
display_data->name = "Resume Nodes";
else if (!strcmp(display_data->name,
"Put Midplanes Down"))
display_data->name = "Put Nodes Down";
else if (!strcmp(display_data->name,
"Make Midplanes Idle"))
display_data->name = "Make Nodes Idle";
}
}
get_info_node(NULL, NULL);
} |
package BimBimWS;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author depit
*/
@Entity
@Table(name = "vterti")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Vterti.findAll", query = "SELECT v FROM Vterti v"),
@NamedQuery(name = "Vterti.findBySediu", query = "SELECT v FROM Vterti v WHERE v.sediu = :sediu"),
@NamedQuery(name = "Vterti.findByCui", query = "SELECT v FROM Vterti v WHERE v.cui = :cui"),
@NamedQuery(name = "Vterti.findByPlt", query = "SELECT v FROM Vterti v WHERE v.plt = :plt"),
@NamedQuery(name = "Vterti.findByDenumire", query = "SELECT v FROM Vterti v WHERE v.denumire = :denumire"),
@NamedQuery(name = "Vterti.findByCategorieId", query = "SELECT v FROM Vterti v WHERE v.categorieId = :categorieId"),
@NamedQuery(name = "Vterti.findByGrupaId", query = "SELECT v FROM Vterti v WHERE v.grupaId = :grupaId"),
@NamedQuery(name = "Vterti.findByClasaId", query = "SELECT v FROM Vterti v WHERE v.clasaId = :clasaId"),
@NamedQuery(name = "Vterti.findBySiruta", query = "SELECT v FROM Vterti v WHERE v.siruta = :siruta"),
@NamedQuery(name = "Vterti.findByTertId", query = "SELECT v FROM Vterti v WHERE v.tertId = :tertId"),
@NamedQuery(name = "Vterti.findBySw0", query = "SELECT v FROM Vterti v WHERE v.sw0 = :sw0"),
@NamedQuery(name = "Vterti.findByTvai", query = "SELECT v FROM Vterti v WHERE v.tvai = :tvai"),
@NamedQuery(name = "Vterti.findByTtipId", query = "SELECT v FROM Vterti v WHERE v.ttipId = :ttipId"),
@NamedQuery(name = "Vterti.findByTrisc", query = "SELECT v FROM Vterti v WHERE v.trisc = :trisc"),
@NamedQuery(name = "Vterti.findByTmodplata", query = "SELECT v FROM Vterti v WHERE v.tmodplata = :tmodplata")})
public class Vterti implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "sediu")
private String sediu;
@Column(name = "cui")
private String cui;
@Column(name = "plt")
private String plt;
@Column(name = "denumire")
private String denumire;
@Column(name = "categorie_id")
private String categorieId;
@Column(name = "grupa_id")
private String grupaId;
@Column(name = "clasa_id")
private String clasaId;
@Column(name = "siruta")
private Integer siruta;
@Column(name = "tert_id")
private String tertId;
@Column(name = "sw_0")
private Character sw0;
@Column(name = "tvai")
private Boolean tvai;
@Column(name = "ttip_id")
private String ttipId;
@Column(name = "trisc")
private Integer trisc;
@Column(name = "tmodplata")
private Integer tmodplata;
public Vterti() {
}
public String getSediu() {
return sediu;
}
public void setSediu(String sediu) {
this.sediu = sediu;
}
public String getCui() {
return cui;
}
public void setCui(String cui) {
this.cui = cui;
}
public String getPlt() {
return plt;
}
public void setPlt(String plt) {
this.plt = plt;
}
public String getDenumire() {
return denumire;
}
public void setDenumire(String denumire) {
this.denumire = denumire;
}
public String getCategorieId() {
return categorieId;
}
public void setCategorieId(String categorieId) {
this.categorieId = categorieId;
}
public String getGrupaId() {
return grupaId;
}
public void setGrupaId(String grupaId) {
this.grupaId = grupaId;
}
public String getClasaId() {
return clasaId;
}
public void setClasaId(String clasaId) {
this.clasaId = clasaId;
}
public Integer getSiruta() {
return siruta;
}
public void setSiruta(Integer siruta) {
this.siruta = siruta;
}
public String getTertId() {
return tertId;
}
public void setTertId(String tertId) {
this.tertId = tertId;
}
public Character getSw0() {
return sw0;
}
public void setSw0(Character sw0) {
this.sw0 = sw0;
}
public Boolean getTvai() {
return tvai;
}
public void setTvai(Boolean tvai) {
this.tvai = tvai;
}
public String getTtipId() {
return ttipId;
}
public void setTtipId(String ttipId) {
this.ttipId = ttipId;
}
public Integer getTrisc() {
return trisc;
}
public void setTrisc(Integer trisc) {
this.trisc = trisc;
}
public Integer getTmodplata() {
return tmodplata;
}
public void setTmodplata(Integer tmodplata) {
this.tmodplata = tmodplata;
}
} |
<?php
defined( '_JEXEC' ) or die;
$bar = ( $this->uix == 'full' ) ? 'on' : 'off';
$data = Helper_Workshop::getParams( 'type', $this->item->master, $this->item->client );
$clone = '';
$positions = array();
if ( JCck::on() ) {
$attr = array( 'class'=>' b', 'span'=>'<span class="icon-pencil-2"></span>' );
} else {
$attr = array( 'class'=>' edit', 'span'=>'' );
}
?>
<div class="seb-wrapper <?php echo $this->uix; ?>">
<div class="width-70 fltlft" id="seblod-main">
<div class="seblod">
<div id="linkage_wrap"><?php echo JCckDev::getForm( $cck['core_linkage'], 1, $config ); ?></div>
<div class="legend top left"><?php echo JText::_( '<API key>'.$this->uix ) . '<span class="mini">('.JText::_( 'COM_CCK_FOR_VIEW_'.$this->item->client ).')</span>'; ?></div>
<?php
$style = array( '1'=>'', '2'=>' hide', '3'=>' hide', '4'=>' hide', '5'=>' hide' );
Helper_Workshop::displayHeader( 'type', $this->item->master );
echo '<ul class="sortable connected" id="sortable1" myid="1">';
foreach ( $this->positions as $pos ) {
if ( isset( $this->fields[$pos->name] ) ) {
$this->setPosition( $pos->name );
foreach ( $this->fields[$pos->name] as $field ) {
$type_field = '';
if ( isset( $this->type_fields[$field->id] ) ) {
$type_field = ' c-'.$this->type_fields[$field->id]->cc;
}
JCck::callFunc_Array( 'plgCCK_Field'.$field->type, '<API key>'.$this->item->master, array( &$field, $style, $data ) );
Helper_Workshop::displayField( $field, $type_field, $attr );
}
} else {
$positions[] = $pos->name;
}
}
$i = 0;
$n = count( $positions );
if ( $this->p <= 6 ) {
$p = $this->p;
for ( $i = 0; $p <= 5; $i++,$p++ ) {
$this->setPosition( $positions[$i] );
}
}
Helper_Workshop::displayPositionEnd( $this->positions_nb );
echo '</ul>';
?>
</div>
<div class="seblod">
<span class="legend top left"><?php echo JText::_( '<API key>' ); ?></span><span class="toggle" id="more_fields">Toggle</span>
<?php
if ( count( $this->fieldsAv ) ) {
echo '<div class="legend top center">'.$this->lists['af_t'].$this->lists['af_c'].$this->lists['af_f'].$this->lists['af_a'].'</div>';
echo '<div id="scroll"><ul class="sortable connected" id="sortable2" myid="2">';
$style = array( '1'=>' hide', '2'=>' hide', '3'=>' hide', '4'=>' hide', '5'=>' hide' );
foreach ( $this->fieldsAv as $field ) {
$type_field = '';
if ( isset( $this->type_fields[$field->id] ) ) {
$type_field = ' c-'.$this->type_fields[$field->id]->cc;
}
JCck::callFunc_Array( 'plgCCK_Field'.$field->type, '<API key>'.$this->item->master, array( &$field, $style, $data ) );
Helper_Workshop::displayField( $field, $type_field, $attr );
}
echo '</ul></div><div id="sortable_original" style="display: none;"></div>';
}
?>
</div>
<div class="seblod">
<span class="legend top left"><?php echo JText::_( '<API key>' ); ?></span><span class="toggle" id="more_positions">Toggle</span>
<ul class="more_pos">
<?php
for ( ; $i < $n; $i++ ) {
$this->setPosition( $positions[$i] );
}
?>
</ul>
</div>
</div>
<div class="width-30 <?php echo $bar; ?> active" id="seblod-sidebar">
<div class="seblod" id="seblod-sideblock">
<div class="fltlft seblod-toolbar"><?php Helper_Workshop::displayToolbar( 'type', $this->item->master, $this->item->client, $this->uix, $clone ); ?></div>
</div>
</div>
</div>
<div class="clr" id="seblod-cleaner"></div>
<script type="text/javascript">
jQuery(document).ready(function($){
$("div#scroll").slideToggle();
$("#more_positions").live("click", function() {
$("ul.more_pos").slideToggle();
});
$("#more_fields").live("click", function() {
$("div#scroll").slideToggle();
});
$(".filter").live("change", function() {
if(this.value) {
$("div#scroll").slideDown();
}
});
});
</script> |
#ifndef DIRECTION_HPP
#define DIRECTION_HPP
enum class DirectionType
{
NORTH = 0,
WEST = 1,
SOUTH = 2,
EAST = 3
};
struct Direction
{
Direction( DirectionType type ) noexcept : type( type ) { }
virtual operator DirectionType( void ) const noexcept;
virtual void rotateClockwise( void ) noexcept;
virtual void <API key>( void ) noexcept;
DirectionType type;
};
#endif |
/*!
* \file AIsEven.hpp Contains general template implementation of the even
* number check algorithm.
* \brief Even number check algorithm.
* \author Ivan Shynkarenka aka 4ekucT
* \version 1.0
* \date 25.01.2007
*/
/*
FILE ID: $Id$
CHANGE LOG:
$Log$
*/
#ifndef __AISEVEN_HPP__
#define __AISEVEN_HPP__
#include <Depth/include/concept/base/MConceptInteger.hpp>
/* NAMESPACE DECLARATIONS */
namespace NDepth {
namespace NAlgorithms {
namespace NNumeric {
/* ALGORITHM DECLARATIONS */
//! Algorithm: Checks if given integer number is even.
/*!
\param a_crX - Constant reference to the number.
\return true - if given integer number is even. \n
false - if given integer number is odd. \n
*/
template <typename T_Type>
Tbool isEven(const T_Type& a_crX);
}
}
}
#include <Depth/include/algorithms/numeric/AIsEven.inl>
#endif |
var jqplotOptions;
var placeHolderCount = 0;
var indicatorPanels = [];
$(document).ready( function() {
jqplotOptions = {
title: ' ',
seriesDefaults: {
shadow: false,
renderer: $.jqplot.PieRenderer,
rendererOptions: {
startAngle: 180,
sliceMargin: 4,
showDataLabels: true,
dataLabels: 'value',
dataLabelThreshold: 0
}
},
grid: {
drawGridLines: false, // wether to draw lines across the grid or not.
gridLineColor: '#cccccc', // CSS color spec of the grid lines.
background: 'white', // CSS color spec for background color of grid.
borderColor: 'white', // CSS color spec for border around grid.
borderWidth: 0, // pixel width of border around grid.
shadow: false, // draw a shadow for grid.
shadowAngle: 0, // angle of the shadow. Clockwise from x axis.
shadowOffset: 0, // offset from the line of the shadow.
shadowWidth: 0, // width of the stroke for the shadow.
shadowDepth: 0
},
legend: { show:true, location: 's' }
};
// get the drill down page
$(".indicatorWrapper").on('click', ".<API key>", function(event) {
event.preventDefault();
var url = "/web/dashboard/display/DrilldownDisplay.do";
var data = new Object();
data.indicatorTemplateId = (this.id).split("_")[1];
data.method = (this.id).split("_")[0];
sendData(url, data, null);
});
$(".indicatorWrapper").on("click", ".indicatorGraph", function(event) {
event.preventDefault();
var url = "/web/dashboard/display/DrilldownDisplay.do";
var data = new Object();
data.indicatorTemplateId = (this.id).split("_")[1];
data.method = "getDrilldown";
sendData(url, data, null);
});
// get the dashboard manager page
$(".dashboardManagerBtn").on('click', function(event) {
event.preventDefault();
var url = "/web/dashboard/admin/DashboardManager.do";
var data = "dashboardId=" + this.id;
sendData(url, data, null);
});
// reload this dashboard with fresh data.
$(".reloadDashboardBtn").on('click', function(event) {
event.preventDefault();
var url = "/web/dashboard/display/DashboardDisplay.do";
var data = new Object();
data.dashboardId = (this.id).split("_")[1];
data.method = (this.id).split("_")[0];
sendData(url, data, null);
});
$(".indicatorWrapper").each(function(){
var data = new Object();
data.method = "getIndicator";
data.indicatorId = this.id.split("_")[1];
sendData("/web/dashboard/display/DisplayIndicator.do", data, this.id.split("_")[0]);
})
placeHolderCount = $(".indicatorWrapper").length;
})
// build Indicator panel with Pie chart.
function buildIndicatorPanel( html, target, id ) {
var indicatorGraph;
if ( indicatorGraph ) {
indicatorGraph.destroy();
}
var panel = $( "#" + target + "_" + id ).html( html ); //.append("<h3>" +id+ "</h3>");
var data = "[" + panel.find( "#graphPlots_" + id ).val() + "]";
data = data.replace(/'/g, '"');
data = JSON.parse( data )
indicatorGraph = $.jqplot ( 'graphContainer_' + id, data, jqplotOptions ).replot();
window.onresize = function(event) {
indicatorGraph.replot();
}
var name = panel.find( ".indicatorHeading div" ).text();
var paneldata = [ name, id, data ];
if( paneldata ) {
indicatorPanels.push( paneldata );
}
if( indicatorPanels.length === placeHolderCount ) {
var panelList;
for(var i = 0; i < indicatorPanels.length; i++ ) {
var ipanel = indicatorPanels[i];
var name, id, data;
if( ipanel ) {
name = ipanel[0].trim();
id = ipanel[1];
data = ipanel[2];
panelList += ( "NAME " + name + ", ID " + id + "\n " + " DATA " + data + "\n" );
}
}
return panelList;
}
}
function sendData(path, param, target) {
$.ajax({
url: ctx + path,
type: 'POST',
data: param,
dataType: 'html',
success: function(data) {
if( target === "indicatorId") {
var panelList = buildIndicatorPanel( data, target, param.indicatorId );
if( panelList ) {
console.log( panelList );
}
} else {
document.open();
document.write(data);
document.close();
}
}
});
} |
#include <linux/crc32.h>
#include "qxl_drv.h"
#include "qxl_object.h"
#include "drm_crtc_helper.h"
#include <drm/drm_plane_helper.h>
static bool qxl_head_enabled(struct qxl_head *head)
{
return head->width && head->height;
}
void <API key>(struct qxl_device *qdev, unsigned count)
{
if (qdev-><API key> &&
count > qdev-><API key>->count) {
kfree(qdev-><API key>);
qdev-><API key> = NULL;
}
if (!qdev-><API key>) {
qdev-><API key> = kzalloc(
sizeof(struct qxl_monitors_config) +
sizeof(struct qxl_head) * count, GFP_KERNEL);
if (!qdev-><API key>) {
qxl_io_log(qdev,
"%s: allocation failure for %u heads\n",
__func__, count);
return;
}
}
qdev-><API key>->count = count;
}
static int <API key>(struct qxl_device *qdev)
{
int i;
int num_monitors;
uint32_t crc;
num_monitors = qdev->rom-><API key>.count;
crc = crc32(0, (const uint8_t *)&qdev->rom-><API key>,
sizeof(qdev->rom-><API key>));
if (crc != qdev->rom-><API key>) {
qxl_io_log(qdev, "crc mismatch: have %X (%zd) != %X\n", crc,
sizeof(qdev->rom-><API key>),
qdev->rom-><API key>);
return 1;
}
if (num_monitors > qdev->monitors_config->max_allowed) {
DRM_DEBUG_KMS("client monitors list will be truncated: %d < %d\n",
qdev->monitors_config->max_allowed, num_monitors);
num_monitors = qdev->monitors_config->max_allowed;
} else {
num_monitors = qdev->rom-><API key>.count;
}
<API key>(qdev, num_monitors);
/* we copy max from the client but it isn't used */
qdev-><API key>->max_allowed =
qdev->monitors_config->max_allowed;
for (i = 0 ; i < qdev-><API key>->count ; ++i) {
struct qxl_urect *c_rect =
&qdev->rom-><API key>.heads[i];
struct qxl_head *client_head =
&qdev-><API key>->heads[i];
client_head->x = c_rect->left;
client_head->y = c_rect->top;
client_head->width = c_rect->right - c_rect->left;
client_head->height = c_rect->bottom - c_rect->top;
client_head->surface_id = 0;
client_head->id = i;
client_head->flags = 0;
DRM_DEBUG_KMS("read %dx%d+%d+%d\n", client_head->width, client_head->height,
client_head->x, client_head->y);
}
return 0;
}
static void <API key>(struct qxl_device *qdev)
{
struct drm_device *dev = qdev->ddev;
struct drm_connector *connector;
struct qxl_output *output;
struct qxl_head *head;
list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
output = <API key>(connector);
head = &qdev-><API key>->heads[output->index];
<API key>(&connector->base,
dev->mode_config.<API key>, head->x);
<API key>(&connector->base,
dev->mode_config.<API key>, head->y);
}
}
void <API key>(struct qxl_device *qdev)
{
struct drm_device *dev = qdev->ddev;
while (<API key>(qdev)) {
qxl_io_log(qdev, "failed crc check for <API key>,"
" retrying\n");
}
<API key>(dev);
<API key>(qdev);
<API key>(dev);
if (!<API key>(qdev->ddev)) {
/* notify that the monitor configuration changed, to
adjust at the arbitrary resolution */
<API key>(qdev->ddev);
}
}
static int <API key>(struct drm_connector *connector,
unsigned *pwidth,
unsigned *pheight)
{
struct drm_device *dev = connector->dev;
struct qxl_device *qdev = dev->dev_private;
struct qxl_output *output = <API key>(connector);
int h = output->index;
struct drm_display_mode *mode = NULL;
struct qxl_head *head;
if (!qdev-><API key>)
return 0;
head = &qdev-><API key>->heads[h];
mode = drm_cvt_mode(dev, head->width, head->height, 60, false, false,
false);
mode->type |= <API key>;
*pwidth = head->width;
*pheight = head->height;
drm_mode_probed_add(connector, mode);
/* remember the last custom size for mode validation */
qdev-><API key> = mode->hdisplay;
qdev-><API key> = mode->vdisplay;
return 1;
}
static struct mode_size {
int w;
int h;
} common_modes[] = {
{ 640, 480},
{ 720, 480},
{ 800, 600},
{ 848, 480},
{1024, 768},
{1152, 768},
{1280, 720},
{1280, 800},
{1280, 854},
{1280, 960},
{1280, 1024},
{1440, 900},
{1400, 1050},
{1680, 1050},
{1600, 1200},
{1920, 1080},
{1920, 1200}
};
static int <API key>(struct drm_connector *connector,
unsigned pwidth,
unsigned pheight)
{
struct drm_device *dev = connector->dev;
struct drm_display_mode *mode = NULL;
int i;
for (i = 0; i < ARRAY_SIZE(common_modes); i++) {
mode = drm_cvt_mode(dev, common_modes[i].w, common_modes[i].h,
60, false, false, false);
if (common_modes[i].w == pwidth && common_modes[i].h == pheight)
mode->type |= <API key>;
drm_mode_probed_add(connector, mode);
}
return i - 1;
}
static void qxl_crtc_destroy(struct drm_crtc *crtc)
{
struct qxl_crtc *qxl_crtc = to_qxl_crtc(crtc);
drm_crtc_cleanup(crtc);
qxl_bo_unref(&qxl_crtc->cursor_bo);
kfree(qxl_crtc);
}
static int qxl_crtc_page_flip(struct drm_crtc *crtc,
struct drm_framebuffer *fb,
struct <API key> *event,
uint32_t page_flip_flags)
{
struct drm_device *dev = crtc->dev;
struct qxl_device *qdev = dev->dev_private;
struct qxl_framebuffer *qfb_src = to_qxl_framebuffer(fb);
struct qxl_framebuffer *qfb_old = to_qxl_framebuffer(crtc->primary->fb);
struct qxl_bo *bo_old = gem_to_qxl_bo(qfb_old->obj);
struct qxl_bo *bo = gem_to_qxl_bo(qfb_src->obj);
unsigned long flags;
struct drm_clip_rect norect = {
.x1 = 0,
.y1 = 0,
.x2 = fb->width,
.y2 = fb->height
};
int inc = 1;
int one_clip_rect = 1;
int ret = 0;
crtc->primary->fb = fb;
bo_old->is_primary = false;
bo->is_primary = true;
ret = qxl_bo_reserve(bo, false);
if (ret)
return ret;
ret = qxl_bo_pin(bo, bo->type, NULL);
qxl_bo_unreserve(bo);
if (ret)
return ret;
qxl_draw_dirty_fb(qdev, qfb_src, bo, 0, 0,
&norect, one_clip_rect, inc);
drm_crtc_vblank_get(crtc);
if (event) {
spin_lock_irqsave(&dev->event_lock, flags);
<API key>(crtc, event);
<API key>(&dev->event_lock, flags);
}
drm_crtc_vblank_put(crtc);
ret = qxl_bo_reserve(bo, false);
if (!ret) {
qxl_bo_unpin(bo);
qxl_bo_unreserve(bo);
}
return 0;
}
static int
qxl_hide_cursor(struct qxl_device *qdev)
{
struct qxl_release *release;
struct qxl_cursor_cmd *cmd;
int ret;
ret = <API key>(qdev, sizeof(*cmd), <API key>,
&release, NULL);
if (ret)
return ret;
ret = <API key>(release, true);
if (ret) {
qxl_release_free(qdev, release);
return ret;
}
cmd = (struct qxl_cursor_cmd *)qxl_release_map(qdev, release);
cmd->type = QXL_CURSOR_HIDE;
qxl_release_unmap(qdev, release, &cmd->release_info);
<API key>(qdev, release, QXL_CMD_CURSOR, false);
<API key>(release);
return 0;
}
static int <API key>(struct drm_crtc *crtc)
{
struct qxl_crtc *qcrtc = to_qxl_crtc(crtc);
struct drm_device *dev = crtc->dev;
struct qxl_device *qdev = dev->dev_private;
struct qxl_cursor_cmd *cmd;
struct qxl_release *release;
int ret = 0;
if (!qcrtc->cursor_bo)
return 0;
ret = <API key>(qdev, sizeof(*cmd),
<API key>,
&release, NULL);
if (ret)
return ret;
ret = <API key>(release, qcrtc->cursor_bo);
if (ret)
goto out_free_release;
ret = <API key>(release, false);
if (ret)
goto out_free_release;
cmd = (struct qxl_cursor_cmd *)qxl_release_map(qdev, release);
cmd->type = QXL_CURSOR_SET;
cmd->u.set.position.x = qcrtc->cur_x + qcrtc->hot_spot_x;
cmd->u.set.position.y = qcrtc->cur_y + qcrtc->hot_spot_y;
cmd->u.set.shape = <API key>(qdev, qcrtc->cursor_bo, 0);
cmd->u.set.visible = 1;
qxl_release_unmap(qdev, release, &cmd->release_info);
<API key>(qdev, release, QXL_CMD_CURSOR, false);
<API key>(release);
return ret;
out_free_release:
qxl_release_free(qdev, release);
return ret;
}
static int <API key>(struct drm_crtc *crtc,
struct drm_file *file_priv,
uint32_t handle,
uint32_t width,
uint32_t height, int32_t hot_x, int32_t hot_y)
{
struct drm_device *dev = crtc->dev;
struct qxl_device *qdev = dev->dev_private;
struct qxl_crtc *qcrtc = to_qxl_crtc(crtc);
struct drm_gem_object *obj;
struct qxl_cursor *cursor;
struct qxl_cursor_cmd *cmd;
struct qxl_bo *cursor_bo, *user_bo;
struct qxl_release *release;
void *user_ptr;
int size = 64*64*4;
int ret = 0;
if (!handle)
return qxl_hide_cursor(qdev);
obj = <API key>(file_priv, handle);
if (!obj) {
DRM_ERROR("cannot find cursor object\n");
return -ENOENT;
}
user_bo = gem_to_qxl_bo(obj);
ret = qxl_bo_reserve(user_bo, false);
if (ret)
goto out_unref;
ret = qxl_bo_pin(user_bo, QXL_GEM_DOMAIN_CPU, NULL);
qxl_bo_unreserve(user_bo);
if (ret)
goto out_unref;
ret = qxl_bo_kmap(user_bo, &user_ptr);
if (ret)
goto out_unpin;
ret = <API key>(qdev, sizeof(*cmd),
<API key>,
&release, NULL);
if (ret)
goto out_kunmap;
ret = <API key>(qdev, release, sizeof(struct qxl_cursor) + size,
&cursor_bo);
if (ret)
goto out_free_release;
ret = <API key>(release, false);
if (ret)
goto out_free_bo;
ret = qxl_bo_kmap(cursor_bo, (void **)&cursor);
if (ret)
goto out_backoff;
cursor->header.unique = 0;
cursor->header.type = <API key>;
cursor->header.width = 64;
cursor->header.height = 64;
cursor->header.hot_spot_x = hot_x;
cursor->header.hot_spot_y = hot_y;
cursor->data_size = size;
cursor->chunk.next_chunk = 0;
cursor->chunk.prev_chunk = 0;
cursor->chunk.data_size = size;
memcpy(cursor->chunk.data, user_ptr, size);
qxl_bo_kunmap(cursor_bo);
qxl_bo_kunmap(user_bo);
qcrtc->cur_x += qcrtc->hot_spot_x - hot_x;
qcrtc->cur_y += qcrtc->hot_spot_y - hot_y;
qcrtc->hot_spot_x = hot_x;
qcrtc->hot_spot_y = hot_y;
cmd = (struct qxl_cursor_cmd *)qxl_release_map(qdev, release);
cmd->type = QXL_CURSOR_SET;
cmd->u.set.position.x = qcrtc->cur_x + qcrtc->hot_spot_x;
cmd->u.set.position.y = qcrtc->cur_y + qcrtc->hot_spot_y;
cmd->u.set.shape = <API key>(qdev, cursor_bo, 0);
cmd->u.set.visible = 1;
qxl_release_unmap(qdev, release, &cmd->release_info);
<API key>(qdev, release, QXL_CMD_CURSOR, false);
<API key>(release);
/* finish with the userspace bo */
ret = qxl_bo_reserve(user_bo, false);
if (!ret) {
qxl_bo_unpin(user_bo);
qxl_bo_unreserve(user_bo);
}
<API key>(obj);
qxl_bo_unref (&qcrtc->cursor_bo);
qcrtc->cursor_bo = cursor_bo;
return ret;
out_backoff:
<API key>(release);
out_free_bo:
qxl_bo_unref(&cursor_bo);
out_free_release:
qxl_release_free(qdev, release);
out_kunmap:
qxl_bo_kunmap(user_bo);
out_unpin:
qxl_bo_unpin(user_bo);
out_unref:
<API key>(obj);
return ret;
}
static int <API key>(struct drm_crtc *crtc,
int x, int y)
{
struct drm_device *dev = crtc->dev;
struct qxl_device *qdev = dev->dev_private;
struct qxl_crtc *qcrtc = to_qxl_crtc(crtc);
struct qxl_release *release;
struct qxl_cursor_cmd *cmd;
int ret;
ret = <API key>(qdev, sizeof(*cmd), <API key>,
&release, NULL);
if (ret)
return ret;
ret = <API key>(release, true);
if (ret) {
qxl_release_free(qdev, release);
return ret;
}
qcrtc->cur_x = x;
qcrtc->cur_y = y;
cmd = (struct qxl_cursor_cmd *)qxl_release_map(qdev, release);
cmd->type = QXL_CURSOR_MOVE;
cmd->u.position.x = qcrtc->cur_x + qcrtc->hot_spot_x;
cmd->u.position.y = qcrtc->cur_y + qcrtc->hot_spot_y;
qxl_release_unmap(qdev, release, &cmd->release_info);
<API key>(qdev, release, QXL_CMD_CURSOR, false);
<API key>(release);
return 0;
}
static const struct drm_crtc_funcs qxl_crtc_funcs = {
.cursor_set2 = <API key>,
.cursor_move = <API key>,
.set_config = <API key>,
.destroy = qxl_crtc_destroy,
.page_flip = qxl_crtc_page_flip,
};
void <API key>(struct drm_framebuffer *fb)
{
struct qxl_framebuffer *qxl_fb = to_qxl_framebuffer(fb);
<API key>(qxl_fb->obj);
<API key>(fb);
kfree(qxl_fb);
}
static int <API key>(struct drm_framebuffer *fb,
struct drm_file *file_priv,
unsigned flags, unsigned color,
struct drm_clip_rect *clips,
unsigned num_clips)
{
/* TODO: vmwgfx where this was cribbed from had locking. Why? */
struct qxl_framebuffer *qxl_fb = to_qxl_framebuffer(fb);
struct qxl_device *qdev = qxl_fb->base.dev->dev_private;
struct drm_clip_rect norect;
struct qxl_bo *qobj;
int inc = 1;
<API key>(fb->dev);
qobj = gem_to_qxl_bo(qxl_fb->obj);
/* if we aren't primary surface ignore this */
if (!qobj->is_primary) {
<API key>(fb->dev);
return 0;
}
if (!num_clips) {
num_clips = 1;
clips = &norect;
norect.x1 = norect.y1 = 0;
norect.x2 = fb->width;
norect.y2 = fb->height;
} else if (flags & <API key>) {
num_clips /= 2;
inc = 2; /* skip source rects */
}
qxl_draw_dirty_fb(qdev, qxl_fb, qobj, flags, color,
clips, num_clips, inc);
<API key>(fb->dev);
return 0;
}
static const struct <API key> qxl_fb_funcs = {
.destroy = <API key>,
.dirty = <API key>,
/* TODO?
* .create_handle = <API key>, */
};
int
<API key>(struct drm_device *dev,
struct qxl_framebuffer *qfb,
const struct drm_mode_fb_cmd2 *mode_cmd,
struct drm_gem_object *obj,
const struct <API key> *funcs)
{
int ret;
qfb->obj = obj;
ret = <API key>(dev, &qfb->base, funcs);
if (ret) {
qfb->obj = NULL;
return ret;
}
<API key>(&qfb->base, mode_cmd);
return 0;
}
static void qxl_crtc_dpms(struct drm_crtc *crtc, int mode)
{
}
static bool qxl_crtc_mode_fixup(struct drm_crtc *crtc,
const struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = crtc->dev;
struct qxl_device *qdev = dev->dev_private;
qxl_io_log(qdev, "%s: (%d,%d) => (%d,%d)\n",
__func__,
mode->hdisplay, mode->vdisplay,
adjusted_mode->hdisplay,
adjusted_mode->vdisplay);
return true;
}
void
<API key>(struct qxl_device *qdev)
{
int i;
BUG_ON(!qdev->ram_header->monitors_config);
if (qdev->monitors_config->count == 0) {
qxl_io_log(qdev, "%s: 0 monitors??\n", __func__);
return;
}
for (i = 0 ; i < qdev->monitors_config->count ; ++i) {
struct qxl_head *head = &qdev->monitors_config->heads[i];
if (head->y > 8192 || head->x > 8192 ||
head->width > 8192 || head->height > 8192) {
DRM_ERROR("head %d wrong: %dx%d+%d+%d\n",
i, head->width, head->height,
head->x, head->y);
return;
}
}
<API key>(qdev);
}
static void <API key>(struct qxl_device *qdev,
int index,
unsigned x, unsigned y,
unsigned width, unsigned height,
unsigned surf_id)
{
DRM_DEBUG_KMS("%d:%dx%d+%d+%d\n", index, width, height, x, y);
qdev->monitors_config->heads[index].x = x;
qdev->monitors_config->heads[index].y = y;
qdev->monitors_config->heads[index].width = width;
qdev->monitors_config->heads[index].height = height;
qdev->monitors_config->heads[index].surface_id = surf_id;
}
static int qxl_crtc_mode_set(struct drm_crtc *crtc,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode,
int x, int y,
struct drm_framebuffer *old_fb)
{
struct drm_device *dev = crtc->dev;
struct qxl_device *qdev = dev->dev_private;
struct qxl_framebuffer *qfb;
struct qxl_bo *bo, *old_bo = NULL;
struct qxl_crtc *qcrtc = to_qxl_crtc(crtc);
bool recreate_primary = false;
int ret;
int surf_id;
if (!crtc->primary->fb) {
DRM_DEBUG_KMS("No FB bound\n");
return 0;
}
if (old_fb) {
qfb = to_qxl_framebuffer(old_fb);
old_bo = gem_to_qxl_bo(qfb->obj);
}
qfb = to_qxl_framebuffer(crtc->primary->fb);
bo = gem_to_qxl_bo(qfb->obj);
DRM_DEBUG("+%d+%d (%d,%d) => (%d,%d)\n",
x, y,
mode->hdisplay, mode->vdisplay,
adjusted_mode->hdisplay,
adjusted_mode->vdisplay);
if (bo->is_primary == false)
recreate_primary = true;
if (bo->surf.stride * bo->surf.height > qdev->vram_size) {
DRM_ERROR("Mode doesn't fit in vram size (vgamem)");
return -EINVAL;
}
ret = qxl_bo_reserve(bo, false);
if (ret != 0)
return ret;
ret = qxl_bo_pin(bo, bo->type, NULL);
if (ret != 0) {
qxl_bo_unreserve(bo);
return -EINVAL;
}
qxl_bo_unreserve(bo);
if (recreate_primary) {
<API key>(qdev);
qxl_io_log(qdev,
"recreate primary: %dx%d,%d,%d\n",
bo->surf.width, bo->surf.height,
bo->surf.stride, bo->surf.format);
<API key>(qdev, 0, bo);
bo->is_primary = true;
ret = <API key>(crtc);
if (ret) {
DRM_ERROR("could not set cursor after modeset");
ret = 0;
}
}
if (bo->is_primary) {
DRM_DEBUG_KMS("setting surface_id to 0 for primary surface %d on crtc %d\n", bo->surface_id, qcrtc->index);
surf_id = 0;
} else {
surf_id = bo->surface_id;
}
if (old_bo && old_bo != bo) {
old_bo->is_primary = false;
ret = qxl_bo_reserve(old_bo, false);
qxl_bo_unpin(old_bo);
qxl_bo_unreserve(old_bo);
}
<API key>(qdev, qcrtc->index, x, y,
mode->hdisplay,
mode->vdisplay, surf_id);
return 0;
}
static void qxl_crtc_prepare(struct drm_crtc *crtc)
{
DRM_DEBUG("current: %dx%d+%d+%d (%d).\n",
crtc->mode.hdisplay, crtc->mode.vdisplay,
crtc->x, crtc->y, crtc->enabled);
}
static void qxl_crtc_commit(struct drm_crtc *crtc)
{
DRM_DEBUG("\n");
}
static void qxl_crtc_disable(struct drm_crtc *crtc)
{
struct qxl_crtc *qcrtc = to_qxl_crtc(crtc);
struct drm_device *dev = crtc->dev;
struct qxl_device *qdev = dev->dev_private;
if (crtc->primary->fb) {
struct qxl_framebuffer *qfb = to_qxl_framebuffer(crtc->primary->fb);
struct qxl_bo *bo = gem_to_qxl_bo(qfb->obj);
int ret;
ret = qxl_bo_reserve(bo, false);
qxl_bo_unpin(bo);
qxl_bo_unreserve(bo);
crtc->primary->fb = NULL;
}
<API key>(qdev, qcrtc->index, 0, 0, 0, 0, 0);
<API key>(qdev);
}
static const struct <API key> <API key> = {
.dpms = qxl_crtc_dpms,
.disable = qxl_crtc_disable,
.mode_fixup = qxl_crtc_mode_fixup,
.mode_set = qxl_crtc_mode_set,
.prepare = qxl_crtc_prepare,
.commit = qxl_crtc_commit,
};
static int qdev_crtc_init(struct drm_device *dev, int crtc_id)
{
struct qxl_crtc *qxl_crtc;
qxl_crtc = kzalloc(sizeof(struct qxl_crtc), GFP_KERNEL);
if (!qxl_crtc)
return -ENOMEM;
drm_crtc_init(dev, &qxl_crtc->base, &qxl_crtc_funcs);
qxl_crtc->index = crtc_id;
drm_crtc_helper_add(&qxl_crtc->base, &<API key>);
return 0;
}
static void qxl_enc_dpms(struct drm_encoder *encoder, int mode)
{
DRM_DEBUG("\n");
}
static void qxl_enc_prepare(struct drm_encoder *encoder)
{
DRM_DEBUG("\n");
}
static void <API key>(struct qxl_device *qdev,
struct drm_encoder *encoder)
{
int i;
struct qxl_output *output = <API key>(encoder);
struct qxl_head *head;
struct drm_display_mode *mode;
BUG_ON(!encoder);
/* TODO: ugly, do better */
i = output->index;
if (!qdev->monitors_config ||
qdev->monitors_config->max_allowed <= i) {
DRM_ERROR(
"head number too large or missing monitors config: %p, %d",
qdev->monitors_config,
qdev->monitors_config ?
qdev->monitors_config->max_allowed : -1);
return;
}
if (!encoder->crtc) {
DRM_ERROR("missing crtc on encoder %p\n", encoder);
return;
}
if (i != 0)
DRM_DEBUG("missing for multiple monitors: no head holes\n");
head = &qdev->monitors_config->heads[i];
head->id = i;
if (encoder->crtc->enabled) {
mode = &encoder->crtc->mode;
head->width = mode->hdisplay;
head->height = mode->vdisplay;
head->x = encoder->crtc->x;
head->y = encoder->crtc->y;
if (qdev->monitors_config->count < i + 1)
qdev->monitors_config->count = i + 1;
} else {
head->width = 0;
head->height = 0;
head->x = 0;
head->y = 0;
}
DRM_DEBUG_KMS("setting head %d to +%d+%d %dx%d out of %d\n",
i, head->x, head->y, head->width, head->height, qdev->monitors_config->count);
head->flags = 0;
/* TODO - somewhere else to call this for multiple monitors
* (config_commit?) */
<API key>(qdev);
}
static void qxl_enc_commit(struct drm_encoder *encoder)
{
struct qxl_device *qdev = encoder->dev->dev_private;
<API key>(qdev, encoder);
DRM_DEBUG("\n");
}
static void qxl_enc_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
DRM_DEBUG("\n");
}
static int qxl_conn_get_modes(struct drm_connector *connector)
{
int ret = 0;
struct qxl_device *qdev = connector->dev->dev_private;
unsigned pwidth = 1024;
unsigned pheight = 768;
DRM_DEBUG_KMS("monitors_config=%p\n", qdev->monitors_config);
/* TODO: what should we do here? only show the configured modes for the
* device, or allow the full list, or both? */
if (qdev->monitors_config && qdev->monitors_config->count) {
ret = <API key>(connector, &pwidth, &pheight);
if (ret < 0)
return ret;
}
ret += <API key>(connector, pwidth, pheight);
return ret;
}
static enum drm_mode_status qxl_conn_mode_valid(struct drm_connector *connector,
struct drm_display_mode *mode)
{
struct drm_device *ddev = connector->dev;
struct qxl_device *qdev = ddev->dev_private;
int i;
/* TODO: is this called for user defined modes? (xrandr --add-mode)
* TODO: check that the mode fits in the framebuffer */
if(qdev-><API key> == mode->hdisplay &&
qdev-><API key> == mode->vdisplay)
return MODE_OK;
for (i = 0; i < ARRAY_SIZE(common_modes); i++) {
if (common_modes[i].w == mode->hdisplay && common_modes[i].h == mode->vdisplay)
return MODE_OK;
}
return MODE_BAD;
}
static struct drm_encoder *qxl_best_encoder(struct drm_connector *connector)
{
struct qxl_output *qxl_output =
<API key>(connector);
DRM_DEBUG("\n");
return &qxl_output->enc;
}
static const struct <API key> <API key> = {
.dpms = qxl_enc_dpms,
.prepare = qxl_enc_prepare,
.mode_set = qxl_enc_mode_set,
.commit = qxl_enc_commit,
};
static const struct <API key> <API key> = {
.get_modes = qxl_conn_get_modes,
.mode_valid = qxl_conn_mode_valid,
.best_encoder = qxl_best_encoder,
};
static enum <API key> qxl_conn_detect(
struct drm_connector *connector,
bool force)
{
struct qxl_output *output =
<API key>(connector);
struct drm_device *ddev = connector->dev;
struct qxl_device *qdev = ddev->dev_private;
bool connected = false;
/* The first monitor is always connected */
if (!qdev-><API key>) {
if (output->index == 0)
connected = true;
} else
connected = qdev-><API key>->count > output->index &&
qxl_head_enabled(&qdev-><API key>->heads[output->index]);
DRM_DEBUG("#%d connected: %d\n", output->index, connected);
if (!connected)
<API key>(qdev, output->index, 0, 0, 0, 0, 0);
return connected ? <API key>
: <API key>;
}
static int <API key>(struct drm_connector *connector,
struct drm_property *property,
uint64_t value)
{
DRM_DEBUG("\n");
return 0;
}
static void qxl_conn_destroy(struct drm_connector *connector)
{
struct qxl_output *qxl_output =
<API key>(connector);
<API key>(connector);
<API key>(connector);
kfree(qxl_output);
}
static const struct drm_connector_funcs qxl_connector_funcs = {
.dpms = <API key>,
.detect = qxl_conn_detect,
.fill_modes = <API key>,
.set_property = <API key>,
.destroy = qxl_conn_destroy,
};
static void qxl_enc_destroy(struct drm_encoder *encoder)
{
drm_encoder_cleanup(encoder);
}
static const struct drm_encoder_funcs qxl_enc_funcs = {
.destroy = qxl_enc_destroy,
};
static int <API key>(struct qxl_device *qdev)
{
if (qdev-><API key>)
return 0;
qdev-><API key> =
<API key>(qdev->ddev, <API key>,
"hotplug_mode_update", 0, 1);
return 0;
}
static int qdev_output_init(struct drm_device *dev, int num_output)
{
struct qxl_device *qdev = dev->dev_private;
struct qxl_output *qxl_output;
struct drm_connector *connector;
struct drm_encoder *encoder;
qxl_output = kzalloc(sizeof(struct qxl_output), GFP_KERNEL);
if (!qxl_output)
return -ENOMEM;
qxl_output->index = num_output;
connector = &qxl_output->base;
encoder = &qxl_output->enc;
drm_connector_init(dev, &qxl_output->base,
&qxl_connector_funcs, <API key>);
drm_encoder_init(dev, &qxl_output->enc, &qxl_enc_funcs,
<API key>, NULL);
/* we get HPD via client monitors config */
connector->polled = <API key>;
encoder->possible_crtcs = 1 << num_output;
<API key>(&qxl_output->base,
&qxl_output->enc);
<API key>(encoder, &<API key>);
<API key>(connector, &<API key>);
<API key>(&connector->base,
qdev-><API key>, 0);
<API key>(&connector->base,
dev->mode_config.<API key>, 0);
<API key>(&connector->base,
dev->mode_config.<API key>, 0);
<API key>(connector);
return 0;
}
static struct drm_framebuffer *
<API key>(struct drm_device *dev,
struct drm_file *file_priv,
const struct drm_mode_fb_cmd2 *mode_cmd)
{
struct drm_gem_object *obj;
struct qxl_framebuffer *qxl_fb;
int ret;
obj = <API key>(file_priv, mode_cmd->handles[0]);
if (!obj)
return NULL;
qxl_fb = kzalloc(sizeof(*qxl_fb), GFP_KERNEL);
if (qxl_fb == NULL)
return NULL;
ret = <API key>(dev, qxl_fb, mode_cmd, obj, &qxl_fb_funcs);
if (ret) {
kfree(qxl_fb);
<API key>(obj);
return NULL;
}
return &qxl_fb->base;
}
static const struct <API key> qxl_mode_funcs = {
.fb_create = <API key>,
};
int <API key>(struct qxl_device *qdev)
{
int ret;
struct drm_gem_object *gobj;
int max_allowed = qxl_num_crtc;
int <API key> = sizeof(struct qxl_monitors_config) +
max_allowed * sizeof(struct qxl_head);
ret = <API key>(qdev, <API key>, 0,
QXL_GEM_DOMAIN_VRAM,
false, false, NULL, &gobj);
if (ret) {
DRM_ERROR("%s: failed to create gem ret=%d\n", __func__, ret);
return -ENOMEM;
}
qdev->monitors_config_bo = gem_to_qxl_bo(gobj);
ret = qxl_bo_reserve(qdev->monitors_config_bo, false);
if (ret)
return ret;
ret = qxl_bo_pin(qdev->monitors_config_bo, QXL_GEM_DOMAIN_VRAM, NULL);
if (ret) {
qxl_bo_unreserve(qdev->monitors_config_bo);
return ret;
}
qxl_bo_unreserve(qdev->monitors_config_bo);
qxl_bo_kmap(qdev->monitors_config_bo, NULL);
qdev->monitors_config = qdev->monitors_config_bo->kptr;
qdev->ram_header->monitors_config =
<API key>(qdev, qdev->monitors_config_bo, 0);
memset(qdev->monitors_config, 0, <API key>);
qdev->monitors_config->max_allowed = max_allowed;
return 0;
}
int <API key>(struct qxl_device *qdev)
{
int ret;
qdev->monitors_config = NULL;
qdev->ram_header->monitors_config = 0;
qxl_bo_kunmap(qdev->monitors_config_bo);
ret = qxl_bo_reserve(qdev->monitors_config_bo, false);
if (ret)
return ret;
qxl_bo_unpin(qdev->monitors_config_bo);
qxl_bo_unreserve(qdev->monitors_config_bo);
qxl_bo_unref(&qdev->monitors_config_bo);
return 0;
}
int qxl_modeset_init(struct qxl_device *qdev)
{
int i;
int ret;
<API key>(qdev->ddev);
ret = <API key>(qdev);
if (ret)
return ret;
qdev->ddev->mode_config.funcs = (void *)&qxl_mode_funcs;
/* modes will be validated against the framebuffer size */
qdev->ddev->mode_config.min_width = 320;
qdev->ddev->mode_config.min_height = 200;
qdev->ddev->mode_config.max_width = 8192;
qdev->ddev->mode_config.max_height = 8192;
qdev->ddev->mode_config.fb_base = qdev->vram_base;
<API key>(qdev->ddev);
<API key>(qdev);
for (i = 0 ; i < qxl_num_crtc; ++i) {
qdev_crtc_init(qdev->ddev, i);
qdev_output_init(qdev->ddev, i);
}
qdev->mode_info.<API key> = true;
qxl_fbdev_init(qdev);
return 0;
}
void qxl_modeset_fini(struct qxl_device *qdev)
{
qxl_fbdev_fini(qdev);
<API key>(qdev);
if (qdev->mode_info.<API key>) {
<API key>(qdev->ddev);
qdev->mode_info.<API key> = false;
}
} |
#ifndef HireUnitH
#define HireUnitH
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include "SHDocVw_OCX.h"
#include <ExtCtrls.hpp>
#include <Graphics.hpp>
#include <OleCtrls.hpp>
class THireForm : public TForm
{
__published: // IDE-managed Components
TCppWebBrowser *CommentsBrowser;
TImage *CodeImage;
TButton *OKButton;
void __fastcall FormShow(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall THireForm(TComponent* Owner);
};
extern PACKAGE THireForm *HireForm;
#endif |
#include "variantsanitizer.h"
#include "Utils.h"
#include "checkmanager.h"
using namespace std;
using namespace clang;
VariantSanitizer::VariantSanitizer(const std::string &name)
: CheckBase(name)
{
}
static bool isMatchingClass(const std::string &name)
{
static const vector<string> classes = {"QBitArray", "QByteArray", "QChar", "QDate", "QDateTime",
"QEasingCurve", "QJsonArray", "QJsonDocument", "QJsonObject",
"QJsonValue", "QLocale", "QModelIndex", "QPoint", "QPointF",
"QRect", "QRectF", "QRegExp", "QString", "QRegularExpression",
"QSize", "QSizeF", "QStringList", "QTime", "QUrl", "QUuid" };
return find(classes.cbegin(), classes.cend(), name) != classes.cend();
}
void VariantSanitizer::VisitStmt(clang::Stmt *stm)
{
auto callExpr = dyn_cast<CXXMemberCallExpr>(stm);
if (callExpr == nullptr)
return;
CXXMethodDecl *methodDecl = callExpr->getMethodDecl();
if (methodDecl == nullptr || methodDecl->getNameAsString() != "value")
return;
CXXRecordDecl *decl = methodDecl->getParent();
if (decl == nullptr || decl->getNameAsString() != "QVariant")
return;
<API key> *specializationInfo = methodDecl-><API key>();
if (specializationInfo == nullptr || specializationInfo->TemplateArguments == nullptr || specializationInfo->TemplateArguments->size() != 1)
return;
const TemplateArgument &argument = specializationInfo->TemplateArguments->get(0);
QualType qt = argument.getAsType();
const Type *t = qt.getTypePtrOrNull();
if (t == nullptr)
return;
bool matches = false;
if (t->isBooleanType() /*|| t->isIntegerType() || t->isFloatingType()*/) {
matches = true;
} else {
CXXRecordDecl *recordDecl = t->getAsCXXRecordDecl();
matches = t->isClassType() && recordDecl && isMatchingClass(recordDecl->getNameAsString());
}
if (matches) {
std::string error = std::string("Use QVariant::toFoo() instead of QVariant::value<Foo>()");
emitWarning(stm->getLocStart(), error.c_str());
}
}
REGISTER_CHECK("variant-sanitizer", VariantSanitizer) |
#include "logic/<API key>.h"
#include <cstdlib>
#include "ai/computer_player.h"
#include "base/i18n.h"
#include "base/random.h"
#include "base/wexception.h"
#include "graphic/playercolor.h"
#include "logic/map_objects/tribes/tribe_basic_info.h"
<API key>::<API key>() {
s.tribes = Widelands::get_all_tribeinfos(nullptr);
s.scenario = false;
s.multiplayer = false;
s.playernum = 0;
}
void <API key>::set_scenario(bool const set) {
s.scenario = set;
}
const GameSettings& <API key>::settings() {
return s;
}
bool <API key>::can_change_map() {
return true;
}
bool <API key>::<API key>(uint8_t number) {
return ((!s.scenario) && (number != s.playernum));
}
bool <API key>::<API key>(uint8_t /*number*/) {
return !s.scenario;
}
bool <API key>::<API key>(uint8_t /*number*/) {
return !s.scenario;
}
bool <API key>::<API key>(uint8_t /*number*/) {
return !s.scenario;
}
bool <API key>::can_launch() {
return !s.mapname.empty() && !s.players.empty();
}
std::string <API key>::get_map() {
return s.mapfilename;
}
bool <API key>::is_peaceful_mode() {
return s.peaceful;
}
void <API key>::set_peaceful_mode(bool peace) {
s.peaceful = peace;
}
bool <API key>::<API key>() {
return s.<API key>;
}
void <API key>::<API key>(bool c) {
s.<API key> = c;
}
void <API key>::set_map(const std::string& mapname,
const std::string& mapfilename,
const std::string& map_theme,
const std::string& map_bg,
uint32_t const maxplayers,
bool const savegame) {
s.mapname = mapname;
s.mapfilename = mapfilename;
s.savegame = savegame;
s.map_background = map_bg;
s.map_theme = map_theme;
s.players.resize(maxplayers);
set_player_number(0);
for (uint32_t player_nr = 0; player_nr < maxplayers; ++player_nr) {
PlayerSettings& player = s.players[player_nr];
player.state =
(player_nr == 0) ? PlayerSettings::State::kHuman : PlayerSettings::State::kComputer;
player.tribe = s.tribes.at(0).name;
player.random_tribe = false;
player.<API key> = 0;
player.name = format(_("Player %u"), (player_nr + 1));
player.team = 0;
player.color = kPlayerColors[player_nr];
// Set default computerplayer ai type
if (player.state == PlayerSettings::State::kComputer) {
const AI::ComputerPlayer::<API key>& impls =
AI::ComputerPlayer::get_implementations();
if (impls.size() > 1) {
player.ai = impls.at(0)->name;
player.random_ai = false;
}
// If AI player then set tribe to random
if (!s.scenario) {
set_player_tribe(player_nr, "", true);
}
}
}
}
void <API key>::set_player_state(uint8_t const number,
PlayerSettings::State state) {
if (number == s.playernum || number >= s.players.size()) {
return;
}
if (state == PlayerSettings::State::kOpen) {
state = PlayerSettings::State::kComputer;
}
s.players[number].state = state;
}
void <API key>::set_player_ai(uint8_t const number,
const std::string& ai,
bool const random_ai) {
if (number < s.players.size()) {
s.players[number].ai = ai;
s.players[number].random_ai = random_ai;
}
}
void <API key>::next_player_state(uint8_t const number) {
if (number == s.playernum || number >= s.players.size()) {
return;
}
const AI::ComputerPlayer::<API key>& impls =
AI::ComputerPlayer::get_implementations();
if (impls.size() > 1) {
AI::ComputerPlayer::<API key>::const_iterator it = impls.begin();
do {
++it;
if ((*(it - 1))->name == s.players[number].ai) {
break;
}
} while (it != impls.end());
if (s.players[number].random_ai) {
s.players[number].random_ai = false;
it = impls.begin();
} else if (it == impls.end()) {
s.players[number].random_ai = true;
do {
// Choose a random AI
uint8_t random = RNG::static_rand(impls.size());
it = impls.begin() + random;
} while ((*it)->type == AI::ComputerPlayer::Implementation::Type::kEmpty);
}
s.players[number].ai = (*it)->name;
}
s.players[number].state = PlayerSettings::State::kComputer;
}
void <API key>::set_player_tribe(uint8_t const number,
const std::string& tribe,
bool random_tribe) {
if (number >= s.players.size()) {
return;
}
std::string actual_tribe = tribe;
PlayerSettings& player = s.players[number];
player.random_tribe = random_tribe;
while (random_tribe) {
uint8_t num_tribes = s.tribes.size();
uint8_t random = RNG::static_rand(num_tribes);
actual_tribe = s.tribes.at(random).name;
if (player.state != PlayerSettings::State::kComputer ||
s.get_tribeinfo(actual_tribe).suited_for_ai) {
break;
}
}
for (const Widelands::TribeBasicInfo& tmp_tribe : s.tribes) {
if (tmp_tribe.name == player.tribe) {
s.players[number].tribe = actual_tribe;
if (tmp_tribe.initializations.size() <= player.<API key>) {
player.<API key> = 0;
}
}
}
}
void <API key>::set_player_init(uint8_t const number, uint8_t const index) {
if (number >= s.players.size()) {
return;
}
for (const Widelands::TribeBasicInfo& tmp_tribe : s.tribes) {
if (tmp_tribe.name == s.players[number].tribe) {
if (index < tmp_tribe.initializations.size()) {
s.players[number].<API key> = index;
}
return;
}
}
NEVER_HERE();
}
void <API key>::set_player_team(uint8_t number, Widelands::TeamNumber team) {
if (number < s.players.size()) {
s.players[number].team = team;
}
}
void <API key>::set_player_color(const uint8_t number, const RGBColor& c) {
if (number < s.players.size()) {
s.players[number].color = c;
}
}
void <API key>::<API key>(uint8_t /*number*/,
bool /*closeable*/) {
// nothing to do
}
void <API key>::set_player_shared(PlayerSlot /*number*/,
Widelands::PlayerNumber /*shared*/) {
// nothing to do
}
void <API key>::set_player_name(uint8_t const number,
const std::string& name) {
if (number < s.players.size()) {
s.players[number].name = name;
}
}
void <API key>::set_player(uint8_t const number, const PlayerSettings& ps) {
if (number < s.players.size()) {
s.players[number] = ps;
}
}
void <API key>::set_player_number(uint8_t const number) {
if (number >= s.players.size()) {
return;
}
PlayerSettings const position = settings().players.at(number);
// Ensure that old player number isn't out of range when we switch to a map with less players
PlayerSettings const player = settings().players.at(
settings().playernum < static_cast<int>(settings().players.size()) ? settings().playernum :
0);
if (number < settings().players.size() && (position.state == PlayerSettings::State::kOpen ||
position.state == PlayerSettings::State::kClosed ||
position.state == PlayerSettings::State::kComputer)) {
// swap player but keep player name
set_player(number, player);
set_player_name(number, position.name);
set_player(settings().playernum, position);
set_player_name(settings().playernum, player.name);
s.playernum = number;
}
}
std::string <API key>::<API key>() {
return s.<API key>;
}
void <API key>::<API key>(const std::string& wc) {
s.<API key> = wc;
} |
#class PageSweeper < ActionController::Caching::Sweeper
# observe CmpPage # This sweeper is going to keep an eye on the CmpPage model
# # If our sweeper detects that a CmpPage was created call this
# def after_create(page)
# expire_cache_for(page)
# end
# # If our sweeper detects that a CmpPage was updated call this
# def after_update(page)
# expire_cache_for(page)
# end
# # If our sweeper detects that a CmpPage was deleted call this
# def after_destroy(page)
# expire_cache_for(page)
# end
# private
# def expire_cache_for(page)
# # Expire the index page now that we added a new product
# expire_page(:controller => 'system/srticles', :action => 'afficher')
# expire_page(:controller => 'system/srticles', :action => '<API key>')
# # Expire a fragment
# expire_fragment('all_available_pages')
# end
#end |
// <API key>.h
// Adium
/*!
* @category NSAppleScript(<API key>)
* @brief Provides methods for executing functions in an NSAppleScript
*
* These methods allow functions to be executed within an NSApplescript and arguments to be passed to those functions
*/
@interface NSAppleScript (<API key>)
/*!
* @brief Execute a function
*
* Executes a function <b>functionName</b> within the <tt>NSAppleScript</tt>, returning error information if necessary
* @param functionName An <tt>NSString</tt> of the function to be called. It is case sensitive.
* @param errorInfo A reference to an <tt>NSDictionary</tt> variable, which will be filled with error information if needed. It may be nil if error information is not requested.
* @return An <tt><API key></tt> generated by executing the function.
*/
- (<API key> *)executeFunction:(NSString *)functionName error:(NSDictionary **)errorInfo;
/*!
* @brief Execute a function with arguments
*
* Executes a function <b>functionName</b> within the <tt>NSAppleScript</tt>, returning error information if necessary. Arguments in <b>argumentArray</b> are passed to the function.
* @param functionName An <tt>NSString</tt> of the function to be called. It is case sensitive.
* @param argumentArray An <tt>NSArray</tt> of <tt>NSString</tt>s to be passed to the function when it is called.
* @param errorInfo A reference to an <tt>NSDictionary</tt> variable, which will be filled with error information if needed. It may be nil if error information is not requested.
* @return An <tt><API key></tt> generated by executing the function.
*/
- (<API key> *)executeFunction:(NSString *)functionName withArguments:(NSArray *)argumentArray error:(NSDictionary **)errorInfo;
@end |
<?php
class <API key> {
public $is_mm_active = false;
private $version = '1.0.0';
/**
* Class constructor used to run actions.
*/
public function __construct() {
add_action( 'init', array( $this, 'init' ) );
//<API key>( __FILE__, array( $this, 'activate' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'add_scripts' ) );
}
/**
* Plugin initializer.
*
* @uses init()
*/
public function init() {
add_filter( 'query_vars', array( $this, 'add_query_vars' ) );
wp_register_script( '<API key>', plugins_url( 'mm-shipping-options.js', __FILE__ ), array( 'jquery' ), $this->version, true );
}
protected function activate() {
if ( false == is_plugin_active( 'membermouse/index.php' ) ) {
$this->is_mm_active = false;
add_action( 'admin_notices', array( $this, 'admin_notice' ) );
}
}
/**
* Add our JavaScript files to the front end.
*/
public function add_scripts() {
// Only add our JS if the mm-fso query exists
if ( $this-><API key>() ) {
wp_enqueue_script( '<API key>' );
}
}
/**
* Add our custom vars to the query_vars filter.
*
* @param $vars Added by the filter.
*
* @return array
*/
public function add_query_vars( $vars ) {
$vars[] = 'mm-fso';
return $vars;
}
/**
* Checks the query string for our custom parameter and gives it to us.
*
* @return bool|string False if query string parameter isn't there; shipping options if it is.
*/
public function <API key>() {
global $wp_query;
if ( isset( $wp_query->query_vars['mm-fso'] ) ) {
return $shipping = urldecode( $wp_query->query_vars['mm-fso'] );
}
return false;
}
/**
* Show a warning notice if this plugin is activated without MemberMouse Platform.
*/
public function admin_notice() {
?>
<div class="error">
<p><?php _e( 'MemberMouse Platform plugin must be installed and activated before you can use Custom Shipping Options for MemberMouse.', 'mm-shipping-options' ); ?></p>
</div>
<?php
}
}
$mm_cso = new <API key>(); |
# -*- python-mode -*-
# -*- coding: UTF-8 -*-
## This program is free software; you can redistribute it and/or modify
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import absolute_import, division, print_function, unicode_literals
from logging import getLogger, DEBUG as _DEBUG
_log = getLogger(__name__)
del getLogger
from copy import copy as _copy
import math
from .common import (
NamedInt as _NamedInt,
NamedInts as _NamedInts,
bytes2int as _bytes2int,
int2bytes as _int2bytes,
)
KIND = _NamedInts(toggle=0x01, choice=0x02, range=0x04)
class Setting(object):
"""A setting descriptor.
Needs to be instantiated for each specific device."""
__slots__ = ('name', 'label', 'description', 'kind', 'persister', 'device_kind',
'_rw', '_validator', '_device', '_value')
def __init__(self, name, rw, validator, kind=None, label=None, description=None, device_kind=None):
assert name
self.name = name
self.label = label or name
self.description = description
self.device_kind = device_kind
self._rw = rw
self._validator = validator
assert kind is None or kind & validator.kind != 0
self.kind = kind or validator.kind
self.persister = None
def __call__(self, device):
assert not hasattr(self, '_value')
assert self.device_kind is None or device.kind in self.device_kind
p = device.protocol
if p == 1.0:
# HID++ 1.0 devices do not support features
assert self._rw.kind == RegisterRW.kind
elif p >= 2.0:
# HID++ 2.0 devices do not support registers
assert self._rw.kind == FeatureRW.kind
o = _copy(self)
o._value = None
o._device = device
return o
@property
def choices(self):
assert hasattr(self, '_value')
assert hasattr(self, '_device')
return self._validator.choices if self._validator.kind & KIND.choice else None
@property
def range(self):
assert hasattr(self, '_value')
assert hasattr(self, '_device')
if self._validator.kind == KIND.range:
return (self._validator.min_value, self._validator.max_value)
def read(self, cached=True):
assert hasattr(self, '_value')
assert hasattr(self, '_device')
if self._value is None and self.persister:
# We haven't read a value from the device yet,
# maybe we have something in the configuration.
self._value = self.persister.get(self.name)
if cached and self._value is not None:
if self.persister and self.name not in self.persister:
# If this is a new device (or a new setting for an old device),
# make sure to save its current value for the next time.
self.persister[self.name] = self._value
return self._value
if self._device.online:
reply = self._rw.read(self._device)
if reply:
self._value = self._validator.validate_read(reply)
if self.persister and self.name not in self.persister:
# Don't update the persister if it already has a value,
# otherwise the first read might overwrite the value we wanted.
self.persister[self.name] = self._value
return self._value
def write(self, value):
assert hasattr(self, '_value')
assert hasattr(self, '_device')
assert value is not None
if _log.isEnabledFor(_DEBUG):
_log.debug("%s: write %r to %s", self.name, value, self._device)
if self._device.online:
# Remember the value we're trying to set, even if the write fails.
# This way even if the device is offline or some other error occurs,
# the last value we've tried to write is remembered in the configuration.
self._value = value
if self.persister:
self.persister[self.name] = value
current_value = None
if self._validator.needs_current_value:
# the validator needs the current value, possibly to merge flag values
current_value = self._rw.read(self._device)
data_bytes = self._validator.prepare_write(value, current_value)
if data_bytes is not None:
if _log.isEnabledFor(_DEBUG):
_log.debug("%s: prepare write(%s) => %r", self.name, value, data_bytes)
reply = self._rw.write(self._device, data_bytes)
if not reply:
# tell whomever is calling that the write failed
return None
return value
def apply(self):
assert hasattr(self, '_value')
assert hasattr(self, '_device')
if _log.isEnabledFor(_DEBUG):
_log.debug("%s: apply %s (%s)", self.name, self._value, self._device)
value = self.read()
if value is not None:
self.write(value)
def __str__(self):
if hasattr(self, '_value'):
assert hasattr(self, '_device')
return '<Setting([%s:%s] %s:%s=%s)>' % (self._rw.kind, self._validator.kind, self._device.codename, self.name, self._value)
return '<Setting([%s:%s] %s)>' % (self._rw.kind, self._validator.kind, self.name)
__unicode__ = __repr__ = __str__
# read/write low-level operators
class RegisterRW(object):
__slots__ = ('register', )
kind = _NamedInt(0x01, 'register')
def __init__(self, register):
assert isinstance(register, int)
self.register = register
def read(self, device):
return device.read_register(self.register)
def write(self, device, data_bytes):
return device.write_register(self.register, data_bytes)
class FeatureRW(object):
__slots__ = ('feature', 'read_fnid', 'write_fnid')
kind = _NamedInt(0x02, 'feature')
default_read_fnid = 0x00
default_write_fnid = 0x10
def __init__(self, feature, read_fnid=default_read_fnid, write_fnid=default_write_fnid):
assert isinstance(feature, _NamedInt)
self.feature = feature
self.read_fnid = read_fnid
self.write_fnid = write_fnid
def read(self, device):
assert self.feature is not None
return device.feature_request(self.feature, self.read_fnid)
def write(self, device, data_bytes):
assert self.feature is not None
return device.feature_request(self.feature, self.write_fnid, data_bytes)
# value validators
# handle the conversion from read bytes, to setting value, and back
class BooleanValidator(object):
__slots__ = ('true_value', 'false_value', 'mask', 'needs_current_value')
kind = KIND.toggle
default_true = 0x01
default_false = 0x00
# mask specifies all the affected bits in the value
default_mask = 0xFF
def __init__(self, true_value=default_true, false_value=default_false, mask=default_mask):
if isinstance(true_value, int):
assert isinstance(false_value, int)
if mask is None:
mask = self.default_mask
else:
assert isinstance(mask, int)
assert true_value & false_value == 0
assert true_value & mask == true_value
assert false_value & mask == false_value
self.needs_current_value = (mask != self.default_mask)
elif isinstance(true_value, bytes):
if false_value is None or false_value == self.default_false:
false_value = b'\x00' * len(true_value)
else:
assert isinstance(false_value, bytes)
if mask is None or mask == self.default_mask:
mask = b'\xFF' * len(true_value)
else:
assert isinstance(mask, bytes)
assert len(mask) == len(true_value) == len(false_value)
tv = _bytes2int(true_value)
fv = _bytes2int(false_value)
mv = _bytes2int(mask)
assert tv & fv == 0
assert tv & mv == tv
assert fv & mv == fv
self.needs_current_value = any(m != b'\xFF' for m in mask)
else:
raise Exception("invalid mask '%r', type %s" % (mask, type(mask)))
self.true_value = true_value
self.false_value = false_value
self.mask = mask
def validate_read(self, reply_bytes):
if isinstance(self.mask, int):
reply_value = ord(reply_bytes[:1]) & self.mask
if _log.isEnabledFor(_DEBUG):
_log.debug("BooleanValidator: validate read %r => %02X", reply_bytes, reply_value)
if reply_value == self.true_value:
return True
if reply_value == self.false_value:
return False
_log.warn("BooleanValidator: reply %02X mismatched %02X/%02X/%02X",
reply_value, self.true_value, self.false_value, self.mask)
return False
count = len(self.mask)
mask = _bytes2int(self.mask)
reply_value = _bytes2int(reply_bytes[:count]) & mask
true_value = _bytes2int(self.true_value)
if reply_value == true_value:
return True
false_value = _bytes2int(self.false_value)
if reply_value == false_value:
return False
_log.warn("BooleanValidator: reply %r mismatched %r/%r/%r",
reply_bytes, self.true_value, self.false_value, self.mask)
return False
def prepare_write(self, new_value, current_value=None):
if new_value is None:
new_value = False
else:
assert isinstance(new_value, bool)
to_write = self.true_value if new_value else self.false_value
if isinstance(self.mask, int):
if current_value is not None and self.needs_current_value:
to_write |= ord(current_value[:1]) & (0xFF ^ self.mask)
if current_value is not None and to_write == ord(current_value[:1]):
return None
else:
to_write = bytearray(to_write)
count = len(self.mask)
for i in range(0, count):
b = ord(to_write[i:i+1])
m = ord(self.mask[i : i + 1])
assert b & m == b
# b &= m
if current_value is not None and self.needs_current_value:
b |= ord(current_value[i : i + 1]) & (0xFF ^ m)
to_write[i] = b
to_write = bytes(to_write)
if current_value is not None and to_write == current_value[:len(to_write)]:
return None
if _log.isEnabledFor(_DEBUG):
_log.debug("BooleanValidator: prepare_write(%s, %s) => %r", new_value, current_value, to_write)
return to_write
class ChoicesValidator(object):
__slots__ = ('choices', 'flag', '_bytes_count', 'needs_current_value')
kind = KIND.choice
"""Translates between NamedInts and a byte sequence.
:param choices: a list of NamedInts
:param bytes_count: the size of the derived byte sequence. If None, it
will be calculated from the choices."""
def __init__(self, choices, bytes_count=None):
assert choices is not None
assert isinstance(choices, _NamedInts)
assert len(choices) > 2
self.choices = choices
self.needs_current_value = False
max_bits = max(x.bit_length() for x in choices)
self._bytes_count = (max_bits // 8) + (1 if max_bits % 8 else 0)
if bytes_count:
assert self._bytes_count <= bytes_count
self._bytes_count = bytes_count
assert self._bytes_count < 8
def validate_read(self, reply_bytes):
reply_value = _bytes2int(reply_bytes[:self._bytes_count])
valid_value = self.choices[reply_value]
assert valid_value is not None, "%s: failed to validate read value %02X" % (self.__class__.__name__, reply_value)
return valid_value
def prepare_write(self, new_value, current_value=None):
if new_value is None:
choice = self.choices[:][0]
else:
if isinstance(new_value, int):
choice = self.choices[new_value]
elif new_value in self.choices:
choice = self.choices[new_value]
else:
raise ValueError(new_value)
if choice is None:
raise ValueError("invalid choice %r" % new_value)
assert isinstance(choice, _NamedInt)
return choice.bytes(self._bytes_count)
class RangeValidator(object):
__slots__ = ('min_value', 'max_value', 'flag', '_bytes_count', 'needs_current_value')
kind = KIND.range
"""Translates between integers and a byte sequence.
:param min_value: minimum accepted value (inclusive)
:param max_value: maximum accepted value (inclusive)
:param bytes_count: the size of the derived byte sequence. If None, it
will be calculated from the range."""
def __init__(self, min_value, max_value, bytes_count=None):
assert max_value > min_value
self.min_value = min_value
self.max_value = max_value
self.needs_current_value = False
self._bytes_count = math.ceil(math.log(max_value + 1, 256))
if bytes_count:
assert self._bytes_count <= bytes_count
self._bytes_count = bytes_count
assert self._bytes_count < 8
def validate_read(self, reply_bytes):
reply_value = _bytes2int(reply_bytes[:self._bytes_count])
assert reply_value >= self.min_value, "%s: failed to validate read value %02X" % (self.__class__.__name__, reply_value)
assert reply_value <= self.max_value, "%s: failed to validate read value %02X" % (self.__class__.__name__, reply_value)
return reply_value
def prepare_write(self, new_value, current_value=None):
if new_value < self.min_value or new_value > self.max_value:
raise ValueError("invalid choice %r" % new_value)
return _int2bytes(new_value, self._bytes_count) |
/**
* The CSS in here controls the appearance of the media manager
*/
#media__manager {
height: 100%;
overflow: hidden;
}
#media__left {
width: 30%;
border-right: solid 1px __border__;
height: 100%;
overflow: auto;
position: absolute;
left: 0;
}
#media__right {
width: 69.7%;
height: 100%;
overflow: auto;
position: absolute;
right: 0;
}
#media__manager h1 {
margin: 0;
padding: 0;
margin-bottom: 0.5em;
}
#media__tree img {
float: left;
padding: 0.5em 0.3em 0 0;
}
#media__tree ul {
list-style-type: none;
list-style-image: none;
margin-left: 1.5em;
}
#media__tree li {
clear: left;
list-style-type: none;
list-style-image: none;
}
*+html #media__tree li,
* html #media__tree li {
border: 1px solid __background__;
}/* I don't understand this, but this fixes a style bug in IE;
it's dirty, so any "real" fixes are welcome */
#media__opts {
padding-left: 1em;
margin-bottom: 0.5em;
}
#media__opts input {
float: left;
display: block;
margin-top: 4px;
position: absolute;
}
*+html #media__opts input,
* html #media__opts input {
position: static;
}
#media__opts label {
display: block;
float: left;
margin-left: 20px;
margin-bottom: 4px;
}
*+html #media__opts label,
* html #media__opts label {
margin-left: 10px;
}
#media__opts br {
clear: left;
}
#media__content img.load {
margin: 1em auto;
}
#media__content #scroll__here {
border: 1px dashed __border__;
}
#media__content .odd {
background-color: <API key>;
padding: 0.4em;
}
#media__content .even {
padding: 0.4em;
}
#media__content a.mediafile {
margin-right: 1.5em;
font-weight: bold;
}
#media__content div.detail {
padding: 0.3em 0 0.3em 2em;
}
#media__content div.detail div.thumb {
float: left;
width: 130px;
text-align: center;
margin-right: 0.4em;
}
#media__content img.btn {
vertical-align: text-bottom;
}
#media__content div.example {
color: __text_neu__;
margin-left: 1em;
}
#media__content div.upload {
font-size: 90%;
padding: 0 0.5em 0.5em 0.5em;
}
#media__content form#dw__upload,
#media__content div#dw__flashupload {
display: block;
border-bottom: solid 1px __border__;
padding: 0 0.5em 1em 0.5em;
}
#media__content form#dw__upload fieldset {
padding: 0;
margin: 0;
border: none;
width: auto;
}
#media__content form#dw__upload p {
text-align: left;
padding: 0.25em 0;
margin: 0;
line-height: 1.0em;
}
#media__content form#dw__upload label.check {
float: none;
width: auto;
margin-left: 11.5em;
}
#media__content form.meta {
display: block;
padding: 0 0 1em 0;
}
#media__content form.meta label {
display: block;
width: 25%;
float: left;
font-weight: bold;
margin-left: 1em;
clear: left;
}
#media__content form.meta .edit {
font: 100% "Lucida Grande", Verdana, Lucida, Helvetica, Arial, sans-serif;
float: left;
width: 70%;
padding-right: 0;
padding-left: 0.2em;
margin: 2px;
}
#media__content form.meta textarea.edit {
height: 8em;
}
#media__content form.meta div.metafield {
clear: left;
}
#media__content form.meta div.buttons {
clear: left;
margin-left: 20%;
padding-left: 1em;
} |
/* from /lib/modules/2.6.27.5-117.fc10.i686/build/include/linux/cn_proc.h */
#ifndef CN_PROC_H
#if defined(__cplusplus) && !CLICK_CXX_PROTECTED
# error "missing #include <click/cxxprotect.h>"
#endif
#define CN_PROC_H
#include <linux/types.h>
/*
* Userspace sends this enum to register with the kernel that it is listening
* for events on the connector.
*/
enum proc_cn_mcast_op {
<API key> = 1,
<API key> = 2
};
/*
* From the user's point of view, the process
* ID is the thread group ID and thread ID is the internal
* kernel "pid". So, fields are assigned as follow:
*
* In user space - In kernel space
*
* parent process ID = parent->tgid
* parent thread ID = parent->pid
* child process ID = child->tgid
* child thread ID = child->pid
*/
struct proc_event {
enum what {
/* Use successive bits so the enums can be used to record
* sets of events as well
*/
PROC_EVENT_NONE = 0x00000000,
PROC_EVENT_FORK = 0x00000001,
PROC_EVENT_EXEC = 0x00000002,
PROC_EVENT_UID = 0x00000004,
PROC_EVENT_GID = 0x00000040,
/* "next" should be 0x00000400 */
/* "last" is the last process event: exit */
PROC_EVENT_EXIT = 0x80000000
} what;
__u32 cpu;
__u64 __attribute__((aligned(8))) timestamp_ns;
/* Number of nano seconds since system boot */
union { /* must be last field of proc_event struct */
struct {
__u32 err;
} ack;
struct fork_proc_event {
pid_t parent_pid;
pid_t parent_tgid;
pid_t child_pid;
pid_t child_tgid;
} fork;
struct exec_proc_event {
pid_t process_pid;
pid_t process_tgid;
} exec;
struct id_proc_event {
pid_t process_pid;
pid_t process_tgid;
union {
__u32 ruid; /* task uid */
__u32 rgid; /* task gid */
} r;
union {
__u32 euid;
__u32 egid;
} e;
} id;
struct exit_proc_event {
pid_t process_pid;
pid_t process_tgid;
__u32 exit_code, exit_signal;
} exit;
} event_data;
};
#ifdef __KERNEL__
#ifdef CONFIG_PROC_EVENTS
void proc_fork_connector(struct task_struct *task);
void proc_exec_connector(struct task_struct *task);
void proc_id_connector(struct task_struct *task, int which_id);
void proc_exit_connector(struct task_struct *task);
#else
static inline void proc_fork_connector(struct task_struct *task)
{}
static inline void proc_exec_connector(struct task_struct *task)
{}
static inline void proc_id_connector(struct task_struct *task,
int which_id)
{}
static inline void proc_exit_connector(struct task_struct *task)
{}
#endif /* CONFIG_PROC_EVENTS */
#endif /* __KERNEL__ */
#endif /* CN_PROC_H */ |
<h3 class="<API key>" id="artist-<?php echo $showdata['artist_id']; ?>"><?php echo $showdata['artist']; ?>
<?php if($gpo['<API key>'] == 1) : ?>
<span class="<API key>">
<a href="<?php echo GIGPRESS_RSS; ?>&artist=<?php echo $showdata['artist_id']; ?>" title="<?php echo $showdata['artist']; ?> RSS"><img src="<?php echo WP_PLUGIN_URL; ?>/gigpress/images/feed-icon-12x12.png" alt="" /></a>
<a href="<?php echo GIGPRESS_WEBCAL . '&artist=' . $showdata['artist_id']; ?>" title="<?php echo $showdata['artist']; ?> iCalendar"><img src="<?php echo WP_PLUGIN_URL; ?>/gigpress/images/icalendar-icon.gif" alt="" /></a></span>
<?php endif; ?>
</h3> |
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace Tsc.WebApi
{
public class Program
{
public static void Main(string[] args)
{
var config = new <API key>()
.AddCommandLine(args)
.<API key>(prefix: "ASPNETCORE_")
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Database.DatabaseModels;
using Database.Repositories.Declarations;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Models.Users;
using Models.Users.Authorization;
using Models.Utilities;
namespace Database.Repositories
{
public class UserRepository : IUserRepository
{
private readonly MoviepickerContext _context;
private readonly UserManager<ApplicationUser> _userManager;
public UserRepository(MoviepickerContext context)
{
_context = context;
_userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
}
public async Task<IdentityResult> RegisterUserAsync(UserModel userModel)
{
var user = new ApplicationUser(userModel.Username);
return await _userManager.CreateAsync(user, userModel.Password);
}
public async Task<ApplicationUser> FindUserAsync(string username, string password)
{
return await _userManager.FindAsync(username, password);
}
public async Task<ClientApplication> FindClientAsync(string clientId)
{
return await _context.ClientApplications.FindAsync(clientId);
}
public async Task<bool> <API key>(RefreshToken refreshToken)
{
var existingToken = _context.RefreshTokens.SingleOrDefault(x => x.Subject == refreshToken.Subject && x.ClientApplicationId == refreshToken.ClientApplicationId);
if (existingToken != null)
{
await <API key>(existingToken);
}
_context.RefreshTokens.Add(refreshToken);
return await _context.SaveChangesAsync() > 0;
}
public async Task<bool> <API key>(string refreshTokenId)
{
var existingToken = await _context.RefreshTokens.FindAsync(refreshTokenId);
if (existingToken != null)
{
_context.RefreshTokens.Remove(existingToken);
return await _context.SaveChangesAsync() > 0;
}
return false;
}
public async Task<bool> <API key>(RefreshToken refreshToken)
{
_context.RefreshTokens.Remove(refreshToken);
return await _context.SaveChangesAsync() > 0;
}
public async Task<RefreshToken> <API key>(string refreshTokenId)
{
return await _context.RefreshTokens.FindAsync(refreshTokenId);
}
public IEnumerable<RefreshToken> GetRefreshTokens()
{
return _context.RefreshTokens;
}
public async Task<bool> <API key>(ClientApplication clientApplication)
{
var existingClient = await _context.ClientApplications.FindAsync(clientApplication.Id);
if (existingClient != null)
{
return false;
}
clientApplication.<API key>.GetHash(clientApplication.Secret ?? string.Empty);
_context.ClientApplications.Add(clientApplication);
return await _context.SaveChangesAsync() > 0;
}
public async Task<ApplicationUser> FindUserAsync(UserLoginInfo loginInfo)
{
return await _userManager.FindAsync(loginInfo);
}
public async Task<IdentityResult> CreateAsync(ApplicationUser user)
{
return await _userManager.CreateAsync(user);
}
public async Task<IdentityResult> AddLoginAsync(string userId, UserLoginInfo loginInfo)
{
return await _userManager.AddLoginAsync(userId, loginInfo);
}
}
} |
/*<![CDATA[*/
/* Utilized for messaging the user */
.<API key> {
display: none;
position: absolute;
z-index: 1000;
border: 1px solid orange;
background-color: #eeeeee; }
.<API key> .title {
font-weight: bold;
font-size: 10pt; }
.<API key> .message {
font-size: 8pt; }
.<API key> {
padding: 5px 5px 3px 5px; }
.<API key> a {
text-decoration: none; }
.<API key> {
font-size: 8pt;
padding: 2px; }
.<API key> .<API key> {
padding: 1px; }
.<API key> {
font-size: 8pt;
padding: 2px;
display: none; }
.<API key> .<API key> {
padding: 1px;
font-weight: bold; }
.<API key> .<API key> .<API key> {}
.<API key> .<API key> .<API key> div {
padding: 1px; }
.<API key> .<API key> .<API key> div span.message {
font-weight: normal; }
.<API key> .<API key> .<API key> .<API key> {
font-weight: bold;
float: right;
position:relative;
z-index: 100; }
.<API key> .<API key> .<API key>.sub {}
.<API key> {
font-size: 8pt;
padding: 2px;
display: none; }
.<API key> .<API key> {
font-weight: bold; }
.<API key> .<API key> span.message {
font-weight: normal; }
.<API key> .<API key> {
display: none; }
.<API key> .<API key> {
font-weight: bold;
float: right;
position:relative;
z-index: 100; }
.<API key> .<API key> a {
text-decoration: none; }
.<API key> {
font-size: 8pt;
padding: 2px;
display: none; }
.<API key> .<API key> {
font-weight: bold; }
.<API key> .<API key> span.message {
font-weight: normal; }
.<API key> .<API key> {
display: none; }
.<API key> .<API key> .<API key> {
padding: 1px;
border-bottom: 1px solid #032341; }
.<API key> .<API key> {
font-weight: bold;
float: right;
position: relative;
z-index: 100; }
.<API key> .<API key> a {
text-decoration: none; }
table#xmpp_node_muc_mucs {}
table#xmpp_node_muc_mucs tr.<API key> {
background-color: #eeeeee;
border-bottom: 1px solid black; }
table#xmpp_node_muc_mucs tr.<API key> td {
font-weight: bold;
padding: 1px; }
div#<API key> {}
div#<API key> table {}
div#<API key> table tr.header {
border-bottom: 1px solid black; }
div#<API key> table tr.header td {
font-weight: bold; }
div#<API key> table tr.data_body {
vertical-align: top; }
.<API key>.title {
padding: 2px;
font-weight: bold;
font-size: 8pt; }
.<API key>.title div.date {
padding: 5px;
float: left; }
.<API key>.title div.user {
padding: 5px;
float: left; }
.<API key>.title div.message {
padding: 5px; }
.<API key> {
padding: 2px;
font-weight: normal;
font-size: 8pt; }
.<API key> div.date {
padding: 5px;
float: left; }
.<API key> div.user {
padding: 5px;
float: left; }
.<API key> div.message {
padding: 5px; } |
/**
* \file timer-low_pc.c
* \brief Timer und Counter
* \author Benjamin Benz (bbe@heise.de)
* \date 26.12.2005
*/
#ifdef PC
#include "ct-Bot.h"
#include "timer.h"
#include "sensor.h"
/**
* initialisiert Timer 2 und startet ihn
*/
void timer_2_init(void) {
// Dummy
}
/**
* Funktion, die die TickCounts um die vergangene Simulzeit erhoeht
*/
void system_time_isr(void) {
// LOG_DEBUG("simultime=%d", simultime);
/* TickCounter [176 us] erhoehen */
static int last_simultime = -11; // kommt vom Sim zuerst als -1, warum auch immer!?! // explizit ** int **
int tmp = simultime - last_simultime; // explizit ** int **
if (tmp < 0) tmp += 10000; // der Sim setzt simultime alle 10s zurueck auf 0
#ifdef ARM_LINUX_BOARD
tickCount = tickCount + (uint_fast32_t) MS_TO_TICKS(tmp);
#else
tickCount += MS_TO_TICKS((double) tmp);
#endif
last_simultime = simultime;
}
/**
* Setzt die Systemzeit zurueck auf 0
*/
void timer_reset(void) {
tickCount = 0;
}
#endif |
<?php
class <API key>
{
function __construct() {
$this->label = __( 'Number Range', 'fwp' );
}
/**
* Generate the facet HTML
*/
function render( $params ) {
$output = '';
$value = $params['selected_values'];
$value = empty( $value ) ? array( '', '', ) : $value;
$output .= '<label>' . __( 'Min', 'fwp' ) . '</label>';
$output .= '<input type="text" class="facetwp-number facetwp-number-min" value="' . $value[0] . '" />';
$output .= '<label>' . __( 'Max', 'fwp' ) . '</label>';
$output .= '<input type="text" class="facetwp-number facetwp-number-max" value="' . $value[1] . '" />';
return $output;
}
/**
* Filter the query based on selected values
*/
function filter_posts( $params ) {
global $wpdb;
$facet = $params['facet'];
$numbers = $params['selected_values'];
$where = '';
if ( '' != $numbers[0] ) {
$where .= " AND (facet_value + 0) >= '" . $numbers[0] . "'";
}
if ( '' != $numbers[1] ) {
$where .= " AND (facet_value + 0) <= '" . $numbers[1] . "'";
}
$sql = "
SELECT DISTINCT post_id FROM {$wpdb->prefix}facetwp_index
WHERE facet_name = '{$facet['name']}' $where";
return $wpdb->get_col( $sql );
}
/**
* Output any admin scripts
*/
function admin_scripts() {
?>
<script>
(function($) {
wp.hooks.addAction('facetwp/load/number_range', function($this, obj) {
$this.find('.facet-source').val(obj.source);
});
wp.hooks.addFilter('facetwp/save/number_range', function($this, obj) {
obj['source'] = $this.find('.facet-source').val();
return obj;
});
})(jQuery);
</script>
<?php
}
/**
* Output any front-end scripts
*/
function front_scripts() {
?>
<script>
(function($) {
wp.hooks.addAction('facetwp/refresh/number_range', function($this, facet_name) {
var min = $this.find('.facetwp-number-min').val() || '';
var max = $this.find('.facetwp-number-max').val() || '';
FWP.facets[facet_name] = ('' != min || '' != max) ? [min, max] : [];
});
wp.hooks.addAction('facetwp/ready', function() {
$(document).on('blur', '.facetwp-number-min, .facetwp-number-max', function() {
FWP.autoload();
});
});
})(jQuery);
</script>
<?php
}
/**
* Output admin settings HTML
*/
function settings_html() {
}
} |
<?php
/* Register nav menus. */
add_action( 'init', '<API key>' );
function <API key>() {
/* Get theme-supported menus. */
$menus = get_theme_support( 'hybrid-core-menus' );
/* If there is no array of menus IDs, return. */
if ( !is_array( $menus[0] ) )
return;
/* Register the 'primary' menu. */
if ( in_array( 'primary', $menus[0] ) )
register_nav_menu( 'primary', _x( 'Primary', 'nav menu location', 'hybrid-core' ) );
/* Register the 'secondary' menu. */
if ( in_array( 'secondary', $menus[0] ) )
register_nav_menu( 'secondary', _x( 'Secondary', 'nav menu location', 'hybrid-core' ) );
/* Register the 'subsidiary' menu. */
if ( in_array( 'subsidiary', $menus[0] ) )
register_nav_menu( 'subsidiary', _x( 'Subsidiary', 'nav menu location', 'hybrid-core' ) );
}
?> |
// $HeadURL$
// Screensaver is an open-source project developed by the ICCB-L and NSRB labs
// at Harvard Medical School. This software is distributed under the terms of
package edu.harvard.med.screensaver.db.datafetcher;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import edu.harvard.med.screensaver.model.libraries.Gene;
import edu.harvard.med.screensaver.model.libraries.Library;
import edu.harvard.med.screensaver.model.libraries.Reagent;
import edu.harvard.med.screensaver.model.libraries.SilencingReagent;
import edu.harvard.med.screensaver.model.libraries.Well;
import edu.harvard.med.screensaver.model.meta.PropertyPath;
import edu.harvard.med.screensaver.model.meta.RelationshipPath;
import edu.harvard.med.screensaver.model.screenresults.DataColumn;
import edu.harvard.med.screensaver.model.screenresults.ResultValue;
import edu.harvard.med.screensaver.model.screenresults.ScreenResult;
import edu.harvard.med.screensaver.model.screens.Screen;
import edu.harvard.med.screensaver.model.screens.ScreenType;
import edu.harvard.med.screensaver.model.users.LabHead;
import edu.harvard.med.screensaver.model.users.ScreeningRoomUser;
import edu.harvard.med.screensaver.test.<API key>;
import edu.harvard.med.screensaver.test.MakeDummyEntities;
public class <API key> extends <API key>
{
public void testSimpleEntity()
{
LabHead labHead = dataFactory.newInstance(LabHead.class);
ScreeningRoomUser user1 = dataFactory.newInstance(ScreeningRoomUser.class);
user1.setLab(labHead.getLab());
ScreeningRoomUser user2 = dataFactory.newInstance(ScreeningRoomUser.class);
genericEntityDao.saveOrUpdateEntity(labHead);
genericEntityDao.saveOrUpdateEntity(user1);
genericEntityDao.saveOrUpdateEntity(user2);
TupleDataFetcher<ScreeningRoomUser,Integer> dataFetcher =
new TupleDataFetcher<ScreeningRoomUser,Integer>(ScreeningRoomUser.class, genericEntityDao);
ArrayList<PropertyPath<ScreeningRoomUser>> properties =
Lists.newArrayList(RelationshipPath.from(ScreeningRoomUser.class).toProperty("id"),
RelationshipPath.from(ScreeningRoomUser.class).toProperty("lastName"),
RelationshipPath.from(ScreeningRoomUser.class).toProperty("firstName"),
RelationshipPath.from(ScreeningRoomUser.class).toProperty("loginId"),
RelationshipPath.from(ScreeningRoomUser.class).toProperty("dateCreated"),
ScreeningRoomUser.LabHead.toProperty("lastName"));
dataFetcher.<API key>(properties);
List<Tuple<Integer>> result = dataFetcher.fetchAllData();
Collections.sort(result, new Comparator<Tuple<Integer>>() {
@Override
public int compare(Tuple<Integer> o1, Tuple<Integer> o2)
{
return o1.getKey().compareTo(o2.getKey());
}
});
assertEquals(3, result.size());
assertEquals(labHead.getEntityId(), result.get(0).getKey());
assertEquals(labHead.getEntityId(), result.get(0).getProperty("id"));
assertEquals(labHead.getLastName(), result.get(0).getProperty("lastName"));
assertEquals(labHead.getDateCreated(), result.get(0).getProperty("dateCreated"));
assertNull(result.get(0).getProperty("labHead.lastName"));
assertEquals(user1.getEntityId(), result.get(1).getKey());
assertEquals(user1.getEntityId(), result.get(1).getProperty("id"));
assertEquals(user1.getLastName(), result.get(1).getProperty("lastName"));
assertEquals(user1.getDateCreated(), result.get(1).getProperty("dateCreated"));
assertEquals(labHead.getLastName(), result.get(1).getProperty("labHead.lastName"));
assertEquals(user2.getEntityId(), result.get(2).getKey());
assertEquals(user2.getEntityId(), result.get(2).getProperty("id"));
assertEquals(user2.getLastName(), result.get(2).getProperty("lastName"));
assertEquals(user2.getDateCreated(), result.get(2).getProperty("dateCreated"));
assertNull(result.get(0).getProperty("labHead.lastName"));
Map<Integer,Tuple<Integer>> result2 = dataFetcher.fetchData(ImmutableSet.of(user1.getEntityId()));
assertEquals(result.get(1), result2.get(user1.getEntityId()));
}
public void <API key>()
{
Library library = MakeDummyEntities.makeDummyLibrary(1, ScreenType.RNAI, 1);
genericEntityDao.saveOrUpdateEntity(library);
Screen screen = MakeDummyEntities.makeDummyScreen(1, ScreenType.RNAI);
ScreenResult screenResult = MakeDummyEntities.<API key>(screen, library);
genericEntityDao.saveOrUpdateEntity(screen);
TupleDataFetcher<Well,String> dataFetcher =
new TupleDataFetcher<Well,String>(Well.class, genericEntityDao);
DataColumn numericDataColumn = screenResult.getDataColumnsList().get(0);
assert numericDataColumn != null && numericDataColumn.getName().equals("numeric_repl1");
DataColumn positiveDataColumn = screenResult.getDataColumnsList().get(6);
assert positiveDataColumn != null && positiveDataColumn.getName().equals("positive");
ArrayList<PropertyPath<Well>> properties =
Lists.newArrayList(RelationshipPath.from(Well.class).toProperty("id"),
Well.library.toProperty("libraryName"),
Well.resultValues.restrict(ResultValue.DataColumn.getLeaf(), numericDataColumn).toProperty("numericValue"),
Well.resultValues.restrict(ResultValue.DataColumn.getLeaf(), numericDataColumn).toProperty("positive"),
Well.resultValues.restrict(ResultValue.DataColumn.getLeaf(), positiveDataColumn).toProperty("value"),
Well.resultValues.restrict(ResultValue.DataColumn.getLeaf(), positiveDataColumn).toProperty("positive"));
dataFetcher.<API key>(properties);
List<Tuple<String>> result = dataFetcher.fetchAllData();
assertEquals(384, result.size());
Map<String,Double> <API key> = Maps.newHashMap();
for (ResultValue resultValue : numericDataColumn.getResultValues()) {
<API key>.put(resultValue.getWell().getWellId(), resultValue.getNumericValue());
}
assertColumnEquals(<API key>,
result,
TupleDataFetcher.makePropertyKey(properties.get(2)));
Map<String,Boolean> <API key> = Maps.newHashMap();
for (ResultValue resultValue : positiveDataColumn.getResultValues()) {
<API key>.put(resultValue.getWell().getWellId(), resultValue.isPositive());
}
assertColumnEquals(<API key>,
result,
TupleDataFetcher.makePropertyKey(properties.get(5)));
String tupleKey = result.get(0).getKey();
Map<String,Tuple<String>> result2 = dataFetcher.fetchData(ImmutableSet.of(tupleKey));
assertEquals(result.get(0), result2.get(tupleKey));
}
public void <API key>()
{
Library library = MakeDummyEntities.makeDummyLibrary(1, ScreenType.RNAI, 1);
genericEntityDao.saveOrUpdateEntity(library);
TupleDataFetcher<Well,String> dataFetcher =
new TupleDataFetcher<Well,String>(Well.class, genericEntityDao);
ArrayList<PropertyPath<Well>> properties =
Lists.newArrayList(RelationshipPath.from(Well.class).toProperty("id"),
Well.<API key>.toProperty("id"),
Well.<API key>.toFullEntity());
dataFetcher.<API key>(properties);
List<Tuple<String>> result = dataFetcher.fetchAllData();
assertNotNull(result.get(0).getProperty("<API key>.*"));
assertTrue(result.get(0).getProperty("<API key>.*") instanceof Reagent);
assertEquals(result.get(0).getProperty("<API key>.id"),
((Reagent) result.get(0).getProperty("<API key>.*")).getEntityId());
}
public void <API key>()
{
Library library = MakeDummyEntities.makeDummyLibrary(1, ScreenType.RNAI, 1);
Well well = library.getWells().iterator().next();
((SilencingReagent) well.<API key>()).getFacilityGene().<API key>("xxx").<API key>("yyy");
genericEntityDao.saveOrUpdateEntity(library);
TupleDataFetcher<Well,String> dataFetcher =
new TupleDataFetcher<Well,String>(Well.class, genericEntityDao);
ArrayList<PropertyPath<Well>> properties =
Lists.newArrayList(RelationshipPath.from(Well.class).toProperty("id"),
Well.<API key>.toProperty("id"),
Well.<API key>.to(SilencingReagent.facilityGenes).to(Gene.entrezgeneSymbols));
dataFetcher.<API key>(properties);
Map<String,Tuple<String>> result = dataFetcher.fetchData(Sets.newHashSet(well.getWellId()));
Tuple<String> tuple = result.get(well.getWellId());
assertNotNull(tuple);
Object propValue = tuple.getProperty("<API key>.facilityGenes.entrezgeneSymbols");
assertNotNull(propValue);
assertTrue(propValue instanceof List);
assertEquals(Sets.newHashSet("xxx", "yyy"), Sets.newHashSet((List<String>) propValue));
}
private <K,V> void assertColumnEquals(Map<String,V> <API key>, List<Tuple<K>> result, String propertyKey)
{
Map<K,V> actualValues = Maps.newHashMap();
for (Tuple<K> tuple : result) {
actualValues.put(tuple.getKey(), (V) tuple.getProperty(propertyKey));
}
assertEquals(<API key>, actualValues);
}
} |
<tr>
<form action="?phpmussel-page=quarantine" method="POST"><input name="qfu" type="hidden" value="{QFU-Name}" />
<td class="h3">
<span class="s">{QFU-Name}</span><br />
{label_upload_date}{Upload-Date}<br />
{label_upload_origin}{Upload-Origin}<br />
{label_upload_size}{Upload-Size}<br />
{label_upload_hash}{Upload-MD5}<br />
{<API key>}{QFU-Size}<br />
</td>
<td class="h3f">
<select id="{QFU-JS-ID}-S" name="do" onchange="javascript:qOpt('{QFU-JS-ID}')">
<option value="delete-file">{field_delete_file}</option>
<option value="restore-file">{field_restore_file}</option>
<option value="download-file">{field_download_file}</option>
</select>
<input type="text" name="qkey" id="{QFU-JS-ID}" style="display:none" placeholder="{<API key>}" />
<input type="submit" value="{field_ok}" class="auto" />
</td>
</form>
</tr> |
#ifndef <API key>
#define <API key>
#include <KDialog>
#include <<API key>.h>
class SCDocument;
class <API key> : public KDialog
{
Q_OBJECT
public:
explicit <API key>(SCDocument *document, QWidget *parent=0);
QString <API key>() const;
private slots:
void editCustomSlideShow();
private:
Ui::<API key> ui;
SCDocument *m_document;
};
#endif // <API key> |
/*
* \brief RAM dataspace utility
* \author Norman Feske
* \date 2008-03-22
*
* The combination of RAM allocation and a local RM attachment
* is a frequent use case. Each function may fail, which makes
* error handling inevitable. This utility class encapsulates
* this functionality to handle both operations as a transaction.
* When embedded as a member, this class also takes care about
* freeing and detaching the dataspace at destruction time.
*/
#ifndef <API key>
#define <API key>
#include <ram_session/ram_session.h>
#include <util/touch.h>
#include <base/env.h>
namespace Genode {
class <API key>
{
private:
size_t _size;
Ram_session *_ram_session;
<API key> _ds;
void *_local_addr;
bool const _cached;
template <typename T>
static void _swap(T &v1, T &v2) { T tmp = v1; v1 = v2; v2 = tmp; }
void <API key>()
{
if (_local_addr)
env()->rm_session()->detach(_local_addr);
if (_ram_session && _ds.valid())
_ram_session->free(_ds);
}
void _alloc_and_attach()
{
if (!_size || !_ram_session) return;
try {
_ds = _ram_session->alloc(_size, _cached);
_local_addr = env()->rm_session()->attach(_ds);
/* revert allocation if attaching the dataspace failed */
} catch (Rm_session::Attach_failed) {
_ram_session->free(_ds);
throw;
}
if (!_cached) {
enum { PAGE_SIZE = 4096 };
unsigned char volatile *base = (unsigned char volatile *)_local_addr;
for (size_t i = 0; i < _size; i += PAGE_SIZE)
touch_read_write(base + i);
}
}
public:
/**
* Constructor
*
* \throw Ram_session::Alloc_failed
* \throw Rm_session::Attach_failed
*/
<API key>(Ram_session *ram_session, size_t size,
bool cached = true)
:
_size(size), _ram_session(ram_session), _local_addr(0),
_cached(cached)
{
_alloc_and_attach();
}
/**
* Destructor
*/
~<API key>() { <API key>(); }
/**
* Return capability of the used RAM dataspace
*/
<API key> cap() const { return _ds; }
/**
* Request local address
*
* This is a template to avoid inconvenient casts at
* the caller. A newly allocated RAM dataspace is
* untyped memory anyway.
*/
template <typename T>
T *local_addr() const { return static_cast<T *>(_local_addr); }
/**
* Return size
*/
size_t size() const { return _size; }
void swap(<API key> &other)
{
_swap(_size, other._size);
_swap(_ram_session, other._ram_session);
_swap(_ds, other._ds);
_swap(_local_addr, other._local_addr);
}
/**
* Re-allocate dataspace with a new size
*
* The content of the original dataspace is not retained.
*/
void realloc(Ram_session *ram_session, size_t new_size)
{
if (new_size < _size) return;
<API key>();
_size = new_size;
_ram_session = ram_session;
_alloc_and_attach();
}
};
}
#endif /* <API key> */ |
<?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Tests\Integration\Conversations\V1\Conversation;
use Twilio\Exceptions\<API key>;
use Twilio\Exceptions\TwilioException;
use Twilio\Http\Response;
use Twilio\Tests\HolodeckTestCase;
use Twilio\Tests\Request;
class MessageTest extends HolodeckTestCase {
public function testCreateRequest() {
$this->holodeck->mock(new Response(500, ''));
try {
$this->twilio->conversations->v1->conversations("<API key>")
->messages->create();
} catch (<API key> $e) {}
catch (TwilioException $e) {}
$this->assertRequest(new Request(
'post',
'https://conversations.twilio.com/v1/Conversations/<API key>/Messages'
));
}
public function testCreateResponse() {
$this->holodeck->mock(new Response(
201,
'
{
"sid": "<API key>",
"account_sid": "<API key>",
"conversation_sid": "<API key>",
"body": "Hello",
"media": null,
"author": "message author",
"participant_sid": "<API key>",
"attributes": "{ \\"importance\\": \\"high\\" }",
"date_created": "2015-12-16T22:18:37Z",
"date_updated": "2015-12-16T22:18:38Z",
"index": 0,
"url": "https://conversations.twilio.com/v1/Conversations/<API key>/Messages/<API key>"
}
'
));
$actual = $this->twilio->conversations->v1->conversations("<API key>")
->messages->create();
$this->assertNotNull($actual);
}
public function <API key>() {
$this->holodeck->mock(new Response(
201,
'
{
"sid": "<API key>",
"account_sid": "<API key>",
"conversation_sid": "<API key>",
"body": null,
"media": [
{
"sid": "<API key>",
"size": 42056,
"content_type": "image/jpeg",
"filename": "car.jpg"
}
],
"author": "message author",
"participant_sid": "<API key>",
"attributes": "{ \\"importance\\": \\"high\\" }",
"date_created": "2015-12-16T22:18:37Z",
"date_updated": "2015-12-16T22:18:38Z",
"index": 0,
"url": "https://conversations.twilio.com/v1/Conversations/<API key>/Messages/<API key>"
}
'
));
$actual = $this->twilio->conversations->v1->conversations("<API key>")
->messages->create();
$this->assertNotNull($actual);
}
public function testUpdateRequest() {
$this->holodeck->mock(new Response(500, ''));
try {
$this->twilio->conversations->v1->conversations("<API key>")
->messages("<API key>")->update();
} catch (<API key> $e) {}
catch (TwilioException $e) {}
$this->assertRequest(new Request(
'post',
'https://conversations.twilio.com/v1/Conversations/<API key>/Messages/<API key>'
));
}
public function testUpdateResponse() {
$this->holodeck->mock(new Response(
200,
'
{
"sid": "<API key>",
"account_sid": "<API key>",
"conversation_sid": "<API key>",
"body": "Hello",
"media": null,
"author": "message author",
"participant_sid": "<API key>",
"attributes": "{ \\"importance\\": \\"high\\" }",
"date_created": "2015-12-16T22:18:37Z",
"date_updated": "2015-12-16T22:18:38Z",
"index": 0,
"url": "https://conversations.twilio.com/v1/Conversations/<API key>/Messages/<API key>"
}
'
));
$actual = $this->twilio->conversations->v1->conversations("<API key>")
->messages("<API key>")->update();
$this->assertNotNull($actual);
}
public function testDeleteRequest() {
$this->holodeck->mock(new Response(500, ''));
try {
$this->twilio->conversations->v1->conversations("<API key>")
->messages("<API key>")->delete();
} catch (<API key> $e) {}
catch (TwilioException $e) {}
$this->assertRequest(new Request(
'delete',
'https://conversations.twilio.com/v1/Conversations/<API key>/Messages/<API key>'
));
}
public function testDeleteResponse() {
$this->holodeck->mock(new Response(
204,
null
));
$actual = $this->twilio->conversations->v1->conversations("<API key>")
->messages("<API key>")->delete();
$this->assertTrue($actual);
}
public function testFetchRequest() {
$this->holodeck->mock(new Response(500, ''));
try {
$this->twilio->conversations->v1->conversations("<API key>")
->messages("<API key>")->fetch();
} catch (<API key> $e) {}
catch (TwilioException $e) {}
$this->assertRequest(new Request(
'get',
'https://conversations.twilio.com/v1/Conversations/<API key>/Messages/<API key>'
));
}
public function testFetchResponse() {
$this->holodeck->mock(new Response(
200,
'
{
"sid": "<API key>",
"account_sid": "<API key>",
"conversation_sid": "<API key>",
"body": "Welcome!",
"media": null,
"author": "system",
"participant_sid": null,
"attributes": "{ \\"importance\\": \\"high\\" }",
"date_created": "2016-03-24T20:37:57Z",
"date_updated": "2016-03-24T20:37:57Z",
"index": 0,
"url": "https://conversations.twilio.com/v1/Conversations/<API key>/Messages/<API key>"
}
'
));
$actual = $this->twilio->conversations->v1->conversations("<API key>")
->messages("<API key>")->fetch();
$this->assertNotNull($actual);
}
public function testReadRequest() {
$this->holodeck->mock(new Response(500, ''));
try {
$this->twilio->conversations->v1->conversations("<API key>")
->messages->read();
} catch (<API key> $e) {}
catch (TwilioException $e) {}
$this->assertRequest(new Request(
'get',
'https://conversations.twilio.com/v1/Conversations/<API key>/Messages'
));
}
public function <API key>() {
$this->holodeck->mock(new Response(
200,
'
{
"meta": {
"page": 0,
"page_size": 50,
"first_page_url": "https://conversations.twilio.com/v1/Conversations/<API key>/Messages?PageSize=50&Page=0",
"previous_page_url": null,
"url": "https://conversations.twilio.com/v1/Conversations/<API key>/Messages?PageSize=50&Page=0",
"next_page_url": null,
"key": "messages"
},
"messages": [
{
"sid": "<API key>",
"account_sid": "<API key>",
"conversation_sid": "<API key>",
"body": "I like pie.",
"media": null,
"author": "pie_preferrer",
"participant_sid": "<API key>",
"attributes": "{ \\"importance\\": \\"high\\" }",
"date_created": "2016-03-24T20:37:57Z",
"date_updated": "2016-03-24T20:37:57Z",
"index": 0,
"url": "https://conversations.twilio.com/v1/Conversations/<API key>/Messages/<API key>"
},
{
"sid": "<API key>",
"account_sid": "<API key>",
"conversation_sid": "<API key>",
"body": "Cake is my favorite!",
"media": null,
"author": "cake_lover",
"participant_sid": "<API key>",
"attributes": "{ \\"importance\\": \\"high\\" }",
"date_created": "2016-03-24T20:38:21Z",
"date_updated": "2016-03-24T20:38:21Z",
"index": 0,
"url": "https://conversations.twilio.com/v1/Conversations/<API key>/Messages/<API key>"
},
{
"sid": "<API key>",
"account_sid": "<API key>",
"conversation_sid": "<API key>",
"body": null,
"media": [
{
"sid": "<API key>",
"size": 42056,
"content_type": "image/jpeg",
"filename": "car.jpg"
}
],
"author": "cake_lover",
"participant_sid": "<API key>",
"attributes": "{ \\"importance\\": \\"high\\" }",
"date_created": "2016-03-24T20:38:21Z",
"date_updated": "2016-03-24T20:38:21Z",
"index": 0,
"url": "https://conversations.twilio.com/v1/Conversations/<API key>/Messages/<API key>"
}
]
}
'
));
$actual = $this->twilio->conversations->v1->conversations("<API key>")
->messages->read();
$this->assertGreaterThan(0, \count($actual));
}
} |
<div style="position: relative; top: 10px;">
<div style="top: 10px; left: 372px;" class="MollusqueLabel"><a href="#mollusques" title="La Galerie des Mollusques" class="btn btn-small" id="all">Mollusques</a></div>
<div style="top: 38px; left: 422px; width: 4px; height: 15px;" class="TreeBranch"> </div>
<div style="top: 53px; left: 98px; width: 535px; height: 4px;" class="TreeBranch"> </div>
<div style="top: 53px; left: 98px; width: 4px; height: 15px;" class="TreeBranch"> </div>
<div style="top: 76px; left: 35px;" class="MollusqueLabel"><a href="
<div style="top: 53px; left: 310px; width: 4px; height: 67px;" class="TreeBranch"> </div>
<div style="top: 76px; left: 250px;" class="MollusqueLabel"><a href="
<div style="top: 120px; left: 168px; width: 280px; height: 4px;" class="TreeBranch"> </div>
<div style="top: 53px; left: 500px; width: 4px; height: 15px;" class="TreeBranch"> </div>
<div style="top: 76px; left: 460px;" class="MollusqueLabel"><a href="#bivalves" title="La Galerie des Bivalves" class="btn btn-small" data-filter="bivalve" data-cat="20|170">Bivalves</a></div>
<div style="top: 53px; left: 630px; width: 4px; height: 195px;" class="TreeBranch"> </div>
<div style="top: 84px; left: 630px; width: 20px; height: 4px;" class="TreeBranch"> </div>
<div style="top: 76px; left: 650px;" class="MollusqueLabel"><a href="#monoplacophores" title="La Galerie des Monoplacophores" class="btn btn-small" data-filter="monoplacophore" data-cat="">Monoplacophores</a></div>
<div style="top: 138px; left: 630px; width: 20px; height: 4px;" class="TreeBranch"> </div>
<div style="top: 130px; left: 650px;" class="MollusqueLabel"><a href="#aplacophores" title="La Galerie des Aplacophores" class="btn btn-small" data-filter="aplacophore" data-cat="">Aplacophores</a></div>
<div style="top: 192px; left: 630px; width: 20px; height: 4px;" class="TreeBranch"> </div>
<div style="top: 184px; left: 650px;" class="MollusqueLabel"><a href="#polyplacophores" title="La Galerie des Polyplacophores" class="btn btn-small" data-filter="polyplacophore" data-cat="">Polyplacophores</a></div>
<div style="top: 246px; left: 630px; width: 20px; height: 4px;" class="TreeBranch"> </div>
<div style="top: 238px; left: 650px;" class="MollusqueLabel"><a href="#scaphopodes" title="La Galerie des Scaphopodes" class="btn btn-small" data-filter="scaphopode" data-cat="">Scaphopodes</a></div>
<div style="top: 124px; left: 168px; width: 4px; height: 70px;" class="TreeBranch"> </div>
<div style="top: 147px; left: 100px;" class="MollusqueLabel"><a href="#opistobranche" title="La Galerie des Opisthobranches" class="btn btn-small" data-filter="opistobranche" data-cat="21|169">Opisthobranches</a></div>
<div style="top: 191px; left: 42px; width: 481px; height: 4px;" class="TreeBranch"> </div>
<div style="top: 124px; left: 444px; width: 4px; height: 15px;" class="TreeBranch"> </div>
<div style="top: 147px; left: 380px;" class="MollusqueLabel"><a href="#prosobranches" title="La Galerie des Prosobranches" class="btn btn-small" data-filter="prosobranche" data-cat="22|171">Prosobranches</a></div>
<div style="top: 195px; left: 42px; width: 4px; height: 140px;" class="TreeBranch"> </div>
<div style="top: 220px; left: 0px;" class="MollusqueLabel"><a href="#nudibranche" title="La Galerie des Nudibranches" class="btn btn-small" data-filter="nudibranche" data-cat="23|172">Nudibranches</a></div>
<div style="top: 335px; left: 42px; width: 555px; height: 4px;" class="TreeBranch"> </div>
<div style="top: 195px; left: 224px; width: 4px; height: 17px;" class="TreeBranch"> </div>
<div style="top: 220px; left: 161px;" class="MollusqueLabel"><a href="
<div style="top: 195px; left: 374px; width: 4px; height: 17px;" class="TreeBranch"> </div>
<div style="top: 220px; left: 322px;" class="MollusqueLabel"><a href="
<div style="top: 195px; left: 519px; width: 4px; height: 17px;" class="TreeBranch"> </div>
<div style="top: 220px; left: 461px;" class="MollusqueLabel"><a href="#thecosomata" title="La Galerie des Thecosomata" class="btn btn-small" data-filter="thecosomata" data-cat="29|182">Thecosomata</a></div>
<div style="top: 195px; left: 148px; width: 4px; height: 80px;" class="TreeBranch"> </div>
<div style="top: 275px; left: 75px;" class="MollusqueLabel"><a href="#gymnosomata" title="La Galerie des Gymnosomata" class="btn btn-small" data-filter="gymnosomata" data-cat="24|177">Gymnosomata</a></div>
<div style="top: 195px; left: 311px; width: 4px; height: 80px;" class="TreeBranch"> </div>
<div style="top: 275px; left: 253px;" class="MollusqueLabel"><a href="#anaspide" title="La Galerie des Anaspidea" class="btn btn-small" data-filter="anaspide" data-cat="26|179">Anaspidea</a></div>
<div style="top: 195px; left: 448px; width: 4px; height: 80px;" class="TreeBranch"> </div>
<div style="top: 275px; left: 390px;" class="MollusqueLabel"><a href="#sacoglosse" title="La Galerie des Sacoglosses" class="btn btn-small" data-filter="sacoglosse" data-cat="28|181">Sacoglosses</a></div>
<div style="top: 335px; left: 89px; width: 4px; height: 30px;" class="TreeBranch"> </div>
<div style="top: 370px; left: 40px;" class="MollusqueLabel"><a href="
<div style="top: 335px; left: 249px; width: 4px; height: 30px;" class="TreeBranch"> </div>
<div style="top: 370px; left: 200px;" class="MollusqueLabel"><a href="
<div style="top: 335px; left: 425px; width: 4px; height: 30px;" class="TreeBranch"> </div>
<div style="top: 370px; left: 360px;" class="MollusqueLabel"><a href="
<div style="top: 335px; left: 596px; width: 4px; height: 30px;" class="TreeBranch"> </div>
<div style="top: 370px; left: 550px;" class="MollusqueLabel"><a href="#doridien" title="La Galerie des Doridiens" class="btn btn-small" data-filter="doridien" data-cat="33|176">Doridiens</a></div>
</div> |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>rml Namespace Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<!-- end header part -->
<!-- Generated by Doxygen 1.8.4 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li class="current"><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="namespaces.html"><span>Namespace List</span></a></li>
<li><a href="namespacemembers.html"><span>Namespace Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#nested-classes">Classes</a> |
<a href="#typedef-members">Typedefs</a> |
<a href="#enum-members">Enumerations</a> |
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<div class="title">rml Namespace Reference</div> </div>
</div><!--header
<div class="contents">
<p>The namespace rml contains components of low-level memory pool interface.
<a href="#details">More...</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a>
Classes</h2></td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="a00107.html">MemPoolPolicy</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="typedef-members"></a>
Typedefs</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
typedef void *(* </td><td class="memItemRight" valign="bottom"><b>rawAllocType</b> )(intptr_t pool_id, size_t &bytes)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
typedef int(* </td><td class="memItemRight" valign="bottom"><b>rawFreeType</b> )(intptr_t pool_id, void *raw_ptr, size_t raw_bytes)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="enum-members"></a>
Enumerations</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">enum  </td><td class="memItemRight" valign="bottom"><b>MemPoolError</b> { <br/>
  <b>POOL_OK</b> = TBBMALLOC_OK,
<b>INVALID_POLICY</b> = <API key>,
<b>UNSUPPORTED_POLICY</b> = <API key>,
<b>NO_MEMORY</b> = TBBMALLOC_NO_MEMORY,
<br/>
  <b>NO_EFFECT</b> = TBBMALLOC_NO_EFFECT
<br/>
}</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
MemPoolError </td><td class="memItemRight" valign="bottom"><b>pool_create_v1</b> (intptr_t pool_id, const <a class="el" href="a00107.html">MemPoolPolicy</a> *policy, rml::MemoryPool **pool)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
bool </td><td class="memItemRight" valign="bottom"><b>pool_destroy</b> (MemoryPool *memPool)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
void * </td><td class="memItemRight" valign="bottom"><b>pool_malloc</b> (MemoryPool *memPool, size_t size)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
void * </td><td class="memItemRight" valign="bottom"><b>pool_realloc</b> (MemoryPool *memPool, void *object, size_t size)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
void * </td><td class="memItemRight" valign="bottom"><b>pool_aligned_malloc</b> (MemoryPool *mPool, size_t size, size_t alignment)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
void * </td><td class="memItemRight" valign="bottom"><b><API key></b> (MemoryPool *mPool, void *ptr, size_t size, size_t alignment)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
bool </td><td class="memItemRight" valign="bottom"><b>pool_reset</b> (MemoryPool *memPool)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
bool </td><td class="memItemRight" valign="bottom"><b>pool_free</b> (MemoryPool *memPool, void *object)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
MemoryPool * </td><td class="memItemRight" valign="bottom"><b>pool_identify</b> (void *object)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>The namespace rml contains components of low-level memory pool interface. </p>
</div></div><!-- contents -->
<hr>
<p></p>
Copyright © 2005-2016 Intel Corporation. All Rights Reserved.
<p></p>
Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are
registered trademarks or trademarks of Intel Corporation or its
subsidiaries in the United States and other countries.
<p></p>
* Other names and brands may be claimed as the property of others. |
<?php
?>
<section class="root content has-cows featured woocommerce">
<section class="row box">
<div class="tb-line clearfix">
<article>
<ul class="products small-block-grid-1 large-block-grid-3">
<?php
?>
</ul>
</article>
</div>
</section>
</section> |
package ome.metakit;
import java.io.IOException;
import loci.common.DataTools;
import loci.common.<API key>;
public class MetakitReader {
// -- Fields --
private <API key> stream;
private String[] tableNames;
private Column[][] columns;
private int[] rowCount;
private Object[][][] data;
private boolean littleEndian = false;
// -- Constructors --
public MetakitReader(String file) throws IOException, MetakitException {
this(new <API key>(file));
}
public MetakitReader(<API key> stream) throws MetakitException {
this.stream = stream;
try {
initialize();
}
catch (IOException e) {
throw new MetakitException(e);
}
}
// -- MetakitReader API methods --
/**
* Close the reader and release any resources in use.
*/
public void close() {
try {
if (stream != null) {
stream.close();
}
stream = null;
tableNames = null;
columns = null;
rowCount = null;
data = null;
littleEndian = false;
}
catch (IOException e) { }
}
/**
* Retrieve the number of tables in this database file.
*/
public int getTableCount() {
return tableNames.length;
}
/**
* Retrieve the name of every table in this database file.
* The length of the returned array is equivalent to
* {@link #getTableCount()}.
*/
public String[] getTableNames() {
return tableNames;
}
/**
* Retrieve the name of every column in the table with the given index.
* Tables are indexed from 0 to <code>{@link #getTableCount()} - 1</code>.
*/
public String[] getColumnNames(int tableIndex) {
String[] columnNames = new String[columns[tableIndex].length];
for (int i=0; i<columnNames.length; i++) {
columnNames[i] = columns[tableIndex][i].getName();
}
return columnNames;
}
/**
* Retrieve the name of every column in the named table.
*/
public String[] getColumnNames(String tableName) {
int index = DataTools.indexOf(tableNames, tableName);
if (index < 0) {
return null;
}
return getColumnNames(index);
}
/**
* Retrieve the type for every column in the table with the given index.
* Tables are indexed from 0 to <code>{@link #getTableCount()} - 1</code>.
*
* Every Object in the arrays returned by {@link #getTableData(int)} and
* {@link #getTableData(String)} will be an instance of the corresponding
* Class in the Class[] returned by this method.
*/
public Class[] getColumnTypes(int tableIndex) {
Class[] types = new Class[columns[tableIndex].length];
for (int i=0; i<types.length; i++) {
types[i] = columns[tableIndex][i].getType();
}
return types;
}
/**
* Retrieve the type for every column in the named table.
*
* Every Object in the arrays returned by {@link #getTableData(int)} and
* {@link #getTableData(String)} will be an instance of the corresponding
* Class in the Class[] returned by this method.
*/
public Class[] getColumnTypes(String tableName) {
int index = DataTools.indexOf(tableNames, tableName);
if (index < 0) {
return null;
}
return getColumnTypes(index);
}
/**
* Retrieve the number of rows in the table with the given index.
* Tables are indexed from 0 to <code>{@link #getTableCount()} - 1</code>.
*/
public int getRowCount(int tableIndex) {
return rowCount[tableIndex];
}
/**
* Retrieve the number of rows in the named table.
*/
public int getRowCount(String tableName) {
return getRowCount(DataTools.indexOf(tableNames, tableName));
}
/**
* Retrieve all of the tabular data for the table with the given index.
* Tables are indexed from 0 to <code>{@link #getTableCount()} - 1</code>.
*
* @see #getColumnTypes(int)
*/
public Object[][] getTableData(int tableIndex) {
Object[][] table = data[tableIndex];
if (table == null) return null;
// table is stored in [column][row] order; reverse it for convenience
int rowCount = table[0] == null ? 0 : table[0].length;
Object[][] newTable = new Object[rowCount][table.length];
for (int row=0; row<newTable.length; row++) {
for (int col=0; col<newTable[row].length; col++) {
if (col < table.length && row < table[col].length) {
newTable[row][col] = table[col][row];
}
}
}
return newTable;
}
/**
* Retrieve all of the tabular data for the named table.
*
* @see #getColumnTypes(String)
*/
public Object[][] getTableData(String tableName) {
int index = DataTools.indexOf(tableNames, tableName);
if (index < 0) {
return null;
}
return getTableData(index);
}
/**
* Retrieve the given row of data from the table with the given index.
* Tables are indexed from 0 to <code>{@link #getTableCount()} - 1</code>.
*
* @see #getColumnTypes(int)
*/
public Object[] getRowData(int rowIndex, int tableIndex) {
Object[] row = new Object[data[tableIndex].length];
for (int col=0; col<data[tableIndex].length; col++) {
row[col] = data[tableIndex][col][rowIndex];
}
return row;
}
/**
* Retrieve the given row of data from the named table.
*
* @see #getColumnTypes(String)
*/
public Object[] getRowData(int rowIndex, String tableName) {
int index = DataTools.indexOf(tableNames, tableName);
if (index < 0) {
return null;
}
return getRowData(rowIndex, index);
}
// -- Helper methods --
private void initialize() throws IOException, MetakitException {
String magic = stream.readString(2);
if (magic.equals("JL")) {
littleEndian = true;
}
else if (!magic.equals("LJ")) {
throw new MetakitException("Invalid magic string; got " + magic);
}
boolean valid = stream.read() == 26;
if (!valid) {
throw new MetakitException("'valid' flag was set to 'false'");
}
int headerType = stream.read();
if (headerType != 0) {
throw new MetakitException(
"Header type " + headerType + " is not valid.");
}
long footerPointer = stream.readInt() - 16;
stream.seek(footerPointer);
readFooter();
}
private void readFooter() throws IOException, MetakitException {
stream.skipBytes(4);
long headerLocation = stream.readInt();
stream.skipBytes(4);
long tocLocation = stream.readInt();
stream.seek(tocLocation);
readTOC();
}
private void readTOC() throws IOException, MetakitException {
int tocMarker = MetakitTools.readBpInt(stream);
String structureDefinition = MetakitTools.readPString(stream);
String[] tables = structureDefinition.split("],");
tableNames = new String[tables.length];
columns = new Column[tables.length][];
boolean[] hasSubviews = new boolean[tables.length];
for (int i=0; i<tables.length; i++) {
String table = tables[i];
int openBracket = table.indexOf("[");
tableNames[i] = table.substring(0, openBracket);
String columnList = table.substring(openBracket + 1);
openBracket = columnList.indexOf("[");
hasSubviews[i] = openBracket >= 0;
columnList = columnList.substring(openBracket + 1);
String[] cols = columnList.split(",");
columns[i] = new Column[cols.length];
for (int col=0; col<cols.length; col++) {
columns[i][col] = new Column(cols[col]);
}
}
rowCount = new int[tables.length];
MetakitTools.readBpInt(stream);
data = new Object[tables.length][][];
for (int table=0; table<tables.length; table++) {
MetakitTools.readBpInt(stream);
int pointer = MetakitTools.readBpInt(stream);
long fp = stream.getFilePointer();
stream.seek(pointer + 1);
rowCount[table] = MetakitTools.readBpInt(stream);
if (hasSubviews[table]) {
int subviewCount = rowCount[table];
long base = stream.getFilePointer();
rowCount[table] = 0;
Object[][][] subviewTable =
new Object[subviewCount][columns[table].length][];
for (int subview=0; subview<subviewCount; subview++) {
// read an IVecRef
if (subview == 0) {
int size = MetakitTools.readBpInt(stream);
long subviewPointer = MetakitTools.readBpInt(stream);
base = stream.getFilePointer();
stream.seek(subviewPointer);
}
MetakitTools.readBpInt(stream); // 0x80
int count = MetakitTools.readBpInt(stream);
if (count > 1) {
rowCount[table] += count;
for (int col=0; col<columns[table].length; col++) {
stream.order(littleEndian);
ColumnMap map = new ColumnMap(columns[table][col], stream, count);
subviewTable[subview][col] = map.getValues();
}
}
}
data[table] = new Object[columns[table].length][rowCount[table]];
int index = 0;
for (int subview=0; subview<subviewCount; subview++) {
if (subviewTable[subview][0] != null) {
for (int col=0; col<columns[table].length; col++) {
System.arraycopy(subviewTable[subview][col], 0, data[table][col],
index, subviewTable[subview][col].length);
}
index += subviewTable[subview][0].length;
}
}
}
else {
data[table] = new Object[columns[table].length][];
if (rowCount[table] > 0) {
for (int col=0; col<columns[table].length; col++) {
stream.order(littleEndian);
ColumnMap map =
new ColumnMap(columns[table][col], stream, rowCount[table]);
data[table][col] = map.getValues();
}
}
}
stream.seek(fp);
}
}
} |
KBUILD_CFLAGS := $(filter-out -O%,$(KBUILD_CFLAGS)) -O3
obj-$(CONFIG_CFG80211) += cfg80211.o
obj-$(CONFIG_LIB80211) += lib80211.o
obj-$(<API key>) += lib80211_crypt_wep.o
obj-$(<API key>) += lib80211_crypt_ccmp.o
obj-$(<API key>) += lib80211_crypt_tkip.o
obj-$(CONFIG_WEXT_CORE) += wext-core.o
obj-$(CONFIG_WEXT_PROC) += wext-proc.o
obj-$(CONFIG_WEXT_SPY) += wext-spy.o
obj-$(CONFIG_WEXT_PRIV) += wext-priv.o
cfg80211-y += core.o sysfs.o radiotap.o util.o reg.o scan.o nl80211.o
cfg80211-y += mlme.o ibss.o sme.o chan.o ethtool.o mesh.o ap.o trace.o
cfg80211-$(<API key>) += debugfs.o
cfg80211-$(<API key>) += wext-compat.o wext-sme.o
cfg80211-$(<API key>) += regdb.o
CFLAGS_trace.o := -I$(src)
ccflags-y += -D__CHECK_ENDIAN__
$(obj)/regdb.c: $(src)/db.txt $(src)/genregdb.awk
@$(AWK) -f $(srctree)/$(src)/genregdb.awk < $< > $@
clean-files := regdb.c |
# Makefile for kernel SPI drivers.
ccflags-$(CONFIG_SPI_DEBUG) := -DDEBUG
# small core, mostly translating board-specific
# config declarations into driver model code
obj-$(CONFIG_SPI_MASTER) += spi.o
obj-$(CONFIG_SPI_SPIDEV) += spidev.o
# SPI master controller drivers (bus)
obj-$(CONFIG_SPI_ALTERA) += spi-altera.o
obj-$(CONFIG_SPI_ATMEL) += spi-atmel.o
obj-$(CONFIG_SPI_ATH79) += spi-ath79.o
obj-$(CONFIG_SPI_AU1550) += spi-au1550.o
obj-$(CONFIG_SPI_BCM2835) += spi-bcm2835.o
obj-$(CONFIG_SPI_BCM63XX) += spi-bcm63xx.o
obj-$(<API key>) += spi-bcm63xx-hsspi.o
obj-$(CONFIG_SPI_BFIN5XX) += spi-bfin5xx.o
obj-$(CONFIG_SPI_BFIN_V3) += spi-bfin-v3.o
obj-$(<API key>) += spi-bfin-sport.o
obj-$(CONFIG_SPI_BITBANG) += spi-bitbang.o
obj-$(<API key>) += spi-butterfly.o
obj-$(CONFIG_SPI_CADENCE) += spi-cadence.o
obj-$(CONFIG_SPI_CLPS711X) += spi-clps711x.o
obj-$(<API key>) += spi-coldfire-qspi.o
obj-$(CONFIG_SPI_DAVINCI) += spi-davinci.o
obj-$(<API key>) += spi-dw.o
obj-$(CONFIG_SPI_DW_MMIO) += spi-dw-mmio.o
obj-$(CONFIG_SPI_DW_PCI) += spi-dw-midpci.o
spi-dw-midpci-objs := spi-dw-pci.o spi-dw-mid.o
obj-$(CONFIG_SPI_EFM32) += spi-efm32.o
obj-$(CONFIG_SPI_EP93XX) += spi-ep93xx.o
obj-$(CONFIG_SPI_FALCON) += spi-falcon.o
obj-$(CONFIG_SPI_FSL_CPM) += spi-fsl-cpm.o
obj-$(CONFIG_SPI_FSL_DSPI) += spi-fsl-dspi.o
obj-$(CONFIG_SPI_FSL_LIB) += spi-fsl-lib.o
obj-$(CONFIG_SPI_FSL_ESPI) += spi-fsl-espi.o
obj-$(CONFIG_SPI_FSL_SPI) += spi-fsl-spi.o
obj-$(CONFIG_SPI_GPIO) += spi-gpio.o
obj-$(CONFIG_SPI_IMX) += spi-imx.o
obj-$(CONFIG_SPI_LM70_LLP) += spi-lm70llp.o
obj-$(<API key>) += spi-mpc512x-psc.o
obj-$(<API key>) += spi-mpc52xx-psc.o
obj-$(CONFIG_SPI_MPC52xx) += spi-mpc52xx.o
obj-$(CONFIG_SPI_MXS) += spi-mxs.o
obj-$(CONFIG_SPI_NUC900) += spi-nuc900.o
obj-$(CONFIG_SPI_OC_TINY) += spi-oc-tiny.o
obj-$(CONFIG_SPI_OCTEON) += spi-octeon.o
obj-$(<API key>) += spi-omap-uwire.o
obj-$(<API key>) += spi-omap-100k.o
obj-$(CONFIG_SPI_OMAP24XX) += spi-omap2-mcspi.o
obj-$(CONFIG_SPI_TI_QSPI) += spi-ti-qspi.o
obj-$(CONFIG_SPI_ORION) += spi-orion.o
obj-$(CONFIG_SPI_PL022) += spi-pl022.o
obj-$(CONFIG_SPI_PPC4xx) += spi-ppc4xx.o
<API key> := spi-pxa2xx.o
spi-pxa2xx-platform-$(<API key>) += spi-pxa2xx-pxadma.o
spi-pxa2xx-platform-$(<API key>) += spi-pxa2xx-dma.o
obj-$(CONFIG_SPI_PXA2XX) += spi-pxa2xx-platform.o
obj-$(<API key>) += spi-pxa2xx-pci.o
obj-$(CONFIG_SPI_QUP) += spi-qup.o
obj-$(CONFIG_SPI_RSPI) += spi-rspi.o
obj-$(CONFIG_SPI_S3C24XX) += spi-s3c24xx-hw.o
spi-s3c24xx-hw-y := spi-s3c24xx.o
spi-s3c24xx-hw-$(<API key>) += spi-s3c24xx-fiq.o
obj-$(CONFIG_SPI_S3C64XX) += spi-s3c64xx.o
obj-$(<API key>) += spi-sc18is602.o
obj-$(CONFIG_SPI_SH) += spi-sh.o
obj-$(CONFIG_SPI_SH_HSPI) += spi-sh-hspi.o
obj-$(CONFIG_SPI_SH_MSIOF) += spi-sh-msiof.o
obj-$(CONFIG_SPI_SH_SCI) += spi-sh-sci.o
obj-$(CONFIG_SPI_SIRF) += spi-sirf.o
obj-$(CONFIG_SPI_SUN4I) += spi-sun4i.o
obj-$(CONFIG_SPI_SUN6I) += spi-sun6i.o
obj-$(CONFIG_SPI_TEGRA114) += spi-tegra114.o
obj-$(<API key>) += spi-tegra20-sflash.o
obj-$(<API key>) += spi-tegra20-slink.o
obj-$(CONFIG_SPI_TLE62X0) += spi-tle62x0.o
obj-$(<API key>) += spi-topcliff-pch.o
obj-$(CONFIG_SPI_TXX9) += spi-txx9.o
obj-$(CONFIG_SPI_XCOMM) += spi-xcomm.o
obj-$(<API key>) += spi-ad9250fmc.o
obj-$(CONFIG_SPI_XILINX) += spi-xilinx.o
obj-$(<API key>) += spi-xtensa-xtfpga.o
obj-$(<API key>) += spi-zynq-qspi.o |
/** @var Root URI for theme files */
var <API key> = "";
/** @var The AJAX proxy URL */
var akeeba_ajax_url = "";
/** @var Current backup job's tag */
var akeeba_backup_tag = 'backend';
/** @var The callback function to call on error */
var <API key> = dummy_error_handler;
/** @var A URL to return to upon successful backup */
var akeeba_return_url = '';
/** @var The translation strings used in the GUI */
var akeeba_translations = new Array();
akeeba_translations['UI-BROWSE'] = 'Browse...';
akeeba_translations['UI-CONFIG'] = 'Configure...';
akeeba_translations['UI-LASTRESPONSE'] = 'Last server response %ss ago';
akeeba_translations['UI-ROOT'] = '<root>';
akeeba_translations['UI-ERROR-FILTER'] = 'An error occured while applying the filter for "%s"';
/** @var Engine definitions array */
var akeeba_engines = new Array();
/** @var Installers definitions array */
var akeeba_installers = new Array();
/** @var The function used to show the directory browser. Takes two params: starting_directory, input_element */
var akeeba_browser_hook = null;
/** @var An array of domains and descriptions, used during backup */
var akeeba_domains = null;
/** @var A function which causes the visual comment editor to save its contents */
var <API key> = null;
/** @var Maximum execution time per step (in msec) */
var <API key> = 14000;
/** @var Maximum execution time per step bias (in percentage units, 0 to 100) */
var akeeba_time_bias = 75;
/** @var Used for filter reset operations */
var akeeba_current_root = '';
/** @var iFrame pseudo-AJAX success callback */
var <API key> = null;
/** @var iFrame pseudo-AJAX error callback */
var <API key> = null;
/** @var iFrame pseudo-AJAX IFRAME element */
var akeeba_iframe = null;
/** @var Should I use IFRAME instead of regular AJAX calls? */
var akeeba_use_iframe = false;
//Akeeba Backup -- Common functions
/**
* An extremely simple error handler, dumping error messages to screen
* @param error The error message string
*/
function dummy_error_handler(error)
{
alert("An error has occured\n"+error);
}
/**
* Poor man's AJAX, using IFRAME elements
* @param data An object with the query data, e.g. a serialized form
* @param successCallback A function accepting a single object parameter, called on success
*/
function doIframeCall(data, successCallback, errorCallback)
{
(function($) {
<API key> = successCallback;
<API key> = errorCallback;
akeeba_iframe = document.createElement('iframe');
$(akeeba_iframe)
.css({
'display' : 'none',
'visibility' : 'hidden',
'height' : '1px'
})
.attr('onload','cbIframeCall()')
.insertAfter('#response-timer');
var url = akeeba_ajax_url + '&' + $.param(data);
$(akeeba_iframe).attr('src',url);
})(akeeba.jQuery);
}
/**
* Poor man's AJAX, using IFRAME elements: the callback function
*/
function cbIframeCall()
{
(function($) {
// Get the contents of the iFrame
var iframeDoc = null;
if (akeeba_iframe.contentDocument) {
iframeDoc = akeeba_iframe.contentDocument; // The rest of the world
} else {
iframeDoc = akeeba_iframe.contentWindow.document; // IE on Windows
}
var msg = iframeDoc.body.innerHTML;
// Dispose of the iframe
$(akeeba_iframe).remove();
akeeba_iframe = null;
// Start processing the message
var junk = null;
var message = "";
// Get rid of junk before the data
var valid_pos = msg.indexOf('
if( valid_pos == -1 ) {
// Valid data not found in the response
msg = 'Invalid AJAX data: ' + msg;
if(<API key> == null)
{
if(<API key> != null)
{
<API key>(msg);
}
}
else
{
<API key>(msg);
}
return;
} else if( valid_pos != 0 ) {
// Data is prefixed with junk
junk = msg.substr(0, valid_pos);
message = msg.substr(valid_pos);
}
else
{
message = msg;
}
message = message.substr(3); // Remove triple hash in the beginning
// Get of rid of junk after the data
var valid_pos = message.lastIndexOf('
message = message.substr(0, valid_pos); // Remove triple hash in the end
try {
var data = JSON.parse(message);
} catch(err) {
var msg = err.message + "\n<br/>\n<pre>\n" + message + "\n</pre>";
if(<API key> == null)
{
if(<API key> != null)
{
<API key>(msg);
}
}
else
{
<API key>(msg);
}
return;
}
// Call the callback function
<API key>(data);
})(akeeba.jQuery);
}
/**
* Performs an AJAX request and returns the parsed JSON output.
* The global akeeba_ajax_url is used as the AJAX proxy URL.
* If there is no errorCallback, the global <API key> is used.
* @param data An object with the query data, e.g. a serialized form
* @param successCallback A function accepting a single object parameter, called on success
* @param errorCallback A function accepting a single string parameter, called on failure
*/
function doAjax(data, successCallback, errorCallback, useCaching)
{
if(akeeba_use_iframe) {
doIframeCall(data, successCallback, errorCallback)
return;
}
if(useCaching == null) useCaching = true;
(function($) {
var structure =
{
type: "POST",
url: akeeba_ajax_url,
cache: false,
data: data,
timeout: 600000,
success: function(msg) {
// Initialize
var junk = null;
var message = "";
// Get rid of junk before the data
var valid_pos = msg.indexOf('
if( valid_pos == -1 ) {
// Valid data not found in the response
msg = 'Invalid AJAX data: ' + msg;
if(errorCallback == null)
{
if(<API key> != null)
{
<API key>(msg);
}
}
else
{
errorCallback(msg);
}
return;
} else if( valid_pos != 0 ) {
// Data is prefixed with junk
junk = msg.substr(0, valid_pos);
message = msg.substr(valid_pos);
}
else
{
message = msg;
}
message = message.substr(3); // Remove triple hash in the beginning
// Get of rid of junk after the data
var valid_pos = message.lastIndexOf('
message = message.substr(0, valid_pos); // Remove triple hash in the end
try {
var data = JSON.parse(message);
} catch(err) {
var msg = err.message + "\n<br/>\n<pre>\n" + message + "\n</pre>";
if(errorCallback == null)
{
if(<API key> != null)
{
<API key>(msg);
}
}
else
{
errorCallback(msg);
}
return;
}
// Call the callback function
successCallback(data);
},
error: function(Request, textStatus, errorThrown) {
var message = '<strong>AJAX Loading Error</strong><br/>HTTP Status: '+Request.status+' ('+Request.statusText+')<br/>';
message = message + 'Internal status: '+textStatus+'<br/>';
message = message + 'XHR ReadyState: ' + Request.readyState + '<br/>';
message = message + 'Raw server response:<br/>'+Request.responseText;
if(errorCallback == null)
{
if(<API key> != null)
{
<API key>(message);
}
}
else
{
errorCallback(message);
}
}
};
if(useCaching)
{
$.manageAjax.add('akeeba-ajax-profile', structure);
}
else
{
$.ajax( structure );
}
})(akeeba.jQuery);
}
//Akeeba Backup -- Configuration page
/**
* Parses the JSON decoded data object defining engine and GUI parameters for the
* configuration page
* @param data The nested objects of engine and GUI definitions
*/
function parse_config_data(data)
{
<API key>(data.engines);
<API key>(data.installers);
<API key>(data.gui);
}
/**
* Parses the engine definition data passed from Akeeba Engine to the UI via JSON
* @param data Nested objects of engine definitions
*/
function <API key>(data)
{
// As simple as it can possibly be!
akeeba_engines = data;
}
/**
* Parses the installer definition data passed from Akeeba Engine to the UI via JSON
* @param data Nested objects of installer definitions
*/
function <API key>(data)
{
akeeba_installers = data;
}
/**
* Parses the main configuration GUI definition, generating the on-page widgets
* @param data The nested objects of the GUI definition ('gui' key of JSON data)
* @param rootnode The jQuery extended root DOM element in which to create the widgets
*/
function <API key>(data, rootnode)
{
(function($) {
if(rootnode == null)
{
// The default root node is the form itself
rootnode = $('#akeebagui');
}
// Begin by slashing contents of the akeebagui DIV
rootnode.empty();
// This is the workhorse, looping through groupdefs and creating HTML elements
var group_id = 0;
$.each(data,function(headertext, groupdef) {
// Loop for each group definition
group_id++;
// Create a fieldset container
var container = $( document.createElement('fieldset') );
container.addClass('ui-corner-all');
container.appendTo( rootnode );
// Create a group header
var header = $( document.createElement('div') );
header.attr('id', 'auigrp_'+rootnode.attr('id')+'_'+group_id);
header.addClass('ui-widget-header').addClass('<API key>');
header.html(headertext);
header.appendTo(container);
// Loop each element
$.each(groupdef, function(config_key, defdata){
// Parameter ID
var current_id = 'var['+config_key+']';
// Option row DIV
var row_div = $(document.createElement('div')).addClass('akeeba-ui-optionrow');
row_div.appendTo(container);
// Create label
var label = $(document.createElement('label'));
label.attr('for', current_id);
label.html( defdata['title'] );
label.tooltip({
track: true,
delay: 0,
showURL: false,
opacity: 1,
fixPNG: true,
fade: 0,
extraClass: 'ui-dialog ui-corner-all',
bodyHandler: function() {
var title = $(this).html();
var description = defdata['description'];
var html = '<h3><div class="ui-icon ui-icon-info"></div><span>'+title+'</span></h3>';
html += '<div>'+description+'</div>';
return html;
}
});
label.appendTo( row_div );
// Create GUI representation based on type
switch( defdata['type'] )
{
// An installer selection
case 'installer':
// Create the select element
var editor = $(document.createElement('select')).attr({
id: current_id,
name: current_id
});
$.each(akeeba_installers, function(key, element){
var option = $(document.createElement('option')).attr('value', key).html(element.name);
if( defdata['default'] == key ) option.attr('selected',1);
option.appendTo( editor );
});
editor.appendTo( row_div );
break;
// An engine selection
case 'engine':
var engine_type = defdata['subtype'];
if( akeeba_engines[engine_type] == null ) break;
// Container for engine parameters, initially hidden
var <API key> = $(document.createElement('div')).attr({
id: config_key+'_config'
}).addClass('ui-helper-hidden').appendTo( container );
// Container for selection & button
var span = $(document.createElement('span'));
span.appendTo( row_div );
// Create the select element
var editor = $(document.createElement('select')).attr({
id: current_id,
name: current_id
});
$.each(akeeba_engines[engine_type], function(key, element){
var option = $(document.createElement('option')).attr('value', key).html(element.information.title);
if( defdata['default'] == key ) option.attr('selected',1);
option.appendTo( editor );
});
editor.bind("change",function(e){
// When the selection changes, we have to repopulate the config container
// First, save any changed values
var old_values = new Object;
$(<API key>).find('input').each(function(i){
if( $(this).attr('type') == 'checkbox' )
{
old_values[$(this).attr('id')] = $(this).is(':checked');
}
else
{
old_values[$(this).attr('id')] = $(this).val();
}
});
// Create the new interface
var new_engine = $(this).val();
var enginedef = akeeba_engines[engine_type][new_engine];
var enginetitle = enginedef.information.title;
var new_data = new Object;
var engine_params = enginedef.parameters;
new_data[enginetitle] = engine_params;
<API key>(new_data, <API key>);
$(<API key>)
.find('.<API key>:first')
.after(
$(document.createElement('p'))
.html(enginedef.information.description)
);
// Reapply changed values
<API key>.find('input').each(function(i){
var old = old_values[$(this).attr('id')];
if( (old != null) && (old != undefined) )
{
if( $(this).attr('type') == 'checkbox' )
{ $(this).attr('checked', old); }
else if ( $(this).attr('type') == 'hidden' )
{
$(this).next().next().slider( 'value' , old );
}
else
{ $(this).val(old); }
}
});
});
editor.appendTo( span );
// Add a configuration show/hide button
var button = $(document.createElement('button')).addClass('ui-state-default').html(akeeba_translations['UI-CONFIG']);
button.bind('click', function(e){
<API key>.toggleClass('ui-helper-hidden');
e.preventDefault();
});
button.appendTo( span );
// Populate config container with the default engine data
if(akeeba_engines[engine_type][defdata['default']] != null)
{
var new_engine = defdata['default'];
var enginedef = akeeba_engines[engine_type][new_engine];
var enginetitle = enginedef.information.title;
var new_data = new Object;
var engine_params = enginedef.parameters;
new_data[enginetitle] = engine_params;
<API key>(new_data, <API key>);
$(<API key>)
.find('.<API key>:first')
.after(
$(document.createElement('p'))
.html(enginedef.information.description)
);
}
break;
// A text box with an option to launch a browser
case 'browsedir':
var editor = $(document.createElement('input')).attr({
type: 'text',
id: current_id,
name: current_id,
size: '30',
value: defdata['default']
});
var button = $(document.createElement('button')).addClass('ui-state-default').html(akeeba_translations['UI-BROWSE']);
button.bind('click',function(event){
event.preventDefault();
if( akeeba_browser_hook != null ) akeeba_browser_hook( editor.val(), editor );
});
var span = $(document.createElement('span'));
editor.appendTo( span );
button.appendTo( span );
span.appendTo(row_div);
break;
// A drop-down list
case 'enum':
var editor = $(document.createElement('select')).attr({
id: current_id,
name: current_id
});
// Create and append options
var enumvalues = defdata['enumvalues'].split("|");
var enumkeys = defdata['enumkeys'].split("|");
$.each(enumvalues, function(counter, value){
var item_description = enumkeys[counter];
var option = $(document.createElement('option')).attr('value', value).html(item_description);
if(value == defdata['default']) option.attr('selected',1);
option.appendTo( editor );
});
editor.appendTo( row_div );
break;
// A simple single-line, unvalidated text box
case 'string':
var editor = $(document.createElement('input')).attr({
type: 'text',
id: current_id,
name: current_id,
size: '40',
value: defdata['default']
});
editor.appendTo( row_div );
break;
// An integer slider
case 'integer':
// Hidden form element which echoes slider's value
var hidden_input = $(document.createElement('input')).attr({
id: current_id,
name: current_id,
type: 'hidden'
}).val(defdata['default']);
hidden_input.appendTo( row_div );
// A label to display the current setting
var notify_label = $(document.createElement('div')).attr({
id: config_key+'_ticker'
}).addClass('ui-widget-content').addClass('<API key>').addClass('ui-corner-all');
notify_label.appendTo( row_div );
// Slider widget
var wrapper_div = $(document.createElement('div'));
var slider_div = $(document.createElement('div')).attr('id',config_key+'_slider');
function fix_slider() {
slider_div.parent()
.stop()
.css({
padding: '0',
top: '0',
bottom: '0',
overflow: 'visible',
height: '24px'
});
slider_div
.stop()
.css({
display: 'block',
margin: '0',
padding: '0',
top: '0',
bottom: '0',
overflow: 'visible',
height: '0.8em'
});
}
function <API key>(event, ui, hack)
{
var display_value = null;
if(hack == null)
{
display_value = ui.value;
}
else
{
display_value = ui.slider('option', 'value');
}
hidden_input.val(display_value);
var uom = defdata['uom'];
if( typeof(uom) != 'string' ) {
uom = '';
} else {
uom = ' '+uom;
}
if( Math.floor(defdata['scale']) == defdata['scale'] ) display_value = display_value / defdata['scale'];
notify_label.html(display_value.toFixed(2) + uom);
fix_slider();
}
slider_div.slider({
animate: 'fast',
max: Number(defdata['max']),
min: Number(defdata['min']),
orientation: 'horizontal',
step: Number(defdata['every']),
change: <API key>,
slide: <API key>,
value: Number(defdata['default'])
});
// Thank you MooTools 2.4 for screwing me. I really appreciate it... NOT!
slider_div.hover(fix_slider, fix_slider);
slider_div.mousemove(fix_slider);
slider_div.mouseover(fix_slider);
slider_div.keyup(fix_slider);
slider_div.blur(fix_slider);
slider_div.appendTo(wrapper_div);
wrapper_div.addClass('akeeba-ui-slider');
wrapper_div.appendTo( row_div );
<API key>(null, slider_div, true);
break;
// A toggle button (stylized checkbox)
case 'bool':
var wrap_div = $(document.createElement('div')).addClass('akeeba-ui-checkbox');
// This hack is required in order to "submit" unchecked checkboxes with a value of 0...
$(document.createElement('input')).attr({
name: current_id,
type: 'hidden',
value: 0
}).appendTo( wrap_div );
// ...and let checked checkboxes post a value equal to 1.
var editor = $(document.createElement('input')).attr({
id: current_id,
name: current_id,
type: 'checkbox',
value: 1
});
if( defdata['default'] != 0 ) editor.attr('checked','checked');
editor.appendTo( wrap_div );
editor.checkbox({
cls: '<API key>',
empty: <API key>+'images/empty.png'
});
wrap_div.appendTo( row_div );
break;
// Button with a custom hook function
case 'button':
// Create the button
var hook = defdata['hook'];
var editor = $(document.createElement('button')).addClass('ui-state-default').attr('id', current_id).html(label.html());
label.html(' ');
editor.hover(
function(){$(this).addClass('ui-state-hover');},
function(){$(this).removeClass('ui-state-hover');}
);
editor.bind('click', function(e){
e.preventDefault();
try {
eval(hook+'()');
} catch(err) {}
});
editor.appendTo( row_div );
break;
}
});
});
})(akeeba.jQuery);
}
//Akeeba Backup -- Backup Now page
function set_ajax_timer()
{
setTimeout('<API key>()', 10);
}
function <API key>()
{
(function($){
doAjax({
// Data to send to AJAX
'ajax' : 'step',
'tag' : akeeba_backup_tag
}, backup_step, backup_error, false );
})(akeeba.jQuery);
}
function start_timeout_bar(max_allowance, bias)
{
(function($) {
var lastResponseSeconds = 0;
$('#response-timer div.text').everyTime(1000, 'lastReponse', function(){
lastResponseSeconds++;
var lastText = akeeba_translations['UI-LASTRESPONSE'].replace('%s', lastResponseSeconds.toFixed(0));
$('#response-timer div.text').html(lastText);
});
var maximum_time = 180000;
var green_time = Number(max_allowance) * (Number(bias) / 100);
var yellow_time = Number(max_allowance) - green_time;
var green_percentage = Number((green_time / maximum_time) * 100).toFixed(2)+'%';
var yellow_percentage = Number((Number(max_allowance) / maximum_time ) * 100).toFixed(2)+'%';
$('div.color-overlay')
.css({
backgroundColor: '#00cc00'
})
.animate({
width: green_percentage
}, green_time, 'none', function() {
$('div.color-overlay').animate({
backgroundColor: '#cccc00'
},{easing: 'none', duration: 1000, queue: false});
})
.animate({
width: yellow_percentage
}, yellow_time, 'none', function() {
$('div.color-overlay').animate({
backgroundColor: '#ff9999'
},{easing: 'none', duration: 1000, queue: false});
})
.animate({
width: '100%'
}, maximum_time - Number(max_allowance), 'none', function() {
$('#response-timer div.text').stopTime('lastReponse');
// TODO Issue a backup failure (more than 3min have passed)
})
.animate({
backgroundColor: '#cc0000'
}, {easing: 'none', duration: 2000});
})(akeeba.jQuery);
}
function reset_timeout_bar()
{
(function($){
$('#response-timer div.text').stopTime();
$('div.color-overlay').stop(true);
$('div.color-overlay')
.css({
backgroundColor: '#00cc00',
width: '1px'
});
var lastText = akeeba_translations['UI-LASTRESPONSE'].replace('%s', '0');
$('#response-timer div.text').html(lastText);
})(akeeba.jQuery);
}
function render_backup_steps(active_step)
{
(function($){
var normal_class = 'step-complete';
if( active_step == '' ) normal_class = 'step-pending';
$('#backup-steps').html('');
$.each(akeeba_domains, function(counter, element){
var step = $(document.createElement('div'))
.html(element[1])
.data('domain',element[0])
.appendTo('#backup-steps');
if(step.data('domain') == active_step )
{
normal_class = 'step-pending';
this_class = 'step-active';
}
else
{
this_class = normal_class;
}
step.attr({
'class': this_class
});
});
})(akeeba.jQuery);
}
function backup_start()
{
(function($){
// Save the editor contents
try {
if( <API key> != null ) <API key>();
} catch(err) {
// If the editor failed to save its content, just move on and ignore the error
$('#comment').val("");
}
// Get encryption key (if applicable)
var jpskey = '';
try {
jpskey = $('#jpskey').val();
} catch(err) {
jpskey = '';
}
// Hide the backup setup
$('#backup-setup').hide("fast");
// Show the backup progress
$('#<API key>').show("fast");
// Initialize steps
render_backup_steps('');
// Start the response timer
start_timeout_bar(<API key>, akeeba_time_bias);
// Perform Ajax request
akeeba_backup_tag = 'backend';
doAjax({
// Data to send to AJAX
'ajax': 'start',
description: $('#backup-description').val(),
comment: $('#comment').val(),
jpskey: jpskey
}, backup_step, backup_error, false );
})(akeeba.jQuery);
}
function backup_step(data)
{
// Update visual step progress from active domain data
reset_timeout_bar();
render_backup_steps(data.Domain);
(function($){
// Update step/substep display
$('#backup-step').html(data.Step);
$('#backup-substep').html(data.Substep);
// Do we have warnings?
if( data.Warnings.length > 0 )
{
$.each(data.Warnings, function(i, warning){
var newDiv = $(document.createElement('div'))
.html(warning)
.appendTo( $('#warnings-list') );
});
if( $('#<API key>').is(":hidden") )
{
$('#<API key>').show('fast');
}
}
// Do we have errors?
var error_message = data.Error;
if(error_message != '')
{
// Uh-oh! An error has occurred.
backup_error(error_message);
return;
}
else
{
// No errors. Good! Are we finished yet?
if(data["HasRun"] == 1)
{
// Yes. Show backup completion page.
backup_complete();
}
else
{
// No. Set the backup tag
akeeba_backup_tag = data.tag;
if(empty(akeeba_backup_tag)) akeeba_backup_tag = 'backend';
// Start the response timer...
start_timeout_bar(<API key>, akeeba_time_bias);
// ...and send an AJAX command
set_ajax_timer();
}
}
})(akeeba.jQuery);
}
function backup_error(message)
{
(function($){
// Make sure the timer is stopped
reset_timeout_bar();
// Hide progress and warnings
$('#<API key>').hide("fast");
$('#<API key>').hide("fast");
// Setup and show error pane
$('#<API key>').html(message);
$('#error-panel').show();
})(akeeba.jQuery);
}
function backup_complete()
{
(function($){
// Make sure the timer is stopped
reset_timeout_bar();
// Hide progress
$('#<API key>').hide("fast");
// Show finished pane
$('#backup-complete').show();
$('#<API key>').width('100%');
// Proceed to the return URL if it is set
if(akeeba_return_url != '')
{
window.location = akeeba_return_url;
}
})(akeeba.jQuery);
}
//Akeeba Backup -- Filesystem Filters (direct)
/**
* Loads the contents of a directory
* @param data
* @return
*/
function fsfilter_load(data)
{
// Add the verb to the data
data.verb = 'list';
// Convert to JSON
var json = JSON.stringify(data);
// Assemble the data array and send the AJAX request
var new_data = new Object;
new_data.action = json;
doAjax(new_data, function(response){
fsfilter_render(response);
});
}
/**
* Toggles a filesystem filter
* @param data
* @param caller
* @return
*/
function fsfilter_toggle(data, caller, callback, use_inner_child)
{
if(use_inner_child == null) use_inner_child = true;
(function($){
// Make the icon spin
if(caller != null)
{
// Do not allow multiple simultaneous AJAX requests on the same object
if( caller.data('loading') == true ) return;
caller.data('loading', true);
if(use_inner_child) {
var icon_span = caller.children('span:first');
} else {
var icon_span = caller;
}
caller.data('icon', icon_span.attr('class') );
icon_span.removeClass(caller.data('icon'));
icon_span.addClass('ui-icon');
icon_span.addClass('<API key>');
icon_span.everyTime(100, 'spinner', function(){
if(icon_span.hasClass('<API key>'))
{
icon_span.removeClass('<API key>');
icon_span.addClass('<API key>');
} else
if(icon_span.hasClass('<API key>'))
{
icon_span.removeClass('<API key>');
icon_span.addClass('<API key>');
} else
if(icon_span.hasClass('<API key>'))
{
icon_span.removeClass('<API key>');
icon_span.addClass('<API key>');
} else
{
icon_span.removeClass('<API key>');
icon_span.addClass('<API key>');
}
});
}
// Convert to JSON
var json = JSON.stringify(data);
// Assemble the data array and send the AJAX request
var new_data = new Object;
new_data.action = json;
doAjax(new_data, function(response){
if(caller != null)
{
icon_span.stopTime();
icon_span.attr('class', caller.data('icon'));
caller.removeData('icon');
caller.removeData('loading');
}
if( response.success == true )
{
if(caller != null)
{
if(use_inner_child)
{
// Update the on-screen filter state
if(response.newstate == true)
{
caller.removeClass('ui-state-normal');
caller.addClass('ui-state-highlight');
}
else
{
caller.addClass('ui-state-normal');
caller.removeClass('ui-state-highlight');
}
}
}
if(!(callback == null)) callback(response, caller);
}
else
{
if(!(callback == null)) callback(response, caller);
// An error occured
var dialog_element = $("#dialog");
dialog_element.html(''); // Clear the dialog's contents
$(document.createElement('p')).html(akeeba_translations['UI-ERROR-FILTER'].replace('%s', data.node)).appendTo(dialog_element);
dialog_element.dialog('open');
}
}, function(msg){
// Error handler
if(caller != null)
{
icon_span.stopTime();
icon_span.attr('class', caller.data('icon'));
caller.removeData('icon');
caller.removeData('loading');
}
<API key>(msg);
});
})(akeeba.jQuery);
}
/**
* Renders the Filesystem Filters page
* @param data
* @return
*/
function fsfilter_render(data)
{
akeeba_current_root = data.root;
(function($){
// Create a new crumbs data array
var crumbsdata = new Array;
// Push the "navigate to root" element
var newCrumb = new Array;
newCrumb[0] = akeeba_translations['UI-ROOT']; // [0] : UI Label
newCrumb[1] = data.root; // [1] : Root node
newCrumb[2] = new Array; // [2] : Crumbs to current directory
newCrumb[3] = ''; // [3] : Node element
crumbsdata.push(newCrumb);
// Iterate existing crumbs
if(data.crumbs.length > 0)
{
var crumbs = new Array;
$.each(data.crumbs,function(counter, crumb) {
var newCrumb = new Array;
newCrumb[0] = crumb;
newCrumb[1] = data.root;
newCrumb[2] = crumbs.slice(0); // Otherwise it is copied by reference
newCrumb[3] = crumb;
crumbsdata.push(newCrumb);
crumbs.push(crumb); // Push this dir into the crumb list
});
}
// Render the UI crumbs elements
var akcrumbs = $('#ak_crumbs');
akcrumbs.html('');
$.each(crumbsdata, function(counter, def){
$(document.createElement('span'))
.html(def[0])
.attr('class', 'ui-state-default')
.hover(
function(){$(this).addClass('ui-state-hover');},
function(){$(this).removeClass('ui-state-hover');}
)
.click(function(){
$(this).append(
$(document.createElement('img'))
.attr('src', <API key>+'../icons/loading.gif')
.attr({
width: 16,
height: 11,
border: 0,
alt: 'Loading...'
})
.css({
marginTop: '5px',
marginLeft: '5px'
})
);
var new_data = new Object;
new_data.root = def[1];
new_data.crumbs = def[2];
new_data.node = def[3];
fsfilter_load(new_data);
})
.appendTo(akcrumbs);
if(counter < (crumbsdata.length-1) ) akcrumbs.append(' • ');
});
var akfolders = $('#folders');
akfolders.html('');
if(data.crumbs.length > 0)
{
// The parent directory element
var uielement = $(document.createElement('div'))
.addClass('folder-container');
uielement
.append($(document.createElement('span')).addClass('folder-padding'))
.append($(document.createElement('span')).addClass('folder-padding'))
.append($(document.createElement('span')).addClass('folder-padding'))
.append(
$(document.createElement('span'))
.addClass('folder-name folder-up')
.html('('+akcrumbs.find('span:last').prev().html()+')')
.prepend(
$(document.createElement('span'))
.addClass('ui-icon <API key>')
)
.click(function(){
akcrumbs.find('span:last').prev().click();
})
)
.appendTo(akfolders);
}
$.each(data.folders, function(folder, def){
var uielement = $(document.createElement('div'))
.addClass('folder-container');
var available_filters = new Array;
available_filters.push('directories');
available_filters.push('skipdirs');
available_filters.push('skipfiles');
$.each(available_filters, function(counter, filter){
var ui_icon = $(document.createElement('span')).addClass('<API key>');
switch(filter)
{
case 'directories':
ui_icon.append('<span class="ui-icon ui-icon-cancel"></span>');
break;
case 'skipdirs':
ui_icon.append('<span class="ui-icon ui-icon-folder-open"></span>');
break;
case 'skipfiles':
ui_icon.append('<span class="ui-icon ui-icon-document"></span>');
break;
}
ui_icon.tooltip({
track: false,
delay: 0,
showURL: false,
opacity: 1,
fixPNG: true,
fade: 0,
extraClass: 'ui-dialog ui-corner-all',
bodyHandler: function() {
html = '<div>'+akeeba_translations['UI-FILTERTYPE-'+filter.toUpperCase()]+'</div>';
return html;
}
});
switch(def[filter])
{
case 2:
ui_icon.addClass('ui-state-error');
break;
case 1:
ui_icon.addClass('ui-state-highlight');
// Don't break; we have to add the handler!
case 0:
ui_icon.click(function(){
var new_data = new Object;
new_data.root = data.root;
new_data.crumbs = crumbs;
new_data.node = folder;
new_data.filter = filter;
new_data.verb = 'toggle';
fsfilter_toggle(new_data, ui_icon);
});
}
ui_icon.appendTo(uielement);
}); // filter loop
// Add the folder label and make clicking on it load its listing
$(document.createElement('span'))
.html(folder)
.addClass('folder-name')
.click(function(){
// Show "loading" animation
$(this).append(
$(document.createElement('img'))
.attr('src', <API key>+'../icons/loading.gif')
.attr({
width: 16,
height: 11,
border: 0,
alt: 'Loading...'
})
.css({
marginTop: '3px',
marginLeft: '5px'
})
);
var new_data = new Object;
new_data.root = data.root;
new_data.crumbs = crumbs;
new_data.node = folder;
fsfilter_load(new_data);
})
.appendTo(uielement);
// Render
uielement.appendTo(akfolders);
});
var akfiles = $('#files');
akfiles.html('');
$.each(data.files, function(file, def){
var uielement = $(document.createElement('div'))
.addClass('file-container');
var available_filters = new Array;
available_filters.push('files');
$.each(available_filters, function(counter, filter){
var ui_icon = $(document.createElement('span')).addClass('file-icon-container');
switch(filter)
{
case 'files':
ui_icon.append('<span class="ui-icon ui-icon-cancel"></span>');
break;
}
ui_icon.tooltip({
track: false,
delay: 0,
showURL: false,
opacity: 1,
fixPNG: true,
fade: 0,
extraClass: 'ui-dialog ui-corner-all',
bodyHandler: function() {
html = '<div>'+akeeba_translations['UI-FILTERTYPE-'+filter.toUpperCase()]+'</div>';
return html;
}
});
switch(def[filter])
{
case 2:
ui_icon.addClass('ui-state-error');
break;
case 1:
ui_icon.addClass('ui-state-highlight');
// Don't break; we have to add the handler!
case 0:
ui_icon.click(function(){
var new_data = new Object;
new_data.root = data.root;
new_data.crumbs = crumbs;
new_data.node = file;
new_data.filter = filter;
new_data.verb = 'toggle';
fsfilter_toggle(new_data, ui_icon);
});
}
ui_icon.appendTo(uielement);
}); // filter loop
// Add the file label
uielement
.append(
$(document.createElement('span'))
.addClass('file-name')
.html(file)
)
.append(
$(document.createElement('span'))
.addClass('file-size')
.html(size_format(def['size']))
);
// Render
uielement.appendTo(akfiles);
});
})(akeeba.jQuery);
}
/**
* Loads the tabular view of the Filesystems Filter for a given root
* @param root
* @return
*/
function fsfilter_load_tab(root)
{
var data = new Object;
data.verb = 'tab';
data.root = root;
// Convert to JSON
var json = JSON.stringify(data);
// Assemble the data array and send the AJAX request
var new_data = new Object;
new_data.action = json;
doAjax(new_data, function(response){
fsfilter_render_tab(response);
});
}
/**
* Add a row in the tabular view of the Filesystems Filter
* @param def
* @param append_to_here
* @return
*/
function fsfilter_add_row(def, append_to_here)
{
(function($){
// Turn def.type into something human readable
var type_text = akeeba_translations['UI-FILTERTYPE-'+def.type.toUpperCase()];
if(type_text == null) type_text = def.type;
$(document.createElement('tr'))
.addClass('ak_filter_row')
.append(
// Filter title
$(document.createElement('td'))
.addClass('ak_filter_type')
.append(
$(document.createElement('span'))
.addClass('ui-icon ui-icon-circle-plus addnew')
.click(function(){
// Add a row below ourselves
var new_def = new Object;
new_def.type = def.type;
new_def.node = '';
fsfilter_add_row(new_def, $(this).parent().parent().parent() );
$(this).parent().parent().parent().children('tr:last').children('td:last').children('span.<API key>:last').click();
})
)
.append(type_text)
)
.append(
$(document.createElement('td'))
.addClass('ak_filter_item')
.append(
$(document.createElement('span'))
.addClass('<API key>')
.click(function(){
if( def.node == '' )
{
// An empty filter is normally not saved to the database; it's a new record row which has to be removed...
$(this).parent().parent().remove();
return;
}
var new_data = new Object;
new_data.root = $('#active_root').val();
new_data.crumbs = new Array();
new_data.node = def.node;
new_data.filter = def.type;
new_data.verb = 'toggle';
fsfilter_toggle(new_data, $(this), function(response, caller){
if(response.success)
{
caller.parent().parent().remove();
}
});
})
.append(
$(document.createElement('span'))
.addClass('ui-icon ui-icon-trash deletebutton')
)
)
.append(
$(document.createElement('span'))
.addClass('<API key>')
.click(function(){
if( $(this).siblings('span.<API key>:first').next().data('editing') ) return;
$(this).siblings('span.<API key>:first').next().data('editing',true);
$(this).next().hide();
$(document.createElement('input'))
.attr({
type: 'text',
size: 60
})
.val( $(this).next().html() )
.appendTo( $(this).parent() )
.blur(function(){
var new_value = $(this).val();
if(new_value == '')
{
// Well, if the user meant to remove the filter, let's help him!
$(this).parent().children('span.ak_filter_name').show();
$(this).siblings('span.<API key>').find('span.deletebutton').click();
$(this).remove();
return;
}
// First, remove the old filter
var new_data = new Object;
new_data.root = $('#active_root').val();
new_data.crumbs = new Array();
new_data.old_node = def.node;
new_data.new_node = new_value;
new_data.filter = def.type;
new_data.verb = 'swap';
var input_box = $(this);
fsfilter_toggle(new_data,
input_box.siblings('span.<API key>:first').next(),
function(response, caller){
// Remove the editor
input_box.siblings('span.<API key>:first').next().removeData('editing');
input_box.parent().find('span.ak_filter_name').show();
input_box.siblings('span.<API key>:first').next().removeClass('ui-state-highlight');
input_box.parent().find('span.ak_filter_name').html( new_value );
input_box.remove();
}
);
})
.focus();
})
.append(
$(document.createElement('span'))
.addClass('ui-icon ui-icon-pencil editbutton')
)
)
.append(
$(document.createElement('span'))
.addClass('ak_filter_name')
.html(def.node)
)
)
.appendTo( $(append_to_here) );
})(akeeba.jQuery);
}
/**
* Renders the tabular view of the Filesystems Filter
* @param data
* @return
*/
function fsfilter_render_tab(data)
{
(function($){
var tbody = $('#ak_list_contents');
tbody.html('');
$.each(data, function(counter, def){
fsfilter_add_row(def, tbody);
});
})(akeeba.jQuery);
}
/**
* Wipes out the filesystem filters
* @return
*/
function fsfilter_nuke()
{
var data = new Object;
data.root = akeeba_current_root;
data.verb = 'reset';
// Convert to JSON
var json = JSON.stringify(data);
// Assemble the data array and send the AJAX request
var new_data = new Object;
new_data.action = json;
doAjax(new_data, function(response){
fsfilter_render(response);
});
}
//Akeeba Backup -- Database Filters (direct)
/**
* Loads the contents of a database
* @param data
* @return
*/
function dbfilter_load(data)
{
// Add the verb to the data
data.verb = 'list';
// Convert to JSON
var json = JSON.stringify(data);
// Assemble the data array and send the AJAX request
var new_data = new Object;
new_data.action = json;
doAjax(new_data, function(response){
dbfilter_render(response);
});
}
/**
* Toggles a database filter
* @param data
* @param caller
* @return
*/
function dbfilter_toggle(data, caller, callback)
{
fsfilter_toggle(data, caller, callback);
}
/**
* Renders the Database Filters page
* @param data
* @return
*/
function dbfilter_render(data)
{
akeeba_current_root = data.root;
(function($){
var aktables = $('#tables');
aktables.html('');
$.each(data.tables, function(table, dbef){
var uielement = $(document.createElement('div'))
.addClass('table-container');
var available_filters = new Array;
available_filters.push('tables');
available_filters.push('tabledata');
$.each(available_filters, function(counter, filter){
var ui_icon = $(document.createElement('span')).addClass('<API key>');
switch(filter)
{
case 'tables':
ui_icon.append('<span class="ui-icon ui-icon-cancel"></span>');
break;
case 'tabledata':
ui_icon.append('<span class="ui-icon ui-icon-contact"></span>');
break;
}
ui_icon.tooltip({
track: false,
delay: 0,
showURL: false,
opacity: 1,
fixPNG: true,
fade: 0,
extraClass: 'ui-dialog ui-corner-all',
bodyHandler: function() {
html = '<div>'+akeeba_translations['UI-FILTERTYPE-'+filter.toUpperCase()]+'</div>';
return html;
}
});
switch(dbef[filter])
{
case 2:
ui_icon.addClass('ui-state-error');
break;
case 1:
ui_icon.addClass('ui-state-highlight');
// Don't break; we have to add the handler!
case 0:
ui_icon.click(function(){
var new_data = new Object;
new_data.root = data.root;
new_data.node = table;
new_data.filter = filter;
new_data.verb = 'toggle';
dbfilter_toggle(new_data, ui_icon);
});
}
ui_icon.appendTo(uielement);
}); // filter loop
// Add the table label
var iconclass = 'ui-icon-link';
var icontip = 'UI-TABLETYPE-MISC';
switch(dbef.type)
{
case 'table':
iconclass = 'ui-icon-calculator';
icontip = 'UI-TABLETYPE-TABLE';
break;
case 'view':
iconclass = 'ui-icon-copy';
icontip = 'UI-TABLETYPE-VIEW';
break;
case 'procedure':
iconclass = 'ui-icon-script';
icontip = '<API key>';
break;
case 'function':
iconclass = 'ui-icon-gear';
icontip = '<API key>';
break;
case 'trigger':
iconclass = 'ui-icon-video';
icontip = '<API key>';
break;
}
$(document.createElement('span'))
.addClass('table-name')
.html(table)
.append(
$(document.createElement('span'))
.addClass('<API key>')
.addClass('table-icon-noclick')
.addClass('table-icon-small')
.append(
$(document.createElement('span'))
.addClass('ui-icon')
.addClass('<API key>')
)
)
.append(
$(document.createElement('span'))
.addClass('<API key>')
.addClass('table-icon-noclick')
.addClass('table-icon-small')
.append(
$(document.createElement('span'))
.addClass('ui-icon')
.addClass(iconclass)
)
.tooltip({
track: false,
delay: 0,
showURL: false,
opacity: 1,
fixPNG: true,
fade: 0,
extraClass: 'ui-dialog ui-corner-all',
bodyHandler: function() {
html = '<div>'+akeeba_translations[icontip]+'</div>';
return html;
}
})
)
.appendTo(uielement);
// Render
uielement.appendTo(aktables);
});
})(akeeba.jQuery);
}
/**
* Loads the tabular view of the Database Filter for a given root
* @param root
* @return
*/
function dbfilter_load_tab(root)
{
var data = new Object;
data.verb = 'tab';
data.root = root;
// Convert to JSON
var json = JSON.stringify(data);
// Assemble the data array and send the AJAX request
var new_data = new Object;
new_data.action = json;
doAjax(new_data, function(response){
dbfilter_render_tab(response);
});
}
/**
* Add a row in the tabular view of the Filesystems Filter
* @param def
* @param append_to_here
* @return
*/
function dbfilter_add_row(def, append_to_here)
{
(function($){
// Turn def.type into something human readable
var type_text = akeeba_translations['UI-FILTERTYPE-'+def.type.toUpperCase()];
if(type_text == null) type_text = def.type;
$(document.createElement('tr'))
.addClass('ak_filter_row')
.append(
// Filter title
$(document.createElement('td'))
.addClass('ak_filter_type')
.append(
$(document.createElement('span'))
.addClass('ui-icon ui-icon-circle-plus addnew')
.click(function(){
// Add a row below ourselves
var new_def = new Object;
new_def.type = def.type;
new_def.node = '';
dbfilter_add_row(new_def, $(this).parent().parent().parent() );
$(this).parent().parent().parent().children('tr:last').children('td:last').children('span.<API key>:last').click();
})
)
.append(type_text)
)
.append(
$(document.createElement('td'))
.addClass('ak_filter_item')
.append(
$(document.createElement('span'))
.addClass('<API key>')
.click(function(){
if( def.node == '' )
{
// An empty filter is normally not saved to the database; it's a new record row which has to be removed...
$(this).parent().parent().remove();
return;
}
var new_data = new Object;
new_data.root = $('#active_root').val();
new_data.node = def.node;
new_data.filter = def.type;
new_data.verb = 'remove';
dbfilter_toggle(new_data, $(this), function(response, caller){
if(response.success)
{
caller.parent().parent().remove();
}
});
})
.append(
$(document.createElement('span'))
.addClass('ui-icon ui-icon-trash deletebutton')
)
)
.append(
$(document.createElement('span'))
.addClass('<API key>')
.click(function(){
if( $(this).siblings('span.<API key>:first').next().data('editing') ) return;
$(this).siblings('span.<API key>:first').next().data('editing',true);
$(this).next().hide();
$(document.createElement('input'))
.attr({
type: 'text',
size: 60
})
.val( $(this).next().html() )
.appendTo( $(this).parent() )
.blur(function(){
var new_value = $(this).val();
if(new_value == '')
{
// Well, if the user meant to remove the filter, let's help him!
$(this).parent().children('span.ak_filter_name').show();
$(this).siblings('span.<API key>').find('span.deletebutton').click();
$(this).remove();
return;
}
// First, remove the old filter
var new_data = new Object;
new_data.root = $('#active_root').val();
new_data.old_node = def.node;
new_data.new_node = new_value;
new_data.filter = def.type;
new_data.verb = 'swap';
var input_box = $(this);
dbfilter_toggle(new_data,
input_box.siblings('span.<API key>:first').next(),
function(response, caller){
// Remove the editor
input_box.siblings('span.<API key>:first').next().removeData('editing');
input_box.parent().find('span.ak_filter_name').show();
input_box.siblings('span.<API key>:first').next().removeClass('ui-state-highlight');
input_box.parent().find('span.ak_filter_name').html( new_value );
input_box.remove();
}
);
})
.focus();
})
.append(
$(document.createElement('span'))
.addClass('ui-icon ui-icon-pencil editbutton')
)
)
.append(
$(document.createElement('span'))
.addClass('ak_filter_name')
.html(def.node)
)
)
.appendTo( $(append_to_here) );
})(akeeba.jQuery);
}
/**
* Renders the tabular view of the Database Filter
* @param data
* @return
*/
function dbfilter_render_tab(data)
{
(function($){
var tbody = $('#ak_list_contents');
tbody.html('');
$.each(data, function(counter, def){
dbfilter_add_row(def, tbody);
});
})(akeeba.jQuery);
}
/**
* Activates the exclusion filters for non-CMS tables
*/
function <API key>()
{
(function($){
$('#tables div').each(function(i, element){
// Get the table name
var tablename = $(element).find('span.table-name:first').text();
var prefix = tablename.substr(0,3);
// If the prefix is #__ it's a CMS table and I have to skip it
if( prefix != '
{
var icon = $(element).find('span.<API key> span.ui-icon:first');
if ( !($(icon).parent().hasClass('ui-state-highlight')) )
{
$(icon).click();
}
}
});
})(akeeba.jQuery);
}
/**
* Wipes out the database filters
* @return
*/
function dbfilter_nuke()
{
var data = new Object;
data.root = akeeba_current_root;
data.verb = 'reset';
// Convert to JSON
var json = JSON.stringify(data);
// Assemble the data array and send the AJAX request
var new_data = new Object;
new_data.action = json;
doAjax(new_data, function(response){
dbfilter_render(response);
});
}
// Akeeba's jQuery extensions
//Custom no easing plug-in
akeeba.jQuery.extend(akeeba.jQuery.easing, {
none: function(fraction, elapsed, attrStart, attrDelta, duration) {
return attrStart + attrDelta * fraction;
}
});
// I N I T I A L I Z A T I O N
akeeba.jQuery(document).ready(function($){
// Create an AJAX manager
var akeeba_ajax_manager = $.manageAjax.create('akeeba_ajax_profile', {
queue: true,
abortOld: false,
maxRequests: 1,
<API key>: false,
cacheResponse: false
});
// Add hover state to buttons and other non jQuery UI elements
$('.ui-state-default').hover(
function(){$(this).addClass('ui-state-hover');},
function(){$(this).removeClass('ui-state-hover');}
);
}); |
#include <stdio.h>
#include <stdlib.h>
#include "rbtree.h"
static void __rb_rotate_left(struct rb_node *node, struct rb_root *root)
{
struct rb_node *right = node->rb_right;
struct rb_node *parent = rb_parent(node);
if ((node->rb_right = right->rb_left))
rb_set_parent(right->rb_left, node);
right->rb_left = node;
rb_set_parent(right, parent);
if (parent)
{
if (node == parent->rb_left)
parent->rb_left = right;
else
parent->rb_right = right;
}
else
root->rb_node = right;
rb_set_parent(node, right);
}
static void __rb_rotate_right(struct rb_node *node, struct rb_root *root)
{
struct rb_node *left = node->rb_left;
struct rb_node *parent = rb_parent(node);
if ((node->rb_left = left->rb_right))
rb_set_parent(left->rb_right, node);
left->rb_right = node;
rb_set_parent(left, parent);
if (parent)
{
if (node == parent->rb_right)
parent->rb_right = left;
else
parent->rb_left = left;
}
else
root->rb_node = left;
rb_set_parent(node, left);
}
void rb_insert_color(struct rb_node *node, struct rb_root *root)
{
struct rb_node *parent, *gparent;
while ((parent = rb_parent(node)) && rb_is_red(parent))
{
gparent = rb_parent(parent);
if (parent == gparent->rb_left)
{
{
register struct rb_node *uncle = gparent->rb_right;
if (uncle && rb_is_red(uncle))
{
rb_set_black(uncle);
rb_set_black(parent);
rb_set_red(gparent);
node = gparent;
continue;
}
}
if (parent->rb_right == node)
{
register struct rb_node *tmp;
__rb_rotate_left(parent, root);
tmp = parent;
parent = node;
node = tmp;
}
rb_set_black(parent);
rb_set_red(gparent);
__rb_rotate_right(gparent, root);
} else {
{
register struct rb_node *uncle = gparent->rb_left;
if (uncle && rb_is_red(uncle))
{
rb_set_black(uncle);
rb_set_black(parent);
rb_set_red(gparent);
node = gparent;
continue;
}
}
if (parent->rb_left == node)
{
register struct rb_node *tmp;
__rb_rotate_right(parent, root);
tmp = parent;
parent = node;
node = tmp;
}
rb_set_black(parent);
rb_set_red(gparent);
__rb_rotate_left(gparent, root);
}
}
rb_set_black(root->rb_node);
}
static void __rb_erase_color(struct rb_node *node, struct rb_node *parent,
struct rb_root *root)
{
struct rb_node *other;
while ((!node || rb_is_black(node)) && node != root->rb_node)
{
if (parent->rb_left == node)
{
other = parent->rb_right;
if (rb_is_red(other))
{
rb_set_black(other);
rb_set_red(parent);
__rb_rotate_left(parent, root);
other = parent->rb_right;
}
if ((!other->rb_left || rb_is_black(other->rb_left)) &&
(!other->rb_right || rb_is_black(other->rb_right)))
{
rb_set_red(other);
node = parent;
parent = rb_parent(node);
}
else
{
if (!other->rb_right || rb_is_black(other->rb_right))
{
rb_set_black(other->rb_left);
rb_set_red(other);
__rb_rotate_right(other, root);
other = parent->rb_right;
}
rb_set_color(other, rb_color(parent));
rb_set_black(parent);
rb_set_black(other->rb_right);
__rb_rotate_left(parent, root);
node = root->rb_node;
break;
}
}
else
{
other = parent->rb_left;
if (rb_is_red(other))
{
rb_set_black(other);
rb_set_red(parent);
__rb_rotate_right(parent, root);
other = parent->rb_left;
}
if ((!other->rb_left || rb_is_black(other->rb_left)) &&
(!other->rb_right || rb_is_black(other->rb_right)))
{
rb_set_red(other);
node = parent;
parent = rb_parent(node);
}
else
{
if (!other->rb_left || rb_is_black(other->rb_left))
{
rb_set_black(other->rb_right);
rb_set_red(other);
__rb_rotate_left(other, root);
other = parent->rb_left;
}
rb_set_color(other, rb_color(parent));
rb_set_black(parent);
rb_set_black(other->rb_left);
__rb_rotate_right(parent, root);
node = root->rb_node;
break;
}
}
}
if (node)
rb_set_black(node);
}
void rb_erase(struct rb_node *node, struct rb_root *root)
{
struct rb_node *child, *parent;
int color;
if (!node->rb_left)
child = node->rb_right;
else if (!node->rb_right)
child = node->rb_left;
else
{
struct rb_node *old = node, *left;
node = node->rb_right;
while ((left = node->rb_left) != NULL)
node = left;
if (rb_parent(old)) {
if (rb_parent(old)->rb_left == old)
rb_parent(old)->rb_left = node;
else
rb_parent(old)->rb_right = node;
} else
root->rb_node = node;
child = node->rb_right;
parent = rb_parent(node);
color = rb_color(node);
if (parent == old) {
parent = node;
} else {
if (child)
rb_set_parent(child, parent);
parent->rb_left = child;
node->rb_right = old->rb_right;
rb_set_parent(old->rb_right, node);
}
node->rb_parent_color = old->rb_parent_color;
node->rb_left = old->rb_left;
rb_set_parent(old->rb_left, node);
goto color;
}
parent = rb_parent(node);
color = rb_color(node);
if (child)
rb_set_parent(child, parent);
if (parent)
{
if (parent->rb_left == node)
parent->rb_left = child;
else
parent->rb_right = child;
}
else
root->rb_node = child;
color:
if (color == RB_BLACK)
__rb_erase_color(child, parent, root);
}
/*
* This function returns the first node (in sort order) of the tree.
*/
struct rb_node *rb_first(const struct rb_root *root)
{
struct rb_node *n;
n = root->rb_node;
if (!n)
return NULL;
while (n->rb_left)
n = n->rb_left;
return n;
}
struct rb_node *rb_last(const struct rb_root *root)
{
struct rb_node *n;
n = root->rb_node;
if (!n)
return NULL;
while (n->rb_right)
n = n->rb_right;
return n;
}
struct rb_node *rb_next(const struct rb_node *node)
{
struct rb_node *parent;
if (rb_parent(node) == node)
return NULL;
/* If we have a right-hand child, go down and then left as far
as we can. */
if (node->rb_right) {
node = node->rb_right;
while (node->rb_left)
node=node->rb_left;
return (struct rb_node *)node;
}
/* No right-hand children. Everything down and left is
smaller than us, so any 'next' node must be in the general
direction of our parent. Go up the tree; any time the
ancestor is a right-hand child of its parent, keep going
up. First time it's a left-hand child of its parent, said
parent is our 'next' node. */
while ((parent = rb_parent(node)) && node == parent->rb_right)
node = parent;
return parent;
}
struct rb_node *rb_prev(const struct rb_node *node)
{
struct rb_node *parent;
if (rb_parent(node) == node)
return NULL;
/* If we have a left-hand child, go down and then right as far
as we can. */
if (node->rb_left) {
node = node->rb_left;
while (node->rb_right)
node=node->rb_right;
return (struct rb_node *)node;
}
/* No left-hand children. Go up till we find an ancestor which
is a right-hand child of its parent */
while ((parent = rb_parent(node)) && node == parent->rb_left)
node = parent;
return parent;
}
void rb_replace_node(struct rb_node *victim, struct rb_node *new,
struct rb_root *root)
{
struct rb_node *parent = rb_parent(victim);
/* Set the surrounding nodes to point to the replacement */
if (parent) {
if (victim == parent->rb_left)
parent->rb_left = new;
else
parent->rb_right = new;
} else {
root->rb_node = new;
}
if (victim->rb_left)
rb_set_parent(victim->rb_left, new);
if (victim->rb_right)
rb_set_parent(victim->rb_right, new);
/* Copy the pointers/colour from the victim to the replacement */
*new = *victim;
}
struct mytype {
struct rb_node my_node;
int num;
};
struct mytype *my_search(struct rb_root *root, int num)
{
struct rb_node *node = root->rb_node;
while (node) {
struct mytype *data = container_of(node, struct mytype, my_node);
if (num < data->num)
node = node->rb_left;
else if (num > data->num)
node = node->rb_right;
else
return data;
}
return NULL;
}
int my_insert(struct rb_root *root, struct mytype *data)
{
struct rb_node **tmp = &(root->rb_node), *parent = NULL;
/* Figure out where to put new node */
while (*tmp) {
struct mytype *this = container_of(*tmp, struct mytype, my_node);
parent = *tmp;
if (data->num < this->num)
tmp = &((*tmp)->rb_left);
else if (data->num > this->num)
tmp = &((*tmp)->rb_right);
else
return -1;
}
/* Add new node and rebalance tree. */
rb_link_node(&data->my_node, parent, tmp);
rb_insert_color(&data->my_node, root);
return 0;
}
void my_delete(struct rb_root *root, int num)
{
struct mytype *data = my_search(root, num);
if (!data) {
fprintf(stderr, "Not found %d.\n", num);
return;
}
rb_erase(&data->my_node, root);
free(data);
}
void print_rbtree(struct rb_root *tree)
{
struct rb_node *node;
for (node = rb_first(tree); node; node = rb_next(node))
printf("%d ", rb_entry(node, struct mytype, my_node)->num);
printf("\n");
}
int main(int argc, char *argv[])
{
struct rb_root mytree = RB_ROOT;
int i, ret, num;
struct mytype *tmp;
if (argc < 2) {
fprintf(stderr, "Usage: %s num\n", argv[0]);
exit(-1);
}
num = atoi(argv[1]);
printf("Please enter %d integers:\n", num);
for (i = 0; i < num; i++) {
tmp = malloc(sizeof(struct mytype));
if (!tmp)
perror("Allocate dynamic memory");
scanf("%d", &tmp->num);
ret = my_insert(&mytree, tmp);
if (ret < 0) {
fprintf(stderr, "The %d already exists.\n", tmp->num);
free(tmp);
}
}
printf("\nthe first test\n");
print_rbtree(&mytree);
my_delete(&mytree, 21);
printf("\nthe second test\n");
print_rbtree(&mytree);
return 0;
} |
<?php
/**
* WordPress Post Thumbnail Template Functions.
*
* Support for post thumbnails.
* Theme's functions.php must call add_theme_support( 'post-thumbnails' ) to use these.
*
* @package WordPress
* @subpackage Template
*/
/**
* Check if post has an image attached.
*
* @since 2.9.0
*
* @param int $post_id Optional. Post ID.
* @return bool Whether post has an image attached.
*/
function has_post_thumbnail($post_id = null) {
return (bool)<API key>($post_id);
}
/**
* Retrieve Post Thumbnail ID.
*
* @since 2.9.0
*
* @param int $post_id Optional. Post ID.
* @return int
*/
function <API key>($post_id = null) {
$post_id = (null === $post_id) ? get_the_ID() : $post_id;
return get_post_meta($post_id, '_thumbnail_id', true);
}
/**
* Display the post thumbnail.
*
* When a theme adds 'post-thumbnail' support, a special 'post-thumbnail' image size
* is registered, which differs from the 'thumbnail' image size managed via the
* Settings > Media screen.
*
* When using the_post_thumbnail() or related functions, the 'post-thumbnail' image
* size is used by default, though a different size can be specified instead as needed.
*
* @since 2.9.0
*
* @see <API key>()
*
* @param string|array $size Optional. Registered image size to use, or flat array of height
* and width values. Default 'post-thumbnail'.
* @param string|array $attr Optional. Query string or array of attributes. Default empty.
*/
function the_post_thumbnail($size = 'post-thumbnail', $attr = '') {
echo <API key>(null, $size, $attr);
}
/**
* Update cache for thumbnails in the current loop
*
* @since 3.2.0
*
* @param object $wp_query Optional. A WP_Query instance. Defaults to the $wp_query global.
*/
function <API key>($wp_query = null) {
if (!$wp_query) $wp_query = $GLOBALS['wp_query'];
if ($wp_query->thumbnails_cached) return;
$thumb_ids = array();
foreach ($wp_query->posts as $post) {
if ($id = <API key>($post->ID)) $thumb_ids[] = $id;
}
if (!empty ($thumb_ids)) {
_prime_post_caches($thumb_ids, false, true);
}
$wp_query->thumbnails_cached = true;
}
/**
* Retrieve the post thumbnail.
*
* When a theme adds 'post-thumbnail' support, a special 'post-thumbnail' image size
* is registered, which differs from the 'thumbnail' image size managed via the
* Settings > Media screen.
*
* When using the_post_thumbnail() or related functions, the 'post-thumbnail' image
* size is used by default, though a different size can be specified instead as needed.
*
* @since 2.9.0
*
* @param int $post_id Post ID. Default is the ID of the `$post` global.
* @param string|array $size Optional. Registered image size to use, or flat array of height
* and width values. Default 'post-thumbnail'.
* @param string|array $attr Optional. Query string or array of attributes. Default empty.
*/
function <API key>($post_id = null, $size = 'post-thumbnail', $attr = '') {
$post_id = (null === $post_id) ? get_the_ID() : $post_id;
$post_thumbnail_id = <API key>($post_id);
/**
* Filter the post thumbnail size.
*
* @since 2.9.0
*
* @param string $size The post thumbnail size.
*/
$size = apply_filters('post_thumbnail_size', $size);
if ($post_thumbnail_id) {
/**
* Fires before fetching the post thumbnail HTML.
*
* Provides "just in time" filtering of all filters in <API key>().
*
* @since 2.9.0
*
* @param string $post_id The post ID.
* @param string $post_thumbnail_id The post thumbnail ID.
* @param string $size The post thumbnail size.
*/
do_action('<API key>', $post_id, $post_thumbnail_id, $size);
if (in_the_loop()) <API key>();
$html = <API key>($post_thumbnail_id, $size, false, $attr);
/**
* Fires after fetching the post thumbnail HTML.
*
* @since 2.9.0
*
* @param string $post_id The post ID.
* @param string $post_thumbnail_id The post thumbnail ID.
* @param string $size The post thumbnail size.
*/
do_action('<API key>', $post_id, $post_thumbnail_id, $size);
} else {
$html = '';
}
/**
* Filter the post thumbnail HTML.
*
* @since 2.9.0
*
* @param string $html The post thumbnail HTML.
* @param string $post_id The post ID.
* @param string $post_thumbnail_id The post thumbnail ID.
* @param string $size The post thumbnail size.
* @param string $attr Query string of attributes.
*/
return apply_filters('post_thumbnail_html', $html, $post_id, $post_thumbnail_id, $size, $attr);
} |
<?php
// Module/Plug-in Social Plugins frontend_render script
// use it as when it is located under "template/inc_script/frontend_render"
// most times it is used to register custom function
// or make a very early redirection...
?> |
using System;
using System.Reflection;
namespace JR.Cms.Cache.CacheCompoment
{
<summary>
Description of CmsCacheUtility.
</summary>
public class CmsCacheUtility
{
public static void EvalCacheUpdate<T>(MethodInfo method) where T:Attribute,ICacheUpdatePolicy
{
object[] attrs=method.GetCustomAttributes(typeof(T),false);
if(attrs.Length!=0)
{
(attrs[0] as ICacheUpdatePolicy).Clear();
}
}
}
} |
#ifndef _CACHE_H__
#define _CACHE_H__
#include <shogun/lib/common.h>
#include <shogun/io/SGIO.h>
#include <shogun/mathematics/Math.h>
#include <shogun/base/SGObject.h>
#include <stdlib.h>
namespace shogun
{
/** @brief Template class Cache implements a simple cache.
*
* When the cache is full -- elements that are least used are freed from the
* cache. Thus for the cache to be effective one should not visit loop over
* objects, i.e. visit elements in order 0...num_elements (with num_elements >>
* the maximal number of entries in cache)
*
*/
template<class T> class CCache : public CSGObject
{
/** cache entry */
struct TEntry
{
/** usage count */
int64_t usage_count;
/** if entry is locked */
bool locked;
/** cached object */
T* obj;
};
public:
/** default constructor */
CCache() :CSGObject()
{
SG_UNSTABLE("CCache::CCache()", "\n");
cache_block=NULL;
lookup_table=NULL;
cache_table=NULL;
cache_is_full=false;
nr_cache_lines=0;
entry_size=0;
}
/** constructor
*
* create a cache in which num_entries objects can be cached
* whose lookup table of sizeof(int64_t)*num_entries
* must fit into memory
*
* @param cache_size cache size in Megabytes
* @param obj_size object size
* @param num_entries number of cached objects
*/
CCache(int64_t cache_size, int64_t obj_size, int64_t num_entries)
: CSGObject()
{
if (cache_size==0 || obj_size==0 || num_entries==0)
{
SG_INFO("doing without cache.\n");
cache_block=NULL;
lookup_table=NULL;
cache_table=NULL;
cache_is_full=false;
nr_cache_lines=0;
entry_size=0;
return;
}
entry_size=obj_size;
nr_cache_lines=CMath::min((int64_t) (cache_size*1024*1024/obj_size/sizeof(T)), num_entries+1);
SG_INFO("creating %d cache lines (total size: %ld byte)\n", nr_cache_lines, nr_cache_lines*obj_size*sizeof(T));
cache_block=SG_MALLOC(T, obj_size*nr_cache_lines);
lookup_table=SG_MALLOC(TEntry, num_entries);
cache_table=SG_MALLOC(TEntry*, nr_cache_lines);
ASSERT(cache_block);
ASSERT(lookup_table);
ASSERT(cache_table);
int64_t i;
for (i=0; i<nr_cache_lines; i++)
cache_table[i]=NULL;
for (i=0; i<num_entries; i++)
{
lookup_table[i].usage_count=-1;
lookup_table[i].locked=false;
lookup_table[i].obj=NULL;
}
cache_is_full=false;
//reserve the very last cache line
//as scratch buffer
nr_cache_lines
}
virtual ~CCache()
{
SG_FREE(cache_block);
SG_FREE(lookup_table);
SG_FREE(cache_table);
}
/** checks if an object is cached
*
* @param number number of object to check for
* @return if an object is cached
*/
inline bool is_cached(int64_t number)
{
return (lookup_table && lookup_table[number].obj);
}
/** lock and get a cache entry
*
* @param number number of object to lock and get
* @return cache entry or NULL when not cached
*/
inline T* lock_entry(int64_t number)
{
if (lookup_table)
{
lookup_table[number].usage_count++;
lookup_table[number].locked=true;
return lookup_table[number].obj;
}
else
return NULL;
}
/** unlock a cache entry
*
* @param number number of object to unlock
*/
inline void unlock_entry(int64_t number)
{
if (lookup_table)
lookup_table[number].locked=false;
}
/** returns the address of a free cache entry
* to where the data of size obj_size has to
* be written
*
* @param number number of object to unlock
* @return address of a free cache entry
*/
T* set_entry(int64_t number)
{
if (lookup_table)
{
// first look for the element with smallest usage count
//int64_t min_idx=((nr_cache_lines-1)*random())/(RAND_MAX+1); //avoid the last elem and the scratch line
int64_t min_idx=0;
int64_t min=-1;
bool found_free_line=false;
int64_t start=0;
for (start=0; start<nr_cache_lines; start++)
{
if (!cache_table[start])
{
min_idx=start;
min=-1;
found_free_line=true;
break;
}
else
{
if (!cache_table[start]->locked)
{
min=cache_table[start]->usage_count;
min_idx=start;
found_free_line=true;
break;
}
}
}
for (int64_t i=start; i<nr_cache_lines; i++)
{
if (!cache_table[i])
{
min_idx=i;
min=-1;
found_free_line=true;
break;
}
else
{
int64_t v=cache_table[i]->usage_count;
if (v<min && !cache_table[i]->locked)
{
min=v;
min_idx=i;
found_free_line=true;
}
}
}
if (cache_table[nr_cache_lines-1]) //since this is an indicator for a full cache
cache_is_full=true;
if (found_free_line)
{
// and overwrite it.
if ( (lookup_table[number].usage_count-min) < 5 && cache_is_full && ! (cache_table[nr_cache_lines] && cache_table[nr_cache_lines]->locked))
min_idx=nr_cache_lines; //scratch entry
if (cache_table[min_idx])
cache_table[min_idx]->obj=NULL;
cache_table[min_idx]=&lookup_table[number];
lookup_table[number].obj=&cache_block[entry_size*min_idx];
//lock cache entry;
lookup_table[number].usage_count=0;
lookup_table[number].locked=true;
return lookup_table[number].obj;
}
else
return NULL;
}
else
return NULL;
}
/** @return object name */
inline virtual const char* get_name() const { return "Cache"; }
protected:
/** if cache is full */
bool cache_is_full;
/** size of one entry */
int64_t entry_size;
/** number of cache lines */
int64_t nr_cache_lines;
/** lookup table */
TEntry* lookup_table;
/** cache table containing cached objects */
TEntry** cache_table;
/** cache block */
T* cache_block;
};
}
#endif |
<?php
// Locale
$_['code'] = 'zh-TW';
$_['direction'] = 'ltr';
$_['date_format_short'] = 'Y/m/d';
$_['date_format_long'] = 'l dS F Y';
$_['time_format'] = 'h:i:s A';
$_['datetime_format'] = 'Y/m/d H:i:s';
$_['decimal_point'] = '.';
$_['thousand_point'] = ',';
// Text
$_['text_yes'] = '';
$_['text_no'] = '';
$_['text_enabled'] = '';
$_['text_disabled'] = '';
$_['text_none'] = '
$_['text_select'] = '
$_['text_select_all'] = '';
$_['text_unselect_all'] = '';
$_['text_all_zones'] = '';
$_['text_default'] = ' <b></b>';
$_['text_close'] = '';
$_['text_pagination'] = ' %d ~ %d %d ';
$_['text_loading'] = '...';
$_['text_no_results'] = '';
$_['text_confirm'] = '?';
$_['text_home'] = '';
// Button
$_['button_add'] = '';
$_['button_delete'] = '';
$_['button_save'] = '';
$_['button_cancel'] = '';
$_['<API key>'] = '';
$_['button_continue'] = '';
$_['button_clear'] = '';
$_['button_close'] = '';
$_['button_enable'] = '';
$_['button_disable'] = '';
$_['button_filter'] = '';
$_['button_send'] = '';
$_['button_edit'] = '';
$_['button_copy'] = '';
$_['button_back'] = '';
$_['button_remove'] = '';
$_['button_refresh'] = '';
$_['button_export'] = '';
$_['button_import'] = '';
$_['button_download'] = '';
$_['button_rebuild'] = '';
$_['button_upload'] = '';
$_['button_submit'] = '';
$_['<API key>'] = '';
$_['<API key>'] = '';
$_['button_address_add'] = '';
$_['<API key>'] = '';
$_['button_banner_add'] = '';
$_['<API key>'] = '';
$_['button_product_add'] = '';
$_['button_filter_add'] = '';
$_['button_option_add'] = '';
$_['<API key>'] = '';
$_['<API key>'] = '';
$_['button_discount_add'] = '';
$_['button_special_add'] = '';
$_['button_image_add'] = '';
$_['button_geo_zone_add'] = '';
$_['button_history_add'] = '';
$_['button_translation'] = '';
$_['<API key>'] = '';
$_['<API key>'] = '';
$_['button_route_add'] = '';
$_['button_rule_add'] = '';
$_['button_module_add'] = '';
$_['button_link_add'] = '';
$_['button_approve'] = '';
$_['button_reset'] = '';
$_['button_generate'] = '';
$_['button_voucher_add'] = '';
$_['button_reward_add'] = '';
$_['<API key>'] = '';
$_['<API key>'] = '';
$_['<API key>'] = '';
$_['button_credit_add'] = '';
$_['<API key>'] = '';
$_['button_ip_add'] = 'IP';
$_['button_parent'] = '';
$_['button_folder'] = '';
$_['button_search'] = '';
$_['button_view'] = '';
$_['button_install'] = '';
$_['button_uninstall'] = '';
$_['button_login'] = '';
$_['button_unlock'] = '';
$_['button_link'] = '';
$_['button_currency'] = '';
$_['button_apply'] = '';
$_['button_category_add'] = '';
$_['button_order'] = '';
$_['<API key>'] = '';
// Tab
$_['tab_address'] = '';
$_['tab_additional'] = '';
$_['tab_admin'] = '';
$_['tab_attribute'] = '';
$_['tab_customer'] = '';
$_['tab_data'] = '';
$_['tab_design'] = '';
$_['tab_discount'] = '';
$_['tab_general'] = '';
$_['tab_history'] = '';
$_['tab_ftp'] = 'FTP';
$_['tab_ip'] = 'IP';
$_['tab_links'] = '';
$_['tab_log'] = 'Log';
$_['tab_image'] = '';
$_['tab_option'] = '';
$_['tab_server'] = '';
$_['tab_store'] = '';
$_['tab_special'] = '';
$_['tab_session'] = '';
$_['tab_local'] = '';
$_['tab_mail'] = '';
$_['tab_module'] = '';
$_['tab_payment'] = '';
$_['tab_product'] = '';
$_['tab_reward'] = '';
$_['tab_shipping'] = '';
$_['tab_total'] = '';
$_['tab_transaction'] = '';
$_['tab_voucher'] = '';
$_['tab_sale'] = '';
$_['tab_marketing'] = '';
$_['tab_online'] = '';
$_['tab_activity'] = '';
$_['tab_recurring'] = '';
$_['tab_action'] = '';
$_['tab_google'] = 'Google';
// Error
$_['error_exception'] = '(%s): %s in %s on line %s';
$_['error_upload_1'] = 'php.ini(upload_max_filesize)';
$_['error_upload_2'] = 'HTML(MAX_FILE_SIZE)';
$_['error_upload_3'] = '';
$_['error_upload_4'] = '';
$_['error_upload_6'] = '';
$_['error_upload_7'] = '';
$_['error_upload_8'] = '';
$_['error_upload_999'] = '';
$_['error_curl'] = 'CURL: Error Code(%s): %s'; |
// For information as to what this class does, see the Javadoc, below. //
// 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph //
// Ramsey, and Clark Glymour. //
// This program is free software; you can redistribute it and/or modify //
// (at your option) any later version. //
// This program is distributed in the hope that it will be useful, //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// along with this program; if not, write to the Free Software //
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //
package edu.cmu.tetradapp.app;
import edu.cmu.tetradapp.util.ImageUtils;
import edu.cmu.tetradapp.workbench.AbstractWorkbench;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.<API key>;
import java.util.HashMap;
import java.util.Map;
/**
* Displays a vertical list of buttons that determine the next action the user
* can take in the session editor workbench, whether it's selecting and moving a
* node, adding a node of a particular type, or adding an edge.
*
* @author Joseph Ramsey jdramsey@andrew.cmu.edu
* @see SessionEditor
* @see <API key>
*/
final class <API key> extends JPanel {
/**
* True iff the toolbar is responding to events.
*/
private boolean respondingToEvents = true;
/**
* The node type of the button that is used for the Select/Move tool.
*/
private final String selectType = "Select";
/**\
* The map from JToggleButtons to String node types.
*/
private final Map<JToggleButton, String> nodeTypes = new HashMap<>();
/**
* True iff the shift key was down on last click.
*/
private boolean shiftDown = false;
/**
* The workbench this toolbar controls.
*/
private <API key> workbench;
/**
* Constructs a new session toolbar.
*
* @param workbench the workbench this toolbar controls.
*/
public <API key>(final <API key> workbench) {
if (workbench == null) {
throw new <API key>("Workbench must not be null.");
}
this.workbench = workbench;
// Set up panel.
Box buttonsPanel = Box.createVerticalBox();
// buttonsPanel.setBackground(new Color(198, 232, 252));
buttonsPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
// Create buttons.
/*
Node infos for all of the nodes.
*/
ButtonInfo[] buttonInfos = new ButtonInfo[]{
new ButtonInfo("Select", "Select and Move", "move",
"<html>Select and move nodes or groups of nodes " +
"<br>on the workbench.</html>"),
new ButtonInfo("Edge", "Draw Edge", "flow",
"<html>Add an edge from one node to another to declare" +
"<br>that the object in the first node should be used " +
"<br>to construct the object in the second node." +
"<br>As a shortcut, hold down the Control key." +
"</html>"),
new ButtonInfo("Data", "Data & Simulation", "data",
"<html>Add a node for a data object.</html>"),
new ButtonInfo("Search", "Search", "search",
"<html>Add a node for a search algorithm.</html>"),
new ButtonInfo("Comparison", "Comparison", "compare",
"<html>Add a node to compare graphs or SEM IM's.</html>"),
new ButtonInfo("Graph", "Graph", "graph", "<html>Add a graph node.</html>"),
new ButtonInfo("PM", "Parametric Model", "pm",
"<html>Add a node for a parametric model.</html>"),
new ButtonInfo("IM", "Instantiated Model", "im",
"<html>Add a node for an instantiated model.</html>"),
new ButtonInfo("Estimator", "Estimator", "estimator",
"<html>Add a node for an estimator.</html>"),
new ButtonInfo("Updater", "Updater", "updater",
"<html>Add a node for an updater.</html>"),
new ButtonInfo("Classify", "Classify", "search",
"<html>Add a node for a classifier.</html>"),
new ButtonInfo("Regression", "Regression", "regression",
"<html>Add a node for a regression.</html>"),
new ButtonInfo("Knowledge", "Knowledge", "knowledge", "<html>Add a knowledge box node.</html>"),
new ButtonInfo("Note", "Note", "note",
"<html>Add a note to the session.</html>")
};
JToggleButton[] buttons = new JToggleButton[buttonInfos.length];
for (int i = 0; i < buttonInfos.length; i++) {
buttons[i] = constructButton(buttonInfos[i]);
}
// Add all buttons to a button group.
ButtonGroup buttonGroup = new ButtonGroup();
for (int i = 0; i < buttonInfos.length; i++) {
buttonGroup.add(buttons[i]);
}
// This seems to be fixed. Now creating weirdness. jdramsey 3/4/2014
// // Add a focus listener to help buttons not deselect when the
// // mouse slides away from the button.
// FocusListener focusListener = new FocusAdapter() {
// public void focusGained(FocusEvent e) {
// JToggleButton component = (JToggleButton) e.getComponent();
// component.getModel().setSelected(true);
// for (int i = 0; i < buttonInfos.length; i++) {
// buttons[i].addFocusListener(focusListener);
// Add an action listener to help send messages to the
// workbench.
ChangeListener changeListener = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JToggleButton _button = (JToggleButton) e.getSource();
if (_button.getModel().isSelected()) {
setWorkbenchMode(_button);
// setCursor(workbench.getCursor());
}
}
};
for (int i = 0; i < buttonInfos.length; i++) {
buttons[i].addChangeListener(changeListener);
}
// Select the Select button.
JToggleButton button = getButtonForType(this.selectType);
button.getModel().setSelected(true);
// Add the buttons to the workbench.
for (int i = 0; i < buttonInfos.length; i++) {
buttonsPanel.add(buttons[i]);
buttonsPanel.add(Box.createVerticalStrut(5));
}
// Put the panel in a scrollpane.
this.setLayout(new BorderLayout());
JScrollPane scroll = new JScrollPane(buttonsPanel);
scroll.setPreferredSize(new Dimension(130, 1000));
add(scroll, BorderLayout.CENTER);
// Add property change listener so that selection can be moved
// back to "SELECT_MOVE" after an action.
workbench.<API key>(new <API key>() {
public void propertyChange(PropertyChangeEvent e) {
if (!<API key>()) {
return;
}
String propertyName = e.getPropertyName();
if ("nodeAdded".equals(propertyName)) {
if (!isShiftDown()) {
resetSelectMove();
}
}
}
});
<API key>.<API key>()
.<API key>(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
int keyCode = e.getKeyCode();
int id = e.getID();
if (keyCode == KeyEvent.VK_SHIFT) {
if (id == KeyEvent.KEY_PRESSED) {
setShiftDown(true);
} else if (id == KeyEvent.KEY_RELEASED) {
setShiftDown(false);
resetSelectMove();
}
}
return false;
}
});
resetSelectMove();
}
/**
* Sets the selection back to move/select.
*/
private void resetSelectMove() {
JToggleButton selectButton = getButtonForType(selectType);
if (!(selectButton.isSelected())) {
selectButton.doClick();
selectButton.requestFocus();
}
}
// /**
// * Sets the selection back to Flowchart.
// */
// public void resetFlowchart() {
// JToggleButton edgeButton = getButtonForType(edgeType);
// edgeButton.doClick();
// edgeButton.requestFocus();
/**
* True iff the toolbar is responding to events. This may need to be turned
* off temporarily.
*/
private boolean <API key>() {
return respondingToEvents;
}
/**
* Sets whether the toolbar should react to events. This may need to be
* turned off temporarily.
*/
public void <API key>(boolean respondingToEvents) {
this.respondingToEvents = respondingToEvents;
}
protected void processKeyEvent(KeyEvent e) {
System.out.println("process key event " + e);
super.processKeyEvent(e);
}
/**
* Constructs the button with the given node type and image prefix. If the
* node type is "Select", constructs a button that allows nodes to be
* selected and moved. If the node type is "Edge", constructs a button that
* allows edges to be drawn. For other node types, constructs buttons that
* allow those type of nodes to be added to the workbench. If a non-null
* image prefix is provided, images for <prefix>Up.gif, <prefix>Down.gif,
* <prefix>Off.gif and <prefix>Roll.gif are loaded from the /images
* directory relative to this compiled class and used to provide up, down,
* off, and rollover images for the constructed button. On construction,
* nodes are mapped to their node types in the Map, <code>nodeTypes</code>.
* Listeners are added to the node.
*
* @param buttonInfo contains the info needed to construct the button.
*/
private JToggleButton constructButton(ButtonInfo buttonInfo) {
String imagePrefix = buttonInfo.getImagePrefix();
if (imagePrefix == null) {
throw new <API key>("Image prefix must not be null.");
}
JToggleButton button = new JToggleButton();
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
setShiftDown(e.isShiftDown());
// setControlDown(e.isControlDown());
}
});
if ("Select".equals(buttonInfo.getNodeTypeName())) {
button.setIcon(new ImageIcon(ImageUtils.getImage(this, "move.gif")));
} else if ("Edge".equals(buttonInfo.getNodeTypeName())) {
button.setIcon(
new ImageIcon(ImageUtils.getImage(this, "flow.gif")));
} else {
button.setName(buttonInfo.getNodeTypeName());
button.setText("<html><center>" + buttonInfo.getDisplayName() +
"</center></html>");
}
button.setMaximumSize(new Dimension(110, 40)); // For a vertical box.
button.setToolTipText(buttonInfo.getToolTipText());
this.nodeTypes.put(button, buttonInfo.getNodeTypeName());
return button;
}
/**
* Sets the state of the workbench in response to a button press.
*
* @param button the JToggleButton whose workbench state is to be set.
*/
private void setWorkbenchMode(JToggleButton button) {
String nodeType = this.nodeTypes.get(button);
/*
The node type of the button that is used for the edge-drawing tool.
*/
String edgeType = "Edge";
if (selectType.equals(nodeType)) {
workbench.setWorkbenchMode(AbstractWorkbench.SELECT_MOVE);
workbench.setNextButtonType(null);
setCursor(new Cursor(Cursor.HAND_CURSOR));
workbench.setCursor(new Cursor(Cursor.HAND_CURSOR));
} else if (edgeType.equals(nodeType)) {
workbench.setWorkbenchMode(AbstractWorkbench.ADD_EDGE);
workbench.setNextButtonType(null);
// setCursor(workbench.getCursor());
// Toolkit toolkit = Toolkit.getDefaultToolkit();
// Image image = ImageUtils.getImage(this, "arrowCursorImage.png");
// Cursor c = toolkit.createCustomCursor(image, new Point(10, 10), "img");
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
workbench.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
} else {
workbench.setWorkbenchMode(AbstractWorkbench.ADD_NODE);
workbench.setNextButtonType(nodeType);
// Toolkit toolkit = Toolkit.getDefaultToolkit();
// Image image = ImageUtils.getImage(this, "cursorImage.png");
// Cursor c = toolkit.createCustomCursor(image, new Point(10, 10), "img");
// setCursor(workbench.getCursor());
setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
workbench.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
}
}
/**
* @return the JToggleButton for the given node type, or null if no such
* button exists.
*/
private JToggleButton getButtonForType(String nodeType) {
for (Object o : nodeTypes.keySet()) {
JToggleButton button = (JToggleButton) o;
if (nodeType.equals(nodeTypes.get(button))) {
return button;
}
}
return null;
}
private boolean isShiftDown() {
return shiftDown;
}
private void setShiftDown(boolean shiftDown) {
this.shiftDown = shiftDown;
}
// public boolean isControlDown() {
// return shiftDown;
// private void setControlDown(boolean shiftDown) {
// this.shiftDown = shiftDown;
/**
* Holds info for constructing a single button.
*/
private static final class ButtonInfo {
/**
* This is the name used to construct nodes on the graph of this type.
* Need to coordinate with session.
*/
private String nodeTypeName;
/**
* The name displayed on the button.
*/
private final String displayName;
/**
* The prefixes for images for this button. It is assumed that files
* <prefix>Up.gif, <prefix>Down.gif, <prefix>Off.gif and
* <prefix>Roll.gif are located in the /images directory relative to
* this compiled class.
*/
private final String imagePrefix;
/**
* Tool tip text displayed for the button.
*/
private final String toolTipText;
public ButtonInfo(String nodeTypeName, String displayName,
String imagePrefix, String toolTipText) {
this.nodeTypeName = nodeTypeName;
this.displayName = displayName;
this.imagePrefix = imagePrefix;
this.toolTipText = toolTipText;
}
public String getNodeTypeName() {
return nodeTypeName;
}
public String getDisplayName() {
return displayName;
}
public void setNodeTypeName(String nodeTypeName) {
this.nodeTypeName = nodeTypeName;
}
public String getImagePrefix() {
return imagePrefix;
}
public String getToolTipText() {
return toolTipText;
}
}
} |
#include <common.h>
#include <asm/io.h>
#include <netdev.h>
#include <asm/arch/cpu.h>
#include <asm/arch/power.h>
#include <asm/arch/gpio.h>
#include <asm/arch/pinmux.h>
#include <asm/arch/mmc.h>
#include <asm/arch/sromc.h>
#include <asm/arch/clk.h>
#ifdef <API key>
#include <asm/arch/pwm.h>
#endif
<API key>;
struct exynos4_gpio_part1 *gpio1;
struct exynos4_gpio_part2 *gpio2;
#ifdef CONFIG_SMC911X
static void smc9115_pre_init(void)
{
u32 smc_bw_conf, smc_bc_conf;
/* gpio configuration GPK0CON */
s5p_gpio_cfg_pin(&gpio2->y0, <API key>, GPIO_FUNC(2));
/* Ethernet needs bus width of 16 bits */
smc_bw_conf = SROMC_DATA16_WIDTH(<API key>);
smc_bc_conf = SROMC_BC_TACS(0x0F) | SROMC_BC_TCOS(0x0F)
| SROMC_BC_TACC(0x0F) | SROMC_BC_TCOH(0x0F)
| SROMC_BC_TAH(0x0F) | SROMC_BC_TACP(0x0F)
| SROMC_BC_PMC(0x0F);
/* Select and configure the SROMC bank */
s5p_config_sromc(<API key>, smc_bw_conf, smc_bc_conf);
}
#endif
#ifdef <API key>
static void hmdk4412_fan_init(void)
{
u8 fan_duty = 255;
u8 fan_enable = getenv_yesno("odroid_fan_enable");
int fan_duty_ns;
if (fan_enable) {
char *fan_duty_str = getenv("odroid_fan_duty");
if (fan_duty_str != NULL) {
fan_duty = simple_strtoul(fan_duty_str, NULL, 10);
}
fan_duty_ns = fan_duty * 20972 / 255;
pwm_init(0, MUX_DIV_8, 1);
pwm_disable(0);
pwm_config(0, fan_duty_ns, 20972);
pwm_enable(0);
s5p_gpio_cfg_pin(&gpio1->d0, 0, GPIO_FUNC(2));
}
}
#endif
int board_init(void)
{
u8 read_id;
u8 read_vol_arm = 0x0;
u8 read_vol_int = 0x0;
u8 read_vol_g3d = 0x0;
u8 read_vol_mif = 0x0;
u8 read_pmic_id = 0x0;
unsigned int vol_conv;
int OmPin = readl(EXYNOS4_POWER_BASE + INFORM3_OFFSET);
char bl1_version[9] = {0};
gpio1 = (struct exynos4_gpio_part1 *) <API key>;
gpio2 = (struct exynos4_gpio_part2 *) <API key>;
/* display BL1 version */
#ifdef CONFIG_TRUSTZONE
printf("\nTrustZone Enabled BSP");
strncpy(&bl1_version[0], (char *)(<API key> + 0x810), 8);
#else
strncpy(&bl1_version[0], (char *)0x020233c8, 8);
#endif
printf("\nBL1 version: %s\n", &bl1_version[0]);
#if !defined(<API key>)
IIC0_ERead(0xcc, 0, &read_id);
if (read_id == 0x77) {
IIC0_ERead(0xcc, 0x19, &read_vol_arm);
IIC0_ERead(0xcc, 0x22, &read_vol_int);
IIC0_ERead(0xcc, 0x2B, &read_vol_g3d);
//IIC0_ERead(0xcc, 0x2D, &read_vol_mif);
} else if ((0 <= read_id) && (read_id <= 0x5)) {
IIC0_ERead(0xcc, 0x33, &read_vol_mif);
IIC0_ERead(0xcc, 0x35, &read_vol_arm);
IIC0_ERead(0xcc, 0x3E, &read_vol_int);
IIC0_ERead(0xcc, 0x47, &read_vol_g3d);
} else {
IIC0_ERead(0x12, 0x11, &read_vol_mif);
IIC0_ERead(0x12, 0x14, &read_vol_arm);
IIC0_ERead(0x12, 0x1E, &read_vol_int);
IIC0_ERead(0x12, 0x28, &read_vol_g3d);
}
printf("vol_arm: %X\n", read_vol_arm);
printf("vol_int: %X\n", read_vol_int);
printf("vol_g3d: %X\n", read_vol_g3d);
printf("vol_mif: %X\n", read_vol_mif);
#else
if(pmic_read(0x00, &read_pmic_id, 1)) printf("pmic read error!\n");
else
printf("PMIC VER : %X, CHIP REV : %X\n", (read_pmic_id & 0x78) >> 3, (read_pmic_id & 0x07));
if(pmic_read(0x11, &read_vol_mif, 1)) printf("pmic read error!\n");
else
{
vol_conv = 750000 + (read_vol_mif >> 3) * 50000;
printf("VDD MIF : %d.%05dV\n", vol_conv / 1000000, vol_conv % 1000000);
}
if(pmic_read(0x14, &read_vol_arm, 1)) printf("pmic read error!\n");
else
{
vol_conv = 600000 + read_vol_arm * 12500;
printf("VDD ARM : %d.%05dV\n", vol_conv / 1000000, vol_conv % 1000000);
}
if(pmic_read(0x1E, &read_vol_int, 1)) printf("pmic read error!\n");
else
{
vol_conv = 600000 + read_vol_int * 12500;
printf("VDD INT : %d.%05dV\n", vol_conv / 1000000, vol_conv % 1000000);
}
if(pmic_read(0x28, &read_vol_g3d, 1)) printf("pmic read error!\n");
else
{
vol_conv = 600000 + read_vol_g3d * 12500;
printf("VDD G3D : %d.%05dV\n", vol_conv / 1000000, vol_conv % 1000000);
}
#endif
#ifdef CONFIG_SMC911X
smc9115_pre_init();
#endif
gd->bd->bi_boot_params = (PHYS_SDRAM_1 + 0x100UL);
printf("\nChecking Boot Mode ...");
switch (OmPin) {
case BOOT_ONENAND:
printf(" OneNand\n");
break;
case BOOT_NAND:
printf(" NAND\n");
break;
case BOOT_MMCSD:
printf(" SDMMC\n");
break;
case BOOT_EMMC:
printf(" EMMC4.3\n");
break;
case BOOT_EMMC_4_4:
printf(" EMMC4.41\n");
break;
default:
break;
}
return 0;
}
int dram_init(void)
{
gd->ram_size = get_ram_size((long *)PHYS_SDRAM_1, PHYS_SDRAM_1_SIZE)
+ get_ram_size((long *)PHYS_SDRAM_2, PHYS_SDRAM_2_SIZE)
+ get_ram_size((long *)PHYS_SDRAM_3, PHYS_SDRAM_3_SIZE)
+ get_ram_size((long *)PHYS_SDRAM_4, PHYS_SDRAM_4_SIZE);
#ifdef USE_2G_DRAM
gd->ram_size += get_ram_size((long *)PHYS_SDRAM_5, PHYS_SDRAM_5_SIZE)
+ get_ram_size((long *)PHYS_SDRAM_6, PHYS_SDRAM_6_SIZE)
+ get_ram_size((long *)PHYS_SDRAM_7, PHYS_SDRAM_7_SIZE)
+ get_ram_size((long *)PHYS_SDRAM_8, PHYS_SDRAM_8_SIZE);
#endif
return 0;
}
void dram_init_banksize(void)
{
gd->bd->bi_dram[0].start = PHYS_SDRAM_1;
gd->bd->bi_dram[0].size = get_ram_size((long *)PHYS_SDRAM_1, \
PHYS_SDRAM_1_SIZE);
gd->bd->bi_dram[1].start = PHYS_SDRAM_2;
gd->bd->bi_dram[1].size = get_ram_size((long *)PHYS_SDRAM_2, \
PHYS_SDRAM_2_SIZE);
gd->bd->bi_dram[2].start = PHYS_SDRAM_3;
gd->bd->bi_dram[2].size = get_ram_size((long *)PHYS_SDRAM_3, \
PHYS_SDRAM_3_SIZE);
gd->bd->bi_dram[3].start = PHYS_SDRAM_4;
gd->bd->bi_dram[3].size = get_ram_size((long *)PHYS_SDRAM_4, \
PHYS_SDRAM_4_SIZE);
#ifdef USE_2G_DRAM
gd->bd->bi_dram[4].start = PHYS_SDRAM_5;
gd->bd->bi_dram[4].size = get_ram_size((long *)PHYS_SDRAM_5, \
PHYS_SDRAM_5_SIZE);
gd->bd->bi_dram[5].start = PHYS_SDRAM_6;
gd->bd->bi_dram[5].size = get_ram_size((long *)PHYS_SDRAM_6, \
PHYS_SDRAM_6_SIZE);
gd->bd->bi_dram[6].start = PHYS_SDRAM_7;
gd->bd->bi_dram[6].size = get_ram_size((long *)PHYS_SDRAM_7, \
PHYS_SDRAM_7_SIZE);
gd->bd->bi_dram[7].start = PHYS_SDRAM_8;
gd->bd->bi_dram[7].size = get_ram_size((long *)PHYS_SDRAM_8, \
PHYS_SDRAM_8_SIZE);
#endif
}
int board_eth_init(bd_t *bis)
{
int rc = 0;
#ifdef CONFIG_SMC911X
rc = smc911x_initialize(0, CONFIG_SMC911X_BASE);
#endif
#ifdef CONFIG_USB_ETHER
setenv("stdin", "serial");
setenv("stdout", "serial");
setenv("stderr", "serial");
rc = usb_eth_initialize(bis);
#endif
return rc;
}
#ifdef <API key>
int checkboard(void)
{
#ifdef CONFIG_EXYNOS4412
printf("\nBoard: SMDK4412\n");
#else
printf("\nBoard: SMDK4212\n");
#endif
return 0;
}
#endif
#ifdef CONFIG_GENERIC_MMC
int board_mmc_init(bd_t *bis)
{
int i, err, OmPin;
u32 clock;
OmPin = readl(EXYNOS4_POWER_BASE + INFORM3_OFFSET);
/*
* MMC2 SD card GPIO:
*
* GPK2[0] SD_2_CLK(2)
* GPK2[1] SD_2_CMD(2)
* GPK2[2] SD_2_CDn
* GPK2[3:6] SD_2_DATA[0:3](2)
*/
for (i = 0; i < 7; i++) {
/* GPK2[0:6] special function 2 */
s5p_gpio_cfg_pin(&gpio2->k2, i, GPIO_FUNC(0x2));
/* GPK2[0:6] drv 4x */
s5p_gpio_set_drv(&gpio2->k2, i, GPIO_DRV_4X);
/* GPK2[0:1] pull disable */
if (i == 0 || i == 1) {
s5p_gpio_set_pull(&gpio2->k2, i, GPIO_PULL_NONE);
continue;
}
/* GPK2[2:6] pull up */
s5p_gpio_set_pull(&gpio2->k2, i, GPIO_PULL_UP);
}
/*
* MMC4 MSHC GPIO:
*
* GPK0[0] SD_4_CLK
* GPK0[1] SD_4_CMD
* GPK0[2] SD_4_CDn
* GPK0[3:6] SD_4_DATA[0:3]
* GPK1[3:6] SD_4_DATA[4:7]
*/
for (i = 0; i < 7; i++) {
/* GPK0[0:6] special function 3 */
s5p_gpio_cfg_pin(&gpio2->k0, i, GPIO_FUNC(0x3));
/* GPK0[0:6] drv 4x */
s5p_gpio_set_drv(&gpio2->k0, i, GPIO_DRV_4X);
/* GPK0[0:1] pull disable */
if (i == 0 || i == 1) {
s5p_gpio_set_pull(&gpio2->k0, i, GPIO_PULL_NONE);
continue;
}
/* GPK0[2:6] pull up */
s5p_gpio_set_pull(&gpio2->k0, i, GPIO_PULL_UP);
}
for (i = 3; i < 7; i++) {
/* GPK1[3:6] special function 3 */
s5p_gpio_cfg_pin(&gpio2->k1, i, GPIO_FUNC(0x4));
/* GPK1[3:6] drv 4x */
s5p_gpio_set_drv(&gpio2->k1, i, GPIO_DRV_4X);
/* GPK1[3:6] pull up */
s5p_gpio_set_pull(&gpio2->k1, i, GPIO_PULL_UP);
}
/* Drive Strength */
writel(0x00010001, 0x1255009C);
clock = get_pll_clk(MPLL)/1000000;
for(i=0 ; i<=0xf; i++)
{
if((clock /(i+1)) <= 400) {
set_mmc_clk(4, i);
break;
}
}
switch (OmPin) {
case BOOT_EMMC_4_4:
err = s5p_mmc_init(4, 8);
if (err)
printf("MSHC Channel 4 init failed!!!\n");
err = s5p_mmc_init(2, 4);
if (err)
printf("SDHC Channel 2 init failed!!!\n");
break;
default:
err = s5p_mmc_init(2, 4);
if (err)
printf("MSHC Channel 2 init failed!!!\n");
err = s5p_mmc_init(4, 8);
if (err)
printf("SDHC Channel 4 init failed!!!\n");
break;
}
}
#endif
int board_late_init(void)
{
struct exynos4_power *pmu = (struct exynos4_power *)EXYNOS4_POWER_BASE;
struct exynos4_gpio_part2 *gpio2 =
(struct exynos4_gpio_part2 *) <API key>();
int second_boot_info = readl(<API key>);
int err;
#ifdef <API key>
hmdk4412_fan_init();
#endif
err = <API key>(<API key>, PINMUX_FLAG_NONE);
if (err) {
debug("GPX0_0 INPUT not configured\n");
return err;
}
udelay(10);
if ((s5p_gpio_get_value(&gpio2->x0, 0) == 0) || second_boot_info == 1) {
printf("
setenv("bootcmd", <API key>);
/* clear secondary boot inform */
writel(0x0, <API key>);
}
if ((readl(&pmu->inform4)) == <API key>) {
writel(0x0, &pmu->inform4);
setenv("bootcmd", <API key>);
}
return 0;
} |
<?php
$root =dirname(dirname(dirname(dirname(dirname(__FILE__)))));
//echo $root;
if ( file_exists( $root.'/wp-load.php' ) ) {
require_once( $root.'/wp-load.php' );
} elseif ( file_exists( $root.'/wp-config.php' ) ) {
require_once( $root.'/wp-config.php' );
}
header("Content-type: text/css; charset=utf-8");
global $theme_option;
function hex2rgb($hex) {
$hex = str_replace("#", "", $hex);
if(strlen($hex) == 3) {
$r = hexdec(substr($hex,0,1).substr($hex,0,1));
$g = hexdec(substr($hex,1,1).substr($hex,1,1));
$b = hexdec(substr($hex,2,1).substr($hex,2,1));
} else {
$r = hexdec(substr($hex,0,2));
$g = hexdec(substr($hex,2,2));
$b = hexdec(substr($hex,4,2));
}
$rgb = array($r, $g, $b);
//return implode(",", $rgb); // returns the rgb values separated by commas
return $rgb; // returns an array with the rgb values
}
$b=$theme_option['main-color'];
$rgba = hex2rgb($b);
?>
a {
color: <?php echo $theme_option['main-color']; ?>;
}
::selection {
color: #fff;
background: <?php echo $theme_option['main-color']; ?>;
}
::-moz-selection {
color: #fff;
background: <?php echo $theme_option['main-color']; ?>;
}
.item a .desc {background: rgba(<?php echo $rgba[0]; ?>, <?php echo $rgba[1]; ?>, <?php echo $rgba[2]; ?>, 0.95);}
.aboutSocial li, .aboutSocial li a, ul#category li a:hover, #category .current a,
.postMeta a:hover, .postDetails .more a:hover, .commentContent .date a, .searchForm .submitSearch,
.widget_categories li, .widget_archive li a,.widget_meta abbr, .widget_categories li span.countCat
{color: <?php echo $theme_option['main-color']; ?>;}
.tagsListSingle li a, #wp-calendar tbody td#today, .download, .download span, .download i,
.dtIco span.date, .getCv i, .postCount.short h3, .tagsListSingle li a
{background: <?php echo $theme_option['main-color']; ?>;}
#category .current a:after {border-bottom: 1px solid <?php echo $theme_option['main-color']; ?>;}
.footerholder {
background: none repeat scroll 0 0 <?php echo $theme_option['background-footer']; ?>;
color: <?php echo $theme_option['color-footer']; ?>;
}
.footerholder p {color: <?php echo $theme_option['color-footer']; ?>;} |
#ifndef __VIDC_HFI_API_H__
#define __VIDC_HFI_API_H__
#include <linux/log2.h>
#include <linux/platform_device.h>
#include <linux/types.h>
#include <media/msm_vidc.h>
#include "msm_vidc_resources.h"
#define CONTAINS(__a, __sz, __t) ({\
int __rc = __t >= __a && \
__t < __a + __sz; \
__rc; \
})
#define OVERLAPS(__t, __tsz, __a, __asz) ({\
int __rc = __t <= __a && \
__t + __tsz >= __a + __asz; \
__rc; \
})
#define HAL_BUFFERFLAG_EOS 0x00000001
#define <API key> 0x00000002
#define <API key> 0x00000004
#define <API key> 0x00000008
#define <API key> 0x00000010
#define <API key> 0x00000020
#define <API key> 0x00000040
#define <API key> 0x00000080
#define <API key> 0x00000100
#define <API key> 0x00000200
#define <API key> 0x00000400
#define <API key> 0x00200000
#define <API key> 0x08000000
#define <API key> 0x10000000
#define <API key> 0x20000000
#define <API key> 0x40000000
#define <API key> 0x80000000
#define HAL_DEBUG_MSG_LOW 0x00000001
#define <API key> 0x00000002
#define HAL_DEBUG_MSG_HIGH 0x00000004
#define HAL_DEBUG_MSG_ERROR 0x00000008
#define HAL_DEBUG_MSG_FATAL 0x00000010
#define MAX_PROFILE_COUNT 16
enum vidc_status {
VIDC_ERR_NONE = 0x0,
VIDC_ERR_FAIL = 0x80000000,
VIDC_ERR_ALLOC_FAIL,
VIDC_ERR_ILLEGAL_OP,
VIDC_ERR_BAD_PARAM,
VIDC_ERR_BAD_HANDLE,
<API key>,
VIDC_ERR_BAD_STATE,
<API key>,
<API key>,
VIDC_ERR_HW_FATAL,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
VIDC_ERR_TIMEOUT,
VIDC_ERR_CMDQFULL,
<API key>,
<API key> = 0x90000001,
<API key>,
<API key>,
VIDC_ERR_UNUSED = 0x10000000
};
enum hal_extradata_id {
HAL_EXTRADATA_NONE,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
HAL_EXTRADATA_INDEX,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
};
enum hal_property {
<API key> = 0x04000001,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
HAL_CONFIG_REALTIME,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
HAL_CONFIG_PRIORITY,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
};
enum hal_domain {
<API key>,
<API key>,
<API key>,
HAL_UNUSED_DOMAIN = 0x10000000,
};
enum multi_stream {
<API key> = 0x00000000,
<API key> = 0x00000001,
<API key> = 0x00000002,
<API key> = 0x00000004,
<API key> = 0x10000000,
};
enum <API key> {
<API key> = 0x00000001,
<API key> = 0x00000002,
<API key> = 0x00000004,
<API key> = 0x00000008,
<API key> = 0x10000000,
};
enum hal_video_codec {
<API key> = 0x00000000,
HAL_VIDEO_CODEC_MVC = 0x00000001,
<API key> = 0x00000002,
<API key> = 0x00000004,
<API key> = 0x00000008,
<API key> = 0x00000010,
<API key> = 0x00000020,
<API key> = 0x00000040,
<API key> = 0x00000080,
HAL_VIDEO_CODEC_VC1 = 0x00000100,
<API key> = 0x00000200,
HAL_VIDEO_CODEC_VP6 = 0x00000400,
HAL_VIDEO_CODEC_VP7 = 0x00000800,
HAL_VIDEO_CODEC_VP8 = 0x00001000,
<API key> = 0x00002000,
<API key> = 0x00004000,
HAL_UNUSED_CODEC = 0x10000000,
};
enum hal_h263_profile {
<API key> = 0x00000001,
<API key> = 0x00000002,
<API key> = 0x00000004,
<API key> = 0x00000008,
<API key> = 0x00000010,
<API key> = 0x00000020,
<API key> = 0x00000040,
<API key> = 0x00000080,
<API key> = 0x00000100,
<API key> = 0x10000000,
};
enum hal_h263_level {
HAL_H263_LEVEL_10 = 0x00000001,
HAL_H263_LEVEL_20 = 0x00000002,
HAL_H263_LEVEL_30 = 0x00000004,
HAL_H263_LEVEL_40 = 0x00000008,
HAL_H263_LEVEL_45 = 0x00000010,
HAL_H263_LEVEL_50 = 0x00000020,
HAL_H263_LEVEL_60 = 0x00000040,
HAL_H263_LEVEL_70 = 0x00000080,
<API key> = 0x10000000,
};
enum hal_mpeg2_profile {
<API key> = 0x00000001,
<API key> = 0x00000002,
<API key> = 0x00000004,
<API key> = 0x00000008,
<API key> = 0x00000010,
<API key> = 0x00000020,
<API key> = 0x10000000,
};
enum hal_mpeg2_level {
HAL_MPEG2_LEVEL_LL = 0x00000001,
HAL_MPEG2_LEVEL_ML = 0x00000002,
HAL_MPEG2_LEVEL_H14 = 0x00000004,
HAL_MPEG2_LEVEL_HL = 0x00000008,
<API key> = 0x10000000,
};
enum hal_mpeg4_profile {
<API key> = 0x00000001,
<API key> = 0x00000002,
<API key> = 0x00000004,
<API key> = 0x00000008,
<API key> = 0x00000010,
<API key> = 0x00000020,
<API key> = 0x00000040,
<API key> = 0x00000080,
<API key> = 0x00000100,
<API key> = 0x00000200,
<API key> = 0x00000400,
<API key> = 0x00000800,
<API key> = 0x00001000,
<API key> = 0x00002000,
<API key> = 0x00004000,
<API key> = 0x00008000,
<API key> = 0x10000000,
};
enum hal_mpeg4_level {
HAL_MPEG4_LEVEL_0 = 0x00000001,
HAL_MPEG4_LEVEL_0b = 0x00000002,
HAL_MPEG4_LEVEL_1 = 0x00000004,
HAL_MPEG4_LEVEL_2 = 0x00000008,
HAL_MPEG4_LEVEL_3 = 0x00000010,
HAL_MPEG4_LEVEL_4 = 0x00000020,
HAL_MPEG4_LEVEL_4a = 0x00000040,
HAL_MPEG4_LEVEL_5 = 0x00000080,
<API key> = 0x7F000000,
HAL_MPEG4_LEVEL_6 = 0x7F000001,
HAL_MPEG4_LEVEL_7 = 0x7F000002,
HAL_MPEG4_LEVEL_8 = 0x7F000003,
HAL_MPEG4_LEVEL_9 = 0x7F000004,
HAL_MPEG4_LEVEL_3b = 0x7F000005,
<API key> = 0x10000000,
};
enum hal_h264_profile {
<API key> = 0x00000001,
<API key> = 0x00000002,
<API key> = 0x00000004,
<API key> = 0x00000008,
<API key> = 0x00000010,
<API key> = 0x00000020,
<API key> = 0x00000040,
<API key> = 0x00000080,
<API key> = 0x00000100,
<API key> = 0x10000000,
};
enum hal_h264_level {
HAL_H264_LEVEL_1 = 0x00000001,
HAL_H264_LEVEL_1b = 0x00000002,
HAL_H264_LEVEL_11 = 0x00000004,
HAL_H264_LEVEL_12 = 0x00000008,
HAL_H264_LEVEL_13 = 0x00000010,
HAL_H264_LEVEL_2 = 0x00000020,
HAL_H264_LEVEL_21 = 0x00000040,
HAL_H264_LEVEL_22 = 0x00000080,
HAL_H264_LEVEL_3 = 0x00000100,
HAL_H264_LEVEL_31 = 0x00000200,
HAL_H264_LEVEL_32 = 0x00000400,
HAL_H264_LEVEL_4 = 0x00000800,
HAL_H264_LEVEL_41 = 0x00001000,
HAL_H264_LEVEL_42 = 0x00002000,
HAL_H264_LEVEL_5 = 0x00004000,
HAL_H264_LEVEL_51 = 0x00008000,
HAL_H264_LEVEL_52 = 0x00010000,
<API key> = 0x10000000,
};
enum hal_hevc_profile {
<API key> = 0x00000001,
<API key> = 0x00000002,
<API key> = 0x00000004,
<API key> = 0x10000000,
};
enum hal_hevc_level {
<API key> = 0x10000001,
<API key> = 0x10000002,
<API key> = 0x10000004,
<API key> = 0x10000008,
<API key> = 0x10000010,
<API key> = 0x10000020,
<API key> = 0x10000040,
<API key> = 0x10000080,
<API key> = 0x10000100,
<API key> = 0x10000200,
<API key> = 0x10000400,
<API key> = 0x10000800,
<API key> = 0x10001000,
<API key> = 0x20000001,
<API key> = 0x20000002,
<API key> = 0x20000004,
<API key> = 0x20000008,
<API key> = 0x20000010,
<API key> = 0x20000020,
<API key> = 0x20000040,
<API key> = 0x20000080,
<API key> = 0x20000100,
<API key> = 0x20000200,
<API key> = 0x20000400,
<API key> = 0x20000800,
<API key> = 0x20001000,
<API key> = 0x80000000,
};
enum hal_hevc_tier {
HAL_HEVC_TIER_MAIN = 0x00000001,
HAL_HEVC_TIER_HIGH = 0x00000002,
<API key> = 0x10000000,
};
enum hal_vpx_profile {
<API key> = 0x00000001,
<API key> = 0x00000002,
<API key> = 0x00000004,
<API key> = 0x00000008,
<API key> = 0x00000010,
<API key> = 0x00000020,
<API key> = 0x10000000,
};
enum hal_vc1_profile {
<API key> = 0x00000001,
<API key> = 0x00000002,
<API key> = 0x00000004,
<API key> = 0x10000000,
};
enum hal_vc1_level {
HAL_VC1_LEVEL_LOW = 0x00000001,
<API key> = 0x00000002,
HAL_VC1_LEVEL_HIGH = 0x00000004,
HAL_VC1_LEVEL_0 = 0x00000008,
HAL_VC1_LEVEL_1 = 0x00000010,
HAL_VC1_LEVEL_2 = 0x00000020,
HAL_VC1_LEVEL_3 = 0x00000040,
HAL_VC1_LEVEL_4 = 0x00000080,
<API key> = 0x10000000,
};
enum hal_divx_format {
HAL_DIVX_FORMAT_4,
HAL_DIVX_FORMAT_5,
HAL_DIVX_FORMAT_6,
<API key> = 0x10000000,
};
enum hal_divx_profile {
<API key> = 0x00000001,
<API key> = 0x00000002,
HAL_DIVX_PROFILE_MT = 0x00000004,
HAL_DIVX_PROFILE_HT = 0x00000008,
HAL_DIVX_PROFILE_HD = 0x00000010,
<API key> = 0x10000000,
};
enum hal_mvc_profile {
<API key> = 0x00001000,
<API key> = 0x10000000,
};
enum hal_mvc_level {
HAL_MVC_LEVEL_1 = 0x00000001,
HAL_MVC_LEVEL_1b = 0x00000002,
HAL_MVC_LEVEL_11 = 0x00000004,
HAL_MVC_LEVEL_12 = 0x00000008,
HAL_MVC_LEVEL_13 = 0x00000010,
HAL_MVC_LEVEL_2 = 0x00000020,
HAL_MVC_LEVEL_21 = 0x00000040,
HAL_MVC_LEVEL_22 = 0x00000080,
HAL_MVC_LEVEL_3 = 0x00000100,
HAL_MVC_LEVEL_31 = 0x00000200,
HAL_MVC_LEVEL_32 = 0x00000400,
HAL_MVC_LEVEL_4 = 0x00000800,
HAL_MVC_LEVEL_41 = 0x00001000,
HAL_MVC_LEVEL_42 = 0x00002000,
HAL_MVC_LEVEL_5 = 0x00004000,
HAL_MVC_LEVEL_51 = 0x00008000,
<API key> = 0x10000000,
};
struct hal_frame_rate {
enum hal_buffer buffer_type;
u32 frame_rate;
};
enum <API key> {
<API key> = 0x00000001,
<API key> = 0x00000002,
<API key> = 0x00000004,
<API key> = 0x00000008,
<API key> = 0x00000010,
<API key> = 0x00000020,
<API key> = 0x00000040,
<API key> = 0x00000080,
<API key> = 0x00000100,
<API key> = 0x00000200,
<API key> = 0x00000400,
<API key> = 0x00000800,
<API key> = 0x00001000,
HAL_UNUSED_COLOR = 0x10000000,
};
enum <API key> {
SSR_ERR_FATAL = 1,
SSR_SW_DIV_BY_ZERO,
SSR_HW_WDOG_IRQ,
};
struct <API key> {
enum hal_buffer buffer_type;
enum <API key> format;
};
struct <API key> {
int actual_stride;
u32 <API key>;
};
struct <API key> {
enum hal_buffer buffer_type;
u32 num_planes;
struct <API key> rg_plane_format[1];
};
struct <API key> {
u32 stride_multiples;
u32 max_stride;
u32 <API key>;
u32 buffer_alignment;
};
struct <API key> {
enum hal_buffer buffer_type;
u32 num_planes;
struct <API key> rg_plane_format[1];
};
struct <API key> {
u32 type;
enum hal_buffer buffer_type;
u32 version;
u32 port_index;
u32 client_extradata_id;
};
struct hal_frame_size {
enum hal_buffer buffer_type;
u32 width;
u32 height;
};
struct hal_enable {
u32 enable;
};
struct <API key> {
enum hal_buffer buffer_type;
u32 buffer_count_actual;
};
enum <API key> {
<API key> = 0x00000001,
<API key> = 0x00000002,
<API key> = 0x00000004,
<API key> = 0x00000008,
<API key> = 0x00000010,
};
enum hal_output_order {
<API key>,
<API key>,
HAL_UNUSED_OUTPUT = 0x10000000,
};
enum hal_picture {
HAL_PICTURE_I = 0x01,
HAL_PICTURE_P = 0x02,
HAL_PICTURE_B = 0x04,
HAL_PICTURE_IDR = 0x08,
HAL_FRAME_NOTCODED = 0x7F002000,
HAL_FRAME_YUV = 0x7F004000,
HAL_UNUSED_PICT = 0x10000000,
};
struct <API key> {
u32 enable;
enum hal_extradata_id index;
};
struct hal_enable_picture {
u32 picture_type;
};
struct hal_multi_stream {
enum hal_buffer buffer_type;
u32 enable;
u32 width;
u32 height;
};
struct <API key> {
u32 enable;
u32 count;
};
struct hal_mb_error_map {
u32 error_map_size;
u8 rg_error_map[1];
};
struct hal_request_iframe {
u32 enable;
};
struct hal_bitrate {
u32 bit_rate;
u32 layer_id;
};
struct hal_profile_level {
u32 profile;
u32 level;
};
struct <API key> {
u32 profile_count;
struct hal_profile_level profile_level[MAX_PROFILE_COUNT];
};
enum hal_h264_entropy {
<API key> = 1,
<API key> = 2,
HAL_UNUSED_ENTROPY = 0x10000000,
};
enum <API key> {
<API key> = 1,
<API key> = 2,
<API key> = 4,
HAL_UNUSED_CABAC = 0x10000000,
};
struct <API key> {
enum hal_h264_entropy entropy_mode;
enum <API key> cabac_model;
};
enum hal_rate_control {
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
HAL_UNUSED_RC = 0x10000000,
};
struct <API key> {
u32 <API key>;
};
struct <API key> {
u32 header_extension;
};
enum hal_h264_db_mode {
<API key>,
<API key>,
<API key>,
HAL_UNUSED_H264_DB = 0x10000000,
};
struct hal_h264_db_control {
enum hal_h264_db_mode mode;
int slice_alpha_offset;
int slice_beta_offset;
};
struct <API key> {
u32 ts_factor;
};
struct hal_quantization {
u32 qpi;
u32 qpp;
u32 qpb;
u32 layer_id;
};
struct <API key> {
u32 qpi;
u32 qpp;
u32 qpb;
u32 init_qp_enable;
};
struct <API key> {
u32 min_qp;
u32 max_qp;
u32 layer_id;
};
struct hal_intra_period {
u32 pframes;
u32 bframes;
};
struct hal_idr_period {
u32 idr_period;
};
enum hal_rotate {
HAL_ROTATE_NONE,
HAL_ROTATE_90,
HAL_ROTATE_180,
HAL_ROTATE_270,
HAL_UNUSED_ROTATE = 0x10000000,
};
enum hal_flip {
HAL_FLIP_NONE,
HAL_FLIP_HORIZONTAL,
HAL_FLIP_VERTICAL,
HAL_UNUSED_FLIP = 0x10000000,
};
struct hal_operations {
enum hal_rotate rotate;
enum hal_flip flip;
};
enum <API key> {
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
HAL_UNUSED_INTRA = 0x10000000,
};
struct hal_intra_refresh {
enum <API key> mode;
u32 air_mbs;
u32 air_ref;
u32 cir_mbs;
};
enum hal_multi_slice {
HAL_MULTI_SLICE_OFF,
<API key>,
<API key>,
HAL_MULTI_SLICE_GOB,
HAL_UNUSED_SLICE = 0x10000000,
};
struct <API key> {
enum hal_multi_slice multi_slice;
u32 slice_size;
};
struct hal_debug_config {
u32 debug_config;
};
struct <API key> {
enum hal_buffer buffer_type;
u32 buffer_size;
u32 buffer_region_size;
u32 buffer_hold_count;
u32 buffer_count_min;
u32 buffer_count_actual;
u32 contiguous;
u32 buffer_alignment;
};
enum hal_priority {/* Priority increases with number */
HAL_PRIORITY_LOW = 10,
HAL_PRIOIRTY_MEDIUM = 20,
HAL_PRIORITY_HIGH = 30,
HAL_UNUSED_PRIORITY = 0x10000000,
};
struct hal_batch_info {
u32 input_batch_count;
u32 output_batch_count;
};
struct <API key> {
u32 enable;
u32 size;
};
struct <API key> {
enum hal_buffer buffer_type;
u32 format_entries;
u32 rg_format_info[1];
};
enum <API key> {
<API key> = 0x01,
<API key> = 0x02,
<API key> = 0x04,
<API key> = 0x08,
<API key> = 0x10,
<API key> = 0x10000000,
};
struct <API key> {
enum hal_buffer buffer_type;
enum <API key> format;
};
enum hal_chroma_site {
HAL_CHROMA_SITE_0,
HAL_CHROMA_SITE_1,
HAL_UNUSED_CHROMA = 0x10000000,
};
struct <API key> {
u32 num_properties;
u32 rg_properties[1];
};
enum hal_capability {
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key> = 0x10000000,
};
struct <API key> {
enum hal_capability capability_type;
u32 min;
u32 max;
u32 step_size;
};
struct <API key> {
u32 num_capabilities;
struct <API key> rg_data[1];
};
struct <API key> {
u32 <API key>;
};
struct <API key> {
u32 <API key>;
};
struct <API key> {
u32 views;
u32 rg_view_order[1];
};
enum <API key> {
<API key>,
<API key>,
<API key> = 0x10000000,
};
struct <API key> {
enum <API key> layout_type;
u32 bright_view_first;
u32 ngap;
};
struct hal_seq_header_info {
u32 nax_header_len;
};
struct hal_codec_supported {
u32 <API key>;
u32 <API key>;
};
struct <API key> {
u32 view_index;
};
struct hal_timestamp_scale {
u32 time_stamp_scale;
};
struct <API key> {
u32 enable;
u32 fixed_frame_rate;
u32 time_scale;
};
struct <API key> {
u32 enable;
};
struct <API key> {
u32 enable;
};
struct <API key> {
struct {
u32 x_subsampled;
u32 y_subsampled;
} i_frame, p_frame, b_frame;
};
enum vidc_resource_id {
VIDC_RESOURCE_OCMEM = 0x00000001,
<API key> = 0x10000000,
};
struct vidc_resource_hdr {
enum vidc_resource_id resource_id;
u32 resource_handle;
u32 size;
};
struct <API key> {
enum hal_buffer buffer_type;
u32 buffer_size;
u32 num_buffers;
ion_phys_addr_t align_device_addr;
ion_phys_addr_t extradata_addr;
u32 extradata_size;
u32 response_required;
};
/* Needs to be exactly the same as hfi_buffer_info */
struct hal_buffer_info {
u32 buffer_addr;
u32 extra_data_addr;
};
struct <API key> {
u32 left;
u32 top;
u32 width;
u32 height;
u32 stride;
u32 scan_lines;
};
struct <API key> {
struct <API key> luma_plane;
struct <API key> chroma_plane;
};
struct vidc_frame_data {
enum hal_buffer buffer_type;
ion_phys_addr_t device_addr;
ion_phys_addr_t extradata_addr;
int64_t timestamp;
u32 flags;
u32 offset;
u32 alloc_len;
u32 filled_len;
u32 mark_target;
u32 mark_data;
u32 clnt_data;
u32 extradata_size;
};
struct vidc_seq_hdr {
ion_phys_addr_t seq_hdr;
u32 seq_hdr_len;
};
enum hal_flush {
HAL_FLUSH_INPUT,
HAL_FLUSH_OUTPUT,
HAL_FLUSH_OUTPUT2,
HAL_FLUSH_ALL,
HAL_UNUSED_FLUSH = 0x10000000,
};
enum hal_event_type {
<API key>,
<API key>,
<API key>,
HAL_UNUSED_SEQCHG = 0x10000000,
};
enum buffer_mode_type {
<API key> = 0x001,
<API key> = 0x010,
<API key> = 0x100,
};
struct <API key> {
enum hal_buffer buffer_type;
enum buffer_mode_type buffer_mode;
};
enum ltr_mode {
<API key>,
HAL_LTR_MODE_MANUAL,
<API key>,
};
struct hal_ltrmode {
enum ltr_mode ltrmode;
u32 ltrcount;
u32 trustmode;
};
struct hal_ltruse {
u32 refltr;
u32 useconstrnt;
u32 frames;
};
struct hal_ltrmark {
u32 markframe;
};
struct hal_venc_perf_mode {
u32 mode;
};
struct hfi_scs_threshold {
u32 threshold_value;
};
struct buffer_requirements {
struct <API key> buffer[HAL_BUFFER_MAX];
};
union hal_get_property {
struct hal_frame_rate frame_rate;
struct <API key> format_select;
struct <API key> plane_actual;
struct <API key> plane_actual_info;
struct <API key> plane_constraints;
struct <API key>
<API key>;
struct <API key> <API key>;
struct hal_frame_size frame_size;
struct hal_enable enable;
struct <API key> buffer_count_actual;
struct <API key> extradata_enable;
struct hal_enable_picture enable_picture;
struct hal_multi_stream multi_stream;
struct <API key> <API key>;
struct hal_mb_error_map mb_error_map;
struct hal_request_iframe request_iframe;
struct hal_bitrate bitrate;
struct hal_profile_level profile_level;
struct <API key> <API key>;
struct <API key> <API key>;
struct <API key> <API key>;
struct <API key> <API key>;
struct hal_h264_db_control h264_db_control;
struct <API key> <API key>;
struct hal_quantization quantization;
struct <API key> quantization_range;
struct hal_intra_period intra_period;
struct hal_idr_period idr_period;
struct hal_operations operations;
struct hal_intra_refresh intra_refresh;
struct <API key> multi_slice_control;
struct hal_debug_config debug_config;
struct hal_batch_info batch_info;
struct <API key> <API key>;
struct <API key> <API key>;
struct <API key> <API key>;
struct <API key> <API key>;
struct <API key> <API key>;
struct <API key> <API key>;
struct <API key> <API key>;
struct <API key> <API key>;
struct <API key> multi_view_format;
struct hal_seq_header_info seq_header_info;
struct hal_codec_supported codec_supported;
struct <API key> multi_view_select;
struct hal_timestamp_scale timestamp_scale;
struct <API key> <API key>;
struct <API key> <API key>;
struct <API key> <API key>;
struct hal_buffer_info buffer_info;
struct <API key> buffer_alloc_mode;
struct buffer_requirements buf_req;
};
/* HAL Response */
enum command_response {
/* SYSTEM COMMANDS_DONE*/
VIDC_EVENT_CHANGE,
SYS_INIT_DONE,
SET_RESOURCE_DONE,
<API key>,
PING_ACK_DONE,
PC_PREP_DONE,
SYS_IDLE,
SYS_DEBUG,
<API key>,
SYS_ERROR,
/* SESSION COMMANDS_DONE */
<API key>,
SESSION_INIT_DONE,
SESSION_END_DONE,
SESSION_ABORT_DONE,
SESSION_START_DONE,
SESSION_STOP_DONE,
SESSION_ETB_DONE,
SESSION_FTB_DONE,
SESSION_FLUSH_DONE,
<API key>,
SESSION_RESUME_DONE,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>,
SESSION_ERROR,
RESPONSE_UNUSED = 0x10000000,
};
/* Command Callback structure */
struct <API key> {
u32 device_id;
void *session_id;
enum vidc_status status;
u32 size;
void *data;
};
struct msm_vidc_cb_event {
u32 device_id;
u32 session_id;
enum vidc_status status;
u32 height;
u32 width;
u32 hal_event_type;
ion_phys_addr_t packet_buffer;
ion_phys_addr_t extra_data_buffer;
};
/* Data callback structure */
struct vidc_hal_ebd {
u32 timestamp_hi;
u32 timestamp_lo;
u32 flags;
enum vidc_status status;
u32 mark_target;
u32 mark_data;
u32 stats;
u32 offset;
u32 alloc_len;
u32 filled_len;
enum hal_picture picture_type;
ion_phys_addr_t packet_buffer;
ion_phys_addr_t extra_data_buffer;
};
struct vidc_hal_fbd {
u32 stream_id;
u32 view_id;
u32 timestamp_hi;
u32 timestamp_lo;
u32 flags1;
u32 mark_target;
u32 mark_data;
u32 stats;
u32 alloc_len1;
u32 filled_len1;
u32 offset1;
u32 frame_width;
u32 frame_height;
u32 start_x_coord;
u32 start_y_coord;
u32 input_tag;
u32 input_tag1;
enum hal_picture picture_type;
ion_phys_addr_t packet_buffer1;
ion_phys_addr_t extra_data_buffer;
u32 flags2;
u32 alloc_len2;
u32 filled_len2;
u32 offset2;
ion_phys_addr_t packet_buffer2;
u32 flags3;
u32 alloc_len3;
u32 filled_len3;
u32 offset3;
ion_phys_addr_t packet_buffer3;
enum hal_buffer buffer_type;
};
struct <API key> {
u32 device_id;
void *session_id;
enum vidc_status status;
u32 size;
u32 clnt_data;
union {
struct vidc_hal_ebd input_done;
struct vidc_hal_fbd output_done;
};
};
struct <API key> {
u32 enc_codec_supported;
u32 dec_codec_supported;
};
struct <API key> {
struct <API key> width;
struct <API key> height;
struct <API key> mbs_per_frame;
struct <API key> mbs_per_sec;
struct <API key> frame_rate;
struct <API key> scale_x;
struct <API key> scale_y;
struct <API key> bitrate;
struct <API key> hier_p;
struct <API key> ltr_count;
struct <API key> <API key>;
struct <API key> uncomp_format;
struct <API key> HAL_format;
struct <API key> nal_stream_format;
struct <API key> profile_level;
/*allocate and released memory for above.*/
struct hal_intra_refresh intra_refresh;
struct hal_seq_header_info seq_hdr_info;
enum buffer_mode_type alloc_mode_out;
};
enum msm_vidc_hfi_type {
VIDC_HFI_VENUS,
VIDC_HFI_Q6,
};
enum fw_info {
FW_BASE_ADDRESS,
FW_REGISTER_BASE,
FW_REGISTER_SIZE,
FW_IRQ,
FW_INFO_MAX,
};
enum <API key> {
<API key> = 0,
/* No declarations exist. Values generated by <API key>
* describe the enumerations e.g.:
*
* enum <API key> <API key> =
* <API key>(<API key>,
* <API key>);
*/
};
/* Careful modifying <API key>().
*
* This macro assigns two bits to each codec: the lower bit denoting the codec
* type, and the higher bit denoting session type. */
static inline enum <API key> <API key>(
enum hal_video_codec c, enum hal_domain d) {
if (d != <API key> && d != <API key>)
return <API key>;
return (1 << ilog2(c) * 2) | ((d - 1) << (ilog2(c) * 2 + 1));
}
struct vidc_bus_vote_data {
enum <API key> session;
int load;
};
#define call_hfi_op(q, op, args...) \
(((q) && (q)->op) ? ((q)->op(args)) : 0)
struct hfi_device {
void *hfi_device_data;
/*Add function pointers for all the hfi functions below*/
int (*core_init)(void *device);
int (*core_release)(void *device);
int (*core_pc_prep)(void *device);
int (*core_ping)(void *device);
int (*core_trigger_ssr)(void *device, enum <API key>);
void *(*session_init)(void *device, void *session_id,
enum hal_domain session_type, enum hal_video_codec codec_type);
int (*session_end)(void *session);
int (*session_abort)(void *session);
int (*session_set_buffers)(void *sess,
struct <API key> *buffer_info);
int (*<API key>)(void *sess,
struct <API key> *buffer_info);
int (*session_load_res)(void *sess);
int (*session_release_res)(void *sess);
int (*session_start)(void *sess);
int (*session_stop)(void *sess);
int (*session_suspend)(void *sess);
int (*session_resume)(void *sess);
int (*session_etb)(void *sess,
struct vidc_frame_data *input_frame);
int (*session_ftb)(void *sess,
struct vidc_frame_data *output_frame);
int (*<API key>)(void *sess,
struct vidc_seq_hdr *seq_hdr);
int (*session_get_seq_hdr)(void *sess,
struct vidc_seq_hdr *seq_hdr);
int (*session_get_buf_req)(void *sess);
int (*session_flush)(void *sess, enum hal_flush flush_mode);
int (*<API key>)(void *sess, enum hal_property ptype,
void *pdata);
int (*<API key>)(void *sess, enum hal_property ptype);
int (*scale_clocks)(void *dev, int load);
int (*vote_bus)(void *dev, struct vidc_bus_vote_data *data,
int num_data);
int (*unvote_bus)(void *dev);
int (*unset_ocmem)(void *dev);
int (*alloc_ocmem)(void *dev, unsigned long size);
int (*free_ocmem)(void *dev);
int (*<API key>)(void *dev, u32 flags, u32 buffer_type,
int *domain_num, int *partition_num);
int (*load_fw)(void *dev);
void (*unload_fw)(void *dev);
int (*get_fw_info)(void *dev, enum fw_info info);
int (*get_stride_scanline)(int color_fmt, int width,
int height, int *stride, int *scanlines);
int (*capability_check)(u32 fourcc, u32 width,
u32 *max_width, u32 *max_height);
int (*session_clean)(void *sess);
int (*<API key>)(void);
int (*power_enable)(void *dev);
int (*suspend)(void *dev);
};
typedef void (*<API key>) (enum command_response cmd,
void *data);
typedef void (*msm_vidc_callback) (u32 response, void *callback);
void *vidc_hfi_initialize(enum msm_vidc_hfi_type hfi_type, u32 device_id,
struct <API key> *res,
<API key> callback);
void <API key>(enum msm_vidc_hfi_type hfi_type,
struct hfi_device *hdev);
#endif /*__VIDC_HFI_API_H__ */ |
starbound-templates
================
A collection of templates for various Starbound asset files. |
body {
margin: 10px;
font: 84% Arial, sans-serif
}
h1 {
font-size: 156%
}
h2 {
border-top: 1px solid #9cc2ef;
background-color: #ebeff9;
padding: 3px 5px;
font-size: 100%
}
#note {
font-size: 75%;
padding: 3px 0px;
} |
import wpilib
from wpilib.command.commandgroup import CommandGroup
class Autonomous(CommandGroup):
def __init__(self, drive, grabber_lift):
super().__init__()
self.drive = drive
self.grabber_lift = grabber_lift
self.addSequential(ClawGrab(grabber_lift))
self.addSequential(MoveLift(grabber_lift, .5), 1.5)
self.addParallel(<API key>(drive, 180))
self.addSequential(ArcadeDrive(drive, 0, 1)) |
<?php
/**
* @file
* Default simple view template to display a list of rows.
*
* @ingroup views_templates
*/
?>
<?php if (!empty($title)): ?>
<h3><?php print $title; ?></h3>
<?php endif; ?>
<?php $i = 0; $len = count($rows); ?>
<?php foreach ($rows as $id => $row): ?>
<?php if($i % $items_per_row == 0): ?>
<div data-equalizer<?php print $row_wrapper_class; ?>>
<?php endif; ?>
<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"'; } print $row_attribute; ?>>
<?php print $row; ?>
</div>
<?php if(($i % $items_per_row == ($items_per_row - 1)) || $i >= ($len - 1)): ?>
</div>
<?php endif; ?>
<?php $i++; ?>
<?php endforeach; ?> |
<?php
require_once <API key> . '/services/Optimization/Filter/Abstract/Base.php';
abstract class <API key>
extends <API key>
{
protected $_filterType = 'head';
} |
package org.openmrs.module.billing.web.controller.company;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.api.context.Context;
import org.openmrs.module.hospitalcore.BillingService;
import org.openmrs.module.hospitalcore.model.Company;
import org.openmrs.module.hospitalcore.util.PagingUtil;
import org.openmrs.module.hospitalcore.util.RequestUtil;
import org.openmrs.web.WebConstants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/module/billing/company.list")
public class <API key> {
Log log = LogFactory.getLog(getClass());
@RequestMapping(method=RequestMethod.POST)
public String deleteCompanies(@RequestParam("ids") String[] ids,HttpServletRequest request){
HttpSession httpSession = request.getSession();
Integer companyId = null;
try{
BillingService billingService = (BillingService)Context.getService(BillingService.class);
if( ids != null && ids.length > 0 ){
for(String sId : ids )
{
companyId = Integer.parseInt(sId);
Company company = billingService.getCompanyById(companyId);
if( company!= null )
{
billingService.deleteCompany(company);
}
}
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
"billing.company.delete.done");
}
}catch (Exception e) {
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
"Can not delete company ");
log.error(e);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
"billing.company.delete.fail");
}
return "redirect:/module/billing/company.list";
}
@RequestMapping(method=RequestMethod.GET)
public String listTender(@RequestParam(value="pageSize",required=false) Integer pageSize,
@RequestParam(value="currentPage",required=false) Integer currentPage,
Map<String, Object> model, HttpServletRequest request){
BillingService billingService = Context.getService(BillingService.class);
int total = billingService.countListCompany();
PagingUtil pagingUtil = new PagingUtil( RequestUtil.getCurrentLink(request) , pageSize, currentPage, total );
List<Company> companies = billingService.listCompany(pagingUtil.getStartPos(), pagingUtil.getPageSize());
model.put("companies", companies );
model.put("pagingUtil", pagingUtil);
return "/module/billing/company/list";
}
} |
package com.hmsphr.jdj.Components.Players;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.VideoView;
import com.hmsphr.jdj.Activities.VideoActivity;
import com.hmsphr.jdj.Class.MediaActivity;
public class MediaPlayerClassic implements PlayerCompat {
private VideoActivity context;
private Uri contentUri;
private int playerPosition;
private VideoView videoView;
private MediaPlayer player;
private ImageView audioShutter;
private FrameLayout loadShutter;
private String mode;
public static final int STATE_STOP = 0;
public static final int STATE_LOAD = 1;
public static final int STATE_READY = 2;
public static final int STATE_PLAY = 3;
private int playerState = STATE_STOP;
private FrameLayout replayShutter;
private FrameLayout replayOverlay;
private ImageButton replayBtn;
private boolean replayEnable = false;
private static int NOW = -1;
private long baganAtTime = NOW;
private long atTimeUse = 0;
private boolean playAfterSeek = true;
public MediaPlayerClassic(VideoActivity ctx, VideoView vview, ImageView aview, FrameLayout shutter) {
context = ctx;
videoView = vview;
playerPosition = 0;
audioShutter = aview;
loadShutter = shutter;
loadShutter.setVisibility(View.VISIBLE);
// Video player events
videoView.<API key>(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
player = mp;
player.setLooping(false);
if (playerState > STATE_STOP) {
playerState = STATE_READY;
Log.d("jdj-VideoClassic", "Player READY");
}
mp.setOnInfoListener(new MediaPlayer.OnInfoListener() {
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
if (what == MediaPlayer.<API key>) {
Log.d("jdj-VideoClassic", "Player RENDERING ? "+what);
loadShutter.setVisibility(View.GONE);
}
return true;
}
});
mp.<API key>(new MediaPlayer.<API key>() {
@Override
public void onSeekComplete(MediaPlayer mp) {
if (playAfterSeek) videoView.start();
Log.d("jdj-VideoClassic", "Player SEEK at " + playerPosition);
}
});
mp.<API key>(new MediaPlayer.<API key>() {
public void onCompletion(MediaPlayer mp) {
playerState = STATE_STOP;
if (replayEnable) replayShutter.setVisibility(View.VISIBLE);
Log.d("jdj-VideoClassic", "Player END");
context.onVideoEnd();
}
});
}
});
}
public void play() {
if (replayEnable) replayShutter.setVisibility(View.GONE);
if (playerState == STATE_PLAY) { playAfterSeek = true; player.seekTo(0); }
else play(contentUri.toString());
}
public void play(String url) {
play(url, NOW);
}
public void play(String url, long atTime) {
stop();
atTime = atTime-70;
baganAtTime = atTime;
contentUri = Uri.parse(url);
videoView.setVideoURI(contentUri);
launchPlayer(atTime);
}
private void launchPlayer(long atTime) {
Log.d("jdj-VideoClassic", "Player LOADING at "+atTime);
playerState = STATE_LOAD;
if (mode != null && mode.equals("audio")) {
audioShutter.setVisibility(View.VISIBLE);
// seek to position to keep sync
if (baganAtTime > 0 && atTime < SystemClock.elapsedRealtime()) {
atTime = SystemClock.elapsedRealtime()+1500; // already late so we postpone the start
playerPosition = (int) (atTime + 510 - baganAtTime); // start at position shifted from beganAtTime
}
}
atTimeUse = atTime;
// seek to
if (playerPosition > 0) {
playAfterSeek = false;
videoView.seekTo(playerPosition);
}
// Sync with atTime
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (playerState == STATE_STOP) return;
else if (playerState >= STATE_READY)
Log.d("jdj-VideoClassic", "Player PLAY - SYNC");
else Log.d("jdj-VideoClassic", "Player PLAY - OUT OF SYNC.. (not ready yet)");
videoView.start();
context.onVideoStart();
playerState = STATE_PLAY;
if (android.os.Build.VERSION.SDK_INT < 17) loadShutter.setVisibility(View.GONE);
Log.d("jdj-ExoPlayer", " Timer shot shift: "+(SystemClock.elapsedRealtime()-atTimeUse));
}
}, Math.max(0, atTime - SystemClock.elapsedRealtime()));
}
public void resume(){
if (player != null && playerPosition > 0) {
context.<API key>(ActivityInfo.<API key>);
Log.d("jdj-VideoClassic", "Player RESUME");
launchPlayer(NOW);
}
}
public void pause(){
if (player != null) {
playerPosition = videoView.getCurrentPosition();
videoView.pause();
Log.d("jdj-VideoClassic", "Player PAUSED at "+playerPosition);
}
}
public void stop(){
playerState = STATE_STOP;
videoView.stopPlayback();
loadShutter.setVisibility(View.VISIBLE);
audioShutter.setVisibility(View.GONE);
if (replayEnable) replayShutter.setVisibility(View.GONE);
playerPosition = 0;
player = null;
Log.d("jdj-VideoClassic", "Player STOP");
}
public void setMode(String m) {
mode = m;
}
public void setReplay(FrameLayout replayV, FrameLayout replayO, ImageButton replayB) {
replayShutter = replayV;
replayOverlay = replayO;
replayBtn = replayB;
// Replay Overlay Alpha
AlphaAnimation animation = new AlphaAnimation(0.5f, 0.5f);
animation.setDuration(0);
animation.setFillAfter(true);
replayOverlay.startAnimation(animation);
// Replay Shutter action
replayBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
play();
}
});
if (replayShutter != null) replayEnable = true;
}
} |
package com.hong.japarser;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.regex.Pattern;
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IAParser {
String expression();
int flag() default Pattern.DOTALL;
int group() default 0;
} |
<?php
namespace Joomla\Component\Csp\Administrator\Helper;
defined('_JEXEC') or die;
use Joomla\CMS\Factory;
/**
* Reporter component helper.
*
* @since 4.0.0
*/
class ReporterHelper
{
/**
* Gets the httpheaders system plugin extension id.
*
* @return integer The httpheaders system plugin extension id.
*
* @since 4.0.0
*/
public static function <API key>()
{
$db = Factory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('extension_id'))
->from($db->quoteName('#__extensions'))
->where($db->quoteName('folder') . ' = ' . $db->quote('system'))
->where($db->quoteName('element') . ' = ' . $db->quote('httpheaders'));
$db->setQuery($query);
try
{
$result = (int) $db->loadResult();
}
catch (\RuntimeException $e)
{
Factory::getApplication()->enqueueMessage($e->getMessage(), 'error');
}
return $result;
}
/**
* Check the com_csp trash to show a warning in this case
*
* @return boolean The status of the trash; Do items exists in the trash
*
* @since 4.0.0
*/
public static function getCspTrashStatus()
{
$db = Factory::getDbo();
$query = $db->getQuery(true)
->select('COUNT(*)')
->from($db->quoteName('#__csp'))
->where($db->quoteName('published') . ' = ' . $db->quote('-2'));
$db->setQuery($query);
try
{
$result = (int) $db->loadResult();
}
catch (\RuntimeException $e)
{
Factory::getApplication()->enqueueMessage($e->getMessage(), 'error');
}
return boolval($result);
}
} |
package org.weymouth.sqltools;
public class Header {
//-- Name: i2b2demodata; Type: SCHEMA; Schema: -; Owner: weymouth
final private String text;
final private String name;
final private HeaderType type;
private String schema;
private String owner;
public Header(String text, String name, HeaderType type, String schema,
String owner) {
this.text = text;
this.name = name;
this.type = type;
this.schema = schema;
this.owner = owner;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getText() {
return text;
}
public String getName() {
return name;
}
public HeaderType getType() {
return type;
}
public String getSchemaWithName() {
return schema + "." + name;
}
@Override
public String toString() {
return "Header [name=" + name + ", type=" + type + ", schema=" + schema
+ ", owner=" + owner + "]";
}
} |
#ifndef FrameWin_h
#define FrameWin_h
#include <wtf/Vector.h>
#include <wtf/win/GDIObject.h>
namespace WebCore {
class Frame;
class IntRect;
GDIObject<HBITMAP> imageFromRect(const Frame*, IntRect&);
GDIObject<HBITMAP> imageFromSelection(Frame*, bool forceBlackText);
void <API key>(Frame*, const IntRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, Vector<IntRect>& outPages, int& outPageHeight);
} // namespace WebCore
#endif // FrameWin_h |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_25) on Mon Jan 19 00:16:43 EST 2015 -->
<title>Uses of Class Launcher</title>
<meta name="date" content="2015-01-19">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class Launcher";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../Launcher.html" title="class in <Unnamed>">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../index.html?class-use/Launcher.html" target="_top">Frames</a></li>
<li><a href="Launcher.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.top">
</a></div>
<div class="header">
<h2 title="Uses of Class Launcher" class="title">Uses of Class<br>Launcher</h2>
</div>
<div class="classUseContainer">No usage of Launcher</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../Launcher.html" title="class in <Unnamed>">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../index.html?class-use/Launcher.html" target="_top">Frames</a></li>
<li><a href="Launcher.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.bottom">
</a></div>
</body>
</html> |
/* Pragmas */
#pragma GCC diagnostic ignored "-Wunused-result" /* Don't care about system() */
/* Headers */
#include <stdlib.h>
#include "prototypes.h"
/* Instantiate externals */
double visbel_interval = 0.15;
/* Static Variables */
static double time_last = 0;
void
visbel()
{
double t;
if ((t = time_now()) - time_last >= visbel_interval)
{
system("tput flash 1 >&2 2>/dev/null");
time_last = t;
} /* if ((t = time_now()) - time_last >= visbel_interval) */
} /* visbel() */ |
#!/usr/bin/python3
import grp,os,pwd
class ROOT_CHOWN(object):
def __init__(self,parent):
parent.declare_option( 'mapping_file' )
self.mapping = {}
def on_start(self,parent):
logger = parent.logger
if not hasattr( parent, "mapping_file" ):
parent.mapping_file = [ None ]
return True
mf_path = parent.mapping_file[0]
try:
f = open(mf_path,'r')
while True:
l = f.readline()
if not l : break
l2 = l.strip()
parts = l2.split()
if len(parts) != 2 :
logger.error("wrong mapping line %s" % l)
continue
self.mapping[parts[0]] = parts[1]
f.close()
logger.info( "ROOT_CHOWN mapping_file loaded %s" % mf_path)
except: logger.error("ROOT_CHOWN problem when parsing %s" % mf_path)
return True
def on_post(self,parent):
import grp,os,pwd
logger = parent.logger
msg = parent.msg
logger.debug("ROOT_CHOWN on_post")
new_dir = parent.new_dir
new_file = parent.new_file
# if remove ...
if msg.headers['sum'].startswith('R,') and not 'newname' in msg.headers: return True
# if move ... sr_watch sets new_dir new_file on destination file so we are ok
# already set ... check for mapping switch
if 'ownership' in msg.headers :
ug = msg.headers['ownership']
if ug in self.mapping :
logger.debug("ROOT_CHOWN mapping from %s to %s" % (ug,self.mapping[ug]))
msg.headers['ownership'] = self.mapping[ug]
return True
# need to add ownership in message
try :
local_file = new_dir + os.sep + new_file
s = os.lstat(local_file)
username = pwd.getpwuid(s.st_uid).pw_name
group = grp.getgrgid(s.st_gid).gr_name
ug = "%s:%s" % (username,group)
# check for mapping switch
if ug in self.mapping :
logger.debug("ROOT_CHOWN mapping from %s to %s" % (ug,self.mapping[ug]))
ug = self.mapping[ug]
msg.headers['ownership'] = ug
logger.debug("ROOT_CHOWN set ownership in headers %s" % msg.headers['ownership'])
except: logger.error("ROOT_CHOWN could not set ownership %s" % local_file)
return True
def on_file(self,parent):
import grp,os,pwd
logger = parent.logger
msg = parent.msg
logger.debug("ROOT_CHOWN on_file")
# the message does not have the requiered info
if not 'ownership' in msg.headers :
logger.info("ROOT_CHOWN no ownership in msg_headers")
return True
# it does, check for mapping
ug = msg.headers['ownership']
if ug in self.mapping :
logger.debug("received ownership %s mapped to %s" % (ug,self.mapping[ug]))
ug = self.mapping[ug]
# try getting/setting ownership info to local_file
local_file = parent.new_dir + os.sep + parent.new_file
try :
parts = ug.split(':')
username = parts[0]
group = parts[1]
uid = pwd.getpwnam(username).pw_uid
gid = grp.getgrnam(group ).pw_gid
os.chown(local_file,uid,gid)
logger.info( "ROOT_CHOWN set ownership %s to %s" % (ug,local_file))
except: logger.error("ROOT_CHOWN could not set %s to %s" % (ug,local_file))
return True
self.plugin='ROOT_CHOWN' |
package org.adempierelbr.apps.form;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PrinterException;
import java.beans.PropertyChangeEvent;
import java.beans.<API key>;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JScrollPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import org.adempierelbr.model.MLBRBoleto;
import org.adempierelbr.util.AdempiereLBR;
import org.adempierelbr.util.TextUtil;
import org.compiere.apps.ADialog;
import org.compiere.apps.ConfirmPanel;
import org.compiere.apps.StatusBar;
import org.compiere.apps.form.FormFrame;
import org.compiere.apps.form.FormPanel;
import org.compiere.grid.ed.VDate;
import org.compiere.grid.ed.VFile;
import org.compiere.grid.ed.VLookup;
import org.compiere.minigrid.IDColumn;
import org.compiere.minigrid.MiniTable;
import org.compiere.model.MBankAccount;
import org.compiere.model.MDocType;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.plaf.CompiereColor;
import org.compiere.print.CPrinter;
import org.compiere.process.ProcessInfo;
import org.compiere.swing.CLabel;
import org.compiere.swing.CPanel;
import org.compiere.swing.CTabbedPane;
import org.compiere.util.ASyncProcess;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Msg;
@Deprecated
public class VFormBoleto extends CPanel
implements FormPanel, ActionListener, <API key>, ChangeListener, TableModelListener, ASyncProcess
{
private static final long serialVersionUID = 1L;
private static final String interval = "7"; // Intervalo de Datas
/**
* Initialize Panel
* @param WindowNo window
* @param frame frame
*/
public void init (int WindowNo, FormFrame frame)
{
log.info("");
m_WindowNo = WindowNo;
m_frame = frame;
Env.setContext(Env.getCtx(), m_WindowNo, "IsSOTrx", "Y");
try
{
fillPicks();
jbInit();
dynInit();
executeQuery();
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
frame.getContentPane().add(statusBar, BorderLayout.SOUTH);
}
catch(Exception ex)
{
log.log(Level.SEVERE, "init", ex);
}
} // init
/** Window No */
private int m_WindowNo = 0;
/** FormFrame */
private FormFrame m_frame;
private boolean m_selectionActive = true;
private String m_whereClause;
private Object m_DateInvoiced = null;
private Object m_C_BankAccount_ID = null;
private Object m_C_BPartner_ID = null;
private Object m_PrinterName = null;
private Object m_FileName = null;
private boolean m_mark = true;
/** Logger */
private static CLogger log = CLogger.getCLogger(VFormBoleto.class);
private CTabbedPane tabbedPane = new CTabbedPane();
private CPanel selPanel = new CPanel();
private CPanel selNorthPanel = new CPanel();
private BorderLayout selPanelLayout = new BorderLayout();
private CLabel lDateInvoiced = new CLabel();
private VDate fDateInvoiced = new VDate("DateInvoiced", false, false, true, 15, "");
private CLabel lBankAccount = new CLabel();
private VLookup fBankAccount;
private CLabel lBPartner = new CLabel();
private VLookup fBPartner;
private CLabel lPrinterName = new CLabel();
private CPrinter fPrinterName = new CPrinter();
private CLabel lFileName = new CLabel();
private VFile fFileName = new VFile("File_Directory",false,false,true,20,false);
private JCheckBox printedBill = new JCheckBox();
private GridBagLayout northPanelLayout = new GridBagLayout();
private ConfirmPanel confirmPanelSel = new ConfirmPanel(true,true,true);
private StatusBar statusBar = new StatusBar();
private JScrollPane scrollPane = new JScrollPane();
private MiniTable miniTable = new MiniTable();
private JButton markButton = new JButton();
/**
* Static Init.
* <pre>
* selPanel (tabbed)
* fOrg, fBPartner
* scrollPane & miniTable
* genPanel
* info
* </pre>
* @throws Exception
*/
void jbInit() throws Exception
{
CompiereColor.setBackground(this);
confirmPanelSel.addButton(markButton);
confirmPanelSel.add(printedBill);
selPanel.setLayout(selPanelLayout);
selPanel.setPreferredSize(new Dimension(1024,450));
lDateInvoiced.setLabelFor(fDateInvoiced);
lDateInvoiced.setText(Msg.translate(Env.getCtx(), "DateInvoiced"));
lBPartner.setLabelFor(fBPartner);
lBPartner.setText(Msg.translate(Env.getCtx(), "C_BPartner_ID"));
lBankAccount.setLabelFor(fBankAccount);
lBankAccount.setText(Msg.translate(Env.getCtx(), "C_BankAccount_ID"));
lPrinterName.setLabelFor(fPrinterName);
lPrinterName.setText(Msg.translate(Env.getCtx(), "PrinterName"));
lFileName.setLabelFor(fFileName);
lFileName.setText(Msg.translate(Env.getCtx(), "File_Directory"));
printedBill.setText(Msg.translate(Env.getCtx(), "IsPrinted"));
printedBill.addActionListener(this);
selNorthPanel.setLayout(northPanelLayout);
tabbedPane.add(selPanel, Msg.getMsg(Env.getCtx(), "Select"));
selPanel.add(selNorthPanel, BorderLayout.NORTH);
selNorthPanel.add(lDateInvoiced, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
selNorthPanel.add(fDateInvoiced, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0));
selNorthPanel.add(lBPartner, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
selNorthPanel.add(fBPartner, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0));
selNorthPanel.add(lBankAccount, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
selNorthPanel.add(fBankAccount, new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0));
selNorthPanel.add(lPrinterName, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
selNorthPanel.add(fPrinterName, new GridBagConstraints(5, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0));
selNorthPanel.add(lFileName, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
selNorthPanel.add(fFileName, new GridBagConstraints(5, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0));
selPanel.setName("selPanel");
selPanel.add(confirmPanelSel, BorderLayout.SOUTH);
selPanel.add(scrollPane, BorderLayout.CENTER);
scrollPane.getViewport().add(miniTable, null);
confirmPanelSel.addActionListener(this);
markButton.setText("Todos");
markButton.addActionListener(this);
fDateInvoiced.<API key>(this);
} // jbInit
/**
* Fill Picks
* Column_ID from C_Order
* @throws Exception if Lookups cannot be initialized
*/
private void fillPicks() throws Exception
{
MLookup BankL = MLookupFactory.get (Env.getCtx(), m_WindowNo, 0, 3077, DisplayType.Search);
fBankAccount = new VLookup ("C_BankAccount_ID", true, false, true, BankL);
fBankAccount.<API key>(this);
MLookup BPartnerL = MLookupFactory.get (Env.getCtx(), m_WindowNo, 0, 2893, DisplayType.Search);
fBPartner = new VLookup ("C_BPartner_ID", false, false, true, BPartnerL);
fBPartner.<API key>(this);
lFileName.setVisible(false);
fFileName.setVisible(false);
} // fillPicks
/**
* Dynamic Init.
* - Create GridController & Panel
* - AD_Column_ID from C_Order
*/
private void dynInit()
{
// create Columns
miniTable.addColumn("C_Invoice_ID");
miniTable.addColumn("AD_Org_ID");
miniTable.addColumn("DocumentNo");
miniTable.addColumn("LBR_NotaFiscal_ID");
miniTable.addColumn("C_BPartner_ID");
miniTable.addColumn("C_PaymentTerm_ID");
miniTable.addColumn("DateInvoiced");
//miniTable.addColumn("DueDate");
miniTable.addColumn("TotalLines");
miniTable.setMultiSelection(true);
miniTable.<API key>(true);
// set details
miniTable.setColumnClass(0, IDColumn.class, false, " ");
miniTable.setColumnClass(1, String.class, true, Msg.translate(Env.getCtx(), "AD_Org_ID"));
miniTable.setColumnClass(2, String.class, true, Msg.translate(Env.getCtx(), "DocumentNo"));
miniTable.setColumnClass(3, String.class, true, Msg.translate(Env.getCtx(), "LBR_NotaFiscal_ID"));
miniTable.setColumnClass(4, String.class, true, Msg.translate(Env.getCtx(), "C_BPartner_ID"));
miniTable.setColumnClass(5, String.class, true, Msg.translate(Env.getCtx(), "C_PaymentTerm_ID"));
miniTable.setColumnClass(6, Timestamp.class, true, Msg.translate(Env.getCtx(), "DateInvoiced"));
//miniTable.setColumnClass(7, Timestamp.class, true, Msg.translate(Env.getCtx(), "DueDate"));
miniTable.setColumnClass(7, BigDecimal.class, true, Msg.translate(Env.getCtx(), "TotalLines"));
miniTable.autoSize();
miniTable.getModel().<API key>(this);
// Info
statusBar.setStatusLine(Msg.getMsg(Env.getCtx(), "InvGenerateSel"));
statusBar.setStatusDB(" ");
// Tabbed Pane Listener
tabbedPane.addChangeListener(this);
} // dynInit
/**
* Query Info
*/
private void executeQuery()
{
log.info("");
statusBar.setStatusLine("");
int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx());
// Create SQL
int index = 0;
Timestamp startDate = Env.getContextAsDate(Env.getCtx(), "#Date");
Timestamp actualDate = Env.getContextAsDate(Env.getCtx(), "#Date");
StringBuffer sql = new StringBuffer(
"SELECT distinct i.C_Invoice_ID, o.Name, i.DocumentNo, nf.DocumentNo, bp.Name, pt.Name, min(i.DateInvoiced) as DateInvoiced, i.GrandTotal " +
"FROM C_Invoice i " +
"INNER JOIN AD_Org o ON i.AD_Org_ID=o.AD_Org_ID " +
"INNER JOIN C_DocType d ON i.C_DocTypeTarget_ID=d.C_DocType_ID " +
"INNER JOIN C_BPartner bp ON i.C_BPartner_ID=bp.C_BPartner_ID " +
//"INNER JOIN RV_OpenItem op ON i.C_Invoice_ID=op.C_Invoice_ID " +
"INNER JOIN C_PaymentTerm pt ON i.C_PaymentTerm_ID=pt.C_PaymentTerm_ID " +
"LEFT JOIN LBR_NotaFiscal nf ON i.LBR_NotaFiscal_ID=nf.LBR_NotaFiscal_ID " +
"WHERE i.IsSOTrx='Y' AND i.IsPaid = 'N' AND i.DocStatus = 'CO' " +
"AND d.lbr_HasOpenItems='Y' AND (i.lbr_PaymentRule IS NULL OR i.lbr_PaymentRule = 'B') " + //mostrar somente faturas boleto ou sem forma de pagamento
"AND i.AD_Client_ID=? ");
sql.append("AND d.DocBaseType like '" + MDocType.<API key> + "' ");
if (printedBill.isSelected()){
sql.append("AND i.lbr_IsBillPrinted='Y' ");
}
else{
sql.append("AND i.lbr_IsBillPrinted='N' ");
}
if (m_DateInvoiced != null){
sql.append("AND i.DateInvoiced=? ");
index = index + 1;
}
if (m_C_BPartner_ID != null){
sql.append("AND i.C_BPartner_ID=? ");
index = index + 2;
}
if (index == 0 && printedBill.isSelected()){ //SEM FILTRO E IMPRESSO, SELECIONA INTERVALO
startDate = AdempiereLBR.addDays(actualDate, Integer.parseInt(interval) * -1);
sql.append("AND nf.DateDoc BETWEEN ? AND ?");
index = 4;
statusBar.setStatusLine("Intervalo definido entre " +
TextUtil.timeToString(startDate,"dd/MM/yyyy") + " e " +
TextUtil.timeToString(actualDate,"dd/MM/yyyy"));
}
sql.append("GROUP BY i.C_Invoice_ID, o.Name, i.DocumentNo, nf.DocumentNo, bp.Name, pt.Name, i.GrandTotal " +
"ORDER BY i.C_Invoice_ID, o.Name, bp.Name, DateInvoiced");
// reset table
int row = 0;
miniTable.setRowCount(row);
// Execute
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setInt(1, AD_Client_ID);
if (index == 1) pstmt.setTimestamp(2, (Timestamp)m_DateInvoiced);
else if (index == 2) pstmt.setInt(2, (Integer)m_C_BPartner_ID);
else if (index == 3){
pstmt.setTimestamp(2, (Timestamp)m_DateInvoiced);
pstmt.setInt(3, (Integer)m_C_BPartner_ID);
}
else if (index == 4){
pstmt.setTimestamp(2, startDate);
pstmt.setTimestamp(3, actualDate);
}
rs = pstmt.executeQuery();
while (rs.next())
{
// extend table
miniTable.setRowCount(row+1);
// set values
miniTable.setValueAt(new IDColumn(rs.getInt(1)), row, 0); // C_Invoice_ID
miniTable.setValueAt(rs.getString(2), row, 1);
miniTable.setValueAt(rs.getString(3), row, 2); // Org
miniTable.setValueAt(rs.getString(4), row, 3); // Doc No
miniTable.setValueAt(rs.getString(5), row, 4); // BPartner
miniTable.setValueAt(rs.getString(6), row, 5); // PaymentTerm
miniTable.setValueAt(rs.getTimestamp(7), row, 6); // DateInvoiced
//miniTable.setValueAt(rs.getTimestamp(8), row, 7); // DueDate
miniTable.setValueAt(rs.getBigDecimal(8), row, 7); // TotalLines
// prepare next
row++;
}
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
}
finally{
DB.close(rs, pstmt);
}
miniTable.autoSize();
statusBar.setStatusDB(String.valueOf(miniTable.getRowCount()));
} // executeQuery
/**
* Dispose
*/
public void dispose()
{
if (m_frame != null)
m_frame.dispose();
m_frame = null;
} // dispose
/**
* Action Listener
* @param e event
*/
public void actionPerformed (ActionEvent e)
{
log.info("Cmd=" + e.getActionCommand());
if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
dispose();
return;
}
if (e.getActionCommand().equals(ConfirmPanel.A_PRINT))
{
boolean change = false;
if (fFileName.isVisible()){
change = true;
}
lPrinterName.setVisible(change);
fPrinterName.setVisible(change);
lFileName.setVisible(!change);
fFileName.setVisible(!change);
return;
}
if (e.getActionCommand().equals(ConfirmPanel.A_REFRESH))
{
executeQuery();
return;
}
if (e.getSource().equals(printedBill))
{
if (printedBill.isSelected()){
fBankAccount.setReadWrite(false);
}
else{
fBankAccount.setReadWrite(true);
}
executeQuery();
return;
}
if (e.getSource().equals(markButton))
{
markAll();
return;
}
m_whereClause = saveSelection();
if (m_whereClause.length() > 0 && m_selectionActive){
if (m_C_BankAccount_ID == null || (Integer)m_C_BankAccount_ID == 0){
if (!printedBill.isSelected()){
String msg = "Selecionar Conta para Geração de Boletos";
statusBar.setStatusLine(msg);
ADialog.info(m_WindowNo, this, msg);
return;
}
}
String printerName = null;
String fileName = null;
if (fPrinterName.isVisible()){
m_PrinterName = fPrinterName.getValue();
if (m_PrinterName == null || ((String)m_PrinterName).equals("")){
String msg = "Selecionar impressora para Impressão dos Boletos";
statusBar.setStatusLine(msg);
ADialog.info(m_WindowNo, this, msg);
return;
}
printerName = (String)m_PrinterName;
fileName = null;
}
else {
m_FileName = fFileName.getValue();
if (m_FileName == null || ((String)m_FileName).equals("")){
String msg = "Selecionar diretório onde os Boletos serão gravados";
statusBar.setStatusLine(msg);
ADialog.info(m_WindowNo, this, msg);
return;
}
printerName = null;
fileName = (String)m_FileName;
}
Properties ctx = Env.getCtx();
String trxName = null; //Trx.createTrxName("PBO");
if (!printedBill.isSelected()){
MBankAccount bankA = new MBankAccount(ctx,(Integer)m_C_BankAccount_ID,null);
if (!bankA.get_ValueAsBoolean("lbr_IsBillPrinted")){
String msg = "Conta não está marcada para Geração de Boletos";
statusBar.setStatusLine(msg);
ADialog.info(m_WindowNo, this, msg);
return;
}
}
Integer[] selection = getSelection();
for (int i=0;i<selection.length;i++){
try {
MLBRBoleto.generateBoleto(ctx, selection[i], (Integer)m_C_BankAccount_ID, fileName, printerName, trxName);
} catch (IOException e1) {
e1.printStackTrace();
} catch (PrinterException e1) {
e1.printStackTrace();
}
}
m_mark = true;
executeQuery();
}
else{
String msg = "Selecionar Faturas para Geração de Boletos";
statusBar.setStatusLine(msg);
ADialog.info(m_WindowNo, this, msg);
return;
}
} // actionPerformed
/**
* Vetoable Change Listener - requery
* @param e event
*/
public void vetoableChange(PropertyChangeEvent e)
{
log.info(e.getPropertyName() + "=" + e.getNewValue());
int i = 0;
if (e.getPropertyName().equals("DateInvoiced"))
{
m_DateInvoiced = e.getNewValue();
fDateInvoiced.setValue(m_DateInvoiced); // display value
if (m_DateInvoiced != null) i = 1;
}
if (e.getPropertyName().equals("C_BPartner_ID"))
{
m_C_BPartner_ID = e.getNewValue();
fBPartner.setValue(m_C_BPartner_ID); // display value
if (m_C_BPartner_ID != null) i = 1;
}
if (e.getPropertyName().equals("C_BankAccount_ID"))
{
m_C_BankAccount_ID = e.getNewValue();
fBankAccount.setValue(m_C_BankAccount_ID); // display value
}
if (i != 0) executeQuery();
} // vetoableChange
/**
* Change Listener (Tab changed)
* @param e event
*/
public void stateChanged (ChangeEvent e)
{
int index = tabbedPane.getSelectedIndex();
m_selectionActive = (index == 0);
} // stateChanged
/**
* Table Model Listener
* @param e event
*/
public void tableChanged(TableModelEvent e)
{
int rowsSelected = 0;
int rows = miniTable.getRowCount();
for (int i = 0; i < rows; i++)
{
IDColumn id = (IDColumn)miniTable.getValueAt(i, 0); // ID in column 0
if (id != null && id.isSelected())
rowsSelected++;
}
statusBar.setStatusDB(" " + rowsSelected + " ");
} // tableChanged
/**
* markAll
*/
private void markAll()
{
log.info("");
// ID selection may be pending
miniTable.editingStopped(new ChangeEvent(this));
// Get selected entries
int rows = miniTable.getRowCount();
for (int i = 0; i < rows; i++)
{
IDColumn id = (IDColumn)miniTable.getValueAt(i, 0); // ID in column 0
id.setSelected(m_mark);
miniTable.setValueAt(id, i, 0);
}
if (m_mark == false) m_mark = true;
else if (m_mark == true) m_mark = false;
}
/**
* Save Selection & return selecion Query or ""
* @return where clause like C_Order_ID IN (...)
*/
private String saveSelection()
{
log.info("");
// ID selection may be pending
miniTable.editingStopped(new ChangeEvent(this));
// Array of Integers
ArrayList<Integer> results = new ArrayList<Integer>();
// Get selected entries
int rows = miniTable.getRowCount();
for (int i = 0; i < rows; i++)
{
IDColumn id = (IDColumn)miniTable.getValueAt(i, 0); // ID in column 0
// log.fine( "Row=" + i + " - " + id);
if (id != null && id.isSelected())
results.add(id.getRecord_ID());
}
if (results.size() == 0)
return "";
// Query String
String keyColumn = "C_Invoice_ID";
StringBuffer sb = new StringBuffer(keyColumn);
if (results.size() > 1)
sb.append(" IN (");
else
sb.append("=");
// Add elements
for (int i = 0; i < results.size(); i++)
{
if (i > 0)
sb.append(",");
if (keyColumn.endsWith("_ID"))
sb.append(results.get(i).toString());
else
sb.append("'").append(results.get(i).toString());
}
if (results.size() > 1)
sb.append(")");
log.config(sb.toString());
return sb.toString();
} // saveSelection
/**
* Save Selection & return Array
* @return Integer[]
*/
private Integer[] getSelection()
{
log.info("");
// ID selection may be pending
miniTable.editingStopped(new ChangeEvent(this));
// Array of Integers
ArrayList<Integer> results = new ArrayList<Integer>();
// Get selected entries
int rows = miniTable.getRowCount();
for (int i = 0; i < rows; i++)
{
IDColumn id = (IDColumn)miniTable.getValueAt(i, 0); // ID in column 0
// log.fine( "Row=" + i + " - " + id);
if (id != null && id.isSelected())
results.add(id.getRecord_ID());
}
Integer[] lines = new Integer[results.size ()];
results.toArray (lines);
return lines;
} // saveSelection
/**************************************************************************
* Lock User Interface.
* Called from the Worker before processing
* @param pi process info
*/
public void lockUI (ProcessInfo pi)
{
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
this.setEnabled(false);
} // lockUI
/**
* Unlock User Interface.
* Called from the Worker when processing is done
* @param pi result of execute ASync call
*/
public void unlockUI (ProcessInfo pi)
{
this.setEnabled(true);
this.setCursor(Cursor.getDefaultCursor());
} // unlockUI
/**
* Is the UI locked (Internal method)
* @return true, if UI is locked
*/
public boolean isUILocked()
{
return this.isEnabled();
} // isUILocked
/**
* Method to be executed async.
* Called from the Worker
* @param pi ProcessInfo
*/
public void executeASync (ProcessInfo pi)
{
} // executeASync
} // FormBoleto |
package info.jbcs.minecraft.vending.proxy;
import info.jbcs.minecraft.vending.Vending;
import info.jbcs.minecraft.vending.block.BlockVendingMachine;
import info.jbcs.minecraft.vending.block.EnumSupports;
import info.jbcs.minecraft.vending.gui.HintGui;
import info.jbcs.minecraft.vending.renderer.<API key>;
import info.jbcs.minecraft.vending.tileentity.<API key>;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.resources.model.<API key>;
import net.minecraft.item.Item;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.client.registry.ClientRegistry;
//import net.minecraft.util.<API key>;
public class ClientProxy extends CommonProxy{
private Minecraft mc;
@Override
public void <API key>(){
MinecraftForge.EVENT_BUS.register(new HintGui(Minecraft.getMinecraft()));
}
@Override
public void registerRenderers() {
ClientRegistry.<API key>(<API key>.class, new <API key>());
RenderItem renderItem = Minecraft.getMinecraft().getRenderItem();
renderItem.getItemModelMesher().register(Vending.itemWrench, 0, new <API key>(Vending.MOD_ID + ":" + "<API key>", "inventory"));
for(int i=0;i<EnumSupports.length;i++){
renderItem.getItemModelMesher().register(Item.getItemFromBlock(Vending.blockVendingMachine), i,
new <API key>(Vending.MOD_ID + ":" + ((BlockVendingMachine) Vending.blockVendingMachine).getName(),
"support=" + EnumSupports.byMetadata(i).getUnlocalizedName()));
renderItem.getItemModelMesher().register(Item.getItemFromBlock(Vending.<API key>), i,
new <API key>(Vending.MOD_ID + ":" + ((BlockVendingMachine) Vending.<API key>).getName(),
"support=" + EnumSupports.byMetadata(i).getUnlocalizedName()));
renderItem.getItemModelMesher().register(Item.getItemFromBlock(Vending.<API key>), i,
new <API key>(Vending.MOD_ID + ":" + ((BlockVendingMachine) Vending.<API key>).getName(),
"support=" + EnumSupports.byMetadata(i).getUnlocalizedName()));
}
}
} |
#ifndef __MUL_ROUTE_H__
#define __MUL_ROUTE_H__
#define RT_HB_INTVL_SEC 2
#define RT_HB_INTVL_INITSEC 6
#define RT_HB_INTVL_USEC 0
#define RT_MAX_GET_RETRIES 100
#define NEIGH_NO_PATH (INT_MAX)
#define NEIGH_NO_LINK (uint16_t)(-1)
struct lweight_pair_
{
uint16_t la;
uint16_t lb;
#define NEIGH_DFL_WEIGHT (100)
int weight;
bool onlink;
};
typedef struct lweight_pair_ lweight_pair_t;
#define RT_MATRIX_ELEM(M, T, sz, row, col) (((T *)((((T (*)[sz])(M))+row)))+col)
struct rt_adj_elem_
{
uint32_t pairs;
#define RT_MAX_ADJ_PAIRS (4)
lweight_pair_t adj_pairs[RT_MAX_ADJ_PAIRS];
};
typedef struct rt_adj_elem_ rt_adj_elem_t;
struct rt_path_elem_
{
int sw_alias;
#define RT_PELEM_FIRST_HOP 0x1
#define RT_PELEM_LAST_HOP 0x2
uint8_t flags;
uint16_t in_port;
lweight_pair_t link;
};
typedef struct rt_path_elem_ rt_path_elem_t;
struct rt_transit_elem_
{
unsigned int n_paths;
#define RT_MAX_EQ_PATHS 4
int sw_alias[RT_MAX_EQ_PATHS]; /* Switch Alias */
};
typedef struct rt_transit_elem_ rt_transit_elem_t;
struct rt_list
{
GSList *route;
struct rt_list *next;
};
typedef struct rt_list rt_list_t;
void <API key>(GSList *iroute, GFunc iter_fn, void *arg);
void mul_destroy_route(GSList *route);
size_t mul_route_get_nodes(void *rt_service);
GSList *mul_route_get(void *rt_service, int src_sw, int dest_sw);
GSList *mul_route_get_mp(void *rt_service, int src_sw, int dest_sw, void *u_arg,
size_t (*mp_select)(void *u_arg, size_t max_routes));
void <API key>(void *rt_info, void *blk);
void *<API key>(void);
void <API key>(void *rt_service);
#endif |
#include <stdio.h>
#include <stdlib.h>
#include "Stroke.h"
//#include "main.h"
#define MAX(a,b) ((a)>(b) ? (a) : (b))
#define MIN(a,b) ((a)<(b) ? (a) : (b))
GLUquadricObj * Stroke::qobj = NULL;
const double Stroke::MEAN_FILTER[3] = { 0.33, 0.34, 0.33 } ;
Stroke::Stroke()
{
_limit = _temp = NULL;
_computed = false;
_stripComputed = false ;
_numLevels = 3;
_cap = false;
// _cap = true ;
_extendLength = false;
_radius = -1;
_color = makeColor(0,0,0);
_adjustedColor = makeColor(0,0,0);
_texture_width = 1 ;
_texture_height= 1 ;
_texture_radius = 1.0;
if (qobj == NULL)
qobj = gluNewQuadric();
_useTexture = false;
_lumAlphaNum = 0;
_alphaNum = 0;
_depth = 0;
_tOffset=0;
}
/*
Stroke::Stroke(FILE* fp)
{
_limit = _temp = NULL;
_computed = false;
_stripComputed = false;
_numLevels = 3;
// _cap = false;
_cap = true ;
_extendLength = false;
_texture_width = 1 ;
_texture_height= 1 ;
_texture_radius = 1.0;
_radius = -1;
_color = makeColor(0,0,0);
_adjustedColor = makeColor(0,0,0);
if (qobj == NULL)
qobj = gluNewQuadric();
_useTexture = false;
_lumAlphaNum = 0;
_Alphanum = 0;
_depth = 0;
_tOffset=0;
load(fp);
}
*/
Stroke::Stroke(float radius,GLuint color,StrokeNumT n)
{
_limit = _temp = NULL;
_computed = false;
_stripComputed = false;
_numLevels = 3;
_cap = true ;
// _cap = false;
_extendLength = false;
_radius = radius;
_color = color;
_adjustedColor = _color;
_tOffset=0;
_texture_width = 1 ;
_texture_height= 1 ;
_texture_radius = 1.0;
_num = n;
if (qobj == NULL)
{
qobj = gluNewQuadric();
}
_useTexture = false;
_lumAlphaNum = 0;
_alphaNum = 0;
_depth = 0;
}
Stroke::Stroke(int cx,int cy,float radius,GLubyte r,GLubyte g,GLubyte b,
StrokeNumT n)
{
_control.push_back(PointR(cx,cy,radius));
_limit = _temp = NULL;
_computed = false;
_stripComputed = false;
_numLevels = 3;
// _cap = false;
_cap = true ;
_extendLength = false;
_radius = radius;
_color = makeColor(r,g,b);
_adjustedColor = makeColor(r,g,b);
_tOffset=0;
_num = n;
_texture_width = 1 ;
_texture_height= 1 ;
_texture_radius = 1.0;
if (qobj == NULL)
{
qobj = gluNewQuadric();
}
_useTexture = false;
_lumAlphaNum = 0;
_alphaNum = 0;
_depth = 0;
}
Stroke::Stroke(int cx,int cy,float radius,GLuint color,StrokeNumT n)
{
_control.push_back(PointR(cx,cy,radius));
_limit = _temp = NULL;
_computed = false;
_stripComputed = false;
_numLevels = 3;
// _cap = false;
_cap = true;
_extendLength = false;
_radius = radius;
_texture_width = 1 ;
_texture_height= 1 ;
_texture_radius = 1.0;
_color = color;
_adjustedColor = color;
_tOffset=0;
_num = n;
if (qobj == NULL)
{
qobj = gluNewQuadric();
}
_useTexture = false;
_lumAlphaNum = 0;
_alphaNum = 0;
_depth = 0;
}
Stroke::Stroke(const vector<PointR> & control, float radius,GLuint color,
StrokeNumT n) : _control(control)
{
_limit = _temp = NULL;
_computed = false;
_stripComputed = false;
_numLevels = 3;
_cap = true ;
// _cap = false;
_extendLength = false;
_radius = radius;
_texture_width = 1 ;
_texture_height= 1 ;
_texture_radius = 1.0;
_color = color;
_adjustedColor = color;
_tOffset=0;
_num = n;
if (qobj == NULL)
{
qobj = gluNewQuadric();
}
_useTexture = false;
_lumAlphaNum = 0;
_alphaNum = 0;
_depth = 0;
}
Stroke::Stroke( const Stroke& s)
{
_control = s._control;
_limit = _temp = NULL;
_computed = false;
_stripComputed = false ;
_numLevels = s._numLevels;
_cap = s._cap;
_extendLength = s._extendLength;
_texture_width = s._texture_width ;
_texture_height= s._texture_height ;
_texture_radius= s._texture_radius ;
_radius = s._radius;
_color = s._color;
_adjustedColor = s._adjustedColor;
_tOffset=s._tOffset;
_num = s._num;
// SKQ
_useTexture = s._useTexture;
_textureName = s._textureName ;
_texture_radius = s._texture_radius;
_ufreq = s._ufreq;
// _vfreq = s._vfreq;
_ustart = s._ustart;
// _vstart = s._vstart;
_depth = s._depth;
_lumAlphaNum = s._lumAlphaNum;
_alphaNum = s._alphaNum;
}
Stroke& Stroke::operator=( const Stroke& s)
{
_control = s._control;
_limit = _temp = NULL;
_computed = false;
_stripComputed = false;
_numLevels = s._numLevels;
_cap = s._cap;
_extendLength = s._extendLength;
_texture_width = s._texture_width ;
_texture_height= s._texture_height ;
_texture_radius= s._texture_radius ;
_radius = s._radius;
_color = s._color;
_adjustedColor = s._adjustedColor;
_tOffset=s._tOffset;
_num = s._num;
// SKQ
_useTexture = s._useTexture;
_textureName = s._textureName ;
_texture_radius = s._texture_radius;
_ufreq = s._ufreq;
// _vfreq = s._vfreq;
_ustart = s._ustart;
// _vstart = s._vstart;
_depth = s._depth;
_lumAlphaNum = s._lumAlphaNum;
_alphaNum = s._alphaNum;
return *this;
}
void Stroke::clear()
{
_computed = false;
_stripComputed = false;
_control.erase(_control.begin(),_control.end());
if (_limit != NULL)
_limit->erase(_limit->begin(),_limit->end());
}
Stroke::~Stroke()
{
if (_limit != NULL)
delete _limit;
if (_temp != NULL)
delete _temp;
}
void Stroke::addControlPoint(float x,float y,float r)
{
if (_control.empty() || _control.back().x != x || _control.back().y != y)
{
_control.push_back(PointR(x,y,r));
_computed = false;
_stripComputed = false;
}
}
void Stroke::drawWideLineCurve( )
{
if (!_computed){
computeLimitCurve();
}
float dx,dy,mag;
PointR p0;
PointR p1;
PointR p2;
if (_limit->empty()){
return;
}
p0 = (*_limit)[0];
if (_limit->size() == 1){
if (_cap)
drawDisc(p0.x,p0.y,depth(),p0.r);//radius());
return;
}
p1 = (*_limit)[1];
dx = p1.y - p0.y;
dy = p0.x - p1.x;
mag = sqrt(dx*dx + dy*dy);
if (mag != 0){
dx /= mag;
dy /= mag;
}
glBegin(GL_TRIANGLE_STRIP);
const float z = depth();
glVertex3f(p0.x + MAX(0,p0.r+_tOffset) * dx, p0.y + MAX(0,p0.r+_tOffset) * dy,z);
glVertex3f(p0.x - MAX(0,p0.r+_tOffset) * dx, p0.y - MAX(0,p0.r+_tOffset) * dy,z);
int curve_length = _limit->size() -1 ;
for(int i=1;i< curve_length -1;i++)
{
p0 = (*_limit)[i-1];
p2 = (*_limit)[i+1];
dx = p2.y - p0.y;
dy = p0.x - p2.x;
mag = sqrt(dx*dx + dy*dy);
if (mag != 0){
dx /= mag;
dy /= mag;
}
glVertex3f(p0.x + MAX(0,p0.r+_tOffset) * dx, p0.y + MAX(0,p0.r+_tOffset) * dy,z);
glVertex3f(p0.x - MAX(0,p0.r+_tOffset) * dx, p0.y - MAX(0,p0.r+_tOffset) * dy,z);
}
p0 = (*_limit)[_limit->size()-2];
p1 = (*_limit)[_limit->size()-1];
dx = p1.y - p0.y;
dy = p0.x - p1.x;
mag = sqrt(dx*dx + dy*dy);
if (mag != 0) {
dx /= mag;
dy /= mag;
}
glVertex3f(p1.x + MAX(0,p1.r+_tOffset) * dx, p1.y + MAX(0,p1.r+_tOffset) * dy,z);
glVertex3f(p1.x - MAX(0,p1.r+_tOffset) * dx, p1.y - MAX(0,p1.r+_tOffset) * dy,z);
glEnd();
}
void Stroke::drawLines(vector<PointR> *curve)
{
glBegin(GL_LINE_STRIP);
for(unsigned int i=0;i<curve->size();i++)
{
PointR & p = (*curve)[i];
glVertex2f(p.x,p.y);
}
glEnd();
}
void Stroke::drawDisc(float x,float y,float z, float radius)
{
glPushMatrix();
glTranslatef(x,y,z);
gluDisk(qobj,0,radius,NUM_SLICES,1);
glPopMatrix();
}
void Stroke::computeCapPoints( PointR p0, float dx, float dy, float * cap_offsets, bool orientation ) {
float dx1, dy1;
float radiusI = RAMP_FACTOR*MAX( 0.0, p0.r + _tOffset);
float radiusO = RAMP_FACTOR_TWO*MAX( 0.0, p0.r + _tOffset);
float capX_inner, capY_inner, capX_outer, capY_outer;
float theta;
float texturePos;
if ( orientation == 0 ) {
inner_cap1.clear() ;
outer_cap1.clear() ;
<API key>.clear() ;
<API key>.clear() ;
texturePos = _ufreq*radiusO;
}else{
inner_cap2.clear() ;
outer_cap2.clear() ;
endCapTexture_inner.clear() ;
endCapTexture_outer.clear() ;
vector<float>::iterator tmp = textureU.end() ;
tmp
texturePos = *tmp;
}
// calculte THETA & avoid divides by zero
if ( dx < 0.000001 && dx > -0.000001 && dy < 0.000001 && dy > -0.000001 ) {
theta = 0.0 ;
float signedDY = dy;
if ( orientation == 0 ) {
signedDY*=-1;
}
if ( signedDY >= 0 ) {
theta+= M_PI;
}
} else if ( dx < 0.000001 && dx > -0.000001) {
// tan undefined
theta = M_PI / 2.0 ;
// correct the sign
float signedDY = dy;
if ( orientation == 0 ) {
signedDY*=-1;
}
if ( signedDY < 0 ) {
theta*=-1;
}
} else if ( orientation == 0 ) {
theta = atan2( -dy , -dx ) ;
}else{
theta = atan2( dy, dx );
}
// debug
if ( ! finite(theta) ) {
printf("dx: %f, dy: %f\n", dx, dy);
printf("theta: %f\n", theta) ;
assert(finite(theta));
}
float texture_theta;
for ( int slice = 0 ; slice <= NUM_SLICES ; slice ++ ) {
dx1 = cos(theta + (float) slice * M_PI / NUM_SLICES);
dy1 = sin(theta + (float) slice * M_PI / NUM_SLICES);
texture_theta = (float)slice*M_PI/NUM_SLICES ;
// no texture cap
if ( !_useTexture ) {
capX_inner = radiusI * dx1 ;
capY_inner = radiusI * dy1 ;
capX_outer = radiusO * dx1 ;
capY_outer = radiusO * dy1 ;
} else if (_textureType == paper) {
// paper texture cap
capX_inner = cap_offsets[slice]*dx1 + radiusI * dx1 ;
capY_inner = cap_offsets[slice]*dy1 + radiusI * dy1 ;
capX_outer = cap_offsets[slice]*dx1 + radiusO * dx1 ;
capY_outer = cap_offsets[slice]*dy1 + radiusO * dy1 ;
}else{
// stroke texture cap
capX_inner = radiusI * dx1 ;
capY_inner = radiusI * dy1 ;
capX_outer = radiusO * dx1 ;
capY_outer = radiusO * dy1 ;
Point textureOuter;
Point textureInner;
if ( orientation == 0 ) {
textureOuter.x = texturePos -_ufreq*radiusO*sin( texture_theta ) ;
textureOuter.y = 0.5 - 0.5*_texture_radius*cos( texture_theta ) ;
<API key>.push_back( textureOuter ) ;
textureInner.x = texturePos - _ufreq*radiusI*sin( texture_theta ) ;
textureInner.y = 0.5 - 0.25*_texture_radius*cos( texture_theta ) ;
<API key>.push_back( textureInner ) ;
}else{
textureOuter.x = texturePos -_ufreq*radiusO*sin( texture_theta + M_PI ) ;
textureOuter.y = 0.5 - 0.5*_texture_radius*cos( texture_theta + M_PI ) ;
endCapTexture_outer.push_back( textureOuter ) ;
textureInner.x = texturePos - _ufreq*radiusI*sin( texture_theta + M_PI) ;
textureInner.y = 0.5 - 0.25*_texture_radius*cos( texture_theta + M_PI) ;
endCapTexture_inner.push_back( textureInner ) ;
}
}
if ( orientation == 0 ) {
inner_cap1.push_back( Point( capX_inner, capY_inner ) );
outer_cap1.push_back( Point( capX_outer, capY_outer ) );
} else {
inner_cap2.push_back( Point( capX_inner, capY_inner ) );
outer_cap2.push_back( Point( capX_outer, capY_outer ) );
}
}
if ( orientation == 0 ) {
startCap.p0 = p0 ;
startCap.dx = dx ;
startCap.dy = dy ;
startCap.orientation = false ;
}else{
endCap.p0 = p0;
endCap.dx = dx;
endCap.dy = dy;
endCap.orientation = true;
}
}
void Stroke::setUniformRadius(const float t) {
for (vector<PointR>::iterator c = _limit->begin(); c!=_limit->end(); ++c)
c->r = t;
}
void Stroke::computeStripPoints( const vector<PointR> *curve) {
left_inner.clear() ;
left_outer.clear() ;
right_inner.clear() ;
right_outer.clear() ;
textureU.clear() ;
if (curve->empty())
{
_stripComputed = true ;
return;
}
// make sure all points are finite
//int length = curve->size() ;
for ( int i = 0 ; i < curve->size() ; i++ ) {
PointR p = (*curve)[i];
if ( !finite(p.x) ) {
printf("curve point i x value = %f\n", p.x);
assert(finite(p.x));
}
if ( !finite(p.y) ) {
printf("curve point i y value = %f\n", p.x);
assert(finite(p.y));
}
}
// get a list of random offsets to use to jitter the line.
// MOVE THIS INTO THE IF STATEMENT...
float ratio = ((float) _texture_width) / (float) _texture_height ;
ratio/=_texture_radius;
float* left_offsets_buffer = new float [curve->size()];
float* <API key> = new float [ curve->size()] ;
float* left_offsets = new float [curve->size()];
float* right_offsets = new float [ curve->size()] ;
// random jitters for the caps
// the first and last jitters of the caps semi circle
// will be taken from the strip offsets so there is continuity
// between the two pieces.
float* cap1_offsets = new float [ NUM_SLICES +1 ];
float* cap2_offsets = new float [ NUM_SLICES +1 ];
float* cap1_offsets_buffer = new float [ NUM_SLICES -1 ] ;
float* cap2_offsets_buffer = new float [ NUM_SLICES -1 ] ;
if (_useTexture && (_textureType == paper)){
makeRandomArray( left_offsets_buffer, curve->size() );
makeRandomArray( <API key>, curve->size());
blendArray( left_offsets, left_offsets_buffer, curve->size(), curve->size(), 0 ) ;
blendArray( right_offsets, <API key>, curve->size(), curve->size(), 0 );
if ( _cap ) {
makeRandomArray( cap1_offsets_buffer, NUM_SLICES-1);
makeRandomArray( cap2_offsets_buffer, NUM_SLICES-1);
blendArray( cap1_offsets, cap1_offsets_buffer, NUM_SLICES+1, NUM_SLICES-1, 1);
blendArray( cap2_offsets, cap2_offsets_buffer, NUM_SLICES+1, NUM_SLICES-1, 1);
// now blend the cap offsets and triangle strip offests so the
// triangle strip and the caps will be continuous
// ( obviously this is not a perfect way to blend them... but not big deal)
left_offsets[0] = 0.5 * left_offsets[1] + 0.5 * cap1_offsets[0] ;
right_offsets[0] = 0.5 * right_offsets[1] + 0.5 * cap1_offsets[NUM_SLICES-2];
left_offsets[curve->size()-1] = 0.5*left_offsets [curve->size()-2] +
0.5*cap2_offsets [NUM_SLICES-2] ;
right_offsets[curve->size()-1] = 0.5*right_offsets[curve->size()-2] +
0.5*cap2_offsets [0];
cap1_offsets[0] = left_offsets[0] ;
cap1_offsets[NUM_SLICES] = right_offsets[0];
cap2_offsets[0] = left_offsets[curve->size()-1];
cap2_offsets[NUM_SLICES] = right_offsets[curve->size()-1];
}
}
delete [] left_offsets_buffer ;
delete [] <API key> ;
delete [] cap1_offsets_buffer ;
delete [] cap2_offsets_buffer ;
/* save all the points need to calculated the blended sides */
assert(curve != NULL);
float dx,dy,mag;
float jitter_left, jitter_right;
PointR p0;
PointR p1;
PointR p2;
// always keep track of the last set of dx,dy that !=0
// so we can tell the direction of the stroke even if there is
// a pause in stroke movement
float dirDX = 0.0;
float dirDY = -1.0;
if ( curve->size() == 0 ) { return ; }
p0 = (*curve)[0];
_ufreq = 1.0 / ( 2.0*(float)p0.r*ratio ) ;
float cur_textureU = _ufreq * p0.r ;
textureU.push_back(cur_textureU) ;
if (curve->size() == 1)
{
if (_cap)
drawDisc(p0.x,p0.y,depth(),p0.r);//radius());
delete [] left_offsets ;
delete [] right_offsets ;
delete [] cap1_offsets ;
delete [] cap2_offsets ;
_stripComputed = true;
return;
}
// curve->size is at least 2
p1 = (*curve)[1];
dx = p1.y - p0.y;
dy = p0.x - p1.x;
mag = sqrt(dx*dx + dy*dy);
if (mag != 0){
dx /= mag;
dy /= mag;
}
// last changed direction
if ( (dx !=0.0 || dy != 0.0) && finite(dx) && finite(dy) ) {
dirDX = dx ;
dirDY = dy ;
}
// compute the start cap
computeCapPoints( p0, dirDX, dirDY, cap1_offsets, 0 );
startCap.textureU = cur_textureU ;
// compute the triangle strip
float X2, Y2, X1, Y1, tmpX, tmpY ;
if ( _useTexture && _textureType == paper) {
jitter_left = left_offsets[0] ;
jitter_right = right_offsets[0] ;
}
if ( _useTexture && _textureType == stroke ){
float dist = sqrt((p1.x-p0.x)*(p1.x-p0.x)+(p1.y-p0.y)*(p1.y-p0.y));
cur_textureU+=_ufreq * dist ;
textureU.push_back(cur_textureU);
}
if ( _useTexture && _textureType == paper ) {
X2 = p0.x + jitter_right*dx + RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dx ;
Y2 = p0.y + jitter_right*dy + RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dy ;
tmpX = p0.x + jitter_right*dx + RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dx ;
tmpY = p0.y + jitter_right*dy + RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dy ;
right_outer.push_back(Point( tmpX , tmpY ));
}else{
X2 = p0.x + RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dx ;
Y2 = p0.y + RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dy ;
tmpX = p0.x + RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dx ;
tmpY = p0.y + RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dy ;
right_outer.push_back(Point( tmpX , tmpY ) );
}
right_inner.push_back(Point( X2, Y2 )) ;
if ( _useTexture && _textureType == paper ) {
X1 = p0.x - jitter_left*dx - RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dx ;
Y1 = p0.y - jitter_left*dy - RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dy ;
tmpX = p0.x - jitter_left*dx - RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dx ;
tmpY = p0.y - jitter_left*dy - RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dy ;
left_outer.push_back(Point( tmpX, tmpY ));
} else {
X1 = p0.x - RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dx ;
Y1 = p0.y - RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dy ;
tmpX = p0.x - RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dx ;
tmpY = p0.y - RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dy ;
left_outer.push_back(Point( tmpX, tmpY ));
}
left_inner.push_back(Point( X1, Y1 ));
// computing strip points
for( unsigned int i=1;i<curve->size()-1;i++){
p0 = (*curve)[i-1];
p2 = (*curve)[i+1];
float jitter_left, jitter_right ;
if ( _useTexture && _textureType == paper ) {
jitter_left = left_offsets[i-1];
jitter_right = right_offsets[i-1];
}
dx = p2.y - p0.y;
dy = p0.x - p2.x;
mag = sqrt(dx*dx + dy*dy);
if (mag != 0) {
dx /= mag;
dy /= mag;
}
if ( dx !=0.0 || dy != 0.0 ) {
dirDX = dx ;
dirDY = dy ;
}
// textureU
if (_useTexture && _textureType == stroke ){
p1 = (*curve)[i];
float dist = sqrt((p1.x-p0.x)*(p1.x-p0.x)+(p1.y-p0.y)*(p1.y-p0.y));
cur_textureU+=_ufreq * dist ;
textureU.push_back(cur_textureU);
}
if ( _useTexture && (_textureType == paper) ) {
X2 = p0.x + jitter_right*dx + RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dx ;
Y2 = p0.y + jitter_right*dy + RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dy ;
right_outer.push_back(Point( p0.x + jitter_right*dx + RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dx ,
p0.y + jitter_right*dy + RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dy ) );
} else {
X2 = p0.x + RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dx ;
Y2 = p0.y + RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dy ;
right_outer.push_back(Point( p0.x + RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dx ,
p0.y + RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dy ) );
}
right_inner.push_back(Point( X2, Y2 ));
if ( _useTexture && _textureType == paper ) {
X1 = p0.x - jitter_left*dx - RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dx ;
Y1 = p0.y - jitter_left*dy - RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dy ;
left_outer.push_back(Point( p0.x - jitter_left*dx - RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dx ,
p0.y - jitter_left*dy - RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dy ) );
}else{
X1 = p0.x - RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dx ;
Y1 = p0.y - RAMP_FACTOR*MAX(0,p0.r+_tOffset) * dy ;
left_outer.push_back(Point( p0.x - RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dx ,
p0.y - RAMP_FACTOR_TWO*MAX(0,p0.r+_tOffset) * dy ) );
}
left_inner.push_back(Point( X1, Y1 )); // save this point
}
p0 = (*curve)[curve->size()-2];
p1 = (*curve)[curve->size()-1];
// textureU
if (_useTexture && _textureType == stroke ){
float dist = sqrt((p1.x-p0.x)*(p1.x-p0.x)+(p1.y-p0.y)*(p1.y-p0.y));
cur_textureU+=_ufreq * dist ;
textureU.push_back(cur_textureU);
}
if ( _useTexture && _textureType == paper ) {
jitter_right = right_offsets[curve->size()-1];
jitter_left = left_offsets[curve->size()-1];
}
dx = p1.y - p0.y;
dy = p0.x - p1.x;
mag = sqrt(dx*dx + dy*dy);
if (mag != 0){
dx /= mag;
dy /= mag;
}
if ( (dx !=0.0 || dy != 0.0) && finite(dx) && finite(dy) ) {
dirDX = dx ;
dirDY = dy ;
}
if ( _useTexture && _textureType == paper ) {
X2 = p1.x + jitter_right*dx + RAMP_FACTOR*MAX(0,p1.r+_tOffset) * dx ;
Y2 = p1.y + jitter_right*dy + RAMP_FACTOR*MAX(0,p1.r+_tOffset) * dy ;
right_outer.push_back(Point( p1.x + jitter_right*dx + RAMP_FACTOR_TWO*MAX(0,p1.r+_tOffset) * dx ,
p1.y + jitter_right*dy + RAMP_FACTOR_TWO*MAX(0,p1.r+_tOffset) * dy ) );
}else{
X2 = p1.x + RAMP_FACTOR*MAX(0,p1.r+_tOffset) * dx ;
Y2 = p1.y + RAMP_FACTOR*MAX(0,p1.r+_tOffset) * dy ;
right_outer.push_back(Point( p1.x + RAMP_FACTOR_TWO*MAX(0,p1.r+_tOffset) * dx ,
p1.y + RAMP_FACTOR_TWO*MAX(0,p1.r+_tOffset) * dy ) );
}
right_inner.push_back( Point( X2, Y2));
if ( _useTexture && _textureType == paper ) {
X1 = p1.x - jitter_left*dx - RAMP_FACTOR*MAX(0, p1.r+_tOffset) * dx ;
Y1 = p1.y - jitter_left*dy - RAMP_FACTOR*MAX(0, p1.r+_tOffset) * dy ;
left_outer.push_back(Point( p1.x - jitter_left*dx - RAMP_FACTOR_TWO*MAX(0,p1.r+_tOffset) * dx ,
p1.y - jitter_left*dy - RAMP_FACTOR_TWO*MAX(0,p1.r+_tOffset) * dy ) );
}else{
X1 = p1.x - RAMP_FACTOR*MAX(0, p1.r+_tOffset) * dx ;
Y1 = p1.y - RAMP_FACTOR*MAX(0, p1.r+_tOffset) * dy ;
left_outer.push_back(Point( p1.x - RAMP_FACTOR_TWO*MAX(0,p1.r+_tOffset) * dx ,
p1.y - RAMP_FACTOR_TWO*MAX(0,p1.r+_tOffset) * dy ) );
}
left_inner.push_back( Point(X1, Y1));
// compute end cap points
computeCapPoints( p1, dirDX, dirDY, cap2_offsets, 1 );
endCap.textureU = cur_textureU ;
_stripComputed = true;
}
void Stroke::drawTriangleStrip( Strip strip )
{
vector<Point>::iterator left_itr;
vector<Point>::iterator right_itr;
vector<Point>::iterator end;
GLboolean blended = glIsEnabled(GL_BLEND);
float left_alpha ;
float right_alpha ;
const float z = depth();
float curve_length ;
float textureX1; // the left edge of the texture;
float textureX2; // the right edge of the texture ;
vector<float>::iterator textureU_itr = textureU.begin() ; // for stroke texture
float X1, Y1, X2, Y2;
if ( left_outer.size() <= 0 || left_inner.size() <= 0 || right_inner.size() <= 0 || right_outer.size() <= 0 ) {
printf("returning size==0\n");
return ;
}
float cur_color[4];
glGetFloatv( GL_CURRENT_COLOR, cur_color) ;
switch( strip ) {
case __left :
left_itr = left_outer.begin() ;
right_itr = left_inner.begin() ;
end = left_outer.end() ;
curve_length = left_outer.size() ;
assert( left_outer.size() == left_inner.size() );
left_alpha = 1.0 ;
right_alpha = 1.0 ;
textureX2 = 0.5 - _texture_radius*0.5;
textureX1 = 0.5 - _texture_radius*0.25;
break ;
case __middle :
left_itr = left_inner.begin() ;
right_itr = right_inner.begin() ;
end = left_inner.end() ;
curve_length = left_inner.size() ;
assert( left_inner.size() == right_inner.size() );
left_alpha = 1.0 ;
right_alpha = 1.0 ;
textureX2 = 0.5 - _texture_radius*0.25 ;
textureX1 = 0.5 + _texture_radius*0.25 ;
break ;
case __right :
left_itr = right_inner.begin() ;
right_itr = right_outer.begin() ;
end = right_inner.end() ;
curve_length = right_outer.size() ;
assert( right_outer.size() == right_inner.size() );
left_alpha = 1.0 ;
right_alpha = 1.0 ; // G! 0
textureX2 = 0.5 + _texture_radius*0.25 ;
textureX1 = 0.5 + _texture_radius*0.5 ;
break;
}
//glEnable( GL_BLEND ) ; //G!
glBegin(GL_TRIANGLE_STRIP);
X2 = left_itr->x ;
Y2 = left_itr->y ;
left_itr++ ;
glColor4f( cur_color[0], cur_color[1], cur_color[2], left_alpha ) ;
if (_useTexture){
if ( _textureType == paper ) {
glTexCoord2f( X2 / _texture_width , Y2 / _texture_height ) ;
}else{
if ( _textureType == stroke ) {
glTexCoord2f( *textureU_itr , textureX2 );
}
}
}
glVertex3f( X2, Y2, z);
X1 = right_itr->x ;
Y1 = right_itr->y ;
right_itr++ ;
glColor4f( cur_color[0], cur_color[1], cur_color[2], right_alpha );
if (_useTexture){
if ( _textureType == paper ) {
glTexCoord2f( X1 / _texture_width ,Y1/ _texture_height ) ;
}else{
if ( _textureType == stroke ) {
glTexCoord2f( *textureU_itr , textureX1 );
}
}
}
glVertex3f( X1, Y1, z);
if ( _textureType == stroke && _useTexture ) {
textureU_itr++;
}
while ( left_itr != end ) {
X2 = left_itr->x ;
Y2 = left_itr->y ;
left_itr++ ;
glColor4f( cur_color[0], cur_color[1], cur_color[2], left_alpha );
if (_useTexture){
if ( _textureType == paper ) {
glTexCoord2f(X2 / _texture_width , Y2 /_texture_height ) ;
}else{
if ( _textureType == stroke ) {
glTexCoord2f( *textureU_itr , textureX2 );
// glTexCoord2f( textureX2, *textureU_itr );
}
}
}
glVertex3f( X2, Y2, z);
X1 = right_itr->x ;
Y1 = right_itr->y ;
right_itr++ ;
glColor4f( cur_color[0], cur_color[1], cur_color[2], right_alpha );
if (_useTexture){
if ( _textureType == paper ) {
glTexCoord2f( X1 / _texture_width , Y1 / _texture_height ) ;
}else{
if ( _textureType == stroke ) {
glTexCoord2f( *textureU_itr , textureX1 );
}
}
}
glVertex3f( X1, Y1, z);
if ( _useTexture && _textureType == stroke ) {
textureU_itr++ ;
}
}
glEnd();
glColor4f( cur_color[0], cur_color[1], cur_color[2], cur_color[3]);
if ( !blended ) {
glDisable(GL_BLEND);
}
assert(!glGetError());
}
/* draws the stroke */
void Stroke::scanConvert( )
{
GLboolean text2D_enabled = glIsEnabled(GL_TEXTURE_2D) ;
if (_useTexture){
glBindTexture(GL_TEXTURE_2D, _textureName );
glEnable( GL_TEXTURE_2D );
}
// _cap= false;
_cap = true;
if (_cap){
drawCap(startCap, inner_cap1, outer_cap1, 0 );
}
drawTriangleStrip( __middle ) ;
drawTriangleStrip( __right ) ;
drawTriangleStrip( __left ) ;
if (_cap){
drawCap(endCap, inner_cap2, outer_cap2, 1 );
}
if ( !text2D_enabled ) {
glDisable(GL_TEXTURE_2D);
}
}
void Stroke::drawControlPolygon()
{
drawLines(&_control);
}
void Stroke::drawLineCurve()
{
if (!_computed){
computeLimitCurve();
}
drawLines(_limit);
}
void Stroke::render()
{
// SKQ
float cur_color[4];
glGetFloatv( GL_CURRENT_COLOR, cur_color);
if (!_computed){
computeLimitCurve();
}
if ( ! _stripComputed ) {
computeStripPoints( _limit ) ;
}
scanConvert( );
}
float Stroke::arcLength()
{
if (!_computed)
computeLimitCurve();
float length = 0;
int limitLength = _limit->size() -1 ;
for (int i=0 ; i < limitLength ; i++ )
{
PointR & p0 = (*_limit)[i];
PointR & p1 = (*_limit)[i+1];
float dist = sqrt((p1.x-p0.x)*(p1.x-p0.x)+(p1.y-p0.y)*(p1.y-p0.y));
length += dist;
}
if (_cap && (limitLength >=2))
{
length += (*_limit)[0].r + (*_limit)[_limit->size()-1].r;
// length += 2*_radius;
}else{
length = 0.0 ;
}
return length;
}
void Stroke::<API key>(vector<PointR> * inputCurve,
vector<PointR> * outputCurve)
{
outputCurve->erase(outputCurve->begin(),outputCurve->end());
if (inputCurve->size() < 1)
return;
PointR pi0;
PointR pi1;
PointR pi2;
pi0 = (*inputCurve)[0];
outputCurve->push_back(pi0);
if (inputCurve->size() == 1)
return;
if (inputCurve->size() == 2)
{
pi1 = (*inputCurve)[1];
outputCurve->push_back(pi1);
return;
}
pi1 = (*inputCurve)[1];
outputCurve->push_back((pi0 + pi1)/2);
for(unsigned int i=1;i<inputCurve->size()-1;i++)
{
pi0 = (*inputCurve)[i-1];
pi1 = (*inputCurve)[i];
pi2 = (*inputCurve)[i+1];
outputCurve->push_back((pi0 + pi1*6 + pi2)/8);
outputCurve->push_back( (pi1 + pi2)/2);
}
outputCurve->push_back(pi2);
}
/*
void Stroke::subdivideFourPoint(vector<PointR> * inputCurve,
vector<PointR> * outputCurve)
{
outputCurve->erase(outputCurve->begin(),outputCurve->end());
if (inputCurve->size() < 1)
return;
PointR pi0;
PointR pi1;
PointR pi2;
PointR pi3;
if (inputCurve->size() == 1)
{
pi0 = (*inputCurve)[0];
outputCurve->push_back(pi0);kPoint(pi0.x,pi0.y));
return;
}
if (inputCurve->size() == 2)
{
pi0 = (*inputCurve)[0];
pi1 = (*inputCurve)[1];
outputCurve->push_back(Point(pi0.x,pi0.y));
outputCurve->push_back(Point((pi0.x+pi1.x)/2,(pi0.y+pi1.y)/2));
outputCurve->push_back(Point(pi1.x,pi1.y));
return;
}
pi0 = (*inputCurve)[0];
pi1 = (*inputCurve)[1];
Point piminus1(2*pi0.x - pi1.x,2*pi0.y - pi1.y);
pi0 = (*inputCurve)[inputCurve->size()-1];
pi1 = (*inputCurve)[inputCurve->size()-2];
Point piplus1(2*pi0.x - pi1.x,2*pi0.y - pi1.y);
for(int i=0;i<inputCurve->size()-1;i++)
{
pi0 = (i==0 ? piminus1 : (*inputCurve)[i-1]);
pi1 = (*inputCurve)[i];
pi2 = (*inputCurve)[i+1];
pi3 = (i==inputCurve->size()-2? piplus1:(*inputCurve)[i+2]);
outputCurve->push_back(Point( pi1.x, pi1.y));
outputCurve->push_back(Point( (-pi0.x + 9*pi1.x + 9*pi2.x - pi3.x)/16,
(-pi0.y + 9*pi1.y + 9*pi2.y - pi3.y)/16));
}
pi0 = inputCurve->back();
outputCurve->push_back(Point(pi0.x,pi0.y));
}
*/
void Stroke::subdivide(vector<PointR> * inputCurve, vector<PointR> * outputCurve)
{
<API key>(inputCurve,outputCurve);
}
void Stroke::computeLimitCurve()
{
if (_limit == NULL)
_limit = new vector<PointR>();
if (_temp == NULL)
_temp = new vector<PointR>();
subdivide(&_control,_limit);
if (_extendLength && _control.size() > 1)
{
PointR & p0 = _control[0];
PointR & p1 = _control[1];
PointR v = p0 - p1;
v.normalize();
v = v*_radius;
_limit->insert(_limit->begin(),p0 + v);
PointR &pn_1 = _control[_control.size()-2];
PointR &pn = _control[_control.size()-1];
v = pn - pn_1;
v.normalize();
v = v*_radius;
_limit->push_back(pn + v);
}
for(int i=0;i<_numLevels/2;i++)
{
subdivide(_limit,_temp);
subdivide(_temp,_limit);
}
_computed = true;
}
void Stroke::print(FILE * fp)
{
fprintf(fp,"Stroke %d: Color = %X. Radius %f. ",
(long int)_num,color(),radius());
fprintf(fp,"Points = ");
for(vector<PointR>::iterator it = _control.begin(); it!=_control.end(); ++it)
fprintf(fp,"[%f,%f] ",(*it).x,(*it).y);
fprintf(fp,"\n\n");
}
/*
void Stroke::save(FILE *fp) const {
int dummy = _control.size();
fwrite(&dummy, sizeof(int), 1, fp); // numPoints
for(vector<PointR>::const_iterator it = _control.begin(); it!=_control.end(); ++it)
fwrite(it, sizeof(PointR), 1, fp);
}
void Stroke::load(FILE *fp) {
int dummy, res;
_numLevels=0;
res = fread(&dummy, sizeof(int), 1, fp); // numPoints
assert(res==1);
_control.reserve(dummy);
PointR ptr;
for (int i=0; i<dummy; i++) {
res = fread(&ptr, sizeof(PointR), 1, fp);
assert(res==1);
_control.push_back(ptr);
}
}
*/
void Stroke::<API key>()
{
//int startsize = _control.size();
vector<PointR>::iterator it = _control.begin();
while (it != _control.end())
{
vector<PointR>::iterator next = it; ++ next;
if (next == _control.end())
return;
if ((*it) == (*next))
_control.erase(it);
it = next;
}
}
/* makes an array of random numbers between 0 and 1 */
void Stroke::makeRandomArray( float arrOut[] , int size ) {
float offset, rand_sign ;
for ( int i = 0 ; i < size ; i++) {
offset = 1.0* rand() / RAND_MAX ;
rand_sign = ( 1.5*rand()/ RAND_MAX );
if ( rand_sign > 0.5 ){
offset = -1.0*offset ;
}
arrOut[i] = offset;
}
}
void Stroke::copyArray( float arrOut[] , float arrIn[], int size){
for ( int i = 0 ; i < size ; i++) {
arrOut[i] = arrIn[i];
}
}
void Stroke::blendArray( float arrOut[], float arrIn[], int sizeOut, int sizeIn, int startIndex ) {
int mid = 1 ;
assert( startIndex >= 0 && startIndex < sizeOut ) ;
assert( sizeOut >= startIndex + sizeIn ) ;
for ( int j = 0 ; j < startIndex ; j++ ) {
arrOut[j] = 0.0;
}
// don't blend the first point
if ( sizeIn > 0 ){
arrOut[startIndex] = arrIn[0] ;
}
int outI = startIndex + 1 ;
for ( int i = 1 ; i < sizeIn-1 ; i++ ){
arrOut[outI] = 0.0;
for ( int neigh = -1; neigh <= 1; neigh ++) {
arrOut[outI] += MEAN_FILTER[mid+neigh]*arrIn[i+neigh];
}
outI ++ ;
}
// don't blend last point
arrOut[outI] = arrIn[sizeIn-1] ;
outI ++ ;
while( outI < sizeOut ) {
arrOut[outI] = 0.0;
outI++;
}
}
void Stroke::drawCap(const _CapData & cap, vector<Point> & inner_points, vector<Point> & outer_points, bool orientation ) {
PointR p0 = cap.p0;
//float textureR ;
float cur_color[4] ;
glGetFloatv( GL_CURRENT_COLOR, cur_color);
glColor4f( cur_color[0], cur_color[1], cur_color[2], 1.0 ) ;
GLboolean blended ;
glGetBooleanv( GL_BLEND, &blended ) ;
float texturePos = -1.0 ;
vector<float>::iterator textureU_itr;
if ( _textureType == stroke && textureU.size() > 0 ) {
if ( orientation == 0 ) {
// drawing the start cap
texturePos = _ufreq*MAX(0.0, (cap.p0).r);
}else{
// drawing the end cap
textureU_itr = textureU.end() ;
textureU_itr
texturePos = *textureU_itr;
}
}
glPushMatrix() ;
glTranslatef(p0.x, p0.y, _depth);
vector<Point>::iterator inner = inner_points.begin();
vector<Point>::iterator outer ;
vector<Point>::iterator inner_end = inner_points.end() ;
vector<Point>::iterator outer_end = outer_points.end() ;
vector<Point>::iterator cap_inner , cap_outer;
if ( orientation == 0 ) {
cap_inner = <API key>.begin() ;
cap_outer = <API key>.begin() ;
} else {
cap_inner = endCapTexture_inner.begin() ;
cap_outer = endCapTexture_outer.begin() ;
}
glBegin( GL_TRIANGLE_FAN );
if (_useTexture){
if ( _textureType == paper ) {
glTexCoord2f(p0.x / _texture_width , p0.y / _texture_height);
}else if ( _textureType == stroke ) {
// stroke texture
glTexCoord2f( texturePos , 0.5 );
}
}
glVertex3i(0,0,0);
while ( inner!= inner_end ){
if (_useTexture){
if ( _textureType == paper ) {
glTexCoord2f( (p0.x + inner->x) / _texture_width , (p0.y + inner->y) / _texture_height ) ;
}else{
if ( _textureType == stroke ) {
// stroke texture
//glTexCoord2f(textureU + _ufreq * p0.r * (-sin(i*M_PI/NUM_SLICES)+1)/2, (-cos(i*M_PI/NUM_SLICES)+1)/2 )
// glTexCoord2f(cap_inner->x, cap_inner->y);
glTexCoord2f(cap_inner->x, cap_inner->y);
cap_inner++;
}
}
}
glVertex3f( inner->x, inner->y, 0);
inner++ ;
}
glEnd() ;
if ( orientation == 0 ) {
cap_inner = <API key>.begin() ;
} else {
cap_inner = endCapTexture_inner.begin() ;
}
inner = inner_points.begin() ;
outer = outer_points.begin() ;
glBegin( GL_TRIANGLE_STRIP );
while ( outer!= outer_end && inner != inner_end ){
// inner point
glColor4f( cur_color[0], cur_color[1], cur_color[2], 1.0 ) ;
if ( _useTexture ) {
if ( _textureType == paper ) {
glTexCoord2f( ( p0.x + inner->x)/_texture_width, (p0.y + inner->y)/_texture_height ) ;
} else if ( _textureType == stroke ) {
glTexCoord2f( cap_inner->x, cap_inner->y ) ;
cap_inner++;
}
}
glVertex3f( inner->x, inner->y, 0) ;
glColor4f( cur_color[0], cur_color[1], cur_color[2], 0.0 ) ;
// outer point
if ( _useTexture ) {
if ( _textureType == paper ) {
glTexCoord2f( ( p0.x + outer->x)/_texture_width, (p0.y + outer->y)/_texture_height ) ;
} else if ( _textureType == stroke ) {
glTexCoord2f( cap_outer->x, cap_outer->y ) ;
cap_outer++;
}
}
glVertex3f( outer->x, outer->y, 0);
outer++ ;
inner++ ;
}
glEnd() ;
glPopMatrix() ;
glColor4f( cur_color[0], cur_color[1], cur_color[2], cur_color[3] ) ;
} |
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* ContactForm is the model behind the contact form.
*/
class PublishForm extends Model
{
public $title;
public $preview;
public $embed;
public $description;
public $category;
public $featured;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['title', 'preview', 'description', 'embed', 'category', 'featured'], 'required'],
];
}
public function post()
{
if ($this->validate()) {
$data = new Data();
$data->title = $this->title;
$data->preview = $this->preview;
$data->description = $this->description;
$data->embed = $this->embed;
$data->category = $this->category;
$data->featured = $this->featured;
$data->date = date("Y-m-d");
$data->save();
return true;
} else {
return false;
}
}
} |
/*
* POSIX Standard: 2.9.2 Minimum Values Added to <limits.h>
*
* Never include this file directly; use <limits.h> instead.
*/
#ifndef _BITS_POSIX1_LIM_H
#define _BITS_POSIX1_LIM_H 1
/* Minimum sizes required by the POSIX P1003.1 standard (Table 2-3). */
#define _POSIX_ARG_MAX 4096 /* exec() may have 4K worth of args */
#define _POSIX_CHILD_MAX 6 /* a process may have 6 children */
#define _POSIX_LINK_MAX 8 /* a file may have 8 links */
#define _POSIX_MAX_CANON 255 /* size of the canonical input queue */
#define _POSIX_MAX_INPUT 255 /* you can type 255 chars ahead */
#define _POSIX_NAME_MAX 255/* max. file name length */
#define _POSIX_NGROUPS_MAX 8 /* supplementary group IDs are optional */
#define _POSIX_OPEN_MAX 16 /* a process may have 16 files open */
#define _POSIX_PATH_MAX 255 /* a pathname may contain 255 chars */
#define _POSIX_PIPE_BUF 512 /* pipes writes of 512 bytes must be atomic */
#define _POSIX_STREAM_MAX 8 /* at least 8 FILEs can be open at once */
#define _POSIX_TZNAME_MAX 3 /* time zone names can be at least 3 chars */
#define _POSIX_SSIZE_MAX 32767 /* read() must support 32767 byte reads */
#define _POSIX_SYMLOOP_MAX 8 /* The number of symbolic links that can be
* traversed in the resolution of a pathname
* in the absence of a loop.
*/
/* Get the <API key> values for the above. */
#include <bits/local_lim.h>
#ifndef SSIZE_MAX
# define SSIZE_MAX LONG_MAX
#endif
/* This value is a guaranteed minimum maximum.
The current maximum can be got from `sysconf'. */
#ifndef NGROUPS_MAX
# define NGROUPS_MAX 8
#endif
#endif /* bits/posix1_lim.h */ |
<?php
namespace Sumo;
class <API key> extends Controller
{
public function index()
{
if (!$this->customer->isLogged()) {
$this->session->data['redirect'] = $this->url->link('account/transaction', '', 'SSL');
$this->redirect($this->url->link('account/login', '', 'SSL'));
}
$this->document->setTitle(Language::getVar('<API key>'));
$this->data['breadcrumbs'] = array();
$this->data['breadcrumbs'][] = array(
'text' => Language::getVar('SUMO_NOUN_HOME'),
'href' => $this->url->link('common/home'),
'separator' => false
);
$this->data['breadcrumbs'][] = array(
'text' => Language::getVar('SUMO_ACCOUNT_TITLE'),
'href' => $this->url->link('account/account', '', 'SSL'),
);
$this->data['breadcrumbs'][] = array(
'text' => Language::getVar('<API key>'),
'href' => $this->url->link('account/transaction', '', 'SSL'),
);
$this->load->model('account/transaction');
//$this->data['column_amount'] = sprintf(Language::getVar('<API key>'), $this->config->get('config_currency'));
if (isset($this->request->get['page'])) {
$page = $this->request->get['page'];
} else {
$page = 1;
}
$this->data['transactions'] = array();
$data = array(
'sort' => 'date_added',
'order' => 'DESC',
'start' => ($page - 1) * 10,
'limit' => 10
);
$transaction_total = $this-><API key>-><API key>($data);
foreach ($this-><API key>->getTransactions($data) as $result) {
$this->data['transactions'][] = array(
'transaction_id' => str_pad($result['<API key>'], 9, 0, STR_PAD_LEFT),
'amount' => Formatter::currency($result['amount']),
'description' => $result['description'],
'date_added' => Formatter::date($result['date_added'])
);
}
$pagination = new Pagination();
$pagination->total = $transaction_total;
$pagination->page = $page;
$pagination->limit = 10;
$pagination->url = $this->url->link('account/transaction', 'page={page}', 'SSL');
$this->data['pagination'] = $pagination->render();
$this->data['total'] = $this->currency->format($this->customer->getBalance());
$this->data['settings'] = $this->config->get('details_account_' . $this->config->get('template'));
if (!is_array($this->data['settings']) || !count($this->data['settings'])) {
$this->data['settings']['left'][] = $this->getChild('app/widgetsimplesidebar/', array('type' => 'accountTree', 'data' => array()));
}
$this->template = 'account/transaction.tpl';
$this->children = array(
'common/footer',
'common/header'
);
$this->response->setOutput($this->render());
}
} |
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
$id = (int) JRequest::getVar('id');
$db = PFdatabase::GetInstance();
$load = PFdatabase::GetInstance();
$load = PFload::GetInstance();
$form = new PFform();
$users = "";
require_once( PFobject::GetHelper('tasks') );
if($id) {
// Include task class
if(!class_exists('PFtasksClass')) require_once($load->Section('tasks.class.php', 'tasks'));
$class = new PFtasksClass();
$query = "SELECT t.*, u.name FROM #__pf_tasks AS t"
. "\n LEFT JOIN #__users AS u ON u.id = t.author"
. "\n WHERE t.id = ".$db->Quote($id);
$db->setQuery($query);
$row = $db->loadObject();
$query = "SELECT * FROM #__pf_progress WHERE id = ".$row->progress;
$db->setQuery($query);
$progr = $db->loadObject();
$query = "SELECT * FROM #__pf_progressing" . "\n WHERE task_id = ".$db->Quote($id); $db->setQuery($query); $steps = $db->loadObjectList();
$query = "SELECT tu.user_id, u.id, u.name FROM #__pf_task_users AS tu"
. "\n RIGHT JOIN #__users AS u ON u.id = tu.user_id"
. "\n WHERE tu.task_id = ".$db->Quote($id)
. "\n GROUP BY tu.user_id ORDER BY u.name ASC";
$db->setQuery($query);
$urows = $db->loadObjectList(); ?>
<table class="admintable"> <tr> <td>Fase</td> <td>Data</td> <td>Utente</td> </tr><?php if(is_array($steps)) { foreach($steps AS $stepp) { $query = "SELECT * FROM #__pf_progress WHERE id = ".$stepp->step; $db->setQuery($query); $progre = $db->loadObject(); $query = "SELECT u.name FROM #__pf_progressing AS pr" . "\n RIGHT JOIN #__users AS u ON u.id = pr.user_id"; $db->setQuery($query); $uname = $db->loadObject(); ?> <tr> <td><?php echo $progre->name;?></td> <td><?php echo PFformat::ToDate($stepp->cdate);?></td> <td><?php echo $uname->name;?></td> </tr><?php } }
?>
</table>
<?php
}
?> |
#include "kexiscripteditor.h"
#include <Kross/Action>
\internal d-pointer class
class KexiScriptEditor::Private
{
public:
Kross::Action* scriptaction;
Private() : scriptaction(0) {}
};
KexiScriptEditor::KexiScriptEditor(QWidget *parent)
: KexiEditor(parent)
, d(new Private())
{
}
KexiScriptEditor::~KexiScriptEditor()
{
delete d;
}
bool KexiScriptEditor::isInitialized() const
{
return d->scriptaction != 0;
}
void KexiScriptEditor::initialize(Kross::Action* scriptaction)
{
d->scriptaction = scriptaction;
Q_ASSERT(d->scriptaction);
disconnect(this, SIGNAL(textChanged()), this, SLOT(slotTextChanged()));
QString code = d->scriptaction->code();
if (code.isEmpty()) {
// If there is no code we just add some information.
@todo remove after release
#if 0
code = "# " + QStringList::split("\n", futureI18n(
"This note will appear for a user in the script's source code "
"as a comment. Keep every row not longer than 60 characters and use '\n.'",
"This is Technology Preview (BETA) version of scripting\n"
"support in Kexi. The scripting API may change in details\n"
"in the next Kexi version.\n"
"For more information and documentation see\n%1",
"http://www.kexi-project.org/scripting/"), true).join("\n
#endif
}
KexiEditor::setText(code);
// We assume Kross and the <API key> are using same
// names for the support languages...
setHighlightMode(d->scriptaction->interpreter());
clearUndoRedo();
KexiEditor::setDirty(false);
connect(this, SIGNAL(textChanged()), this, SLOT(slotTextChanged()));
}
void KexiScriptEditor::slotTextChanged()
{
KexiEditor::setDirty(true);
if (d->scriptaction) {
d->scriptaction->setCode(KexiEditor::text().toUtf8());
}
}
void KexiScriptEditor::setLineNo(long lineno)
{
setCursorPosition(lineno, 0);
} |
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "rtl.h"
#include "tm_p.h"
#include "hard-reg-set.h"
#include "regs.h"
#include "basic-block.h"
#include "flags.h"
#include "insn-config.h"
#include "recog.h"
#include "function.h"
#include "expr.h"
#include "diagnostic-core.h"
#include "toplev.h"
#include "output.h"
#include "ggc.h"
#include "timevar.h"
#include "except.h"
#include "target.h"
#include "params.h"
#include "rtlhooks-def.h"
#include "tree-pass.h"
#include "df.h"
#include "dbgcnt.h"
/* The basic idea of common subexpression elimination is to go
through the code, keeping a record of expressions that would
have the same value at the current scan point, and replacing
expressions encountered with the cheapest equivalent expression.
It is too complicated to keep track of the different possibilities
when control paths merge in this code; so, at each label, we forget all
that is known and start fresh. This can be described as processing each
extended basic block separately. We have a separate pass to perform
global CSE.
Note CSE can turn a conditional or computed jump into a nop or
an unconditional jump. When this occurs we arrange to run the jump
optimizer after CSE to delete the unreachable code.
We use two data structures to record the equivalent expressions:
a hash table for most expressions, and a vector of "quantity
numbers" to record equivalent (pseudo) registers.
The use of the special data structure for registers is desirable
because it is faster. It is possible because registers references
contain a fairly small number, the register number, taken from
a contiguously allocated series, and two register references are
identical if they have the same number. General expressions
do not have any such thing, so the only way to retrieve the
information recorded on an expression other than a register
is to keep it in a hash table.
Registers and "quantity numbers":
At the start of each basic block, all of the (hardware and pseudo)
registers used in the function are given distinct quantity
numbers to indicate their contents. During scan, when the code
copies one register into another, we copy the quantity number.
When a register is loaded in any other way, we allocate a new
quantity number to describe the value generated by this operation.
`REG_QTY (N)' records what quantity register N is currently thought
of as containing.
All real quantity numbers are greater than or equal to zero.
If register N has not been assigned a quantity, `REG_QTY (N)' will
equal -N - 1, which is always negative.
Quantity numbers below zero do not exist and none of the `qty_table'
entries should be referenced with a negative index.
We also maintain a bidirectional chain of registers for each
quantity number. The `qty_table` members `first_reg' and `last_reg',
and `reg_eqv_table' members `next' and `prev' hold these chains.
The first register in a chain is the one whose lifespan is least local.
Among equals, it is the one that was seen first.
We replace any equivalent register with that one.
If two registers have the same quantity number, it must be true that
REG expressions with qty_table `mode' must be in the hash table for both
registers and must be in the same class.
The converse is not true. Since hard registers may be referenced in
any mode, two REG expressions might be equivalent in the hash table
but not have the same quantity number if the quantity number of one
of the registers is not the same mode as those expressions.
Constants and quantity numbers
When a quantity has a known constant value, that value is stored
in the appropriate qty_table `const_rtx'. This is in addition to
putting the constant in the hash table as is usual for non-regs.
Whether a reg or a constant is preferred is determined by the configuration
macro CONST_COSTS and will often depend on the constant value. In any
event, expressions containing constants can be simplified, by fold_rtx.
When a quantity has a known nearly constant value (such as an address
of a stack slot), that value is stored in the appropriate qty_table
`const_rtx'.
Integer constants don't have a machine mode. However, cse
determines the intended machine mode from the destination
of the instruction that moves the constant. The machine mode
is recorded in the hash table along with the actual RTL
constant expression so that different modes are kept separate.
Other expressions:
To record known equivalences among expressions in general
we use a hash table called `table'. It has a fixed number of buckets
that contain chains of `struct table_elt' elements for expressions.
These chains connect the elements whose expressions have the same
hash codes.
Other chains through the same elements connect the elements which
currently have equivalent values.
Register references in an expression are canonicalized before hashing
the expression. This is done using `reg_qty' and qty_table `first_reg'.
The hash code of a register reference is computed using the quantity
number, not the register number.
When the value of an expression changes, it is necessary to remove from the
hash table not just that expression but all expressions whose values
could be different as a result.
1. If the value changing is in memory, except in special cases
ANYTHING referring to memory could be changed. That is because
nobody knows where a pointer does not point.
The function `invalidate_memory' removes what is necessary.
The special cases are when the address is constant or is
a constant plus a fixed register such as the frame pointer
or a static chain pointer. When such addresses are stored in,
we can tell exactly which other such addresses must be invalidated
due to overlap. `invalidate' does this.
All expressions that refer to non-constant
memory addresses are also invalidated. `invalidate_memory' does this.
2. If the value changing is a register, all expressions
containing references to that register, and only those,
must be removed.
Because searching the entire hash table for expressions that contain
a register is very slow, we try to figure out when it isn't necessary.
Precisely, this is necessary only when expressions have been
entered in the hash table using this register, and then the value has
changed, and then another expression wants to be added to refer to
the register's new value. This sequence of circumstances is rare
within any one basic block.
`REG_TICK' and `REG_IN_TABLE', accessors for members of
cse_reg_info, are used to detect this case. REG_TICK (i) is
incremented whenever a value is stored in register i.
REG_IN_TABLE (i) holds -1 if no references to register i have been
entered in the table; otherwise, it contains the value REG_TICK (i)
had when the references were entered. If we want to enter a
reference and REG_IN_TABLE (i) != REG_TICK (i), we must scan and
remove old references. Until we want to enter a new entry, the
mere fact that the two vectors don't match makes the entries be
ignored if anyone tries to match them.
Registers themselves are entered in the hash table as well as in
the equivalent-register chains. However, `REG_TICK' and
`REG_IN_TABLE' do not apply to expressions which are simple
register references. These expressions are removed from the table
immediately when they become invalid, and this can be done even if
we do not immediately search for all the expressions that refer to
the register.
A CLOBBER rtx in an instruction invalidates its operand for further
reuse. A CLOBBER or SET rtx whose operand is a MEM:BLK
invalidates everything that resides in memory.
Related expressions:
Constant expressions that differ only by an additive integer
are called related. When a constant expression is put in
the table, the related expression with no constant term
is also entered. These are made to point at each other
so that it is possible to find out if there exists any
register equivalent to an expression related to a given expression. */
/* Length of qty_table vector. We know in advance we will not need
a quantity number this big. */
static int max_qty;
/* Next quantity number to be allocated.
This is 1 + the largest number needed so far. */
static int next_qty;
/* Per-qty information tracking.
`first_reg' and `last_reg' track the head and tail of the
chain of registers which currently contain this quantity.
`mode' contains the machine mode of this quantity.
`const_rtx' holds the rtx of the constant value of this
quantity, if known. A summations of the frame/arg pointer
and a constant can also be entered here. When this holds
a known value, `const_insn' is the insn which stored the
constant value.
`comparison_{code,const,qty}' are used to track when a
comparison between a quantity and some constant or register has
been passed. In such a case, we know the results of the comparison
in case we see it again. These members record a comparison that
is known to be true. `comparison_code' holds the rtx code of such
a comparison, else it is set to UNKNOWN and the other two
comparison members are undefined. `comparison_const' holds
the constant being compared against, or zero if the comparison
is not against a constant. `comparison_qty' holds the quantity
being compared against when the result is known. If the comparison
is not with a register, `comparison_qty' is -1. */
struct qty_table_elem
{
rtx const_rtx;
rtx const_insn;
rtx comparison_const;
int comparison_qty;
unsigned int first_reg, last_reg;
/* The sizes of these fields should match the sizes of the
code and mode fields of struct rtx_def (see rtl.h). */
ENUM_BITFIELD(rtx_code) comparison_code : 16;
ENUM_BITFIELD(machine_mode) mode : 8;
};
/* The table of all qtys, indexed by qty number. */
static struct qty_table_elem *qty_table;
/* Structure used to pass arguments via for_each_rtx to function
cse_change_cc_mode. */
struct change_cc_mode_args
{
rtx insn;
rtx newreg;
};
#ifdef HAVE_cc0
/* For machines that have a CC0, we do not record its value in the hash
table since its use is guaranteed to be the insn immediately following
its definition and any other insn is presumed to invalidate it.
Instead, we store below the current and last value assigned to CC0.
If it should happen to be a constant, it is stored in preference
to the actual assigned value. In case it is a constant, we store
the mode in which the constant should be interpreted. */
static rtx this_insn_cc0, prev_insn_cc0;
static enum machine_mode this_insn_cc0_mode, prev_insn_cc0_mode;
#endif
/* Insn being scanned. */
static rtx this_insn;
static bool <API key>;
/* Index by register number, gives the number of the next (or
previous) register in the chain of registers sharing the same
value.
Or -1 if this register is at the end of the chain.
If REG_QTY (N) == -N - 1, reg_eqv_table[N].next is undefined. */
/* Per-register equivalence chain. */
struct reg_eqv_elem
{
int next, prev;
};
/* The table of all register equivalence chains. */
static struct reg_eqv_elem *reg_eqv_table;
struct cse_reg_info
{
/* The timestamp at which this register is initialized. */
unsigned int timestamp;
/* The quantity number of the register's current contents. */
int reg_qty;
/* The number of times the register has been altered in the current
basic block. */
int reg_tick;
/* The REG_TICK value at which rtx's containing this register are
valid in the hash table. If this does not equal the current
reg_tick value, such expressions existing in the hash table are
invalid. */
int reg_in_table;
/* The SUBREG that was set when REG_TICK was last incremented. Set
to -1 if the last store was to the whole register, not a subreg. */
unsigned int subreg_ticked;
};
/* A table of cse_reg_info indexed by register numbers. */
static struct cse_reg_info *cse_reg_info_table;
/* The size of the above table. */
static unsigned int <API key>;
/* The index of the first entry that has not been initialized. */
static unsigned int <API key>;
/* The timestamp at the beginning of the current run of
<API key>. We increment this variable at the beginning of
the current run of <API key>. The timestamp field of a
cse_reg_info entry matches the value of this variable if and only
if the entry has been initialized during the current run of
<API key>. */
static unsigned int <API key>;
/* A HARD_REG_SET containing all the hard registers for which there is
currently a REG expression in the hash table. Note the difference
from the above variables, which indicate if the REG is mentioned in some
expression in the table. */
static HARD_REG_SET hard_regs_in_table;
/* True if CSE has altered the CFG. */
static bool cse_cfg_altered;
/* True if CSE has altered conditional jump insns in such a way
that jump optimization should be redone. */
static bool cse_jumps_altered;
/* True if we put a LABEL_REF into the hash table for an INSN
without a REG_LABEL_OPERAND, we have to rerun jump after CSE
to put in the note. */
static bool recorded_label_ref;
/* canon_hash stores 1 in do_not_record
if it notices a reference to CC0, PC, or some other volatile
subexpression. */
static int do_not_record;
/* canon_hash stores 1 in hash_arg_in_memory
if it notices a reference to memory within the expression being hashed. */
static int hash_arg_in_memory;
/* The hash table contains buckets which are chains of `struct table_elt's,
each recording one expression's information.
That expression is in the `exp' field.
The canon_exp field contains a canonical (from the point of view of
alias analysis) version of the `exp' field.
Those elements with the same hash code are chained in both directions
through the `next_same_hash' and `prev_same_hash' fields.
Each set of expressions with equivalent values
are on a two-way chain through the `next_same_value'
and `prev_same_value' fields, and all point with
the `first_same_value' field at the first element in
that chain. The chain is in order of increasing cost.
Each element's cost value is in its `cost' field.
The `in_memory' field is nonzero for elements that
involve any reference to memory. These elements are removed
whenever a write is done to an unidentified location in memory.
To be safe, we assume that a memory address is unidentified unless
the address is either a symbol constant or a constant plus
the frame pointer or argument pointer.
The `related_value' field is used to connect related expressions
(that differ by adding an integer).
The related expressions are chained in a circular fashion.
`related_value' is zero for expressions for which this
chain is not useful.
The `cost' field stores the cost of this element's expression.
The `regcost' field stores the value returned by approx_reg_cost for
this element's expression.
The `is_const' flag is set if the element is a constant (including
a fixed address).
The `flag' field is used as a temporary during some search routines.
The `mode' field is usually the same as GET_MODE (`exp'), but
if `exp' is a CONST_INT and has no machine mode then the `mode'
field is the mode it was being used as. Each constant is
recorded separately for each mode it is used with. */
struct table_elt
{
rtx exp;
rtx canon_exp;
struct table_elt *next_same_hash;
struct table_elt *prev_same_hash;
struct table_elt *next_same_value;
struct table_elt *prev_same_value;
struct table_elt *first_same_value;
struct table_elt *related_value;
int cost;
int regcost;
/* The size of this field should match the size
of the mode field of struct rtx_def (see rtl.h). */
ENUM_BITFIELD(machine_mode) mode : 8;
char in_memory;
char is_const;
char flag;
};
/* We don't want a lot of buckets, because we rarely have very many
things stored in the hash table, and a lot of buckets slows
down a lot of loops that happen frequently. */
#define HASH_SHIFT 5
#define HASH_SIZE (1 << HASH_SHIFT)
#define HASH_MASK (HASH_SIZE - 1)
/* Compute hash code of X in mode M. Special-case case where X is a pseudo
register (hard registers may require `do_not_record' to be set). */
#define HASH(X, M) \
((REG_P (X) && REGNO (X) >= <API key> \
? (((unsigned) REG << 7) + (unsigned) REG_QTY (REGNO (X))) \
: canon_hash (X, M)) & HASH_MASK)
/* Like HASH, but without side-effects. */
#define SAFE_HASH(X, M) \
((REG_P (X) && REGNO (X) >= <API key> \
? (((unsigned) REG << 7) + (unsigned) REG_QTY (REGNO (X))) \
: safe_hash (X, M)) & HASH_MASK)
/* Determine whether register number N is considered a fixed register for the
purpose of approximating register costs.
It is desirable to replace other regs with fixed regs, to reduce need for
non-fixed hard regs.
A reg wins if it is either the frame pointer or designated as fixed. */
#define FIXED_REGNO_P(N) \
((N) == <API key> || (N) == <API key> \
|| fixed_regs[N] || global_regs[N])
/* Compute cost of X, as stored in the `cost' field of a table_elt. Fixed
hard registers and pointers into the frame are the cheapest with a cost
of 0. Next come pseudos with a cost of one and other hard registers with
a cost of 2. Aside from these special cases, call `rtx_cost'. */
#define CHEAP_REGNO(N) \
(REGNO_PTR_FRAME_P(N) \
|| (HARD_REGISTER_NUM_P (N) \
&& FIXED_REGNO_P (N) && REGNO_REG_CLASS (N) != NO_REGS))
#define COST(X) (REG_P (X) ? 0 : notreg_cost (X, SET, 1))
#define COST_IN(X, OUTER, OPNO) (REG_P (X) ? 0 : notreg_cost (X, OUTER, OPNO))
/* Get the number of times this register has been updated in this
basic block. */
#define REG_TICK(N) (get_cse_reg_info (N)->reg_tick)
/* Get the point at which REG was recorded in the table. */
#define REG_IN_TABLE(N) (get_cse_reg_info (N)->reg_in_table)
/* Get the SUBREG set at the last increment to REG_TICK (-1 if not a
SUBREG). */
#define SUBREG_TICKED(N) (get_cse_reg_info (N)->subreg_ticked)
/* Get the quantity number for REG. */
#define REG_QTY(N) (get_cse_reg_info (N)->reg_qty)
/* Determine if the quantity number for register X represents a valid index
into the qty_table. */
#define REGNO_QTY_VALID_P(N) (REG_QTY (N) >= 0)
/* Compare table_elt X and Y and return true iff X is cheaper than Y. */
#define CHEAPER(X, Y) \
(preferable ((X)->cost, (X)->regcost, (Y)->cost, (Y)->regcost) < 0)
static struct table_elt *table[HASH_SIZE];
/* Chain of `struct table_elt's made so far for this function
but currently removed from the table. */
static struct table_elt *free_element_chain;
/* Set to the cost of a constant pool reference if one was found for a
symbolic constant. If this was found, it means we should try to
convert constants into constant pool entries if they don't fit in
the insn. */
static int <API key>;
static int <API key>;
/* Trace a patch through the CFG. */
struct branch_path
{
/* The basic block for this path entry. */
basic_block bb;
};
/* This data describes a block that will be processed by
<API key>. */
struct <API key>
{
/* Total number of SETs in block. */
int nsets;
/* Size of current branch path, if any. */
int path_size;
/* Current path, indicating which basic_blocks will be processed. */
struct branch_path *path;
};
/* Pointers to the live in/live out bitmaps for the boundaries of the
current EBB. */
static bitmap cse_ebb_live_in, cse_ebb_live_out;
/* A simple bitmap to track which basic blocks have been visited
already as part of an already processed extended basic block. */
static sbitmap <API key>;
static bool fixed_base_plus_p (rtx x);
static int notreg_cost (rtx, enum rtx_code, int);
static int approx_reg_cost_1 (rtx *, void *);
static int approx_reg_cost (rtx);
static int preferable (int, int, int, int);
static void new_basic_block (void);
static void make_new_qty (unsigned int, enum machine_mode);
static void make_regs_eqv (unsigned int, unsigned int);
static void delete_reg_equiv (unsigned int);
static int mention_regs (rtx);
static int insert_regs (rtx, struct table_elt *, int);
static void remove_from_table (struct table_elt *, unsigned);
static void <API key> (rtx, unsigned);
static struct table_elt *lookup (rtx, unsigned, enum machine_mode);
static struct table_elt *lookup_for_remove (rtx, unsigned, enum machine_mode);
static rtx lookup_as_function (rtx, enum rtx_code);
static struct table_elt *insert_with_costs (rtx, struct table_elt *, unsigned,
enum machine_mode, int, int);
static struct table_elt *insert (rtx, struct table_elt *, unsigned,
enum machine_mode);
static void merge_equiv_classes (struct table_elt *, struct table_elt *);
static void invalidate (rtx, enum machine_mode);
static void remove_invalid_refs (unsigned int);
static void <API key> (unsigned int, unsigned int,
enum machine_mode);
static void rehash_using_reg (rtx);
static void invalidate_memory (void);
static void invalidate_for_call (void);
static rtx use_related_value (rtx, struct table_elt *);
static inline unsigned canon_hash (rtx, enum machine_mode);
static inline unsigned safe_hash (rtx, enum machine_mode);
static inline unsigned hash_rtx_string (const char *);
static rtx canon_reg (rtx, rtx);
static enum rtx_code <API key> (enum rtx_code, rtx *, rtx *,
enum machine_mode *,
enum machine_mode *);
static rtx fold_rtx (rtx, rtx);
static rtx equiv_constant (rtx);
static void record_jump_equiv (rtx, bool);
static void record_jump_cond (enum rtx_code, enum machine_mode, rtx, rtx,
int);
static void cse_insn (rtx);
static void cse_prescan_path (struct <API key> *);
static void <API key> (rtx);
static void <API key> (rtx);
static rtx cse_process_notes (rtx, rtx, bool *);
static void <API key> (struct <API key> *);
static void count_reg_usage (rtx, int *, rtx, int);
static int check_for_label_ref (rtx *, void *);
extern void dump_class (struct table_elt*);
static void get_cse_reg_info_1 (unsigned int regno);
static struct cse_reg_info * get_cse_reg_info (unsigned int regno);
static int check_dependence (rtx *, void *);
static void flush_hash_table (void);
static bool insn_live_p (rtx, int *);
static bool set_live_p (rtx, rtx, int *);
static int cse_change_cc_mode (rtx *, void *);
static void <API key> (rtx, rtx);
static void <API key> (rtx, rtx, rtx);
static enum machine_mode cse_cc_succs (basic_block, basic_block, rtx, rtx,
bool);
#undef <API key>
#define <API key> <API key>
static const struct rtl_hooks cse_rtl_hooks = <API key>;
/* Nonzero if X has the form (PLUS frame-pointer integer). We check for
virtual regs here because the simplify_*_operation routines are called
by integrate.c, which is called before virtual register instantiation. */
static bool
fixed_base_plus_p (rtx x)
{
switch (GET_CODE (x))
{
case REG:
if (x == frame_pointer_rtx || x == <API key>)
return true;
if (x == arg_pointer_rtx && fixed_regs[ARG_POINTER_REGNUM])
return true;
if (REGNO (x) >= <API key>
&& REGNO (x) <= <API key>)
return true;
return false;
case PLUS:
if (!CONST_INT_P (XEXP (x, 1)))
return false;
return fixed_base_plus_p (XEXP (x, 0));
default:
return false;
}
}
/* Dump the expressions in the equivalence class indicated by CLASSP.
This function is used only for debugging. */
DEBUG_FUNCTION void
dump_class (struct table_elt *classp)
{
struct table_elt *elt;
fprintf (stderr, "Equivalence chain for ");
print_rtl (stderr, classp->exp);
fprintf (stderr, ": \n");
for (elt = classp->first_same_value; elt; elt = elt->next_same_value)
{
print_rtl (stderr, elt->exp);
fprintf (stderr, "\n");
}
}
/* Subroutine of approx_reg_cost; called through for_each_rtx. */
static int
approx_reg_cost_1 (rtx *xp, void *data)
{
rtx x = *xp;
int *cost_p = (int *) data;
if (x && REG_P (x))
{
unsigned int regno = REGNO (x);
if (! CHEAP_REGNO (regno))
{
if (regno < <API key>)
{
if (targetm.<API key> (GET_MODE (x)))
return 1;
*cost_p += 2;
}
else
*cost_p += 1;
}
}
return 0;
}
/* Return an estimate of the cost of the registers used in an rtx.
This is mostly the number of different REG expressions in the rtx;
however for some exceptions like fixed registers we use a cost of
0. If any other hard register reference occurs, return MAX_COST. */
static int
approx_reg_cost (rtx x)
{
int cost = 0;
if (for_each_rtx (&x, approx_reg_cost_1, (void *) &cost))
return MAX_COST;
return cost;
}
/* Return a negative value if an rtx A, whose costs are given by COST_A
and REGCOST_A, is more desirable than an rtx B.
Return a positive value if A is less desirable, or 0 if the two are
equally good. */
static int
preferable (int cost_a, int regcost_a, int cost_b, int regcost_b)
{
/* First, get rid of cases involving expressions that are entirely
unwanted. */
if (cost_a != cost_b)
{
if (cost_a == MAX_COST)
return 1;
if (cost_b == MAX_COST)
return -1;
}
/* Avoid extending lifetimes of hardregs. */
if (regcost_a != regcost_b)
{
if (regcost_a == MAX_COST)
return 1;
if (regcost_b == MAX_COST)
return -1;
}
/* Normal operation costs take precedence. */
if (cost_a != cost_b)
return cost_a - cost_b;
/* Only if these are identical consider effects on register pressure. */
if (regcost_a != regcost_b)
return regcost_a - regcost_b;
return 0;
}
/* Internal function, to compute cost when X is not a register; called
from COST macro to keep it simple. */
static int
notreg_cost (rtx x, enum rtx_code outer, int opno)
{
return ((GET_CODE (x) == SUBREG
&& REG_P (SUBREG_REG (x))
&& GET_MODE_CLASS (GET_MODE (x)) == MODE_INT
&& GET_MODE_CLASS (GET_MODE (SUBREG_REG (x))) == MODE_INT
&& (GET_MODE_SIZE (GET_MODE (x))
< GET_MODE_SIZE (GET_MODE (SUBREG_REG (x))))
&& subreg_lowpart_p (x)
&& <API key> (GET_MODE (x),
GET_MODE (SUBREG_REG (x))))
? 0
: rtx_cost (x, outer, opno, <API key>) * 2);
}
/* Initialize CSE_REG_INFO_TABLE. */
static void
init_cse_reg_info (unsigned int nregs)
{
/* Do we need to grow the table? */
if (nregs > <API key>)
{
unsigned int new_size;
if (<API key> < 2048)
{
/* Compute a new size that is a power of 2 and no smaller
than the large of NREGS and 64. */
new_size = (<API key>
? <API key> : 64);
while (new_size < nregs)
new_size *= 2;
}
else
{
/* If we need a big table, allocate just enough to hold
NREGS registers. */
new_size = nregs;
}
/* Reallocate the table with NEW_SIZE entries. */
free (cse_reg_info_table);
cse_reg_info_table = XNEWVEC (struct cse_reg_info, new_size);
<API key> = new_size;
<API key> = 0;
}
/* Do we have all of the first NREGS entries initialized? */
if (<API key> < nregs)
{
unsigned int old_timestamp = <API key> - 1;
unsigned int i;
/* Put the old timestamp on newly allocated entries so that they
will all be considered out of date. We do not touch those
entries beyond the first NREGS entries to be nice to the
virtual memory. */
for (i = <API key>; i < nregs; i++)
cse_reg_info_table[i].timestamp = old_timestamp;
<API key> = nregs;
}
}
/* Given REGNO, initialize the cse_reg_info entry for REGNO. */
static void
get_cse_reg_info_1 (unsigned int regno)
{
/* Set TIMESTAMP field to <API key> so that this
entry will be considered to have been initialized. */
cse_reg_info_table[regno].timestamp = <API key>;
/* Initialize the rest of the entry. */
cse_reg_info_table[regno].reg_tick = 1;
cse_reg_info_table[regno].reg_in_table = -1;
cse_reg_info_table[regno].subreg_ticked = -1;
cse_reg_info_table[regno].reg_qty = -regno - 1;
}
/* Find a cse_reg_info entry for REGNO. */
static inline struct cse_reg_info *
get_cse_reg_info (unsigned int regno)
{
struct cse_reg_info *p = &cse_reg_info_table[regno];
/* If this entry has not been initialized, go ahead and initialize
it. */
if (p->timestamp != <API key>)
get_cse_reg_info_1 (regno);
return p;
}
/* Clear the hash table and initialize each register with its own quantity,
for a new basic block. */
static void
new_basic_block (void)
{
int i;
next_qty = 0;
/* Invalidate cse_reg_info_table. */
<API key>++;
/* Clear out hash table state for this pass. */
CLEAR_HARD_REG_SET (hard_regs_in_table);
/* The per-quantity values used to be initialized here, but it is
much faster to initialize each as it is made in `make_new_qty'. */
for (i = 0; i < HASH_SIZE; i++)
{
struct table_elt *first;
first = table[i];
if (first != NULL)
{
struct table_elt *last = first;
table[i] = NULL;
while (last->next_same_hash != NULL)
last = last->next_same_hash;
/* Now relink this hash entire chain into
the free element list. */
last->next_same_hash = free_element_chain;
free_element_chain = first;
}
}
#ifdef HAVE_cc0
prev_insn_cc0 = 0;
#endif
}
/* Say that register REG contains a quantity in mode MODE not in any
register before and initialize that quantity. */
static void
make_new_qty (unsigned int reg, enum machine_mode mode)
{
int q;
struct qty_table_elem *ent;
struct reg_eqv_elem *eqv;
gcc_assert (next_qty < max_qty);
q = REG_QTY (reg) = next_qty++;
ent = &qty_table[q];
ent->first_reg = reg;
ent->last_reg = reg;
ent->mode = mode;
ent->const_rtx = ent->const_insn = NULL_RTX;
ent->comparison_code = UNKNOWN;
eqv = ®_eqv_table[reg];
eqv->next = eqv->prev = -1;
}
/* Make reg NEW equivalent to reg OLD.
OLD is not changing; NEW is. */
static void
make_regs_eqv (unsigned int new_reg, unsigned int old_reg)
{
unsigned int lastr, firstr;
int q = REG_QTY (old_reg);
struct qty_table_elem *ent;
ent = &qty_table[q];
/* Nothing should become eqv until it has a "non-invalid" qty number. */
gcc_assert (REGNO_QTY_VALID_P (old_reg));
REG_QTY (new_reg) = q;
firstr = ent->first_reg;
lastr = ent->last_reg;
/* Prefer fixed hard registers to anything. Prefer pseudo regs to other
hard regs. Among pseudos, if NEW will live longer than any other reg
of the same qty, and that is beyond the current basic block,
make it the new canonical replacement for this qty. */
if (! (firstr < <API key> && FIXED_REGNO_P (firstr))
/* Certain fixed registers might be of the class NO_REGS. This means
that not only can they not be allocated by the compiler, but
they cannot be used in substitutions or canonicalizations
either. */
&& (new_reg >= <API key> || REGNO_REG_CLASS (new_reg) != NO_REGS)
&& ((new_reg < <API key> && FIXED_REGNO_P (new_reg))
|| (new_reg >= <API key>
&& (firstr < <API key>
|| (bitmap_bit_p (cse_ebb_live_out, new_reg)
&& !bitmap_bit_p (cse_ebb_live_out, firstr))
|| (bitmap_bit_p (cse_ebb_live_in, new_reg)
&& !bitmap_bit_p (cse_ebb_live_in, firstr))))))
{
reg_eqv_table[firstr].prev = new_reg;
reg_eqv_table[new_reg].next = firstr;
reg_eqv_table[new_reg].prev = -1;
ent->first_reg = new_reg;
}
else
{
/* If NEW is a hard reg (known to be non-fixed), insert at end.
Otherwise, insert before any non-fixed hard regs that are at the
end. Registers of class NO_REGS cannot be used as an
equivalent for anything. */
while (lastr < <API key> && reg_eqv_table[lastr].prev >= 0
&& (REGNO_REG_CLASS (lastr) == NO_REGS || ! FIXED_REGNO_P (lastr))
&& new_reg >= <API key>)
lastr = reg_eqv_table[lastr].prev;
reg_eqv_table[new_reg].next = reg_eqv_table[lastr].next;
if (reg_eqv_table[lastr].next >= 0)
reg_eqv_table[reg_eqv_table[lastr].next].prev = new_reg;
else
qty_table[q].last_reg = new_reg;
reg_eqv_table[lastr].next = new_reg;
reg_eqv_table[new_reg].prev = lastr;
}
}
/* Remove REG from its equivalence class. */
static void
delete_reg_equiv (unsigned int reg)
{
struct qty_table_elem *ent;
int q = REG_QTY (reg);
int p, n;
/* If invalid, do nothing. */
if (! REGNO_QTY_VALID_P (reg))
return;
ent = &qty_table[q];
p = reg_eqv_table[reg].prev;
n = reg_eqv_table[reg].next;
if (n != -1)
reg_eqv_table[n].prev = p;
else
ent->last_reg = p;
if (p != -1)
reg_eqv_table[p].next = n;
else
ent->first_reg = n;
REG_QTY (reg) = -reg - 1;
}
/* Remove any invalid expressions from the hash table
that refer to any of the registers contained in expression X.
Make sure that newly inserted references to those registers
as subexpressions will be considered valid.
mention_regs is not called when a register itself
is being stored in the table.
Return 1 if we have done something that may have changed the hash code
of X. */
static int
mention_regs (rtx x)
{
enum rtx_code code;
int i, j;
const char *fmt;
int changed = 0;
if (x == 0)
return 0;
code = GET_CODE (x);
if (code == REG)
{
unsigned int regno = REGNO (x);
unsigned int endregno = END_REGNO (x);
unsigned int i;
for (i = regno; i < endregno; i++)
{
if (REG_IN_TABLE (i) >= 0 && REG_IN_TABLE (i) != REG_TICK (i))
remove_invalid_refs (i);
REG_IN_TABLE (i) = REG_TICK (i);
SUBREG_TICKED (i) = -1;
}
return 0;
}
/* If this is a SUBREG, we don't want to discard other SUBREGs of the same
pseudo if they don't use overlapping words. We handle only pseudos
here for simplicity. */
if (code == SUBREG && REG_P (SUBREG_REG (x))
&& REGNO (SUBREG_REG (x)) >= <API key>)
{
unsigned int i = REGNO (SUBREG_REG (x));
if (REG_IN_TABLE (i) >= 0 && REG_IN_TABLE (i) != REG_TICK (i))
{
/* If REG_IN_TABLE (i) differs from REG_TICK (i) by one, and
the last store to this register really stored into this
subreg, then remove the memory of this subreg.
Otherwise, remove any memory of the entire register and
all its subregs from the table. */
if (REG_TICK (i) - REG_IN_TABLE (i) > 1
|| SUBREG_TICKED (i) != REGNO (SUBREG_REG (x)))
remove_invalid_refs (i);
else
<API key> (i, SUBREG_BYTE (x), GET_MODE (x));
}
REG_IN_TABLE (i) = REG_TICK (i);
SUBREG_TICKED (i) = REGNO (SUBREG_REG (x));
return 0;
}
/* If X is a comparison or a COMPARE and either operand is a register
that does not have a quantity, give it one. This is so that a later
call to record_jump_equiv won't cause X to be assigned a different
hash code and not found in the table after that call.
It is not necessary to do this here, since rehash_using_reg can
fix up the table later, but doing this here eliminates the need to
call that expensive function in the most common case where the only
use of the register is in the comparison. */
if (code == COMPARE || COMPARISON_P (x))
{
if (REG_P (XEXP (x, 0))
&& ! REGNO_QTY_VALID_P (REGNO (XEXP (x, 0))))
if (insert_regs (XEXP (x, 0), NULL, 0))
{
rehash_using_reg (XEXP (x, 0));
changed = 1;
}
if (REG_P (XEXP (x, 1))
&& ! REGNO_QTY_VALID_P (REGNO (XEXP (x, 1))))
if (insert_regs (XEXP (x, 1), NULL, 0))
{
rehash_using_reg (XEXP (x, 1));
changed = 1;
}
}
fmt = GET_RTX_FORMAT (code);
for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i
if (fmt[i] == 'e')
changed |= mention_regs (XEXP (x, i));
else if (fmt[i] == 'E')
for (j = 0; j < XVECLEN (x, i); j++)
changed |= mention_regs (XVECEXP (x, i, j));
return changed;
}
/* Update the register quantities for inserting X into the hash table
with a value equivalent to CLASSP.
(If the class does not contain a REG, it is irrelevant.)
If MODIFIED is nonzero, X is a destination; it is being modified.
Note that delete_reg_equiv should be called on a register
before insert_regs is done on that register with MODIFIED != 0.
Nonzero value means that elements of reg_qty have changed
so X's hash code may be different. */
static int
insert_regs (rtx x, struct table_elt *classp, int modified)
{
if (REG_P (x))
{
unsigned int regno = REGNO (x);
int qty_valid;
/* If REGNO is in the equivalence table already but is of the
wrong mode for that equivalence, don't do anything here. */
qty_valid = REGNO_QTY_VALID_P (regno);
if (qty_valid)
{
struct qty_table_elem *ent = &qty_table[REG_QTY (regno)];
if (ent->mode != GET_MODE (x))
return 0;
}
if (modified || ! qty_valid)
{
if (classp)
for (classp = classp->first_same_value;
classp != 0;
classp = classp->next_same_value)
if (REG_P (classp->exp)
&& GET_MODE (classp->exp) == GET_MODE (x))
{
unsigned c_regno = REGNO (classp->exp);
gcc_assert (REGNO_QTY_VALID_P (c_regno));
/* Suppose that 5 is hard reg and 100 and 101 are
pseudos. Consider
(set (reg:si 100) (reg:si 5))
(set (reg:si 5) (reg:si 100))
(set (reg:di 101) (reg:di 5))
We would now set REG_QTY (101) = REG_QTY (5), but the
entry for 5 is in SImode. When we use this later in
copy propagation, we get the register in wrong mode. */
if (qty_table[REG_QTY (c_regno)].mode != GET_MODE (x))
continue;
make_regs_eqv (regno, c_regno);
return 1;
}
/* Mention_regs for a SUBREG checks if REG_TICK is exactly one larger
than REG_IN_TABLE to find out if there was only a single preceding
invalidation - for the SUBREG - or another one, which would be
for the full register. However, if we find here that REG_TICK
indicates that the register is invalid, it means that it has
been invalidated in a separate operation. The SUBREG might be used
now (then this is a recursive call), or we might use the full REG
now and a SUBREG of it later. So bump up REG_TICK so that
mention_regs will do the right thing. */
if (! modified
&& REG_IN_TABLE (regno) >= 0
&& REG_TICK (regno) == REG_IN_TABLE (regno) + 1)
REG_TICK (regno)++;
make_new_qty (regno, GET_MODE (x));
return 1;
}
return 0;
}
/* If X is a SUBREG, we will likely be inserting the inner register in the
table. If that register doesn't have an assigned quantity number at
this point but does later, the insertion that we will be doing now will
not be accessible because its hash code will have changed. So assign
a quantity number now. */
else if (GET_CODE (x) == SUBREG && REG_P (SUBREG_REG (x))
&& ! REGNO_QTY_VALID_P (REGNO (SUBREG_REG (x))))
{
insert_regs (SUBREG_REG (x), NULL, 0);
mention_regs (x);
return 1;
}
else
return mention_regs (x);
}
/* Compute upper and lower anchors for CST. Also compute the offset of CST
from these anchors/bases such that *_BASE + *_OFFS = CST. Return false iff
CST is equal to an anchor. */
static bool
<API key> (rtx cst,
HOST_WIDE_INT *lower_base, HOST_WIDE_INT *lower_offs,
HOST_WIDE_INT *upper_base, HOST_WIDE_INT *upper_offs)
{
HOST_WIDE_INT n = INTVAL (cst);
*lower_base = n & ~(targetm.const_anchor - 1);
if (*lower_base == n)
return false;
*upper_base =
(n + (targetm.const_anchor - 1)) & ~(targetm.const_anchor - 1);
*upper_offs = n - *upper_base;
*lower_offs = n - *lower_base;
return true;
}
/* Insert the equivalence between ANCHOR and (REG + OFF) in mode MODE. */
static void
insert_const_anchor (HOST_WIDE_INT anchor, rtx reg, HOST_WIDE_INT offs,
enum machine_mode mode)
{
struct table_elt *elt;
unsigned hash;
rtx anchor_exp;
rtx exp;
anchor_exp = GEN_INT (anchor);
hash = HASH (anchor_exp, mode);
elt = lookup (anchor_exp, hash, mode);
if (!elt)
elt = insert (anchor_exp, NULL, hash, mode);
exp = plus_constant (reg, offs);
/* REG has just been inserted and the hash codes recomputed. */
mention_regs (exp);
hash = HASH (exp, mode);
/* Use the cost of the register rather than the whole expression. When
looking up constant anchors we will further offset the corresponding
expression therefore it does not make sense to prefer REGs over
reg-immediate additions. Prefer instead the oldest expression. Also
don't prefer pseudos over hard regs so that we derive constants in
argument registers from other argument registers rather than from the
original pseudo that was used to synthesize the constant. */
insert_with_costs (exp, elt, hash, mode, COST (reg), 1);
}
/* The constant CST is equivalent to the register REG. Create
equivalences between the two anchors of CST and the corresponding
register-offset expressions using REG. */
static void
<API key> (rtx reg, rtx cst, enum machine_mode mode)
{
HOST_WIDE_INT lower_base, lower_offs, upper_base, upper_offs;
if (!<API key> (cst, &lower_base, &lower_offs,
&upper_base, &upper_offs))
return;
/* Ignore anchors of value 0. Constants accessible from zero are
simple. */
if (lower_base != 0)
insert_const_anchor (lower_base, reg, -lower_offs, mode);
if (upper_base != 0)
insert_const_anchor (upper_base, reg, -upper_offs, mode);
}
/* We need to express ANCHOR_ELT->exp + OFFS. Walk the equivalence list of
ANCHOR_ELT and see if offsetting any of the entries by OFFS would create a
valid expression. Return the cheapest and oldest of such expressions. In
*OLD, return how old the resulting expression is compared to the other
equivalent expressions. */
static rtx
<API key> (struct table_elt *anchor_elt, HOST_WIDE_INT offs,
unsigned *old)
{
struct table_elt *elt;
unsigned idx;
struct table_elt *match_elt;
rtx match;
/* Find the cheapest and *oldest* expression to maximize the chance of
reusing the same pseudo. */
match_elt = NULL;
match = NULL_RTX;
for (elt = anchor_elt->first_same_value, idx = 0;
elt;
elt = elt->next_same_value, idx++)
{
if (match_elt && CHEAPER (match_elt, elt))
return match;
if (REG_P (elt->exp)
|| (GET_CODE (elt->exp) == PLUS
&& REG_P (XEXP (elt->exp, 0))
&& GET_CODE (XEXP (elt->exp, 1)) == CONST_INT))
{
rtx x;
/* Ignore expressions that are no longer valid. */
if (!REG_P (elt->exp) && !exp_equiv_p (elt->exp, elt->exp, 1, false))
continue;
x = plus_constant (elt->exp, offs);
if (REG_P (x)
|| (GET_CODE (x) == PLUS
&& IN_RANGE (INTVAL (XEXP (x, 1)),
-targetm.const_anchor,
targetm.const_anchor - 1)))
{
match = x;
match_elt = elt;
*old = idx;
}
}
}
return match;
}
/* Try to express the constant SRC_CONST using a register+offset expression
derived from a constant anchor. Return it if successful or NULL_RTX,
otherwise. */
static rtx
try_const_anchors (rtx src_const, enum machine_mode mode)
{
struct table_elt *lower_elt, *upper_elt;
HOST_WIDE_INT lower_base, lower_offs, upper_base, upper_offs;
rtx lower_anchor_rtx, upper_anchor_rtx;
rtx lower_exp = NULL_RTX, upper_exp = NULL_RTX;
unsigned lower_old, upper_old;
if (!<API key> (src_const, &lower_base, &lower_offs,
&upper_base, &upper_offs))
return NULL_RTX;
lower_anchor_rtx = GEN_INT (lower_base);
upper_anchor_rtx = GEN_INT (upper_base);
lower_elt = lookup (lower_anchor_rtx, HASH (lower_anchor_rtx, mode), mode);
upper_elt = lookup (upper_anchor_rtx, HASH (upper_anchor_rtx, mode), mode);
if (lower_elt)
lower_exp = <API key> (lower_elt, lower_offs, &lower_old);
if (upper_elt)
upper_exp = <API key> (upper_elt, upper_offs, &upper_old);
if (!lower_exp)
return upper_exp;
if (!upper_exp)
return lower_exp;
/* Return the older expression. */
return (upper_old > lower_old ? upper_exp : lower_exp);
}
/* Look in or update the hash table. */
/* Remove table element ELT from use in the table.
HASH is its hash code, made using the HASH macro.
It's an argument because often that is known in advance
and we save much time not recomputing it. */
static void
remove_from_table (struct table_elt *elt, unsigned int hash)
{
if (elt == 0)
return;
/* Mark this element as removed. See cse_insn. */
elt->first_same_value = 0;
/* Remove the table element from its equivalence class. */
{
struct table_elt *prev = elt->prev_same_value;
struct table_elt *next = elt->next_same_value;
if (next)
next->prev_same_value = prev;
if (prev)
prev->next_same_value = next;
else
{
struct table_elt *newfirst = next;
while (next)
{
next->first_same_value = newfirst;
next = next->next_same_value;
}
}
}
/* Remove the table element from its hash bucket. */
{
struct table_elt *prev = elt->prev_same_hash;
struct table_elt *next = elt->next_same_hash;
if (next)
next->prev_same_hash = prev;
if (prev)
prev->next_same_hash = next;
else if (table[hash] == elt)
table[hash] = next;
else
{
/* This entry is not in the proper hash bucket. This can happen
when two classes were merged by `merge_equiv_classes'. Search
for the hash bucket that it heads. This happens only very
rarely, so the cost is acceptable. */
for (hash = 0; hash < HASH_SIZE; hash++)
if (table[hash] == elt)
table[hash] = next;
}
}
/* Remove the table element from its related-value circular chain. */
if (elt->related_value != 0 && elt->related_value != elt)
{
struct table_elt *p = elt->related_value;
while (p->related_value != elt)
p = p->related_value;
p->related_value = elt->related_value;
if (p->related_value == p)
p->related_value = 0;
}
/* Now add it to the free element chain. */
elt->next_same_hash = free_element_chain;
free_element_chain = elt;
}
/* Same as above, but X is a pseudo-register. */
static void
<API key> (rtx x, unsigned int hash)
{
struct table_elt *elt;
/* Because a pseudo-register can be referenced in more than one
mode, we might have to remove more than one table entry. */
while ((elt = lookup_for_remove (x, hash, VOIDmode)))
remove_from_table (elt, hash);
}
/* Look up X in the hash table and return its table element,
or 0 if X is not in the table.
MODE is the machine-mode of X, or if X is an integer constant
with VOIDmode then MODE is the mode with which X will be used.
Here we are satisfied to find an expression whose tree structure
looks like X. */
static struct table_elt *
lookup (rtx x, unsigned int hash, enum machine_mode mode)
{
struct table_elt *p;
for (p = table[hash]; p; p = p->next_same_hash)
if (mode == p->mode && ((x == p->exp && REG_P (x))
|| exp_equiv_p (x, p->exp, !REG_P (x), false)))
return p;
return 0;
}
/* Like `lookup' but don't care whether the table element uses invalid regs.
Also ignore discrepancies in the machine mode of a register. */
static struct table_elt *
lookup_for_remove (rtx x, unsigned int hash, enum machine_mode mode)
{
struct table_elt *p;
if (REG_P (x))
{
unsigned int regno = REGNO (x);
/* Don't check the machine mode when comparing registers;
invalidating (REG:SI 0) also invalidates (REG:DF 0). */
for (p = table[hash]; p; p = p->next_same_hash)
if (REG_P (p->exp)
&& REGNO (p->exp) == regno)
return p;
}
else
{
for (p = table[hash]; p; p = p->next_same_hash)
if (mode == p->mode
&& (x == p->exp || exp_equiv_p (x, p->exp, 0, false)))
return p;
}
return 0;
}
/* Look for an expression equivalent to X and with code CODE.
If one is found, return that expression. */
static rtx
lookup_as_function (rtx x, enum rtx_code code)
{
struct table_elt *p
= lookup (x, SAFE_HASH (x, VOIDmode), GET_MODE (x));
if (p == 0)
return 0;
for (p = p->first_same_value; p; p = p->next_same_value)
if (GET_CODE (p->exp) == code
/* Make sure this is a valid entry in the table. */
&& exp_equiv_p (p->exp, p->exp, 1, false))
return p->exp;
return 0;
}
/* Insert X in the hash table, assuming HASH is its hash code and
CLASSP is an element of the class it should go in (or 0 if a new
class should be made). COST is the code of X and reg_cost is the
cost of registers in X. It is inserted at the proper position to
keep the class in the order cheapest first.
MODE is the machine-mode of X, or if X is an integer constant
with VOIDmode then MODE is the mode with which X will be used.
For elements of equal cheapness, the most recent one
goes in front, except that the first element in the list
remains first unless a cheaper element is added. The order of
pseudo-registers does not matter, as canon_reg will be called to
find the cheapest when a register is retrieved from the table.
The in_memory field in the hash table element is set to 0.
The caller must set it nonzero if appropriate.
You should call insert_regs (X, CLASSP, MODIFY) before calling here,
and if insert_regs returns a nonzero value
you must then recompute its hash code before calling here.
If necessary, update table showing constant values of quantities. */
static struct table_elt *
insert_with_costs (rtx x, struct table_elt *classp, unsigned int hash,
enum machine_mode mode, int cost, int reg_cost)
{
struct table_elt *elt;
/* If X is a register and we haven't made a quantity for it,
something is wrong. */
gcc_assert (!REG_P (x) || REGNO_QTY_VALID_P (REGNO (x)));
/* If X is a hard register, show it is being put in the table. */
if (REG_P (x) && REGNO (x) < <API key>)
add_to_hard_reg_set (&hard_regs_in_table, GET_MODE (x), REGNO (x));
/* Put an element for X into the right hash bucket. */
elt = free_element_chain;
if (elt)
free_element_chain = elt->next_same_hash;
else
elt = XNEW (struct table_elt);
elt->exp = x;
elt->canon_exp = NULL_RTX;
elt->cost = cost;
elt->regcost = reg_cost;
elt->next_same_value = 0;
elt->prev_same_value = 0;
elt->next_same_hash = table[hash];
elt->prev_same_hash = 0;
elt->related_value = 0;
elt->in_memory = 0;
elt->mode = mode;
elt->is_const = (CONSTANT_P (x) || fixed_base_plus_p (x));
if (table[hash])
table[hash]->prev_same_hash = elt;
table[hash] = elt;
/* Put it into the proper value-class. */
if (classp)
{
classp = classp->first_same_value;
if (CHEAPER (elt, classp))
/* Insert at the head of the class. */
{
struct table_elt *p;
elt->next_same_value = classp;
classp->prev_same_value = elt;
elt->first_same_value = elt;
for (p = classp; p; p = p->next_same_value)
p->first_same_value = elt;
}
else
{
/* Insert not at head of the class. */
/* Put it after the last element cheaper than X. */
struct table_elt *p, *next;
for (p = classp;
(next = p->next_same_value) && CHEAPER (next, elt);
p = next)
;
/* Put it after P and before NEXT. */
elt->next_same_value = next;
if (next)
next->prev_same_value = elt;
elt->prev_same_value = p;
p->next_same_value = elt;
elt->first_same_value = classp;
}
}
else
elt->first_same_value = elt;
/* If this is a constant being set equivalent to a register or a register
being set equivalent to a constant, note the constant equivalence.
If this is a constant, it cannot be equivalent to a different constant,
and a constant is the only thing that can be cheaper than a register. So
we know the register is the head of the class (before the constant was
inserted).
If this is a register that is not already known equivalent to a
constant, we must check the entire class.
If this is a register that is already known equivalent to an insn,
update the qtys `const_insn' to show that `this_insn' is the latest
insn making that quantity equivalent to the constant. */
if (elt->is_const && classp && REG_P (classp->exp)
&& !REG_P (x))
{
int exp_q = REG_QTY (REGNO (classp->exp));
struct qty_table_elem *exp_ent = &qty_table[exp_q];
exp_ent->const_rtx = gen_lowpart (exp_ent->mode, x);
exp_ent->const_insn = this_insn;
}
else if (REG_P (x)
&& classp
&& ! qty_table[REG_QTY (REGNO (x))].const_rtx
&& ! elt->is_const)
{
struct table_elt *p;
for (p = classp; p != 0; p = p->next_same_value)
{
if (p->is_const && !REG_P (p->exp))
{
int x_q = REG_QTY (REGNO (x));
struct qty_table_elem *x_ent = &qty_table[x_q];
x_ent->const_rtx
= gen_lowpart (GET_MODE (x), p->exp);
x_ent->const_insn = this_insn;
break;
}
}
}
else if (REG_P (x)
&& qty_table[REG_QTY (REGNO (x))].const_rtx
&& GET_MODE (x) == qty_table[REG_QTY (REGNO (x))].mode)
qty_table[REG_QTY (REGNO (x))].const_insn = this_insn;
/* If this is a constant with symbolic value,
and it has a term with an explicit integer value,
link it up with related expressions. */
if (GET_CODE (x) == CONST)
{
rtx subexp = get_related_value (x);
unsigned subhash;
struct table_elt *subelt, *subelt_prev;
if (subexp != 0)
{
/* Get the integer-free subexpression in the hash table. */
subhash = SAFE_HASH (subexp, mode);
subelt = lookup (subexp, subhash, mode);
if (subelt == 0)
subelt = insert (subexp, NULL, subhash, mode);
/* Initialize SUBELT's circular chain if it has none. */
if (subelt->related_value == 0)
subelt->related_value = subelt;
/* Find the element in the circular chain that precedes SUBELT. */
subelt_prev = subelt;
while (subelt_prev->related_value != subelt)
subelt_prev = subelt_prev->related_value;
/* Put new ELT into SUBELT's circular chain just before SUBELT.
This way the element that follows SUBELT is the oldest one. */
elt->related_value = subelt_prev->related_value;
subelt_prev->related_value = elt;
}
}
return elt;
}
/* Wrap insert_with_costs by passing the default costs. */
static struct table_elt *
insert (rtx x, struct table_elt *classp, unsigned int hash,
enum machine_mode mode)
{
return
insert_with_costs (x, classp, hash, mode, COST (x), approx_reg_cost (x));
}
/* Given two equivalence classes, CLASS1 and CLASS2, put all the entries from
CLASS2 into CLASS1. This is done when we have reached an insn which makes
the two classes equivalent.
CLASS1 will be the surviving class; CLASS2 should not be used after this
call.
Any invalid entries in CLASS2 will not be copied. */
static void
merge_equiv_classes (struct table_elt *class1, struct table_elt *class2)
{
struct table_elt *elt, *next, *new_elt;
/* Ensure we start with the head of the classes. */
class1 = class1->first_same_value;
class2 = class2->first_same_value;
/* If they were already equal, forget it. */
if (class1 == class2)
return;
for (elt = class2; elt; elt = next)
{
unsigned int hash;
rtx exp = elt->exp;
enum machine_mode mode = elt->mode;
next = elt->next_same_value;
/* Remove old entry, make a new one in CLASS1's class.
Don't do this for invalid entries as we cannot find their
hash code (it also isn't necessary). */
if (REG_P (exp) || exp_equiv_p (exp, exp, 1, false))
{
bool need_rehash = false;
hash_arg_in_memory = 0;
hash = HASH (exp, mode);
if (REG_P (exp))
{
need_rehash = REGNO_QTY_VALID_P (REGNO (exp));
delete_reg_equiv (REGNO (exp));
}
if (REG_P (exp) && REGNO (exp) >= <API key>)
<API key> (exp, hash);
else
remove_from_table (elt, hash);
if (insert_regs (exp, class1, 0) || need_rehash)
{
rehash_using_reg (exp);
hash = HASH (exp, mode);
}
new_elt = insert (exp, class1, hash, mode);
new_elt->in_memory = hash_arg_in_memory;
}
}
}
/* Flush the entire hash table. */
static void
flush_hash_table (void)
{
int i;
struct table_elt *p;
for (i = 0; i < HASH_SIZE; i++)
for (p = table[i]; p; p = table[i])
{
/* Note that invalidate can remove elements
after P in the current hash chain. */
if (REG_P (p->exp))
invalidate (p->exp, VOIDmode);
else
remove_from_table (p, i);
}
}
/* Function called for each rtx to check whether true dependence exist. */
struct <API key>
{
enum machine_mode mode;
rtx exp;
rtx addr;
};
static int
check_dependence (rtx *x, void *data)
{
struct <API key> *d = (struct <API key> *) data;
if (*x && MEM_P (*x))
return <API key> (d->exp, d->mode, d->addr, *x, NULL_RTX);
else
return 0;
}
/* Remove from the hash table, or mark as invalid, all expressions whose
values could be altered by storing in X. X is a register, a subreg, or
a memory reference with nonvarying address (because, when a memory
reference with a varying address is stored in, all memory references are
removed by invalidate_memory so specific invalidation is superfluous).
FULL_MODE, if not VOIDmode, indicates that this much should be
invalidated instead of just the amount indicated by the mode of X. This
is only used for bitfield stores into memory.
A nonvarying address may be just a register or just a symbol reference,
or it may be either of those plus a numeric offset. */
static void
invalidate (rtx x, enum machine_mode full_mode)
{
int i;
struct table_elt *p;
rtx addr;
switch (GET_CODE (x))
{
case REG:
{
/* If X is a register, dependencies on its contents are recorded
through the qty number mechanism. Just change the qty number of
the register, mark it as invalid for expressions that refer to it,
and remove it itself. */
unsigned int regno = REGNO (x);
unsigned int hash = HASH (x, GET_MODE (x));
/* Remove REGNO from any quantity list it might be on and indicate
that its value might have changed. If it is a pseudo, remove its
entry from the hash table.
For a hard register, we do the first two actions above for any
additional hard registers corresponding to X. Then, if any of these
registers are in the table, we must remove any REG entries that
overlap these registers. */
delete_reg_equiv (regno);
REG_TICK (regno)++;
SUBREG_TICKED (regno) = -1;
if (regno >= <API key>)
<API key> (x, hash);
else
{
HOST_WIDE_INT in_table
= TEST_HARD_REG_BIT (hard_regs_in_table, regno);
unsigned int endregno = END_HARD_REGNO (x);
unsigned int tregno, tendregno, rn;
struct table_elt *p, *next;
CLEAR_HARD_REG_BIT (hard_regs_in_table, regno);
for (rn = regno + 1; rn < endregno; rn++)
{
in_table |= TEST_HARD_REG_BIT (hard_regs_in_table, rn);
CLEAR_HARD_REG_BIT (hard_regs_in_table, rn);
delete_reg_equiv (rn);
REG_TICK (rn)++;
SUBREG_TICKED (rn) = -1;
}
if (in_table)
for (hash = 0; hash < HASH_SIZE; hash++)
for (p = table[hash]; p; p = next)
{
next = p->next_same_hash;
if (!REG_P (p->exp)
|| REGNO (p->exp) >= <API key>)
continue;
tregno = REGNO (p->exp);
tendregno = END_HARD_REGNO (p->exp);
if (tendregno > regno && tregno < endregno)
remove_from_table (p, hash);
}
}
}
return;
case SUBREG:
invalidate (SUBREG_REG (x), VOIDmode);
return;
case PARALLEL:
for (i = XVECLEN (x, 0) - 1; i >= 0; --i)
invalidate (XVECEXP (x, 0, i), VOIDmode);
return;
case EXPR_LIST:
/* This is part of a disjoint return value; extract the location in
question ignoring the offset. */
invalidate (XEXP (x, 0), VOIDmode);
return;
case MEM:
addr = canon_rtx (get_addr (XEXP (x, 0)));
/* Calculate the canonical version of X here so that
true_dependence doesn't generate new RTL for X on each call. */
x = canon_rtx (x);
/* Remove all hash table elements that refer to overlapping pieces of
memory. */
if (full_mode == VOIDmode)
full_mode = GET_MODE (x);
for (i = 0; i < HASH_SIZE; i++)
{
struct table_elt *next;
for (p = table[i]; p; p = next)
{
next = p->next_same_hash;
if (p->in_memory)
{
struct <API key> d;
/* Just canonicalize the expression once;
otherwise each time we call invalidate
true_dependence will canonicalize the
expression again. */
if (!p->canon_exp)
p->canon_exp = canon_rtx (p->exp);
d.exp = x;
d.addr = addr;
d.mode = full_mode;
if (for_each_rtx (&p->canon_exp, check_dependence, &d))
remove_from_table (p, i);
}
}
}
return;
default:
gcc_unreachable ();
}
}
/* Remove all expressions that refer to register REGNO,
since they are already invalid, and we are about to
mark that register valid again and don't want the old
expressions to reappear as valid. */
static void
remove_invalid_refs (unsigned int regno)
{
unsigned int i;
struct table_elt *p, *next;
for (i = 0; i < HASH_SIZE; i++)
for (p = table[i]; p; p = next)
{
next = p->next_same_hash;
if (!REG_P (p->exp)
&& refers_to_regno_p (regno, regno + 1, p->exp, (rtx *) 0))
remove_from_table (p, i);
}
}
/* Likewise for a subreg with subreg_reg REGNO, subreg_byte OFFSET,
and mode MODE. */
static void
<API key> (unsigned int regno, unsigned int offset,
enum machine_mode mode)
{
unsigned int i;
struct table_elt *p, *next;
unsigned int end = offset + (GET_MODE_SIZE (mode) - 1);
for (i = 0; i < HASH_SIZE; i++)
for (p = table[i]; p; p = next)
{
rtx exp = p->exp;
next = p->next_same_hash;
if (!REG_P (exp)
&& (GET_CODE (exp) != SUBREG
|| !REG_P (SUBREG_REG (exp))
|| REGNO (SUBREG_REG (exp)) != regno
|| (((SUBREG_BYTE (exp)
+ (GET_MODE_SIZE (GET_MODE (exp)) - 1)) >= offset)
&& SUBREG_BYTE (exp) <= end))
&& refers_to_regno_p (regno, regno + 1, p->exp, (rtx *) 0))
remove_from_table (p, i);
}
}
/* Recompute the hash codes of any valid entries in the hash table that
reference X, if X is a register, or SUBREG_REG (X) if X is a SUBREG.
This is called when we make a jump equivalence. */
static void
rehash_using_reg (rtx x)
{
unsigned int i;
struct table_elt *p, *next;
unsigned hash;
if (GET_CODE (x) == SUBREG)
x = SUBREG_REG (x);
/* If X is not a register or if the register is known not to be in any
valid entries in the table, we have no work to do. */
if (!REG_P (x)
|| REG_IN_TABLE (REGNO (x)) < 0
|| REG_IN_TABLE (REGNO (x)) != REG_TICK (REGNO (x)))
return;
/* Scan all hash chains looking for valid entries that mention X.
If we find one and it is in the wrong hash chain, move it. */
for (i = 0; i < HASH_SIZE; i++)
for (p = table[i]; p; p = next)
{
next = p->next_same_hash;
if (reg_mentioned_p (x, p->exp)
&& exp_equiv_p (p->exp, p->exp, 1, false)
&& i != (hash = SAFE_HASH (p->exp, p->mode)))
{
if (p->next_same_hash)
p->next_same_hash->prev_same_hash = p->prev_same_hash;
if (p->prev_same_hash)
p->prev_same_hash->next_same_hash = p->next_same_hash;
else
table[i] = p->next_same_hash;
p->next_same_hash = table[hash];
p->prev_same_hash = 0;
if (table[hash])
table[hash]->prev_same_hash = p;
table[hash] = p;
}
}
}
/* Remove from the hash table any expression that is a call-clobbered
register. Also update their TICK values. */
static void
invalidate_for_call (void)
{
unsigned int regno, endregno;
unsigned int i;
unsigned hash;
struct table_elt *p, *next;
int in_table = 0;
/* Go through all the hard registers. For each that is clobbered in
a CALL_INSN, remove the register from quantity chains and update
reg_tick if defined. Also see if any of these registers is currently
in the table. */
for (regno = 0; regno < <API key>; regno++)
if (TEST_HARD_REG_BIT (<API key>, regno))
{
delete_reg_equiv (regno);
if (REG_TICK (regno) >= 0)
{
REG_TICK (regno)++;
SUBREG_TICKED (regno) = -1;
}
in_table |= (TEST_HARD_REG_BIT (hard_regs_in_table, regno) != 0);
}
/* In the case where we have no call-clobbered hard registers in the
table, we are done. Otherwise, scan the table and remove any
entry that overlaps a call-clobbered register. */
if (in_table)
for (hash = 0; hash < HASH_SIZE; hash++)
for (p = table[hash]; p; p = next)
{
next = p->next_same_hash;
if (!REG_P (p->exp)
|| REGNO (p->exp) >= <API key>)
continue;
regno = REGNO (p->exp);
endregno = END_HARD_REGNO (p->exp);
for (i = regno; i < endregno; i++)
if (TEST_HARD_REG_BIT (<API key>, i))
{
remove_from_table (p, hash);
break;
}
}
}
/* Given an expression X of type CONST,
and ELT which is its table entry (or 0 if it
is not in the hash table),
return an alternate expression for X as a register plus integer.
If none can be found, return 0. */
static rtx
use_related_value (rtx x, struct table_elt *elt)
{
struct table_elt *relt = 0;
struct table_elt *p, *q;
HOST_WIDE_INT offset;
/* First, is there anything related known?
If we have a table element, we can tell from that.
Otherwise, must look it up. */
if (elt != 0 && elt->related_value != 0)
relt = elt;
else if (elt == 0 && GET_CODE (x) == CONST)
{
rtx subexp = get_related_value (x);
if (subexp != 0)
relt = lookup (subexp,
SAFE_HASH (subexp, GET_MODE (subexp)),
GET_MODE (subexp));
}
if (relt == 0)
return 0;
/* Search all related table entries for one that has an
equivalent register. */
p = relt;
while (1)
{
/* This loop is strange in that it is executed in two different cases.
The first is when X is already in the table. Then it is searching
the RELATED_VALUE list of X's class (RELT). The second case is when
X is not in the table. Then RELT points to a class for the related
value.
Ensure that, whatever case we are in, that we ignore classes that have
the same value as X. */
if (rtx_equal_p (x, p->exp))
q = 0;
else
for (q = p->first_same_value; q; q = q->next_same_value)
if (REG_P (q->exp))
break;
if (q)
break;
p = p->related_value;
/* We went all the way around, so there is nothing to be found.
Alternatively, perhaps RELT was in the table for some other reason
and it has no related values recorded. */
if (p == relt || p == 0)
break;
}
if (q == 0)
return 0;
offset = (get_integer_term (x) - get_integer_term (p->exp));
/* Note: OFFSET may be 0 if P->xexp and X are related by commutativity. */
return plus_constant (q->exp, offset);
}
/* Hash a string. Just add its bytes up. */
static inline unsigned
hash_rtx_string (const char *ps)
{
unsigned hash = 0;
const unsigned char *p = (const unsigned char *) ps;
if (p)
while (*p)
hash += *p++;
return hash;
}
/* Same as hash_rtx, but call CB on each rtx if it is not NULL.
When the callback returns true, we continue with the new rtx. */
unsigned
hash_rtx_cb (const_rtx x, enum machine_mode mode,
int *do_not_record_p, int *<API key>,
bool have_reg_qty, <API key> cb)
{
int i, j;
unsigned hash = 0;
enum rtx_code code;
const char *fmt;
enum machine_mode newmode;
rtx newx;
/* Used to turn recursion into iteration. We can't rely on GCC's
tail-recursion elimination since we need to keep accumulating values
in HASH. */
repeat:
if (x == 0)
return hash;
/* Invoke the callback first. */
if (cb != NULL
&& ((*cb) (x, mode, &newx, &newmode)))
{
hash += hash_rtx_cb (newx, newmode, do_not_record_p,
<API key>, have_reg_qty, cb);
return hash;
}
code = GET_CODE (x);
switch (code)
{
case REG:
{
unsigned int regno = REGNO (x);
if (do_not_record_p && !reload_completed)
{
/* On some machines, we can't record any non-fixed hard register,
because extending its life will cause reload problems. We
consider ap, fp, sp, gp to be fixed for this purpose.
We also consider CCmode registers to be fixed for this purpose;
failure to do so leads to failure to simplify 0<100 type of
conditionals.
On all machines, we can't record any global registers.
Nor should we record any register that is in a small
class, as defined by <API key>. */
bool record;
if (regno >= <API key>)
record = true;
else if (x == frame_pointer_rtx
|| x == <API key>
|| x == arg_pointer_rtx
|| x == stack_pointer_rtx
|| x == <API key>)
record = true;
else if (global_regs[regno])
record = false;
else if (fixed_regs[regno])
record = true;
else if (GET_MODE_CLASS (GET_MODE (x)) == MODE_CC)
record = true;
else if (targetm.<API key> (GET_MODE (x)))
record = false;
else if (targetm.<API key> (REGNO_REG_CLASS (regno)))
record = false;
else
record = true;
if (!record)
{
*do_not_record_p = 1;
return 0;
}
}
hash += ((unsigned int) REG << 7);
hash += (have_reg_qty ? (unsigned) REG_QTY (regno) : regno);
return hash;
}
/* We handle SUBREG of a REG specially because the underlying
reg changes its hash value with every value change; we don't
want to have to forget unrelated subregs when one subreg changes. */
case SUBREG:
{
if (REG_P (SUBREG_REG (x)))
{
hash += (((unsigned int) SUBREG << 7)
+ REGNO (SUBREG_REG (x))
+ (SUBREG_BYTE (x) / UNITS_PER_WORD));
return hash;
}
break;
}
case CONST_INT:
hash += (((unsigned int) CONST_INT << 7) + (unsigned int) mode
+ (unsigned int) INTVAL (x));
return hash;
case CONST_DOUBLE:
/* This is like the general case, except that it only counts
the integers representing the constant. */
hash += (unsigned int) code + (unsigned int) GET_MODE (x);
if (GET_MODE (x) != VOIDmode)
hash += real_hash (<API key> (x));
else
hash += ((unsigned int) CONST_DOUBLE_LOW (x)
+ (unsigned int) CONST_DOUBLE_HIGH (x));
return hash;
case CONST_FIXED:
hash += (unsigned int) code + (unsigned int) GET_MODE (x);
hash += fixed_hash (CONST_FIXED_VALUE (x));
return hash;
case CONST_VECTOR:
{
int units;
rtx elt;
units = CONST_VECTOR_NUNITS (x);
for (i = 0; i < units; ++i)
{
elt = CONST_VECTOR_ELT (x, i);
hash += hash_rtx_cb (elt, GET_MODE (elt),
do_not_record_p, <API key>,
have_reg_qty, cb);
}
return hash;
}
/* Assume there is only one rtx object for any given label. */
case LABEL_REF:
/* We don't hash on the address of the CODE_LABEL to avoid bootstrap
differences and differences between each stage's debugging dumps. */
hash += (((unsigned int) LABEL_REF << 7)
+ CODE_LABEL_NUMBER (XEXP (x, 0)));
return hash;
case SYMBOL_REF:
{
/* Don't hash on the symbol's address to avoid bootstrap differences.
Different hash values may cause expressions to be recorded in
different orders and thus different registers to be used in the
final assembler. This also avoids differences in the dump files
between various stages. */
unsigned int h = 0;
const unsigned char *p = (const unsigned char *) XSTR (x, 0);
while (*p)
h += (h << 7) + *p++; /* ??? revisit */
hash += ((unsigned int) SYMBOL_REF << 7) + h;
return hash;
}
case MEM:
/* We don't record if marked volatile or if BLKmode since we don't
know the size of the move. */
if (do_not_record_p && (MEM_VOLATILE_P (x) || GET_MODE (x) == BLKmode))
{
*do_not_record_p = 1;
return 0;
}
if (<API key> && !MEM_READONLY_P (x))
*<API key> = 1;
/* Now that we have already found this special case,
might as well speed it up as much as possible. */
hash += (unsigned) MEM;
x = XEXP (x, 0);
goto repeat;
case USE:
/* A USE that mentions non-volatile memory needs special
handling since the MEM may be BLKmode which normally
prevents an entry from being made. Pure calls are
marked by a USE which mentions BLKmode memory.
See calls.c:emit_call_1. */
if (MEM_P (XEXP (x, 0))
&& ! MEM_VOLATILE_P (XEXP (x, 0)))
{
hash += (unsigned) USE;
x = XEXP (x, 0);
if (<API key> && !MEM_READONLY_P (x))
*<API key> = 1;
/* Now that we have already found this special case,
might as well speed it up as much as possible. */
hash += (unsigned) MEM;
x = XEXP (x, 0);
goto repeat;
}
break;
case PRE_DEC:
case PRE_INC:
case POST_DEC:
case POST_INC:
case PRE_MODIFY:
case POST_MODIFY:
case PC:
case CC0:
case CALL:
case UNSPEC_VOLATILE:
if (do_not_record_p) {
*do_not_record_p = 1;
return 0;
}
else
return hash;
break;
case ASM_OPERANDS:
if (do_not_record_p && MEM_VOLATILE_P (x))
{
*do_not_record_p = 1;
return 0;
}
else
{
/* We don't want to take the filename and line into account. */
hash += (unsigned) code + (unsigned) GET_MODE (x)
+ hash_rtx_string (<API key> (x))
+ hash_rtx_string (<API key> (x))
+ (unsigned) <API key> (x);
if (<API key> (x))
{
for (i = 1; i < <API key> (x); i++)
{
hash += (hash_rtx_cb (ASM_OPERANDS_INPUT (x, i),
GET_MODE (ASM_OPERANDS_INPUT (x, i)),
do_not_record_p, <API key>,
have_reg_qty, cb)
+ hash_rtx_string
(<API key> (x, i)));
}
hash += hash_rtx_string (<API key> (x, 0));
x = ASM_OPERANDS_INPUT (x, 0);
mode = GET_MODE (x);
goto repeat;
}
return hash;
}
break;
default:
break;
}
i = GET_RTX_LENGTH (code) - 1;
hash += (unsigned) code + (unsigned) GET_MODE (x);
fmt = GET_RTX_FORMAT (code);
for (; i >= 0; i
{
switch (fmt[i])
{
case 'e':
/* If we are about to do the last recursive call
needed at this level, change it into iteration.
This function is called enough to be worth it. */
if (i == 0)
{
x = XEXP (x, i);
goto repeat;
}
hash += hash_rtx_cb (XEXP (x, i), VOIDmode, do_not_record_p,
<API key>,
have_reg_qty, cb);
break;
case 'E':
for (j = 0; j < XVECLEN (x, i); j++)
hash += hash_rtx_cb (XVECEXP (x, i, j), VOIDmode, do_not_record_p,
<API key>,
have_reg_qty, cb);
break;
case 's':
hash += hash_rtx_string (XSTR (x, i));
break;
case 'i':
hash += (unsigned int) XINT (x, i);
break;
case '0': case 't':
/* Unused. */
break;
default:
gcc_unreachable ();
}
}
return hash;
}
/* Hash an rtx. We are careful to make sure the value is never negative.
Equivalent registers hash identically.
MODE is used in hashing for CONST_INTs only;
otherwise the mode of X is used.
Store 1 in DO_NOT_RECORD_P if any subexpression is volatile.
If <API key> is not NULL, store 1 in it if X contains
a MEM rtx which does not have the RTX_UNCHANGING_P bit set.
Note that cse_insn knows that the hash code of a MEM expression
is just (int) MEM plus the hash code of the address. */
unsigned
hash_rtx (const_rtx x, enum machine_mode mode, int *do_not_record_p,
int *<API key>, bool have_reg_qty)
{
return hash_rtx_cb (x, mode, do_not_record_p,
<API key>, have_reg_qty, NULL);
}
/* Hash an rtx X for cse via hash_rtx.
Stores 1 in do_not_record if any subexpression is volatile.
Stores 1 in hash_arg_in_memory if X contains a mem rtx which
does not have the RTX_UNCHANGING_P bit set. */
static inline unsigned
canon_hash (rtx x, enum machine_mode mode)
{
return hash_rtx (x, mode, &do_not_record, &hash_arg_in_memory, true);
}
/* Like canon_hash but with no side effects, i.e. do_not_record
and hash_arg_in_memory are not changed. */
static inline unsigned
safe_hash (rtx x, enum machine_mode mode)
{
int dummy_do_not_record;
return hash_rtx (x, mode, &dummy_do_not_record, NULL, true);
}
/* Return 1 iff X and Y would canonicalize into the same thing,
without actually constructing the canonicalization of either one.
If VALIDATE is nonzero,
we assume X is an expression being processed from the rtl
and Y was found in the hash table. We check register refs
in Y for being marked as valid.
If FOR_GCSE is true, we compare X and Y for equivalence for GCSE. */
int
exp_equiv_p (const_rtx x, const_rtx y, int validate, bool for_gcse)
{
int i, j;
enum rtx_code code;
const char *fmt;
/* Note: it is incorrect to assume an expression is equivalent to itself
if VALIDATE is nonzero. */
if (x == y && !validate)
return 1;
if (x == 0 || y == 0)
return x == y;
code = GET_CODE (x);
if (code != GET_CODE (y))
return 0;
/* (MULT:SI x y) and (MULT:HI x y) are NOT equivalent. */
if (GET_MODE (x) != GET_MODE (y))
return 0;
/* MEMs referring to different address space are not equivalent. */
if (code == MEM && MEM_ADDR_SPACE (x) != MEM_ADDR_SPACE (y))
return 0;
switch (code)
{
case PC:
case CC0:
case CONST_INT:
case CONST_DOUBLE:
case CONST_FIXED:
return x == y;
case LABEL_REF:
return XEXP (x, 0) == XEXP (y, 0);
case SYMBOL_REF:
return XSTR (x, 0) == XSTR (y, 0);
case REG:
if (for_gcse)
return REGNO (x) == REGNO (y);
else
{
unsigned int regno = REGNO (y);
unsigned int i;
unsigned int endregno = END_REGNO (y);
/* If the quantities are not the same, the expressions are not
equivalent. If there are and we are not to validate, they
are equivalent. Otherwise, ensure all regs are up-to-date. */
if (REG_QTY (REGNO (x)) != REG_QTY (regno))
return 0;
if (! validate)
return 1;
for (i = regno; i < endregno; i++)
if (REG_IN_TABLE (i) != REG_TICK (i))
return 0;
return 1;
}
case MEM:
if (for_gcse)
{
/* A volatile mem should not be considered equivalent to any
other. */
if (MEM_VOLATILE_P (x) || MEM_VOLATILE_P (y))
return 0;
/* Can't merge two expressions in different alias sets, since we
can decide that the expression is transparent in a block when
it isn't, due to it being set with the different alias set.
Also, can't merge two expressions with different MEM_ATTRS.
They could e.g. be two different entities allocated into the
same space on the stack (see e.g. PR25130). In that case, the
MEM addresses can be the same, even though the two MEMs are
absolutely not equivalent.
But because really all MEM attributes should be the same for
equivalent MEMs, we just use the invariant that MEMs that have
the same attributes share the same mem_attrs data structure. */
if (MEM_ATTRS (x) != MEM_ATTRS (y))
return 0;
}
break;
/* For commutative operations, check both orders. */
case PLUS:
case MULT:
case AND:
case IOR:
case XOR:
case NE:
case EQ:
return ((exp_equiv_p (XEXP (x, 0), XEXP (y, 0),
validate, for_gcse)
&& exp_equiv_p (XEXP (x, 1), XEXP (y, 1),
validate, for_gcse))
|| (exp_equiv_p (XEXP (x, 0), XEXP (y, 1),
validate, for_gcse)
&& exp_equiv_p (XEXP (x, 1), XEXP (y, 0),
validate, for_gcse)));
case ASM_OPERANDS:
/* We don't use the generic code below because we want to
disregard filename and line numbers. */
/* A volatile asm isn't equivalent to any other. */
if (MEM_VOLATILE_P (x) || MEM_VOLATILE_P (y))
return 0;
if (GET_MODE (x) != GET_MODE (y)
|| strcmp (<API key> (x), <API key> (y))
|| strcmp (<API key> (x),
<API key> (y))
|| <API key> (x) != <API key> (y)
|| <API key> (x) != <API key> (y))
return 0;
if (<API key> (x))
{
for (i = <API key> (x) - 1; i >= 0; i
if (! exp_equiv_p (ASM_OPERANDS_INPUT (x, i),
ASM_OPERANDS_INPUT (y, i),
validate, for_gcse)
|| strcmp (<API key> (x, i),
<API key> (y, i)))
return 0;
}
return 1;
default:
break;
}
/* Compare the elements. If any pair of corresponding elements
fail to match, return 0 for the whole thing. */
fmt = GET_RTX_FORMAT (code);
for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i
{
switch (fmt[i])
{
case 'e':
if (! exp_equiv_p (XEXP (x, i), XEXP (y, i),
validate, for_gcse))
return 0;
break;
case 'E':
if (XVECLEN (x, i) != XVECLEN (y, i))
return 0;
for (j = 0; j < XVECLEN (x, i); j++)
if (! exp_equiv_p (XVECEXP (x, i, j), XVECEXP (y, i, j),
validate, for_gcse))
return 0;
break;
case 's':
if (strcmp (XSTR (x, i), XSTR (y, i)))
return 0;
break;
case 'i':
if (XINT (x, i) != XINT (y, i))
return 0;
break;
case 'w':
if (XWINT (x, i) != XWINT (y, i))
return 0;
break;
case '0':
case 't':
break;
default:
gcc_unreachable ();
}
}
return 1;
}
/* Subroutine of canon_reg. Pass *XLOC through canon_reg, and validate
the result if necessary. INSN is as for canon_reg. */
static void
validate_canon_reg (rtx *xloc, rtx insn)
{
if (*xloc)
{
rtx new_rtx = canon_reg (*xloc, insn);
/* If replacing pseudo with hard reg or vice versa, ensure the
insn remains valid. Likewise if the insn has MATCH_DUPs. */
gcc_assert (insn && new_rtx);
validate_change (insn, xloc, new_rtx, 1);
}
}
/* Canonicalize an expression:
replace each register reference inside it
with the "oldest" equivalent register.
If INSN is nonzero validate_change is used to ensure that INSN remains valid
after we make our substitution. The calls are made with IN_GROUP nonzero
so apply_change_group must be called upon the outermost return from this
function (unless INSN is zero). The result of apply_change_group can
generally be discarded since the changes we are making are optional. */
static rtx
canon_reg (rtx x, rtx insn)
{
int i;
enum rtx_code code;
const char *fmt;
if (x == 0)
return x;
code = GET_CODE (x);
switch (code)
{
case PC:
case CC0:
case CONST:
case CONST_INT:
case CONST_DOUBLE:
case CONST_FIXED:
case CONST_VECTOR:
case SYMBOL_REF:
case LABEL_REF:
case ADDR_VEC:
case ADDR_DIFF_VEC:
return x;
case REG:
{
int first;
int q;
struct qty_table_elem *ent;
/* Never replace a hard reg, because hard regs can appear
in more than one machine mode, and we must preserve the mode
of each occurrence. Also, some hard regs appear in
MEMs that are shared and mustn't be altered. Don't try to
replace any reg that maps to a reg of class NO_REGS. */
if (REGNO (x) < <API key>
|| ! REGNO_QTY_VALID_P (REGNO (x)))
return x;
q = REG_QTY (REGNO (x));
ent = &qty_table[q];
first = ent->first_reg;
return (first >= <API key> ? regno_reg_rtx[first]
: REGNO_REG_CLASS (first) == NO_REGS ? x
: gen_rtx_REG (ent->mode, first));
}
default:
break;
}
fmt = GET_RTX_FORMAT (code);
for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i
{
int j;
if (fmt[i] == 'e')
validate_canon_reg (&XEXP (x, i), insn);
else if (fmt[i] == 'E')
for (j = 0; j < XVECLEN (x, i); j++)
validate_canon_reg (&XVECEXP (x, i, j), insn);
}
return x;
}
/* Given an operation (CODE, *PARG1, *PARG2), where code is a comparison
operation (EQ, NE, GT, etc.), follow it back through the hash table and
what values are being compared.
*PARG1 and *PARG2 are updated to contain the rtx representing the values
actually being compared. For example, if *PARG1 was (cc0) and *PARG2
was (const_int 0), *PARG1 and *PARG2 will be set to the objects that were
compared to produce cc0.
The return value is the comparison operator and is either the code of
A or the code corresponding to the inverse of the comparison. */
static enum rtx_code
<API key> (enum rtx_code code, rtx *parg1, rtx *parg2,
enum machine_mode *pmode1, enum machine_mode *pmode2)
{
rtx arg1, arg2;
arg1 = *parg1, arg2 = *parg2;
/* If ARG2 is const0_rtx, see what ARG1 is equivalent to. */
while (arg2 == CONST0_RTX (GET_MODE (arg1)))
{
/* Set nonzero when we find something of interest. */
rtx x = 0;
int reverse_code = 0;
struct table_elt *p = 0;
/* If arg1 is a COMPARE, extract the comparison arguments from it.
On machines with CC0, this is the only case that can occur, since
fold_rtx will return the COMPARE or item being compared with zero
when given CC0. */
if (GET_CODE (arg1) == COMPARE && arg2 == const0_rtx)
x = arg1;
/* If ARG1 is a comparison operator and CODE is testing for
STORE_FLAG_VALUE, get the inner arguments. */
else if (COMPARISON_P (arg1))
{
#ifdef <API key>
REAL_VALUE_TYPE fsfv;
#endif
if (code == NE
|| (GET_MODE_CLASS (GET_MODE (arg1)) == MODE_INT
&& code == LT && STORE_FLAG_VALUE == -1)
#ifdef <API key>
|| (SCALAR_FLOAT_MODE_P (GET_MODE (arg1))
&& (fsfv = <API key> (GET_MODE (arg1)),
REAL_VALUE_NEGATIVE (fsfv)))
#endif
)
x = arg1;
else if (code == EQ
|| (GET_MODE_CLASS (GET_MODE (arg1)) == MODE_INT
&& code == GE && STORE_FLAG_VALUE == -1)
#ifdef <API key>
|| (SCALAR_FLOAT_MODE_P (GET_MODE (arg1))
&& (fsfv = <API key> (GET_MODE (arg1)),
REAL_VALUE_NEGATIVE (fsfv)))
#endif
)
x = arg1, reverse_code = 1;
}
/* ??? We could also check for
(ne (and (eq (...) (const_int 1))) (const_int 0))
and related forms, but let's wait until we see them occurring. */
if (x == 0)
/* Look up ARG1 in the hash table and see if it has an equivalence
that lets us see what is being compared. */
p = lookup (arg1, SAFE_HASH (arg1, GET_MODE (arg1)), GET_MODE (arg1));
if (p)
{
p = p->first_same_value;
/* If what we compare is already known to be constant, that is as
good as it gets.
We need to break the loop in this case, because otherwise we
can have an infinite loop when looking at a reg that is known
to be a constant which is the same as a comparison of a reg
against zero which appears later in the insn stream, which in
turn is constant and the same as the comparison of the first reg
against zero... */
if (p->is_const)
break;
}
for (; p; p = p->next_same_value)
{
enum machine_mode inner_mode = GET_MODE (p->exp);
#ifdef <API key>
REAL_VALUE_TYPE fsfv;
#endif
/* If the entry isn't valid, skip it. */
if (! exp_equiv_p (p->exp, p->exp, 1, false))
continue;
/* If it's the same comparison we're already looking at, skip it. */
if (COMPARISON_P (p->exp)
&& XEXP (p->exp, 0) == arg1
&& XEXP (p->exp, 1) == arg2)
continue;
if (GET_CODE (p->exp) == COMPARE
/* Another possibility is that this machine has a compare insn
that includes the comparison code. In that case, ARG1 would
be equivalent to a comparison operation that would set ARG1 to
either STORE_FLAG_VALUE or zero. If this is an NE operation,
ORIG_CODE is the actual comparison being done; if it is an EQ,
we must reverse ORIG_CODE. On machine with a negative value
for STORE_FLAG_VALUE, also look at LT and GE operations. */
|| ((code == NE
|| (code == LT
&& <API key> (inner_mode,
STORE_FLAG_VALUE))
#ifdef <API key>
|| (code == LT
&& SCALAR_FLOAT_MODE_P (inner_mode)
&& (fsfv = <API key> (GET_MODE (arg1)),
REAL_VALUE_NEGATIVE (fsfv)))
#endif
)
&& COMPARISON_P (p->exp)))
{
x = p->exp;
break;
}
else if ((code == EQ
|| (code == GE
&& <API key> (inner_mode,
STORE_FLAG_VALUE))
#ifdef <API key>
|| (code == GE
&& SCALAR_FLOAT_MODE_P (inner_mode)
&& (fsfv = <API key> (GET_MODE (arg1)),
REAL_VALUE_NEGATIVE (fsfv)))
#endif
)
&& COMPARISON_P (p->exp))
{
reverse_code = 1;
x = p->exp;
break;
}
/* If this non-trapping address, e.g. fp + constant, the
equivalent is a better operand since it may let us predict
the value of the comparison. */
else if (!rtx_addr_can_trap_p (p->exp))
{
arg1 = p->exp;
continue;
}
}
/* If we didn't find a useful equivalence for ARG1, we are done.
Otherwise, set up for the next iteration. */
if (x == 0)
break;
/* If we need to reverse the comparison, make sure that that is
possible -- we can't necessarily infer the value of GE from LT
with floating-point operands. */
if (reverse_code)
{
enum rtx_code reversed = <API key> (x, NULL_RTX);
if (reversed == UNKNOWN)
break;
else
code = reversed;
}
else if (COMPARISON_P (x))
code = GET_CODE (x);
arg1 = XEXP (x, 0), arg2 = XEXP (x, 1);
}
/* Return our results. Return the modes from before fold_rtx
because fold_rtx might produce const_int, and then it's too late. */
*pmode1 = GET_MODE (arg1), *pmode2 = GET_MODE (arg2);
*parg1 = fold_rtx (arg1, 0), *parg2 = fold_rtx (arg2, 0);
return code;
}
/* If X is a nontrivial arithmetic operation on an argument for which
a constant value can be determined, return the result of operating
on that value, as a constant. Otherwise, return X, possibly with
one or more operands changed to a forward-propagated constant.
If X is a register whose contents are known, we do NOT return
those contents here; equiv_constant is called to perform that task.
For SUBREGs and MEMs, we do that both here and in equiv_constant.
INSN is the insn that we may be modifying. If it is 0, make a copy
of X before modifying it. */
static rtx
fold_rtx (rtx x, rtx insn)
{
enum rtx_code code;
enum machine_mode mode;
const char *fmt;
int i;
rtx new_rtx = 0;
int changed = 0;
/* Operands of X. */
rtx folded_arg0;
rtx folded_arg1;
/* Constant equivalents of first three operands of X;
0 when no such equivalent is known. */
rtx const_arg0;
rtx const_arg1;
rtx const_arg2;
/* The mode of the first operand of X. We need this for sign and zero
extends. */
enum machine_mode mode_arg0;
if (x == 0)
return x;
/* Try to perform some initial simplifications on X. */
code = GET_CODE (x);
switch (code)
{
case MEM:
case SUBREG:
if ((new_rtx = equiv_constant (x)) != NULL_RTX)
return new_rtx;
return x;
case CONST:
case CONST_INT:
case CONST_DOUBLE:
case CONST_FIXED:
case CONST_VECTOR:
case SYMBOL_REF:
case LABEL_REF:
case REG:
case PC:
/* No use simplifying an EXPR_LIST
since they are used only for lists of args
in a function call's REG_EQUAL note. */
case EXPR_LIST:
return x;
#ifdef HAVE_cc0
case CC0:
return prev_insn_cc0;
#endif
case ASM_OPERANDS:
if (insn)
{
for (i = <API key> (x) - 1; i >= 0; i
validate_change (insn, &ASM_OPERANDS_INPUT (x, i),
fold_rtx (ASM_OPERANDS_INPUT (x, i), insn), 0);
}
return x;
#ifdef NO_FUNCTION_CSE
case CALL:
if (CONSTANT_P (XEXP (XEXP (x, 0), 0)))
return x;
break;
#endif
/* Anything else goes through the loop below. */
default:
break;
}
mode = GET_MODE (x);
const_arg0 = 0;
const_arg1 = 0;
const_arg2 = 0;
mode_arg0 = VOIDmode;
/* Try folding our operands.
Then see which ones have constant values known. */
fmt = GET_RTX_FORMAT (code);
for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i
if (fmt[i] == 'e')
{
rtx folded_arg = XEXP (x, i), const_arg;
enum machine_mode mode_arg = GET_MODE (folded_arg);
switch (GET_CODE (folded_arg))
{
case MEM:
case REG:
case SUBREG:
const_arg = equiv_constant (folded_arg);
break;
case CONST:
case CONST_INT:
case SYMBOL_REF:
case LABEL_REF:
case CONST_DOUBLE:
case CONST_FIXED:
case CONST_VECTOR:
const_arg = folded_arg;
break;
#ifdef HAVE_cc0
case CC0:
folded_arg = prev_insn_cc0;
mode_arg = prev_insn_cc0_mode;
const_arg = equiv_constant (folded_arg);
break;
#endif
default:
folded_arg = fold_rtx (folded_arg, insn);
const_arg = equiv_constant (folded_arg);
break;
}
/* For the first three operands, see if the operand
is constant or equivalent to a constant. */
switch (i)
{
case 0:
folded_arg0 = folded_arg;
const_arg0 = const_arg;
mode_arg0 = mode_arg;
break;
case 1:
folded_arg1 = folded_arg;
const_arg1 = const_arg;
break;
case 2:
const_arg2 = const_arg;
break;
}
/* Pick the least expensive of the argument and an equivalent constant
argument. */
if (const_arg != 0
&& const_arg != folded_arg
&& COST_IN (const_arg, code, i) <= COST_IN (folded_arg, code, i)
/* It's not safe to substitute the operand of a conversion
operator with a constant, as the conversion's identity
depends upon the mode of its operand. This optimization
is handled by the call to <API key>. */
&& (GET_RTX_CLASS (code) != RTX_UNARY
|| GET_MODE (const_arg) == mode_arg0
|| (code != ZERO_EXTEND
&& code != SIGN_EXTEND
&& code != TRUNCATE
&& code != FLOAT_TRUNCATE
&& code != FLOAT_EXTEND
&& code != FLOAT
&& code != FIX
&& code != UNSIGNED_FLOAT
&& code != UNSIGNED_FIX)))
folded_arg = const_arg;
if (folded_arg == XEXP (x, i))
continue;
if (insn == NULL_RTX && !changed)
x = copy_rtx (x);
changed = 1;
<API key> (insn, &XEXP (x, i), folded_arg, 1);
}
if (changed)
{
/* Canonicalize X if necessary, and keep const_argN and folded_argN
consistent with the order in X. */
if (<API key> (insn, x))
{
rtx tem;
tem = const_arg0, const_arg0 = const_arg1, const_arg1 = tem;
tem = folded_arg0, folded_arg0 = folded_arg1, folded_arg1 = tem;
}
apply_change_group ();
}
/* If X is an arithmetic operation, see if we can simplify it. */
switch (GET_RTX_CLASS (code))
{
case RTX_UNARY:
{
/* We can't simplify extension ops unless we know the
original mode. */
if ((code == ZERO_EXTEND || code == SIGN_EXTEND)
&& mode_arg0 == VOIDmode)
break;
new_rtx = <API key> (code, mode,
const_arg0 ? const_arg0 : folded_arg0,
mode_arg0);
}
break;
case RTX_COMPARE:
case RTX_COMM_COMPARE:
/* See what items are actually being compared and set FOLDED_ARG[01]
to those values and CODE to the actual comparison code. If any are
constant, set CONST_ARG0 and CONST_ARG1 appropriately. We needn't
do anything if both operands are already known to be constant. */
/* ??? Vector mode comparisons are not supported yet. */
if (VECTOR_MODE_P (mode))
break;
if (const_arg0 == 0 || const_arg1 == 0)
{
struct table_elt *p0, *p1;
rtx true_rtx, false_rtx;
enum machine_mode mode_arg1;
if (SCALAR_FLOAT_MODE_P (mode))
{
#ifdef <API key>
true_rtx = (<API key>
(<API key> (mode), mode));
#else
true_rtx = NULL_RTX;
#endif
false_rtx = CONST0_RTX (mode);
}
else
{
true_rtx = const_true_rtx;
false_rtx = const0_rtx;
}
code = <API key> (code, &folded_arg0, &folded_arg1,
&mode_arg0, &mode_arg1);
/* If the mode is VOIDmode or a MODE_CC mode, we don't know
what kinds of things are being compared, so we can't do
anything with this comparison. */
if (mode_arg0 == VOIDmode || GET_MODE_CLASS (mode_arg0) == MODE_CC)
break;
const_arg0 = equiv_constant (folded_arg0);
const_arg1 = equiv_constant (folded_arg1);
/* If we do not now have two constants being compared, see
if we can nevertheless deduce some things about the
comparison. */
if (const_arg0 == 0 || const_arg1 == 0)
{
if (const_arg1 != NULL)
{
rtx <API key>;
int cheapest_cost;
rtx simp_result;
struct table_elt *p;
/* See if we can find an equivalent of folded_arg0
that gets us a cheaper expression, possibly a
constant through simplifications. */
p = lookup (folded_arg0, SAFE_HASH (folded_arg0, mode_arg0),
mode_arg0);
if (p != NULL)
{
<API key> = x;
cheapest_cost = COST (x);
for (p = p->first_same_value; p != NULL; p = p->next_same_value)
{
int cost;
/* If the entry isn't valid, skip it. */
if (! exp_equiv_p (p->exp, p->exp, 1, false))
continue;
/* Try to simplify using this equivalence. */
simp_result
= <API key> (code, mode,
mode_arg0,
p->exp,
const_arg1);
if (simp_result == NULL)
continue;
cost = COST (simp_result);
if (cost < cheapest_cost)
{
cheapest_cost = cost;
<API key> = simp_result;
}
}
/* If we have a cheaper expression now, use that
and try folding it further, from the top. */
if (<API key> != x)
return fold_rtx (copy_rtx (<API key>),
insn);
}
}
/* See if the two operands are the same. */
if ((REG_P (folded_arg0)
&& REG_P (folded_arg1)
&& (REG_QTY (REGNO (folded_arg0))
== REG_QTY (REGNO (folded_arg1))))
|| ((p0 = lookup (folded_arg0,
SAFE_HASH (folded_arg0, mode_arg0),
mode_arg0))
&& (p1 = lookup (folded_arg1,
SAFE_HASH (folded_arg1, mode_arg0),
mode_arg0))
&& p0->first_same_value == p1->first_same_value))
folded_arg1 = folded_arg0;
/* If FOLDED_ARG0 is a register, see if the comparison we are
doing now is either the same as we did before or the reverse
(we only check the reverse if not floating-point). */
else if (REG_P (folded_arg0))
{
int qty = REG_QTY (REGNO (folded_arg0));
if (REGNO_QTY_VALID_P (REGNO (folded_arg0)))
{
struct qty_table_elem *ent = &qty_table[qty];
if ((<API key> (ent->comparison_code, code)
|| (! FLOAT_MODE_P (mode_arg0)
&& <API key> (ent->comparison_code,
reverse_condition (code))))
&& (rtx_equal_p (ent->comparison_const, folded_arg1)
|| (const_arg1
&& rtx_equal_p (ent->comparison_const,
const_arg1))
|| (REG_P (folded_arg1)
&& (REG_QTY (REGNO (folded_arg1)) == ent->comparison_qty))))
{
if (<API key> (ent->comparison_code, code))
{
if (true_rtx)
return true_rtx;
else
break;
}
else
return false_rtx;
}
}
}
}
}
/* If we are comparing against zero, see if the first operand is
equivalent to an IOR with a constant. If so, we may be able to
determine the result of this comparison. */
if (const_arg1 == const0_rtx && !const_arg0)
{
rtx y = lookup_as_function (folded_arg0, IOR);
rtx inner_const;
if (y != 0
&& (inner_const = equiv_constant (XEXP (y, 1))) != 0
&& CONST_INT_P (inner_const)
&& INTVAL (inner_const) != 0)
folded_arg0 = gen_rtx_IOR (mode_arg0, XEXP (y, 0), inner_const);
}
{
rtx op0 = const_arg0 ? const_arg0 : folded_arg0;
rtx op1 = const_arg1 ? const_arg1 : folded_arg1;
new_rtx = <API key> (code, mode, mode_arg0, op0, op1);
}
break;
case RTX_BIN_ARITH:
case RTX_COMM_ARITH:
switch (code)
{
case PLUS:
/* If the second operand is a LABEL_REF, see if the first is a MINUS
with that LABEL_REF as its second operand. If so, the result is
the first operand of that MINUS. This handles switches with an
ADDR_DIFF_VEC table. */
if (const_arg1 && GET_CODE (const_arg1) == LABEL_REF)
{
rtx y
= GET_CODE (folded_arg0) == MINUS ? folded_arg0
: lookup_as_function (folded_arg0, MINUS);
if (y != 0 && GET_CODE (XEXP (y, 1)) == LABEL_REF
&& XEXP (XEXP (y, 1), 0) == XEXP (const_arg1, 0))
return XEXP (y, 0);
/* Now try for a CONST of a MINUS like the above. */
if ((y = (GET_CODE (folded_arg0) == CONST ? folded_arg0
: lookup_as_function (folded_arg0, CONST))) != 0
&& GET_CODE (XEXP (y, 0)) == MINUS
&& GET_CODE (XEXP (XEXP (y, 0), 1)) == LABEL_REF
&& XEXP (XEXP (XEXP (y, 0), 1), 0) == XEXP (const_arg1, 0))
return XEXP (XEXP (y, 0), 0);
}
/* Likewise if the operands are in the other order. */
if (const_arg0 && GET_CODE (const_arg0) == LABEL_REF)
{
rtx y
= GET_CODE (folded_arg1) == MINUS ? folded_arg1
: lookup_as_function (folded_arg1, MINUS);
if (y != 0 && GET_CODE (XEXP (y, 1)) == LABEL_REF
&& XEXP (XEXP (y, 1), 0) == XEXP (const_arg0, 0))
return XEXP (y, 0);
/* Now try for a CONST of a MINUS like the above. */
if ((y = (GET_CODE (folded_arg1) == CONST ? folded_arg1
: lookup_as_function (folded_arg1, CONST))) != 0
&& GET_CODE (XEXP (y, 0)) == MINUS
&& GET_CODE (XEXP (XEXP (y, 0), 1)) == LABEL_REF
&& XEXP (XEXP (XEXP (y, 0), 1), 0) == XEXP (const_arg0, 0))
return XEXP (XEXP (y, 0), 0);
}
/* If second operand is a register equivalent to a negative
CONST_INT, see if we can find a register equivalent to the
positive constant. Make a MINUS if so. Don't do this for
a non-negative constant since we might then alternate between
choosing positive and negative constants. Having the positive
constant previously-used is the more common case. Be sure
the resulting constant is non-negative; if const_arg1 were
the smallest negative number this would overflow: depending
on the mode, this would either just be the same value (and
hence not save anything) or be incorrect. */
if (const_arg1 != 0 && CONST_INT_P (const_arg1)
&& INTVAL (const_arg1) < 0
/* This used to test
-INTVAL (const_arg1) >= 0
But The Sun V5.0 compilers mis-compiled that test. So
instead we test for the problematic value in a more direct
manner and hope the Sun compilers get it correct. */
&& INTVAL (const_arg1) !=
((HOST_WIDE_INT) 1 << (<API key> - 1))
&& REG_P (folded_arg1))
{
rtx new_const = GEN_INT (-INTVAL (const_arg1));
struct table_elt *p
= lookup (new_const, SAFE_HASH (new_const, mode), mode);
if (p)
for (p = p->first_same_value; p; p = p->next_same_value)
if (REG_P (p->exp))
return simplify_gen_binary (MINUS, mode, folded_arg0,
canon_reg (p->exp, NULL_RTX));
}
goto from_plus;
case MINUS:
/* If we have (MINUS Y C), see if Y is known to be (PLUS Z C2).
If so, produce (PLUS Z C2-C). */
if (const_arg1 != 0 && CONST_INT_P (const_arg1))
{
rtx y = lookup_as_function (XEXP (x, 0), PLUS);
if (y && CONST_INT_P (XEXP (y, 1)))
return fold_rtx (plus_constant (copy_rtx (y),
-INTVAL (const_arg1)),
NULL_RTX);
}
/* Fall through. */
from_plus:
case SMIN: case SMAX: case UMIN: case UMAX:
case IOR: case AND: case XOR:
case MULT:
case ASHIFT: case LSHIFTRT: case ASHIFTRT:
/* If we have (<op> <reg> <const_int>) for an associative OP and REG
is known to be of similar form, we may be able to replace the
operation with a combined operation. This may eliminate the
intermediate operation if every use is simplified in this way.
Note that the similar optimization done by combine.c only works
if the intermediate operation's result has only one reference. */
if (REG_P (folded_arg0)
&& const_arg1 && CONST_INT_P (const_arg1))
{
int is_shift
= (code == ASHIFT || code == ASHIFTRT || code == LSHIFTRT);
rtx y, inner_const, new_const;
rtx canon_const_arg1 = const_arg1;
enum rtx_code associate_code;
if (is_shift
&& (INTVAL (const_arg1) >= GET_MODE_PRECISION (mode)
|| INTVAL (const_arg1) < 0))
{
if (<API key>)
canon_const_arg1 = GEN_INT (INTVAL (const_arg1)
& (GET_MODE_BITSIZE (mode)
- 1));
else
break;
}
y = lookup_as_function (folded_arg0, code);
if (y == 0)
break;
/* If we have compiled a statement like
"if (x == (x & mask1))", and now are looking at
"x & mask2", we will have a case where the first operand
of Y is the same as our first operand. Unless we detect
this case, an infinite loop will result. */
if (XEXP (y, 0) == folded_arg0)
break;
inner_const = equiv_constant (fold_rtx (XEXP (y, 1), 0));
if (!inner_const || !CONST_INT_P (inner_const))
break;
/* Don't associate these operations if they are a PLUS with the
same constant and it is a power of two. These might be doable
with a pre- or post-increment. Similarly for two subtracts of
identical powers of two with post decrement. */
if (code == PLUS && const_arg1 == inner_const
&& ((HAVE_PRE_INCREMENT
&& exact_log2 (INTVAL (const_arg1)) >= 0)
|| (HAVE_POST_INCREMENT
&& exact_log2 (INTVAL (const_arg1)) >= 0)
|| (HAVE_PRE_DECREMENT
&& exact_log2 (- INTVAL (const_arg1)) >= 0)
|| (HAVE_POST_DECREMENT
&& exact_log2 (- INTVAL (const_arg1)) >= 0)))
break;
/* ??? Vector mode shifts by scalar
shift operand are not supported yet. */
if (is_shift && VECTOR_MODE_P (mode))
break;
if (is_shift
&& (INTVAL (inner_const) >= GET_MODE_PRECISION (mode)
|| INTVAL (inner_const) < 0))
{
if (<API key>)
inner_const = GEN_INT (INTVAL (inner_const)
& (GET_MODE_BITSIZE (mode) - 1));
else
break;
}
/* Compute the code used to compose the constants. For example,
A-C1-C2 is A-(C1 + C2), so if CODE == MINUS, we want PLUS. */
associate_code = (is_shift || code == MINUS ? PLUS : code);
new_const = <API key> (associate_code, mode,
canon_const_arg1,
inner_const);
if (new_const == 0)
break;
/* If we are associating shift operations, don't let this
produce a shift of the size of the object or larger.
This could occur when we follow a sign-extend by a right
shift on a machine that does a sign-extend as a pair
of shifts. */
if (is_shift
&& CONST_INT_P (new_const)
&& INTVAL (new_const) >= GET_MODE_PRECISION (mode))
{
/* As an exception, we can turn an ASHIFTRT of this
form into a shift of the number of bits - 1. */
if (code == ASHIFTRT)
new_const = GEN_INT (GET_MODE_BITSIZE (mode) - 1);
else if (!side_effects_p (XEXP (y, 0)))
return CONST0_RTX (mode);
else
break;
}
y = copy_rtx (XEXP (y, 0));
/* If Y contains our first operand (the most common way this
can happen is if Y is a MEM), we would do into an infinite
loop if we tried to fold it. So don't in that case. */
if (! reg_mentioned_p (folded_arg0, y))
y = fold_rtx (y, insn);
return simplify_gen_binary (code, mode, y, new_const);
}
break;
case DIV: case UDIV:
/* ??? The associative optimization performed immediately above is
also possible for DIV and UDIV using associate_code of MULT.
However, we would need extra code to verify that the
multiplication does not overflow, that is, there is no overflow
in the calculation of new_const. */
break;
default:
break;
}
new_rtx = <API key> (code, mode,
const_arg0 ? const_arg0 : folded_arg0,
const_arg1 ? const_arg1 : folded_arg1);
break;
case RTX_OBJ:
/* (lo_sum (high X) X) is simply X. */
if (code == LO_SUM && const_arg0 != 0
&& GET_CODE (const_arg0) == HIGH
&& rtx_equal_p (XEXP (const_arg0, 0), const_arg1))
return const_arg1;
break;
case RTX_TERNARY:
case RTX_BITFIELD_OPS:
new_rtx = <API key> (code, mode, mode_arg0,
const_arg0 ? const_arg0 : folded_arg0,
const_arg1 ? const_arg1 : folded_arg1,
const_arg2 ? const_arg2 : XEXP (x, 2));
break;
default:
break;
}
return new_rtx ? new_rtx : x;
}
/* Return a constant value currently equivalent to X.
Return 0 if we don't know one. */
static rtx
equiv_constant (rtx x)
{
if (REG_P (x)
&& REGNO_QTY_VALID_P (REGNO (x)))
{
int x_q = REG_QTY (REGNO (x));
struct qty_table_elem *x_ent = &qty_table[x_q];
if (x_ent->const_rtx)
x = gen_lowpart (GET_MODE (x), x_ent->const_rtx);
}
if (x == 0 || CONSTANT_P (x))
return x;
if (GET_CODE (x) == SUBREG)
{
enum machine_mode mode = GET_MODE (x);
enum machine_mode imode = GET_MODE (SUBREG_REG (x));
rtx new_rtx;
/* See if we previously assigned a constant value to this SUBREG. */
if ((new_rtx = lookup_as_function (x, CONST_INT)) != 0
|| (new_rtx = lookup_as_function (x, CONST_DOUBLE)) != 0
|| (new_rtx = lookup_as_function (x, CONST_FIXED)) != 0)
return new_rtx;
/* If we didn't and if doing so makes sense, see if we previously
assigned a constant value to the enclosing word mode SUBREG. */
if (GET_MODE_SIZE (mode) < GET_MODE_SIZE (word_mode)
&& GET_MODE_SIZE (word_mode) < GET_MODE_SIZE (imode))
{
int byte = SUBREG_BYTE (x) - <API key> (mode, word_mode);
if (byte >= 0 && (byte % UNITS_PER_WORD) == 0)
{
rtx y = gen_rtx_SUBREG (word_mode, SUBREG_REG (x), byte);
new_rtx = lookup_as_function (y, CONST_INT);
if (new_rtx)
return gen_lowpart (mode, new_rtx);
}
}
/* Otherwise see if we already have a constant for the inner REG. */
if (REG_P (SUBREG_REG (x))
&& (new_rtx = equiv_constant (SUBREG_REG (x))) != 0)
return simplify_subreg (mode, new_rtx, imode, SUBREG_BYTE (x));
return 0;
}
/* If X is a MEM, see if it is a constant-pool reference, or look it up in
the hash table in case its value was seen before. */
if (MEM_P (x))
{
struct table_elt *elt;
x = <API key> (x);
if (CONSTANT_P (x))
return x;
elt = lookup (x, SAFE_HASH (x, GET_MODE (x)), GET_MODE (x));
if (elt == 0)
return 0;
for (elt = elt->first_same_value; elt; elt = elt->next_same_value)
if (elt->is_const && CONSTANT_P (elt->exp))
return elt->exp;
}
return 0;
}
/* Given INSN, a jump insn, TAKEN indicates if we are following the
"taken" branch.
In certain cases, this can cause us to add an equivalence. For example,
if we are following the taken case of
if (i == 2)
we can add the fact that `i' and '2' are now equivalent.
In any case, we can record that this comparison was passed. If the same
comparison is seen later, we will know its value. */
static void
record_jump_equiv (rtx insn, bool taken)
{
int cond_known_true;
rtx op0, op1;
rtx set;
enum machine_mode mode, mode0, mode1;
int <API key> = 0;
enum rtx_code code;
/* Ensure this is the right kind of insn. */
gcc_assert (any_condjump_p (insn));
set = pc_set (insn);
/* See if this jump condition is known true or false. */
if (taken)
cond_known_true = (XEXP (SET_SRC (set), 2) == pc_rtx);
else
cond_known_true = (XEXP (SET_SRC (set), 1) == pc_rtx);
/* Get the type of comparison being done and the operands being compared.
If we had to reverse a non-equality condition, record that fact so we
know that it isn't valid for floating-point. */
code = GET_CODE (XEXP (SET_SRC (set), 0));
op0 = fold_rtx (XEXP (XEXP (SET_SRC (set), 0), 0), insn);
op1 = fold_rtx (XEXP (XEXP (SET_SRC (set), 0), 1), insn);
code = <API key> (code, &op0, &op1, &mode0, &mode1);
if (! cond_known_true)
{
code = <API key> (code, op0, op1, insn);
/* Don't remember if we can't find the inverse. */
if (code == UNKNOWN)
return;
}
/* The mode is the mode of the non-constant. */
mode = mode0;
if (mode1 != VOIDmode)
mode = mode1;
record_jump_cond (code, mode, op0, op1, <API key>);
}
/* Yet another form of subreg creation. In this case, we want something in
MODE, and we should assume OP has MODE iff it is naturally modeless. */
static rtx
<API key> (enum machine_mode mode, rtx op)
{
enum machine_mode op_mode = GET_MODE (op);
if (op_mode == mode || op_mode == VOIDmode)
return op;
return lowpart_subreg (mode, op, op_mode);
}
/* We know that comparison CODE applied to OP0 and OP1 in MODE is true.
<API key> is nonzero if CODE had to be swapped.
Make any useful entries we can with that information. Called from
above function and called recursively. */
static void
record_jump_cond (enum rtx_code code, enum machine_mode mode, rtx op0,
rtx op1, int <API key>)
{
unsigned op0_hash, op1_hash;
int op0_in_memory, op1_in_memory;
struct table_elt *op0_elt, *op1_elt;
/* If OP0 and OP1 are known equal, and either is a paradoxical SUBREG,
we know that they are also equal in the smaller mode (this is also
true for all smaller modes whether or not there is a SUBREG, but
is not worth testing for with no SUBREG). */
/* Note that GET_MODE (op0) may not equal MODE. */
if (code == EQ && <API key> (op0))
{
enum machine_mode inner_mode = GET_MODE (SUBREG_REG (op0));
rtx tem = <API key> (inner_mode, op1);
if (tem)
record_jump_cond (code, mode, SUBREG_REG (op0), tem,
<API key>);
}
if (code == EQ && <API key> (op1))
{
enum machine_mode inner_mode = GET_MODE (SUBREG_REG (op1));
rtx tem = <API key> (inner_mode, op0);
if (tem)
record_jump_cond (code, mode, SUBREG_REG (op1), tem,
<API key>);
}
/* Similarly, if this is an NE comparison, and either is a SUBREG
making a smaller mode, we know the whole thing is also NE. */
/* Note that GET_MODE (op0) may not equal MODE;
if we test MODE instead, we can get an infinite recursion
alternating between two modes each wider than MODE. */
if (code == NE && GET_CODE (op0) == SUBREG
&& subreg_lowpart_p (op0)
&& (GET_MODE_SIZE (GET_MODE (op0))
< GET_MODE_SIZE (GET_MODE (SUBREG_REG (op0)))))
{
enum machine_mode inner_mode = GET_MODE (SUBREG_REG (op0));
rtx tem = <API key> (inner_mode, op1);
if (tem)
record_jump_cond (code, mode, SUBREG_REG (op0), tem,
<API key>);
}
if (code == NE && GET_CODE (op1) == SUBREG
&& subreg_lowpart_p (op1)
&& (GET_MODE_SIZE (GET_MODE (op1))
< GET_MODE_SIZE (GET_MODE (SUBREG_REG (op1)))))
{
enum machine_mode inner_mode = GET_MODE (SUBREG_REG (op1));
rtx tem = <API key> (inner_mode, op0);
if (tem)
record_jump_cond (code, mode, SUBREG_REG (op1), tem,
<API key>);
}
/* Hash both operands. */
do_not_record = 0;
hash_arg_in_memory = 0;
op0_hash = HASH (op0, mode);
op0_in_memory = hash_arg_in_memory;
if (do_not_record)
return;
do_not_record = 0;
hash_arg_in_memory = 0;
op1_hash = HASH (op1, mode);
op1_in_memory = hash_arg_in_memory;
if (do_not_record)
return;
/* Look up both operands. */
op0_elt = lookup (op0, op0_hash, mode);
op1_elt = lookup (op1, op1_hash, mode);
/* If both operands are already equivalent or if they are not in the
table but are identical, do nothing. */
if ((op0_elt != 0 && op1_elt != 0
&& op0_elt->first_same_value == op1_elt->first_same_value)
|| op0 == op1 || rtx_equal_p (op0, op1))
return;
/* If we aren't setting two things equal all we can do is save this
comparison. Similarly if this is floating-point. In the latter
case, OP1 might be zero and both -0.0 and 0.0 are equal to it.
If we record the equality, we might inadvertently delete code
whose intent was to change -0 to +0. */
if (code != EQ || FLOAT_MODE_P (GET_MODE (op0)))
{
struct qty_table_elem *ent;
int qty;
/* If we reversed a floating-point comparison, if OP0 is not a
register, or if OP1 is neither a register or constant, we can't
do anything. */
if (!REG_P (op1))
op1 = equiv_constant (op1);
if ((<API key> && FLOAT_MODE_P (mode))
|| !REG_P (op0) || op1 == 0)
return;
/* Put OP0 in the hash table if it isn't already. This gives it a
new quantity number. */
if (op0_elt == 0)
{
if (insert_regs (op0, NULL, 0))
{
rehash_using_reg (op0);
op0_hash = HASH (op0, mode);
/* If OP0 is contained in OP1, this changes its hash code
as well. Faster to rehash than to check, except
for the simple case of a constant. */
if (! CONSTANT_P (op1))
op1_hash = HASH (op1,mode);
}
op0_elt = insert (op0, NULL, op0_hash, mode);
op0_elt->in_memory = op0_in_memory;
}
qty = REG_QTY (REGNO (op0));
ent = &qty_table[qty];
ent->comparison_code = code;
if (REG_P (op1))
{
/* Look it up again--in case op0 and op1 are the same. */
op1_elt = lookup (op1, op1_hash, mode);
/* Put OP1 in the hash table so it gets a new quantity number. */
if (op1_elt == 0)
{
if (insert_regs (op1, NULL, 0))
{
rehash_using_reg (op1);
op1_hash = HASH (op1, mode);
}
op1_elt = insert (op1, NULL, op1_hash, mode);
op1_elt->in_memory = op1_in_memory;
}
ent->comparison_const = NULL_RTX;
ent->comparison_qty = REG_QTY (REGNO (op1));
}
else
{
ent->comparison_const = op1;
ent->comparison_qty = -1;
}
return;
}
/* If either side is still missing an equivalence, make it now,
then merge the equivalences. */
if (op0_elt == 0)
{
if (insert_regs (op0, NULL, 0))
{
rehash_using_reg (op0);
op0_hash = HASH (op0, mode);
}
op0_elt = insert (op0, NULL, op0_hash, mode);
op0_elt->in_memory = op0_in_memory;
}
if (op1_elt == 0)
{
if (insert_regs (op1, NULL, 0))
{
rehash_using_reg (op1);
op1_hash = HASH (op1, mode);
}
op1_elt = insert (op1, NULL, op1_hash, mode);
op1_elt->in_memory = op1_in_memory;
}
merge_equiv_classes (op0_elt, op1_elt);
}
/* CSE processing for one instruction.
Most "true" common subexpressions are mostly optimized away in GIMPLE,
but the few that "leak through" are cleaned up by cse_insn, and complex
addressing modes are often formed here.
The main function is cse_insn, and between here and that function
a couple of helper functions is defined to keep the size of cse_insn
within reasonable proportions.
Data is shared between the main and helper functions via STRUCT SET,
that contains all data related for every set in the instruction that
is being processed.
Note that cse_main processes all sets in the instruction. Most
passes in GCC only process simple SET insns or single_set insns, but
CSE processes insns with multiple sets as well. */
/* Data on one SET contained in the instruction. */
struct set
{
/* The SET rtx itself. */
rtx rtl;
/* The SET_SRC of the rtx (the original value, if it is changing). */
rtx src;
/* The hash-table element for the SET_SRC of the SET. */
struct table_elt *src_elt;
/* Hash value for the SET_SRC. */
unsigned src_hash;
/* Hash value for the SET_DEST. */
unsigned dest_hash;
/* The SET_DEST, with SUBREG, etc., stripped. */
rtx inner_dest;
/* Nonzero if the SET_SRC is in memory. */
char src_in_memory;
/* Nonzero if the SET_SRC contains something
whose value cannot be predicted and understood. */
char src_volatile;
/* Original machine mode, in case it becomes a CONST_INT.
The size of this field should match the size of the mode
field of struct rtx_def (see rtl.h). */
ENUM_BITFIELD(machine_mode) mode : 8;
/* A constant equivalent for SET_SRC, if any. */
rtx src_const;
/* Hash value of constant equivalent for SET_SRC. */
unsigned src_const_hash;
/* Table entry for constant equivalent for SET_SRC, if any. */
struct table_elt *src_const_elt;
/* Table entry for the destination address. */
struct table_elt *dest_addr_elt;
};
/* Special handling for (set REG0 REG1) where REG0 is the
"cheapest", cheaper than REG1. After cse, REG1 will probably not
be used in the sequel, so (if easily done) change this insn to
(set REG1 REG0) and replace REG1 with REG0 in the previous insn
that computed their value. Then REG1 will become a dead store
and won't cloud the situation for later optimizations.
Do not make this change if REG1 is a hard register, because it will
then be used in the sequel and we may be changing a two-operand insn
into a three-operand insn.
This is the last transformation that cse_insn will try to do. */
static void
<API key> (rtx set, rtx insn)
{
rtx dest = SET_DEST (set);
rtx src = SET_SRC (set);
if (REG_P (dest)
&& REG_P (src) && ! HARD_REGISTER_P (src)
&& REGNO_QTY_VALID_P (REGNO (src)))
{
int src_q = REG_QTY (REGNO (src));
struct qty_table_elem *src_ent = &qty_table[src_q];
if (src_ent->first_reg == REGNO (dest))
{
/* Scan for the previous nonnote insn, but stop at a basic
block boundary. */
rtx prev = insn;
rtx bb_head = BB_HEAD (BLOCK_FOR_INSN (insn));
do
{
prev = PREV_INSN (prev);
}
while (prev != bb_head && (NOTE_P (prev) || DEBUG_INSN_P (prev)));
/* Do not swap the registers around if the previous instruction
attaches a REG_EQUIV note to REG1.
??? It's not entirely clear whether we can transfer a REG_EQUIV
from the pseudo that originally shadowed an incoming argument
to another register. Some uses of REG_EQUIV might rely on it
being attached to REG1 rather than REG2.
This section previously turned the REG_EQUIV into a REG_EQUAL
note. We cannot do that because REG_EQUIV may provide an
uninitialized stack slot when <API key> is used. */
if (NONJUMP_INSN_P (prev)
&& GET_CODE (PATTERN (prev)) == SET
&& SET_DEST (PATTERN (prev)) == src
&& ! find_reg_note (prev, REG_EQUIV, NULL_RTX))
{
rtx note;
validate_change (prev, &SET_DEST (PATTERN (prev)), dest, 1);
validate_change (insn, &SET_DEST (set), src, 1);
validate_change (insn, &SET_SRC (set), dest, 1);
apply_change_group ();
/* If INSN has a REG_EQUAL note, and this note mentions
REG0, then we must delete it, because the value in
REG0 has changed. If the note's value is REG1, we must
also delete it because that is now this insn's dest. */
note = find_reg_note (insn, REG_EQUAL, NULL_RTX);
if (note != 0
&& (reg_mentioned_p (dest, XEXP (note, 0))
|| rtx_equal_p (src, XEXP (note, 0))))
remove_note (insn, note);
}
}
}
}
/* Record all the SETs in this instruction into SETS_PTR,
and return the number of recorded sets. */
static int
find_sets_in_insn (rtx insn, struct set **psets)
{
struct set *sets = *psets;
int n_sets = 0;
rtx x = PATTERN (insn);
if (GET_CODE (x) == SET)
{
/* Ignore SETs that are unconditional jumps.
They never need cse processing, so this does not hurt.
The reason is not efficiency but rather
so that we can test at the end for instructions
that have been simplified to unconditional jumps
and not be misled by unchanged instructions
that were unconditional jumps to begin with. */
if (SET_DEST (x) == pc_rtx
&& GET_CODE (SET_SRC (x)) == LABEL_REF)
;
/* Don't count call-insns, (set (reg 0) (call ...)), as a set.
The hard function value register is used only once, to copy to
someplace else, so it isn't worth cse'ing. */
else if (GET_CODE (SET_SRC (x)) == CALL)
;
else
sets[n_sets++].rtl = x;
}
else if (GET_CODE (x) == PARALLEL)
{
int i, lim = XVECLEN (x, 0);
/* Go over the epressions of the PARALLEL in forward order, to
put them in the same order in the SETS array. */
for (i = 0; i < lim; i++)
{
rtx y = XVECEXP (x, 0, i);
if (GET_CODE (y) == SET)
{
/* As above, we ignore unconditional jumps and call-insns and
ignore the result of apply_change_group. */
if (SET_DEST (y) == pc_rtx
&& GET_CODE (SET_SRC (y)) == LABEL_REF)
;
else if (GET_CODE (SET_SRC (y)) == CALL)
;
else
sets[n_sets++].rtl = y;
}
}
}
return n_sets;
}
/* Where possible, substitute every register reference in the N_SETS
number of SETS in INSN with the the canonical register.
Register canonicalization propagatest the earliest register (i.e.
one that is set before INSN) with the same value. This is a very
useful, simple form of CSE, to clean up warts from expanding GIMPLE
to RTL. For instance, a CONST for an address is usually expanded
multiple times to loads into different registers, thus creating many
subexpressions of the form:
(set (reg1) (some_const))
(set (mem (... reg1 ...) (thing)))
(set (reg2) (some_const))
(set (mem (... reg2 ...) (thing)))
After canonicalizing, the code takes the following form:
(set (reg1) (some_const))
(set (mem (... reg1 ...) (thing)))
(set (reg2) (some_const))
(set (mem (... reg1 ...) (thing)))
The set to reg2 is now trivially dead, and the memory reference (or
address, or whatever) may be a candidate for further CSEing.
In this function, the result of apply_change_group can be ignored;
see canon_reg. */
static void
canonicalize_insn (rtx insn, struct set **psets, int n_sets)
{
struct set *sets = *psets;
rtx tem;
rtx x = PATTERN (insn);
int i;
if (CALL_P (insn))
{
for (tem = <API key> (insn); tem; tem = XEXP (tem, 1))
XEXP (tem, 0) = canon_reg (XEXP (tem, 0), insn);
}
if (GET_CODE (x) == SET && GET_CODE (SET_SRC (x)) == CALL)
{
canon_reg (SET_SRC (x), insn);
apply_change_group ();
fold_rtx (SET_SRC (x), insn);
}
else if (GET_CODE (x) == CLOBBER)
{
/* If we clobber memory, canon the address.
This does nothing when a register is clobbered
because we have already invalidated the reg. */
if (MEM_P (XEXP (x, 0)))
canon_reg (XEXP (x, 0), insn);
}
else if (GET_CODE (x) == USE
&& ! (REG_P (XEXP (x, 0))
&& REGNO (XEXP (x, 0)) < <API key>))
/* Canonicalize a USE of a pseudo register or memory location. */
canon_reg (x, insn);
else if (GET_CODE (x) == ASM_OPERANDS)
{
for (i = <API key> (x) - 1; i >= 0; i
{
rtx input = ASM_OPERANDS_INPUT (x, i);
if (!(REG_P (input) && REGNO (input) < <API key>))
{
input = canon_reg (input, insn);
validate_change (insn, &ASM_OPERANDS_INPUT (x, i), input, 1);
}
}
}
else if (GET_CODE (x) == CALL)
{
canon_reg (x, insn);
apply_change_group ();
fold_rtx (x, insn);
}
else if (DEBUG_INSN_P (insn))
canon_reg (PATTERN (insn), insn);
else if (GET_CODE (x) == PARALLEL)
{
for (i = XVECLEN (x, 0) - 1; i >= 0; i
{
rtx y = XVECEXP (x, 0, i);
if (GET_CODE (y) == SET && GET_CODE (SET_SRC (y)) == CALL)
{
canon_reg (SET_SRC (y), insn);
apply_change_group ();
fold_rtx (SET_SRC (y), insn);
}
else if (GET_CODE (y) == CLOBBER)
{
if (MEM_P (XEXP (y, 0)))
canon_reg (XEXP (y, 0), insn);
}
else if (GET_CODE (y) == USE
&& ! (REG_P (XEXP (y, 0))
&& REGNO (XEXP (y, 0)) < <API key>))
canon_reg (y, insn);
else if (GET_CODE (y) == CALL)
{
canon_reg (y, insn);
apply_change_group ();
fold_rtx (y, insn);
}
}
}
if (n_sets == 1 && REG_NOTES (insn) != 0
&& (tem = find_reg_note (insn, REG_EQUAL, NULL_RTX)) != 0)
{
/* We potentially will process this insn many times. Therefore,
drop the REG_EQUAL note if it is equal to the SET_SRC of the
unique set in INSN.
Do not do so if the REG_EQUAL note is for a STRICT_LOW_PART,
because cse_insn handles those specially. */
if (GET_CODE (SET_DEST (sets[0].rtl)) != STRICT_LOW_PART
&& rtx_equal_p (XEXP (tem, 0), SET_SRC (sets[0].rtl)))
remove_note (insn, tem);
else
{
canon_reg (XEXP (tem, 0), insn);
apply_change_group ();
XEXP (tem, 0) = fold_rtx (XEXP (tem, 0), insn);
df_notes_rescan (insn);
}
}
/* Canonicalize sources and addresses of destinations.
We do this in a separate pass to avoid problems when a MATCH_DUP is
present in the insn pattern. In that case, we want to ensure that
we don't break the duplicate nature of the pattern. So we will replace
both operands at the same time. Otherwise, we would fail to find an
equivalent substitution in the loop calling validate_change below.
We used to suppress canonicalization of DEST if it appears in SRC,
but we don't do this any more. */
for (i = 0; i < n_sets; i++)
{
rtx dest = SET_DEST (sets[i].rtl);
rtx src = SET_SRC (sets[i].rtl);
rtx new_rtx = canon_reg (src, insn);
validate_change (insn, &SET_SRC (sets[i].rtl), new_rtx, 1);
if (GET_CODE (dest) == ZERO_EXTRACT)
{
validate_change (insn, &XEXP (dest, 1),
canon_reg (XEXP (dest, 1), insn), 1);
validate_change (insn, &XEXP (dest, 2),
canon_reg (XEXP (dest, 2), insn), 1);
}
while (GET_CODE (dest) == SUBREG
|| GET_CODE (dest) == ZERO_EXTRACT
|| GET_CODE (dest) == STRICT_LOW_PART)
dest = XEXP (dest, 0);
if (MEM_P (dest))
canon_reg (dest, insn);
}
/* Now that we have done all the replacements, we can apply the change
group and see if they all work. Note that this will cause some
canonicalizations that would have worked individually not to be applied
because some other canonicalization didn't work, but this should not
occur often.
The result of apply_change_group can be ignored; see canon_reg. */
apply_change_group ();
}
/* Main function of CSE.
First simplify sources and addresses of all assignments
in the instruction, using previously-computed equivalents values.
Then install the new sources and destinations in the table
of available values. */
static void
cse_insn (rtx insn)
{
rtx x = PATTERN (insn);
int i;
rtx tem;
int n_sets = 0;
rtx src_eqv = 0;
struct table_elt *src_eqv_elt = 0;
int src_eqv_volatile = 0;
int src_eqv_in_memory = 0;
unsigned src_eqv_hash = 0;
struct set *sets = (struct set *) 0;
if (GET_CODE (x) == SET)
sets = XALLOCA (struct set);
else if (GET_CODE (x) == PARALLEL)
sets = XALLOCAVEC (struct set, XVECLEN (x, 0));
this_insn = insn;
#ifdef HAVE_cc0
/* Records what this insn does to set CC0. */
this_insn_cc0 = 0;
this_insn_cc0_mode = VOIDmode;
#endif
/* Find all regs explicitly clobbered in this insn,
to ensure they are not replaced with any other regs
elsewhere in this insn. */
<API key> (insn);
/* Record all the SETs in this instruction. */
n_sets = find_sets_in_insn (insn, &sets);
/* Substitute the canonical register where possible. */
canonicalize_insn (insn, &sets, n_sets);
/* If this insn has a REG_EQUAL note, store the equivalent value in SRC_EQV,
if different, or if the DEST is a STRICT_LOW_PART. The latter condition
is necessary because SRC_EQV is handled specially for this case, and if
it isn't set, then there will be no equivalence for the destination. */
if (n_sets == 1 && REG_NOTES (insn) != 0
&& (tem = find_reg_note (insn, REG_EQUAL, NULL_RTX)) != 0
&& (! rtx_equal_p (XEXP (tem, 0), SET_SRC (sets[0].rtl))
|| GET_CODE (SET_DEST (sets[0].rtl)) == STRICT_LOW_PART))
src_eqv = copy_rtx (XEXP (tem, 0));
/* Set sets[i].src_elt to the class each source belongs to.
Detect assignments from or to volatile things
and set set[i] to zero so they will be ignored
in the rest of this function.
Nothing in this loop changes the hash table or the register chains. */
for (i = 0; i < n_sets; i++)
{
bool repeat = false;
rtx src, dest;
rtx src_folded;
struct table_elt *elt = 0, *p;
enum machine_mode mode;
rtx src_eqv_here;
rtx src_const = 0;
rtx src_related = 0;
bool <API key> = false;
struct table_elt *src_const_elt = 0;
int src_cost = MAX_COST;
int src_eqv_cost = MAX_COST;
int src_folded_cost = MAX_COST;
int src_related_cost = MAX_COST;
int src_elt_cost = MAX_COST;
int src_regcost = MAX_COST;
int src_eqv_regcost = MAX_COST;
int src_folded_regcost = MAX_COST;
int src_related_regcost = MAX_COST;
int src_elt_regcost = MAX_COST;
/* Set nonzero if we need to call force_const_mem on with the
contents of src_folded before using it. */
int <API key> = 0;
dest = SET_DEST (sets[i].rtl);
src = SET_SRC (sets[i].rtl);
/* If SRC is a constant that has no machine mode,
hash it with the destination's machine mode.
This way we can keep different modes separate. */
mode = GET_MODE (src) == VOIDmode ? GET_MODE (dest) : GET_MODE (src);
sets[i].mode = mode;
if (src_eqv)
{
enum machine_mode eqvmode = mode;
if (GET_CODE (dest) == STRICT_LOW_PART)
eqvmode = GET_MODE (SUBREG_REG (XEXP (dest, 0)));
do_not_record = 0;
hash_arg_in_memory = 0;
src_eqv_hash = HASH (src_eqv, eqvmode);
/* Find the equivalence class for the equivalent expression. */
if (!do_not_record)
src_eqv_elt = lookup (src_eqv, src_eqv_hash, eqvmode);
src_eqv_volatile = do_not_record;
src_eqv_in_memory = hash_arg_in_memory;
}
/* If this is a STRICT_LOW_PART assignment, src_eqv corresponds to the
value of the INNER register, not the destination. So it is not
a valid substitution for the source. But save it for later. */
if (GET_CODE (dest) == STRICT_LOW_PART)
src_eqv_here = 0;
else
src_eqv_here = src_eqv;
/* Simplify and foldable subexpressions in SRC. Then get the fully-
simplified result, which may not necessarily be valid. */
src_folded = fold_rtx (src, insn);
#if 0
/* ??? This caused bad code to be generated for the m68k port with -O2.
Suppose src is (CONST_INT -1), and that after truncation src_folded
is (CONST_INT 3). Suppose src_folded is then used for src_const.
At the end we will add src and src_const to the same equivalence
class. We now have 3 and -1 on the same equivalence class. This
causes later instructions to be mis-optimized. */
/* If storing a constant in a bitfield, pre-truncate the constant
so we will be able to record it later. */
if (GET_CODE (SET_DEST (sets[i].rtl)) == ZERO_EXTRACT)
{
rtx width = XEXP (SET_DEST (sets[i].rtl), 1);
if (CONST_INT_P (src)
&& CONST_INT_P (width)
&& INTVAL (width) < <API key>
&& (INTVAL (src) & ((HOST_WIDE_INT) (-1) << INTVAL (width))))
src_folded
= GEN_INT (INTVAL (src) & (((HOST_WIDE_INT) 1
<< INTVAL (width)) - 1));
}
#endif
/* Compute SRC's hash code, and also notice if it
should not be recorded at all. In that case,
prevent any further processing of this assignment. */
do_not_record = 0;
hash_arg_in_memory = 0;
sets[i].src = src;
sets[i].src_hash = HASH (src, mode);
sets[i].src_volatile = do_not_record;
sets[i].src_in_memory = hash_arg_in_memory;
/* If SRC is a MEM, there is a REG_EQUIV note for SRC, and DEST is
a pseudo, do not record SRC. Using SRC as a replacement for
anything else will be incorrect in that situation. Note that
this usually occurs only for stack slots, in which case all the
RTL would be referring to SRC, so we don't lose any optimization
opportunities by not having SRC in the hash table. */
if (MEM_P (src)
&& find_reg_note (insn, REG_EQUIV, NULL_RTX) != 0
&& REG_P (dest)
&& REGNO (dest) >= <API key>)
sets[i].src_volatile = 1;
#if 0
/* It is no longer clear why we used to do this, but it doesn't
appear to still be needed. So let's try without it since this
code hurts cse'ing widened ops. */
/* If source is a paradoxical subreg (such as QI treated as an SI),
treat it as volatile. It may do the work of an SI in one context
where the extra bits are not being used, but cannot replace an SI
in general. */
if (<API key> (src))
sets[i].src_volatile = 1;
#endif
/* Locate all possible equivalent forms for SRC. Try to replace
SRC in the insn with each cheaper equivalent.
We have the following types of equivalents: SRC itself, a folded
version, a value given in a REG_EQUAL note, or a value related
to a constant.
Each of these equivalents may be part of an additional class
of equivalents (if more than one is in the table, they must be in
the same class; we check for this).
If the source is volatile, we don't do any table lookups.
We note any constant equivalent for possible later use in a
REG_NOTE. */
if (!sets[i].src_volatile)
elt = lookup (src, sets[i].src_hash, mode);
sets[i].src_elt = elt;
if (elt && src_eqv_here && src_eqv_elt)
{
if (elt->first_same_value != src_eqv_elt->first_same_value)
{
/* The REG_EQUAL is indicating that two formerly distinct
classes are now equivalent. So merge them. */
merge_equiv_classes (elt, src_eqv_elt);
src_eqv_hash = HASH (src_eqv, elt->mode);
src_eqv_elt = lookup (src_eqv, src_eqv_hash, elt->mode);
}
src_eqv_here = 0;
}
else if (src_eqv_elt)
elt = src_eqv_elt;
/* Try to find a constant somewhere and record it in `src_const'.
Record its table element, if any, in `src_const_elt'. Look in
any known equivalences first. (If the constant is not in the
table, also set `sets[i].src_const_hash'). */
if (elt)
for (p = elt->first_same_value; p; p = p->next_same_value)
if (p->is_const)
{
src_const = p->exp;
src_const_elt = elt;
break;
}
if (src_const == 0
&& (CONSTANT_P (src_folded)
/* Consider (minus (label_ref L1) (label_ref L2)) as
"constant" here so we will record it. This allows us
to fold switch statements when an ADDR_DIFF_VEC is used. */
|| (GET_CODE (src_folded) == MINUS
&& GET_CODE (XEXP (src_folded, 0)) == LABEL_REF
&& GET_CODE (XEXP (src_folded, 1)) == LABEL_REF)))
src_const = src_folded, src_const_elt = elt;
else if (src_const == 0 && src_eqv_here && CONSTANT_P (src_eqv_here))
src_const = src_eqv_here, src_const_elt = src_eqv_elt;
/* If we don't know if the constant is in the table, get its
hash code and look it up. */
if (src_const && src_const_elt == 0)
{
sets[i].src_const_hash = HASH (src_const, mode);
src_const_elt = lookup (src_const, sets[i].src_const_hash, mode);
}
sets[i].src_const = src_const;
sets[i].src_const_elt = src_const_elt;
/* If the constant and our source are both in the table, mark them as
equivalent. Otherwise, if a constant is in the table but the source
isn't, set ELT to it. */
if (src_const_elt && elt
&& src_const_elt->first_same_value != elt->first_same_value)
merge_equiv_classes (elt, src_const_elt);
else if (src_const_elt && elt == 0)
elt = src_const_elt;
/* See if there is a register linearly related to a constant
equivalent of SRC. */
if (src_const
&& (GET_CODE (src_const) == CONST
|| (src_const_elt && src_const_elt->related_value != 0)))
{
src_related = use_related_value (src_const, src_const_elt);
if (src_related)
{
struct table_elt *src_related_elt
= lookup (src_related, HASH (src_related, mode), mode);
if (src_related_elt && elt)
{
if (elt->first_same_value
!= src_related_elt->first_same_value)
/* This can occur when we previously saw a CONST
involving a SYMBOL_REF and then see the SYMBOL_REF
twice. Merge the involved classes. */
merge_equiv_classes (elt, src_related_elt);
src_related = 0;
src_related_elt = 0;
}
else if (src_related_elt && elt == 0)
elt = src_related_elt;
}
}
/* See if we have a CONST_INT that is already in a register in a
wider mode. */
if (src_const && src_related == 0 && CONST_INT_P (src_const)
&& GET_MODE_CLASS (mode) == MODE_INT
&& GET_MODE_PRECISION (mode) < BITS_PER_WORD)
{
enum machine_mode wider_mode;
for (wider_mode = GET_MODE_WIDER_MODE (mode);
wider_mode != VOIDmode
&& GET_MODE_PRECISION (wider_mode) <= BITS_PER_WORD
&& src_related == 0;
wider_mode = GET_MODE_WIDER_MODE (wider_mode))
{
struct table_elt *const_elt
= lookup (src_const, HASH (src_const, wider_mode), wider_mode);
if (const_elt == 0)
continue;
for (const_elt = const_elt->first_same_value;
const_elt; const_elt = const_elt->next_same_value)
if (REG_P (const_elt->exp))
{
src_related = gen_lowpart (mode, const_elt->exp);
break;
}
}
}
/* Another possibility is that we have an AND with a constant in
a mode narrower than a word. If so, it might have been generated
as part of an "if" which would narrow the AND. If we already
have done the AND in a wider mode, we can use a SUBREG of that
value. */
if (<API key> && ! src_related
&& GET_CODE (src) == AND && CONST_INT_P (XEXP (src, 1))
&& GET_MODE_SIZE (mode) < UNITS_PER_WORD)
{
enum machine_mode tmode;
rtx new_and = gen_rtx_AND (VOIDmode, NULL_RTX, XEXP (src, 1));
for (tmode = GET_MODE_WIDER_MODE (mode);
GET_MODE_SIZE (tmode) <= UNITS_PER_WORD;
tmode = GET_MODE_WIDER_MODE (tmode))
{
rtx inner = gen_lowpart (tmode, XEXP (src, 0));
struct table_elt *larger_elt;
if (inner)
{
PUT_MODE (new_and, tmode);
XEXP (new_and, 0) = inner;
larger_elt = lookup (new_and, HASH (new_and, tmode), tmode);
if (larger_elt == 0)
continue;
for (larger_elt = larger_elt->first_same_value;
larger_elt; larger_elt = larger_elt->next_same_value)
if (REG_P (larger_elt->exp))
{
src_related
= gen_lowpart (mode, larger_elt->exp);
break;
}
if (src_related)
break;
}
}
}
#ifdef LOAD_EXTEND_OP
/* See if a MEM has already been loaded with a widening operation;
if it has, we can use a subreg of that. Many CISC machines
also have such operations, but this is only likely to be
beneficial on these machines. */
if (<API key> && src_related == 0
&& (GET_MODE_SIZE (mode) < UNITS_PER_WORD)
&& GET_MODE_CLASS (mode) == MODE_INT
&& MEM_P (src) && ! do_not_record
&& LOAD_EXTEND_OP (mode) != UNKNOWN)
{
struct rtx_def memory_extend_buf;
rtx memory_extend_rtx = &memory_extend_buf;
enum machine_mode tmode;
/* Set what we are trying to extend and the operation it might
have been extended with. */
memset (memory_extend_rtx, 0, sizeof(*memory_extend_rtx));
PUT_CODE (memory_extend_rtx, LOAD_EXTEND_OP (mode));
XEXP (memory_extend_rtx, 0) = src;
for (tmode = GET_MODE_WIDER_MODE (mode);
GET_MODE_SIZE (tmode) <= UNITS_PER_WORD;
tmode = GET_MODE_WIDER_MODE (tmode))
{
struct table_elt *larger_elt;
PUT_MODE (memory_extend_rtx, tmode);
larger_elt = lookup (memory_extend_rtx,
HASH (memory_extend_rtx, tmode), tmode);
if (larger_elt == 0)
continue;
for (larger_elt = larger_elt->first_same_value;
larger_elt; larger_elt = larger_elt->next_same_value)
if (REG_P (larger_elt->exp))
{
src_related = gen_lowpart (mode, larger_elt->exp);
break;
}
if (src_related)
break;
}
}
#endif /* LOAD_EXTEND_OP */
/* Try to express the constant using a register+offset expression
derived from a constant anchor. */
if (targetm.const_anchor
&& !src_related
&& src_const
&& GET_CODE (src_const) == CONST_INT)
{
src_related = try_const_anchors (src_const, mode);
<API key> = src_related != NULL_RTX;
}
if (src == src_folded)
src_folded = 0;
/* At this point, ELT, if nonzero, points to a class of expressions
equivalent to the source of this SET and SRC, SRC_EQV, SRC_FOLDED,
and SRC_RELATED, if nonzero, each contain additional equivalent
expressions. Prune these latter expressions by deleting expressions
already in the equivalence class.
Check for an equivalent identical to the destination. If found,
this is the preferred equivalent since it will likely lead to
elimination of the insn. Indicate this by placing it in
`src_related'. */
if (elt)
elt = elt->first_same_value;
for (p = elt; p; p = p->next_same_value)
{
enum rtx_code code = GET_CODE (p->exp);
/* If the expression is not valid, ignore it. Then we do not
have to check for validity below. In most cases, we can use
`rtx_equal_p', since canonicalization has already been done. */
if (code != REG && ! exp_equiv_p (p->exp, p->exp, 1, false))
continue;
/* Also skip paradoxical subregs, unless that's what we're
looking for. */
if (<API key> (p->exp)
&& ! (src != 0
&& GET_CODE (src) == SUBREG
&& GET_MODE (src) == GET_MODE (p->exp)
&& (GET_MODE_SIZE (GET_MODE (SUBREG_REG (src)))
< GET_MODE_SIZE (GET_MODE (SUBREG_REG (p->exp))))))
continue;
if (src && GET_CODE (src) == code && rtx_equal_p (src, p->exp))
src = 0;
else if (src_folded && GET_CODE (src_folded) == code
&& rtx_equal_p (src_folded, p->exp))
src_folded = 0;
else if (src_eqv_here && GET_CODE (src_eqv_here) == code
&& rtx_equal_p (src_eqv_here, p->exp))
src_eqv_here = 0;
else if (src_related && GET_CODE (src_related) == code
&& rtx_equal_p (src_related, p->exp))
src_related = 0;
/* This is the same as the destination of the insns, we want
to prefer it. Copy it to src_related. The code below will
then give it a negative cost. */
if (GET_CODE (dest) == code && rtx_equal_p (p->exp, dest))
src_related = dest;
}
/* Find the cheapest valid equivalent, trying all the available
possibilities. Prefer items not in the hash table to ones
that are when they are equal cost. Note that we can never
worsen an insn as the current contents will also succeed.
If we find an equivalent identical to the destination, use it as best,
since this insn will probably be eliminated in that case. */
if (src)
{
if (rtx_equal_p (src, dest))
src_cost = src_regcost = -1;
else
{
src_cost = COST (src);
src_regcost = approx_reg_cost (src);
}
}
if (src_eqv_here)
{
if (rtx_equal_p (src_eqv_here, dest))
src_eqv_cost = src_eqv_regcost = -1;
else
{
src_eqv_cost = COST (src_eqv_here);
src_eqv_regcost = approx_reg_cost (src_eqv_here);
}
}
if (src_folded)
{
if (rtx_equal_p (src_folded, dest))
src_folded_cost = src_folded_regcost = -1;
else
{
src_folded_cost = COST (src_folded);
src_folded_regcost = approx_reg_cost (src_folded);
}
}
if (src_related)
{
if (rtx_equal_p (src_related, dest))
src_related_cost = src_related_regcost = -1;
else
{
src_related_cost = COST (src_related);
src_related_regcost = approx_reg_cost (src_related);
/* If a const-anchor is used to synthesize a constant that
normally requires multiple instructions then slightly prefer
it over the original sequence. These instructions are likely
to become redundant now. We can't compare against the cost
of src_eqv_here because, on MIPS for example, multi-insn
constants have zero cost; they are assumed to be hoisted from
loops. */
if (<API key>
&& src_related_cost == src_cost
&& src_eqv_here)
src_related_cost
}
}
/* If this was an indirect jump insn, a known label will really be
cheaper even though it looks more expensive. */
if (dest == pc_rtx && src_const && GET_CODE (src_const) == LABEL_REF)
src_folded = src_const, src_folded_cost = src_folded_regcost = -1;
/* Terminate loop when replacement made. This must terminate since
the current contents will be tested and will always be valid. */
while (1)
{
rtx trial;
/* Skip invalid entries. */
while (elt && !REG_P (elt->exp)
&& ! exp_equiv_p (elt->exp, elt->exp, 1, false))
elt = elt->next_same_value;
/* A paradoxical subreg would be bad here: it'll be the right
size, but later may be adjusted so that the upper bits aren't
what we want. So reject it. */
if (elt != 0
&& <API key> (elt->exp)
/* It is okay, though, if the rtx we're trying to match
will ignore any of the bits we can't predict. */
&& ! (src != 0
&& GET_CODE (src) == SUBREG
&& GET_MODE (src) == GET_MODE (elt->exp)
&& (GET_MODE_SIZE (GET_MODE (SUBREG_REG (src)))
< GET_MODE_SIZE (GET_MODE (SUBREG_REG (elt->exp))))))
{
elt = elt->next_same_value;
continue;
}
if (elt)
{
src_elt_cost = elt->cost;
src_elt_regcost = elt->regcost;
}
/* Find cheapest and skip it for the next time. For items
of equal cost, use this order:
src_folded, src, src_eqv, src_related and hash table entry. */
if (src_folded
&& preferable (src_folded_cost, src_folded_regcost,
src_cost, src_regcost) <= 0
&& preferable (src_folded_cost, src_folded_regcost,
src_eqv_cost, src_eqv_regcost) <= 0
&& preferable (src_folded_cost, src_folded_regcost,
src_related_cost, src_related_regcost) <= 0
&& preferable (src_folded_cost, src_folded_regcost,
src_elt_cost, src_elt_regcost) <= 0)
{
trial = src_folded, src_folded_cost = MAX_COST;
if (<API key>)
{
rtx forced = force_const_mem (mode, trial);
if (forced)
trial = forced;
}
}
else if (src
&& preferable (src_cost, src_regcost,
src_eqv_cost, src_eqv_regcost) <= 0
&& preferable (src_cost, src_regcost,
src_related_cost, src_related_regcost) <= 0
&& preferable (src_cost, src_regcost,
src_elt_cost, src_elt_regcost) <= 0)
trial = src, src_cost = MAX_COST;
else if (src_eqv_here
&& preferable (src_eqv_cost, src_eqv_regcost,
src_related_cost, src_related_regcost) <= 0
&& preferable (src_eqv_cost, src_eqv_regcost,
src_elt_cost, src_elt_regcost) <= 0)
trial = src_eqv_here, src_eqv_cost = MAX_COST;
else if (src_related
&& preferable (src_related_cost, src_related_regcost,
src_elt_cost, src_elt_regcost) <= 0)
trial = src_related, src_related_cost = MAX_COST;
else
{
trial = elt->exp;
elt = elt->next_same_value;
src_elt_cost = MAX_COST;
}
/* Avoid creation of overlapping memory moves. */
if (MEM_P (trial) && MEM_P (SET_DEST (sets[i].rtl)))
{
rtx src, dest;
/* BLKmode moves are not handled by cse anyway. */
if (GET_MODE (trial) == BLKmode)
break;
src = canon_rtx (trial);
dest = canon_rtx (SET_DEST (sets[i].rtl));
if (!MEM_P (src) || !MEM_P (dest)
|| !<API key> (src, dest, false))
break;
}
/* Try to optimize
(set (reg:M N) (const_int A))
(set (reg:M2 O) (const_int B))
(set (zero_extract:M2 (reg:M N) (const_int C) (const_int D))
(reg:M2 O)). */
if (GET_CODE (SET_DEST (sets[i].rtl)) == ZERO_EXTRACT
&& CONST_INT_P (trial)
&& CONST_INT_P (XEXP (SET_DEST (sets[i].rtl), 1))
&& CONST_INT_P (XEXP (SET_DEST (sets[i].rtl), 2))
&& REG_P (XEXP (SET_DEST (sets[i].rtl), 0))
&& (GET_MODE_PRECISION (GET_MODE (SET_DEST (sets[i].rtl)))
>= INTVAL (XEXP (SET_DEST (sets[i].rtl), 1)))
&& ((unsigned) INTVAL (XEXP (SET_DEST (sets[i].rtl), 1))
+ (unsigned) INTVAL (XEXP (SET_DEST (sets[i].rtl), 2))
<= <API key>))
{
rtx dest_reg = XEXP (SET_DEST (sets[i].rtl), 0);
rtx width = XEXP (SET_DEST (sets[i].rtl), 1);
rtx pos = XEXP (SET_DEST (sets[i].rtl), 2);
unsigned int dest_hash = HASH (dest_reg, GET_MODE (dest_reg));
struct table_elt *dest_elt
= lookup (dest_reg, dest_hash, GET_MODE (dest_reg));
rtx dest_cst = NULL;
if (dest_elt)
for (p = dest_elt->first_same_value; p; p = p->next_same_value)
if (p->is_const && CONST_INT_P (p->exp))
{
dest_cst = p->exp;
break;
}
if (dest_cst)
{
HOST_WIDE_INT val = INTVAL (dest_cst);
HOST_WIDE_INT mask;
unsigned int shift;
if (BITS_BIG_ENDIAN)
shift = GET_MODE_PRECISION (GET_MODE (dest_reg))
- INTVAL (pos) - INTVAL (width);
else
shift = INTVAL (pos);
if (INTVAL (width) == <API key>)
mask = ~(HOST_WIDE_INT) 0;
else
mask = ((HOST_WIDE_INT) 1 << INTVAL (width)) - 1;
val &= ~(mask << shift);
val |= (INTVAL (trial) & mask) << shift;
val = trunc_int_for_mode (val, GET_MODE (dest_reg));
<API key> (insn, &SET_DEST (sets[i].rtl),
dest_reg, 1);
<API key> (insn, &SET_SRC (sets[i].rtl),
GEN_INT (val), 1);
if (apply_change_group ())
{
rtx note = find_reg_note (insn, REG_EQUAL, NULL_RTX);
if (note)
{
remove_note (insn, note);
df_notes_rescan (insn);
}
src_eqv = NULL_RTX;
src_eqv_elt = NULL;
src_eqv_volatile = 0;
src_eqv_in_memory = 0;
src_eqv_hash = 0;
repeat = true;
break;
}
}
}
/* We don't normally have an insn matching (set (pc) (pc)), so
check for this separately here. We will delete such an
insn below.
For other cases such as a table jump or conditional jump
where we know the ultimate target, go ahead and replace the
operand. While that may not make a valid insn, we will
reemit the jump below (and also insert any necessary
barriers). */
if (n_sets == 1 && dest == pc_rtx
&& (trial == pc_rtx
|| (GET_CODE (trial) == LABEL_REF
&& ! condjump_p (insn))))
{
/* Don't substitute non-local labels, this confuses CFG. */
if (GET_CODE (trial) == LABEL_REF
&& <API key> (trial))
continue;
SET_SRC (sets[i].rtl) = trial;
cse_jumps_altered = true;
break;
}
/* Reject certain invalid forms of CONST that we create. */
else if (CONSTANT_P (trial)
&& GET_CODE (trial) == CONST
/* Reject cases that will cause decode_rtx_const to
die. On the alpha when simplifying a switch, we
get (const (truncate (minus (label_ref)
(label_ref)))). */
&& (GET_CODE (XEXP (trial, 0)) == TRUNCATE
/* Likewise on IA-64, except without the
truncate. */
|| (GET_CODE (XEXP (trial, 0)) == MINUS
&& GET_CODE (XEXP (XEXP (trial, 0), 0)) == LABEL_REF
&& GET_CODE (XEXP (XEXP (trial, 0), 1)) == LABEL_REF)))
/* Do nothing for this case. */
;
/* Look for a substitution that makes a valid insn. */
else if (<API key>
(insn, &SET_SRC (sets[i].rtl), trial, 0))
{
rtx new_rtx = canon_reg (SET_SRC (sets[i].rtl), insn);
/* The result of apply_change_group can be ignored; see
canon_reg. */
validate_change (insn, &SET_SRC (sets[i].rtl), new_rtx, 1);
apply_change_group ();
break;
}
/* If we previously found constant pool entries for
constants and this is a constant, try making a
pool entry. Put it in src_folded unless we already have done
this since that is where it likely came from. */
else if (<API key>
&& CONSTANT_P (trial)
&& (src_folded == 0
|| (!MEM_P (src_folded)
&& ! <API key>))
&& GET_MODE_CLASS (mode) != MODE_CC
&& mode != VOIDmode)
{
<API key> = 1;
src_folded = trial;
src_folded_cost = <API key>;
src_folded_regcost = <API key>;
}
}
/* If we changed the insn too much, handle this set from scratch. */
if (repeat)
{
i
continue;
}
src = SET_SRC (sets[i].rtl);
/* In general, it is good to have a SET with SET_SRC == SET_DEST.
However, there is an important exception: If both are registers
that are not the head of their equivalence class, replace SET_SRC
with the head of the class. If we do not do this, we will have
both registers live over a portion of the basic block. This way,
their lifetimes will likely abut instead of overlapping. */
if (REG_P (dest)
&& REGNO_QTY_VALID_P (REGNO (dest)))
{
int dest_q = REG_QTY (REGNO (dest));
struct qty_table_elem *dest_ent = &qty_table[dest_q];
if (dest_ent->mode == GET_MODE (dest)
&& dest_ent->first_reg != REGNO (dest)
&& REG_P (src) && REGNO (src) == REGNO (dest)
/* Don't do this if the original insn had a hard reg as
SET_SRC or SET_DEST. */
&& (!REG_P (sets[i].src)
|| REGNO (sets[i].src) >= <API key>)
&& (!REG_P (dest) || REGNO (dest) >= <API key>))
/* We can't call canon_reg here because it won't do anything if
SRC is a hard register. */
{
int src_q = REG_QTY (REGNO (src));
struct qty_table_elem *src_ent = &qty_table[src_q];
int first = src_ent->first_reg;
rtx new_src
= (first >= <API key>
? regno_reg_rtx[first] : gen_rtx_REG (GET_MODE (src), first));
/* We must use validate-change even for this, because this
might be a special no-op instruction, suitable only to
tag notes onto. */
if (validate_change (insn, &SET_SRC (sets[i].rtl), new_src, 0))
{
src = new_src;
/* If we had a constant that is cheaper than what we are now
setting SRC to, use that constant. We ignored it when we
thought we could make this into a no-op. */
if (src_const && COST (src_const) < COST (src)
&& validate_change (insn, &SET_SRC (sets[i].rtl),
src_const, 0))
src = src_const;
}
}
}
/* If we made a change, recompute SRC values. */
if (src != sets[i].src)
{
do_not_record = 0;
hash_arg_in_memory = 0;
sets[i].src = src;
sets[i].src_hash = HASH (src, mode);
sets[i].src_volatile = do_not_record;
sets[i].src_in_memory = hash_arg_in_memory;
sets[i].src_elt = lookup (src, sets[i].src_hash, mode);
}
/* If this is a single SET, we are setting a register, and we have an
equivalent constant, we want to add a REG_NOTE. We don't want
to write a REG_EQUAL note for a constant pseudo since verifying that
that pseudo hasn't been eliminated is a pain. Such a note also
won't help anything.
Avoid a REG_EQUAL note for (CONST (MINUS (LABEL_REF) (LABEL_REF)))
which can be created for a reference to a compile time computable
entry in a jump table. */
if (n_sets == 1 && src_const && REG_P (dest)
&& !REG_P (src_const)
&& ! (GET_CODE (src_const) == CONST
&& GET_CODE (XEXP (src_const, 0)) == MINUS
&& GET_CODE (XEXP (XEXP (src_const, 0), 0)) == LABEL_REF
&& GET_CODE (XEXP (XEXP (src_const, 0), 1)) == LABEL_REF))
{
/* We only want a REG_EQUAL note if src_const != src. */
if (! rtx_equal_p (src, src_const))
{
/* Make sure that the rtx is not shared. */
src_const = copy_rtx (src_const);
/* Record the actual constant value in a REG_EQUAL note,
making a new one if one does not already exist. */
set_unique_reg_note (insn, REG_EQUAL, src_const);
df_notes_rescan (insn);
}
}
/* Now deal with the destination. */
do_not_record = 0;
/* Look within any ZERO_EXTRACT to the MEM or REG within it. */
while (GET_CODE (dest) == SUBREG
|| GET_CODE (dest) == ZERO_EXTRACT
|| GET_CODE (dest) == STRICT_LOW_PART)
dest = XEXP (dest, 0);
sets[i].inner_dest = dest;
if (MEM_P (dest))
{
#ifdef PUSH_ROUNDING
/* Stack pushes invalidate the stack pointer. */
rtx addr = XEXP (dest, 0);
if (GET_RTX_CLASS (GET_CODE (addr)) == RTX_AUTOINC
&& XEXP (addr, 0) == stack_pointer_rtx)
invalidate (stack_pointer_rtx, VOIDmode);
#endif
dest = fold_rtx (dest, insn);
}
/* Compute the hash code of the destination now,
before the effects of this instruction are recorded,
since the register values used in the address computation
are those before this instruction. */
sets[i].dest_hash = HASH (dest, mode);
/* Don't enter a bit-field in the hash table
because the value in it after the store
may not equal what was stored, due to truncation. */
if (GET_CODE (SET_DEST (sets[i].rtl)) == ZERO_EXTRACT)
{
rtx width = XEXP (SET_DEST (sets[i].rtl), 1);
if (src_const != 0 && CONST_INT_P (src_const)
&& CONST_INT_P (width)
&& INTVAL (width) < <API key>
&& ! (INTVAL (src_const)
& ((HOST_WIDE_INT) (-1) << INTVAL (width))))
/* Exception: if the value is constant,
and it won't be truncated, record it. */
;
else
{
/* This is chosen so that the destination will be invalidated
but no new value will be recorded.
We must invalidate because sometimes constant
values can be recorded for bitfields. */
sets[i].src_elt = 0;
sets[i].src_volatile = 1;
src_eqv = 0;
src_eqv_elt = 0;
}
}
/* If only one set in a JUMP_INSN and it is now a no-op, we can delete
the insn. */
else if (n_sets == 1 && dest == pc_rtx && src == pc_rtx)
{
/* One less use of the label this insn used to jump to. */
<API key> (insn);
cse_jumps_altered = true;
/* No more processing for this set. */
sets[i].rtl = 0;
}
/* If this SET is now setting PC to a label, we know it used to
be a conditional or computed branch. */
else if (dest == pc_rtx && GET_CODE (src) == LABEL_REF
&& !<API key> (src))
{
/* We reemit the jump in as many cases as possible just in
case the form of an unconditional jump is significantly
different than a computed jump or conditional jump.
If this insn has multiple sets, then reemitting the
jump is nontrivial. So instead we just force rerecognition
and hope for the best. */
if (n_sets == 1)
{
rtx new_rtx, note;
new_rtx = <API key> (gen_jump (XEXP (src, 0)), insn);
JUMP_LABEL (new_rtx) = XEXP (src, 0);
LABEL_NUSES (XEXP (src, 0))++;
/* Make sure to copy over REG_NON_LOCAL_GOTO. */
note = find_reg_note (insn, REG_NON_LOCAL_GOTO, 0);
if (note)
{
XEXP (note, 1) = NULL_RTX;
REG_NOTES (new_rtx) = note;
}
<API key> (insn);
insn = new_rtx;
}
else
INSN_CODE (insn) = -1;
/* Do not bother deleting any unreachable code, let jump do it. */
cse_jumps_altered = true;
sets[i].rtl = 0;
}
/* If destination is volatile, invalidate it and then do no further
processing for this assignment. */
else if (do_not_record)
{
if (REG_P (dest) || GET_CODE (dest) == SUBREG)
invalidate (dest, VOIDmode);
else if (MEM_P (dest))
invalidate (dest, VOIDmode);
else if (GET_CODE (dest) == STRICT_LOW_PART
|| GET_CODE (dest) == ZERO_EXTRACT)
invalidate (XEXP (dest, 0), GET_MODE (dest));
sets[i].rtl = 0;
}
if (sets[i].rtl != 0 && dest != SET_DEST (sets[i].rtl))
sets[i].dest_hash = HASH (SET_DEST (sets[i].rtl), mode);
#ifdef HAVE_cc0
/* If setting CC0, record what it was set to, or a constant, if it
is equivalent to a constant. If it is being set to a floating-point
value, make a COMPARE with the appropriate constant of 0. If we
don't do this, later code can interpret this as a test against
const0_rtx, which can cause problems if we try to put it into an
insn as a floating-point operand. */
if (dest == cc0_rtx)
{
this_insn_cc0 = src_const && mode != VOIDmode ? src_const : src;
this_insn_cc0_mode = mode;
if (FLOAT_MODE_P (mode))
this_insn_cc0 = gen_rtx_COMPARE (VOIDmode, this_insn_cc0,
CONST0_RTX (mode));
}
#endif
}
/* Now enter all non-volatile source expressions in the hash table
if they are not already present.
Record their equivalence classes in src_elt.
This way we can insert the corresponding destinations into
the same classes even if the actual sources are no longer in them
(having been invalidated). */
if (src_eqv && src_eqv_elt == 0 && sets[0].rtl != 0 && ! src_eqv_volatile
&& ! rtx_equal_p (src_eqv, SET_DEST (sets[0].rtl)))
{
struct table_elt *elt;
struct table_elt *classp = sets[0].src_elt;
rtx dest = SET_DEST (sets[0].rtl);
enum machine_mode eqvmode = GET_MODE (dest);
if (GET_CODE (dest) == STRICT_LOW_PART)
{
eqvmode = GET_MODE (SUBREG_REG (XEXP (dest, 0)));
classp = 0;
}
if (insert_regs (src_eqv, classp, 0))
{
rehash_using_reg (src_eqv);
src_eqv_hash = HASH (src_eqv, eqvmode);
}
elt = insert (src_eqv, classp, src_eqv_hash, eqvmode);
elt->in_memory = src_eqv_in_memory;
src_eqv_elt = elt;
/* Check to see if src_eqv_elt is the same as a set source which
does not yet have an elt, and if so set the elt of the set source
to src_eqv_elt. */
for (i = 0; i < n_sets; i++)
if (sets[i].rtl && sets[i].src_elt == 0
&& rtx_equal_p (SET_SRC (sets[i].rtl), src_eqv))
sets[i].src_elt = src_eqv_elt;
}
for (i = 0; i < n_sets; i++)
if (sets[i].rtl && ! sets[i].src_volatile
&& ! rtx_equal_p (SET_SRC (sets[i].rtl), SET_DEST (sets[i].rtl)))
{
if (GET_CODE (SET_DEST (sets[i].rtl)) == STRICT_LOW_PART)
{
/* REG_EQUAL in setting a STRICT_LOW_PART
gives an equivalent for the entire destination register,
not just for the subreg being stored in now.
This is a more interesting equivalence, so we arrange later
to treat the entire reg as the destination. */
sets[i].src_elt = src_eqv_elt;
sets[i].src_hash = src_eqv_hash;
}
else
{
/* Insert source and constant equivalent into hash table, if not
already present. */
struct table_elt *classp = src_eqv_elt;
rtx src = sets[i].src;
rtx dest = SET_DEST (sets[i].rtl);
enum machine_mode mode
= GET_MODE (src) == VOIDmode ? GET_MODE (dest) : GET_MODE (src);
/* It's possible that we have a source value known to be
constant but don't have a REG_EQUAL note on the insn.
Lack of a note will mean src_eqv_elt will be NULL. This
can happen where we've generated a SUBREG to access a
CONST_INT that is already in a register in a wider mode.
Ensure that the source expression is put in the proper
constant class. */
if (!classp)
classp = sets[i].src_const_elt;
if (sets[i].src_elt == 0)
{
struct table_elt *elt;
/* Note that these insert_regs calls cannot remove
any of the src_elt's, because they would have failed to
match if not still valid. */
if (insert_regs (src, classp, 0))
{
rehash_using_reg (src);
sets[i].src_hash = HASH (src, mode);
}
elt = insert (src, classp, sets[i].src_hash, mode);
elt->in_memory = sets[i].src_in_memory;
sets[i].src_elt = classp = elt;
}
if (sets[i].src_const && sets[i].src_const_elt == 0
&& src != sets[i].src_const
&& ! rtx_equal_p (sets[i].src_const, src))
sets[i].src_elt = insert (sets[i].src_const, classp,
sets[i].src_const_hash, mode);
}
}
else if (sets[i].src_elt == 0)
/* If we did not insert the source into the hash table (e.g., it was
volatile), note the equivalence class for the REG_EQUAL value, if any,
so that the destination goes into that class. */
sets[i].src_elt = src_eqv_elt;
/* Record destination addresses in the hash table. This allows us to
check if they are invalidated by other sets. */
for (i = 0; i < n_sets; i++)
{
if (sets[i].rtl)
{
rtx x = sets[i].inner_dest;
struct table_elt *elt;
enum machine_mode mode;
unsigned hash;
if (MEM_P (x))
{
x = XEXP (x, 0);
mode = GET_MODE (x);
hash = HASH (x, mode);
elt = lookup (x, hash, mode);
if (!elt)
{
if (insert_regs (x, NULL, 0))
{
rtx dest = SET_DEST (sets[i].rtl);
rehash_using_reg (x);
hash = HASH (x, mode);
sets[i].dest_hash = HASH (dest, GET_MODE (dest));
}
elt = insert (x, NULL, hash, mode);
}
sets[i].dest_addr_elt = elt;
}
else
sets[i].dest_addr_elt = NULL;
}
}
<API key> (insn);
/* Some registers are invalidated by subroutine calls. Memory is
invalidated by non-constant calls. */
if (CALL_P (insn))
{
if (!(<API key> (insn)))
invalidate_memory ();
invalidate_for_call ();
}
/* Now invalidate everything set by this instruction.
If a SUBREG or other funny destination is being set,
sets[i].rtl is still nonzero, so here we invalidate the reg
a part of which is being set. */
for (i = 0; i < n_sets; i++)
if (sets[i].rtl)
{
/* We can't use the inner dest, because the mode associated with
a ZERO_EXTRACT is significant. */
rtx dest = SET_DEST (sets[i].rtl);
/* Needed for registers to remove the register from its
previous quantity's chain.
Needed for memory if this is a nonvarying address, unless
we have just done an invalidate_memory that covers even those. */
if (REG_P (dest) || GET_CODE (dest) == SUBREG)
invalidate (dest, VOIDmode);
else if (MEM_P (dest))
invalidate (dest, VOIDmode);
else if (GET_CODE (dest) == STRICT_LOW_PART
|| GET_CODE (dest) == ZERO_EXTRACT)
invalidate (XEXP (dest, 0), GET_MODE (dest));
}
/* A volatile ASM invalidates everything. */
if (NONJUMP_INSN_P (insn)
&& GET_CODE (PATTERN (insn)) == ASM_OPERANDS
&& MEM_VOLATILE_P (PATTERN (insn)))
flush_hash_table ();
/* Don't cse over a call to setjmp; on some machines (eg VAX)
the regs restored by the longjmp come from a later time
than the setjmp. */
if (CALL_P (insn) && find_reg_note (insn, REG_SETJMP, NULL))
{
flush_hash_table ();
goto done;
}
/* Make sure registers mentioned in destinations
are safe for use in an expression to be inserted.
This removes from the hash table
any invalid entry that refers to one of these registers.
We don't care about the return value from mention_regs because
we are going to hash the SET_DEST values unconditionally. */
for (i = 0; i < n_sets; i++)
{
if (sets[i].rtl)
{
rtx x = SET_DEST (sets[i].rtl);
if (!REG_P (x))
mention_regs (x);
else
{
/* We used to rely on all references to a register becoming
inaccessible when a register changes to a new quantity,
since that changes the hash code. However, that is not
safe, since after HASH_SIZE new quantities we get a
hash 'collision' of a register with its own invalid
entries. And since SUBREGs have been changed not to
change their hash code with the hash code of the register,
it wouldn't work any longer at all. So we have to check
for any invalid references lying around now.
This code is similar to the REG case in mention_regs,
but it knows that reg_tick has been incremented, and
it leaves reg_in_table as -1 . */
unsigned int regno = REGNO (x);
unsigned int endregno = END_REGNO (x);
unsigned int i;
for (i = regno; i < endregno; i++)
{
if (REG_IN_TABLE (i) >= 0)
{
remove_invalid_refs (i);
REG_IN_TABLE (i) = -1;
}
}
}
}
}
/* We may have just removed some of the src_elt's from the hash table.
So replace each one with the current head of the same class.
Also check if destination addresses have been removed. */
for (i = 0; i < n_sets; i++)
if (sets[i].rtl)
{
if (sets[i].dest_addr_elt
&& sets[i].dest_addr_elt->first_same_value == 0)
{
/* The elt was removed, which means this destination is not
valid after this instruction. */
sets[i].rtl = NULL_RTX;
}
else if (sets[i].src_elt && sets[i].src_elt->first_same_value == 0)
/* If elt was removed, find current head of same class,
or 0 if nothing remains of that class. */
{
struct table_elt *elt = sets[i].src_elt;
while (elt && elt->prev_same_value)
elt = elt->prev_same_value;
while (elt && elt->first_same_value == 0)
elt = elt->next_same_value;
sets[i].src_elt = elt ? elt->first_same_value : 0;
}
}
/* Now insert the destinations into their equivalence classes. */
for (i = 0; i < n_sets; i++)
if (sets[i].rtl)
{
rtx dest = SET_DEST (sets[i].rtl);
struct table_elt *elt;
/* Don't record value if we are not supposed to risk allocating
floating-point values in registers that might be wider than
memory. */
if ((flag_float_store
&& MEM_P (dest)
&& FLOAT_MODE_P (GET_MODE (dest)))
/* Don't record BLKmode values, because we don't know the
size of it, and can't be sure that other BLKmode values
have the same or smaller size. */
|| GET_MODE (dest) == BLKmode
/* If we didn't put a REG_EQUAL value or a source into the hash
table, there is no point is recording DEST. */
|| sets[i].src_elt == 0
/* If DEST is a paradoxical SUBREG and SRC is a ZERO_EXTEND
or SIGN_EXTEND, don't record DEST since it can cause
some tracking to be wrong.
??? Think about this more later. */
|| (<API key> (dest)
&& (GET_CODE (sets[i].src) == SIGN_EXTEND
|| GET_CODE (sets[i].src) == ZERO_EXTEND)))
continue;
/* STRICT_LOW_PART isn't part of the value BEING set,
and neither is the SUBREG inside it.
Note that in this case SETS[I].SRC_ELT is really SRC_EQV_ELT. */
if (GET_CODE (dest) == STRICT_LOW_PART)
dest = SUBREG_REG (XEXP (dest, 0));
if (REG_P (dest) || GET_CODE (dest) == SUBREG)
/* Registers must also be inserted into chains for quantities. */
if (insert_regs (dest, sets[i].src_elt, 1))
{
/* If `insert_regs' changes something, the hash code must be
recalculated. */
rehash_using_reg (dest);
sets[i].dest_hash = HASH (dest, GET_MODE (dest));
}
elt = insert (dest, sets[i].src_elt,
sets[i].dest_hash, GET_MODE (dest));
/* If this is a constant, insert the constant anchors with the
equivalent register-offset expressions using register DEST. */
if (targetm.const_anchor
&& REG_P (dest)
&& SCALAR_INT_MODE_P (GET_MODE (dest))
&& GET_CODE (sets[i].src_elt->exp) == CONST_INT)
<API key> (dest, sets[i].src_elt->exp, GET_MODE (dest));
elt->in_memory = (MEM_P (sets[i].inner_dest)
&& !MEM_READONLY_P (sets[i].inner_dest));
/* If we have (set (subreg:m1 (reg:m2 foo) 0) (bar:m1)), M1 is no
narrower than M2, and both M1 and M2 are the same number of words,
we are also doing (set (reg:m2 foo) (subreg:m2 (bar:m1) 0)) so
make that equivalence as well.
However, BAR may have equivalences for which gen_lowpart
will produce a simpler value than gen_lowpart applied to
BAR (e.g., if BAR was ZERO_EXTENDed from M2), so we will scan all
BAR's equivalences. If we don't get a simplified form, make
the SUBREG. It will not be used in an equivalence, but will
cause two similar assignments to be detected.
Note the loop below will find SUBREG_REG (DEST) since we have
already entered SRC and DEST of the SET in the table. */
if (GET_CODE (dest) == SUBREG
&& (((GET_MODE_SIZE (GET_MODE (SUBREG_REG (dest))) - 1)
/ UNITS_PER_WORD)
== (GET_MODE_SIZE (GET_MODE (dest)) - 1) / UNITS_PER_WORD)
&& (GET_MODE_SIZE (GET_MODE (dest))
>= GET_MODE_SIZE (GET_MODE (SUBREG_REG (dest))))
&& sets[i].src_elt != 0)
{
enum machine_mode new_mode = GET_MODE (SUBREG_REG (dest));
struct table_elt *elt, *classp = 0;
for (elt = sets[i].src_elt->first_same_value; elt;
elt = elt->next_same_value)
{
rtx new_src = 0;
unsigned src_hash;
struct table_elt *src_elt;
int byte = 0;
/* Ignore invalid entries. */
if (!REG_P (elt->exp)
&& ! exp_equiv_p (elt->exp, elt->exp, 1, false))
continue;
/* We may have already been playing subreg games. If the
mode is already correct for the destination, use it. */
if (GET_MODE (elt->exp) == new_mode)
new_src = elt->exp;
else
{
/* Calculate big endian correction for the SUBREG_BYTE.
We have already checked that M1 (GET_MODE (dest))
is not narrower than M2 (new_mode). */
if (BYTES_BIG_ENDIAN)
byte = (GET_MODE_SIZE (GET_MODE (dest))
- GET_MODE_SIZE (new_mode));
new_src = simplify_gen_subreg (new_mode, elt->exp,
GET_MODE (dest), byte);
}
/* The call to simplify_gen_subreg fails if the value
is VOIDmode, yet we can't do any simplification, e.g.
for EXPR_LISTs denoting function call results.
It is invalid to construct a SUBREG with a VOIDmode
SUBREG_REG, hence a zero new_src means we can't do
this substitution. */
if (! new_src)
continue;
src_hash = HASH (new_src, new_mode);
src_elt = lookup (new_src, src_hash, new_mode);
/* Put the new source in the hash table is if isn't
already. */
if (src_elt == 0)
{
if (insert_regs (new_src, classp, 0))
{
rehash_using_reg (new_src);
src_hash = HASH (new_src, new_mode);
}
src_elt = insert (new_src, classp, src_hash, new_mode);
src_elt->in_memory = elt->in_memory;
}
else if (classp && classp != src_elt->first_same_value)
/* Show that two things that we've seen before are
actually the same. */
merge_equiv_classes (src_elt, classp);
classp = src_elt->first_same_value;
/* Ignore invalid entries. */
while (classp
&& !REG_P (classp->exp)
&& ! exp_equiv_p (classp->exp, classp->exp, 1, false))
classp = classp->next_same_value;
}
}
}
/* Special handling for (set REG0 REG1) where REG0 is the
"cheapest", cheaper than REG1. After cse, REG1 will probably not
be used in the sequel, so (if easily done) change this insn to
(set REG1 REG0) and replace REG1 with REG0 in the previous insn
that computed their value. Then REG1 will become a dead store
and won't cloud the situation for later optimizations.
Do not make this change if REG1 is a hard register, because it will
then be used in the sequel and we may be changing a two-operand insn
into a three-operand insn.
Also do not do this if we are operating on a copy of INSN. */
if (n_sets == 1 && sets[0].rtl)
<API key> (sets[0].rtl, insn);
done:;
}
/* Remove from the hash table all expressions that reference memory. */
static void
invalidate_memory (void)
{
int i;
struct table_elt *p, *next;
for (i = 0; i < HASH_SIZE; i++)
for (p = table[i]; p; p = next)
{
next = p->next_same_hash;
if (p->in_memory)
remove_from_table (p, i);
}
}
/* Perform invalidation on the basis of everything about INSN,
except for invalidating the actual places that are SET in it.
This includes the places CLOBBERed, and anything that might
alias with something that is SET or CLOBBERed. */
static void
<API key> (rtx insn)
{
rtx x = PATTERN (insn);
if (GET_CODE (x) == CLOBBER)
{
rtx ref = XEXP (x, 0);
if (ref)
{
if (REG_P (ref) || GET_CODE (ref) == SUBREG
|| MEM_P (ref))
invalidate (ref, VOIDmode);
else if (GET_CODE (ref) == STRICT_LOW_PART
|| GET_CODE (ref) == ZERO_EXTRACT)
invalidate (XEXP (ref, 0), GET_MODE (ref));
}
}
else if (GET_CODE (x) == PARALLEL)
{
int i;
for (i = XVECLEN (x, 0) - 1; i >= 0; i
{
rtx y = XVECEXP (x, 0, i);
if (GET_CODE (y) == CLOBBER)
{
rtx ref = XEXP (y, 0);
if (REG_P (ref) || GET_CODE (ref) == SUBREG
|| MEM_P (ref))
invalidate (ref, VOIDmode);
else if (GET_CODE (ref) == STRICT_LOW_PART
|| GET_CODE (ref) == ZERO_EXTRACT)
invalidate (XEXP (ref, 0), GET_MODE (ref));
}
}
}
}
/* Perform invalidation on the basis of everything about INSN.
This includes the places CLOBBERed, and anything that might
alias with something that is SET or CLOBBERed. */
static void
<API key> (rtx insn)
{
rtx tem;
rtx x = PATTERN (insn);
if (CALL_P (insn))
{
for (tem = <API key> (insn); tem; tem = XEXP (tem, 1))
if (GET_CODE (XEXP (tem, 0)) == CLOBBER)
invalidate (SET_DEST (XEXP (tem, 0)), VOIDmode);
}
/* Ensure we invalidate the destination register of a CALL insn.
This is necessary for machines where this register is a fixed_reg,
because no other code would invalidate it. */
if (GET_CODE (x) == SET && GET_CODE (SET_SRC (x)) == CALL)
invalidate (SET_DEST (x), VOIDmode);
else if (GET_CODE (x) == PARALLEL)
{
int i;
for (i = XVECLEN (x, 0) - 1; i >= 0; i
{
rtx y = XVECEXP (x, 0, i);
if (GET_CODE (y) == CLOBBER)
{
rtx clobbered = XEXP (y, 0);
if (REG_P (clobbered)
|| GET_CODE (clobbered) == SUBREG)
invalidate (clobbered, VOIDmode);
else if (GET_CODE (clobbered) == STRICT_LOW_PART
|| GET_CODE (clobbered) == ZERO_EXTRACT)
invalidate (XEXP (clobbered, 0), GET_MODE (clobbered));
}
else if (GET_CODE (y) == SET && GET_CODE (SET_SRC (y)) == CALL)
invalidate (SET_DEST (y), VOIDmode);
}
}
}
/* Process X, part of the REG_NOTES of an insn. Look at any REG_EQUAL notes
and replace any registers in them with either an equivalent constant
or the canonical form of the register. If we are inside an address,
only do this if the address remains valid.
OBJECT is 0 except when within a MEM in which case it is the MEM.
Return the replacement for X. */
static rtx
cse_process_notes_1 (rtx x, rtx object, bool *changed)
{
enum rtx_code code = GET_CODE (x);
const char *fmt = GET_RTX_FORMAT (code);
int i;
switch (code)
{
case CONST_INT:
case CONST:
case SYMBOL_REF:
case LABEL_REF:
case CONST_DOUBLE:
case CONST_FIXED:
case CONST_VECTOR:
case PC:
case CC0:
case LO_SUM:
return x;
case MEM:
validate_change (x, &XEXP (x, 0),
cse_process_notes (XEXP (x, 0), x, changed), 0);
return x;
case EXPR_LIST:
case INSN_LIST:
if (REG_NOTE_KIND (x) == REG_EQUAL)
XEXP (x, 0) = cse_process_notes (XEXP (x, 0), NULL_RTX, changed);
if (XEXP (x, 1))
XEXP (x, 1) = cse_process_notes (XEXP (x, 1), NULL_RTX, changed);
return x;
case SIGN_EXTEND:
case ZERO_EXTEND:
case SUBREG:
{
rtx new_rtx = cse_process_notes (XEXP (x, 0), object, changed);
/* We don't substitute VOIDmode constants into these rtx,
since they would impede folding. */
if (GET_MODE (new_rtx) != VOIDmode)
validate_change (object, &XEXP (x, 0), new_rtx, 0);
return x;
}
case REG:
i = REG_QTY (REGNO (x));
/* Return a constant or a constant register. */
if (REGNO_QTY_VALID_P (REGNO (x)))
{
struct qty_table_elem *ent = &qty_table[i];
if (ent->const_rtx != NULL_RTX
&& (CONSTANT_P (ent->const_rtx)
|| REG_P (ent->const_rtx)))
{
rtx new_rtx = gen_lowpart (GET_MODE (x), ent->const_rtx);
if (new_rtx)
return copy_rtx (new_rtx);
}
}
/* Otherwise, canonicalize this register. */
return canon_reg (x, NULL_RTX);
default:
break;
}
for (i = 0; i < GET_RTX_LENGTH (code); i++)
if (fmt[i] == 'e')
validate_change (object, &XEXP (x, i),
cse_process_notes (XEXP (x, i), object, changed), 0);
return x;
}
static rtx
cse_process_notes (rtx x, rtx object, bool *changed)
{
rtx new_rtx = cse_process_notes_1 (x, object, changed);
if (new_rtx != x)
*changed = true;
return new_rtx;
}
/* Find a path in the CFG, starting with FIRST_BB to perform CSE on.
DATA is a pointer to a struct <API key>, that is used to
describe the path.
It is filled with a queue of basic blocks, starting with FIRST_BB
and following a trace through the CFG.
If all paths starting at FIRST_BB have been followed, or no new path
starting at FIRST_BB can be constructed, this function returns FALSE.
Otherwise, DATA->path is filled and the function returns TRUE indicating
that a path to follow was found.
If FOLLOW_JUMPS is false, the maximum path length is 1 and the only
block in the path will be FIRST_BB. */
static bool
cse_find_path (basic_block first_bb, struct <API key> *data,
int follow_jumps)
{
basic_block bb;
edge e;
int path_size;
SET_BIT (<API key>, first_bb->index);
/* See if there is a previous path. */
path_size = data->path_size;
/* There is a previous path. Make sure it started with FIRST_BB. */
if (path_size)
gcc_assert (data->path[0].bb == first_bb);
/* There was only one basic block in the last path. Clear the path and
return, so that paths starting at another basic block can be tried. */
if (path_size == 1)
{
path_size = 0;
goto done;
}
/* If the path was empty from the beginning, construct a new path. */
if (path_size == 0)
data->path[path_size++].bb = first_bb;
else
{
/* Otherwise, path_size must be equal to or greater than 2, because
a previous path exists that is at least two basic blocks long.
Update the previous branch path, if any. If the last branch was
previously along the branch edge, take the fallthrough edge now. */
while (path_size >= 2)
{
basic_block last_bb_in_path, previous_bb_in_path;
edge e;
--path_size;
last_bb_in_path = data->path[path_size].bb;
previous_bb_in_path = data->path[path_size - 1].bb;
/* If we previously followed a path along the branch edge, try
the fallthru edge now. */
if (EDGE_COUNT (previous_bb_in_path->succs) == 2
&& any_condjump_p (BB_END (previous_bb_in_path))
&& (e = find_edge (previous_bb_in_path, last_bb_in_path))
&& e == BRANCH_EDGE (previous_bb_in_path))
{
bb = FALLTHRU_EDGE (previous_bb_in_path)->dest;
if (bb != EXIT_BLOCK_PTR
&& single_pred_p (bb)
/* We used to assert here that we would only see blocks
that we have not visited yet. But we may end up
visiting basic blocks twice if the CFG has changed
in this run of cse_main, because when the CFG changes
the topological sort of the CFG also changes. A basic
blocks that previously had more than two predecessors
may now have a single predecessor, and become part of
a path that starts at another basic block.
We still want to visit each basic block only once, so
halt the path here if we have already visited BB. */
&& !TEST_BIT (<API key>, bb->index))
{
SET_BIT (<API key>, bb->index);
data->path[path_size++].bb = bb;
break;
}
}
data->path[path_size].bb = NULL;
}
/* If only one block remains in the path, bail. */
if (path_size == 1)
{
path_size = 0;
goto done;
}
}
/* Extend the path if possible. */
if (follow_jumps)
{
bb = data->path[path_size - 1].bb;
while (bb && path_size < PARAM_VALUE (<API key>))
{
if (single_succ_p (bb))
e = single_succ_edge (bb);
else if (EDGE_COUNT (bb->succs) == 2
&& any_condjump_p (BB_END (bb)))
{
/* First try to follow the branch. If that doesn't lead
to a useful path, follow the fallthru edge. */
e = BRANCH_EDGE (bb);
if (!single_pred_p (e->dest))
e = FALLTHRU_EDGE (bb);
}
else
e = NULL;
if (e
&& !((e->flags & EDGE_ABNORMAL_CALL) && cfun->has_nonlocal_label)
&& e->dest != EXIT_BLOCK_PTR
&& single_pred_p (e->dest)
/* Avoid visiting basic blocks twice. The large comment
above explains why this can happen. */
&& !TEST_BIT (<API key>, e->dest->index))
{
basic_block bb2 = e->dest;
SET_BIT (<API key>, bb2->index);
data->path[path_size++].bb = bb2;
bb = bb2;
}
else
bb = NULL;
}
}
done:
data->path_size = path_size;
return path_size != 0;
}
/* Dump the path in DATA to file F. NSETS is the number of sets
in the path. */
static void
cse_dump_path (struct <API key> *data, int nsets, FILE *f)
{
int path_entry;
fprintf (f, ";; Following path with %d sets: ", nsets);
for (path_entry = 0; path_entry < data->path_size; path_entry++)
fprintf (f, "%d ", (data->path[path_entry].bb)->index);
fputc ('\n', dump_file);
fflush (f);
}
/* Return true if BB has exception handling successor edges. */
static bool
have_eh_succ_edges (basic_block bb)
{
edge e;
edge_iterator ei;
FOR_EACH_EDGE (e, ei, bb->succs)
if (e->flags & EDGE_EH)
return true;
return false;
}
/* Scan to the end of the path described by DATA. Return an estimate of
the total number of SETs of all insns in the path. */
static void
cse_prescan_path (struct <API key> *data)
{
int nsets = 0;
int path_size = data->path_size;
int path_entry;
/* Scan to end of each basic block in the path. */
for (path_entry = 0; path_entry < path_size; path_entry++)
{
basic_block bb;
rtx insn;
bb = data->path[path_entry].bb;
FOR_BB_INSNS (bb, insn)
{
if (!INSN_P (insn))
continue;
/* A PARALLEL can have lots of SETs in it,
especially if it is really an ASM_OPERANDS. */
if (GET_CODE (PATTERN (insn)) == PARALLEL)
nsets += XVECLEN (PATTERN (insn), 0);
else
nsets += 1;
}
}
data->nsets = nsets;
}
/* Process a single extended basic block described by EBB_DATA. */
static void
<API key> (struct <API key> *ebb_data)
{
int path_size = ebb_data->path_size;
int path_entry;
int num_insns = 0;
/* Allocate the space needed by qty_table. */
qty_table = XNEWVEC (struct qty_table_elem, max_qty);
new_basic_block ();
cse_ebb_live_in = df_get_live_in (ebb_data->path[0].bb);
cse_ebb_live_out = df_get_live_out (ebb_data->path[path_size - 1].bb);
for (path_entry = 0; path_entry < path_size; path_entry++)
{
basic_block bb;
rtx insn;
bb = ebb_data->path[path_entry].bb;
/* Invalidate recorded information for eh regs if there is an EH
edge pointing to that bb. */
if (bb_has_eh_pred (bb))
{
df_ref *def_rec;
for (def_rec = <API key> (bb->index); *def_rec; def_rec++)
{
df_ref def = *def_rec;
if (DF_REF_FLAGS (def) & DF_REF_AT_TOP)
invalidate (DF_REF_REG (def), GET_MODE (DF_REF_REG (def)));
}
}
<API key> = <API key> (bb);
FOR_BB_INSNS (bb, insn)
{
/* If we have processed 1,000 insns, flush the hash table to
avoid extreme quadratic behavior. We must not include NOTEs
in the count since there may be more of them when generating
debugging information. If we clear the table at different
times, code generated with -g -O might be different than code
generated with -O but not -g.
FIXME: This is a real kludge and needs to be done some other
way. */
if (NONDEBUG_INSN_P (insn)
&& num_insns++ > PARAM_VALUE (PARAM_MAX_CSE_INSNS))
{
flush_hash_table ();
num_insns = 0;
}
if (INSN_P (insn))
{
/* Process notes first so we have all notes in canonical forms
when looking for duplicate operations. */
if (REG_NOTES (insn))
{
bool changed = false;
REG_NOTES (insn) = cse_process_notes (REG_NOTES (insn),
NULL_RTX, &changed);
if (changed)
df_notes_rescan (insn);
}
cse_insn (insn);
/* If we haven't already found an insn where we added a LABEL_REF,
check this one. */
if (INSN_P (insn) && !recorded_label_ref
&& for_each_rtx (&PATTERN (insn), check_for_label_ref,
(void *) insn))
recorded_label_ref = true;
#ifdef HAVE_cc0
if (NONDEBUG_INSN_P (insn))
{
/* If the previous insn sets CC0 and this insn no
longer references CC0, delete the previous insn.
Here we use fact that nothing expects CC0 to be
valid over an insn, which is true until the final
pass. */
rtx prev_insn, tem;
prev_insn = <API key> (insn);
if (prev_insn && NONJUMP_INSN_P (prev_insn)
&& (tem = single_set (prev_insn)) != NULL_RTX
&& SET_DEST (tem) == cc0_rtx
&& ! reg_mentioned_p (cc0_rtx, PATTERN (insn)))
delete_insn (prev_insn);
/* If this insn is not the last insn in the basic
block, it will be PREV_INSN(insn) in the next
iteration. If we recorded any CC0-related
information for this insn, remember it. */
if (insn != BB_END (bb))
{
prev_insn_cc0 = this_insn_cc0;
prev_insn_cc0_mode = this_insn_cc0_mode;
}
}
#endif
}
}
/* With non-call exceptions, we are not always able to update
the CFG properly inside cse_insn. So clean up possibly
redundant EH edges here. */
if (cfun-><API key> && have_eh_succ_edges (bb))
cse_cfg_altered |= purge_dead_edges (bb);
/* If we changed a conditional jump, we may have terminated
the path we are following. Check that by verifying that
the edge we would take still exists. If the edge does
not exist anymore, purge the remainder of the path.
Note that this will cause us to return to the caller. */
if (path_entry < path_size - 1)
{
basic_block next_bb = ebb_data->path[path_entry + 1].bb;
if (!find_edge (bb, next_bb))
{
do
{
path_size
/* If we truncate the path, we must also reset the
visited bit on the remaining blocks in the path,
or we will never visit them at all. */
RESET_BIT (<API key>,
ebb_data->path[path_size].bb->index);
ebb_data->path[path_size].bb = NULL;
}
while (path_size - 1 != path_entry);
ebb_data->path_size = path_size;
}
}
/* If this is a conditional jump insn, record any known
equivalences due to the condition being tested. */
insn = BB_END (bb);
if (path_entry < path_size - 1
&& JUMP_P (insn)
&& single_set (insn)
&& any_condjump_p (insn))
{
basic_block next_bb = ebb_data->path[path_entry + 1].bb;
bool taken = (next_bb == BRANCH_EDGE (bb)->dest);
record_jump_equiv (insn, taken);
}
#ifdef HAVE_cc0
/* Clear the CC0-tracking related insns, they can't provide
useful information across basic block boundaries. */
prev_insn_cc0 = 0;
#endif
}
gcc_assert (next_qty <= max_qty);
free (qty_table);
}
/* Perform cse on the instructions of a function.
F is the first instruction.
NREGS is one plus the highest pseudo-reg number used in the instruction.
Return 2 if jump optimizations should be redone due to simplifications
in conditional jump instructions.
Return 1 if the CFG should be cleaned up because it has been modified.
Return 0 otherwise. */
static int
cse_main (rtx f ATTRIBUTE_UNUSED, int nregs)
{
struct <API key> ebb_data;
basic_block bb;
int *rc_order = XNEWVEC (int, last_basic_block);
int i, n_blocks;
df_set_flags (DF_LR_RUN_DCE);
df_analyze ();
df_set_flags (<API key>);
reg_scan (get_insns (), max_reg_num ());
init_cse_reg_info (nregs);
ebb_data.path = XNEWVEC (struct branch_path,
PARAM_VALUE (<API key>));
cse_cfg_altered = false;
cse_jumps_altered = false;
recorded_label_ref = false;
<API key> = 0;
<API key> = 0;
ebb_data.path_size = 0;
ebb_data.nsets = 0;
rtl_hooks = cse_rtl_hooks;
init_recog ();
init_alias_analysis ();
reg_eqv_table = XNEWVEC (struct reg_eqv_elem, nregs);
/* Set up the table of already visited basic blocks. */
<API key> = sbitmap_alloc (last_basic_block);
sbitmap_zero (<API key>);
/* Loop over basic blocks in reverse completion order (RPO),
excluding the ENTRY and EXIT blocks. */
n_blocks = <API key> (NULL, rc_order, false);
i = 0;
while (i < n_blocks)
{
/* Find the first block in the RPO queue that we have not yet
processed before. */
do
{
bb = BASIC_BLOCK (rc_order[i++]);
}
while (TEST_BIT (<API key>, bb->index)
&& i < n_blocks);
/* Find all paths starting with BB, and process them. */
while (cse_find_path (bb, &ebb_data, <API key>))
{
/* Pre-scan the path. */
cse_prescan_path (&ebb_data);
/* If this basic block has no sets, skip it. */
if (ebb_data.nsets == 0)
continue;
/* Get a reasonable estimate for the maximum number of qty's
needed for this path. For this, we take the number of sets
and multiply that by MAX_RECOG_OPERANDS. */
max_qty = ebb_data.nsets * MAX_RECOG_OPERANDS;
/* Dump the path we're about to process. */
if (dump_file)
cse_dump_path (&ebb_data, ebb_data.nsets, dump_file);
<API key> (&ebb_data);
}
}
/* Clean up. */
end_alias_analysis ();
free (reg_eqv_table);
free (ebb_data.path);
sbitmap_free (<API key>);
free (rc_order);
rtl_hooks = general_rtl_hooks;
if (cse_jumps_altered || recorded_label_ref)
return 2;
else if (cse_cfg_altered)
return 1;
else
return 0;
}
/* Called via for_each_rtx to see if an insn is using a LABEL_REF for
which there isn't a REG_LABEL_OPERAND note.
Return one if so. DATA is the insn. */
static int
check_for_label_ref (rtx *rtl, void *data)
{
rtx insn = (rtx) data;
/* If this insn uses a LABEL_REF and there isn't a REG_LABEL_OPERAND
note for it, we must rerun jump since it needs to place the note. If
this is a LABEL_REF for a CODE_LABEL that isn't in the insn chain,
don't do this since no REG_LABEL_OPERAND will be added. */
return (GET_CODE (*rtl) == LABEL_REF
&& ! <API key> (*rtl)
&& (!JUMP_P (insn)
|| !<API key> (XEXP (*rtl, 0), insn))
&& LABEL_P (XEXP (*rtl, 0))
&& INSN_UID (XEXP (*rtl, 0)) != 0
&& ! find_reg_note (insn, REG_LABEL_OPERAND, XEXP (*rtl, 0)));
}
/* Count the number of times registers are used (not set) in X.
COUNTS is an array in which we accumulate the count, INCR is how much
we count each register usage.
Don't count a usage of DEST, which is the SET_DEST of a SET which
contains X in its SET_SRC. This is because such a SET does not
modify the liveness of DEST.
DEST is set to pc_rtx for a trapping insn, or for an insn with side effects.
We must then count uses of a SET_DEST regardless, because the insn can't be
deleted here. */
static void
count_reg_usage (rtx x, int *counts, rtx dest, int incr)
{
enum rtx_code code;
rtx note;
const char *fmt;
int i, j;
if (x == 0)
return;
switch (code = GET_CODE (x))
{
case REG:
if (x != dest)
counts[REGNO (x)] += incr;
return;
case PC:
case CC0:
case CONST:
case CONST_INT:
case CONST_DOUBLE:
case CONST_FIXED:
case CONST_VECTOR:
case SYMBOL_REF:
case LABEL_REF:
return;
case CLOBBER:
/* If we are clobbering a MEM, mark any registers inside the address
as being used. */
if (MEM_P (XEXP (x, 0)))
count_reg_usage (XEXP (XEXP (x, 0), 0), counts, NULL_RTX, incr);
return;
case SET:
/* Unless we are setting a REG, count everything in SET_DEST. */
if (!REG_P (SET_DEST (x)))
count_reg_usage (SET_DEST (x), counts, NULL_RTX, incr);
count_reg_usage (SET_SRC (x), counts,
dest ? dest : SET_DEST (x),
incr);
return;
case DEBUG_INSN:
return;
case CALL_INSN:
case INSN:
case JUMP_INSN:
/* We expect dest to be NULL_RTX here. If the insn may trap,
or if it cannot be deleted due to side-effects, mark this fact
by setting DEST to pc_rtx. */
if (insn_could_throw_p (x) || side_effects_p (PATTERN (x)))
dest = pc_rtx;
if (code == CALL_INSN)
count_reg_usage (<API key> (x), counts, dest, incr);
count_reg_usage (PATTERN (x), counts, dest, incr);
/* Things used in a REG_EQUAL note aren't dead since loop may try to
use them. */
note = <API key> (x);
if (note)
{
rtx eqv = XEXP (note, 0);
if (GET_CODE (eqv) == EXPR_LIST)
/* This REG_EQUAL note describes the result of a function call.
Process all the arguments. */
do
{
count_reg_usage (XEXP (eqv, 0), counts, dest, incr);
eqv = XEXP (eqv, 1);
}
while (eqv && GET_CODE (eqv) == EXPR_LIST);
else
count_reg_usage (eqv, counts, dest, incr);
}
return;
case EXPR_LIST:
if (REG_NOTE_KIND (x) == REG_EQUAL
|| (REG_NOTE_KIND (x) != REG_NONNEG && GET_CODE (XEXP (x,0)) == USE)
/* FUNCTION_USAGE expression lists may include (CLOBBER (mem /u)),
involving registers in the address. */
|| GET_CODE (XEXP (x, 0)) == CLOBBER)
count_reg_usage (XEXP (x, 0), counts, NULL_RTX, incr);
count_reg_usage (XEXP (x, 1), counts, NULL_RTX, incr);
return;
case ASM_OPERANDS:
/* Iterate over just the inputs, not the constraints as well. */
for (i = <API key> (x) - 1; i >= 0; i
count_reg_usage (ASM_OPERANDS_INPUT (x, i), counts, dest, incr);
return;
case INSN_LIST:
gcc_unreachable ();
default:
break;
}
fmt = GET_RTX_FORMAT (code);
for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i
{
if (fmt[i] == 'e')
count_reg_usage (XEXP (x, i), counts, dest, incr);
else if (fmt[i] == 'E')
for (j = XVECLEN (x, i) - 1; j >= 0; j
count_reg_usage (XVECEXP (x, i, j), counts, dest, incr);
}
}
/* Return true if X is a dead register. */
static inline int
is_dead_reg (rtx x, int *counts)
{
return (REG_P (x)
&& REGNO (x) >= <API key>
&& counts[REGNO (x)] == 0);
}
/* Return true if set is live. */
static bool
set_live_p (rtx set, rtx insn ATTRIBUTE_UNUSED, /* Only used with HAVE_cc0. */
int *counts)
{
#ifdef HAVE_cc0
rtx tem;
#endif
if (set_noop_p (set))
;
#ifdef HAVE_cc0
else if (GET_CODE (SET_DEST (set)) == CC0
&& !side_effects_p (SET_SRC (set))
&& ((tem = <API key> (insn)) == NULL_RTX
|| !INSN_P (tem)
|| !reg_referenced_p (cc0_rtx, PATTERN (tem))))
return false;
#endif
else if (!is_dead_reg (SET_DEST (set), counts)
|| side_effects_p (SET_SRC (set)))
return true;
return false;
}
/* Return true if insn is live. */
static bool
insn_live_p (rtx insn, int *counts)
{
int i;
if (insn_could_throw_p (insn))
return true;
else if (GET_CODE (PATTERN (insn)) == SET)
return set_live_p (PATTERN (insn), insn, counts);
else if (GET_CODE (PATTERN (insn)) == PARALLEL)
{
for (i = XVECLEN (PATTERN (insn), 0) - 1; i >= 0; i
{
rtx elt = XVECEXP (PATTERN (insn), 0, i);
if (GET_CODE (elt) == SET)
{
if (set_live_p (elt, insn, counts))
return true;
}
else if (GET_CODE (elt) != CLOBBER && GET_CODE (elt) != USE)
return true;
}
return false;
}
else if (DEBUG_INSN_P (insn))
{
rtx next;
for (next = NEXT_INSN (insn); next; next = NEXT_INSN (next))
if (NOTE_P (next))
continue;
else if (!DEBUG_INSN_P (next))
return true;
else if (<API key> (insn) == <API key> (next))
return false;
return true;
}
else
return true;
}
/* Count the number of stores into pseudo. Callback for note_stores. */
static void
count_stores (rtx x, const_rtx set ATTRIBUTE_UNUSED, void *data)
{
int *counts = (int *) data;
if (REG_P (x) && REGNO (x) >= <API key>)
counts[REGNO (x)]++;
}
struct <API key>
{
int *counts;
rtx *replacements;
bool seen_repl;
};
/* Return if a DEBUG_INSN needs to be reset because some dead
pseudo doesn't have a replacement. Callback for for_each_rtx. */
static int
is_dead_debug_insn (rtx *loc, void *data)
{
rtx x = *loc;
struct <API key> *ddid = (struct <API key> *) data;
if (is_dead_reg (x, ddid->counts))
{
if (ddid->replacements && ddid->replacements[REGNO (x)] != NULL_RTX)
ddid->seen_repl = true;
else
return 1;
}
return 0;
}
/* Replace a dead pseudo in a DEBUG_INSN with replacement DEBUG_EXPR.
Callback for <API key>. */
static rtx
replace_dead_reg (rtx x, const_rtx old_rtx ATTRIBUTE_UNUSED, void *data)
{
rtx *replacements = (rtx *) data;
if (REG_P (x)
&& REGNO (x) >= <API key>
&& replacements[REGNO (x)] != NULL_RTX)
{
if (GET_MODE (x) == GET_MODE (replacements[REGNO (x)]))
return replacements[REGNO (x)];
return lowpart_subreg (GET_MODE (x), replacements[REGNO (x)],
GET_MODE (replacements[REGNO (x)]));
}
return NULL_RTX;
}
/* Scan all the insns and delete any that are dead; i.e., they store a register
that is never used or they copy a register to itself.
This is used to remove insns made obviously dead by cse, loop or other
optimizations. It improves the heuristics in loop since it won't try to
move dead invariants out of loops or make givs for dead quantities. The
remaining passes of the compilation are also sped up. */
int
<API key> (rtx insns, int nreg)
{
int *counts;
rtx insn, prev;
rtx *replacements = NULL;
int ndead = 0;
timevar_push (<API key>);
/* First count the number of times each register is used. */
if (<API key>)
{
counts = XCNEWVEC (int, nreg * 3);
for (insn = insns; insn; insn = NEXT_INSN (insn))
if (DEBUG_INSN_P (insn))
count_reg_usage (<API key> (insn), counts + nreg,
NULL_RTX, 1);
else if (INSN_P (insn))
{
count_reg_usage (insn, counts, NULL_RTX, 1);
note_stores (PATTERN (insn), count_stores, counts + nreg * 2);
}
/* If there can be debug insns, COUNTS are 3 consecutive arrays.
First one counts how many times each pseudo is used outside
of debug insns, second counts how many times each pseudo is
used in debug insns and third counts how many times a pseudo
is stored. */
}
else
{
counts = XCNEWVEC (int, nreg);
for (insn = insns; insn; insn = NEXT_INSN (insn))
if (INSN_P (insn))
count_reg_usage (insn, counts, NULL_RTX, 1);
/* If no debug insns can be present, COUNTS is just an array
which counts how many times each pseudo is used. */
}
/* Go from the last insn to the first and delete insns that only set unused
registers or copy a register to itself. As we delete an insn, remove
usage counts for registers it uses.
The first jump optimization pass may leave a real insn as the last
insn in the function. We must not skip that insn or we may end
up deleting code that is not really dead.
If some otherwise unused register is only used in DEBUG_INSNs,
try to create a DEBUG_EXPR temporary and emit a DEBUG_INSN before
the setter. Then go through DEBUG_INSNs and if a DEBUG_EXPR
has been created for the unused register, replace it with
the DEBUG_EXPR, otherwise reset the DEBUG_INSN. */
for (insn = get_last_insn (); insn; insn = prev)
{
int live_insn = 0;
prev = PREV_INSN (insn);
if (!INSN_P (insn))
continue;
live_insn = insn_live_p (insn, counts);
/* If this is a dead insn, delete it and show registers in it aren't
being used. */
if (! live_insn && dbg_cnt (delete_trivial_dead))
{
if (DEBUG_INSN_P (insn))
count_reg_usage (<API key> (insn), counts + nreg,
NULL_RTX, -1);
else
{
rtx set;
if (<API key>
&& (set = single_set (insn)) != NULL_RTX
&& is_dead_reg (SET_DEST (set), counts)
/* Used at least once in some DEBUG_INSN. */
&& counts[REGNO (SET_DEST (set)) + nreg] > 0
/* And set exactly once. */
&& counts[REGNO (SET_DEST (set)) + nreg * 2] == 1
&& !side_effects_p (SET_SRC (set))
&& asm_noperands (PATTERN (insn)) < 0)
{
rtx dval, bind;
/* Create DEBUG_EXPR (and DEBUG_EXPR_DECL). */
dval = <API key> (SET_DEST (set));
/* Emit a debug bind insn before the insn in which
reg dies. */
bind = <API key> (GET_MODE (SET_DEST (set)),
<API key> (dval),
SET_SRC (set),
<API key>);
count_reg_usage (bind, counts + nreg, NULL_RTX, 1);
bind = <API key> (bind, insn);
df_insn_rescan (bind);
if (replacements == NULL)
replacements = XCNEWVEC (rtx, nreg);
replacements[REGNO (SET_DEST (set))] = dval;
}
count_reg_usage (insn, counts, NULL_RTX, -1);
ndead++;
}
<API key> (insn);
}
}
if (<API key>)
{
struct <API key> ddid;
ddid.counts = counts;
ddid.replacements = replacements;
for (insn = get_last_insn (); insn; insn = PREV_INSN (insn))
if (DEBUG_INSN_P (insn))
{
/* If this debug insn references a dead register that wasn't replaced
with an DEBUG_EXPR, reset the DEBUG_INSN. */
ddid.seen_repl = false;
if (for_each_rtx (&<API key> (insn),
is_dead_debug_insn, &ddid))
{
<API key> (insn) = <API key> ();
df_insn_rescan (insn);
}
else if (ddid.seen_repl)
{
<API key> (insn)
= <API key> (<API key> (insn),
NULL_RTX, replace_dead_reg,
replacements);
df_insn_rescan (insn);
}
}
free (replacements);
}
if (dump_file && ndead)
fprintf (dump_file, "Deleted %i trivially dead insns\n",
ndead);
/* Clean up. */
free (counts);
timevar_pop (<API key>);
return ndead;
}
/* This function is called via for_each_rtx. The argument, NEWREG, is
a condition code register with the desired mode. If we are looking
at the same register in a different mode, replace it with
NEWREG. */
static int
cse_change_cc_mode (rtx *loc, void *data)
{
struct change_cc_mode_args* args = (struct change_cc_mode_args*)data;
if (*loc
&& REG_P (*loc)
&& REGNO (*loc) == REGNO (args->newreg)
&& GET_MODE (*loc) != GET_MODE (args->newreg))
{
validate_change (args->insn, loc, args->newreg, 1);
return -1;
}
return 0;
}
/* Change the mode of any reference to the register REGNO (NEWREG) to
GET_MODE (NEWREG) in INSN. */
static void
<API key> (rtx insn, rtx newreg)
{
struct change_cc_mode_args args;
int success;
if (!INSN_P (insn))
return;
args.insn = insn;
args.newreg = newreg;
for_each_rtx (&PATTERN (insn), cse_change_cc_mode, &args);
for_each_rtx (®_NOTES (insn), cse_change_cc_mode, &args);
/* If the following assertion was triggered, there is most probably
something wrong with the cc_modes_compatible back end function.
CC modes only can be considered compatible if the insn - with the mode
replaced by any of the compatible modes - can still be recognized. */
success = apply_change_group ();
gcc_assert (success);
}
/* Change the mode of any reference to the register REGNO (NEWREG) to
GET_MODE (NEWREG), starting at START. Stop before END. Stop at
any instruction which modifies NEWREG. */
static void
<API key> (rtx start, rtx end, rtx newreg)
{
rtx insn;
for (insn = start; insn != end; insn = NEXT_INSN (insn))
{
if (! INSN_P (insn))
continue;
if (reg_set_p (newreg, insn))
return;
<API key> (insn, newreg);
}
}
/* BB is a basic block which finishes with CC_REG as a condition code
register which is set to CC_SRC. Look through the successors of BB
to find blocks which have a single predecessor (i.e., this one),
and look through those blocks for an assignment to CC_REG which is
equivalent to CC_SRC. CAN_CHANGE_MODE indicates whether we are
permitted to change the mode of CC_SRC to a compatible mode. This
returns VOIDmode if no equivalent assignments were found.
Otherwise it returns the mode which CC_SRC should wind up with.
ORIG_BB should be the same as BB in the outermost cse_cc_succs call,
but is passed unmodified down to recursive calls in order to prevent
endless recursion.
The main complexity in this function is handling the mode issues.
We may have more than one duplicate which we can eliminate, and we
try to find a mode which will work for multiple duplicates. */
static enum machine_mode
cse_cc_succs (basic_block bb, basic_block orig_bb, rtx cc_reg, rtx cc_src,
bool can_change_mode)
{
bool found_equiv;
enum machine_mode mode;
unsigned int insn_count;
edge e;
rtx insns[2];
enum machine_mode modes[2];
rtx last_insns[2];
unsigned int i;
rtx newreg;
edge_iterator ei;
/* We expect to have two successors. Look at both before picking
the final mode for the comparison. If we have more successors
(i.e., some sort of table jump, although that seems unlikely),
then we require all beyond the first two to use the same
mode. */
found_equiv = false;
mode = GET_MODE (cc_src);
insn_count = 0;
FOR_EACH_EDGE (e, ei, bb->succs)
{
rtx insn;
rtx end;
if (e->flags & EDGE_COMPLEX)
continue;
if (EDGE_COUNT (e->dest->preds) != 1
|| e->dest == EXIT_BLOCK_PTR
/* Avoid endless recursion on unreachable blocks. */
|| e->dest == orig_bb)
continue;
end = NEXT_INSN (BB_END (e->dest));
for (insn = BB_HEAD (e->dest); insn != end; insn = NEXT_INSN (insn))
{
rtx set;
if (! INSN_P (insn))
continue;
/* If CC_SRC is modified, we have to stop looking for
something which uses it. */
if (modified_in_p (cc_src, insn))
break;
/* Check whether INSN sets CC_REG to CC_SRC. */
set = single_set (insn);
if (set
&& REG_P (SET_DEST (set))
&& REGNO (SET_DEST (set)) == REGNO (cc_reg))
{
bool found;
enum machine_mode set_mode;
enum machine_mode comp_mode;
found = false;
set_mode = GET_MODE (SET_SRC (set));
comp_mode = set_mode;
if (rtx_equal_p (cc_src, SET_SRC (set)))
found = true;
else if (GET_CODE (cc_src) == COMPARE
&& GET_CODE (SET_SRC (set)) == COMPARE
&& mode != set_mode
&& rtx_equal_p (XEXP (cc_src, 0),
XEXP (SET_SRC (set), 0))
&& rtx_equal_p (XEXP (cc_src, 1),
XEXP (SET_SRC (set), 1)))
{
comp_mode = targetm.cc_modes_compatible (mode, set_mode);
if (comp_mode != VOIDmode
&& (can_change_mode || comp_mode == mode))
found = true;
}
if (found)
{
found_equiv = true;
if (insn_count < ARRAY_SIZE (insns))
{
insns[insn_count] = insn;
modes[insn_count] = set_mode;
last_insns[insn_count] = end;
++insn_count;
if (mode != comp_mode)
{
gcc_assert (can_change_mode);
mode = comp_mode;
/* The modified insn will be re-recognized later. */
PUT_MODE (cc_src, mode);
}
}
else
{
if (set_mode != mode)
{
/* We found a matching expression in the
wrong mode, but we don't have room to
store it in the array. Punt. This case
should be rare. */
break;
}
/* INSN sets CC_REG to a value equal to CC_SRC
with the right mode. We can simply delete
it. */
delete_insn (insn);
}
/* We found an instruction to delete. Keep looking,
in the hopes of finding a three-way jump. */
continue;
}
/* We found an instruction which sets the condition
code, so don't look any farther. */
break;
}
/* If INSN sets CC_REG in some other way, don't look any
farther. */
if (reg_set_p (cc_reg, insn))
break;
}
/* If we fell off the bottom of the block, we can keep looking
through successors. We pass CAN_CHANGE_MODE as false because
we aren't prepared to handle compatibility between the
further blocks and this block. */
if (insn == end)
{
enum machine_mode submode;
submode = cse_cc_succs (e->dest, orig_bb, cc_reg, cc_src, false);
if (submode != VOIDmode)
{
gcc_assert (submode == mode);
found_equiv = true;
can_change_mode = false;
}
}
}
if (! found_equiv)
return VOIDmode;
/* Now INSN_COUNT is the number of instructions we found which set
CC_REG to a value equivalent to CC_SRC. The instructions are in
INSNS. The modes used by those instructions are in MODES. */
newreg = NULL_RTX;
for (i = 0; i < insn_count; ++i)
{
if (modes[i] != mode)
{
/* We need to change the mode of CC_REG in INSNS[i] and
subsequent instructions. */
if (! newreg)
{
if (GET_MODE (cc_reg) == mode)
newreg = cc_reg;
else
newreg = gen_rtx_REG (mode, REGNO (cc_reg));
}
<API key> (NEXT_INSN (insns[i]), last_insns[i],
newreg);
}
<API key> (insns[i]);
}
return mode;
}
/* If we have a fixed condition code register (or two), walk through
the instructions and try to eliminate duplicate assignments. */
static void
<API key> (void)
{
unsigned int cc_regno_1;
unsigned int cc_regno_2;
rtx cc_reg_1;
rtx cc_reg_2;
basic_block bb;
if (! targetm.<API key> (&cc_regno_1, &cc_regno_2))
return;
cc_reg_1 = gen_rtx_REG (CCmode, cc_regno_1);
if (cc_regno_2 != INVALID_REGNUM)
cc_reg_2 = gen_rtx_REG (CCmode, cc_regno_2);
else
cc_reg_2 = NULL_RTX;
FOR_EACH_BB (bb)
{
rtx last_insn;
rtx cc_reg;
rtx insn;
rtx cc_src_insn;
rtx cc_src;
enum machine_mode mode;
enum machine_mode orig_mode;
/* Look for blocks which end with a conditional jump based on a
condition code register. Then look for the instruction which
sets the condition code register. Then look through the
successor blocks for instructions which set the condition
code register to the same value. There are other possible
uses of the condition code register, but these are by far the
most common and the ones which we are most likely to be able
to optimize. */
last_insn = BB_END (bb);
if (!JUMP_P (last_insn))
continue;
if (reg_referenced_p (cc_reg_1, PATTERN (last_insn)))
cc_reg = cc_reg_1;
else if (cc_reg_2 && reg_referenced_p (cc_reg_2, PATTERN (last_insn)))
cc_reg = cc_reg_2;
else
continue;
cc_src_insn = NULL_RTX;
cc_src = NULL_RTX;
for (insn = PREV_INSN (last_insn);
insn && insn != PREV_INSN (BB_HEAD (bb));
insn = PREV_INSN (insn))
{
rtx set;
if (! INSN_P (insn))
continue;
set = single_set (insn);
if (set
&& REG_P (SET_DEST (set))
&& REGNO (SET_DEST (set)) == REGNO (cc_reg))
{
cc_src_insn = insn;
cc_src = SET_SRC (set);
break;
}
else if (reg_set_p (cc_reg, insn))
break;
}
if (! cc_src_insn)
continue;
if (modified_between_p (cc_src, cc_src_insn, NEXT_INSN (last_insn)))
continue;
/* Now CC_REG is a condition code register used for a
conditional jump at the end of the block, and CC_SRC, in
CC_SRC_INSN, is the value to which that condition code
register is set, and CC_SRC is still meaningful at the end of
the basic block. */
orig_mode = GET_MODE (cc_src);
mode = cse_cc_succs (bb, bb, cc_reg, cc_src, true);
if (mode != VOIDmode)
{
gcc_assert (mode == GET_MODE (cc_src));
if (mode != orig_mode)
{
rtx newreg = gen_rtx_REG (mode, REGNO (cc_reg));
<API key> (cc_src_insn, newreg);
/* Do the same in the following insns that use the
current value of CC_REG within BB. */
<API key> (NEXT_INSN (cc_src_insn),
NEXT_INSN (last_insn),
newreg);
}
}
}
}
/* Perform common subexpression elimination. Nonzero value from
`cse_main' means that jumps were simplified and some code may now
be unreachable, so do jump optimization again. */
static bool
gate_handle_cse (void)
{
return optimize > 0;
}
static unsigned int
rest_of_handle_cse (void)
{
int tem;
if (dump_file)
dump_flow_info (dump_file, dump_flags);
tem = cse_main (get_insns (), max_reg_num ());
/* If we are not running more CSE passes, then we are no longer
expecting CSE to be run. But always rerun it in a cheap mode. */
cse_not_expected = !<API key> && !flag_gcse;
if (tem == 2)
{
timevar_push (TV_JUMP);
rebuild_jump_labels (get_insns ());
cleanup_cfg (CLEANUP_CFG_CHANGED);
timevar_pop (TV_JUMP);
}
else if (tem == 1 || optimize > 1)
cleanup_cfg (0);
return 0;
}
struct rtl_opt_pass pass_cse =
{
{
RTL_PASS,
"cse1", /* name */
gate_handle_cse, /* gate */
rest_of_handle_cse, /* execute */
NULL, /* sub */
NULL, /* next */
0, /* static_pass_number */
TV_CSE, /* tv_id */
0, /* properties_required */
0, /* properties_provided */
0, /* <API key> */
0, /* todo_flags_start */
TODO_df_finish | <API key> |
TODO_ggc_collect |
TODO_verify_flow, /* todo_flags_finish */
}
};
static bool
gate_handle_cse2 (void)
{
return optimize > 0 && <API key>;
}
/* Run second CSE pass after loop optimizations. */
static unsigned int
rest_of_handle_cse2 (void)
{
int tem;
if (dump_file)
dump_flow_info (dump_file, dump_flags);
tem = cse_main (get_insns (), max_reg_num ());
/* Run a pass to eliminate duplicated assignments to condition code
registers. We have to run this after bypass_jumps, because it
makes it harder for that pass to determine whether a jump can be
bypassed safely. */
<API key> ();
<API key> (get_insns (), max_reg_num ());
if (tem == 2)
{
timevar_push (TV_JUMP);
rebuild_jump_labels (get_insns ());
cleanup_cfg (CLEANUP_CFG_CHANGED);
timevar_pop (TV_JUMP);
}
else if (tem == 1)
cleanup_cfg (0);
cse_not_expected = 1;
return 0;
}
struct rtl_opt_pass pass_cse2 =
{
{
RTL_PASS,
"cse2", /* name */
gate_handle_cse2, /* gate */
rest_of_handle_cse2, /* execute */
NULL, /* sub */
NULL, /* next */
0, /* static_pass_number */
TV_CSE2, /* tv_id */
0, /* properties_required */
0, /* properties_provided */
0, /* <API key> */
0, /* todo_flags_start */
TODO_df_finish | <API key> |
TODO_ggc_collect |
TODO_verify_flow /* todo_flags_finish */
}
};
static bool
<API key> (void)
{
return optimize > 0 && <API key>;
}
/* Run second CSE pass after loop optimizations. */
static unsigned int
<API key> (void)
{
int save_cfj;
int tem;
/* We only want to do local CSE, so don't follow jumps. */
save_cfj = <API key>;
<API key> = 0;
rebuild_jump_labels (get_insns ());
tem = cse_main (get_insns (), max_reg_num ());
<API key> ();
<API key> (get_insns (), max_reg_num ());
cse_not_expected = !<API key>;
/* If cse altered any jumps, rerun jump opts to clean things up. */
if (tem == 2)
{
timevar_push (TV_JUMP);
rebuild_jump_labels (get_insns ());
cleanup_cfg (CLEANUP_CFG_CHANGED);
timevar_pop (TV_JUMP);
}
else if (tem == 1)
cleanup_cfg (0);
<API key> = save_cfj;
return 0;
}
struct rtl_opt_pass <API key> =
{
{
RTL_PASS,
"cse_local", /* name */
<API key>, /* gate */
<API key>, /* execute */
NULL, /* sub */
NULL, /* next */
0, /* static_pass_number */
TV_CSE, /* tv_id */
0, /* properties_required */
0, /* properties_provided */
0, /* <API key> */
0, /* todo_flags_start */
TODO_df_finish | <API key> |
TODO_ggc_collect |
TODO_verify_flow /* todo_flags_finish */
}
}; |
<?php
?>
<section class="no-results not-found">
<div class="inside-article">
<?php do_action( '<API key>'); ?>
<header class="entry-header">
<n1 class="entry-title"><?php _e( 'Nothing Found', 'generate' ); ?></n1>
</header><!-- .entry-header -->
<?php do_action( '<API key>'); ?>
<div class="entry-content">
<?php if ( is_home() && current_user_can( 'publish_posts' ) ) : ?>
<p><?php printf( __( 'Ready to publish your first post? <a href="%1$s">Get started here</a>.', 'generate' ), esc_url( admin_url( 'post-new.php' ) ) ); ?></p>
<?php elseif ( is_search() ) : ?>
<p><?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'generate' ); ?></p>
<?php get_search_form(); ?>
<?php else : ?>
<p><?php _e( 'It seems we can’t find what you’re looking for. Perhaps searching can help.', 'generate' ); ?></p>
<?php get_search_form(); ?>
<?php endif; ?>
</div><!-- .entry-content -->
<?php do_action( '<API key>'); ?>
</div><!-- .inside-article -->
</section><!-- .no-results --> |
"""
This module handles the Google Signup for a new user
"""
from oauth2client import client
from django.contrib.auth.models import User
from django.shortcuts import redirect
from django.shortcuts import render
from rest_framework.decorators import api_view, permission_classes
from rest_framework.views import APIView
from rest_framework import authentication, permissions
from rest_framework.authtoken.models import Token
from models import GoogleData
import httplib2
import json
flow = client.<API key>(
'./client_secrets.json',
scope='https:
redirect_uri='http://localhost:8000/oauth2callback'
)
flow.params['access_type'] = 'offline'
flow.params['prompt'] = 'consent'
@api_view(['GET'])
def google_signup(request):
"""
This method redirects the user to the different url which provides
the code
"""
auth_uri = flow.<API key>()
return redirect(auth_uri)
@api_view(['GET'])
def callback(request):
"""
This method sign up the user to the calender app and redirect to
the main page
"""
code = request.GET['code']
credentials = flow.step2_exchange(code)
http_auth = credentials.authorize(httplib2.Http())
user_dictionary = json.loads(credentials.to_json())
try:
email = str(user_dictionary['id_token']['email'])
username = User.objects.get(username=email)
except User.DoesNotExist:
username = None
if username is None:
user = User()
user.username = str(user_dictionary['id_token']['email'])
user.set_password(str(user_dictionary['refresh_token']))
user.save()
new_token = Token.objects.create(user=user)
new_token.save()
google_obj = GoogleData()
google_obj.refresh_token = str(user_dictionary['refresh_token'])
google_obj.user = user
google_obj.save()
return render(request, 'api/index.html',
{'key' : str(new_token.key),
'msg':"Signup Successful"})
else:
old_token = Token.objects.get(user=username)
return render(request, 'api/index.html',
{'msg': 'Email already exists',
'key' : str(old_token.key)}) |
<?php
$menu_section='menu_misc';
include ("../lib/defines.php");
include ("../lib/module.access.php");
include ("../lib/Form/Class.FormHandler.inc.php");
include ("./form_data/FG_var_prefix.inc");
if (! has_rights (ACX_MISC)){
Header ("HTTP/1.0 401 Unauthorized");
Header ("Location: PP_error.php?c=accessdenied");
die();
}
$HD_Form -> setDBHandler (DbConnect());
$HD_Form -> init();
if ($id!="" || !is_null($id)){
$HD_Form -> FG_EDITION_CLAUSE = str_replace("%id", "$id", $HD_Form -> FG_EDITION_CLAUSE);
}
if (!isset($form_action)) $form_action="list"; //ask-add
if (!isset($action)) $action = $form_action;
$list = $HD_Form -> perform_action($form_action);
if ($popup_select){
?>
<SCRIPT LANGUAGE="javascript">
<!-- Begin
function sendValue(selvalue){
window.opener.document.<?php echo $popup_formname ?>.<?php echo $popup_fieldname ?>.value = selvalue;
window.close();
}
// End -->
</script>
<?php
}
//
include("PP_header.php");
//
if (!($popup_select==1) && ($form_action=='list')) echo $CC_help_list_prefix;
elseif (!($popup_select==1)) echo $CC_help_edit_prefix;
//
$HD_Form -> create_toppage ($form_action);
//
//$HD_Form -> CV_TOPVIEWER = "menu";
if (strlen($_GET["menu"])>0) $_SESSION["menu"] = $_GET["menu"];
$HD_Form -> create_form ($form_action, $list, $id=null) ;
//
if (!($popup_select==1)) include("PP_footer.php");
?> |
using System;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using MrCMS.Entities.Documents.Web;
using MrCMS.Web.Areas.Admin.Models.WebpageEdit;
namespace MrCMS.Web.Apps.Commenting.Areas.Admin.Models
{
public class <API key> : WebpageTab
{
public override int Order
{
get { return 1000; }
}
public override string Name(Webpage webpage)
{
return "Comments";
}
public override bool ShouldShow(Webpage webpage)
{
return true;
}
public override Type ParentType
{
get { return null; }
}
public override string TabHtmlId
{
get { return "webpage-comments"; }
}
public override void RenderTabPane(HtmlHelper<Webpage> html, Webpage webpage)
{
html.RenderAction("Show", "WebpageComments", new { webpage });
}
}
} |
#import <Foundation/Foundation.h>
@interface PJUser : NSObject
+ (PJUser *)currentUser;
+ (PJUser *)defaultManager;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *first_name;
@property (nonatomic, strong) NSString *last_name;//==@"@"CAS
@property (nonatomic, strong) NSString *email;
@property (nonatomic, strong) NSString *last_login_date;
-(void)save;
+(void)logOut;
@end |
package org.eclipse.jgit.internal.storage.file;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.<API key>;
import com.googlecode.javaewah.<API key>;
import com.googlecode.javaewah.IntIterator;
import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.BitmapIndex;
import org.eclipse.jgit.lib.BitmapObject;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectIdOwnerMap;
import org.eclipse.jgit.util.BlockList;
/** A compressed bitmap representation of the entire object graph. */
public class BitmapIndexImpl implements BitmapIndex {
private static final int EXTRA_BITS = 10 * 1024;
private final PackBitmapIndex packIndex;
private final MutableBitmapIndex mutableIndex;
private final int indexObjectCount;
/**
* Creates a BitmapIndex that is back by Compressed bitmaps.
*
* @param packIndex
* the bitmap index for the pack.
*/
public BitmapIndexImpl(PackBitmapIndex packIndex) {
this.packIndex = packIndex;
mutableIndex = new MutableBitmapIndex();
indexObjectCount = packIndex.getObjectCount();
}
PackBitmapIndex getPackBitmapIndex() {
return packIndex;
}
public CompressedBitmap getBitmap(AnyObjectId objectId) {
<API key> compressed = packIndex.getBitmap(objectId);
if (compressed == null)
return null;
return new CompressedBitmap(compressed);
}
public <API key> newBitmapBuilder() {
return new <API key>();
}
private int findPosition(AnyObjectId objectId) {
int position = packIndex.findPosition(objectId);
if (position < 0) {
position = mutableIndex.findPosition(objectId);
if (position >= 0)
position += indexObjectCount;
}
return position;
}
private int addObject(AnyObjectId objectId, int type) {
int position = findPosition(objectId);
if (position < 0) {
position = mutableIndex.addObject(objectId, type);
position += indexObjectCount;
}
return position;
}
private static final class ComboBitset {
private InflatingBitSet inflatingBitmap;
private BitSet toAdd;
private BitSet toRemove;
private ComboBitset() {
this(new <API key>());
}
private ComboBitset(<API key> bitmap) {
this.inflatingBitmap = new InflatingBitSet(bitmap);
}
<API key> combine() {
<API key> toAddCompressed = null;
if (toAdd != null) {
toAddCompressed = toAdd.<API key>();
toAdd = null;
}
<API key> toRemoveCompressed = null;
if (toRemove != null) {
toRemoveCompressed = toRemove.<API key>();
toRemove = null;
}
if (toAddCompressed != null)
or(toAddCompressed);
if (toRemoveCompressed != null)
andNot(toRemoveCompressed);
return inflatingBitmap.getBitmap();
}
void or(<API key> inbits) {
if (toRemove != null)
combine();
inflatingBitmap = inflatingBitmap.or(inbits);
}
void andNot(<API key> inbits) {
if (toAdd != null || toRemove != null)
combine();
inflatingBitmap = inflatingBitmap.andNot(inbits);
}
void xor(<API key> inbits) {
if (toAdd != null || toRemove != null)
combine();
inflatingBitmap = inflatingBitmap.xor(inbits);
}
boolean contains(int position) {
if (toRemove != null && toRemove.get(position))
return false;
if (toAdd != null && toAdd.get(position))
return true;
return inflatingBitmap.contains(position);
}
void remove(int position) {
if (toAdd != null)
toAdd.clear(position);
if (inflatingBitmap.maybeContains(position)) {
if (toRemove == null)
toRemove = new BitSet(position + EXTRA_BITS);
toRemove.set(position);
}
}
void set(int position) {
if (toRemove != null)
toRemove.clear(position);
if (toAdd == null)
toAdd = new BitSet(position + EXTRA_BITS);
toAdd.set(position);
}
}
private final class <API key> implements BitmapBuilder {
private ComboBitset bitset = new ComboBitset();
public boolean add(AnyObjectId objectId, int type) {
int position = addObject(objectId, type);
if (bitset.contains(position))
return false;
Bitmap entry = getBitmap(objectId);
if (entry != null) {
or(entry);
return false;
}
bitset.set(position);
return true;
}
public boolean contains(AnyObjectId objectId) {
int position = findPosition(objectId);
return 0 <= position && bitset.contains(position);
}
public void remove(AnyObjectId objectId) {
int position = findPosition(objectId);
if (0 <= position)
bitset.remove(position);
}
public <API key> or(Bitmap other) {
if (<API key>(other)) {
bitset.or(((CompressedBitmap) other).bitmap);
} else if (<API key>(other)) {
<API key> b = (<API key>) other;
bitset.or(b.bitset.combine());
} else {
throw new <API key>();
}
return this;
}
public <API key> andNot(Bitmap other) {
if (<API key>(other)) {
bitset.andNot(((CompressedBitmap) other).bitmap);
} else if (<API key>(other)) {
<API key> b = (<API key>) other;
bitset.andNot(b.bitset.combine());
} else {
throw new <API key>();
}
return this;
}
public <API key> xor(Bitmap other) {
if (<API key>(other)) {
bitset.xor(((CompressedBitmap) other).bitmap);
} else if (<API key>(other)) {
<API key> b = (<API key>) other;
bitset.xor(b.bitset.combine());
} else {
throw new <API key>();
}
return this;
}
/** @return the fully built immutable bitmap */
public CompressedBitmap build() {
return new CompressedBitmap(bitset.combine());
}
public Iterator<BitmapObject> iterator() {
return build().iterator();
}
public int cardinality() {
return bitset.combine().cardinality();
}
public boolean removeAllOrNone(PackBitmapIndex index) {
if (!packIndex.equals(index))
return false;
<API key> curr = bitset.combine()
.xor(ones(indexObjectCount));
IntIterator ii = curr.intIterator();
if (ii.hasNext() && ii.next() < indexObjectCount)
return false;
bitset = new ComboBitset(curr);
return true;
}
private BitmapIndexImpl getBitmapIndex() {
return BitmapIndexImpl.this;
}
}
final class CompressedBitmap implements Bitmap {
private final <API key> bitmap;
private CompressedBitmap(<API key> bitmap) {
this.bitmap = bitmap;
}
public CompressedBitmap or(Bitmap other) {
return new CompressedBitmap(bitmap.or(bitmapOf(other)));
}
public CompressedBitmap andNot(Bitmap other) {
return new CompressedBitmap(bitmap.andNot(bitmapOf(other)));
}
public CompressedBitmap xor(Bitmap other) {
return new CompressedBitmap(bitmap.xor(bitmapOf(other)));
}
private <API key> bitmapOf(Bitmap other) {
if (<API key>(other))
return ((CompressedBitmap) other).bitmap;
if (<API key>(other))
return ((<API key>) other).build().bitmap;
<API key> builder = newBitmapBuilder();
builder.or(other);
return builder.build().bitmap;
}
private final IntIterator ofObjectType(int type) {
return packIndex.ofObjectType(bitmap, type).intIterator();
}
public Iterator<BitmapObject> iterator() {
final IntIterator dynamic = bitmap.andNot(ones(indexObjectCount))
.intIterator();
final IntIterator commits = ofObjectType(Constants.OBJ_COMMIT);
final IntIterator trees = ofObjectType(Constants.OBJ_TREE);
final IntIterator blobs = ofObjectType(Constants.OBJ_BLOB);
final IntIterator tags = ofObjectType(Constants.OBJ_TAG);
return new Iterator<BitmapObject>() {
private final BitmapObjectImpl out = new BitmapObjectImpl();
private int type;
private IntIterator cached = dynamic;
public boolean hasNext() {
if (!cached.hasNext()) {
if (commits.hasNext()) {
type = Constants.OBJ_COMMIT;
cached = commits;
} else if (trees.hasNext()) {
type = Constants.OBJ_TREE;
cached = trees;
} else if (blobs.hasNext()) {
type = Constants.OBJ_BLOB;
cached = blobs;
} else if (tags.hasNext()) {
type = Constants.OBJ_TAG;
cached = tags;
} else {
return false;
}
}
return true;
}
public BitmapObject next() {
if (!hasNext())
throw new <API key>();
int position = cached.next();
if (position < indexObjectCount) {
out.type = type;
out.objectId = packIndex.getObject(position);
} else {
position -= indexObjectCount;
MutableEntry entry = mutableIndex.getObject(position);
out.type = entry.type;
out.objectId = entry;
}
return out;
}
public void remove() {
throw new <API key>();
}
};
}
<API key> <API key>() {
return bitmap;
}
private BitmapIndexImpl getPackBitmapIndex() {
return BitmapIndexImpl.this;
}
}
private static final class MutableBitmapIndex {
private final ObjectIdOwnerMap<MutableEntry>
revMap = new ObjectIdOwnerMap<MutableEntry>();
private final BlockList<MutableEntry>
revList = new BlockList<MutableEntry>();
int findPosition(AnyObjectId objectId) {
MutableEntry entry = revMap.get(objectId);
if (entry == null)
return -1;
return entry.position;
}
MutableEntry getObject(int position) {
try {
MutableEntry entry = revList.get(position);
if (entry == null)
throw new <API key>(MessageFormat.format(
JGitText.get().objectNotFound,
String.valueOf(position)));
return entry;
} catch (<API key> ex) {
throw new <API key>(ex);
}
}
int addObject(AnyObjectId objectId, int type) {
MutableEntry entry = new MutableEntry(
objectId, type, revList.size());
revList.add(entry);
revMap.add(entry);
return entry.position;
}
}
private static final class MutableEntry extends ObjectIdOwnerMap.Entry {
private final int type;
private final int position;
MutableEntry(AnyObjectId objectId, int type, int position) {
super(objectId);
this.type = type;
this.position = position;
}
}
private static final class BitmapObjectImpl extends BitmapObject {
private ObjectId objectId;
private int type;
@Override
public ObjectId getObjectId() {
return objectId;
}
@Override
public int getType() {
return type;
}
}
private boolean <API key>(Bitmap other) {
if (other instanceof CompressedBitmap) {
CompressedBitmap b = (CompressedBitmap) other;
return this == b.getPackBitmapIndex();
}
return false;
}
private boolean <API key>(Bitmap other) {
if (other instanceof <API key>) {
<API key> b = (<API key>) other;
return this == b.getBitmapIndex();
}
return false;
}
private static final <API key> ones(int sizeInBits) {
<API key> mask = new <API key>();
mask.<API key>(
true, sizeInBits / <API key>.wordinbits);
int remaining = sizeInBits % <API key>.wordinbits;
if (remaining > 0)
mask.add((1L << remaining) - 1, remaining);
return mask;
}
} |
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
#include "utf8.h"
#include "util.h"
#include "strv.h"
#include "unaligned.h"
#include "dns-domain.h"
#include "resolved-dns-packet.h"
int dns_packet_new(DnsPacket **ret, DnsProtocol protocol, size_t mtu) {
DnsPacket *p;
size_t a;
assert(ret);
if (mtu <= <API key>)
a = <API key>;
else
a = mtu - <API key>;
if (a < <API key>)
a = <API key>;
/* round up to next page size */
a = PAGE_ALIGN(ALIGN(sizeof(DnsPacket)) + a) - ALIGN(sizeof(DnsPacket));
/* make sure we never allocate more than useful */
if (a > DNS_PACKET_SIZE_MAX)
a = DNS_PACKET_SIZE_MAX;
p = malloc0(ALIGN(sizeof(DnsPacket)) + a);
if (!p)
return -ENOMEM;
p->size = p->rindex = <API key>;
p->allocated = a;
p->protocol = protocol;
p->n_ref = 1;
*ret = p;
return 0;
}
int <API key>(DnsPacket **ret, DnsProtocol protocol, size_t mtu) {
DnsPacket *p;
DnsPacketHeader *h;
int r;
assert(ret);
r = dns_packet_new(&p, protocol, mtu);
if (r < 0)
return r;
h = DNS_PACKET_HEADER(p);
if (protocol == DNS_PROTOCOL_LLMNR)
h->flags = htobe16(<API key>(0 ,
0 /* opcode */,
0 ,
0 ,
0 ,
0 ,
0 ,
0 ,
0 /* rcode */));
else
h->flags = htobe16(<API key>(0 ,
0 /* opcode */,
0 ,
0 ,
1 /* rd (ask for recursion) */,
0 ,
0 ,
0 ,
0 /* rcode */));
*ret = p;
return 0;
}
DnsPacket *dns_packet_ref(DnsPacket *p) {
if (!p)
return NULL;
assert(p->n_ref > 0);
p->n_ref++;
return p;
}
static void dns_packet_free(DnsPacket *p) {
char *s;
assert(p);
dns_question_unref(p->question);
dns_answer_unref(p->answer);
while ((s = <API key>(p->names)))
free(s);
hashmap_free(p->names);
free(p->_data);
free(p);
}
DnsPacket *dns_packet_unref(DnsPacket *p) {
if (!p)
return NULL;
assert(p->n_ref > 0);
if (p->n_ref == 1)
dns_packet_free(p);
else
p->n_ref
return NULL;
}
int dns_packet_validate(DnsPacket *p) {
assert(p);
if (p->size < <API key>)
return -EBADMSG;
if (p->size > DNS_PACKET_SIZE_MAX)
return -EBADMSG;
return 1;
}
int <API key>(DnsPacket *p) {
int r;
assert(p);
r = dns_packet_validate(p);
if (r < 0)
return r;
if (DNS_PACKET_QR(p) != 1)
return 0;
if (DNS_PACKET_OPCODE(p) != 0)
return -EBADMSG;
switch (p->protocol) {
case DNS_PROTOCOL_LLMNR:
/* RFC 4795, Section 2.1.1. says to discard all replies with QDCOUNT != 1 */
if (DNS_PACKET_QDCOUNT(p) != 1)
return -EBADMSG;
break;
default:
break;
}
return 1;
}
int <API key>(DnsPacket *p) {
int r;
assert(p);
r = dns_packet_validate(p);
if (r < 0)
return r;
if (DNS_PACKET_QR(p) != 0)
return 0;
if (DNS_PACKET_OPCODE(p) != 0)
return -EBADMSG;
if (DNS_PACKET_TC(p))
return -EBADMSG;
switch (p->protocol) {
case DNS_PROTOCOL_LLMNR:
/* RFC 4795, Section 2.1.1. says to discard all queries with QDCOUNT != 1 */
if (DNS_PACKET_QDCOUNT(p) != 1)
return -EBADMSG;
/* RFC 4795, Section 2.1.1. says to discard all queries with ANCOUNT != 0 */
if (DNS_PACKET_ANCOUNT(p) > 0)
return -EBADMSG;
/* RFC 4795, Section 2.1.1. says to discard all queries with NSCOUNT != 0 */
if (DNS_PACKET_NSCOUNT(p) > 0)
return -EBADMSG;
break;
default:
break;
}
return 1;
}
static int dns_packet_extend(DnsPacket *p, size_t add, void **ret, size_t *start) {
assert(p);
if (p->size + add > p->allocated) {
size_t a;
a = PAGE_ALIGN((p->size + add) * 2);
if (a > DNS_PACKET_SIZE_MAX)
a = DNS_PACKET_SIZE_MAX;
if (p->size + add > a)
return -EMSGSIZE;
if (p->_data) {
void *d;
d = realloc(p->_data, a);
if (!d)
return -ENOMEM;
p->_data = d;
} else {
p->_data = malloc(a);
if (!p->_data)
return -ENOMEM;
memcpy(p->_data, (uint8_t*) p + ALIGN(sizeof(DnsPacket)), p->size);
memzero((uint8_t*) p->_data + p->size, a - p->size);
}
p->allocated = a;
}
if (start)
*start = p->size;
if (ret)
*ret = (uint8_t*) DNS_PACKET_DATA(p) + p->size;
p->size += add;
return 0;
}
static void dns_packet_truncate(DnsPacket *p, size_t sz) {
Iterator i;
char *s;
void *n;
assert(p);
if (p->size <= sz)
return;
HASHMAP_FOREACH_KEY(s, n, p->names, i) {
if (PTR_TO_SIZE(n) < sz)
continue;
hashmap_remove(p->names, s);
free(s);
}
p->size = sz;
}
int <API key>(DnsPacket *p, const void *d, size_t l, size_t *start) {
void *q;
int r;
assert(p);
r = dns_packet_extend(p, l, &q, start);
if (r < 0)
return r;
memcpy(q, d, l);
return 0;
}
int <API key>(DnsPacket *p, uint8_t v, size_t *start) {
void *d;
int r;
assert(p);
r = dns_packet_extend(p, sizeof(uint8_t), &d, start);
if (r < 0)
return r;
((uint8_t*) d)[0] = v;
return 0;
}
int <API key>(DnsPacket *p, uint16_t v, size_t *start) {
void *d;
int r;
assert(p);
r = dns_packet_extend(p, sizeof(uint16_t), &d, start);
if (r < 0)
return r;
<API key>(d, v);
return 0;
}
int <API key>(DnsPacket *p, uint32_t v, size_t *start) {
void *d;
int r;
assert(p);
r = dns_packet_extend(p, sizeof(uint32_t), &d, start);
if (r < 0)
return r;
<API key>(d, v);
return 0;
}
int <API key>(DnsPacket *p, const char *s, size_t *start) {
void *d;
size_t l;
int r;
assert(p);
assert(s);
l = strlen(s);
if (l > 255)
return -E2BIG;
r = dns_packet_extend(p, 1 + l, &d, start);
if (r < 0)
return r;
((uint8_t*) d)[0] = (uint8_t) l;
memcpy(((uint8_t*) d) + 1, s, l);
return 0;
}
int <API key>(DnsPacket *p, const char *d, size_t l, size_t *start) {
void *w;
int r;
assert(p);
assert(d);
if (l > DNS_LABEL_MAX)
return -E2BIG;
r = dns_packet_extend(p, 1 + l, &w, start);
if (r < 0)
return r;
((uint8_t*) w)[0] = (uint8_t) l;
memcpy(((uint8_t*) w) + 1, d, l);
return 0;
}
int <API key>(DnsPacket *p, const char *name,
bool allow_compression, size_t *start) {
size_t saved_size;
int r;
assert(p);
assert(name);
saved_size = p->size;
while (*name) {
_cleanup_free_ char *s = NULL;
char label[DNS_LABEL_MAX];
size_t n = 0;
int k;
if (allow_compression)
n = PTR_TO_SIZE(hashmap_get(p->names, name));
if (n > 0) {
assert(n < p->size);
if (n < 0x4000) {
r = <API key>(p, 0xC000 | n, NULL);
if (r < 0)
goto fail;
goto done;
}
}
s = strdup(name);
if (!s) {
r = -ENOMEM;
goto fail;
}
r = dns_label_unescape(&name, label, sizeof(label));
if (r < 0)
goto fail;
if (p->protocol == DNS_PROTOCOL_DNS)
k = <API key>(label, r, label, sizeof(label));
else
k = dns_label_undo_idna(label, r, label, sizeof(label));
if (k < 0) {
r = k;
goto fail;
}
if (k > 0)
r = k;
r = <API key>(p, label, r, &n);
if (r < 0)
goto fail;
if (allow_compression) {
r = <API key>(&p->names, &dns_name_hash_ops);
if (r < 0)
goto fail;
r = hashmap_put(p->names, s, SIZE_TO_PTR(n));
if (r < 0)
goto fail;
s = NULL;
}
}
r = <API key>(p, 0, NULL);
if (r < 0)
return r;
done:
if (start)
*start = saved_size;
return 0;
fail:
dns_packet_truncate(p, saved_size);
return r;
}
int <API key>(DnsPacket *p, const DnsResourceKey *k, size_t *start) {
size_t saved_size;
int r;
assert(p);
assert(k);
saved_size = p->size;
r = <API key>(p, <API key>(k), true, NULL);
if (r < 0)
goto fail;
r = <API key>(p, k->type, NULL);
if (r < 0)
goto fail;
r = <API key>(p, k->class, NULL);
if (r < 0)
goto fail;
if (start)
*start = saved_size;
return 0;
fail:
dns_packet_truncate(p, saved_size);
return r;
}
int <API key>(DnsPacket *p, const DnsResourceRecord *rr, size_t *start) {
size_t saved_size, rdlength_offset, end, rdlength;
int r;
assert(p);
assert(rr);
saved_size = p->size;
r = <API key>(p, rr->key, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->ttl, NULL);
if (r < 0)
goto fail;
/* Initially we write 0 here */
r = <API key>(p, 0, &rdlength_offset);
if (r < 0)
goto fail;
switch (rr->unparseable ? _DNS_TYPE_INVALID : rr->key->type) {
case DNS_TYPE_SRV:
r = <API key>(p, rr->srv.priority, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->srv.weight, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->srv.port, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->srv.name, true, NULL);
break;
case DNS_TYPE_PTR:
case DNS_TYPE_NS:
case DNS_TYPE_CNAME:
case DNS_TYPE_DNAME:
r = <API key>(p, rr->ptr.name, true, NULL);
break;
case DNS_TYPE_HINFO:
r = <API key>(p, rr->hinfo.cpu, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->hinfo.os, NULL);
break;
case DNS_TYPE_SPF: /* exactly the same as TXT */
case DNS_TYPE_TXT: {
char **s;
if (strv_isempty(rr->txt.strings)) {
/* RFC 6763, section 6.1 suggests to generate
* single empty string for an empty array. */
r = <API key>(p, "", NULL);
if (r < 0)
goto fail;
} else {
STRV_FOREACH(s, rr->txt.strings) {
r = <API key>(p, *s, NULL);
if (r < 0)
goto fail;
}
}
r = 0;
break;
}
case DNS_TYPE_A:
r = <API key>(p, &rr->a.in_addr, sizeof(struct in_addr), NULL);
break;
case DNS_TYPE_AAAA:
r = <API key>(p, &rr->aaaa.in6_addr, sizeof(struct in6_addr), NULL);
break;
case DNS_TYPE_SOA:
r = <API key>(p, rr->soa.mname, true, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->soa.rname, true, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->soa.serial, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->soa.refresh, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->soa.retry, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->soa.expire, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->soa.minimum, NULL);
break;
case DNS_TYPE_MX:
r = <API key>(p, rr->mx.priority, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->mx.exchange, true, NULL);
break;
case DNS_TYPE_LOC:
r = <API key>(p, rr->loc.version, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->loc.size, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->loc.horiz_pre, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->loc.vert_pre, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->loc.latitude, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->loc.longitude, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->loc.altitude, NULL);
break;
case DNS_TYPE_DS:
r = <API key>(p, rr->ds.key_tag, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->ds.algorithm, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->ds.digest_type, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->ds.digest, rr->ds.digest_size, NULL);
break;
case DNS_TYPE_SSHFP:
r = <API key>(p, rr->sshfp.algorithm, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->sshfp.fptype, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->sshfp.key, rr->sshfp.key_size, NULL);
break;
case DNS_TYPE_DNSKEY:
r = <API key>(p, dnskey_to_flags(rr), NULL);
if (r < 0)
goto fail;
r = <API key>(p, 3u, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->dnskey.algorithm, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->dnskey.key, rr->dnskey.key_size, NULL);
break;
case DNS_TYPE_RRSIG:
r = <API key>(p, rr->rrsig.type_covered, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->rrsig.algorithm, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->rrsig.labels, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->rrsig.original_ttl, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->rrsig.expiration, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->rrsig.inception, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->rrsig.key_tag, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->rrsig.signer, false, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rr->rrsig.signature, rr->rrsig.signature_size, NULL);
break;
case _DNS_TYPE_INVALID: /* unparseable */
default:
r = <API key>(p, rr->generic.data, rr->generic.size, NULL);
break;
}
if (r < 0)
goto fail;
/* Let's calculate the actual data size and update the field */
rdlength = p->size - rdlength_offset - sizeof(uint16_t);
if (rdlength > 0xFFFF) {
r = ENOSPC;
goto fail;
}
end = p->size;
p->size = rdlength_offset;
r = <API key>(p, rdlength, NULL);
if (r < 0)
goto fail;
p->size = end;
if (start)
*start = saved_size;
return 0;
fail:
dns_packet_truncate(p, saved_size);
return r;
}
int dns_packet_read(DnsPacket *p, size_t sz, const void **ret, size_t *start) {
assert(p);
if (p->rindex + sz > p->size)
return -EMSGSIZE;
if (ret)
*ret = (uint8_t*) DNS_PACKET_DATA(p) + p->rindex;
if (start)
*start = p->rindex;
p->rindex += sz;
return 0;
}
void dns_packet_rewind(DnsPacket *p, size_t idx) {
assert(p);
assert(idx <= p->size);
assert(idx >= <API key>);
p->rindex = idx;
}
int <API key>(DnsPacket *p, void *d, size_t sz, size_t *start) {
const void *q;
int r;
assert(p);
assert(d);
r = dns_packet_read(p, sz, &q, start);
if (r < 0)
return r;
memcpy(d, q, sz);
return 0;
}
int <API key>(DnsPacket *p, uint8_t *ret, size_t *start) {
const void *d;
int r;
assert(p);
r = dns_packet_read(p, sizeof(uint8_t), &d, start);
if (r < 0)
return r;
*ret = ((uint8_t*) d)[0];
return 0;
}
int <API key>(DnsPacket *p, uint16_t *ret, size_t *start) {
const void *d;
int r;
assert(p);
r = dns_packet_read(p, sizeof(uint16_t), &d, start);
if (r < 0)
return r;
*ret = unaligned_read_be16(d);
return 0;
}
int <API key>(DnsPacket *p, uint32_t *ret, size_t *start) {
const void *d;
int r;
assert(p);
r = dns_packet_read(p, sizeof(uint32_t), &d, start);
if (r < 0)
return r;
*ret = unaligned_read_be32(d);
return 0;
}
int <API key>(DnsPacket *p, char **ret, size_t *start) {
size_t saved_rindex;
const void *d;
char *t;
uint8_t c;
int r;
assert(p);
saved_rindex = p->rindex;
r = <API key>(p, &c, NULL);
if (r < 0)
goto fail;
r = dns_packet_read(p, c, &d, NULL);
if (r < 0)
goto fail;
if (memchr(d, 0, c)) {
r = -EBADMSG;
goto fail;
}
t = strndup(d, c);
if (!t) {
r = -ENOMEM;
goto fail;
}
if (!utf8_is_valid(t)) {
free(t);
r = -EBADMSG;
goto fail;
}
*ret = t;
if (start)
*start = saved_rindex;
return 0;
fail:
dns_packet_rewind(p, saved_rindex);
return r;
}
int <API key>(DnsPacket *p, char **_ret,
bool allow_compression, size_t *start) {
size_t saved_rindex, after_rindex = 0, jump_barrier;
_cleanup_free_ char *ret = NULL;
size_t n = 0, allocated = 0;
bool first = true;
int r;
assert(p);
assert(_ret);
saved_rindex = p->rindex;
jump_barrier = p->rindex;
for (;;) {
uint8_t c, d;
r = <API key>(p, &c, NULL);
if (r < 0)
goto fail;
if (c == 0)
/* End of name */
break;
else if (c <= 63) {
_cleanup_free_ char *t = NULL;
const char *label;
/* Literal label */
r = dns_packet_read(p, c, (const void**) &label, NULL);
if (r < 0)
goto fail;
r = dns_label_escape(label, c, &t);
if (r < 0)
goto fail;
if (!GREEDY_REALLOC(ret, allocated, n + !first + strlen(t) + 1)) {
r = -ENOMEM;
goto fail;
}
if (!first)
ret[n++] = '.';
else
first = false;
memcpy(ret + n, t, r);
n += r;
continue;
} else if (allow_compression && (c & 0xc0) == 0xc0) {
uint16_t ptr;
/* Pointer */
r = <API key>(p, &d, NULL);
if (r < 0)
goto fail;
ptr = (uint16_t) (c & ~0xc0) << 8 | (uint16_t) d;
if (ptr < <API key> || ptr >= jump_barrier) {
r = -EBADMSG;
goto fail;
}
if (after_rindex == 0)
after_rindex = p->rindex;
/* Jumps are limited to a "prior occurrence" (RFC-1035 4.1.4) */
jump_barrier = ptr;
p->rindex = ptr;
} else {
r = -EBADMSG;
goto fail;
}
}
if (!GREEDY_REALLOC(ret, allocated, n + 1)) {
r = -ENOMEM;
goto fail;
}
ret[n] = 0;
if (after_rindex != 0)
p->rindex= after_rindex;
*_ret = ret;
ret = NULL;
if (start)
*start = saved_rindex;
return 0;
fail:
dns_packet_rewind(p, saved_rindex);
return r;
}
int dns_packet_read_key(DnsPacket *p, DnsResourceKey **ret, size_t *start) {
_cleanup_free_ char *name = NULL;
uint16_t class, type;
DnsResourceKey *key;
size_t saved_rindex;
int r;
assert(p);
assert(ret);
saved_rindex = p->rindex;
r = <API key>(p, &name, true, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &type, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &class, NULL);
if (r < 0)
goto fail;
key = <API key>(class, type, name);
if (!key) {
r = -ENOMEM;
goto fail;
}
name = NULL;
*ret = key;
if (start)
*start = saved_rindex;
return 0;
fail:
dns_packet_rewind(p, saved_rindex);
return r;
}
static int <API key>(DnsPacket *p, size_t length,
void **dp, size_t *lengthp,
size_t *start) {
int r;
const void *d;
void *d2;
r = dns_packet_read(p, length, &d, NULL);
if (r < 0)
return r;
d2 = memdup(d, length);
if (!d2)
return -ENOMEM;
*dp = d2;
*lengthp = length;
return 0;
}
static bool loc_size_ok(uint8_t size) {
uint8_t m = size >> 4, e = size & 0xF;
return m <= 9 && e <= 9 && (m > 0 || e == 0);
}
static int dnskey_parse_flags(DnsResourceRecord *rr, uint16_t flags) {
assert(rr);
if (flags & ~(DNSKEY_FLAG_SEP | <API key>))
return -EBADMSG;
rr->dnskey.zone_key_flag = flags & <API key>;
rr->dnskey.sep_flag = flags & DNSKEY_FLAG_SEP;
return 0;
}
int dns_packet_read_rr(DnsPacket *p, DnsResourceRecord **ret, size_t *start) {
_cleanup_(<API key>) DnsResourceRecord *rr = NULL;
_cleanup_(<API key>) DnsResourceKey *key = NULL;
size_t saved_rindex, offset;
uint16_t rdlength;
const void *d;
int r;
assert(p);
assert(ret);
saved_rindex = p->rindex;
r = dns_packet_read_key(p, &key, NULL);
if (r < 0)
goto fail;
if (key->class == DNS_CLASS_ANY ||
key->type == DNS_TYPE_ANY) {
r = -EBADMSG;
goto fail;
}
rr = <API key>(key);
if (!rr) {
r = -ENOMEM;
goto fail;
}
r = <API key>(p, &rr->ttl, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rdlength, NULL);
if (r < 0)
goto fail;
if (p->rindex + rdlength > p->size) {
r = -EBADMSG;
goto fail;
}
offset = p->rindex;
switch (rr->key->type) {
case DNS_TYPE_SRV:
r = <API key>(p, &rr->srv.priority, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->srv.weight, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->srv.port, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->srv.name, true, NULL);
break;
case DNS_TYPE_PTR:
case DNS_TYPE_NS:
case DNS_TYPE_CNAME:
case DNS_TYPE_DNAME:
r = <API key>(p, &rr->ptr.name, true, NULL);
break;
case DNS_TYPE_HINFO:
r = <API key>(p, &rr->hinfo.cpu, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->hinfo.os, NULL);
break;
case DNS_TYPE_SPF: /* exactly the same as TXT */
case DNS_TYPE_TXT:
if (rdlength <= 0) {
/* RFC 6763, section 6.1 suggests to treat
* empty TXT RRs as equivalent to a TXT record
* with a single empty string. */
r = strv_extend(&rr->txt.strings, "");
if (r < 0)
goto fail;
} else {
while (p->rindex < offset + rdlength) {
char *s;
r = <API key>(p, &s, NULL);
if (r < 0)
goto fail;
r = strv_consume(&rr->txt.strings, s);
if (r < 0)
goto fail;
}
}
r = 0;
break;
case DNS_TYPE_A:
r = <API key>(p, &rr->a.in_addr, sizeof(struct in_addr), NULL);
break;
case DNS_TYPE_AAAA:
r = <API key>(p, &rr->aaaa.in6_addr, sizeof(struct in6_addr), NULL);
break;
case DNS_TYPE_SOA:
r = <API key>(p, &rr->soa.mname, true, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->soa.rname, true, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->soa.serial, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->soa.refresh, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->soa.retry, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->soa.expire, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->soa.minimum, NULL);
break;
case DNS_TYPE_MX:
r = <API key>(p, &rr->mx.priority, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->mx.exchange, true, NULL);
break;
case DNS_TYPE_LOC: {
uint8_t t;
size_t pos;
r = <API key>(p, &t, &pos);
if (r < 0)
goto fail;
if (t == 0) {
rr->loc.version = t;
r = <API key>(p, &rr->loc.size, NULL);
if (r < 0)
goto fail;
if (!loc_size_ok(rr->loc.size)) {
r = -EBADMSG;
goto fail;
}
r = <API key>(p, &rr->loc.horiz_pre, NULL);
if (r < 0)
goto fail;
if (!loc_size_ok(rr->loc.horiz_pre)) {
r = -EBADMSG;
goto fail;
}
r = <API key>(p, &rr->loc.vert_pre, NULL);
if (r < 0)
goto fail;
if (!loc_size_ok(rr->loc.vert_pre)) {
r = -EBADMSG;
goto fail;
}
r = <API key>(p, &rr->loc.latitude, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->loc.longitude, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->loc.altitude, NULL);
if (r < 0)
goto fail;
break;
} else {
dns_packet_rewind(p, pos);
rr->unparseable = true;
goto unparseable;
}
}
case DNS_TYPE_DS:
r = <API key>(p, &rr->ds.key_tag, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->ds.algorithm, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->ds.digest_type, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rdlength - 4,
&rr->ds.digest, &rr->ds.digest_size,
NULL);
if (r < 0)
goto fail;
break;
case DNS_TYPE_SSHFP:
r = <API key>(p, &rr->sshfp.algorithm, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->sshfp.fptype, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rdlength - 2,
&rr->sshfp.key, &rr->sshfp.key_size,
NULL);
break;
case DNS_TYPE_DNSKEY: {
uint16_t flags;
uint8_t proto;
r = <API key>(p, &flags, NULL);
if (r < 0)
goto fail;
r = dnskey_parse_flags(rr, flags);
if (r < 0)
goto fail;
r = <API key>(p, &proto, NULL);
if (r < 0)
goto fail;
/* protocol is required to be always 3 */
if (proto != 3) {
r = -EBADMSG;
goto fail;
}
r = <API key>(p, &rr->dnskey.algorithm, NULL);
if (r < 0)
goto fail;
r = <API key>(p, rdlength - 4,
&rr->dnskey.key, &rr->dnskey.key_size,
NULL);
break;
}
case DNS_TYPE_RRSIG:
r = <API key>(p, &rr->rrsig.type_covered, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->rrsig.algorithm, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->rrsig.labels, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->rrsig.original_ttl, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->rrsig.expiration, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->rrsig.inception, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->rrsig.key_tag, NULL);
if (r < 0)
goto fail;
r = <API key>(p, &rr->rrsig.signer, false, NULL);
if (r < 0)
goto fail;
r = <API key>(p, offset + rdlength - p->rindex,
&rr->rrsig.signature, &rr->rrsig.signature_size,
NULL);
break;
default:
unparseable:
r = dns_packet_read(p, rdlength, &d, NULL);
if (r < 0)
goto fail;
rr->generic.data = memdup(d, rdlength);
if (!rr->generic.data) {
r = -ENOMEM;
goto fail;
}
rr->generic.size = rdlength;
break;
}
if (r < 0)
goto fail;
if (p->rindex != offset + rdlength) {
r = -EBADMSG;
goto fail;
}
*ret = rr;
rr = NULL;
if (start)
*start = saved_rindex;
return 0;
fail:
dns_packet_rewind(p, saved_rindex);
return r;
}
int dns_packet_extract(DnsPacket *p) {
_cleanup_(dns_question_unrefp) DnsQuestion *question = NULL;
_cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
size_t saved_rindex;
unsigned n, i;
int r;
if (p->extracted)
return 0;
saved_rindex = p->rindex;
dns_packet_rewind(p, <API key>);
n = DNS_PACKET_QDCOUNT(p);
if (n > 0) {
question = dns_question_new(n);
if (!question) {
r = -ENOMEM;
goto finish;
}
for (i = 0; i < n; i++) {
_cleanup_(<API key>) DnsResourceKey *key = NULL;
r = dns_packet_read_key(p, &key, NULL);
if (r < 0)
goto finish;
r = dns_question_add(question, key);
if (r < 0)
goto finish;
}
}
n = DNS_PACKET_RRCOUNT(p);
if (n > 0) {
answer = dns_answer_new(n);
if (!answer) {
r = -ENOMEM;
goto finish;
}
for (i = 0; i < n; i++) {
_cleanup_(<API key>) DnsResourceRecord *rr = NULL;
r = dns_packet_read_rr(p, &rr, NULL);
if (r < 0)
goto finish;
r = dns_answer_add(answer, rr);
if (r < 0)
goto finish;
}
}
p->question = question;
question = NULL;
p->answer = answer;
answer = NULL;
p->extracted = true;
r = 0;
finish:
p->rindex = saved_rindex;
return r;
}
static const char* const dns_rcode_table[<API key>] = {
[DNS_RCODE_SUCCESS] = "SUCCESS",
[DNS_RCODE_FORMERR] = "FORMERR",
[DNS_RCODE_SERVFAIL] = "SERVFAIL",
[DNS_RCODE_NXDOMAIN] = "NXDOMAIN",
[DNS_RCODE_NOTIMP] = "NOTIMP",
[DNS_RCODE_REFUSED] = "REFUSED",
[DNS_RCODE_YXDOMAIN] = "YXDOMAIN",
[DNS_RCODE_YXRRSET] = "YRRSET",
[DNS_RCODE_NXRRSET] = "NXRRSET",
[DNS_RCODE_NOTAUTH] = "NOTAUTH",
[DNS_RCODE_NOTZONE] = "NOTZONE",
[DNS_RCODE_BADVERS] = "BADVERS",
[DNS_RCODE_BADKEY] = "BADKEY",
[DNS_RCODE_BADTIME] = "BADTIME",
[DNS_RCODE_BADMODE] = "BADMODE",
[DNS_RCODE_BADNAME] = "BADNAME",
[DNS_RCODE_BADALG] = "BADALG",
[DNS_RCODE_BADTRUNC] = "BADTRUNC",
};
<API key>(dns_rcode, int);
static const char* const dns_protocol_table[_DNS_PROTOCOL_MAX] = {
[DNS_PROTOCOL_DNS] = "dns",
[DNS_PROTOCOL_MDNS] = "mdns",
[DNS_PROTOCOL_LLMNR] = "llmnr",
};
<API key>(dns_protocol, DnsProtocol);
static const char* const <API key>[<API key>] = {
[<API key>] = "RSAMD5",
[DNSSEC_ALGORITHM_DH] = "DH",
[<API key>] = "DSA",
[<API key>] = "ECC",
[<API key>] = "RSASHA1",
[<API key>] = "INDIRECT",
[<API key>] = "PRIVATEDNS",
[<API key>] = "PRIVATEOID",
};
<API key>(dnssec_algorithm, int); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.