]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/s390/crypto/ap_bus.c
Merge branch 'for-4.8/core' of git://git.kernel.dk/linux-block
[karo-tx-linux.git] / drivers / s390 / crypto / ap_bus.c
1 /*
2  * Copyright IBM Corp. 2006, 2012
3  * Author(s): Cornelia Huck <cornelia.huck@de.ibm.com>
4  *            Martin Schwidefsky <schwidefsky@de.ibm.com>
5  *            Ralph Wuerthner <rwuerthn@de.ibm.com>
6  *            Felix Beck <felix.beck@de.ibm.com>
7  *            Holger Dengler <hd@linux.vnet.ibm.com>
8  *
9  * Adjunct processor bus.
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2, or (at your option)
14  * any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24  */
25
26 #define KMSG_COMPONENT "ap"
27 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
28
29 #include <linux/kernel_stat.h>
30 #include <linux/module.h>
31 #include <linux/init.h>
32 #include <linux/delay.h>
33 #include <linux/err.h>
34 #include <linux/interrupt.h>
35 #include <linux/workqueue.h>
36 #include <linux/slab.h>
37 #include <linux/notifier.h>
38 #include <linux/kthread.h>
39 #include <linux/mutex.h>
40 #include <linux/suspend.h>
41 #include <asm/reset.h>
42 #include <asm/airq.h>
43 #include <linux/atomic.h>
44 #include <asm/isc.h>
45 #include <linux/hrtimer.h>
46 #include <linux/ktime.h>
47 #include <asm/facility.h>
48 #include <linux/crypto.h>
49
50 #include "ap_bus.h"
51
52 /*
53  * Module description.
54  */
55 MODULE_AUTHOR("IBM Corporation");
56 MODULE_DESCRIPTION("Adjunct Processor Bus driver, " \
57                    "Copyright IBM Corp. 2006, 2012");
58 MODULE_LICENSE("GPL");
59 MODULE_ALIAS_CRYPTO("z90crypt");
60
61 /*
62  * Module parameter
63  */
64 int ap_domain_index = -1;       /* Adjunct Processor Domain Index */
65 module_param_named(domain, ap_domain_index, int, S_IRUSR|S_IRGRP);
66 MODULE_PARM_DESC(domain, "domain index for ap devices");
67 EXPORT_SYMBOL(ap_domain_index);
68
69 static int ap_thread_flag = 0;
70 module_param_named(poll_thread, ap_thread_flag, int, S_IRUSR|S_IRGRP);
71 MODULE_PARM_DESC(poll_thread, "Turn on/off poll thread, default is 0 (off).");
72
73 static struct device *ap_root_device = NULL;
74 static struct ap_config_info *ap_configuration;
75 static DEFINE_SPINLOCK(ap_device_list_lock);
76 static LIST_HEAD(ap_device_list);
77 static bool initialised;
78
79 /*
80  * Workqueue timer for bus rescan.
81  */
82 static struct timer_list ap_config_timer;
83 static int ap_config_time = AP_CONFIG_TIME;
84 static void ap_scan_bus(struct work_struct *);
85 static DECLARE_WORK(ap_scan_work, ap_scan_bus);
86
87 /*
88  * Tasklet & timer for AP request polling and interrupts
89  */
90 static void ap_tasklet_fn(unsigned long);
91 static DECLARE_TASKLET(ap_tasklet, ap_tasklet_fn, 0);
92 static atomic_t ap_poll_requests = ATOMIC_INIT(0);
93 static DECLARE_WAIT_QUEUE_HEAD(ap_poll_wait);
94 static struct task_struct *ap_poll_kthread = NULL;
95 static DEFINE_MUTEX(ap_poll_thread_mutex);
96 static DEFINE_SPINLOCK(ap_poll_timer_lock);
97 static struct hrtimer ap_poll_timer;
98 /* In LPAR poll with 4kHz frequency. Poll every 250000 nanoseconds.
99  * If z/VM change to 1500000 nanoseconds to adjust to z/VM polling.*/
100 static unsigned long long poll_timeout = 250000;
101
102 /* Suspend flag */
103 static int ap_suspend_flag;
104 /* Maximum domain id */
105 static int ap_max_domain_id;
106 /* Flag to check if domain was set through module parameter domain=. This is
107  * important when supsend and resume is done in a z/VM environment where the
108  * domain might change. */
109 static int user_set_domain = 0;
110 static struct bus_type ap_bus_type;
111
112 /* Adapter interrupt definitions */
113 static void ap_interrupt_handler(struct airq_struct *airq);
114
115 static int ap_airq_flag;
116
117 static struct airq_struct ap_airq = {
118         .handler = ap_interrupt_handler,
119         .isc = AP_ISC,
120 };
121
122 /**
123  * ap_using_interrupts() - Returns non-zero if interrupt support is
124  * available.
125  */
126 static inline int ap_using_interrupts(void)
127 {
128         return ap_airq_flag;
129 }
130
131 /**
132  * ap_intructions_available() - Test if AP instructions are available.
133  *
134  * Returns 0 if the AP instructions are installed.
135  */
136 static inline int ap_instructions_available(void)
137 {
138         register unsigned long reg0 asm ("0") = AP_MKQID(0,0);
139         register unsigned long reg1 asm ("1") = -ENODEV;
140         register unsigned long reg2 asm ("2") = 0UL;
141
142         asm volatile(
143                 "   .long 0xb2af0000\n"         /* PQAP(TAPQ) */
144                 "0: la    %1,0\n"
145                 "1:\n"
146                 EX_TABLE(0b, 1b)
147                 : "+d" (reg0), "+d" (reg1), "+d" (reg2) : : "cc" );
148         return reg1;
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 static inline struct ap_queue_status
173 __pqap_tapq(ap_qid_t qid, unsigned long *info)
174 {
175         register unsigned long reg0 asm ("0") = qid;
176         register struct ap_queue_status reg1 asm ("1");
177         register unsigned long reg2 asm ("2") = 0UL;
178
179         asm volatile(".long 0xb2af0000"         /* PQAP(TAPQ) */
180                      : "+d" (reg0), "=d" (reg1), "+d" (reg2) : : "cc");
181         *info = reg2;
182         return reg1;
183 }
184
185 /**
186  * ap_test_queue(): Test adjunct processor queue.
187  * @qid: The AP queue number
188  * @info: Pointer to queue descriptor
189  *
190  * Returns AP queue status structure.
191  */
192 static inline struct ap_queue_status
193 ap_test_queue(ap_qid_t qid, unsigned long *info)
194 {
195         struct ap_queue_status aqs;
196         unsigned long _info;
197
198         if (test_facility(15))
199                 qid |= 1UL << 23;               /* set APFT T bit*/
200         aqs = __pqap_tapq(qid, &_info);
201         if (info)
202                 *info = _info;
203         return aqs;
204 }
205
206 /**
207  * ap_reset_queue(): Reset adjunct processor queue.
208  * @qid: The AP queue number
209  *
210  * Returns AP queue status structure.
211  */
212 static inline struct ap_queue_status ap_reset_queue(ap_qid_t qid)
213 {
214         register unsigned long reg0 asm ("0") = qid | 0x01000000UL;
215         register struct ap_queue_status reg1 asm ("1");
216         register unsigned long reg2 asm ("2") = 0UL;
217
218         asm volatile(
219                 ".long 0xb2af0000"              /* PQAP(RAPQ) */
220                 : "+d" (reg0), "=d" (reg1), "+d" (reg2) : : "cc");
221         return reg1;
222 }
223
224 /**
225  * ap_queue_interruption_control(): Enable interruption for a specific AP.
226  * @qid: The AP queue number
227  * @ind: The notification indicator byte
228  *
229  * Returns AP queue status.
230  */
231 static inline struct ap_queue_status
232 ap_queue_interruption_control(ap_qid_t qid, void *ind)
233 {
234         register unsigned long reg0 asm ("0") = qid | 0x03000000UL;
235         register unsigned long reg1_in asm ("1") = 0x0000800000000000UL | AP_ISC;
236         register struct ap_queue_status reg1_out asm ("1");
237         register void *reg2 asm ("2") = ind;
238         asm volatile(
239                 ".long 0xb2af0000"              /* PQAP(AQIC) */
240                 : "+d" (reg0), "+d" (reg1_in), "=d" (reg1_out), "+d" (reg2)
241                 :
242                 : "cc" );
243         return reg1_out;
244 }
245
246 /**
247  * ap_query_configuration(): Get AP configuration data
248  *
249  * Returns 0 on success, or -EOPNOTSUPP.
250  */
251 static inline int __ap_query_configuration(void)
252 {
253         register unsigned long reg0 asm ("0") = 0x04000000UL;
254         register unsigned long reg1 asm ("1") = -EINVAL;
255         register void *reg2 asm ("2") = (void *) ap_configuration;
256
257         asm volatile(
258                 ".long 0xb2af0000\n"            /* PQAP(QCI) */
259                 "0: la    %1,0\n"
260                 "1:\n"
261                 EX_TABLE(0b, 1b)
262                 : "+d" (reg0), "+d" (reg1), "+d" (reg2)
263                 :
264                 : "cc");
265
266         return reg1;
267 }
268
269 static inline int ap_query_configuration(void)
270 {
271         if (!ap_configuration)
272                 return -EOPNOTSUPP;
273         return __ap_query_configuration();
274 }
275
276 /**
277  * ap_init_configuration(): Allocate and query configuration array.
278  */
279 static void ap_init_configuration(void)
280 {
281         if (!ap_configuration_available())
282                 return;
283
284         ap_configuration = kzalloc(sizeof(*ap_configuration), GFP_KERNEL);
285         if (!ap_configuration)
286                 return;
287         if (ap_query_configuration() != 0) {
288                 kfree(ap_configuration);
289                 ap_configuration = NULL;
290                 return;
291         }
292 }
293
294 /*
295  * ap_test_config(): helper function to extract the nrth bit
296  *                   within the unsigned int array field.
297  */
298 static inline int ap_test_config(unsigned int *field, unsigned int nr)
299 {
300         return ap_test_bit((field + (nr >> 5)), (nr & 0x1f));
301 }
302
303 /*
304  * ap_test_config_card_id(): Test, whether an AP card ID is configured.
305  * @id AP card ID
306  *
307  * Returns 0 if the card is not configured
308  *         1 if the card is configured or
309  *           if the configuration information is not available
310  */
311 static inline int ap_test_config_card_id(unsigned int id)
312 {
313         if (!ap_configuration)  /* QCI not supported */
314                 return 1;
315         return ap_test_config(ap_configuration->apm, id);
316 }
317
318 /*
319  * ap_test_config_domain(): Test, whether an AP usage domain is configured.
320  * @domain AP usage domain ID
321  *
322  * Returns 0 if the usage domain is not configured
323  *         1 if the usage domain is configured or
324  *           if the configuration information is not available
325  */
326 static inline int ap_test_config_domain(unsigned int domain)
327 {
328         if (!ap_configuration)  /* QCI not supported */
329                 return domain < 16;
330         return ap_test_config(ap_configuration->aqm, domain);
331 }
332
333 /**
334  * ap_queue_enable_interruption(): Enable interruption on an AP.
335  * @qid: The AP queue number
336  * @ind: the notification indicator byte
337  *
338  * Enables interruption on AP queue via ap_queue_interruption_control(). Based
339  * on the return value it waits a while and tests the AP queue if interrupts
340  * have been switched on using ap_test_queue().
341  */
342 static int ap_queue_enable_interruption(struct ap_device *ap_dev, void *ind)
343 {
344         struct ap_queue_status status;
345
346         status = ap_queue_interruption_control(ap_dev->qid, ind);
347         switch (status.response_code) {
348         case AP_RESPONSE_NORMAL:
349         case AP_RESPONSE_OTHERWISE_CHANGED:
350                 return 0;
351         case AP_RESPONSE_Q_NOT_AVAIL:
352         case AP_RESPONSE_DECONFIGURED:
353         case AP_RESPONSE_CHECKSTOPPED:
354         case AP_RESPONSE_INVALID_ADDRESS:
355                 pr_err("Registering adapter interrupts for AP %d failed\n",
356                        AP_QID_DEVICE(ap_dev->qid));
357                 return -EOPNOTSUPP;
358         case AP_RESPONSE_RESET_IN_PROGRESS:
359         case AP_RESPONSE_BUSY:
360         default:
361                 return -EBUSY;
362         }
363 }
364
365 static inline struct ap_queue_status
366 __nqap(ap_qid_t qid, unsigned long long psmid, void *msg, size_t length)
367 {
368         typedef struct { char _[length]; } msgblock;
369         register unsigned long reg0 asm ("0") = qid | 0x40000000UL;
370         register struct ap_queue_status reg1 asm ("1");
371         register unsigned long reg2 asm ("2") = (unsigned long) msg;
372         register unsigned long reg3 asm ("3") = (unsigned long) length;
373         register unsigned long reg4 asm ("4") = (unsigned int) (psmid >> 32);
374         register unsigned long reg5 asm ("5") = psmid & 0xffffffff;
375
376         asm volatile (
377                 "0: .long 0xb2ad0042\n"         /* NQAP */
378                 "   brc   2,0b"
379                 : "+d" (reg0), "=d" (reg1), "+d" (reg2), "+d" (reg3)
380                 : "d" (reg4), "d" (reg5), "m" (*(msgblock *) msg)
381                 : "cc");
382         return reg1;
383 }
384
385 /**
386  * __ap_send(): Send message to adjunct processor queue.
387  * @qid: The AP queue number
388  * @psmid: The program supplied message identifier
389  * @msg: The message text
390  * @length: The message length
391  * @special: Special Bit
392  *
393  * Returns AP queue status structure.
394  * Condition code 1 on NQAP can't happen because the L bit is 1.
395  * Condition code 2 on NQAP also means the send is incomplete,
396  * because a segment boundary was reached. The NQAP is repeated.
397  */
398 static inline struct ap_queue_status
399 __ap_send(ap_qid_t qid, unsigned long long psmid, void *msg, size_t length,
400           unsigned int special)
401 {
402         if (special == 1)
403                 qid |= 0x400000UL;
404         return __nqap(qid, psmid, msg, length);
405 }
406
407 int ap_send(ap_qid_t qid, unsigned long long psmid, void *msg, size_t length)
408 {
409         struct ap_queue_status status;
410
411         status = __ap_send(qid, psmid, msg, length, 0);
412         switch (status.response_code) {
413         case AP_RESPONSE_NORMAL:
414                 return 0;
415         case AP_RESPONSE_Q_FULL:
416         case AP_RESPONSE_RESET_IN_PROGRESS:
417                 return -EBUSY;
418         case AP_RESPONSE_REQ_FAC_NOT_INST:
419                 return -EINVAL;
420         default:        /* Device is gone. */
421                 return -ENODEV;
422         }
423 }
424 EXPORT_SYMBOL(ap_send);
425
426 /**
427  * __ap_recv(): Receive message from adjunct processor queue.
428  * @qid: The AP queue number
429  * @psmid: Pointer to program supplied message identifier
430  * @msg: The message text
431  * @length: The message length
432  *
433  * Returns AP queue status structure.
434  * Condition code 1 on DQAP means the receive has taken place
435  * but only partially.  The response is incomplete, hence the
436  * DQAP is repeated.
437  * Condition code 2 on DQAP also means the receive is incomplete,
438  * this time because a segment boundary was reached. Again, the
439  * DQAP is repeated.
440  * Note that gpr2 is used by the DQAP instruction to keep track of
441  * any 'residual' length, in case the instruction gets interrupted.
442  * Hence it gets zeroed before the instruction.
443  */
444 static inline struct ap_queue_status
445 __ap_recv(ap_qid_t qid, unsigned long long *psmid, void *msg, size_t length)
446 {
447         typedef struct { char _[length]; } msgblock;
448         register unsigned long reg0 asm("0") = qid | 0x80000000UL;
449         register struct ap_queue_status reg1 asm ("1");
450         register unsigned long reg2 asm("2") = 0UL;
451         register unsigned long reg4 asm("4") = (unsigned long) msg;
452         register unsigned long reg5 asm("5") = (unsigned long) length;
453         register unsigned long reg6 asm("6") = 0UL;
454         register unsigned long reg7 asm("7") = 0UL;
455
456
457         asm volatile(
458                 "0: .long 0xb2ae0064\n"         /* DQAP */
459                 "   brc   6,0b\n"
460                 : "+d" (reg0), "=d" (reg1), "+d" (reg2),
461                 "+d" (reg4), "+d" (reg5), "+d" (reg6), "+d" (reg7),
462                 "=m" (*(msgblock *) msg) : : "cc" );
463         *psmid = (((unsigned long long) reg6) << 32) + reg7;
464         return reg1;
465 }
466
467 int ap_recv(ap_qid_t qid, unsigned long long *psmid, void *msg, size_t length)
468 {
469         struct ap_queue_status status;
470
471         status = __ap_recv(qid, psmid, msg, length);
472         switch (status.response_code) {
473         case AP_RESPONSE_NORMAL:
474                 return 0;
475         case AP_RESPONSE_NO_PENDING_REPLY:
476                 if (status.queue_empty)
477                         return -ENOENT;
478                 return -EBUSY;
479         case AP_RESPONSE_RESET_IN_PROGRESS:
480                 return -EBUSY;
481         default:
482                 return -ENODEV;
483         }
484 }
485 EXPORT_SYMBOL(ap_recv);
486
487 /**
488  * ap_query_queue(): Check if an AP queue is available.
489  * @qid: The AP queue number
490  * @queue_depth: Pointer to queue depth value
491  * @device_type: Pointer to device type value
492  * @facilities: Pointer to facility indicator
493  */
494 static int ap_query_queue(ap_qid_t qid, int *queue_depth, int *device_type,
495                           unsigned int *facilities)
496 {
497         struct ap_queue_status status;
498         unsigned long info;
499         int nd;
500
501         if (!ap_test_config_card_id(AP_QID_DEVICE(qid)))
502                 return -ENODEV;
503
504         status = ap_test_queue(qid, &info);
505         switch (status.response_code) {
506         case AP_RESPONSE_NORMAL:
507                 *queue_depth = (int)(info & 0xff);
508                 *device_type = (int)((info >> 24) & 0xff);
509                 *facilities = (unsigned int)(info >> 32);
510                 /* Update maximum domain id */
511                 nd = (info >> 16) & 0xff;
512                 if ((info & (1UL << 57)) && nd > 0)
513                         ap_max_domain_id = nd;
514                 return 0;
515         case AP_RESPONSE_Q_NOT_AVAIL:
516         case AP_RESPONSE_DECONFIGURED:
517         case AP_RESPONSE_CHECKSTOPPED:
518         case AP_RESPONSE_INVALID_ADDRESS:
519                 return -ENODEV;
520         case AP_RESPONSE_RESET_IN_PROGRESS:
521         case AP_RESPONSE_OTHERWISE_CHANGED:
522         case AP_RESPONSE_BUSY:
523                 return -EBUSY;
524         default:
525                 BUG();
526         }
527 }
528
529 /* State machine definitions and helpers */
530
531 static void ap_sm_wait(enum ap_wait wait)
532 {
533         ktime_t hr_time;
534
535         switch (wait) {
536         case AP_WAIT_AGAIN:
537         case AP_WAIT_INTERRUPT:
538                 if (ap_using_interrupts())
539                         break;
540                 if (ap_poll_kthread) {
541                         wake_up(&ap_poll_wait);
542                         break;
543                 }
544                 /* Fall through */
545         case AP_WAIT_TIMEOUT:
546                 spin_lock_bh(&ap_poll_timer_lock);
547                 if (!hrtimer_is_queued(&ap_poll_timer)) {
548                         hr_time = ktime_set(0, poll_timeout);
549                         hrtimer_forward_now(&ap_poll_timer, hr_time);
550                         hrtimer_restart(&ap_poll_timer);
551                 }
552                 spin_unlock_bh(&ap_poll_timer_lock);
553                 break;
554         case AP_WAIT_NONE:
555         default:
556                 break;
557         }
558 }
559
560 static enum ap_wait ap_sm_nop(struct ap_device *ap_dev)
561 {
562         return AP_WAIT_NONE;
563 }
564
565 /**
566  * ap_sm_recv(): Receive pending reply messages from an AP device but do
567  *      not change the state of the device.
568  * @ap_dev: pointer to the AP device
569  *
570  * Returns AP_WAIT_NONE, AP_WAIT_AGAIN, or AP_WAIT_INTERRUPT
571  */
572 static struct ap_queue_status ap_sm_recv(struct ap_device *ap_dev)
573 {
574         struct ap_queue_status status;
575         struct ap_message *ap_msg;
576
577         status = __ap_recv(ap_dev->qid, &ap_dev->reply->psmid,
578                            ap_dev->reply->message, ap_dev->reply->length);
579         switch (status.response_code) {
580         case AP_RESPONSE_NORMAL:
581                 atomic_dec(&ap_poll_requests);
582                 ap_dev->queue_count--;
583                 if (ap_dev->queue_count > 0)
584                         mod_timer(&ap_dev->timeout,
585                                   jiffies + ap_dev->drv->request_timeout);
586                 list_for_each_entry(ap_msg, &ap_dev->pendingq, list) {
587                         if (ap_msg->psmid != ap_dev->reply->psmid)
588                                 continue;
589                         list_del_init(&ap_msg->list);
590                         ap_dev->pendingq_count--;
591                         ap_msg->receive(ap_dev, ap_msg, ap_dev->reply);
592                         break;
593                 }
594         case AP_RESPONSE_NO_PENDING_REPLY:
595                 if (!status.queue_empty || ap_dev->queue_count <= 0)
596                         break;
597                 /* The card shouldn't forget requests but who knows. */
598                 atomic_sub(ap_dev->queue_count, &ap_poll_requests);
599                 ap_dev->queue_count = 0;
600                 list_splice_init(&ap_dev->pendingq, &ap_dev->requestq);
601                 ap_dev->requestq_count += ap_dev->pendingq_count;
602                 ap_dev->pendingq_count = 0;
603                 break;
604         default:
605                 break;
606         }
607         return status;
608 }
609
610 /**
611  * ap_sm_read(): Receive pending reply messages from an AP device.
612  * @ap_dev: pointer to the AP device
613  *
614  * Returns AP_WAIT_NONE, AP_WAIT_AGAIN, or AP_WAIT_INTERRUPT
615  */
616 static enum ap_wait ap_sm_read(struct ap_device *ap_dev)
617 {
618         struct ap_queue_status status;
619
620         status = ap_sm_recv(ap_dev);
621         switch (status.response_code) {
622         case AP_RESPONSE_NORMAL:
623                 if (ap_dev->queue_count > 0) {
624                         ap_dev->state = AP_STATE_WORKING;
625                         return AP_WAIT_AGAIN;
626                 }
627                 ap_dev->state = AP_STATE_IDLE;
628                 return AP_WAIT_NONE;
629         case AP_RESPONSE_NO_PENDING_REPLY:
630                 if (ap_dev->queue_count > 0)
631                         return AP_WAIT_INTERRUPT;
632                 ap_dev->state = AP_STATE_IDLE;
633                 return AP_WAIT_NONE;
634         default:
635                 ap_dev->state = AP_STATE_BORKED;
636                 return AP_WAIT_NONE;
637         }
638 }
639
640 /**
641  * ap_sm_write(): Send messages from the request queue to an AP device.
642  * @ap_dev: pointer to the AP device
643  *
644  * Returns AP_WAIT_NONE, AP_WAIT_AGAIN, or AP_WAIT_INTERRUPT
645  */
646 static enum ap_wait ap_sm_write(struct ap_device *ap_dev)
647 {
648         struct ap_queue_status status;
649         struct ap_message *ap_msg;
650
651         if (ap_dev->requestq_count <= 0)
652                 return AP_WAIT_NONE;
653         /* Start the next request on the queue. */
654         ap_msg = list_entry(ap_dev->requestq.next, struct ap_message, list);
655         status = __ap_send(ap_dev->qid, ap_msg->psmid,
656                            ap_msg->message, ap_msg->length, ap_msg->special);
657         switch (status.response_code) {
658         case AP_RESPONSE_NORMAL:
659                 atomic_inc(&ap_poll_requests);
660                 ap_dev->queue_count++;
661                 if (ap_dev->queue_count == 1)
662                         mod_timer(&ap_dev->timeout,
663                                   jiffies + ap_dev->drv->request_timeout);
664                 list_move_tail(&ap_msg->list, &ap_dev->pendingq);
665                 ap_dev->requestq_count--;
666                 ap_dev->pendingq_count++;
667                 if (ap_dev->queue_count < ap_dev->queue_depth) {
668                         ap_dev->state = AP_STATE_WORKING;
669                         return AP_WAIT_AGAIN;
670                 }
671                 /* fall through */
672         case AP_RESPONSE_Q_FULL:
673                 ap_dev->state = AP_STATE_QUEUE_FULL;
674                 return AP_WAIT_INTERRUPT;
675         case AP_RESPONSE_RESET_IN_PROGRESS:
676                 ap_dev->state = AP_STATE_RESET_WAIT;
677                 return AP_WAIT_TIMEOUT;
678         case AP_RESPONSE_MESSAGE_TOO_BIG:
679         case AP_RESPONSE_REQ_FAC_NOT_INST:
680                 list_del_init(&ap_msg->list);
681                 ap_dev->requestq_count--;
682                 ap_msg->rc = -EINVAL;
683                 ap_msg->receive(ap_dev, ap_msg, NULL);
684                 return AP_WAIT_AGAIN;
685         default:
686                 ap_dev->state = AP_STATE_BORKED;
687                 return AP_WAIT_NONE;
688         }
689 }
690
691 /**
692  * ap_sm_read_write(): Send and receive messages to/from an AP device.
693  * @ap_dev: pointer to the AP device
694  *
695  * Returns AP_WAIT_NONE, AP_WAIT_AGAIN, or AP_WAIT_INTERRUPT
696  */
697 static enum ap_wait ap_sm_read_write(struct ap_device *ap_dev)
698 {
699         return min(ap_sm_read(ap_dev), ap_sm_write(ap_dev));
700 }
701
702 /**
703  * ap_sm_reset(): Reset an AP queue.
704  * @qid: The AP queue number
705  *
706  * Submit the Reset command to an AP queue.
707  */
708 static enum ap_wait ap_sm_reset(struct ap_device *ap_dev)
709 {
710         struct ap_queue_status status;
711
712         status = ap_reset_queue(ap_dev->qid);
713         switch (status.response_code) {
714         case AP_RESPONSE_NORMAL:
715         case AP_RESPONSE_RESET_IN_PROGRESS:
716                 ap_dev->state = AP_STATE_RESET_WAIT;
717                 ap_dev->interrupt = AP_INTR_DISABLED;
718                 return AP_WAIT_TIMEOUT;
719         case AP_RESPONSE_BUSY:
720                 return AP_WAIT_TIMEOUT;
721         case AP_RESPONSE_Q_NOT_AVAIL:
722         case AP_RESPONSE_DECONFIGURED:
723         case AP_RESPONSE_CHECKSTOPPED:
724         default:
725                 ap_dev->state = AP_STATE_BORKED;
726                 return AP_WAIT_NONE;
727         }
728 }
729
730 /**
731  * ap_sm_reset_wait(): Test queue for completion of the reset operation
732  * @ap_dev: pointer to the AP device
733  *
734  * Returns AP_POLL_IMMEDIATELY, AP_POLL_AFTER_TIMEROUT or 0.
735  */
736 static enum ap_wait ap_sm_reset_wait(struct ap_device *ap_dev)
737 {
738         struct ap_queue_status status;
739         unsigned long info;
740
741         if (ap_dev->queue_count > 0)
742                 /* Try to read a completed message and get the status */
743                 status = ap_sm_recv(ap_dev);
744         else
745                 /* Get the status with TAPQ */
746                 status = ap_test_queue(ap_dev->qid, &info);
747
748         switch (status.response_code) {
749         case AP_RESPONSE_NORMAL:
750                 if (ap_using_interrupts() &&
751                     ap_queue_enable_interruption(ap_dev,
752                                                  ap_airq.lsi_ptr) == 0)
753                         ap_dev->state = AP_STATE_SETIRQ_WAIT;
754                 else
755                         ap_dev->state = (ap_dev->queue_count > 0) ?
756                                 AP_STATE_WORKING : AP_STATE_IDLE;
757                 return AP_WAIT_AGAIN;
758         case AP_RESPONSE_BUSY:
759         case AP_RESPONSE_RESET_IN_PROGRESS:
760                 return AP_WAIT_TIMEOUT;
761         case AP_RESPONSE_Q_NOT_AVAIL:
762         case AP_RESPONSE_DECONFIGURED:
763         case AP_RESPONSE_CHECKSTOPPED:
764         default:
765                 ap_dev->state = AP_STATE_BORKED;
766                 return AP_WAIT_NONE;
767         }
768 }
769
770 /**
771  * ap_sm_setirq_wait(): Test queue for completion of the irq enablement
772  * @ap_dev: pointer to the AP device
773  *
774  * Returns AP_POLL_IMMEDIATELY, AP_POLL_AFTER_TIMEROUT or 0.
775  */
776 static enum ap_wait ap_sm_setirq_wait(struct ap_device *ap_dev)
777 {
778         struct ap_queue_status status;
779         unsigned long info;
780
781         if (ap_dev->queue_count > 0)
782                 /* Try to read a completed message and get the status */
783                 status = ap_sm_recv(ap_dev);
784         else
785                 /* Get the status with TAPQ */
786                 status = ap_test_queue(ap_dev->qid, &info);
787
788         if (status.int_enabled == 1) {
789                 /* Irqs are now enabled */
790                 ap_dev->interrupt = AP_INTR_ENABLED;
791                 ap_dev->state = (ap_dev->queue_count > 0) ?
792                         AP_STATE_WORKING : AP_STATE_IDLE;
793         }
794
795         switch (status.response_code) {
796         case AP_RESPONSE_NORMAL:
797                 if (ap_dev->queue_count > 0)
798                         return AP_WAIT_AGAIN;
799                 /* fallthrough */
800         case AP_RESPONSE_NO_PENDING_REPLY:
801                 return AP_WAIT_TIMEOUT;
802         default:
803                 ap_dev->state = AP_STATE_BORKED;
804                 return AP_WAIT_NONE;
805         }
806 }
807
808 /*
809  * AP state machine jump table
810  */
811 static ap_func_t *ap_jumptable[NR_AP_STATES][NR_AP_EVENTS] = {
812         [AP_STATE_RESET_START] = {
813                 [AP_EVENT_POLL] = ap_sm_reset,
814                 [AP_EVENT_TIMEOUT] = ap_sm_nop,
815         },
816         [AP_STATE_RESET_WAIT] = {
817                 [AP_EVENT_POLL] = ap_sm_reset_wait,
818                 [AP_EVENT_TIMEOUT] = ap_sm_nop,
819         },
820         [AP_STATE_SETIRQ_WAIT] = {
821                 [AP_EVENT_POLL] = ap_sm_setirq_wait,
822                 [AP_EVENT_TIMEOUT] = ap_sm_nop,
823         },
824         [AP_STATE_IDLE] = {
825                 [AP_EVENT_POLL] = ap_sm_write,
826                 [AP_EVENT_TIMEOUT] = ap_sm_nop,
827         },
828         [AP_STATE_WORKING] = {
829                 [AP_EVENT_POLL] = ap_sm_read_write,
830                 [AP_EVENT_TIMEOUT] = ap_sm_reset,
831         },
832         [AP_STATE_QUEUE_FULL] = {
833                 [AP_EVENT_POLL] = ap_sm_read,
834                 [AP_EVENT_TIMEOUT] = ap_sm_reset,
835         },
836         [AP_STATE_SUSPEND_WAIT] = {
837                 [AP_EVENT_POLL] = ap_sm_read,
838                 [AP_EVENT_TIMEOUT] = ap_sm_nop,
839         },
840         [AP_STATE_BORKED] = {
841                 [AP_EVENT_POLL] = ap_sm_nop,
842                 [AP_EVENT_TIMEOUT] = ap_sm_nop,
843         },
844 };
845
846 static inline enum ap_wait ap_sm_event(struct ap_device *ap_dev,
847                                        enum ap_event event)
848 {
849         return ap_jumptable[ap_dev->state][event](ap_dev);
850 }
851
852 static inline enum ap_wait ap_sm_event_loop(struct ap_device *ap_dev,
853                                             enum ap_event event)
854 {
855         enum ap_wait wait;
856
857         while ((wait = ap_sm_event(ap_dev, event)) == AP_WAIT_AGAIN)
858                 ;
859         return wait;
860 }
861
862 /**
863  * ap_request_timeout(): Handling of request timeouts
864  * @data: Holds the AP device.
865  *
866  * Handles request timeouts.
867  */
868 static void ap_request_timeout(unsigned long data)
869 {
870         struct ap_device *ap_dev = (struct ap_device *) data;
871
872         if (ap_suspend_flag)
873                 return;
874         spin_lock_bh(&ap_dev->lock);
875         ap_sm_wait(ap_sm_event(ap_dev, AP_EVENT_TIMEOUT));
876         spin_unlock_bh(&ap_dev->lock);
877 }
878
879 /**
880  * ap_poll_timeout(): AP receive polling for finished AP requests.
881  * @unused: Unused pointer.
882  *
883  * Schedules the AP tasklet using a high resolution timer.
884  */
885 static enum hrtimer_restart ap_poll_timeout(struct hrtimer *unused)
886 {
887         if (!ap_suspend_flag)
888                 tasklet_schedule(&ap_tasklet);
889         return HRTIMER_NORESTART;
890 }
891
892 /**
893  * ap_interrupt_handler() - Schedule ap_tasklet on interrupt
894  * @airq: pointer to adapter interrupt descriptor
895  */
896 static void ap_interrupt_handler(struct airq_struct *airq)
897 {
898         inc_irq_stat(IRQIO_APB);
899         if (!ap_suspend_flag)
900                 tasklet_schedule(&ap_tasklet);
901 }
902
903 /**
904  * ap_tasklet_fn(): Tasklet to poll all AP devices.
905  * @dummy: Unused variable
906  *
907  * Poll all AP devices on the bus.
908  */
909 static void ap_tasklet_fn(unsigned long dummy)
910 {
911         struct ap_device *ap_dev;
912         enum ap_wait wait = AP_WAIT_NONE;
913
914         /* Reset the indicator if interrupts are used. Thus new interrupts can
915          * be received. Doing it in the beginning of the tasklet is therefor
916          * important that no requests on any AP get lost.
917          */
918         if (ap_using_interrupts())
919                 xchg(ap_airq.lsi_ptr, 0);
920
921         spin_lock(&ap_device_list_lock);
922         list_for_each_entry(ap_dev, &ap_device_list, list) {
923                 spin_lock_bh(&ap_dev->lock);
924                 wait = min(wait, ap_sm_event_loop(ap_dev, AP_EVENT_POLL));
925                 spin_unlock_bh(&ap_dev->lock);
926         }
927         spin_unlock(&ap_device_list_lock);
928         ap_sm_wait(wait);
929 }
930
931 /**
932  * ap_poll_thread(): Thread that polls for finished requests.
933  * @data: Unused pointer
934  *
935  * AP bus poll thread. The purpose of this thread is to poll for
936  * finished requests in a loop if there is a "free" cpu - that is
937  * a cpu that doesn't have anything better to do. The polling stops
938  * as soon as there is another task or if all messages have been
939  * delivered.
940  */
941 static int ap_poll_thread(void *data)
942 {
943         DECLARE_WAITQUEUE(wait, current);
944
945         set_user_nice(current, MAX_NICE);
946         set_freezable();
947         while (!kthread_should_stop()) {
948                 add_wait_queue(&ap_poll_wait, &wait);
949                 set_current_state(TASK_INTERRUPTIBLE);
950                 if (ap_suspend_flag ||
951                     atomic_read(&ap_poll_requests) <= 0) {
952                         schedule();
953                         try_to_freeze();
954                 }
955                 set_current_state(TASK_RUNNING);
956                 remove_wait_queue(&ap_poll_wait, &wait);
957                 if (need_resched()) {
958                         schedule();
959                         try_to_freeze();
960                         continue;
961                 }
962                 ap_tasklet_fn(0);
963         } while (!kthread_should_stop());
964         return 0;
965 }
966
967 static int ap_poll_thread_start(void)
968 {
969         int rc;
970
971         if (ap_using_interrupts() || ap_poll_kthread)
972                 return 0;
973         mutex_lock(&ap_poll_thread_mutex);
974         ap_poll_kthread = kthread_run(ap_poll_thread, NULL, "appoll");
975         rc = PTR_RET(ap_poll_kthread);
976         if (rc)
977                 ap_poll_kthread = NULL;
978         mutex_unlock(&ap_poll_thread_mutex);
979         return rc;
980 }
981
982 static void ap_poll_thread_stop(void)
983 {
984         if (!ap_poll_kthread)
985                 return;
986         mutex_lock(&ap_poll_thread_mutex);
987         kthread_stop(ap_poll_kthread);
988         ap_poll_kthread = NULL;
989         mutex_unlock(&ap_poll_thread_mutex);
990 }
991
992 /**
993  * ap_queue_message(): Queue a request to an AP device.
994  * @ap_dev: The AP device to queue the message to
995  * @ap_msg: The message that is to be added
996  */
997 void ap_queue_message(struct ap_device *ap_dev, struct ap_message *ap_msg)
998 {
999         /* For asynchronous message handling a valid receive-callback
1000          * is required. */
1001         BUG_ON(!ap_msg->receive);
1002
1003         spin_lock_bh(&ap_dev->lock);
1004         /* Queue the message. */
1005         list_add_tail(&ap_msg->list, &ap_dev->requestq);
1006         ap_dev->requestq_count++;
1007         ap_dev->total_request_count++;
1008         /* Send/receive as many request from the queue as possible. */
1009         ap_sm_wait(ap_sm_event_loop(ap_dev, AP_EVENT_POLL));
1010         spin_unlock_bh(&ap_dev->lock);
1011 }
1012 EXPORT_SYMBOL(ap_queue_message);
1013
1014 /**
1015  * ap_cancel_message(): Cancel a crypto request.
1016  * @ap_dev: The AP device that has the message queued
1017  * @ap_msg: The message that is to be removed
1018  *
1019  * Cancel a crypto request. This is done by removing the request
1020  * from the device pending or request queue. Note that the
1021  * request stays on the AP queue. When it finishes the message
1022  * reply will be discarded because the psmid can't be found.
1023  */
1024 void ap_cancel_message(struct ap_device *ap_dev, struct ap_message *ap_msg)
1025 {
1026         struct ap_message *tmp;
1027
1028         spin_lock_bh(&ap_dev->lock);
1029         if (!list_empty(&ap_msg->list)) {
1030                 list_for_each_entry(tmp, &ap_dev->pendingq, list)
1031                         if (tmp->psmid == ap_msg->psmid) {
1032                                 ap_dev->pendingq_count--;
1033                                 goto found;
1034                         }
1035                 ap_dev->requestq_count--;
1036 found:
1037                 list_del_init(&ap_msg->list);
1038         }
1039         spin_unlock_bh(&ap_dev->lock);
1040 }
1041 EXPORT_SYMBOL(ap_cancel_message);
1042
1043 /*
1044  * AP device related attributes.
1045  */
1046 static ssize_t ap_hwtype_show(struct device *dev,
1047                               struct device_attribute *attr, char *buf)
1048 {
1049         struct ap_device *ap_dev = to_ap_dev(dev);
1050         return snprintf(buf, PAGE_SIZE, "%d\n", ap_dev->device_type);
1051 }
1052
1053 static DEVICE_ATTR(hwtype, 0444, ap_hwtype_show, NULL);
1054
1055 static ssize_t ap_raw_hwtype_show(struct device *dev,
1056                               struct device_attribute *attr, char *buf)
1057 {
1058         struct ap_device *ap_dev = to_ap_dev(dev);
1059
1060         return snprintf(buf, PAGE_SIZE, "%d\n", ap_dev->raw_hwtype);
1061 }
1062
1063 static DEVICE_ATTR(raw_hwtype, 0444, ap_raw_hwtype_show, NULL);
1064
1065 static ssize_t ap_depth_show(struct device *dev, struct device_attribute *attr,
1066                              char *buf)
1067 {
1068         struct ap_device *ap_dev = to_ap_dev(dev);
1069         return snprintf(buf, PAGE_SIZE, "%d\n", ap_dev->queue_depth);
1070 }
1071
1072 static DEVICE_ATTR(depth, 0444, ap_depth_show, NULL);
1073 static ssize_t ap_request_count_show(struct device *dev,
1074                                      struct device_attribute *attr,
1075                                      char *buf)
1076 {
1077         struct ap_device *ap_dev = to_ap_dev(dev);
1078         int rc;
1079
1080         spin_lock_bh(&ap_dev->lock);
1081         rc = snprintf(buf, PAGE_SIZE, "%d\n", ap_dev->total_request_count);
1082         spin_unlock_bh(&ap_dev->lock);
1083         return rc;
1084 }
1085
1086 static DEVICE_ATTR(request_count, 0444, ap_request_count_show, NULL);
1087
1088 static ssize_t ap_requestq_count_show(struct device *dev,
1089                                       struct device_attribute *attr, char *buf)
1090 {
1091         struct ap_device *ap_dev = to_ap_dev(dev);
1092         int rc;
1093
1094         spin_lock_bh(&ap_dev->lock);
1095         rc = snprintf(buf, PAGE_SIZE, "%d\n", ap_dev->requestq_count);
1096         spin_unlock_bh(&ap_dev->lock);
1097         return rc;
1098 }
1099
1100 static DEVICE_ATTR(requestq_count, 0444, ap_requestq_count_show, NULL);
1101
1102 static ssize_t ap_pendingq_count_show(struct device *dev,
1103                                       struct device_attribute *attr, char *buf)
1104 {
1105         struct ap_device *ap_dev = to_ap_dev(dev);
1106         int rc;
1107
1108         spin_lock_bh(&ap_dev->lock);
1109         rc = snprintf(buf, PAGE_SIZE, "%d\n", ap_dev->pendingq_count);
1110         spin_unlock_bh(&ap_dev->lock);
1111         return rc;
1112 }
1113
1114 static DEVICE_ATTR(pendingq_count, 0444, ap_pendingq_count_show, NULL);
1115
1116 static ssize_t ap_reset_show(struct device *dev,
1117                                       struct device_attribute *attr, char *buf)
1118 {
1119         struct ap_device *ap_dev = to_ap_dev(dev);
1120         int rc = 0;
1121
1122         spin_lock_bh(&ap_dev->lock);
1123         switch (ap_dev->state) {
1124         case AP_STATE_RESET_START:
1125         case AP_STATE_RESET_WAIT:
1126                 rc = snprintf(buf, PAGE_SIZE, "Reset in progress.\n");
1127                 break;
1128         case AP_STATE_WORKING:
1129         case AP_STATE_QUEUE_FULL:
1130                 rc = snprintf(buf, PAGE_SIZE, "Reset Timer armed.\n");
1131                 break;
1132         default:
1133                 rc = snprintf(buf, PAGE_SIZE, "No Reset Timer set.\n");
1134         }
1135         spin_unlock_bh(&ap_dev->lock);
1136         return rc;
1137 }
1138
1139 static DEVICE_ATTR(reset, 0444, ap_reset_show, NULL);
1140
1141 static ssize_t ap_interrupt_show(struct device *dev,
1142                                       struct device_attribute *attr, char *buf)
1143 {
1144         struct ap_device *ap_dev = to_ap_dev(dev);
1145         int rc = 0;
1146
1147         spin_lock_bh(&ap_dev->lock);
1148         if (ap_dev->state == AP_STATE_SETIRQ_WAIT)
1149                 rc = snprintf(buf, PAGE_SIZE, "Enable Interrupt pending.\n");
1150         else if (ap_dev->interrupt == AP_INTR_ENABLED)
1151                 rc = snprintf(buf, PAGE_SIZE, "Interrupts enabled.\n");
1152         else
1153                 rc = snprintf(buf, PAGE_SIZE, "Interrupts disabled.\n");
1154         spin_unlock_bh(&ap_dev->lock);
1155         return rc;
1156 }
1157
1158 static DEVICE_ATTR(interrupt, 0444, ap_interrupt_show, NULL);
1159
1160 static ssize_t ap_modalias_show(struct device *dev,
1161                                 struct device_attribute *attr, char *buf)
1162 {
1163         return sprintf(buf, "ap:t%02X\n", to_ap_dev(dev)->device_type);
1164 }
1165
1166 static DEVICE_ATTR(modalias, 0444, ap_modalias_show, NULL);
1167
1168 static ssize_t ap_functions_show(struct device *dev,
1169                                  struct device_attribute *attr, char *buf)
1170 {
1171         struct ap_device *ap_dev = to_ap_dev(dev);
1172         return snprintf(buf, PAGE_SIZE, "0x%08X\n", ap_dev->functions);
1173 }
1174
1175 static DEVICE_ATTR(ap_functions, 0444, ap_functions_show, NULL);
1176
1177 static struct attribute *ap_dev_attrs[] = {
1178         &dev_attr_hwtype.attr,
1179         &dev_attr_raw_hwtype.attr,
1180         &dev_attr_depth.attr,
1181         &dev_attr_request_count.attr,
1182         &dev_attr_requestq_count.attr,
1183         &dev_attr_pendingq_count.attr,
1184         &dev_attr_reset.attr,
1185         &dev_attr_interrupt.attr,
1186         &dev_attr_modalias.attr,
1187         &dev_attr_ap_functions.attr,
1188         NULL
1189 };
1190 static struct attribute_group ap_dev_attr_group = {
1191         .attrs = ap_dev_attrs
1192 };
1193
1194 /**
1195  * ap_bus_match()
1196  * @dev: Pointer to device
1197  * @drv: Pointer to device_driver
1198  *
1199  * AP bus driver registration/unregistration.
1200  */
1201 static int ap_bus_match(struct device *dev, struct device_driver *drv)
1202 {
1203         struct ap_device *ap_dev = to_ap_dev(dev);
1204         struct ap_driver *ap_drv = to_ap_drv(drv);
1205         struct ap_device_id *id;
1206
1207         /*
1208          * Compare device type of the device with the list of
1209          * supported types of the device_driver.
1210          */
1211         for (id = ap_drv->ids; id->match_flags; id++) {
1212                 if ((id->match_flags & AP_DEVICE_ID_MATCH_DEVICE_TYPE) &&
1213                     (id->dev_type != ap_dev->device_type))
1214                         continue;
1215                 return 1;
1216         }
1217         return 0;
1218 }
1219
1220 /**
1221  * ap_uevent(): Uevent function for AP devices.
1222  * @dev: Pointer to device
1223  * @env: Pointer to kobj_uevent_env
1224  *
1225  * It sets up a single environment variable DEV_TYPE which contains the
1226  * hardware device type.
1227  */
1228 static int ap_uevent (struct device *dev, struct kobj_uevent_env *env)
1229 {
1230         struct ap_device *ap_dev = to_ap_dev(dev);
1231         int retval = 0;
1232
1233         if (!ap_dev)
1234                 return -ENODEV;
1235
1236         /* Set up DEV_TYPE environment variable. */
1237         retval = add_uevent_var(env, "DEV_TYPE=%04X", ap_dev->device_type);
1238         if (retval)
1239                 return retval;
1240
1241         /* Add MODALIAS= */
1242         retval = add_uevent_var(env, "MODALIAS=ap:t%02X", ap_dev->device_type);
1243
1244         return retval;
1245 }
1246
1247 static int ap_dev_suspend(struct device *dev, pm_message_t state)
1248 {
1249         struct ap_device *ap_dev = to_ap_dev(dev);
1250
1251         /* Poll on the device until all requests are finished. */
1252         spin_lock_bh(&ap_dev->lock);
1253         ap_dev->state = AP_STATE_SUSPEND_WAIT;
1254         while (ap_sm_event(ap_dev, AP_EVENT_POLL) != AP_WAIT_NONE)
1255                 ;
1256         ap_dev->state = AP_STATE_BORKED;
1257         spin_unlock_bh(&ap_dev->lock);
1258         return 0;
1259 }
1260
1261 static int ap_dev_resume(struct device *dev)
1262 {
1263         return 0;
1264 }
1265
1266 static void ap_bus_suspend(void)
1267 {
1268         ap_suspend_flag = 1;
1269         /*
1270          * Disable scanning for devices, thus we do not want to scan
1271          * for them after removing.
1272          */
1273         flush_work(&ap_scan_work);
1274         tasklet_disable(&ap_tasklet);
1275 }
1276
1277 static int __ap_devices_unregister(struct device *dev, void *dummy)
1278 {
1279         device_unregister(dev);
1280         return 0;
1281 }
1282
1283 static void ap_bus_resume(void)
1284 {
1285         int rc;
1286
1287         /* Unconditionally remove all AP devices */
1288         bus_for_each_dev(&ap_bus_type, NULL, NULL, __ap_devices_unregister);
1289         /* Reset thin interrupt setting */
1290         if (ap_interrupts_available() && !ap_using_interrupts()) {
1291                 rc = register_adapter_interrupt(&ap_airq);
1292                 ap_airq_flag = (rc == 0);
1293         }
1294         if (!ap_interrupts_available() && ap_using_interrupts()) {
1295                 unregister_adapter_interrupt(&ap_airq);
1296                 ap_airq_flag = 0;
1297         }
1298         /* Reset domain */
1299         if (!user_set_domain)
1300                 ap_domain_index = -1;
1301         /* Get things going again */
1302         ap_suspend_flag = 0;
1303         if (ap_airq_flag)
1304                 xchg(ap_airq.lsi_ptr, 0);
1305         tasklet_enable(&ap_tasklet);
1306         queue_work(system_long_wq, &ap_scan_work);
1307 }
1308
1309 static int ap_power_event(struct notifier_block *this, unsigned long event,
1310                           void *ptr)
1311 {
1312         switch (event) {
1313         case PM_HIBERNATION_PREPARE:
1314         case PM_SUSPEND_PREPARE:
1315                 ap_bus_suspend();
1316                 break;
1317         case PM_POST_HIBERNATION:
1318         case PM_POST_SUSPEND:
1319                 ap_bus_resume();
1320                 break;
1321         default:
1322                 break;
1323         }
1324         return NOTIFY_DONE;
1325 }
1326 static struct notifier_block ap_power_notifier = {
1327         .notifier_call = ap_power_event,
1328 };
1329
1330 static struct bus_type ap_bus_type = {
1331         .name = "ap",
1332         .match = &ap_bus_match,
1333         .uevent = &ap_uevent,
1334         .suspend = ap_dev_suspend,
1335         .resume = ap_dev_resume,
1336 };
1337
1338 static int ap_device_probe(struct device *dev)
1339 {
1340         struct ap_device *ap_dev = to_ap_dev(dev);
1341         struct ap_driver *ap_drv = to_ap_drv(dev->driver);
1342         int rc;
1343
1344         ap_dev->drv = ap_drv;
1345         rc = ap_drv->probe ? ap_drv->probe(ap_dev) : -ENODEV;
1346         if (rc)
1347                 ap_dev->drv = NULL;
1348         return rc;
1349 }
1350
1351 /**
1352  * __ap_flush_queue(): Flush requests.
1353  * @ap_dev: Pointer to the AP device
1354  *
1355  * Flush all requests from the request/pending queue of an AP device.
1356  */
1357 static void __ap_flush_queue(struct ap_device *ap_dev)
1358 {
1359         struct ap_message *ap_msg, *next;
1360
1361         list_for_each_entry_safe(ap_msg, next, &ap_dev->pendingq, list) {
1362                 list_del_init(&ap_msg->list);
1363                 ap_dev->pendingq_count--;
1364                 ap_msg->rc = -EAGAIN;
1365                 ap_msg->receive(ap_dev, ap_msg, NULL);
1366         }
1367         list_for_each_entry_safe(ap_msg, next, &ap_dev->requestq, list) {
1368                 list_del_init(&ap_msg->list);
1369                 ap_dev->requestq_count--;
1370                 ap_msg->rc = -EAGAIN;
1371                 ap_msg->receive(ap_dev, ap_msg, NULL);
1372         }
1373 }
1374
1375 void ap_flush_queue(struct ap_device *ap_dev)
1376 {
1377         spin_lock_bh(&ap_dev->lock);
1378         __ap_flush_queue(ap_dev);
1379         spin_unlock_bh(&ap_dev->lock);
1380 }
1381 EXPORT_SYMBOL(ap_flush_queue);
1382
1383 static int ap_device_remove(struct device *dev)
1384 {
1385         struct ap_device *ap_dev = to_ap_dev(dev);
1386         struct ap_driver *ap_drv = ap_dev->drv;
1387
1388         ap_flush_queue(ap_dev);
1389         del_timer_sync(&ap_dev->timeout);
1390         spin_lock_bh(&ap_device_list_lock);
1391         list_del_init(&ap_dev->list);
1392         spin_unlock_bh(&ap_device_list_lock);
1393         if (ap_drv->remove)
1394                 ap_drv->remove(ap_dev);
1395         spin_lock_bh(&ap_dev->lock);
1396         atomic_sub(ap_dev->queue_count, &ap_poll_requests);
1397         spin_unlock_bh(&ap_dev->lock);
1398         return 0;
1399 }
1400
1401 static void ap_device_release(struct device *dev)
1402 {
1403         kfree(to_ap_dev(dev));
1404 }
1405
1406 int ap_driver_register(struct ap_driver *ap_drv, struct module *owner,
1407                        char *name)
1408 {
1409         struct device_driver *drv = &ap_drv->driver;
1410
1411         if (!initialised)
1412                 return -ENODEV;
1413
1414         drv->bus = &ap_bus_type;
1415         drv->probe = ap_device_probe;
1416         drv->remove = ap_device_remove;
1417         drv->owner = owner;
1418         drv->name = name;
1419         return driver_register(drv);
1420 }
1421 EXPORT_SYMBOL(ap_driver_register);
1422
1423 void ap_driver_unregister(struct ap_driver *ap_drv)
1424 {
1425         driver_unregister(&ap_drv->driver);
1426 }
1427 EXPORT_SYMBOL(ap_driver_unregister);
1428
1429 void ap_bus_force_rescan(void)
1430 {
1431         if (ap_suspend_flag)
1432                 return;
1433         /* processing a asynchronous bus rescan */
1434         del_timer(&ap_config_timer);
1435         queue_work(system_long_wq, &ap_scan_work);
1436         flush_work(&ap_scan_work);
1437 }
1438 EXPORT_SYMBOL(ap_bus_force_rescan);
1439
1440 /*
1441  * AP bus attributes.
1442  */
1443 static ssize_t ap_domain_show(struct bus_type *bus, char *buf)
1444 {
1445         return snprintf(buf, PAGE_SIZE, "%d\n", ap_domain_index);
1446 }
1447
1448 static BUS_ATTR(ap_domain, 0444, ap_domain_show, NULL);
1449
1450 static ssize_t ap_control_domain_mask_show(struct bus_type *bus, char *buf)
1451 {
1452         if (!ap_configuration)  /* QCI not supported */
1453                 return snprintf(buf, PAGE_SIZE, "not supported\n");
1454         if (!test_facility(76))
1455                 /* format 0 - 16 bit domain field */
1456                 return snprintf(buf, PAGE_SIZE, "%08x%08x\n",
1457                                 ap_configuration->adm[0],
1458                                 ap_configuration->adm[1]);
1459         /* format 1 - 256 bit domain field */
1460         return snprintf(buf, PAGE_SIZE,
1461                         "0x%08x%08x%08x%08x%08x%08x%08x%08x\n",
1462                         ap_configuration->adm[0], ap_configuration->adm[1],
1463                         ap_configuration->adm[2], ap_configuration->adm[3],
1464                         ap_configuration->adm[4], ap_configuration->adm[5],
1465                         ap_configuration->adm[6], ap_configuration->adm[7]);
1466 }
1467
1468 static BUS_ATTR(ap_control_domain_mask, 0444,
1469                 ap_control_domain_mask_show, NULL);
1470
1471 static ssize_t ap_config_time_show(struct bus_type *bus, char *buf)
1472 {
1473         return snprintf(buf, PAGE_SIZE, "%d\n", ap_config_time);
1474 }
1475
1476 static ssize_t ap_interrupts_show(struct bus_type *bus, char *buf)
1477 {
1478         return snprintf(buf, PAGE_SIZE, "%d\n",
1479                         ap_using_interrupts() ? 1 : 0);
1480 }
1481
1482 static BUS_ATTR(ap_interrupts, 0444, ap_interrupts_show, NULL);
1483
1484 static ssize_t ap_config_time_store(struct bus_type *bus,
1485                                     const char *buf, size_t count)
1486 {
1487         int time;
1488
1489         if (sscanf(buf, "%d\n", &time) != 1 || time < 5 || time > 120)
1490                 return -EINVAL;
1491         ap_config_time = time;
1492         mod_timer(&ap_config_timer, jiffies + ap_config_time * HZ);
1493         return count;
1494 }
1495
1496 static BUS_ATTR(config_time, 0644, ap_config_time_show, ap_config_time_store);
1497
1498 static ssize_t ap_poll_thread_show(struct bus_type *bus, char *buf)
1499 {
1500         return snprintf(buf, PAGE_SIZE, "%d\n", ap_poll_kthread ? 1 : 0);
1501 }
1502
1503 static ssize_t ap_poll_thread_store(struct bus_type *bus,
1504                                     const char *buf, size_t count)
1505 {
1506         int flag, rc;
1507
1508         if (sscanf(buf, "%d\n", &flag) != 1)
1509                 return -EINVAL;
1510         if (flag) {
1511                 rc = ap_poll_thread_start();
1512                 if (rc)
1513                         count = rc;
1514         } else
1515                 ap_poll_thread_stop();
1516         return count;
1517 }
1518
1519 static BUS_ATTR(poll_thread, 0644, ap_poll_thread_show, ap_poll_thread_store);
1520
1521 static ssize_t poll_timeout_show(struct bus_type *bus, char *buf)
1522 {
1523         return snprintf(buf, PAGE_SIZE, "%llu\n", poll_timeout);
1524 }
1525
1526 static ssize_t poll_timeout_store(struct bus_type *bus, const char *buf,
1527                                   size_t count)
1528 {
1529         unsigned long long time;
1530         ktime_t hr_time;
1531
1532         /* 120 seconds = maximum poll interval */
1533         if (sscanf(buf, "%llu\n", &time) != 1 || time < 1 ||
1534             time > 120000000000ULL)
1535                 return -EINVAL;
1536         poll_timeout = time;
1537         hr_time = ktime_set(0, poll_timeout);
1538
1539         spin_lock_bh(&ap_poll_timer_lock);
1540         hrtimer_cancel(&ap_poll_timer);
1541         hrtimer_set_expires(&ap_poll_timer, hr_time);
1542         hrtimer_start_expires(&ap_poll_timer, HRTIMER_MODE_ABS);
1543         spin_unlock_bh(&ap_poll_timer_lock);
1544
1545         return count;
1546 }
1547
1548 static BUS_ATTR(poll_timeout, 0644, poll_timeout_show, poll_timeout_store);
1549
1550 static ssize_t ap_max_domain_id_show(struct bus_type *bus, char *buf)
1551 {
1552         int max_domain_id;
1553
1554         if (ap_configuration)
1555                 max_domain_id = ap_max_domain_id ? : -1;
1556         else
1557                 max_domain_id = 15;
1558         return snprintf(buf, PAGE_SIZE, "%d\n", max_domain_id);
1559 }
1560
1561 static BUS_ATTR(ap_max_domain_id, 0444, ap_max_domain_id_show, NULL);
1562
1563 static struct bus_attribute *const ap_bus_attrs[] = {
1564         &bus_attr_ap_domain,
1565         &bus_attr_ap_control_domain_mask,
1566         &bus_attr_config_time,
1567         &bus_attr_poll_thread,
1568         &bus_attr_ap_interrupts,
1569         &bus_attr_poll_timeout,
1570         &bus_attr_ap_max_domain_id,
1571         NULL,
1572 };
1573
1574 /**
1575  * ap_select_domain(): Select an AP domain.
1576  *
1577  * Pick one of the 16 AP domains.
1578  */
1579 static int ap_select_domain(void)
1580 {
1581         int count, max_count, best_domain;
1582         struct ap_queue_status status;
1583         int i, j;
1584
1585         /*
1586          * We want to use a single domain. Either the one specified with
1587          * the "domain=" parameter or the domain with the maximum number
1588          * of devices.
1589          */
1590         if (ap_domain_index >= 0)
1591                 /* Domain has already been selected. */
1592                 return 0;
1593         best_domain = -1;
1594         max_count = 0;
1595         for (i = 0; i < AP_DOMAINS; i++) {
1596                 if (!ap_test_config_domain(i))
1597                         continue;
1598                 count = 0;
1599                 for (j = 0; j < AP_DEVICES; j++) {
1600                         if (!ap_test_config_card_id(j))
1601                                 continue;
1602                         status = ap_test_queue(AP_MKQID(j, i), NULL);
1603                         if (status.response_code != AP_RESPONSE_NORMAL)
1604                                 continue;
1605                         count++;
1606                 }
1607                 if (count > max_count) {
1608                         max_count = count;
1609                         best_domain = i;
1610                 }
1611         }
1612         if (best_domain >= 0){
1613                 ap_domain_index = best_domain;
1614                 return 0;
1615         }
1616         return -ENODEV;
1617 }
1618
1619 /**
1620  * __ap_scan_bus(): Scan the AP bus.
1621  * @dev: Pointer to device
1622  * @data: Pointer to data
1623  *
1624  * Scan the AP bus for new devices.
1625  */
1626 static int __ap_scan_bus(struct device *dev, void *data)
1627 {
1628         return to_ap_dev(dev)->qid == (ap_qid_t)(unsigned long) data;
1629 }
1630
1631 static void ap_scan_bus(struct work_struct *unused)
1632 {
1633         struct ap_device *ap_dev;
1634         struct device *dev;
1635         ap_qid_t qid;
1636         int queue_depth = 0, device_type = 0;
1637         unsigned int device_functions = 0;
1638         int rc, i, borked;
1639
1640         ap_query_configuration();
1641         if (ap_select_domain() != 0)
1642                 goto out;
1643
1644         for (i = 0; i < AP_DEVICES; i++) {
1645                 qid = AP_MKQID(i, ap_domain_index);
1646                 dev = bus_find_device(&ap_bus_type, NULL,
1647                                       (void *)(unsigned long)qid,
1648                                       __ap_scan_bus);
1649                 rc = ap_query_queue(qid, &queue_depth, &device_type,
1650                                     &device_functions);
1651                 if (dev) {
1652                         ap_dev = to_ap_dev(dev);
1653                         spin_lock_bh(&ap_dev->lock);
1654                         if (rc == -ENODEV)
1655                                 ap_dev->state = AP_STATE_BORKED;
1656                         borked = ap_dev->state == AP_STATE_BORKED;
1657                         spin_unlock_bh(&ap_dev->lock);
1658                         if (borked)     /* Remove broken device */
1659                                 device_unregister(dev);
1660                         put_device(dev);
1661                         if (!borked)
1662                                 continue;
1663                 }
1664                 if (rc)
1665                         continue;
1666                 ap_dev = kzalloc(sizeof(*ap_dev), GFP_KERNEL);
1667                 if (!ap_dev)
1668                         break;
1669                 ap_dev->qid = qid;
1670                 ap_dev->state = AP_STATE_RESET_START;
1671                 ap_dev->interrupt = AP_INTR_DISABLED;
1672                 ap_dev->queue_depth = queue_depth;
1673                 ap_dev->raw_hwtype = device_type;
1674                 ap_dev->device_type = device_type;
1675                 ap_dev->functions = device_functions;
1676                 spin_lock_init(&ap_dev->lock);
1677                 INIT_LIST_HEAD(&ap_dev->pendingq);
1678                 INIT_LIST_HEAD(&ap_dev->requestq);
1679                 INIT_LIST_HEAD(&ap_dev->list);
1680                 setup_timer(&ap_dev->timeout, ap_request_timeout,
1681                             (unsigned long) ap_dev);
1682
1683                 ap_dev->device.bus = &ap_bus_type;
1684                 ap_dev->device.parent = ap_root_device;
1685                 rc = dev_set_name(&ap_dev->device, "card%02x",
1686                                   AP_QID_DEVICE(ap_dev->qid));
1687                 if (rc) {
1688                         kfree(ap_dev);
1689                         continue;
1690                 }
1691                 /* Add to list of devices */
1692                 spin_lock_bh(&ap_device_list_lock);
1693                 list_add(&ap_dev->list, &ap_device_list);
1694                 spin_unlock_bh(&ap_device_list_lock);
1695                 /* Start with a device reset */
1696                 spin_lock_bh(&ap_dev->lock);
1697                 ap_sm_wait(ap_sm_event(ap_dev, AP_EVENT_POLL));
1698                 spin_unlock_bh(&ap_dev->lock);
1699                 /* Register device */
1700                 ap_dev->device.release = ap_device_release;
1701                 rc = device_register(&ap_dev->device);
1702                 if (rc) {
1703                         spin_lock_bh(&ap_dev->lock);
1704                         list_del_init(&ap_dev->list);
1705                         spin_unlock_bh(&ap_dev->lock);
1706                         put_device(&ap_dev->device);
1707                         continue;
1708                 }
1709                 /* Add device attributes. */
1710                 rc = sysfs_create_group(&ap_dev->device.kobj,
1711                                         &ap_dev_attr_group);
1712                 if (rc) {
1713                         device_unregister(&ap_dev->device);
1714                         continue;
1715                 }
1716         }
1717 out:
1718         mod_timer(&ap_config_timer, jiffies + ap_config_time * HZ);
1719 }
1720
1721 static void ap_config_timeout(unsigned long ptr)
1722 {
1723         if (ap_suspend_flag)
1724                 return;
1725         queue_work(system_long_wq, &ap_scan_work);
1726 }
1727
1728 static void ap_reset_domain(void)
1729 {
1730         int i;
1731
1732         if (ap_domain_index == -1 || !ap_test_config_domain(ap_domain_index))
1733                 return;
1734         for (i = 0; i < AP_DEVICES; i++)
1735                 ap_reset_queue(AP_MKQID(i, ap_domain_index));
1736 }
1737
1738 static void ap_reset_all(void)
1739 {
1740         int i, j;
1741
1742         for (i = 0; i < AP_DOMAINS; i++) {
1743                 if (!ap_test_config_domain(i))
1744                         continue;
1745                 for (j = 0; j < AP_DEVICES; j++) {
1746                         if (!ap_test_config_card_id(j))
1747                                 continue;
1748                         ap_reset_queue(AP_MKQID(j, i));
1749                 }
1750         }
1751 }
1752
1753 static struct reset_call ap_reset_call = {
1754         .fn = ap_reset_all,
1755 };
1756
1757 /**
1758  * ap_module_init(): The module initialization code.
1759  *
1760  * Initializes the module.
1761  */
1762 int __init ap_module_init(void)
1763 {
1764         int max_domain_id;
1765         int rc, i;
1766
1767         if (ap_instructions_available() != 0) {
1768                 pr_warn("The hardware system does not support AP instructions\n");
1769                 return -ENODEV;
1770         }
1771
1772         /* Get AP configuration data if available */
1773         ap_init_configuration();
1774
1775         if (ap_configuration)
1776                 max_domain_id = ap_max_domain_id ? : (AP_DOMAINS - 1);
1777         else
1778                 max_domain_id = 15;
1779         if (ap_domain_index < -1 || ap_domain_index > max_domain_id) {
1780                 pr_warn("%d is not a valid cryptographic domain\n",
1781                         ap_domain_index);
1782                 return -EINVAL;
1783         }
1784         /* In resume callback we need to know if the user had set the domain.
1785          * If so, we can not just reset it.
1786          */
1787         if (ap_domain_index >= 0)
1788                 user_set_domain = 1;
1789
1790         if (ap_interrupts_available()) {
1791                 rc = register_adapter_interrupt(&ap_airq);
1792                 ap_airq_flag = (rc == 0);
1793         }
1794
1795         register_reset_call(&ap_reset_call);
1796
1797         /* Create /sys/bus/ap. */
1798         rc = bus_register(&ap_bus_type);
1799         if (rc)
1800                 goto out;
1801         for (i = 0; ap_bus_attrs[i]; i++) {
1802                 rc = bus_create_file(&ap_bus_type, ap_bus_attrs[i]);
1803                 if (rc)
1804                         goto out_bus;
1805         }
1806
1807         /* Create /sys/devices/ap. */
1808         ap_root_device = root_device_register("ap");
1809         rc = PTR_RET(ap_root_device);
1810         if (rc)
1811                 goto out_bus;
1812
1813         /* Setup the AP bus rescan timer. */
1814         setup_timer(&ap_config_timer, ap_config_timeout, 0);
1815
1816         /*
1817          * Setup the high resultion poll timer.
1818          * If we are running under z/VM adjust polling to z/VM polling rate.
1819          */
1820         if (MACHINE_IS_VM)
1821                 poll_timeout = 1500000;
1822         spin_lock_init(&ap_poll_timer_lock);
1823         hrtimer_init(&ap_poll_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
1824         ap_poll_timer.function = ap_poll_timeout;
1825
1826         /* Start the low priority AP bus poll thread. */
1827         if (ap_thread_flag) {
1828                 rc = ap_poll_thread_start();
1829                 if (rc)
1830                         goto out_work;
1831         }
1832
1833         rc = register_pm_notifier(&ap_power_notifier);
1834         if (rc)
1835                 goto out_pm;
1836
1837         queue_work(system_long_wq, &ap_scan_work);
1838         initialised = true;
1839
1840         return 0;
1841
1842 out_pm:
1843         ap_poll_thread_stop();
1844 out_work:
1845         hrtimer_cancel(&ap_poll_timer);
1846         root_device_unregister(ap_root_device);
1847 out_bus:
1848         while (i--)
1849                 bus_remove_file(&ap_bus_type, ap_bus_attrs[i]);
1850         bus_unregister(&ap_bus_type);
1851 out:
1852         unregister_reset_call(&ap_reset_call);
1853         if (ap_using_interrupts())
1854                 unregister_adapter_interrupt(&ap_airq);
1855         kfree(ap_configuration);
1856         return rc;
1857 }
1858
1859 /**
1860  * ap_modules_exit(): The module termination code
1861  *
1862  * Terminates the module.
1863  */
1864 void ap_module_exit(void)
1865 {
1866         int i;
1867
1868         initialised = false;
1869         ap_reset_domain();
1870         ap_poll_thread_stop();
1871         del_timer_sync(&ap_config_timer);
1872         hrtimer_cancel(&ap_poll_timer);
1873         tasklet_kill(&ap_tasklet);
1874         bus_for_each_dev(&ap_bus_type, NULL, NULL, __ap_devices_unregister);
1875         for (i = 0; ap_bus_attrs[i]; i++)
1876                 bus_remove_file(&ap_bus_type, ap_bus_attrs[i]);
1877         unregister_pm_notifier(&ap_power_notifier);
1878         root_device_unregister(ap_root_device);
1879         bus_unregister(&ap_bus_type);
1880         kfree(ap_configuration);
1881         unregister_reset_call(&ap_reset_call);
1882         if (ap_using_interrupts())
1883                 unregister_adapter_interrupt(&ap_airq);
1884 }
1885
1886 module_init(ap_module_init);
1887 module_exit(ap_module_exit);