text:
import { ConfiguredRenderable, SerializedRenderable } from '../dom';
import { SerializerContainer, Serializer } from '../serialization';
import { View } from './View';
import { isBoolean, isNumber } from '../utils';
import { ResolverStrategy, CacheStrategy } from './common';
import { ConfiguredItem } from '../ConfiguredItem';

export interface SerializedView extends SerializedRenderable {
  lazy: boolean|null;
  ref: string|null;
  caching?: CacheStrategy|null;
  token: string;
  useClass: string;
  resolution: ResolverStrategy|null;
  viewComponentConfig: any;
}

export class ViewSerializer extends Serializer<View, SerializedView> {
  serialize(node: View): SerializedView {
    const token = this.container.resolveClassString(node.token);

    if (!token) {
      throw new Error('Can not serialize view with no registered token.');
    }

    return {
      token,
      name: 'View',
      tags: [ ...node.tags ],
      ref: node.ref,
      caching: node.caching != null ? node.caching : undefined,
      lazy: node.lazy,
      useClass: token,
      resolution: node.resolution,
      viewComponentConfig: node.viewComponentConfig
    };
  }

  deserialize(node: SerializedView): ConfiguredRenderable<View> {
    const token = this.container.resolveClass(node.token);
    const useClass = this.container.resolveClass(node.useClass);

    if (!token || !useClass) {
      throw new Error('Could not resolve view classes.');
    }

    return View.configure({
      token,
      useClass: new ConfiguredItem(useClass, node.viewComponentConfig),
      caching: node.caching != null ? node.caching : undefined,
      lazy: isBoolean(node.lazy) ? node.lazy : undefined,
      resolution: isNumber(node.resolution) ? node.resolution : undefined,
      ref: node.ref,
      tags: node.tags
    });
  }

  static register(container: SerializerContainer): void {
    container.registerClass('View', View);

    Serializer.register.call(this, container);
  }
}


text:
package com.infinities.keystone4j.assignment.api.command.group;

import com.infinities.keystone4j.NonTruncatedCommand;
import com.infinities.keystone4j.assignment.AssignmentApi;
import com.infinities.keystone4j.assignment.AssignmentDriver;
import com.infinities.keystone4j.assignment.api.command.AbstractAssignmentCommand;
import com.infinities.keystone4j.contrib.revoke.RevokeApi;
import com.infinities.keystone4j.credential.CredentialApi;
import com.infinities.keystone4j.identity.IdentityApi;
import com.infinities.keystone4j.model.identity.Group;

public class DeleteGroupCommand extends AbstractAssignmentCommand implements NonTruncatedCommand<Group> {

	// private final static Logger logger =
	// LoggerFactory.getLogger(DeleteUserCommand.class);
	private final String groupid;

	public DeleteGroupCommand(CredentialApi credentialApi, IdentityApi identityApi, AssignmentApi assignmentApi,
			RevokeApi revokeApi, AssignmentDriver assignmentDriver, String groupid) {
		super(credentialApi, identityApi, assignmentApi, revokeApi, assignmentDriver);
		this.groupid = groupid;
	}

	@Override
	public Group execute() throws Exception {
		this.getAssignmentDriver().deleteGroup(groupid);
		return null;
	}
}

redpajama_set_name: RedPajamaGithub


text:
private: \
    friend class AcDbSystemInternals; \
protected: \
    CLASSNAME(AcDbSystemInternals*); \
public: \
    ACRX_DECLARE_MEMBERS(CLASSNAME)

#define ACDBCORE2D_DECLARE_MEMBERS(CLASSNAME) \
private: \
    friend class AcDbSystemInternals; \
protected: \
    CLASSNAME(AcDbSystemInternals*); \
public: \
    ACRX_DECLARE_MEMBERS_EXPIMP(CLASSNAME, ACDBCORE2D_PORT)

#endif


text:
0.7.3 (2015-03-03)
------------------
* Fix upgrade of CDB_StringToDate function
* Add a test for to validate CDB_TableMetadataTouch usage with OID

0.7.2 (2015-03-03)
------------------
* Fix conversion of strings to datetime

0.7.1 (2015-02-27)
------------------
* Revert quota checks to `pg_total_relation_size`

0.7.0 (2015-02-19)
------------------
* Adds CDB_ZoomFromScale function

0.6.0 (2015-02-19)
------------------
* Select permission in CDB_TableMetadata no longer granted to public
* New function to upsert the updated_at in CDB_TableMetadata for a regclass

0.5.3 (2015-02-17)
------------------
* Fixed security problem related with system tables
* Changed quota checks to use `pg_relation_size` instead of `pg_total_relation_size`

0.5.2 (2015-01-29)
------------------
* Improvement: make CDB_UserDataSize functions much faster.

0.5.1 (2014-11-21)
------------------
* Bugfix: Quota check and some organization permissions functions were not properly escaping table name.

0.5.0 (2014-11-03)
------------------
* Support of raster tables for cartodbfication
* Modified quota functions: vector tables stay the same, raster tables count as full size (as have no
  the_geom + the_geom_webmercator combo) and raster overviews are not counted

0.4.1 (2014-09-21)
------------------
* Bugfix for Cartodbfication: Set primary key of the table if not already present (e.g. tables created from SQL API)

0.4.0 (2014-08-27)
------------------
Added CDB_Math_Mode function
Changes in versioning: no revision is attached so it no longer uses `git describe` for the version.

0.3.6 (2014-08-11)
------------------
Dummy release to solve some issues with cdb branch/tag

0.3.5 (2014-08-11)
------------------
Inverting priority of CDB_CheckQuota qmax so gies more priority to existing user quota function over parameter value.

0.3.4 (2014-08-01)
------------------
Fixes issue with schemas in CDB_QueryTables

0.3.3 (2014-07-30)
------------------
* Splitting of CartodbfyTable method in subfunctions to be able to call in fragments and evade timeouts on hot zones

0.3.2 (2014-07-28)
------------------
* Make 0.3.0dev version upgradeable

0.3.1 (2014-07-22)
------------------
* Dummy version. We start using semantic versioning

0.3.0 (2014-07-15)
------------------
* Permission management functions
* Adapt functions to use schemas

0.2.1 - 2014-06-11
------------------

Enhancements:

 - Do not force re-cartodbfication on CREATE FROM unpackaged
 - Drop useless DEFAULT specification in plpgsql variable declarations
 - List plpythonu requirement first, to get pg_catalog scanned before public

Bug fixes:

 - Do not add unique index on cartodb_id if already a primary key (#38)

0.2.0 - 2014-06-09
------------------

Important changes:

 - This release adds dependency on "plpythonu" extension
 - Roles are not created anymore, previously private functions
   for table information extraction (CDB_UserTables, CDB_TableIndexes,
   CDB_ColumnNames, CDB_ColumnType) will now be callable by anyone while
   only returning information about tables over which the calling user
   has SELECT privilege (#36)

Bug fixes:

 - Fix recursive trigger on create table (#32)
 - Ensure cartodb_id uses an associated sequence (#33)
 - Fully qualify call to cdb_disable_ddl_hooks from cdb_enable_ddl_hooks
 - Fully qualify call to CDB_UserDataSize from quota trigger
 - Fully qualify call to CDB_TransformToWebmercator from CDB_CartodbfyTable
 - Fix potential infinite loop in CDB_CartodbfyTable
 - Fix potential infinite loop in CDB_QueryStatements

Enhancements:

 - Include revision info in cdb_version() output (#34)

New features:

 - Add a cdb_extension_reload() function

0.1.0 - 2014-05-23
------------------

Initial release


text:
import sys
from distutils.core import setup
import os

version = '0.1.0'

setup(
    name='django-deploy',
    version=version,
    description="A utility for Django to create/deploy Django applications.",
    long_description=open('README.rst', 'r').read(),
    author='Nowell Strite',
    author_email='nowell@strite.org',
    url='http://github.com/nowells/django-deploy/',
    packages=['djangodeploy'],
    license='MIT',
    classifiers=[
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Utilities',
        'Environment :: Console',
        'Natural Language :: English',
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: POSIX :: Linux',
        'Operating System :: Unix',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.4',
        'Programming Language :: Python :: 2.5',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Utilities',
        ],
    scripts=['bin/django-skeleton'],
    )


text:
//===--- RequirementEnvironment.cpp - Requirement Environments ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the RequirementEnvironment class, which is used to
// capture how a witness to a protocol requirement maps type parameters.
//
//===----------------------------------------------------------------------===//

#include "swift/AST/RequirementEnvironment.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DeclContext.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/Types.h"
#include "llvm/ADT/Statistic.h"

#define DEBUG_TYPE "Protocol conformance checking"

using namespace swift;

STATISTIC(NumRequirementEnvironments, "# of requirement environments");

RequirementEnvironment::RequirementEnvironment(
                                           DeclContext *conformanceDC,
                                           GenericSignature reqSig,
                                           ProtocolDecl *proto,
                                           ClassDecl *covariantSelf,
                                           ProtocolConformance *conformance)
    : reqSig(reqSig) {
  ASTContext &ctx = conformanceDC->getASTContext();

  auto concreteType = conformanceDC->getSelfInterfaceType();
  auto conformanceSig = conformanceDC->getGenericSignatureOfContext();

  // This is a substitution function from the generic parameters of the
  // conforming type to the synthetic environment.
  //
  // For structs, enums and protocols, this is a 1:1 mapping; for classes,
  // we increase the depth of each generic parameter by 1 so that we can
  // introduce a class-bound 'Self' parameter.
  //
  // This is a raw function rather than a substitution map because we need to
  // keep generic parameters as generic, even if the conformanceSig (the best
  // way to create the substitution map) equates them to concrete types.
  auto conformanceToSyntheticTypeFn = [&](SubstitutableType *type) {
    auto *genericParam = cast<GenericTypeParamType>(type);
    if (covariantSelf) {
      return GenericTypeParamType::get(genericParam->getDepth() + 1,
                                       genericParam->getIndex(), ctx);
    }

    return GenericTypeParamType::get(genericParam->getDepth(),
                                     genericParam->getIndex(), ctx);
  };
  auto conformanceToSyntheticConformanceFn =
      MakeAbstractConformanceForGenericType();

  auto substConcreteType = concreteType.subst(
      conformanceToSyntheticTypeFn, conformanceToSyntheticConformanceFn);

  // Calculate the depth at which the requirement's generic parameters
  // appear in the synthetic signature.
  unsigned depth = 0;
  if (covariantSelf) {
    ++depth;
  }
  if (conformanceSig) {
    depth += conformanceSig.getGenericParams().back()->getDepth() + 1;
  }

  // Build a substitution map to replace the protocol's \c Self and the type
  // parameters of the requirement into a combined context that provides the
  // type parameters of the conformance context and the parameters of the
  // requirement.
  auto selfType = cast<GenericTypeParamType>(
      proto->getSelfInterfaceType()->getCanonicalType());

  reqToSyntheticEnvMap = SubstitutionMap::get(reqSig,
    [selfType, substConcreteType, depth, covariantSelf, &ctx]
    (SubstitutableType *type) -> Type {
      // If the conforming type is a class, the protocol 'Self' maps to
      // the class-constrained 'Self'. Otherwise, it maps to the concrete
      // type.
      if (type->isEqual(selfType)) {
        if (covariantSelf)
          return GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
        return substConcreteType;
      }
      // Other requirement generic parameters map 1:1 with their depth
      // increased appropriately.
      auto *genericParam = cast<GenericTypeParamType>(type);
      // In a protocol requirement, the only generic parameter at depth 0
      // should be 'Self', and all others at depth 1. Anything else is
      // invalid code.
      if (genericParam->getDepth() != 1)
        return Type();
      auto substGenericParam =
        GenericTypeParamType::get(depth, genericParam->getIndex(), ctx);
      return substGenericParam;
    },
    [selfType, substConcreteType, conformance, conformanceDC, &ctx](
        CanType type, Type replacement, ProtocolDecl *proto)
          -> ProtocolConformanceRef {
      // The protocol 'Self' conforms concretely to the conforming type.
      if (type->isEqual(selfType)) {
        ProtocolConformance *specialized = conformance;
        if (conformance && conformance->getGenericSignature()) {
          auto concreteSubs =
            substConcreteType->getContextSubstitutionMap(
              conformanceDC->getParentModule(), conformanceDC);
          specialized =
            ctx.getSpecializedConformance(substConcreteType, conformance,
                                          concreteSubs);
        }

        if (specialized)
          return ProtocolConformanceRef(specialized);
      }

      // All other generic parameters come from the requirement itself
      // and conform abstractly.
      return ProtocolConformanceRef(proto);
    });

  // If the requirement itself is non-generic, the synthetic signature
  // is that of the conformance context.
  if (!covariantSelf &&
      reqSig.getGenericParams().size() == 1 &&
      reqSig.getRequirements().size() == 1) {
    syntheticSignature = conformanceDC->getGenericSignatureOfContext().getCanonicalSignature();
    syntheticEnvironment =
      syntheticSignature.getGenericEnvironment();

    return;
  }

  // Construct a generic signature by collecting the constraints
  // from the requirement and the context of the conformance together,
  // because both define the capabilities of the requirement.
  SmallVector<GenericTypeParamType *, 2> genericParamTypes;

  // If the conforming type is a class, add a class-constrained 'Self'
  // parameter.
  if (covariantSelf) {
    auto paramTy = GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
    genericParamTypes.push_back(paramTy);
  }

  // Now, add all generic parameters from the conforming type.
  if (conformanceSig) {
    for (auto param : conformanceSig.getGenericParams()) {
      auto substParam = Type(param).subst(conformanceToSyntheticTypeFn,
                                          conformanceToSyntheticConformanceFn);
      genericParamTypes.push_back(substParam->castTo<GenericTypeParamType>());
    }
  }

  // Next, add requirements.
  SmallVector<Requirement, 2> requirements;
  if (covariantSelf) {
    auto paramTy = GenericTypeParamType::get(/*depth=*/0, /*index=*/0, ctx);
    Requirement reqt(RequirementKind::Superclass, paramTy, substConcreteType);
    requirements.push_back(reqt);
  }

  if (conformanceSig) {
    for (auto &rawReq : conformanceSig.getRequirements()) {
      if (auto req = rawReq.subst(conformanceToSyntheticTypeFn,
                                  conformanceToSyntheticConformanceFn))
        requirements.push_back(*req);
    }
  }

  // Finally, add the generic parameters from the requirement.
  for (auto genericParam : reqSig.getGenericParams().slice(1)) {
    // The only depth that makes sense is depth == 1, the generic parameters
    // of the requirement itself. Anything else is from invalid code.
    if (genericParam->getDepth() != 1) {
      return;
    }

    // Create an equivalent generic parameter at the next depth.
    auto substGenericParam =
      GenericTypeParamType::get(depth, genericParam->getIndex(), ctx);

    genericParamTypes.push_back(substGenericParam);
  }

  ++NumRequirementEnvironments;

  // Next, add each of the requirements (mapped from the requirement's
  // interface types into the abstract type parameters).
  for (auto &rawReq : reqSig.getRequirements()) {
    if (auto req = rawReq.subst(reqToSyntheticEnvMap))
      requirements.push_back(*req);
  }

  // Produce the generic signature and environment.
  // FIXME: Pass in a source location for the conformance, perhaps? It seems
  // like this could fail.
  syntheticSignature = evaluateOrDefault(
      ctx.evaluator,
      AbstractGenericSignatureRequest{
        nullptr, std::move(genericParamTypes), std::move(requirements)},
      GenericSignature());
  syntheticEnvironment = syntheticSignature.getGenericEnvironment();
}


text:
from __future__ import unicode_literals, division, absolute_import

from flask import request
from flask.ext.login import current_user

from flexget.api import api, APIResource
from flexget.webserver import change_password, generate_token, WeakPassword

user_api = api.namespace('user', description='Manage user login credentials')

user_password_input = {
    'type': 'object',
    'properties': {
        'password': {'type': 'string'}
    }
}
user_password_input_schema = api.schema('user_password_input', user_password_input)

@user_api.route('/')
@api.doc('Change user password')
class UserManagementAPI(APIResource):
    @api.validate(model=user_password_input_schema, description='Password change schema')
    @api.response(400, 'Password not strong enough')
    def put(self, session=None):
        """ Change user password """
        user = current_user
        data = request.json
        try:
            change_password(user_name=user.name, password=data.get('password'), session=session)
        except WeakPassword as e:
            return {'status': 'error',
                    'message': e.value}, 400
        return {'status': 'success',
                'message': 'Successfully changed user password'}

user_token_response = {
    'type': 'object',
    'properties': {
        'status': {'type': 'string'},
        'message': {'type': 'string'},
        'token': {'type': 'string'}
    }
}

user_token_response_schema = api.schema('user_token_response', user_token_response)

@user_api.route('/token/')
@api.doc('Change user token')
class UserManagementAPI(APIResource):
    @api.response(200, 'Successfully changed user token', user_token_response_schema)
    def get(self, session=None):
        """ Change current user token """
        user = generate_token(user_name=current_user.name, session=session)
        return {'status': 'success',
                'message': 'Successfully changed user token',
                'token': user.token}


text:
layout: post
title: Shared Ideas
date: 2018-06-22
categories:
  - devoctomy
  - website
  - announcements
  - ideas
description: My thoughts, shared with my readers.
image: /assets/images/lightbulbs.jpg
image-sm: /assets/images/lightbulbs_small.jpg
type: blog
author: nick
---

This is just a super-quick post to mention about a new section on my website, "[Ideas](/?tab=2)".  The whole intent of this new section is to share ideas for software related projects, be-it applications, games or just techniques.  I may work on some of them, I may not, but the intention was to share ideas rather than just letting them float off into the ether, which is too easily done unfortunately.

Please check it out via the main navigation bar.  I've also spent the time tweaking some styles of this site, HTML / CSS really isn't my thing, so it may take me some attempts before things look right.


text:
using System;

namespace Facturapi
{
    public class Certificate
    {
        public DateTime UpdatedAt { get; set; }
        public DateTime ExpiresAt { get; set; }
        public bool HasCertificate { get; set; }
    }
}


text:
class Platform:
    def __init__(self, id_address, id_qty_container):
        self.id_address = id_address
        self.id_qty_container = id_qty_container


text:
/**
 * Action to select the participant to be displayed in LargeVideo.
 *
 * {
 *     type: SELECT_LARGE_VIDEO_PARTICIPANT,
 *     participantId: (string|undefined)
 * }
 */
export const SELECT_LARGE_VIDEO_PARTICIPANT
    = 'SELECT_LARGE_VIDEO_PARTICIPANT';

/**
 * Action to update the redux store with the current resolution of large video.
 *
 * @returns {{
 *     type: UPDATE_KNOWN_LARGE_VIDEO_RESOLUTION,
 *     resolution: number
 * }}
 */
export const UPDATE_KNOWN_LARGE_VIDEO_RESOLUTION
    = 'UPDATE_KNOWN_LARGE_VIDEO_RESOLUTION';

/**
 * Action to update the redux store with the current media event name of large video.
 *
 * @returns {{
 *     type: UPDATE_LAST_LARGE_VIDEO_MEDIA_EVENT,
 *     name: string
 * }}
 */
export const UPDATE_LAST_LARGE_VIDEO_MEDIA_EVENT
    = 'UPDATE_LAST_LARGE_VIDEO_MEDIA_EVENT';


text:
package com.jgeppert.struts2.jquery.showcase.datatables;

import com.jgeppert.struts2.jquery.showcase.model.Customer;
import com.jgeppert.struts2.jquery.showcase.model.CustomerDAO;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.SessionAware;

import java.util.List;
import java.util.Map;
import java.util.Random;

public class DatatablesSave extends ActionSupport implements SessionAware {

    private static final Log log = LogFactory.getLog(DatatablesSave.class);

    private Map<String, Object> session;
    private String id;
    private String name;
    private String country;
    private String city;
    private String creditLimit;
    private Customer customer;

    public DatatablesSave() {
    }

    @Override
    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    @Override
    @Action(interceptorRefs = @InterceptorRef("jsonValidationWorkflowStack"), results = {
            @Result(name = SUCCESS, type = "json", params = {"includeProperties", "actionMessages.*,customer.*",
                    "ignoreHierarchy", "false"}),
            @Result(name = ERROR, type = "json", params = {"includeProperties", "actionErrors.*", "ignoreHierarchy",
                    "false", "statusCode", "500"})})
    public String execute() throws Exception {
        String ret = SUCCESS;
        try {
            List<Customer> list = (List<Customer>) session.get("mylist");
            Customer customer = null;
            if (this.id != null && !"".equals(id)) {
                customer = CustomerDAO.findById(list, Integer.parseInt(id));
                log.debug("Updating customer");
            } else {
                customer = new Customer();
                customer.setId(new Random().nextInt());
                list.add(customer);
                log.debug("Created customer");
            }
            customer.setName(name);
            customer.setCountry(country);
            customer.setCity(city);
            customer.setCreditLimit(Double.parseDouble(creditLimit));
            this.customer = customer;
        } catch (Exception e) {
            ret = ERROR;
            this.addActionError("Error while saving customer : " + e.getMessage());
        }
        return ret;
    }

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @RequiredStringValidator(fieldName = "name", type = ValidatorType.FIELD, message = "Name is required")
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @RequiredStringValidator(fieldName = "country", type = ValidatorType.FIELD, message = "Country is required")
    public String getCountry() {
        return this.country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @RequiredStringValidator(fieldName = "city", type = ValidatorType.FIELD, message = "City is required")
    public String getCity() {
        return this.city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @RequiredStringValidator(fieldName = "creditLimit", type = ValidatorType.FIELD, message = "CreditLimit is required")
    public String getCreditLimit() {
        return this.creditLimit;
    }

    public void setCreditLimit(String creditLimit) {
        this.creditLimit = creditLimit;
    }

    public Map<String, Object> getSession() {
        return this.session;
    }

    public Customer getCustomer() {
        return this.customer;
    }

}


text:
namespace {

#if V8_OS_MACOSX
int64_t ComputeThreadTicks() {
  mach_msg_type_number_t thread_info_count = THREAD_BASIC_INFO_COUNT;
  thread_basic_info_data_t thread_info_data;
  kern_return_t kr = thread_info(
      pthread_mach_thread_np(pthread_self()),
      THREAD_BASIC_INFO,
      reinterpret_cast<thread_info_t>(&thread_info_data),
      &thread_info_count);
  CHECK(kr == KERN_SUCCESS);

  v8::base::CheckedNumeric<int64_t> absolute_micros(
      thread_info_data.user_time.seconds +
      thread_info_data.system_time.seconds);
  absolute_micros *= v8::base::Time::kMicrosecondsPerSecond;
  absolute_micros += (thread_info_data.user_time.microseconds +
                      thread_info_data.system_time.microseconds);
  return absolute_micros.ValueOrDie();
}
#elif V8_OS_POSIX
// Helper function to get results from clock_gettime() and convert to a
// microsecond timebase. Minimum requirement is MONOTONIC_CLOCK to be supported
// on the system. FreeBSD 6 has CLOCK_MONOTONIC but defines
// _POSIX_MONOTONIC_CLOCK to -1.
V8_INLINE int64_t ClockNow(clockid_t clk_id) {
#if (defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0) || \
  defined(V8_OS_BSD) || defined(V8_OS_ANDROID)
// On AIX clock_gettime for CLOCK_THREAD_CPUTIME_ID outputs time with
// resolution of 10ms. thread_cputime API provides the time in ns
#if defined(V8_OS_AIX)
  thread_cputime_t tc;
  if (clk_id == CLOCK_THREAD_CPUTIME_ID) {
    if (thread_cputime(-1, &tc) != 0) {
      UNREACHABLE();
      return 0;
    }
  }
#endif
  struct timespec ts;
  if (clock_gettime(clk_id, &ts) != 0) {
    UNREACHABLE();
    return 0;
  }
  v8::base::internal::CheckedNumeric<int64_t> result(ts.tv_sec);
  result *= v8::base::Time::kMicrosecondsPerSecond;
#if defined(V8_OS_AIX)
  if (clk_id == CLOCK_THREAD_CPUTIME_ID) {
    result += (tc.stime / v8::base::Time::kNanosecondsPerMicrosecond);
  } else {
    result += (ts.tv_nsec / v8::base::Time::kNanosecondsPerMicrosecond);
  }
#else
  result += (ts.tv_nsec / v8::base::Time::kNanosecondsPerMicrosecond);
#endif
  return result.ValueOrDie();
#else  // Monotonic clock not supported.
  return 0;
#endif
}
#elif V8_OS_WIN
V8_INLINE bool IsQPCReliable() {
  v8::base::CPU cpu;
  // On Athlon X2 CPUs (e.g. model 15) QueryPerformanceCounter is unreliable.
  return strcmp(cpu.vendor(), "AuthenticAMD") == 0 && cpu.family() == 15;
}

// Returns the current value of the performance counter.
V8_INLINE uint64_t QPCNowRaw() {
  LARGE_INTEGER perf_counter_now = {};
  // According to the MSDN documentation for QueryPerformanceCounter(), this
  // will never fail on systems that run XP or later.
  // https://msdn.microsoft.com/library/windows/desktop/ms644904.aspx
  BOOL result = ::QueryPerformanceCounter(&perf_counter_now);
  DCHECK(result);
  USE(result);
  return perf_counter_now.QuadPart;
}
#endif  // V8_OS_MACOSX

}  // namespace

namespace v8 {
namespace base {

TimeDelta TimeDelta::FromDays(int days) {
  return TimeDelta(days * Time::kMicrosecondsPerDay);
}

TimeDelta TimeDelta::FromHours(int hours) {
  return TimeDelta(hours * Time::kMicrosecondsPerHour);
}

TimeDelta TimeDelta::FromMinutes(int minutes) {
  return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
}

TimeDelta TimeDelta::FromSeconds(int64_t seconds) {
  return TimeDelta(seconds * Time::kMicrosecondsPerSecond);
}

TimeDelta TimeDelta::FromMilliseconds(int64_t milliseconds) {
  return TimeDelta(milliseconds * Time::kMicrosecondsPerMillisecond);
}

TimeDelta TimeDelta::FromNanoseconds(int64_t nanoseconds) {
  return TimeDelta(nanoseconds / Time::kNanosecondsPerMicrosecond);
}

int TimeDelta::InDays() const {
  return static_cast<int>(delta_ / Time::kMicrosecondsPerDay);
}

int TimeDelta::InHours() const {
  return static_cast<int>(delta_ / Time::kMicrosecondsPerHour);
}

int TimeDelta::InMinutes() const {
  return static_cast<int>(delta_ / Time::kMicrosecondsPerMinute);
}

double TimeDelta::InSecondsF() const {
  return static_cast<double>(delta_) / Time::kMicrosecondsPerSecond;
}

int64_t TimeDelta::InSeconds() const {
  return delta_ / Time::kMicrosecondsPerSecond;
}

double TimeDelta::InMillisecondsF() const {
  return static_cast<double>(delta_) / Time::kMicrosecondsPerMillisecond;
}

int64_t TimeDelta::InMilliseconds() const {
  return delta_ / Time::kMicrosecondsPerMillisecond;
}

int64_t TimeDelta::InNanoseconds() const {
  return delta_ * Time::kNanosecondsPerMicrosecond;
}

#if V8_OS_MACOSX

TimeDelta TimeDelta::FromMachTimespec(struct mach_timespec ts) {
  DCHECK_GE(ts.tv_nsec, 0);
  DCHECK_LT(ts.tv_nsec,
            static_cast<long>(Time::kNanosecondsPerSecond));  // NOLINT
  return TimeDelta(ts.tv_sec * Time::kMicrosecondsPerSecond +
                   ts.tv_nsec / Time::kNanosecondsPerMicrosecond);
}

struct mach_timespec TimeDelta::ToMachTimespec() const {
  struct mach_timespec ts;
  DCHECK(delta_ >= 0);
  ts.tv_sec = static_cast<unsigned>(delta_ / Time::kMicrosecondsPerSecond);
  ts.tv_nsec = (delta_ % Time::kMicrosecondsPerSecond) *
      Time::kNanosecondsPerMicrosecond;
  return ts;
}

#endif  // V8_OS_MACOSX

#if V8_OS_POSIX

TimeDelta TimeDelta::FromTimespec(struct timespec ts) {
  DCHECK_GE(ts.tv_nsec, 0);
  DCHECK_LT(ts.tv_nsec,
            static_cast<long>(Time::kNanosecondsPerSecond));  // NOLINT
  return TimeDelta(ts.tv_sec * Time::kMicrosecondsPerSecond +
                   ts.tv_nsec / Time::kNanosecondsPerMicrosecond);
}

struct timespec TimeDelta::ToTimespec() const {
  struct timespec ts;
  ts.tv_sec = static_cast<time_t>(delta_ / Time::kMicrosecondsPerSecond);
  ts.tv_nsec = (delta_ % Time::kMicrosecondsPerSecond) *
      Time::kNanosecondsPerMicrosecond;
  return ts;
}

#endif  // V8_OS_POSIX

#if V8_OS_WIN

// We implement time using the high-resolution timers so that we can get
// timeouts which are smaller than 10-15ms. To avoid any drift, we
// periodically resync the internal clock to the system clock.
class Clock final {
 public:
  Clock() : initial_ticks_(GetSystemTicks()), initial_time_(GetSystemTime()) {}

  Time Now() {
    // Time between resampling the un-granular clock for this API (1 minute).
    const TimeDelta kMaxElapsedTime = TimeDelta::FromMinutes(1);

    LockGuard<Mutex> lock_guard(&mutex_);

    // Determine current time and ticks.
    TimeTicks ticks = GetSystemTicks();
    Time time = GetSystemTime();

    // Check if we need to synchronize with the system clock due to a backwards
    // time change or the amount of time elapsed.
    TimeDelta elapsed = ticks - initial_ticks_;
    if (time < initial_time_ || elapsed > kMaxElapsedTime) {
      initial_ticks_ = ticks;
      initial_time_ = time;
      return time;
    }

    return initial_time_ + elapsed;
  }

  Time NowFromSystemTime() {
    LockGuard<Mutex> lock_guard(&mutex_);
    initial_ticks_ = GetSystemTicks();
    initial_time_ = GetSystemTime();
    return initial_time_;
  }

 private:
  static TimeTicks GetSystemTicks() {
    return TimeTicks::Now();
  }

  static Time GetSystemTime() {
    FILETIME ft;
    ::GetSystemTimeAsFileTime(&ft);
    return Time::FromFiletime(ft);
  }

  TimeTicks initial_ticks_;
  Time initial_time_;
  Mutex mutex_;
};

static LazyStaticInstance<Clock, DefaultConstructTrait<Clock>,
                          ThreadSafeInitOnceTrait>::type clock =
    LAZY_STATIC_INSTANCE_INITIALIZER;

Time Time::Now() {
  return clock.Pointer()->Now();
}

Time Time::NowFromSystemTime() {
  return clock.Pointer()->NowFromSystemTime();
}

// Time between windows epoch and standard epoch.
static const int64_t kTimeToEpochInMicroseconds = V8_INT64_C(11644473600000000);

Time Time::FromFiletime(FILETIME ft) {
  if (ft.dwLowDateTime == 0 && ft.dwHighDateTime == 0) {
    return Time();
  }
  if (ft.dwLowDateTime == std::numeric_limits<DWORD>::max() &&
      ft.dwHighDateTime == std::numeric_limits<DWORD>::max()) {
    return Max();
  }
  int64_t us = (static_cast<uint64_t>(ft.dwLowDateTime) +
                (static_cast<uint64_t>(ft.dwHighDateTime) << 32)) / 10;
  return Time(us - kTimeToEpochInMicroseconds);
}

FILETIME Time::ToFiletime() const {
  DCHECK(us_ >= 0);
  FILETIME ft;
  if (IsNull()) {
    ft.dwLowDateTime = 0;
    ft.dwHighDateTime = 0;
    return ft;
  }
  if (IsMax()) {
    ft.dwLowDateTime = std::numeric_limits<DWORD>::max();
    ft.dwHighDateTime = std::numeric_limits<DWORD>::max();
    return ft;
  }
  uint64_t us = static_cast<uint64_t>(us_ + kTimeToEpochInMicroseconds) * 10;
  ft.dwLowDateTime = static_cast<DWORD>(us);
  ft.dwHighDateTime = static_cast<DWORD>(us >> 32);
  return ft;
}

#elif V8_OS_POSIX

Time Time::Now() {
  struct timeval tv;
  int result = gettimeofday(&tv, NULL);
  DCHECK_EQ(0, result);
  USE(result);
  return FromTimeval(tv);
}

Time Time::NowFromSystemTime() {
  return Now();
}

Time Time::FromTimespec(struct timespec ts) {
  DCHECK(ts.tv_nsec >= 0);
  DCHECK(ts.tv_nsec < static_cast<long>(kNanosecondsPerSecond));  // NOLINT
  if (ts.tv_nsec == 0 && ts.tv_sec == 0) {
    return Time();
  }
  if (ts.tv_nsec == static_cast<long>(kNanosecondsPerSecond - 1) &&  // NOLINT
      ts.tv_sec == std::numeric_limits<time_t>::max()) {
    return Max();
  }
  return Time(ts.tv_sec * kMicrosecondsPerSecond +
              ts.tv_nsec / kNanosecondsPerMicrosecond);
}

struct timespec Time::ToTimespec() const {
  struct timespec ts;
  if (IsNull()) {
    ts.tv_sec = 0;
    ts.tv_nsec = 0;
    return ts;
  }
  if (IsMax()) {
    ts.tv_sec = std::numeric_limits<time_t>::max();
    ts.tv_nsec = static_cast<long>(kNanosecondsPerSecond - 1);  // NOLINT
    return ts;
  }
  ts.tv_sec = static_cast<time_t>(us_ / kMicrosecondsPerSecond);
  ts.tv_nsec = (us_ % kMicrosecondsPerSecond) * kNanosecondsPerMicrosecond;
  return ts;
}

Time Time::FromTimeval(struct timeval tv) {
  DCHECK(tv.tv_usec >= 0);
  DCHECK(tv.tv_usec < static_cast<suseconds_t>(kMicrosecondsPerSecond));
  if (tv.tv_usec == 0 && tv.tv_sec == 0) {
    return Time();
  }
  if (tv.tv_usec == static_cast<suseconds_t>(kMicrosecondsPerSecond - 1) &&
      tv.tv_sec == std::numeric_limits<time_t>::max()) {
    return Max();
  }
  return Time(tv.tv_sec * kMicrosecondsPerSecond + tv.tv_usec);
}

struct timeval Time::ToTimeval() const {
  struct timeval tv;
  if (IsNull()) {
    tv.tv_sec = 0;
    tv.tv_usec = 0;
    return tv;
  }
  if (IsMax()) {
    tv.tv_sec = std::numeric_limits<time_t>::max();
    tv.tv_usec = static_cast<suseconds_t>(kMicrosecondsPerSecond - 1);
    return tv;
  }
  tv.tv_sec = static_cast<time_t>(us_ / kMicrosecondsPerSecond);
  tv.tv_usec = us_ % kMicrosecondsPerSecond;
  return tv;
}

#endif  // V8_OS_WIN

Time Time::FromJsTime(double ms_since_epoch) {
  // The epoch is a valid time, so this constructor doesn't interpret
  // 0 as the null time.
  if (ms_since_epoch == std::numeric_limits<double>::max()) {
    return Max();
  }
  return Time(
      static_cast<int64_t>(ms_since_epoch * kMicrosecondsPerMillisecond));
}

double Time::ToJsTime() const {
  if (IsNull()) {
    // Preserve 0 so the invalid result doesn't depend on the platform.
    return 0;
  }
  if (IsMax()) {
    // Preserve max without offset to prevent overflow.
    return std::numeric_limits<double>::max();
  }
  return static_cast<double>(us_) / kMicrosecondsPerMillisecond;
}

std::ostream& operator<<(std::ostream& os, const Time& time) {
  return os << time.ToJsTime();
}

#if V8_OS_WIN

class TickClock {
 public:
  virtual ~TickClock() {}
  virtual int64_t Now() = 0;
  virtual bool IsHighResolution() = 0;
};

// Overview of time counters:
// (1) CPU cycle counter. (Retrieved via RDTSC)
// The CPU counter provides the highest resolution time stamp and is the least
// expensive to retrieve. However, the CPU counter is unreliable and should not
// be used in production. Its biggest issue is that it is per processor and it
// is not synchronized between processors. Also, on some computers, the counters
// will change frequency due to thermal and power changes, and stop in some
// states.
//
// (2) QueryPerformanceCounter (QPC). The QPC counter provides a high-
// resolution (100 nanoseconds) time stamp but is comparatively more expensive
// to retrieve. What QueryPerformanceCounter actually does is up to the HAL.
// (with some help from ACPI).
// According to http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx
// in the worst case, it gets the counter from the rollover interrupt on the
// programmable interrupt timer. In best cases, the HAL may conclude that the
// RDTSC counter runs at a constant frequency, then it uses that instead. On
// multiprocessor machines, it will try to verify the values returned from
// RDTSC on each processor are consistent with each other, and apply a handful
// of workarounds for known buggy hardware. In other words, QPC is supposed to
// give consistent result on a multiprocessor computer, but it is unreliable in
// reality due to bugs in BIOS or HAL on some, especially old computers.
// With recent updates on HAL and newer BIOS, QPC is getting more reliable but
// it should be used with caution.
//
// (3) System time. The system time provides a low-resolution (typically 10ms
// to 55 milliseconds) time stamp but is comparatively less expensive to
// retrieve and more reliable.
class HighResolutionTickClock final : public TickClock {
 public:
  explicit HighResolutionTickClock(int64_t ticks_per_second)
      : ticks_per_second_(ticks_per_second) {
    DCHECK_LT(0, ticks_per_second);
  }
  virtual ~HighResolutionTickClock() {}

  int64_t Now() override {
    uint64_t now = QPCNowRaw();

    // Intentionally calculate microseconds in a round about manner to avoid
    // overflow and precision issues. Think twice before simplifying!
    int64_t whole_seconds = now / ticks_per_second_;
    int64_t leftover_ticks = now % ticks_per_second_;
    int64_t ticks = (whole_seconds * Time::kMicrosecondsPerSecond) +
        ((leftover_ticks * Time::kMicrosecondsPerSecond) / ticks_per_second_);

    // Make sure we never return 0 here, so that TimeTicks::HighResolutionNow()
    // will never return 0.
    return ticks + 1;
  }

  bool IsHighResolution() override { return true; }

 private:
  int64_t ticks_per_second_;
};

class RolloverProtectedTickClock final : public TickClock {
 public:
  RolloverProtectedTickClock() : rollover_(0) {}
  virtual ~RolloverProtectedTickClock() {}

  int64_t Now() override {
    // We use timeGetTime() to implement TimeTicks::Now(), which rolls over
    // every ~49.7 days. We try to track rollover ourselves, which works if
    // TimeTicks::Now() is called at least every 24 days.
    // Note that we do not use GetTickCount() here, since timeGetTime() gives
    // more predictable delta values, as described here:
    // http://blogs.msdn.com/b/larryosterman/archive/2009/09/02/what-s-the-difference-between-gettickcount-and-timegettime.aspx
    // timeGetTime() provides 1ms granularity when combined with
    // timeBeginPeriod(). If the host application for V8 wants fast timers, it
    // can use timeBeginPeriod() to increase the resolution.
    // We use a lock-free version because the sampler thread calls it
    // while having the rest of the world stopped, that could cause a deadlock.
    base::Atomic32 rollover = base::Acquire_Load(&rollover_);
    uint32_t now = static_cast<uint32_t>(timeGetTime());
    if ((now >> 31) != static_cast<uint32_t>(rollover & 1)) {
      base::Release_CompareAndSwap(&rollover_, rollover, rollover + 1);
      ++rollover;
    }
    uint64_t ms = (static_cast<uint64_t>(rollover) << 31) | now;
    return static_cast<int64_t>(ms * Time::kMicrosecondsPerMillisecond);
  }

  bool IsHighResolution() override { return false; }

 private:
  base::Atomic32 rollover_;
};

static LazyStaticInstance<RolloverProtectedTickClock,
                          DefaultConstructTrait<RolloverProtectedTickClock>,
                          ThreadSafeInitOnceTrait>::type tick_clock =
    LAZY_STATIC_INSTANCE_INITIALIZER;

struct CreateHighResTickClockTrait {
  static TickClock* Create() {
    // Check if the installed hardware supports a high-resolution performance
    // counter, and if not fallback to the low-resolution tick clock.
    LARGE_INTEGER ticks_per_second;
    if (!QueryPerformanceFrequency(&ticks_per_second)) {
      return tick_clock.Pointer();
    }

    // If QPC not reliable, fallback to low-resolution tick clock.
    if (IsQPCReliable()) {
      return tick_clock.Pointer();
    }

    return new HighResolutionTickClock(ticks_per_second.QuadPart);
  }
};

static LazyDynamicInstance<TickClock, CreateHighResTickClockTrait,
                           ThreadSafeInitOnceTrait>::type high_res_tick_clock =
    LAZY_DYNAMIC_INSTANCE_INITIALIZER;

TimeTicks TimeTicks::Now() {
  // Make sure we never return 0 here.
  TimeTicks ticks(tick_clock.Pointer()->Now());
  DCHECK(!ticks.IsNull());
  return ticks;
}

TimeTicks TimeTicks::HighResolutionNow() {
  // Make sure we never return 0 here.
  TimeTicks ticks(high_res_tick_clock.Pointer()->Now());
  DCHECK(!ticks.IsNull());
  return ticks;
}

// static
bool TimeTicks::IsHighResolutionClockWorking() {
  return high_res_tick_clock.Pointer()->IsHighResolution();
}

#else  // V8_OS_WIN

TimeTicks TimeTicks::Now() {
  return HighResolutionNow();
}

TimeTicks TimeTicks::HighResolutionNow() {
  int64_t ticks;
#if V8_OS_MACOSX
  static struct mach_timebase_info info;
  if (info.denom == 0) {
    kern_return_t result = mach_timebase_info(&info);
    DCHECK_EQ(KERN_SUCCESS, result);
    USE(result);
  }
  ticks = (mach_absolute_time() / Time::kNanosecondsPerMicrosecond *
           info.numer / info.denom);
#elif V8_OS_SOLARIS
  ticks = (gethrtime() / Time::kNanosecondsPerMicrosecond);
#elif V8_OS_POSIX
  ticks = ClockNow(CLOCK_MONOTONIC);
#endif  // V8_OS_MACOSX
  // Make sure we never return 0 here.
  return TimeTicks(ticks + 1);
}

// static
bool TimeTicks::IsHighResolutionClockWorking() {
  return true;
}

#endif  // V8_OS_WIN

bool ThreadTicks::IsSupported() {
#if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
    defined(V8_OS_MACOSX) || defined(V8_OS_ANDROID) || defined(V8_OS_SOLARIS)
  return true;
#elif defined(V8_OS_WIN)
  return IsSupportedWin();
#else
  return false;
#endif
}

ThreadTicks ThreadTicks::Now() {
#if V8_OS_MACOSX
  return ThreadTicks(ComputeThreadTicks());
#elif(defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
  defined(V8_OS_ANDROID)
  return ThreadTicks(ClockNow(CLOCK_THREAD_CPUTIME_ID));
#elif V8_OS_SOLARIS
  return ThreadTicks(gethrvtime() / Time::kNanosecondsPerMicrosecond);
#elif V8_OS_WIN
  return ThreadTicks::GetForThread(::GetCurrentThread());
#else
  UNREACHABLE();
  return ThreadTicks();
#endif
}

#if V8_OS_WIN
ThreadTicks ThreadTicks::GetForThread(const HANDLE& thread_handle) {
  DCHECK(IsSupported());

  // Get the number of TSC ticks used by the current thread.
  ULONG64 thread_cycle_time = 0;
  ::QueryThreadCycleTime(thread_handle, &thread_cycle_time);

  // Get the frequency of the TSC.
  double tsc_ticks_per_second = TSCTicksPerSecond();
  if (tsc_ticks_per_second == 0)
    return ThreadTicks();

  // Return the CPU time of the current thread.
  double thread_time_seconds = thread_cycle_time / tsc_ticks_per_second;
  return ThreadTicks(
      static_cast<int64_t>(thread_time_seconds * Time::kMicrosecondsPerSecond));
}

// static
bool ThreadTicks::IsSupportedWin() {
  static bool is_supported = base::CPU().has_non_stop_time_stamp_counter() &&
                             !IsQPCReliable();
  return is_supported;
}

// static
void ThreadTicks::WaitUntilInitializedWin() {
  while (TSCTicksPerSecond() == 0)
    ::Sleep(10);
}

double ThreadTicks::TSCTicksPerSecond() {
  DCHECK(IsSupported());

  // The value returned by QueryPerformanceFrequency() cannot be used as the TSC
  // frequency, because there is no guarantee that the TSC frequency is equal to
  // the performance counter frequency.

  // The TSC frequency is cached in a static variable because it takes some time
  // to compute it.
  static double tsc_ticks_per_second = 0;
  if (tsc_ticks_per_second != 0)
    return tsc_ticks_per_second;

  // Increase the thread priority to reduces the chances of having a context
  // switch during a reading of the TSC and the performance counter.
  int previous_priority = ::GetThreadPriority(::GetCurrentThread());
  ::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_HIGHEST);

  // The first time that this function is called, make an initial reading of the
  // TSC and the performance counter.
  static const uint64_t tsc_initial = __rdtsc();
  static const uint64_t perf_counter_initial = QPCNowRaw();

  // Make a another reading of the TSC and the performance counter every time
  // that this function is called.
  uint64_t tsc_now = __rdtsc();
  uint64_t perf_counter_now = QPCNowRaw();

  // Reset the thread priority.
  ::SetThreadPriority(::GetCurrentThread(), previous_priority);

  // Make sure that at least 50 ms elapsed between the 2 readings. The first
  // time that this function is called, we don't expect this to be the case.
  // Note: The longer the elapsed time between the 2 readings is, the more
  //   accurate the computed TSC frequency will be. The 50 ms value was
  //   chosen because local benchmarks show that it allows us to get a
  //   stddev of less than 1 tick/us between multiple runs.
  // Note: According to the MSDN documentation for QueryPerformanceFrequency(),
  //   this will never fail on systems that run XP or later.
  //   https://msdn.microsoft.com/library/windows/desktop/ms644905.aspx
  LARGE_INTEGER perf_counter_frequency = {};
  ::QueryPerformanceFrequency(&perf_counter_frequency);
  DCHECK_GE(perf_counter_now, perf_counter_initial);
  uint64_t perf_counter_ticks = perf_counter_now - perf_counter_initial;
  double elapsed_time_seconds =
      perf_counter_ticks / static_cast<double>(perf_counter_frequency.QuadPart);

  const double kMinimumEvaluationPeriodSeconds = 0.05;
  if (elapsed_time_seconds < kMinimumEvaluationPeriodSeconds)
    return 0;

  // Compute the frequency of the TSC.
  DCHECK_GE(tsc_now, tsc_initial);
  uint64_t tsc_ticks = tsc_now - tsc_initial;
  tsc_ticks_per_second = tsc_ticks / elapsed_time_seconds;

  return tsc_ticks_per_second;
}
#endif  // V8_OS_WIN

}  // namespace base
}  // namespace v8


text:
<?xml version="1.0"?>
<Document>

	<Sentence>
		<value>A neck lump is any lump, bump, or swelling in the neck.</value>
		<pattern_crowdsource> A [[neck lump|C0149736]] is any [[lump|C0577559]], bump, or [[swelling|C0013604]] in the [[neck|C1281592]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>neck lump</surface-form>
				<RDF-ID>C0149736</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>lump</surface-form>
				<RDF-ID>C0577559</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>swelling</surface-form>
				<RDF-ID>C0013604</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>neck</surface-form>
				<RDF-ID>C1281592</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0149736 ISA C0577559</triple>
			<triple>C1281592 LOCATION_OF C0013604</triple>
			<triple>C1281592 LOCATION_OF C0577559</triple>
			<triple>C1281592 LOCATION_OF C0149736</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>There are many causes of lumps in the neck.</value>
		<pattern_crowdsource> There are many causes of [[lumps|C0577559]] in the [[neck|C1281592]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>causes</surface-form>
				<RDF-ID>C0015127</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>lumps</surface-form>
				<RDF-ID>C0577559</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>neck</surface-form>
				<RDF-ID>C1281592</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C1281592 LOCATION_OF C0577559</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Lumps in the muscles of the neck are caused by injury or torticollis.</value>
		<pattern_crowdsource> Lumps in the [[muscles|C0026845]] of the [[neck|C1281592]] are caused by injury or torticollis.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Lumps</surface-form>
				<RDF-ID>C0577559</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>muscles</surface-form>
				<RDF-ID>C0026845</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>neck</surface-form>
				<RDF-ID>C1281592</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>injury</surface-form>
				<RDF-ID>C0175677</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>torticollis</surface-form>
				<RDF-ID>C0040485</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0026845 PART_OF C1281592</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Lumps in the skin or just below the skin are often caused by cysts, such as sebaceous cysts.</value>
		<pattern_crowdsource> Lumps in the skin or just below the skin are often caused by [[cysts|C0010709]], such as [[sebaceous cysts|C0014511]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Lumps</surface-form>
				<RDF-ID>C0577559</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>skin</surface-form>
				<RDF-ID>C0037267</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>skin</surface-form>
				<RDF-ID>C0037267</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>often</surface-form>
				<RDF-ID>C0332183</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>cysts</surface-form>
				<RDF-ID>C0010709</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>sebaceous cysts</surface-form>
				<RDF-ID>C0014511</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0014511 ISA C0010709</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Most cancers of the thyroid gland grow very slowly.</value>
		<pattern_crowdsource> Most [[cancers|C0006826]] of the [[thyroid gland|C0040132]] grow very slowly.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>cancers</surface-form>
				<RDF-ID>C0006826</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>thyroid gland</surface-form>
				<RDF-ID>C0040132</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>very</surface-form>
				<RDF-ID>C0442824</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0006826 PART_OF C0040132</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>All neck lumps in children and adults should be checked right away by a health care provider.</value>
		<pattern_crowdsource> All [[neck lumps|C0149736]] in [[children|C0008059]] and [[adults|C0001675]] should be checked right away by a health care provider.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>neck lumps</surface-form>
				<RDF-ID>C0149736</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>children</surface-form>
				<RDF-ID>C0008059</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>adults</surface-form>
				<RDF-ID>C0001675</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>right</surface-form>
				<RDF-ID>C0205090</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>health care provider</surface-form>
				<RDF-ID>C0018724</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0149736 PROCESS_OF C0008059</triple>
			<triple>C0149736 PROCESS_OF C0001675</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>In children, most neck lumps are caused by infections that can be treated.</value>
		<pattern_crowdsource> In children, most [[neck lumps|C0149736]] are caused by [[infections|C0021311]] that can be treated.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>children</surface-form>
				<RDF-ID>C0008059</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>neck lumps</surface-form>
				<RDF-ID>C0149736</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>infections</surface-form>
				<RDF-ID>C0021311</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0021311 CAUSES C0149736</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Treatment should start quickly to prevent complications or the spread of infection.</value>
		<pattern_crowdsource> [[Treatment|C0087111]] should start quickly to prevent [[complications|C0009566]] or the spread of infection.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Treatment</surface-form>
				<RDF-ID>C0087111</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>complications</surface-form>
				<RDF-ID>C0009566</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>infection</surface-form>
				<RDF-ID>C0009450</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0087111 PREVENTS C0009566</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Lumps in the neck from swollen lymph nodes may be caused by:  - Bacterial or viral infection  - Cancer  - Thyroid disease  - Allergic reaction   Lumps in the neck due to enlarged salivary glands may be caused by:  - Infection  - Mumps  - Salivary gland tumor  - Stone in salivary duct</value>
		<pattern_crowdsource> [[Lumps|C0577559]] in the [[neck|C0027530]] from swollen lymph nodes may be caused by:  - Bacterial or viral infection  - Cancer  - [[Thyroid disease  - Allergic reaction   Lumps|C0349453]] in the [[neck|C0027530]] due to enlarged salivary glands may be caused by:  - Infection  - Mumps  - Salivary gland tumor  - Stone in [[salivary duct|C0282582]]		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Lumps</surface-form>
				<RDF-ID>C0577559</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>neck</surface-form>
				<RDF-ID>C0027530</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>swollen lymph nodes</surface-form>
				<RDF-ID>C0497156</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Bacterial</surface-form>
				<RDF-ID>C0521009</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>infection</surface-form>
				<RDF-ID>C0009450</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>viral infection  - Cancer</surface-form>
				<RDF-ID>C1516237</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>disease</surface-form>
				<RDF-ID>C0012634</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Allergic reaction</surface-form>
				<RDF-ID>C1527304</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Thyroid disease  - Allergic reaction   Lumps</surface-form>
				<RDF-ID>C0349453</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>neck</surface-form>
				<RDF-ID>C0027530</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>enlarged</surface-form>
				<RDF-ID>C0442800</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>salivary glands</surface-form>
				<RDF-ID>C0036098</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Infection</surface-form>
				<RDF-ID>C0009450</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Mumps</surface-form>
				<RDF-ID>C0026780</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Salivary gland tumor</surface-form>
				<RDF-ID>C0036095</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Stone</surface-form>
				<RDF-ID>C0006736</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>salivary duct</surface-form>
				<RDF-ID>C0282582</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0027530 LOCATION_OF C0577559</triple>
			<triple>C0027530 LOCATION_OF C0349453</triple>
			<triple>C0027530 LOCATION_OF C0349453</triple>
			<triple>C0027530 LOCATION_OF C0577559</triple>
			<triple>C0282582 LOCATION_OF C0349453</triple>
			<triple>C0282582 LOCATION_OF C0577559</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Call your health care provider if you have an abnormal neck swelling or lumps in your neck.</value>
		<pattern_crowdsource> Call your [[health care provider|C0018724]] if you have an abnormal [[neck swelling|C0578454]] or [[lumps|C0577559]] in your [[neck|C1281592]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>health care provider</surface-form>
				<RDF-ID>C0018724</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>abnormal</surface-form>
				<RDF-ID>C0205161</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>neck swelling</surface-form>
				<RDF-ID>C0578454</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>lumps</surface-form>
				<RDF-ID>C0577559</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>neck</surface-form>
				<RDF-ID>C1281592</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0578454 PROCESS_OF C0018724</triple>
			<triple>C0577559 PROCESS_OF C0018724</triple>
			<triple>C1281592 LOCATION_OF C0577559</triple>
			<triple>C1281592 LOCATION_OF C0578454</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>- Do you have a rash or other symptoms  - Do you have difficulty breathing?</value>
		<pattern_crowdsource> - Do you have a [[rash|C0015230]] or other [[symptoms|C1457887]]  - Do you have difficulty breathing?		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>rash</surface-form>
				<RDF-ID>C0015230</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>symptoms</surface-form>
				<RDF-ID>C1457887</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>difficulty breathing</surface-form>
				<RDF-ID>C0013404</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0015230 ISA C1457887</triple>
			<triple>C1457887 ISA C0015230</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>You may need the following tests if the provider suspects a thyroid nodule:   - CT scan of the head or neck  - Radioactive thyroid scan  - Thyroid biopsy   If the lump is caused by a bacterial infection, you may need to take antibiotics.</value>
		<pattern_crowdsource> You may need the following tests if the [[provider|C1441436]] suspects a thyroid nodule:   - [[CT scan|C0040405]] of the [[head|C0018670]] or neck  - Radioactive thyroid scan  - Thyroid biopsy   If the lump is caused by a [[bacterial infection|C0004623]], you may need to take antibiotics.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>following</surface-form>
				<RDF-ID>C0332282</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>tests</surface-form>
				<RDF-ID>C0392366</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>provider</surface-form>
				<RDF-ID>C1441436</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>thyroid nodule</surface-form>
				<RDF-ID>C0040137</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>CT scan</surface-form>
				<RDF-ID>C0040405</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>head</surface-form>
				<RDF-ID>C0018670</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Radioactive</surface-form>
				<RDF-ID>C1514697</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>thyroid scan</surface-form>
				<RDF-ID>C0203779</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>neck  - Radioactive thyroid scan  - Thyroid biopsy</surface-form>
				<RDF-ID>C0195314</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>lump</surface-form>
				<RDF-ID>C0577559</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>bacterial infection</surface-form>
				<RDF-ID>C0004623</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>antibiotics</surface-form>
				<RDF-ID>C0003232</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0018670 LOCATION_OF C0040405</triple>
			<triple>C0004623 CAUSES C1441436</triple>
		</triples>
	</Sentence>

</Document>


text:
import os

import backoff
from google.api_core.exceptions import InternalServerError
import pytest

import list_operation_status

PROJECT_ID = os.environ["AUTOML_PROJECT_ID"]

@pytest.mark.slow
def test_list_operation_status(capsys):
    # We saw 500 InternalServerError. Now we just retry few times.
    @backoff.on_exception(backoff.expo, InternalServerError, max_time=120)
    def run_sample():
        list_operation_status.list_operation_status(PROJECT_ID)

    run_sample()
    out, _ = capsys.readouterr()
    assert "Operation details" in out


text:
var User       = require('../app/models/user');

module.exports = function(app, passport) {

// normal routes ===============================================================

	// show the home page (will also have our login links)
	app.get('/', function(req, res) {
		res.render('index.ejs');
	});

	// PROFILE SECTION =========================
	app.get('/profile', isLoggedIn, function(req, res) {
		res.render('profile.ejs', {
			user : req.user
		});
	});

	// LOGOUT ==============================
	app.get('/logout', function(req, res) {
		req.logout();
		res.redirect('/');
	});

// =============================================================================
// AUTHENTICATE (FIRST LOGIN) ==================================================
// =============================================================================

	// locally --------------------------------
		// LOGIN ===============================
		// show the login form
		app.get('/login', function(req, res) {
			res.render('login.ejs', { message: req.flash('loginMessage') });
		});

		// process the login form
		app.post('/login', passport.authenticate('local-login', {
			successRedirect : '/profile', // redirect to the secure profile section
			failureRedirect : '/login', // redirect back to the signup page if there is an error
			failureFlash : true // allow flash messages
		}));

		// SIGNUP =================================
		// show the signup form
		app.get('/signup', function(req, res) {
			res.render('signup.ejs', { message: req.flash('signupMessage') });
		});

		// process the signup form
		app.post('/signup', passport.authenticate('local-signup', {
			successRedirect : '/profile', // redirect to the secure profile section
			failureRedirect : '/signup', // redirect back to the signup page if there is an error
			failureFlash : true // allow flash messages
		}));

// =============================================================================
// AUTHORIZE (ALREADY LOGGED IN / CONNECTING OTHER SOCIAL ACCOUNT) =============
// =============================================================================

	// locally --------------------------------
		app.get('/connect/local', function(req, res) {
			res.render('connect-local.ejs', { message: req.flash('loginMessage') });
		});
		app.post('/connect/local', passport.authenticate('local-signup', {
			successRedirect : '/profile', // redirect to the secure profile section
			failureRedirect : '/connect/local', // redirect back to the signup page if there is an error
			failureFlash : true // allow flash messages
		}));

// =============================================================================
// UNLINK ACCOUNTS =============================================================
// =============================================================================
// used to unlink accounts. for social accounts, just remove the token
// for local account, remove email and password
// user account will stay active in case they want to reconnect in the future

	// local -----------------------------------
	app.get('/unlink/local', isLoggedIn, function(req, res) {
		console.log('req.user[0].email :',req.user[0].email);
		console.log('User',User);
		User.db.find({ email:req.user.email }, function(err, user) {
			console.log('user :',user);
			user.email = undefined;
			user.password = undefined;
			user.delete(user,function(err){
				if (err) throw err;
				res.redirect('/');
			});
		});
	/*
		var user      = req.user;
		console.log('user:',user);
		user.email    = undefined;
		user.password = undefined;
		user.delete(user.id, function(err) {
			if (err) throw err;
			res.redirect('/');
		});
	*/
	});

};

// route middleware to ensure user is logged in
function isLoggedIn(req, res, next) {
	if (req.isAuthenticated())
		return next();

	res.redirect('/');
}


text:
ionic-site
==========

Repo for the ionicframework.com site.  To preview local Ionic changes, follow the instructions at the [Ionic repo](https://github.com/driftyco/ionic#documentation).

gulp watch uses LiveReload. You may have to up your max file limit with the following command:

    ulimit -n 5000

## Local Build

    jekyll serve -w

    npm install

    sudo npm install -g gulp

    gulp watch

    http://localhost:4000/

## Deploy

Install [heroku-toolbelt](https://toolbelt.heroku.com/) or with homebrew

```bash
brew install heroku-toolbelt
```

Then log into  heroku

```bash
heroku login
# enter your email and password when promted
```

Then add the heroku remote

```bash
git remote add heroku https://git.heroku.com/ionic-site.git
```

- Make your changes
- Run `gulp`
- Run `./deploy.sh`
- `git push heroku master`

## Community

* Follow [@ionicframework on Twitter](https://twitter.com/ionicframework).
* Subscribe to the [Ionic Newsletter](http://ionicframework.com/subscribe/).
* Have a question that's not a feature request or bug report? [Discuss on the Ionic Forum](http://forum.ionicframework.com/).
* Read our [Blog](http://ionicframework.com/blog/).
* Have a feature request or find a bug? [Submit an issue](https://github.com/driftyco/ionic/issues).

## Authors

**Max Lynch**

+ <https://twitter.com/maxlynch>
+ <https://github.com/mlynch>

**Ben Sperry**

+ <https://twitter.com/benjsperry>
+ <https://github.com/bensperry>

**Adam Bradley**

+ <https://twitter.com/adamdbradley>
+ <https://github.com/adamdbradley>


text:
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/pci.h>
#include <linux/pci_regs.h>
#include <linux/errno.h>
#include <linux/pm.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/delay.h>
#include <linux/pci-aspm.h>
#include "../pci.h"

#ifdef MODULE_PARAM_PREFIX
#undef MODULE_PARAM_PREFIX
#endif
#define MODULE_PARAM_PREFIX "pcie_aspm."

/* Note: those are not register definitions */
#define ASPM_STATE_L0S_UP	(1)	/* Upstream direction L0s state */
#define ASPM_STATE_L0S_DW	(2)	/* Downstream direction L0s state */
#define ASPM_STATE_L1		(4)	/* L1 state */
#define ASPM_STATE_L0S		(ASPM_STATE_L0S_UP | ASPM_STATE_L0S_DW)
#define ASPM_STATE_ALL		(ASPM_STATE_L0S | ASPM_STATE_L1)

struct aspm_latency {
	u32 l0s;			/* L0s latency (nsec) */
	u32 l1;				/* L1 latency (nsec) */
};

struct pcie_link_state {
	struct pci_dev *pdev;		/* Upstream component of the Link */
	struct pcie_link_state *root;	/* pointer to the root port link */
	struct pcie_link_state *parent;	/* pointer to the parent Link state */
	struct list_head sibling;	/* node in link_list */
	struct list_head children;	/* list of child link states */
	struct list_head link;		/* node in parent's children list */

	/* ASPM state */
	u32 aspm_support:3;		/* Supported ASPM state */
	u32 aspm_enabled:3;		/* Enabled ASPM state */
	u32 aspm_capable:3;		/* Capable ASPM state with latency */
	u32 aspm_default:3;		/* Default ASPM state by BIOS */
	u32 aspm_disable:3;		/* Disabled ASPM state */

	/* Clock PM state */
	u32 clkpm_capable:1;		/* Clock PM capable? */
	u32 clkpm_enabled:1;		/* Current Clock PM state */
	u32 clkpm_default:1;		/* Default Clock PM state by BIOS */

	/* Exit latencies */
	struct aspm_latency latency_up;	/* Upstream direction exit latency */
	struct aspm_latency latency_dw;	/* Downstream direction exit latency */
	/*
	 * Endpoint acceptable latencies. A pcie downstream port only
	 * has one slot under it, so at most there are 8 functions.
	 */
	struct aspm_latency acceptable[8];
};

static int aspm_disabled, aspm_force;
static bool aspm_support_enabled = true;
static DEFINE_MUTEX(aspm_lock);
static LIST_HEAD(link_list);

#define POLICY_DEFAULT 0	/* BIOS default setting */
#define POLICY_PERFORMANCE 1	/* high performance */
#define POLICY_POWERSAVE 2	/* high power saving */

#ifdef CONFIG_PCIEASPM_PERFORMANCE
static int aspm_policy = POLICY_PERFORMANCE;
#elif defined CONFIG_PCIEASPM_POWERSAVE
static int aspm_policy = POLICY_POWERSAVE;
#else
static int aspm_policy;
#endif

static const char *policy_str[] = {
	[POLICY_DEFAULT] = "default",
	[POLICY_PERFORMANCE] = "performance",
	[POLICY_POWERSAVE] = "powersave"
};

#define LINK_RETRAIN_TIMEOUT HZ

static int policy_to_aspm_state(struct pcie_link_state *link)
{
	switch (aspm_policy) {
	case POLICY_PERFORMANCE:
		/* Disable ASPM and Clock PM */
		return 0;
	case POLICY_POWERSAVE:
		/* Enable ASPM L0s/L1 */
		return ASPM_STATE_ALL;
	case POLICY_DEFAULT:
		return link->aspm_default;
	}
	return 0;
}

static int policy_to_clkpm_state(struct pcie_link_state *link)
{
	switch (aspm_policy) {
	case POLICY_PERFORMANCE:
		/* Disable ASPM and Clock PM */
		return 0;
	case POLICY_POWERSAVE:
		/* Disable Clock PM */
		return 1;
	case POLICY_DEFAULT:
		return link->clkpm_default;
	}
	return 0;
}

static void pcie_set_clkpm_nocheck(struct pcie_link_state *link, int enable)
{
	struct pci_dev *child;
	struct pci_bus *linkbus = link->pdev->subordinate;
	u32 val = enable ? PCI_EXP_LNKCTL_CLKREQ_EN : 0;

	list_for_each_entry(child, &linkbus->devices, bus_list)
		pcie_capability_clear_and_set_word(child, PCI_EXP_LNKCTL,
						   PCI_EXP_LNKCTL_CLKREQ_EN,
						   val);
	link->clkpm_enabled = !!enable;
}

static void pcie_set_clkpm(struct pcie_link_state *link, int enable)
{
	/* Don't enable Clock PM if the link is not Clock PM capable */
	if (!link->clkpm_capable && enable)
		enable = 0;
	/* Need nothing if the specified equals to current state */
	if (link->clkpm_enabled == enable)
		return;
	pcie_set_clkpm_nocheck(link, enable);
}

static void pcie_clkpm_cap_init(struct pcie_link_state *link, int blacklist)
{
	int capable = 1, enabled = 1;
	u32 reg32;
	u16 reg16;
	struct pci_dev *child;
	struct pci_bus *linkbus = link->pdev->subordinate;

	/* All functions should have the same cap and state, take the worst */
	list_for_each_entry(child, &linkbus->devices, bus_list) {
		pcie_capability_read_dword(child, PCI_EXP_LNKCAP, &reg32);
		if (!(reg32 & PCI_EXP_LNKCAP_CLKPM)) {
			capable = 0;
			enabled = 0;
			break;
		}
		pcie_capability_read_word(child, PCI_EXP_LNKCTL, &reg16);
		if (!(reg16 & PCI_EXP_LNKCTL_CLKREQ_EN))
			enabled = 0;
	}
	link->clkpm_enabled = enabled;
	link->clkpm_default = enabled;
	link->clkpm_capable = (blacklist) ? 0 : capable;
}

/*
 * pcie_aspm_configure_common_clock: check if the 2 ends of a link
 *   could use common clock. If they are, configure them to use the
 *   common clock. That will reduce the ASPM state exit latency.
 */
static void pcie_aspm_configure_common_clock(struct pcie_link_state *link)
{
	int same_clock = 1;
	u16 reg16, parent_reg, child_reg[8];
	unsigned long start_jiffies;
	struct pci_dev *child, *parent = link->pdev;
	struct pci_bus *linkbus = parent->subordinate;
	/*
	 * All functions of a slot should have the same Slot Clock
	 * Configuration, so just check one function
	 */
	child = list_entry(linkbus->devices.next, struct pci_dev, bus_list);
	BUG_ON(!pci_is_pcie(child));

	/* Check downstream component if bit Slot Clock Configuration is 1 */
	pcie_capability_read_word(child, PCI_EXP_LNKSTA, &reg16);
	if (!(reg16 & PCI_EXP_LNKSTA_SLC))
		same_clock = 0;

	/* Check upstream component if bit Slot Clock Configuration is 1 */
	pcie_capability_read_word(parent, PCI_EXP_LNKSTA, &reg16);
	if (!(reg16 & PCI_EXP_LNKSTA_SLC))
		same_clock = 0;

	/* Configure downstream component, all functions */
	list_for_each_entry(child, &linkbus->devices, bus_list) {
		pcie_capability_read_word(child, PCI_EXP_LNKCTL, &reg16);
		child_reg[PCI_FUNC(child->devfn)] = reg16;
		if (same_clock)
			reg16 |= PCI_EXP_LNKCTL_CCC;
		else
			reg16 &= ~PCI_EXP_LNKCTL_CCC;
		pcie_capability_write_word(child, PCI_EXP_LNKCTL, reg16);
	}

	/* Configure upstream component */
	pcie_capability_read_word(parent, PCI_EXP_LNKCTL, &reg16);
	parent_reg = reg16;
	if (same_clock)
		reg16 |= PCI_EXP_LNKCTL_CCC;
	else
		reg16 &= ~PCI_EXP_LNKCTL_CCC;
	pcie_capability_write_word(parent, PCI_EXP_LNKCTL, reg16);

	/* Retrain link */
	reg16 |= PCI_EXP_LNKCTL_RL;
	pcie_capability_write_word(parent, PCI_EXP_LNKCTL, reg16);

	/* Wait for link training end. Break out after waiting for timeout */
	start_jiffies = jiffies;
	for (;;) {
		pcie_capability_read_word(parent, PCI_EXP_LNKSTA, &reg16);
		if (!(reg16 & PCI_EXP_LNKSTA_LT))
			break;
		if (time_after(jiffies, start_jiffies + LINK_RETRAIN_TIMEOUT))
			break;
		msleep(1);
	}
	if (!(reg16 & PCI_EXP_LNKSTA_LT))
		return;

	/* Training failed. Restore common clock configurations */
	dev_err(&parent->dev, "ASPM: Could not configure common clock\n");
	list_for_each_entry(child, &linkbus->devices, bus_list)
		pcie_capability_write_word(child, PCI_EXP_LNKCTL,
					   child_reg[PCI_FUNC(child->devfn)]);
	pcie_capability_write_word(parent, PCI_EXP_LNKCTL, parent_reg);
}

/* Convert L0s latency encoding to ns */
static u32 calc_l0s_latency(u32 encoding)
{
	if (encoding == 0x7)
		return (5 * 1000);	/* > 4us */
	return (64 << encoding);
}

/* Convert L0s acceptable latency encoding to ns */
static u32 calc_l0s_acceptable(u32 encoding)
{
	if (encoding == 0x7)
		return -1U;
	return (64 << encoding);
}

/* Convert L1 latency encoding to ns */
static u32 calc_l1_latency(u32 encoding)
{
	if (encoding == 0x7)
		return (65 * 1000);	/* > 64us */
	return (1000 << encoding);
}

/* Convert L1 acceptable latency encoding to ns */
static u32 calc_l1_acceptable(u32 encoding)
{
	if (encoding == 0x7)
		return -1U;
	return (1000 << encoding);
}

struct aspm_register_info {
	u32 support:2;
	u32 enabled:2;
	u32 latency_encoding_l0s;
	u32 latency_encoding_l1;
};

static void pcie_get_aspm_reg(struct pci_dev *pdev,
			      struct aspm_register_info *info)
{
	u16 reg16;
	u32 reg32;

	pcie_capability_read_dword(pdev, PCI_EXP_LNKCAP, &reg32);
	info->support = (reg32 & PCI_EXP_LNKCAP_ASPMS) >> 10;
	info->latency_encoding_l0s = (reg32 & PCI_EXP_LNKCAP_L0SEL) >> 12;
	info->latency_encoding_l1  = (reg32 & PCI_EXP_LNKCAP_L1EL) >> 15;
	pcie_capability_read_word(pdev, PCI_EXP_LNKCTL, &reg16);
	info->enabled = reg16 & PCI_EXP_LNKCTL_ASPMC;
}

static void pcie_aspm_check_latency(struct pci_dev *endpoint)
{
	u32 latency, l1_switch_latency = 0;
	struct aspm_latency *acceptable;
	struct pcie_link_state *link;

	/* Device not in D0 doesn't need latency check */
	if ((endpoint->current_state != PCI_D0) &&
	    (endpoint->current_state != PCI_UNKNOWN))
		return;

	link = endpoint->bus->self->link_state;
	acceptable = &link->acceptable[PCI_FUNC(endpoint->devfn)];

	while (link) {
		/* Check upstream direction L0s latency */
		if ((link->aspm_capable & ASPM_STATE_L0S_UP) &&
		    (link->latency_up.l0s > acceptable->l0s))
			link->aspm_capable &= ~ASPM_STATE_L0S_UP;

		/* Check downstream direction L0s latency */
		if ((link->aspm_capable & ASPM_STATE_L0S_DW) &&
		    (link->latency_dw.l0s > acceptable->l0s))
			link->aspm_capable &= ~ASPM_STATE_L0S_DW;
		/*
		 * Check L1 latency.
		 * Every switch on the path to root complex need 1
		 * more microsecond for L1. Spec doesn't mention L0s.
		 */
		latency = max_t(u32, link->latency_up.l1, link->latency_dw.l1);
		if ((link->aspm_capable & ASPM_STATE_L1) &&
		    (latency + l1_switch_latency > acceptable->l1))
			link->aspm_capable &= ~ASPM_STATE_L1;
		l1_switch_latency += 1000;

		link = link->parent;
	}
}

static void pcie_aspm_cap_init(struct pcie_link_state *link, int blacklist)
{
	struct pci_dev *child, *parent = link->pdev;
	struct pci_bus *linkbus = parent->subordinate;
	struct aspm_register_info upreg, dwreg;

	if (blacklist) {
		/* Set enabled/disable so that we will disable ASPM later */
		link->aspm_enabled = ASPM_STATE_ALL;
		link->aspm_disable = ASPM_STATE_ALL;
		return;
	}

	/* Configure common clock before checking latencies */
	pcie_aspm_configure_common_clock(link);

	/* Get upstream/downstream components' register state */
	pcie_get_aspm_reg(parent, &upreg);
	child = list_entry(linkbus->devices.next, struct pci_dev, bus_list);
	pcie_get_aspm_reg(child, &dwreg);

	/*
	 * Setup L0s state
	 *
	 * Note that we must not enable L0s in either direction on a
	 * given link unless components on both sides of the link each
	 * support L0s.
	 */
	if (dwreg.support & upreg.support & PCIE_LINK_STATE_L0S)
		link->aspm_support |= ASPM_STATE_L0S;
	if (dwreg.enabled & PCIE_LINK_STATE_L0S)
		link->aspm_enabled |= ASPM_STATE_L0S_UP;
	if (upreg.enabled & PCIE_LINK_STATE_L0S)
		link->aspm_enabled |= ASPM_STATE_L0S_DW;
	link->latency_up.l0s = calc_l0s_latency(upreg.latency_encoding_l0s);
	link->latency_dw.l0s = calc_l0s_latency(dwreg.latency_encoding_l0s);

	/* Setup L1 state */
	if (upreg.support & dwreg.support & PCIE_LINK_STATE_L1)
		link->aspm_support |= ASPM_STATE_L1;
	if (upreg.enabled & dwreg.enabled & PCIE_LINK_STATE_L1)
		link->aspm_enabled |= ASPM_STATE_L1;
	link->latency_up.l1 = calc_l1_latency(upreg.latency_encoding_l1);
	link->latency_dw.l1 = calc_l1_latency(dwreg.latency_encoding_l1);

	/* Save default state */
	link->aspm_default = link->aspm_enabled;

	/* Setup initial capable state. Will be updated later */
	link->aspm_capable = link->aspm_support;
	/*
	 * If the downstream component has pci bridge function, don't
	 * do ASPM for now.
	 */
	list_for_each_entry(child, &linkbus->devices, bus_list) {
		if (pci_pcie_type(child) == PCI_EXP_TYPE_PCI_BRIDGE) {
			link->aspm_disable = ASPM_STATE_ALL;
			break;
		}
	}

	/* Get and check endpoint acceptable latencies */
	list_for_each_entry(child, &linkbus->devices, bus_list) {
		u32 reg32, encoding;
		struct aspm_latency *acceptable =
			&link->acceptable[PCI_FUNC(child->devfn)];

		if (pci_pcie_type(child) != PCI_EXP_TYPE_ENDPOINT &&
		    pci_pcie_type(child) != PCI_EXP_TYPE_LEG_END)
			continue;

		pcie_capability_read_dword(child, PCI_EXP_DEVCAP, &reg32);
		/* Calculate endpoint L0s acceptable latency */
		encoding = (reg32 & PCI_EXP_DEVCAP_L0S) >> 6;
		acceptable->l0s = calc_l0s_acceptable(encoding);
		/* Calculate endpoint L1 acceptable latency */
		encoding = (reg32 & PCI_EXP_DEVCAP_L1) >> 9;
		acceptable->l1 = calc_l1_acceptable(encoding);

		pcie_aspm_check_latency(child);
	}
}

static void pcie_config_aspm_dev(struct pci_dev *pdev, u32 val)
{
	pcie_capability_clear_and_set_word(pdev, PCI_EXP_LNKCTL,
					   PCI_EXP_LNKCTL_ASPMC, val);
}

static void pcie_config_aspm_link(struct pcie_link_state *link, u32 state)
{
	u32 upstream = 0, dwstream = 0;
	struct pci_dev *child, *parent = link->pdev;
	struct pci_bus *linkbus = parent->subordinate;

	/* Nothing to do if the link is already in the requested state */
	state &= (link->aspm_capable & ~link->aspm_disable);
	if (link->aspm_enabled == state)
		return;
	/* Convert ASPM state to upstream/downstream ASPM register state */
	if (state & ASPM_STATE_L0S_UP)
		dwstream |= PCI_EXP_LNKCTL_ASPM_L0S;
	if (state & ASPM_STATE_L0S_DW)
		upstream |= PCI_EXP_LNKCTL_ASPM_L0S;
	if (state & ASPM_STATE_L1) {
		upstream |= PCI_EXP_LNKCTL_ASPM_L1;
		dwstream |= PCI_EXP_LNKCTL_ASPM_L1;
	}
	/*
	 * Spec 2.0 suggests all functions should be configured the
	 * same setting for ASPM. Enabling ASPM L1 should be done in
	 * upstream component first and then downstream, and vice
	 * versa for disabling ASPM L1. Spec doesn't mention L0S.
	 */
	if (state & ASPM_STATE_L1)
		pcie_config_aspm_dev(parent, upstream);
	list_for_each_entry(child, &linkbus->devices, bus_list)
		pcie_config_aspm_dev(child, dwstream);
	if (!(state & ASPM_STATE_L1))
		pcie_config_aspm_dev(parent, upstream);

	link->aspm_enabled = state;
}

static void pcie_config_aspm_path(struct pcie_link_state *link)
{
	while (link) {
		pcie_config_aspm_link(link, policy_to_aspm_state(link));
		link = link->parent;
	}
}

static void free_link_state(struct pcie_link_state *link)
{
	link->pdev->link_state = NULL;
	kfree(link);
}

static int pcie_aspm_sanity_check(struct pci_dev *pdev)
{
	struct pci_dev *child;
	u32 reg32;

	/*
	 * Some functions in a slot might not all be PCIe functions,
	 * very strange. Disable ASPM for the whole slot
	 */
	list_for_each_entry(child, &pdev->subordinate->devices, bus_list) {
		if (!pci_is_pcie(child))
			return -EINVAL;

		/*
		 * If ASPM is disabled then we're not going to change
		 * the BIOS state. It's safe to continue even if it's a
		 * pre-1.1 device
		 */

		if (aspm_disabled)
			continue;

		/*
		 * Disable ASPM for pre-1.1 PCIe device, we follow MS to use
		 * RBER bit to determine if a function is 1.1 version device
		 */
		pcie_capability_read_dword(child, PCI_EXP_DEVCAP, &reg32);
		if (!(reg32 & PCI_EXP_DEVCAP_RBER) && !aspm_force) {
			dev_info(&child->dev, "disabling ASPM on pre-1.1 PCIe device.  You can enable it with 'pcie_aspm=force'\n");
			return -EINVAL;
		}
	}
	return 0;
}

static struct pcie_link_state *alloc_pcie_link_state(struct pci_dev *pdev)
{
	struct pcie_link_state *link;

	link = kzalloc(sizeof(*link), GFP_KERNEL);
	if (!link)
		return NULL;
	INIT_LIST_HEAD(&link->sibling);
	INIT_LIST_HEAD(&link->children);
	INIT_LIST_HEAD(&link->link);
	link->pdev = pdev;
	if (pci_pcie_type(pdev) != PCI_EXP_TYPE_ROOT_PORT) {
		struct pcie_link_state *parent;
		parent = pdev->bus->parent->self->link_state;
		if (!parent) {
			kfree(link);
			return NULL;
		}
		link->parent = parent;
		list_add(&link->link, &parent->children);
	}
	/* Setup a pointer to the root port link */
	if (!link->parent)
		link->root = link;
	else
		link->root = link->parent->root;

	list_add(&link->sibling, &link_list);
	pdev->link_state = link;
	return link;
}

/*
 * pcie_aspm_init_link_state: Initiate PCI express link state.
 * It is called after the pcie and its children devices are scanned.
 * @pdev: the root port or switch downstream port
 */
void pcie_aspm_init_link_state(struct pci_dev *pdev)
{
	struct pcie_link_state *link;
	int blacklist = !!pcie_aspm_sanity_check(pdev);

	if (!aspm_support_enabled)
		return;

	if (pdev->link_state)
		return;

	/*
	 * We allocate pcie_link_state for the component on the upstream
	 * end of a Link, so there's nothing to do unless this device has a
	 * Link on its secondary side.
	 */
	if (!pdev->has_secondary_link)
		return;

	/* VIA has a strange chipset, root port is under a bridge */
	if (pci_pcie_type(pdev) == PCI_EXP_TYPE_ROOT_PORT &&
	    pdev->bus->self)
		return;

	down_read(&pci_bus_sem);
	if (list_empty(&pdev->subordinate->devices))
		goto out;

	mutex_lock(&aspm_lock);
	link = alloc_pcie_link_state(pdev);
	if (!link)
		goto unlock;
	/*
	 * Setup initial ASPM state. Note that we need to configure
	 * upstream links also because capable state of them can be
	 * update through pcie_aspm_cap_init().
	 */
	pcie_aspm_cap_init(link, blacklist);

	/* Setup initial Clock PM state */
	pcie_clkpm_cap_init(link, blacklist);

	/*
	 * At this stage drivers haven't had an opportunity to change the
	 * link policy setting. Enabling ASPM on broken hardware can cripple
	 * it even before the driver has had a chance to disable ASPM, so
	 * default to a safe level right now. If we're enabling ASPM beyond
	 * the BIOS's expectation, we'll do so once pci_enable_device() is
	 * called.
	 */
	if (aspm_policy != POLICY_POWERSAVE) {
		pcie_config_aspm_path(link);
		pcie_set_clkpm(link, policy_to_clkpm_state(link));
	}

unlock:
	mutex_unlock(&aspm_lock);
out:
	up_read(&pci_bus_sem);
}

/* Recheck latencies and update aspm_capable for links under the root */
static void pcie_update_aspm_capable(struct pcie_link_state *root)
{
	struct pcie_link_state *link;
	BUG_ON(root->parent);
	list_for_each_entry(link, &link_list, sibling) {
		if (link->root != root)
			continue;
		link->aspm_capable = link->aspm_support;
	}
	list_for_each_entry(link, &link_list, sibling) {
		struct pci_dev *child;
		struct pci_bus *linkbus = link->pdev->subordinate;
		if (link->root != root)
			continue;
		list_for_each_entry(child, &linkbus->devices, bus_list) {
			if ((pci_pcie_type(child) != PCI_EXP_TYPE_ENDPOINT) &&
			    (pci_pcie_type(child) != PCI_EXP_TYPE_LEG_END))
				continue;
			pcie_aspm_check_latency(child);
		}
	}
}

/* @pdev: the endpoint device */
void pcie_aspm_exit_link_state(struct pci_dev *pdev)
{
	struct pci_dev *parent = pdev->bus->self;
	struct pcie_link_state *link, *root, *parent_link;

	if (!parent || !parent->link_state)
		return;

	down_read(&pci_bus_sem);
	mutex_lock(&aspm_lock);
	/*
	 * All PCIe functions are in one slot, remove one function will remove
	 * the whole slot, so just wait until we are the last function left.
	 */
	if (!list_is_last(&pdev->bus_list, &parent->subordinate->devices))
		goto out;

	link = parent->link_state;
	root = link->root;
	parent_link = link->parent;

	/* All functions are removed, so just disable ASPM for the link */
	pcie_config_aspm_link(link, 0);
	list_del(&link->sibling);
	list_del(&link->link);
	/* Clock PM is for endpoint device */
	free_link_state(link);

	/* Recheck latencies and configure upstream links */
	if (parent_link) {
		pcie_update_aspm_capable(root);
		pcie_config_aspm_path(parent_link);
	}
out:
	mutex_unlock(&aspm_lock);
	up_read(&pci_bus_sem);
}

/* @pdev: the root port or switch downstream port */
void pcie_aspm_pm_state_change(struct pci_dev *pdev)
{
	struct pcie_link_state *link = pdev->link_state;

	if (aspm_disabled || !link)
		return;
	/*
	 * Devices changed PM state, we should recheck if latency
	 * meets all functions' requirement
	 */
	down_read(&pci_bus_sem);
	mutex_lock(&aspm_lock);
	pcie_update_aspm_capable(link->root);
	pcie_config_aspm_path(link);
	mutex_unlock(&aspm_lock);
	up_read(&pci_bus_sem);
}

void pcie_aspm_powersave_config_link(struct pci_dev *pdev)
{
	struct pcie_link_state *link = pdev->link_state;

	if (aspm_disabled || !link)
		return;

	if (aspm_policy != POLICY_POWERSAVE)
		return;

	down_read(&pci_bus_sem);
	mutex_lock(&aspm_lock);
	pcie_config_aspm_path(link);
	pcie_set_clkpm(link, policy_to_clkpm_state(link));
	mutex_unlock(&aspm_lock);
	up_read(&pci_bus_sem);
}

static void __pci_disable_link_state(struct pci_dev *pdev, int state, bool sem)
{
	struct pci_dev *parent = pdev->bus->self;
	struct pcie_link_state *link;

	if (!pci_is_pcie(pdev))
		return;

	if (pdev->has_secondary_link)
		parent = pdev;
	if (!parent || !parent->link_state)
		return;

	/*
	 * A driver requested that ASPM be disabled on this device, but
	 * if we don't have permission to manage ASPM (e.g., on ACPI
	 * systems we have to observe the FADT ACPI_FADT_NO_ASPM bit and
	 * the _OSC method), we can't honor that request.  Windows has
	 * a similar mechanism using "PciASPMOptOut", which is also
	 * ignored in this situation.
	 */
	if (aspm_disabled) {
		dev_warn(&pdev->dev, "can't disable ASPM; OS doesn't have ASPM control\n");
		return;
	}

	if (sem)
		down_read(&pci_bus_sem);
	mutex_lock(&aspm_lock);
	link = parent->link_state;
	if (state & PCIE_LINK_STATE_L0S)
		link->aspm_disable |= ASPM_STATE_L0S;
	if (state & PCIE_LINK_STATE_L1)
		link->aspm_disable |= ASPM_STATE_L1;
	pcie_config_aspm_link(link, policy_to_aspm_state(link));

	if (state & PCIE_LINK_STATE_CLKPM) {
		link->clkpm_capable = 0;
		pcie_set_clkpm(link, 0);
	}
	mutex_unlock(&aspm_lock);
	if (sem)
		up_read(&pci_bus_sem);
}

void pci_disable_link_state_locked(struct pci_dev *pdev, int state)
{
	__pci_disable_link_state(pdev, state, false);
}
EXPORT_SYMBOL(pci_disable_link_state_locked);

/**
 * pci_disable_link_state - Disable device's link state, so the link will
 * never enter specific states.  Note that if the BIOS didn't grant ASPM
 * control to the OS, this does nothing because we can't touch the LNKCTL
 * register.
 *
 * @pdev: PCI device
 * @state: ASPM link state to disable
 */
void pci_disable_link_state(struct pci_dev *pdev, int state)
{
	__pci_disable_link_state(pdev, state, true);
}
EXPORT_SYMBOL(pci_disable_link_state);

static int pcie_aspm_set_policy(const char *val, struct kernel_param *kp)
{
	int i;
	struct pcie_link_state *link;

	if (aspm_disabled)
		return -EPERM;
	for (i = 0; i < ARRAY_SIZE(policy_str); i++)
		if (!strncmp(val, policy_str[i], strlen(policy_str[i])))
			break;
	if (i >= ARRAY_SIZE(policy_str))
		return -EINVAL;
	if (i == aspm_policy)
		return 0;

	down_read(&pci_bus_sem);
	mutex_lock(&aspm_lock);
	aspm_policy = i;
	list_for_each_entry(link, &link_list, sibling) {
		pcie_config_aspm_link(link, policy_to_aspm_state(link));
		pcie_set_clkpm(link, policy_to_clkpm_state(link));
	}
	mutex_unlock(&aspm_lock);
	up_read(&pci_bus_sem);
	return 0;
}

static int pcie_aspm_get_policy(char *buffer, struct kernel_param *kp)
{
	int i, cnt = 0;
	for (i = 0; i < ARRAY_SIZE(policy_str); i++)
		if (i == aspm_policy)
			cnt += sprintf(buffer + cnt, "[%s] ", policy_str[i]);
		else
			cnt += sprintf(buffer + cnt, "%s ", policy_str[i]);
	return cnt;
}

module_param_call(policy, pcie_aspm_set_policy, pcie_aspm_get_policy,
	NULL, 0644);

#ifdef CONFIG_PCIEASPM_DEBUG
static ssize_t link_state_show(struct device *dev,
		struct device_attribute *attr,
		char *buf)
{
	struct pci_dev *pci_device = to_pci_dev(dev);
	struct pcie_link_state *link_state = pci_device->link_state;

	return sprintf(buf, "%d\n", link_state->aspm_enabled);
}

static ssize_t link_state_store(struct device *dev,
		struct device_attribute *attr,
		const char *buf,
		size_t n)
{
	struct pci_dev *pdev = to_pci_dev(dev);
	struct pcie_link_state *link, *root = pdev->link_state->root;
	u32 val, state = 0;

	if (kstrtouint(buf, 10, &val))
		return -EINVAL;

	if (aspm_disabled)
		return -EPERM;
	if (n < 1 || val > 3)
		return -EINVAL;

	/* Convert requested state to ASPM state */
	if (val & PCIE_LINK_STATE_L0S)
		state |= ASPM_STATE_L0S;
	if (val & PCIE_LINK_STATE_L1)
		state |= ASPM_STATE_L1;

	down_read(&pci_bus_sem);
	mutex_lock(&aspm_lock);
	list_for_each_entry(link, &link_list, sibling) {
		if (link->root != root)
			continue;
		pcie_config_aspm_link(link, state);
	}
	mutex_unlock(&aspm_lock);
	up_read(&pci_bus_sem);
	return n;
}

static ssize_t clk_ctl_show(struct device *dev,
		struct device_attribute *attr,
		char *buf)
{
	struct pci_dev *pci_device = to_pci_dev(dev);
	struct pcie_link_state *link_state = pci_device->link_state;

	return sprintf(buf, "%d\n", link_state->clkpm_enabled);
}

static ssize_t clk_ctl_store(struct device *dev,
		struct device_attribute *attr,
		const char *buf,
		size_t n)
{
	struct pci_dev *pdev = to_pci_dev(dev);
	bool state;

	if (strtobool(buf, &state))
		return -EINVAL;

	down_read(&pci_bus_sem);
	mutex_lock(&aspm_lock);
	pcie_set_clkpm_nocheck(pdev->link_state, state);
	mutex_unlock(&aspm_lock);
	up_read(&pci_bus_sem);

	return n;
}

static DEVICE_ATTR(link_state, 0644, link_state_show, link_state_store);
static DEVICE_ATTR(clk_ctl, 0644, clk_ctl_show, clk_ctl_store);

static char power_group[] = "power";
void pcie_aspm_create_sysfs_dev_files(struct pci_dev *pdev)
{
	struct pcie_link_state *link_state = pdev->link_state;

	if (!link_state)
		return;

	if (link_state->aspm_support)
		sysfs_add_file_to_group(&pdev->dev.kobj,
			&dev_attr_link_state.attr, power_group);
	if (link_state->clkpm_capable)
		sysfs_add_file_to_group(&pdev->dev.kobj,
			&dev_attr_clk_ctl.attr, power_group);
}

void pcie_aspm_remove_sysfs_dev_files(struct pci_dev *pdev)
{
	struct pcie_link_state *link_state = pdev->link_state;

	if (!link_state)
		return;

	if (link_state->aspm_support)
		sysfs_remove_file_from_group(&pdev->dev.kobj,
			&dev_attr_link_state.attr, power_group);
	if (link_state->clkpm_capable)
		sysfs_remove_file_from_group(&pdev->dev.kobj,
			&dev_attr_clk_ctl.attr, power_group);
}
#endif

static int __init pcie_aspm_disable(char *str)
{
	if (!strcmp(str, "off")) {
		aspm_policy = POLICY_DEFAULT;
		aspm_disabled = 1;
		aspm_support_enabled = false;
		printk(KERN_INFO "PCIe ASPM is disabled\n");
	} else if (!strcmp(str, "force")) {
		aspm_force = 1;
		printk(KERN_INFO "PCIe ASPM is forcibly enabled\n");
	}
	return 1;
}

__setup("pcie_aspm=", pcie_aspm_disable);

void pcie_no_aspm(void)
{
	/*
	 * Disabling ASPM is intended to prevent the kernel from modifying
	 * existing hardware state, not to clear existing state. To that end:
	 * (a) set policy to POLICY_DEFAULT in order to avoid changing state
	 * (b) prevent userspace from changing policy
	 */
	if (!aspm_force) {
		aspm_policy = POLICY_DEFAULT;
		aspm_disabled = 1;
	}
}

bool pcie_aspm_support_enabled(void)
{
	return aspm_support_enabled;
}
EXPORT_SYMBOL(pcie_aspm_support_enabled);


text:
@interface SettingTableViewController ()

@end

@implementation SettingTableViewController

- (id)initWithStyle:(UITableViewStyle)style {
  self = [super initWithStyle:style];

  if (self) {
    // Custom initialization
  }

  return self;
}

- (void)viewDidLoad {
  [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  if (section == 0) {
    return 1;
  }

  return 3;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
  switch (section) {
    case 0:
      return @"Auto Switch URL Link";

    case 1:
      return @"URL Link";

    default:
      break;
  }
  return @"";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  UITableViewCell *cell;

  switch (indexPath.section) {
    case 0: {
      cell = [tableView dequeueReusableCellWithIdentifier:@"autoswitch" forIndexPath:indexPath];

      NSString *autoSwitchString = [[NSUserDefaults standardUserDefaults] objectForKey:@"Setting_AUTOSWITCH"];
      if (autoSwitchString && [autoSwitchString isEqualToString:@"YES"]) {
        [(UISwitch *)[cell viewWithTag:100] setOn:YES];
      } else {
        [(UISwitch *)[cell viewWithTag:100] setOn:NO];
      }
    }
      break;
    case 1: {
      cell = [tableView dequeueReusableCellWithIdentifier:@"url" forIndexPath:indexPath];

      NSString *labeltext;
      switch (indexPath.row) {
        case 0:
          labeltext = @"Google";
          break;
        case 1:
          labeltext = @"Amazon";
          break;
        case 2:
          labeltext = @"Walmart";
        default:
          break;
      }
      UILabel *label = (UILabel *)[cell viewWithTag:100];
      label.text = labeltext;

      NSString *row = [[NSUserDefaults standardUserDefaults] objectForKey:@"SelectLink"];
      if (row && [row isEqualToString:[NSString stringWithFormat:@"%d", (int)[indexPath row]]]) {
        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
      } else {
        [cell setAccessoryType:UITableViewCellAccessoryNone];
      }
    }
      break;
    default:
      break;
  }

  return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES];

  switch ([indexPath section]) {
    case 1: {
      NSString *url = @"";
      switch ([indexPath row]) {
        case 0:
          url = @"http://www.google.com/m/search?q=@@";
          break;
        case 1:
          url = @"http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=@@";
          break;
        case 2:
          url = @"http://www.walmart.com/search/search-ng.do?search_query=@@&ic=48_0&Find=Find&search_constraint=0";
          break;
        default:
          break;
      }

      [[NSUserDefaults standardUserDefaults] setValue:url forKey:@"WEBLINK"];

      NSString *row = [NSString stringWithFormat:@"%d", (int)[indexPath row]];
      [[NSUserDefaults standardUserDefaults] setValue:row forKey:@"SelectLink"];
      [[NSUserDefaults standardUserDefaults] synchronize];
      [tableView reloadData];
    }
      break;

    default:
      break;
  }
}

#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
}

#pragma mark - private

- (IBAction)saveAutoswitchSetting:(id)sender {
  UISwitch *autoSwitch = (UISwitch *)sender;
  if ([autoSwitch isOn]) {
    [[NSUserDefaults standardUserDefaults] setValue:@"YES" forKey:@"Setting_AUTOSWITCH"];
  } else {
    [[NSUserDefaults standardUserDefaults] setValue:@"NO" forKey:@"Setting_AUTOSWITCH"];
  }

  [[NSUserDefaults standardUserDefaults] synchronize];
}

@end


text:
@implementation AppDelegate

#pragma mark - state

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [Parse enableLocalDatastore];
    [DJContents registerSubclass];
    [Parse setApplicationId:@"9bsJRraxnOoVjbhqsCjA35Gb4OMc29jzwcuZCKRq"
                  clientKey:@"A3ydVgCH2c8QKwLUEmUS36fMprzVingTwDuMVyGb"];
    [PFAnalytics trackAppOpenedWithLaunchOptions:launchOptions];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
}

- (void)applicationWillTerminate:(UIApplication *)application
{
}

@end