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