GNU Linux-libre 4.9.288-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/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/iommu.h>
31 #include <linux/proc_fs.h>
32 #include <linux/rbtree.h>
33 #include <linux/reboot.h>
34 #include <linux/seq_file.h>
35 #include <linux/spinlock.h>
36 #include <linux/export.h>
37 #include <linux/of.h>
38
39 #include <linux/atomic.h>
40 #include <asm/debug.h>
41 #include <asm/eeh.h>
42 #include <asm/eeh_event.h>
43 #include <asm/io.h>
44 #include <asm/iommu.h>
45 #include <asm/machdep.h>
46 #include <asm/ppc-pci.h>
47 #include <asm/rtas.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                        edev->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                 edev->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_linux_pte_or_hugepte(init_mm.pgd, token,
362                                            NULL, &hugepage_shift);
363         if (!ptep)
364                 return token;
365
366         pa = pte_pfn(*ptep);
367
368         /* On radix we can do hugepage mappings for io, so handle that */
369         if (!hugepage_shift)
370                 hugepage_shift = PAGE_SHIFT;
371
372         pa <<= PAGE_SHIFT;
373         pa |= token & ((1ul << hugepage_shift) - 1);
374         return pa;
375 }
376
377 /*
378  * On PowerNV platform, we might already have fenced PHB there.
379  * For that case, it's meaningless to recover frozen PE. Intead,
380  * We have to handle fenced PHB firstly.
381  */
382 static int eeh_phb_check_failure(struct eeh_pe *pe)
383 {
384         struct eeh_pe *phb_pe;
385         unsigned long flags;
386         int ret;
387
388         if (!eeh_has_flag(EEH_PROBE_MODE_DEV))
389                 return -EPERM;
390
391         /* Find the PHB PE */
392         phb_pe = eeh_phb_pe_get(pe->phb);
393         if (!phb_pe) {
394                 pr_warn("%s Can't find PE for PHB#%d\n",
395                         __func__, pe->phb->global_number);
396                 return -EEXIST;
397         }
398
399         /* If the PHB has been in problematic state */
400         eeh_serialize_lock(&flags);
401         if (phb_pe->state & EEH_PE_ISOLATED) {
402                 ret = 0;
403                 goto out;
404         }
405
406         /* Check PHB state */
407         ret = eeh_ops->get_state(phb_pe, NULL);
408         if ((ret < 0) ||
409             (ret == EEH_STATE_NOT_SUPPORT) ||
410             (ret & (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE)) ==
411             (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE)) {
412                 ret = 0;
413                 goto out;
414         }
415
416         /* Isolate the PHB and send event */
417         eeh_pe_state_mark(phb_pe, EEH_PE_ISOLATED);
418         eeh_serialize_unlock(flags);
419
420         pr_err("EEH: PHB#%x failure detected, location: %s\n",
421                 phb_pe->phb->global_number, eeh_pe_loc_get(phb_pe));
422         dump_stack();
423         eeh_send_failure_event(phb_pe);
424
425         return 1;
426 out:
427         eeh_serialize_unlock(flags);
428         return ret;
429 }
430
431 /**
432  * eeh_dev_check_failure - Check if all 1's data is due to EEH slot freeze
433  * @edev: eeh device
434  *
435  * Check for an EEH failure for the given device node.  Call this
436  * routine if the result of a read was all 0xff's and you want to
437  * find out if this is due to an EEH slot freeze.  This routine
438  * will query firmware for the EEH status.
439  *
440  * Returns 0 if there has not been an EEH error; otherwise returns
441  * a non-zero value and queues up a slot isolation event notification.
442  *
443  * It is safe to call this routine in an interrupt context.
444  */
445 int eeh_dev_check_failure(struct eeh_dev *edev)
446 {
447         int ret;
448         int active_flags = (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE);
449         unsigned long flags;
450         struct pci_dn *pdn;
451         struct pci_dev *dev;
452         struct eeh_pe *pe, *parent_pe, *phb_pe;
453         int rc = 0;
454         const char *location = NULL;
455
456         eeh_stats.total_mmio_ffs++;
457
458         if (!eeh_enabled())
459                 return 0;
460
461         if (!edev) {
462                 eeh_stats.no_dn++;
463                 return 0;
464         }
465         dev = eeh_dev_to_pci_dev(edev);
466         pe = eeh_dev_to_pe(edev);
467
468         /* Access to IO BARs might get this far and still not want checking. */
469         if (!pe) {
470                 eeh_stats.ignored_check++;
471                 pr_debug("EEH: Ignored check for %s\n",
472                         eeh_pci_name(dev));
473                 return 0;
474         }
475
476         if (!pe->addr && !pe->config_addr) {
477                 eeh_stats.no_cfg_addr++;
478                 return 0;
479         }
480
481         /*
482          * On PowerNV platform, we might already have fenced PHB
483          * there and we need take care of that firstly.
484          */
485         ret = eeh_phb_check_failure(pe);
486         if (ret > 0)
487                 return ret;
488
489         /*
490          * If the PE isn't owned by us, we shouldn't check the
491          * state. Instead, let the owner handle it if the PE has
492          * been frozen.
493          */
494         if (eeh_pe_passed(pe))
495                 return 0;
496
497         /* If we already have a pending isolation event for this
498          * slot, we know it's bad already, we don't need to check.
499          * Do this checking under a lock; as multiple PCI devices
500          * in one slot might report errors simultaneously, and we
501          * only want one error recovery routine running.
502          */
503         eeh_serialize_lock(&flags);
504         rc = 1;
505         if (pe->state & EEH_PE_ISOLATED) {
506                 pe->check_count++;
507                 if (pe->check_count % EEH_MAX_FAILS == 0) {
508                         pdn = eeh_dev_to_pdn(edev);
509                         if (pdn->node)
510                                 location = of_get_property(pdn->node, "ibm,loc-code", 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#%d-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_reset_pe_once - Assert the pci #RST line for 1/4 second
831  * @pe: EEH PE
832  *
833  * Assert the PCI #RST line for 1/4 second.
834  */
835 static void eeh_reset_pe_once(struct eeh_pe *pe)
836 {
837         unsigned int freset = 0;
838
839         /* Determine type of EEH reset required for
840          * Partitionable Endpoint, a hot-reset (1)
841          * or a fundamental reset (3).
842          * A fundamental reset required by any device under
843          * Partitionable Endpoint trumps hot-reset.
844          */
845         eeh_pe_dev_traverse(pe, eeh_set_dev_freset, &freset);
846
847         if (freset)
848                 eeh_ops->reset(pe, EEH_RESET_FUNDAMENTAL);
849         else
850                 eeh_ops->reset(pe, EEH_RESET_HOT);
851
852         eeh_ops->reset(pe, EEH_RESET_DEACTIVATE);
853 }
854
855 /**
856  * eeh_reset_pe - Reset the indicated PE
857  * @pe: EEH PE
858  *
859  * This routine should be called to reset indicated device, including
860  * PE. A PE might include multiple PCI devices and sometimes PCI bridges
861  * might be involved as well.
862  */
863 int eeh_reset_pe(struct eeh_pe *pe)
864 {
865         int flags = (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE);
866         int i, state, ret;
867
868         /* Mark as reset and block config space */
869         eeh_pe_state_mark(pe, EEH_PE_RESET | EEH_PE_CFG_BLOCKED);
870
871         /* Take three shots at resetting the bus */
872         for (i = 0; i < 3; i++) {
873                 eeh_reset_pe_once(pe);
874
875                 /*
876                  * EEH_PE_ISOLATED is expected to be removed after
877                  * BAR restore.
878                  */
879                 state = eeh_ops->wait_state(pe, PCI_BUS_RESET_WAIT_MSEC);
880                 if ((state & flags) == flags) {
881                         ret = 0;
882                         goto out;
883                 }
884
885                 if (state < 0) {
886                         pr_warn("%s: Unrecoverable slot failure on PHB#%d-PE#%x",
887                                 __func__, pe->phb->global_number, pe->addr);
888                         ret = -ENOTRECOVERABLE;
889                         goto out;
890                 }
891
892                 /* We might run out of credits */
893                 ret = -EIO;
894                 pr_warn("%s: Failure %d resetting PHB#%x-PE#%x\n (%d)\n",
895                         __func__, state, pe->phb->global_number, pe->addr, (i + 1));
896         }
897
898 out:
899         eeh_pe_state_clear(pe, EEH_PE_RESET | EEH_PE_CFG_BLOCKED);
900         return ret;
901 }
902
903 /**
904  * eeh_save_bars - Save device bars
905  * @edev: PCI device associated EEH device
906  *
907  * Save the values of the device bars. Unlike the restore
908  * routine, this routine is *not* recursive. This is because
909  * PCI devices are added individually; but, for the restore,
910  * an entire slot is reset at a time.
911  */
912 void eeh_save_bars(struct eeh_dev *edev)
913 {
914         struct pci_dn *pdn;
915         int i;
916
917         pdn = eeh_dev_to_pdn(edev);
918         if (!pdn)
919                 return;
920
921         for (i = 0; i < 16; i++)
922                 eeh_ops->read_config(pdn, i * 4, 4, &edev->config_space[i]);
923
924         /*
925          * For PCI bridges including root port, we need enable bus
926          * master explicitly. Otherwise, it can't fetch IODA table
927          * entries correctly. So we cache the bit in advance so that
928          * we can restore it after reset, either PHB range or PE range.
929          */
930         if (edev->mode & EEH_DEV_BRIDGE)
931                 edev->config_space[1] |= PCI_COMMAND_MASTER;
932 }
933
934 /**
935  * eeh_ops_register - Register platform dependent EEH operations
936  * @ops: platform dependent EEH operations
937  *
938  * Register the platform dependent EEH operation callback
939  * functions. The platform should call this function before
940  * any other EEH operations.
941  */
942 int __init eeh_ops_register(struct eeh_ops *ops)
943 {
944         if (!ops->name) {
945                 pr_warn("%s: Invalid EEH ops name for %p\n",
946                         __func__, ops);
947                 return -EINVAL;
948         }
949
950         if (eeh_ops && eeh_ops != ops) {
951                 pr_warn("%s: EEH ops of platform %s already existing (%s)\n",
952                         __func__, eeh_ops->name, ops->name);
953                 return -EEXIST;
954         }
955
956         eeh_ops = ops;
957
958         return 0;
959 }
960
961 /**
962  * eeh_ops_unregister - Unreigster platform dependent EEH operations
963  * @name: name of EEH platform operations
964  *
965  * Unregister the platform dependent EEH operation callback
966  * functions.
967  */
968 int __exit eeh_ops_unregister(const char *name)
969 {
970         if (!name || !strlen(name)) {
971                 pr_warn("%s: Invalid EEH ops name\n",
972                         __func__);
973                 return -EINVAL;
974         }
975
976         if (eeh_ops && !strcmp(eeh_ops->name, name)) {
977                 eeh_ops = NULL;
978                 return 0;
979         }
980
981         return -EEXIST;
982 }
983
984 static int eeh_reboot_notifier(struct notifier_block *nb,
985                                unsigned long action, void *unused)
986 {
987         eeh_clear_flag(EEH_ENABLED);
988         return NOTIFY_DONE;
989 }
990
991 static struct notifier_block eeh_reboot_nb = {
992         .notifier_call = eeh_reboot_notifier,
993 };
994
995 /**
996  * eeh_init - EEH initialization
997  *
998  * Initialize EEH by trying to enable it for all of the adapters in the system.
999  * As a side effect we can determine here if eeh is supported at all.
1000  * Note that we leave EEH on so failed config cycles won't cause a machine
1001  * check.  If a user turns off EEH for a particular adapter they are really
1002  * telling Linux to ignore errors.  Some hardware (e.g. POWER5) won't
1003  * grant access to a slot if EEH isn't enabled, and so we always enable
1004  * EEH for all slots/all devices.
1005  *
1006  * The eeh-force-off option disables EEH checking globally, for all slots.
1007  * Even if force-off is set, the EEH hardware is still enabled, so that
1008  * newer systems can boot.
1009  */
1010 int eeh_init(void)
1011 {
1012         struct pci_controller *hose, *tmp;
1013         struct pci_dn *pdn;
1014         static int cnt = 0;
1015         int ret = 0;
1016
1017         /*
1018          * We have to delay the initialization on PowerNV after
1019          * the PCI hierarchy tree has been built because the PEs
1020          * are figured out based on PCI devices instead of device
1021          * tree nodes
1022          */
1023         if (machine_is(powernv) && cnt++ <= 0)
1024                 return ret;
1025
1026         /* Register reboot notifier */
1027         ret = register_reboot_notifier(&eeh_reboot_nb);
1028         if (ret) {
1029                 pr_warn("%s: Failed to register notifier (%d)\n",
1030                         __func__, ret);
1031                 return ret;
1032         }
1033
1034         /* call platform initialization function */
1035         if (!eeh_ops) {
1036                 pr_warn("%s: Platform EEH operation not found\n",
1037                         __func__);
1038                 return -EEXIST;
1039         } else if ((ret = eeh_ops->init()))
1040                 return ret;
1041
1042         /* Initialize EEH event */
1043         ret = eeh_event_init();
1044         if (ret)
1045                 return ret;
1046
1047         /* Enable EEH for all adapters */
1048         list_for_each_entry_safe(hose, tmp, &hose_list, list_node) {
1049                 pdn = hose->pci_data;
1050                 traverse_pci_dn(pdn, eeh_ops->probe, NULL);
1051         }
1052
1053         /*
1054          * Call platform post-initialization. Actually, It's good chance
1055          * to inform platform that EEH is ready to supply service if the
1056          * I/O cache stuff has been built up.
1057          */
1058         if (eeh_ops->post_init) {
1059                 ret = eeh_ops->post_init();
1060                 if (ret)
1061                         return ret;
1062         }
1063
1064         if (eeh_enabled())
1065                 pr_info("EEH: PCI Enhanced I/O Error Handling Enabled\n");
1066         else
1067                 pr_info("EEH: No capable adapters found\n");
1068
1069         return ret;
1070 }
1071
1072 core_initcall_sync(eeh_init);
1073
1074 /**
1075  * eeh_add_device_early - Enable EEH for the indicated device node
1076  * @pdn: PCI device node for which to set up EEH
1077  *
1078  * This routine must be used to perform EEH initialization for PCI
1079  * devices that were added after system boot (e.g. hotplug, dlpar).
1080  * This routine must be called before any i/o is performed to the
1081  * adapter (inluding any config-space i/o).
1082  * Whether this actually enables EEH or not for this device depends
1083  * on the CEC architecture, type of the device, on earlier boot
1084  * command-line arguments & etc.
1085  */
1086 void eeh_add_device_early(struct pci_dn *pdn)
1087 {
1088         struct pci_controller *phb;
1089         struct eeh_dev *edev = pdn_to_eeh_dev(pdn);
1090
1091         if (!edev)
1092                 return;
1093
1094         if (!eeh_has_flag(EEH_PROBE_MODE_DEVTREE))
1095                 return;
1096
1097         /* USB Bus children of PCI devices will not have BUID's */
1098         phb = edev->phb;
1099         if (NULL == phb ||
1100             (eeh_has_flag(EEH_PROBE_MODE_DEVTREE) && 0 == phb->buid))
1101                 return;
1102
1103         eeh_ops->probe(pdn, NULL);
1104 }
1105
1106 /**
1107  * eeh_add_device_tree_early - Enable EEH for the indicated device
1108  * @pdn: PCI device node
1109  *
1110  * This routine must be used to perform EEH initialization for the
1111  * indicated PCI device that was added after system boot (e.g.
1112  * hotplug, dlpar).
1113  */
1114 void eeh_add_device_tree_early(struct pci_dn *pdn)
1115 {
1116         struct pci_dn *n;
1117
1118         if (!pdn)
1119                 return;
1120
1121         list_for_each_entry(n, &pdn->child_list, list)
1122                 eeh_add_device_tree_early(n);
1123         eeh_add_device_early(pdn);
1124 }
1125 EXPORT_SYMBOL_GPL(eeh_add_device_tree_early);
1126
1127 /**
1128  * eeh_add_device_late - Perform EEH initialization for the indicated pci device
1129  * @dev: pci device for which to set up EEH
1130  *
1131  * This routine must be used to complete EEH initialization for PCI
1132  * devices that were added after system boot (e.g. hotplug, dlpar).
1133  */
1134 void eeh_add_device_late(struct pci_dev *dev)
1135 {
1136         struct pci_dn *pdn;
1137         struct eeh_dev *edev;
1138
1139         if (!dev || !eeh_enabled())
1140                 return;
1141
1142         pr_debug("EEH: Adding device %s\n", pci_name(dev));
1143
1144         pdn = pci_get_pdn_by_devfn(dev->bus, dev->devfn);
1145         edev = pdn_to_eeh_dev(pdn);
1146         if (edev->pdev == dev) {
1147                 pr_debug("EEH: Already referenced !\n");
1148                 return;
1149         }
1150
1151         /*
1152          * The EEH cache might not be removed correctly because of
1153          * unbalanced kref to the device during unplug time, which
1154          * relies on pcibios_release_device(). So we have to remove
1155          * that here explicitly.
1156          */
1157         if (edev->pdev) {
1158                 eeh_rmv_from_parent_pe(edev);
1159                 eeh_addr_cache_rmv_dev(edev->pdev);
1160                 eeh_sysfs_remove_device(edev->pdev);
1161                 edev->mode &= ~EEH_DEV_SYSFS;
1162
1163                 /*
1164                  * We definitely should have the PCI device removed
1165                  * though it wasn't correctly. So we needn't call
1166                  * into error handler afterwards.
1167                  */
1168                 edev->mode |= EEH_DEV_NO_HANDLER;
1169
1170                 edev->pdev = NULL;
1171                 dev->dev.archdata.edev = NULL;
1172         }
1173
1174         if (eeh_has_flag(EEH_PROBE_MODE_DEV))
1175                 eeh_ops->probe(pdn, NULL);
1176
1177         edev->pdev = dev;
1178         dev->dev.archdata.edev = edev;
1179
1180         eeh_addr_cache_insert_dev(dev);
1181 }
1182
1183 /**
1184  * eeh_add_device_tree_late - Perform EEH initialization for the indicated PCI bus
1185  * @bus: PCI bus
1186  *
1187  * This routine must be used to perform EEH initialization for PCI
1188  * devices which are attached to the indicated PCI bus. The PCI bus
1189  * is added after system boot through hotplug or dlpar.
1190  */
1191 void eeh_add_device_tree_late(struct pci_bus *bus)
1192 {
1193         struct pci_dev *dev;
1194
1195         list_for_each_entry(dev, &bus->devices, bus_list) {
1196                 eeh_add_device_late(dev);
1197                 if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE) {
1198                         struct pci_bus *subbus = dev->subordinate;
1199                         if (subbus)
1200                                 eeh_add_device_tree_late(subbus);
1201                 }
1202         }
1203 }
1204 EXPORT_SYMBOL_GPL(eeh_add_device_tree_late);
1205
1206 /**
1207  * eeh_add_sysfs_files - Add EEH sysfs files for the indicated PCI bus
1208  * @bus: PCI bus
1209  *
1210  * This routine must be used to add EEH sysfs files for PCI
1211  * devices which are attached to the indicated PCI bus. The PCI bus
1212  * is added after system boot through hotplug or dlpar.
1213  */
1214 void eeh_add_sysfs_files(struct pci_bus *bus)
1215 {
1216         struct pci_dev *dev;
1217
1218         list_for_each_entry(dev, &bus->devices, bus_list) {
1219                 eeh_sysfs_add_device(dev);
1220                 if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE) {
1221                         struct pci_bus *subbus = dev->subordinate;
1222                         if (subbus)
1223                                 eeh_add_sysfs_files(subbus);
1224                 }
1225         }
1226 }
1227 EXPORT_SYMBOL_GPL(eeh_add_sysfs_files);
1228
1229 /**
1230  * eeh_remove_device - Undo EEH setup for the indicated pci device
1231  * @dev: pci device to be removed
1232  *
1233  * This routine should be called when a device is removed from
1234  * a running system (e.g. by hotplug or dlpar).  It unregisters
1235  * the PCI device from the EEH subsystem.  I/O errors affecting
1236  * this device will no longer be detected after this call; thus,
1237  * i/o errors affecting this slot may leave this device unusable.
1238  */
1239 void eeh_remove_device(struct pci_dev *dev)
1240 {
1241         struct eeh_dev *edev;
1242
1243         if (!dev || !eeh_enabled())
1244                 return;
1245         edev = pci_dev_to_eeh_dev(dev);
1246
1247         /* Unregister the device with the EEH/PCI address search system */
1248         pr_debug("EEH: Removing device %s\n", pci_name(dev));
1249
1250         if (!edev || !edev->pdev || !edev->pe) {
1251                 pr_debug("EEH: Not referenced !\n");
1252                 return;
1253         }
1254
1255         /*
1256          * During the hotplug for EEH error recovery, we need the EEH
1257          * device attached to the parent PE in order for BAR restore
1258          * a bit later. So we keep it for BAR restore and remove it
1259          * from the parent PE during the BAR resotre.
1260          */
1261         edev->pdev = NULL;
1262
1263         /*
1264          * The flag "in_error" is used to trace EEH devices for VFs
1265          * in error state or not. It's set in eeh_report_error(). If
1266          * it's not set, eeh_report_{reset,resume}() won't be called
1267          * for the VF EEH device.
1268          */
1269         edev->in_error = false;
1270         dev->dev.archdata.edev = NULL;
1271         if (!(edev->pe->state & EEH_PE_KEEP))
1272                 eeh_rmv_from_parent_pe(edev);
1273         else
1274                 edev->mode |= EEH_DEV_DISCONNECTED;
1275
1276         /*
1277          * We're removing from the PCI subsystem, that means
1278          * the PCI device driver can't support EEH or not
1279          * well. So we rely on hotplug completely to do recovery
1280          * for the specific PCI device.
1281          */
1282         edev->mode |= EEH_DEV_NO_HANDLER;
1283
1284         eeh_addr_cache_rmv_dev(dev);
1285         eeh_sysfs_remove_device(dev);
1286         edev->mode &= ~EEH_DEV_SYSFS;
1287 }
1288
1289 int eeh_unfreeze_pe(struct eeh_pe *pe, bool sw_state)
1290 {
1291         int ret;
1292
1293         ret = eeh_pci_enable(pe, EEH_OPT_THAW_MMIO);
1294         if (ret) {
1295                 pr_warn("%s: Failure %d enabling IO on PHB#%x-PE#%x\n",
1296                         __func__, ret, pe->phb->global_number, pe->addr);
1297                 return ret;
1298         }
1299
1300         ret = eeh_pci_enable(pe, EEH_OPT_THAW_DMA);
1301         if (ret) {
1302                 pr_warn("%s: Failure %d enabling DMA on PHB#%x-PE#%x\n",
1303                         __func__, ret, pe->phb->global_number, pe->addr);
1304                 return ret;
1305         }
1306
1307         /* Clear software isolated state */
1308         if (sw_state && (pe->state & EEH_PE_ISOLATED))
1309                 eeh_pe_state_clear(pe, EEH_PE_ISOLATED);
1310
1311         return ret;
1312 }
1313
1314
1315 static struct pci_device_id eeh_reset_ids[] = {
1316         { PCI_DEVICE(0x19a2, 0x0710) }, /* Emulex, BE     */
1317         { PCI_DEVICE(0x10df, 0xe220) }, /* Emulex, Lancer */
1318         { PCI_DEVICE(0x14e4, 0x1657) }, /* Broadcom BCM5719 */
1319         { 0 }
1320 };
1321
1322 static int eeh_pe_change_owner(struct eeh_pe *pe)
1323 {
1324         struct eeh_dev *edev, *tmp;
1325         struct pci_dev *pdev;
1326         struct pci_device_id *id;
1327         int flags, ret;
1328
1329         /* Check PE state */
1330         flags = (EEH_STATE_MMIO_ACTIVE | EEH_STATE_DMA_ACTIVE);
1331         ret = eeh_ops->get_state(pe, NULL);
1332         if (ret < 0 || ret == EEH_STATE_NOT_SUPPORT)
1333                 return 0;
1334
1335         /* Unfrozen PE, nothing to do */
1336         if ((ret & flags) == flags)
1337                 return 0;
1338
1339         /* Frozen PE, check if it needs PE level reset */
1340         eeh_pe_for_each_dev(pe, edev, tmp) {
1341                 pdev = eeh_dev_to_pci_dev(edev);
1342                 if (!pdev)
1343                         continue;
1344
1345                 for (id = &eeh_reset_ids[0]; id->vendor != 0; id++) {
1346                         if (id->vendor != PCI_ANY_ID &&
1347                             id->vendor != pdev->vendor)
1348                                 continue;
1349                         if (id->device != PCI_ANY_ID &&
1350                             id->device != pdev->device)
1351                                 continue;
1352                         if (id->subvendor != PCI_ANY_ID &&
1353                             id->subvendor != pdev->subsystem_vendor)
1354                                 continue;
1355                         if (id->subdevice != PCI_ANY_ID &&
1356                             id->subdevice != pdev->subsystem_device)
1357                                 continue;
1358
1359                         return eeh_pe_reset_and_recover(pe);
1360                 }
1361         }
1362
1363         return eeh_unfreeze_pe(pe, true);
1364 }
1365
1366 /**
1367  * eeh_dev_open - Increase count of pass through devices for PE
1368  * @pdev: PCI device
1369  *
1370  * Increase count of passed through devices for the indicated
1371  * PE. In the result, the EEH errors detected on the PE won't be
1372  * reported. The PE owner will be responsible for detection
1373  * and recovery.
1374  */
1375 int eeh_dev_open(struct pci_dev *pdev)
1376 {
1377         struct eeh_dev *edev;
1378         int ret = -ENODEV;
1379
1380         mutex_lock(&eeh_dev_mutex);
1381
1382         /* No PCI device ? */
1383         if (!pdev)
1384                 goto out;
1385
1386         /* No EEH device or PE ? */
1387         edev = pci_dev_to_eeh_dev(pdev);
1388         if (!edev || !edev->pe)
1389                 goto out;
1390
1391         /*
1392          * The PE might have been put into frozen state, but we
1393          * didn't detect that yet. The passed through PCI devices
1394          * in frozen PE won't work properly. Clear the frozen state
1395          * in advance.
1396          */
1397         ret = eeh_pe_change_owner(edev->pe);
1398         if (ret)
1399                 goto out;
1400
1401         /* Increase PE's pass through count */
1402         atomic_inc(&edev->pe->pass_dev_cnt);
1403         mutex_unlock(&eeh_dev_mutex);
1404
1405         return 0;
1406 out:
1407         mutex_unlock(&eeh_dev_mutex);
1408         return ret;
1409 }
1410 EXPORT_SYMBOL_GPL(eeh_dev_open);
1411
1412 /**
1413  * eeh_dev_release - Decrease count of pass through devices for PE
1414  * @pdev: PCI device
1415  *
1416  * Decrease count of pass through devices for the indicated PE. If
1417  * there is no passed through device in PE, the EEH errors detected
1418  * on the PE will be reported and handled as usual.
1419  */
1420 void eeh_dev_release(struct pci_dev *pdev)
1421 {
1422         struct eeh_dev *edev;
1423
1424         mutex_lock(&eeh_dev_mutex);
1425
1426         /* No PCI device ? */
1427         if (!pdev)
1428                 goto out;
1429
1430         /* No EEH device ? */
1431         edev = pci_dev_to_eeh_dev(pdev);
1432         if (!edev || !edev->pe || !eeh_pe_passed(edev->pe))
1433                 goto out;
1434
1435         /* Decrease PE's pass through count */
1436         WARN_ON(atomic_dec_if_positive(&edev->pe->pass_dev_cnt) < 0);
1437         eeh_pe_change_owner(edev->pe);
1438 out:
1439         mutex_unlock(&eeh_dev_mutex);
1440 }
1441 EXPORT_SYMBOL(eeh_dev_release);
1442
1443 #ifdef CONFIG_IOMMU_API
1444
1445 static int dev_has_iommu_table(struct device *dev, void *data)
1446 {
1447         struct pci_dev *pdev = to_pci_dev(dev);
1448         struct pci_dev **ppdev = data;
1449
1450         if (!dev)
1451                 return 0;
1452
1453         if (dev->iommu_group) {
1454                 *ppdev = pdev;
1455                 return 1;
1456         }
1457
1458         return 0;
1459 }
1460
1461 /**
1462  * eeh_iommu_group_to_pe - Convert IOMMU group to EEH PE
1463  * @group: IOMMU group
1464  *
1465  * The routine is called to convert IOMMU group to EEH PE.
1466  */
1467 struct eeh_pe *eeh_iommu_group_to_pe(struct iommu_group *group)
1468 {
1469         struct pci_dev *pdev = NULL;
1470         struct eeh_dev *edev;
1471         int ret;
1472
1473         /* No IOMMU group ? */
1474         if (!group)
1475                 return NULL;
1476
1477         ret = iommu_group_for_each_dev(group, &pdev, dev_has_iommu_table);
1478         if (!ret || !pdev)
1479                 return NULL;
1480
1481         /* No EEH device or PE ? */
1482         edev = pci_dev_to_eeh_dev(pdev);
1483         if (!edev || !edev->pe)
1484                 return NULL;
1485
1486         return edev->pe;
1487 }
1488 EXPORT_SYMBOL_GPL(eeh_iommu_group_to_pe);
1489
1490 #endif /* CONFIG_IOMMU_API */
1491
1492 /**
1493  * eeh_pe_set_option - Set options for the indicated PE
1494  * @pe: EEH PE
1495  * @option: requested option
1496  *
1497  * The routine is called to enable or disable EEH functionality
1498  * on the indicated PE, to enable IO or DMA for the frozen PE.
1499  */
1500 int eeh_pe_set_option(struct eeh_pe *pe, int option)
1501 {
1502         int ret = 0;
1503
1504         /* Invalid PE ? */
1505         if (!pe)
1506                 return -ENODEV;
1507
1508         /*
1509          * EEH functionality could possibly be disabled, just
1510          * return error for the case. And the EEH functinality
1511          * isn't expected to be disabled on one specific PE.
1512          */
1513         switch (option) {
1514         case EEH_OPT_ENABLE:
1515                 if (eeh_enabled()) {
1516                         ret = eeh_pe_change_owner(pe);
1517                         break;
1518                 }
1519                 ret = -EIO;
1520                 break;
1521         case EEH_OPT_DISABLE:
1522                 break;
1523         case EEH_OPT_THAW_MMIO:
1524         case EEH_OPT_THAW_DMA:
1525         case EEH_OPT_FREEZE_PE:
1526                 if (!eeh_ops || !eeh_ops->set_option) {
1527                         ret = -ENOENT;
1528                         break;
1529                 }
1530
1531                 ret = eeh_pci_enable(pe, option);
1532                 break;
1533         default:
1534                 pr_debug("%s: Option %d out of range (%d, %d)\n",
1535                         __func__, option, EEH_OPT_DISABLE, EEH_OPT_THAW_DMA);
1536                 ret = -EINVAL;
1537         }
1538
1539         return ret;
1540 }
1541 EXPORT_SYMBOL_GPL(eeh_pe_set_option);
1542
1543 /**
1544  * eeh_pe_get_state - Retrieve PE's state
1545  * @pe: EEH PE
1546  *
1547  * Retrieve the PE's state, which includes 3 aspects: enabled
1548  * DMA, enabled IO and asserted reset.
1549  */
1550 int eeh_pe_get_state(struct eeh_pe *pe)
1551 {
1552         int result, ret = 0;
1553         bool rst_active, dma_en, mmio_en;
1554
1555         /* Existing PE ? */
1556         if (!pe)
1557                 return -ENODEV;
1558
1559         if (!eeh_ops || !eeh_ops->get_state)
1560                 return -ENOENT;
1561
1562         /*
1563          * If the parent PE is owned by the host kernel and is undergoing
1564          * error recovery, we should return the PE state as temporarily
1565          * unavailable so that the error recovery on the guest is suspended
1566          * until the recovery completes on the host.
1567          */
1568         if (pe->parent &&
1569             !(pe->state & EEH_PE_REMOVED) &&
1570             (pe->parent->state & (EEH_PE_ISOLATED | EEH_PE_RECOVERING)))
1571                 return EEH_PE_STATE_UNAVAIL;
1572
1573         result = eeh_ops->get_state(pe, NULL);
1574         rst_active = !!(result & EEH_STATE_RESET_ACTIVE);
1575         dma_en = !!(result & EEH_STATE_DMA_ENABLED);
1576         mmio_en = !!(result & EEH_STATE_MMIO_ENABLED);
1577
1578         if (rst_active)
1579                 ret = EEH_PE_STATE_RESET;
1580         else if (dma_en && mmio_en)
1581                 ret = EEH_PE_STATE_NORMAL;
1582         else if (!dma_en && !mmio_en)
1583                 ret = EEH_PE_STATE_STOPPED_IO_DMA;
1584         else if (!dma_en && mmio_en)
1585                 ret = EEH_PE_STATE_STOPPED_DMA;
1586         else
1587                 ret = EEH_PE_STATE_UNAVAIL;
1588
1589         return ret;
1590 }
1591 EXPORT_SYMBOL_GPL(eeh_pe_get_state);
1592
1593 static int eeh_pe_reenable_devices(struct eeh_pe *pe)
1594 {
1595         struct eeh_dev *edev, *tmp;
1596         struct pci_dev *pdev;
1597         int ret = 0;
1598
1599         /* Restore config space */
1600         eeh_pe_restore_bars(pe);
1601
1602         /*
1603          * Reenable PCI devices as the devices passed
1604          * through are always enabled before the reset.
1605          */
1606         eeh_pe_for_each_dev(pe, edev, tmp) {
1607                 pdev = eeh_dev_to_pci_dev(edev);
1608                 if (!pdev)
1609                         continue;
1610
1611                 ret = pci_reenable_device(pdev);
1612                 if (ret) {
1613                         pr_warn("%s: Failure %d reenabling %s\n",
1614                                 __func__, ret, pci_name(pdev));
1615                         return ret;
1616                 }
1617         }
1618
1619         /* The PE is still in frozen state */
1620         return eeh_unfreeze_pe(pe, true);
1621 }
1622
1623 /**
1624  * eeh_pe_reset - Issue PE reset according to specified type
1625  * @pe: EEH PE
1626  * @option: reset type
1627  *
1628  * The routine is called to reset the specified PE with the
1629  * indicated type, either fundamental reset or hot reset.
1630  * PE reset is the most important part for error recovery.
1631  */
1632 int eeh_pe_reset(struct eeh_pe *pe, int option)
1633 {
1634         int ret = 0;
1635
1636         /* Invalid PE ? */
1637         if (!pe)
1638                 return -ENODEV;
1639
1640         if (!eeh_ops || !eeh_ops->set_option || !eeh_ops->reset)
1641                 return -ENOENT;
1642
1643         switch (option) {
1644         case EEH_RESET_DEACTIVATE:
1645                 ret = eeh_ops->reset(pe, option);
1646                 eeh_pe_state_clear(pe, EEH_PE_CFG_BLOCKED);
1647                 if (ret)
1648                         break;
1649
1650                 ret = eeh_pe_reenable_devices(pe);
1651                 break;
1652         case EEH_RESET_HOT:
1653         case EEH_RESET_FUNDAMENTAL:
1654                 /*
1655                  * Proactively freeze the PE to drop all MMIO access
1656                  * during reset, which should be banned as it's always
1657                  * cause recursive EEH error.
1658                  */
1659                 eeh_ops->set_option(pe, EEH_OPT_FREEZE_PE);
1660
1661                 eeh_pe_state_mark(pe, EEH_PE_CFG_BLOCKED);
1662                 ret = eeh_ops->reset(pe, option);
1663                 break;
1664         default:
1665                 pr_debug("%s: Unsupported option %d\n",
1666                         __func__, option);
1667                 ret = -EINVAL;
1668         }
1669
1670         return ret;
1671 }
1672 EXPORT_SYMBOL_GPL(eeh_pe_reset);
1673
1674 /**
1675  * eeh_pe_configure - Configure PCI bridges after PE reset
1676  * @pe: EEH PE
1677  *
1678  * The routine is called to restore the PCI config space for
1679  * those PCI devices, especially PCI bridges affected by PE
1680  * reset issued previously.
1681  */
1682 int eeh_pe_configure(struct eeh_pe *pe)
1683 {
1684         int ret = 0;
1685
1686         /* Invalid PE ? */
1687         if (!pe)
1688                 return -ENODEV;
1689
1690         return ret;
1691 }
1692 EXPORT_SYMBOL_GPL(eeh_pe_configure);
1693
1694 /**
1695  * eeh_pe_inject_err - Injecting the specified PCI error to the indicated PE
1696  * @pe: the indicated PE
1697  * @type: error type
1698  * @function: error function
1699  * @addr: address
1700  * @mask: address mask
1701  *
1702  * The routine is called to inject the specified PCI error, which
1703  * is determined by @type and @function, to the indicated PE for
1704  * testing purpose.
1705  */
1706 int eeh_pe_inject_err(struct eeh_pe *pe, int type, int func,
1707                       unsigned long addr, unsigned long mask)
1708 {
1709         /* Invalid PE ? */
1710         if (!pe)
1711                 return -ENODEV;
1712
1713         /* Unsupported operation ? */
1714         if (!eeh_ops || !eeh_ops->err_inject)
1715                 return -ENOENT;
1716
1717         /* Check on PCI error type */
1718         if (type != EEH_ERR_TYPE_32 && type != EEH_ERR_TYPE_64)
1719                 return -EINVAL;
1720
1721         /* Check on PCI error function */
1722         if (func < EEH_ERR_FUNC_MIN || func > EEH_ERR_FUNC_MAX)
1723                 return -EINVAL;
1724
1725         return eeh_ops->err_inject(pe, type, func, addr, mask);
1726 }
1727 EXPORT_SYMBOL_GPL(eeh_pe_inject_err);
1728
1729 static int proc_eeh_show(struct seq_file *m, void *v)
1730 {
1731         if (!eeh_enabled()) {
1732                 seq_printf(m, "EEH Subsystem is globally disabled\n");
1733                 seq_printf(m, "eeh_total_mmio_ffs=%llu\n", eeh_stats.total_mmio_ffs);
1734         } else {
1735                 seq_printf(m, "EEH Subsystem is enabled\n");
1736                 seq_printf(m,
1737                                 "no device=%llu\n"
1738                                 "no device node=%llu\n"
1739                                 "no config address=%llu\n"
1740                                 "check not wanted=%llu\n"
1741                                 "eeh_total_mmio_ffs=%llu\n"
1742                                 "eeh_false_positives=%llu\n"
1743                                 "eeh_slot_resets=%llu\n",
1744                                 eeh_stats.no_device,
1745                                 eeh_stats.no_dn,
1746                                 eeh_stats.no_cfg_addr,
1747                                 eeh_stats.ignored_check,
1748                                 eeh_stats.total_mmio_ffs,
1749                                 eeh_stats.false_positives,
1750                                 eeh_stats.slot_resets);
1751         }
1752
1753         return 0;
1754 }
1755
1756 static int proc_eeh_open(struct inode *inode, struct file *file)
1757 {
1758         return single_open(file, proc_eeh_show, NULL);
1759 }
1760
1761 static const struct file_operations proc_eeh_operations = {
1762         .open      = proc_eeh_open,
1763         .read      = seq_read,
1764         .llseek    = seq_lseek,
1765         .release   = single_release,
1766 };
1767
1768 #ifdef CONFIG_DEBUG_FS
1769 static int eeh_enable_dbgfs_set(void *data, u64 val)
1770 {
1771         if (val)
1772                 eeh_clear_flag(EEH_FORCE_DISABLED);
1773         else
1774                 eeh_add_flag(EEH_FORCE_DISABLED);
1775
1776         /* Notify the backend */
1777         if (eeh_ops->post_init)
1778                 eeh_ops->post_init();
1779
1780         return 0;
1781 }
1782
1783 static int eeh_enable_dbgfs_get(void *data, u64 *val)
1784 {
1785         if (eeh_enabled())
1786                 *val = 0x1ul;
1787         else
1788                 *val = 0x0ul;
1789         return 0;
1790 }
1791
1792 static int eeh_freeze_dbgfs_set(void *data, u64 val)
1793 {
1794         eeh_max_freezes = val;
1795         return 0;
1796 }
1797
1798 static int eeh_freeze_dbgfs_get(void *data, u64 *val)
1799 {
1800         *val = eeh_max_freezes;
1801         return 0;
1802 }
1803
1804 DEFINE_SIMPLE_ATTRIBUTE(eeh_enable_dbgfs_ops, eeh_enable_dbgfs_get,
1805                         eeh_enable_dbgfs_set, "0x%llx\n");
1806 DEFINE_SIMPLE_ATTRIBUTE(eeh_freeze_dbgfs_ops, eeh_freeze_dbgfs_get,
1807                         eeh_freeze_dbgfs_set, "0x%llx\n");
1808 #endif
1809
1810 static int __init eeh_init_proc(void)
1811 {
1812         if (machine_is(pseries) || machine_is(powernv)) {
1813                 proc_create("powerpc/eeh", 0, NULL, &proc_eeh_operations);
1814 #ifdef CONFIG_DEBUG_FS
1815                 debugfs_create_file("eeh_enable", 0600,
1816                                     powerpc_debugfs_root, NULL,
1817                                     &eeh_enable_dbgfs_ops);
1818                 debugfs_create_file("eeh_max_freezes", 0600,
1819                                     powerpc_debugfs_root, NULL,
1820                                     &eeh_freeze_dbgfs_ops);
1821 #endif
1822         }
1823
1824         return 0;
1825 }
1826 __initcall(eeh_init_proc);