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