]> err.no Git - linux-2.6/blob - drivers/scsi/libiscsi.c
[SCSI] libiscsi: modify libiscsi so it supports offloaded data paths
[linux-2.6] / drivers / scsi / libiscsi.c
1 /*
2  * iSCSI lib functions
3  *
4  * Copyright (C) 2006 Red Hat, Inc.  All rights reserved.
5  * Copyright (C) 2004 - 2006 Mike Christie
6  * Copyright (C) 2004 - 2005 Dmitry Yusupov
7  * Copyright (C) 2004 - 2005 Alex Aizman
8  * maintained by open-iscsi@googlegroups.com
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23  */
24 #include <linux/types.h>
25 #include <linux/kfifo.h>
26 #include <linux/delay.h>
27 #include <linux/log2.h>
28 #include <asm/unaligned.h>
29 #include <net/tcp.h>
30 #include <scsi/scsi_cmnd.h>
31 #include <scsi/scsi_device.h>
32 #include <scsi/scsi_eh.h>
33 #include <scsi/scsi_tcq.h>
34 #include <scsi/scsi_host.h>
35 #include <scsi/scsi.h>
36 #include <scsi/iscsi_proto.h>
37 #include <scsi/scsi_transport.h>
38 #include <scsi/scsi_transport_iscsi.h>
39 #include <scsi/libiscsi.h>
40
41 /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */
42 #define SNA32_CHECK 2147483648UL
43
44 static int iscsi_sna_lt(u32 n1, u32 n2)
45 {
46         return n1 != n2 && ((n1 < n2 && (n2 - n1 < SNA32_CHECK)) ||
47                             (n1 > n2 && (n2 - n1 < SNA32_CHECK)));
48 }
49
50 /* Serial Number Arithmetic, 32 bits, less than, RFC1982 */
51 static int iscsi_sna_lte(u32 n1, u32 n2)
52 {
53         return n1 == n2 || ((n1 < n2 && (n2 - n1 < SNA32_CHECK)) ||
54                             (n1 > n2 && (n2 - n1 < SNA32_CHECK)));
55 }
56
57 void
58 iscsi_update_cmdsn(struct iscsi_session *session, struct iscsi_nopin *hdr)
59 {
60         uint32_t max_cmdsn = be32_to_cpu(hdr->max_cmdsn);
61         uint32_t exp_cmdsn = be32_to_cpu(hdr->exp_cmdsn);
62
63         /*
64          * standard specifies this check for when to update expected and
65          * max sequence numbers
66          */
67         if (iscsi_sna_lt(max_cmdsn, exp_cmdsn - 1))
68                 return;
69
70         if (exp_cmdsn != session->exp_cmdsn &&
71             !iscsi_sna_lt(exp_cmdsn, session->exp_cmdsn))
72                 session->exp_cmdsn = exp_cmdsn;
73
74         if (max_cmdsn != session->max_cmdsn &&
75             !iscsi_sna_lt(max_cmdsn, session->max_cmdsn)) {
76                 session->max_cmdsn = max_cmdsn;
77                 /*
78                  * if the window closed with IO queued, then kick the
79                  * xmit thread
80                  */
81                 if (!list_empty(&session->leadconn->xmitqueue) ||
82                     !list_empty(&session->leadconn->mgmtqueue)) {
83                         if (!(session->tt->caps & CAP_DATA_PATH_OFFLOAD))
84                                 scsi_queue_work(session->host,
85                                                 &session->leadconn->xmitwork);
86                 }
87         }
88 }
89 EXPORT_SYMBOL_GPL(iscsi_update_cmdsn);
90
91 void iscsi_prep_unsolicit_data_pdu(struct iscsi_cmd_task *ctask,
92                                    struct iscsi_data *hdr)
93 {
94         struct iscsi_conn *conn = ctask->conn;
95
96         memset(hdr, 0, sizeof(struct iscsi_data));
97         hdr->ttt = cpu_to_be32(ISCSI_RESERVED_TAG);
98         hdr->datasn = cpu_to_be32(ctask->unsol_datasn);
99         ctask->unsol_datasn++;
100         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
101         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
102
103         hdr->itt = ctask->hdr->itt;
104         hdr->exp_statsn = cpu_to_be32(conn->exp_statsn);
105         hdr->offset = cpu_to_be32(ctask->unsol_offset);
106
107         if (ctask->unsol_count > conn->max_xmit_dlength) {
108                 hton24(hdr->dlength, conn->max_xmit_dlength);
109                 ctask->data_count = conn->max_xmit_dlength;
110                 ctask->unsol_offset += ctask->data_count;
111                 hdr->flags = 0;
112         } else {
113                 hton24(hdr->dlength, ctask->unsol_count);
114                 ctask->data_count = ctask->unsol_count;
115                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
116         }
117 }
118 EXPORT_SYMBOL_GPL(iscsi_prep_unsolicit_data_pdu);
119
120 static int iscsi_add_hdr(struct iscsi_cmd_task *ctask, unsigned len)
121 {
122         unsigned exp_len = ctask->hdr_len + len;
123
124         if (exp_len > ctask->hdr_max) {
125                 WARN_ON(1);
126                 return -EINVAL;
127         }
128
129         WARN_ON(len & (ISCSI_PAD_LEN - 1)); /* caller must pad the AHS */
130         ctask->hdr_len = exp_len;
131         return 0;
132 }
133
134 /*
135  * make an extended cdb AHS
136  */
137 static int iscsi_prep_ecdb_ahs(struct iscsi_cmd_task *ctask)
138 {
139         struct scsi_cmnd *cmd = ctask->sc;
140         unsigned rlen, pad_len;
141         unsigned short ahslength;
142         struct iscsi_ecdb_ahdr *ecdb_ahdr;
143         int rc;
144
145         ecdb_ahdr = iscsi_next_hdr(ctask);
146         rlen = cmd->cmd_len - ISCSI_CDB_SIZE;
147
148         BUG_ON(rlen > sizeof(ecdb_ahdr->ecdb));
149         ahslength = rlen + sizeof(ecdb_ahdr->reserved);
150
151         pad_len = iscsi_padding(rlen);
152
153         rc = iscsi_add_hdr(ctask, sizeof(ecdb_ahdr->ahslength) +
154                            sizeof(ecdb_ahdr->ahstype) + ahslength + pad_len);
155         if (rc)
156                 return rc;
157
158         if (pad_len)
159                 memset(&ecdb_ahdr->ecdb[rlen], 0, pad_len);
160
161         ecdb_ahdr->ahslength = cpu_to_be16(ahslength);
162         ecdb_ahdr->ahstype = ISCSI_AHSTYPE_CDB;
163         ecdb_ahdr->reserved = 0;
164         memcpy(ecdb_ahdr->ecdb, cmd->cmnd + ISCSI_CDB_SIZE, rlen);
165
166         debug_scsi("iscsi_prep_ecdb_ahs: varlen_cdb_len %d "
167                    "rlen %d pad_len %d ahs_length %d iscsi_headers_size %u\n",
168                    cmd->cmd_len, rlen, pad_len, ahslength, ctask->hdr_len);
169
170         return 0;
171 }
172
173 static int iscsi_prep_bidi_ahs(struct iscsi_cmd_task *ctask)
174 {
175         struct scsi_cmnd *sc = ctask->sc;
176         struct iscsi_rlength_ahdr *rlen_ahdr;
177         int rc;
178
179         rlen_ahdr = iscsi_next_hdr(ctask);
180         rc = iscsi_add_hdr(ctask, sizeof(*rlen_ahdr));
181         if (rc)
182                 return rc;
183
184         rlen_ahdr->ahslength =
185                 cpu_to_be16(sizeof(rlen_ahdr->read_length) +
186                                                   sizeof(rlen_ahdr->reserved));
187         rlen_ahdr->ahstype = ISCSI_AHSTYPE_RLENGTH;
188         rlen_ahdr->reserved = 0;
189         rlen_ahdr->read_length = cpu_to_be32(scsi_in(sc)->length);
190
191         debug_scsi("bidi-in rlen_ahdr->read_length(%d) "
192                    "rlen_ahdr->ahslength(%d)\n",
193                    be32_to_cpu(rlen_ahdr->read_length),
194                    be16_to_cpu(rlen_ahdr->ahslength));
195         return 0;
196 }
197
198 /**
199  * iscsi_prep_scsi_cmd_pdu - prep iscsi scsi cmd pdu
200  * @ctask: iscsi cmd task
201  *
202  * Prep basic iSCSI PDU fields for a scsi cmd pdu. The LLD should set
203  * fields like dlength or final based on how much data it sends
204  */
205 static int iscsi_prep_scsi_cmd_pdu(struct iscsi_cmd_task *ctask)
206 {
207         struct iscsi_conn *conn = ctask->conn;
208         struct iscsi_session *session = conn->session;
209         struct iscsi_cmd *hdr = ctask->hdr;
210         struct scsi_cmnd *sc = ctask->sc;
211         unsigned hdrlength, cmd_len;
212         int rc;
213
214         ctask->hdr_len = 0;
215         rc = iscsi_add_hdr(ctask, sizeof(*hdr));
216         if (rc)
217                 return rc;
218         hdr->opcode = ISCSI_OP_SCSI_CMD;
219         hdr->flags = ISCSI_ATTR_SIMPLE;
220         int_to_scsilun(sc->device->lun, (struct scsi_lun *)hdr->lun);
221         hdr->itt = build_itt(ctask->itt, session->age);
222         hdr->cmdsn = cpu_to_be32(session->cmdsn);
223         session->cmdsn++;
224         hdr->exp_statsn = cpu_to_be32(conn->exp_statsn);
225         cmd_len = sc->cmd_len;
226         if (cmd_len < ISCSI_CDB_SIZE)
227                 memset(&hdr->cdb[cmd_len], 0, ISCSI_CDB_SIZE - cmd_len);
228         else if (cmd_len > ISCSI_CDB_SIZE) {
229                 rc = iscsi_prep_ecdb_ahs(ctask);
230                 if (rc)
231                         return rc;
232                 cmd_len = ISCSI_CDB_SIZE;
233         }
234         memcpy(hdr->cdb, sc->cmnd, cmd_len);
235
236         ctask->imm_count = 0;
237         if (scsi_bidi_cmnd(sc)) {
238                 hdr->flags |= ISCSI_FLAG_CMD_READ;
239                 rc = iscsi_prep_bidi_ahs(ctask);
240                 if (rc)
241                         return rc;
242         }
243         if (sc->sc_data_direction == DMA_TO_DEVICE) {
244                 unsigned out_len = scsi_out(sc)->length;
245                 hdr->data_length = cpu_to_be32(out_len);
246                 hdr->flags |= ISCSI_FLAG_CMD_WRITE;
247                 /*
248                  * Write counters:
249                  *
250                  *      imm_count       bytes to be sent right after
251                  *                      SCSI PDU Header
252                  *
253                  *      unsol_count     bytes(as Data-Out) to be sent
254                  *                      without R2T ack right after
255                  *                      immediate data
256                  *
257                  *      r2t_data_count  bytes to be sent via R2T ack's
258                  *
259                  *      pad_count       bytes to be sent as zero-padding
260                  */
261                 ctask->unsol_count = 0;
262                 ctask->unsol_offset = 0;
263                 ctask->unsol_datasn = 0;
264
265                 if (session->imm_data_en) {
266                         if (out_len >= session->first_burst)
267                                 ctask->imm_count = min(session->first_burst,
268                                                         conn->max_xmit_dlength);
269                         else
270                                 ctask->imm_count = min(out_len,
271                                                         conn->max_xmit_dlength);
272                         hton24(hdr->dlength, ctask->imm_count);
273                 } else
274                         zero_data(hdr->dlength);
275
276                 if (!session->initial_r2t_en) {
277                         ctask->unsol_count = min(session->first_burst, out_len)
278                                                              - ctask->imm_count;
279                         ctask->unsol_offset = ctask->imm_count;
280                 }
281
282                 if (!ctask->unsol_count)
283                         /* No unsolicit Data-Out's */
284                         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
285         } else {
286                 hdr->flags |= ISCSI_FLAG_CMD_FINAL;
287                 zero_data(hdr->dlength);
288                 hdr->data_length = cpu_to_be32(scsi_in(sc)->length);
289
290                 if (sc->sc_data_direction == DMA_FROM_DEVICE)
291                         hdr->flags |= ISCSI_FLAG_CMD_READ;
292         }
293
294         /* calculate size of additional header segments (AHSs) */
295         hdrlength = ctask->hdr_len - sizeof(*hdr);
296
297         WARN_ON(hdrlength & (ISCSI_PAD_LEN-1));
298         hdrlength /= ISCSI_PAD_LEN;
299
300         WARN_ON(hdrlength >= 256);
301         hdr->hlength = hdrlength & 0xFF;
302
303         if (conn->session->tt->init_cmd_task &&
304             conn->session->tt->init_cmd_task(ctask))
305                 return -EIO;
306
307         ctask->state = ISCSI_TASK_RUNNING;
308         list_move_tail(&ctask->running, &conn->run_list);
309
310         conn->scsicmd_pdus_cnt++;
311         debug_scsi("iscsi prep [%s cid %d sc %p cdb 0x%x itt 0x%x "
312                 "len %d bidi_len %d cmdsn %d win %d]\n",
313                 scsi_bidi_cmnd(sc) ? "bidirectional" :
314                      sc->sc_data_direction == DMA_TO_DEVICE ? "write" : "read",
315                 conn->id, sc, sc->cmnd[0], ctask->itt,
316                 scsi_bufflen(sc), scsi_bidi_cmnd(sc) ? scsi_in(sc)->length : 0,
317                 session->cmdsn, session->max_cmdsn - session->exp_cmdsn + 1);
318         return 0;
319 }
320
321 /**
322  * iscsi_complete_command - return command back to scsi-ml
323  * @ctask: iscsi cmd task
324  *
325  * Must be called with session lock.
326  * This function returns the scsi command to scsi-ml and returns
327  * the cmd task to the pool of available cmd tasks.
328  */
329 static void iscsi_complete_command(struct iscsi_cmd_task *ctask)
330 {
331         struct iscsi_conn *conn = ctask->conn;
332         struct iscsi_session *session = conn->session;
333         struct scsi_cmnd *sc = ctask->sc;
334
335         ctask->state = ISCSI_TASK_COMPLETED;
336         ctask->sc = NULL;
337         /* SCSI eh reuses commands to verify us */
338         sc->SCp.ptr = NULL;
339         if (conn->ctask == ctask)
340                 conn->ctask = NULL;
341         list_del_init(&ctask->running);
342         __kfifo_put(session->cmdpool.queue, (void*)&ctask, sizeof(void*));
343
344         if (sc->scsi_done)
345                 sc->scsi_done(sc);
346 }
347
348 static void __iscsi_get_ctask(struct iscsi_cmd_task *ctask)
349 {
350         atomic_inc(&ctask->refcount);
351 }
352
353 static void __iscsi_put_ctask(struct iscsi_cmd_task *ctask)
354 {
355         if (atomic_dec_and_test(&ctask->refcount))
356                 iscsi_complete_command(ctask);
357 }
358
359 /*
360  * session lock must be held
361  */
362 static void fail_command(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
363                          int err)
364 {
365         struct scsi_cmnd *sc;
366
367         sc = ctask->sc;
368         if (!sc)
369                 return;
370
371         if (ctask->state == ISCSI_TASK_PENDING)
372                 /*
373                  * cmd never made it to the xmit thread, so we should not count
374                  * the cmd in the sequencing
375                  */
376                 conn->session->queued_cmdsn--;
377         else
378                 conn->session->tt->cleanup_cmd_task(conn, ctask);
379
380         sc->result = err;
381         if (!scsi_bidi_cmnd(sc))
382                 scsi_set_resid(sc, scsi_bufflen(sc));
383         else {
384                 scsi_out(sc)->resid = scsi_out(sc)->length;
385                 scsi_in(sc)->resid = scsi_in(sc)->length;
386         }
387         if (conn->ctask == ctask)
388                 conn->ctask = NULL;
389         /* release ref from queuecommand */
390         __iscsi_put_ctask(ctask);
391 }
392
393 /**
394  * iscsi_free_mgmt_task - return mgmt task back to pool
395  * @conn: iscsi connection
396  * @mtask: mtask
397  *
398  * Must be called with session lock.
399  */
400 void iscsi_free_mgmt_task(struct iscsi_conn *conn,
401                           struct iscsi_mgmt_task *mtask)
402 {
403         list_del_init(&mtask->running);
404         if (conn->login_mtask == mtask)
405                 return;
406
407         if (conn->ping_mtask == mtask)
408                 conn->ping_mtask = NULL;
409         __kfifo_put(conn->session->mgmtpool.queue,
410                     (void*)&mtask, sizeof(void*));
411 }
412 EXPORT_SYMBOL_GPL(iscsi_free_mgmt_task);
413
414 static int iscsi_prep_mtask(struct iscsi_conn *conn,
415                             struct iscsi_mgmt_task *mtask)
416 {
417         struct iscsi_session *session = conn->session;
418         struct iscsi_hdr *hdr = mtask->hdr;
419         struct iscsi_nopout *nop = (struct iscsi_nopout *)hdr;
420
421         if (conn->session->state == ISCSI_STATE_LOGGING_OUT)
422                 return -ENOTCONN;
423
424         if (hdr->opcode != (ISCSI_OP_LOGIN | ISCSI_OP_IMMEDIATE) &&
425             hdr->opcode != (ISCSI_OP_TEXT | ISCSI_OP_IMMEDIATE))
426                 nop->exp_statsn = cpu_to_be32(conn->exp_statsn);
427         /*
428          * pre-format CmdSN for outgoing PDU.
429          */
430         nop->cmdsn = cpu_to_be32(session->cmdsn);
431         if (hdr->itt != RESERVED_ITT) {
432                 hdr->itt = build_itt(mtask->itt, session->age);
433                 /*
434                  * TODO: We always use immediate, so we never hit this.
435                  * If we start to send tmfs or nops as non-immediate then
436                  * we should start checking the cmdsn numbers for mgmt tasks.
437                  */
438                 if (conn->c_stage == ISCSI_CONN_STARTED &&
439                     !(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
440                         session->queued_cmdsn++;
441                         session->cmdsn++;
442                 }
443         }
444
445         if (session->tt->init_mgmt_task)
446                 session->tt->init_mgmt_task(conn, mtask);
447
448         if ((hdr->opcode & ISCSI_OPCODE_MASK) == ISCSI_OP_LOGOUT)
449                 session->state = ISCSI_STATE_LOGGING_OUT;
450
451         list_move_tail(&mtask->running, &conn->mgmt_run_list);
452         debug_scsi("mgmtpdu [op 0x%x hdr->itt 0x%x datalen %d]\n",
453                    hdr->opcode & ISCSI_OPCODE_MASK, hdr->itt,
454                    mtask->data_count);
455         return 0;
456 }
457
458 static struct iscsi_mgmt_task *
459 __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
460                       char *data, uint32_t data_size)
461 {
462         struct iscsi_session *session = conn->session;
463         struct iscsi_mgmt_task *mtask;
464
465         if (session->state == ISCSI_STATE_TERMINATE)
466                 return NULL;
467
468         if (hdr->opcode == (ISCSI_OP_LOGIN | ISCSI_OP_IMMEDIATE) ||
469             hdr->opcode == (ISCSI_OP_TEXT | ISCSI_OP_IMMEDIATE))
470                 /*
471                  * Login and Text are sent serially, in
472                  * request-followed-by-response sequence.
473                  * Same mtask can be used. Same ITT must be used.
474                  * Note that login_mtask is preallocated at conn_create().
475                  */
476                 mtask = conn->login_mtask;
477         else {
478                 BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE);
479                 BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED);
480
481                 if (!__kfifo_get(session->mgmtpool.queue,
482                                  (void*)&mtask, sizeof(void*)))
483                         return NULL;
484
485                 if ((hdr->opcode == (ISCSI_OP_NOOP_OUT | ISCSI_OP_IMMEDIATE)) &&
486                      hdr->ttt == RESERVED_ITT) {
487                         conn->ping_mtask = mtask;
488                         conn->last_ping = jiffies;
489                 }
490         }
491
492         if (data_size) {
493                 memcpy(mtask->data, data, data_size);
494                 mtask->data_count = data_size;
495         } else
496                 mtask->data_count = 0;
497
498         memcpy(mtask->hdr, hdr, sizeof(struct iscsi_hdr));
499         INIT_LIST_HEAD(&mtask->running);
500         list_add_tail(&mtask->running, &conn->mgmtqueue);
501
502         if (session->tt->caps & CAP_DATA_PATH_OFFLOAD) {
503                 if (iscsi_prep_mtask(conn, mtask)) {
504                         iscsi_free_mgmt_task(conn, mtask);
505                         return NULL;
506                 }
507
508                 if (session->tt->xmit_mgmt_task(conn, mtask))
509                         mtask = NULL;
510
511         } else
512                 scsi_queue_work(conn->session->host, &conn->xmitwork);
513
514         return mtask;
515 }
516
517 int iscsi_conn_send_pdu(struct iscsi_cls_conn *cls_conn, struct iscsi_hdr *hdr,
518                         char *data, uint32_t data_size)
519 {
520         struct iscsi_conn *conn = cls_conn->dd_data;
521         struct iscsi_session *session = conn->session;
522         int err = 0;
523
524         spin_lock_bh(&session->lock);
525         if (!__iscsi_conn_send_pdu(conn, hdr, data, data_size))
526                 err = -EPERM;
527         spin_unlock_bh(&session->lock);
528         return err;
529 }
530 EXPORT_SYMBOL_GPL(iscsi_conn_send_pdu);
531
532 /**
533  * iscsi_cmd_rsp - SCSI Command Response processing
534  * @conn: iscsi connection
535  * @hdr: iscsi header
536  * @ctask: scsi command task
537  * @data: cmd data buffer
538  * @datalen: len of buffer
539  *
540  * iscsi_cmd_rsp sets up the scsi_cmnd fields based on the PDU and
541  * then completes the command and task.
542  **/
543 static void iscsi_scsi_cmd_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
544                                struct iscsi_cmd_task *ctask, char *data,
545                                int datalen)
546 {
547         struct iscsi_cmd_rsp *rhdr = (struct iscsi_cmd_rsp *)hdr;
548         struct iscsi_session *session = conn->session;
549         struct scsi_cmnd *sc = ctask->sc;
550
551         iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr);
552         conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
553
554         sc->result = (DID_OK << 16) | rhdr->cmd_status;
555
556         if (rhdr->response != ISCSI_STATUS_CMD_COMPLETED) {
557                 sc->result = DID_ERROR << 16;
558                 goto out;
559         }
560
561         if (rhdr->cmd_status == SAM_STAT_CHECK_CONDITION) {
562                 uint16_t senselen;
563
564                 if (datalen < 2) {
565 invalid_datalen:
566                         iscsi_conn_printk(KERN_ERR,  conn,
567                                          "Got CHECK_CONDITION but invalid data "
568                                          "buffer size of %d\n", datalen);
569                         sc->result = DID_BAD_TARGET << 16;
570                         goto out;
571                 }
572
573                 senselen = be16_to_cpu(get_unaligned((__be16 *) data));
574                 if (datalen < senselen)
575                         goto invalid_datalen;
576
577                 memcpy(sc->sense_buffer, data + 2,
578                        min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE));
579                 debug_scsi("copied %d bytes of sense\n",
580                            min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE));
581         }
582
583         if (rhdr->flags & (ISCSI_FLAG_CMD_BIDI_UNDERFLOW |
584                            ISCSI_FLAG_CMD_BIDI_OVERFLOW)) {
585                 int res_count = be32_to_cpu(rhdr->bi_residual_count);
586
587                 if (scsi_bidi_cmnd(sc) && res_count > 0 &&
588                                 (rhdr->flags & ISCSI_FLAG_CMD_BIDI_OVERFLOW ||
589                                  res_count <= scsi_in(sc)->length))
590                         scsi_in(sc)->resid = res_count;
591                 else
592                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
593         }
594
595         if (rhdr->flags & (ISCSI_FLAG_CMD_UNDERFLOW |
596                            ISCSI_FLAG_CMD_OVERFLOW)) {
597                 int res_count = be32_to_cpu(rhdr->residual_count);
598
599                 if (res_count > 0 &&
600                     (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW ||
601                      res_count <= scsi_bufflen(sc)))
602                         /* write side for bidi or uni-io set_resid */
603                         scsi_set_resid(sc, res_count);
604                 else
605                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
606         }
607 out:
608         debug_scsi("done [sc %lx res %d itt 0x%x]\n",
609                    (long)sc, sc->result, ctask->itt);
610         conn->scsirsp_pdus_cnt++;
611
612         __iscsi_put_ctask(ctask);
613 }
614
615 static void iscsi_tmf_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr)
616 {
617         struct iscsi_tm_rsp *tmf = (struct iscsi_tm_rsp *)hdr;
618
619         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
620         conn->tmfrsp_pdus_cnt++;
621
622         if (conn->tmf_state != TMF_QUEUED)
623                 return;
624
625         if (tmf->response == ISCSI_TMF_RSP_COMPLETE)
626                 conn->tmf_state = TMF_SUCCESS;
627         else if (tmf->response == ISCSI_TMF_RSP_NO_TASK)
628                 conn->tmf_state = TMF_NOT_FOUND;
629         else
630                 conn->tmf_state = TMF_FAILED;
631         wake_up(&conn->ehwait);
632 }
633
634 static void iscsi_send_nopout(struct iscsi_conn *conn, struct iscsi_nopin *rhdr)
635 {
636         struct iscsi_nopout hdr;
637         struct iscsi_mgmt_task *mtask;
638
639         if (!rhdr && conn->ping_mtask)
640                 return;
641
642         memset(&hdr, 0, sizeof(struct iscsi_nopout));
643         hdr.opcode = ISCSI_OP_NOOP_OUT | ISCSI_OP_IMMEDIATE;
644         hdr.flags = ISCSI_FLAG_CMD_FINAL;
645
646         if (rhdr) {
647                 memcpy(hdr.lun, rhdr->lun, 8);
648                 hdr.ttt = rhdr->ttt;
649                 hdr.itt = RESERVED_ITT;
650         } else
651                 hdr.ttt = RESERVED_ITT;
652
653         mtask = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)&hdr, NULL, 0);
654         if (!mtask)
655                 iscsi_conn_printk(KERN_ERR, conn, "Could not send nopout\n");
656 }
657
658 static int iscsi_handle_reject(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
659                                char *data, int datalen)
660 {
661         struct iscsi_reject *reject = (struct iscsi_reject *)hdr;
662         struct iscsi_hdr rejected_pdu;
663         uint32_t itt;
664
665         conn->exp_statsn = be32_to_cpu(reject->statsn) + 1;
666
667         if (reject->reason == ISCSI_REASON_DATA_DIGEST_ERROR) {
668                 if (ntoh24(reject->dlength) > datalen)
669                         return ISCSI_ERR_PROTO;
670
671                 if (ntoh24(reject->dlength) >= sizeof(struct iscsi_hdr)) {
672                         memcpy(&rejected_pdu, data, sizeof(struct iscsi_hdr));
673                         itt = get_itt(rejected_pdu.itt);
674                         iscsi_conn_printk(KERN_ERR, conn,
675                                           "itt 0x%x had pdu (op 0x%x) rejected "
676                                           "due to DataDigest error.\n", itt,
677                                           rejected_pdu.opcode);
678                 }
679         }
680         return 0;
681 }
682
683 /**
684  * __iscsi_complete_pdu - complete pdu
685  * @conn: iscsi conn
686  * @hdr: iscsi header
687  * @data: data buffer
688  * @datalen: len of data buffer
689  *
690  * Completes pdu processing by freeing any resources allocated at
691  * queuecommand or send generic. session lock must be held and verify
692  * itt must have been called.
693  */
694 static int __iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
695                                 char *data, int datalen)
696 {
697         struct iscsi_session *session = conn->session;
698         int opcode = hdr->opcode & ISCSI_OPCODE_MASK, rc = 0;
699         struct iscsi_cmd_task *ctask;
700         struct iscsi_mgmt_task *mtask;
701         uint32_t itt;
702
703         conn->last_recv = jiffies;
704         rc = iscsi_verify_itt(conn, hdr->itt);
705         if (rc)
706                 return rc;
707
708         if (hdr->itt != RESERVED_ITT)
709                 itt = get_itt(hdr->itt);
710         else
711                 itt = ~0U;
712
713         if (itt < session->cmds_max) {
714                 ctask = session->cmds[itt];
715
716                 debug_scsi("cmdrsp [op 0x%x cid %d itt 0x%x len %d]\n",
717                            opcode, conn->id, ctask->itt, datalen);
718
719                 switch(opcode) {
720                 case ISCSI_OP_SCSI_CMD_RSP:
721                         BUG_ON((void*)ctask != ctask->sc->SCp.ptr);
722                         iscsi_scsi_cmd_rsp(conn, hdr, ctask, data,
723                                            datalen);
724                         break;
725                 case ISCSI_OP_SCSI_DATA_IN:
726                         BUG_ON((void*)ctask != ctask->sc->SCp.ptr);
727                         if (hdr->flags & ISCSI_FLAG_DATA_STATUS) {
728                                 conn->scsirsp_pdus_cnt++;
729                                 __iscsi_put_ctask(ctask);
730                         }
731                         break;
732                 case ISCSI_OP_R2T:
733                         /* LLD handles this for now */
734                         break;
735                 default:
736                         rc = ISCSI_ERR_BAD_OPCODE;
737                         break;
738                 }
739         } else if (itt >= ISCSI_MGMT_ITT_OFFSET &&
740                    itt < ISCSI_MGMT_ITT_OFFSET + session->mgmtpool_max) {
741                 mtask = session->mgmt_cmds[itt - ISCSI_MGMT_ITT_OFFSET];
742
743                 debug_scsi("immrsp [op 0x%x cid %d itt 0x%x len %d]\n",
744                            opcode, conn->id, mtask->itt, datalen);
745
746                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
747                 switch(opcode) {
748                 case ISCSI_OP_LOGOUT_RSP:
749                         if (datalen) {
750                                 rc = ISCSI_ERR_PROTO;
751                                 break;
752                         }
753                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
754                         /* fall through */
755                 case ISCSI_OP_LOGIN_RSP:
756                 case ISCSI_OP_TEXT_RSP:
757                         /*
758                          * login related PDU's exp_statsn is handled in
759                          * userspace
760                          */
761                         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
762                                 rc = ISCSI_ERR_CONN_FAILED;
763                         iscsi_free_mgmt_task(conn, mtask);
764                         break;
765                 case ISCSI_OP_SCSI_TMFUNC_RSP:
766                         if (datalen) {
767                                 rc = ISCSI_ERR_PROTO;
768                                 break;
769                         }
770
771                         iscsi_tmf_rsp(conn, hdr);
772                         iscsi_free_mgmt_task(conn, mtask);
773                         break;
774                 case ISCSI_OP_NOOP_IN:
775                         if (hdr->ttt != cpu_to_be32(ISCSI_RESERVED_TAG) ||
776                             datalen) {
777                                 rc = ISCSI_ERR_PROTO;
778                                 break;
779                         }
780                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
781
782                         if (conn->ping_mtask != mtask) {
783                                 /*
784                                  * If this is not in response to one of our
785                                  * nops then it must be from userspace.
786                                  */
787                                 if (iscsi_recv_pdu(conn->cls_conn, hdr, data,
788                                                    datalen))
789                                         rc = ISCSI_ERR_CONN_FAILED;
790                         } else
791                                 mod_timer(&conn->transport_timer,
792                                           jiffies + conn->recv_timeout);
793                         iscsi_free_mgmt_task(conn, mtask);
794                         break;
795                 default:
796                         rc = ISCSI_ERR_BAD_OPCODE;
797                         break;
798                 }
799         } else if (itt == ~0U) {
800                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
801
802                 switch(opcode) {
803                 case ISCSI_OP_NOOP_IN:
804                         if (datalen) {
805                                 rc = ISCSI_ERR_PROTO;
806                                 break;
807                         }
808
809                         if (hdr->ttt == cpu_to_be32(ISCSI_RESERVED_TAG))
810                                 break;
811
812                         iscsi_send_nopout(conn, (struct iscsi_nopin*)hdr);
813                         break;
814                 case ISCSI_OP_REJECT:
815                         rc = iscsi_handle_reject(conn, hdr, data, datalen);
816                         break;
817                 case ISCSI_OP_ASYNC_EVENT:
818                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
819                         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
820                                 rc = ISCSI_ERR_CONN_FAILED;
821                         break;
822                 default:
823                         rc = ISCSI_ERR_BAD_OPCODE;
824                         break;
825                 }
826         } else
827                 rc = ISCSI_ERR_BAD_ITT;
828
829         return rc;
830 }
831
832 int iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
833                        char *data, int datalen)
834 {
835         int rc;
836
837         spin_lock(&conn->session->lock);
838         rc = __iscsi_complete_pdu(conn, hdr, data, datalen);
839         spin_unlock(&conn->session->lock);
840         return rc;
841 }
842 EXPORT_SYMBOL_GPL(iscsi_complete_pdu);
843
844 int iscsi_verify_itt(struct iscsi_conn *conn, itt_t itt)
845 {
846         struct iscsi_session *session = conn->session;
847         struct iscsi_cmd_task *ctask;
848
849         if (itt == RESERVED_ITT)
850                 return 0;
851
852         if (((__force u32)itt & ISCSI_AGE_MASK) !=
853             (session->age << ISCSI_AGE_SHIFT)) {
854                 iscsi_conn_printk(KERN_ERR, conn,
855                                   "received itt %x expected session age (%x)\n",
856                                   (__force u32)itt,
857                                   session->age & ISCSI_AGE_MASK);
858                 return ISCSI_ERR_BAD_ITT;
859         }
860
861         if (itt < session->cmds_max) {
862                 ctask = session->cmds[itt];
863
864                 if (!ctask->sc) {
865                         iscsi_conn_printk(KERN_INFO, conn, "dropping ctask "
866                                           "with itt 0x%x\n", ctask->itt);
867                         /* force drop */
868                         return ISCSI_ERR_NO_SCSI_CMD;
869                 }
870
871                 if (ctask->sc->SCp.phase != session->age) {
872                         iscsi_conn_printk(KERN_ERR, conn,
873                                           "iscsi: ctask's session age %d, "
874                                           "expected %d\n", ctask->sc->SCp.phase,
875                                           session->age);
876                         return ISCSI_ERR_SESSION_FAILED;
877                 }
878         }
879
880         return 0;
881 }
882 EXPORT_SYMBOL_GPL(iscsi_verify_itt);
883
884 struct iscsi_cmd_task *
885 iscsi_itt_to_ctask(struct iscsi_conn *conn, itt_t itt)
886 {
887         struct iscsi_session *session = conn->session;
888         struct iscsi_cmd_task *ctask;
889         uint32_t i;
890
891         if (iscsi_verify_itt(conn, itt))
892                 return NULL;
893
894         if (itt == RESERVED_ITT)
895                 return NULL;
896
897         i = get_itt(itt);
898         if (i >= session->cmds_max)
899                 return NULL;
900
901         ctask = session->cmds[i];
902         if (!ctask->sc)
903                 return NULL;
904
905         if (ctask->sc->SCp.phase != session->age)
906                 return NULL;
907
908         return ctask;
909 }
910 EXPORT_SYMBOL_GPL(iscsi_itt_to_ctask);
911
912 void iscsi_conn_failure(struct iscsi_conn *conn, enum iscsi_err err)
913 {
914         struct iscsi_session *session = conn->session;
915         unsigned long flags;
916
917         spin_lock_irqsave(&session->lock, flags);
918         if (session->state == ISCSI_STATE_FAILED) {
919                 spin_unlock_irqrestore(&session->lock, flags);
920                 return;
921         }
922
923         if (conn->stop_stage == 0)
924                 session->state = ISCSI_STATE_FAILED;
925         spin_unlock_irqrestore(&session->lock, flags);
926         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
927         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
928         iscsi_conn_error(conn->cls_conn, err);
929 }
930 EXPORT_SYMBOL_GPL(iscsi_conn_failure);
931
932 static int iscsi_xmit_mtask(struct iscsi_conn *conn)
933 {
934         int rc;
935
936         spin_unlock_bh(&conn->session->lock);
937         rc = conn->session->tt->xmit_mgmt_task(conn, conn->mtask);
938         spin_lock_bh(&conn->session->lock);
939         if (rc)
940                 return rc;
941         /* done with this in-progress mtask */
942         conn->mtask = NULL;
943         return 0;
944 }
945
946 static int iscsi_check_cmdsn_window_closed(struct iscsi_conn *conn)
947 {
948         struct iscsi_session *session = conn->session;
949
950         /*
951          * Check for iSCSI window and take care of CmdSN wrap-around
952          */
953         if (!iscsi_sna_lte(session->queued_cmdsn, session->max_cmdsn)) {
954                 debug_scsi("iSCSI CmdSN closed. ExpCmdSn %u MaxCmdSN %u "
955                            "CmdSN %u/%u\n", session->exp_cmdsn,
956                            session->max_cmdsn, session->cmdsn,
957                            session->queued_cmdsn);
958                 return -ENOSPC;
959         }
960         return 0;
961 }
962
963 static int iscsi_xmit_ctask(struct iscsi_conn *conn)
964 {
965         struct iscsi_cmd_task *ctask = conn->ctask;
966         int rc;
967
968         __iscsi_get_ctask(ctask);
969         spin_unlock_bh(&conn->session->lock);
970         rc = conn->session->tt->xmit_cmd_task(conn, ctask);
971         spin_lock_bh(&conn->session->lock);
972         __iscsi_put_ctask(ctask);
973         if (!rc)
974                 /* done with this ctask */
975                 conn->ctask = NULL;
976         return rc;
977 }
978
979 /**
980  * iscsi_requeue_ctask - requeue ctask to run from session workqueue
981  * @ctask: ctask to requeue
982  *
983  * LLDs that need to run a ctask from the session workqueue should call
984  * this. The session lock must be held. This should only be called
985  * by software drivers.
986  */
987 void iscsi_requeue_ctask(struct iscsi_cmd_task *ctask)
988 {
989         struct iscsi_conn *conn = ctask->conn;
990
991         list_move_tail(&ctask->running, &conn->requeue);
992         scsi_queue_work(conn->session->host, &conn->xmitwork);
993 }
994 EXPORT_SYMBOL_GPL(iscsi_requeue_ctask);
995
996 /**
997  * iscsi_data_xmit - xmit any command into the scheduled connection
998  * @conn: iscsi connection
999  *
1000  * Notes:
1001  *      The function can return -EAGAIN in which case the caller must
1002  *      re-schedule it again later or recover. '0' return code means
1003  *      successful xmit.
1004  **/
1005 static int iscsi_data_xmit(struct iscsi_conn *conn)
1006 {
1007         int rc = 0;
1008
1009         spin_lock_bh(&conn->session->lock);
1010         if (unlikely(conn->suspend_tx)) {
1011                 debug_scsi("conn %d Tx suspended!\n", conn->id);
1012                 spin_unlock_bh(&conn->session->lock);
1013                 return -ENODATA;
1014         }
1015
1016         if (conn->ctask) {
1017                 rc = iscsi_xmit_ctask(conn);
1018                 if (rc)
1019                         goto again;
1020         }
1021
1022         if (conn->mtask) {
1023                 rc = iscsi_xmit_mtask(conn);
1024                 if (rc)
1025                         goto again;
1026         }
1027
1028         /*
1029          * process mgmt pdus like nops before commands since we should
1030          * only have one nop-out as a ping from us and targets should not
1031          * overflow us with nop-ins
1032          */
1033 check_mgmt:
1034         while (!list_empty(&conn->mgmtqueue)) {
1035                 conn->mtask = list_entry(conn->mgmtqueue.next,
1036                                          struct iscsi_mgmt_task, running);
1037                 if (iscsi_prep_mtask(conn, conn->mtask)) {
1038                         iscsi_free_mgmt_task(conn, conn->mtask);
1039                         conn->mtask = NULL;
1040                         continue;
1041                 }
1042                 rc = iscsi_xmit_mtask(conn);
1043                 if (rc)
1044                         goto again;
1045         }
1046
1047         /* process pending command queue */
1048         while (!list_empty(&conn->xmitqueue)) {
1049                 if (conn->tmf_state == TMF_QUEUED)
1050                         break;
1051
1052                 conn->ctask = list_entry(conn->xmitqueue.next,
1053                                          struct iscsi_cmd_task, running);
1054                 if (conn->session->state == ISCSI_STATE_LOGGING_OUT) {
1055                         fail_command(conn, conn->ctask, DID_IMM_RETRY << 16);
1056                         continue;
1057                 }
1058                 if (iscsi_prep_scsi_cmd_pdu(conn->ctask)) {
1059                         fail_command(conn, conn->ctask, DID_ABORT << 16);
1060                         continue;
1061                 }
1062                 rc = iscsi_xmit_ctask(conn);
1063                 if (rc)
1064                         goto again;
1065                 /*
1066                  * we could continuously get new ctask requests so
1067                  * we need to check the mgmt queue for nops that need to
1068                  * be sent to aviod starvation
1069                  */
1070                 if (!list_empty(&conn->mgmtqueue))
1071                         goto check_mgmt;
1072         }
1073
1074         while (!list_empty(&conn->requeue)) {
1075                 if (conn->session->fast_abort && conn->tmf_state != TMF_INITIAL)
1076                         break;
1077
1078                 /*
1079                  * we always do fastlogout - conn stop code will clean up.
1080                  */
1081                 if (conn->session->state == ISCSI_STATE_LOGGING_OUT)
1082                         break;
1083
1084                 conn->ctask = list_entry(conn->requeue.next,
1085                                          struct iscsi_cmd_task, running);
1086                 conn->ctask->state = ISCSI_TASK_RUNNING;
1087                 list_move_tail(conn->requeue.next, &conn->run_list);
1088                 rc = iscsi_xmit_ctask(conn);
1089                 if (rc)
1090                         goto again;
1091                 if (!list_empty(&conn->mgmtqueue))
1092                         goto check_mgmt;
1093         }
1094         spin_unlock_bh(&conn->session->lock);
1095         return -ENODATA;
1096
1097 again:
1098         if (unlikely(conn->suspend_tx))
1099                 rc = -ENODATA;
1100         spin_unlock_bh(&conn->session->lock);
1101         return rc;
1102 }
1103
1104 static void iscsi_xmitworker(struct work_struct *work)
1105 {
1106         struct iscsi_conn *conn =
1107                 container_of(work, struct iscsi_conn, xmitwork);
1108         int rc;
1109         /*
1110          * serialize Xmit worker on a per-connection basis.
1111          */
1112         do {
1113                 rc = iscsi_data_xmit(conn);
1114         } while (rc >= 0 || rc == -EAGAIN);
1115 }
1116
1117 enum {
1118         FAILURE_BAD_HOST = 1,
1119         FAILURE_SESSION_FAILED,
1120         FAILURE_SESSION_FREED,
1121         FAILURE_WINDOW_CLOSED,
1122         FAILURE_OOM,
1123         FAILURE_SESSION_TERMINATE,
1124         FAILURE_SESSION_IN_RECOVERY,
1125         FAILURE_SESSION_RECOVERY_TIMEOUT,
1126         FAILURE_SESSION_LOGGING_OUT,
1127         FAILURE_SESSION_NOT_READY,
1128 };
1129
1130 int iscsi_queuecommand(struct scsi_cmnd *sc, void (*done)(struct scsi_cmnd *))
1131 {
1132         struct iscsi_cls_session *cls_session;
1133         struct Scsi_Host *host;
1134         int reason = 0;
1135         struct iscsi_session *session;
1136         struct iscsi_conn *conn;
1137         struct iscsi_cmd_task *ctask = NULL;
1138
1139         sc->scsi_done = done;
1140         sc->result = 0;
1141         sc->SCp.ptr = NULL;
1142
1143         host = sc->device->host;
1144         spin_unlock(host->host_lock);
1145
1146         cls_session = starget_to_session(scsi_target(sc->device));
1147         session = cls_session->dd_data;
1148         spin_lock(&session->lock);
1149
1150         reason = iscsi_session_chkready(cls_session);
1151         if (reason) {
1152                 sc->result = reason;
1153                 goto fault;
1154         }
1155
1156         /*
1157          * ISCSI_STATE_FAILED is a temp. state. The recovery
1158          * code will decide what is best to do with command queued
1159          * during this time
1160          */
1161         if (session->state != ISCSI_STATE_LOGGED_IN &&
1162             session->state != ISCSI_STATE_FAILED) {
1163                 /*
1164                  * to handle the race between when we set the recovery state
1165                  * and block the session we requeue here (commands could
1166                  * be entering our queuecommand while a block is starting
1167                  * up because the block code is not locked)
1168                  */
1169                 switch (session->state) {
1170                 case ISCSI_STATE_IN_RECOVERY:
1171                         reason = FAILURE_SESSION_IN_RECOVERY;
1172                         sc->result = DID_IMM_RETRY << 16;
1173                         break;
1174                 case ISCSI_STATE_LOGGING_OUT:
1175                         reason = FAILURE_SESSION_LOGGING_OUT;
1176                         sc->result = DID_IMM_RETRY << 16;
1177                         break;
1178                 case ISCSI_STATE_RECOVERY_FAILED:
1179                         reason = FAILURE_SESSION_RECOVERY_TIMEOUT;
1180                         sc->result = DID_NO_CONNECT << 16;
1181                         break;
1182                 case ISCSI_STATE_TERMINATE:
1183                         reason = FAILURE_SESSION_TERMINATE;
1184                         sc->result = DID_NO_CONNECT << 16;
1185                         break;
1186                 default:
1187                         reason = FAILURE_SESSION_FREED;
1188                         sc->result = DID_NO_CONNECT << 16;
1189                 }
1190                 goto fault;
1191         }
1192
1193         conn = session->leadconn;
1194         if (!conn) {
1195                 reason = FAILURE_SESSION_FREED;
1196                 sc->result = DID_NO_CONNECT << 16;
1197                 goto fault;
1198         }
1199
1200         if (iscsi_check_cmdsn_window_closed(conn)) {
1201                 reason = FAILURE_WINDOW_CLOSED;
1202                 goto reject;
1203         }
1204
1205         if (!__kfifo_get(session->cmdpool.queue, (void*)&ctask,
1206                          sizeof(void*))) {
1207                 reason = FAILURE_OOM;
1208                 goto reject;
1209         }
1210         sc->SCp.phase = session->age;
1211         sc->SCp.ptr = (char *)ctask;
1212
1213         atomic_set(&ctask->refcount, 1);
1214         ctask->state = ISCSI_TASK_PENDING;
1215         ctask->conn = conn;
1216         ctask->sc = sc;
1217         INIT_LIST_HEAD(&ctask->running);
1218         list_add_tail(&ctask->running, &conn->xmitqueue);
1219
1220         if (session->tt->caps & CAP_DATA_PATH_OFFLOAD) {
1221                 if (iscsi_prep_scsi_cmd_pdu(ctask)) {
1222                         sc->result = DID_ABORT << 16;
1223                         sc->scsi_done = NULL;
1224                         iscsi_complete_command(ctask);
1225                         goto fault;
1226                 }
1227                 if (session->tt->xmit_cmd_task(conn, ctask)) {
1228                         sc->scsi_done = NULL;
1229                         iscsi_complete_command(ctask);
1230                         reason = FAILURE_SESSION_NOT_READY;
1231                         goto reject;
1232                 }
1233         } else
1234                 scsi_queue_work(session->host, &conn->xmitwork);
1235
1236         session->queued_cmdsn++;
1237         spin_unlock(&session->lock);
1238         spin_lock(host->host_lock);
1239         return 0;
1240
1241 reject:
1242         spin_unlock(&session->lock);
1243         debug_scsi("cmd 0x%x rejected (%d)\n", sc->cmnd[0], reason);
1244         spin_lock(host->host_lock);
1245         return SCSI_MLQUEUE_HOST_BUSY;
1246
1247 fault:
1248         spin_unlock(&session->lock);
1249         debug_scsi("iscsi: cmd 0x%x is not queued (%d)\n", sc->cmnd[0], reason);
1250         if (!scsi_bidi_cmnd(sc))
1251                 scsi_set_resid(sc, scsi_bufflen(sc));
1252         else {
1253                 scsi_out(sc)->resid = scsi_out(sc)->length;
1254                 scsi_in(sc)->resid = scsi_in(sc)->length;
1255         }
1256         done(sc);
1257         spin_lock(host->host_lock);
1258         return 0;
1259 }
1260 EXPORT_SYMBOL_GPL(iscsi_queuecommand);
1261
1262 int iscsi_change_queue_depth(struct scsi_device *sdev, int depth)
1263 {
1264         if (depth > ISCSI_MAX_CMD_PER_LUN)
1265                 depth = ISCSI_MAX_CMD_PER_LUN;
1266         scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth);
1267         return sdev->queue_depth;
1268 }
1269 EXPORT_SYMBOL_GPL(iscsi_change_queue_depth);
1270
1271 void iscsi_session_recovery_timedout(struct iscsi_cls_session *cls_session)
1272 {
1273         struct iscsi_session *session = cls_session->dd_data;
1274
1275         spin_lock_bh(&session->lock);
1276         if (session->state != ISCSI_STATE_LOGGED_IN) {
1277                 session->state = ISCSI_STATE_RECOVERY_FAILED;
1278                 if (session->leadconn)
1279                         wake_up(&session->leadconn->ehwait);
1280         }
1281         spin_unlock_bh(&session->lock);
1282 }
1283 EXPORT_SYMBOL_GPL(iscsi_session_recovery_timedout);
1284
1285 int iscsi_eh_host_reset(struct scsi_cmnd *sc)
1286 {
1287         struct iscsi_cls_session *cls_session;
1288         struct iscsi_session *session;
1289         struct iscsi_conn *conn;
1290
1291         cls_session = starget_to_session(scsi_target(sc->device));
1292         session = cls_session->dd_data;
1293         conn = session->leadconn;
1294
1295         mutex_lock(&session->eh_mutex);
1296         spin_lock_bh(&session->lock);
1297         if (session->state == ISCSI_STATE_TERMINATE) {
1298 failed:
1299                 debug_scsi("failing host reset: session terminated "
1300                            "[CID %d age %d]\n", conn->id, session->age);
1301                 spin_unlock_bh(&session->lock);
1302                 mutex_unlock(&session->eh_mutex);
1303                 return FAILED;
1304         }
1305
1306         spin_unlock_bh(&session->lock);
1307         mutex_unlock(&session->eh_mutex);
1308         /*
1309          * we drop the lock here but the leadconn cannot be destoyed while
1310          * we are in the scsi eh
1311          */
1312         iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1313
1314         debug_scsi("iscsi_eh_host_reset wait for relogin\n");
1315         wait_event_interruptible(conn->ehwait,
1316                                  session->state == ISCSI_STATE_TERMINATE ||
1317                                  session->state == ISCSI_STATE_LOGGED_IN ||
1318                                  session->state == ISCSI_STATE_RECOVERY_FAILED);
1319         if (signal_pending(current))
1320                 flush_signals(current);
1321
1322         mutex_lock(&session->eh_mutex);
1323         spin_lock_bh(&session->lock);
1324         if (session->state == ISCSI_STATE_LOGGED_IN)
1325                 iscsi_session_printk(KERN_INFO, session,
1326                                      "host reset succeeded\n");
1327         else
1328                 goto failed;
1329         spin_unlock_bh(&session->lock);
1330         mutex_unlock(&session->eh_mutex);
1331         return SUCCESS;
1332 }
1333 EXPORT_SYMBOL_GPL(iscsi_eh_host_reset);
1334
1335 static void iscsi_tmf_timedout(unsigned long data)
1336 {
1337         struct iscsi_conn *conn = (struct iscsi_conn *)data;
1338         struct iscsi_session *session = conn->session;
1339
1340         spin_lock(&session->lock);
1341         if (conn->tmf_state == TMF_QUEUED) {
1342                 conn->tmf_state = TMF_TIMEDOUT;
1343                 debug_scsi("tmf timedout\n");
1344                 /* unblock eh_abort() */
1345                 wake_up(&conn->ehwait);
1346         }
1347         spin_unlock(&session->lock);
1348 }
1349
1350 static int iscsi_exec_task_mgmt_fn(struct iscsi_conn *conn,
1351                                    struct iscsi_tm *hdr, int age,
1352                                    int timeout)
1353 {
1354         struct iscsi_session *session = conn->session;
1355         struct iscsi_mgmt_task *mtask;
1356
1357         mtask = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)hdr,
1358                                       NULL, 0);
1359         if (!mtask) {
1360                 spin_unlock_bh(&session->lock);
1361                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1362                 spin_lock_bh(&session->lock);
1363                 debug_scsi("tmf exec failure\n");
1364                 return -EPERM;
1365         }
1366         conn->tmfcmd_pdus_cnt++;
1367         conn->tmf_timer.expires = timeout * HZ + jiffies;
1368         conn->tmf_timer.function = iscsi_tmf_timedout;
1369         conn->tmf_timer.data = (unsigned long)conn;
1370         add_timer(&conn->tmf_timer);
1371         debug_scsi("tmf set timeout\n");
1372
1373         spin_unlock_bh(&session->lock);
1374         mutex_unlock(&session->eh_mutex);
1375
1376         /*
1377          * block eh thread until:
1378          *
1379          * 1) tmf response
1380          * 2) tmf timeout
1381          * 3) session is terminated or restarted or userspace has
1382          * given up on recovery
1383          */
1384         wait_event_interruptible(conn->ehwait, age != session->age ||
1385                                  session->state != ISCSI_STATE_LOGGED_IN ||
1386                                  conn->tmf_state != TMF_QUEUED);
1387         if (signal_pending(current))
1388                 flush_signals(current);
1389         del_timer_sync(&conn->tmf_timer);
1390
1391         mutex_lock(&session->eh_mutex);
1392         spin_lock_bh(&session->lock);
1393         /* if the session drops it will clean up the mtask */
1394         if (age != session->age ||
1395             session->state != ISCSI_STATE_LOGGED_IN)
1396                 return -ENOTCONN;
1397         return 0;
1398 }
1399
1400 /*
1401  * Fail commands. session lock held and recv side suspended and xmit
1402  * thread flushed
1403  */
1404 static void fail_all_commands(struct iscsi_conn *conn, unsigned lun,
1405                               int error)
1406 {
1407         struct iscsi_cmd_task *ctask, *tmp;
1408
1409         if (conn->ctask && (conn->ctask->sc->device->lun == lun || lun == -1))
1410                 conn->ctask = NULL;
1411
1412         /* flush pending */
1413         list_for_each_entry_safe(ctask, tmp, &conn->xmitqueue, running) {
1414                 if (lun == ctask->sc->device->lun || lun == -1) {
1415                         debug_scsi("failing pending sc %p itt 0x%x\n",
1416                                    ctask->sc, ctask->itt);
1417                         fail_command(conn, ctask, error << 16);
1418                 }
1419         }
1420
1421         list_for_each_entry_safe(ctask, tmp, &conn->requeue, running) {
1422                 if (lun == ctask->sc->device->lun || lun == -1) {
1423                         debug_scsi("failing requeued sc %p itt 0x%x\n",
1424                                    ctask->sc, ctask->itt);
1425                         fail_command(conn, ctask, error << 16);
1426                 }
1427         }
1428
1429         /* fail all other running */
1430         list_for_each_entry_safe(ctask, tmp, &conn->run_list, running) {
1431                 if (lun == ctask->sc->device->lun || lun == -1) {
1432                         debug_scsi("failing in progress sc %p itt 0x%x\n",
1433                                    ctask->sc, ctask->itt);
1434                         fail_command(conn, ctask, DID_BUS_BUSY << 16);
1435                 }
1436         }
1437 }
1438
1439 void iscsi_suspend_tx(struct iscsi_conn *conn)
1440 {
1441         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1442         if (!(conn->session->tt->caps & CAP_DATA_PATH_OFFLOAD))
1443                 scsi_flush_work(conn->session->host);
1444 }
1445 EXPORT_SYMBOL_GPL(iscsi_suspend_tx);
1446
1447 static void iscsi_start_tx(struct iscsi_conn *conn)
1448 {
1449         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1450         if (!(conn->session->tt->caps & CAP_DATA_PATH_OFFLOAD))
1451                 scsi_queue_work(conn->session->host, &conn->xmitwork);
1452 }
1453
1454 static enum scsi_eh_timer_return iscsi_eh_cmd_timed_out(struct scsi_cmnd *scmd)
1455 {
1456         struct iscsi_cls_session *cls_session;
1457         struct iscsi_session *session;
1458         struct iscsi_conn *conn;
1459         enum scsi_eh_timer_return rc = EH_NOT_HANDLED;
1460
1461         cls_session = starget_to_session(scsi_target(scmd->device));
1462         session = cls_session->dd_data;
1463
1464         debug_scsi("scsi cmd %p timedout\n", scmd);
1465
1466         spin_lock(&session->lock);
1467         if (session->state != ISCSI_STATE_LOGGED_IN) {
1468                 /*
1469                  * We are probably in the middle of iscsi recovery so let
1470                  * that complete and handle the error.
1471                  */
1472                 rc = EH_RESET_TIMER;
1473                 goto done;
1474         }
1475
1476         conn = session->leadconn;
1477         if (!conn) {
1478                 /* In the middle of shuting down */
1479                 rc = EH_RESET_TIMER;
1480                 goto done;
1481         }
1482
1483         if (!conn->recv_timeout && !conn->ping_timeout)
1484                 goto done;
1485         /*
1486          * if the ping timedout then we are in the middle of cleaning up
1487          * and can let the iscsi eh handle it
1488          */
1489         if (time_before_eq(conn->last_recv + (conn->recv_timeout * HZ) +
1490                             (conn->ping_timeout * HZ), jiffies))
1491                 rc = EH_RESET_TIMER;
1492         /*
1493          * if we are about to check the transport then give the command
1494          * more time
1495          */
1496         if (time_before_eq(conn->last_recv + (conn->recv_timeout * HZ),
1497                            jiffies))
1498                 rc = EH_RESET_TIMER;
1499         /* if in the middle of checking the transport then give us more time */
1500         if (conn->ping_mtask)
1501                 rc = EH_RESET_TIMER;
1502 done:
1503         spin_unlock(&session->lock);
1504         debug_scsi("return %s\n", rc == EH_RESET_TIMER ? "timer reset" : "nh");
1505         return rc;
1506 }
1507
1508 static void iscsi_check_transport_timeouts(unsigned long data)
1509 {
1510         struct iscsi_conn *conn = (struct iscsi_conn *)data;
1511         struct iscsi_session *session = conn->session;
1512         unsigned long recv_timeout, next_timeout = 0, last_recv;
1513
1514         spin_lock(&session->lock);
1515         if (session->state != ISCSI_STATE_LOGGED_IN)
1516                 goto done;
1517
1518         recv_timeout = conn->recv_timeout;
1519         if (!recv_timeout)
1520                 goto done;
1521
1522         recv_timeout *= HZ;
1523         last_recv = conn->last_recv;
1524         if (conn->ping_mtask &&
1525             time_before_eq(conn->last_ping + (conn->ping_timeout * HZ),
1526                            jiffies)) {
1527                 iscsi_conn_printk(KERN_ERR, conn, "ping timeout of %d secs "
1528                                   "expired, last rx %lu, last ping %lu, "
1529                                   "now %lu\n", conn->ping_timeout, last_recv,
1530                                   conn->last_ping, jiffies);
1531                 spin_unlock(&session->lock);
1532                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1533                 return;
1534         }
1535
1536         if (time_before_eq(last_recv + recv_timeout, jiffies)) {
1537                 /* send a ping to try to provoke some traffic */
1538                 debug_scsi("Sending nopout as ping on conn %p\n", conn);
1539                 iscsi_send_nopout(conn, NULL);
1540                 next_timeout = conn->last_ping + (conn->ping_timeout * HZ);
1541         } else
1542                 next_timeout = last_recv + recv_timeout;
1543
1544         debug_scsi("Setting next tmo %lu\n", next_timeout);
1545         mod_timer(&conn->transport_timer, next_timeout);
1546 done:
1547         spin_unlock(&session->lock);
1548 }
1549
1550 static void iscsi_prep_abort_task_pdu(struct iscsi_cmd_task *ctask,
1551                                       struct iscsi_tm *hdr)
1552 {
1553         memset(hdr, 0, sizeof(*hdr));
1554         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
1555         hdr->flags = ISCSI_TM_FUNC_ABORT_TASK & ISCSI_FLAG_TM_FUNC_MASK;
1556         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
1557         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
1558         hdr->rtt = ctask->hdr->itt;
1559         hdr->refcmdsn = ctask->hdr->cmdsn;
1560 }
1561
1562 int iscsi_eh_abort(struct scsi_cmnd *sc)
1563 {
1564         struct iscsi_cls_session *cls_session;
1565         struct iscsi_session *session;
1566         struct iscsi_conn *conn;
1567         struct iscsi_cmd_task *ctask;
1568         struct iscsi_tm *hdr;
1569         int rc, age;
1570
1571         cls_session = starget_to_session(scsi_target(sc->device));
1572         session = cls_session->dd_data;
1573
1574         mutex_lock(&session->eh_mutex);
1575         spin_lock_bh(&session->lock);
1576         /*
1577          * if session was ISCSI_STATE_IN_RECOVERY then we may not have
1578          * got the command.
1579          */
1580         if (!sc->SCp.ptr) {
1581                 debug_scsi("sc never reached iscsi layer or it completed.\n");
1582                 spin_unlock_bh(&session->lock);
1583                 mutex_unlock(&session->eh_mutex);
1584                 return SUCCESS;
1585         }
1586
1587         /*
1588          * If we are not logged in or we have started a new session
1589          * then let the host reset code handle this
1590          */
1591         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN ||
1592             sc->SCp.phase != session->age) {
1593                 spin_unlock_bh(&session->lock);
1594                 mutex_unlock(&session->eh_mutex);
1595                 return FAILED;
1596         }
1597
1598         conn = session->leadconn;
1599         conn->eh_abort_cnt++;
1600         age = session->age;
1601
1602         ctask = (struct iscsi_cmd_task *)sc->SCp.ptr;
1603         debug_scsi("aborting [sc %p itt 0x%x]\n", sc, ctask->itt);
1604
1605         /* ctask completed before time out */
1606         if (!ctask->sc) {
1607                 debug_scsi("sc completed while abort in progress\n");
1608                 goto success;
1609         }
1610
1611         if (ctask->state == ISCSI_TASK_PENDING) {
1612                 fail_command(conn, ctask, DID_ABORT << 16);
1613                 goto success;
1614         }
1615
1616         /* only have one tmf outstanding at a time */
1617         if (conn->tmf_state != TMF_INITIAL)
1618                 goto failed;
1619         conn->tmf_state = TMF_QUEUED;
1620
1621         hdr = &conn->tmhdr;
1622         iscsi_prep_abort_task_pdu(ctask, hdr);
1623
1624         if (iscsi_exec_task_mgmt_fn(conn, hdr, age, session->abort_timeout)) {
1625                 rc = FAILED;
1626                 goto failed;
1627         }
1628
1629         switch (conn->tmf_state) {
1630         case TMF_SUCCESS:
1631                 spin_unlock_bh(&session->lock);
1632                 iscsi_suspend_tx(conn);
1633                 /*
1634                  * clean up task if aborted. grab the recv lock as a writer
1635                  */
1636                 write_lock_bh(conn->recv_lock);
1637                 spin_lock(&session->lock);
1638                 fail_command(conn, ctask, DID_ABORT << 16);
1639                 conn->tmf_state = TMF_INITIAL;
1640                 spin_unlock(&session->lock);
1641                 write_unlock_bh(conn->recv_lock);
1642                 iscsi_start_tx(conn);
1643                 goto success_unlocked;
1644         case TMF_TIMEDOUT:
1645                 spin_unlock_bh(&session->lock);
1646                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1647                 goto failed_unlocked;
1648         case TMF_NOT_FOUND:
1649                 if (!sc->SCp.ptr) {
1650                         conn->tmf_state = TMF_INITIAL;
1651                         /* ctask completed before tmf abort response */
1652                         debug_scsi("sc completed while abort in progress\n");
1653                         goto success;
1654                 }
1655                 /* fall through */
1656         default:
1657                 conn->tmf_state = TMF_INITIAL;
1658                 goto failed;
1659         }
1660
1661 success:
1662         spin_unlock_bh(&session->lock);
1663 success_unlocked:
1664         debug_scsi("abort success [sc %lx itt 0x%x]\n", (long)sc, ctask->itt);
1665         mutex_unlock(&session->eh_mutex);
1666         return SUCCESS;
1667
1668 failed:
1669         spin_unlock_bh(&session->lock);
1670 failed_unlocked:
1671         debug_scsi("abort failed [sc %p itt 0x%x]\n", sc,
1672                     ctask ? ctask->itt : 0);
1673         mutex_unlock(&session->eh_mutex);
1674         return FAILED;
1675 }
1676 EXPORT_SYMBOL_GPL(iscsi_eh_abort);
1677
1678 static void iscsi_prep_lun_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr)
1679 {
1680         memset(hdr, 0, sizeof(*hdr));
1681         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
1682         hdr->flags = ISCSI_TM_FUNC_LOGICAL_UNIT_RESET & ISCSI_FLAG_TM_FUNC_MASK;
1683         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
1684         int_to_scsilun(sc->device->lun, (struct scsi_lun *)hdr->lun);
1685         hdr->rtt = RESERVED_ITT;
1686 }
1687
1688 int iscsi_eh_device_reset(struct scsi_cmnd *sc)
1689 {
1690         struct iscsi_cls_session *cls_session;
1691         struct iscsi_session *session;
1692         struct iscsi_conn *conn;
1693         struct iscsi_tm *hdr;
1694         int rc = FAILED;
1695
1696         cls_session = starget_to_session(scsi_target(sc->device));
1697         session = cls_session->dd_data;
1698
1699         debug_scsi("LU Reset [sc %p lun %u]\n", sc, sc->device->lun);
1700
1701         mutex_lock(&session->eh_mutex);
1702         spin_lock_bh(&session->lock);
1703         /*
1704          * Just check if we are not logged in. We cannot check for
1705          * the phase because the reset could come from a ioctl.
1706          */
1707         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN)
1708                 goto unlock;
1709         conn = session->leadconn;
1710
1711         /* only have one tmf outstanding at a time */
1712         if (conn->tmf_state != TMF_INITIAL)
1713                 goto unlock;
1714         conn->tmf_state = TMF_QUEUED;
1715
1716         hdr = &conn->tmhdr;
1717         iscsi_prep_lun_reset_pdu(sc, hdr);
1718
1719         if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age,
1720                                     session->lu_reset_timeout)) {
1721                 rc = FAILED;
1722                 goto unlock;
1723         }
1724
1725         switch (conn->tmf_state) {
1726         case TMF_SUCCESS:
1727                 break;
1728         case TMF_TIMEDOUT:
1729                 spin_unlock_bh(&session->lock);
1730                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1731                 goto done;
1732         default:
1733                 conn->tmf_state = TMF_INITIAL;
1734                 goto unlock;
1735         }
1736
1737         rc = SUCCESS;
1738         spin_unlock_bh(&session->lock);
1739
1740         iscsi_suspend_tx(conn);
1741         /* need to grab the recv lock then session lock */
1742         write_lock_bh(conn->recv_lock);
1743         spin_lock(&session->lock);
1744         fail_all_commands(conn, sc->device->lun, DID_ERROR);
1745         conn->tmf_state = TMF_INITIAL;
1746         spin_unlock(&session->lock);
1747         write_unlock_bh(conn->recv_lock);
1748
1749         iscsi_start_tx(conn);
1750         goto done;
1751
1752 unlock:
1753         spin_unlock_bh(&session->lock);
1754 done:
1755         debug_scsi("iscsi_eh_device_reset %s\n",
1756                   rc == SUCCESS ? "SUCCESS" : "FAILED");
1757         mutex_unlock(&session->eh_mutex);
1758         return rc;
1759 }
1760 EXPORT_SYMBOL_GPL(iscsi_eh_device_reset);
1761
1762 /*
1763  * Pre-allocate a pool of @max items of @item_size. By default, the pool
1764  * should be accessed via kfifo_{get,put} on q->queue.
1765  * Optionally, the caller can obtain the array of object pointers
1766  * by passing in a non-NULL @items pointer
1767  */
1768 int
1769 iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size)
1770 {
1771         int i, num_arrays = 1;
1772
1773         memset(q, 0, sizeof(*q));
1774
1775         q->max = max;
1776
1777         /* If the user passed an items pointer, he wants a copy of
1778          * the array. */
1779         if (items)
1780                 num_arrays++;
1781         q->pool = kzalloc(num_arrays * max * sizeof(void*), GFP_KERNEL);
1782         if (q->pool == NULL)
1783                 goto enomem;
1784
1785         q->queue = kfifo_init((void*)q->pool, max * sizeof(void*),
1786                               GFP_KERNEL, NULL);
1787         if (q->queue == ERR_PTR(-ENOMEM))
1788                 goto enomem;
1789
1790         for (i = 0; i < max; i++) {
1791                 q->pool[i] = kzalloc(item_size, GFP_KERNEL);
1792                 if (q->pool[i] == NULL) {
1793                         q->max = i;
1794                         goto enomem;
1795                 }
1796                 __kfifo_put(q->queue, (void*)&q->pool[i], sizeof(void*));
1797         }
1798
1799         if (items) {
1800                 *items = q->pool + max;
1801                 memcpy(*items, q->pool, max * sizeof(void *));
1802         }
1803
1804         return 0;
1805
1806 enomem:
1807         iscsi_pool_free(q);
1808         return -ENOMEM;
1809 }
1810 EXPORT_SYMBOL_GPL(iscsi_pool_init);
1811
1812 void iscsi_pool_free(struct iscsi_pool *q)
1813 {
1814         int i;
1815
1816         for (i = 0; i < q->max; i++)
1817                 kfree(q->pool[i]);
1818         if (q->pool)
1819                 kfree(q->pool);
1820 }
1821 EXPORT_SYMBOL_GPL(iscsi_pool_free);
1822
1823 /**
1824  * iscsi_host_add - add host to system
1825  * @shost: scsi host
1826  * @pdev: parent device
1827  *
1828  * This should be called by partial offload and software iscsi drivers
1829  * to add a host to the system.
1830  */
1831 int iscsi_host_add(struct Scsi_Host *shost, struct device *pdev)
1832 {
1833         return scsi_add_host(shost, pdev);
1834 }
1835 EXPORT_SYMBOL_GPL(iscsi_host_add);
1836
1837 /**
1838  * iscsi_host_alloc - allocate a host and driver data
1839  * @sht: scsi host template
1840  * @dd_data_size: driver host data size
1841  * @qdepth: default device queue depth
1842  *
1843  * This should be called by partial offload and software iscsi drivers.
1844  * To access the driver specific memory use the iscsi_host_priv() macro.
1845  */
1846 struct Scsi_Host *iscsi_host_alloc(struct scsi_host_template *sht,
1847                                    int dd_data_size, uint16_t qdepth)
1848 {
1849         struct Scsi_Host *shost;
1850
1851         shost = scsi_host_alloc(sht, sizeof(struct iscsi_host) + dd_data_size);
1852         if (!shost)
1853                 return NULL;
1854         shost->transportt->eh_timed_out = iscsi_eh_cmd_timed_out;
1855
1856         if (qdepth > ISCSI_MAX_CMD_PER_LUN || qdepth < 1) {
1857                 if (qdepth != 0)
1858                         printk(KERN_ERR "iscsi: invalid queue depth of %d. "
1859                                "Queue depth must be between 1 and %d.\n",
1860                                qdepth, ISCSI_MAX_CMD_PER_LUN);
1861                 qdepth = ISCSI_DEF_CMD_PER_LUN;
1862         }
1863         shost->cmd_per_lun = qdepth;
1864         return shost;
1865 }
1866 EXPORT_SYMBOL_GPL(iscsi_host_alloc);
1867
1868 /**
1869  * iscsi_host_remove - remove host and sessions
1870  * @shost: scsi host
1871  *
1872  * This will also remove any sessions attached to the host, but if userspace
1873  * is managing the session at the same time this will break. TODO: add
1874  * refcounting to the netlink iscsi interface so a rmmod or host hot unplug
1875  * does not remove the memory from under us.
1876  */
1877 void iscsi_host_remove(struct Scsi_Host *shost)
1878 {
1879         iscsi_host_for_each_session(shost, iscsi_session_teardown);
1880         scsi_remove_host(shost);
1881 }
1882 EXPORT_SYMBOL_GPL(iscsi_host_remove);
1883
1884 void iscsi_host_free(struct Scsi_Host *shost)
1885 {
1886         struct iscsi_host *ihost = shost_priv(shost);
1887
1888         kfree(ihost->netdev);
1889         kfree(ihost->hwaddress);
1890         kfree(ihost->initiatorname);
1891         scsi_host_put(shost);
1892 }
1893 EXPORT_SYMBOL_GPL(iscsi_host_free);
1894
1895 /**
1896  * iscsi_session_setup - create iscsi cls session and host and session
1897  * @iscsit: iscsi transport template
1898  * @shost: scsi host
1899  * @cmds_max: session can queue
1900  * @cmd_task_size: LLD ctask private data size
1901  * @mgmt_task_size: LLD mtask private data size
1902  * @initial_cmdsn: initial CmdSN
1903  *
1904  * This can be used by software iscsi_transports that allocate
1905  * a session per scsi host.
1906  */
1907 struct iscsi_cls_session *
1908 iscsi_session_setup(struct iscsi_transport *iscsit, struct Scsi_Host *shost,
1909                     uint16_t cmds_max, int cmd_task_size, int mgmt_task_size,
1910                     uint32_t initial_cmdsn)
1911 {
1912         struct iscsi_session *session;
1913         struct iscsi_cls_session *cls_session;
1914         int cmd_i;
1915
1916         if (!is_power_of_2(cmds_max) || cmds_max >= ISCSI_MGMT_ITT_OFFSET ||
1917             cmds_max < 2) {
1918                 if (cmds_max != 0)
1919                         printk(KERN_ERR "iscsi: invalid can_queue of %d. "
1920                                "can_queue must be a power of 2 and between "
1921                                "2 and %d - setting to %d.\n", cmds_max,
1922                                ISCSI_MGMT_ITT_OFFSET, ISCSI_DEF_XMIT_CMDS_MAX);
1923                 cmds_max = ISCSI_DEF_XMIT_CMDS_MAX;
1924         }
1925
1926         cls_session = iscsi_alloc_session(shost, iscsit,
1927                                           sizeof(struct iscsi_session));
1928         if (!cls_session)
1929                 return NULL;
1930         session = cls_session->dd_data;
1931         session->cls_session = cls_session;
1932         session->host = shost;
1933         session->state = ISCSI_STATE_FREE;
1934         session->fast_abort = 1;
1935         session->lu_reset_timeout = 15;
1936         session->abort_timeout = 10;
1937         session->mgmtpool_max = ISCSI_MGMT_CMDS_MAX;
1938         session->cmds_max = cmds_max;
1939         session->queued_cmdsn = session->cmdsn = initial_cmdsn;
1940         session->exp_cmdsn = initial_cmdsn + 1;
1941         session->max_cmdsn = initial_cmdsn + 1;
1942         session->max_r2t = 1;
1943         session->tt = iscsit;
1944         mutex_init(&session->eh_mutex);
1945         spin_lock_init(&session->lock);
1946
1947         /* initialize SCSI PDU commands pool */
1948         if (iscsi_pool_init(&session->cmdpool, session->cmds_max,
1949                             (void***)&session->cmds,
1950                             cmd_task_size + sizeof(struct iscsi_cmd_task)))
1951                 goto cmdpool_alloc_fail;
1952
1953         /* pre-format cmds pool with ITT */
1954         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
1955                 struct iscsi_cmd_task *ctask = session->cmds[cmd_i];
1956
1957                 if (cmd_task_size)
1958                         ctask->dd_data = &ctask[1];
1959                 ctask->itt = cmd_i;
1960                 INIT_LIST_HEAD(&ctask->running);
1961         }
1962
1963         /* initialize immediate command pool */
1964         if (iscsi_pool_init(&session->mgmtpool, session->mgmtpool_max,
1965                            (void***)&session->mgmt_cmds,
1966                            mgmt_task_size + sizeof(struct iscsi_mgmt_task)))
1967                 goto mgmtpool_alloc_fail;
1968
1969
1970         /* pre-format immediate cmds pool with ITT */
1971         for (cmd_i = 0; cmd_i < session->mgmtpool_max; cmd_i++) {
1972                 struct iscsi_mgmt_task *mtask = session->mgmt_cmds[cmd_i];
1973
1974                 if (mgmt_task_size)
1975                         mtask->dd_data = &mtask[1];
1976                 mtask->itt = ISCSI_MGMT_ITT_OFFSET + cmd_i;
1977                 INIT_LIST_HEAD(&mtask->running);
1978         }
1979
1980         if (!try_module_get(iscsit->owner))
1981                 goto module_get_fail;
1982
1983         if (iscsi_add_session(cls_session, 0))
1984                 goto cls_session_fail;
1985         return cls_session;
1986
1987 cls_session_fail:
1988         module_put(iscsit->owner);
1989 module_get_fail:
1990         iscsi_pool_free(&session->mgmtpool);
1991 mgmtpool_alloc_fail:
1992         iscsi_pool_free(&session->cmdpool);
1993 cmdpool_alloc_fail:
1994         iscsi_free_session(cls_session);
1995         return NULL;
1996 }
1997 EXPORT_SYMBOL_GPL(iscsi_session_setup);
1998
1999 /**
2000  * iscsi_session_teardown - destroy session, host, and cls_session
2001  * @cls_session: iscsi session
2002  *
2003  * The driver must have called iscsi_remove_session before
2004  * calling this.
2005  */
2006 void iscsi_session_teardown(struct iscsi_cls_session *cls_session)
2007 {
2008         struct iscsi_session *session = cls_session->dd_data;
2009         struct module *owner = cls_session->transport->owner;
2010
2011         iscsi_pool_free(&session->mgmtpool);
2012         iscsi_pool_free(&session->cmdpool);
2013
2014         kfree(session->password);
2015         kfree(session->password_in);
2016         kfree(session->username);
2017         kfree(session->username_in);
2018         kfree(session->targetname);
2019
2020         iscsi_destroy_session(cls_session);
2021         module_put(owner);
2022 }
2023 EXPORT_SYMBOL_GPL(iscsi_session_teardown);
2024
2025 /**
2026  * iscsi_conn_setup - create iscsi_cls_conn and iscsi_conn
2027  * @cls_session: iscsi_cls_session
2028  * @dd_size: private driver data size
2029  * @conn_idx: cid
2030  */
2031 struct iscsi_cls_conn *
2032 iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size,
2033                  uint32_t conn_idx)
2034 {
2035         struct iscsi_session *session = cls_session->dd_data;
2036         struct iscsi_conn *conn;
2037         struct iscsi_cls_conn *cls_conn;
2038         char *data;
2039
2040         cls_conn = iscsi_create_conn(cls_session, sizeof(*conn) + dd_size,
2041                                      conn_idx);
2042         if (!cls_conn)
2043                 return NULL;
2044         conn = cls_conn->dd_data;
2045         memset(conn, 0, sizeof(*conn) + dd_size);
2046
2047         conn->dd_data = cls_conn->dd_data + sizeof(*conn);
2048         conn->session = session;
2049         conn->cls_conn = cls_conn;
2050         conn->c_stage = ISCSI_CONN_INITIAL_STAGE;
2051         conn->id = conn_idx;
2052         conn->exp_statsn = 0;
2053         conn->tmf_state = TMF_INITIAL;
2054
2055         init_timer(&conn->transport_timer);
2056         conn->transport_timer.data = (unsigned long)conn;
2057         conn->transport_timer.function = iscsi_check_transport_timeouts;
2058
2059         INIT_LIST_HEAD(&conn->run_list);
2060         INIT_LIST_HEAD(&conn->mgmt_run_list);
2061         INIT_LIST_HEAD(&conn->mgmtqueue);
2062         INIT_LIST_HEAD(&conn->xmitqueue);
2063         INIT_LIST_HEAD(&conn->requeue);
2064         INIT_WORK(&conn->xmitwork, iscsi_xmitworker);
2065
2066         /* allocate login_mtask used for the login/text sequences */
2067         spin_lock_bh(&session->lock);
2068         if (!__kfifo_get(session->mgmtpool.queue,
2069                          (void*)&conn->login_mtask,
2070                          sizeof(void*))) {
2071                 spin_unlock_bh(&session->lock);
2072                 goto login_mtask_alloc_fail;
2073         }
2074         spin_unlock_bh(&session->lock);
2075
2076         data = kmalloc(ISCSI_DEF_MAX_RECV_SEG_LEN, GFP_KERNEL);
2077         if (!data)
2078                 goto login_mtask_data_alloc_fail;
2079         conn->login_mtask->data = conn->data = data;
2080
2081         init_timer(&conn->tmf_timer);
2082         init_waitqueue_head(&conn->ehwait);
2083
2084         return cls_conn;
2085
2086 login_mtask_data_alloc_fail:
2087         __kfifo_put(session->mgmtpool.queue, (void*)&conn->login_mtask,
2088                     sizeof(void*));
2089 login_mtask_alloc_fail:
2090         iscsi_destroy_conn(cls_conn);
2091         return NULL;
2092 }
2093 EXPORT_SYMBOL_GPL(iscsi_conn_setup);
2094
2095 /**
2096  * iscsi_conn_teardown - teardown iscsi connection
2097  * cls_conn: iscsi class connection
2098  *
2099  * TODO: we may need to make this into a two step process
2100  * like scsi-mls remove + put host
2101  */
2102 void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn)
2103 {
2104         struct iscsi_conn *conn = cls_conn->dd_data;
2105         struct iscsi_session *session = conn->session;
2106         unsigned long flags;
2107
2108         del_timer_sync(&conn->transport_timer);
2109
2110         spin_lock_bh(&session->lock);
2111         conn->c_stage = ISCSI_CONN_CLEANUP_WAIT;
2112         if (session->leadconn == conn) {
2113                 /*
2114                  * leading connection? then give up on recovery.
2115                  */
2116                 session->state = ISCSI_STATE_TERMINATE;
2117                 wake_up(&conn->ehwait);
2118         }
2119         spin_unlock_bh(&session->lock);
2120
2121         /*
2122          * Block until all in-progress commands for this connection
2123          * time out or fail.
2124          */
2125         for (;;) {
2126                 spin_lock_irqsave(session->host->host_lock, flags);
2127                 if (!session->host->host_busy) { /* OK for ERL == 0 */
2128                         spin_unlock_irqrestore(session->host->host_lock, flags);
2129                         break;
2130                 }
2131                 spin_unlock_irqrestore(session->host->host_lock, flags);
2132                 msleep_interruptible(500);
2133                 iscsi_conn_printk(KERN_INFO, conn, "iscsi conn_destroy(): "
2134                                   "host_busy %d host_failed %d\n",
2135                                   session->host->host_busy,
2136                                   session->host->host_failed);
2137                 /*
2138                  * force eh_abort() to unblock
2139                  */
2140                 wake_up(&conn->ehwait);
2141         }
2142
2143         /* flush queued up work because we free the connection below */
2144         iscsi_suspend_tx(conn);
2145
2146         spin_lock_bh(&session->lock);
2147         kfree(conn->data);
2148         kfree(conn->persistent_address);
2149         __kfifo_put(session->mgmtpool.queue, (void*)&conn->login_mtask,
2150                     sizeof(void*));
2151         if (session->leadconn == conn)
2152                 session->leadconn = NULL;
2153         spin_unlock_bh(&session->lock);
2154
2155         iscsi_destroy_conn(cls_conn);
2156 }
2157 EXPORT_SYMBOL_GPL(iscsi_conn_teardown);
2158
2159 int iscsi_conn_start(struct iscsi_cls_conn *cls_conn)
2160 {
2161         struct iscsi_conn *conn = cls_conn->dd_data;
2162         struct iscsi_session *session = conn->session;
2163
2164         if (!session) {
2165                 iscsi_conn_printk(KERN_ERR, conn,
2166                                   "can't start unbound connection\n");
2167                 return -EPERM;
2168         }
2169
2170         if ((session->imm_data_en || !session->initial_r2t_en) &&
2171              session->first_burst > session->max_burst) {
2172                 iscsi_conn_printk(KERN_INFO, conn, "invalid burst lengths: "
2173                                   "first_burst %d max_burst %d\n",
2174                                   session->first_burst, session->max_burst);
2175                 return -EINVAL;
2176         }
2177
2178         if (conn->ping_timeout && !conn->recv_timeout) {
2179                 iscsi_conn_printk(KERN_ERR, conn, "invalid recv timeout of "
2180                                   "zero. Using 5 seconds\n.");
2181                 conn->recv_timeout = 5;
2182         }
2183
2184         if (conn->recv_timeout && !conn->ping_timeout) {
2185                 iscsi_conn_printk(KERN_ERR, conn, "invalid ping timeout of "
2186                                   "zero. Using 5 seconds.\n");
2187                 conn->ping_timeout = 5;
2188         }
2189
2190         spin_lock_bh(&session->lock);
2191         conn->c_stage = ISCSI_CONN_STARTED;
2192         session->state = ISCSI_STATE_LOGGED_IN;
2193         session->queued_cmdsn = session->cmdsn;
2194
2195         conn->last_recv = jiffies;
2196         conn->last_ping = jiffies;
2197         if (conn->recv_timeout && conn->ping_timeout)
2198                 mod_timer(&conn->transport_timer,
2199                           jiffies + (conn->recv_timeout * HZ));
2200
2201         switch(conn->stop_stage) {
2202         case STOP_CONN_RECOVER:
2203                 /*
2204                  * unblock eh_abort() if it is blocked. re-try all
2205                  * commands after successful recovery
2206                  */
2207                 conn->stop_stage = 0;
2208                 conn->tmf_state = TMF_INITIAL;
2209                 session->age++;
2210                 if (session->age == 16)
2211                         session->age = 0;
2212                 break;
2213         case STOP_CONN_TERM:
2214                 conn->stop_stage = 0;
2215                 break;
2216         default:
2217                 break;
2218         }
2219         spin_unlock_bh(&session->lock);
2220
2221         iscsi_unblock_session(session->cls_session);
2222         wake_up(&conn->ehwait);
2223         return 0;
2224 }
2225 EXPORT_SYMBOL_GPL(iscsi_conn_start);
2226
2227 static void
2228 flush_control_queues(struct iscsi_session *session, struct iscsi_conn *conn)
2229 {
2230         struct iscsi_mgmt_task *mtask, *tmp;
2231
2232         /* handle pending */
2233         list_for_each_entry_safe(mtask, tmp, &conn->mgmtqueue, running) {
2234                 debug_scsi("flushing pending mgmt task itt 0x%x\n", mtask->itt);
2235                 iscsi_free_mgmt_task(conn, mtask);
2236         }
2237
2238         /* handle running */
2239         list_for_each_entry_safe(mtask, tmp, &conn->mgmt_run_list, running) {
2240                 debug_scsi("flushing running mgmt task itt 0x%x\n", mtask->itt);
2241                 iscsi_free_mgmt_task(conn, mtask);
2242         }
2243
2244         conn->mtask = NULL;
2245 }
2246
2247 static void iscsi_start_session_recovery(struct iscsi_session *session,
2248                                          struct iscsi_conn *conn, int flag)
2249 {
2250         int old_stop_stage;
2251
2252         del_timer_sync(&conn->transport_timer);
2253
2254         mutex_lock(&session->eh_mutex);
2255         spin_lock_bh(&session->lock);
2256         if (conn->stop_stage == STOP_CONN_TERM) {
2257                 spin_unlock_bh(&session->lock);
2258                 mutex_unlock(&session->eh_mutex);
2259                 return;
2260         }
2261
2262         /*
2263          * The LLD either freed/unset the lock on us, or userspace called
2264          * stop but did not create a proper connection (connection was never
2265          * bound or it was unbound then stop was called).
2266          */
2267         if (!conn->recv_lock) {
2268                 spin_unlock_bh(&session->lock);
2269                 mutex_unlock(&session->eh_mutex);
2270                 return;
2271         }
2272
2273         /*
2274          * When this is called for the in_login state, we only want to clean
2275          * up the login task and connection. We do not need to block and set
2276          * the recovery state again
2277          */
2278         if (flag == STOP_CONN_TERM)
2279                 session->state = ISCSI_STATE_TERMINATE;
2280         else if (conn->stop_stage != STOP_CONN_RECOVER)
2281                 session->state = ISCSI_STATE_IN_RECOVERY;
2282
2283         old_stop_stage = conn->stop_stage;
2284         conn->stop_stage = flag;
2285         conn->c_stage = ISCSI_CONN_STOPPED;
2286         spin_unlock_bh(&session->lock);
2287
2288         iscsi_suspend_tx(conn);
2289
2290         write_lock_bh(conn->recv_lock);
2291         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
2292         write_unlock_bh(conn->recv_lock);
2293
2294         /*
2295          * for connection level recovery we should not calculate
2296          * header digest. conn->hdr_size used for optimization
2297          * in hdr_extract() and will be re-negotiated at
2298          * set_param() time.
2299          */
2300         if (flag == STOP_CONN_RECOVER) {
2301                 conn->hdrdgst_en = 0;
2302                 conn->datadgst_en = 0;
2303                 if (session->state == ISCSI_STATE_IN_RECOVERY &&
2304                     old_stop_stage != STOP_CONN_RECOVER) {
2305                         debug_scsi("blocking session\n");
2306                         iscsi_block_session(session->cls_session);
2307                 }
2308         }
2309
2310         /*
2311          * flush queues.
2312          */
2313         spin_lock_bh(&session->lock);
2314         fail_all_commands(conn, -1,
2315                         STOP_CONN_RECOVER ? DID_BUS_BUSY : DID_ERROR);
2316         flush_control_queues(session, conn);
2317         spin_unlock_bh(&session->lock);
2318         mutex_unlock(&session->eh_mutex);
2319 }
2320
2321 void iscsi_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
2322 {
2323         struct iscsi_conn *conn = cls_conn->dd_data;
2324         struct iscsi_session *session = conn->session;
2325
2326         switch (flag) {
2327         case STOP_CONN_RECOVER:
2328         case STOP_CONN_TERM:
2329                 iscsi_start_session_recovery(session, conn, flag);
2330                 break;
2331         default:
2332                 iscsi_conn_printk(KERN_ERR, conn,
2333                                   "invalid stop flag %d\n", flag);
2334         }
2335 }
2336 EXPORT_SYMBOL_GPL(iscsi_conn_stop);
2337
2338 int iscsi_conn_bind(struct iscsi_cls_session *cls_session,
2339                     struct iscsi_cls_conn *cls_conn, int is_leading)
2340 {
2341         struct iscsi_session *session = cls_session->dd_data;
2342         struct iscsi_conn *conn = cls_conn->dd_data;
2343
2344         spin_lock_bh(&session->lock);
2345         if (is_leading)
2346                 session->leadconn = conn;
2347         spin_unlock_bh(&session->lock);
2348
2349         /*
2350          * Unblock xmitworker(), Login Phase will pass through.
2351          */
2352         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
2353         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
2354         return 0;
2355 }
2356 EXPORT_SYMBOL_GPL(iscsi_conn_bind);
2357
2358
2359 int iscsi_set_param(struct iscsi_cls_conn *cls_conn,
2360                     enum iscsi_param param, char *buf, int buflen)
2361 {
2362         struct iscsi_conn *conn = cls_conn->dd_data;
2363         struct iscsi_session *session = conn->session;
2364         uint32_t value;
2365
2366         switch(param) {
2367         case ISCSI_PARAM_FAST_ABORT:
2368                 sscanf(buf, "%d", &session->fast_abort);
2369                 break;
2370         case ISCSI_PARAM_ABORT_TMO:
2371                 sscanf(buf, "%d", &session->abort_timeout);
2372                 break;
2373         case ISCSI_PARAM_LU_RESET_TMO:
2374                 sscanf(buf, "%d", &session->lu_reset_timeout);
2375                 break;
2376         case ISCSI_PARAM_PING_TMO:
2377                 sscanf(buf, "%d", &conn->ping_timeout);
2378                 break;
2379         case ISCSI_PARAM_RECV_TMO:
2380                 sscanf(buf, "%d", &conn->recv_timeout);
2381                 break;
2382         case ISCSI_PARAM_MAX_RECV_DLENGTH:
2383                 sscanf(buf, "%d", &conn->max_recv_dlength);
2384                 break;
2385         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
2386                 sscanf(buf, "%d", &conn->max_xmit_dlength);
2387                 break;
2388         case ISCSI_PARAM_HDRDGST_EN:
2389                 sscanf(buf, "%d", &conn->hdrdgst_en);
2390                 break;
2391         case ISCSI_PARAM_DATADGST_EN:
2392                 sscanf(buf, "%d", &conn->datadgst_en);
2393                 break;
2394         case ISCSI_PARAM_INITIAL_R2T_EN:
2395                 sscanf(buf, "%d", &session->initial_r2t_en);
2396                 break;
2397         case ISCSI_PARAM_MAX_R2T:
2398                 sscanf(buf, "%d", &session->max_r2t);
2399                 break;
2400         case ISCSI_PARAM_IMM_DATA_EN:
2401                 sscanf(buf, "%d", &session->imm_data_en);
2402                 break;
2403         case ISCSI_PARAM_FIRST_BURST:
2404                 sscanf(buf, "%d", &session->first_burst);
2405                 break;
2406         case ISCSI_PARAM_MAX_BURST:
2407                 sscanf(buf, "%d", &session->max_burst);
2408                 break;
2409         case ISCSI_PARAM_PDU_INORDER_EN:
2410                 sscanf(buf, "%d", &session->pdu_inorder_en);
2411                 break;
2412         case ISCSI_PARAM_DATASEQ_INORDER_EN:
2413                 sscanf(buf, "%d", &session->dataseq_inorder_en);
2414                 break;
2415         case ISCSI_PARAM_ERL:
2416                 sscanf(buf, "%d", &session->erl);
2417                 break;
2418         case ISCSI_PARAM_IFMARKER_EN:
2419                 sscanf(buf, "%d", &value);
2420                 BUG_ON(value);
2421                 break;
2422         case ISCSI_PARAM_OFMARKER_EN:
2423                 sscanf(buf, "%d", &value);
2424                 BUG_ON(value);
2425                 break;
2426         case ISCSI_PARAM_EXP_STATSN:
2427                 sscanf(buf, "%u", &conn->exp_statsn);
2428                 break;
2429         case ISCSI_PARAM_USERNAME:
2430                 kfree(session->username);
2431                 session->username = kstrdup(buf, GFP_KERNEL);
2432                 if (!session->username)
2433                         return -ENOMEM;
2434                 break;
2435         case ISCSI_PARAM_USERNAME_IN:
2436                 kfree(session->username_in);
2437                 session->username_in = kstrdup(buf, GFP_KERNEL);
2438                 if (!session->username_in)
2439                         return -ENOMEM;
2440                 break;
2441         case ISCSI_PARAM_PASSWORD:
2442                 kfree(session->password);
2443                 session->password = kstrdup(buf, GFP_KERNEL);
2444                 if (!session->password)
2445                         return -ENOMEM;
2446                 break;
2447         case ISCSI_PARAM_PASSWORD_IN:
2448                 kfree(session->password_in);
2449                 session->password_in = kstrdup(buf, GFP_KERNEL);
2450                 if (!session->password_in)
2451                         return -ENOMEM;
2452                 break;
2453         case ISCSI_PARAM_TARGET_NAME:
2454                 /* this should not change between logins */
2455                 if (session->targetname)
2456                         break;
2457
2458                 session->targetname = kstrdup(buf, GFP_KERNEL);
2459                 if (!session->targetname)
2460                         return -ENOMEM;
2461                 break;
2462         case ISCSI_PARAM_TPGT:
2463                 sscanf(buf, "%d", &session->tpgt);
2464                 break;
2465         case ISCSI_PARAM_PERSISTENT_PORT:
2466                 sscanf(buf, "%d", &conn->persistent_port);
2467                 break;
2468         case ISCSI_PARAM_PERSISTENT_ADDRESS:
2469                 /*
2470                  * this is the address returned in discovery so it should
2471                  * not change between logins.
2472                  */
2473                 if (conn->persistent_address)
2474                         break;
2475
2476                 conn->persistent_address = kstrdup(buf, GFP_KERNEL);
2477                 if (!conn->persistent_address)
2478                         return -ENOMEM;
2479                 break;
2480         default:
2481                 return -ENOSYS;
2482         }
2483
2484         return 0;
2485 }
2486 EXPORT_SYMBOL_GPL(iscsi_set_param);
2487
2488 int iscsi_session_get_param(struct iscsi_cls_session *cls_session,
2489                             enum iscsi_param param, char *buf)
2490 {
2491         struct iscsi_session *session = cls_session->dd_data;
2492         int len;
2493
2494         switch(param) {
2495         case ISCSI_PARAM_FAST_ABORT:
2496                 len = sprintf(buf, "%d\n", session->fast_abort);
2497                 break;
2498         case ISCSI_PARAM_ABORT_TMO:
2499                 len = sprintf(buf, "%d\n", session->abort_timeout);
2500                 break;
2501         case ISCSI_PARAM_LU_RESET_TMO:
2502                 len = sprintf(buf, "%d\n", session->lu_reset_timeout);
2503                 break;
2504         case ISCSI_PARAM_INITIAL_R2T_EN:
2505                 len = sprintf(buf, "%d\n", session->initial_r2t_en);
2506                 break;
2507         case ISCSI_PARAM_MAX_R2T:
2508                 len = sprintf(buf, "%hu\n", session->max_r2t);
2509                 break;
2510         case ISCSI_PARAM_IMM_DATA_EN:
2511                 len = sprintf(buf, "%d\n", session->imm_data_en);
2512                 break;
2513         case ISCSI_PARAM_FIRST_BURST:
2514                 len = sprintf(buf, "%u\n", session->first_burst);
2515                 break;
2516         case ISCSI_PARAM_MAX_BURST:
2517                 len = sprintf(buf, "%u\n", session->max_burst);
2518                 break;
2519         case ISCSI_PARAM_PDU_INORDER_EN:
2520                 len = sprintf(buf, "%d\n", session->pdu_inorder_en);
2521                 break;
2522         case ISCSI_PARAM_DATASEQ_INORDER_EN:
2523                 len = sprintf(buf, "%d\n", session->dataseq_inorder_en);
2524                 break;
2525         case ISCSI_PARAM_ERL:
2526                 len = sprintf(buf, "%d\n", session->erl);
2527                 break;
2528         case ISCSI_PARAM_TARGET_NAME:
2529                 len = sprintf(buf, "%s\n", session->targetname);
2530                 break;
2531         case ISCSI_PARAM_TPGT:
2532                 len = sprintf(buf, "%d\n", session->tpgt);
2533                 break;
2534         case ISCSI_PARAM_USERNAME:
2535                 len = sprintf(buf, "%s\n", session->username);
2536                 break;
2537         case ISCSI_PARAM_USERNAME_IN:
2538                 len = sprintf(buf, "%s\n", session->username_in);
2539                 break;
2540         case ISCSI_PARAM_PASSWORD:
2541                 len = sprintf(buf, "%s\n", session->password);
2542                 break;
2543         case ISCSI_PARAM_PASSWORD_IN:
2544                 len = sprintf(buf, "%s\n", session->password_in);
2545                 break;
2546         default:
2547                 return -ENOSYS;
2548         }
2549
2550         return len;
2551 }
2552 EXPORT_SYMBOL_GPL(iscsi_session_get_param);
2553
2554 int iscsi_conn_get_param(struct iscsi_cls_conn *cls_conn,
2555                          enum iscsi_param param, char *buf)
2556 {
2557         struct iscsi_conn *conn = cls_conn->dd_data;
2558         int len;
2559
2560         switch(param) {
2561         case ISCSI_PARAM_PING_TMO:
2562                 len = sprintf(buf, "%u\n", conn->ping_timeout);
2563                 break;
2564         case ISCSI_PARAM_RECV_TMO:
2565                 len = sprintf(buf, "%u\n", conn->recv_timeout);
2566                 break;
2567         case ISCSI_PARAM_MAX_RECV_DLENGTH:
2568                 len = sprintf(buf, "%u\n", conn->max_recv_dlength);
2569                 break;
2570         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
2571                 len = sprintf(buf, "%u\n", conn->max_xmit_dlength);
2572                 break;
2573         case ISCSI_PARAM_HDRDGST_EN:
2574                 len = sprintf(buf, "%d\n", conn->hdrdgst_en);
2575                 break;
2576         case ISCSI_PARAM_DATADGST_EN:
2577                 len = sprintf(buf, "%d\n", conn->datadgst_en);
2578                 break;
2579         case ISCSI_PARAM_IFMARKER_EN:
2580                 len = sprintf(buf, "%d\n", conn->ifmarker_en);
2581                 break;
2582         case ISCSI_PARAM_OFMARKER_EN:
2583                 len = sprintf(buf, "%d\n", conn->ofmarker_en);
2584                 break;
2585         case ISCSI_PARAM_EXP_STATSN:
2586                 len = sprintf(buf, "%u\n", conn->exp_statsn);
2587                 break;
2588         case ISCSI_PARAM_PERSISTENT_PORT:
2589                 len = sprintf(buf, "%d\n", conn->persistent_port);
2590                 break;
2591         case ISCSI_PARAM_PERSISTENT_ADDRESS:
2592                 len = sprintf(buf, "%s\n", conn->persistent_address);
2593                 break;
2594         default:
2595                 return -ENOSYS;
2596         }
2597
2598         return len;
2599 }
2600 EXPORT_SYMBOL_GPL(iscsi_conn_get_param);
2601
2602 int iscsi_host_get_param(struct Scsi_Host *shost, enum iscsi_host_param param,
2603                          char *buf)
2604 {
2605         struct iscsi_host *ihost = shost_priv(shost);
2606         int len;
2607
2608         switch (param) {
2609         case ISCSI_HOST_PARAM_NETDEV_NAME:
2610                 if (!ihost->netdev)
2611                         len = sprintf(buf, "%s\n", "default");
2612                 else
2613                         len = sprintf(buf, "%s\n", ihost->netdev);
2614                 break;
2615         case ISCSI_HOST_PARAM_HWADDRESS:
2616                 if (!ihost->hwaddress)
2617                         len = sprintf(buf, "%s\n", "default");
2618                 else
2619                         len = sprintf(buf, "%s\n", ihost->hwaddress);
2620                 break;
2621         case ISCSI_HOST_PARAM_INITIATOR_NAME:
2622                 if (!ihost->initiatorname)
2623                         len = sprintf(buf, "%s\n", "unknown");
2624                 else
2625                         len = sprintf(buf, "%s\n", ihost->initiatorname);
2626                 break;
2627         case ISCSI_HOST_PARAM_IPADDRESS:
2628                 if (!strlen(ihost->local_address))
2629                         len = sprintf(buf, "%s\n", "unknown");
2630                 else
2631                         len = sprintf(buf, "%s\n",
2632                                       ihost->local_address);
2633         default:
2634                 return -ENOSYS;
2635         }
2636
2637         return len;
2638 }
2639 EXPORT_SYMBOL_GPL(iscsi_host_get_param);
2640
2641 int iscsi_host_set_param(struct Scsi_Host *shost, enum iscsi_host_param param,
2642                          char *buf, int buflen)
2643 {
2644         struct iscsi_host *ihost = shost_priv(shost);
2645
2646         switch (param) {
2647         case ISCSI_HOST_PARAM_NETDEV_NAME:
2648                 if (!ihost->netdev)
2649                         ihost->netdev = kstrdup(buf, GFP_KERNEL);
2650                 break;
2651         case ISCSI_HOST_PARAM_HWADDRESS:
2652                 if (!ihost->hwaddress)
2653                         ihost->hwaddress = kstrdup(buf, GFP_KERNEL);
2654                 break;
2655         case ISCSI_HOST_PARAM_INITIATOR_NAME:
2656                 if (!ihost->initiatorname)
2657                         ihost->initiatorname = kstrdup(buf, GFP_KERNEL);
2658                 break;
2659         default:
2660                 return -ENOSYS;
2661         }
2662
2663         return 0;
2664 }
2665 EXPORT_SYMBOL_GPL(iscsi_host_set_param);
2666
2667 MODULE_AUTHOR("Mike Christie");
2668 MODULE_DESCRIPTION("iSCSI library functions");
2669 MODULE_LICENSE("GPL");