GNU Linux-libre 4.14.332-gnu1
[releases.git] / arch / powerpc / kernel / eeh.c
1 /*
2  * Copyright IBM Corporation 2001, 2005, 2006
3  * Copyright Dave Engebretsen & Todd Inglett 2001
4  * Copyright Linas Vepstas 2005, 2006
5  * Copyright 2001-2012 IBM Corporation.
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20  *
21  * Please address comments and feedback to Linas Vepstas <linas@austin.ibm.com>
22  */
23
24 #include <linux/delay.h>
25 #include <linux/sched.h>
26 #include <linux/init.h>
27 #include <linux/list.h>
28 #include <linux/pci.h>
29 #include <linux/iommu.h>
30 #include <linux/proc_fs.h>
31 #include <linux/rbtree.h>
32 #include <linux/reboot.h>
33 #include <linux/seq_file.h>
34 #include <linux/spinlock.h>
35 #include <linux/export.h>
36 #include <linux/of.h>
37
38 #include <linux/atomic.h>
39 #include <asm/debugfs.h>
40 #include <asm/eeh.h>
41 #include <asm/eeh_event.h>
42 #include <asm/io.h>
43 #include <asm/iommu.h>
44 #include <asm/machdep.h>
45 #include <asm/ppc-pci.h>
46 #include <asm/rtas.h>
47 #include <asm/pte-walk.h>
48
49
50 /** Overview:
51  *  EEH, or "Enhanced Error Handling" is a PCI bridge technology for
52  *  dealing with PCI bus errors that can't be dealt with within the
53  *  usual PCI framework, except by check-stopping the CPU.  Systems
54  *  that are designed for high-availability/reliability cannot afford
55  *  to crash due to a "mere" PCI error, thus the need for EEH.
56  *  An EEH-capable bridge operates by converting a detected error
57  *  into a "slot freeze", taking the PCI adapter off-line, making
58  *  the slot behave, from the OS'es point of view, as if the slot
59  *  were "empty": all reads return 0xff's and all writes are silently
60  *  ignored.  EEH slot isolation events can be triggered by parity
61  *  errors on the address or data busses (e.g. during posted writes),
62  *  which in turn might be caused by low voltage on the bus, dust,
63  *  vibration, humidity, radioactivity or plain-old failed hardware.
64  *
65  *  Note, however, that one of the leading causes of EEH slot
66  *  freeze events are buggy device drivers, buggy device microcode,
67  *  or buggy device hardware.  This is because any attempt by the
68  *  device to bus-master data to a memory address that is not
69  *  assigned to the device will trigger a slot freeze.   (The idea
70  *  is to prevent devices-gone-wild from corrupting system memory).
71  *  Buggy hardware/drivers will have a miserable time co-existing
72  *  with EEH.
73  *
74  *  Ideally, a PCI device driver, when suspecting that an isolation
75  *  event has occurred (e.g. by reading 0xff's), will then ask EEH
76  *  whether this is the case, and then take appropriate steps to
77  *  reset the PCI slot, the PCI device, and then resume operations.
78  *  However, until that day,  the checking is done here, with the
79  *  eeh_check_failure() routine embedded in the MMIO macros.  If
80  *  the slot is found to be isolated, an "EEH Event" is synthesized
81  *  and sent out for processing.
82  */
83
84 /* If a device driver keeps reading an MMIO register in an interrupt
85  * handler after a slot isolation event, it might be broken.
86  * This sets the threshold for how many read attempts we allow
87  * before printing an error message.
88  */
89 #define EEH_MAX_FAILS   2100000
90
91 /* Time to wait for a PCI slot to report status, in milliseconds */
92 #define PCI_BUS_RESET_WAIT_MSEC (5*60*1000)
93
94 /*
95  * EEH probe mode support, which is part of the flags,
96  * is to support multiple platforms for EEH. Some platforms
97  * like pSeries do PCI emunation based on device tree.
98  * However, other platforms like powernv probe PCI devices
99  * from hardware. The flag is used to distinguish that.
100  * In addition, struct eeh_ops::probe would be invoked for
101  * particular OF node or PCI device so that the corresponding
102  * PE would be created there.
103  */
104 int eeh_subsystem_flags;
105 EXPORT_SYMBOL(eeh_subsystem_flags);
106
107 /*
108  * EEH allowed maximal frozen times. If one particular PE's
109  * frozen count in last hour exceeds this limit, the PE will
110  * be forced to be offline permanently.
111  */
112 int eeh_max_freezes = 5;
113
114 /* Platform dependent EEH operations */
115 struct eeh_ops *eeh_ops = NULL;
116
117 /* Lock to avoid races due to multiple reports of an error */
118 DEFINE_RAW_SPINLOCK(confirm_error_lock);
119 EXPORT_SYMBOL_GPL(confirm_error_lock);
120
121 /* Lock to protect passed flags */
122 static DEFINE_MUTEX(eeh_dev_mutex);
123
124 /* Buffer for reporting pci register dumps. Its here in BSS, and
125  * not dynamically alloced, so that it ends up in RMO where RTAS
126  * can access it.
127  */
128 #define EEH_PCI_REGS_LOG_LEN 8192
129 static unsigned char pci_regs_buf[EEH_PCI_REGS_LOG_LEN];
130
131 /*
132  * The struct is used to maintain the EEH global statistic
133  * information. Besides, the EEH global statistics will be
134  * exported to user space through procfs
135  */
136 struct eeh_stats {
137         u64 no_device;          /* PCI device not found         */
138         u64 no_dn;              /* OF node not found            */
139         u64 no_cfg_addr;        /* Config address not found     */
140         u64 ignored_check;      /* EEH check skipped            */
141         u64 total_mmio_ffs;     /* Total EEH checks             */
142         u64 false_positives;    /* Unnecessary EEH checks       */
143         u64 slot_resets;        /* PE reset                     */
144 };
145
146 static struct eeh_stats eeh_stats;
147
148 static int __init eeh_setup(char *str)
149 {
150         if (!strcmp(str, "off"))
151                 eeh_add_flag(EEH_FORCE_DISABLED);
152         else if (!strcmp(str, "early_log"))
153                 eeh_add_flag(EEH_EARLY_DUMP_LOG);
154
155         return 1;
156 }
157 __setup("eeh=", eeh_setup);
158
159 /*
160  * This routine captures assorted PCI configuration space data
161  * for the indicated PCI device, and puts them into a buffer
162  * for RTAS error logging.
163  */
164 static size_t eeh_dump_dev_log(struct eeh_dev *edev, char *buf, size_t len)
165 {
166         struct pci_dn *pdn = eeh_dev_to_pdn(edev);
167         u32 cfg;
168         int cap, i;
169         int n = 0, l = 0;
170         char buffer[128];
171
172         if (!pdn) {
173                 pr_warn("EEH: Note: No error log for absent device.\n");
174                 return 0;
175         }
176
177         n += scnprintf(buf+n, len-n, "%04x:%02x:%02x.%01x\n",
178                        pdn->phb->global_number, pdn->busno,
179                        PCI_SLOT(pdn->devfn), PCI_FUNC(pdn->devfn));
180         pr_warn("EEH: of node=%04x:%02x:%02x.%01x\n",
181                 pdn->phb->global_number, pdn->busno,
182                 PCI_SLOT(pdn->devfn), PCI_FUNC(pdn->devfn));
183
184         eeh_ops->read_config(pdn, PCI_VENDOR_ID, 4, &cfg);
185         n += scnprintf(buf+n, len-n, "dev/vend:%08x\n", cfg);
186         pr_warn("EEH: PCI device/vendor: %08x\n", cfg);
187
188         eeh_ops->read_config(pdn, PCI_COMMAND, 4, &cfg);
189         n += scnprintf(buf+n, len-n, "cmd/stat:%x\n", cfg);
190         pr_warn("EEH: PCI cmd/status register: %08x\n", cfg);
191
192         /* Gather bridge-specific registers */
193         if (edev->mode & EEH_DEV_BRIDGE) {
194                 eeh_ops->read_config(pdn, PCI_SEC_STATUS, 2, &cfg);
195                 n += scnprintf(buf+n, len-n, "sec stat:%x\n", cfg);
196                 pr_warn("EEH: Bridge secondary status: %04x\n", cfg);
197
198                 eeh_ops->read_config(pdn, PCI_BRIDGE_CONTROL, 2, &cfg);
199                 n += scnprintf(buf+n, len-n, "brdg ctl:%x\n", cfg);
200                 pr_warn("EEH: Bridge control: %04x\n", cfg);
201         }
202
203         /* Dump out the PCI-X command and status regs */
204         cap = edev->pcix_cap;
205         if (cap) {
206                 eeh_ops->read_config(pdn, cap, 4, &cfg);
207                 n += scnprintf(buf+n, len-n, "pcix-cmd:%x\n", cfg);
208                 pr_warn("EEH: PCI-X cmd: %08x\n", cfg);
209
210                 eeh_ops->read_config(pdn, cap+4, 4, &cfg);
211                 n += scnprintf(buf+n, len-n, "pcix-stat:%x\n", cfg);
212                 pr_warn("EEH: PCI-X status: %08x\n", cfg);
213         }
214
215         /* If PCI-E capable, dump PCI-E cap 10 */
216         cap = edev->pcie_cap;
217         if (cap) {
218                 n += scnprintf(buf+n, len-n, "pci-e cap10:\n");
219                 pr_warn("EEH: PCI-E capabilities and status follow:\n");
220
221                 for (i=0; i<=8; i++) {
222                         eeh_ops->read_config(pdn, cap+4*i, 4, &cfg);
223                         n += scnprintf(buf+n, len-n, "%02x:%x\n", 4*i, cfg);
224
225                         if ((i % 4) == 0) {
226                                 if (i != 0)
227                                         pr_warn("%s\n", buffer);
228
229                                 l = scnprintf(buffer, sizeof(buffer),
230                                               "EEH: PCI-E %02x: %08x ",
231                                               4*i, cfg);
232                         } else {
233                                 l += scnprintf(buffer+l, sizeof(buffer)-l,
234                                                "%08x ", cfg);
235                         }
236
237                 }
238
239                 pr_warn("%s\n", buffer);
240         }
241
242         /* If AER capable, dump it */
243         cap = edev->aer_cap;
244         if (cap) {
245                 n += scnprintf(buf+n, len-n, "pci-e AER:\n");
246                 pr_warn("EEH: PCI-E AER capability register set follows:\n");
247
248                 for (i=0; i<=13; i++) {
249                         eeh_ops->read_config(pdn, cap+4*i, 4, &cfg);
250                         n += scnprintf(buf+n, len-n, "%02x:%x\n", 4*i, cfg);
251
252                         if ((i % 4) == 0) {
253                                 if (i != 0)
254                                         pr_warn("%s\n", buffer);
255
256                                 l = scnprintf(buffer, sizeof(buffer),
257                                               "EEH: PCI-E AER %02x: %08x ",
258                                               4*i, cfg);
259                         } else {
260                                 l += scnprintf(buffer+l, sizeof(buffer)-l,
261                                                "%08x ", cfg);
262                         }
263                 }
264
265                 pr_warn("%s\n", buffer);
266         }
267
268         return n;
269 }
270
271 static void *eeh_dump_pe_log(void *data, void *flag)
272 {
273         struct eeh_pe *pe = data;
274         struct eeh_dev *edev, *tmp;
275         size_t *plen = flag;
276
277         eeh_pe_for_each_dev(pe, edev, tmp)
278                 *plen += eeh_dump_dev_log(edev, pci_regs_buf + *plen,
279                                           EEH_PCI_REGS_LOG_LEN - *plen);
280
281         return NULL;
282 }
283
284 /**
285  * eeh_slot_error_detail - Generate combined log including driver log and error log
286  * @pe: EEH PE
287  * @severity: temporary or permanent error log
288  *
289  * This routine should be called to generate the combined log, which
290  * is comprised of driver log and error log. The driver log is figured
291  * out from the config space of the corresponding PCI device, while
292  * the error log is fetched through platform dependent function call.
293  */
294 void eeh_slot_error_detail(struct eeh_pe *pe, int severity)
295 {
296         size_t loglen = 0;
297
298         /*
299          * When the PHB is fenced or dead, it's pointless to collect
300          * the data from PCI config space because it should return
301          * 0xFF's. For ER, we still retrieve the data from the PCI
302          * config space.
303          *
304          * For pHyp, we have to enable IO for log retrieval. Otherwise,
305          * 0xFF's is always returned from PCI config space.
306          *
307          * When the @severity is EEH_LOG_PERM, the PE is going to be
308          * removed. Prior to that, the drivers for devices included in
309          * the PE will be closed. The drivers rely on working IO path
310          * to bring the devices to quiet state. Otherwise, PCI traffic
311          * from those devices after they are removed is like to cause
312          * another unexpected EEH error.
313          */
314         if (!(pe->type & EEH_PE_PHB)) {
315                 if (eeh_has_flag(EEH_ENABLE_IO_FOR_LOG) ||
316                     severity == EEH_LOG_PERM)
317                         eeh_pci_enable(pe, EEH_OPT_THAW_MMIO);
318
319                 /*
320                  * The config space of some PCI devices can't be accessed
321                  * when their PEs are in frozen state. Otherwise, fenced
322                  * PHB might be seen. Those PEs are identified with flag
323                  * EEH_PE_CFG_RESTRICTED, indicating EEH_PE_CFG_BLOCKED
324                  * is set automatically when the PE is put to EEH_PE_ISOLATED.
325                  *
326                  * Restoring BARs possibly triggers PCI config access in
327                  * (OPAL) firmware and then causes fenced PHB. If the
328                  * PCI config is blocked with flag EEH_PE_CFG_BLOCKED, it's
329                  * pointless to restore BARs and dump config space.
330                  */
331                 eeh_ops->configure_bridge(pe);
332                 if (!(pe->state & EEH_PE_CFG_BLOCKED)) {
333                         eeh_pe_restore_bars(pe);
334
335                         pci_regs_buf[0] = 0;
336                         eeh_pe_traverse(pe, eeh_dump_pe_log, &loglen);
337                 }
338         }
339
340         eeh_ops->get_log(pe, severity, pci_regs_buf, loglen);
341 }
342
343 /**
344  * eeh_token_to_phys - Convert EEH address token to phys address
345  * @token: I/O token, should be address in the form 0xA....
346  *
347  * This routine should be called to convert virtual I/O address
348  * to physical one.
349  */
350 static inline unsigned long eeh_token_to_phys(unsigned long token)
351 {
352         pte_t *ptep;
353         unsigned long pa;
354         int hugepage_shift;
355
356         /*
357          * We won't find hugepages here(this is iomem). Hence we are not
358          * worried about _PAGE_SPLITTING/collapse. Also we will not hit
359          * page table free, because of init_mm.
360          */
361         ptep = find_init_mm_pte(token, &hugepage_shift);
362         if (!ptep)
363                 return token;
364
365         pa = pte_pfn(*ptep);
366
367         /* On radix we can do hugepage mappings for io, so handle that */
368         if (!hugepage_shift)
369                 hugepage_shift = PAGE_SHIFT;
370
371         pa <<= PAGE_SHIFT;
372         pa |= token & ((1ul << hugepage_shift) - 1);
373         return pa;
374 }
375
376 /*
377  * On PowerNV platform, we might already have fenced PHB there.
378  * For that case, it's meaningless to recover frozen PE. Intead,
379  * We have to handle fenced PHB firstly.
380  */
381 static int eeh_phb_check_failure(struct eeh_pe *pe)
382 {
383         struct eeh_pe *phb_pe;
384         unsigned long flags;
385         int ret;
386
387         if (!eeh_has_flag(EEH_PROBE_MODE_DEV))
388                 return -EPERM;
389
390         /* Find the PHB PE */
391         phb_pe = eeh_phb_pe_get(pe->phb);
392         if (!phb_pe) {
393                 pr_warn("%s Can't find PE for PHB#%x\n",
394                         __func__, pe->phb->global_number);
395                 return -EEXIST;
396         }
397
398         /* If the PHB has been in problematic state */
399         eeh_serialize_lock(&flags);
400         if (phb_pe->state & EEH_PE_ISOLATED) {
401                 ret = 0;
402                 goto out;
403         }
404
405         /* Check PHB state */
406         ret = eeh_ops->get_state(phb_pe, NULL);
407         if ((ret < 0) ||
408             (ret == EEH_STATE_NOT_SUPPORT) ||
409             (ret & (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE)) ==
410             (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE)) {
411                 ret = 0;
412                 goto out;
413         }
414
415         /* Isolate the PHB and send event */
416         eeh_pe_state_mark(phb_pe, EEH_PE_ISOLATED);
417         eeh_serialize_unlock(flags);
418
419         pr_err("EEH: PHB#%x failure detected, location: %s\n",
420                 phb_pe->phb->global_number, eeh_pe_loc_get(phb_pe));
421         dump_stack();
422         eeh_send_failure_event(phb_pe);
423
424         return 1;
425 out:
426         eeh_serialize_unlock(flags);
427         return ret;
428 }
429
430 /**
431  * eeh_dev_check_failure - Check if all 1's data is due to EEH slot freeze
432  * @edev: eeh device
433  *
434  * Check for an EEH failure for the given device node.  Call this
435  * routine if the result of a read was all 0xff's and you want to
436  * find out if this is due to an EEH slot freeze.  This routine
437  * will query firmware for the EEH status.
438  *
439  * Returns 0 if there has not been an EEH error; otherwise returns
440  * a non-zero value and queues up a slot isolation event notification.
441  *
442  * It is safe to call this routine in an interrupt context.
443  */
444 int eeh_dev_check_failure(struct eeh_dev *edev)
445 {
446         int ret;
447         int active_flags = (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE);
448         unsigned long flags;
449         struct device_node *dn;
450         struct pci_dev *dev;
451         struct eeh_pe *pe, *parent_pe, *phb_pe;
452         int rc = 0;
453         const char *location = NULL;
454
455         eeh_stats.total_mmio_ffs++;
456
457         if (!eeh_enabled())
458                 return 0;
459
460         if (!edev) {
461                 eeh_stats.no_dn++;
462                 return 0;
463         }
464         dev = eeh_dev_to_pci_dev(edev);
465         pe = eeh_dev_to_pe(edev);
466
467         /* Access to IO BARs might get this far and still not want checking. */
468         if (!pe) {
469                 eeh_stats.ignored_check++;
470                 pr_debug("EEH: Ignored check for %s\n",
471                         eeh_pci_name(dev));
472                 return 0;
473         }
474
475         if (!pe->addr && !pe->config_addr) {
476                 eeh_stats.no_cfg_addr++;
477                 return 0;
478         }
479
480         /*
481          * On PowerNV platform, we might already have fenced PHB
482          * there and we need take care of that firstly.
483          */
484         ret = eeh_phb_check_failure(pe);
485         if (ret > 0)
486                 return ret;
487
488         /*
489          * If the PE isn't owned by us, we shouldn't check the
490          * state. Instead, let the owner handle it if the PE has
491          * been frozen.
492          */
493         if (eeh_pe_passed(pe))
494                 return 0;
495
496         /* If we already have a pending isolation event for this
497          * slot, we know it's bad already, we don't need to check.
498          * Do this checking under a lock; as multiple PCI devices
499          * in one slot might report errors simultaneously, and we
500          * only want one error recovery routine running.
501          */
502         eeh_serialize_lock(&flags);
503         rc = 1;
504         if (pe->state & EEH_PE_ISOLATED) {
505                 pe->check_count++;
506                 if (pe->check_count == EEH_MAX_FAILS) {
507                         dn = pci_device_to_OF_node(dev);
508                         if (dn)
509                                 location = of_get_property(dn, "ibm,loc-code",
510                                                 NULL);
511                         printk(KERN_ERR "EEH: %d reads ignored for recovering device at "
512                                 "location=%s driver=%s pci addr=%s\n",
513                                 pe->check_count,
514                                 location ? location : "unknown",
515                                 eeh_driver_name(dev), eeh_pci_name(dev));
516                         printk(KERN_ERR "EEH: Might be infinite loop in %s driver\n",
517                                 eeh_driver_name(dev));
518                         dump_stack();
519                 }
520                 goto dn_unlock;
521         }
522
523         /*
524          * Now test for an EEH failure.  This is VERY expensive.
525          * Note that the eeh_config_addr may be a parent device
526          * in the case of a device behind a bridge, or it may be
527          * function zero of a multi-function device.
528          * In any case they must share a common PHB.
529          */
530         ret = eeh_ops->get_state(pe, NULL);
531
532         /* Note that config-io to empty slots may fail;
533          * they are empty when they don't have children.
534          * We will punt with the following conditions: Failure to get
535          * PE's state, EEH not support and Permanently unavailable
536          * state, PE is in good state.
537          */
538         if ((ret < 0) ||
539             (ret == EEH_STATE_NOT_SUPPORT) ||
540             ((ret & active_flags) == active_flags)) {
541                 eeh_stats.false_positives++;
542                 pe->false_positives++;
543                 rc = 0;
544                 goto dn_unlock;
545         }
546
547         /*
548          * It should be corner case that the parent PE has been
549          * put into frozen state as well. We should take care
550          * that at first.
551          */
552         parent_pe = pe->parent;
553         while (parent_pe) {
554                 /* Hit the ceiling ? */
555                 if (parent_pe->type & EEH_PE_PHB)
556                         break;
557
558                 /* Frozen parent PE ? */
559                 ret = eeh_ops->get_state(parent_pe, NULL);
560                 if (ret > 0 &&
561                     (ret & active_flags) != active_flags)
562                         pe = parent_pe;
563
564                 /* Next parent level */
565                 parent_pe = parent_pe->parent;
566         }
567
568         eeh_stats.slot_resets++;
569
570         /* Avoid repeated reports of this failure, including problems
571          * with other functions on this device, and functions under
572          * bridges.
573          */
574         eeh_pe_state_mark(pe, EEH_PE_ISOLATED);
575         eeh_serialize_unlock(flags);
576
577         /* Most EEH events are due to device driver bugs.  Having
578          * a stack trace will help the device-driver authors figure
579          * out what happened.  So print that out.
580          */
581         phb_pe = eeh_phb_pe_get(pe->phb);
582         pr_err("EEH: Frozen PHB#%x-PE#%x detected\n",
583                pe->phb->global_number, pe->addr);
584         pr_err("EEH: PE location: %s, PHB location: %s\n",
585                eeh_pe_loc_get(pe), eeh_pe_loc_get(phb_pe));
586         dump_stack();
587
588         eeh_send_failure_event(pe);
589
590         return 1;
591
592 dn_unlock:
593         eeh_serialize_unlock(flags);
594         return rc;
595 }
596
597 EXPORT_SYMBOL_GPL(eeh_dev_check_failure);
598
599 /**
600  * eeh_check_failure - Check if all 1's data is due to EEH slot freeze
601  * @token: I/O address
602  *
603  * Check for an EEH failure at the given I/O address. Call this
604  * routine if the result of a read was all 0xff's and you want to
605  * find out if this is due to an EEH slot freeze event. This routine
606  * will query firmware for the EEH status.
607  *
608  * Note this routine is safe to call in an interrupt context.
609  */
610 int eeh_check_failure(const volatile void __iomem *token)
611 {
612         unsigned long addr;
613         struct eeh_dev *edev;
614
615         /* Finding the phys addr + pci device; this is pretty quick. */
616         addr = eeh_token_to_phys((unsigned long __force) token);
617         edev = eeh_addr_cache_get_dev(addr);
618         if (!edev) {
619                 eeh_stats.no_device++;
620                 return 0;
621         }
622
623         return eeh_dev_check_failure(edev);
624 }
625 EXPORT_SYMBOL(eeh_check_failure);
626
627
628 /**
629  * eeh_pci_enable - Enable MMIO or DMA transfers for this slot
630  * @pe: EEH PE
631  *
632  * This routine should be called to reenable frozen MMIO or DMA
633  * so that it would work correctly again. It's useful while doing
634  * recovery or log collection on the indicated device.
635  */
636 int eeh_pci_enable(struct eeh_pe *pe, int function)
637 {
638         int active_flag, rc;
639
640         /*
641          * pHyp doesn't allow to enable IO or DMA on unfrozen PE.
642          * Also, it's pointless to enable them on unfrozen PE. So
643          * we have to check before enabling IO or DMA.
644          */
645         switch (function) {
646         case EEH_OPT_THAW_MMIO:
647                 active_flag = EEH_STATE_MMIO_ACTIVE | EEH_STATE_MMIO_ENABLED;
648                 break;
649         case EEH_OPT_THAW_DMA:
650                 active_flag = EEH_STATE_DMA_ACTIVE;
651                 break;
652         case EEH_OPT_DISABLE:
653         case EEH_OPT_ENABLE:
654         case EEH_OPT_FREEZE_PE:
655                 active_flag = 0;
656                 break;
657         default:
658                 pr_warn("%s: Invalid function %d\n",
659                         __func__, function);
660                 return -EINVAL;
661         }
662
663         /*
664          * Check if IO or DMA has been enabled before
665          * enabling them.
666          */
667         if (active_flag) {
668                 rc = eeh_ops->get_state(pe, NULL);
669                 if (rc < 0)
670                         return rc;
671
672                 /* Needn't enable it at all */
673                 if (rc == EEH_STATE_NOT_SUPPORT)
674                         return 0;
675
676                 /* It's already enabled */
677                 if (rc & active_flag)
678                         return 0;
679         }
680
681
682         /* Issue the request */
683         rc = eeh_ops->set_option(pe, function);
684         if (rc)
685                 pr_warn("%s: Unexpected state change %d on "
686                         "PHB#%x-PE#%x, err=%d\n",
687                         __func__, function, pe->phb->global_number,
688                         pe->addr, rc);
689
690         /* Check if the request is finished successfully */
691         if (active_flag) {
692                 rc = eeh_ops->wait_state(pe, PCI_BUS_RESET_WAIT_MSEC);
693                 if (rc < 0)
694                         return rc;
695
696                 if (rc & active_flag)
697                         return 0;
698
699                 return -EIO;
700         }
701
702         return rc;
703 }
704
705 static void *eeh_disable_and_save_dev_state(void *data, void *userdata)
706 {
707         struct eeh_dev *edev = data;
708         struct pci_dev *pdev = eeh_dev_to_pci_dev(edev);
709         struct pci_dev *dev = userdata;
710
711         /*
712          * The caller should have disabled and saved the
713          * state for the specified device
714          */
715         if (!pdev || pdev == dev)
716                 return NULL;
717
718         /* Ensure we have D0 power state */
719         pci_set_power_state(pdev, PCI_D0);
720
721         /* Save device state */
722         pci_save_state(pdev);
723
724         /*
725          * Disable device to avoid any DMA traffic and
726          * interrupt from the device
727          */
728         pci_write_config_word(pdev, PCI_COMMAND, PCI_COMMAND_INTX_DISABLE);
729
730         return NULL;
731 }
732
733 static void *eeh_restore_dev_state(void *data, void *userdata)
734 {
735         struct eeh_dev *edev = data;
736         struct pci_dn *pdn = eeh_dev_to_pdn(edev);
737         struct pci_dev *pdev = eeh_dev_to_pci_dev(edev);
738         struct pci_dev *dev = userdata;
739
740         if (!pdev)
741                 return NULL;
742
743         /* Apply customization from firmware */
744         if (pdn && eeh_ops->restore_config)
745                 eeh_ops->restore_config(pdn);
746
747         /* The caller should restore state for the specified device */
748         if (pdev != dev)
749                 pci_restore_state(pdev);
750
751         return NULL;
752 }
753
754 /**
755  * pcibios_set_pcie_reset_state - Set PCI-E reset state
756  * @dev: pci device struct
757  * @state: reset state to enter
758  *
759  * Return value:
760  *      0 if success
761  */
762 int pcibios_set_pcie_reset_state(struct pci_dev *dev, enum pcie_reset_state state)
763 {
764         struct eeh_dev *edev = pci_dev_to_eeh_dev(dev);
765         struct eeh_pe *pe = eeh_dev_to_pe(edev);
766
767         if (!pe) {
768                 pr_err("%s: No PE found on PCI device %s\n",
769                         __func__, pci_name(dev));
770                 return -EINVAL;
771         }
772
773         switch (state) {
774         case pcie_deassert_reset:
775                 eeh_ops->reset(pe, EEH_RESET_DEACTIVATE);
776                 eeh_unfreeze_pe(pe, false);
777                 if (!(pe->type & EEH_PE_VF))
778                         eeh_pe_state_clear(pe, EEH_PE_CFG_BLOCKED);
779                 eeh_pe_dev_traverse(pe, eeh_restore_dev_state, dev);
780                 eeh_pe_state_clear(pe, EEH_PE_ISOLATED);
781                 break;
782         case pcie_hot_reset:
783                 eeh_pe_state_mark_with_cfg(pe, EEH_PE_ISOLATED);
784                 eeh_ops->set_option(pe, EEH_OPT_FREEZE_PE);
785                 eeh_pe_dev_traverse(pe, eeh_disable_and_save_dev_state, dev);
786                 if (!(pe->type & EEH_PE_VF))
787                         eeh_pe_state_mark(pe, EEH_PE_CFG_BLOCKED);
788                 eeh_ops->reset(pe, EEH_RESET_HOT);
789                 break;
790         case pcie_warm_reset:
791                 eeh_pe_state_mark_with_cfg(pe, EEH_PE_ISOLATED);
792                 eeh_ops->set_option(pe, EEH_OPT_FREEZE_PE);
793                 eeh_pe_dev_traverse(pe, eeh_disable_and_save_dev_state, dev);
794                 if (!(pe->type & EEH_PE_VF))
795                         eeh_pe_state_mark(pe, EEH_PE_CFG_BLOCKED);
796                 eeh_ops->reset(pe, EEH_RESET_FUNDAMENTAL);
797                 break;
798         default:
799                 eeh_pe_state_clear(pe, EEH_PE_ISOLATED | EEH_PE_CFG_BLOCKED);
800                 return -EINVAL;
801         };
802
803         return 0;
804 }
805
806 /**
807  * eeh_set_pe_freset - Check the required reset for the indicated device
808  * @data: EEH device
809  * @flag: return value
810  *
811  * Each device might have its preferred reset type: fundamental or
812  * hot reset. The routine is used to collected the information for
813  * the indicated device and its children so that the bunch of the
814  * devices could be reset properly.
815  */
816 static void *eeh_set_dev_freset(void *data, void *flag)
817 {
818         struct pci_dev *dev;
819         unsigned int *freset = (unsigned int *)flag;
820         struct eeh_dev *edev = (struct eeh_dev *)data;
821
822         dev = eeh_dev_to_pci_dev(edev);
823         if (dev)
824                 *freset |= dev->needs_freset;
825
826         return NULL;
827 }
828
829 /**
830  * eeh_pe_reset_full - Complete a full reset process on the indicated PE
831  * @pe: EEH PE
832  *
833  * This function executes a full reset procedure on a PE, including setting
834  * the appropriate flags, performing a fundamental or hot reset, and then
835  * deactivating the reset status.  It is designed to be used within the EEH
836  * subsystem, as opposed to eeh_pe_reset which is exported to drivers and
837  * only performs a single operation at a time.
838  *
839  * This function will attempt to reset a PE three times before failing.
840  */
841 int eeh_pe_reset_full(struct eeh_pe *pe)
842 {
843         int active_flags = (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE);
844         int reset_state = (EEH_PE_RESET | EEH_PE_CFG_BLOCKED);
845         int type = EEH_RESET_HOT;
846         unsigned int freset = 0;
847         int i, state, ret;
848
849         /*
850          * Determine the type of reset to perform - hot or fundamental.
851          * Hot reset is the default operation, unless any device under the
852          * PE requires a fundamental reset.
853          */
854         eeh_pe_dev_traverse(pe, eeh_set_dev_freset, &freset);
855
856         if (freset)
857                 type = EEH_RESET_FUNDAMENTAL;
858
859         /* Mark the PE as in reset state and block config space accesses */
860         eeh_pe_state_mark(pe, reset_state);
861
862         /* Make three attempts at resetting the bus */
863         for (i = 0; i < 3; i++) {
864                 ret = eeh_pe_reset(pe, type);
865                 if (ret)
866                         break;
867
868                 ret = eeh_pe_reset(pe, EEH_RESET_DEACTIVATE);
869                 if (ret)
870                         break;
871
872                 /* Wait until the PE is in a functioning state */
873                 state = eeh_ops->wait_state(pe, PCI_BUS_RESET_WAIT_MSEC);
874                 if ((state & active_flags) == active_flags)
875                         break;
876
877                 if (state < 0) {
878                         pr_warn("%s: Unrecoverable slot failure on PHB#%x-PE#%x",
879                                 __func__, pe->phb->global_number, pe->addr);
880                         ret = -ENOTRECOVERABLE;
881                         break;
882                 }
883
884                 /* Set error in case this is our last attempt */
885                 ret = -EIO;
886                 pr_warn("%s: Failure %d resetting PHB#%x-PE#%x\n (%d)\n",
887                         __func__, state, pe->phb->global_number, pe->addr, (i + 1));
888         }
889
890         eeh_pe_state_clear(pe, reset_state);
891         return ret;
892 }
893
894 /**
895  * eeh_save_bars - Save device bars
896  * @edev: PCI device associated EEH device
897  *
898  * Save the values of the device bars. Unlike the restore
899  * routine, this routine is *not* recursive. This is because
900  * PCI devices are added individually; but, for the restore,
901  * an entire slot is reset at a time.
902  */
903 void eeh_save_bars(struct eeh_dev *edev)
904 {
905         struct pci_dn *pdn;
906         int i;
907
908         pdn = eeh_dev_to_pdn(edev);
909         if (!pdn)
910                 return;
911
912         for (i = 0; i < 16; i++)
913                 eeh_ops->read_config(pdn, i * 4, 4, &edev->config_space[i]);
914
915         /*
916          * For PCI bridges including root port, we need enable bus
917          * master explicitly. Otherwise, it can't fetch IODA table
918          * entries correctly. So we cache the bit in advance so that
919          * we can restore it after reset, either PHB range or PE range.
920          */
921         if (edev->mode & EEH_DEV_BRIDGE)
922                 edev->config_space[1] |= PCI_COMMAND_MASTER;
923 }
924
925 /**
926  * eeh_ops_register - Register platform dependent EEH operations
927  * @ops: platform dependent EEH operations
928  *
929  * Register the platform dependent EEH operation callback
930  * functions. The platform should call this function before
931  * any other EEH operations.
932  */
933 int __init eeh_ops_register(struct eeh_ops *ops)
934 {
935         if (!ops->name) {
936                 pr_warn("%s: Invalid EEH ops name for %p\n",
937                         __func__, ops);
938                 return -EINVAL;
939         }
940
941         if (eeh_ops && eeh_ops != ops) {
942                 pr_warn("%s: EEH ops of platform %s already existing (%s)\n",
943                         __func__, eeh_ops->name, ops->name);
944                 return -EEXIST;
945         }
946
947         eeh_ops = ops;
948
949         return 0;
950 }
951
952 /**
953  * eeh_ops_unregister - Unreigster platform dependent EEH operations
954  * @name: name of EEH platform operations
955  *
956  * Unregister the platform dependent EEH operation callback
957  * functions.
958  */
959 int __exit eeh_ops_unregister(const char *name)
960 {
961         if (!name || !strlen(name)) {
962                 pr_warn("%s: Invalid EEH ops name\n",
963                         __func__);
964                 return -EINVAL;
965         }
966
967         if (eeh_ops && !strcmp(eeh_ops->name, name)) {
968                 eeh_ops = NULL;
969                 return 0;
970         }
971
972         return -EEXIST;
973 }
974
975 static int eeh_reboot_notifier(struct notifier_block *nb,
976                                unsigned long action, void *unused)
977 {
978         eeh_clear_flag(EEH_ENABLED);
979         return NOTIFY_DONE;
980 }
981
982 static struct notifier_block eeh_reboot_nb = {
983         .notifier_call = eeh_reboot_notifier,
984 };
985
986 /**
987  * eeh_init - EEH initialization
988  *
989  * Initialize EEH by trying to enable it for all of the adapters in the system.
990  * As a side effect we can determine here if eeh is supported at all.
991  * Note that we leave EEH on so failed config cycles won't cause a machine
992  * check.  If a user turns off EEH for a particular adapter they are really
993  * telling Linux to ignore errors.  Some hardware (e.g. POWER5) won't
994  * grant access to a slot if EEH isn't enabled, and so we always enable
995  * EEH for all slots/all devices.
996  *
997  * The eeh-force-off option disables EEH checking globally, for all slots.
998  * Even if force-off is set, the EEH hardware is still enabled, so that
999  * newer systems can boot.
1000  */
1001 int eeh_init(void)
1002 {
1003         struct pci_controller *hose, *tmp;
1004         struct pci_dn *pdn;
1005         static int cnt = 0;
1006         int ret = 0;
1007
1008         /*
1009          * We have to delay the initialization on PowerNV after
1010          * the PCI hierarchy tree has been built because the PEs
1011          * are figured out based on PCI devices instead of device
1012          * tree nodes
1013          */
1014         if (machine_is(powernv) && cnt++ <= 0)
1015                 return ret;
1016
1017         /* Register reboot notifier */
1018         ret = register_reboot_notifier(&eeh_reboot_nb);
1019         if (ret) {
1020                 pr_warn("%s: Failed to register notifier (%d)\n",
1021                         __func__, ret);
1022                 return ret;
1023         }
1024
1025         /* call platform initialization function */
1026         if (!eeh_ops) {
1027                 pr_warn("%s: Platform EEH operation not found\n",
1028                         __func__);
1029                 return -EEXIST;
1030         } else if ((ret = eeh_ops->init()))
1031                 return ret;
1032
1033         /* Initialize PHB PEs */
1034         list_for_each_entry_safe(hose, tmp, &hose_list, list_node)
1035                 eeh_dev_phb_init_dynamic(hose);
1036
1037         /* Initialize EEH event */
1038         ret = eeh_event_init();
1039         if (ret)
1040                 return ret;
1041
1042         /* Enable EEH for all adapters */
1043         list_for_each_entry_safe(hose, tmp, &hose_list, list_node) {
1044                 pdn = hose->pci_data;
1045                 traverse_pci_dn(pdn, eeh_ops->probe, NULL);
1046         }
1047
1048         /*
1049          * Call platform post-initialization. Actually, It's good chance
1050          * to inform platform that EEH is ready to supply service if the
1051          * I/O cache stuff has been built up.
1052          */
1053         if (eeh_ops->post_init) {
1054                 ret = eeh_ops->post_init();
1055                 if (ret)
1056                         return ret;
1057         }
1058
1059         if (eeh_enabled())
1060                 pr_info("EEH: PCI Enhanced I/O Error Handling Enabled\n");
1061         else
1062                 pr_info("EEH: No capable adapters found\n");
1063
1064         return ret;
1065 }
1066
1067 core_initcall_sync(eeh_init);
1068
1069 /**
1070  * eeh_add_device_early - Enable EEH for the indicated device node
1071  * @pdn: PCI device node for which to set up EEH
1072  *
1073  * This routine must be used to perform EEH initialization for PCI
1074  * devices that were added after system boot (e.g. hotplug, dlpar).
1075  * This routine must be called before any i/o is performed to the
1076  * adapter (inluding any config-space i/o).
1077  * Whether this actually enables EEH or not for this device depends
1078  * on the CEC architecture, type of the device, on earlier boot
1079  * command-line arguments & etc.
1080  */
1081 void eeh_add_device_early(struct pci_dn *pdn)
1082 {
1083         struct pci_controller *phb = pdn ? pdn->phb : NULL;
1084         struct eeh_dev *edev = pdn_to_eeh_dev(pdn);
1085
1086         if (!edev)
1087                 return;
1088
1089         if (!eeh_has_flag(EEH_PROBE_MODE_DEVTREE))
1090                 return;
1091
1092         /* USB Bus children of PCI devices will not have BUID's */
1093         if (NULL == phb ||
1094             (eeh_has_flag(EEH_PROBE_MODE_DEVTREE) && 0 == phb->buid))
1095                 return;
1096
1097         eeh_ops->probe(pdn, NULL);
1098 }
1099
1100 /**
1101  * eeh_add_device_tree_early - Enable EEH for the indicated device
1102  * @pdn: PCI device node
1103  *
1104  * This routine must be used to perform EEH initialization for the
1105  * indicated PCI device that was added after system boot (e.g.
1106  * hotplug, dlpar).
1107  */
1108 void eeh_add_device_tree_early(struct pci_dn *pdn)
1109 {
1110         struct pci_dn *n;
1111
1112         if (!pdn)
1113                 return;
1114
1115         list_for_each_entry(n, &pdn->child_list, list)
1116                 eeh_add_device_tree_early(n);
1117         eeh_add_device_early(pdn);
1118 }
1119 EXPORT_SYMBOL_GPL(eeh_add_device_tree_early);
1120
1121 /**
1122  * eeh_add_device_late - Perform EEH initialization for the indicated pci device
1123  * @dev: pci device for which to set up EEH
1124  *
1125  * This routine must be used to complete EEH initialization for PCI
1126  * devices that were added after system boot (e.g. hotplug, dlpar).
1127  */
1128 void eeh_add_device_late(struct pci_dev *dev)
1129 {
1130         struct pci_dn *pdn;
1131         struct eeh_dev *edev;
1132
1133         if (!dev || !eeh_enabled())
1134                 return;
1135
1136         pr_debug("EEH: Adding device %s\n", pci_name(dev));
1137
1138         pdn = pci_get_pdn_by_devfn(dev->bus, dev->devfn);
1139         edev = pdn_to_eeh_dev(pdn);
1140         if (edev->pdev == dev) {
1141                 pr_debug("EEH: Already referenced !\n");
1142                 return;
1143         }
1144
1145         /*
1146          * The EEH cache might not be removed correctly because of
1147          * unbalanced kref to the device during unplug time, which
1148          * relies on pcibios_release_device(). So we have to remove
1149          * that here explicitly.
1150          */
1151         if (edev->pdev) {
1152                 eeh_rmv_from_parent_pe(edev);
1153                 eeh_addr_cache_rmv_dev(edev->pdev);
1154                 eeh_sysfs_remove_device(edev->pdev);
1155                 edev->mode &= ~EEH_DEV_SYSFS;
1156
1157                 /*
1158                  * We definitely should have the PCI device removed
1159                  * though it wasn't correctly. So we needn't call
1160                  * into error handler afterwards.
1161                  */
1162                 edev->mode |= EEH_DEV_NO_HANDLER;
1163
1164                 edev->pdev = NULL;
1165                 dev->dev.archdata.edev = NULL;
1166         }
1167
1168         if (eeh_has_flag(EEH_PROBE_MODE_DEV))
1169                 eeh_ops->probe(pdn, NULL);
1170
1171         edev->pdev = dev;
1172         dev->dev.archdata.edev = edev;
1173
1174         eeh_addr_cache_insert_dev(dev);
1175 }
1176
1177 /**
1178  * eeh_add_device_tree_late - Perform EEH initialization for the indicated PCI bus
1179  * @bus: PCI bus
1180  *
1181  * This routine must be used to perform EEH initialization for PCI
1182  * devices which are attached to the indicated PCI bus. The PCI bus
1183  * is added after system boot through hotplug or dlpar.
1184  */
1185 void eeh_add_device_tree_late(struct pci_bus *bus)
1186 {
1187         struct pci_dev *dev;
1188
1189         list_for_each_entry(dev, &bus->devices, bus_list) {
1190                 eeh_add_device_late(dev);
1191                 if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE) {
1192                         struct pci_bus *subbus = dev->subordinate;
1193                         if (subbus)
1194                                 eeh_add_device_tree_late(subbus);
1195                 }
1196         }
1197 }
1198 EXPORT_SYMBOL_GPL(eeh_add_device_tree_late);
1199
1200 /**
1201  * eeh_add_sysfs_files - Add EEH sysfs files for the indicated PCI bus
1202  * @bus: PCI bus
1203  *
1204  * This routine must be used to add EEH sysfs files for PCI
1205  * devices which are attached to the indicated PCI bus. The PCI bus
1206  * is added after system boot through hotplug or dlpar.
1207  */
1208 void eeh_add_sysfs_files(struct pci_bus *bus)
1209 {
1210         struct pci_dev *dev;
1211
1212         list_for_each_entry(dev, &bus->devices, bus_list) {
1213                 eeh_sysfs_add_device(dev);
1214                 if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE) {
1215                         struct pci_bus *subbus = dev->subordinate;
1216                         if (subbus)
1217                                 eeh_add_sysfs_files(subbus);
1218                 }
1219         }
1220 }
1221 EXPORT_SYMBOL_GPL(eeh_add_sysfs_files);
1222
1223 /**
1224  * eeh_remove_device - Undo EEH setup for the indicated pci device
1225  * @dev: pci device to be removed
1226  *
1227  * This routine should be called when a device is removed from
1228  * a running system (e.g. by hotplug or dlpar).  It unregisters
1229  * the PCI device from the EEH subsystem.  I/O errors affecting
1230  * this device will no longer be detected after this call; thus,
1231  * i/o errors affecting this slot may leave this device unusable.
1232  */
1233 void eeh_remove_device(struct pci_dev *dev)
1234 {
1235         struct eeh_dev *edev;
1236
1237         if (!dev || !eeh_enabled())
1238                 return;
1239         edev = pci_dev_to_eeh_dev(dev);
1240
1241         /* Unregister the device with the EEH/PCI address search system */
1242         pr_debug("EEH: Removing device %s\n", pci_name(dev));
1243
1244         if (!edev || !edev->pdev || !edev->pe) {
1245                 pr_debug("EEH: Not referenced !\n");
1246                 return;
1247         }
1248
1249         /*
1250          * During the hotplug for EEH error recovery, we need the EEH
1251          * device attached to the parent PE in order for BAR restore
1252          * a bit later. So we keep it for BAR restore and remove it
1253          * from the parent PE during the BAR resotre.
1254          */
1255         edev->pdev = NULL;
1256
1257         /*
1258          * The flag "in_error" is used to trace EEH devices for VFs
1259          * in error state or not. It's set in eeh_report_error(). If
1260          * it's not set, eeh_report_{reset,resume}() won't be called
1261          * for the VF EEH device.
1262          */
1263         edev->in_error = false;
1264         dev->dev.archdata.edev = NULL;
1265         if (!(edev->pe->state & EEH_PE_KEEP))
1266                 eeh_rmv_from_parent_pe(edev);
1267         else
1268                 edev->mode |= EEH_DEV_DISCONNECTED;
1269
1270         /*
1271          * We're removing from the PCI subsystem, that means
1272          * the PCI device driver can't support EEH or not
1273          * well. So we rely on hotplug completely to do recovery
1274          * for the specific PCI device.
1275          */
1276         edev->mode |= EEH_DEV_NO_HANDLER;
1277
1278         eeh_addr_cache_rmv_dev(dev);
1279         eeh_sysfs_remove_device(dev);
1280         edev->mode &= ~EEH_DEV_SYSFS;
1281 }
1282
1283 int eeh_unfreeze_pe(struct eeh_pe *pe, bool sw_state)
1284 {
1285         int ret;
1286
1287         ret = eeh_pci_enable(pe, EEH_OPT_THAW_MMIO);
1288         if (ret) {
1289                 pr_warn("%s: Failure %d enabling IO on PHB#%x-PE#%x\n",
1290                         __func__, ret, pe->phb->global_number, pe->addr);
1291                 return ret;
1292         }
1293
1294         ret = eeh_pci_enable(pe, EEH_OPT_THAW_DMA);
1295         if (ret) {
1296                 pr_warn("%s: Failure %d enabling DMA on PHB#%x-PE#%x\n",
1297                         __func__, ret, pe->phb->global_number, pe->addr);
1298                 return ret;
1299         }
1300
1301         /* Clear software isolated state */
1302         if (sw_state && (pe->state & EEH_PE_ISOLATED))
1303                 eeh_pe_state_clear(pe, EEH_PE_ISOLATED);
1304
1305         return ret;
1306 }
1307
1308
1309 static struct pci_device_id eeh_reset_ids[] = {
1310         { PCI_DEVICE(0x19a2, 0x0710) }, /* Emulex, BE     */
1311         { PCI_DEVICE(0x10df, 0xe220) }, /* Emulex, Lancer */
1312         { PCI_DEVICE(0x14e4, 0x1657) }, /* Broadcom BCM5719 */
1313         { 0 }
1314 };
1315
1316 static int eeh_pe_change_owner(struct eeh_pe *pe)
1317 {
1318         struct eeh_dev *edev, *tmp;
1319         struct pci_dev *pdev;
1320         struct pci_device_id *id;
1321         int flags, ret;
1322
1323         /* Check PE state */
1324         flags = (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE);
1325         ret = eeh_ops->get_state(pe, NULL);
1326         if (ret < 0 || ret == EEH_STATE_NOT_SUPPORT)
1327                 return 0;
1328
1329         /* Unfrozen PE, nothing to do */
1330         if ((ret & flags) == flags)
1331                 return 0;
1332
1333         /* Frozen PE, check if it needs PE level reset */
1334         eeh_pe_for_each_dev(pe, edev, tmp) {
1335                 pdev = eeh_dev_to_pci_dev(edev);
1336                 if (!pdev)
1337                         continue;
1338
1339                 for (id = &eeh_reset_ids[0]; id->vendor != 0; id++) {
1340                         if (id->vendor != PCI_ANY_ID &&
1341                             id->vendor != pdev->vendor)
1342                                 continue;
1343                         if (id->device != PCI_ANY_ID &&
1344                             id->device != pdev->device)
1345                                 continue;
1346                         if (id->subvendor != PCI_ANY_ID &&
1347                             id->subvendor != pdev->subsystem_vendor)
1348                                 continue;
1349                         if (id->subdevice != PCI_ANY_ID &&
1350                             id->subdevice != pdev->subsystem_device)
1351                                 continue;
1352
1353                         return eeh_pe_reset_and_recover(pe);
1354                 }
1355         }
1356
1357         return eeh_unfreeze_pe(pe, true);
1358 }
1359
1360 /**
1361  * eeh_dev_open - Increase count of pass through devices for PE
1362  * @pdev: PCI device
1363  *
1364  * Increase count of passed through devices for the indicated
1365  * PE. In the result, the EEH errors detected on the PE won't be
1366  * reported. The PE owner will be responsible for detection
1367  * and recovery.
1368  */
1369 int eeh_dev_open(struct pci_dev *pdev)
1370 {
1371         struct eeh_dev *edev;
1372         int ret = -ENODEV;
1373
1374         mutex_lock(&eeh_dev_mutex);
1375
1376         /* No PCI device ? */
1377         if (!pdev)
1378                 goto out;
1379
1380         /* No EEH device or PE ? */
1381         edev = pci_dev_to_eeh_dev(pdev);
1382         if (!edev || !edev->pe)
1383                 goto out;
1384
1385         /*
1386          * The PE might have been put into frozen state, but we
1387          * didn't detect that yet. The passed through PCI devices
1388          * in frozen PE won't work properly. Clear the frozen state
1389          * in advance.
1390          */
1391         ret = eeh_pe_change_owner(edev->pe);
1392         if (ret)
1393                 goto out;
1394
1395         /* Increase PE's pass through count */
1396         atomic_inc(&edev->pe->pass_dev_cnt);
1397         mutex_unlock(&eeh_dev_mutex);
1398
1399         return 0;
1400 out:
1401         mutex_unlock(&eeh_dev_mutex);
1402         return ret;
1403 }
1404 EXPORT_SYMBOL_GPL(eeh_dev_open);
1405
1406 /**
1407  * eeh_dev_release - Decrease count of pass through devices for PE
1408  * @pdev: PCI device
1409  *
1410  * Decrease count of pass through devices for the indicated PE. If
1411  * there is no passed through device in PE, the EEH errors detected
1412  * on the PE will be reported and handled as usual.
1413  */
1414 void eeh_dev_release(struct pci_dev *pdev)
1415 {
1416         struct eeh_dev *edev;
1417
1418         mutex_lock(&eeh_dev_mutex);
1419
1420         /* No PCI device ? */
1421         if (!pdev)
1422                 goto out;
1423
1424         /* No EEH device ? */
1425         edev = pci_dev_to_eeh_dev(pdev);
1426         if (!edev || !edev->pe || !eeh_pe_passed(edev->pe))
1427                 goto out;
1428
1429         /* Decrease PE's pass through count */
1430         WARN_ON(atomic_dec_if_positive(&edev->pe->pass_dev_cnt) < 0);
1431         eeh_pe_change_owner(edev->pe);
1432 out:
1433         mutex_unlock(&eeh_dev_mutex);
1434 }
1435 EXPORT_SYMBOL(eeh_dev_release);
1436
1437 #ifdef CONFIG_IOMMU_API
1438
1439 static int dev_has_iommu_table(struct device *dev, void *data)
1440 {
1441         struct pci_dev *pdev = to_pci_dev(dev);
1442         struct pci_dev **ppdev = data;
1443
1444         if (!dev)
1445                 return 0;
1446
1447         if (dev->iommu_group) {
1448                 *ppdev = pdev;
1449                 return 1;
1450         }
1451
1452         return 0;
1453 }
1454
1455 /**
1456  * eeh_iommu_group_to_pe - Convert IOMMU group to EEH PE
1457  * @group: IOMMU group
1458  *
1459  * The routine is called to convert IOMMU group to EEH PE.
1460  */
1461 struct eeh_pe *eeh_iommu_group_to_pe(struct iommu_group *group)
1462 {
1463         struct pci_dev *pdev = NULL;
1464         struct eeh_dev *edev;
1465         int ret;
1466
1467         /* No IOMMU group ? */
1468         if (!group)
1469                 return NULL;
1470
1471         ret = iommu_group_for_each_dev(group, &pdev, dev_has_iommu_table);
1472         if (!ret || !pdev)
1473                 return NULL;
1474
1475         /* No EEH device or PE ? */
1476         edev = pci_dev_to_eeh_dev(pdev);
1477         if (!edev || !edev->pe)
1478                 return NULL;
1479
1480         return edev->pe;
1481 }
1482 EXPORT_SYMBOL_GPL(eeh_iommu_group_to_pe);
1483
1484 #endif /* CONFIG_IOMMU_API */
1485
1486 /**
1487  * eeh_pe_set_option - Set options for the indicated PE
1488  * @pe: EEH PE
1489  * @option: requested option
1490  *
1491  * The routine is called to enable or disable EEH functionality
1492  * on the indicated PE, to enable IO or DMA for the frozen PE.
1493  */
1494 int eeh_pe_set_option(struct eeh_pe *pe, int option)
1495 {
1496         int ret = 0;
1497
1498         /* Invalid PE ? */
1499         if (!pe)
1500                 return -ENODEV;
1501
1502         /*
1503          * EEH functionality could possibly be disabled, just
1504          * return error for the case. And the EEH functinality
1505          * isn't expected to be disabled on one specific PE.
1506          */
1507         switch (option) {
1508         case EEH_OPT_ENABLE:
1509                 if (eeh_enabled()) {
1510                         ret = eeh_pe_change_owner(pe);
1511                         break;
1512                 }
1513                 ret = -EIO;
1514                 break;
1515         case EEH_OPT_DISABLE:
1516                 break;
1517         case EEH_OPT_THAW_MMIO:
1518         case EEH_OPT_THAW_DMA:
1519         case EEH_OPT_FREEZE_PE:
1520                 if (!eeh_ops || !eeh_ops->set_option) {
1521                         ret = -ENOENT;
1522                         break;
1523                 }
1524
1525                 ret = eeh_pci_enable(pe, option);
1526                 break;
1527         default:
1528                 pr_debug("%s: Option %d out of range (%d, %d)\n",
1529                         __func__, option, EEH_OPT_DISABLE, EEH_OPT_THAW_DMA);
1530                 ret = -EINVAL;
1531         }
1532
1533         return ret;
1534 }
1535 EXPORT_SYMBOL_GPL(eeh_pe_set_option);
1536
1537 /**
1538  * eeh_pe_get_state - Retrieve PE's state
1539  * @pe: EEH PE
1540  *
1541  * Retrieve the PE's state, which includes 3 aspects: enabled
1542  * DMA, enabled IO and asserted reset.
1543  */
1544 int eeh_pe_get_state(struct eeh_pe *pe)
1545 {
1546         int result, ret = 0;
1547         bool rst_active, dma_en, mmio_en;
1548
1549         /* Existing PE ? */
1550         if (!pe)
1551                 return -ENODEV;
1552
1553         if (!eeh_ops || !eeh_ops->get_state)
1554                 return -ENOENT;
1555
1556         /*
1557          * If the parent PE is owned by the host kernel and is undergoing
1558          * error recovery, we should return the PE state as temporarily
1559          * unavailable so that the error recovery on the guest is suspended
1560          * until the recovery completes on the host.
1561          */
1562         if (pe->parent &&
1563             !(pe->state & EEH_PE_REMOVED) &&
1564             (pe->parent->state & (EEH_PE_ISOLATED | EEH_PE_RECOVERING)))
1565                 return EEH_PE_STATE_UNAVAIL;
1566
1567         result = eeh_ops->get_state(pe, NULL);
1568         rst_active = !!(result & EEH_STATE_RESET_ACTIVE);
1569         dma_en = !!(result & EEH_STATE_DMA_ENABLED);
1570         mmio_en = !!(result & EEH_STATE_MMIO_ENABLED);
1571
1572         if (rst_active)
1573                 ret = EEH_PE_STATE_RESET;
1574         else if (dma_en && mmio_en)
1575                 ret = EEH_PE_STATE_NORMAL;
1576         else if (!dma_en && !mmio_en)
1577                 ret = EEH_PE_STATE_STOPPED_IO_DMA;
1578         else if (!dma_en && mmio_en)
1579                 ret = EEH_PE_STATE_STOPPED_DMA;
1580         else
1581                 ret = EEH_PE_STATE_UNAVAIL;
1582
1583         return ret;
1584 }
1585 EXPORT_SYMBOL_GPL(eeh_pe_get_state);
1586
1587 static int eeh_pe_reenable_devices(struct eeh_pe *pe)
1588 {
1589         struct eeh_dev *edev, *tmp;
1590         struct pci_dev *pdev;
1591         int ret = 0;
1592
1593         /* Restore config space */
1594         eeh_pe_restore_bars(pe);
1595
1596         /*
1597          * Reenable PCI devices as the devices passed
1598          * through are always enabled before the reset.
1599          */
1600         eeh_pe_for_each_dev(pe, edev, tmp) {
1601                 pdev = eeh_dev_to_pci_dev(edev);
1602                 if (!pdev)
1603                         continue;
1604
1605                 ret = pci_reenable_device(pdev);
1606                 if (ret) {
1607                         pr_warn("%s: Failure %d reenabling %s\n",
1608                                 __func__, ret, pci_name(pdev));
1609                         return ret;
1610                 }
1611         }
1612
1613         /* The PE is still in frozen state */
1614         return eeh_unfreeze_pe(pe, true);
1615 }
1616
1617
1618 /**
1619  * eeh_pe_reset - Issue PE reset according to specified type
1620  * @pe: EEH PE
1621  * @option: reset type
1622  *
1623  * The routine is called to reset the specified PE with the
1624  * indicated type, either fundamental reset or hot reset.
1625  * PE reset is the most important part for error recovery.
1626  */
1627 int eeh_pe_reset(struct eeh_pe *pe, int option)
1628 {
1629         int ret = 0;
1630
1631         /* Invalid PE ? */
1632         if (!pe)
1633                 return -ENODEV;
1634
1635         if (!eeh_ops || !eeh_ops->set_option || !eeh_ops->reset)
1636                 return -ENOENT;
1637
1638         switch (option) {
1639         case EEH_RESET_DEACTIVATE:
1640                 ret = eeh_ops->reset(pe, option);
1641                 eeh_pe_state_clear(pe, EEH_PE_CFG_BLOCKED);
1642                 if (ret)
1643                         break;
1644
1645                 ret = eeh_pe_reenable_devices(pe);
1646                 break;
1647         case EEH_RESET_HOT:
1648         case EEH_RESET_FUNDAMENTAL:
1649                 /*
1650                  * Proactively freeze the PE to drop all MMIO access
1651                  * during reset, which should be banned as it's always
1652                  * cause recursive EEH error.
1653                  */
1654                 eeh_ops->set_option(pe, EEH_OPT_FREEZE_PE);
1655
1656                 eeh_pe_state_mark(pe, EEH_PE_CFG_BLOCKED);
1657                 ret = eeh_ops->reset(pe, option);
1658                 break;
1659         default:
1660                 pr_debug("%s: Unsupported option %d\n",
1661                         __func__, option);
1662                 ret = -EINVAL;
1663         }
1664
1665         return ret;
1666 }
1667 EXPORT_SYMBOL_GPL(eeh_pe_reset);
1668
1669 /**
1670  * eeh_pe_configure - Configure PCI bridges after PE reset
1671  * @pe: EEH PE
1672  *
1673  * The routine is called to restore the PCI config space for
1674  * those PCI devices, especially PCI bridges affected by PE
1675  * reset issued previously.
1676  */
1677 int eeh_pe_configure(struct eeh_pe *pe)
1678 {
1679         int ret = 0;
1680
1681         /* Invalid PE ? */
1682         if (!pe)
1683                 return -ENODEV;
1684
1685         return ret;
1686 }
1687 EXPORT_SYMBOL_GPL(eeh_pe_configure);
1688
1689 /**
1690  * eeh_pe_inject_err - Injecting the specified PCI error to the indicated PE
1691  * @pe: the indicated PE
1692  * @type: error type
1693  * @function: error function
1694  * @addr: address
1695  * @mask: address mask
1696  *
1697  * The routine is called to inject the specified PCI error, which
1698  * is determined by @type and @function, to the indicated PE for
1699  * testing purpose.
1700  */
1701 int eeh_pe_inject_err(struct eeh_pe *pe, int type, int func,
1702                       unsigned long addr, unsigned long mask)
1703 {
1704         /* Invalid PE ? */
1705         if (!pe)
1706                 return -ENODEV;
1707
1708         /* Unsupported operation ? */
1709         if (!eeh_ops || !eeh_ops->err_inject)
1710                 return -ENOENT;
1711
1712         /* Check on PCI error type */
1713         if (type != EEH_ERR_TYPE_32 && type != EEH_ERR_TYPE_64)
1714                 return -EINVAL;
1715
1716         /* Check on PCI error function */
1717         if (func < EEH_ERR_FUNC_MIN || func > EEH_ERR_FUNC_MAX)
1718                 return -EINVAL;
1719
1720         return eeh_ops->err_inject(pe, type, func, addr, mask);
1721 }
1722 EXPORT_SYMBOL_GPL(eeh_pe_inject_err);
1723
1724 static int proc_eeh_show(struct seq_file *m, void *v)
1725 {
1726         if (!eeh_enabled()) {
1727                 seq_printf(m, "EEH Subsystem is globally disabled\n");
1728                 seq_printf(m, "eeh_total_mmio_ffs=%llu\n", eeh_stats.total_mmio_ffs);
1729         } else {
1730                 seq_printf(m, "EEH Subsystem is enabled\n");
1731                 seq_printf(m,
1732                                 "no device=%llu\n"
1733                                 "no device node=%llu\n"
1734                                 "no config address=%llu\n"
1735                                 "check not wanted=%llu\n"
1736                                 "eeh_total_mmio_ffs=%llu\n"
1737                                 "eeh_false_positives=%llu\n"
1738                                 "eeh_slot_resets=%llu\n",
1739                                 eeh_stats.no_device,
1740                                 eeh_stats.no_dn,
1741                                 eeh_stats.no_cfg_addr,
1742                                 eeh_stats.ignored_check,
1743                                 eeh_stats.total_mmio_ffs,
1744                                 eeh_stats.false_positives,
1745                                 eeh_stats.slot_resets);
1746         }
1747
1748         return 0;
1749 }
1750
1751 static int proc_eeh_open(struct inode *inode, struct file *file)
1752 {
1753         return single_open(file, proc_eeh_show, NULL);
1754 }
1755
1756 static const struct file_operations proc_eeh_operations = {
1757         .open      = proc_eeh_open,
1758         .read      = seq_read,
1759         .llseek    = seq_lseek,
1760         .release   = single_release,
1761 };
1762
1763 #ifdef CONFIG_DEBUG_FS
1764 static int eeh_enable_dbgfs_set(void *data, u64 val)
1765 {
1766         if (val)
1767                 eeh_clear_flag(EEH_FORCE_DISABLED);
1768         else
1769                 eeh_add_flag(EEH_FORCE_DISABLED);
1770
1771         /* Notify the backend */
1772         if (eeh_ops->post_init)
1773                 eeh_ops->post_init();
1774
1775         return 0;
1776 }
1777
1778 static int eeh_enable_dbgfs_get(void *data, u64 *val)
1779 {
1780         if (eeh_enabled())
1781                 *val = 0x1ul;
1782         else
1783                 *val = 0x0ul;
1784         return 0;
1785 }
1786
1787 static int eeh_freeze_dbgfs_set(void *data, u64 val)
1788 {
1789         eeh_max_freezes = val;
1790         return 0;
1791 }
1792
1793 static int eeh_freeze_dbgfs_get(void *data, u64 *val)
1794 {
1795         *val = eeh_max_freezes;
1796         return 0;
1797 }
1798
1799 DEFINE_SIMPLE_ATTRIBUTE(eeh_enable_dbgfs_ops, eeh_enable_dbgfs_get,
1800                         eeh_enable_dbgfs_set, "0x%llx\n");
1801 DEFINE_SIMPLE_ATTRIBUTE(eeh_freeze_dbgfs_ops, eeh_freeze_dbgfs_get,
1802                         eeh_freeze_dbgfs_set, "0x%llx\n");
1803 #endif
1804
1805 static int __init eeh_init_proc(void)
1806 {
1807         if (machine_is(pseries) || machine_is(powernv)) {
1808                 proc_create("powerpc/eeh", 0, NULL, &proc_eeh_operations);
1809 #ifdef CONFIG_DEBUG_FS
1810                 debugfs_create_file("eeh_enable", 0600,
1811                                     powerpc_debugfs_root, NULL,
1812                                     &eeh_enable_dbgfs_ops);
1813                 debugfs_create_file("eeh_max_freezes", 0600,
1814                                     powerpc_debugfs_root, NULL,
1815                                     &eeh_freeze_dbgfs_ops);
1816 #endif
1817         }
1818
1819         return 0;
1820 }
1821 __initcall(eeh_init_proc);