linux/drivers/s390/crypto/ap_bus.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0+
   2/*
   3 * Copyright IBM Corp. 2006, 2020
   4 * Author(s): Cornelia Huck <cornelia.huck@de.ibm.com>
   5 *            Martin Schwidefsky <schwidefsky@de.ibm.com>
   6 *            Ralph Wuerthner <rwuerthn@de.ibm.com>
   7 *            Felix Beck <felix.beck@de.ibm.com>
   8 *            Holger Dengler <hd@linux.vnet.ibm.com>
   9 *            Harald Freudenberger <freude@linux.ibm.com>
  10 *
  11 * Adjunct processor bus.
  12 */
  13
  14#define KMSG_COMPONENT "ap"
  15#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
  16
  17#include <linux/kernel_stat.h>
  18#include <linux/moduleparam.h>
  19#include <linux/init.h>
  20#include <linux/delay.h>
  21#include <linux/err.h>
  22#include <linux/freezer.h>
  23#include <linux/interrupt.h>
  24#include <linux/workqueue.h>
  25#include <linux/slab.h>
  26#include <linux/notifier.h>
  27#include <linux/kthread.h>
  28#include <linux/mutex.h>
  29#include <asm/airq.h>
  30#include <linux/atomic.h>
  31#include <asm/isc.h>
  32#include <linux/hrtimer.h>
  33#include <linux/ktime.h>
  34#include <asm/facility.h>
  35#include <linux/crypto.h>
  36#include <linux/mod_devicetable.h>
  37#include <linux/debugfs.h>
  38#include <linux/ctype.h>
  39
  40#include "ap_bus.h"
  41#include "ap_debug.h"
  42
  43/*
  44 * Module parameters; note though this file itself isn't modular.
  45 */
  46int ap_domain_index = -1;       /* Adjunct Processor Domain Index */
  47static DEFINE_SPINLOCK(ap_domain_lock);
  48module_param_named(domain, ap_domain_index, int, 0440);
  49MODULE_PARM_DESC(domain, "domain index for ap devices");
  50EXPORT_SYMBOL(ap_domain_index);
  51
  52static int ap_thread_flag;
  53module_param_named(poll_thread, ap_thread_flag, int, 0440);
  54MODULE_PARM_DESC(poll_thread, "Turn on/off poll thread, default is 0 (off).");
  55
  56static char *apm_str;
  57module_param_named(apmask, apm_str, charp, 0440);
  58MODULE_PARM_DESC(apmask, "AP bus adapter mask.");
  59
  60static char *aqm_str;
  61module_param_named(aqmask, aqm_str, charp, 0440);
  62MODULE_PARM_DESC(aqmask, "AP bus domain mask.");
  63
  64static struct device *ap_root_device;
  65
  66/* Hashtable of all queue devices on the AP bus */
  67DEFINE_HASHTABLE(ap_queues, 8);
  68/* lock used for the ap_queues hashtable */
  69DEFINE_SPINLOCK(ap_queues_lock);
  70
  71/* Default permissions (ioctl, card and domain masking) */
  72struct ap_perms ap_perms;
  73EXPORT_SYMBOL(ap_perms);
  74DEFINE_MUTEX(ap_perms_mutex);
  75EXPORT_SYMBOL(ap_perms_mutex);
  76
  77/* # of bus scans since init */
  78static atomic64_t ap_scan_bus_count;
  79
  80/* completion for initial APQN bindings complete */
  81static DECLARE_COMPLETION(ap_init_apqn_bindings_complete);
  82
  83static struct ap_config_info *ap_qci_info;
  84
  85/*
  86 * AP bus related debug feature things.
  87 */
  88debug_info_t *ap_dbf_info;
  89
  90/*
  91 * Workqueue timer for bus rescan.
  92 */
  93static struct timer_list ap_config_timer;
  94static int ap_config_time = AP_CONFIG_TIME;
  95static void ap_scan_bus(struct work_struct *);
  96static DECLARE_WORK(ap_scan_work, ap_scan_bus);
  97
  98/*
  99 * Tasklet & timer for AP request polling and interrupts
 100 */
 101static void ap_tasklet_fn(unsigned long);
 102static DECLARE_TASKLET_OLD(ap_tasklet, ap_tasklet_fn);
 103static DECLARE_WAIT_QUEUE_HEAD(ap_poll_wait);
 104static struct task_struct *ap_poll_kthread;
 105static DEFINE_MUTEX(ap_poll_thread_mutex);
 106static DEFINE_SPINLOCK(ap_poll_timer_lock);
 107static struct hrtimer ap_poll_timer;
 108/*
 109 * In LPAR poll with 4kHz frequency. Poll every 250000 nanoseconds.
 110 * If z/VM change to 1500000 nanoseconds to adjust to z/VM polling.
 111 */
 112static unsigned long long poll_timeout = 250000;
 113
 114/* Maximum domain id, if not given via qci */
 115static int ap_max_domain_id = 15;
 116/* Maximum adapter id, if not given via qci */
 117static int ap_max_adapter_id = 63;
 118
 119static struct bus_type ap_bus_type;
 120
 121/* Adapter interrupt definitions */
 122static void ap_interrupt_handler(struct airq_struct *airq, bool floating);
 123
 124static bool ap_irq_flag;
 125
 126static struct airq_struct ap_airq = {
 127        .handler = ap_interrupt_handler,
 128        .isc = AP_ISC,
 129};
 130
 131/**
 132 * ap_airq_ptr() - Get the address of the adapter interrupt indicator
 133 *
 134 * Returns the address of the local-summary-indicator of the adapter
 135 * interrupt handler for AP, or NULL if adapter interrupts are not
 136 * available.
 137 */
 138void *ap_airq_ptr(void)
 139{
 140        if (ap_irq_flag)
 141                return ap_airq.lsi_ptr;
 142        return NULL;
 143}
 144
 145/**
 146 * ap_interrupts_available(): Test if AP interrupts are available.
 147 *
 148 * Returns 1 if AP interrupts are available.
 149 */
 150static int ap_interrupts_available(void)
 151{
 152        return test_facility(65);
 153}
 154
 155/**
 156 * ap_qci_available(): Test if AP configuration
 157 * information can be queried via QCI subfunction.
 158 *
 159 * Returns 1 if subfunction PQAP(QCI) is available.
 160 */
 161static int ap_qci_available(void)
 162{
 163        return test_facility(12);
 164}
 165
 166/**
 167 * ap_apft_available(): Test if AP facilities test (APFT)
 168 * facility is available.
 169 *
 170 * Returns 1 if APFT is is available.
 171 */
 172static int ap_apft_available(void)
 173{
 174        return test_facility(15);
 175}
 176
 177/*
 178 * ap_qact_available(): Test if the PQAP(QACT) subfunction is available.
 179 *
 180 * Returns 1 if the QACT subfunction is available.
 181 */
 182static inline int ap_qact_available(void)
 183{
 184        if (ap_qci_info)
 185                return ap_qci_info->qact;
 186        return 0;
 187}
 188
 189/*
 190 * ap_fetch_qci_info(): Fetch cryptographic config info
 191 *
 192 * Returns the ap configuration info fetched via PQAP(QCI).
 193 * On success 0 is returned, on failure a negative errno
 194 * is returned, e.g. if the PQAP(QCI) instruction is not
 195 * available, the return value will be -EOPNOTSUPP.
 196 */
 197static inline int ap_fetch_qci_info(struct ap_config_info *info)
 198{
 199        if (!ap_qci_available())
 200                return -EOPNOTSUPP;
 201        if (!info)
 202                return -EINVAL;
 203        return ap_qci(info);
 204}
 205
 206/**
 207 * ap_init_qci_info(): Allocate and query qci config info.
 208 * Does also update the static variables ap_max_domain_id
 209 * and ap_max_adapter_id if this info is available.
 210
 211 */
 212static void __init ap_init_qci_info(void)
 213{
 214        if (!ap_qci_available()) {
 215                AP_DBF_INFO("%s QCI not supported\n", __func__);
 216                return;
 217        }
 218
 219        ap_qci_info = kzalloc(sizeof(*ap_qci_info), GFP_KERNEL);
 220        if (!ap_qci_info)
 221                return;
 222        if (ap_fetch_qci_info(ap_qci_info) != 0) {
 223                kfree(ap_qci_info);
 224                ap_qci_info = NULL;
 225                return;
 226        }
 227        AP_DBF_INFO("%s successful fetched initial qci info\n", __func__);
 228
 229        if (ap_qci_info->apxa) {
 230                if (ap_qci_info->Na) {
 231                        ap_max_adapter_id = ap_qci_info->Na;
 232                        AP_DBF_INFO("%s new ap_max_adapter_id is %d\n",
 233                                    __func__, ap_max_adapter_id);
 234                }
 235                if (ap_qci_info->Nd) {
 236                        ap_max_domain_id = ap_qci_info->Nd;
 237                        AP_DBF_INFO("%s new ap_max_domain_id is %d\n",
 238                                    __func__, ap_max_domain_id);
 239                }
 240        }
 241}
 242
 243/*
 244 * ap_test_config(): helper function to extract the nrth bit
 245 *                   within the unsigned int array field.
 246 */
 247static inline int ap_test_config(unsigned int *field, unsigned int nr)
 248{
 249        return ap_test_bit((field + (nr >> 5)), (nr & 0x1f));
 250}
 251
 252/*
 253 * ap_test_config_card_id(): Test, whether an AP card ID is configured.
 254 *
 255 * Returns 0 if the card is not configured
 256 *         1 if the card is configured or
 257 *           if the configuration information is not available
 258 */
 259static inline int ap_test_config_card_id(unsigned int id)
 260{
 261        if (id > ap_max_adapter_id)
 262                return 0;
 263        if (ap_qci_info)
 264                return ap_test_config(ap_qci_info->apm, id);
 265        return 1;
 266}
 267
 268/*
 269 * ap_test_config_usage_domain(): Test, whether an AP usage domain
 270 * is configured.
 271 *
 272 * Returns 0 if the usage domain is not configured
 273 *         1 if the usage domain is configured or
 274 *           if the configuration information is not available
 275 */
 276int ap_test_config_usage_domain(unsigned int domain)
 277{
 278        if (domain > ap_max_domain_id)
 279                return 0;
 280        if (ap_qci_info)
 281                return ap_test_config(ap_qci_info->aqm, domain);
 282        return 1;
 283}
 284EXPORT_SYMBOL(ap_test_config_usage_domain);
 285
 286/*
 287 * ap_test_config_ctrl_domain(): Test, whether an AP control domain
 288 * is configured.
 289 * @domain AP control domain ID
 290 *
 291 * Returns 1 if the control domain is configured
 292 *         0 in all other cases
 293 */
 294int ap_test_config_ctrl_domain(unsigned int domain)
 295{
 296        if (!ap_qci_info || domain > ap_max_domain_id)
 297                return 0;
 298        return ap_test_config(ap_qci_info->adm, domain);
 299}
 300EXPORT_SYMBOL(ap_test_config_ctrl_domain);
 301
 302/*
 303 * ap_queue_info(): Check and get AP queue info.
 304 * Returns true if TAPQ succeeded and the info is filled or
 305 * false otherwise.
 306 */
 307static bool ap_queue_info(ap_qid_t qid, int *q_type,
 308                          unsigned int *q_fac, int *q_depth, bool *q_decfg)
 309{
 310        struct ap_queue_status status;
 311        unsigned long info = 0;
 312
 313        /* make sure we don't run into a specifiation exception */
 314        if (AP_QID_CARD(qid) > ap_max_adapter_id ||
 315            AP_QID_QUEUE(qid) > ap_max_domain_id)
 316                return false;
 317
 318        /* call TAPQ on this APQN */
 319        status = ap_test_queue(qid, ap_apft_available(), &info);
 320        switch (status.response_code) {
 321        case AP_RESPONSE_NORMAL:
 322        case AP_RESPONSE_RESET_IN_PROGRESS:
 323        case AP_RESPONSE_DECONFIGURED:
 324        case AP_RESPONSE_CHECKSTOPPED:
 325        case AP_RESPONSE_BUSY:
 326                /*
 327                 * According to the architecture in all these cases the
 328                 * info should be filled. All bits 0 is not possible as
 329                 * there is at least one of the mode bits set.
 330                 */
 331                if (WARN_ON_ONCE(!info))
 332                        return false;
 333                *q_type = (int)((info >> 24) & 0xff);
 334                *q_fac = (unsigned int)(info >> 32);
 335                *q_depth = (int)(info & 0xff);
 336                *q_decfg = status.response_code == AP_RESPONSE_DECONFIGURED;
 337                switch (*q_type) {
 338                        /* For CEX2 and CEX3 the available functions
 339                         * are not reflected by the facilities bits.
 340                         * Instead it is coded into the type. So here
 341                         * modify the function bits based on the type.
 342                         */
 343                case AP_DEVICE_TYPE_CEX2A:
 344                case AP_DEVICE_TYPE_CEX3A:
 345                        *q_fac |= 0x08000000;
 346                        break;
 347                case AP_DEVICE_TYPE_CEX2C:
 348                case AP_DEVICE_TYPE_CEX3C:
 349                        *q_fac |= 0x10000000;
 350                        break;
 351                default:
 352                        break;
 353                }
 354                return true;
 355        default:
 356                /*
 357                 * A response code which indicates, there is no info available.
 358                 */
 359                return false;
 360        }
 361}
 362
 363void ap_wait(enum ap_sm_wait wait)
 364{
 365        ktime_t hr_time;
 366
 367        switch (wait) {
 368        case AP_SM_WAIT_AGAIN:
 369        case AP_SM_WAIT_INTERRUPT:
 370                if (ap_irq_flag)
 371                        break;
 372                if (ap_poll_kthread) {
 373                        wake_up(&ap_poll_wait);
 374                        break;
 375                }
 376                fallthrough;
 377        case AP_SM_WAIT_TIMEOUT:
 378                spin_lock_bh(&ap_poll_timer_lock);
 379                if (!hrtimer_is_queued(&ap_poll_timer)) {
 380                        hr_time = poll_timeout;
 381                        hrtimer_forward_now(&ap_poll_timer, hr_time);
 382                        hrtimer_restart(&ap_poll_timer);
 383                }
 384                spin_unlock_bh(&ap_poll_timer_lock);
 385                break;
 386        case AP_SM_WAIT_NONE:
 387        default:
 388                break;
 389        }
 390}
 391
 392/**
 393 * ap_request_timeout(): Handling of request timeouts
 394 * @t: timer making this callback
 395 *
 396 * Handles request timeouts.
 397 */
 398void ap_request_timeout(struct timer_list *t)
 399{
 400        struct ap_queue *aq = from_timer(aq, t, timeout);
 401
 402        spin_lock_bh(&aq->lock);
 403        ap_wait(ap_sm_event(aq, AP_SM_EVENT_TIMEOUT));
 404        spin_unlock_bh(&aq->lock);
 405}
 406
 407/**
 408 * ap_poll_timeout(): AP receive polling for finished AP requests.
 409 * @unused: Unused pointer.
 410 *
 411 * Schedules the AP tasklet using a high resolution timer.
 412 */
 413static enum hrtimer_restart ap_poll_timeout(struct hrtimer *unused)
 414{
 415        tasklet_schedule(&ap_tasklet);
 416        return HRTIMER_NORESTART;
 417}
 418
 419/**
 420 * ap_interrupt_handler() - Schedule ap_tasklet on interrupt
 421 * @airq: pointer to adapter interrupt descriptor
 422 */
 423static void ap_interrupt_handler(struct airq_struct *airq, bool floating)
 424{
 425        inc_irq_stat(IRQIO_APB);
 426        tasklet_schedule(&ap_tasklet);
 427}
 428
 429/**
 430 * ap_tasklet_fn(): Tasklet to poll all AP devices.
 431 * @dummy: Unused variable
 432 *
 433 * Poll all AP devices on the bus.
 434 */
 435static void ap_tasklet_fn(unsigned long dummy)
 436{
 437        int bkt;
 438        struct ap_queue *aq;
 439        enum ap_sm_wait wait = AP_SM_WAIT_NONE;
 440
 441        /* Reset the indicator if interrupts are used. Thus new interrupts can
 442         * be received. Doing it in the beginning of the tasklet is therefor
 443         * important that no requests on any AP get lost.
 444         */
 445        if (ap_irq_flag)
 446                xchg(ap_airq.lsi_ptr, 0);
 447
 448        spin_lock_bh(&ap_queues_lock);
 449        hash_for_each(ap_queues, bkt, aq, hnode) {
 450                spin_lock_bh(&aq->lock);
 451                wait = min(wait, ap_sm_event_loop(aq, AP_SM_EVENT_POLL));
 452                spin_unlock_bh(&aq->lock);
 453        }
 454        spin_unlock_bh(&ap_queues_lock);
 455
 456        ap_wait(wait);
 457}
 458
 459static int ap_pending_requests(void)
 460{
 461        int bkt;
 462        struct ap_queue *aq;
 463
 464        spin_lock_bh(&ap_queues_lock);
 465        hash_for_each(ap_queues, bkt, aq, hnode) {
 466                if (aq->queue_count == 0)
 467                        continue;
 468                spin_unlock_bh(&ap_queues_lock);
 469                return 1;
 470        }
 471        spin_unlock_bh(&ap_queues_lock);
 472        return 0;
 473}
 474
 475/**
 476 * ap_poll_thread(): Thread that polls for finished requests.
 477 * @data: Unused pointer
 478 *
 479 * AP bus poll thread. The purpose of this thread is to poll for
 480 * finished requests in a loop if there is a "free" cpu - that is
 481 * a cpu that doesn't have anything better to do. The polling stops
 482 * as soon as there is another task or if all messages have been
 483 * delivered.
 484 */
 485static int ap_poll_thread(void *data)
 486{
 487        DECLARE_WAITQUEUE(wait, current);
 488
 489        set_user_nice(current, MAX_NICE);
 490        set_freezable();
 491        while (!kthread_should_stop()) {
 492                add_wait_queue(&ap_poll_wait, &wait);
 493                set_current_state(TASK_INTERRUPTIBLE);
 494                if (!ap_pending_requests()) {
 495                        schedule();
 496                        try_to_freeze();
 497                }
 498                set_current_state(TASK_RUNNING);
 499                remove_wait_queue(&ap_poll_wait, &wait);
 500                if (need_resched()) {
 501                        schedule();
 502                        try_to_freeze();
 503                        continue;
 504                }
 505                ap_tasklet_fn(0);
 506        }
 507
 508        return 0;
 509}
 510
 511static int ap_poll_thread_start(void)
 512{
 513        int rc;
 514
 515        if (ap_irq_flag || ap_poll_kthread)
 516                return 0;
 517        mutex_lock(&ap_poll_thread_mutex);
 518        ap_poll_kthread = kthread_run(ap_poll_thread, NULL, "appoll");
 519        rc = PTR_ERR_OR_ZERO(ap_poll_kthread);
 520        if (rc)
 521                ap_poll_kthread = NULL;
 522        mutex_unlock(&ap_poll_thread_mutex);
 523        return rc;
 524}
 525
 526static void ap_poll_thread_stop(void)
 527{
 528        if (!ap_poll_kthread)
 529                return;
 530        mutex_lock(&ap_poll_thread_mutex);
 531        kthread_stop(ap_poll_kthread);
 532        ap_poll_kthread = NULL;
 533        mutex_unlock(&ap_poll_thread_mutex);
 534}
 535
 536#define is_card_dev(x) ((x)->parent == ap_root_device)
 537#define is_queue_dev(x) ((x)->parent != ap_root_device)
 538
 539/**
 540 * ap_bus_match()
 541 * @dev: Pointer to device
 542 * @drv: Pointer to device_driver
 543 *
 544 * AP bus driver registration/unregistration.
 545 */
 546static int ap_bus_match(struct device *dev, struct device_driver *drv)
 547{
 548        struct ap_driver *ap_drv = to_ap_drv(drv);
 549        struct ap_device_id *id;
 550
 551        /*
 552         * Compare device type of the device with the list of
 553         * supported types of the device_driver.
 554         */
 555        for (id = ap_drv->ids; id->match_flags; id++) {
 556                if (is_card_dev(dev) &&
 557                    id->match_flags & AP_DEVICE_ID_MATCH_CARD_TYPE &&
 558                    id->dev_type == to_ap_dev(dev)->device_type)
 559                        return 1;
 560                if (is_queue_dev(dev) &&
 561                    id->match_flags & AP_DEVICE_ID_MATCH_QUEUE_TYPE &&
 562                    id->dev_type == to_ap_dev(dev)->device_type)
 563                        return 1;
 564        }
 565        return 0;
 566}
 567
 568/**
 569 * ap_uevent(): Uevent function for AP devices.
 570 * @dev: Pointer to device
 571 * @env: Pointer to kobj_uevent_env
 572 *
 573 * It sets up a single environment variable DEV_TYPE which contains the
 574 * hardware device type.
 575 */
 576static int ap_uevent(struct device *dev, struct kobj_uevent_env *env)
 577{
 578        int rc;
 579        struct ap_device *ap_dev = to_ap_dev(dev);
 580
 581        /* Uevents from ap bus core don't need extensions to the env */
 582        if (dev == ap_root_device)
 583                return 0;
 584
 585        /* Set up DEV_TYPE environment variable. */
 586        rc = add_uevent_var(env, "DEV_TYPE=%04X", ap_dev->device_type);
 587        if (rc)
 588                return rc;
 589
 590        /* Add MODALIAS= */
 591        rc = add_uevent_var(env, "MODALIAS=ap:t%02X", ap_dev->device_type);
 592        if (rc)
 593                return rc;
 594
 595        return 0;
 596}
 597
 598static void ap_send_init_scan_done_uevent(void)
 599{
 600        char *envp[] = { "INITSCAN=done", NULL };
 601
 602        kobject_uevent_env(&ap_root_device->kobj, KOBJ_CHANGE, envp);
 603}
 604
 605static void ap_send_bindings_complete_uevent(void)
 606{
 607        char *envp[] = { "BINDINGS=complete", NULL };
 608
 609        kobject_uevent_env(&ap_root_device->kobj, KOBJ_CHANGE, envp);
 610}
 611
 612/*
 613 * calc # of bound APQNs
 614 */
 615
 616struct __ap_calc_ctrs {
 617        unsigned int apqns;
 618        unsigned int bound;
 619};
 620
 621static int __ap_calc_helper(struct device *dev, void *arg)
 622{
 623        struct __ap_calc_ctrs *pctrs = (struct __ap_calc_ctrs *) arg;
 624
 625        if (is_queue_dev(dev)) {
 626                pctrs->apqns++;
 627                if ((to_ap_dev(dev))->drv)
 628                        pctrs->bound++;
 629        }
 630
 631        return 0;
 632}
 633
 634static void ap_calc_bound_apqns(unsigned int *apqns, unsigned int *bound)
 635{
 636        struct __ap_calc_ctrs ctrs;
 637
 638        memset(&ctrs, 0, sizeof(ctrs));
 639        bus_for_each_dev(&ap_bus_type, NULL, (void *) &ctrs, __ap_calc_helper);
 640
 641        *apqns = ctrs.apqns;
 642        *bound = ctrs.bound;
 643}
 644
 645/*
 646 * After initial ap bus scan do check if all existing APQNs are
 647 * bound to device drivers.
 648 */
 649static void ap_check_bindings_complete(void)
 650{
 651        unsigned int apqns, bound;
 652
 653        if (atomic64_read(&ap_scan_bus_count) >= 1) {
 654                ap_calc_bound_apqns(&apqns, &bound);
 655                if (bound == apqns) {
 656                        if (!completion_done(&ap_init_apqn_bindings_complete)) {
 657                                complete_all(&ap_init_apqn_bindings_complete);
 658                                AP_DBF(DBF_INFO, "%s complete\n", __func__);
 659                        }
 660                        ap_send_bindings_complete_uevent();
 661                }
 662        }
 663}
 664
 665/*
 666 * Interface to wait for the AP bus to have done one initial ap bus
 667 * scan and all detected APQNs have been bound to device drivers.
 668 * If these both conditions are not fulfilled, this function blocks
 669 * on a condition with wait_for_completion_interruptible_timeout().
 670 * If these both conditions are fulfilled (before the timeout hits)
 671 * the return value is 0. If the timeout (in jiffies) hits instead
 672 * -ETIME is returned. On failures negative return values are
 673 * returned to the caller.
 674 */
 675int ap_wait_init_apqn_bindings_complete(unsigned long timeout)
 676{
 677        long l;
 678
 679        if (completion_done(&ap_init_apqn_bindings_complete))
 680                return 0;
 681
 682        if (timeout)
 683                l = wait_for_completion_interruptible_timeout(
 684                        &ap_init_apqn_bindings_complete, timeout);
 685        else
 686                l = wait_for_completion_interruptible(
 687                        &ap_init_apqn_bindings_complete);
 688        if (l < 0)
 689                return l == -ERESTARTSYS ? -EINTR : l;
 690        else if (l == 0 && timeout)
 691                return -ETIME;
 692
 693        return 0;
 694}
 695EXPORT_SYMBOL(ap_wait_init_apqn_bindings_complete);
 696
 697static int __ap_queue_devices_with_id_unregister(struct device *dev, void *data)
 698{
 699        if (is_queue_dev(dev) &&
 700            AP_QID_CARD(to_ap_queue(dev)->qid) == (int)(long) data)
 701                device_unregister(dev);
 702        return 0;
 703}
 704
 705static int __ap_revise_reserved(struct device *dev, void *dummy)
 706{
 707        int rc, card, queue, devres, drvres;
 708
 709        if (is_queue_dev(dev)) {
 710                card = AP_QID_CARD(to_ap_queue(dev)->qid);
 711                queue = AP_QID_QUEUE(to_ap_queue(dev)->qid);
 712                mutex_lock(&ap_perms_mutex);
 713                devres = test_bit_inv(card, ap_perms.apm)
 714                        && test_bit_inv(queue, ap_perms.aqm);
 715                mutex_unlock(&ap_perms_mutex);
 716                drvres = to_ap_drv(dev->driver)->flags
 717                        & AP_DRIVER_FLAG_DEFAULT;
 718                if (!!devres != !!drvres) {
 719                        AP_DBF_DBG("reprobing queue=%02x.%04x\n",
 720                                   card, queue);
 721                        rc = device_reprobe(dev);
 722                }
 723        }
 724
 725        return 0;
 726}
 727
 728static void ap_bus_revise_bindings(void)
 729{
 730        bus_for_each_dev(&ap_bus_type, NULL, NULL, __ap_revise_reserved);
 731}
 732
 733int ap_owned_by_def_drv(int card, int queue)
 734{
 735        int rc = 0;
 736
 737        if (card < 0 || card >= AP_DEVICES || queue < 0 || queue >= AP_DOMAINS)
 738                return -EINVAL;
 739
 740        mutex_lock(&ap_perms_mutex);
 741
 742        if (test_bit_inv(card, ap_perms.apm)
 743            && test_bit_inv(queue, ap_perms.aqm))
 744                rc = 1;
 745
 746        mutex_unlock(&ap_perms_mutex);
 747
 748        return rc;
 749}
 750EXPORT_SYMBOL(ap_owned_by_def_drv);
 751
 752int ap_apqn_in_matrix_owned_by_def_drv(unsigned long *apm,
 753                                       unsigned long *aqm)
 754{
 755        int card, queue, rc = 0;
 756
 757        mutex_lock(&ap_perms_mutex);
 758
 759        for (card = 0; !rc && card < AP_DEVICES; card++)
 760                if (test_bit_inv(card, apm) &&
 761                    test_bit_inv(card, ap_perms.apm))
 762                        for (queue = 0; !rc && queue < AP_DOMAINS; queue++)
 763                                if (test_bit_inv(queue, aqm) &&
 764                                    test_bit_inv(queue, ap_perms.aqm))
 765                                        rc = 1;
 766
 767        mutex_unlock(&ap_perms_mutex);
 768
 769        return rc;
 770}
 771EXPORT_SYMBOL(ap_apqn_in_matrix_owned_by_def_drv);
 772
 773static int ap_device_probe(struct device *dev)
 774{
 775        struct ap_device *ap_dev = to_ap_dev(dev);
 776        struct ap_driver *ap_drv = to_ap_drv(dev->driver);
 777        int card, queue, devres, drvres, rc = -ENODEV;
 778
 779        if (!get_device(dev))
 780                return rc;
 781
 782        if (is_queue_dev(dev)) {
 783                /*
 784                 * If the apqn is marked as reserved/used by ap bus and
 785                 * default drivers, only probe with drivers with the default
 786                 * flag set. If it is not marked, only probe with drivers
 787                 * with the default flag not set.
 788                 */
 789                card = AP_QID_CARD(to_ap_queue(dev)->qid);
 790                queue = AP_QID_QUEUE(to_ap_queue(dev)->qid);
 791                mutex_lock(&ap_perms_mutex);
 792                devres = test_bit_inv(card, ap_perms.apm)
 793                        && test_bit_inv(queue, ap_perms.aqm);
 794                mutex_unlock(&ap_perms_mutex);
 795                drvres = ap_drv->flags & AP_DRIVER_FLAG_DEFAULT;
 796                if (!!devres != !!drvres)
 797                        goto out;
 798        }
 799
 800        /* Add queue/card to list of active queues/cards */
 801        spin_lock_bh(&ap_queues_lock);
 802        if (is_queue_dev(dev))
 803                hash_add(ap_queues, &to_ap_queue(dev)->hnode,
 804                         to_ap_queue(dev)->qid);
 805        spin_unlock_bh(&ap_queues_lock);
 806
 807        ap_dev->drv = ap_drv;
 808        rc = ap_drv->probe ? ap_drv->probe(ap_dev) : -ENODEV;
 809
 810        if (rc) {
 811                spin_lock_bh(&ap_queues_lock);
 812                if (is_queue_dev(dev))
 813                        hash_del(&to_ap_queue(dev)->hnode);
 814                spin_unlock_bh(&ap_queues_lock);
 815                ap_dev->drv = NULL;
 816        } else
 817                ap_check_bindings_complete();
 818
 819out:
 820        if (rc)
 821                put_device(dev);
 822        return rc;
 823}
 824
 825static int ap_device_remove(struct device *dev)
 826{
 827        struct ap_device *ap_dev = to_ap_dev(dev);
 828        struct ap_driver *ap_drv = ap_dev->drv;
 829
 830        /* prepare ap queue device removal */
 831        if (is_queue_dev(dev))
 832                ap_queue_prepare_remove(to_ap_queue(dev));
 833
 834        /* driver's chance to clean up gracefully */
 835        if (ap_drv->remove)
 836                ap_drv->remove(ap_dev);
 837
 838        /* now do the ap queue device remove */
 839        if (is_queue_dev(dev))
 840                ap_queue_remove(to_ap_queue(dev));
 841
 842        /* Remove queue/card from list of active queues/cards */
 843        spin_lock_bh(&ap_queues_lock);
 844        if (is_queue_dev(dev))
 845                hash_del(&to_ap_queue(dev)->hnode);
 846        spin_unlock_bh(&ap_queues_lock);
 847        ap_dev->drv = NULL;
 848
 849        put_device(dev);
 850
 851        return 0;
 852}
 853
 854struct ap_queue *ap_get_qdev(ap_qid_t qid)
 855{
 856        int bkt;
 857        struct ap_queue *aq;
 858
 859        spin_lock_bh(&ap_queues_lock);
 860        hash_for_each(ap_queues, bkt, aq, hnode) {
 861                if (aq->qid == qid) {
 862                        get_device(&aq->ap_dev.device);
 863                        spin_unlock_bh(&ap_queues_lock);
 864                        return aq;
 865                }
 866        }
 867        spin_unlock_bh(&ap_queues_lock);
 868
 869        return NULL;
 870}
 871EXPORT_SYMBOL(ap_get_qdev);
 872
 873int ap_driver_register(struct ap_driver *ap_drv, struct module *owner,
 874                       char *name)
 875{
 876        struct device_driver *drv = &ap_drv->driver;
 877
 878        drv->bus = &ap_bus_type;
 879        drv->probe = ap_device_probe;
 880        drv->remove = ap_device_remove;
 881        drv->owner = owner;
 882        drv->name = name;
 883        return driver_register(drv);
 884}
 885EXPORT_SYMBOL(ap_driver_register);
 886
 887void ap_driver_unregister(struct ap_driver *ap_drv)
 888{
 889        driver_unregister(&ap_drv->driver);
 890}
 891EXPORT_SYMBOL(ap_driver_unregister);
 892
 893void ap_bus_force_rescan(void)
 894{
 895        /* processing a asynchronous bus rescan */
 896        del_timer(&ap_config_timer);
 897        queue_work(system_long_wq, &ap_scan_work);
 898        flush_work(&ap_scan_work);
 899}
 900EXPORT_SYMBOL(ap_bus_force_rescan);
 901
 902/*
 903* A config change has happened, force an ap bus rescan.
 904*/
 905void ap_bus_cfg_chg(void)
 906{
 907        AP_DBF_DBG("%s config change, forcing bus rescan\n", __func__);
 908
 909        ap_bus_force_rescan();
 910}
 911
 912/*
 913 * hex2bitmap() - parse hex mask string and set bitmap.
 914 * Valid strings are "0x012345678" with at least one valid hex number.
 915 * Rest of the bitmap to the right is padded with 0. No spaces allowed
 916 * within the string, the leading 0x may be omitted.
 917 * Returns the bitmask with exactly the bits set as given by the hex
 918 * string (both in big endian order).
 919 */
 920static int hex2bitmap(const char *str, unsigned long *bitmap, int bits)
 921{
 922        int i, n, b;
 923
 924        /* bits needs to be a multiple of 8 */
 925        if (bits & 0x07)
 926                return -EINVAL;
 927
 928        if (str[0] == '0' && str[1] == 'x')
 929                str++;
 930        if (*str == 'x')
 931                str++;
 932
 933        for (i = 0; isxdigit(*str) && i < bits; str++) {
 934                b = hex_to_bin(*str);
 935                for (n = 0; n < 4; n++)
 936                        if (b & (0x08 >> n))
 937                                set_bit_inv(i + n, bitmap);
 938                i += 4;
 939        }
 940
 941        if (*str == '\n')
 942                str++;
 943        if (*str)
 944                return -EINVAL;
 945        return 0;
 946}
 947
 948/*
 949 * modify_bitmap() - parse bitmask argument and modify an existing
 950 * bit mask accordingly. A concatenation (done with ',') of these
 951 * terms is recognized:
 952 *   +<bitnr>[-<bitnr>] or -<bitnr>[-<bitnr>]
 953 * <bitnr> may be any valid number (hex, decimal or octal) in the range
 954 * 0...bits-1; the leading + or - is required. Here are some examples:
 955 *   +0-15,+32,-128,-0xFF
 956 *   -0-255,+1-16,+0x128
 957 *   +1,+2,+3,+4,-5,-7-10
 958 * Returns the new bitmap after all changes have been applied. Every
 959 * positive value in the string will set a bit and every negative value
 960 * in the string will clear a bit. As a bit may be touched more than once,
 961 * the last 'operation' wins:
 962 * +0-255,-128 = first bits 0-255 will be set, then bit 128 will be
 963 * cleared again. All other bits are unmodified.
 964 */
 965static int modify_bitmap(const char *str, unsigned long *bitmap, int bits)
 966{
 967        int a, i, z;
 968        char *np, sign;
 969
 970        /* bits needs to be a multiple of 8 */
 971        if (bits & 0x07)
 972                return -EINVAL;
 973
 974        while (*str) {
 975                sign = *str++;
 976                if (sign != '+' && sign != '-')
 977                        return -EINVAL;
 978                a = z = simple_strtoul(str, &np, 0);
 979                if (str == np || a >= bits)
 980                        return -EINVAL;
 981                str = np;
 982                if (*str == '-') {
 983                        z = simple_strtoul(++str, &np, 0);
 984                        if (str == np || a > z || z >= bits)
 985                                return -EINVAL;
 986                        str = np;
 987                }
 988                for (i = a; i <= z; i++)
 989                        if (sign == '+')
 990                                set_bit_inv(i, bitmap);
 991                        else
 992                                clear_bit_inv(i, bitmap);
 993                while (*str == ',' || *str == '\n')
 994                        str++;
 995        }
 996
 997        return 0;
 998}
 999
1000int ap_parse_mask_str(const char *str,
1001                      unsigned long *bitmap, int bits,
1002                      struct mutex *lock)
1003{
1004        unsigned long *newmap, size;
1005        int rc;
1006
1007        /* bits needs to be a multiple of 8 */
1008        if (bits & 0x07)
1009                return -EINVAL;
1010
1011        size = BITS_TO_LONGS(bits)*sizeof(unsigned long);
1012        newmap = kmalloc(size, GFP_KERNEL);
1013        if (!newmap)
1014                return -ENOMEM;
1015        if (mutex_lock_interruptible(lock)) {
1016                kfree(newmap);
1017                return -ERESTARTSYS;
1018        }
1019
1020        if (*str == '+' || *str == '-') {
1021                memcpy(newmap, bitmap, size);
1022                rc = modify_bitmap(str, newmap, bits);
1023        } else {
1024                memset(newmap, 0, size);
1025                rc = hex2bitmap(str, newmap, bits);
1026        }
1027        if (rc == 0)
1028                memcpy(bitmap, newmap, size);
1029        mutex_unlock(lock);
1030        kfree(newmap);
1031        return rc;
1032}
1033EXPORT_SYMBOL(ap_parse_mask_str);
1034
1035/*
1036 * AP bus attributes.
1037 */
1038
1039static ssize_t ap_domain_show(struct bus_type *bus, char *buf)
1040{
1041        return scnprintf(buf, PAGE_SIZE, "%d\n", ap_domain_index);
1042}
1043
1044static ssize_t ap_domain_store(struct bus_type *bus,
1045                               const char *buf, size_t count)
1046{
1047        int domain;
1048
1049        if (sscanf(buf, "%i\n", &domain) != 1 ||
1050            domain < 0 || domain > ap_max_domain_id ||
1051            !test_bit_inv(domain, ap_perms.aqm))
1052                return -EINVAL;
1053
1054        spin_lock_bh(&ap_domain_lock);
1055        ap_domain_index = domain;
1056        spin_unlock_bh(&ap_domain_lock);
1057
1058        AP_DBF_INFO("stored new default domain=%d\n", domain);
1059
1060        return count;
1061}
1062
1063static BUS_ATTR_RW(ap_domain);
1064
1065static ssize_t ap_control_domain_mask_show(struct bus_type *bus, char *buf)
1066{
1067        if (!ap_qci_info)       /* QCI not supported */
1068                return scnprintf(buf, PAGE_SIZE, "not supported\n");
1069
1070        return scnprintf(buf, PAGE_SIZE,
1071                         "0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
1072                         ap_qci_info->adm[0], ap_qci_info->adm[1],
1073                         ap_qci_info->adm[2], ap_qci_info->adm[3],
1074                         ap_qci_info->adm[4], ap_qci_info->adm[5],
1075                         ap_qci_info->adm[6], ap_qci_info->adm[7]);
1076}
1077
1078static BUS_ATTR_RO(ap_control_domain_mask);
1079
1080static ssize_t ap_usage_domain_mask_show(struct bus_type *bus, char *buf)
1081{
1082        if (!ap_qci_info)       /* QCI not supported */
1083                return scnprintf(buf, PAGE_SIZE, "not supported\n");
1084
1085        return scnprintf(buf, PAGE_SIZE,
1086                         "0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
1087                         ap_qci_info->aqm[0], ap_qci_info->aqm[1],
1088                         ap_qci_info->aqm[2], ap_qci_info->aqm[3],
1089                         ap_qci_info->aqm[4], ap_qci_info->aqm[5],
1090                         ap_qci_info->aqm[6], ap_qci_info->aqm[7]);
1091}
1092
1093static BUS_ATTR_RO(ap_usage_domain_mask);
1094
1095static ssize_t ap_adapter_mask_show(struct bus_type *bus, char *buf)
1096{
1097        if (!ap_qci_info)       /* QCI not supported */
1098                return scnprintf(buf, PAGE_SIZE, "not supported\n");
1099
1100        return scnprintf(buf, PAGE_SIZE,
1101                         "0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
1102                         ap_qci_info->apm[0], ap_qci_info->apm[1],
1103                         ap_qci_info->apm[2], ap_qci_info->apm[3],
1104                         ap_qci_info->apm[4], ap_qci_info->apm[5],
1105                         ap_qci_info->apm[6], ap_qci_info->apm[7]);
1106}
1107
1108static BUS_ATTR_RO(ap_adapter_mask);
1109
1110static ssize_t ap_interrupts_show(struct bus_type *bus, char *buf)
1111{
1112        return scnprintf(buf, PAGE_SIZE, "%d\n",
1113                         ap_irq_flag ? 1 : 0);
1114}
1115
1116static BUS_ATTR_RO(ap_interrupts);
1117
1118static ssize_t config_time_show(struct bus_type *bus, char *buf)
1119{
1120        return scnprintf(buf, PAGE_SIZE, "%d\n", ap_config_time);
1121}
1122
1123static ssize_t config_time_store(struct bus_type *bus,
1124                                 const char *buf, size_t count)
1125{
1126        int time;
1127
1128        if (sscanf(buf, "%d\n", &time) != 1 || time < 5 || time > 120)
1129                return -EINVAL;
1130        ap_config_time = time;
1131        mod_timer(&ap_config_timer, jiffies + ap_config_time * HZ);
1132        return count;
1133}
1134
1135static BUS_ATTR_RW(config_time);
1136
1137static ssize_t poll_thread_show(struct bus_type *bus, char *buf)
1138{
1139        return scnprintf(buf, PAGE_SIZE, "%d\n", ap_poll_kthread ? 1 : 0);
1140}
1141
1142static ssize_t poll_thread_store(struct bus_type *bus,
1143                                 const char *buf, size_t count)
1144{
1145        int flag, rc;
1146
1147        if (sscanf(buf, "%d\n", &flag) != 1)
1148                return -EINVAL;
1149        if (flag) {
1150                rc = ap_poll_thread_start();
1151                if (rc)
1152                        count = rc;
1153        } else
1154                ap_poll_thread_stop();
1155        return count;
1156}
1157
1158static BUS_ATTR_RW(poll_thread);
1159
1160static ssize_t poll_timeout_show(struct bus_type *bus, char *buf)
1161{
1162        return scnprintf(buf, PAGE_SIZE, "%llu\n", poll_timeout);
1163}
1164
1165static ssize_t poll_timeout_store(struct bus_type *bus, const char *buf,
1166                                  size_t count)
1167{
1168        unsigned long long time;
1169        ktime_t hr_time;
1170
1171        /* 120 seconds = maximum poll interval */
1172        if (sscanf(buf, "%llu\n", &time) != 1 || time < 1 ||
1173            time > 120000000000ULL)
1174                return -EINVAL;
1175        poll_timeout = time;
1176        hr_time = poll_timeout;
1177
1178        spin_lock_bh(&ap_poll_timer_lock);
1179        hrtimer_cancel(&ap_poll_timer);
1180        hrtimer_set_expires(&ap_poll_timer, hr_time);
1181        hrtimer_start_expires(&ap_poll_timer, HRTIMER_MODE_ABS);
1182        spin_unlock_bh(&ap_poll_timer_lock);
1183
1184        return count;
1185}
1186
1187static BUS_ATTR_RW(poll_timeout);
1188
1189static ssize_t ap_max_domain_id_show(struct bus_type *bus, char *buf)
1190{
1191        return scnprintf(buf, PAGE_SIZE, "%d\n", ap_max_domain_id);
1192}
1193
1194static BUS_ATTR_RO(ap_max_domain_id);
1195
1196static ssize_t ap_max_adapter_id_show(struct bus_type *bus, char *buf)
1197{
1198        return scnprintf(buf, PAGE_SIZE, "%d\n", ap_max_adapter_id);
1199}
1200
1201static BUS_ATTR_RO(ap_max_adapter_id);
1202
1203static ssize_t apmask_show(struct bus_type *bus, char *buf)
1204{
1205        int rc;
1206
1207        if (mutex_lock_interruptible(&ap_perms_mutex))
1208                return -ERESTARTSYS;
1209        rc = scnprintf(buf, PAGE_SIZE,
1210                       "0x%016lx%016lx%016lx%016lx\n",
1211                       ap_perms.apm[0], ap_perms.apm[1],
1212                       ap_perms.apm[2], ap_perms.apm[3]);
1213        mutex_unlock(&ap_perms_mutex);
1214
1215        return rc;
1216}
1217
1218static ssize_t apmask_store(struct bus_type *bus, const char *buf,
1219                            size_t count)
1220{
1221        int rc;
1222
1223        rc = ap_parse_mask_str(buf, ap_perms.apm, AP_DEVICES, &ap_perms_mutex);
1224        if (rc)
1225                return rc;
1226
1227        ap_bus_revise_bindings();
1228
1229        return count;
1230}
1231
1232static BUS_ATTR_RW(apmask);
1233
1234static ssize_t aqmask_show(struct bus_type *bus, char *buf)
1235{
1236        int rc;
1237
1238        if (mutex_lock_interruptible(&ap_perms_mutex))
1239                return -ERESTARTSYS;
1240        rc = scnprintf(buf, PAGE_SIZE,
1241                       "0x%016lx%016lx%016lx%016lx\n",
1242                       ap_perms.aqm[0], ap_perms.aqm[1],
1243                       ap_perms.aqm[2], ap_perms.aqm[3]);
1244        mutex_unlock(&ap_perms_mutex);
1245
1246        return rc;
1247}
1248
1249static ssize_t aqmask_store(struct bus_type *bus, const char *buf,
1250                            size_t count)
1251{
1252        int rc;
1253
1254        rc = ap_parse_mask_str(buf, ap_perms.aqm, AP_DOMAINS, &ap_perms_mutex);
1255        if (rc)
1256                return rc;
1257
1258        ap_bus_revise_bindings();
1259
1260        return count;
1261}
1262
1263static BUS_ATTR_RW(aqmask);
1264
1265static ssize_t scans_show(struct bus_type *bus, char *buf)
1266{
1267        return scnprintf(buf, PAGE_SIZE, "%llu\n",
1268                         atomic64_read(&ap_scan_bus_count));
1269}
1270
1271static BUS_ATTR_RO(scans);
1272
1273static ssize_t bindings_show(struct bus_type *bus, char *buf)
1274{
1275        int rc;
1276        unsigned int apqns, n;
1277
1278        ap_calc_bound_apqns(&apqns, &n);
1279        if (atomic64_read(&ap_scan_bus_count) >= 1 && n == apqns)
1280                rc = scnprintf(buf, PAGE_SIZE, "%u/%u (complete)\n", n, apqns);
1281        else
1282                rc = scnprintf(buf, PAGE_SIZE, "%u/%u\n", n, apqns);
1283
1284        return rc;
1285}
1286
1287static BUS_ATTR_RO(bindings);
1288
1289static struct attribute *ap_bus_attrs[] = {
1290        &bus_attr_ap_domain.attr,
1291        &bus_attr_ap_control_domain_mask.attr,
1292        &bus_attr_ap_usage_domain_mask.attr,
1293        &bus_attr_ap_adapter_mask.attr,
1294        &bus_attr_config_time.attr,
1295        &bus_attr_poll_thread.attr,
1296        &bus_attr_ap_interrupts.attr,
1297        &bus_attr_poll_timeout.attr,
1298        &bus_attr_ap_max_domain_id.attr,
1299        &bus_attr_ap_max_adapter_id.attr,
1300        &bus_attr_apmask.attr,
1301        &bus_attr_aqmask.attr,
1302        &bus_attr_scans.attr,
1303        &bus_attr_bindings.attr,
1304        NULL,
1305};
1306ATTRIBUTE_GROUPS(ap_bus);
1307
1308static struct bus_type ap_bus_type = {
1309        .name = "ap",
1310        .bus_groups = ap_bus_groups,
1311        .match = &ap_bus_match,
1312        .uevent = &ap_uevent,
1313};
1314
1315/**
1316 * ap_select_domain(): Select an AP domain if possible and we haven't
1317 * already done so before.
1318 */
1319static void ap_select_domain(void)
1320{
1321        struct ap_queue_status status;
1322        int card, dom;
1323
1324        /*
1325         * Choose the default domain. Either the one specified with
1326         * the "domain=" parameter or the first domain with at least
1327         * one valid APQN.
1328         */
1329        spin_lock_bh(&ap_domain_lock);
1330        if (ap_domain_index >= 0) {
1331                /* Domain has already been selected. */
1332                goto out;
1333        }
1334        for (dom = 0; dom <= ap_max_domain_id; dom++) {
1335                if (!ap_test_config_usage_domain(dom) ||
1336                    !test_bit_inv(dom, ap_perms.aqm))
1337                        continue;
1338                for (card = 0; card <= ap_max_adapter_id; card++) {
1339                        if (!ap_test_config_card_id(card) ||
1340                            !test_bit_inv(card, ap_perms.apm))
1341                                continue;
1342                        status = ap_test_queue(AP_MKQID(card, dom),
1343                                               ap_apft_available(),
1344                                               NULL);
1345                        if (status.response_code == AP_RESPONSE_NORMAL)
1346                                break;
1347                }
1348                if (card <= ap_max_adapter_id)
1349                        break;
1350        }
1351        if (dom <= ap_max_domain_id) {
1352                ap_domain_index = dom;
1353                AP_DBF_INFO("%s new default domain is %d\n",
1354                            __func__, ap_domain_index);
1355        }
1356out:
1357        spin_unlock_bh(&ap_domain_lock);
1358}
1359
1360/*
1361 * This function checks the type and returns either 0 for not
1362 * supported or the highest compatible type value (which may
1363 * include the input type value).
1364 */
1365static int ap_get_compatible_type(ap_qid_t qid, int rawtype, unsigned int func)
1366{
1367        int comp_type = 0;
1368
1369        /* < CEX2A is not supported */
1370        if (rawtype < AP_DEVICE_TYPE_CEX2A) {
1371                AP_DBF_WARN("get_comp_type queue=%02x.%04x unsupported type %d\n",
1372                            AP_QID_CARD(qid), AP_QID_QUEUE(qid), rawtype);
1373                return 0;
1374        }
1375        /* up to CEX7 known and fully supported */
1376        if (rawtype <= AP_DEVICE_TYPE_CEX7)
1377                return rawtype;
1378        /*
1379         * unknown new type > CEX7, check for compatibility
1380         * to the highest known and supported type which is
1381         * currently CEX7 with the help of the QACT function.
1382         */
1383        if (ap_qact_available()) {
1384                struct ap_queue_status status;
1385                union ap_qact_ap_info apinfo = {0};
1386
1387                apinfo.mode = (func >> 26) & 0x07;
1388                apinfo.cat = AP_DEVICE_TYPE_CEX7;
1389                status = ap_qact(qid, 0, &apinfo);
1390                if (status.response_code == AP_RESPONSE_NORMAL
1391                    && apinfo.cat >= AP_DEVICE_TYPE_CEX2A
1392                    && apinfo.cat <= AP_DEVICE_TYPE_CEX7)
1393                        comp_type = apinfo.cat;
1394        }
1395        if (!comp_type)
1396                AP_DBF_WARN("get_comp_type queue=%02x.%04x unable to map type %d\n",
1397                            AP_QID_CARD(qid), AP_QID_QUEUE(qid), rawtype);
1398        else if (comp_type != rawtype)
1399                AP_DBF_INFO("get_comp_type queue=%02x.%04x map type %d to %d\n",
1400                            AP_QID_CARD(qid), AP_QID_QUEUE(qid),
1401                            rawtype, comp_type);
1402        return comp_type;
1403}
1404
1405/*
1406 * Helper function to be used with bus_find_dev
1407 * matches for the card device with the given id
1408 */
1409static int __match_card_device_with_id(struct device *dev, const void *data)
1410{
1411        return is_card_dev(dev) && to_ap_card(dev)->id == (int)(long)(void *) data;
1412}
1413
1414/*
1415 * Helper function to be used with bus_find_dev
1416 * matches for the queue device with a given qid
1417 */
1418static int __match_queue_device_with_qid(struct device *dev, const void *data)
1419{
1420        return is_queue_dev(dev) && to_ap_queue(dev)->qid == (int)(long) data;
1421}
1422
1423/*
1424 * Helper function to be used with bus_find_dev
1425 * matches any queue device with given queue id
1426 */
1427static int __match_queue_device_with_queue_id(struct device *dev, const void *data)
1428{
1429        return is_queue_dev(dev)
1430                && AP_QID_QUEUE(to_ap_queue(dev)->qid) == (int)(long) data;
1431}
1432
1433/*
1434 * Helper function for ap_scan_bus().
1435 * Remove card device and associated queue devices.
1436 */
1437static inline void ap_scan_rm_card_dev_and_queue_devs(struct ap_card *ac)
1438{
1439        bus_for_each_dev(&ap_bus_type, NULL,
1440                         (void *)(long) ac->id,
1441                         __ap_queue_devices_with_id_unregister);
1442        device_unregister(&ac->ap_dev.device);
1443}
1444
1445/*
1446 * Helper function for ap_scan_bus().
1447 * Does the scan bus job for all the domains within
1448 * a valid adapter given by an ap_card ptr.
1449 */
1450static inline void ap_scan_domains(struct ap_card *ac)
1451{
1452        bool decfg;
1453        ap_qid_t qid;
1454        unsigned int func;
1455        struct device *dev;
1456        struct ap_queue *aq;
1457        int rc, dom, depth, type;
1458
1459        /*
1460         * Go through the configuration for the domains and compare them
1461         * to the existing queue devices. Also take care of the config
1462         * and error state for the queue devices.
1463         */
1464
1465        for (dom = 0; dom <= ap_max_domain_id; dom++) {
1466                qid = AP_MKQID(ac->id, dom);
1467                dev = bus_find_device(&ap_bus_type, NULL,
1468                                      (void *)(long) qid,
1469                                      __match_queue_device_with_qid);
1470                aq = dev ? to_ap_queue(dev) : NULL;
1471                if (!ap_test_config_usage_domain(dom)) {
1472                        if (dev) {
1473                                AP_DBF_INFO("%s(%d,%d) not in config any more, rm queue device\n",
1474                                            __func__, ac->id, dom);
1475                                device_unregister(dev);
1476                                put_device(dev);
1477                        }
1478                        continue;
1479                }
1480                /* domain is valid, get info from this APQN */
1481                if (!ap_queue_info(qid, &type, &func, &depth, &decfg)) {
1482                        if (aq) {
1483                                AP_DBF_INFO(
1484                                        "%s(%d,%d) ap_queue_info() not successful, rm queue device\n",
1485                                        __func__, ac->id, dom);
1486                                device_unregister(dev);
1487                                put_device(dev);
1488                        }
1489                        continue;
1490                }
1491                /* if no queue device exists, create a new one */
1492                if (!aq) {
1493                        aq = ap_queue_create(qid, ac->ap_dev.device_type);
1494                        if (!aq) {
1495                                AP_DBF_WARN("%s(%d,%d) ap_queue_create() failed\n",
1496                                            __func__, ac->id, dom);
1497                                continue;
1498                        }
1499                        aq->card = ac;
1500                        aq->config = !decfg;
1501                        dev = &aq->ap_dev.device;
1502                        dev->bus = &ap_bus_type;
1503                        dev->parent = &ac->ap_dev.device;
1504                        dev_set_name(dev, "%02x.%04x", ac->id, dom);
1505                        /* register queue device */
1506                        rc = device_register(dev);
1507                        if (rc) {
1508                                AP_DBF_WARN("%s(%d,%d) device_register() failed\n",
1509                                            __func__, ac->id, dom);
1510                                goto put_dev_and_continue;
1511                        }
1512                        /* get it and thus adjust reference counter */
1513                        get_device(dev);
1514                        if (decfg)
1515                                AP_DBF_INFO("%s(%d,%d) new (decfg) queue device created\n",
1516                                            __func__, ac->id, dom);
1517                        else
1518                                AP_DBF_INFO("%s(%d,%d) new queue device created\n",
1519                                            __func__, ac->id, dom);
1520                        goto put_dev_and_continue;
1521                }
1522                /* Check config state on the already existing queue device */
1523                spin_lock_bh(&aq->lock);
1524                if (decfg && aq->config) {
1525                        /* config off this queue device */
1526                        aq->config = false;
1527                        if (aq->dev_state > AP_DEV_STATE_UNINITIATED) {
1528                                aq->dev_state = AP_DEV_STATE_ERROR;
1529                                aq->last_err_rc = AP_RESPONSE_DECONFIGURED;
1530                        }
1531                        spin_unlock_bh(&aq->lock);
1532                        AP_DBF_INFO("%s(%d,%d) queue device config off\n",
1533                                    __func__, ac->id, dom);
1534                        /* 'receive' pending messages with -EAGAIN */
1535                        ap_flush_queue(aq);
1536                        goto put_dev_and_continue;
1537                }
1538                if (!decfg && !aq->config) {
1539                        /* config on this queue device */
1540                        aq->config = true;
1541                        if (aq->dev_state > AP_DEV_STATE_UNINITIATED) {
1542                                aq->dev_state = AP_DEV_STATE_OPERATING;
1543                                aq->sm_state = AP_SM_STATE_RESET_START;
1544                        }
1545                        spin_unlock_bh(&aq->lock);
1546                        AP_DBF_INFO("%s(%d,%d) queue device config on\n",
1547                                    __func__, ac->id, dom);
1548                        goto put_dev_and_continue;
1549                }
1550                /* handle other error states */
1551                if (!decfg && aq->dev_state == AP_DEV_STATE_ERROR) {
1552                        spin_unlock_bh(&aq->lock);
1553                        /* 'receive' pending messages with -EAGAIN */
1554                        ap_flush_queue(aq);
1555                        /* re-init (with reset) the queue device */
1556                        ap_queue_init_state(aq);
1557                        AP_DBF_INFO("%s(%d,%d) queue device reinit enforced\n",
1558                                    __func__, ac->id, dom);
1559                        goto put_dev_and_continue;
1560                }
1561                spin_unlock_bh(&aq->lock);
1562put_dev_and_continue:
1563                put_device(dev);
1564        }
1565}
1566
1567/*
1568 * Helper function for ap_scan_bus().
1569 * Does the scan bus job for the given adapter id.
1570 */
1571static inline void ap_scan_adapter(int ap)
1572{
1573        bool decfg;
1574        ap_qid_t qid;
1575        unsigned int func;
1576        struct device *dev;
1577        struct ap_card *ac;
1578        int rc, dom, depth, type, comp_type;
1579
1580        /* Is there currently a card device for this adapter ? */
1581        dev = bus_find_device(&ap_bus_type, NULL,
1582                              (void *)(long) ap,
1583                              __match_card_device_with_id);
1584        ac = dev ? to_ap_card(dev) : NULL;
1585
1586        /* Adapter not in configuration ? */
1587        if (!ap_test_config_card_id(ap)) {
1588                if (ac) {
1589                        AP_DBF_INFO("%s(%d) ap not in config any more, rm card and queue devices\n",
1590                                    __func__, ap);
1591                        ap_scan_rm_card_dev_and_queue_devs(ac);
1592                        put_device(dev);
1593                }
1594                return;
1595        }
1596
1597        /*
1598         * Adapter ap is valid in the current configuration. So do some checks:
1599         * If no card device exists, build one. If a card device exists, check
1600         * for type and functions changed. For all this we need to find a valid
1601         * APQN first.
1602         */
1603
1604        for (dom = 0; dom <= ap_max_domain_id; dom++)
1605                if (ap_test_config_usage_domain(dom)) {
1606                        qid = AP_MKQID(ap, dom);
1607                        if (ap_queue_info(qid, &type, &func, &depth, &decfg))
1608                                break;
1609                }
1610        if (dom > ap_max_domain_id) {
1611                /* Could not find a valid APQN for this adapter */
1612                if (ac) {
1613                        AP_DBF_INFO(
1614                                "%s(%d) no type info (no APQN found), rm card and queue devices\n",
1615                                __func__, ap);
1616                        ap_scan_rm_card_dev_and_queue_devs(ac);
1617                        put_device(dev);
1618                } else {
1619                        AP_DBF_DBG("%s(%d) no type info (no APQN found), ignored\n",
1620                                   __func__, ap);
1621                }
1622                return;
1623        }
1624        if (!type) {
1625                /* No apdater type info available, an unusable adapter */
1626                if (ac) {
1627                        AP_DBF_INFO("%s(%d) no valid type (0) info, rm card and queue devices\n",
1628                                    __func__, ap);
1629                        ap_scan_rm_card_dev_and_queue_devs(ac);
1630                        put_device(dev);
1631                } else {
1632                        AP_DBF_DBG("%s(%d) no valid type (0) info, ignored\n",
1633                                   __func__, ap);
1634                }
1635                return;
1636        }
1637
1638        if (ac) {
1639                /* Check APQN against existing card device for changes */
1640                if (ac->raw_hwtype != type) {
1641                        AP_DBF_INFO("%s(%d) hwtype %d changed, rm card and queue devices\n",
1642                                    __func__, ap, type);
1643                        ap_scan_rm_card_dev_and_queue_devs(ac);
1644                        put_device(dev);
1645                        ac = NULL;
1646                } else if (ac->functions != func) {
1647                        AP_DBF_INFO("%s(%d) functions 0x%08x changed, rm card and queue devices\n",
1648                                    __func__, ap, type);
1649                        ap_scan_rm_card_dev_and_queue_devs(ac);
1650                        put_device(dev);
1651                        ac = NULL;
1652                } else {
1653                        if (decfg && ac->config) {
1654                                ac->config = false;
1655                                AP_DBF_INFO("%s(%d) card device config off\n",
1656                                            __func__, ap);
1657
1658                        }
1659                        if (!decfg && !ac->config) {
1660                                ac->config = true;
1661                                AP_DBF_INFO("%s(%d) card device config on\n",
1662                                            __func__, ap);
1663                        }
1664                }
1665        }
1666
1667        if (!ac) {
1668                /* Build a new card device */
1669                comp_type = ap_get_compatible_type(qid, type, func);
1670                if (!comp_type) {
1671                        AP_DBF_WARN("%s(%d) type %d, can't get compatibility type\n",
1672                                    __func__, ap, type);
1673                        return;
1674                }
1675                ac = ap_card_create(ap, depth, type, comp_type, func);
1676                if (!ac) {
1677                        AP_DBF_WARN("%s(%d) ap_card_create() failed\n",
1678                                    __func__, ap);
1679                        return;
1680                }
1681                ac->config = !decfg;
1682                dev = &ac->ap_dev.device;
1683                dev->bus = &ap_bus_type;
1684                dev->parent = ap_root_device;
1685                dev_set_name(dev, "card%02x", ap);
1686                /* Register the new card device with AP bus */
1687                rc = device_register(dev);
1688                if (rc) {
1689                        AP_DBF_WARN("%s(%d) device_register() failed\n",
1690                                    __func__, ap);
1691                        put_device(dev);
1692                        return;
1693                }
1694                /* get it and thus adjust reference counter */
1695                get_device(dev);
1696                if (decfg)
1697                        AP_DBF_INFO("%s(%d) new (decfg) card device type=%d func=0x%08x created\n",
1698                                    __func__, ap, type, func);
1699                else
1700                        AP_DBF_INFO("%s(%d) new card device type=%d func=0x%08x created\n",
1701                                    __func__, ap, type, func);
1702        }
1703
1704        /* Verify the domains and the queue devices for this card */
1705        ap_scan_domains(ac);
1706
1707        /* release the card device */
1708        put_device(&ac->ap_dev.device);
1709}
1710
1711/**
1712 * ap_scan_bus(): Scan the AP bus for new devices
1713 * Runs periodically, workqueue timer (ap_config_time)
1714 */
1715static void ap_scan_bus(struct work_struct *unused)
1716{
1717        int ap;
1718
1719        ap_fetch_qci_info(ap_qci_info);
1720        ap_select_domain();
1721
1722        AP_DBF_DBG("%s running\n", __func__);
1723
1724        /* loop over all possible adapters */
1725        for (ap = 0; ap <= ap_max_adapter_id; ap++)
1726                ap_scan_adapter(ap);
1727
1728        /* check if there is at least one queue available with default domain */
1729        if (ap_domain_index >= 0) {
1730                struct device *dev =
1731                        bus_find_device(&ap_bus_type, NULL,
1732                                        (void *)(long) ap_domain_index,
1733                                        __match_queue_device_with_queue_id);
1734                if (dev)
1735                        put_device(dev);
1736                else
1737                        AP_DBF_INFO("no queue device with default domain %d available\n",
1738                                    ap_domain_index);
1739        }
1740
1741        if (atomic64_inc_return(&ap_scan_bus_count) == 1) {
1742                AP_DBF(DBF_DEBUG, "%s init scan complete\n", __func__);
1743                ap_send_init_scan_done_uevent();
1744                ap_check_bindings_complete();
1745        }
1746
1747        mod_timer(&ap_config_timer, jiffies + ap_config_time * HZ);
1748}
1749
1750static void ap_config_timeout(struct timer_list *unused)
1751{
1752        queue_work(system_long_wq, &ap_scan_work);
1753}
1754
1755static int __init ap_debug_init(void)
1756{
1757        ap_dbf_info = debug_register("ap", 1, 1,
1758                                     DBF_MAX_SPRINTF_ARGS * sizeof(long));
1759        debug_register_view(ap_dbf_info, &debug_sprintf_view);
1760        debug_set_level(ap_dbf_info, DBF_ERR);
1761
1762        return 0;
1763}
1764
1765static void __init ap_perms_init(void)
1766{
1767        /* all resources useable if no kernel parameter string given */
1768        memset(&ap_perms.ioctlm, 0xFF, sizeof(ap_perms.ioctlm));
1769        memset(&ap_perms.apm, 0xFF, sizeof(ap_perms.apm));
1770        memset(&ap_perms.aqm, 0xFF, sizeof(ap_perms.aqm));
1771
1772        /* apm kernel parameter string */
1773        if (apm_str) {
1774                memset(&ap_perms.apm, 0, sizeof(ap_perms.apm));
1775                ap_parse_mask_str(apm_str, ap_perms.apm, AP_DEVICES,
1776                                  &ap_perms_mutex);
1777        }
1778
1779        /* aqm kernel parameter string */
1780        if (aqm_str) {
1781                memset(&ap_perms.aqm, 0, sizeof(ap_perms.aqm));
1782                ap_parse_mask_str(aqm_str, ap_perms.aqm, AP_DOMAINS,
1783                                  &ap_perms_mutex);
1784        }
1785}
1786
1787/**
1788 * ap_module_init(): The module initialization code.
1789 *
1790 * Initializes the module.
1791 */
1792static int __init ap_module_init(void)
1793{
1794        int rc;
1795
1796        rc = ap_debug_init();
1797        if (rc)
1798                return rc;
1799
1800        if (!ap_instructions_available()) {
1801                pr_warn("The hardware system does not support AP instructions\n");
1802                return -ENODEV;
1803        }
1804
1805        /* init ap_queue hashtable */
1806        hash_init(ap_queues);
1807
1808        /* set up the AP permissions (ioctls, ap and aq masks) */
1809        ap_perms_init();
1810
1811        /* Get AP configuration data if available */
1812        ap_init_qci_info();
1813
1814        /* check default domain setting */
1815        if (ap_domain_index < -1 || ap_domain_index > ap_max_domain_id ||
1816            (ap_domain_index >= 0 &&
1817             !test_bit_inv(ap_domain_index, ap_perms.aqm))) {
1818                pr_warn("%d is not a valid cryptographic domain\n",
1819                        ap_domain_index);
1820                ap_domain_index = -1;
1821        }
1822
1823        /* enable interrupts if available */
1824        if (ap_interrupts_available()) {
1825                rc = register_adapter_interrupt(&ap_airq);
1826                ap_irq_flag = (rc == 0);
1827        }
1828
1829        /* Create /sys/bus/ap. */
1830        rc = bus_register(&ap_bus_type);
1831        if (rc)
1832                goto out;
1833
1834        /* Create /sys/devices/ap. */
1835        ap_root_device = root_device_register("ap");
1836        rc = PTR_ERR_OR_ZERO(ap_root_device);
1837        if (rc)
1838                goto out_bus;
1839        ap_root_device->bus = &ap_bus_type;
1840
1841        /* Setup the AP bus rescan timer. */
1842        timer_setup(&ap_config_timer, ap_config_timeout, 0);
1843
1844        /*
1845         * Setup the high resultion poll timer.
1846         * If we are running under z/VM adjust polling to z/VM polling rate.
1847         */
1848        if (MACHINE_IS_VM)
1849                poll_timeout = 1500000;
1850        hrtimer_init(&ap_poll_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
1851        ap_poll_timer.function = ap_poll_timeout;
1852
1853        /* Start the low priority AP bus poll thread. */
1854        if (ap_thread_flag) {
1855                rc = ap_poll_thread_start();
1856                if (rc)
1857                        goto out_work;
1858        }
1859
1860        queue_work(system_long_wq, &ap_scan_work);
1861
1862        return 0;
1863
1864out_work:
1865        hrtimer_cancel(&ap_poll_timer);
1866        root_device_unregister(ap_root_device);
1867out_bus:
1868        bus_unregister(&ap_bus_type);
1869out:
1870        if (ap_irq_flag)
1871                unregister_adapter_interrupt(&ap_airq);
1872        kfree(ap_qci_info);
1873        return rc;
1874}
1875device_initcall(ap_module_init);
1876