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