powerpc/eeh: Report frozen parent PE prior to child PE
[firefly-linux-kernel-4.4.55.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/debugfs.h>
26 #include <linux/sched.h>
27 #include <linux/init.h>
28 #include <linux/list.h>
29 #include <linux/pci.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/debug.h>
40 #include <asm/eeh.h>
41 #include <asm/eeh_event.h>
42 #include <asm/io.h>
43 #include <asm/machdep.h>
44 #include <asm/ppc-pci.h>
45 #include <asm/rtas.h>
46
47
48 /** Overview:
49  *  EEH, or "Extended Error Handling" is a PCI bridge technology for
50  *  dealing with PCI bus errors that can't be dealt with within the
51  *  usual PCI framework, except by check-stopping the CPU.  Systems
52  *  that are designed for high-availability/reliability cannot afford
53  *  to crash due to a "mere" PCI error, thus the need for EEH.
54  *  An EEH-capable bridge operates by converting a detected error
55  *  into a "slot freeze", taking the PCI adapter off-line, making
56  *  the slot behave, from the OS'es point of view, as if the slot
57  *  were "empty": all reads return 0xff's and all writes are silently
58  *  ignored.  EEH slot isolation events can be triggered by parity
59  *  errors on the address or data busses (e.g. during posted writes),
60  *  which in turn might be caused by low voltage on the bus, dust,
61  *  vibration, humidity, radioactivity or plain-old failed hardware.
62  *
63  *  Note, however, that one of the leading causes of EEH slot
64  *  freeze events are buggy device drivers, buggy device microcode,
65  *  or buggy device hardware.  This is because any attempt by the
66  *  device to bus-master data to a memory address that is not
67  *  assigned to the device will trigger a slot freeze.   (The idea
68  *  is to prevent devices-gone-wild from corrupting system memory).
69  *  Buggy hardware/drivers will have a miserable time co-existing
70  *  with EEH.
71  *
72  *  Ideally, a PCI device driver, when suspecting that an isolation
73  *  event has occurred (e.g. by reading 0xff's), will then ask EEH
74  *  whether this is the case, and then take appropriate steps to
75  *  reset the PCI slot, the PCI device, and then resume operations.
76  *  However, until that day,  the checking is done here, with the
77  *  eeh_check_failure() routine embedded in the MMIO macros.  If
78  *  the slot is found to be isolated, an "EEH Event" is synthesized
79  *  and sent out for processing.
80  */
81
82 /* If a device driver keeps reading an MMIO register in an interrupt
83  * handler after a slot isolation event, it might be broken.
84  * This sets the threshold for how many read attempts we allow
85  * before printing an error message.
86  */
87 #define EEH_MAX_FAILS   2100000
88
89 /* Time to wait for a PCI slot to report status, in milliseconds */
90 #define PCI_BUS_RESET_WAIT_MSEC (5*60*1000)
91
92 /*
93  * EEH probe mode support, which is part of the flags,
94  * is to support multiple platforms for EEH. Some platforms
95  * like pSeries do PCI emunation based on device tree.
96  * However, other platforms like powernv probe PCI devices
97  * from hardware. The flag is used to distinguish that.
98  * In addition, struct eeh_ops::probe would be invoked for
99  * particular OF node or PCI device so that the corresponding
100  * PE would be created there.
101  */
102 int eeh_subsystem_flags;
103 EXPORT_SYMBOL(eeh_subsystem_flags);
104
105 /* Platform dependent EEH operations */
106 struct eeh_ops *eeh_ops = NULL;
107
108 /* Lock to avoid races due to multiple reports of an error */
109 DEFINE_RAW_SPINLOCK(confirm_error_lock);
110
111 /* Buffer for reporting pci register dumps. Its here in BSS, and
112  * not dynamically alloced, so that it ends up in RMO where RTAS
113  * can access it.
114  */
115 #define EEH_PCI_REGS_LOG_LEN 4096
116 static unsigned char pci_regs_buf[EEH_PCI_REGS_LOG_LEN];
117
118 /*
119  * The struct is used to maintain the EEH global statistic
120  * information. Besides, the EEH global statistics will be
121  * exported to user space through procfs
122  */
123 struct eeh_stats {
124         u64 no_device;          /* PCI device not found         */
125         u64 no_dn;              /* OF node not found            */
126         u64 no_cfg_addr;        /* Config address not found     */
127         u64 ignored_check;      /* EEH check skipped            */
128         u64 total_mmio_ffs;     /* Total EEH checks             */
129         u64 false_positives;    /* Unnecessary EEH checks       */
130         u64 slot_resets;        /* PE reset                     */
131 };
132
133 static struct eeh_stats eeh_stats;
134
135 #define IS_BRIDGE(class_code) (((class_code)<<16) == PCI_BASE_CLASS_BRIDGE)
136
137 static int __init eeh_setup(char *str)
138 {
139         if (!strcmp(str, "off"))
140                 eeh_subsystem_flags |= EEH_FORCE_DISABLED;
141
142         return 1;
143 }
144 __setup("eeh=", eeh_setup);
145
146 /**
147  * eeh_gather_pci_data - Copy assorted PCI config space registers to buff
148  * @edev: device to report data for
149  * @buf: point to buffer in which to log
150  * @len: amount of room in buffer
151  *
152  * This routine captures assorted PCI configuration space data,
153  * and puts them into a buffer for RTAS error logging.
154  */
155 static size_t eeh_gather_pci_data(struct eeh_dev *edev, char * buf, size_t len)
156 {
157         struct device_node *dn = eeh_dev_to_of_node(edev);
158         u32 cfg;
159         int cap, i;
160         int n = 0;
161
162         n += scnprintf(buf+n, len-n, "%s\n", dn->full_name);
163         pr_warn("EEH: of node=%s\n", dn->full_name);
164
165         eeh_ops->read_config(dn, PCI_VENDOR_ID, 4, &cfg);
166         n += scnprintf(buf+n, len-n, "dev/vend:%08x\n", cfg);
167         pr_warn("EEH: PCI device/vendor: %08x\n", cfg);
168
169         eeh_ops->read_config(dn, PCI_COMMAND, 4, &cfg);
170         n += scnprintf(buf+n, len-n, "cmd/stat:%x\n", cfg);
171         pr_warn("EEH: PCI cmd/status register: %08x\n", cfg);
172
173         /* Gather bridge-specific registers */
174         if (edev->mode & EEH_DEV_BRIDGE) {
175                 eeh_ops->read_config(dn, PCI_SEC_STATUS, 2, &cfg);
176                 n += scnprintf(buf+n, len-n, "sec stat:%x\n", cfg);
177                 pr_warn("EEH: Bridge secondary status: %04x\n", cfg);
178
179                 eeh_ops->read_config(dn, PCI_BRIDGE_CONTROL, 2, &cfg);
180                 n += scnprintf(buf+n, len-n, "brdg ctl:%x\n", cfg);
181                 pr_warn("EEH: Bridge control: %04x\n", cfg);
182         }
183
184         /* Dump out the PCI-X command and status regs */
185         cap = edev->pcix_cap;
186         if (cap) {
187                 eeh_ops->read_config(dn, cap, 4, &cfg);
188                 n += scnprintf(buf+n, len-n, "pcix-cmd:%x\n", cfg);
189                 pr_warn("EEH: PCI-X cmd: %08x\n", cfg);
190
191                 eeh_ops->read_config(dn, cap+4, 4, &cfg);
192                 n += scnprintf(buf+n, len-n, "pcix-stat:%x\n", cfg);
193                 pr_warn("EEH: PCI-X status: %08x\n", cfg);
194         }
195
196         /* If PCI-E capable, dump PCI-E cap 10 */
197         cap = edev->pcie_cap;
198         if (cap) {
199                 n += scnprintf(buf+n, len-n, "pci-e cap10:\n");
200                 pr_warn("EEH: PCI-E capabilities and status follow:\n");
201
202                 for (i=0; i<=8; i++) {
203                         eeh_ops->read_config(dn, cap+4*i, 4, &cfg);
204                         n += scnprintf(buf+n, len-n, "%02x:%x\n", 4*i, cfg);
205                         pr_warn("EEH: PCI-E %02x: %08x\n", i, cfg);
206                 }
207         }
208
209         /* If AER capable, dump it */
210         cap = edev->aer_cap;
211         if (cap) {
212                 n += scnprintf(buf+n, len-n, "pci-e AER:\n");
213                 pr_warn("EEH: PCI-E AER capability register set follows:\n");
214
215                 for (i=0; i<14; i++) {
216                         eeh_ops->read_config(dn, cap+4*i, 4, &cfg);
217                         n += scnprintf(buf+n, len-n, "%02x:%x\n", 4*i, cfg);
218                         pr_warn("EEH: PCI-E AER %02x: %08x\n", i, cfg);
219                 }
220         }
221
222         return n;
223 }
224
225 /**
226  * eeh_slot_error_detail - Generate combined log including driver log and error log
227  * @pe: EEH PE
228  * @severity: temporary or permanent error log
229  *
230  * This routine should be called to generate the combined log, which
231  * is comprised of driver log and error log. The driver log is figured
232  * out from the config space of the corresponding PCI device, while
233  * the error log is fetched through platform dependent function call.
234  */
235 void eeh_slot_error_detail(struct eeh_pe *pe, int severity)
236 {
237         size_t loglen = 0;
238         struct eeh_dev *edev, *tmp;
239
240         /*
241          * When the PHB is fenced or dead, it's pointless to collect
242          * the data from PCI config space because it should return
243          * 0xFF's. For ER, we still retrieve the data from the PCI
244          * config space.
245          *
246          * For pHyp, we have to enable IO for log retrieval. Otherwise,
247          * 0xFF's is always returned from PCI config space.
248          */
249         if (!(pe->type & EEH_PE_PHB)) {
250                 if (eeh_probe_mode_devtree())
251                         eeh_pci_enable(pe, EEH_OPT_THAW_MMIO);
252                 eeh_ops->configure_bridge(pe);
253                 eeh_pe_restore_bars(pe);
254
255                 pci_regs_buf[0] = 0;
256                 eeh_pe_for_each_dev(pe, edev, tmp) {
257                         loglen += eeh_gather_pci_data(edev, pci_regs_buf + loglen,
258                                                       EEH_PCI_REGS_LOG_LEN - loglen);
259                 }
260         }
261
262         eeh_ops->get_log(pe, severity, pci_regs_buf, loglen);
263 }
264
265 /**
266  * eeh_token_to_phys - Convert EEH address token to phys address
267  * @token: I/O token, should be address in the form 0xA....
268  *
269  * This routine should be called to convert virtual I/O address
270  * to physical one.
271  */
272 static inline unsigned long eeh_token_to_phys(unsigned long token)
273 {
274         pte_t *ptep;
275         unsigned long pa;
276         int hugepage_shift;
277
278         /*
279          * We won't find hugepages here, iomem
280          */
281         ptep = find_linux_pte_or_hugepte(init_mm.pgd, token, &hugepage_shift);
282         if (!ptep)
283                 return token;
284         WARN_ON(hugepage_shift);
285         pa = pte_pfn(*ptep) << PAGE_SHIFT;
286
287         return pa | (token & (PAGE_SIZE-1));
288 }
289
290 /*
291  * On PowerNV platform, we might already have fenced PHB there.
292  * For that case, it's meaningless to recover frozen PE. Intead,
293  * We have to handle fenced PHB firstly.
294  */
295 static int eeh_phb_check_failure(struct eeh_pe *pe)
296 {
297         struct eeh_pe *phb_pe;
298         unsigned long flags;
299         int ret;
300
301         if (!eeh_probe_mode_dev())
302                 return -EPERM;
303
304         /* Find the PHB PE */
305         phb_pe = eeh_phb_pe_get(pe->phb);
306         if (!phb_pe) {
307                 pr_warning("%s Can't find PE for PHB#%d\n",
308                            __func__, pe->phb->global_number);
309                 return -EEXIST;
310         }
311
312         /* If the PHB has been in problematic state */
313         eeh_serialize_lock(&flags);
314         if (phb_pe->state & EEH_PE_ISOLATED) {
315                 ret = 0;
316                 goto out;
317         }
318
319         /* Check PHB state */
320         ret = eeh_ops->get_state(phb_pe, NULL);
321         if ((ret < 0) ||
322             (ret == EEH_STATE_NOT_SUPPORT) ||
323             (ret & (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE)) ==
324             (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE)) {
325                 ret = 0;
326                 goto out;
327         }
328
329         /* Isolate the PHB and send event */
330         eeh_pe_state_mark(phb_pe, EEH_PE_ISOLATED);
331         eeh_serialize_unlock(flags);
332
333         pr_err("EEH: PHB#%x failure detected\n",
334                 phb_pe->phb->global_number);
335         dump_stack();
336         eeh_send_failure_event(phb_pe);
337
338         return 1;
339 out:
340         eeh_serialize_unlock(flags);
341         return ret;
342 }
343
344 /**
345  * eeh_dev_check_failure - Check if all 1's data is due to EEH slot freeze
346  * @edev: eeh device
347  *
348  * Check for an EEH failure for the given device node.  Call this
349  * routine if the result of a read was all 0xff's and you want to
350  * find out if this is due to an EEH slot freeze.  This routine
351  * will query firmware for the EEH status.
352  *
353  * Returns 0 if there has not been an EEH error; otherwise returns
354  * a non-zero value and queues up a slot isolation event notification.
355  *
356  * It is safe to call this routine in an interrupt context.
357  */
358 int eeh_dev_check_failure(struct eeh_dev *edev)
359 {
360         int ret;
361         int active_flags = (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE);
362         unsigned long flags;
363         struct device_node *dn;
364         struct pci_dev *dev;
365         struct eeh_pe *pe, *parent_pe;
366         int rc = 0;
367         const char *location;
368
369         eeh_stats.total_mmio_ffs++;
370
371         if (!eeh_enabled())
372                 return 0;
373
374         if (!edev) {
375                 eeh_stats.no_dn++;
376                 return 0;
377         }
378         dn = eeh_dev_to_of_node(edev);
379         dev = eeh_dev_to_pci_dev(edev);
380         pe = edev->pe;
381
382         /* Access to IO BARs might get this far and still not want checking. */
383         if (!pe) {
384                 eeh_stats.ignored_check++;
385                 pr_debug("EEH: Ignored check for %s %s\n",
386                         eeh_pci_name(dev), dn->full_name);
387                 return 0;
388         }
389
390         if (!pe->addr && !pe->config_addr) {
391                 eeh_stats.no_cfg_addr++;
392                 return 0;
393         }
394
395         /*
396          * On PowerNV platform, we might already have fenced PHB
397          * there and we need take care of that firstly.
398          */
399         ret = eeh_phb_check_failure(pe);
400         if (ret > 0)
401                 return ret;
402
403         /* If we already have a pending isolation event for this
404          * slot, we know it's bad already, we don't need to check.
405          * Do this checking under a lock; as multiple PCI devices
406          * in one slot might report errors simultaneously, and we
407          * only want one error recovery routine running.
408          */
409         eeh_serialize_lock(&flags);
410         rc = 1;
411         if (pe->state & EEH_PE_ISOLATED) {
412                 pe->check_count++;
413                 if (pe->check_count % EEH_MAX_FAILS == 0) {
414                         location = of_get_property(dn, "ibm,loc-code", NULL);
415                         printk(KERN_ERR "EEH: %d reads ignored for recovering device at "
416                                 "location=%s driver=%s pci addr=%s\n",
417                                 pe->check_count, location,
418                                 eeh_driver_name(dev), eeh_pci_name(dev));
419                         printk(KERN_ERR "EEH: Might be infinite loop in %s driver\n",
420                                 eeh_driver_name(dev));
421                         dump_stack();
422                 }
423                 goto dn_unlock;
424         }
425
426         /*
427          * Now test for an EEH failure.  This is VERY expensive.
428          * Note that the eeh_config_addr may be a parent device
429          * in the case of a device behind a bridge, or it may be
430          * function zero of a multi-function device.
431          * In any case they must share a common PHB.
432          */
433         ret = eeh_ops->get_state(pe, NULL);
434
435         /* Note that config-io to empty slots may fail;
436          * they are empty when they don't have children.
437          * We will punt with the following conditions: Failure to get
438          * PE's state, EEH not support and Permanently unavailable
439          * state, PE is in good state.
440          */
441         if ((ret < 0) ||
442             (ret == EEH_STATE_NOT_SUPPORT) ||
443             ((ret & active_flags) == active_flags)) {
444                 eeh_stats.false_positives++;
445                 pe->false_positives++;
446                 rc = 0;
447                 goto dn_unlock;
448         }
449
450         /*
451          * It should be corner case that the parent PE has been
452          * put into frozen state as well. We should take care
453          * that at first.
454          */
455         parent_pe = pe->parent;
456         while (parent_pe) {
457                 /* Hit the ceiling ? */
458                 if (parent_pe->type & EEH_PE_PHB)
459                         break;
460
461                 /* Frozen parent PE ? */
462                 ret = eeh_ops->get_state(parent_pe, NULL);
463                 if (ret > 0 &&
464                     (ret & active_flags) != active_flags)
465                         pe = parent_pe;
466
467                 /* Next parent level */
468                 parent_pe = parent_pe->parent;
469         }
470
471         eeh_stats.slot_resets++;
472
473         /* Avoid repeated reports of this failure, including problems
474          * with other functions on this device, and functions under
475          * bridges.
476          */
477         eeh_pe_state_mark(pe, EEH_PE_ISOLATED);
478         eeh_serialize_unlock(flags);
479
480         /* Most EEH events are due to device driver bugs.  Having
481          * a stack trace will help the device-driver authors figure
482          * out what happened.  So print that out.
483          */
484         pr_err("EEH: Frozen PE#%x detected on PHB#%x\n",
485                 pe->addr, pe->phb->global_number);
486         dump_stack();
487
488         eeh_send_failure_event(pe);
489
490         return 1;
491
492 dn_unlock:
493         eeh_serialize_unlock(flags);
494         return rc;
495 }
496
497 EXPORT_SYMBOL_GPL(eeh_dev_check_failure);
498
499 /**
500  * eeh_check_failure - Check if all 1's data is due to EEH slot freeze
501  * @token: I/O token, should be address in the form 0xA....
502  * @val: value, should be all 1's (XXX why do we need this arg??)
503  *
504  * Check for an EEH failure at the given token address.  Call this
505  * routine if the result of a read was all 0xff's and you want to
506  * find out if this is due to an EEH slot freeze event.  This routine
507  * will query firmware for the EEH status.
508  *
509  * Note this routine is safe to call in an interrupt context.
510  */
511 unsigned long eeh_check_failure(const volatile void __iomem *token, unsigned long val)
512 {
513         unsigned long addr;
514         struct eeh_dev *edev;
515
516         /* Finding the phys addr + pci device; this is pretty quick. */
517         addr = eeh_token_to_phys((unsigned long __force) token);
518         edev = eeh_addr_cache_get_dev(addr);
519         if (!edev) {
520                 eeh_stats.no_device++;
521                 return val;
522         }
523
524         eeh_dev_check_failure(edev);
525         return val;
526 }
527
528 EXPORT_SYMBOL(eeh_check_failure);
529
530
531 /**
532  * eeh_pci_enable - Enable MMIO or DMA transfers for this slot
533  * @pe: EEH PE
534  *
535  * This routine should be called to reenable frozen MMIO or DMA
536  * so that it would work correctly again. It's useful while doing
537  * recovery or log collection on the indicated device.
538  */
539 int eeh_pci_enable(struct eeh_pe *pe, int function)
540 {
541         int rc, flags = (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE);
542
543         /*
544          * pHyp doesn't allow to enable IO or DMA on unfrozen PE.
545          * Also, it's pointless to enable them on unfrozen PE. So
546          * we have the check here.
547          */
548         if (function == EEH_OPT_THAW_MMIO ||
549             function == EEH_OPT_THAW_DMA) {
550                 rc = eeh_ops->get_state(pe, NULL);
551                 if (rc < 0)
552                         return rc;
553
554                 /* Needn't to enable or already enabled */
555                 if ((rc == EEH_STATE_NOT_SUPPORT) ||
556                     ((rc & flags) == flags))
557                         return 0;
558         }
559
560         rc = eeh_ops->set_option(pe, function);
561         if (rc)
562                 pr_warn("%s: Unexpected state change %d on "
563                         "PHB#%d-PE#%x, err=%d\n",
564                         __func__, function, pe->phb->global_number,
565                         pe->addr, rc);
566
567         rc = eeh_ops->wait_state(pe, PCI_BUS_RESET_WAIT_MSEC);
568         if (rc <= 0)
569                 return rc;
570
571         if ((function == EEH_OPT_THAW_MMIO) &&
572             (rc & EEH_STATE_MMIO_ENABLED))
573                 return 0;
574
575         if ((function == EEH_OPT_THAW_DMA) &&
576             (rc & EEH_STATE_DMA_ENABLED))
577                 return 0;
578
579         return rc;
580 }
581
582 /**
583  * pcibios_set_pcie_slot_reset - Set PCI-E reset state
584  * @dev: pci device struct
585  * @state: reset state to enter
586  *
587  * Return value:
588  *      0 if success
589  */
590 int pcibios_set_pcie_reset_state(struct pci_dev *dev, enum pcie_reset_state state)
591 {
592         struct eeh_dev *edev = pci_dev_to_eeh_dev(dev);
593         struct eeh_pe *pe = edev->pe;
594
595         if (!pe) {
596                 pr_err("%s: No PE found on PCI device %s\n",
597                         __func__, pci_name(dev));
598                 return -EINVAL;
599         }
600
601         switch (state) {
602         case pcie_deassert_reset:
603                 eeh_ops->reset(pe, EEH_RESET_DEACTIVATE);
604                 break;
605         case pcie_hot_reset:
606                 eeh_ops->reset(pe, EEH_RESET_HOT);
607                 break;
608         case pcie_warm_reset:
609                 eeh_ops->reset(pe, EEH_RESET_FUNDAMENTAL);
610                 break;
611         default:
612                 return -EINVAL;
613         };
614
615         return 0;
616 }
617
618 /**
619  * eeh_set_pe_freset - Check the required reset for the indicated device
620  * @data: EEH device
621  * @flag: return value
622  *
623  * Each device might have its preferred reset type: fundamental or
624  * hot reset. The routine is used to collected the information for
625  * the indicated device and its children so that the bunch of the
626  * devices could be reset properly.
627  */
628 static void *eeh_set_dev_freset(void *data, void *flag)
629 {
630         struct pci_dev *dev;
631         unsigned int *freset = (unsigned int *)flag;
632         struct eeh_dev *edev = (struct eeh_dev *)data;
633
634         dev = eeh_dev_to_pci_dev(edev);
635         if (dev)
636                 *freset |= dev->needs_freset;
637
638         return NULL;
639 }
640
641 /**
642  * eeh_reset_pe_once - Assert the pci #RST line for 1/4 second
643  * @pe: EEH PE
644  *
645  * Assert the PCI #RST line for 1/4 second.
646  */
647 static void eeh_reset_pe_once(struct eeh_pe *pe)
648 {
649         unsigned int freset = 0;
650
651         /* Determine type of EEH reset required for
652          * Partitionable Endpoint, a hot-reset (1)
653          * or a fundamental reset (3).
654          * A fundamental reset required by any device under
655          * Partitionable Endpoint trumps hot-reset.
656          */
657         eeh_pe_dev_traverse(pe, eeh_set_dev_freset, &freset);
658
659         if (freset)
660                 eeh_ops->reset(pe, EEH_RESET_FUNDAMENTAL);
661         else
662                 eeh_ops->reset(pe, EEH_RESET_HOT);
663
664         eeh_ops->reset(pe, EEH_RESET_DEACTIVATE);
665 }
666
667 /**
668  * eeh_reset_pe - Reset the indicated PE
669  * @pe: EEH PE
670  *
671  * This routine should be called to reset indicated device, including
672  * PE. A PE might include multiple PCI devices and sometimes PCI bridges
673  * might be involved as well.
674  */
675 int eeh_reset_pe(struct eeh_pe *pe)
676 {
677         int flags = (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE);
678         int i, rc;
679
680         /* Take three shots at resetting the bus */
681         for (i=0; i<3; i++) {
682                 eeh_reset_pe_once(pe);
683
684                 /*
685                  * EEH_PE_ISOLATED is expected to be removed after
686                  * BAR restore.
687                  */
688                 rc = eeh_ops->wait_state(pe, PCI_BUS_RESET_WAIT_MSEC);
689                 if ((rc & flags) == flags)
690                         return 0;
691
692                 if (rc < 0) {
693                         pr_err("%s: Unrecoverable slot failure on PHB#%d-PE#%x",
694                                 __func__, pe->phb->global_number, pe->addr);
695                         return -1;
696                 }
697                 pr_err("EEH: bus reset %d failed on PHB#%d-PE#%x, rc=%d\n",
698                         i+1, pe->phb->global_number, pe->addr, rc);
699         }
700
701         return -1;
702 }
703
704 /**
705  * eeh_save_bars - Save device bars
706  * @edev: PCI device associated EEH device
707  *
708  * Save the values of the device bars. Unlike the restore
709  * routine, this routine is *not* recursive. This is because
710  * PCI devices are added individually; but, for the restore,
711  * an entire slot is reset at a time.
712  */
713 void eeh_save_bars(struct eeh_dev *edev)
714 {
715         int i;
716         struct device_node *dn;
717
718         if (!edev)
719                 return;
720         dn = eeh_dev_to_of_node(edev);
721
722         for (i = 0; i < 16; i++)
723                 eeh_ops->read_config(dn, i * 4, 4, &edev->config_space[i]);
724
725         /*
726          * For PCI bridges including root port, we need enable bus
727          * master explicitly. Otherwise, it can't fetch IODA table
728          * entries correctly. So we cache the bit in advance so that
729          * we can restore it after reset, either PHB range or PE range.
730          */
731         if (edev->mode & EEH_DEV_BRIDGE)
732                 edev->config_space[1] |= PCI_COMMAND_MASTER;
733 }
734
735 /**
736  * eeh_ops_register - Register platform dependent EEH operations
737  * @ops: platform dependent EEH operations
738  *
739  * Register the platform dependent EEH operation callback
740  * functions. The platform should call this function before
741  * any other EEH operations.
742  */
743 int __init eeh_ops_register(struct eeh_ops *ops)
744 {
745         if (!ops->name) {
746                 pr_warning("%s: Invalid EEH ops name for %p\n",
747                         __func__, ops);
748                 return -EINVAL;
749         }
750
751         if (eeh_ops && eeh_ops != ops) {
752                 pr_warning("%s: EEH ops of platform %s already existing (%s)\n",
753                         __func__, eeh_ops->name, ops->name);
754                 return -EEXIST;
755         }
756
757         eeh_ops = ops;
758
759         return 0;
760 }
761
762 /**
763  * eeh_ops_unregister - Unreigster platform dependent EEH operations
764  * @name: name of EEH platform operations
765  *
766  * Unregister the platform dependent EEH operation callback
767  * functions.
768  */
769 int __exit eeh_ops_unregister(const char *name)
770 {
771         if (!name || !strlen(name)) {
772                 pr_warning("%s: Invalid EEH ops name\n",
773                         __func__);
774                 return -EINVAL;
775         }
776
777         if (eeh_ops && !strcmp(eeh_ops->name, name)) {
778                 eeh_ops = NULL;
779                 return 0;
780         }
781
782         return -EEXIST;
783 }
784
785 static int eeh_reboot_notifier(struct notifier_block *nb,
786                                unsigned long action, void *unused)
787 {
788         eeh_set_enable(false);
789         return NOTIFY_DONE;
790 }
791
792 static struct notifier_block eeh_reboot_nb = {
793         .notifier_call = eeh_reboot_notifier,
794 };
795
796 /**
797  * eeh_init - EEH initialization
798  *
799  * Initialize EEH by trying to enable it for all of the adapters in the system.
800  * As a side effect we can determine here if eeh is supported at all.
801  * Note that we leave EEH on so failed config cycles won't cause a machine
802  * check.  If a user turns off EEH for a particular adapter they are really
803  * telling Linux to ignore errors.  Some hardware (e.g. POWER5) won't
804  * grant access to a slot if EEH isn't enabled, and so we always enable
805  * EEH for all slots/all devices.
806  *
807  * The eeh-force-off option disables EEH checking globally, for all slots.
808  * Even if force-off is set, the EEH hardware is still enabled, so that
809  * newer systems can boot.
810  */
811 int eeh_init(void)
812 {
813         struct pci_controller *hose, *tmp;
814         struct device_node *phb;
815         static int cnt = 0;
816         int ret = 0;
817
818         /*
819          * We have to delay the initialization on PowerNV after
820          * the PCI hierarchy tree has been built because the PEs
821          * are figured out based on PCI devices instead of device
822          * tree nodes
823          */
824         if (machine_is(powernv) && cnt++ <= 0)
825                 return ret;
826
827         /* Register reboot notifier */
828         ret = register_reboot_notifier(&eeh_reboot_nb);
829         if (ret) {
830                 pr_warn("%s: Failed to register notifier (%d)\n",
831                         __func__, ret);
832                 return ret;
833         }
834
835         /* call platform initialization function */
836         if (!eeh_ops) {
837                 pr_warning("%s: Platform EEH operation not found\n",
838                         __func__);
839                 return -EEXIST;
840         } else if ((ret = eeh_ops->init())) {
841                 pr_warning("%s: Failed to call platform init function (%d)\n",
842                         __func__, ret);
843                 return ret;
844         }
845
846         /* Initialize EEH event */
847         ret = eeh_event_init();
848         if (ret)
849                 return ret;
850
851         /* Enable EEH for all adapters */
852         if (eeh_probe_mode_devtree()) {
853                 list_for_each_entry_safe(hose, tmp,
854                         &hose_list, list_node) {
855                         phb = hose->dn;
856                         traverse_pci_devices(phb, eeh_ops->of_probe, NULL);
857                 }
858         } else if (eeh_probe_mode_dev()) {
859                 list_for_each_entry_safe(hose, tmp,
860                         &hose_list, list_node)
861                         pci_walk_bus(hose->bus, eeh_ops->dev_probe, NULL);
862         } else {
863                 pr_warn("%s: Invalid probe mode %x",
864                         __func__, eeh_subsystem_flags);
865                 return -EINVAL;
866         }
867
868         /*
869          * Call platform post-initialization. Actually, It's good chance
870          * to inform platform that EEH is ready to supply service if the
871          * I/O cache stuff has been built up.
872          */
873         if (eeh_ops->post_init) {
874                 ret = eeh_ops->post_init();
875                 if (ret)
876                         return ret;
877         }
878
879         if (eeh_enabled())
880                 pr_info("EEH: PCI Enhanced I/O Error Handling Enabled\n");
881         else
882                 pr_warning("EEH: No capable adapters found\n");
883
884         return ret;
885 }
886
887 core_initcall_sync(eeh_init);
888
889 /**
890  * eeh_add_device_early - Enable EEH for the indicated device_node
891  * @dn: device node for which to set up EEH
892  *
893  * This routine must be used to perform EEH initialization for PCI
894  * devices that were added after system boot (e.g. hotplug, dlpar).
895  * This routine must be called before any i/o is performed to the
896  * adapter (inluding any config-space i/o).
897  * Whether this actually enables EEH or not for this device depends
898  * on the CEC architecture, type of the device, on earlier boot
899  * command-line arguments & etc.
900  */
901 void eeh_add_device_early(struct device_node *dn)
902 {
903         struct pci_controller *phb;
904
905         /*
906          * If we're doing EEH probe based on PCI device, we
907          * would delay the probe until late stage because
908          * the PCI device isn't available this moment.
909          */
910         if (!eeh_probe_mode_devtree())
911                 return;
912
913         if (!of_node_to_eeh_dev(dn))
914                 return;
915         phb = of_node_to_eeh_dev(dn)->phb;
916
917         /* USB Bus children of PCI devices will not have BUID's */
918         if (NULL == phb || 0 == phb->buid)
919                 return;
920
921         eeh_ops->of_probe(dn, NULL);
922 }
923
924 /**
925  * eeh_add_device_tree_early - Enable EEH for the indicated device
926  * @dn: device node
927  *
928  * This routine must be used to perform EEH initialization for the
929  * indicated PCI device that was added after system boot (e.g.
930  * hotplug, dlpar).
931  */
932 void eeh_add_device_tree_early(struct device_node *dn)
933 {
934         struct device_node *sib;
935
936         for_each_child_of_node(dn, sib)
937                 eeh_add_device_tree_early(sib);
938         eeh_add_device_early(dn);
939 }
940 EXPORT_SYMBOL_GPL(eeh_add_device_tree_early);
941
942 /**
943  * eeh_add_device_late - Perform EEH initialization for the indicated pci device
944  * @dev: pci device for which to set up EEH
945  *
946  * This routine must be used to complete EEH initialization for PCI
947  * devices that were added after system boot (e.g. hotplug, dlpar).
948  */
949 void eeh_add_device_late(struct pci_dev *dev)
950 {
951         struct device_node *dn;
952         struct eeh_dev *edev;
953
954         if (!dev || !eeh_enabled())
955                 return;
956
957         pr_debug("EEH: Adding device %s\n", pci_name(dev));
958
959         dn = pci_device_to_OF_node(dev);
960         edev = of_node_to_eeh_dev(dn);
961         if (edev->pdev == dev) {
962                 pr_debug("EEH: Already referenced !\n");
963                 return;
964         }
965
966         /*
967          * The EEH cache might not be removed correctly because of
968          * unbalanced kref to the device during unplug time, which
969          * relies on pcibios_release_device(). So we have to remove
970          * that here explicitly.
971          */
972         if (edev->pdev) {
973                 eeh_rmv_from_parent_pe(edev);
974                 eeh_addr_cache_rmv_dev(edev->pdev);
975                 eeh_sysfs_remove_device(edev->pdev);
976                 edev->mode &= ~EEH_DEV_SYSFS;
977
978                 /*
979                  * We definitely should have the PCI device removed
980                  * though it wasn't correctly. So we needn't call
981                  * into error handler afterwards.
982                  */
983                 edev->mode |= EEH_DEV_NO_HANDLER;
984
985                 edev->pdev = NULL;
986                 dev->dev.archdata.edev = NULL;
987         }
988
989         edev->pdev = dev;
990         dev->dev.archdata.edev = edev;
991
992         /*
993          * We have to do the EEH probe here because the PCI device
994          * hasn't been created yet in the early stage.
995          */
996         if (eeh_probe_mode_dev())
997                 eeh_ops->dev_probe(dev, NULL);
998
999         eeh_addr_cache_insert_dev(dev);
1000 }
1001
1002 /**
1003  * eeh_add_device_tree_late - Perform EEH initialization for the indicated PCI bus
1004  * @bus: PCI bus
1005  *
1006  * This routine must be used to perform EEH initialization for PCI
1007  * devices which are attached to the indicated PCI bus. The PCI bus
1008  * is added after system boot through hotplug or dlpar.
1009  */
1010 void eeh_add_device_tree_late(struct pci_bus *bus)
1011 {
1012         struct pci_dev *dev;
1013
1014         list_for_each_entry(dev, &bus->devices, bus_list) {
1015                 eeh_add_device_late(dev);
1016                 if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE) {
1017                         struct pci_bus *subbus = dev->subordinate;
1018                         if (subbus)
1019                                 eeh_add_device_tree_late(subbus);
1020                 }
1021         }
1022 }
1023 EXPORT_SYMBOL_GPL(eeh_add_device_tree_late);
1024
1025 /**
1026  * eeh_add_sysfs_files - Add EEH sysfs files for the indicated PCI bus
1027  * @bus: PCI bus
1028  *
1029  * This routine must be used to add EEH sysfs files for PCI
1030  * devices which are attached to the indicated PCI bus. The PCI bus
1031  * is added after system boot through hotplug or dlpar.
1032  */
1033 void eeh_add_sysfs_files(struct pci_bus *bus)
1034 {
1035         struct pci_dev *dev;
1036
1037         list_for_each_entry(dev, &bus->devices, bus_list) {
1038                 eeh_sysfs_add_device(dev);
1039                 if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE) {
1040                         struct pci_bus *subbus = dev->subordinate;
1041                         if (subbus)
1042                                 eeh_add_sysfs_files(subbus);
1043                 }
1044         }
1045 }
1046 EXPORT_SYMBOL_GPL(eeh_add_sysfs_files);
1047
1048 /**
1049  * eeh_remove_device - Undo EEH setup for the indicated pci device
1050  * @dev: pci device to be removed
1051  *
1052  * This routine should be called when a device is removed from
1053  * a running system (e.g. by hotplug or dlpar).  It unregisters
1054  * the PCI device from the EEH subsystem.  I/O errors affecting
1055  * this device will no longer be detected after this call; thus,
1056  * i/o errors affecting this slot may leave this device unusable.
1057  */
1058 void eeh_remove_device(struct pci_dev *dev)
1059 {
1060         struct eeh_dev *edev;
1061
1062         if (!dev || !eeh_enabled())
1063                 return;
1064         edev = pci_dev_to_eeh_dev(dev);
1065
1066         /* Unregister the device with the EEH/PCI address search system */
1067         pr_debug("EEH: Removing device %s\n", pci_name(dev));
1068
1069         if (!edev || !edev->pdev || !edev->pe) {
1070                 pr_debug("EEH: Not referenced !\n");
1071                 return;
1072         }
1073
1074         /*
1075          * During the hotplug for EEH error recovery, we need the EEH
1076          * device attached to the parent PE in order for BAR restore
1077          * a bit later. So we keep it for BAR restore and remove it
1078          * from the parent PE during the BAR resotre.
1079          */
1080         edev->pdev = NULL;
1081         dev->dev.archdata.edev = NULL;
1082         if (!(edev->pe->state & EEH_PE_KEEP))
1083                 eeh_rmv_from_parent_pe(edev);
1084         else
1085                 edev->mode |= EEH_DEV_DISCONNECTED;
1086
1087         /*
1088          * We're removing from the PCI subsystem, that means
1089          * the PCI device driver can't support EEH or not
1090          * well. So we rely on hotplug completely to do recovery
1091          * for the specific PCI device.
1092          */
1093         edev->mode |= EEH_DEV_NO_HANDLER;
1094
1095         eeh_addr_cache_rmv_dev(dev);
1096         eeh_sysfs_remove_device(dev);
1097         edev->mode &= ~EEH_DEV_SYSFS;
1098 }
1099
1100 static int proc_eeh_show(struct seq_file *m, void *v)
1101 {
1102         if (!eeh_enabled()) {
1103                 seq_printf(m, "EEH Subsystem is globally disabled\n");
1104                 seq_printf(m, "eeh_total_mmio_ffs=%llu\n", eeh_stats.total_mmio_ffs);
1105         } else {
1106                 seq_printf(m, "EEH Subsystem is enabled\n");
1107                 seq_printf(m,
1108                                 "no device=%llu\n"
1109                                 "no device node=%llu\n"
1110                                 "no config address=%llu\n"
1111                                 "check not wanted=%llu\n"
1112                                 "eeh_total_mmio_ffs=%llu\n"
1113                                 "eeh_false_positives=%llu\n"
1114                                 "eeh_slot_resets=%llu\n",
1115                                 eeh_stats.no_device,
1116                                 eeh_stats.no_dn,
1117                                 eeh_stats.no_cfg_addr,
1118                                 eeh_stats.ignored_check,
1119                                 eeh_stats.total_mmio_ffs,
1120                                 eeh_stats.false_positives,
1121                                 eeh_stats.slot_resets);
1122         }
1123
1124         return 0;
1125 }
1126
1127 static int proc_eeh_open(struct inode *inode, struct file *file)
1128 {
1129         return single_open(file, proc_eeh_show, NULL);
1130 }
1131
1132 static const struct file_operations proc_eeh_operations = {
1133         .open      = proc_eeh_open,
1134         .read      = seq_read,
1135         .llseek    = seq_lseek,
1136         .release   = single_release,
1137 };
1138
1139 #ifdef CONFIG_DEBUG_FS
1140 static int eeh_enable_dbgfs_set(void *data, u64 val)
1141 {
1142         if (val)
1143                 eeh_subsystem_flags &= ~EEH_FORCE_DISABLED;
1144         else
1145                 eeh_subsystem_flags |= EEH_FORCE_DISABLED;
1146
1147         /* Notify the backend */
1148         if (eeh_ops->post_init)
1149                 eeh_ops->post_init();
1150
1151         return 0;
1152 }
1153
1154 static int eeh_enable_dbgfs_get(void *data, u64 *val)
1155 {
1156         if (eeh_enabled())
1157                 *val = 0x1ul;
1158         else
1159                 *val = 0x0ul;
1160         return 0;
1161 }
1162
1163 DEFINE_SIMPLE_ATTRIBUTE(eeh_enable_dbgfs_ops, eeh_enable_dbgfs_get,
1164                         eeh_enable_dbgfs_set, "0x%llx\n");
1165 #endif
1166
1167 static int __init eeh_init_proc(void)
1168 {
1169         if (machine_is(pseries) || machine_is(powernv)) {
1170                 proc_create("powerpc/eeh", 0, NULL, &proc_eeh_operations);
1171 #ifdef CONFIG_DEBUG_FS
1172                 debugfs_create_file("eeh_enable", 0600,
1173                                     powerpc_debugfs_root, NULL,
1174                                     &eeh_enable_dbgfs_ops);
1175 #endif
1176         }
1177
1178         return 0;
1179 }
1180 __initcall(eeh_init_proc);