]> Pileus Git - ~andy/linux/blob - drivers/scsi/libiscsi.c
[SCSI] iscsi: fix run list corruption
[~andy/linux] / 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/mutex.h>
26 #include <linux/kfifo.h>
27 #include <linux/delay.h>
28 #include <net/tcp.h>
29 #include <scsi/scsi_cmnd.h>
30 #include <scsi/scsi_device.h>
31 #include <scsi/scsi_eh.h>
32 #include <scsi/scsi_tcq.h>
33 #include <scsi/scsi_host.h>
34 #include <scsi/scsi.h>
35 #include <scsi/iscsi_proto.h>
36 #include <scsi/scsi_transport.h>
37 #include <scsi/scsi_transport_iscsi.h>
38 #include <scsi/libiscsi.h>
39
40 struct iscsi_session *
41 class_to_transport_session(struct iscsi_cls_session *cls_session)
42 {
43         struct Scsi_Host *shost = iscsi_session_to_shost(cls_session);
44         return iscsi_hostdata(shost->hostdata);
45 }
46 EXPORT_SYMBOL_GPL(class_to_transport_session);
47
48 #define INVALID_SN_DELTA        0xffff
49
50 int
51 iscsi_check_assign_cmdsn(struct iscsi_session *session, struct iscsi_nopin *hdr)
52 {
53         uint32_t max_cmdsn = be32_to_cpu(hdr->max_cmdsn);
54         uint32_t exp_cmdsn = be32_to_cpu(hdr->exp_cmdsn);
55
56         if (max_cmdsn < exp_cmdsn -1 &&
57             max_cmdsn > exp_cmdsn - INVALID_SN_DELTA)
58                 return ISCSI_ERR_MAX_CMDSN;
59         if (max_cmdsn > session->max_cmdsn ||
60             max_cmdsn < session->max_cmdsn - INVALID_SN_DELTA)
61                 session->max_cmdsn = max_cmdsn;
62         if (exp_cmdsn > session->exp_cmdsn ||
63             exp_cmdsn < session->exp_cmdsn - INVALID_SN_DELTA)
64                 session->exp_cmdsn = exp_cmdsn;
65
66         return 0;
67 }
68 EXPORT_SYMBOL_GPL(iscsi_check_assign_cmdsn);
69
70 void iscsi_prep_unsolicit_data_pdu(struct iscsi_cmd_task *ctask,
71                                    struct iscsi_data *hdr,
72                                    int transport_data_cnt)
73 {
74         struct iscsi_conn *conn = ctask->conn;
75
76         memset(hdr, 0, sizeof(struct iscsi_data));
77         hdr->ttt = cpu_to_be32(ISCSI_RESERVED_TAG);
78         hdr->datasn = cpu_to_be32(ctask->unsol_datasn);
79         ctask->unsol_datasn++;
80         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
81         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
82
83         hdr->itt = ctask->hdr->itt;
84         hdr->exp_statsn = cpu_to_be32(conn->exp_statsn);
85
86         hdr->offset = cpu_to_be32(ctask->total_length -
87                                   transport_data_cnt -
88                                   ctask->unsol_count);
89
90         if (ctask->unsol_count > conn->max_xmit_dlength) {
91                 hton24(hdr->dlength, conn->max_xmit_dlength);
92                 ctask->data_count = conn->max_xmit_dlength;
93                 hdr->flags = 0;
94         } else {
95                 hton24(hdr->dlength, ctask->unsol_count);
96                 ctask->data_count = ctask->unsol_count;
97                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
98         }
99 }
100 EXPORT_SYMBOL_GPL(iscsi_prep_unsolicit_data_pdu);
101
102 /**
103  * iscsi_prep_scsi_cmd_pdu - prep iscsi scsi cmd pdu
104  * @ctask: iscsi cmd task
105  *
106  * Prep basic iSCSI PDU fields for a scsi cmd pdu. The LLD should set
107  * fields like dlength or final based on how much data it sends
108  */
109 static void iscsi_prep_scsi_cmd_pdu(struct iscsi_cmd_task *ctask)
110 {
111         struct iscsi_conn *conn = ctask->conn;
112         struct iscsi_session *session = conn->session;
113         struct iscsi_cmd *hdr = ctask->hdr;
114         struct scsi_cmnd *sc = ctask->sc;
115
116         hdr->opcode = ISCSI_OP_SCSI_CMD;
117         hdr->flags = ISCSI_ATTR_SIMPLE;
118         int_to_scsilun(sc->device->lun, (struct scsi_lun *)hdr->lun);
119         hdr->itt = ctask->itt | (conn->id << ISCSI_CID_SHIFT) |
120                          (session->age << ISCSI_AGE_SHIFT);
121         hdr->data_length = cpu_to_be32(sc->request_bufflen);
122         hdr->cmdsn = cpu_to_be32(session->cmdsn);
123         session->cmdsn++;
124         hdr->exp_statsn = cpu_to_be32(conn->exp_statsn);
125         memcpy(hdr->cdb, sc->cmnd, sc->cmd_len);
126         memset(&hdr->cdb[sc->cmd_len], 0, MAX_COMMAND_SIZE - sc->cmd_len);
127
128         if (sc->sc_data_direction == DMA_TO_DEVICE) {
129                 hdr->flags |= ISCSI_FLAG_CMD_WRITE;
130                 /*
131                  * Write counters:
132                  *
133                  *      imm_count       bytes to be sent right after
134                  *                      SCSI PDU Header
135                  *
136                  *      unsol_count     bytes(as Data-Out) to be sent
137                  *                      without R2T ack right after
138                  *                      immediate data
139                  *
140                  *      r2t_data_count  bytes to be sent via R2T ack's
141                  *
142                  *      pad_count       bytes to be sent as zero-padding
143                  */
144                 ctask->imm_count = 0;
145                 ctask->unsol_count = 0;
146                 ctask->unsol_datasn = 0;
147
148                 if (session->imm_data_en) {
149                         if (ctask->total_length >= session->first_burst)
150                                 ctask->imm_count = min(session->first_burst,
151                                                         conn->max_xmit_dlength);
152                         else
153                                 ctask->imm_count = min(ctask->total_length,
154                                                         conn->max_xmit_dlength);
155                         hton24(ctask->hdr->dlength, ctask->imm_count);
156                 } else
157                         zero_data(ctask->hdr->dlength);
158
159                 if (!session->initial_r2t_en)
160                         ctask->unsol_count = min(session->first_burst,
161                                 ctask->total_length) - ctask->imm_count;
162                 if (!ctask->unsol_count)
163                         /* No unsolicit Data-Out's */
164                         ctask->hdr->flags |= ISCSI_FLAG_CMD_FINAL;
165         } else {
166                 ctask->datasn = 0;
167                 hdr->flags |= ISCSI_FLAG_CMD_FINAL;
168                 zero_data(hdr->dlength);
169
170                 if (sc->sc_data_direction == DMA_FROM_DEVICE)
171                         hdr->flags |= ISCSI_FLAG_CMD_READ;
172         }
173
174         conn->scsicmd_pdus_cnt++;
175 }
176 EXPORT_SYMBOL_GPL(iscsi_prep_scsi_cmd_pdu);
177
178 /**
179  * iscsi_complete_command - return command back to scsi-ml
180  * @session: iscsi session
181  * @ctask: iscsi cmd task
182  *
183  * Must be called with session lock.
184  * This function returns the scsi command to scsi-ml and returns
185  * the cmd task to the pool of available cmd tasks.
186  */
187 static void iscsi_complete_command(struct iscsi_session *session,
188                                    struct iscsi_cmd_task *ctask)
189 {
190         struct scsi_cmnd *sc = ctask->sc;
191
192         ctask->sc = NULL;
193         list_del_init(&ctask->running);
194         __kfifo_put(session->cmdpool.queue, (void*)&ctask, sizeof(void*));
195         sc->scsi_done(sc);
196 }
197
198 /**
199  * iscsi_cmd_rsp - SCSI Command Response processing
200  * @conn: iscsi connection
201  * @hdr: iscsi header
202  * @ctask: scsi command task
203  * @data: cmd data buffer
204  * @datalen: len of buffer
205  *
206  * iscsi_cmd_rsp sets up the scsi_cmnd fields based on the PDU and
207  * then completes the command and task.
208  **/
209 static int iscsi_scsi_cmd_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
210                               struct iscsi_cmd_task *ctask, char *data,
211                               int datalen)
212 {
213         int rc;
214         struct iscsi_cmd_rsp *rhdr = (struct iscsi_cmd_rsp *)hdr;
215         struct iscsi_session *session = conn->session;
216         struct scsi_cmnd *sc = ctask->sc;
217
218         rc = iscsi_check_assign_cmdsn(session, (struct iscsi_nopin*)rhdr);
219         if (rc) {
220                 sc->result = DID_ERROR << 16;
221                 goto out;
222         }
223
224         conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
225
226         sc->result = (DID_OK << 16) | rhdr->cmd_status;
227
228         if (rhdr->response != ISCSI_STATUS_CMD_COMPLETED) {
229                 sc->result = DID_ERROR << 16;
230                 goto out;
231         }
232
233         if (rhdr->cmd_status == SAM_STAT_CHECK_CONDITION) {
234                 int senselen;
235
236                 if (datalen < 2) {
237 invalid_datalen:
238                         printk(KERN_ERR "iscsi: Got CHECK_CONDITION but "
239                                "invalid data buffer size of %d\n", datalen);
240                         sc->result = DID_BAD_TARGET << 16;
241                         goto out;
242                 }
243
244                 senselen = (data[0] << 8) | data[1];
245                 if (datalen < senselen)
246                         goto invalid_datalen;
247
248                 memcpy(sc->sense_buffer, data + 2,
249                        min(senselen, SCSI_SENSE_BUFFERSIZE));
250                 debug_scsi("copied %d bytes of sense\n",
251                            min(senselen, SCSI_SENSE_BUFFERSIZE));
252         }
253
254         if (sc->sc_data_direction == DMA_TO_DEVICE)
255                 goto out;
256
257         if (rhdr->flags & ISCSI_FLAG_CMD_UNDERFLOW) {
258                 int res_count = be32_to_cpu(rhdr->residual_count);
259
260                 if (res_count > 0 && res_count <= sc->request_bufflen)
261                         sc->resid = res_count;
262                 else
263                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
264         } else if (rhdr->flags & ISCSI_FLAG_CMD_BIDI_UNDERFLOW)
265                 sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
266         else if (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW)
267                 sc->resid = be32_to_cpu(rhdr->residual_count);
268
269 out:
270         debug_scsi("done [sc %lx res %d itt 0x%x]\n",
271                    (long)sc, sc->result, ctask->itt);
272         conn->scsirsp_pdus_cnt++;
273
274         iscsi_complete_command(conn->session, ctask);
275         return rc;
276 }
277
278 /**
279  * __iscsi_complete_pdu - complete pdu
280  * @conn: iscsi conn
281  * @hdr: iscsi header
282  * @data: data buffer
283  * @datalen: len of data buffer
284  *
285  * Completes pdu processing by freeing any resources allocated at
286  * queuecommand or send generic. session lock must be held and verify
287  * itt must have been called.
288  */
289 int __iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
290                          char *data, int datalen)
291 {
292         struct iscsi_session *session = conn->session;
293         int opcode = hdr->opcode & ISCSI_OPCODE_MASK, rc = 0;
294         struct iscsi_cmd_task *ctask;
295         struct iscsi_mgmt_task *mtask;
296         uint32_t itt;
297
298         if (hdr->itt != cpu_to_be32(ISCSI_RESERVED_TAG))
299                 itt = hdr->itt & ISCSI_ITT_MASK;
300         else
301                 itt = hdr->itt;
302
303         if (itt < session->cmds_max) {
304                 ctask = session->cmds[itt];
305
306                 debug_scsi("cmdrsp [op 0x%x cid %d itt 0x%x len %d]\n",
307                            opcode, conn->id, ctask->itt, datalen);
308
309                 switch(opcode) {
310                 case ISCSI_OP_SCSI_CMD_RSP:
311                         BUG_ON((void*)ctask != ctask->sc->SCp.ptr);
312                         rc = iscsi_scsi_cmd_rsp(conn, hdr, ctask, data,
313                                                 datalen);
314                         break;
315                 case ISCSI_OP_SCSI_DATA_IN:
316                         BUG_ON((void*)ctask != ctask->sc->SCp.ptr);
317                         if (hdr->flags & ISCSI_FLAG_DATA_STATUS) {
318                                 conn->scsirsp_pdus_cnt++;
319                                 iscsi_complete_command(session, ctask);
320                         }
321                         break;
322                 case ISCSI_OP_R2T:
323                         /* LLD handles this for now */
324                         break;
325                 default:
326                         rc = ISCSI_ERR_BAD_OPCODE;
327                         break;
328                 }
329         } else if (itt >= ISCSI_MGMT_ITT_OFFSET &&
330                    itt < ISCSI_MGMT_ITT_OFFSET + session->mgmtpool_max) {
331                 mtask = session->mgmt_cmds[itt - ISCSI_MGMT_ITT_OFFSET];
332
333                 debug_scsi("immrsp [op 0x%x cid %d itt 0x%x len %d]\n",
334                            opcode, conn->id, mtask->itt, datalen);
335
336                 rc = iscsi_check_assign_cmdsn(session,
337                                               (struct iscsi_nopin*)hdr);
338                 if (rc)
339                         goto done;
340
341                 switch(opcode) {
342                 case ISCSI_OP_LOGOUT_RSP:
343                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
344                         /* fall through */
345                 case ISCSI_OP_LOGIN_RSP:
346                 case ISCSI_OP_TEXT_RSP:
347                         /*
348                          * login related PDU's exp_statsn is handled in
349                          * userspace
350                          */
351                         rc = iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen);
352                         list_del(&mtask->running);
353                         if (conn->login_mtask != mtask)
354                                 __kfifo_put(session->mgmtpool.queue,
355                                             (void*)&mtask, sizeof(void*));
356                         break;
357                 case ISCSI_OP_SCSI_TMFUNC_RSP:
358                         if (datalen) {
359                                 rc = ISCSI_ERR_PROTO;
360                                 break;
361                         }
362
363                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
364                         conn->tmfrsp_pdus_cnt++;
365                         if (conn->tmabort_state == TMABORT_INITIAL) {
366                                 conn->tmabort_state =
367                                         ((struct iscsi_tm_rsp *)hdr)->
368                                         response == ISCSI_TMF_RSP_COMPLETE ?
369                                                 TMABORT_SUCCESS:TMABORT_FAILED;
370                                 /* unblock eh_abort() */
371                                 wake_up(&conn->ehwait);
372                         }
373                         break;
374                 case ISCSI_OP_NOOP_IN:
375                         if (hdr->ttt != ISCSI_RESERVED_TAG) {
376                                 rc = ISCSI_ERR_PROTO;
377                                 break;
378                         }
379                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
380
381                         rc = iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen);
382                         list_del(&mtask->running);
383                         if (conn->login_mtask != mtask)
384                                 __kfifo_put(session->mgmtpool.queue,
385                                             (void*)&mtask, sizeof(void*));
386                         break;
387                 default:
388                         rc = ISCSI_ERR_BAD_OPCODE;
389                         break;
390                 }
391         } else if (itt == ISCSI_RESERVED_TAG) {
392                 switch(opcode) {
393                 case ISCSI_OP_NOOP_IN:
394                         if (!datalen) {
395                                 rc = iscsi_check_assign_cmdsn(session,
396                                                  (struct iscsi_nopin*)hdr);
397                                 if (!rc && hdr->ttt != ISCSI_RESERVED_TAG)
398                                         rc = iscsi_recv_pdu(conn->cls_conn,
399                                                             hdr, NULL, 0);
400                         } else
401                                 rc = ISCSI_ERR_PROTO;
402                         break;
403                 case ISCSI_OP_REJECT:
404                         /* we need sth like iscsi_reject_rsp()*/
405                 case ISCSI_OP_ASYNC_EVENT:
406                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
407                         /* we need sth like iscsi_async_event_rsp() */
408                         rc = ISCSI_ERR_BAD_OPCODE;
409                         break;
410                 default:
411                         rc = ISCSI_ERR_BAD_OPCODE;
412                         break;
413                 }
414         } else
415                 rc = ISCSI_ERR_BAD_ITT;
416
417 done:
418         return rc;
419 }
420 EXPORT_SYMBOL_GPL(__iscsi_complete_pdu);
421
422 int iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
423                        char *data, int datalen)
424 {
425         int rc;
426
427         spin_lock(&conn->session->lock);
428         rc = __iscsi_complete_pdu(conn, hdr, data, datalen);
429         spin_unlock(&conn->session->lock);
430         return rc;
431 }
432 EXPORT_SYMBOL_GPL(iscsi_complete_pdu);
433
434 /* verify itt (itt encoding: age+cid+itt) */
435 int iscsi_verify_itt(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
436                      uint32_t *ret_itt)
437 {
438         struct iscsi_session *session = conn->session;
439         struct iscsi_cmd_task *ctask;
440         uint32_t itt;
441
442         if (hdr->itt != cpu_to_be32(ISCSI_RESERVED_TAG)) {
443                 if ((hdr->itt & ISCSI_AGE_MASK) !=
444                     (session->age << ISCSI_AGE_SHIFT)) {
445                         printk(KERN_ERR "iscsi: received itt %x expected "
446                                 "session age (%x)\n", hdr->itt,
447                                 session->age & ISCSI_AGE_MASK);
448                         return ISCSI_ERR_BAD_ITT;
449                 }
450
451                 if ((hdr->itt & ISCSI_CID_MASK) !=
452                     (conn->id << ISCSI_CID_SHIFT)) {
453                         printk(KERN_ERR "iscsi: received itt %x, expected "
454                                 "CID (%x)\n", hdr->itt, conn->id);
455                         return ISCSI_ERR_BAD_ITT;
456                 }
457                 itt = hdr->itt & ISCSI_ITT_MASK;
458         } else
459                 itt = hdr->itt;
460
461         if (itt < session->cmds_max) {
462                 ctask = session->cmds[itt];
463
464                 if (!ctask->sc) {
465                         printk(KERN_INFO "iscsi: dropping ctask with "
466                                "itt 0x%x\n", ctask->itt);
467                         /* force drop */
468                         return ISCSI_ERR_NO_SCSI_CMD;
469                 }
470
471                 if (ctask->sc->SCp.phase != session->age) {
472                         printk(KERN_ERR "iscsi: ctask's session age %d, "
473                                 "expected %d\n", ctask->sc->SCp.phase,
474                                 session->age);
475                         return ISCSI_ERR_SESSION_FAILED;
476                 }
477         }
478
479         *ret_itt = itt;
480         return 0;
481 }
482 EXPORT_SYMBOL_GPL(iscsi_verify_itt);
483
484 void iscsi_conn_failure(struct iscsi_conn *conn, enum iscsi_err err)
485 {
486         struct iscsi_session *session = conn->session;
487         unsigned long flags;
488
489         spin_lock_irqsave(&session->lock, flags);
490         if (session->state == ISCSI_STATE_FAILED) {
491                 spin_unlock_irqrestore(&session->lock, flags);
492                 return;
493         }
494
495         if (conn->stop_stage == 0)
496                 session->state = ISCSI_STATE_FAILED;
497         spin_unlock_irqrestore(&session->lock, flags);
498         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
499         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
500         iscsi_conn_error(conn->cls_conn, err);
501 }
502 EXPORT_SYMBOL_GPL(iscsi_conn_failure);
503
504 /**
505  * iscsi_data_xmit - xmit any command into the scheduled connection
506  * @conn: iscsi connection
507  *
508  * Notes:
509  *      The function can return -EAGAIN in which case the caller must
510  *      re-schedule it again later or recover. '0' return code means
511  *      successful xmit.
512  **/
513 static int iscsi_data_xmit(struct iscsi_conn *conn)
514 {
515         struct iscsi_transport *tt;
516
517         if (unlikely(conn->suspend_tx)) {
518                 debug_scsi("conn %d Tx suspended!\n", conn->id);
519                 return 0;
520         }
521         tt = conn->session->tt;
522
523         /*
524          * Transmit in the following order:
525          *
526          * 1) un-finished xmit (ctask or mtask)
527          * 2) immediate control PDUs
528          * 3) write data
529          * 4) SCSI commands
530          * 5) non-immediate control PDUs
531          *
532          * No need to lock around __kfifo_get as long as
533          * there's one producer and one consumer.
534          */
535
536         BUG_ON(conn->ctask && conn->mtask);
537
538         if (conn->ctask) {
539                 if (tt->xmit_cmd_task(conn, conn->ctask))
540                         goto again;
541                 /* done with this in-progress ctask */
542                 conn->ctask = NULL;
543         }
544         if (conn->mtask) {
545                 if (tt->xmit_mgmt_task(conn, conn->mtask))
546                         goto again;
547                 /* done with this in-progress mtask */
548                 conn->mtask = NULL;
549         }
550
551         /* process immediate first */
552         if (unlikely(__kfifo_len(conn->immqueue))) {
553                 while (__kfifo_get(conn->immqueue, (void*)&conn->mtask,
554                                    sizeof(void*))) {
555                         spin_lock_bh(&conn->session->lock);
556                         list_add_tail(&conn->mtask->running,
557                                       &conn->mgmt_run_list);
558                         spin_unlock_bh(&conn->session->lock);
559                         if (tt->xmit_mgmt_task(conn, conn->mtask))
560                                 goto again;
561                 }
562                 /* done with this mtask */
563                 conn->mtask = NULL;
564         }
565
566         /* process command queue */
567         while (__kfifo_get(conn->xmitqueue, (void*)&conn->ctask,
568                            sizeof(void*))) {
569                 /*
570                  * iscsi tcp may readd the task to the xmitqueue to send
571                  * write data
572                  */
573                 spin_lock_bh(&conn->session->lock);
574                 if (list_empty(&conn->ctask->running))
575                         list_add_tail(&conn->ctask->running, &conn->run_list);
576                 spin_unlock_bh(&conn->session->lock);
577                 if (tt->xmit_cmd_task(conn, conn->ctask))
578                         goto again;
579         }
580         /* done with this ctask */
581         conn->ctask = NULL;
582
583         /* process the rest control plane PDUs, if any */
584         if (unlikely(__kfifo_len(conn->mgmtqueue))) {
585                 while (__kfifo_get(conn->mgmtqueue, (void*)&conn->mtask,
586                                    sizeof(void*))) {
587                         spin_lock_bh(&conn->session->lock);
588                         list_add_tail(&conn->mtask->running,
589                                       &conn->mgmt_run_list);
590                         spin_unlock_bh(&conn->session->lock);
591                         if (tt->xmit_mgmt_task(conn, conn->mtask))
592                                 goto again;
593                 }
594                 /* done with this mtask */
595                 conn->mtask = NULL;
596         }
597
598         return 0;
599
600 again:
601         if (unlikely(conn->suspend_tx))
602                 return 0;
603
604         return -EAGAIN;
605 }
606
607 static void iscsi_xmitworker(void *data)
608 {
609         struct iscsi_conn *conn = data;
610
611         /*
612          * serialize Xmit worker on a per-connection basis.
613          */
614         mutex_lock(&conn->xmitmutex);
615         if (iscsi_data_xmit(conn))
616                 scsi_queue_work(conn->session->host, &conn->xmitwork);
617         mutex_unlock(&conn->xmitmutex);
618 }
619
620 enum {
621         FAILURE_BAD_HOST = 1,
622         FAILURE_SESSION_FAILED,
623         FAILURE_SESSION_FREED,
624         FAILURE_WINDOW_CLOSED,
625         FAILURE_SESSION_TERMINATE,
626         FAILURE_SESSION_IN_RECOVERY,
627         FAILURE_SESSION_RECOVERY_TIMEOUT,
628 };
629
630 int iscsi_queuecommand(struct scsi_cmnd *sc, void (*done)(struct scsi_cmnd *))
631 {
632         struct Scsi_Host *host;
633         int reason = 0;
634         struct iscsi_session *session;
635         struct iscsi_conn *conn;
636         struct iscsi_cmd_task *ctask = NULL;
637
638         sc->scsi_done = done;
639         sc->result = 0;
640
641         host = sc->device->host;
642         session = iscsi_hostdata(host->hostdata);
643
644         spin_lock(&session->lock);
645
646         /*
647          * ISCSI_STATE_FAILED is a temp. state. The recovery
648          * code will decide what is best to do with command queued
649          * during this time
650          */
651         if (session->state != ISCSI_STATE_LOGGED_IN &&
652             session->state != ISCSI_STATE_FAILED) {
653                 /*
654                  * to handle the race between when we set the recovery state
655                  * and block the session we requeue here (commands could
656                  * be entering our queuecommand while a block is starting
657                  * up because the block code is not locked)
658                  */
659                 if (session->state == ISCSI_STATE_IN_RECOVERY) {
660                         reason = FAILURE_SESSION_IN_RECOVERY;
661                         goto reject;
662                 }
663
664                 if (session->state == ISCSI_STATE_RECOVERY_FAILED)
665                         reason = FAILURE_SESSION_RECOVERY_TIMEOUT;
666                 else if (session->state == ISCSI_STATE_TERMINATE)
667                         reason = FAILURE_SESSION_TERMINATE;
668                 else
669                         reason = FAILURE_SESSION_FREED;
670                 goto fault;
671         }
672
673         /*
674          * Check for iSCSI window and take care of CmdSN wrap-around
675          */
676         if ((int)(session->max_cmdsn - session->cmdsn) < 0) {
677                 reason = FAILURE_WINDOW_CLOSED;
678                 goto reject;
679         }
680
681         conn = session->leadconn;
682
683         __kfifo_get(session->cmdpool.queue, (void*)&ctask, sizeof(void*));
684         sc->SCp.phase = session->age;
685         sc->SCp.ptr = (char *)ctask;
686
687         ctask->mtask = NULL;
688         ctask->conn = conn;
689         ctask->sc = sc;
690         INIT_LIST_HEAD(&ctask->running);
691         ctask->total_length = sc->request_bufflen;
692         iscsi_prep_scsi_cmd_pdu(ctask);
693
694         session->tt->init_cmd_task(ctask);
695
696         __kfifo_put(conn->xmitqueue, (void*)&ctask, sizeof(void*));
697         debug_scsi(
698                "ctask enq [%s cid %d sc %lx itt 0x%x len %d cmdsn %d win %d]\n",
699                 sc->sc_data_direction == DMA_TO_DEVICE ? "write" : "read",
700                 conn->id, (long)sc, ctask->itt, sc->request_bufflen,
701                 session->cmdsn, session->max_cmdsn - session->exp_cmdsn + 1);
702         spin_unlock(&session->lock);
703
704         scsi_queue_work(host, &conn->xmitwork);
705         return 0;
706
707 reject:
708         spin_unlock(&session->lock);
709         debug_scsi("cmd 0x%x rejected (%d)\n", sc->cmnd[0], reason);
710         return SCSI_MLQUEUE_HOST_BUSY;
711
712 fault:
713         spin_unlock(&session->lock);
714         printk(KERN_ERR "iscsi: cmd 0x%x is not queued (%d)\n",
715                sc->cmnd[0], reason);
716         sc->result = (DID_NO_CONNECT << 16);
717         sc->resid = sc->request_bufflen;
718         sc->scsi_done(sc);
719         return 0;
720 }
721 EXPORT_SYMBOL_GPL(iscsi_queuecommand);
722
723 int iscsi_change_queue_depth(struct scsi_device *sdev, int depth)
724 {
725         if (depth > ISCSI_MAX_CMD_PER_LUN)
726                 depth = ISCSI_MAX_CMD_PER_LUN;
727         scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth);
728         return sdev->queue_depth;
729 }
730 EXPORT_SYMBOL_GPL(iscsi_change_queue_depth);
731
732 static int
733 iscsi_conn_send_generic(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
734                         char *data, uint32_t data_size)
735 {
736         struct iscsi_session *session = conn->session;
737         struct iscsi_nopout *nop = (struct iscsi_nopout *)hdr;
738         struct iscsi_mgmt_task *mtask;
739
740         spin_lock_bh(&session->lock);
741         if (session->state == ISCSI_STATE_TERMINATE) {
742                 spin_unlock_bh(&session->lock);
743                 return -EPERM;
744         }
745         if (hdr->opcode == (ISCSI_OP_LOGIN | ISCSI_OP_IMMEDIATE) ||
746             hdr->opcode == (ISCSI_OP_TEXT | ISCSI_OP_IMMEDIATE))
747                 /*
748                  * Login and Text are sent serially, in
749                  * request-followed-by-response sequence.
750                  * Same mtask can be used. Same ITT must be used.
751                  * Note that login_mtask is preallocated at conn_create().
752                  */
753                 mtask = conn->login_mtask;
754         else {
755                 BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE);
756                 BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED);
757
758                 nop->exp_statsn = cpu_to_be32(conn->exp_statsn);
759                 if (!__kfifo_get(session->mgmtpool.queue,
760                                  (void*)&mtask, sizeof(void*))) {
761                         spin_unlock_bh(&session->lock);
762                         return -ENOSPC;
763                 }
764         }
765
766         /*
767          * pre-format CmdSN for outgoing PDU.
768          */
769         if (hdr->itt != cpu_to_be32(ISCSI_RESERVED_TAG)) {
770                 hdr->itt = mtask->itt | (conn->id << ISCSI_CID_SHIFT) |
771                            (session->age << ISCSI_AGE_SHIFT);
772                 nop->cmdsn = cpu_to_be32(session->cmdsn);
773                 if (conn->c_stage == ISCSI_CONN_STARTED &&
774                     !(hdr->opcode & ISCSI_OP_IMMEDIATE))
775                         session->cmdsn++;
776         } else
777                 /* do not advance CmdSN */
778                 nop->cmdsn = cpu_to_be32(session->cmdsn);
779
780         if (data_size) {
781                 memcpy(mtask->data, data, data_size);
782                 mtask->data_count = data_size;
783         } else
784                 mtask->data_count = 0;
785
786         INIT_LIST_HEAD(&mtask->running);
787         memcpy(mtask->hdr, hdr, sizeof(struct iscsi_hdr));
788         if (session->tt->init_mgmt_task)
789                 session->tt->init_mgmt_task(conn, mtask, data, data_size);
790         spin_unlock_bh(&session->lock);
791
792         debug_scsi("mgmtpdu [op 0x%x hdr->itt 0x%x datalen %d]\n",
793                    hdr->opcode, hdr->itt, data_size);
794
795         /*
796          * since send_pdu() could be called at least from two contexts,
797          * we need to serialize __kfifo_put, so we don't have to take
798          * additional lock on fast data-path
799          */
800         if (hdr->opcode & ISCSI_OP_IMMEDIATE)
801                 __kfifo_put(conn->immqueue, (void*)&mtask, sizeof(void*));
802         else
803                 __kfifo_put(conn->mgmtqueue, (void*)&mtask, sizeof(void*));
804
805         scsi_queue_work(session->host, &conn->xmitwork);
806         return 0;
807 }
808
809 int iscsi_conn_send_pdu(struct iscsi_cls_conn *cls_conn, struct iscsi_hdr *hdr,
810                         char *data, uint32_t data_size)
811 {
812         struct iscsi_conn *conn = cls_conn->dd_data;
813         int rc;
814
815         mutex_lock(&conn->xmitmutex);
816         rc = iscsi_conn_send_generic(conn, hdr, data, data_size);
817         mutex_unlock(&conn->xmitmutex);
818
819         return rc;
820 }
821 EXPORT_SYMBOL_GPL(iscsi_conn_send_pdu);
822
823 void iscsi_session_recovery_timedout(struct iscsi_cls_session *cls_session)
824 {
825         struct iscsi_session *session = class_to_transport_session(cls_session);
826         struct iscsi_conn *conn = session->leadconn;
827
828         spin_lock_bh(&session->lock);
829         if (session->state != ISCSI_STATE_LOGGED_IN) {
830                 session->state = ISCSI_STATE_RECOVERY_FAILED;
831                 if (conn)
832                         wake_up(&conn->ehwait);
833         }
834         spin_unlock_bh(&session->lock);
835 }
836 EXPORT_SYMBOL_GPL(iscsi_session_recovery_timedout);
837
838 int iscsi_eh_host_reset(struct scsi_cmnd *sc)
839 {
840         struct Scsi_Host *host = sc->device->host;
841         struct iscsi_session *session = iscsi_hostdata(host->hostdata);
842         struct iscsi_conn *conn = session->leadconn;
843         int fail_session = 0;
844
845         spin_lock_bh(&session->lock);
846         if (session->state == ISCSI_STATE_TERMINATE) {
847 failed:
848                 debug_scsi("failing host reset: session terminated "
849                            "[CID %d age %d]", conn->id, session->age);
850                 spin_unlock_bh(&session->lock);
851                 return FAILED;
852         }
853
854         if (sc->SCp.phase == session->age) {
855                 debug_scsi("failing connection CID %d due to SCSI host reset",
856                            conn->id);
857                 fail_session = 1;
858         }
859         spin_unlock_bh(&session->lock);
860
861         /*
862          * we drop the lock here but the leadconn cannot be destoyed while
863          * we are in the scsi eh
864          */
865         if (fail_session)
866                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
867
868         debug_scsi("iscsi_eh_host_reset wait for relogin\n");
869         wait_event_interruptible(conn->ehwait,
870                                  session->state == ISCSI_STATE_TERMINATE ||
871                                  session->state == ISCSI_STATE_LOGGED_IN ||
872                                  session->state == ISCSI_STATE_RECOVERY_FAILED);
873         if (signal_pending(current))
874                 flush_signals(current);
875
876         spin_lock_bh(&session->lock);
877         if (session->state == ISCSI_STATE_LOGGED_IN)
878                 printk(KERN_INFO "iscsi: host reset succeeded\n");
879         else
880                 goto failed;
881         spin_unlock_bh(&session->lock);
882
883         return SUCCESS;
884 }
885 EXPORT_SYMBOL_GPL(iscsi_eh_host_reset);
886
887 static void iscsi_tmabort_timedout(unsigned long data)
888 {
889         struct iscsi_cmd_task *ctask = (struct iscsi_cmd_task *)data;
890         struct iscsi_conn *conn = ctask->conn;
891         struct iscsi_session *session = conn->session;
892
893         spin_lock(&session->lock);
894         if (conn->tmabort_state == TMABORT_INITIAL) {
895                 conn->tmabort_state = TMABORT_TIMEDOUT;
896                 debug_scsi("tmabort timedout [sc %p itt 0x%x]\n",
897                         ctask->sc, ctask->itt);
898                 /* unblock eh_abort() */
899                 wake_up(&conn->ehwait);
900         }
901         spin_unlock(&session->lock);
902 }
903
904 /* must be called with the mutex lock */
905 static int iscsi_exec_abort_task(struct scsi_cmnd *sc,
906                                  struct iscsi_cmd_task *ctask)
907 {
908         struct iscsi_conn *conn = ctask->conn;
909         struct iscsi_session *session = conn->session;
910         struct iscsi_tm *hdr = &conn->tmhdr;
911         int rc;
912
913         /*
914          * ctask timed out but session is OK requests must be serialized.
915          */
916         memset(hdr, 0, sizeof(struct iscsi_tm));
917         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
918         hdr->flags = ISCSI_TM_FUNC_ABORT_TASK;
919         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
920         memcpy(hdr->lun, ctask->hdr->lun, sizeof(hdr->lun));
921         hdr->rtt = ctask->hdr->itt;
922         hdr->refcmdsn = ctask->hdr->cmdsn;
923
924         rc = iscsi_conn_send_generic(conn, (struct iscsi_hdr *)hdr,
925                                      NULL, 0);
926         if (rc) {
927                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
928                 debug_scsi("abort sent failure [itt 0x%x] %d", ctask->itt, rc);
929                 return rc;
930         }
931
932         debug_scsi("abort sent [itt 0x%x]\n", ctask->itt);
933
934         spin_lock_bh(&session->lock);
935         ctask->mtask = (struct iscsi_mgmt_task *)
936                         session->mgmt_cmds[(hdr->itt & ISCSI_ITT_MASK) -
937                                         ISCSI_MGMT_ITT_OFFSET];
938
939         if (conn->tmabort_state == TMABORT_INITIAL) {
940                 conn->tmfcmd_pdus_cnt++;
941                 conn->tmabort_timer.expires = 10*HZ + jiffies;
942                 conn->tmabort_timer.function = iscsi_tmabort_timedout;
943                 conn->tmabort_timer.data = (unsigned long)ctask;
944                 add_timer(&conn->tmabort_timer);
945                 debug_scsi("abort set timeout [itt 0x%x]", ctask->itt);
946         }
947         spin_unlock_bh(&session->lock);
948         mutex_unlock(&conn->xmitmutex);
949
950         /*
951          * block eh thread until:
952          *
953          * 1) abort response
954          * 2) abort timeout
955          * 3) session is terminated or restarted or userspace has
956          * given up on recovery
957          */
958         wait_event_interruptible(conn->ehwait,
959                                  sc->SCp.phase != session->age ||
960                                  session->state != ISCSI_STATE_LOGGED_IN ||
961                                  conn->tmabort_state != TMABORT_INITIAL);
962         if (signal_pending(current))
963                 flush_signals(current);
964         del_timer_sync(&conn->tmabort_timer);
965
966         mutex_lock(&conn->xmitmutex);
967         return 0;
968 }
969
970 /*
971  * xmit mutex and session lock must be held
972  */
973 #define iscsi_remove_task(tasktype)                                     \
974 static struct iscsi_##tasktype *                                        \
975 iscsi_remove_##tasktype(struct kfifo *fifo, uint32_t itt)               \
976 {                                                                       \
977         int i, nr_tasks = __kfifo_len(fifo) / sizeof(void*);            \
978         struct iscsi_##tasktype *task;                                  \
979                                                                         \
980         debug_scsi("searching %d tasks\n", nr_tasks);                   \
981                                                                         \
982         for (i = 0; i < nr_tasks; i++) {                                \
983                 __kfifo_get(fifo, (void*)&task, sizeof(void*));         \
984                 debug_scsi("check task %u\n", task->itt);               \
985                                                                         \
986                 if (task->itt == itt) {                                 \
987                         debug_scsi("matched task\n");                   \
988                         break;                                          \
989                 }                                                       \
990                                                                         \
991                 __kfifo_put(fifo, (void*)&task, sizeof(void*));         \
992         }                                                               \
993         return NULL;                                                    \
994 }
995
996 iscsi_remove_task(mgmt_task);
997 iscsi_remove_task(cmd_task);
998
999 static int iscsi_ctask_mtask_cleanup(struct iscsi_cmd_task *ctask)
1000 {
1001         struct iscsi_conn *conn = ctask->conn;
1002         struct iscsi_session *session = conn->session;
1003
1004         if (!ctask->mtask)
1005                 return -EINVAL;
1006
1007         if (!iscsi_remove_mgmt_task(conn->immqueue, ctask->mtask->itt))
1008                 list_del(&ctask->mtask->running);
1009         __kfifo_put(session->mgmtpool.queue, (void*)&ctask->mtask,
1010                     sizeof(void*));
1011         ctask->mtask = NULL;
1012         return 0;
1013 }
1014
1015 /*
1016  * session lock and xmitmutex must be held
1017  */
1018 static void fail_command(struct iscsi_conn *conn, struct iscsi_cmd_task *ctask,
1019                          int err)
1020 {
1021         struct scsi_cmnd *sc;
1022
1023         conn->session->tt->cleanup_cmd_task(conn, ctask);
1024         iscsi_ctask_mtask_cleanup(ctask);
1025
1026         sc = ctask->sc;
1027         if (!sc)
1028                 return;
1029         sc->result = err;
1030         sc->resid = sc->request_bufflen;
1031         iscsi_complete_command(conn->session, ctask);
1032 }
1033
1034 int iscsi_eh_abort(struct scsi_cmnd *sc)
1035 {
1036         struct iscsi_cmd_task *ctask = (struct iscsi_cmd_task *)sc->SCp.ptr;
1037         struct iscsi_conn *conn = ctask->conn;
1038         struct iscsi_session *session = conn->session;
1039         struct iscsi_cmd_task *pending_ctask;
1040         int rc;
1041
1042         conn->eh_abort_cnt++;
1043         debug_scsi("aborting [sc %p itt 0x%x]\n", sc, ctask->itt);
1044
1045         mutex_lock(&conn->xmitmutex);
1046         spin_lock_bh(&session->lock);
1047
1048         /*
1049          * If we are not logged in or we have started a new session
1050          * then let the host reset code handle this
1051          */
1052         if (session->state != ISCSI_STATE_LOGGED_IN ||
1053             sc->SCp.phase != session->age)
1054                 goto failed;
1055
1056         /* ctask completed before time out */
1057         if (!ctask->sc)
1058                 goto success;
1059
1060         /* what should we do here ? */
1061         if (conn->ctask == ctask) {
1062                 printk(KERN_INFO "iscsi: sc %p itt 0x%x partially sent. "
1063                        "Failing abort\n", sc, ctask->itt);
1064                 goto failed;
1065         }
1066
1067         /* check for the easy pending cmd abort */
1068         pending_ctask = iscsi_remove_cmd_task(conn->xmitqueue, ctask->itt);
1069         if (pending_ctask) {
1070                 /* iscsi_tcp queues write transfers on the xmitqueue */
1071                 if (list_empty(&pending_ctask->running)) {
1072                         debug_scsi("found pending task\n");
1073                         goto success;
1074                 } else
1075                         __kfifo_put(conn->xmitqueue, (void*)&pending_ctask,
1076                                     sizeof(void*));
1077         }
1078
1079         conn->tmabort_state = TMABORT_INITIAL;
1080
1081         spin_unlock_bh(&session->lock);
1082         rc = iscsi_exec_abort_task(sc, ctask);
1083         spin_lock_bh(&session->lock);
1084
1085         iscsi_ctask_mtask_cleanup(ctask);
1086         if (rc || sc->SCp.phase != session->age ||
1087             session->state != ISCSI_STATE_LOGGED_IN)
1088                 goto failed;
1089
1090         /* ctask completed before tmf abort response */
1091         if (!ctask->sc) {
1092                 debug_scsi("sc completed while abort in progress\n");
1093                 goto success;
1094         }
1095
1096         if (conn->tmabort_state != TMABORT_SUCCESS) {
1097                 spin_unlock_bh(&session->lock);
1098                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1099                 spin_lock_bh(&session->lock);
1100                 goto failed;
1101         }
1102
1103 success:
1104         debug_scsi("abort success [sc %lx itt 0x%x]\n", (long)sc, ctask->itt);
1105         spin_unlock_bh(&session->lock);
1106
1107         /*
1108          * clean up task if aborted. we have the xmitmutex so grab
1109          * the recv lock as a writer
1110          */
1111         write_lock_bh(conn->recv_lock);
1112         spin_lock(&session->lock);
1113         fail_command(conn, ctask, DID_ABORT << 16);
1114         spin_unlock(&session->lock);
1115         write_unlock_bh(conn->recv_lock);
1116
1117         mutex_unlock(&conn->xmitmutex);
1118         return SUCCESS;
1119
1120 failed:
1121         spin_unlock_bh(&session->lock);
1122         mutex_unlock(&conn->xmitmutex);
1123
1124         debug_scsi("abort failed [sc %lx itt 0x%x]\n", (long)sc, ctask->itt);
1125         return FAILED;
1126 }
1127 EXPORT_SYMBOL_GPL(iscsi_eh_abort);
1128
1129 int
1130 iscsi_pool_init(struct iscsi_queue *q, int max, void ***items, int item_size)
1131 {
1132         int i;
1133
1134         *items = kmalloc(max * sizeof(void*), GFP_KERNEL);
1135         if (*items == NULL)
1136                 return -ENOMEM;
1137
1138         q->max = max;
1139         q->pool = kmalloc(max * sizeof(void*), GFP_KERNEL);
1140         if (q->pool == NULL) {
1141                 kfree(*items);
1142                 return -ENOMEM;
1143         }
1144
1145         q->queue = kfifo_init((void*)q->pool, max * sizeof(void*),
1146                               GFP_KERNEL, NULL);
1147         if (q->queue == ERR_PTR(-ENOMEM)) {
1148                 kfree(q->pool);
1149                 kfree(*items);
1150                 return -ENOMEM;
1151         }
1152
1153         for (i = 0; i < max; i++) {
1154                 q->pool[i] = kmalloc(item_size, GFP_KERNEL);
1155                 if (q->pool[i] == NULL) {
1156                         int j;
1157
1158                         for (j = 0; j < i; j++)
1159                                 kfree(q->pool[j]);
1160
1161                         kfifo_free(q->queue);
1162                         kfree(q->pool);
1163                         kfree(*items);
1164                         return -ENOMEM;
1165                 }
1166                 memset(q->pool[i], 0, item_size);
1167                 (*items)[i] = q->pool[i];
1168                 __kfifo_put(q->queue, (void*)&q->pool[i], sizeof(void*));
1169         }
1170         return 0;
1171 }
1172 EXPORT_SYMBOL_GPL(iscsi_pool_init);
1173
1174 void iscsi_pool_free(struct iscsi_queue *q, void **items)
1175 {
1176         int i;
1177
1178         for (i = 0; i < q->max; i++)
1179                 kfree(items[i]);
1180         kfree(q->pool);
1181         kfree(items);
1182 }
1183 EXPORT_SYMBOL_GPL(iscsi_pool_free);
1184
1185 /*
1186  * iSCSI Session's hostdata organization:
1187  *
1188  *    *------------------* <== hostdata_session(host->hostdata)
1189  *    | ptr to class sess|
1190  *    |------------------| <== iscsi_hostdata(host->hostdata)
1191  *    | iscsi_session    |
1192  *    *------------------*
1193  */
1194
1195 #define hostdata_privsize(_sz)  (sizeof(unsigned long) + _sz + \
1196                                  _sz % sizeof(unsigned long))
1197
1198 #define hostdata_session(_hostdata) (iscsi_ptr(*(unsigned long *)_hostdata))
1199
1200 /**
1201  * iscsi_session_setup - create iscsi cls session and host and session
1202  * @scsit: scsi transport template
1203  * @iscsit: iscsi transport template
1204  * @initial_cmdsn: initial CmdSN
1205  * @hostno: host no allocated
1206  *
1207  * This can be used by software iscsi_transports that allocate
1208  * a session per scsi host.
1209  **/
1210 struct iscsi_cls_session *
1211 iscsi_session_setup(struct iscsi_transport *iscsit,
1212                     struct scsi_transport_template *scsit,
1213                     int cmd_task_size, int mgmt_task_size,
1214                     uint32_t initial_cmdsn, uint32_t *hostno)
1215 {
1216         struct Scsi_Host *shost;
1217         struct iscsi_session *session;
1218         struct iscsi_cls_session *cls_session;
1219         int cmd_i;
1220
1221         shost = scsi_host_alloc(iscsit->host_template,
1222                                 hostdata_privsize(sizeof(*session)));
1223         if (!shost)
1224                 return NULL;
1225
1226         shost->max_id = 1;
1227         shost->max_channel = 0;
1228         shost->max_lun = iscsit->max_lun;
1229         shost->max_cmd_len = iscsit->max_cmd_len;
1230         shost->transportt = scsit;
1231         shost->transportt->create_work_queue = 1;
1232         *hostno = shost->host_no;
1233
1234         session = iscsi_hostdata(shost->hostdata);
1235         memset(session, 0, sizeof(struct iscsi_session));
1236         session->host = shost;
1237         session->state = ISCSI_STATE_FREE;
1238         session->mgmtpool_max = ISCSI_MGMT_CMDS_MAX;
1239         session->cmds_max = ISCSI_XMIT_CMDS_MAX;
1240         session->cmdsn = initial_cmdsn;
1241         session->exp_cmdsn = initial_cmdsn + 1;
1242         session->max_cmdsn = initial_cmdsn + 1;
1243         session->max_r2t = 1;
1244         session->tt = iscsit;
1245
1246         /* initialize SCSI PDU commands pool */
1247         if (iscsi_pool_init(&session->cmdpool, session->cmds_max,
1248                             (void***)&session->cmds,
1249                             cmd_task_size + sizeof(struct iscsi_cmd_task)))
1250                 goto cmdpool_alloc_fail;
1251
1252         /* pre-format cmds pool with ITT */
1253         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
1254                 struct iscsi_cmd_task *ctask = session->cmds[cmd_i];
1255
1256                 if (cmd_task_size)
1257                         ctask->dd_data = &ctask[1];
1258                 ctask->itt = cmd_i;
1259         }
1260
1261         spin_lock_init(&session->lock);
1262         INIT_LIST_HEAD(&session->connections);
1263
1264         /* initialize immediate command pool */
1265         if (iscsi_pool_init(&session->mgmtpool, session->mgmtpool_max,
1266                            (void***)&session->mgmt_cmds,
1267                            mgmt_task_size + sizeof(struct iscsi_mgmt_task)))
1268                 goto mgmtpool_alloc_fail;
1269
1270
1271         /* pre-format immediate cmds pool with ITT */
1272         for (cmd_i = 0; cmd_i < session->mgmtpool_max; cmd_i++) {
1273                 struct iscsi_mgmt_task *mtask = session->mgmt_cmds[cmd_i];
1274
1275                 if (mgmt_task_size)
1276                         mtask->dd_data = &mtask[1];
1277                 mtask->itt = ISCSI_MGMT_ITT_OFFSET + cmd_i;
1278         }
1279
1280         if (scsi_add_host(shost, NULL))
1281                 goto add_host_fail;
1282
1283         cls_session = iscsi_create_session(shost, iscsit, 0);
1284         if (!cls_session)
1285                 goto cls_session_fail;
1286         *(unsigned long*)shost->hostdata = (unsigned long)cls_session;
1287
1288         return cls_session;
1289
1290 cls_session_fail:
1291         scsi_remove_host(shost);
1292 add_host_fail:
1293         iscsi_pool_free(&session->mgmtpool, (void**)session->mgmt_cmds);
1294 mgmtpool_alloc_fail:
1295         iscsi_pool_free(&session->cmdpool, (void**)session->cmds);
1296 cmdpool_alloc_fail:
1297         scsi_host_put(shost);
1298         return NULL;
1299 }
1300 EXPORT_SYMBOL_GPL(iscsi_session_setup);
1301
1302 /**
1303  * iscsi_session_teardown - destroy session, host, and cls_session
1304  * shost: scsi host
1305  *
1306  * This can be used by software iscsi_transports that allocate
1307  * a session per scsi host.
1308  **/
1309 void iscsi_session_teardown(struct iscsi_cls_session *cls_session)
1310 {
1311         struct Scsi_Host *shost = iscsi_session_to_shost(cls_session);
1312         struct iscsi_session *session = iscsi_hostdata(shost->hostdata);
1313
1314         scsi_remove_host(shost);
1315
1316         iscsi_pool_free(&session->mgmtpool, (void**)session->mgmt_cmds);
1317         iscsi_pool_free(&session->cmdpool, (void**)session->cmds);
1318
1319         iscsi_destroy_session(cls_session);
1320         scsi_host_put(shost);
1321 }
1322 EXPORT_SYMBOL_GPL(iscsi_session_teardown);
1323
1324 /**
1325  * iscsi_conn_setup - create iscsi_cls_conn and iscsi_conn
1326  * @cls_session: iscsi_cls_session
1327  * @conn_idx: cid
1328  **/
1329 struct iscsi_cls_conn *
1330 iscsi_conn_setup(struct iscsi_cls_session *cls_session, uint32_t conn_idx)
1331 {
1332         struct iscsi_session *session = class_to_transport_session(cls_session);
1333         struct iscsi_conn *conn;
1334         struct iscsi_cls_conn *cls_conn;
1335         char *data;
1336
1337         cls_conn = iscsi_create_conn(cls_session, conn_idx);
1338         if (!cls_conn)
1339                 return NULL;
1340         conn = cls_conn->dd_data;
1341         memset(conn, 0, sizeof(*conn));
1342
1343         conn->session = session;
1344         conn->cls_conn = cls_conn;
1345         conn->c_stage = ISCSI_CONN_INITIAL_STAGE;
1346         conn->id = conn_idx;
1347         conn->exp_statsn = 0;
1348         conn->tmabort_state = TMABORT_INITIAL;
1349         INIT_LIST_HEAD(&conn->run_list);
1350         INIT_LIST_HEAD(&conn->mgmt_run_list);
1351
1352         /* initialize general xmit PDU commands queue */
1353         conn->xmitqueue = kfifo_alloc(session->cmds_max * sizeof(void*),
1354                                         GFP_KERNEL, NULL);
1355         if (conn->xmitqueue == ERR_PTR(-ENOMEM))
1356                 goto xmitqueue_alloc_fail;
1357
1358         /* initialize general immediate & non-immediate PDU commands queue */
1359         conn->immqueue = kfifo_alloc(session->mgmtpool_max * sizeof(void*),
1360                                         GFP_KERNEL, NULL);
1361         if (conn->immqueue == ERR_PTR(-ENOMEM))
1362                 goto immqueue_alloc_fail;
1363
1364         conn->mgmtqueue = kfifo_alloc(session->mgmtpool_max * sizeof(void*),
1365                                         GFP_KERNEL, NULL);
1366         if (conn->mgmtqueue == ERR_PTR(-ENOMEM))
1367                 goto mgmtqueue_alloc_fail;
1368
1369         INIT_WORK(&conn->xmitwork, iscsi_xmitworker, conn);
1370
1371         /* allocate login_mtask used for the login/text sequences */
1372         spin_lock_bh(&session->lock);
1373         if (!__kfifo_get(session->mgmtpool.queue,
1374                          (void*)&conn->login_mtask,
1375                          sizeof(void*))) {
1376                 spin_unlock_bh(&session->lock);
1377                 goto login_mtask_alloc_fail;
1378         }
1379         spin_unlock_bh(&session->lock);
1380
1381         data = kmalloc(DEFAULT_MAX_RECV_DATA_SEGMENT_LENGTH, GFP_KERNEL);
1382         if (!data)
1383                 goto login_mtask_data_alloc_fail;
1384         conn->login_mtask->data = data;
1385
1386         init_timer(&conn->tmabort_timer);
1387         mutex_init(&conn->xmitmutex);
1388         init_waitqueue_head(&conn->ehwait);
1389
1390         return cls_conn;
1391
1392 login_mtask_data_alloc_fail:
1393         __kfifo_put(session->mgmtpool.queue, (void*)&conn->login_mtask,
1394                     sizeof(void*));
1395 login_mtask_alloc_fail:
1396         kfifo_free(conn->mgmtqueue);
1397 mgmtqueue_alloc_fail:
1398         kfifo_free(conn->immqueue);
1399 immqueue_alloc_fail:
1400         kfifo_free(conn->xmitqueue);
1401 xmitqueue_alloc_fail:
1402         iscsi_destroy_conn(cls_conn);
1403         return NULL;
1404 }
1405 EXPORT_SYMBOL_GPL(iscsi_conn_setup);
1406
1407 /**
1408  * iscsi_conn_teardown - teardown iscsi connection
1409  * cls_conn: iscsi class connection
1410  *
1411  * TODO: we may need to make this into a two step process
1412  * like scsi-mls remove + put host
1413  */
1414 void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn)
1415 {
1416         struct iscsi_conn *conn = cls_conn->dd_data;
1417         struct iscsi_session *session = conn->session;
1418         unsigned long flags;
1419
1420         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1421         mutex_lock(&conn->xmitmutex);
1422         if (conn->c_stage == ISCSI_CONN_INITIAL_STAGE) {
1423                 if (session->tt->suspend_conn_recv)
1424                         session->tt->suspend_conn_recv(conn);
1425
1426                 session->tt->terminate_conn(conn);
1427         }
1428
1429         spin_lock_bh(&session->lock);
1430         conn->c_stage = ISCSI_CONN_CLEANUP_WAIT;
1431         if (session->leadconn == conn) {
1432                 /*
1433                  * leading connection? then give up on recovery.
1434                  */
1435                 session->state = ISCSI_STATE_TERMINATE;
1436                 wake_up(&conn->ehwait);
1437         }
1438         spin_unlock_bh(&session->lock);
1439
1440         mutex_unlock(&conn->xmitmutex);
1441
1442         /*
1443          * Block until all in-progress commands for this connection
1444          * time out or fail.
1445          */
1446         for (;;) {
1447                 spin_lock_irqsave(session->host->host_lock, flags);
1448                 if (!session->host->host_busy) { /* OK for ERL == 0 */
1449                         spin_unlock_irqrestore(session->host->host_lock, flags);
1450                         break;
1451                 }
1452                 spin_unlock_irqrestore(session->host->host_lock, flags);
1453                 msleep_interruptible(500);
1454                 printk(KERN_INFO "iscsi: scsi conn_destroy(): host_busy %d "
1455                        "host_failed %d\n", session->host->host_busy,
1456                        session->host->host_failed);
1457                 /*
1458                  * force eh_abort() to unblock
1459                  */
1460                 wake_up(&conn->ehwait);
1461         }
1462
1463         spin_lock_bh(&session->lock);
1464         kfree(conn->login_mtask->data);
1465         __kfifo_put(session->mgmtpool.queue, (void*)&conn->login_mtask,
1466                     sizeof(void*));
1467         list_del(&conn->item);
1468         if (list_empty(&session->connections))
1469                 session->leadconn = NULL;
1470         if (session->leadconn && session->leadconn == conn)
1471                 session->leadconn = container_of(session->connections.next,
1472                         struct iscsi_conn, item);
1473
1474         if (session->leadconn == NULL)
1475                 /* no connections exits.. reset sequencing */
1476                 session->cmdsn = session->max_cmdsn = session->exp_cmdsn = 1;
1477         spin_unlock_bh(&session->lock);
1478
1479         kfifo_free(conn->xmitqueue);
1480         kfifo_free(conn->immqueue);
1481         kfifo_free(conn->mgmtqueue);
1482
1483         iscsi_destroy_conn(cls_conn);
1484 }
1485 EXPORT_SYMBOL_GPL(iscsi_conn_teardown);
1486
1487 int iscsi_conn_start(struct iscsi_cls_conn *cls_conn)
1488 {
1489         struct iscsi_conn *conn = cls_conn->dd_data;
1490         struct iscsi_session *session = conn->session;
1491
1492         if (session == NULL) {
1493                 printk(KERN_ERR "iscsi: can't start unbound connection\n");
1494                 return -EPERM;
1495         }
1496
1497         spin_lock_bh(&session->lock);
1498         conn->c_stage = ISCSI_CONN_STARTED;
1499         session->state = ISCSI_STATE_LOGGED_IN;
1500
1501         switch(conn->stop_stage) {
1502         case STOP_CONN_RECOVER:
1503                 /*
1504                  * unblock eh_abort() if it is blocked. re-try all
1505                  * commands after successful recovery
1506                  */
1507                 conn->stop_stage = 0;
1508                 conn->tmabort_state = TMABORT_INITIAL;
1509                 session->age++;
1510                 spin_unlock_bh(&session->lock);
1511
1512                 iscsi_unblock_session(session_to_cls(session));
1513                 wake_up(&conn->ehwait);
1514                 return 0;
1515         case STOP_CONN_TERM:
1516                 conn->stop_stage = 0;
1517                 break;
1518         default:
1519                 break;
1520         }
1521         spin_unlock_bh(&session->lock);
1522
1523         return 0;
1524 }
1525 EXPORT_SYMBOL_GPL(iscsi_conn_start);
1526
1527 static void
1528 flush_control_queues(struct iscsi_session *session, struct iscsi_conn *conn)
1529 {
1530         struct iscsi_mgmt_task *mtask, *tmp;
1531
1532         /* handle pending */
1533         while (__kfifo_get(conn->immqueue, (void*)&mtask, sizeof(void*)) ||
1534                __kfifo_get(conn->mgmtqueue, (void*)&mtask, sizeof(void*))) {
1535                 if (mtask == conn->login_mtask)
1536                         continue;
1537                 debug_scsi("flushing pending mgmt task itt 0x%x\n", mtask->itt);
1538                 __kfifo_put(session->mgmtpool.queue, (void*)&mtask,
1539                             sizeof(void*));
1540         }
1541
1542         /* handle running */
1543         list_for_each_entry_safe(mtask, tmp, &conn->mgmt_run_list, running) {
1544                 debug_scsi("flushing running mgmt task itt 0x%x\n", mtask->itt);
1545                 list_del(&mtask->running);
1546
1547                 if (mtask == conn->login_mtask)
1548                         continue;
1549                 __kfifo_put(session->mgmtpool.queue, (void*)&mtask,
1550                            sizeof(void*));
1551         }
1552
1553         conn->mtask = NULL;
1554 }
1555
1556 /* Fail commands. Mutex and session lock held and recv side suspended */
1557 static void fail_all_commands(struct iscsi_conn *conn)
1558 {
1559         struct iscsi_cmd_task *ctask, *tmp;
1560
1561         /* flush pending */
1562         while (__kfifo_get(conn->xmitqueue, (void*)&ctask, sizeof(void*))) {
1563                 debug_scsi("failing pending sc %p itt 0x%x\n", ctask->sc,
1564                            ctask->itt);
1565                 fail_command(conn, ctask, DID_BUS_BUSY << 16);
1566         }
1567
1568         /* fail all other running */
1569         list_for_each_entry_safe(ctask, tmp, &conn->run_list, running) {
1570                 debug_scsi("failing in progress sc %p itt 0x%x\n",
1571                            ctask->sc, ctask->itt);
1572                 fail_command(conn, ctask, DID_BUS_BUSY << 16);
1573         }
1574
1575         conn->ctask = NULL;
1576 }
1577
1578 static void iscsi_start_session_recovery(struct iscsi_session *session,
1579                                          struct iscsi_conn *conn, int flag)
1580 {
1581         int old_stop_stage;
1582
1583         spin_lock_bh(&session->lock);
1584         if (conn->stop_stage == STOP_CONN_TERM) {
1585                 spin_unlock_bh(&session->lock);
1586                 return;
1587         }
1588
1589         /*
1590          * When this is called for the in_login state, we only want to clean
1591          * up the login task and connection. We do not need to block and set
1592          * the recovery state again
1593          */
1594         if (flag == STOP_CONN_TERM)
1595                 session->state = ISCSI_STATE_TERMINATE;
1596         else if (conn->stop_stage != STOP_CONN_RECOVER)
1597                 session->state = ISCSI_STATE_IN_RECOVERY;
1598
1599         old_stop_stage = conn->stop_stage;
1600         conn->stop_stage = flag;
1601         conn->c_stage = ISCSI_CONN_STOPPED;
1602         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1603         spin_unlock_bh(&session->lock);
1604
1605         if (session->tt->suspend_conn_recv)
1606                 session->tt->suspend_conn_recv(conn);
1607
1608         mutex_lock(&conn->xmitmutex);
1609         /*
1610          * for connection level recovery we should not calculate
1611          * header digest. conn->hdr_size used for optimization
1612          * in hdr_extract() and will be re-negotiated at
1613          * set_param() time.
1614          */
1615         if (flag == STOP_CONN_RECOVER) {
1616                 conn->hdrdgst_en = 0;
1617                 conn->datadgst_en = 0;
1618                 if (session->state == ISCSI_STATE_IN_RECOVERY &&
1619                     old_stop_stage != STOP_CONN_RECOVER) {
1620                         debug_scsi("blocking session\n");
1621                         iscsi_block_session(session_to_cls(session));
1622                 }
1623         }
1624
1625         session->tt->terminate_conn(conn);
1626         /*
1627          * flush queues.
1628          */
1629         spin_lock_bh(&session->lock);
1630         fail_all_commands(conn);
1631         flush_control_queues(session, conn);
1632         spin_unlock_bh(&session->lock);
1633
1634         mutex_unlock(&conn->xmitmutex);
1635 }
1636
1637 void iscsi_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
1638 {
1639         struct iscsi_conn *conn = cls_conn->dd_data;
1640         struct iscsi_session *session = conn->session;
1641
1642         switch (flag) {
1643         case STOP_CONN_RECOVER:
1644         case STOP_CONN_TERM:
1645                 iscsi_start_session_recovery(session, conn, flag);
1646                 break;
1647         default:
1648                 printk(KERN_ERR "iscsi: invalid stop flag %d\n", flag);
1649         }
1650 }
1651 EXPORT_SYMBOL_GPL(iscsi_conn_stop);
1652
1653 int iscsi_conn_bind(struct iscsi_cls_session *cls_session,
1654                     struct iscsi_cls_conn *cls_conn, int is_leading)
1655 {
1656         struct iscsi_session *session = class_to_transport_session(cls_session);
1657         struct iscsi_conn *tmp = ERR_PTR(-EEXIST), *conn = cls_conn->dd_data;
1658
1659         /* lookup for existing connection */
1660         spin_lock_bh(&session->lock);
1661         list_for_each_entry(tmp, &session->connections, item) {
1662                 if (tmp == conn) {
1663                         if (conn->c_stage != ISCSI_CONN_STOPPED ||
1664                             conn->stop_stage == STOP_CONN_TERM) {
1665                                 printk(KERN_ERR "iscsi: can't bind "
1666                                        "non-stopped connection (%d:%d)\n",
1667                                        conn->c_stage, conn->stop_stage);
1668                                 spin_unlock_bh(&session->lock);
1669                                 return -EIO;
1670                         }
1671                         break;
1672                 }
1673         }
1674         if (tmp != conn) {
1675                 /* bind new iSCSI connection to session */
1676                 conn->session = session;
1677                 list_add(&conn->item, &session->connections);
1678         }
1679         spin_unlock_bh(&session->lock);
1680
1681         if (is_leading)
1682                 session->leadconn = conn;
1683
1684         /*
1685          * Unblock xmitworker(), Login Phase will pass through.
1686          */
1687         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
1688         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1689         return 0;
1690 }
1691 EXPORT_SYMBOL_GPL(iscsi_conn_bind);
1692
1693 MODULE_AUTHOR("Mike Christie");
1694 MODULE_DESCRIPTION("iSCSI library functions");
1695 MODULE_LICENSE("GPL");