text:
#ifndef DAV_SVN_H
#define DAV_SVN_H

#include <apr_tables.h>
#include <apr_xml.h>

#include <httpd.h>
#include <http_log.h>
#include <mod_dav.h>

#include "svn_error.h"
#include "svn_fs.h"
#include "svn_repos.h"
#include "svn_path.h"
#include "svn_xml.h"
#include "private/svn_dav_protocol.h"
#include "private/svn_skel.h"
#include "mod_authz_svn.h"

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

/* what the one VCC is called */
#define DAV_SVN__DEFAULT_VCC_NAME        "default"

/* a pool-key for the shared dav_svn_root used by autoversioning  */
#define DAV_SVN__AUTOVERSIONING_ACTIVITY "svn-autoversioning-activity"

/* Option values for SVNAllowBulkUpdates.  Note that
   it's important that CONF_BULKUPD_DEFAULT is 0 to make
   dav_svn_merge_dir_config do the right thing. */
typedef enum dav_svn__bulk_upd_conf {
    CONF_BULKUPD_DEFAULT,
    CONF_BULKUPD_ON,
    CONF_BULKUPD_OFF,
    CONF_BULKUPD_PREFER
} dav_svn__bulk_upd_conf;

/* dav_svn_repos
 *
 * Record information about the repository that a resource belongs to.
 * This structure will be shared between multiple resources so that we
 * can optimized our FS access.
 *
 * Note that we do not refcount this structure. Presumably, we will need
 * it throughout the life of the request. Therefore, we can just leave it
 * for the request pool to cleanup/close.
 *
 * Also, note that it is possible that two resources may have distinct
 * dav_svn_repos structures, yet refer to the same repository. This is
 * allowed by the SVN FS interface.
 *
 * ### should we attempt to merge them when we detect this situation in
 * ### places like is_same_resource, is_parent_resource, or copy/move?
 * ### I say yes: the FS will certainly have an easier time if there is
 * ### only a single FS open; otherwise, it will have to work a bit harder
 * ### to keep the things in sync.
 */
typedef struct dav_svn_repos {
  apr_pool_t *pool;     /* request_rec -> pool */

  /* Remember the root URL path of this repository (just a path; no
     scheme, host, or port).

     Example: the URI is "http://host/repos/file", this will be "/repos".

     This always starts with "/", and if there are any components
     beyond that, then it does not end with "/".
  */
  const char *root_path;

  /* Remember an absolute URL for constructing other URLs. In the above
     example, this would be "http://host" (note: no trailing slash)
  */
  const char *base_url;

  /* Remember the special URI component for this repository */
  const char *special_uri;

  /* This records the filesystem path to the SVN FS */
  const char *fs_path;

  /* The name of this repository */
  const char *repo_name;

  /* The repository filesystem basename */
  const char *repo_basename;

  /* The URI of the XSL transform for directory indexes */
  const char *xslt_uri;

  /* Whether autoversioning is active for this repository. */
  svn_boolean_t autoversioning;

  /* Whether bulk updates are allowed for this repository. */
  dav_svn__bulk_upd_conf bulk_updates;

  /* Whether HTTP protocol version 2 is allowed to be used. */
  svn_boolean_t v2_protocol;

  /* the open repository */
  svn_repos_t *repos;

  /* a cached copy of REPOS->fs above. */
  svn_fs_t *fs;

  /* the user operating against this repository */
  const char *username;

  /* is the client a Subversion client? */
  svn_boolean_t is_svn_client;

  /* The client's capabilities.  Maps SVN_RA_CAPABILITY_* keys to
     "yes" or "no" values.  If a capability is not yet discovered, it
     is absent from the table.  The table itself is allocated in this
     structure's 'pool' field, and the keys and values must have at
     least that lifetime.  Most likely the keys and values are
     constants anyway (and sufficiently well-informed internal code
     may therefore compare against those constants' addresses).  If
     'is_svn_client' is false, then 'capabilities' should be empty. */
  apr_hash_t *client_capabilities;

  /* The path to the activities db */
  const char *activities_db;

} dav_svn_repos;

/*
** dav_svn_private_restype: identifiers for our different private resources
**
** There are some resources within mod_dav_svn that are "privately defined".
** This isn't so much to prevent other people from knowing what they are,
** but merely that mod_dav doesn't have a standard name for them.
*/
enum dav_svn_private_restype {
  DAV_SVN_RESTYPE_UNSET,

  DAV_SVN_RESTYPE_ROOT_COLLECTION,      /* .../!svn/     */
  DAV_SVN_RESTYPE_VER_COLLECTION,       /* .../!svn/ver/ */
  DAV_SVN_RESTYPE_HIS_COLLECTION,       /* .../!svn/his/ */
  DAV_SVN_RESTYPE_WRK_COLLECTION,       /* .../!svn/wrk/ */
  DAV_SVN_RESTYPE_ACT_COLLECTION,       /* .../!svn/act/ */
  DAV_SVN_RESTYPE_VCC_COLLECTION,       /* .../!svn/vcc/ */
  DAV_SVN_RESTYPE_BC_COLLECTION,        /* .../!svn/bc/  */
  DAV_SVN_RESTYPE_BLN_COLLECTION,       /* .../!svn/bln/ */
  DAV_SVN_RESTYPE_WBL_COLLECTION,       /* .../!svn/wbl/ */
  DAV_SVN_RESTYPE_VCC,                  /* .../!svn/vcc/NAME */
  DAV_SVN_RESTYPE_PARENTPATH_COLLECTION,/* see SVNParentPath directive */

  /* new types in HTTP protocol v2: */
  DAV_SVN_RESTYPE_ME,                   /* .../!svn/me   */
  DAV_SVN_RESTYPE_REV_COLLECTION,       /* .../!svn/rev/ */
  DAV_SVN_RESTYPE_REVROOT_COLLECTION,   /* .../!svn/rvr/ */
  DAV_SVN_RESTYPE_TXN_COLLECTION,       /* .../!svn/txn/ */
  DAV_SVN_RESTYPE_TXNROOT_COLLECTION    /* .../!svn/txr/ */
};

/* store info about a root in a repository */
typedef struct dav_svn_root {
  /* If a root within the FS has been opened, the value is stored here.
     Otherwise, this field is NULL. */
  svn_fs_root_t *root;

  /* If the root has been opened, and it was opened for a specific revision,
     then it is contained in REV. If the root is unopened or corresponds to
     a transaction, then REV will be SVN_INVALID_REVNUM. */
  svn_revnum_t rev;

  /* If this resource is an activity or part of an activity, this specifies
     the ID of that activity. It may not (yet) correspond to a transaction
     in the FS.

     WORKING and ACTIVITY resources use this field.
  */
  const char *activity_id;

  /* If the root is part of a transaction, this contains the FS's tranaction
     name. It may be NULL if this root corresponds to a specific revision.
     It may also be NULL if we have not opened the root yet.

     WORKING and ACTIVITY resources use this field, as well as PRIVATE
     resources that directly represent either a txn or txn-root.
  */
  const char *txn_name;

  /* The optional vtxn name supplied by an HTTPv2 client and
     used in subsequent requests.  This may be NULL if the client
     is not using a vtxn name.

     PRIVATE resources that directly represent either a txn or
     txn-root use this field.
  */
  const char *vtxn_name;

  /* If the root is part of a transaction, this contains the FS's transaction
     handle. It may be NULL if this root corresponds to a specific revision.
     It may also be NULL if we have not opened the transaction yet.

     WORKING resources use this field.
  */
  svn_fs_txn_t *txn;

} dav_svn_root;

/* internal structure to hold information about this resource */
struct dav_resource_private {
  /* Path from the SVN repository root to this resource. This value has
     a leading slash. It will never have a trailing slash, even if the
     resource represents a collection.

     For example: URI is http://host/repos/file -- path will be "/file".

     NOTE: this path is from the URI and does NOT necessarily correspond
           to a path within the FS repository.
  */
  svn_stringbuf_t *uri_path;

  /* The FS repository path to this resource, with a leading "/". Note
     that this is "/" the root. This value will be NULL for resources
     that have no corresponding resource within the repository (such as
     the PRIVATE resources, Baselines, or Working Baselines). */
  const char *repos_path;

  /* the FS repository this resource is associated with */
  dav_svn_repos *repos;

  /* what FS root this resource occurs within */
  dav_svn_root root;

  /* for PRIVATE resources: the private resource type */
  enum dav_svn_private_restype restype;

  /* The request which created this resource.  We need this to
     generate subrequests. */
  request_rec *r;

  /* ### hack to deal with the Content-Type header on a PUT */
  int is_svndiff;

  /* ### record the base for computing a delta during a GET */
  const char *delta_base;

  /* SVNDIFF version we can transmit to the client.  */
  int svndiff_version;

  /* the value of any SVN_DAV_OPTIONS_HEADER that came in the request */
  const char *svn_client_options;

  /* the revnum value from a possible SVN_DAV_VERSION_NAME_HEADER */
  svn_revnum_t version_name;

  /* Hex MD5 digests for base text and resultant fulltext.
     Either or both of these may be null, in which case ignored. */
  const char *base_checksum;
  const char *result_checksum;

  /* was this resource auto-checked-out? */
  svn_boolean_t auto_checked_out;

  /* was this resource fetched using our public peg-/working-rev CGI
     interface (ie: /path/to/item?p=PEGREV)? */
  svn_boolean_t pegged;

  /* Cache any revprop change error */
  svn_error_t *revprop_error;

  /* was keyword substitution requested using our public CGI interface
     (ie: /path/to/item?kw=1)? */
  svn_boolean_t keyword_subst;
};

/* Every provider needs to define an opaque locktoken type. */
struct dav_locktoken
{
  /* This is identical to the 'token' field of an svn_lock_t. */
  const char *uuid_str;
};

/* for the repository referred to by this request, where is the SVN FS? */
const char *dav_svn__get_fs_path(request_rec *r);
const char *dav_svn__get_fs_parent_path(request_rec *r);

/* for the repository referred to by this request, is autoversioning active? */
svn_boolean_t dav_svn__get_autoversioning_flag(request_rec *r);

/* for the repository referred to by this request, are bulk updates allowed? */
dav_svn__bulk_upd_conf dav_svn__get_bulk_updates_flag(request_rec *r);

/* for the repository referred to by this request, are subrequests active? */
svn_boolean_t dav_svn__get_pathauthz_flag(request_rec *r);

/* for the repository referred to by this request, is txdelta caching active? */
svn_boolean_t dav_svn__get_txdelta_cache_flag(request_rec *r);

/* for the repository referred to by this request, is fulltext caching active? */
svn_boolean_t dav_svn__get_fulltext_cache_flag(request_rec *r);

/* for the repository referred to by this request, is revprop caching active? */
svn_boolean_t dav_svn__get_revprop_cache_flag(request_rec *r);

/* for the repository referred to by this request, are subrequests bypassed?
 * A function pointer if yes, NULL if not.
 */
authz_svn__subreq_bypass_func_t dav_svn__get_pathauthz_bypass(request_rec *r);

/* for the repository referred to by this request, is a GET of
   SVNParentPath allowed? */
svn_boolean_t dav_svn__get_list_parentpath_flag(request_rec *r);

/* For the repository referred to by this request, should HTTPv2
   protocol support be advertised?  Note that this also takes into
   account the support level expected of based on the specified
   master server version (if provided via SVNMasterVersion).  */
svn_boolean_t dav_svn__check_httpv2_support(request_rec *r);

/* For the repository referred to by this request, should ephemeral
   txnprop support be advertised?  */
svn_boolean_t dav_svn__check_ephemeral_txnprops_support(request_rec *r);

/* SPECIAL URI

   SVN needs to create many types of "pseudo resources" -- resources
   that don't correspond to the users' files/directories in the
   repository. Specifically, these are:

   - working resources
   - activities
   - version resources
   - version history resources

   Each of these will be placed under a portion of the URL namespace
   that defines the SVN repository. For example, let's say the user
   has configured an SVN repository at http://host/svn/repos. The
   special resources could be configured to live at .../!svn/ under
   that repository. Thus, an activity might be located at
   http://host/svn/repos/!svn/act/1234.

   The special URI is configurable on a per-server basis and defaults
   to "!svn".

   NOTE: the special URI is RELATIVE to the "root" of the
   repository. The root is generally available only to
   dav_svn_get_resource(). This is okay, however, because we can cache
   the root_dir when the resource structure is built.
*/

/* Return the repo-root-relative URI of the special namespace to be used for
 * this resource.
 * Comes from the <SVNSpecialURI> directive. */
/* ### Is this assumed to be URI-encoded? */
const char *dav_svn__get_special_uri(request_rec *r);

/* Return a descriptive name for the repository.
 * Comes from the <SVNReposName> directive. */
const char *dav_svn__get_repo_name(request_rec *r);

/* Return the server-relative URI of an XSL transform stylesheet.
   Comes from the <SVNIndexXSLT> directive. */
/* ### Is this assumed to be URI-encoded? */
const char *dav_svn__get_xslt_uri(request_rec *r);

/* Return the full URL of the master repository (for mirroring).
   Comes from the <SVNMasterURI> directive. */
/* ### Is this assumed to be URI-encoded? */
const char *dav_svn__get_master_uri(request_rec *r);

/* Return the version of the master server (used for mirroring) iff a
   master URI is in place for this location; otherwise, return NULL.
   Comes from the <SVNMasterVersion> directive. */
svn_version_t *dav_svn__get_master_version(request_rec *r);

/* Return the disk path to the activities db.
   Comes from the <SVNActivitiesDB> directive. */
const char *dav_svn__get_activities_db(request_rec *r);

/* Return the server-relative URI of the repository root.
   Comes from the <Location> directive. */
/* ### Is this assumed to be URI-encoded? */
const char *dav_svn__get_root_dir(request_rec *r);

/* Return the data compression level to be used over the wire. */
int dav_svn__get_compression_level(request_rec *r);

/* Return the hook script environment parsed from the configuration. */
const char *dav_svn__get_hooks_env(request_rec *r);

/** For HTTP protocol v2, these are the new URIs and URI stubs
    returned to the client in our OPTIONS response.  They all depend
    on the 'special uri', which is configurable in httpd.conf.  **/

/* Where REPORT requests are sent (typically "!svn/me") */
const char *dav_svn__get_me_resource_uri(request_rec *r);

/* For accessing revision resources (typically "!svn/rev") */
const char *dav_svn__get_rev_stub(request_rec *r);

/* For accessing REV/PATH pairs (typically "!svn/bc") */
const char *dav_svn__get_rev_root_stub(request_rec *r);

/* For accessing transaction resources (typically "!svn/txn") */
const char *dav_svn__get_txn_stub(request_rec *r);

/* For accessing transaction properties (typically "!svn/txr") */
const char *dav_svn__get_txn_root_stub(request_rec *r);

/* For accessing transaction resources (typically "!svn/vtxn") */
const char *dav_svn__get_vtxn_stub(request_rec *r);

/* For accessing transaction properties (typically "!svn/vtxr") */
const char *dav_svn__get_vtxn_root_stub(request_rec *r);

/*** activity.c ***/

/* Create a new transaction based on HEAD in REPOS, setting *PTXN_NAME
   to the name of that transaction.  REVPROPS is an optional hash of
   const char * property names and const svn_string_t * values which
   will be set as transactions properties on the transaction this
   function creates.  Use POOL for allocations.

   NOTE:  This function will overwrite the svn:author property, if
   any, found in REVPROPS.  */
dav_error *
dav_svn__create_txn(const dav_svn_repos *repos,
                    const char **ptxn_name,
                    apr_hash_t *revprops,
                    apr_pool_t *pool);

/* If it exists, abort the transaction named TXN_NAME from REPOS.  Use
   POOL for allocations. */
dav_error *
dav_svn__abort_txn(const dav_svn_repos *repos,
                   const char *txn_name,
                   apr_pool_t *pool);

/* Functions for looking up, storing, and deleting ACTIVITY->TXN mappings.  */
const char *
dav_svn__get_txn(const dav_svn_repos *repos, const char *activity_id);

dav_error *
dav_svn__delete_activity(const dav_svn_repos *repos, const char *activity_id);

dav_error *
dav_svn__store_activity(const dav_svn_repos *repos,
                        const char *activity_id,
                        const char *txn_name);

/* POST request handler.  (Used by HTTP protocol v2 clients only.)  */
int dav_svn__method_post(request_rec *r);

/*** repos.c ***/

/* generate an ETag for RESOURCE and return it, allocated in POOL. */
const char *
dav_svn__getetag(const dav_resource *resource, apr_pool_t *pool);

/*
  Construct a working resource for a given resource.

  The internal information (repository, URL parts, etc) for the new
  resource comes from BASE, the activity to use is specified by
  ACTIVITY_ID, and the name of the transaction is specified by
  TXN_NAME. These will be assembled into a new dav_resource and
  returned.

  If TWEAK_IN_PLACE is non-zero, then directly tweak BASE into a
  working resource and return NULL.
*/
dav_resource *
dav_svn__create_working_resource(dav_resource *base,
                                 const char *activity_id,
                                 const char *txn_name,
                                 int tweak_in_place);
/*
   Convert a working RESOURCE back into a regular one, in-place.

   In particular: change the resource type to regular, removing the
   'working' flag, change the fs root from a txn-root to a rev-root,
   and set the URL back into either a public URL or bc URL.
*/
dav_error *
dav_svn__working_to_regular_resource(dav_resource *resource);

/*
   Given a version-resource URI, construct a new version-resource in
   POOL and return it in  *VERSION_RES.
*/
dav_error *
dav_svn__create_version_resource(dav_resource **version_res,
                                 const char *uri,
                                 apr_pool_t *pool);

extern const dav_hooks_repository dav_svn__hooks_repository;

/*** deadprops.c ***/
extern const dav_hooks_propdb dav_svn__hooks_propdb;

/*** lock.c ***/
extern const dav_hooks_locks dav_svn__hooks_locks;

/*** version.c ***/

/* For an autoversioning commit, a helper function which attaches an
   auto-generated 'svn:log' property to a txn, as well as a property
   that indicates the revision was made via autoversioning. */
svn_error_t *
dav_svn__attach_auto_revprops(svn_fs_txn_t *txn,
                              const char *fs_path,
                              apr_pool_t *pool);

/* Hook function of types 'checkout' and 'checkin', as defined in
   mod_dav.h's versioning provider hooks table (see dav_hooks_vsn).  */
dav_error *
dav_svn__checkout(dav_resource *resource,
                  int auto_checkout,
                  int is_unreserved,
                  int is_fork_ok,
                  int create_activity,
                  apr_array_header_t *activities,
                  dav_resource **working_resource);

dav_error *
dav_svn__checkin(dav_resource *resource,
                 int keep_checked_out,
                 dav_resource **version_resource);

/* Helper for reading lock-tokens out of request bodies, by looking
   for cached body in R->pool's userdata.

   Return a hash that maps (const char *) absolute fs paths to (const
   char *) locktokens.  Allocate the hash and all keys/vals in POOL.
   PATH_PREFIX is the prefix we need to prepend to each relative
   'lock-path' in the xml in order to create an absolute fs-path.  */
dav_error *
dav_svn__build_lock_hash(apr_hash_t **locks,
                         request_rec *r,
                         const char *path_prefix,
                         apr_pool_t *pool);

/* Helper: push all of the lock-tokens (hash values) in LOCKS into
   RESOURCE's already-open svn_fs_t. */
dav_error *
dav_svn__push_locks(dav_resource *resource,
                    apr_hash_t *locks,
                    apr_pool_t *pool);

extern const dav_hooks_vsn dav_svn__hooks_vsn;

/*** liveprops.c ***/

extern const dav_liveprop_group dav_svn__liveprop_group;

/*
  LIVE PROPERTY HOOKS

  These are standard hooks defined by mod_dav. We implement them to expose
  various live properties on the resources under our control.

  gather_propsets: appends URIs into the array; the property set URIs are
                   used to specify which sets of custom properties we
                   define/expose.
  find_liveprop: given a namespace and name, return the hooks for the
                 provider who defines that property.
  insert_all_liveprops: for a given resource, insert all of the live
                        properties defined on that resource. The properties
                        are inserted according to the WHAT parameter.
*/
void dav_svn__gather_propsets(apr_array_header_t *uris);

int
dav_svn__find_liveprop(const dav_resource *resource,
                       const char *ns_uri,
                       const char *name,
                       const dav_hooks_liveprop **hooks);

void
dav_svn__insert_all_liveprops(request_rec *r,
                              const dav_resource *resource,
                              dav_prop_insert what,
                              apr_text_header *phdr);

/*** merge.c ***/

/* Generate the HTTP response body for a successful MERGE. */
/* ### more docco */
dav_error *
dav_svn__merge_response(ap_filter_t *output,
                        const dav_svn_repos *repos,
                        svn_revnum_t new_rev,
                        const char *post_commit_err,
                        apr_xml_elem *prop_elem,
                        svn_boolean_t disable_merge_response,
                        apr_pool_t *pool);

/*** reports/ ***/

/* The list of Subversion's custom REPORTs. */
/* ### should move these report names to a public header to share with
   ### the client (and third parties). */
static const dav_report_elem dav_svn__reports_list[] = {
  { SVN_XML_NAMESPACE, "update-report" },
  { SVN_XML_NAMESPACE, "log-report" },
  { SVN_XML_NAMESPACE, "dated-rev-report" },
  { SVN_XML_NAMESPACE, "get-locations" },
  { SVN_XML_NAMESPACE, "get-location-segments" },
  { SVN_XML_NAMESPACE, "file-revs-report" },
  { SVN_XML_NAMESPACE, "get-locks-report" },
  { SVN_XML_NAMESPACE, "replay-report" },
  { SVN_XML_NAMESPACE, "get-deleted-rev-report" },
  { SVN_XML_NAMESPACE, SVN_DAV__MERGEINFO_REPORT },
  { SVN_XML_NAMESPACE, SVN_DAV__INHERITED_PROPS_REPORT },
  { NULL, NULL },
};

/* The various report handlers, defined in reports/, and used by version.c.  */
dav_error *
dav_svn__update_report(const dav_resource *resource,
                       const apr_xml_doc *doc,
                       ap_filter_t *output);
dav_error *
dav_svn__log_report(const dav_resource *resource,
                    const apr_xml_doc *doc,
                    ap_filter_t *output);
dav_error *
dav_svn__dated_rev_report(const dav_resource *resource,
                          const apr_xml_doc *doc,
                          ap_filter_t *output);
dav_error *
dav_svn__get_locations_report(const dav_resource *resource,
                              const apr_xml_doc *doc,
                              ap_filter_t *output);
dav_error *
dav_svn__get_location_segments_report(const dav_resource *resource,
                                      const apr_xml_doc *doc,
                                      ap_filter_t *output);
dav_error *
dav_svn__file_revs_report(const dav_resource *resource,
                          const apr_xml_doc *doc,
                          ap_filter_t *output);
dav_error *
dav_svn__replay_report(const dav_resource *resource,
                       const apr_xml_doc *doc,
                       ap_filter_t *output);
dav_error *
dav_svn__get_mergeinfo_report(const dav_resource *resource,
                              const apr_xml_doc *doc,
                              ap_filter_t *output);
dav_error *
dav_svn__get_locks_report(const dav_resource *resource,
                          const apr_xml_doc *doc,
                          ap_filter_t *output);

dav_error *
dav_svn__get_deleted_rev_report(const dav_resource *resource,
                                const apr_xml_doc *doc,
                                ap_filter_t *output);

dav_error *
dav_svn__get_inherited_props_report(const dav_resource *resource,
                                    const apr_xml_doc *doc,
                                    ap_filter_t *output);

/*** posts/ ***/

/* The various POST handlers, defined in posts/, and used by repos.c.  */
dav_error *
dav_svn__post_create_txn(const dav_resource *resource,
                         svn_skel_t *request_skel,
                         ap_filter_t *output);
dav_error *
dav_svn__post_create_txn_with_props(const dav_resource *resource,
                                    svn_skel_t *request_skel,
                                    ap_filter_t *output);

/*** authz.c ***/

/* A baton needed by dav_svn__authz_read_func(). */
typedef struct dav_svn__authz_read_baton
{
  /* The original request, needed to generate a subrequest. */
  request_rec *r;

  /* We need this to construct a URI based on a repository abs path. */
  const dav_svn_repos *repos;

} dav_svn__authz_read_baton;

/* Return TRUE iff the current user (as determined by Apache's
   authentication system) has permission to read PATH in REPOS at REV
   (where an invalid REV means "HEAD").  This will invoke any authz
   modules loaded into Apache unless this Subversion location has been
   configured to bypass those in favor of a direct lookup in the
   Subversion authz subsystem.  Use POOL for any temporary allocation.
*/
svn_boolean_t
dav_svn__allow_read(request_rec *r,
                    const dav_svn_repos *repos,
                    const char *path,
                    svn_revnum_t rev,
                    apr_pool_t *pool);

/* Return TRUE iff the current user (as determined by Apache's
   authentication system) has permission to read RESOURCE in REV
   (where an invalid REV means "HEAD").  This will invoke any authz
   modules loaded into Apache unless this Subversion location has been
   configured to bypass those in favor of a direct lookup in the
   Subversion authz subsystem.  Use POOL for any temporary allocation.
*/
svn_boolean_t
dav_svn__allow_read_resource(const dav_resource *resource,
                             svn_revnum_t rev,
                             apr_pool_t *pool);

/* Return TRUE iff the current user (as determined by Apache's
   authentication system) has permission to read repository REPOS_NAME.
   This will invoke any authz modules loaded into Apache unless this
   Subversion location has been configured to bypass those in favor of a
   direct lookup in the Subversion authz subsystem. Use POOL for any
   temporary allocation.
   IMPORTANT: R must be request for DAV_SVN_RESTYPE_PARENTPATH_COLLECTION
   resource.
*/
svn_boolean_t
dav_svn__allow_list_repos(request_rec *r,
                          const char *repos_name,
                          apr_pool_t *pool);

/* If authz is enabled in the specified BATON, return a read authorization
   function. Otherwise, return NULL. */
svn_repos_authz_func_t
dav_svn__authz_read_func(dav_svn__authz_read_baton *baton);

/*** util.c ***/

/* A wrapper around mod_dav's dav_new_error_tag, mod_dav_svn uses this
   instead of the mod_dav function to enable special mod_dav_svn specific
   processing.  See dav_new_error_tag for parameter documentation.
   Note that DESC may be null (it's hard to track this down from
   dav_new_error_tag()'s documentation, but see the dav_error type,
   which says that its desc field may be NULL).

   If ERROR_ID is 0, SVN_ERR_RA_DAV_REQUEST_FAILED will be used as a
   default value for the error code.
*/
dav_error *
dav_svn__new_error_tag(apr_pool_t *pool,
                       int status,
                       int error_id,
                       const char *desc,
                       const char *namespace,
                       const char *tagname);

/* A wrapper around mod_dav's dav_new_error, mod_dav_svn uses this
   instead of the mod_dav function to enable special mod_dav_svn specific
   processing.  See dav_new_error for parameter documentation.
   Note that DESC may be null (it's hard to track this down from
   dav_new_error()'s documentation, but see the dav_error type,
   which says that its desc field may be NULL).

   If ERROR_ID is 0, SVN_ERR_RA_DAV_REQUEST_FAILED will be used as a
   default value for the error code.
*/
dav_error *
dav_svn__new_error(apr_pool_t *pool,
                   int status,
                   int error_id,
                   const char *desc);

/* Convert an svn_error_t into a dav_error, pushing another error based on
   MESSAGE if MESSAGE is not NULL.  Use the provided HTTP status for the
   DAV errors.  Allocate new DAV errors from POOL.

   NOTE: this function destroys (cleanly, of course) SERR after it has
   copied/converted its data to the new DAV error.

   NOTE: MESSAGE needs to hang around for the lifetime of the error since
   the current implementation doesn't copy it!  Lots of callers pass static
   string constant. */
dav_error *
dav_svn__convert_err(svn_error_t *serr,
                     int status,
                     const char *message,
                     apr_pool_t *pool);

/* Compare (PATH in ROOT) to (PATH in ROOT/PATH's created_rev).

   If these nodes are identical, then return the created_rev.

   If the nodes aren't identical, or if PATH simply doesn't exist in
   the created_rev, then return the revision represented by ROOT.

   (This is a helper to functions that want to build version-urls and
    use the CR if possible.) */
svn_revnum_t
dav_svn__get_safe_cr(svn_fs_root_t *root, const char *path, apr_pool_t *pool);

/* Construct various kinds of URIs.

   REPOS is always required, as all URIs will be built to refer to elements
   within that repository. WHAT specifies the type of URI to build. The
   ADD_HREF flag determines whether the URI is to be wrapped inside of
   <D:href>uri</D:href> elements (for inclusion in a response).

   Different pieces of information are required for the various URI types:

   ACT_COLLECTION: no additional params required
   BASELINE:       REVISION should be specified
   BC:             REVISION should be specified
   PUBLIC:         PATH should be specified with a leading slash
   VERSION:        REVISION and PATH should be specified
   VCC:            no additional params required
*/
enum dav_svn__build_what {
  DAV_SVN__BUILD_URI_ACT_COLLECTION, /* the collection of activities */
  DAV_SVN__BUILD_URI_BASELINE,   /* a Baseline */
  DAV_SVN__BUILD_URI_BC,         /* a Baseline Collection */
  DAV_SVN__BUILD_URI_PUBLIC,     /* the "public" VCR */
  DAV_SVN__BUILD_URI_VERSION,    /* a Version Resource */
  DAV_SVN__BUILD_URI_VCC,        /* a Version Controlled Configuration */
  DAV_SVN__BUILD_URI_REVROOT     /* HTTPv2: Revision Root resource */
};

const char *
dav_svn__build_uri(const dav_svn_repos *repos,
                   enum dav_svn__build_what what,
                   svn_revnum_t revision,
                   const char *path,
                   int add_href,
                   apr_pool_t *pool);

/* Simple parsing of a URI. This is used for URIs which appear within a
   request body. It enables us to verify and break out the necessary pieces
   to figure out what is being referred to.

   ### this is horribly duplicative with the parsing functions in repos.c
   ### for now, this implements only a minor subset of the full range of
   ### URIs which we may need to parse. it also ignores any scheme, host,
   ### and port in the URI and simply assumes it refers to the same server.
*/
typedef struct dav_svn__uri_info {
  svn_revnum_t rev;
  const char *repos_path;
  const char *activity_id;
} dav_svn__uri_info;

svn_error_t *
dav_svn__simple_parse_uri(dav_svn__uri_info *info,
                          const dav_resource *relative,
                          const char *uri,
                          apr_pool_t *pool);

/* Test the request R to determine if we should return the list of
 * repositories at the parent path.  Only true if SVNListParentPath directive
 * is 'on' and the request is for our configured root path. */
svn_boolean_t
dav_svn__is_parentpath_list(request_rec *r);

int dav_svn__find_ns(const apr_array_header_t *namespaces, const char *uri);

/*** Brigade I/O wrappers ***/

/* Write LEN bytes from DATA to OUTPUT using BB.  */
svn_error_t *dav_svn__brigade_write(apr_bucket_brigade *bb,
                                    ap_filter_t *output,
                                    const char *buf,
                                    apr_size_t len);

/* Write NULL-terminated string STR to OUTPUT using BB.  */
svn_error_t *dav_svn__brigade_puts(apr_bucket_brigade *bb,
                                   ap_filter_t *output,
                                   const char *str);

/* Write data to OUTPUT using BB, using FMT as the output format string.  */
svn_error_t *dav_svn__brigade_printf(apr_bucket_brigade *bb,
                                     ap_filter_t *output,
                                     const char *fmt,
                                     ...)
  __attribute__((format(printf, 3, 4)));

/* Test PATH for canonicalness (defined as "what won't make the
   svn_path_* functions immediately explode"), returning an
   HTTP_BAD_REQUEST error tag if the test fails. */
dav_error *dav_svn__test_canonical(const char *path, apr_pool_t *pool);

/* Convert @a serr into a dav_error.  If @a new_msg is non-NULL, use
   @a new_msg in the returned error, and write the original
   @a serr->message to httpd's log.  Destroy the passed-in @a serr,
   similarly to dav_svn__convert_err().

   @a new_msg is usually a "sanitized" version of @a serr->message.
   That is, if @a serr->message contains security-sensitive data,
   @a new_msg does not.

   The purpose of sanitization is to prevent security-sensitive data
   from being transmitted over the network to the client.  The error
   messages produced by various APIs (e.g., svn_fs, svn_repos) may
   contain security-sensitive data such as the actual server file
   system's path to the repository.  We don't want to send that to the
   client, but we do want to log the real error on the server side.
 */
dav_error *
dav_svn__sanitize_error(svn_error_t *serr,
                        const char *new_msg,
                        int http_status,
                        request_rec *r);

/* Return a writable generic stream that will encode its output to base64
   and send it to the Apache filter OUTPUT using BB.  Allocate the stream in
   POOL. */
svn_stream_t *
dav_svn__make_base64_output_stream(apr_bucket_brigade *bb,
                                   ap_filter_t *output,
                                   apr_pool_t *pool);

/* In INFO->r->subprocess_env set "SVN-ACTION" to LINE, "SVN-REPOS" to
 * INFO->repos->fs_path, and "SVN-REPOS-NAME" to INFO->repos->repo_basename. */
void
dav_svn__operational_log(struct dav_resource_private *info, const char *line);

/* Flush BB if it's okay and useful to do so, but treat PREFERRED_ERR
 * as a more important error to return (if it is non-NULL).
 *
 * This is intended to be used at the end of response processing,
 * probably called as a direct return generator, like so:
 *
 *   return dav_svn__final_flush_or_error(r, bb, output, derr, resource->pool);
 *
 * SOME BACKGROUND INFO:
 *
 * We don't flush the brigade unless there's something in it to
 * flush; that way, we have the opportunity to package a dav_error up
 * for transmission back to the client.
 *
 * To understand this, see mod_dav.c:dav_method_report(): as long as
 * it doesn't think we've sent anything to the client, it'll send
 * the real error, which is what we'd prefer.  This situation is
 * described in httpd-2.2.6/modules/dav/main/mod_dav.c, line 4066,
 * in the comment in dav_method_report() that says:
 *
 *    If an error occurred during the report delivery, there's
 *    basically nothing we can do but abort the connection and
 *    log an error.  This is one of the limitations of HTTP; it
 *    needs to "know" the entire status of the response before
 *    generating it, which is just impossible in these streamy
 *    response situations.
 *
 * In other words, flushing the brigade causes r->sent_bodyct (see
 * dav_method_report()) to become non-zero, even if we hadn't tried to
 * send any data to the brigade yet.  So we don't flush unless data
 * was actually sent.
 */
dav_error *
dav_svn__final_flush_or_error(request_rec *r, apr_bucket_brigade *bb,
                              ap_filter_t *output, dav_error *preferred_err,
                              apr_pool_t *pool);

/* Log a DAV error response.
 *
 * NOTE: Copied from mod_dav's dav_log_err which is not public.
 */
void dav_svn__log_err(request_rec *r,
                      dav_error *err,
                      int level);

/* Send a "standardized" DAV error response based on the ERR's
 * namespace and tag.
 *
 * NOTE:  This was copied pretty much directory from mod_dav's
 * dav_error_response_tag() function which is, sadly, not public.
 */
int dav_svn__error_response_tag(request_rec *r, dav_error *err);

/* Set *SKEL to a parsed skel read from the body of request R, and
 * allocated in POOL.
 */
int dav_svn__parse_request_skel(svn_skel_t **skel, request_rec *r,
                                apr_pool_t *pool);

/*** mirror.c ***/

/* Perform the fixup hook for the R request.  */
int dav_svn__proxy_request_fixup(request_rec *r);

/* An Apache input filter which rewrites the locations in headers and
   request body.  It reads from filter F using BB data, MODE mode, BLOCK
   blocking strategy, and READBYTES. */
apr_status_t dav_svn__location_in_filter(ap_filter_t *f,
                                         apr_bucket_brigade *bb,
                                         ap_input_mode_t mode,
                                         apr_read_type_e block,
                                         apr_off_t readbytes);

/* An Apache output filter F which rewrites the response headers for
 * location headers.  It will modify the stream in BB. */
apr_status_t dav_svn__location_header_filter(ap_filter_t *f,
                                             apr_bucket_brigade *bb);

/* An Apache output filter F which rewrites the response body for
 * location headers.  It will modify the stream in BB. */
apr_status_t dav_svn__location_body_filter(ap_filter_t *f,
                                           apr_bucket_brigade *bb);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* DAV_SVN_H */


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="generator" content="Hugo 0.57.2" />
<meta property="og:title" content="Contact Information" />
<meta name="twitter:title" content="Contact Information"/>
<meta itemprop="name" content="Contact Information"><meta property="og:description" content="If you’d like to contact us by email - organizers-seattle-2017@devopsdays.org Our local team
Rob CummingsOrganizer    Dominica DeGrandisOrganizer    Dan DicamilloOrganizer    Jeremy DycheOrganizer    Michael GoetzOrganizer    Ken MugrageOrganizer Ken promotes DevOps and Continuous Delivery for ThoughtWorks. He’ll be the guy with dog hair on his clothes.     Michael TowbinOrganizer    Todd WilsonOrganizer       .organizer-image { max-width: 100%; }  The core devopsdays organizer group" />
  <meta name="twitter:description" content="If you’d like to contact us by email - organizers-seattle-2017@devopsdays.org Our local team
Rob CummingsOrganizer    Dominica DeGrandisOrganizer    Dan DicamilloOrganizer    Jeremy DycheOrganizer    Michael GoetzOrganizer    Ken MugrageOrganizer Ken promotes DevOps and Continuous Delivery for ThoughtWorks. He’ll be the guy with dog hair on his clothes.     Michael TowbinOrganizer    Todd WilsonOrganizer       .organizer-image { max-width: 100%; }  The core devopsdays organizer group" />
  <meta itemprop="description" content="If you’d like to contact us by email - organizers-seattle-2017@devopsdays.org Our local team
Rob CummingsOrganizer    Dominica DeGrandisOrganizer    Dan DicamilloOrganizer    Jeremy DycheOrganizer    Michael GoetzOrganizer    Ken MugrageOrganizer Ken promotes DevOps and Continuous Delivery for ThoughtWorks. He’ll be the guy with dog hair on his clothes.     Michael TowbinOrganizer    Todd WilsonOrganizer       .organizer-image { max-width: 100%; }  The core devopsdays organizer group"><meta name="twitter:site" content="@devopsdays">
<meta property="og:type" content="event" />
<meta property="og:url" content="/events/2017-seattle/contact/" /><meta name="twitter:creator" content="@devopsdayssea" /><meta name="twitter:label1" value="Event" />
  <meta name="twitter:data1" value="devopsdays Seattle 2017" /><meta name="twitter:label2" value="Dates" />
    <meta name="twitter:data2" value="April 26 - 27, 2017" /><meta property="og:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta itemprop="image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta property="fb:app_id" content="1904065206497317" /><meta itemprop="wordCount" content="100">
<title>Contact Information
</title>

<link href="/css/site.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700" rel="stylesheet"><link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">

      <link href="/events/index.xml" rel="alternate" type="application/rss+xml" title="DevOpsDays" />
      <link href="/events/index.xml" rel="feed" type="application/rss+xml" title="DevOpsDays" />

  DevOpsDays

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

</button>

events

blog

sponsor

speaking

organizing

about

  Seattle
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar2">

</button>

                  program

                  speakers

                  location

                  registration

                  sponsor

                  contact

                  conduct

devopsdays Seattle - Contact Information

If you’d like to contact us by email - organizers-seattle-2017@devopsdays.org

Our local team

Rob Cummings

Organizer

Dominica DeGrandis

Organizer

Dan Dicamillo

Organizer

Jeremy Dyche

Organizer

Michael Goetz

Organizer

Ken Mugrage

Organizer

                  Ken promotes DevOps and Continuous Delivery for ThoughtWorks. He’ll be the guy with dog hair on his clothes.

Michael Towbin

Organizer

Todd Wilson

Organizer

The core devopsdays organizer group

Active
Bridget Kromhout (lead), Kris Buytaert, Serhat Can, Jennifer Davis, Bernd Erk, Rafael Gomes, Nathen Harvey, Matthew Jones, Dan Maher, Ken Mugrage, Mike Rosado, Andrew Clay Shafer, Matt Stratton (web team lead), John Willis

Historic
Patrick Debois (founder), Damon Edwards, Anthony Goddard, Lindsay Holmwood, Gildas Le Nadan, Stephen Nelson-Smith, Julian Simpson, Christian Trabold, John Vincent, James Wickett

Gold Sponsors

Silver Sponsors

Bronze Sponsors

Community Sponsors

@DEVOPSDAYS

BLOG

10 years of devopsdays

by Kris Buytaert - 10 May, 2019

It’s hard to believe but it is almost 10 years ago since #devopsdays happened for the first time in Gent. Back then there were almost 70 of us talking about topics that were of interest to both Operations and Development, we were exchanging our ideas and experiences `on how we were improving the quality of software delivery.
Our ideas got started on the crossroads of Open Source, Agile and early Cloud Adoption.

Blogs

10 May, 2019

Feed

CFP OPEN
Campinas
Macapá
Shanghai
Recife
Charlotte
Prague
Tokyo
Salt Lake City

Propose a talk at an event near you!

About

    devopsdays is a worldwide community conference series for anyone interested in IT improvement.

    About devopsdays

    Privacy Policy

    Code of Conduct

redpajama_set_name: RedPajamaGithub


text:
package org.jkiss.dbeaver.ui.editors.sql;

import org.eclipse.jface.action.*;
import org.eclipse.ui.IEditorInput;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBPScriptObject;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.ui.DBeaverIcons;
import org.jkiss.dbeaver.ui.UIIcon;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.editors.IDatabaseEditorInput;
import org.jkiss.dbeaver.ui.editors.sql.handlers.OpenHandler;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Display Source text (Read Only)
 */
public class SQLSourceViewer<T extends DBPScriptObject & DBSObject> extends SQLEditorNested<T> {

    private IAction OPEN_CONSOLE_ACTION = new Action("Open in SQL console", DBeaverIcons.getImageDescriptor(UIIcon.SQL_CONSOLE)) {
        @Override
        public void run()
        {
            final DBPDataSource dataSource = getDataSource();
            OpenHandler.openSQLConsole(
                UIUtils.getActiveWorkbenchWindow(),
                dataSource == null ? null : dataSource.getContainer(),
                "Source",
                getDocument().get()
            );
        }
    };

    @Override
    protected String getSourceText(DBRProgressMonitor monitor) throws DBException
    {
        return getSourceObject().getObjectDefinitionText(monitor, getSourceOptions());
    }

    protected Map<String, Object> getSourceOptions() {
        IEditorInput editorInput = getEditorInput();
        Map<String, Object> options = new HashMap<>();
        if (editorInput instanceof IDatabaseEditorInput) {
            Collection<String> attributeNames = ((IDatabaseEditorInput)editorInput).getAttributeNames();
            options.put(DBPScriptObject.OPTION_DDL_SOURCE, true);
            if (!attributeNames.isEmpty()) {
                for (String name : attributeNames) {
                    Object attribute = ((IDatabaseEditorInput)editorInput).getAttribute(name);
                    options.put(name, attribute);
                }
            }
        }
        return options;
    }

    @Override
    protected boolean isReadOnly()
    {
        return true;
    }

    @Override
    protected void setSourceText(DBRProgressMonitor monitor, String sourceText)
    {
    }

    @Override
    protected void contributeEditorCommands(IContributionManager toolBarManager) {
        super.contributeEditorCommands(toolBarManager);
        toolBarManager.add(new Separator());
        toolBarManager.add(OPEN_CONSOLE_ACTION);
    }

}


text:
namespace Microsoft.Azure.Management.DevTestLabs.Models
{
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using System.Runtime.Serialization;

    /// <summary>
    /// Defines values for TransportProtocol.
    /// </summary>
    public static class TransportProtocol
    {
        public const string Tcp = "Tcp";
        public const string Udp = "Udp";
    }
}


text: <title>Play God</title><meta http-equiv='refresh' content='0.01'>


text:
#ifdef RTMP_MAC_USB

#include	"rt_config.h"

#define MAX_VENDOR_REQ_RETRY_COUNT  10

/*
	========================================================================

	Routine Description: NIC initialization complete

	Arguments:

	Return Value:

	IRQL =

	Note:

	========================================================================
*/

static NTSTATUS	RTUSBFirmwareRun(
	IN	PRTMP_ADAPTER	pAd)
{
	NTSTATUS	Status;

	Status = RTUSB_VendorRequest(
		pAd,
		USBD_TRANSFER_DIRECTION_OUT,
		DEVICE_VENDOR_REQUEST_OUT,
		0x01,
		0x8,
		0,
		NULL,
		0);

	return Status;
}

/*
	========================================================================

	Routine Description: Get current firmware operation mode (Return Value)

	Arguments:

	Return Value:
		0 or 1 = Downloaded by host driver
		others = Driver doesn't download firmware

	IRQL =

	Note:

	========================================================================
*/
NTSTATUS	RTUSBFirmwareOpmode(
	IN	PRTMP_ADAPTER	pAd,
	OUT	PULONG			pValue)
{
	NTSTATUS	Status;

	Status = RTUSB_VendorRequest(
		pAd,
		(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
		DEVICE_VENDOR_REQUEST_IN,
		0x1,
		0x11,
		0,
		pValue,
		4);
	return Status;
}

/*
	========================================================================

	Routine Description: Write Firmware to NIC.

	Arguments:

	Return Value:

	IRQL =

	Note:

	========================================================================
*/
NTSTATUS RTUSBFirmwareWrite(
	IN PRTMP_ADAPTER pAd,
	IN PUCHAR		pFwImage,
	IN ULONG		FwLen)
{
	UINT32		MacReg;
	NTSTATUS 	Status;
//	ULONG 		i;
	USHORT		writeLen;
	//ULONG		FMode = 0;

	Status = RTUSBReadMACRegister(pAd, MAC_CSR0, &MacReg);

	/* write firmware */
	writeLen = FwLen;
	RTUSBMultiWrite(pAd, FIRMWARE_IMAGE_BASE, pFwImage, writeLen);

	Status = RTUSBWriteMACRegister(pAd, 0x7014, 0xffffffff);
	Status = RTUSBWriteMACRegister(pAd, 0x701c, 0xffffffff);

	/* change 8051 from ROM to RAM */
	Status = RTUSBFirmwareRun(pAd);

	return Status;
}

NTSTATUS	RTUSBVenderReset(
	IN	PRTMP_ADAPTER	pAd)
{
	NTSTATUS	Status;
	DBGPRINT_RAW(RT_DEBUG_ERROR, ("-->RTUSBVenderReset\n"));
	Status = RTUSB_VendorRequest(
		pAd,
		USBD_TRANSFER_DIRECTION_OUT,
		DEVICE_VENDOR_REQUEST_OUT,
		0x01,
		0x1,
		0,
		NULL,
		0);

	DBGPRINT_RAW(RT_DEBUG_ERROR, ("<--RTUSBVenderReset\n"));
	return Status;
}
/*
	========================================================================

	Routine Description: Read various length data from RT2573

	Arguments:

	Return Value:

	IRQL =

	Note:

	========================================================================
*/
NTSTATUS	RTUSBMultiRead(
	IN	PRTMP_ADAPTER	pAd,
	IN	USHORT			Offset,
	OUT	PUCHAR			pData,
	IN	USHORT			length)
{
	NTSTATUS	Status;

	Status = RTUSB_VendorRequest(
		pAd,
		(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
		DEVICE_VENDOR_REQUEST_IN,
		0x7,
		0,
		Offset,
		pData,
		length);

	return Status;
}

/*
	========================================================================

	Routine Description: Write various length data to RT USB Wifi device, the maxima length should not large than 65535 bytes.

	Arguments:

	Return Value:

	IRQL =

	Note:
		Use this funciton carefully cause it may not stable in some special USB host controllers.

	========================================================================
*/
NTSTATUS RTUSBMultiWrite_nBytes(
	IN	PRTMP_ADAPTER	pAd,
	IN	USHORT			Offset,
	IN	PUCHAR			pData,
	IN	USHORT			length,
	IN	USHORT			batchLen)
{
	NTSTATUS Status = STATUS_SUCCESS;
	USHORT index = Offset, actLen = batchLen, leftLen = length;
	PUCHAR pSrc = pData;

	do
	{
		actLen = (actLen > batchLen ? batchLen : actLen);
		Status = RTUSB_VendorRequest(
			pAd,
			USBD_TRANSFER_DIRECTION_OUT,
			DEVICE_VENDOR_REQUEST_OUT,
			0x6,
			0,
			index,
			pSrc,
			actLen);

		if (Status != STATUS_SUCCESS)
		{
			DBGPRINT(RT_DEBUG_ERROR, ("VendrCmdMultiWrite_nBytes failed!\n"));
			break;
		}

		index += actLen;
		leftLen -= actLen;
		pSrc = pSrc + actLen;
	}while(leftLen > 0);

	return Status;
}

/*
	========================================================================

	Routine Description: Write various length data to RT2573

	Arguments:

	Return Value:

	IRQL =

	Note:

	========================================================================
*/
NTSTATUS	RTUSBMultiWrite_OneByte(
	IN	PRTMP_ADAPTER	pAd,
	IN	USHORT			Offset,
	IN	PUCHAR			pData)
{
	NTSTATUS	Status;

	// TODO: In 2870, use this funciton carefully cause it's not stable.
	Status = RTUSB_VendorRequest(
		pAd,
		USBD_TRANSFER_DIRECTION_OUT,
		DEVICE_VENDOR_REQUEST_OUT,
		0x6,
		0,
		Offset,
		pData,
		1);

	return Status;
}

NTSTATUS	RTUSBMultiWrite(
	IN	PRTMP_ADAPTER	pAd,
	IN	USHORT			Offset,
	IN	PUCHAR			pData,
	IN	USHORT			length)
{
	NTSTATUS	Status;

	USHORT          index = 0,Value;
	PUCHAR          pSrc = pData;
	USHORT          resude = 0;

	resude = length % 2;
	length  += resude;
	do
	{
			Value =(USHORT)( *pSrc  | (*(pSrc + 1) << 8));
		Status = RTUSBSingleWrite(pAd,Offset + index,Value);
            index +=2;
            length -= 2;
            pSrc = pSrc + 2;
        }while(length > 0);

	return Status;
}

NTSTATUS RTUSBSingleWrite(
	IN 	RTMP_ADAPTER 	*pAd,
	IN	USHORT			Offset,
	IN	USHORT			Value)
{
	NTSTATUS	Status;

	Status = RTUSB_VendorRequest(
		pAd,
		USBD_TRANSFER_DIRECTION_OUT,
		DEVICE_VENDOR_REQUEST_OUT,
		0x2,
		Value,
		Offset,
		NULL,
		0);

	return Status;

}

/*
	========================================================================

	Routine Description: Read 32-bit MAC register

	Arguments:

	Return Value:

	IRQL =

	Note:

	========================================================================
*/
NTSTATUS	RTUSBReadMACRegister(
	IN	PRTMP_ADAPTER	pAd,
	IN	USHORT			Offset,
	OUT	PUINT32			pValue)
{
	NTSTATUS	Status = 0;
	UINT32		localVal;

	Status = RTUSB_VendorRequest(
		pAd,
		(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
		DEVICE_VENDOR_REQUEST_IN,
		0x7,
		0,
		Offset,
		&localVal,
		4);

	*pValue = le2cpu32(localVal);

	if (Status < 0)
		*pValue = 0xffffffff;

	return Status;
}

/*
	========================================================================

	Routine Description: Write 32-bit MAC register

	Arguments:

	Return Value:

	IRQL =

	Note:

	========================================================================
*/
NTSTATUS	RTUSBWriteMACRegister(
	IN	PRTMP_ADAPTER	pAd,
	IN	USHORT			Offset,
	IN	UINT32			Value)
{
	NTSTATUS	Status;
	UINT32		localVal;

	localVal = Value;

	Status = RTUSBSingleWrite(pAd, Offset, (USHORT)(localVal & 0xffff));
	Status = RTUSBSingleWrite(pAd, Offset + 2, (USHORT)((localVal & 0xffff0000) >> 16));

	return Status;
}

/*
	========================================================================

	Routine Description: Read 8-bit BBP register

	Arguments:

	Return Value:

	IRQL =

	Note:

	========================================================================
*/
NTSTATUS	RTUSBReadBBPRegister(
	IN	PRTMP_ADAPTER	pAd,
	IN	UCHAR			Id,
	IN	PUCHAR			pValue)
{
	BBP_CSR_CFG_STRUC	BbpCsr;
	UINT			i = 0;
	NTSTATUS		status;

	// Verify the busy condition
	do
	{
		status = RTUSBReadMACRegister(pAd, BBP_CSR_CFG, &BbpCsr.word);
		if(status >= 0)
		{
		if (!(BbpCsr.field.Busy == BUSY))
			break;
		}
		DBGPRINT(RT_DEBUG_TRACE, ("RTUSBReadBBPRegister(BBP_CSR_CFG_1):retry count=%d!\n", i));
		i++;
	}while ((i < RETRY_LIMIT) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)));

	if ((i == RETRY_LIMIT) || (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
	{
		//
		// Read failed then Return Default value.
		//
		*pValue = pAd->BbpWriteLatch[Id];

		DBGPRINT_RAW(RT_DEBUG_ERROR, ("Retry count exhausted or device removed!!!\n"));
		return STATUS_UNSUCCESSFUL;
	}

	// Prepare for write material
	BbpCsr.word 				= 0;
	BbpCsr.field.fRead			= 1;
	BbpCsr.field.Busy			= 1;
	BbpCsr.field.RegNum 		= Id;
	RTUSBWriteMACRegister(pAd, BBP_CSR_CFG, BbpCsr.word);

	i = 0;
	// Verify the busy condition
	do
	{
		status = RTUSBReadMACRegister(pAd, BBP_CSR_CFG, &BbpCsr.word);
		if (status >= 0)
		{
		if (!(BbpCsr.field.Busy == BUSY))
		{
			*pValue = (UCHAR)BbpCsr.field.Value;
			break;
		}
		}
		DBGPRINT(RT_DEBUG_TRACE, ("RTUSBReadBBPRegister(BBP_CSR_CFG_2):retry count=%d!\n", i));
		i++;
	}while ((i < RETRY_LIMIT) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)));

	if ((i == RETRY_LIMIT) || (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
	{
		//
		// Read failed then Return Default value.
		//
		*pValue = pAd->BbpWriteLatch[Id];

		DBGPRINT_RAW(RT_DEBUG_ERROR, ("Retry count exhausted or device removed!!!\n"));
		return STATUS_UNSUCCESSFUL;
	}

	return STATUS_SUCCESS;
}

/*
	========================================================================

	Routine Description: Write 8-bit BBP register

	Arguments:

	Return Value:

	IRQL =

	Note:

	========================================================================
*/
NTSTATUS	RTUSBWriteBBPRegister(
	IN	PRTMP_ADAPTER	pAd,
	IN	UCHAR			Id,
	IN	UCHAR			Value)
{
	BBP_CSR_CFG_STRUC	BbpCsr;
	UINT			i = 0;
	NTSTATUS		status;
	// Verify the busy condition
	do
	{
		status = RTUSBReadMACRegister(pAd, BBP_CSR_CFG, &BbpCsr.word);
		if (status >= 0)
		{
		if (!(BbpCsr.field.Busy == BUSY))
			break;
		}
		DBGPRINT(RT_DEBUG_TRACE, ("RTUSBWriteBBPRegister(BBP_CSR_CFG):retry count=%d!\n", i));
		i++;
	}
	while ((i < RETRY_LIMIT) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)));

	if ((i == RETRY_LIMIT) || (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
	{
		DBGPRINT_RAW(RT_DEBUG_ERROR, ("Retry count exhausted or device removed!!!\n"));
		return STATUS_UNSUCCESSFUL;
	}

	// Prepare for write material
	BbpCsr.word 				= 0;
	BbpCsr.field.fRead			= 0;
	BbpCsr.field.Value			= Value;
	BbpCsr.field.Busy			= 1;
	BbpCsr.field.RegNum 		= Id;
	RTUSBWriteMACRegister(pAd, BBP_CSR_CFG, BbpCsr.word);

	pAd->BbpWriteLatch[Id] = Value;

	return STATUS_SUCCESS;
}
/*
	========================================================================

	Routine Description: Write RF register through MAC

	Arguments:

	Return Value:

	IRQL =

	Note:

	========================================================================
*/
NTSTATUS	RTUSBWriteRFRegister(
	IN	PRTMP_ADAPTER	pAd,
	IN	UINT32			Value)
{
	PHY_CSR4_STRUC	PhyCsr4;
	UINT			i = 0;
	NTSTATUS		status;

	NdisZeroMemory(&PhyCsr4, sizeof(PHY_CSR4_STRUC));
	do
	{
		status = RTUSBReadMACRegister(pAd, RF_CSR_CFG0, &PhyCsr4.word);
		if (status >= 0)
		{
		if (!(PhyCsr4.field.Busy))
			break;
		}
		DBGPRINT(RT_DEBUG_TRACE, ("RTUSBWriteRFRegister(RF_CSR_CFG0):retry count=%d!\n", i));
		i++;
	}
	while ((i < RETRY_LIMIT) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)));

	if ((i == RETRY_LIMIT) || (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
	{
		DBGPRINT_RAW(RT_DEBUG_ERROR, ("Retry count exhausted or device removed!!!\n"));
		return STATUS_UNSUCCESSFUL;
	}

	RTUSBWriteMACRegister(pAd, RF_CSR_CFG0, Value);

	return STATUS_SUCCESS;
}

/*
	========================================================================

	Routine Description:

	Arguments:

	Return Value:

	IRQL =

	Note:

	========================================================================
*/
NTSTATUS RTUSBReadEEPROM(
	IN	PRTMP_ADAPTER	pAd,
	IN	USHORT			Offset,
	OUT	PUCHAR			pData,
	IN	USHORT			length)
{
	NTSTATUS	Status = STATUS_SUCCESS;

		Status = RTUSB_VendorRequest(
			pAd,
			(USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK),
			DEVICE_VENDOR_REQUEST_IN,
			0x9,
			0,
			Offset,
			pData,
			length);

	return Status;
}

/*
	========================================================================

	Routine Description:

	Arguments:

	Return Value:

	IRQL =

	Note:

	========================================================================
*/
NTSTATUS RTUSBWriteEEPROM(
	IN	PRTMP_ADAPTER	pAd,
	IN	USHORT			Offset,
	IN	PUCHAR			pData,
	IN	USHORT			length)
{
	NTSTATUS	Status = STATUS_SUCCESS;

		Status = RTUSB_VendorRequest(
			pAd,
			USBD_TRANSFER_DIRECTION_OUT,
			DEVICE_VENDOR_REQUEST_OUT,
			0x8,
			0,
			Offset,
			pData,
			length);

	return Status;
}

NTSTATUS RTUSBReadEEPROM16(
	IN	PRTMP_ADAPTER	pAd,
	IN	USHORT			offset,
	OUT	PUSHORT			pData)
{
	NTSTATUS status;
	USHORT  localData;

	status = RTUSBReadEEPROM(pAd, offset, (PUCHAR)(&localData), 2);
	if (status == STATUS_SUCCESS)
		*pData = le2cpu16(localData);

	return status;

}

NTSTATUS RTUSBWriteEEPROM16(
	IN RTMP_ADAPTER *pAd,
	IN USHORT offset,
	IN USHORT value)
{
	USHORT tmpVal;

	tmpVal = cpu2le16(value);
	return RTUSBWriteEEPROM(pAd, offset, (PUCHAR)&(tmpVal), 2);
}

/*
	========================================================================

	Routine Description:

	Arguments:

	Return Value:

	IRQL =

	Note:

	========================================================================
*/
VOID RTUSBPutToSleep(
	IN	PRTMP_ADAPTER	pAd)
{
	UINT32		value;

	// Timeout 0x40 x 50us
	value = (SLEEPCID<<16)+(OWNERMCU<<24)+ (0x40<<8)+1;
	RTUSBWriteMACRegister(pAd, 0x7010, value);
	RTUSBWriteMACRegister(pAd, 0x404, 0x30);
	//RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS);
	DBGPRINT_RAW(RT_DEBUG_ERROR, ("Sleep Mailbox testvalue %x\n", value));

}

/*
	========================================================================

	Routine Description:

	Arguments:

	Return Value:

	IRQL =

	Note:

	========================================================================
*/
NTSTATUS RTUSBWakeUp(
	IN	PRTMP_ADAPTER	pAd)
{
	NTSTATUS	Status;

	Status = RTUSB_VendorRequest(
		pAd,
		USBD_TRANSFER_DIRECTION_OUT,
		DEVICE_VENDOR_REQUEST_OUT,
		0x01,
		0x09,
		0,
		NULL,
		0);

	return Status;
}

/*
	========================================================================

	Routine Description:

	Arguments:

	Return Value:

	IRQL =

	Note:

	========================================================================
*/
NDIS_STATUS	RTUSBEnqueueCmdFromNdis(
	IN	PRTMP_ADAPTER	pAd,
	IN	NDIS_OID		Oid,
	IN	BOOLEAN			SetInformation,
	IN	PVOID			pInformationBuffer,
	IN	UINT32			InformationBufferLength)
{
	NDIS_STATUS	status;
	PCmdQElmt	cmdqelmt = NULL;
	RTMP_OS_TASK	*pTask = &pAd->cmdQTask;

#ifdef KTHREAD_SUPPORT
	if (pTask->kthread_task == NULL)
#else
	CHECK_PID_LEGALITY(pTask->taskPID)
		;
	else
#endif
		return (NDIS_STATUS_RESOURCES);

	status = os_alloc_mem(pAd, (PUCHAR *)(&cmdqelmt), sizeof(CmdQElmt));
	if ((status != NDIS_STATUS_SUCCESS) || (cmdqelmt == NULL))
		return (NDIS_STATUS_RESOURCES);

		cmdqelmt->buffer = NULL;
		if (pInformationBuffer != NULL)
		{
			status = os_alloc_mem(pAd, (PUCHAR *)&cmdqelmt->buffer, InformationBufferLength);
			if ((status != NDIS_STATUS_SUCCESS) || (cmdqelmt->buffer == NULL))
			{
				kfree(cmdqelmt);
				return (NDIS_STATUS_RESOURCES);
			}
			else
			{
				NdisMoveMemory(cmdqelmt->buffer, pInformationBuffer, InformationBufferLength);
				cmdqelmt->bufferlength = InformationBufferLength;
			}
		}
		else
			cmdqelmt->bufferlength = 0;

	cmdqelmt->command = Oid;
	cmdqelmt->CmdFromNdis = TRUE;
	if (SetInformation == TRUE)
		cmdqelmt->SetOperation = TRUE;
	else
		cmdqelmt->SetOperation = FALSE;

	NdisAcquireSpinLock(&pAd->CmdQLock);
	if (pAd->CmdQ.CmdQState & RTMP_TASK_CAN_DO_INSERT)
	{
		EnqueueCmd((&pAd->CmdQ), cmdqelmt);
		status = NDIS_STATUS_SUCCESS;
	}
	else
	{
		status = NDIS_STATUS_FAILURE;
	}
	NdisReleaseSpinLock(&pAd->CmdQLock);

	if (status == NDIS_STATUS_FAILURE)
	{
		if (cmdqelmt->buffer)
			os_free_mem(pAd, cmdqelmt->buffer);
		os_free_mem(pAd, cmdqelmt);
	}
	else
	RTCMDUp(pAd);

    return(NDIS_STATUS_SUCCESS);
}

/*
    ========================================================================
 	Routine Description:
		RTUSB_VendorRequest - Builds a ralink specific request, sends it off to USB endpoint zero and waits for completion

	Arguments:
		@pAd:
	  	@TransferFlags:
	  	@RequestType: USB message request type value
	  	@Request: USB message request value
	  	@Value: USB message value
	  	@Index: USB message index value
	  	@TransferBuffer: USB data to be sent
	  	@TransferBufferLength: Lengths in bytes of the data to be sent

	Context: ! in atomic context

	Return Value:
		NDIS_STATUS_SUCCESS
		NDIS_STATUS_FAILURE

	Note:
		This function sends a simple control message to endpoint zero
		and waits for the message to complete, or CONTROL_TIMEOUT_JIFFIES timeout.
		Because it is synchronous transfer, so don't use this function within an atomic context,
		otherwise system will hang, do be careful.

		TransferBuffer may located in stack region which may not in DMA'able region in some embedded platforms,
		so need to copy TransferBuffer to UsbVendorReqBuf allocated by kmalloc to do DMA transfer.
		Use UsbVendorReq_semaphore to protect this region which may be accessed by multi task.
		Normally, coherent issue is resloved by low-level HC driver, so do not flush this zone by RTUSB_VendorRequest.

	========================================================================
*/
NTSTATUS    RTUSB_VendorRequest(
	IN	PRTMP_ADAPTER	pAd,
	IN	UINT32			TransferFlags,
	IN	UCHAR			RequestType,
	IN	UCHAR			Request,
	IN	USHORT			Value,
	IN	USHORT			Index,
	IN	PVOID			TransferBuffer,
	IN	UINT32			TransferBufferLength)
{
	int				RET = 0;
	POS_COOKIE		pObj = (POS_COOKIE) pAd->OS_Cookie;

	if(in_interrupt())
	{
		DBGPRINT(RT_DEBUG_ERROR, ("BUG: RTUSB_VendorRequest is called from invalid context\n"));
		return NDIS_STATUS_FAILURE;
	}

	if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
	{
		/*DBGPRINT(RT_DEBUG_ERROR, ("WIFI device has been disconnected\n"));*/
		return NDIS_STATUS_FAILURE;
	}
	else
	{

		int RetryCount = 0; // RTUSB_CONTROL_MSG retry counts
		ASSERT(TransferBufferLength <MAX_PARAM_BUFFER_SIZE);

		RTMP_SEM_EVENT_WAIT(&(pAd->UsbVendorReq_semaphore), RET);
		if (RET != 0)
		{
			DBGPRINT(RT_DEBUG_ERROR, ("UsbVendorReq_semaphore get failed\n"));
			return NDIS_STATUS_FAILURE;
		}

		if ((TransferBufferLength > 0) && (RequestType == DEVICE_VENDOR_REQUEST_OUT))
				NdisMoveMemory(pAd->UsbVendorReqBuf, TransferBuffer, TransferBufferLength);

		do {
			RTUSB_CONTROL_MSG(pObj->pUsb_Dev, 0, Request, RequestType, Value, Index, pAd->UsbVendorReqBuf, TransferBufferLength, CONTROL_TIMEOUT_JIFFIES, RET);

			if (RET < 0) {
				DBGPRINT(RT_DEBUG_OFF, ("#\n"));
				if (RET == -ENODEV)
				{
					RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST);
					break;
				}
				RetryCount++;
				RTMPusecDelay(5000); // wait for 5ms
			}
		} while((RET < 0) && (RetryCount < MAX_VENDOR_REQ_RETRY_COUNT));

	  	if ( (!(RET < 0)) && (TransferBufferLength > 0) && (RequestType == DEVICE_VENDOR_REQUEST_IN))
			NdisMoveMemory(TransferBuffer, pAd->UsbVendorReqBuf, TransferBufferLength);

	  	RTMP_SEM_EVENT_UP(&(pAd->UsbVendorReq_semaphore));

        	if (RET < 0) {
			DBGPRINT(RT_DEBUG_ERROR, ("RTUSB_VendorRequest failed(%d),TxFlags=0x%x, ReqType=%s, Req=0x%x, Idx=0x%x,pAd->Flags=0x%lx\n",
						RET, TransferFlags, (RequestType == DEVICE_VENDOR_REQUEST_OUT ? "OUT" : "IN"), Request, Index, pAd->Flags));
			if (Request == 0x2)
				DBGPRINT(RT_DEBUG_ERROR, ("\tRequest Value=0x%04x!\n", Value));

			if ((!TransferBuffer) && (TransferBufferLength > 0))
				hex_dump("Failed TransferBuffer value", TransferBuffer, TransferBufferLength);

			if (RET == -ENODEV)
					RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST);

		}

	}

	if (RET < 0)
		return NDIS_STATUS_FAILURE;
	else
		return NDIS_STATUS_SUCCESS;

}

/*
	========================================================================

	Routine Description:
	  Creates an IRP to submite an IOCTL_INTERNAL_USB_RESET_PORT
	  synchronously. Callers of this function must be running at
	  PASSIVE LEVEL.

	Arguments:

	Return Value:

	Note:

	========================================================================
*/
NTSTATUS RTUSB_ResetDevice(
	IN	PRTMP_ADAPTER	pAd)
{
	NTSTATUS		Status = TRUE;

	DBGPRINT_RAW(RT_DEBUG_TRACE, ("--->USB_ResetDevice\n"));
	//RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_RESET_IN_PROGRESS);
	return Status;
}

NTSTATUS CheckGPIOHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{

#ifdef RALINK_ATE
		if (ATE_ON(pAd))
		{
			DBGPRINT(RT_DEBUG_TRACE, ("The driver is in ATE mode now\n"));
			return NDIS_STATUS_SUCCESS;
		}
#endif // RALINK_ATE //

#ifdef CONFIG_STA_SUPPORT

		IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
		{
			UINT32 data;
			// Read GPIO pin2 as Hardware controlled radio state

			RTUSBReadMACRegister( pAd, GPIO_CTRL_CFG, &data);

			if (data & 0x04)
			{
				pAd->StaCfg.bHwRadio = TRUE;
			}
			else
			{
				pAd->StaCfg.bHwRadio = FALSE;
			}

			if (pAd->StaCfg.bRadio != (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio))
			{
				pAd->StaCfg.bRadio = (pAd->StaCfg.bHwRadio && pAd->StaCfg.bSwRadio);
				if (pAd->StaCfg.bRadio == TRUE)
				{
					DBGPRINT_RAW(RT_DEBUG_ERROR, ("!!! Radio On !!!\n"));

					MlmeRadioOn(pAd);
					// Update extra information
					pAd->ExtraInfo = EXTRA_INFO_CLEAR;
				}
				else
				{
					DBGPRINT_RAW(RT_DEBUG_ERROR, ("!!! Radio Off !!!\n"));

					MlmeRadioOff(pAd);
					// Update extra information
					pAd->ExtraInfo = HW_RADIO_OFF;
				}
			}
		} // end IF_DEV_CONFIG_OPMODE_ON_STA

#endif // CONFIG_STA_SUPPORT //

	return NDIS_STATUS_SUCCESS;
}

static NTSTATUS ResetBulkOutHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{

	INT32 MACValue = 0;
	UCHAR Index = 0;
	int ret=0;
	PHT_TX_CONTEXT	pHTTXContext;
//	RTMP_TX_RING *pTxRing;
	unsigned long IrqFlags;

	DBGPRINT(RT_DEBUG_TRACE, ("CMDTHREAD_RESET_BULK_OUT(ResetPipeid=0x%0x)===>\n", pAd->bulkResetPipeid));

	// All transfers must be aborted or cancelled before attempting to reset the pipe.
	//RTUSBCancelPendingBulkOutIRP(pAd);
	// Wait 10ms to let previous packet that are already in HW FIFO to clear. by MAXLEE 12-25-2007
	do
	{
		if(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
			break;

		RTUSBReadMACRegister(pAd, TXRXQ_PCNT, &MACValue);
		if ((MACValue & 0xf00000/*0x800000*/) == 0)
			break;

		Index++;
		RTMPusecDelay(10000);
	}while(Index < 100);

	RTUSBReadMACRegister(pAd, USB_DMA_CFG, &MACValue);

	// 2nd, to prevent Read Register error, we check the validity.
	if ((MACValue & 0xc00000) == 0)
		RTUSBReadMACRegister(pAd, USB_DMA_CFG, &MACValue);

	// 3rd, to prevent Read Register error, we check the validity.
	if ((MACValue & 0xc00000) == 0)
		RTUSBReadMACRegister(pAd, USB_DMA_CFG, &MACValue);

	MACValue |= 0x80000;
	RTUSBWriteMACRegister(pAd, USB_DMA_CFG, MACValue);

	// Wait 1ms to prevent next URB to bulkout before HW reset. by MAXLEE 12-25-2007
	RTMPusecDelay(1000);

	MACValue &= (~0x80000);
	RTUSBWriteMACRegister(pAd, USB_DMA_CFG, MACValue);
	DBGPRINT(RT_DEBUG_TRACE, ("\tSet 0x2a0 bit19. Clear USB DMA TX path\n"));

	// Wait 5ms to prevent next URB to bulkout before HW reset. by MAXLEE 12-25-2007
	//RTMPusecDelay(5000);

	if ((pAd->bulkResetPipeid & BULKOUT_MGMT_RESET_FLAG) == BULKOUT_MGMT_RESET_FLAG)
	{
		RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);

		if (pAd->MgmtRing.TxSwFreeIdx < MGMT_RING_SIZE /* pMLMEContext->bWaitingBulkOut == TRUE */)
			RTUSB_SET_BULK_FLAG(pAd, fRTUSB_BULK_OUT_MLME);

		RTUSBKickBulkOut(pAd);
		DBGPRINT(RT_DEBUG_TRACE, ("\tTX MGMT RECOVER Done!\n"));
	}
	else
	{
		pHTTXContext = &(pAd->TxContext[pAd->bulkResetPipeid]);

		//NdisAcquireSpinLock(&pAd->BulkOutLock[pAd->bulkResetPipeid]);
		RTMP_INT_LOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
		if ( pAd->BulkOutPending[pAd->bulkResetPipeid] == FALSE)
		{
			pAd->BulkOutPending[pAd->bulkResetPipeid] = TRUE;
			pHTTXContext->IRPPending = TRUE;
			pAd->watchDogTxPendingCnt[pAd->bulkResetPipeid] = 1;

			// no matter what, clean the flag
			RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);

			//NdisReleaseSpinLock(&pAd->BulkOutLock[pAd->bulkResetPipeid]);
			RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);

#ifdef RALINK_ATE
			if (ATE_ON(pAd))
				ret = ATEResetBulkOut(pAd);
			else
#endif // RALINK_ATE //
			{
				RTUSBInitHTTxDesc(pAd, pHTTXContext, pAd->bulkResetPipeid,
													pHTTXContext->BulkOutSize,
													(usb_complete_t)RTUSBBulkOutDataPacketComplete);

				if ((ret = RTUSB_SUBMIT_URB(pHTTXContext->pUrb))!=0)
				{
						RTMP_INT_LOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);
						pAd->BulkOutPending[pAd->bulkResetPipeid] = FALSE;
						pHTTXContext->IRPPending = FALSE;
						pAd->watchDogTxPendingCnt[pAd->bulkResetPipeid] = 0;
						RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);

						DBGPRINT(RT_DEBUG_ERROR, ("CMDTHREAD_RESET_BULK_OUT:Submit Tx URB failed %d\n", ret));
				}
				else
				{
						RTMP_INT_LOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);

						DBGPRINT(RT_DEBUG_TRACE,("\tCMDTHREAD_RESET_BULK_OUT: TxContext[%d]:CWPos=%ld, NBPos=%ld, ENBPos=%ld, bCopy=%d, pending=%d!\n",
											pAd->bulkResetPipeid, pHTTXContext->CurWritePosition, pHTTXContext->NextBulkOutPosition,
											pHTTXContext->ENextBulkOutPosition, pHTTXContext->bCopySavePad,
											pAd->BulkOutPending[pAd->bulkResetPipeid]));
						DBGPRINT(RT_DEBUG_TRACE,("\t\tBulkOut Req=0x%lx, Complete=0x%lx, Other=0x%lx\n",
											pAd->BulkOutReq, pAd->BulkOutComplete, pAd->BulkOutCompleteOther));

						RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);

						DBGPRINT(RT_DEBUG_TRACE, ("\tCMDTHREAD_RESET_BULK_OUT: Submit Tx DATA URB for failed BulkReq(0x%lx) Done, status=%d!\n",
											pAd->bulkResetReq[pAd->bulkResetPipeid],
											pHTTXContext->pUrb->rtusb_urb_status));
				}
			}
		}
		else
		{
			//NdisReleaseSpinLock(&pAd->BulkOutLock[pAd->bulkResetPipeid]);
			//RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);

			DBGPRINT(RT_DEBUG_ERROR, ("CmdThread : TX DATA RECOVER FAIL for BulkReq(0x%lx) because BulkOutPending[%d] is TRUE!\n",
								pAd->bulkResetReq[pAd->bulkResetPipeid], pAd->bulkResetPipeid));

			if (pAd->bulkResetPipeid == 0)
			{
				UCHAR	pendingContext = 0;
				PHT_TX_CONTEXT pHTTXContext = (PHT_TX_CONTEXT)(&pAd->TxContext[pAd->bulkResetPipeid ]);
				PTX_CONTEXT pMLMEContext = (PTX_CONTEXT)(pAd->MgmtRing.Cell[pAd->MgmtRing.TxDmaIdx].AllocVa);
				PTX_CONTEXT pNULLContext = (PTX_CONTEXT)(&pAd->PsPollContext);
				PTX_CONTEXT pPsPollContext = (PTX_CONTEXT)(&pAd->NullContext);

				if (pHTTXContext->IRPPending)
					pendingContext |= 1;
				else if (pMLMEContext->IRPPending)
					pendingContext |= 2;
				else if (pNULLContext->IRPPending)
					pendingContext |= 4;
				else if (pPsPollContext->IRPPending)
					pendingContext |= 8;
				else
					pendingContext = 0;

				DBGPRINT(RT_DEBUG_ERROR, ("\tTX Occupied by %d!\n", pendingContext));
			}

			// no matter what, clean the flag
			RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BULKOUT_RESET);

			RTMP_INT_UNLOCK(&pAd->BulkOutLock[pAd->bulkResetPipeid], IrqFlags);

			RTUSB_SET_BULK_FLAG(pAd, (fRTUSB_BULK_OUT_DATA_NORMAL << pAd->bulkResetPipeid));
		}

		RTMPDeQueuePacket(pAd, FALSE, NUM_OF_TX_RING, MAX_TX_PROCESS);
		//RTUSBKickBulkOut(pAd);
	}
/*

	// Don't cancel BULKIN.
	while ((atomic_read(&pAd->PendingRx) > 0) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
	{
		if (atomic_read(&pAd->PendingRx) > 0)
		{
			DBGPRINT_RAW(RT_DEBUG_ERROR, ("BulkIn IRP Pending!!cancel it!\n"));
			RTUSBCancelPendingBulkInIRP(pAd);
		}
			RTMPusecDelay(100000);
	}

	if ((atomic_read(&pAd->PendingRx) == 0) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)))
	{
		UCHAR	i;
		RTUSBRxPacket(pAd);
		pAd->NextRxBulkInReadIndex = 0;	// Next Rx Read index
		pAd->NextRxBulkInIndex		= 0;	// Rx Bulk pointer
		for (i = 0; i < (RX_RING_SIZE); i++)
		{
			PRX_CONTEXT  pRxContext = &(pAd->RxContext[i]);

			pRxContext->pAd	= pAd;
			pRxContext->InUse		= FALSE;
			pRxContext->IRPPending	= FALSE;
			pRxContext->Readable	= FALSE;
			pRxContext->ReorderInUse = FALSE;

		}
			RTUSBBulkReceive(pAd);
			DBGPRINT_RAW(RT_DEBUG_ERROR, ("RTUSBBulkReceive\n"));
	}*/

	DBGPRINT_RAW(RT_DEBUG_TRACE, ("CmdThread : CMDTHREAD_RESET_BULK_OUT<===\n"));
	return NDIS_STATUS_SUCCESS;

}

// All transfers must be aborted or cancelled before attempting to reset the pipe.
static NTSTATUS ResetBulkInHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	UINT32 MACValue;
	NTSTATUS ntStatus;

	DBGPRINT_RAW(RT_DEBUG_TRACE, ("CmdThread : CMDTHREAD_RESET_BULK_IN === >\n"));

#ifdef RALINK_ATE
	if (ATE_ON(pAd))
		ATEResetBulkIn(pAd);
	else
#endif // RALINK_ATE //
	{
		//while ((atomic_read(&pAd->PendingRx) > 0) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
		if((pAd->PendingRx > 0) && (!RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST)))
		{
			DBGPRINT_RAW(RT_DEBUG_ERROR, ("BulkIn IRP Pending!!!\n"));
			RTUSBCancelPendingBulkInIRP(pAd);
			RTMPusecDelay(100000);
			pAd->PendingRx = 0;
		}
	}

	// Wait 10ms before reading register.
	RTMPusecDelay(10000);
	ntStatus = RTUSBReadMACRegister(pAd, MAC_CSR0, &MACValue);

	if ((NT_SUCCESS(ntStatus) == TRUE) &&
				(!(RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS | fRTMP_ADAPTER_RADIO_OFF |
												fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST)))))
	{
		UCHAR	i;

		if (RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS | fRTMP_ADAPTER_RADIO_OFF |
									fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST)))
			return NDIS_STATUS_SUCCESS;

		pAd->NextRxBulkInPosition = pAd->RxContext[pAd->NextRxBulkInIndex].BulkInOffset;

		DBGPRINT(RT_DEBUG_TRACE, ("BULK_IN_RESET: NBIIdx=0x%x,NBIRIdx=0x%x, BIRPos=0x%lx. BIReq=x%lx, BIComplete=0x%lx, BICFail0x%lx\n",
					pAd->NextRxBulkInIndex,  pAd->NextRxBulkInReadIndex, pAd->NextRxBulkInPosition, pAd->BulkInReq, pAd->BulkInComplete, pAd->BulkInCompleteFail));

		for (i = 0; i < RX_RING_SIZE; i++)
		{
 			DBGPRINT(RT_DEBUG_TRACE, ("\tRxContext[%d]: IRPPending=%d, InUse=%d, Readable=%d!\n"
							, i, pAd->RxContext[i].IRPPending, pAd->RxContext[i].InUse, pAd->RxContext[i].Readable));
		}

 		/*
			DBGPRINT_RAW(RT_DEBUG_ERROR, ("==========================================\n"));

			pAd->NextRxBulkInReadIndex = 0;	// Next Rx Read index
			pAd->NextRxBulkInIndex		= 0;	// Rx Bulk pointer
			for (i = 0; i < (RX_RING_SIZE); i++)
			{
				PRX_CONTEXT  pRxContext = &(pAd->RxContext[i]);

				pRxContext->pAd	= pAd;
				pRxContext->InUse		= FALSE;
				pRxContext->IRPPending	= FALSE;
				pRxContext->Readable	= FALSE;
				pRxContext->ReorderInUse = FALSE;

			}*/
		RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_BULKIN_RESET);

		for (i = 0; i < pAd->CommonCfg.NumOfBulkInIRP; i++)
		{
			//RTUSBBulkReceive(pAd);
			PRX_CONTEXT		pRxContext;
			PURB			pUrb;
			int				ret = 0;
			unsigned long	IrqFlags;

			RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
			pRxContext = &(pAd->RxContext[pAd->NextRxBulkInIndex]);

			if ((pAd->PendingRx > 0) || (pRxContext->Readable == TRUE) || (pRxContext->InUse == TRUE))
			{
				RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
				return NDIS_STATUS_SUCCESS;
			}

			pRxContext->InUse = TRUE;
			pRxContext->IRPPending = TRUE;
			pAd->PendingRx++;
			pAd->BulkInReq++;
			RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);

			// Init Rx context descriptor
			RTUSBInitRxDesc(pAd, pRxContext);
			pUrb = pRxContext->pUrb;
			if ((ret = RTUSB_SUBMIT_URB(pUrb))!=0)
			{	// fail
				RTMP_IRQ_LOCK(&pAd->BulkInLock, IrqFlags);
				pRxContext->InUse = FALSE;
				pRxContext->IRPPending = FALSE;
				pAd->PendingRx--;
				pAd->BulkInReq--;
				RTMP_IRQ_UNLOCK(&pAd->BulkInLock, IrqFlags);
				DBGPRINT(RT_DEBUG_ERROR, ("CMDTHREAD_RESET_BULK_IN: Submit Rx URB failed(%d), status=%d\n", ret, pUrb->rtusb_urb_status));
			}
			else
			{	// success
				//DBGPRINT(RT_DEBUG_TRACE, ("BIDone, Pend=%d,BIIdx=%d,BIRIdx=%d!\n",
				//							pAd->PendingRx, pAd->NextRxBulkInIndex, pAd->NextRxBulkInReadIndex));
				DBGPRINT_RAW(RT_DEBUG_TRACE, ("CMDTHREAD_RESET_BULK_IN: Submit Rx URB Done, status=%d!\n", pUrb->rtusb_urb_status));
				ASSERT((pRxContext->InUse == pRxContext->IRPPending));
			}
		}

	}
	else
	{
		// Card must be removed
		if (NT_SUCCESS(ntStatus) != TRUE)
		{
			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST);
			DBGPRINT_RAW(RT_DEBUG_ERROR, ("CMDTHREAD_RESET_BULK_IN: Read Register Failed!Card must be removed!!\n\n"));
		}
		else
			DBGPRINT_RAW(RT_DEBUG_ERROR, ("CMDTHREAD_RESET_BULK_IN: Cannot do bulk in because flags(0x%lx) on !\n", pAd->Flags));
	}

	DBGPRINT_RAW(RT_DEBUG_TRACE, ("CmdThread : CMDTHREAD_RESET_BULK_IN <===\n"));
	return NDIS_STATUS_SUCCESS;
}

static NTSTATUS SetAsicWcidHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	RT_SET_ASIC_WCID	SetAsicWcid;
	USHORT		offset;
	UINT32		MACValue, MACRValue = 0;
	SetAsicWcid = *((PRT_SET_ASIC_WCID)(CMDQelmt->buffer));

	if (SetAsicWcid.WCID >= MAX_LEN_OF_MAC_TABLE)
		return NDIS_STATUS_FAILURE;

	offset = MAC_WCID_BASE + ((UCHAR)SetAsicWcid.WCID)*HW_WCID_ENTRY_SIZE;

	DBGPRINT_RAW(RT_DEBUG_TRACE, ("CmdThread : CMDTHREAD_SET_ASIC_WCID : WCID = %ld, SetTid  = %lx, DeleteTid = %lx.\n",
						SetAsicWcid.WCID, SetAsicWcid.SetTid, SetAsicWcid.DeleteTid));

	MACValue = (pAd->MacTab.Content[SetAsicWcid.WCID].Addr[3]<<24)+(pAd->MacTab.Content[SetAsicWcid.WCID].Addr[2]<<16)+(pAd->MacTab.Content[SetAsicWcid.WCID].Addr[1]<<8)+(pAd->MacTab.Content[SetAsicWcid.WCID].Addr[0]);

	DBGPRINT_RAW(RT_DEBUG_TRACE, ("1-MACValue= %x,\n", MACValue));
	RTUSBWriteMACRegister(pAd, offset, MACValue);
	// Read bitmask
	RTUSBReadMACRegister(pAd, offset+4, &MACRValue);
	if ( SetAsicWcid.DeleteTid != 0xffffffff)
		MACRValue &= (~SetAsicWcid.DeleteTid);
	if (SetAsicWcid.SetTid != 0xffffffff)
		MACRValue |= (SetAsicWcid.SetTid);

	MACRValue &= 0xffff0000;
	MACValue = (pAd->MacTab.Content[SetAsicWcid.WCID].Addr[5]<<8)+pAd->MacTab.Content[SetAsicWcid.WCID].Addr[4];
	MACValue |= MACRValue;
	RTUSBWriteMACRegister(pAd, offset+4, MACValue);

	DBGPRINT_RAW(RT_DEBUG_TRACE, ("2-MACValue= %x,\n", MACValue));

	return NDIS_STATUS_SUCCESS;
}

static NTSTATUS SetWcidSecInfoHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	PRT_ASIC_WCID_SEC_INFO pInfo;

	pInfo = (PRT_ASIC_WCID_SEC_INFO)CMDQelmt->buffer;
	RTMPSetWcidSecurityInfo(pAd,
							 pInfo->BssIdx,
							 pInfo->KeyIdx,
							 pInfo->CipherAlg,
							 pInfo->Wcid,
							 pInfo->KeyTabFlag);

	return NDIS_STATUS_SUCCESS;
}

static NTSTATUS SetAsicWcidIVEIVHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	PRT_ASIC_WCID_IVEIV_ENTRY pInfo;

	pInfo = (PRT_ASIC_WCID_IVEIV_ENTRY)CMDQelmt->buffer;
	AsicUpdateWCIDIVEIV(pAd,
						  pInfo->Wcid,
						  pInfo->Iv,
						  pInfo->Eiv);

	return NDIS_STATUS_SUCCESS;
}

static NTSTATUS SetAsicWcidAttrHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	PRT_ASIC_WCID_ATTR_ENTRY pInfo;

	pInfo = (PRT_ASIC_WCID_ATTR_ENTRY)CMDQelmt->buffer;
	AsicUpdateWcidAttributeEntry(pAd,
								  pInfo->BssIdx,
								  pInfo->KeyIdx,
								  pInfo->CipherAlg,
								  pInfo->Wcid,
								  pInfo->KeyTabFlag);

	return NDIS_STATUS_SUCCESS;
}

static NTSTATUS SETAsicSharedKeyHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	PRT_ASIC_SHARED_KEY pInfo;

	pInfo = (PRT_ASIC_SHARED_KEY)CMDQelmt->buffer;
	AsicAddSharedKeyEntry(pAd,
						       pInfo->BssIndex,
							pInfo->KeyIdx,
							&pInfo->CipherKey);

	return NDIS_STATUS_SUCCESS;
}

static NTSTATUS SetAsicPairwiseKeyHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	PRT_ASIC_PAIRWISE_KEY pInfo;

	pInfo = (PRT_ASIC_PAIRWISE_KEY)CMDQelmt->buffer;
	AsicAddPairwiseKeyEntry(pAd,
							 pInfo->WCID,
							 &pInfo->CipherKey);

	return NDIS_STATUS_SUCCESS;
}

#ifdef CONFIG_STA_SUPPORT
static NTSTATUS SetPortSecuredHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	STA_PORT_SECURED(pAd);
	return NDIS_STATUS_SUCCESS;
}
#endif // CONFIG_STA_SUPPORT //

static NTSTATUS RemovePairwiseKeyHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	UCHAR Wcid = *((PUCHAR)(CMDQelmt->buffer));

	AsicRemovePairwiseKeyEntry(pAd, Wcid);
	return NDIS_STATUS_SUCCESS;
}

static NTSTATUS SetClientMACEntryHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	PRT_SET_ASIC_WCID pInfo;

	pInfo = (PRT_SET_ASIC_WCID)CMDQelmt->buffer;
	AsicUpdateRxWCIDTable(pAd, pInfo->WCID, pInfo->Addr);
	return NDIS_STATUS_SUCCESS;
}

// add by johnli, fix "in_interrupt" error when call "MacTableDeleteEntry" in Rx tasklet
static NTSTATUS UpdateProtectHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	AsicUpdateProtect(pAd, 0, (ALLN_SETPROTECT), TRUE, 0);
	return NDIS_STATUS_SUCCESS;
}

// end johnli

#ifdef CONFIG_STA_SUPPORT
static NTSTATUS SetPSMBitHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
	{
		USHORT *pPsm = (USHORT *)CMDQelmt->buffer;
		MlmeSetPsmBit(pAd, *pPsm);
	}

	return NDIS_STATUS_SUCCESS;
}

static NTSTATUS ForceWakeUpHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	IF_DEV_CONFIG_OPMODE_ON_STA(pAd)
		AsicForceWakeup(pAd, TRUE);

	return NDIS_STATUS_SUCCESS;
}

static NTSTATUS ForceSleepAutoWakeupHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	USHORT  TbttNumToNextWakeUp;
	USHORT  NextDtim = pAd->StaCfg.DtimPeriod;
	ULONG   Now;

	NdisGetSystemUpTime(&Now);
	NextDtim -= (USHORT)(Now - pAd->StaCfg.LastBeaconRxTime)/pAd->CommonCfg.BeaconPeriod;

	TbttNumToNextWakeUp = pAd->StaCfg.DefaultListenCount;
	if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM) && (TbttNumToNextWakeUp > NextDtim))
		TbttNumToNextWakeUp = NextDtim;

	RTMP_SET_PSM_BIT(pAd, PWR_SAVE);

	// if WMM-APSD is failed, try to disable following line
	AsicSleepThenAutoWakeup(pAd, TbttNumToNextWakeUp);

	return NDIS_STATUS_SUCCESS;
}

NTSTATUS QkeriodicExecutHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	StaQuickResponeForRateUpExec(NULL, pAd, NULL, NULL);
	return NDIS_STATUS_SUCCESS;
}
#endif // CONFIG_STA_SUPPORT

#ifdef LINUX
#ifdef RT_CFG80211_SUPPORT
static NTSTATUS RegHintHdlr (IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	RT_CFG80211_CRDA_REG_HINT(pAd, CMDQelmt->buffer, CMDQelmt->bufferlength);
	return NDIS_STATUS_SUCCESS;
}

static NTSTATUS RegHint11DHdlr(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	RT_CFG80211_CRDA_REG_HINT11D(pAd, CMDQelmt->buffer, CMDQelmt->bufferlength);
	return NDIS_STATUS_SUCCESS;
}

static NTSTATUS RT_Mac80211_ScanEnd(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	RT_CFG80211_SCAN_END(pAd, FALSE);
	return NDIS_STATUS_SUCCESS;
}

static NTSTATUS RT_Mac80211_ConnResultInfom(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt)
{
	RT_CFG80211_CONN_RESULT_INFORM(pAd,
								pAd->MlmeAux.Bssid,
								CMDQelmt->buffer, CMDQelmt->bufferlength,
								CMDQelmt->buffer, CMDQelmt->bufferlength,
								1);
	return NDIS_STATUS_SUCCESS;
}
#endif // RT_CFG80211_SUPPORT //
#endif // LINUX //

typedef NTSTATUS (*CMDHdlr)(IN PRTMP_ADAPTER pAd, IN PCmdQElmt CMDQelmt);

static CMDHdlr CMDHdlrTable[] = {
	ResetBulkOutHdlr,				// CMDTHREAD_RESET_BULK_OUT
	ResetBulkInHdlr,					// CMDTHREAD_RESET_BULK_IN
	CheckGPIOHdlr,					// CMDTHREAD_CHECK_GPIO
	SetAsicWcidHdlr,					// CMDTHREAD_SET_ASIC_WCID
	SetClientMACEntryHdlr,			// CMDTHREAD_SET_CLIENT_MAC_ENTRY

#ifdef CONFIG_STA_SUPPORT
	SetPSMBitHdlr,					// CMDTHREAD_SET_PSM_BIT
	ForceWakeUpHdlr,				// CMDTHREAD_FORCE_WAKE_UP
	ForceSleepAutoWakeupHdlr,		// CMDTHREAD_FORCE_SLEEP_AUTO_WAKEUP
	QkeriodicExecutHdlr,				// CMDTHREAD_QKERIODIC_EXECUT
#else
	NULL,
	NULL,
	NULL,
	NULL,
#endif // CONFIG_STA_SUPPORT //

	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,

	NULL,
	NULL,

	/* Security related */
	SetWcidSecInfoHdlr,				// CMDTHREAD_SET_WCID_SEC_INFO
	SetAsicWcidIVEIVHdlr,			// CMDTHREAD_SET_ASIC_WCID_IVEIV
	SetAsicWcidAttrHdlr,				// CMDTHREAD_SET_ASIC_WCID_ATTR
	SETAsicSharedKeyHdlr,			// CMDTHREAD_SET_ASIC_SHARED_KEY
	SetAsicPairwiseKeyHdlr,			// CMDTHREAD_SET_ASIC_PAIRWISE_KEY
	RemovePairwiseKeyHdlr,			// CMDTHREAD_REMOVE_PAIRWISE_KEY

#ifdef CONFIG_STA_SUPPORT
	SetPortSecuredHdlr,				// CMDTHREAD_SET_PORT_SECURED
#else
	NULL,
#endif // CONFIG_STA_SUPPORT //

	NULL,

	UpdateProtectHdlr,				// CMDTHREAD_UPDATE_PROTECT

#ifdef LINUX
#ifdef RT_CFG80211_SUPPORT
	RegHintHdlr,
	RegHint11DHdlr,
	RT_Mac80211_ScanEnd,
	RT_Mac80211_ConnResultInfom,
#else
	NULL,
	NULL,
	NULL,
	NULL,
#endif // RT_CFG80211_SUPPORT //

#else
	NULL,
	NULL,
	NULL,
	NULL,
#endif // LINUX //

};

static inline BOOLEAN ValidCMD(IN PCmdQElmt CMDQelmt)
{
	SHORT CMDIndex = CMDQelmt->command - CMDTHREAD_FIRST_CMD_ID;
	USHORT CMDHdlrTableLength= sizeof(CMDHdlrTable) / sizeof(CMDHdlr);

	if ( (CMDIndex >= 0) && (CMDIndex < CMDHdlrTableLength))
	{
		if (CMDHdlrTable[CMDIndex] > 0)
			return TRUE;
		else
		{
			DBGPRINT(RT_DEBUG_ERROR, ("No corresponding CMDHdlr for this CMD(%x)\n",  CMDQelmt->command));
			return FALSE;
		}
	}
	else
	{
		DBGPRINT(RT_DEBUG_ERROR, ("CMD(%x) is out of boundary\n", CMDQelmt->command));
		return FALSE;
	}
}

VOID CMDHandler(
    IN PRTMP_ADAPTER pAd)
{
	PCmdQElmt		cmdqelmt;
	NDIS_STATUS		NdisStatus = NDIS_STATUS_SUCCESS;
	NTSTATUS		ntStatus;
//	unsigned long	IrqFlags;

	while (pAd && pAd->CmdQ.size > 0)
	{
		NdisStatus = NDIS_STATUS_SUCCESS;

		NdisAcquireSpinLock(&pAd->CmdQLock);
		RTThreadDequeueCmd(&pAd->CmdQ, &cmdqelmt);
		NdisReleaseSpinLock(&pAd->CmdQLock);

		if (cmdqelmt == NULL)
			break;

		if(!(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST) || RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)))
		{
			if(ValidCMD(cmdqelmt))
				ntStatus = (*CMDHdlrTable[cmdqelmt->command - CMDTHREAD_FIRST_CMD_ID])(pAd, cmdqelmt);
		}

		if (cmdqelmt->CmdFromNdis == TRUE)
		{
			if (cmdqelmt->buffer != NULL)
				os_free_mem(pAd, cmdqelmt->buffer);
			os_free_mem(pAd, cmdqelmt);
		}
		else
		{
			if ((cmdqelmt->buffer != NULL) && (cmdqelmt->bufferlength != 0))
				os_free_mem(pAd, cmdqelmt->buffer);
			os_free_mem(pAd, cmdqelmt);
		}
	}	/* end of while */
}

VOID RTUSBWatchDog(IN RTMP_ADAPTER *pAd)
{
	PHT_TX_CONTEXT		pHTTXContext;
	int 					idx;
	ULONG				irqFlags;
	PURB		   		pUrb;
	BOOLEAN				needDumpSeq = FALSE;
	UINT32          	MACValue;

	if(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_NIC_NOT_EXIST))
		return;
	idx = 0;
	RTMP_IO_READ32(pAd, TXRXQ_PCNT, &MACValue);
	if ((MACValue & 0xff) !=0 )
	{
		DBGPRINT(RT_DEBUG_TRACE, ("TX QUEUE 0 Not EMPTY(Value=0x%0x). !!!!!!!!!!!!!!!\n", MACValue));
		RTMP_IO_WRITE32(pAd, PBF_CFG, 0xf40012);
		while((MACValue &0xff) != 0 && (idx++ < 10))
		{
		        RTMP_IO_READ32(pAd, TXRXQ_PCNT, &MACValue);
		        RTMPusecDelay(1);
		}
		RTMP_IO_WRITE32(pAd, PBF_CFG, 0xf40006);
	}

	idx = 0;
	if ((MACValue & 0xff00) !=0 )
	{
		DBGPRINT(RT_DEBUG_TRACE, ("TX QUEUE 1 Not EMPTY(Value=0x%0x). !!!!!!!!!!!!!!!\n", MACValue));
		RTMP_IO_WRITE32(pAd, PBF_CFG, 0xf4000a);
		while((MACValue &0xff00) != 0 && (idx++ < 10))
		{
			RTMP_IO_READ32(pAd, TXRXQ_PCNT, &MACValue);
			RTMPusecDelay(1);
		}
		RTMP_IO_WRITE32(pAd, PBF_CFG, 0xf40006);
	}

	if (pAd->watchDogRxOverFlowCnt >= 2)
	{
		DBGPRINT(RT_DEBUG_TRACE, ("Maybe the Rx Bulk-In hanged! Cancel the pending Rx bulks request!\n"));
		if ((!RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS |
									fRTMP_ADAPTER_BULKIN_RESET |
									fRTMP_ADAPTER_HALT_IN_PROGRESS |
									fRTMP_ADAPTER_NIC_NOT_EXIST))))
		{
			DBGPRINT(RT_DEBUG_TRACE, ("Call CMDTHREAD_RESET_BULK_IN to cancel the pending Rx Bulk!\n"));
			RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_BULKIN_RESET);
			RTEnqueueInternalCmd(pAd, CMDTHREAD_RESET_BULK_IN, NULL, 0);
			needDumpSeq = TRUE;
		}
		pAd->watchDogRxOverFlowCnt = 0;
	}

	for (idx = 0; idx < NUM_OF_TX_RING; idx++)
	{
		pUrb = NULL;

		RTMP_IRQ_LOCK(&pAd->BulkOutLock[idx], irqFlags);
		if ((pAd->BulkOutPending[idx] == TRUE) && pAd->watchDogTxPendingCnt)
		{
			pAd->watchDogTxPendingCnt[idx]++;

			if ((pAd->watchDogTxPendingCnt[idx] > 2) &&
				 (!RTMP_TEST_FLAG(pAd, (fRTMP_ADAPTER_RESET_IN_PROGRESS | fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST | fRTMP_ADAPTER_BULKOUT_RESET)))
				)
			{
				// FIXME: Following code just support single bulk out. If you wanna support multiple bulk out. Modify it!
				pHTTXContext = (PHT_TX_CONTEXT)(&pAd->TxContext[idx]);
				if (pHTTXContext->IRPPending)
				{	// Check TxContext.
					pUrb = pHTTXContext->pUrb;
				}
				else if (idx == MGMTPIPEIDX)
				{
					PTX_CONTEXT pMLMEContext, pNULLContext, pPsPollContext;

					//Check MgmtContext.
					pMLMEContext = (PTX_CONTEXT)(pAd->MgmtRing.Cell[pAd->MgmtRing.TxDmaIdx].AllocVa);
					pPsPollContext = (PTX_CONTEXT)(&pAd->PsPollContext);
					pNULLContext = (PTX_CONTEXT)(&pAd->NullContext);

					if (pMLMEContext->IRPPending)
					{
						ASSERT(pMLMEContext->IRPPending);
						pUrb = pMLMEContext->pUrb;
					}
					else if (pNULLContext->IRPPending)
					{
						ASSERT(pNULLContext->IRPPending);
						pUrb = pNULLContext->pUrb;
					}
					else if (pPsPollContext->IRPPending)
					{
						ASSERT(pPsPollContext->IRPPending);
						pUrb = pPsPollContext->pUrb;
					}
				}

				RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[idx], irqFlags);

				DBGPRINT(RT_DEBUG_TRACE, ("Maybe the Tx Bulk-Out hanged! Cancel the pending Tx bulks request of idx(%d)!\n", idx));
				if (pUrb)
				{
					DBGPRINT(RT_DEBUG_TRACE, ("Unlink the pending URB!\n"));
					// unlink it now
					RTUSB_UNLINK_URB(pUrb);
					// Sleep 200 microseconds to give cancellation time to work
					RTMPusecDelay(200);
					needDumpSeq = TRUE;
				}
				else
				{
					DBGPRINT(RT_DEBUG_ERROR, ("Unkonw bulkOut URB maybe hanged!!!!!!!!!!!!\n"));
				}
			}
			else
			{
				RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[idx], irqFlags);
			}
		}
		else
		{
			RTMP_IRQ_UNLOCK(&pAd->BulkOutLock[idx], irqFlags);
		}
	}

#ifdef DOT11_N_SUPPORT
	// For Sigma debug, dump the ba_reordering sequence.
	if((needDumpSeq == TRUE) && (pAd->CommonCfg.bDisableReordering == 0))
	{
		USHORT				Idx;
		PBA_REC_ENTRY		pBAEntry = NULL;
		UCHAR				count = 0;
		struct reordering_mpdu *mpdu_blk;

		Idx = pAd->MacTab.Content[BSSID_WCID].BARecWcidArray[0];

		pBAEntry = &pAd->BATable.BARecEntry[Idx];
		if((pBAEntry->list.qlen > 0) && (pBAEntry->list.next != NULL))
		{
			DBGPRINT(RT_DEBUG_TRACE, ("NICUpdateRawCounters():The Queueing pkt in reordering buffer:\n"));
			NdisAcquireSpinLock(&pBAEntry->RxReRingLock);
			mpdu_blk = pBAEntry->list.next;
			while (mpdu_blk)
			{
				DBGPRINT(RT_DEBUG_TRACE, ("\t%d:Seq-%d, bAMSDU-%d!\n", count, mpdu_blk->Sequence, mpdu_blk->bAMSDU));
				mpdu_blk = mpdu_blk->next;
				count++;
			}

			DBGPRINT(RT_DEBUG_TRACE, ("\npBAEntry->LastIndSeq=%d!\n", pBAEntry->LastIndSeq));
			NdisReleaseSpinLock(&pBAEntry->RxReRingLock);
		}
	}
#endif // DOT11_N_SUPPORT //
}

#endif // RTMP_MAC_USB //


text:
apigility-xml-negotiation
=========================

Apigility Module providing XML content-negotiation features

----------

This module is inspired from [abandoned ApigilityXml project][source] for [Markus][source_dev]!
[source]: https://github.com/zpetr/apigility-xmlnegotiation
[source_dev]: https://github.com/markushausammann

----------

Necessary infrastructure to handle XML with ZF Apigility with HAL structure.

Response type is based on *Accept* header :

- request that specifies **application/xml** (or **application/\*+xml**) get the content in XML
- **application/hal+json** (or **application/\*+json**) request get the content in HalJson as usual.

### Installation
Install composer in your project

    curl -s http://getcomposer.org/installer | php

Define dependencies in your composer.json file

```json
{
    "require": {
        "diegograssato/apigility-xml-negotiation" : "dev-master"
    }
}
```

Finally install dependencies

    php composer.phar install

or update it

    php composer.phar update

### Usage
- Add *ZF\ContentNegotiation\XML* to modules.config.php:
```php
	return array(
    	...,
        'ZF\ContentNegotiation\XML',
        ....
	)
```
- Go to admin, select your API and change *Content Negotiation Selector* to **HalJsonXML**
- Add **application/xml** to *Accept whitelist* and *Content-Type whitelist*. Add other headers if needed.
- Save configuration


text:
package support;

import data.ModelAccessException;
import data.TrustView;

/**
 *
Represents a bootstrap service.

 *
 *
A method to bootstrap the {@link TrustView} is described in
 * <q>Trust views for the web pki</q> [1], section 4.3.1.

 *
 *
[1] Johannes Braun, Florian Volk, Johannes Buchmann, and Max Mühlhäuser.
 * Trust views for the web pki. 2013.

 *
 * @author Pascal Weisenburger
 */
public interface BootstrapService {
	/**
	 * Bootstraps the given trust view
	 * @param securityLevel the security level that is to be assumed while
	 * validating during the bootstrapping process
	 * @param observer an observer that can be used to gather information on the
	 * current bootstrapping progress, can be null
	 * @throws ModelAccee usedssException
	 */
	void bootstrap(double securityLevel, Observer observer) throws ModelAccessException;

	/**
	 * Represents the bootstrap service observer interface that can be used to
	 * gather information on the current bootstrapping progress
	 */
	static interface Observer {
		/**
		 * Informs an observer on the bootstrapping progress
		 * @param progress the progress between 0 and 1
		 * @param item the item currently processed
		 * @return returns false to indicate that the bootstrapping
		 * progress should be canceled
		 */
		boolean update(double progress, String item);
	}
}


text:
from operator import xor

PADDED_BINARY_BIT_STRING = "{0:0{1:0d}b}"

def bitwise_dot_product(bs0: str, bs1: str) -> str:
    """
    A helper to calculate the bitwise dot-product between two string representing bit-vectors

    :param bs0: String of 0's and 1's representing a number in binary representations
    :param bs1: String of 0's and 1's representing a number in binary representations
    :return: 0 or 1 as a string corresponding to the dot-product value
    """
    if len(bs0) != len(bs1):
        raise ValueError("Bit strings are not of equal length")
    return str(sum([int(bs0[i]) * int(bs1[i]) for i in range(len(bs0))]) % 2)

def bitwise_xor(bs0: str, bs1: str) -> str:
    """
    A helper to calculate the bitwise XOR of two bit string

    :param bs0: String of 0's and 1's representing a number in binary representations
    :param bs1: String of 0's and 1's representing a number in binary representations
    :return: String of 0's and 1's representing the XOR between bs0 and bs1
    """
    if len(bs0) != len(bs1):
        raise ValueError("Bit strings are not of equal length")
    n_bits = len(bs0)
    return PADDED_BINARY_BIT_STRING.format(xor(int(bs0, 2), int(bs1, 2)), n_bits)