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