summaryrefslogtreecommitdiffstats
path: root/src/providers/ldap/sdap_child_helpers.c
blob: 5a15e661e3ca014e511dc5647dd199d9839100a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
/*
    SSSD

    LDAP Backend Module -- child helpers

    Authors:
        Jakub Hrozek <jhrozek@redhat.com>

    Copyright (C) 2009 Red Hat

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <sys/types.h>
#include <sys/wait.h>
#include <pwd.h>
#include <unistd.h>
#include <fcntl.h>

#include "util/util.h"
#include "util/sss_krb5.h"
#include "providers/ldap/ldap_common.h"
#include "providers/ldap/sdap_async_private.h"
#include "providers/child_common.h"

#ifndef SSSD_LIBEXEC_PATH
#error "SSSD_LIBEXEC_PATH not defined"
#else
#define LDAP_CHILD SSSD_LIBEXEC_PATH"/ldap_child"
#endif

#ifndef LDAP_CHILD_USER
#define LDAP_CHILD_USER  "nobody"
#endif

struct sdap_child {
    /* child info */
    pid_t pid;
    int read_from_child_fd;
    int write_to_child_fd;
};

static void sdap_close_fd(int *fd)
{
    int ret;

    if (*fd == -1) {
        DEBUG(6, ("fd already closed\n"));
        return;
    }

    ret = close(*fd);
    if (ret) {
        ret = errno;
        DEBUG(2, ("Closing fd %d, return error %d (%s)\n",
                  *fd, ret, strerror(ret)));
    }

    *fd = -1;
}

static int sdap_child_destructor(void *ptr)
{
    struct sdap_child *child = talloc_get_type(ptr, struct sdap_child);

    child_cleanup(child->read_from_child_fd, child->write_to_child_fd);

    return 0;
}

static errno_t sdap_fork_child(struct tevent_context *ev,
                               struct sdap_child *child)
{
    int pipefd_to_child[2];
    int pipefd_from_child[2];
    pid_t pid;
    int ret;
    errno_t err;

    ret = pipe(pipefd_from_child);
    if (ret == -1) {
        err = errno;
        DEBUG(1, ("pipe failed [%d][%s].\n", err, strerror(err)));
        return err;
    }
    ret = pipe(pipefd_to_child);
    if (ret == -1) {
        err = errno;
        DEBUG(1, ("pipe failed [%d][%s].\n", err, strerror(err)));
        return err;
    }

    pid = fork();

    if (pid == 0) { /* child */
        err = exec_child(child,
                         pipefd_to_child, pipefd_from_child,
                         LDAP_CHILD, ldap_child_debug_fd);
        if (err != EOK) {
            DEBUG(1, ("Could not exec LDAP child: [%d][%s].\n",
                      err, strerror(err)));
            return err;
        }
    } else if (pid > 0) { /* parent */
        child->pid = pid;
        child->read_from_child_fd = pipefd_from_child[0];
        close(pipefd_from_child[1]);
        child->write_to_child_fd = pipefd_to_child[1];
        close(pipefd_to_child[0]);
        fd_nonblocking(child->read_from_child_fd);
        fd_nonblocking(child->write_to_child_fd);

        ret = child_handler_setup(ev, pid, NULL, NULL);
        if (ret != EOK) {
            return ret;
        }

    } else { /* error */
        err = errno;
        DEBUG(1, ("fork failed [%d][%s].\n", err, strerror(err)));
        return err;
    }

    return EOK;
}

static errno_t create_tgt_req_send_buffer(TALLOC_CTX *mem_ctx,
                                          const char *realm_str,
                                          const char *princ_str,
                                          const char *keytab_name,
                                          int32_t lifetime,
                                          struct io_buffer **io_buf)
{
    struct io_buffer *buf;
    size_t rp;

    buf = talloc(mem_ctx, struct io_buffer);
    if (buf == NULL) {
        DEBUG(1, ("talloc failed.\n"));
        return ENOMEM;
    }

    buf->size = 4 * sizeof(uint32_t);
    if (realm_str) {
        buf->size += strlen(realm_str);
    }
    if (princ_str) {
        buf->size += strlen(princ_str);
    }
    if (keytab_name) {
        buf->size += strlen(keytab_name);
    }

    DEBUG(7, ("buffer size: %d\n", buf->size));

    buf->data = talloc_size(buf, buf->size);
    if (buf->data == NULL) {
        DEBUG(1, ("talloc_size failed.\n"));
        talloc_free(buf);
        return ENOMEM;
    }

    rp = 0;

    /* realm */
    if (realm_str) {
        SAFEALIGN_SET_UINT32(&buf->data[rp], strlen(realm_str), &rp);
        safealign_memcpy(&buf->data[rp], realm_str, strlen(realm_str), &rp);
    } else {
        SAFEALIGN_SET_UINT32(&buf->data[rp], 0, &rp);
    }

    /* principal */
    if (princ_str) {
        SAFEALIGN_SET_UINT32(&buf->data[rp], strlen(princ_str), &rp);
        safealign_memcpy(&buf->data[rp], princ_str, strlen(princ_str), &rp);
    } else {
        SAFEALIGN_SET_UINT32(&buf->data[rp], 0, &rp);
    }

    /* keytab */
    if (keytab_name) {
        SAFEALIGN_SET_UINT32(&buf->data[rp], strlen(keytab_name), &rp);
        safealign_memcpy(&buf->data[rp], keytab_name, strlen(keytab_name), &rp);
    } else {
        SAFEALIGN_SET_UINT32(&buf->data[rp], 0, &rp);
    }

    /* lifetime */
    SAFEALIGN_SET_UINT32(&buf->data[rp], lifetime, &rp);

    *io_buf = buf;
    return EOK;
}

static int parse_child_response(TALLOC_CTX *mem_ctx,
                                uint8_t *buf, ssize_t size,
                                int  *result, krb5_error_code *kerr,
                                char **ccache, time_t *expire_time_out)
{
    size_t p = 0;
    uint32_t len;
    uint32_t res;
    char *ccn;
    time_t expire_time;
    krb5_error_code krberr;

    /* operation result code */
    SAFEALIGN_COPY_UINT32_CHECK(&res, buf + p, size, &p);

    /* krb5 error code */
    safealign_memcpy(&krberr, buf+p, sizeof(krberr), &p);

    /* ccache name size */
    SAFEALIGN_COPY_UINT32_CHECK(&len, buf + p, size, &p);

    if ((p + len ) > size) return EINVAL;

    ccn = talloc_size(mem_ctx, sizeof(char) * (len + 1));
    if (ccn == NULL) {
        DEBUG(1, ("talloc_size failed.\n"));
        return ENOMEM;
    }
    safealign_memcpy(ccn, buf+p, sizeof(char) * len, &p);
    ccn[len] = '\0';

    if (p + sizeof(time_t) > size) {
        talloc_free(ccn);
        return EINVAL;
    }
    safealign_memcpy(&expire_time, buf+p, sizeof(time_t), &p);

    *result = res;
    *ccache = ccn;
    *expire_time_out = expire_time;
    *kerr = krberr;
    return EOK;
}

/* ==The-public-async-interface============================================*/

struct sdap_get_tgt_state {
    struct tevent_context *ev;
    struct sdap_child *child;
    ssize_t len;
    uint8_t *buf;
};

static errno_t set_tgt_child_timeout(struct tevent_req *req,
                                     struct tevent_context *ev,
                                     int timeout);
static void sdap_get_tgt_step(struct tevent_req *subreq);
static void sdap_get_tgt_done(struct tevent_req *subreq);

struct tevent_req *sdap_get_tgt_send(TALLOC_CTX *mem_ctx,
                                     struct tevent_context *ev,
                                     const char *realm_str,
                                     const char *princ_str,
                                     const char *keytab_name,
                                     int32_t lifetime,
                                     int timeout)
{
    struct tevent_req *req, *subreq;
    struct sdap_get_tgt_state *state;
    struct io_buffer *buf;
    int ret;

    req = tevent_req_create(mem_ctx, &state, struct sdap_get_tgt_state);
    if (!req) {
        return NULL;
    }

    state->ev = ev;

    state->child = talloc_zero(state, struct sdap_child);
    if (!state->child) {
        ret = ENOMEM;
        goto fail;
    }

    state->child->read_from_child_fd = -1;
    state->child->write_to_child_fd = -1;
    talloc_set_destructor((TALLOC_CTX *)state->child, sdap_child_destructor);

    /* prepare the data to pass to child */
    ret = create_tgt_req_send_buffer(state,
                                     realm_str, princ_str, keytab_name, lifetime,
                                     &buf);
    if (ret != EOK) {
        DEBUG(1, ("create_tgt_req_send_buffer failed.\n"));
        goto fail;
    }

    ret = sdap_fork_child(state->ev, state->child);
    if (ret != EOK) {
        DEBUG(1, ("sdap_fork_child failed.\n"));
        goto fail;
    }

    ret = set_tgt_child_timeout(req, ev, timeout);
    if (ret != EOK) {
        DEBUG(1, ("activate_child_timeout_handler failed.\n"));
        goto fail;
    }

    subreq = write_pipe_send(state, ev, buf->data, buf->size,
                             state->child->write_to_child_fd);
    if (!subreq) {
        ret = ENOMEM;
        goto fail;
    }
    tevent_req_set_callback(subreq, sdap_get_tgt_step, req);

    return req;

fail:
    tevent_req_error(req, ret);
    tevent_req_post(req, ev);
    return req;
}

static void sdap_get_tgt_step(struct tevent_req *subreq)
{
    struct tevent_req *req = tevent_req_callback_data(subreq,
                                                      struct tevent_req);
    struct sdap_get_tgt_state *state = tevent_req_data(req,
                                                  struct sdap_get_tgt_state);
    int ret;

    ret = write_pipe_recv(subreq);
    talloc_zfree(subreq);
    if (ret != EOK) {
        tevent_req_error(req, ret);
        return;
    }

    sdap_close_fd(&state->child->write_to_child_fd);

    subreq = read_pipe_send(state, state->ev,
                            state->child->read_from_child_fd);
    if (!subreq) {
        tevent_req_error(req, ENOMEM);
        return;
    }
    tevent_req_set_callback(subreq, sdap_get_tgt_done, req);
}

static void sdap_get_tgt_done(struct tevent_req *subreq)
{
    struct tevent_req *req = tevent_req_callback_data(subreq,
                                                      struct tevent_req);
    struct sdap_get_tgt_state *state = tevent_req_data(req,
                                                  struct sdap_get_tgt_state);
    int ret;

    ret = read_pipe_recv(subreq, state, &state->buf, &state->len);
    talloc_zfree(subreq);
    if (ret != EOK) {
        tevent_req_error(req, ret);
        return;
    }

    sdap_close_fd(&state->child->read_from_child_fd);

    tevent_req_done(req);
}

int sdap_get_tgt_recv(struct tevent_req *req,
                      TALLOC_CTX *mem_ctx,
                      int  *result,
                      krb5_error_code *kerr,
                      char **ccname,
                      time_t *expire_time_out)
{
    struct sdap_get_tgt_state *state = tevent_req_data(req,
                                             struct sdap_get_tgt_state);
    char *ccn;
    time_t expire_time;
    int  res;
    int ret;
    krb5_error_code krberr;

    TEVENT_REQ_RETURN_ON_ERROR(req);

    ret = parse_child_response(mem_ctx, state->buf, state->len,
                               &res, &krberr, &ccn, &expire_time);
    if (ret != EOK) {
        DEBUG(1, ("Cannot parse child response: [%d][%s]\n", ret, strerror(ret)));
        return ret;
    }

    DEBUG(6, ("Child responded: %d [%s], expired on [%ld]\n", res, ccn, (long)expire_time));
    *result = res;
    *kerr = krberr;
    *ccname = ccn;
    *expire_time_out = expire_time;
    return EOK;
}



static void get_tgt_timeout_handler(struct tevent_context *ev,
                                    struct tevent_timer *te,
                                    struct timeval tv, void *pvt)
{
    struct tevent_req *req = talloc_get_type(pvt, struct tevent_req);
    struct sdap_get_tgt_state *state = tevent_req_data(req,
                                            struct sdap_get_tgt_state);
    int ret;

    DEBUG(9, ("timeout for tgt child [%d] reached.\n", state->child->pid));

    ret = kill(state->child->pid, SIGKILL);
    if (ret == -1) {
        DEBUG(1, ("kill failed [%d][%s].\n", errno, strerror(errno)));
    }

    tevent_req_error(req, ETIMEDOUT);
}

static errno_t set_tgt_child_timeout(struct tevent_req *req,
                                     struct tevent_context *ev,
                                     int timeout)
{
    struct tevent_timer *te;
    struct timeval tv;

    DEBUG(6, ("Setting %d seconds timeout for tgt child\n", timeout));

    tv = tevent_timeval_current_ofs(timeout, 0);

    te = tevent_add_timer(ev, req, tv, get_tgt_timeout_handler, req);
    if (te == NULL) {
        DEBUG(1, ("tevent_add_timer failed.\n"));
        return ENOMEM;
    }

    return EOK;
}



/* Setup child logging */
int setup_child(struct sdap_id_ctx *ctx)
{
    int ret;
    const char *mech;
    unsigned v;
    FILE *debug_filep;

    mech = dp_opt_get_string(ctx->opts->basic,
                             SDAP_SASL_MECH);
    if (!mech) {
        return EOK;
    }

    if (mech && (strcasecmp(mech, "GSSAPI") == 0)) {
        ret = sss_krb5_verify_keytab(dp_opt_get_string(ctx->opts->basic,
                                                       SDAP_SASL_AUTHID),
                                     dp_opt_get_string(ctx->opts->basic,
                                                       SDAP_KRB5_REALM),
                                     dp_opt_get_string(ctx->opts->basic,
                                                       SDAP_KRB5_KEYTAB));

        if (ret != EOK) {
            DEBUG(0, ("Could not verify keytab\n"))
            return ret;
        }

    }

    if (debug_to_file != 0 && ldap_child_debug_fd == -1) {
        ret = open_debug_file_ex("ldap_child", &debug_filep);
        if (ret != EOK) {
            DEBUG(0, ("Error setting up logging (%d) [%s]\n",
                        ret, strerror(ret)));
            return ret;
        }

        ldap_child_debug_fd = fileno(debug_filep);
        if (ldap_child_debug_fd == -1) {
            DEBUG(0, ("fileno failed [%d][%s]\n", errno, strerror(errno)));
            ret = errno;
            return ret;
        }

        v = fcntl(ldap_child_debug_fd, F_GETFD, 0);
        fcntl(ldap_child_debug_fd, F_SETFD, v & ~FD_CLOEXEC);
    }

    return EOK;
}
> 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504
/*
 * This is the Fusion MPT base driver providing common API layer interface
 * for access to MPT (Message Passing Technology) firmware.
 *
 * This code is based on drivers/scsi/mpt2sas/mpt2_base.c
 * Copyright (C) 2007-2008  LSI Corporation
 *  (mailto:DL-MPTFusionLinux@lsi.com)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * NO WARRANTY
 * THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
 * LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
 * solely responsible for determining the appropriateness of using and
 * distributing the Program and assumes all risks associated with its
 * exercise of rights under this Agreement, including but not limited to
 * the risks and costs of program errors, damage to or loss of data,
 * programs or equipment, and unavailability or interruption of operations.

 * DISCLAIMER OF LIABILITY
 * NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
 * HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 */

#include <linux/version.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/kdev_t.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/sort.h>
#include <linux/io.h>

#include "mpt2sas_base.h"

static MPT_CALLBACK	mpt_callbacks[MPT_MAX_CALLBACKS];

#define FAULT_POLLING_INTERVAL 1000 /* in milliseconds */
#define MPT2SAS_MAX_REQUEST_QUEUE 500 /* maximum controller queue depth */

static int max_queue_depth = -1;
module_param(max_queue_depth, int, 0);
MODULE_PARM_DESC(max_queue_depth, " max controller queue depth ");

static int max_sgl_entries = -1;
module_param(max_sgl_entries, int, 0);
MODULE_PARM_DESC(max_sgl_entries, " max sg entries ");

static int msix_disable = -1;
module_param(msix_disable, int, 0);
MODULE_PARM_DESC(msix_disable, " disable msix routed interrupts (default=0)");

/**
 * _base_fault_reset_work - workq handling ioc fault conditions
 * @work: input argument, used to derive ioc
 * Context: sleep.
 *
 * Return nothing.
 */
static void
_base_fault_reset_work(struct work_struct *work)
{
	struct MPT2SAS_ADAPTER *ioc =
	    container_of(work, struct MPT2SAS_ADAPTER, fault_reset_work.work);
	unsigned long	 flags;
	u32 doorbell;
	int rc;

	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
	if (ioc->ioc_reset_in_progress)
		goto rearm_timer;
	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);

	doorbell = mpt2sas_base_get_iocstate(ioc, 0);
	if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
		rc = mpt2sas_base_hard_reset_handler(ioc, CAN_SLEEP,
		    FORCE_BIG_HAMMER);
		printk(MPT2SAS_WARN_FMT "%s: hard reset: %s\n", ioc->name,
		    __func__, (rc == 0) ? "success" : "failed");
		doorbell = mpt2sas_base_get_iocstate(ioc, 0);
		if ((doorbell & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT)
			mpt2sas_base_fault_info(ioc, doorbell &
			    MPI2_DOORBELL_DATA_MASK);
	}

	spin_lock_irqsave(&ioc->ioc_reset_in_progress_lock, flags);
 rearm_timer:
	if (ioc->fault_reset_work_q)
		queue_delayed_work(ioc->fault_reset_work_q,
		    &ioc->fault_reset_work,
		    msecs_to_jiffies(FAULT_POLLING_INTERVAL));
	spin_unlock_irqrestore(&ioc->ioc_reset_in_progress_lock, flags);
}

#ifdef CONFIG_SCSI_MPT2SAS_LOGGING
/**
 * _base_sas_ioc_info - verbose translation of the ioc status
 * @ioc: pointer to scsi command object
 * @mpi_reply: reply mf payload returned from firmware
 * @request_hdr: request mf
 *
 * Return nothing.
 */
static void
_base_sas_ioc_info(struct MPT2SAS_ADAPTER *ioc, MPI2DefaultReply_t *mpi_reply,
     MPI2RequestHeader_t *request_hdr)
{
	u16 ioc_status = le16_to_cpu(mpi_reply->IOCStatus) &
	    MPI2_IOCSTATUS_MASK;
	char *desc = NULL;
	u16 frame_sz;
	char *func_str = NULL;

	/* SCSI_IO, RAID_PASS are handled from _scsih_scsi_ioc_info */
	if (request_hdr->Function == MPI2_FUNCTION_SCSI_IO_REQUEST ||
	    request_hdr->Function == MPI2_FUNCTION_RAID_SCSI_IO_PASSTHROUGH ||
	    request_hdr->Function == MPI2_FUNCTION_EVENT_NOTIFICATION)
		return;

	switch (ioc_status) {

/****************************************************************************
*  Common IOCStatus values for all replies
****************************************************************************/

	case MPI2_IOCSTATUS_INVALID_FUNCTION:
		desc = "invalid function";
		break;
	case MPI2_IOCSTATUS_BUSY:
		desc = "busy";
		break;
	case MPI2_IOCSTATUS_INVALID_SGL:
		desc = "invalid sgl";
		break;
	case MPI2_IOCSTATUS_INTERNAL_ERROR:
		desc = "internal error";
		break;
	case MPI2_IOCSTATUS_INVALID_VPID:
		desc = "invalid vpid";
		break;
	case MPI2_IOCSTATUS_INSUFFICIENT_RESOURCES:
		desc = "insufficient resources";
		break;
	case MPI2_IOCSTATUS_INVALID_FIELD:
		desc = "invalid field";
		break;
	case MPI2_IOCSTATUS_INVALID_STATE:
		desc = "invalid state";
		break;
	case MPI2_IOCSTATUS_OP_STATE_NOT_SUPPORTED:
		desc = "op state not supported";
		break;

/****************************************************************************
*  Config IOCStatus values
****************************************************************************/

	case MPI2_IOCSTATUS_CONFIG_INVALID_ACTION:
		desc = "config invalid action";
		break;
	case MPI2_IOCSTATUS_CONFIG_INVALID_TYPE:
		desc = "config invalid type";
		break;
	case MPI2_IOCSTATUS_CONFIG_INVALID_PAGE:
		desc = "config invalid page";
		break;
	case MPI2_IOCSTATUS_CONFIG_INVALID_DATA:
		desc = "config invalid data";
		break;
	case MPI2_IOCSTATUS_CONFIG_NO_DEFAULTS:
		desc = "config no defaults";
		break;
	case MPI2_IOCSTATUS_CONFIG_CANT_COMMIT:
		desc = "config cant commit";
		break;

/****************************************************************************
*  SCSI IO Reply
****************************************************************************/

	case MPI2_IOCSTATUS_SCSI_RECOVERED_ERROR:
	case MPI2_IOCSTATUS_SCSI_INVALID_DEVHANDLE:
	case MPI2_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
	case MPI2_IOCSTATUS_SCSI_DATA_OVERRUN:
	case MPI2_IOCSTATUS_SCSI_DATA_UNDERRUN:
	case MPI2_IOCSTATUS_SCSI_IO_DATA_ERROR:
	case MPI2_IOCSTATUS_SCSI_PROTOCOL_ERROR:
	case MPI2_IOCSTATUS_SCSI_TASK_TERMINATED:
	case MPI2_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
	case MPI2_IOCSTATUS_SCSI_TASK_MGMT_FAILED:
	case MPI2_IOCSTATUS_SCSI_IOC_TERMINATED:
	case MPI2_IOCSTATUS_SCSI_EXT_TERMINATED:
		break;

/****************************************************************************
*  For use by SCSI Initiator and SCSI Target end-to-end data protection
****************************************************************************/

	case MPI2_IOCSTATUS_EEDP_GUARD_ERROR:
		desc = "eedp guard error";
		break;
	case MPI2_IOCSTATUS_EEDP_REF_TAG_ERROR:
		desc = "eedp ref tag error";
		break;
	case MPI2_IOCSTATUS_EEDP_APP_TAG_ERROR:
		desc = "eedp app tag error";
		break;

/****************************************************************************
*  SCSI Target values
****************************************************************************/

	case MPI2_IOCSTATUS_TARGET_INVALID_IO_INDEX:
		desc = "target invalid io index";
		break;
	case MPI2_IOCSTATUS_TARGET_ABORTED:
		desc = "target aborted";
		break;
	case MPI2_IOCSTATUS_TARGET_NO_CONN_RETRYABLE:
		desc = "target no conn retryable";
		break;
	case MPI2_IOCSTATUS_TARGET_NO_CONNECTION:
		desc = "target no connection";
		break;
	case MPI2_IOCSTATUS_TARGET_XFER_COUNT_MISMATCH:
		desc = "target xfer count mismatch";
		break;
	case MPI2_IOCSTATUS_TARGET_DATA_OFFSET_ERROR:
		desc = "target data offset error";
		break;
	case MPI2_IOCSTATUS_TARGET_TOO_MUCH_WRITE_DATA:
		desc = "target too much write data";
		break;
	case MPI2_IOCSTATUS_TARGET_IU_TOO_SHORT:
		desc = "target iu too short";
		break;
	case MPI2_IOCSTATUS_TARGET_ACK_NAK_TIMEOUT:
		desc = "target ack nak timeout";
		break;
	case MPI2_IOCSTATUS_TARGET_NAK_RECEIVED:
		desc = "target nak received";
		break;

/****************************************************************************
*  Serial Attached SCSI values
****************************************************************************/

	case MPI2_IOCSTATUS_SAS_SMP_REQUEST_FAILED:
		desc = "smp request failed";
		break;
	case MPI2_IOCSTATUS_SAS_SMP_DATA_OVERRUN:
		desc = "smp data overrun";
		break;

/****************************************************************************
*  Diagnostic Buffer Post / Diagnostic Release values
****************************************************************************/

	case MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED:
		desc = "diagnostic released";
		break;
	default:
		break;
	}

	if (!desc)
		return;

	switch (request_hdr->Function) {
	case MPI2_FUNCTION_CONFIG:
		frame_sz = sizeof(Mpi2ConfigRequest_t) + ioc->sge_size;
		func_str = "config_page";
		break;
	case MPI2_FUNCTION_SCSI_TASK_MGMT:
		frame_sz = sizeof(Mpi2SCSITaskManagementRequest_t);
		func_str = "task_mgmt";
		break;
	case MPI2_FUNCTION_SAS_IO_UNIT_CONTROL:
		frame_sz = sizeof(Mpi2SasIoUnitControlRequest_t);
		func_str = "sas_iounit_ctl";
		break;
	case MPI2_FUNCTION_SCSI_ENCLOSURE_PROCESSOR:
		frame_sz = sizeof(Mpi2SepRequest_t);
		func_str = "enclosure";
		break;
	case MPI2_FUNCTION_IOC_INIT:
		frame_sz = sizeof(Mpi2IOCInitRequest_t);
		func_str = "ioc_init";
		break;
	case MPI2_FUNCTION_PORT_ENABLE:
		frame_sz = sizeof(Mpi2PortEnableRequest_t);
		func_str = "port_enable";
		break;
	case MPI2_FUNCTION_SMP_PASSTHROUGH:
		frame_sz = sizeof(Mpi2SmpPassthroughRequest_t) + ioc->sge_size;
		func_str = "smp_passthru";
		break;
	default:
		frame_sz = 32;
		func_str = "unknown";
		break;
	}

	printk(MPT2SAS_WARN_FMT "ioc_status: %s(0x%04x), request(0x%p),"
	    " (%s)\n", ioc->name, desc, ioc_status, request_hdr, func_str);

	_debug_dump_mf(request_hdr, frame_sz/4);
}

/**
 * _base_display_event_data - verbose translation of firmware asyn events
 * @ioc: pointer to scsi command object
 * @mpi_reply: reply mf payload returned from firmware
 *
 * Return nothing.
 */
static void
_base_display_event_data(struct MPT2SAS_ADAPTER *ioc,
    Mpi2EventNotificationReply_t *mpi_reply)
{
	char *desc = NULL;
	u16 event;

	if (!(ioc->logging_level & MPT_DEBUG_EVENTS))
		return;

	event = le16_to_cpu(mpi_reply->Event);

	switch (event) {
	case MPI2_EVENT_LOG_DATA:
		desc = "Log Data";
		break;
	case MPI2_EVENT_STATE_CHANGE:
		desc = "Status Change";
		break;
	case MPI2_EVENT_HARD_RESET_RECEIVED:
		desc = "Hard Reset Received";
		break;
	case MPI2_EVENT_EVENT_CHANGE:
		desc = "Event Change";
		break;
	case MPI2_EVENT_TASK_SET_FULL:
		desc = "Task Set Full";
		break;
	case MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE:
		desc = "Device Status Change";
		break;
	case MPI2_EVENT_IR_OPERATION_STATUS:
		desc = "IR Operation Status";
		break;
	case MPI2_EVENT_SAS_DISCOVERY:
		desc =  "Discovery";
		break;
	case MPI2_EVENT_SAS_BROADCAST_PRIMITIVE:
		desc = "SAS Broadcast Primitive";
		break;
	case MPI2_EVENT_SAS_INIT_DEVICE_STATUS_CHANGE:
		desc = "SAS Init Device Status Change";
		break;
	case MPI2_EVENT_SAS_INIT_TABLE_OVERFLOW:
		desc = "SAS Init Table Overflow";
		break;
	case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
		desc = "SAS Topology Change List";
		break;
	case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
		desc = "SAS Enclosure Device Status Change";
		break;
	case MPI2_EVENT_IR_VOLUME:
		desc = "IR Volume";
		break;
	case MPI2_EVENT_IR_PHYSICAL_DISK:
		desc = "IR Physical Disk";
		break;
	case MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST:
		desc = "IR Configuration Change List";
		break;
	case MPI2_EVENT_LOG_ENTRY_ADDED:
		desc = "Log Entry Added";
		break;
	}

	if (!desc)
		return;

	printk(MPT2SAS_INFO_FMT "%s\n", ioc->name, desc);
}
#endif

/**
 * _base_sas_log_info - verbose translation of firmware log info
 * @ioc: pointer to scsi command object
 * @log_info: log info
 *
 * Return nothing.
 */
static void
_base_sas_log_info(struct MPT2SAS_ADAPTER *ioc , u32 log_info)
{
	union loginfo_type {
		u32	loginfo;
		struct {
			u32	subcode:16;
			u32	code:8;
			u32	originator:4;
			u32	bus_type:4;
		} dw;
	};
	union loginfo_type sas_loginfo;
	char *originator_str = NULL;

	sas_loginfo.loginfo = log_info;
	if (sas_loginfo.dw.bus_type != 3 /*SAS*/)
		return;

	/* eat the loginfos associated with task aborts */
	if (ioc->ignore_loginfos && (log_info == 30050000 || log_info ==
	    0x31140000 || log_info == 0x31130000))
		return;

	switch (sas_loginfo.dw.originator) {
	case 0:
		originator_str = "IOP";
		break;
	case 1:
		originator_str = "PL";
		break;
	case 2:
		originator_str = "IR";
		break;
	}

	printk(MPT2SAS_WARN_FMT "log_info(0x%08x): originator(%s), "
	    "code(0x%02x), sub_code(0x%04x)\n", ioc->name, log_info,
	     originator_str, sas_loginfo.dw.code,
	     sas_loginfo.dw.subcode);
}

/**
 * mpt2sas_base_fault_info - verbose translation of firmware FAULT code
 * @ioc: pointer to scsi command object
 * @fault_code: fault code
 *
 * Return nothing.
 */
void
mpt2sas_base_fault_info(struct MPT2SAS_ADAPTER *ioc , u16 fault_code)
{
	printk(MPT2SAS_ERR_FMT "fault_state(0x%04x)!\n",
	    ioc->name, fault_code);
}

/**
 * _base_display_reply_info -
 * @ioc: pointer to scsi command object
 * @smid: system request message index
 * @VF_ID: virtual function id
 * @reply: reply message frame(lower 32bit addr)
 *
 * Return nothing.
 */
static void
_base_display_reply_info(struct MPT2SAS_ADAPTER *ioc, u16 smid, u8 VF_ID,
    u32 reply)
{
	MPI2DefaultReply_t *mpi_reply;
	u16 ioc_status;

	mpi_reply = mpt2sas_base_get_reply_virt_addr(ioc, reply);
	ioc_status = le16_to_cpu(mpi_reply->IOCStatus);
#ifdef CONFIG_SCSI_MPT2SAS_LOGGING
	if ((ioc_status & MPI2_IOCSTATUS_MASK) &&
	    (ioc->logging_level & MPT_DEBUG_REPLY)) {
		_base_sas_ioc_info(ioc , mpi_reply,
		   mpt2sas_base_get_msg_frame(ioc, smid));
	}
#endif
	if (ioc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE)
		_base_sas_log_info(ioc, le32_to_cpu(mpi_reply->IOCLogInfo));
}

/**
 * mpt2sas_base_done - base internal command completion routine
 * @ioc: pointer to scsi command object
 * @smid: system request message index
 * @VF_ID: virtual function id
 * @reply: reply message frame(lower 32bit addr)
 *
 * Return nothing.
 */
void
mpt2sas_base_done(struct MPT2SAS_ADAPTER *ioc, u16 smid, u8 VF_ID, u32 reply)
{
	MPI2DefaultReply_t *mpi_reply;

	mpi_reply = mpt2sas_base_get_reply_virt_addr(ioc, reply);
	if (mpi_reply && mpi_reply->Function == MPI2_FUNCTION_EVENT_ACK)
		return;

	if (ioc->base_cmds.status == MPT2_CMD_NOT_USED)
		return;

	ioc->base_cmds.status |= MPT2_CMD_COMPLETE;
	if (mpi_reply) {
		ioc->base_cmds.status |= MPT2_CMD_REPLY_VALID;
		memcpy(ioc->base_cmds.reply, mpi_reply, mpi_reply->MsgLength*4);
	}
	ioc->base_cmds.status &= ~MPT2_CMD_PENDING;
	complete(&ioc->base_cmds.done);
}

/**
 * _base_async_event - main callback handler for firmware asyn events
 * @ioc: pointer to scsi command object
 * @VF_ID: virtual function id
 * @reply: reply message frame(lower 32bit addr)
 *
 * Return nothing.
 */
static void
_base_async_event(struct MPT2SAS_ADAPTER *ioc, u8 VF_ID, u32 reply)
{
	Mpi2EventNotificationReply_t *mpi_reply;
	Mpi2EventAckRequest_t *ack_request;
	u16 smid;

	mpi_reply = mpt2sas_base_get_reply_virt_addr(ioc, reply);
	if (!mpi_reply)
		return;
	if (mpi_reply->Function != MPI2_FUNCTION_EVENT_NOTIFICATION)
		return;
#ifdef CONFIG_SCSI_MPT2SAS_LOGGING
	_base_display_event_data(ioc, mpi_reply);
#endif
	if (!(mpi_reply->AckRequired & MPI2_EVENT_NOTIFICATION_ACK_REQUIRED))
		goto out;
	smid = mpt2sas_base_get_smid(ioc, ioc->base_cb_idx);
	if (!smid) {
		printk(MPT2SAS_ERR_FMT "%s: failed obtaining a smid\n",
		    ioc->name, __func__);
		goto out;
	}

	ack_request = mpt2sas_base_get_msg_frame(ioc, smid);
	memset(ack_request, 0, sizeof(Mpi2EventAckRequest_t));
	ack_request->Function = MPI2_FUNCTION_EVENT_ACK;
	ack_request->Event = mpi_reply->Event;
	ack_request->EventContext = mpi_reply->EventContext;
	ack_request->VF_ID = VF_ID;
	mpt2sas_base_put_smid_default(ioc, smid, VF_ID);

 out:

	/* scsih callback handler */
	mpt2sas_scsih_event_callback(ioc, VF_ID, reply);

	/* ctl callback handler */
	mpt2sas_ctl_event_callback(ioc, VF_ID, reply);
}

/**
 * _base_mask_interrupts - disable interrupts
 * @ioc: pointer to scsi command object
 *
 * Disabling ResetIRQ, Reply and Doorbell Interrupts
 *
 * Return nothing.
 */
static void
_base_mask_interrupts(struct MPT2SAS_ADAPTER *ioc)
{
	u32 him_register;

	ioc->mask_interrupts = 1;
	him_register = readl(&ioc->chip->HostInterruptMask);
	him_register |= MPI2_HIM_DIM + MPI2_HIM_RIM + MPI2_HIM_RESET_IRQ_MASK;
	writel(him_register, &ioc->chip->HostInterruptMask);
	readl(&ioc->chip->HostInterruptMask);
}

/**
 * _base_unmask_interrupts - enable interrupts
 * @ioc: pointer to scsi command object
 *
 * Enabling only Reply Interrupts
 *
 * Return nothing.
 */
static void
_base_unmask_interrupts(struct MPT2SAS_ADAPTER *ioc)
{
	u32 him_register;

	writel(0, &ioc->chip->HostInterruptStatus);
	him_register = readl(&ioc->chip->HostInterruptMask);
	him_register &= ~MPI2_HIM_RIM;
	writel(him_register, &ioc->chip->HostInterruptMask);
	ioc->mask_interrupts = 0;
}

/**
 * _base_interrupt - MPT adapter (IOC) specific interrupt handler.
 * @irq: irq number (not used)
 * @bus_id: bus identifier cookie == pointer to MPT_ADAPTER structure
 * @r: pt_regs pointer (not used)
 *
 * Return IRQ_HANDLE if processed, else IRQ_NONE.
 */
static irqreturn_t
_base_interrupt(int irq, void *bus_id)
{
	union reply_descriptor {
		u64 word;
		struct {
			u32 low;
			u32 high;
		} u;
	};
	union reply_descriptor rd;
	u32 post_index, post_index_next, completed_cmds;
	u8 request_desript_type;
	u16 smid;
	u8 cb_idx;
	u32 reply;
	u8 VF_ID;
	int i;
	struct MPT2SAS_ADAPTER *ioc = bus_id;

	if (ioc->mask_interrupts)
		return IRQ_NONE;

	post_index = ioc->reply_post_host_index;
	request_desript_type = ioc->reply_post_free[post_index].
	    Default.ReplyFlags & MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
	if (request_desript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
		return IRQ_NONE;

	completed_cmds = 0;
	do {
		rd.word = ioc->reply_post_free[post_index].Words;
		if (rd.u.low == UINT_MAX || rd.u.high == UINT_MAX)
			goto out;
		reply = 0;
		cb_idx = 0xFF;
		smid = le16_to_cpu(ioc->reply_post_free[post_index].
		    Default.DescriptorTypeDependent1);
		VF_ID = ioc->reply_post_free[post_index].
		    Default.VF_ID;
		if (request_desript_type ==
		    MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY) {
			reply = le32_to_cpu(ioc->reply_post_free[post_index].
			    AddressReply.ReplyFrameAddress);
		} else if (request_desript_type ==
		    MPI2_RPY_DESCRIPT_FLAGS_TARGET_COMMAND_BUFFER)
			goto next;
		else if (request_desript_type ==
		    MPI2_RPY_DESCRIPT_FLAGS_TARGETASSIST_SUCCESS)
			goto next;
		if (smid)
			cb_idx = ioc->scsi_lookup[smid - 1].cb_idx;
		if (smid && cb_idx != 0xFF) {
			mpt_callbacks[cb_idx](ioc, smid, VF_ID, reply);
			if (reply)
				_base_display_reply_info(ioc, smid, VF_ID,
				    reply);
			mpt2sas_base_free_smid(ioc, smid);
		}
		if (!smid)
			_base_async_event(ioc, VF_ID, reply);

		/* reply free queue handling */
		if (reply) {
			ioc->reply_free_host_index =
			    (ioc->reply_free_host_index ==
			    (ioc->reply_free_queue_depth - 1)) ?
			    0 : ioc->reply_free_host_index + 1;
			ioc->reply_free[ioc->reply_free_host_index] =
			    cpu_to_le32(reply);
			writel(ioc->reply_free_host_index,
			    &ioc->chip->ReplyFreeHostIndex);
			wmb();
		}

 next:
		post_index_next = (post_index == (ioc->reply_post_queue_depth -
		    1)) ? 0 : post_index + 1;
		request_desript_type =
		    ioc->reply_post_free[post_index_next].Default.ReplyFlags
		    & MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
		completed_cmds++;
		if (request_desript_type == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
			goto out;
		post_index = post_index_next;
	} while (1);

 out:

	if (!completed_cmds)
		return IRQ_NONE;

	/* reply post descriptor handling */
	post_index_next = ioc->reply_post_host_index;
	for (i = 0 ; i < completed_cmds; i++) {
		post_index = post_index_next;
		/* poison the reply post descriptor */
		ioc->reply_post_free[post_index_next].Words = ULLONG_MAX;
		post_index_next = (post_index ==
		    (ioc->reply_post_queue_depth - 1))
		    ? 0 : post_index + 1;
	}
	ioc->reply_post_host_index = post_index_next;
	writel(post_index_next, &ioc->chip->ReplyPostHostIndex);
	wmb();
	return IRQ_HANDLED;
}

/**
 * mpt2sas_base_release_callback_handler - clear interupt callback handler
 * @cb_idx: callback index
 *
 * Return nothing.
 */
void
mpt2sas_base_release_callback_handler(u8 cb_idx)
{
	mpt_callbacks[cb_idx] = NULL;
}

/**
 * mpt2sas_base_register_callback_handler - obtain index for the interrupt callback handler
 * @cb_func: callback function
 *
 * Returns cb_func.
 */
u8
mpt2sas_base_register_callback_handler(MPT_CALLBACK cb_func)
{
	u8 cb_idx;

	for (cb_idx = MPT_MAX_CALLBACKS-1; cb_idx; cb_idx--)
		if (mpt_callbacks[cb_idx] == NULL)
			break;

	mpt_callbacks[cb_idx] = cb_func;
	return cb_idx;
}

/**
 * mpt2sas_base_initialize_callback_handler - initialize the interrupt callback handler
 *
 * Return nothing.
 */
void
mpt2sas_base_initialize_callback_handler(void)
{
	u8 cb_idx;

	for (cb_idx = 0; cb_idx < MPT_MAX_CALLBACKS; cb_idx++)
		mpt2sas_base_release_callback_handler(cb_idx);
}

/**
 * mpt2sas_base_build_zero_len_sge - build zero length sg entry
 * @ioc: per adapter object
 * @paddr: virtual address for SGE
 *
 * Create a zero length scatter gather entry to insure the IOCs hardware has
 * something to use if the target device goes brain dead and tries
 * to send data even when none is asked for.
 *
 * Return nothing.
 */
void
mpt2sas_base_build_zero_len_sge(struct MPT2SAS_ADAPTER *ioc, void *paddr)
{
	u32 flags_length = (u32)((MPI2_SGE_FLAGS_LAST_ELEMENT |
	    MPI2_SGE_FLAGS_END_OF_BUFFER | MPI2_SGE_FLAGS_END_OF_LIST |
	    MPI2_SGE_FLAGS_SIMPLE_ELEMENT) <<
	    MPI2_SGE_FLAGS_SHIFT);
	ioc->base_add_sg_single(paddr, flags_length, -1);
}

/**
 * _base_add_sg_single_32 - Place a simple 32 bit SGE at address pAddr.
 * @paddr: virtual address for SGE
 * @flags_length: SGE flags and data transfer length
 * @dma_addr: Physical address
 *
 * Return nothing.
 */
static void
_base_add_sg_single_32(void *paddr, u32 flags_length, dma_addr_t dma_addr)
{
	Mpi2SGESimple32_t *sgel = paddr;

	flags_length |= (MPI2_SGE_FLAGS_32_BIT_ADDRESSING |
	    MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT;
	sgel->FlagsLength = cpu_to_le32(flags_length);
	sgel->Address = cpu_to_le32(dma_addr);
}


/**
 * _base_add_sg_single_64 - Place a simple 64 bit SGE at address pAddr.
 * @paddr: virtual address for SGE
 * @flags_length: SGE flags and data transfer length
 * @dma_addr: Physical address
 *
 * Return nothing.
 */
static void
_base_add_sg_single_64(void *paddr, u32 flags_length, dma_addr_t dma_addr)
{
	Mpi2SGESimple64_t *sgel = paddr;

	flags_length |= (MPI2_SGE_FLAGS_64_BIT_ADDRESSING |
	    MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT;
	sgel->FlagsLength = cpu_to_le32(flags_length);
	sgel->Address = cpu_to_le64(dma_addr);
}

#define convert_to_kb(x) ((x) << (PAGE_SHIFT - 10))

/**
 * _base_config_dma_addressing - set dma addressing
 * @ioc: per adapter object
 * @pdev: PCI device struct
 *
 * Returns 0 for success, non-zero for failure.
 */
static int
_base_config_dma_addressing(struct MPT2SAS_ADAPTER *ioc, struct pci_dev *pdev)
{
	struct sysinfo s;
	char *desc = NULL;

	if (sizeof(dma_addr_t) > 4) {
		const uint64_t required_mask =
		    dma_get_required_mask(&pdev->dev);
		if ((required_mask > DMA_BIT_MASK(32)) && !pci_set_dma_mask(pdev,
		    DMA_BIT_MASK(64)) && !pci_set_consistent_dma_mask(pdev,
		    DMA_BIT_MASK(64))) {
			ioc->base_add_sg_single = &_base_add_sg_single_64;
			ioc->sge_size = sizeof(Mpi2SGESimple64_t);
			desc = "64";
			goto out;
		}
	}

	if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(32))
	    && !pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) {
		ioc->base_add_sg_single = &_base_add_sg_single_32;
		ioc->sge_size = sizeof(Mpi2SGESimple32_t);
		desc = "32";
	} else
		return -ENODEV;

 out:
	si_meminfo(&s);
	printk(MPT2SAS_INFO_FMT "%s BIT PCI BUS DMA ADDRESSING SUPPORTED, "
	    "total mem (%ld kB)\n", ioc->name, desc, convert_to_kb(s.totalram));

	return 0;
}

/**
 * _base_save_msix_table - backup msix vector table
 * @ioc: per adapter object
 *
 * This address an errata where diag reset clears out the table
 */
static void
_base_save_msix_table(struct MPT2SAS_ADAPTER *ioc)
{
	int i;

	if (!ioc->msix_enable || ioc->msix_table_backup == NULL)
		return;

	for (i = 0; i < ioc->msix_vector_count; i++)
		ioc->msix_table_backup[i] = ioc->msix_table[i];
}

/**
 * _base_restore_msix_table - this restores the msix vector table
 * @ioc: per adapter object
 *
 */
static void
_base_restore_msix_table(struct MPT2SAS_ADAPTER *ioc)
{
	int i;

	if (!ioc->msix_enable || ioc->msix_table_backup == NULL)
		return;

	for (i = 0; i < ioc->msix_vector_count; i++)
		ioc->msix_table[i] = ioc->msix_table_backup[i];
}

/**
 * _base_check_enable_msix - checks MSIX capabable.
 * @ioc: per adapter object
 *
 * Check to see if card is capable of MSIX, and set number
 * of avaliable msix vectors
 */
static int
_base_check_enable_msix(struct MPT2SAS_ADAPTER *ioc)
{
	int base;
	u16 message_control;
	u32 msix_table_offset;

	base = pci_find_capability(ioc->pdev, PCI_CAP_ID_MSIX);
	if (!base) {
		dfailprintk(ioc, printk(MPT2SAS_INFO_FMT "msix not "
		    "supported\n", ioc->name));
		return -EINVAL;
	}

	/* get msix vector count */
	pci_read_config_word(ioc->pdev, base + 2, &message_control);
	ioc->msix_vector_count = (message_control & 0x3FF) + 1;

	/* get msix table  */
	pci_read_config_dword(ioc->pdev, base + 4, &msix_table_offset);
	msix_table_offset &= 0xFFFFFFF8;
	ioc->msix_table = (u32 *)((void *)ioc->chip + msix_table_offset);

	dinitprintk(ioc, printk(MPT2SAS_INFO_FMT "msix is supported, "
	    "vector_count(%d), table_offset(0x%08x), table(%p)\n", ioc->name,
	    ioc->msix_vector_count, msix_table_offset, ioc->msix_table));
	return 0;
}

/**
 * _base_disable_msix - disables msix
 * @ioc: per adapter object
 *
 */
static void
_base_disable_msix(struct MPT2SAS_ADAPTER *ioc)
{
	if (ioc->msix_enable) {
		pci_disable_msix(ioc->pdev);
		kfree(ioc->msix_table_backup);
		ioc->msix_table_backup = NULL;
		ioc->msix_enable = 0;
	}
}

/**
 * _base_enable_msix - enables msix, failback to io_apic
 * @ioc: per adapter object
 *
 */
static int
_base_enable_msix(struct MPT2SAS_ADAPTER *ioc)
{
	struct msix_entry entries;
	int r;
	u8 try_msix = 0;

	if (msix_disable == -1 || msix_disable == 0)
		try_msix = 1;

	if (!try_msix)
		goto try_ioapic;

	if (_base_check_enable_msix(ioc) != 0)
		goto try_ioapic;

	ioc->msix_table_backup = kcalloc(ioc->msix_vector_count,
	    sizeof(u32), GFP_KERNEL);
	if (!ioc->msix_table_backup) {
		dfailprintk(ioc, printk(MPT2SAS_INFO_FMT "allocation for "
		    "msix_table_backup failed!!!\n", ioc->name));
		goto try_ioapic;
	}

	memset(&entries, 0, sizeof(struct msix_entry));
	r = pci_enable_msix(ioc->pdev, &entries, 1);
	if (r) {
		dfailprintk(ioc, printk(MPT2SAS_INFO_FMT "pci_enable_msix "
		    "failed (r=%d) !!!\n", ioc->name, r));
		goto try_ioapic;
	}

	r = request_irq(entries.vector, _base_interrupt, IRQF_SHARED,
	    ioc->name, ioc);
	if (r) {
		dfailprintk(ioc, printk(MPT2SAS_INFO_FMT "unable to allocate "
		    "interrupt %d !!!\n", ioc->name, entries.vector));
		pci_disable_msix(ioc->pdev);
		goto try_ioapic;
	}

	ioc->pci_irq = entries.vector;
	ioc->msix_enable = 1;
	return 0;

/* failback to io_apic interrupt routing */
 try_ioapic:

	r = request_irq(ioc->pdev->irq, _base_interrupt, IRQF_SHARED,
	    ioc->name, ioc);
	if (r) {
		printk(MPT2SAS_ERR_FMT "unable to allocate interrupt %d!\n",
		    ioc->name, ioc->pdev->irq);
		r = -EBUSY;
		goto out_fail;
	}

	ioc->pci_irq = ioc->pdev->irq;
	return 0;

 out_fail:
	return r;
}

/**
 * mpt2sas_base_map_resources - map in controller resources (io/irq/memap)
 * @ioc: per adapter object
 *
 * Returns 0 for success, non-zero for failure.
 */
int
mpt2sas_base_map_resources(struct MPT2SAS_ADAPTER *ioc)
{
	struct pci_dev *pdev = ioc->pdev;
	u32 memap_sz;
	u32 pio_sz;
	int i, r = 0;

	dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n",
	    ioc->name, __func__));

	ioc->bars = pci_select_bars(pdev, IORESOURCE_MEM);
	if (pci_enable_device_mem(pdev)) {
		printk(MPT2SAS_WARN_FMT "pci_enable_device_mem: "
		    "failed\n", ioc->name);
		return -ENODEV;
	}


	if (pci_request_selected_regions(pdev, ioc->bars,
	    MPT2SAS_DRIVER_NAME)) {
		printk(MPT2SAS_WARN_FMT "pci_request_selected_regions: "
		    "failed\n", ioc->name);
		r = -ENODEV;
		goto out_fail;
	}

	pci_set_master(pdev);

	if (_base_config_dma_addressing(ioc, pdev) != 0) {
		printk(MPT2SAS_WARN_FMT "no suitable DMA mask for %s\n",
		    ioc->name, pci_name(pdev));
		r = -ENODEV;
		goto out_fail;
	}

	for (i = 0, memap_sz = 0, pio_sz = 0 ; i < DEVICE_COUNT_RESOURCE; i++) {
		if (pci_resource_flags(pdev, i) & PCI_BASE_ADDRESS_SPACE_IO) {
			if (pio_sz)
				continue;
			ioc->pio_chip = pci_resource_start(pdev, i);
			pio_sz = pci_resource_len(pdev, i);
		} else {
			if (memap_sz)
				continue;
			ioc->chip_phys = pci_resource_start(pdev, i);
			memap_sz = pci_resource_len(pdev, i);
			ioc->chip = ioremap(ioc->chip_phys, memap_sz);
			if (ioc->chip == NULL) {
				printk(MPT2SAS_ERR_FMT "unable to map adapter "
				    "memory!\n", ioc->name);
				r = -EINVAL;
				goto out_fail;
			}
		}
	}

	pci_set_drvdata(pdev, ioc->shost);
	_base_mask_interrupts(ioc);
	r = _base_enable_msix(ioc);
	if (r)
		goto out_fail;

	printk(MPT2SAS_INFO_FMT "%s: IRQ %d\n",
	    ioc->name,  ((ioc->msix_enable) ? "PCI-MSI-X enabled" :
	    "IO-APIC enabled"), ioc->pci_irq);
	printk(MPT2SAS_INFO_FMT "iomem(0x%lx), mapped(0x%p), size(%d)\n",
	    ioc->name, ioc->chip_phys, ioc->chip, memap_sz);
	printk(MPT2SAS_INFO_FMT "ioport(0x%lx), size(%d)\n",
	    ioc->name, ioc->pio_chip, pio_sz);

	return 0;

 out_fail:
	if (ioc->chip_phys)
		iounmap(ioc->chip);
	ioc->chip_phys = 0;
	ioc->pci_irq = -1;
	pci_release_selected_regions(ioc->pdev, ioc->bars);
	pci_disable_device(pdev);
	pci_set_drvdata(pdev, NULL);
	return r;
}

/**
 * mpt2sas_base_get_msg_frame_dma - obtain request mf pointer phys addr
 * @ioc: per adapter object
 * @smid: system request message index(smid zero is invalid)
 *
 * Returns phys pointer to message frame.
 */
dma_addr_t
mpt2sas_base_get_msg_frame_dma(struct MPT2SAS_ADAPTER *ioc, u16 smid)
{
	return ioc->request_dma + (smid * ioc->request_sz);
}

/**
 * mpt2sas_base_get_msg_frame - obtain request mf pointer
 * @ioc: per adapter object
 * @smid: system request message index(smid zero is invalid)
 *
 * Returns virt pointer to message frame.
 */
void *
mpt2sas_base_get_msg_frame(struct MPT2SAS_ADAPTER *ioc, u16 smid)
{
	return (void *)(ioc->request + (smid * ioc->request_sz));
}

/**
 * mpt2sas_base_get_sense_buffer - obtain a sense buffer assigned to a mf request
 * @ioc: per adapter object
 * @smid: system request message index
 *
 * Returns virt pointer to sense buffer.
 */
void *
mpt2sas_base_get_sense_buffer(struct MPT2SAS_ADAPTER *ioc, u16 smid)
{
	return (void *)(ioc->sense + ((smid - 1) * SCSI_SENSE_BUFFERSIZE));
}

/**
 * mpt2sas_base_get_sense_buffer_dma - obtain a sense buffer assigned to a mf request
 * @ioc: per adapter object
 * @smid: system request message index
 *
 * Returns phys pointer to sense buffer.
 */
dma_addr_t
mpt2sas_base_get_sense_buffer_dma(struct MPT2SAS_ADAPTER *ioc, u16 smid)
{
	return ioc->sense_dma + ((smid - 1) * SCSI_SENSE_BUFFERSIZE);
}

/**
 * mpt2sas_base_get_reply_virt_addr - obtain reply frames virt address
 * @ioc: per adapter object
 * @phys_addr: lower 32 physical addr of the reply
 *
 * Converts 32bit lower physical addr into a virt address.
 */
void *
mpt2sas_base_get_reply_virt_addr(struct MPT2SAS_ADAPTER *ioc, u32 phys_addr)
{
	if (!phys_addr)
		return NULL;
	return ioc->reply + (phys_addr - (u32)ioc->reply_dma);
}

/**
 * mpt2sas_base_get_smid - obtain a free smid
 * @ioc: per adapter object
 * @cb_idx: callback index
 *
 * Returns smid (zero is invalid)
 */
u16
mpt2sas_base_get_smid(struct MPT2SAS_ADAPTER *ioc, u8 cb_idx)
{
	unsigned long flags;
	struct request_tracker *request;
	u16 smid;

	spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
	if (list_empty(&ioc->free_list)) {
		spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
		printk(MPT2SAS_ERR_FMT "%s: smid not available\n",
		    ioc->name, __func__);
		return 0;
	}

	request = list_entry(ioc->free_list.next,
	    struct request_tracker, tracker_list);
	request->cb_idx = cb_idx;
	smid = request->smid;
	list_del(&request->tracker_list);
	spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);
	return smid;
}


/**
 * mpt2sas_base_free_smid - put smid back on free_list
 * @ioc: per adapter object
 * @smid: system request message index
 *
 * Return nothing.
 */
void
mpt2sas_base_free_smid(struct MPT2SAS_ADAPTER *ioc, u16 smid)
{
	unsigned long flags;

	spin_lock_irqsave(&ioc->scsi_lookup_lock, flags);
	ioc->scsi_lookup[smid - 1].cb_idx = 0xFF;
	list_add_tail(&ioc->scsi_lookup[smid - 1].tracker_list,
	    &ioc->free_list);
	spin_unlock_irqrestore(&ioc->scsi_lookup_lock, flags);

	/*
	 * See _wait_for_commands_to_complete() call with regards to this code.
	 */
	if (ioc->shost_recovery && ioc->pending_io_count) {
		if (ioc->pending_io_count == 1)
			wake_up(&ioc->reset_wq);
		ioc->pending_io_count--;
	}
}

/**
 * _base_writeq - 64 bit write to MMIO
 * @ioc: per adapter object
 * @b: data payload
 * @addr: address in MMIO space
 * @writeq_lock: spin lock
 *
 * Glue for handling an atomic 64 bit word to MMIO. This special handling takes
 * care of 32 bit environment where its not quarenteed to send the entire word
 * in one transfer.
 */
#ifndef writeq
static inline void _base_writeq(__u64 b, volatile void __iomem *addr,
    spinlock_t *writeq_lock)
{
	unsigned long flags;
	__u64 data_out = cpu_to_le64(b);

	spin_lock_irqsave(writeq_lock, flags);
	writel((u32)(data_out), addr);
	writel((u32)(data_out >> 32), (addr + 4));
	spin_unlock_irqrestore(writeq_lock, flags);
}
#else
static inline void _base_writeq(__u64 b, volatile void __iomem *addr,
    spinlock_t *writeq_lock)
{
	writeq(cpu_to_le64(b), addr);
}
#endif

/**
 * mpt2sas_base_put_smid_scsi_io - send SCSI_IO request to firmware
 * @ioc: per adapter object
 * @smid: system request message index
 * @vf_id: virtual function id
 * @handle: device handle
 *
 * Return nothing.
 */
void
mpt2sas_base_put_smid_scsi_io(struct MPT2SAS_ADAPTER *ioc, u16 smid, u8 vf_id,
    u16 handle)
{
	Mpi2RequestDescriptorUnion_t descriptor;
	u64 *request = (u64 *)&descriptor;


	descriptor.SCSIIO.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
	descriptor.SCSIIO.VF_ID = vf_id;
	descriptor.SCSIIO.SMID = cpu_to_le16(smid);
	descriptor.SCSIIO.DevHandle = cpu_to_le16(handle);
	descriptor.SCSIIO.LMID = 0;
	_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
	    &ioc->scsi_lookup_lock);
}


/**
 * mpt2sas_base_put_smid_hi_priority - send Task Managment request to firmware
 * @ioc: per adapter object
 * @smid: system request message index
 * @vf_id: virtual function id
 *
 * Return nothing.
 */
void
mpt2sas_base_put_smid_hi_priority(struct MPT2SAS_ADAPTER *ioc, u16 smid,
    u8 vf_id)
{
	Mpi2RequestDescriptorUnion_t descriptor;
	u64 *request = (u64 *)&descriptor;

	descriptor.HighPriority.RequestFlags =
	    MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY;
	descriptor.HighPriority.VF_ID = vf_id;
	descriptor.HighPriority.SMID = cpu_to_le16(smid);
	descriptor.HighPriority.LMID = 0;
	descriptor.HighPriority.Reserved1 = 0;
	_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
	    &ioc->scsi_lookup_lock);
}

/**
 * mpt2sas_base_put_smid_default - Default, primarily used for config pages
 * @ioc: per adapter object
 * @smid: system request message index
 * @vf_id: virtual function id
 *
 * Return nothing.
 */
void
mpt2sas_base_put_smid_default(struct MPT2SAS_ADAPTER *ioc, u16 smid, u8 vf_id)
{
	Mpi2RequestDescriptorUnion_t descriptor;
	u64 *request = (u64 *)&descriptor;

	descriptor.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
	descriptor.Default.VF_ID = vf_id;
	descriptor.Default.SMID = cpu_to_le16(smid);
	descriptor.Default.LMID = 0;
	descriptor.Default.DescriptorTypeDependent = 0;
	_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
	    &ioc->scsi_lookup_lock);
}

/**
 * mpt2sas_base_put_smid_target_assist - send Target Assist/Status to firmware
 * @ioc: per adapter object
 * @smid: system request message index
 * @vf_id: virtual function id
 * @io_index: value used to track the IO
 *
 * Return nothing.
 */
void
mpt2sas_base_put_smid_target_assist(struct MPT2SAS_ADAPTER *ioc, u16 smid,
    u8 vf_id, u16 io_index)
{
	Mpi2RequestDescriptorUnion_t descriptor;
	u64 *request = (u64 *)&descriptor;

	descriptor.SCSITarget.RequestFlags =
	    MPI2_REQ_DESCRIPT_FLAGS_SCSI_TARGET;
	descriptor.SCSITarget.VF_ID = vf_id;
	descriptor.SCSITarget.SMID = cpu_to_le16(smid);
	descriptor.SCSITarget.LMID = 0;
	descriptor.SCSITarget.IoIndex = cpu_to_le16(io_index);
	_base_writeq(*request, &ioc->chip->RequestDescriptorPostLow,
	    &ioc->scsi_lookup_lock);
}

/**
 * _base_display_dell_branding - Disply branding string
 * @ioc: per adapter object
 *
 * Return nothing.
 */
static void
_base_display_dell_branding(struct MPT2SAS_ADAPTER *ioc)
{
	char dell_branding[MPT2SAS_DELL_BRANDING_SIZE];

	if (ioc->pdev->subsystem_vendor != PCI_VENDOR_ID_DELL)
		return;

	memset(dell_branding, 0, MPT2SAS_DELL_BRANDING_SIZE);
	switch (ioc->pdev->subsystem_device) {
	case MPT2SAS_DELL_6GBPS_SAS_HBA_SSDID:
		strncpy(dell_branding, MPT2SAS_DELL_6GBPS_SAS_HBA_BRANDING,
		    MPT2SAS_DELL_BRANDING_SIZE - 1);
		break;
	case MPT2SAS_DELL_PERC_H200_ADAPTER_SSDID:
		strncpy(dell_branding, MPT2SAS_DELL_PERC_H200_ADAPTER_BRANDING,
		    MPT2SAS_DELL_BRANDING_SIZE - 1);
		break;
	case MPT2SAS_DELL_PERC_H200_INTEGRATED_SSDID:
		strncpy(dell_branding,
		    MPT2SAS_DELL_PERC_H200_INTEGRATED_BRANDING,
		    MPT2SAS_DELL_BRANDING_SIZE - 1);
		break;
	case MPT2SAS_DELL_PERC_H200_MODULAR_SSDID:
		strncpy(dell_branding,
		    MPT2SAS_DELL_PERC_H200_MODULAR_BRANDING,
		    MPT2SAS_DELL_BRANDING_SIZE - 1);
		break;
	case MPT2SAS_DELL_PERC_H200_EMBEDDED_SSDID:
		strncpy(dell_branding,
		    MPT2SAS_DELL_PERC_H200_EMBEDDED_BRANDING,
		    MPT2SAS_DELL_BRANDING_SIZE - 1);
		break;
	case MPT2SAS_DELL_PERC_H200_SSDID:
		strncpy(dell_branding, MPT2SAS_DELL_PERC_H200_BRANDING,
		    MPT2SAS_DELL_BRANDING_SIZE - 1);
		break;
	case MPT2SAS_DELL_6GBPS_SAS_SSDID:
		strncpy(dell_branding, MPT2SAS_DELL_6GBPS_SAS_BRANDING,
		    MPT2SAS_DELL_BRANDING_SIZE - 1);
		break;
	default:
		sprintf(dell_branding, "0x%4X", ioc->pdev->subsystem_device);
		break;
	}

	printk(MPT2SAS_INFO_FMT "%s: Vendor(0x%04X), Device(0x%04X),"
	    " SSVID(0x%04X), SSDID(0x%04X)\n", ioc->name, dell_branding,
	    ioc->pdev->vendor, ioc->pdev->device, ioc->pdev->subsystem_vendor,
	    ioc->pdev->subsystem_device);
}

/**
 * _base_display_ioc_capabilities - Disply IOC's capabilities.
 * @ioc: per adapter object
 *
 * Return nothing.
 */
static void
_base_display_ioc_capabilities(struct MPT2SAS_ADAPTER *ioc)
{
	int i = 0;
	char desc[16];
	u8 revision;
	u32 iounit_pg1_flags;

	pci_read_config_byte(ioc->pdev, PCI_CLASS_REVISION, &revision);
	strncpy(desc, ioc->manu_pg0.ChipName, 16);
	printk(MPT2SAS_INFO_FMT "%s: FWVersion(%02d.%02d.%02d.%02d), "
	   "ChipRevision(0x%02x), BiosVersion(%02d.%02d.%02d.%02d)\n",
	    ioc->name, desc,
	   (ioc->facts.FWVersion.Word & 0xFF000000) >> 24,
	   (ioc->facts.FWVersion.Word & 0x00FF0000) >> 16,
	   (ioc->facts.FWVersion.Word & 0x0000FF00) >> 8,
	   ioc->facts.FWVersion.Word & 0x000000FF,
	   revision,
	   (ioc->bios_pg3.BiosVersion & 0xFF000000) >> 24,
	   (ioc->bios_pg3.BiosVersion & 0x00FF0000) >> 16,
	   (ioc->bios_pg3.BiosVersion & 0x0000FF00) >> 8,
	    ioc->bios_pg3.BiosVersion & 0x000000FF);

	printk(MPT2SAS_INFO_FMT "Protocol=(", ioc->name);

	if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_INITIATOR) {
		printk("Initiator");
		i++;
	}

	if (ioc->facts.ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_SCSI_TARGET) {
		printk("%sTarget", i ? "," : "");
		i++;
	}

	_base_display_dell_branding(ioc);

	i = 0;
	printk("), ");
	printk("Capabilities=(");

	if (ioc->facts.IOCCapabilities &
	    MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID) {
		printk("Raid");
		i++;
	}

	if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR) {
		printk("%sTLR", i ? "," : "");
		i++;
	}

	if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_MULTICAST) {
		printk("%sMulticast", i ? "," : "");
		i++;
	}

	if (ioc->facts.IOCCapabilities &
	    MPI2_IOCFACTS_CAPABILITY_BIDIRECTIONAL_TARGET) {
		printk("%sBIDI Target", i ? "," : "");
		i++;
	}

	if (ioc->facts.IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP) {
		printk("%sEEDP", i ? "," : "");
		i++;
	}

	if (ioc->facts.IOCCapabilities &
	    MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER) {
		printk("%sSnapshot Buffer", i ? "," : "");
		i++;
	}

	if (ioc->facts.IOCCapabilities &
	    MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER) {
		printk("%sDiag Trace Buffer", i ? "," : "");
		i++;
	}

	if (ioc->facts.IOCCapabilities &
	    MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING) {
		printk("%sTask Set Full", i ? "," : "");
		i++;
	}

	iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
	if (!(iounit_pg1_flags & MPI2_IOUNITPAGE1_NATIVE_COMMAND_Q_DISABLE)) {
		printk("%sNCQ", i ? "," : "");
		i++;
	}

	printk(")\n");
}

/**
 * _base_static_config_pages - static start of day config pages
 * @ioc: per adapter object
 *
 * Return nothing.
 */
static void
_base_static_config_pages(struct MPT2SAS_ADAPTER *ioc)
{
	Mpi2ConfigReply_t mpi_reply;
	u32 iounit_pg1_flags;

	mpt2sas_config_get_manufacturing_pg0(ioc, &mpi_reply, &ioc->manu_pg0);
	mpt2sas_config_get_bios_pg2(ioc, &mpi_reply, &ioc->bios_pg2);
	mpt2sas_config_get_bios_pg3(ioc, &mpi_reply, &ioc->bios_pg3);
	mpt2sas_config_get_ioc_pg8(ioc, &mpi_reply, &ioc->ioc_pg8);
	mpt2sas_config_get_iounit_pg0(ioc, &mpi_reply, &ioc->iounit_pg0);
	mpt2sas_config_get_iounit_pg1(ioc, &mpi_reply, &ioc->iounit_pg1);
	_base_display_ioc_capabilities(ioc);

	/*
	 * Enable task_set_full handling in iounit_pg1 when the
	 * facts capabilities indicate that its supported.
	 */
	iounit_pg1_flags = le32_to_cpu(ioc->iounit_pg1.Flags);
	if ((ioc->facts.IOCCapabilities &
	    MPI2_IOCFACTS_CAPABILITY_TASK_SET_FULL_HANDLING))
		iounit_pg1_flags &=
		    ~MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
	else
		iounit_pg1_flags |=
		    MPI2_IOUNITPAGE1_DISABLE_TASK_SET_FULL_HANDLING;
	ioc->iounit_pg1.Flags = cpu_to_le32(iounit_pg1_flags);
	mpt2sas_config_set_iounit_pg1(ioc, &mpi_reply, ioc->iounit_pg1);
}

/**
 * _base_release_memory_pools - release memory
 * @ioc: per adapter object
 *
 * Free memory allocated from _base_allocate_memory_pools.
 *
 * Return nothing.
 */
static void
_base_release_memory_pools(struct MPT2SAS_ADAPTER *ioc)
{
	dexitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
	    __func__));

	if (ioc->request) {
		pci_free_consistent(ioc->pdev, ioc->request_dma_sz,
		    ioc->request,  ioc->request_dma);
		dexitprintk(ioc, printk(MPT2SAS_INFO_FMT "request_pool(0x%p)"
		    ": free\n", ioc->name, ioc->request));
		ioc->request = NULL;
	}

	if (ioc->sense) {
		pci_pool_free(ioc->sense_dma_pool, ioc->sense, ioc->sense_dma);
		if (ioc->sense_dma_pool)
			pci_pool_destroy(ioc->sense_dma_pool);
		dexitprintk(ioc, printk(MPT2SAS_INFO_FMT "sense_pool(0x%p)"
		    ": free\n", ioc->name, ioc->sense));
		ioc->sense = NULL;
	}

	if (ioc->reply) {
		pci_pool_free(ioc->reply_dma_pool, ioc->reply, ioc->reply_dma);
		if (ioc->reply_dma_pool)
			pci_pool_destroy(ioc->reply_dma_pool);
		dexitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply_pool(0x%p)"
		     ": free\n", ioc->name, ioc->reply));
		ioc->reply = NULL;
	}

	if (ioc->reply_free) {
		pci_pool_free(ioc->reply_free_dma_pool, ioc->reply_free,
		    ioc->reply_free_dma);
		if (ioc->reply_free_dma_pool)
			pci_pool_destroy(ioc->reply_free_dma_pool);
		dexitprintk(ioc, printk(MPT2SAS_INFO_FMT "reply_free_pool"
		    "(0x%p): free\n", ioc->name, ioc->reply_free));
		ioc->reply_free = NULL;
	}

	if (ioc->reply_post_free) {
		pci_pool_free(ioc->reply_post_free_dma_pool,
		    ioc->reply_post_free, ioc->reply_post_free_dma);
		if (ioc->reply_post_free_dma_pool)
			pci_pool_destroy(ioc->reply_post_free_dma_pool);
		dexitprintk(ioc, printk(MPT2SAS_INFO_FMT
		    "reply_post_free_pool(0x%p): free\n", ioc->name,
		    ioc->reply_post_free));
		ioc->reply_post_free = NULL;
	}

	if (ioc->config_page) {
		dexitprintk(ioc, printk(MPT2SAS_INFO_FMT
		    "config_page(0x%p): free\n", ioc->name,
		    ioc->config_page));
		pci_free_consistent(ioc->pdev, ioc->config_page_sz,
		    ioc->config_page, ioc->config_page_dma);
	}

	kfree(ioc->scsi_lookup);
}


/**
 * _base_allocate_memory_pools - allocate start of day memory pools
 * @ioc: per adapter object
 * @sleep_flag: CAN_SLEEP or NO_SLEEP
 *
 * Returns 0 success, anything else error
 */
static int
_base_allocate_memory_pools(struct MPT2SAS_ADAPTER *ioc,  int sleep_flag)
{
	Mpi2IOCFactsReply_t *facts;
	u32 queue_size, queue_diff;
	u16 max_sge_elements;
	u16 num_of_reply_frames;
	u16 chains_needed_per_io;
	u32 sz, total_sz;
	u16 i;
	u32 retry_sz;
	u16 max_request_credit;

	dinitprintk(ioc, printk(MPT2SAS_DEBUG_FMT "%s\n", ioc->name,
	    __func__));

	retry_sz = 0;
	facts = &ioc->facts;

	/* command line tunables  for max sgl entries */
	if (max_sgl_entries != -1) {
		ioc->shost->sg_tablesize = (max_sgl_entries <
		    MPT2SAS_SG_DEPTH) ? max_sgl_entries :
		    MPT2SAS_SG_DEPTH;
	} else {
		ioc->shost->sg_tablesize = MPT2SAS_SG_DEPTH;
	}

	/* command line tunables  for max controller queue depth */
	if (max_queue_depth != -1) {
		max_request_credit = (max_queue_depth < facts->RequestCredit)
		    ? max_queue_depth : facts->RequestCredit;
	} else {
		max_request_credit = (facts->RequestCredit >
		    MPT2SAS_MAX_REQUEST_QUEUE) ? MPT2SAS_MAX_REQUEST_QUEUE :
		    facts->RequestCredit;
	}
	ioc->request_depth = max_request_credit;

	/* request frame size */
	ioc->request_sz = facts->IOCRequestFrameSize * 4;

	/* reply frame size */
	ioc->reply_sz = facts->ReplyFrameSize * 4;

 retry_allocation:
	total_sz = 0;
	/* calculate number of sg elements left over in the 1st frame */
	max_sge_elements = ioc->request_sz - ((sizeof(Mpi2SCSIIORequest_t) -
	    sizeof(Mpi2SGEIOUnion_t)) + ioc->sge_size);
	ioc->max_sges_in_main_message = max_sge_elements/ioc->sge_size;

	/* now do the same for a chain buffer */
	max_sge_elements = ioc->request_sz - ioc->sge_size;
	ioc->max_sges_in_chain_message = max_sge_elements/ioc->sge_size;

	ioc->chain_offset_value_for_main_message =
	    ((sizeof(Mpi2SCSIIORequest_t) - sizeof(Mpi2SGEIOUnion_t)) +
	     (ioc->max_sges_in_chain_message * ioc->sge_size)) / 4;

	/*
	 *  MPT2SAS_SG_DEPTH = CONFIG_FUSION_MAX_SGE
	 */
	chains_needed_per_io = ((ioc->shost->sg_tablesize -
	   ioc->max_sges_in_main_message)/ioc->max_sges_in_chain_message)
	    + 1;
	if (chains_needed_per_io > facts->MaxChainDepth) {
		chains_needed_per_io = facts->MaxChainDepth;
		ioc->shost->sg_tablesize = min_t(u16,
		ioc->max_sges_in_main_message + (ioc->max_sges_in_chain_message
		* chains_needed_per_io), ioc->shost->sg_tablesize);
	}
	ioc->chains_needed_per_io = chains_needed_per_io;

	/* reply free queue sizing - taking into account for events */
	num_of_reply_frames = ioc->request_depth + 32;

	/* number of replies frames can't be a multiple of 16 */
	/* decrease number of reply frames by 1 */
	if (!(num_of_reply_frames % 16))
		num_of_reply_frames--;

	/* calculate number of reply free queue entries
	 *  (must be multiple of 16)
	 */

	/* (we know reply_free_queue_depth is not a multiple of 16) */
	queue_size = num_of_reply_frames;
	queue_size += 16 - (queue_size % 16);
	ioc->reply_free_queue_depth = queue_size;

	/* reply descriptor post queue sizing */