]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cam/cam_periph.c
cam: clear stack-allocated CCB in the target layer
[FreeBSD/FreeBSD.git] / sys / cam / cam_periph.c
1 /*-
2  * Common functions for CAM "type" (peripheral) drivers.
3  *
4  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
5  *
6  * Copyright (c) 1997, 1998 Justin T. Gibbs.
7  * Copyright (c) 1997, 1998, 1999, 2000 Kenneth D. Merry.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification, immediately at the beginning of the file.
16  * 2. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
23  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/types.h>
38 #include <sys/malloc.h>
39 #include <sys/kernel.h>
40 #include <sys/bio.h>
41 #include <sys/conf.h>
42 #include <sys/devctl.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/buf.h>
46 #include <sys/proc.h>
47 #include <sys/devicestat.h>
48 #include <sys/sbuf.h>
49 #include <sys/sysctl.h>
50 #include <vm/vm.h>
51 #include <vm/vm_extern.h>
52
53 #include <cam/cam.h>
54 #include <cam/cam_ccb.h>
55 #include <cam/cam_queue.h>
56 #include <cam/cam_xpt_periph.h>
57 #include <cam/cam_xpt_internal.h>
58 #include <cam/cam_periph.h>
59 #include <cam/cam_debug.h>
60 #include <cam/cam_sim.h>
61
62 #include <cam/scsi/scsi_all.h>
63 #include <cam/scsi/scsi_message.h>
64 #include <cam/scsi/scsi_pass.h>
65
66 static  u_int           camperiphnextunit(struct periph_driver *p_drv,
67                                           u_int newunit, int wired,
68                                           path_id_t pathid, target_id_t target,
69                                           lun_id_t lun);
70 static  u_int           camperiphunit(struct periph_driver *p_drv,
71                                       path_id_t pathid, target_id_t target,
72                                       lun_id_t lun); 
73 static  void            camperiphdone(struct cam_periph *periph, 
74                                         union ccb *done_ccb);
75 static  void            camperiphfree(struct cam_periph *periph);
76 static int              camperiphscsistatuserror(union ccb *ccb,
77                                                 union ccb **orig_ccb,
78                                                  cam_flags camflags,
79                                                  u_int32_t sense_flags,
80                                                  int *openings,
81                                                  u_int32_t *relsim_flags,
82                                                  u_int32_t *timeout,
83                                                  u_int32_t  *action,
84                                                  const char **action_string);
85 static  int             camperiphscsisenseerror(union ccb *ccb,
86                                                 union ccb **orig_ccb,
87                                                 cam_flags camflags,
88                                                 u_int32_t sense_flags,
89                                                 int *openings,
90                                                 u_int32_t *relsim_flags,
91                                                 u_int32_t *timeout,
92                                                 u_int32_t *action,
93                                                 const char **action_string);
94 static void             cam_periph_devctl_notify(union ccb *ccb);
95
96 static int nperiph_drivers;
97 static int initialized = 0;
98 struct periph_driver **periph_drivers;
99
100 static MALLOC_DEFINE(M_CAMPERIPH, "CAM periph", "CAM peripheral buffers");
101
102 static int periph_selto_delay = 1000;
103 TUNABLE_INT("kern.cam.periph_selto_delay", &periph_selto_delay);
104 static int periph_noresrc_delay = 500;
105 TUNABLE_INT("kern.cam.periph_noresrc_delay", &periph_noresrc_delay);
106 static int periph_busy_delay = 500;
107 TUNABLE_INT("kern.cam.periph_busy_delay", &periph_busy_delay);
108
109 static u_int periph_mapmem_thresh = 65536;
110 SYSCTL_UINT(_kern_cam, OID_AUTO, mapmem_thresh, CTLFLAG_RWTUN,
111     &periph_mapmem_thresh, 0, "Threshold for user-space buffer mapping");
112
113 void
114 periphdriver_register(void *data)
115 {
116         struct periph_driver *drv = (struct periph_driver *)data;
117         struct periph_driver **newdrivers, **old;
118         int ndrivers;
119
120 again:
121         ndrivers = nperiph_drivers + 2;
122         newdrivers = malloc(sizeof(*newdrivers) * ndrivers, M_CAMPERIPH,
123                             M_WAITOK);
124         xpt_lock_buses();
125         if (ndrivers != nperiph_drivers + 2) {
126                 /*
127                  * Lost race against itself; go around.
128                  */
129                 xpt_unlock_buses();
130                 free(newdrivers, M_CAMPERIPH);
131                 goto again;
132         }
133         if (periph_drivers)
134                 bcopy(periph_drivers, newdrivers,
135                       sizeof(*newdrivers) * nperiph_drivers);
136         newdrivers[nperiph_drivers] = drv;
137         newdrivers[nperiph_drivers + 1] = NULL;
138         old = periph_drivers;
139         periph_drivers = newdrivers;
140         nperiph_drivers++;
141         xpt_unlock_buses();
142         if (old)
143                 free(old, M_CAMPERIPH);
144         /* If driver marked as early or it is late now, initialize it. */
145         if (((drv->flags & CAM_PERIPH_DRV_EARLY) != 0 && initialized > 0) ||
146             initialized > 1)
147                 (*drv->init)();
148 }
149
150 int
151 periphdriver_unregister(void *data)
152 {
153         struct periph_driver *drv = (struct periph_driver *)data;
154         int error, n;
155
156         /* If driver marked as early or it is late now, deinitialize it. */
157         if (((drv->flags & CAM_PERIPH_DRV_EARLY) != 0 && initialized > 0) ||
158             initialized > 1) {
159                 if (drv->deinit == NULL) {
160                         printf("CAM periph driver '%s' doesn't have deinit.\n",
161                             drv->driver_name);
162                         return (EOPNOTSUPP);
163                 }
164                 error = drv->deinit();
165                 if (error != 0)
166                         return (error);
167         }
168
169         xpt_lock_buses();
170         for (n = 0; n < nperiph_drivers && periph_drivers[n] != drv; n++)
171                 ;
172         KASSERT(n < nperiph_drivers,
173             ("Periph driver '%s' was not registered", drv->driver_name));
174         for (; n + 1 < nperiph_drivers; n++)
175                 periph_drivers[n] = periph_drivers[n + 1];
176         periph_drivers[n + 1] = NULL;
177         nperiph_drivers--;
178         xpt_unlock_buses();
179         return (0);
180 }
181
182 void
183 periphdriver_init(int level)
184 {
185         int     i, early;
186
187         initialized = max(initialized, level);
188         for (i = 0; periph_drivers[i] != NULL; i++) {
189                 early = (periph_drivers[i]->flags & CAM_PERIPH_DRV_EARLY) ? 1 : 2;
190                 if (early == initialized)
191                         (*periph_drivers[i]->init)();
192         }
193 }
194
195 cam_status
196 cam_periph_alloc(periph_ctor_t *periph_ctor,
197                  periph_oninv_t *periph_oninvalidate,
198                  periph_dtor_t *periph_dtor, periph_start_t *periph_start,
199                  char *name, cam_periph_type type, struct cam_path *path,
200                  ac_callback_t *ac_callback, ac_code code, void *arg)
201 {
202         struct          periph_driver **p_drv;
203         struct          cam_sim *sim;
204         struct          cam_periph *periph;
205         struct          cam_periph *cur_periph;
206         path_id_t       path_id;
207         target_id_t     target_id;
208         lun_id_t        lun_id;
209         cam_status      status;
210         u_int           init_level;
211
212         init_level = 0;
213         /*
214          * Handle Hot-Plug scenarios.  If there is already a peripheral
215          * of our type assigned to this path, we are likely waiting for
216          * final close on an old, invalidated, peripheral.  If this is
217          * the case, queue up a deferred call to the peripheral's async
218          * handler.  If it looks like a mistaken re-allocation, complain.
219          */
220         if ((periph = cam_periph_find(path, name)) != NULL) {
221                 if ((periph->flags & CAM_PERIPH_INVALID) != 0
222                  && (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) == 0) {
223                         periph->flags |= CAM_PERIPH_NEW_DEV_FOUND;
224                         periph->deferred_callback = ac_callback;
225                         periph->deferred_ac = code;
226                         return (CAM_REQ_INPROG);
227                 } else {
228                         printf("cam_periph_alloc: attempt to re-allocate "
229                                "valid device %s%d rejected flags %#x "
230                                "refcount %d\n", periph->periph_name,
231                                periph->unit_number, periph->flags,
232                                periph->refcount);
233                 }
234                 return (CAM_REQ_INVALID);
235         }
236
237         periph = (struct cam_periph *)malloc(sizeof(*periph), M_CAMPERIPH,
238                                              M_NOWAIT|M_ZERO);
239
240         if (periph == NULL)
241                 return (CAM_RESRC_UNAVAIL);
242
243         init_level++;
244
245         sim = xpt_path_sim(path);
246         path_id = xpt_path_path_id(path);
247         target_id = xpt_path_target_id(path);
248         lun_id = xpt_path_lun_id(path);
249         periph->periph_start = periph_start;
250         periph->periph_dtor = periph_dtor;
251         periph->periph_oninval = periph_oninvalidate;
252         periph->type = type;
253         periph->periph_name = name;
254         periph->scheduled_priority = CAM_PRIORITY_NONE;
255         periph->immediate_priority = CAM_PRIORITY_NONE;
256         periph->refcount = 1;           /* Dropped by invalidation. */
257         periph->sim = sim;
258         SLIST_INIT(&periph->ccb_list);
259         status = xpt_create_path(&path, periph, path_id, target_id, lun_id);
260         if (status != CAM_REQ_CMP)
261                 goto failure;
262         periph->path = path;
263
264         xpt_lock_buses();
265         for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
266                 if (strcmp((*p_drv)->driver_name, name) == 0)
267                         break;
268         }
269         if (*p_drv == NULL) {
270                 printf("cam_periph_alloc: invalid periph name '%s'\n", name);
271                 xpt_unlock_buses();
272                 xpt_free_path(periph->path);
273                 free(periph, M_CAMPERIPH);
274                 return (CAM_REQ_INVALID);
275         }
276         periph->unit_number = camperiphunit(*p_drv, path_id, target_id, lun_id);
277         cur_periph = TAILQ_FIRST(&(*p_drv)->units);
278         while (cur_periph != NULL
279             && cur_periph->unit_number < periph->unit_number)
280                 cur_periph = TAILQ_NEXT(cur_periph, unit_links);
281         if (cur_periph != NULL) {
282                 KASSERT(cur_periph->unit_number != periph->unit_number, ("duplicate units on periph list"));
283                 TAILQ_INSERT_BEFORE(cur_periph, periph, unit_links);
284         } else {
285                 TAILQ_INSERT_TAIL(&(*p_drv)->units, periph, unit_links);
286                 (*p_drv)->generation++;
287         }
288         xpt_unlock_buses();
289
290         init_level++;
291
292         status = xpt_add_periph(periph);
293         if (status != CAM_REQ_CMP)
294                 goto failure;
295
296         init_level++;
297         CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph created\n"));
298
299         status = periph_ctor(periph, arg);
300
301         if (status == CAM_REQ_CMP)
302                 init_level++;
303
304 failure:
305         switch (init_level) {
306         case 4:
307                 /* Initialized successfully */
308                 break;
309         case 3:
310                 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
311                 xpt_remove_periph(periph);
312                 /* FALLTHROUGH */
313         case 2:
314                 xpt_lock_buses();
315                 TAILQ_REMOVE(&(*p_drv)->units, periph, unit_links);
316                 xpt_unlock_buses();
317                 xpt_free_path(periph->path);
318                 /* FALLTHROUGH */
319         case 1:
320                 free(periph, M_CAMPERIPH);
321                 /* FALLTHROUGH */
322         case 0:
323                 /* No cleanup to perform. */
324                 break;
325         default:
326                 panic("%s: Unknown init level", __func__);
327         }
328         return(status);
329 }
330
331 /*
332  * Find a peripheral structure with the specified path, target, lun, 
333  * and (optionally) type.  If the name is NULL, this function will return
334  * the first peripheral driver that matches the specified path.
335  */
336 struct cam_periph *
337 cam_periph_find(struct cam_path *path, char *name)
338 {
339         struct periph_driver **p_drv;
340         struct cam_periph *periph;
341
342         xpt_lock_buses();
343         for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
344                 if (name != NULL && (strcmp((*p_drv)->driver_name, name) != 0))
345                         continue;
346
347                 TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
348                         if (xpt_path_comp(periph->path, path) == 0) {
349                                 xpt_unlock_buses();
350                                 cam_periph_assert(periph, MA_OWNED);
351                                 return(periph);
352                         }
353                 }
354                 if (name != NULL) {
355                         xpt_unlock_buses();
356                         return(NULL);
357                 }
358         }
359         xpt_unlock_buses();
360         return(NULL);
361 }
362
363 /*
364  * Find peripheral driver instances attached to the specified path.
365  */
366 int
367 cam_periph_list(struct cam_path *path, struct sbuf *sb)
368 {
369         struct sbuf local_sb;
370         struct periph_driver **p_drv;
371         struct cam_periph *periph;
372         int count;
373         int sbuf_alloc_len;
374
375         sbuf_alloc_len = 16;
376 retry:
377         sbuf_new(&local_sb, NULL, sbuf_alloc_len, SBUF_FIXEDLEN);
378         count = 0;
379         xpt_lock_buses();
380         for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
381                 TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
382                         if (xpt_path_comp(periph->path, path) != 0)
383                                 continue;
384
385                         if (sbuf_len(&local_sb) != 0)
386                                 sbuf_cat(&local_sb, ",");
387
388                         sbuf_printf(&local_sb, "%s%d", periph->periph_name,
389                                     periph->unit_number);
390
391                         if (sbuf_error(&local_sb) == ENOMEM) {
392                                 sbuf_alloc_len *= 2;
393                                 xpt_unlock_buses();
394                                 sbuf_delete(&local_sb);
395                                 goto retry;
396                         }
397                         count++;
398                 }
399         }
400         xpt_unlock_buses();
401         sbuf_finish(&local_sb);
402         if (sbuf_len(sb) != 0)
403                 sbuf_cat(sb, ",");
404         sbuf_cat(sb, sbuf_data(&local_sb));
405         sbuf_delete(&local_sb);
406         return (count);
407 }
408
409 int
410 cam_periph_acquire(struct cam_periph *periph)
411 {
412         int status;
413
414         if (periph == NULL)
415                 return (EINVAL);
416
417         status = ENOENT;
418         xpt_lock_buses();
419         if ((periph->flags & CAM_PERIPH_INVALID) == 0) {
420                 periph->refcount++;
421                 status = 0;
422         }
423         xpt_unlock_buses();
424
425         return (status);
426 }
427
428 void
429 cam_periph_doacquire(struct cam_periph *periph)
430 {
431
432         xpt_lock_buses();
433         KASSERT(periph->refcount >= 1,
434             ("cam_periph_doacquire() with refcount == %d", periph->refcount));
435         periph->refcount++;
436         xpt_unlock_buses();
437 }
438
439 void
440 cam_periph_release_locked_buses(struct cam_periph *periph)
441 {
442
443         cam_periph_assert(periph, MA_OWNED);
444         KASSERT(periph->refcount >= 1, ("periph->refcount >= 1"));
445         if (--periph->refcount == 0)
446                 camperiphfree(periph);
447 }
448
449 void
450 cam_periph_release_locked(struct cam_periph *periph)
451 {
452
453         if (periph == NULL)
454                 return;
455
456         xpt_lock_buses();
457         cam_periph_release_locked_buses(periph);
458         xpt_unlock_buses();
459 }
460
461 void
462 cam_periph_release(struct cam_periph *periph)
463 {
464         struct mtx *mtx;
465
466         if (periph == NULL)
467                 return;
468
469         cam_periph_assert(periph, MA_NOTOWNED);
470         mtx = cam_periph_mtx(periph);
471         mtx_lock(mtx);
472         cam_periph_release_locked(periph);
473         mtx_unlock(mtx);
474 }
475
476 /*
477  * hold/unhold act as mutual exclusion for sections of the code that
478  * need to sleep and want to make sure that other sections that
479  * will interfere are held off. This only protects exclusive sections
480  * from each other.
481  */
482 int
483 cam_periph_hold(struct cam_periph *periph, int priority)
484 {
485         int error;
486
487         /*
488          * Increment the reference count on the peripheral
489          * while we wait for our lock attempt to succeed
490          * to ensure the peripheral doesn't disappear out
491          * from user us while we sleep.
492          */
493
494         if (cam_periph_acquire(periph) != 0)
495                 return (ENXIO);
496
497         cam_periph_assert(periph, MA_OWNED);
498         while ((periph->flags & CAM_PERIPH_LOCKED) != 0) {
499                 periph->flags |= CAM_PERIPH_LOCK_WANTED;
500                 if ((error = cam_periph_sleep(periph, periph, priority,
501                     "caplck", 0)) != 0) {
502                         cam_periph_release_locked(periph);
503                         return (error);
504                 }
505                 if (periph->flags & CAM_PERIPH_INVALID) {
506                         cam_periph_release_locked(periph);
507                         return (ENXIO);
508                 }
509         }
510
511         periph->flags |= CAM_PERIPH_LOCKED;
512         return (0);
513 }
514
515 void
516 cam_periph_unhold(struct cam_periph *periph)
517 {
518
519         cam_periph_assert(periph, MA_OWNED);
520
521         periph->flags &= ~CAM_PERIPH_LOCKED;
522         if ((periph->flags & CAM_PERIPH_LOCK_WANTED) != 0) {
523                 periph->flags &= ~CAM_PERIPH_LOCK_WANTED;
524                 wakeup(periph);
525         }
526
527         cam_periph_release_locked(periph);
528 }
529
530 /*
531  * Look for the next unit number that is not currently in use for this
532  * peripheral type starting at "newunit".  Also exclude unit numbers that
533  * are reserved by for future "hardwiring" unless we already know that this
534  * is a potential wired device.  Only assume that the device is "wired" the
535  * first time through the loop since after that we'll be looking at unit
536  * numbers that did not match a wiring entry.
537  */
538 static u_int
539 camperiphnextunit(struct periph_driver *p_drv, u_int newunit, int wired,
540                   path_id_t pathid, target_id_t target, lun_id_t lun)
541 {
542         struct  cam_periph *periph;
543         char    *periph_name;
544         int     i, val, dunit, r;
545         const char *dname, *strval;
546
547         periph_name = p_drv->driver_name;
548         for (;;newunit++) {
549                 for (periph = TAILQ_FIRST(&p_drv->units);
550                      periph != NULL && periph->unit_number != newunit;
551                      periph = TAILQ_NEXT(periph, unit_links))
552                         ;
553
554                 if (periph != NULL && periph->unit_number == newunit) {
555                         if (wired != 0) {
556                                 xpt_print(periph->path, "Duplicate Wired "
557                                     "Device entry!\n");
558                                 xpt_print(periph->path, "Second device (%s "
559                                     "device at scbus%d target %d lun %d) will "
560                                     "not be wired\n", periph_name, pathid,
561                                     target, lun);
562                                 wired = 0;
563                         }
564                         continue;
565                 }
566                 if (wired)
567                         break;
568
569                 /*
570                  * Don't match entries like "da 4" as a wired down
571                  * device, but do match entries like "da 4 target 5"
572                  * or even "da 4 scbus 1". 
573                  */
574                 i = 0;
575                 dname = periph_name;
576                 for (;;) {
577                         r = resource_find_dev(&i, dname, &dunit, NULL, NULL);
578                         if (r != 0)
579                                 break;
580                         /* if no "target" and no specific scbus, skip */
581                         if (resource_int_value(dname, dunit, "target", &val) &&
582                             (resource_string_value(dname, dunit, "at",&strval)||
583                              strcmp(strval, "scbus") == 0))
584                                 continue;
585                         if (newunit == dunit)
586                                 break;
587                 }
588                 if (r != 0)
589                         break;
590         }
591         return (newunit);
592 }
593
594 static u_int
595 camperiphunit(struct periph_driver *p_drv, path_id_t pathid,
596               target_id_t target, lun_id_t lun)
597 {
598         u_int   unit;
599         int     wired, i, val, dunit;
600         const char *dname, *strval;
601         char    pathbuf[32], *periph_name;
602
603         periph_name = p_drv->driver_name;
604         snprintf(pathbuf, sizeof(pathbuf), "scbus%d", pathid);
605         unit = 0;
606         i = 0;
607         dname = periph_name;
608         for (wired = 0; resource_find_dev(&i, dname, &dunit, NULL, NULL) == 0;
609              wired = 0) {
610                 if (resource_string_value(dname, dunit, "at", &strval) == 0) {
611                         if (strcmp(strval, pathbuf) != 0)
612                                 continue;
613                         wired++;
614                 }
615                 if (resource_int_value(dname, dunit, "target", &val) == 0) {
616                         if (val != target)
617                                 continue;
618                         wired++;
619                 }
620                 if (resource_int_value(dname, dunit, "lun", &val) == 0) {
621                         if (val != lun)
622                                 continue;
623                         wired++;
624                 }
625                 if (wired != 0) {
626                         unit = dunit;
627                         break;
628                 }
629         }
630
631         /*
632          * Either start from 0 looking for the next unit or from
633          * the unit number given in the resource config.  This way,
634          * if we have wildcard matches, we don't return the same
635          * unit number twice.
636          */
637         unit = camperiphnextunit(p_drv, unit, wired, pathid, target, lun);
638
639         return (unit);
640 }
641
642 void
643 cam_periph_invalidate(struct cam_periph *periph)
644 {
645
646         cam_periph_assert(periph, MA_OWNED);
647         /*
648          * We only tear down the device the first time a peripheral is
649          * invalidated.
650          */
651         if ((periph->flags & CAM_PERIPH_INVALID) != 0)
652                 return;
653
654         CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph invalidated\n"));
655         if ((periph->flags & CAM_PERIPH_ANNOUNCED) && !rebooting) {
656                 struct sbuf sb;
657                 char buffer[160];
658
659                 sbuf_new(&sb, buffer, 160, SBUF_FIXEDLEN);
660                 xpt_denounce_periph_sbuf(periph, &sb);
661                 sbuf_finish(&sb);
662                 sbuf_putbuf(&sb);
663         }
664         periph->flags |= CAM_PERIPH_INVALID;
665         periph->flags &= ~CAM_PERIPH_NEW_DEV_FOUND;
666         if (periph->periph_oninval != NULL)
667                 periph->periph_oninval(periph);
668         cam_periph_release_locked(periph);
669 }
670
671 static void
672 camperiphfree(struct cam_periph *periph)
673 {
674         struct periph_driver **p_drv;
675         struct periph_driver *drv;
676
677         cam_periph_assert(periph, MA_OWNED);
678         KASSERT(periph->periph_allocating == 0, ("%s%d: freed while allocating",
679             periph->periph_name, periph->unit_number));
680         for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
681                 if (strcmp((*p_drv)->driver_name, periph->periph_name) == 0)
682                         break;
683         }
684         if (*p_drv == NULL) {
685                 printf("camperiphfree: attempt to free non-existant periph\n");
686                 return;
687         }
688         /*
689          * Cache a pointer to the periph_driver structure.  If a
690          * periph_driver is added or removed from the array (see
691          * periphdriver_register()) while we drop the toplogy lock
692          * below, p_drv may change.  This doesn't protect against this
693          * particular periph_driver going away.  That will require full
694          * reference counting in the periph_driver infrastructure.
695          */
696         drv = *p_drv;
697
698         /*
699          * We need to set this flag before dropping the topology lock, to
700          * let anyone who is traversing the list that this peripheral is
701          * about to be freed, and there will be no more reference count
702          * checks.
703          */
704         periph->flags |= CAM_PERIPH_FREE;
705
706         /*
707          * The peripheral destructor semantics dictate calling with only the
708          * SIM mutex held.  Since it might sleep, it should not be called
709          * with the topology lock held.
710          */
711         xpt_unlock_buses();
712
713         /*
714          * We need to call the peripheral destructor prior to removing the
715          * peripheral from the list.  Otherwise, we risk running into a
716          * scenario where the peripheral unit number may get reused
717          * (because it has been removed from the list), but some resources
718          * used by the peripheral are still hanging around.  In particular,
719          * the devfs nodes used by some peripherals like the pass(4) driver
720          * aren't fully cleaned up until the destructor is run.  If the
721          * unit number is reused before the devfs instance is fully gone,
722          * devfs will panic.
723          */
724         if (periph->periph_dtor != NULL)
725                 periph->periph_dtor(periph);
726
727         /*
728          * The peripheral list is protected by the topology lock. We have to
729          * remove the periph from the drv list before we call deferred_ac. The
730          * AC_FOUND_DEVICE callback won't create a new periph if it's still there.
731          */
732         xpt_lock_buses();
733
734         TAILQ_REMOVE(&drv->units, periph, unit_links);
735         drv->generation++;
736
737         xpt_remove_periph(periph);
738
739         xpt_unlock_buses();
740         if ((periph->flags & CAM_PERIPH_ANNOUNCED) && !rebooting)
741                 xpt_print(periph->path, "Periph destroyed\n");
742         else
743                 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
744
745         if (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) {
746                 union ccb ccb;
747                 void *arg;
748
749                 memset(&ccb, 0, sizeof(ccb));
750                 switch (periph->deferred_ac) {
751                 case AC_FOUND_DEVICE:
752                         ccb.ccb_h.func_code = XPT_GDEV_TYPE;
753                         xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
754                         xpt_action(&ccb);
755                         arg = &ccb;
756                         break;
757                 case AC_PATH_REGISTERED:
758                         xpt_path_inq(&ccb.cpi, periph->path);
759                         arg = &ccb;
760                         break;
761                 default:
762                         arg = NULL;
763                         break;
764                 }
765                 periph->deferred_callback(NULL, periph->deferred_ac,
766                                           periph->path, arg);
767         }
768         xpt_free_path(periph->path);
769         free(periph, M_CAMPERIPH);
770         xpt_lock_buses();
771 }
772
773 /*
774  * Map user virtual pointers into kernel virtual address space, so we can
775  * access the memory.  This is now a generic function that centralizes most
776  * of the sanity checks on the data flags, if any.
777  * This also only works for up to maxphys memory.  Since we use
778  * buffers to map stuff in and out, we're limited to the buffer size.
779  */
780 int
781 cam_periph_mapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo,
782     u_int maxmap)
783 {
784         int numbufs, i;
785         u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
786         u_int32_t lengths[CAM_PERIPH_MAXMAPS];
787         u_int32_t dirs[CAM_PERIPH_MAXMAPS];
788
789         bzero(mapinfo, sizeof(*mapinfo));
790         if (maxmap == 0)
791                 maxmap = DFLTPHYS;      /* traditional default */
792         else if (maxmap > maxphys)
793                 maxmap = maxphys;       /* for safety */
794         switch(ccb->ccb_h.func_code) {
795         case XPT_DEV_MATCH:
796                 if (ccb->cdm.match_buf_len == 0) {
797                         printf("cam_periph_mapmem: invalid match buffer "
798                                "length 0\n");
799                         return(EINVAL);
800                 }
801                 if (ccb->cdm.pattern_buf_len > 0) {
802                         data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
803                         lengths[0] = ccb->cdm.pattern_buf_len;
804                         dirs[0] = CAM_DIR_OUT;
805                         data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
806                         lengths[1] = ccb->cdm.match_buf_len;
807                         dirs[1] = CAM_DIR_IN;
808                         numbufs = 2;
809                 } else {
810                         data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
811                         lengths[0] = ccb->cdm.match_buf_len;
812                         dirs[0] = CAM_DIR_IN;
813                         numbufs = 1;
814                 }
815                 /*
816                  * This request will not go to the hardware, no reason
817                  * to be so strict. vmapbuf() is able to map up to maxphys.
818                  */
819                 maxmap = maxphys;
820                 break;
821         case XPT_SCSI_IO:
822         case XPT_CONT_TARGET_IO:
823                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
824                         return(0);
825                 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
826                         return (EINVAL);
827                 data_ptrs[0] = &ccb->csio.data_ptr;
828                 lengths[0] = ccb->csio.dxfer_len;
829                 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
830                 numbufs = 1;
831                 break;
832         case XPT_ATA_IO:
833                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
834                         return(0);
835                 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
836                         return (EINVAL);
837                 data_ptrs[0] = &ccb->ataio.data_ptr;
838                 lengths[0] = ccb->ataio.dxfer_len;
839                 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
840                 numbufs = 1;
841                 break;
842         case XPT_MMC_IO:
843                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
844                         return(0);
845                 /* Two mappings: one for cmd->data and one for cmd->data->data */
846                 data_ptrs[0] = (unsigned char **)&ccb->mmcio.cmd.data;
847                 lengths[0] = sizeof(struct mmc_data *);
848                 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
849                 data_ptrs[1] = (unsigned char **)&ccb->mmcio.cmd.data->data;
850                 lengths[1] = ccb->mmcio.cmd.data->len;
851                 dirs[1] = ccb->ccb_h.flags & CAM_DIR_MASK;
852                 numbufs = 2;
853                 break;
854         case XPT_SMP_IO:
855                 data_ptrs[0] = &ccb->smpio.smp_request;
856                 lengths[0] = ccb->smpio.smp_request_len;
857                 dirs[0] = CAM_DIR_OUT;
858                 data_ptrs[1] = &ccb->smpio.smp_response;
859                 lengths[1] = ccb->smpio.smp_response_len;
860                 dirs[1] = CAM_DIR_IN;
861                 numbufs = 2;
862                 break;
863         case XPT_NVME_IO:
864         case XPT_NVME_ADMIN:
865                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
866                         return (0);
867                 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
868                         return (EINVAL);
869                 data_ptrs[0] = &ccb->nvmeio.data_ptr;
870                 lengths[0] = ccb->nvmeio.dxfer_len;
871                 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
872                 numbufs = 1;
873                 break;
874         case XPT_DEV_ADVINFO:
875                 if (ccb->cdai.bufsiz == 0)
876                         return (0);
877
878                 data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
879                 lengths[0] = ccb->cdai.bufsiz;
880                 dirs[0] = CAM_DIR_IN;
881                 numbufs = 1;
882
883                 /*
884                  * This request will not go to the hardware, no reason
885                  * to be so strict. vmapbuf() is able to map up to maxphys.
886                  */
887                 maxmap = maxphys;
888                 break;
889         default:
890                 return(EINVAL);
891                 break; /* NOTREACHED */
892         }
893
894         /*
895          * Check the transfer length and permissions first, so we don't
896          * have to unmap any previously mapped buffers.
897          */
898         for (i = 0; i < numbufs; i++) {
899                 if (lengths[i] > maxmap) {
900                         printf("cam_periph_mapmem: attempt to map %lu bytes, "
901                                "which is greater than %lu\n",
902                                (long)(lengths[i]), (u_long)maxmap);
903                         return (E2BIG);
904                 }
905         }
906
907         /*
908          * This keeps the kernel stack of current thread from getting
909          * swapped.  In low-memory situations where the kernel stack might
910          * otherwise get swapped out, this holds it and allows the thread
911          * to make progress and release the kernel mapped pages sooner.
912          *
913          * XXX KDM should I use P_NOSWAP instead?
914          */
915         PHOLD(curproc);
916
917         for (i = 0; i < numbufs; i++) {
918                 /* Save the user's data address. */
919                 mapinfo->orig[i] = *data_ptrs[i];
920
921                 /*
922                  * For small buffers use malloc+copyin/copyout instead of
923                  * mapping to KVA to avoid expensive TLB shootdowns.  For
924                  * small allocations malloc is backed by UMA, and so much
925                  * cheaper on SMP systems.
926                  */
927                 if (lengths[i] <= periph_mapmem_thresh &&
928                     ccb->ccb_h.func_code != XPT_MMC_IO) {
929                         *data_ptrs[i] = malloc(lengths[i], M_CAMPERIPH,
930                             M_WAITOK);
931                         if (dirs[i] != CAM_DIR_IN) {
932                                 if (copyin(mapinfo->orig[i], *data_ptrs[i],
933                                     lengths[i]) != 0) {
934                                         free(*data_ptrs[i], M_CAMPERIPH);
935                                         *data_ptrs[i] = mapinfo->orig[i];
936                                         goto fail;
937                                 }
938                         } else
939                                 bzero(*data_ptrs[i], lengths[i]);
940                         continue;
941                 }
942
943                 /*
944                  * Get the buffer.
945                  */
946                 mapinfo->bp[i] = uma_zalloc(pbuf_zone, M_WAITOK);
947
948                 /* set the direction */
949                 mapinfo->bp[i]->b_iocmd = (dirs[i] == CAM_DIR_OUT) ?
950                     BIO_WRITE : BIO_READ;
951
952                 /* Map the buffer into kernel memory. */
953                 if (vmapbuf(mapinfo->bp[i], *data_ptrs[i], lengths[i], 1) < 0) {
954                         uma_zfree(pbuf_zone, mapinfo->bp[i]);
955                         goto fail;
956                 }
957
958                 /* set our pointer to the new mapped area */
959                 *data_ptrs[i] = mapinfo->bp[i]->b_data;
960         }
961
962         /*
963          * Now that we've gotten this far, change ownership to the kernel
964          * of the buffers so that we don't run afoul of returning to user
965          * space with locks (on the buffer) held.
966          */
967         for (i = 0; i < numbufs; i++) {
968                 if (mapinfo->bp[i])
969                         BUF_KERNPROC(mapinfo->bp[i]);
970         }
971
972         mapinfo->num_bufs_used = numbufs;
973         return(0);
974
975 fail:
976         for (i--; i >= 0; i--) {
977                 if (mapinfo->bp[i]) {
978                         vunmapbuf(mapinfo->bp[i]);
979                         uma_zfree(pbuf_zone, mapinfo->bp[i]);
980                 } else
981                         free(*data_ptrs[i], M_CAMPERIPH);
982                 *data_ptrs[i] = mapinfo->orig[i];
983         }
984         PRELE(curproc);
985         return(EACCES);
986 }
987
988 /*
989  * Unmap memory segments mapped into kernel virtual address space by
990  * cam_periph_mapmem().
991  */
992 void
993 cam_periph_unmapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
994 {
995         int numbufs, i;
996         u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
997         u_int32_t lengths[CAM_PERIPH_MAXMAPS];
998         u_int32_t dirs[CAM_PERIPH_MAXMAPS];
999
1000         if (mapinfo->num_bufs_used <= 0) {
1001                 /* nothing to free and the process wasn't held. */
1002                 return;
1003         }
1004
1005         switch (ccb->ccb_h.func_code) {
1006         case XPT_DEV_MATCH:
1007                 if (ccb->cdm.pattern_buf_len > 0) {
1008                         data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
1009                         lengths[0] = ccb->cdm.pattern_buf_len;
1010                         dirs[0] = CAM_DIR_OUT;
1011                         data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
1012                         lengths[1] = ccb->cdm.match_buf_len;
1013                         dirs[1] = CAM_DIR_IN;
1014                         numbufs = 2;
1015                 } else {
1016                         data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
1017                         lengths[0] = ccb->cdm.match_buf_len;
1018                         dirs[0] = CAM_DIR_IN;
1019                         numbufs = 1;
1020                 }
1021                 break;
1022         case XPT_SCSI_IO:
1023         case XPT_CONT_TARGET_IO:
1024                 data_ptrs[0] = &ccb->csio.data_ptr;
1025                 lengths[0] = ccb->csio.dxfer_len;
1026                 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1027                 numbufs = 1;
1028                 break;
1029         case XPT_ATA_IO:
1030                 data_ptrs[0] = &ccb->ataio.data_ptr;
1031                 lengths[0] = ccb->ataio.dxfer_len;
1032                 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1033                 numbufs = 1;
1034                 break;
1035         case XPT_MMC_IO:
1036                 data_ptrs[0] = (u_int8_t **)&ccb->mmcio.cmd.data;
1037                 lengths[0] = sizeof(struct mmc_data *);
1038                 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1039                 data_ptrs[1] = (u_int8_t **)&ccb->mmcio.cmd.data->data;
1040                 lengths[1] = ccb->mmcio.cmd.data->len;
1041                 dirs[1] = ccb->ccb_h.flags & CAM_DIR_MASK;
1042                 numbufs = 2;
1043                 break;
1044         case XPT_SMP_IO:
1045                 data_ptrs[0] = &ccb->smpio.smp_request;
1046                 lengths[0] = ccb->smpio.smp_request_len;
1047                 dirs[0] = CAM_DIR_OUT;
1048                 data_ptrs[1] = &ccb->smpio.smp_response;
1049                 lengths[1] = ccb->smpio.smp_response_len;
1050                 dirs[1] = CAM_DIR_IN;
1051                 numbufs = 2;
1052                 break;
1053         case XPT_NVME_IO:
1054         case XPT_NVME_ADMIN:
1055                 data_ptrs[0] = &ccb->nvmeio.data_ptr;
1056                 lengths[0] = ccb->nvmeio.dxfer_len;
1057                 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1058                 numbufs = 1;
1059                 break;
1060         case XPT_DEV_ADVINFO:
1061                 data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
1062                 lengths[0] = ccb->cdai.bufsiz;
1063                 dirs[0] = CAM_DIR_IN;
1064                 numbufs = 1;
1065                 break;
1066         default:
1067                 /* allow ourselves to be swapped once again */
1068                 PRELE(curproc);
1069                 return;
1070                 break; /* NOTREACHED */ 
1071         }
1072
1073         for (i = 0; i < numbufs; i++) {
1074                 if (mapinfo->bp[i]) {
1075                         /* unmap the buffer */
1076                         vunmapbuf(mapinfo->bp[i]);
1077
1078                         /* release the buffer */
1079                         uma_zfree(pbuf_zone, mapinfo->bp[i]);
1080                 } else {
1081                         if (dirs[i] != CAM_DIR_OUT) {
1082                                 copyout(*data_ptrs[i], mapinfo->orig[i],
1083                                     lengths[i]);
1084                         }
1085                         free(*data_ptrs[i], M_CAMPERIPH);
1086                 }
1087
1088                 /* Set the user's pointer back to the original value */
1089                 *data_ptrs[i] = mapinfo->orig[i];
1090         }
1091
1092         /* allow ourselves to be swapped once again */
1093         PRELE(curproc);
1094 }
1095
1096 int
1097 cam_periph_ioctl(struct cam_periph *periph, u_long cmd, caddr_t addr,
1098                  int (*error_routine)(union ccb *ccb, 
1099                                       cam_flags camflags,
1100                                       u_int32_t sense_flags))
1101 {
1102         union ccb            *ccb;
1103         int                  error;
1104         int                  found;
1105
1106         error = found = 0;
1107
1108         switch(cmd){
1109         case CAMGETPASSTHRU:
1110                 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1111                 xpt_setup_ccb(&ccb->ccb_h,
1112                               ccb->ccb_h.path,
1113                               CAM_PRIORITY_NORMAL);
1114                 ccb->ccb_h.func_code = XPT_GDEVLIST;
1115
1116                 /*
1117                  * Basically, the point of this is that we go through
1118                  * getting the list of devices, until we find a passthrough
1119                  * device.  In the current version of the CAM code, the
1120                  * only way to determine what type of device we're dealing
1121                  * with is by its name.
1122                  */
1123                 while (found == 0) {
1124                         ccb->cgdl.index = 0;
1125                         ccb->cgdl.status = CAM_GDEVLIST_MORE_DEVS;
1126                         while (ccb->cgdl.status == CAM_GDEVLIST_MORE_DEVS) {
1127                                 /* we want the next device in the list */
1128                                 xpt_action(ccb);
1129                                 if (strncmp(ccb->cgdl.periph_name, 
1130                                     "pass", 4) == 0){
1131                                         found = 1;
1132                                         break;
1133                                 }
1134                         }
1135                         if ((ccb->cgdl.status == CAM_GDEVLIST_LAST_DEVICE) &&
1136                             (found == 0)) {
1137                                 ccb->cgdl.periph_name[0] = '\0';
1138                                 ccb->cgdl.unit_number = 0;
1139                                 break;
1140                         }
1141                 }
1142
1143                 /* copy the result back out */  
1144                 bcopy(ccb, addr, sizeof(union ccb));
1145
1146                 /* and release the ccb */
1147                 xpt_release_ccb(ccb);
1148
1149                 break;
1150         default:
1151                 error = ENOTTY;
1152                 break;
1153         }
1154         return(error);
1155 }
1156
1157 static void
1158 cam_periph_done_panic(struct cam_periph *periph, union ccb *done_ccb)
1159 {
1160
1161         panic("%s: already done with ccb %p", __func__, done_ccb);
1162 }
1163
1164 static void
1165 cam_periph_done(struct cam_periph *periph, union ccb *done_ccb)
1166 {
1167
1168         /* Caller will release the CCB */
1169         xpt_path_assert(done_ccb->ccb_h.path, MA_OWNED);
1170         done_ccb->ccb_h.cbfcnp = cam_periph_done_panic;
1171         wakeup(&done_ccb->ccb_h.cbfcnp);
1172 }
1173
1174 static void
1175 cam_periph_ccbwait(union ccb *ccb)
1176 {
1177
1178         if ((ccb->ccb_h.func_code & XPT_FC_QUEUED) != 0) {
1179                 while (ccb->ccb_h.cbfcnp != cam_periph_done_panic)
1180                         xpt_path_sleep(ccb->ccb_h.path, &ccb->ccb_h.cbfcnp,
1181                             PRIBIO, "cbwait", 0);
1182         }
1183         KASSERT(ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX &&
1184             (ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG,
1185             ("%s: proceeding with incomplete ccb: ccb=%p, func_code=%#x, "
1186              "status=%#x, index=%d", __func__, ccb, ccb->ccb_h.func_code,
1187              ccb->ccb_h.status, ccb->ccb_h.pinfo.index));
1188 }
1189
1190 /*
1191  * Dispatch a CCB and wait for it to complete.  If the CCB has set a
1192  * callback function (ccb->ccb_h.cbfcnp), it will be overwritten and lost.
1193  */
1194 int
1195 cam_periph_runccb(union ccb *ccb,
1196                   int (*error_routine)(union ccb *ccb,
1197                                        cam_flags camflags,
1198                                        u_int32_t sense_flags),
1199                   cam_flags camflags, u_int32_t sense_flags,
1200                   struct devstat *ds)
1201 {
1202         struct bintime *starttime;
1203         struct bintime ltime;
1204         int error;
1205         bool must_poll;
1206         uint32_t timeout = 1;
1207
1208         starttime = NULL;
1209         xpt_path_assert(ccb->ccb_h.path, MA_OWNED);
1210         KASSERT((ccb->ccb_h.flags & CAM_UNLOCKED) == 0,
1211             ("%s: ccb=%p, func_code=%#x, flags=%#x", __func__, ccb,
1212              ccb->ccb_h.func_code, ccb->ccb_h.flags));
1213
1214         /*
1215          * If the user has supplied a stats structure, and if we understand
1216          * this particular type of ccb, record the transaction start.
1217          */
1218         if (ds != NULL &&
1219             (ccb->ccb_h.func_code == XPT_SCSI_IO ||
1220             ccb->ccb_h.func_code == XPT_ATA_IO ||
1221             ccb->ccb_h.func_code == XPT_NVME_IO)) {
1222                 starttime = &ltime;
1223                 binuptime(starttime);
1224                 devstat_start_transaction(ds, starttime);
1225         }
1226
1227         /*
1228          * We must poll the I/O while we're dumping. The scheduler is normally
1229          * stopped for dumping, except when we call doadump from ddb. While the
1230          * scheduler is running in this case, we still need to poll the I/O to
1231          * avoid sleeping waiting for the ccb to complete.
1232          *
1233          * A panic triggered dump stops the scheduler, any callback from the
1234          * shutdown_post_sync event will run with the scheduler stopped, but
1235          * before we're officially dumping. To avoid hanging in adashutdown
1236          * initiated commands (or other similar situations), we have to test for
1237          * either SCHEDULER_STOPPED() here as well.
1238          *
1239          * To avoid locking problems, dumping/polling callers must call
1240          * without a periph lock held.
1241          */
1242         must_poll = dumping || SCHEDULER_STOPPED();
1243         ccb->ccb_h.cbfcnp = cam_periph_done;
1244
1245         /*
1246          * If we're polling, then we need to ensure that we have ample resources
1247          * in the periph.  cam_periph_error can reschedule the ccb by calling
1248          * xpt_action and returning ERESTART, so we have to effect the polling
1249          * in the do loop below.
1250          */
1251         if (must_poll) {
1252                 if (cam_sim_pollable(ccb->ccb_h.path->bus->sim))
1253                         timeout = xpt_poll_setup(ccb);
1254                 else
1255                         timeout = 0;
1256         }
1257
1258         if (timeout == 0) {
1259                 ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
1260                 error = EBUSY;
1261         } else {
1262                 xpt_action(ccb);
1263                 do {
1264                         if (must_poll) {
1265                                 xpt_pollwait(ccb, timeout);
1266                                 timeout = ccb->ccb_h.timeout * 10;
1267                         } else {
1268                                 cam_periph_ccbwait(ccb);
1269                         }
1270                         if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1271                                 error = 0;
1272                         else if (error_routine != NULL) {
1273                                 ccb->ccb_h.cbfcnp = cam_periph_done;
1274                                 error = (*error_routine)(ccb, camflags, sense_flags);
1275                         } else
1276                                 error = 0;
1277                 } while (error == ERESTART);
1278         }
1279
1280         if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1281                 cam_release_devq(ccb->ccb_h.path,
1282                                  /* relsim_flags */0,
1283                                  /* openings */0,
1284                                  /* timeout */0,
1285                                  /* getcount_only */ FALSE);
1286                 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1287         }
1288
1289         if (ds != NULL) {
1290                 uint32_t bytes;
1291                 devstat_tag_type tag;
1292                 bool valid = true;
1293
1294                 if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1295                         bytes = ccb->csio.dxfer_len - ccb->csio.resid;
1296                         tag = (devstat_tag_type)(ccb->csio.tag_action & 0x3);
1297                 } else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1298                         bytes = ccb->ataio.dxfer_len - ccb->ataio.resid;
1299                         tag = (devstat_tag_type)0;
1300                 } else if (ccb->ccb_h.func_code == XPT_NVME_IO) {
1301                         bytes = ccb->nvmeio.dxfer_len; /* NB: resid no possible */
1302                         tag = (devstat_tag_type)0;
1303                 } else {
1304                         valid = false;
1305                 }
1306                 if (valid)
1307                         devstat_end_transaction(ds, bytes, tag,
1308                             ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE) ?
1309                             DEVSTAT_NO_DATA : (ccb->ccb_h.flags & CAM_DIR_OUT) ?
1310                             DEVSTAT_WRITE : DEVSTAT_READ, NULL, starttime);
1311         }
1312
1313         return(error);
1314 }
1315
1316 void
1317 cam_freeze_devq(struct cam_path *path)
1318 {
1319         struct ccb_hdr ccb_h;
1320
1321         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_freeze_devq\n"));
1322         memset(&ccb_h, 0, sizeof(ccb_h));
1323         xpt_setup_ccb(&ccb_h, path, /*priority*/1);
1324         ccb_h.func_code = XPT_NOOP;
1325         ccb_h.flags = CAM_DEV_QFREEZE;
1326         xpt_action((union ccb *)&ccb_h);
1327 }
1328
1329 u_int32_t
1330 cam_release_devq(struct cam_path *path, u_int32_t relsim_flags,
1331                  u_int32_t openings, u_int32_t arg,
1332                  int getcount_only)
1333 {
1334         struct ccb_relsim crs;
1335
1336         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_release_devq(%u, %u, %u, %d)\n",
1337             relsim_flags, openings, arg, getcount_only));
1338         memset(&crs, 0, sizeof(crs));
1339         xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
1340         crs.ccb_h.func_code = XPT_REL_SIMQ;
1341         crs.ccb_h.flags = getcount_only ? CAM_DEV_QFREEZE : 0;
1342         crs.release_flags = relsim_flags;
1343         crs.openings = openings;
1344         crs.release_timeout = arg;
1345         xpt_action((union ccb *)&crs);
1346         return (crs.qfrozen_cnt);
1347 }
1348
1349 #define saved_ccb_ptr ppriv_ptr0
1350 static void
1351 camperiphdone(struct cam_periph *periph, union ccb *done_ccb)
1352 {
1353         union ccb      *saved_ccb;
1354         cam_status      status;
1355         struct scsi_start_stop_unit *scsi_cmd;
1356         int             error = 0, error_code, sense_key, asc, ascq;
1357         u_int16_t       done_flags;
1358
1359         scsi_cmd = (struct scsi_start_stop_unit *)
1360             &done_ccb->csio.cdb_io.cdb_bytes;
1361         status = done_ccb->ccb_h.status;
1362
1363         if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1364                 if (scsi_extract_sense_ccb(done_ccb,
1365                     &error_code, &sense_key, &asc, &ascq)) {
1366                         /*
1367                          * If the error is "invalid field in CDB",
1368                          * and the load/eject flag is set, turn the
1369                          * flag off and try again.  This is just in
1370                          * case the drive in question barfs on the
1371                          * load eject flag.  The CAM code should set
1372                          * the load/eject flag by default for
1373                          * removable media.
1374                          */
1375                         if ((scsi_cmd->opcode == START_STOP_UNIT) &&
1376                             ((scsi_cmd->how & SSS_LOEJ) != 0) &&
1377                              (asc == 0x24) && (ascq == 0x00)) {
1378                                 scsi_cmd->how &= ~SSS_LOEJ;
1379                                 if (status & CAM_DEV_QFRZN) {
1380                                         cam_release_devq(done_ccb->ccb_h.path,
1381                                             0, 0, 0, 0);
1382                                         done_ccb->ccb_h.status &=
1383                                             ~CAM_DEV_QFRZN;
1384                                 }
1385                                 xpt_action(done_ccb);
1386                                 goto out;
1387                         }
1388                 }
1389                 error = cam_periph_error(done_ccb, 0,
1390                     SF_RETRY_UA | SF_NO_PRINT);
1391                 if (error == ERESTART)
1392                         goto out;
1393                 if (done_ccb->ccb_h.status & CAM_DEV_QFRZN) {
1394                         cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1395                         done_ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1396                 }
1397         } else {
1398                 /*
1399                  * If we have successfully taken a device from the not
1400                  * ready to ready state, re-scan the device and re-get
1401                  * the inquiry information.  Many devices (mostly disks)
1402                  * don't properly report their inquiry information unless
1403                  * they are spun up.
1404                  */
1405                 if (scsi_cmd->opcode == START_STOP_UNIT)
1406                         xpt_async(AC_INQ_CHANGED, done_ccb->ccb_h.path, NULL);
1407         }
1408
1409         /* If we tried long wait and still failed, remember that. */
1410         if ((periph->flags & CAM_PERIPH_RECOVERY_WAIT) &&
1411             (done_ccb->csio.cdb_io.cdb_bytes[0] == TEST_UNIT_READY)) {
1412                 periph->flags &= ~CAM_PERIPH_RECOVERY_WAIT;
1413                 if (error != 0 && done_ccb->ccb_h.retry_count == 0)
1414                         periph->flags |= CAM_PERIPH_RECOVERY_WAIT_FAILED;
1415         }
1416
1417         /*
1418          * After recovery action(s) completed, return to the original CCB.
1419          * If the recovery CCB has failed, considering its own possible
1420          * retries and recovery, assume we are back in state where we have
1421          * been originally, but without recovery hopes left.  In such case,
1422          * after the final attempt below, we cancel any further retries,
1423          * blocking by that also any new recovery attempts for this CCB,
1424          * and the result will be the final one returned to the CCB owher.
1425          */
1426
1427         /*
1428          * Copy the CCB back, preserving the alloc_flags field.  Things
1429          * will crash horribly if the CCBs are not of the same size.
1430          */
1431         saved_ccb = (union ccb *)done_ccb->ccb_h.saved_ccb_ptr;
1432         KASSERT(saved_ccb->ccb_h.func_code == XPT_SCSI_IO,
1433             ("%s: saved_ccb func_code %#x != XPT_SCSI_IO",
1434              __func__, saved_ccb->ccb_h.func_code));
1435         KASSERT(done_ccb->ccb_h.func_code == XPT_SCSI_IO,
1436             ("%s: done_ccb func_code %#x != XPT_SCSI_IO",
1437              __func__, done_ccb->ccb_h.func_code));
1438         done_flags = done_ccb->ccb_h.alloc_flags;
1439         bcopy(saved_ccb, done_ccb, sizeof(struct ccb_scsiio));
1440         done_ccb->ccb_h.alloc_flags = done_flags;
1441         xpt_free_ccb(saved_ccb);
1442         if (done_ccb->ccb_h.cbfcnp != camperiphdone)
1443                 periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1444         if (error != 0)
1445                 done_ccb->ccb_h.retry_count = 0;
1446         xpt_action(done_ccb);
1447
1448 out:
1449         /* Drop freeze taken due to CAM_DEV_QFREEZE flag set. */
1450         cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1451 }
1452
1453 /*
1454  * Generic Async Event handler.  Peripheral drivers usually
1455  * filter out the events that require personal attention,
1456  * and leave the rest to this function.
1457  */
1458 void
1459 cam_periph_async(struct cam_periph *periph, u_int32_t code,
1460                  struct cam_path *path, void *arg)
1461 {
1462         switch (code) {
1463         case AC_LOST_DEVICE:
1464                 cam_periph_invalidate(periph);
1465                 break; 
1466         default:
1467                 break;
1468         }
1469 }
1470
1471 void
1472 cam_periph_bus_settle(struct cam_periph *periph, u_int bus_settle)
1473 {
1474         struct ccb_getdevstats cgds;
1475
1476         memset(&cgds, 0, sizeof(cgds));
1477         xpt_setup_ccb(&cgds.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1478         cgds.ccb_h.func_code = XPT_GDEV_STATS;
1479         xpt_action((union ccb *)&cgds);
1480         cam_periph_freeze_after_event(periph, &cgds.last_reset, bus_settle);
1481 }
1482
1483 void
1484 cam_periph_freeze_after_event(struct cam_periph *periph,
1485                               struct timeval* event_time, u_int duration_ms)
1486 {
1487         struct timeval delta;
1488         struct timeval duration_tv;
1489
1490         if (!timevalisset(event_time))
1491                 return;
1492
1493         microtime(&delta);
1494         timevalsub(&delta, event_time);
1495         duration_tv.tv_sec = duration_ms / 1000;
1496         duration_tv.tv_usec = (duration_ms % 1000) * 1000;
1497         if (timevalcmp(&delta, &duration_tv, <)) {
1498                 timevalsub(&duration_tv, &delta);
1499
1500                 duration_ms = duration_tv.tv_sec * 1000;
1501                 duration_ms += duration_tv.tv_usec / 1000;
1502                 cam_freeze_devq(periph->path); 
1503                 cam_release_devq(periph->path,
1504                                 RELSIM_RELEASE_AFTER_TIMEOUT,
1505                                 /*reduction*/0,
1506                                 /*timeout*/duration_ms,
1507                                 /*getcount_only*/0);
1508         }
1509
1510 }
1511
1512 static int
1513 camperiphscsistatuserror(union ccb *ccb, union ccb **orig_ccb,
1514     cam_flags camflags, u_int32_t sense_flags,
1515     int *openings, u_int32_t *relsim_flags,
1516     u_int32_t *timeout, u_int32_t *action, const char **action_string)
1517 {
1518         struct cam_periph *periph;
1519         int error;
1520
1521         switch (ccb->csio.scsi_status) {
1522         case SCSI_STATUS_OK:
1523         case SCSI_STATUS_COND_MET:
1524         case SCSI_STATUS_INTERMED:
1525         case SCSI_STATUS_INTERMED_COND_MET:
1526                 error = 0;
1527                 break;
1528         case SCSI_STATUS_CMD_TERMINATED:
1529         case SCSI_STATUS_CHECK_COND:
1530                 error = camperiphscsisenseerror(ccb, orig_ccb,
1531                                                 camflags,
1532                                                 sense_flags,
1533                                                 openings,
1534                                                 relsim_flags,
1535                                                 timeout,
1536                                                 action,
1537                                                 action_string);
1538                 break;
1539         case SCSI_STATUS_QUEUE_FULL:
1540         {
1541                 /* no decrement */
1542                 struct ccb_getdevstats cgds;
1543
1544                 /*
1545                  * First off, find out what the current
1546                  * transaction counts are.
1547                  */
1548                 memset(&cgds, 0, sizeof(cgds));
1549                 xpt_setup_ccb(&cgds.ccb_h,
1550                               ccb->ccb_h.path,
1551                               CAM_PRIORITY_NORMAL);
1552                 cgds.ccb_h.func_code = XPT_GDEV_STATS;
1553                 xpt_action((union ccb *)&cgds);
1554
1555                 /*
1556                  * If we were the only transaction active, treat
1557                  * the QUEUE FULL as if it were a BUSY condition.
1558                  */
1559                 if (cgds.dev_active != 0) {
1560                         int total_openings;
1561
1562                         /*
1563                          * Reduce the number of openings to
1564                          * be 1 less than the amount it took
1565                          * to get a queue full bounded by the
1566                          * minimum allowed tag count for this
1567                          * device.
1568                          */
1569                         total_openings = cgds.dev_active + cgds.dev_openings;
1570                         *openings = cgds.dev_active;
1571                         if (*openings < cgds.mintags)
1572                                 *openings = cgds.mintags;
1573                         if (*openings < total_openings)
1574                                 *relsim_flags = RELSIM_ADJUST_OPENINGS;
1575                         else {
1576                                 /*
1577                                  * Some devices report queue full for
1578                                  * temporary resource shortages.  For
1579                                  * this reason, we allow a minimum
1580                                  * tag count to be entered via a
1581                                  * quirk entry to prevent the queue
1582                                  * count on these devices from falling
1583                                  * to a pessimisticly low value.  We
1584                                  * still wait for the next successful
1585                                  * completion, however, before queueing
1586                                  * more transactions to the device.
1587                                  */
1588                                 *relsim_flags = RELSIM_RELEASE_AFTER_CMDCMPLT;
1589                         }
1590                         *timeout = 0;
1591                         error = ERESTART;
1592                         *action &= ~SSQ_PRINT_SENSE;
1593                         break;
1594                 }
1595                 /* FALLTHROUGH */
1596         }
1597         case SCSI_STATUS_BUSY:
1598                 /*
1599                  * Restart the queue after either another
1600                  * command completes or a 1 second timeout.
1601                  */
1602                 periph = xpt_path_periph(ccb->ccb_h.path);
1603                 if (periph->flags & CAM_PERIPH_INVALID) {
1604                         error = EIO;
1605                         *action_string = "Periph was invalidated";
1606                 } else if ((sense_flags & SF_RETRY_BUSY) != 0 ||
1607                     ccb->ccb_h.retry_count > 0) {
1608                         if ((sense_flags & SF_RETRY_BUSY) == 0)
1609                                 ccb->ccb_h.retry_count--;
1610                         error = ERESTART;
1611                         *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT
1612                                       | RELSIM_RELEASE_AFTER_CMDCMPLT;
1613                         *timeout = 1000;
1614                 } else {
1615                         error = EIO;
1616                         *action_string = "Retries exhausted";
1617                 }
1618                 break;
1619         case SCSI_STATUS_RESERV_CONFLICT:
1620         default:
1621                 error = EIO;
1622                 break;
1623         }
1624         return (error);
1625 }
1626
1627 static int
1628 camperiphscsisenseerror(union ccb *ccb, union ccb **orig,
1629     cam_flags camflags, u_int32_t sense_flags,
1630     int *openings, u_int32_t *relsim_flags,
1631     u_int32_t *timeout, u_int32_t *action, const char **action_string)
1632 {
1633         struct cam_periph *periph;
1634         union ccb *orig_ccb = ccb;
1635         int error, recoveryccb;
1636         u_int16_t flags;
1637
1638 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
1639         if (ccb->ccb_h.func_code == XPT_SCSI_IO && ccb->csio.bio != NULL)
1640                 biotrack(ccb->csio.bio, __func__);
1641 #endif
1642
1643         periph = xpt_path_periph(ccb->ccb_h.path);
1644         recoveryccb = (ccb->ccb_h.cbfcnp == camperiphdone);
1645         if ((periph->flags & CAM_PERIPH_RECOVERY_INPROG) && !recoveryccb) {
1646                 /*
1647                  * If error recovery is already in progress, don't attempt
1648                  * to process this error, but requeue it unconditionally
1649                  * and attempt to process it once error recovery has
1650                  * completed.  This failed command is probably related to
1651                  * the error that caused the currently active error recovery
1652                  * action so our  current recovery efforts should also
1653                  * address this command.  Be aware that the error recovery
1654                  * code assumes that only one recovery action is in progress
1655                  * on a particular peripheral instance at any given time
1656                  * (e.g. only one saved CCB for error recovery) so it is
1657                  * imperitive that we don't violate this assumption.
1658                  */
1659                 error = ERESTART;
1660                 *action &= ~SSQ_PRINT_SENSE;
1661         } else {
1662                 scsi_sense_action err_action;
1663                 struct ccb_getdev cgd;
1664
1665                 /*
1666                  * Grab the inquiry data for this device.
1667                  */
1668                 memset(&cgd, 0, sizeof(cgd));
1669                 xpt_setup_ccb(&cgd.ccb_h, ccb->ccb_h.path, CAM_PRIORITY_NORMAL);
1670                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1671                 xpt_action((union ccb *)&cgd);
1672
1673                 err_action = scsi_error_action(&ccb->csio, &cgd.inq_data,
1674                     sense_flags);
1675                 error = err_action & SS_ERRMASK;
1676
1677                 /*
1678                  * Do not autostart sequential access devices
1679                  * to avoid unexpected tape loading.
1680                  */
1681                 if ((err_action & SS_MASK) == SS_START &&
1682                     SID_TYPE(&cgd.inq_data) == T_SEQUENTIAL) {
1683                         *action_string = "Will not autostart a "
1684                             "sequential access device";
1685                         goto sense_error_done;
1686                 }
1687
1688                 /*
1689                  * Avoid recovery recursion if recovery action is the same.
1690                  */
1691                 if ((err_action & SS_MASK) >= SS_START && recoveryccb) {
1692                         if (((err_action & SS_MASK) == SS_START &&
1693                              ccb->csio.cdb_io.cdb_bytes[0] == START_STOP_UNIT) ||
1694                             ((err_action & SS_MASK) == SS_TUR &&
1695                              (ccb->csio.cdb_io.cdb_bytes[0] == TEST_UNIT_READY))) {
1696                                 err_action = SS_RETRY|SSQ_DECREMENT_COUNT|EIO;
1697                                 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1698                                 *timeout = 500;
1699                         }
1700                 }
1701
1702                 /*
1703                  * If the recovery action will consume a retry,
1704                  * make sure we actually have retries available.
1705                  */
1706                 if ((err_action & SSQ_DECREMENT_COUNT) != 0) {
1707                         if (ccb->ccb_h.retry_count > 0 &&
1708                             (periph->flags & CAM_PERIPH_INVALID) == 0)
1709                                 ccb->ccb_h.retry_count--;
1710                         else {
1711                                 *action_string = "Retries exhausted";
1712                                 goto sense_error_done;
1713                         }
1714                 }
1715
1716                 if ((err_action & SS_MASK) >= SS_START) {
1717                         /*
1718                          * Do common portions of commands that
1719                          * use recovery CCBs.
1720                          */
1721                         orig_ccb = xpt_alloc_ccb_nowait();
1722                         if (orig_ccb == NULL) {
1723                                 *action_string = "Can't allocate recovery CCB";
1724                                 goto sense_error_done;
1725                         }
1726                         /*
1727                          * Clear freeze flag for original request here, as
1728                          * this freeze will be dropped as part of ERESTART.
1729                          */
1730                         ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1731
1732                         KASSERT(ccb->ccb_h.func_code == XPT_SCSI_IO,
1733                             ("%s: ccb func_code %#x != XPT_SCSI_IO",
1734                              __func__, ccb->ccb_h.func_code));
1735                         flags = orig_ccb->ccb_h.alloc_flags;
1736                         bcopy(ccb, orig_ccb, sizeof(struct ccb_scsiio));
1737                         orig_ccb->ccb_h.alloc_flags = flags;
1738                 }
1739
1740                 switch (err_action & SS_MASK) {
1741                 case SS_NOP:
1742                         *action_string = "No recovery action needed";
1743                         error = 0;
1744                         break;
1745                 case SS_RETRY:
1746                         *action_string = "Retrying command (per sense data)";
1747                         error = ERESTART;
1748                         break;
1749                 case SS_FAIL:
1750                         *action_string = "Unretryable error";
1751                         break;
1752                 case SS_START:
1753                 {
1754                         int le;
1755
1756                         /*
1757                          * Send a start unit command to the device, and
1758                          * then retry the command.
1759                          */
1760                         *action_string = "Attempting to start unit";
1761                         periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1762
1763                         /*
1764                          * Check for removable media and set
1765                          * load/eject flag appropriately.
1766                          */
1767                         if (SID_IS_REMOVABLE(&cgd.inq_data))
1768                                 le = TRUE;
1769                         else
1770                                 le = FALSE;
1771
1772                         scsi_start_stop(&ccb->csio,
1773                                         /*retries*/1,
1774                                         camperiphdone,
1775                                         MSG_SIMPLE_Q_TAG,
1776                                         /*start*/TRUE,
1777                                         /*load/eject*/le,
1778                                         /*immediate*/FALSE,
1779                                         SSD_FULL_SIZE,
1780                                         /*timeout*/50000);
1781                         break;
1782                 }
1783                 case SS_TUR:
1784                 {
1785                         /*
1786                          * Send a Test Unit Ready to the device.
1787                          * If the 'many' flag is set, we send 120
1788                          * test unit ready commands, one every half 
1789                          * second.  Otherwise, we just send one TUR.
1790                          * We only want to do this if the retry 
1791                          * count has not been exhausted.
1792                          */
1793                         int retries;
1794
1795                         if ((err_action & SSQ_MANY) != 0 && (periph->flags &
1796                              CAM_PERIPH_RECOVERY_WAIT_FAILED) == 0) {
1797                                 periph->flags |= CAM_PERIPH_RECOVERY_WAIT;
1798                                 *action_string = "Polling device for readiness";
1799                                 retries = 120;
1800                         } else {
1801                                 *action_string = "Testing device for readiness";
1802                                 retries = 1;
1803                         }
1804                         periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1805                         scsi_test_unit_ready(&ccb->csio,
1806                                              retries,
1807                                              camperiphdone,
1808                                              MSG_SIMPLE_Q_TAG,
1809                                              SSD_FULL_SIZE,
1810                                              /*timeout*/5000);
1811
1812                         /*
1813                          * Accomplish our 500ms delay by deferring
1814                          * the release of our device queue appropriately.
1815                          */
1816                         *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1817                         *timeout = 500;
1818                         break;
1819                 }
1820                 default:
1821                         panic("Unhandled error action %x", err_action);
1822                 }
1823                 
1824                 if ((err_action & SS_MASK) >= SS_START) {
1825                         /*
1826                          * Drop the priority, so that the recovery
1827                          * CCB is the first to execute.  Freeze the queue
1828                          * after this command is sent so that we can
1829                          * restore the old csio and have it queued in
1830                          * the proper order before we release normal 
1831                          * transactions to the device.
1832                          */
1833                         ccb->ccb_h.pinfo.priority--;
1834                         ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1835                         ccb->ccb_h.saved_ccb_ptr = orig_ccb;
1836                         error = ERESTART;
1837                         *orig = orig_ccb;
1838                 }
1839
1840 sense_error_done:
1841                 *action = err_action;
1842         }
1843         return (error);
1844 }
1845
1846 /*
1847  * Generic error handler.  Peripheral drivers usually filter
1848  * out the errors that they handle in a unique manner, then
1849  * call this function.
1850  */
1851 int
1852 cam_periph_error(union ccb *ccb, cam_flags camflags,
1853                  u_int32_t sense_flags)
1854 {
1855         struct cam_path *newpath;
1856         union ccb  *orig_ccb, *scan_ccb;
1857         struct cam_periph *periph;
1858         const char *action_string;
1859         cam_status  status;
1860         int         frozen, error, openings, devctl_err;
1861         u_int32_t   action, relsim_flags, timeout;
1862
1863         action = SSQ_PRINT_SENSE;
1864         periph = xpt_path_periph(ccb->ccb_h.path);
1865         action_string = NULL;
1866         status = ccb->ccb_h.status;
1867         frozen = (status & CAM_DEV_QFRZN) != 0;
1868         status &= CAM_STATUS_MASK;
1869         devctl_err = openings = relsim_flags = timeout = 0;
1870         orig_ccb = ccb;
1871
1872         /* Filter the errors that should be reported via devctl */
1873         switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
1874         case CAM_CMD_TIMEOUT:
1875         case CAM_REQ_ABORTED:
1876         case CAM_REQ_CMP_ERR:
1877         case CAM_REQ_TERMIO:
1878         case CAM_UNREC_HBA_ERROR:
1879         case CAM_DATA_RUN_ERR:
1880         case CAM_SCSI_STATUS_ERROR:
1881         case CAM_ATA_STATUS_ERROR:
1882         case CAM_SMP_STATUS_ERROR:
1883                 devctl_err++;
1884                 break;
1885         default:
1886                 break;
1887         }
1888
1889         switch (status) {
1890         case CAM_REQ_CMP:
1891                 error = 0;
1892                 action &= ~SSQ_PRINT_SENSE;
1893                 break;
1894         case CAM_SCSI_STATUS_ERROR:
1895                 error = camperiphscsistatuserror(ccb, &orig_ccb,
1896                     camflags, sense_flags, &openings, &relsim_flags,
1897                     &timeout, &action, &action_string);
1898                 break;
1899         case CAM_AUTOSENSE_FAIL:
1900                 error = EIO;    /* we have to kill the command */
1901                 break;
1902         case CAM_UA_ABORT:
1903         case CAM_UA_TERMIO:
1904         case CAM_MSG_REJECT_REC:
1905                 /* XXX Don't know that these are correct */
1906                 error = EIO;
1907                 break;
1908         case CAM_SEL_TIMEOUT:
1909                 if ((camflags & CAM_RETRY_SELTO) != 0) {
1910                         if (ccb->ccb_h.retry_count > 0 &&
1911                             (periph->flags & CAM_PERIPH_INVALID) == 0) {
1912                                 ccb->ccb_h.retry_count--;
1913                                 error = ERESTART;
1914
1915                                 /*
1916                                  * Wait a bit to give the device
1917                                  * time to recover before we try again.
1918                                  */
1919                                 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1920                                 timeout = periph_selto_delay;
1921                                 break;
1922                         }
1923                         action_string = "Retries exhausted";
1924                 }
1925                 /* FALLTHROUGH */
1926         case CAM_DEV_NOT_THERE:
1927                 error = ENXIO;
1928                 action = SSQ_LOST;
1929                 break;
1930         case CAM_REQ_INVALID:
1931         case CAM_PATH_INVALID:
1932         case CAM_NO_HBA:
1933         case CAM_PROVIDE_FAIL:
1934         case CAM_REQ_TOO_BIG:
1935         case CAM_LUN_INVALID:
1936         case CAM_TID_INVALID:
1937         case CAM_FUNC_NOTAVAIL:
1938                 error = EINVAL;
1939                 break;
1940         case CAM_SCSI_BUS_RESET:
1941         case CAM_BDR_SENT:
1942                 /*
1943                  * Commands that repeatedly timeout and cause these
1944                  * kinds of error recovery actions, should return
1945                  * CAM_CMD_TIMEOUT, which allows us to safely assume
1946                  * that this command was an innocent bystander to
1947                  * these events and should be unconditionally
1948                  * retried.
1949                  */
1950         case CAM_REQUEUE_REQ:
1951                 /* Unconditional requeue if device is still there */
1952                 if (periph->flags & CAM_PERIPH_INVALID) {
1953                         action_string = "Periph was invalidated";
1954                         error = EIO;
1955                 } else if (sense_flags & SF_NO_RETRY) {
1956                         error = EIO;
1957                         action_string = "Retry was blocked";
1958                 } else {
1959                         error = ERESTART;
1960                         action &= ~SSQ_PRINT_SENSE;
1961                 }
1962                 break;
1963         case CAM_RESRC_UNAVAIL:
1964                 /* Wait a bit for the resource shortage to abate. */
1965                 timeout = periph_noresrc_delay;
1966                 /* FALLTHROUGH */
1967         case CAM_BUSY:
1968                 if (timeout == 0) {
1969                         /* Wait a bit for the busy condition to abate. */
1970                         timeout = periph_busy_delay;
1971                 }
1972                 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1973                 /* FALLTHROUGH */
1974         case CAM_ATA_STATUS_ERROR:
1975         case CAM_REQ_CMP_ERR:
1976         case CAM_CMD_TIMEOUT:
1977         case CAM_UNEXP_BUSFREE:
1978         case CAM_UNCOR_PARITY:
1979         case CAM_DATA_RUN_ERR:
1980         default:
1981                 if (periph->flags & CAM_PERIPH_INVALID) {
1982                         error = EIO;
1983                         action_string = "Periph was invalidated";
1984                 } else if (ccb->ccb_h.retry_count == 0) {
1985                         error = EIO;
1986                         action_string = "Retries exhausted";
1987                 } else if (sense_flags & SF_NO_RETRY) {
1988                         error = EIO;
1989                         action_string = "Retry was blocked";
1990                 } else {
1991                         ccb->ccb_h.retry_count--;
1992                         error = ERESTART;
1993                 }
1994                 break;
1995         }
1996
1997         if ((sense_flags & SF_PRINT_ALWAYS) ||
1998             CAM_DEBUGGED(ccb->ccb_h.path, CAM_DEBUG_INFO))
1999                 action |= SSQ_PRINT_SENSE;
2000         else if (sense_flags & SF_NO_PRINT)
2001                 action &= ~SSQ_PRINT_SENSE;
2002         if ((action & SSQ_PRINT_SENSE) != 0)
2003                 cam_error_print(orig_ccb, CAM_ESF_ALL, CAM_EPF_ALL);
2004         if (error != 0 && (action & SSQ_PRINT_SENSE) != 0) {
2005                 if (error != ERESTART) {
2006                         if (action_string == NULL)
2007                                 action_string = "Unretryable error";
2008                         xpt_print(ccb->ccb_h.path, "Error %d, %s\n",
2009                             error, action_string);
2010                 } else if (action_string != NULL)
2011                         xpt_print(ccb->ccb_h.path, "%s\n", action_string);
2012                 else {
2013                         xpt_print(ccb->ccb_h.path,
2014                             "Retrying command, %d more tries remain\n",
2015                             ccb->ccb_h.retry_count);
2016                 }
2017         }
2018
2019         if (devctl_err && (error != 0 || (action & SSQ_PRINT_SENSE) != 0))
2020                 cam_periph_devctl_notify(orig_ccb);
2021
2022         if ((action & SSQ_LOST) != 0) {
2023                 lun_id_t lun_id;
2024
2025                 /*
2026                  * For a selection timeout, we consider all of the LUNs on
2027                  * the target to be gone.  If the status is CAM_DEV_NOT_THERE,
2028                  * then we only get rid of the device(s) specified by the
2029                  * path in the original CCB.
2030                  */
2031                 if (status == CAM_SEL_TIMEOUT)
2032                         lun_id = CAM_LUN_WILDCARD;
2033                 else
2034                         lun_id = xpt_path_lun_id(ccb->ccb_h.path);
2035
2036                 /* Should we do more if we can't create the path?? */
2037                 if (xpt_create_path(&newpath, periph,
2038                                     xpt_path_path_id(ccb->ccb_h.path),
2039                                     xpt_path_target_id(ccb->ccb_h.path),
2040                                     lun_id) == CAM_REQ_CMP) {
2041                         /*
2042                          * Let peripheral drivers know that this
2043                          * device has gone away.
2044                          */
2045                         xpt_async(AC_LOST_DEVICE, newpath, NULL);
2046                         xpt_free_path(newpath);
2047                 }
2048         }
2049
2050         /* Broadcast UNIT ATTENTIONs to all periphs. */
2051         if ((action & SSQ_UA) != 0)
2052                 xpt_async(AC_UNIT_ATTENTION, orig_ccb->ccb_h.path, orig_ccb);
2053
2054         /* Rescan target on "Reported LUNs data has changed" */
2055         if ((action & SSQ_RESCAN) != 0) {
2056                 if (xpt_create_path(&newpath, NULL,
2057                                     xpt_path_path_id(ccb->ccb_h.path),
2058                                     xpt_path_target_id(ccb->ccb_h.path),
2059                                     CAM_LUN_WILDCARD) == CAM_REQ_CMP) {
2060                         scan_ccb = xpt_alloc_ccb_nowait();
2061                         if (scan_ccb != NULL) {
2062                                 scan_ccb->ccb_h.path = newpath;
2063                                 scan_ccb->ccb_h.func_code = XPT_SCAN_TGT;
2064                                 scan_ccb->crcn.flags = 0;
2065                                 xpt_rescan(scan_ccb);
2066                         } else {
2067                                 xpt_print(newpath,
2068                                     "Can't allocate CCB to rescan target\n");
2069                                 xpt_free_path(newpath);
2070                         }
2071                 }
2072         }
2073
2074         /* Attempt a retry */
2075         if (error == ERESTART || error == 0) {
2076                 if (frozen != 0)
2077                         ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
2078                 if (error == ERESTART)
2079                         xpt_action(ccb);
2080                 if (frozen != 0)
2081                         cam_release_devq(ccb->ccb_h.path,
2082                                          relsim_flags,
2083                                          openings,
2084                                          timeout,
2085                                          /*getcount_only*/0);
2086         }
2087
2088         return (error);
2089 }
2090
2091 #define CAM_PERIPH_DEVD_MSG_SIZE        256
2092
2093 static void
2094 cam_periph_devctl_notify(union ccb *ccb)
2095 {
2096         struct cam_periph *periph;
2097         struct ccb_getdev *cgd;
2098         struct sbuf sb;
2099         int serr, sk, asc, ascq;
2100         char *sbmsg, *type;
2101
2102         sbmsg = malloc(CAM_PERIPH_DEVD_MSG_SIZE, M_CAMPERIPH, M_NOWAIT);
2103         if (sbmsg == NULL)
2104                 return;
2105
2106         sbuf_new(&sb, sbmsg, CAM_PERIPH_DEVD_MSG_SIZE, SBUF_FIXEDLEN);
2107
2108         periph = xpt_path_periph(ccb->ccb_h.path);
2109         sbuf_printf(&sb, "device=%s%d ", periph->periph_name,
2110             periph->unit_number);
2111
2112         sbuf_printf(&sb, "serial=\"");
2113         if ((cgd = (struct ccb_getdev *)xpt_alloc_ccb_nowait()) != NULL) {
2114                 xpt_setup_ccb(&cgd->ccb_h, ccb->ccb_h.path,
2115                     CAM_PRIORITY_NORMAL);
2116                 cgd->ccb_h.func_code = XPT_GDEV_TYPE;
2117                 xpt_action((union ccb *)cgd);
2118
2119                 if (cgd->ccb_h.status == CAM_REQ_CMP)
2120                         sbuf_bcat(&sb, cgd->serial_num, cgd->serial_num_len);
2121                 xpt_free_ccb((union ccb *)cgd);
2122         }
2123         sbuf_printf(&sb, "\" ");
2124         sbuf_printf(&sb, "cam_status=\"0x%x\" ", ccb->ccb_h.status);
2125
2126         switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
2127         case CAM_CMD_TIMEOUT:
2128                 sbuf_printf(&sb, "timeout=%d ", ccb->ccb_h.timeout);
2129                 type = "timeout";
2130                 break;
2131         case CAM_SCSI_STATUS_ERROR:
2132                 sbuf_printf(&sb, "scsi_status=%d ", ccb->csio.scsi_status);
2133                 if (scsi_extract_sense_ccb(ccb, &serr, &sk, &asc, &ascq))
2134                         sbuf_printf(&sb, "scsi_sense=\"%02x %02x %02x %02x\" ",
2135                             serr, sk, asc, ascq);
2136                 type = "error";
2137                 break;
2138         case CAM_ATA_STATUS_ERROR:
2139                 sbuf_printf(&sb, "RES=\"");
2140                 ata_res_sbuf(&ccb->ataio.res, &sb);
2141                 sbuf_printf(&sb, "\" ");
2142                 type = "error";
2143                 break;
2144         default:
2145                 type = "error";
2146                 break;
2147         }
2148
2149         if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2150                 sbuf_printf(&sb, "CDB=\"");
2151                 scsi_cdb_sbuf(scsiio_cdb_ptr(&ccb->csio), &sb);
2152                 sbuf_printf(&sb, "\" ");
2153         } else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
2154                 sbuf_printf(&sb, "ACB=\"");
2155                 ata_cmd_sbuf(&ccb->ataio.cmd, &sb);
2156                 sbuf_printf(&sb, "\" ");
2157         }
2158
2159         if (sbuf_finish(&sb) == 0)
2160                 devctl_notify("CAM", "periph", type, sbuf_data(&sb));
2161         sbuf_delete(&sb);
2162         free(sbmsg, M_CAMPERIPH);
2163 }
2164
2165 /*
2166  * Sysctl to force an invalidation of the drive right now. Can be
2167  * called with CTLFLAG_MPSAFE since we take periph lock.
2168  */
2169 int
2170 cam_periph_invalidate_sysctl(SYSCTL_HANDLER_ARGS)
2171 {
2172         struct cam_periph *periph;
2173         int error, value;
2174
2175         periph = arg1;
2176         value = 0;
2177         error = sysctl_handle_int(oidp, &value, 0, req);
2178         if (error != 0 || req->newptr == NULL || value != 1)
2179                 return (error);
2180
2181         cam_periph_lock(periph);
2182         cam_periph_invalidate(periph);
2183         cam_periph_unlock(periph);
2184
2185         return (0);
2186 }