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